language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Markdown
hhvm/hphp/hack/doc/HIPs/gradual_modularity.md
# Gradual Modularity in Hack Status: draft, not actively being worked on. If this changes, this pre-HIP proposal should be updated to match the current HIP template. Last updated: 2019-10-09 Shared as a HIP for external visibility ## The Problem In production builds of Facebook WWW, certain directories are dropped, such as internal tools and test directories. This means that any code attempting to access symbols in those directories will fatal at runtime with an autoloader fatal. Hack is not currently able to enforce this. As a related problem, due to the global nature of our repo, framework developers struggle to hide the implementation details of their frameworks. Often, we rely on naming conventions like `_DO_NOT_USE`. But, again, there is no static analysis to enforce this, and these symbols end up getting used anyway. Then, there are similar problems that arise when attempting to define 'black box' APIs - we may want hard isolation while maintaining access to core infrastructure: for example, there may be a blessed library to interact with a data store, and direct access should be banned except by the library. Lastly, there's the classic problem of open-sourcing Hack frameworks with a source of truth as part of a proprietary monorepo: for example, all of Facebook WWW can use the HSL, but the HSL can not depend on any proprietary code. These problems are manifestations of a more general problem: the lack of modularity in the Hack language—everything is globally accessible. Upon closer inspection, we can see that there are multiple granularities to this problem: two examples are the "environment" level and the "library" level. * Environments represent build-time partitioning of the repository. The 'intern' (internal tools and libraries)/production boundary is a classic example: code in intern may access code in prod, but not vice-versa. This is most akin to the workspaces feature of modern package managers (see Prior Art). * Libraries are logically related groups of code. These are like modules/packages that we see in most modern languages. Libraries may selectively hide their internals from their dependencies. Note that these granularities are not mutually exclusive—for example, HSL is both a library and an environment. In the same way that we slowly introduced types into an untyped Hack, we can introduce modularity gradually, from coarsest to finest granularity. Accordingly, **this document explores a solution to the problem of "environments,"** while leaving the possibility open to solving the "libraries" problem in the future. ## Solution Requirements * **Discreet.** We desire a limited number of environments in Facebook's WWW codebase, to retain the advantaged of monorepo development. Environment definitions should be hidden from developers, and should be hard for developers to subvert. Essentially, this means that any per-file syntax is undesirable. * **Hierarchical.** Environments should be able to depend on others, where "environment A depends on environment B" is defined as: code from A may reference code from B, but code from B may *not* reference code from A. This allows, for example, Intern to access Prod code but not vice-versa. Dependencies are not transitive: i.e. if A depends on B and B depends on C, A does not implicitly depend on C. * **Permeable.** While environment dependency is generally one-way, we must have a type-safe way of piercing that boundary (for example, *some* Intern symbols *can* be accessed from Prod). This implies that the feature should be first-class-ish enough for the typechecker/compiler/runtime to interact with it. This requirement is intended to be a WWW-only compromise, so we can tolerate it being clunky to use as a deterrent. * **Single Source of Truth.** Environment specifications should be able to be consumed by the typechecker (to statically enforce the boundaries), the runtime (to dynamically enforce the boundaries), and the build system (to selectively include code in the build). This way, the typechecker has an accurate view of reality. ## Abstract Proposal: Environments *This section describes the environments feature in an abstract sense, using pseudocode, to bring the semantics of the feature to the forefront. Later sections propose a concrete syntax for the feature.* An "environment" is an isolated subdivision of a monorepo, where "isolated" means that code defined outside of a particular environment may not access code within that environment (barring certain exceptions). The boundaries are enforced both by the typechecker and the runtime. The build system will select environments to include in the build, but all environments do not have to correspond to a hard runtime boundary. This allows environments to be used for massive sections of a repository (e.g. intern/prod), but also for libraries (e.g. HSL). ### Defining Environments and Builds An environment is specified inside a special configuration file in a directory. A special filename isn't strictly necessary, but it makes environments easy to find within a codebase containing extremely large numbers of files, and makes it harder for users to accidentally define environments. ``` // Example: in ~/www/flib/environment.x: environment { name = Prod } ``` All code in source files in said directory and recursive subdirectories belongs to this environment. A source file belongs to exactly one environment: the nearest one defined. For example, if `flib/` defines an environment "Prod" and `flib/intern/` defines an environment "Intern", then all code under `flib/intern/` belongs only to Intern. Source files which do not have a nearest environment definition belong to a “default environment”. Environments can depend on multiple other environments. For migration purposes, all environments implicitly depend on the “default environment,” with the assumption that all code will eventually move to a defined environment. To define an environment that depends on another, simply define the environment normally and include its dependencies: ``` // Example: in ~/www/flib/intern/environment.x: environment { name = Intern dependencies = [Prod] } ``` As with the first example, all code under `flib/intern/` belongs only to Intern. However, now that Intern depends on Prod, code belonging to Intern may access code in Prod, but not vice-versa! The dependency relationship is not transitive; for example, if there were an environment "Scripts" that depended on Intern, it would only be able to access code in Prod, if it also depended on Prod. That `flib/intern/` is a subdirectory of `flib/` is irrelevant—dependent environments don't have to be defined in subdirectories of the environments they depend on. Conversely, Intern doesn't have to depend on Prod just because `flib/intern/` is a subdirectory of `flib/`. In fact, the relationship can be inverted—for example, Prod could depend on an "HSL" environment defined in `flib/core/hack/lib/`! All environments implicitly depend on the aforementioned “default environment”. This allows for environments to be gradually migrated into a monorepo, without having to do it all at once. It also handles the case of HHVM builtins, which are currently provided by HHIs. Eventually, they may all be inside of a “builtin” environment, but initially they will simply live in the default environment and be accessible everywhere. Given that `__tests__` are scattered around the codebase currently, any proposed feature would be restricted to running regexes on filenames, which would hamstring its ability to integrate into the language. **Ideally, this feature assumes that tests in WWW are moved from `__tests__` directories to one top-level `tests/` directory.** But, we may be able to reach a compromise if one environment.x file is able to define multiple environments via regular expressions that only apply to files in that directory. ``` // Example: in ~/www/flib/environment.x: environments { ProdTests { regex = "#/__tests__/#" dependencies = [Prod] } Prod { regex = "#.*#" } } ``` A “build” is a collection of environments that indicate the code that’s available in a particular build of the repository. It is specified inside a special configuration file in the root directory of the repository. For example, Facebook’s builds might look like this. Note that our builds evolved to be hierarchical, allowing us to only specify one environment per build, but it's not necessary. ``` // Example: in ~/www/builds.x: build { name = Prod environments = [Prod] } build { name = Intern environments = [Intern] } build { name = Scripts environments = [Scripts] } ``` ### Permeability There are two cases of issues in which existing boundaries in WWW are violated. The first issue is simpler than the other: certain classes are defined in Intern, but really should be in Prod. The solution to this problem is to make environments typechecker-only initially, and use the static analysis to move definitions to where they need to be before turning on runtime enforcement. The second issue is trickier. Sometimes, definitions can't be moved, explicit checks on the current environment at runtime, which explicitly break the abstraction. To support this permeability, we need to be able to introspect on which environments are available in the current build. ``` // Example: in some prod file: if (<current build includes Intern>) { // Access intern code here... } ``` Or, if we’re refining with some other mechanism (for example, being is a script context implies that the Scripts environment is available), then users can assert an environment is available with `invariant` to provide a useful error message. ``` // Example: in some prod file: if (Environment::isScript()) { invariant( <current build includes Scripts>, 'Being in a script implies that Scripts is available', ); // Access scripts code here... } ``` ### Enforcement & User Experience Environment accessibility is enforced whenever an identifier is referenced. Enforcement is based entirely on the source files of the “caller” and “callee”—the permeability construct doesn’t affect functions called within a permeability block. ``` // Example: in some prod file: class ProdClass extends InternClass // Error implements InternInterface { // Error use InternTrait; // Error } function f(mixed $x): void { intern_function(); // Error intern_function<>; // Error InternClass::SOME_CONST; // Error h<InternClass>(); // Error new InternClass(); // Error $x is InternClass; // Error if (<current build includes Intern>) { intern_function(); // OK intern_function<>; OK InternClass::SOME_CONST; // OK h<InternClass>(); // OK new InternClass(); // OK $x is InternClass; // OK g(); // Note that the usages in g() are still errors } } function g(): void { intern_function(); // Error echo InternClass::SOME_CONST; // Error // etc... } function h<reify T>(): void {} ``` **When typechecking a file**, the typechecker maintains a list of available environments. Initially, the list has exactly one element. Whenever a symbol is referenced, the typechecker compares the environment of the current source file against the environment of the referenced symbol. If they’re incompatible, an error is raised. The permeability construct will add the checked environment to the otherwise singleton list of current environments, and the typechecker will iterate over the current environments within the permeating block. When a boundary violation is found, the typechecker's error message will list the two environments, including an explanation as to why each source file is in its respective environment. The explanation can be computed from the two ways environments can be defined (directory plus optional string pattern). However, the error message will *not* point to the environment file, as we do not want to advertise this feature to WWW users (but they can easily find it by looking in the directory specified). For example, consider the environments defined above (Prod, ProdTests, Intern). If code from Intern attempted to access code from ProdTests, the error message would say: ``` Cannot reference a symbol in another environment This use-site is in the Intern environment because it is in directory flib/intern/ The symbol X is in the ProdTests environment because it is in directory flib/ and matches the pattern __tests__ Intern does not depend on ProdTests ``` **In repo-authoritative mode,** the current build should be known when the repository is compiled (e.g. we know if we are going to deploy to prod, intern, etc). This means that environments that aren’t part of the build will simply be dropped from the repository, any environment checks on identifiers can be elided, and permeability conditions can be statically checked and compiled out (akin to `ifdef`). However, if a function is annotated with the `__DynamicallyCallable` attribute, then the checks must remain, because we don’t know which environments it may be called from. **In sandbox mode,** the available environments must be defined per-request, so that they behave identically to how such a request would behave in production. For example, in development, a user should not be able to access scripts in a web request. The native autoloader can be environment-aware, and refuse to load symbols if the environments are incompatible. Similarly to the typechecker, the permeability construct will “refine” the current environment to the one checked within the scope of the checked block. Some ideas on how to determine the available environments: * Could introspect on WebController and related frameworks to create a build object * Could use native autoloader to determine the right build object * __EntryPoint could have a way of specifying which environments are available ## Application in WWW ### Philosophy Facebook has benefited tremendously by betting on the monorepo model. This feature is intended to mitigate some shortcomings of the monorepo without cutting into the benefits. We want to help users understand when they’re writing code that will behave differently in production, but we do not want to encourage carving up the WWW repo into silos. We want to avoid a world in which developers do not feel empowered to contribute to parts of the codebase because it “belongs” to someone else. We also don’t want to enable an intractable dependency graph to develop in the WWW repo. Therefore, for the initial rollout of this feature, **we will only allow environments that correspond to a form of hard isolation (e.g. a build boundary, or an OSS library).** Framework maintainers who wish to hide implementation details will have to wait—environments are not intended to be a packages feature. ### Rollback Plan What if we decide that environments aren't the right solution for WWW? Perhaps they'd proliferate too quickly or make the WWW developer experience too cumbersome. Recall this property of environment definitions discussed above: > Source files which do not have a nearest environment definition belong to a “default environment”. It follows that to roll back to a pre-environment state in WWW, it would be sufficient to delete all environment files from WWW. Then, all declarations would be in the default environment, and would be accessible to each other, both in the typechecker and the runtime (if we get that far before rolling back). The environment checking code could then be removed from the typechecker, followed by the code that records environments into saved states. ### Sample Configuration This is one possible initial configuration which adheres to the principle defined above: * **HSL: **The Hack Standard Library, which should depend on nothing except builtins provided by HHVM. * Depends on: <NONE> * **HSL-Experimental: **Components that are in development for eventual addition into the HSL, but not ready to be used in WWW. * Depends on: HSL * **HSL-FB:** Components that may be promoted to HSL eventually, but are useful for some FB use-cases. * Depends on: HSL * **TestInfra: **Components of our test frameworks, such as UnitTest, ExpectObj, etc. * Depends on: HSL, HSL-FB * **Build** Build steps that we may want to isolate from WWW at large. * Depends on: HSL, HSL-FB * **Prod:** WWW at large, anything under `flib/` but not `flib/intern/`. * Depends on: HSL, HSL-FB * Test environment: **Prod-Tests** * Depends on: HSL, HSL-FB, Prod, TestInfra * **Intern:** Internal code, anything under `flib/intern/`. * Depends on: HSL, HSL-FB, Prod * Test environment: **Intern-Tests** * Depends on: HSL, HSL-FB, Intern, Prod, TestInfra * **Scripts:** Scripts, anything under `scripts/`. * Depends on: HSL, HSL-FB, Intern, Prod Then, our three builds would be: * Prod: includes Prod and dependencies * Intern: includes Intern and dependencies * Scripts: includes Scripts and dependencies ## Other Considerations ### Incremental Typechecking There are a few fundamental points that determine how environments will affect Hack's incremental typechecking model. 1. Environments do not create implicit namespaces. Each name in the monorepo is still globally unique, and is defined in exactly one file. 2. We already maintain a best-effort dependency graph between every file in the codebase, so that if a particular file changes, we re-typecheck it and its dependents. 3. All source files belong to exactly one environment (either in a user-defined environment or the "default" environment). Then, _most working copy changes related to environments may be reduced down to one or more files moving from environment A to B_, in which case we re-typecheck those files and their dependents. This means that the only machinery we must add to the server is watching for environment changes, and mapping those changes to a list of files that moved environments. Consider the following situations: * **If a file moves between environments,** that file must be re-typechecked, along with its dependent files. * **If the name of an environment changes, **it's analogous to every file in the environment moving to the new one. Therefore, all files in that environment must be re-typechecked, along with their dependent files. * **If an environment file is added,** it's analogous to all files in that directory moving to the newly-added environment. Therefore, all files under the directory containing the new environment file must be re-typechecked, along with their dependent files. * **If an environment file is removed,** it's analogous to all files in that directory moving to the next-closest environment. Therefore everything under the directory containing the deleted environment file must be re-typechecked, along with their dependent files. * **If an environment file is moved,** it's analogous to zero or more files being added and/or removed from the environment. Therefore everything under the new and old directories containing the environment file must be re-typechecked, along with their dependent files. * **If the environment's dependencies change,** then all files in that environment must be re-typechecked, along with their dependent files. Another concern is how the addition of environments affect saved states. TODO: * add an environments table along with the dependencies between them * add a reference to environment for each file in the naming table. * Need to do performance testing for O(repo) updates to the naming table when environments change. ### Open Source If each of our OSS libraries will be an environment internally, there is potential to integrate environment specification files with package managers. In order to do so specifications would have to be extended with at least the following information: * Dependency version: allowing for multiple semver constraints * Dependency source: e.g. npm, GitHub, this repo (in the case of local environments) * Separation of production vs. development dependencies For a specific package manager, the current frontrunner is Esy, Reason's package manager. One large factor in choosing Esy over Yarn is that it's a binary (versus Yarn requiring Node on the machine, or us having to package Node with HHVM). We'd need to implement a plugin to read HDF and make sure environment definitions are flexible enough to be used by package managers, and the developers of Esy have been open to collaborating on the design process. A pitfall to consider is that Esy and Yarn install packages in a global cache on the system (instead of in the project root). This means that the typechecker will need to be taught about this cache in some way to still work in OSS. ## Concrete Syntax Proposal: HDF *For a concrete proposal for environments, we’ll choose HDF. It’s consistent with HHVM’s current configuration format, and it supports dictionaries and lists. Other options considered were YAML, TOML, and JSON, but each were either inappropriate or suboptimal.* To define environments, define named nodes inside an environments field in a file named `__environments.hdf` in a directory. The special filename isn't strictly necessary, but it makes environments easy to find within a 2.5M file codebase, and makes it harder for users to accidentally define environments. To define an environment that depends on another, simply define the environment normally add a `dependencies` field: ``` // Example: in ~/www/flib/__environments.hdf: environments { ProdTests { regex = "#/__tests__/#" dependencies { Prod TestInfra } } Prod { regex = "#.*#" } } // Example: in ~/www/flib/intern/__environments.hdf: environments { InternTests { regex = "#/__tests__/#" dependencies { Intern TestInfra } } Intern { regex = "#.*#" dependencies { Prod } } ``` A "build" represents a concrete subdivision of a monorepo which is composed of environments. To define builds, define named nodes inside a `builds` field inside a file named `__builds.hdf` in the root directory of the repository. ``` // Example: in ~/www/__builds.hdf: builds { Prod { environments { Prod } } Intern { environments { Intern } } Scripts { environments { Scripts } } } ``` Note that our builds evolved to be hierarchical, allowing us to only specify one environment per build, but it's not necessary. A build may contain multiple completely separate environments. To implement runtime permeability, we use a new builtin function `HH\environment_available`, which takes a string representing an environment name as defined above. If the environment is included in the current build, it returns true, or false otherwise. The typechecker understands this function and will include the listed environment for the duration of the block. It follows that the argument passed to the function must be a string literal. ``` // Example: in some prod file: if (HH\environment_available('Intern')) { // Access intern code here... } ``` Or, we’re refining with some other mechanism (for example, being in a script implies that the Scripts environment is available), then we can assert an environment is available with `invariant` to provide a better error message. ``` // Example: in some prod file: if (Environment::isScript()) { invariant( HH\environment_available('Scripts'), 'Being in a script implies that Scripts is available', ); // Access scripts code here... } ``` ## Prior Art ### [Cargo Workspaces](https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html) (Rust) A *Cargo workspace* is a set of packages that share the same `Cargo.lock` and output directory. Packages within a workspace may depend on each other, and depend on the same set of external dependencies. This is similar to this proposal in which the repo is the workspace, and each “package” is an environment. At Facebook, there is no lock file, but externally, a repo would have just one `composer.lock`, and each environment in the repo would depend on the same external dependencies. One key difference is that there isn’t a notion of transitive dependencies (there was at some point, [but it was a bug](https://github.com/rust-lang/cargo/issues/1037)); dependencies must be declared explicitly: > The top-level *Cargo.lock* now contains information about the dependency of `add-one` on `rand`. However, even though `rand` is used somewhere in the workspace, we can’t use it in other crates in the workspace unless we add `rand` to their *Cargo.toml* files as well. ### [Yarn Workspaces](https://yarnpkg.com/lang/en/docs/workspaces/) (JS) The nomenclature is different here, but the concepts are similar to Cargo workspaces. A *Yarn workspace* is what Cargo would call a package (or we’d call an environment), but otherwise works similarly for interdependencies and external dependencies: > Requiring `workspace-a` from a file located in `workspace-b` will now use the exact code currently located inside your project rather than what is published on npm, and the `cross-env` package has been correctly deduped and put at the root of your project to be used by both `workspace-a` and `workspace-b`. Some key differences between Yarn workspaces and this proposal include: * *“Workspaces must be descendants of the workspace root in terms of folder hierarchy. You cannot and must not reference a workspace that is located outside of this filesystem hierarchy.”* * In our proposal, the environments could be anywhere, as long as both the typechecker and the autoloader know about them. * *“Nested workspaces are not supported at this time.”* * Our proposal does support nested environments, with the restriction that a source file may only be in exactly one environment. * *“Be careful when publishing packages in a workspace. If you are preparing your next release and you decided to use a new dependency but forgot to declare it in the `package.json` file, your tests might still pass locally if another package already downloaded that dependency into the workspace root.”* * This is more than a transitive dependency problem. This means if any other workspace in the project has downloaded an external dependency, the current workspace can import it (even if it doesn’t depend on one of those other workspaces). This is a limitation of the package resolution algorithm. Our proposal requires dependencies to be either explicitly declared transitive or imported in each environment, and this will be enforced both by the typechecker and runtime. ### [Assemblies](https://docs.microsoft.com/en-us/dotnet/standard/assembly/index) (C#) > You can think of an assembly as a collection of types and resources that form a logical unit of functionality and are built to work together. In .NET Core and .NET Framework, an assembly can be built from one or more source code files. In .NET Framework, assemblies can contain one or more modules. Assemblies are analogous to environments in our proposal, and modules would be analogous to packages, which we may design in the future. One key difference between assemblies and our proposal is the notion of [friend assemblies](https://docs.microsoft.com/en-us/dotnet/standard/assembly/friend-assemblies): a *friend assembly* is an assembly that can access another assembly's [internal](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/internal) (in C# or [Friend](https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/modifiers/friend) in Visual Basic) types and members. For V1 of this proposal, we have omitted environment-level visibility and punted until we choose to design a packages feature. ### [MODULES](https://blog.golang.org/using-go-modules) (Go) Probably something to look into as well, because: * it’s Google scale * fairly new (mid-2019) * there were mixed opinions around vendoring & dependencies before * * * # Design Meeting Notes ## Discussion with Dwayne (9/10) * Permeability needs to be fleshed out more * There appear to be two kinds of permeability * 1: Explicitly introspecting on the current build to see which environments are available * 2: Certain files simply being included in the prod build, seems arbitrary. The proposal kind of hand-waves these away by saying we’ll use the typechecker to move them to the right environment. But why haven’t we done that already? Is there a deeper reason? * Is it intended to be a permanent feature? * If so, it should be designed like a real language feature, not a special function with a string. It should support autocomplete, jump-to-definition, etc. * If not, we need to deeply understand the current use-cases and discuss a 100% migration story. Possibly post in Intern/Prod Boundary Working Group to gain more specific use cases to discuss * Needs more code examples * How to break up switch cases that match on symbols within and outside of the current environment? * How does this fit into our dependency tracking model? * What if environment files change? Must we re-typecheck that environment and all of its dependencies? * What if a file moves between environments? * How will this feature affect saved state (e.g. will it increase the size on disk)? * Since we intend for this feature to be used for OSS libraries, how does this feature interact with package managers? ## Brainstorm 3 (8/19) * Scala packages appear to be pretty close to Hack namespaces already * note the “agnostic to file layout”: https://docs.scala-lang.org/tour/packages-and-imports.html * If code is not declared in a package, it’s in the empty package (e.g. root namespace in Hack) * But does Scala have the problem of people injecting their code into packages? * Idea: Environments define which namespaces(packages) can be defined within them. If code inside another environment declares that namespace(package), raise a typechecker error * Entering a permeability block does NOT change the current environment, it just gives access to another environment * This distinction is important when we have non-transitive dependencies * TODO: Go back and revisit assumptions that may have changed due to existence of non-transitive dependencies * Also explicitly list use-cases for non-transitive dependencies * Tests * Problem 1: We never want code in intern/prod etc. to depend on code in tests (environments problem) * Problem 2: We want test code to have access to namespace internals (namespaces problem ## Brainstorm 2 (8/05) * We should find a way to model the needs of libraries with environments as well * Fundamentally, namespaces can be declared everywhere, so they do not fit well into notion of “packages” * Could namespaces be converted to a “packages” feature? * Scala packages appear to be pretty close to Hack namespaces already; note the “agnostic to file layout”: https://docs.scala-lang.org/tour/packages-and-imports.html * If code is not declared in a package, it’s in the empty package (e.g. root namespace in Hack) * Transitivity should be configurable (transitive by default). Or, ability to seal environments * Could have an internal (or export) keyword to control access to declarations within an environment * Tests: might need some notion of “Friend” environment * Could replace <<__TestsBypassVisibility>> attribute * Decision: not ready for design review * Want to have an explicit plan on how to support libraries * What about method-level granularity? * Should this replace namespaces? ## Brainstorm 1 (7/29) * Research other languages * Scala has a relatively fine-grained visibility system * Research Rust crates * JS (package managers like Yarn) * ✅ How to enforce environments at runtime in sandbox mode? * Could you construct builds at runtime? * Sandbox enforcement should be identical to production environment * Will need to integrate with autoloader and facts * Symbols would need to track the environment that they’re in * That may be an argument against is expressions, because introspecting on the current build would change this runtime enforcement! * ✅ Are Hack classes/interfaces the right DSL to model environments? Are they markedly better than just regular config files (e.g. package.json, etc.)? * If we decide Hack syntax is not appropriate, what’s the alternative? HDF? TOML? * Maybe this is a question for design review. * Resolution: split proposal into abstract and concrete, will discuss syntax at design review. * ✅ Do we REALLY need to centralize tests? Is there a middle ground between a first class feature and just regexes on file paths? * ✅ The idea of hiding framework internals seems more like a language-level module problem (i.e. written in syntax, potentially via improved namespace support), while the problem at hand appears more to be a package management problem. Reflect that in the problem statement.
Markdown
hhvm/hphp/hack/doc/HIPs/implicit_pessimisation.md
# HIP: Implicit pessimisation ## Motivation The existence of HH_FIXME and use of unsound dynamic in a large Hack codebase precludes us from statically determining which values are used dynamically, and which classes and functions may safely opt out. We would like to start from a position that every value in the codebase supports safe dynamic operations. This makes it safe for a value to fall into the blast radius of an HH_FIXME, because it may simply be replaced with an upcast to an appropriate like type instead using `HH\FIXME\UNSAFE_CAST`, and flow unimpeded into functions that support dynamic calls. # Proposal We propose a uniform pessimisation strategy where every class and function in the codebase is implicitly marked `<<__SupportDynamicType>>`. To meet the conditions for supporting dynamic, we implicitly interpret as follows: All function and method returns of unenforced types become like types. ``` type D<T> = T; class C { public function good(): int { return 4; } public function bad(): D<int> { /* HH_FIXME[4110] */ return "hello"; } } function test(): void { $c = new C(); $a = $c->good(); // $a: int $b = $c->bad(); // $b: ~int } ``` Enums get partial enforcement at their base types to prevent override errors. ``` enum Transparent: int as int { A = 1; } enum Opaque: int { B = 2; } class C { public function f(): int { return 4; } public function g(): arraykey { return 4; } } class D extends C { public function f(): Transparent /* ~Transparent & int */ { return Transparent::A; } public function g(): Opaque /* ~Opaque & arraykey */ { return Opaque::B; } } ``` Add supportdyn bounds on abstract type constants ``` abstract class A { abstract const type T /* as supportdyn<mixed> */; public function f(): this::T { ... }; } ``` Interpret `HH\FIXME\UNSAFE_CAST<T1, T2>(e)` as `e upcast ~T1`. ``` public function bad(): this::T /* like type */ { return HH\FIXME\UNSAFE_CAST<string, int>("hello"); // returning ~int } ``` Interpret `mixed`, `nonnull`, function types, and open shape types as wrapped in `supportdyn`. ``` function d(dynamic $d): void {} function m(mixed $m): void { // $m: supportdyn<mixed> d($m); // implicit upcast to dynamic } ``` Weaken returns and inouts in function type hints ``` function f((function(): string) $f): void { // $f: supportdyn<(function(): ~string)> } function g((function(inout string): void) $g): void { // $f: supportdyn<(function(inout ~string): ~void)> } ``` > The `~void` is unfortunate, but is addressed by the `return await f();` proposal. Interpret interface and abstract method returns as like types, as they have no function body to trigger enforcement. ``` interface I { public function f(): int; } abstract class A { public function g(): int; } class C extends A implements I { const type T = int; public function f(): this::T { ... } // ~this::T overrides ~int public function g(): this::T { ... } } ``` TODO: @sowens for the complex extends / implements case. ## Hierarchy Poisoning Interpreting unenforced types as like types causes problems in hierarchies. ``` class A { public function f(): int { ... } } class B { const type T = int; public function f(): this::T { ... } /* override error */ } ``` We resolve this by manually weakening the type of the parent class ahead of time to prepare the codebase for implicit pessimisation ``` class A { public function f(): ~int { ... } } ``` We introduce a handful of marker types to aid this preparation | Marker name | Current interpretation | Sound dynamic interpretation | | ---------------------- | ---------------------- | ---------------------------- | | `POISON_MARKER<T>` | `T` | `~T` | | `TANY_MARKER<T>` | `_` | `T` | | `SUPPORTDYN_MARKER<T>` | `T` | `supportdyn<T>` | # Future ## <<__NoAutoDynamic>> Implicit pessimisation locks all classes and functions into supporting dynamic. In order to migrate away from dynamism, we propose an opt-out mechanism `<<__NoAutoDynamic>>` that can be used for functions that are not dynamically callable, and classes in the future once they are similarly verified. The attribute turns off implicit pessimisation for the attached definition. The definitions ``` class C {} <<__NoAutoDynamic, __SupportDynamicType>> class D extends C {} ``` under implicit pessimisation are equivalent to ``` <<__SupportDynamicType>> class C {} <<__SupportDynamicType>> class D extends C {} ``` without implicit pessimisation. ## Elimination of implicit pessimisation The core goal of this project is to make explicit the use of dynamism in the codebase by eliminating misfeatures such as HH_FIXME. Once a sufficient number of classes are marked up with `<<__NoAutoDynamic>>`, we would like to "flip the switch" and turn off implicit pessimisation. This will require explicit insertion of `<<__SupportDynamicType>>` and like type hints. Then, any new classes and functions will be outside dynamic by default, and users can reap the benefits of static typing. # Decision points - (copy paste) Which parts of sound dynamic will we ship? - `~T` vs. `HH\FIXME\POISON_MARKER<T>` - `supportdyn<T>` vs. `HH\FIXME\SUPPORTDYN_MARKER<T>` - `e upcast T` vs. `HH\FIXME\UNSAFE_CAST<_, T>` (like types only) - naming of `<<__SupportDynamicType>>` - Hierarchy overrides in the context of implicit pessimisation
Markdown
hhvm/hphp/hack/doc/HIPs/int_intish_shape_keys.md
# Feature Name: int/intish shape keys ## Start Date: 2020-06-29 ## Status: Draft # Summary: Shape keys are currently required to be: - string literals that do not start with an int - class constants This proposal is to permit any `arraykey` literal, in addition to class constants. More specifically: - permit int literal shape keys - permit any string literal shape key, even if they would be converted to ints by PHP # Feature motivation: - The ban on int-like shape keys is a PHPIsm in disguise: this exists because of array-key-cast behavior which no longer exists in hack. - The ban on actual int shape keys was to avoid any confusion with int-like keys, however there are other reasons (e.g. avoiding confusion with tuples) - The bans are not actually consistently enforced, due to permitting type constants - HSL Regex is already special and creates shapes with integer keys. It would be useful to be able to type regexp patterns and matches fully as they're passed around - This would remove some special-casing from the typechecker # User experience: Generally as already-present for `Regex\Match`; additionally, this will now be possible: ``` // Takes any regex, returns the entire matched string function helper<T as Regex\Pattern(shape(0 => string, ...))>( T $pattern, ): string { return Regex\Match($pattern); } ``` Currently, it can only be typed as `Regex\Match`, which is declared as `shape(...)` and it is impossible to refine it or redeclare it to say that `0` (entire string) or any specific numbered captures are present. # IDE experience: Already present for Regex\Match; no change expected. # Implementation details: * How the feature will interact with other Hack features - will make HSL Regex more consistent; other interactions as already applying * How the feature will be implemented - removal of restrictions/special-casing * A description of corner cases - existing problems with class constants * Any changes to HHVM - none * If applicable, strategies for codemodding - n/a # Design rationale and alternatives: Largely covered by 'motivation' above. No alternatives have been considered for removal of ban on 'int-like' `string` keys. These are a PHPism. ## Alternatives for the Regexp problem The rest of this section addresses alternatives for actual `int` shape keys. ### Using int-like string keys positional captures For example, `$shape['0']`. The main problem is potential future issues: while PCRE currently bans named capture groups that start with a number, the syntax for referencing them differs; it appears that it would be possible to remove this restriction without breaking compatibility, *unless* we introduce this syntax. This would also have a minor drawback from usability/familiarity benefit, as it would be different to the representations in all other languages. ### Using objects with getters e.g. `->getNameCapture(string $name)`, `->getPositionalCapture(int $idx)` This is the approach taken by most other languages/libraries that support named captures. This would remove the need for any changes to shapes and tuples, however to maintain the same static safety that we currently have (i.e. we know which named and positional captures are valid), these objects will in turn need to be special-cased - for example, perhaps `re"/(foo(?<bar>baz))/"` is inferred to be a `RegexpPattern<tuple(string, string), shape('bar' => string)>` - however, if tuples are used as part of the generic, changes will be needed to support subtyping. ### Tuples These natively support sequential integer keys, however they have several drawbacks here: - it's valid to mix named and positional captures (and common, especially for 0); in practice, would likely return both a tuple and shape, especially from some APIs - no sub-typing; in particular, most requests for specifying a type are for "I want to take any regexp with at least these captures" - for example: - whole string, and a specific named capture: `shape(0 => string, 'foo' => string, ...)` - Perhaps this would be `((string, ...), shape('foo' => string, ...)` - at least one position capture: `shape(1 => string, ...)` - perhaps `((string, string, ...), shape(...))` Combined with the fact that all elements are the same type, this problem feels like it would be better solved by bounded-size vecs - i.e. a `vec<string>` with at least `n` elements - however, in the regexp case, the user normally cares about presence of a specific n, not `0..=n`, which is a problem already addressed by shapes. # Drawbacks: - may be misused when tuples are a better fit - can not be converted to be class-based in the future - unlikely due to existing COW semantics - likely already impractical due to class constant hole and lack of runtime enforcement - can not be converted to 'data classes' (a.k.a. 'records') in the future - likely already impractical due to class constant hole and lack of runtime enforcement # Unresolved questions: # Future possibilities: - remove class constant support
Markdown
hhvm/hphp/hack/doc/HIPs/memoization_options.md
# Memoization options This document describes proposed changes to the already defined Implicit Context feature in pursuit of the following goals: * Expedite wide-scale usage of Implicit Context (IC) * Ensure IC is always properly accounted for in memoization * Reduce risk of breaking runtime assertions as part of initial migration or normal development * Reduce risk of breaking existing logic depending on behavior of `<<__Memoize>>` today > This feature is also referred to as the "Dynamically Enforced Implicit Context" feature. ## Today: IC requires Contexts and Capabilities The Implicit Context feature provides a value that is implicitly propagated to callees recursively. For example: ``` // Native, in HH namespace abstract class ImplicitContext { abstract const type T as nonnull; public static function set<Tout>( this::T $context, (function ()[zoned]: Tout) $f )[zoned]: Tout { ... } public static function get()[zoned]: ?this::T; } // Userland final class MyPolicyImplicitContext extends HH\ImplicitContext { ... } ``` ``` MyPolicyImplicitContext::set( $my_policy, ()[zoned] ==> do_stuff(), ); ... function some_recursive_callee_of_do_stuff()[zoned]: void { $_ = MyPolicyImplicitContext::get(); // returns $my_policy } ``` In order to prevent poisoning memoization caches (fetching the cached results computed under one IC value when executing under a different IC value), we designed the IC feature to be coupled with the coeffects feature which applies static recursive restrictions. We required that: * You can only set an IC for the execution of functions requiring at most `[zoned]` (or `[zoned_with<T>]` but we ignore this context in this document) * Memoized functions that are callable from a `[zoned]` function must either: * shard the memoization cache based on the IC value (iff the context of the function is `[zoned]`) * guarantee that the IC is not used by having a context without the `ImplicitPolicy` capability which is required to access the IC (e.g. `[leak_safe]`) While tying the IC to contexts and capabilities gives us static guarantees about code, adding these more restrictive contexts to code requires a lot of effort, and some developers want the benefits of the IC without the requirement of using contexts. ## Proposal We propose allowing setting an IC when executing functions requiring `[defaults]`. The new signature for this method on the `ImplicitContext::` class will be: ``` public static function runWith<Tout>( this::T $context, (function ()[_]: Tout) $f )[ctx $f, zoned]: Tout { ... } ``` >In the above, we have also renamed `ImpicitContext::set` to `ImplicitContet::runWith` in order to avoid an incorrect assumption that the IC is set to the given value *after* the completion of this method call. We use the new “runWith” name for the remainder of this document. We will avoid poisoning memoization caches by dynamically requiring that memoized functions executing under an IC fall into one of two safe categories: * The function is marked as having its memoization cache key incorporate the IC. This is achieved by using the `__Memoize(#KeyedByIC)` attribute (formerly known as `__PolicyShardedMemoize`) instead of regular `__Memoize`. We will allow this attribute to be used with any function with the `ImplicitPolicy` capability including `[defaults]` functions. * The functions is marked as never using the IC. This can be achieved either by: * Using the new attribute `__Memoize(#MakeICInaccessible)` instead of regular `__Memoize`. This attribute will act like `__Memoize` except: attempting to fetch the IC or calling an uncategorized memoized function from a function with this attribute will throw. This behavior applies to immediate and recursive callees until an IC value is set again (if ever). * Using regular `__Memoize` and requiring a context that does not have the `ImplicitPolicy` capability. Because fetching the IC requires `[zoned]`, we know that recursive callees cannot access the IC. (Given the current set of contexts, this is the set of contexts as capable as or less capable than `[leak_safe, globals]`.) >In the above, we are adding an optional enum class label argument to the `__Memoize` attribute. See the “Syntax” section. If a memoized function is executed under a non-null IC and does not fall into one of the above two categories, the runtime will throw an exception. The primary example of such a function would be a function that requires `[defaults]` and has the regular `__Memoize` attribute. We also propose adding the following features to allow for migration to the above while minimizing the risk of surprise exceptions: * `soft_run_with($callable, $blame_string)` - This function will execute the callable and log in the same circumstances when calling `runWith` instead would throw: namely when calling a function that is `__Memoize` + `[defaults]`. The blame string distinguishes distinct uses of this API. Developers can use this function before using `runWith` in order to identify functions to fix. * Note that this function does not belong to an `ImplicitContext` class because it does not effect propagation of a user-provided value. * `__Memoize(#SoftMakeICInaccessible)` - This attribute is analogous to `__Memoize(#MakeICInaccessible)` and will cause logs in cases when using `__Memoize(#MakeICInaccessible)` instead would throw: namely when calling a function that is `__Memoize` + `[defaults]` or when attempting to fetch the IC. Developers can use this before using `__Memoize(#MakeICInaccessible)` in order to identify functions to fix. * Note that since a function with `[defaults]` and this attribute behaves exactly like a function with `[defaults]` and `__Memoize` except for the logging, a function with this attribute will also be considered "uncategorized." * When using `#SoftMakeICInaccessible`, the attribute will also take an integer as an optional second argument. This integer will be used as a sample rate. That is, if you pass N, then when this function is called there is a 1/N chance that we will enter the “soft inaccessible” state and produce logs; otherwise, this function will act as if no arguments we passed. * `run_with_soft_inaccessible_state($callable, $blame_string)` - This function will execute the callable and log in the same circumstances when calling this from a `#MakeICInaccessible` function would throw. The purpose of this function is to allow removing calls to backdoors in code that is already running under an “inaccessible” state. * This currently will only be allowed from the “null” state which is the state you are in in a backdoor. The goal of logging is to allow developers to get signal if making changes would result in exceptions due to disallowed access to the IC or calls to uncategorized memoized functions. Developers who use these "soft" variations should get at least one log for problematic dependencies if any exist, even if other callers of the same dependencies exist (assuming 1:1 sampling). Note that while getting logs for every problematic dependency that could be detected at runtime is ideal, logs for a single dependency should be sufficient to block the developer from upgrading to throwing variants. These various memoization options are mutually exclusive and cannot be used together on the same function. Note: In this document, we describe semantics in terms of `__Memoize` and `__Memoize()`. The same statements apply to `__MemoizeLSB` and new `__MemoizeLSB()`. ## Description of states Under this proposal, the IC can be in one of five states: ``` null : The IC has not been set value(T) : The IC has been set to some value inaccessible : Fetching the IC or calling uncategorized memoized functions will result in an exception soft_set(vector<soft inaccessible blame>, vector<soft run blame>) : The IC has not been set, but you will get logs for uncategorized memoization soft_inaccessibl(vector<soft inaccessible blame>, vector<soft run blame>) : The IC has not been set, but you will get logs for uncategorized memoization and for fetching the IC ``` Both soft states maintain two vectors of information on caller frames: one for strings associated with the reason for entering a “soft inaccessible” state (usually the names of functions with `__Memoize(#SoftMakeICInaccessible)`), the other for the list of user-provided strings passed to calls to `soft_run_with`. They are used as in two places: * Functions with `__Memoize(#KeyedByIC)` will account for both vectors in the memoization cache key. * Warnings that are raised for calling uncategorized memoized functions (from either soft state) or fetching the Implicit Context (from `soft_inaccessible`) will not include the blame information in the error string. However, this blame information will be passed as an additional argument to the error handler — a 2-tuple of the two vectors of strings. The "blame" values help indicate what function calls or functions' attributes are responsible for the logs. This is necessary in order to address logs during migrations, especially when migrating multiple code-sites at once. ## Description of state transitions The following actions will have the following behavior: ### Calling a function with regular `__Memoize` that has the `ImplicitPolicy` capability (e.g. `[defaults]`) This does not affect the state of the IC. ``` null: Run, do not use IC for cache key value: throw inaccessible: throw soft_set: log, run, do not use IC for cache key soft_inaccessible: log, run, do not use IC for cache key ``` Note that although `[zoned]` has the `ImplicitPolicy` capability, it is an error for a function with the `[zoned]` context to use regular `__Memoize` and so is not subject to this ### Calling a function with `__Memoize(#KeyedByIC)` This does not affect the state of the IC. ``` null: Run and use null as the IC key value: Run and use the IC value as the IC key inaccessible: Run and use the inaccessible state (singleton value) as the IC key soft_set: Run and use the the state plus blame vectors as the IC key soft_inaccessible: Run and use the the state plus blame vectors as the IC key ``` For the soft states, it is necessary to key by blame information. Otherwise, if there are multiple callers that enable logging and a callee that would produce a log, if all the callers share the same cache key, that logging callee will not produce logs for every caller and non-first callers will lose signal that the callee may eventually throw. ### Calling a function with `__Memoize(#MakeICInaccessible)` ``` * : Run, do not key cache with IC, transition to inaccessible state with this function as blame ``` ### Calling a function with `__Memoize(#SoftMakeICInaccessible) ` Recall that functions with this attribute are still considered uncategorized and so have similar behavior to a `__Memoize` + `[defaults]` function. ``` null: Run, do not key with IC, transition to soft_inaccessible state with this function as blame value: throw inaccessible: throw soft_set: log, run, do not key with IC, transition to soft_inaccessible state, inherit both blame vectors and append this function name to the inaccessible blame vector soft_inaccessible: log, run, do not key with IC, stay in soft_inaccessible state and add this function to existing inaccesible blame vector ``` ### Calling a function with `__Memoize` that does not have the `ImplicitPolicy` capability This does not affect the state of the IC. ``` * : Run, do not key with IC ``` ### Calling `ImplicitContext::get` This does not affect the state of the IC. ``` null: return null value: return value inaccessible: throw soft_set: return null soft_inaccessible: log, return null ``` ### Calling `ImplicitContext::runWith` ``` * : set the IC to a value, transition to the value state with this function call as blame ``` ### Calling `soft_run_with` ``` null: transition to soft_set state with the given string as blame value: no op (relevant callees will already throw) inaccessible: no op (relevant callees will already throw) soft_set: stay in soft_set state and add the given blame string to the existing soft run blame vector soft_inaccessible: stay in soft_inaccessible state and add the given blame string to the existing soft run blame vector ``` Note: From the `soft_inaccessible` state, we stay in `soft_inaccessible` instead of transitioning to `soft_set` because we still want to produce warnings for downstream calls to `ImplicitContext::get` in order to associate them with the previous `__Memoize(#SoftMakeICInaccessible)` and `soft_inaccessible` has this behavior in addition to the warning behaviors of `soft_set`. ### Calling `run_with_soft_inaccessible_state` ``` null: transition to soft_inaccessible state with the given string in the soft inaccessible function blame vector value: throw inaccessible: throw soft_set: throw soft_inaccessible: throw ``` We may consider supporting this call from other states if we determine there are other uses for it. ### Calling `HH\Coeffects\backdoor` or aliases These backdoors allow calling code requiring `[defaults]` from various, less-capable contexts. ``` * : move to null state (clears any IC value) ``` ### Calling `HH\Coeffects\fb\backdoor_to_globals_leak_safe__DO_NOT_USE` This backdoor allows calling code requiring at most `[leak_safe, globals]` from any context. ``` * : no op, no state change ``` Note that by enforcing that the code executed via this backdoor can only require at most `[globals, leak_safe]`, we prevent problematic calls to unsafe memoized functions and calls to fetch the IC. ## Attributes’ interactions with coeffects This section describes rules for what functions with what coeffects can use these new attributes. * `__Memoize(#KeyedByIC)` will only be permitted on functions that are known to have the `ImplicitPolicy` capability at compile time. * This means that the functions’ context list must be implicitly `[defaults]` or contain one of the following contexts explicitly: `defaults`, `zoned`, `zoned_shallow`, `zoned_local`. * Reason: A developer should be able to expect that a function without the `ImplicitPolicy` capability is not affected by the Implicit Context. However, this would not be the case if we allowed `#KeyedByIC` — e.g. imagine a memoized, leak-safe function that returns a random number. * `__Memoize(#MakeICInaccessible)` and `__Memoize(#SoftMakeICInaccessible)` will only be allowed on functions with any of the following contexts: `defaults`, `leak_safe_shallow`, `leak_safe_local` * Reason: For functions without the `ImplicitPolicy` capability, the IC is already inaccessible and the function can use regular `__Memoize`. For functions with `zoned`, using this attribute seems contradictory. * This will be similarly enforced at compile time. * (As before) A memoized function with the `zoned` context must use `#KeyedByIC`. * (As before) A function with dependent contexts may not be memoized. ## Expected use A developer that wants to execute code under an IC would: 1. Start by executing the code using `soft_run_with` 2. Address logs for uncategorized memoized functions by either (a) switch to `__Memoize(#KeyedByIC)` or (b) use `__Memoize(#SoftMakeICInaccessible)`. 1. The latter may produce additional logs for uncategorized memoized functions and additional logs for `ImplicitContext::get`. 3. Continue to categorize detected uncategorized memoized functions AND address logs for `ImplicitContext::get`. Options for addressing `ImplicitContext::get`: 1. Use `__Memoize(#KeyedByIC)` instead of `__Memoize(#SoftMakeICInaccessible)` 2. Introduce a new IC between the `__Memoize(#SoftMakeICInaccessible)` and the `ImplicitContext::get` using another `soft_run_with` and eventually `runWith` (or by removing the IC via a backdoor function) 4. New uses of `__Memoize(#SoftMakeICInaccessible)` may produce additional logs as in step (2) and/or additional logs for `ImplicitContext::get`; Continue to categorize uncategorized memoized functions detected by logging and address 5. Harden `__Memoize(#SoftMakeICInaccessible)` to `__Memoize(#MakeICInaccessible)` when logging indicates it is safe. 6. Harden calls to `soft_run_with` to `runWith` when logging indicates it is safe. Note that developers may also choose to use static analysis or existing runtime profiling to identify uncategorized, memoized dependencies ahead of using `soft_run_with` or `__Memoize(#SoftMakeICInaccessible)`. Framework developers that want to make their frameworks compatible with being executed under an IC would use similar steps except likely by starting with making their regular `__Memoize` calls either `__Memoize(#KeyedByIC)` or `__Memoize(#SoftMakeICInaccessible)` depending on intended semantics. ## Path to contexts and capabilities Allowing use of a dynamically-enforced Implicit Context is compatible with a statically-enforced Implicit Context using Contexts and Capabilities. In fact, the work to specify IC-handling for memoized functions is a subset of the work required to make functions callable from `[zoned]` contexts. In abstract, you can think of functions using `__Memoize(#KeyedByIC)` as being functions where the intention is to eventually require `[zoned]` (if it does not already) and think of functions using `__Memoize(#MakeICInaccessible)` as being functions where the intention is to eventually require `[leak_safe]` or some more restrictive context. ## Explicit Uncategorization We also propose another memoization option `#Uncategorized`. Passing this argument will have the same behavior described above for not passing any arguments (with the exception of functions without the `ImplicitPolicy` capability). The purpose of this is that you can then require that the memoize attribute takes an argument. This encourages developers to consider how their function should behave w.r.t. the IC when writing new functions. Even under such a requirement though, memoized functions without the `ImplicitPolicy` capability will continue to require that no arguments are passed to the memoize attribute as the context list already explicitly designates the behavior. ## Syntax The current proposal introduces an optional, enum class label argument to the existing `__Memoize` (and `__MemoizeLSB`) attributes e.g. `__Memoize(#KeyedByIC)`. This would require adding the ability to use enum class labels in attribute argument positions. ``` enum class MemoizeOption: string { string KeyedByIC = 'KeyedByIC'; string MakeICInaccessible = 'MakeICInaccessible'; string SoftMakeICInaccessible = 'SoftMakeICInaccessible'; string Uncategorized = 'Uncategorized'; } ``` Currently, the `__Memoize` attribute is hard-coded into the typechecker and there is no declaration for it. However, you could declare it like so: ``` final class __Memoize implements HH\FunctionAttribute, HH\MethodAttribute { public function __construct( private ?HH\EnumClass\Label<MemoizeOption, string> $kind, ) {} } ``` Alternatives we considered: * Using special constants e.g. `__Memoize(KeyedByIC)`. However, constants are not permitted as attribute arguments as attributes are evaluated at compile time and using evaluation constants would require “decls in compilation.” We also compute attributes in order to build indices for Facts which may never have access to cross-file declarations. * Using special strings e.g. `__Memoize("KeyedByIC")` — this has the downside of a string argument appears to take arbitrary strings, but can only take specific, special strings. This may also require additional changes to support autocompleting these strings in IDEs. * Creating a new attribute to replace each variant e.g. `__MemoizeKeyedByIC` and `__MemoizeMakeICInaccessible` * If we choose this option, we may consider more fluid names like `__MemoizeWithIC` and `__MemoizeAndMakeICInaccessible` * This has the downside of adding each attribute for memoize and lsb variants, increasing the code complexity in parser/runtime * Creating auxiliary attributes to use alongside `__Memoize` e.g. `<<__Memoize, __MakeICInaccessible>>` * This option has the downside of introducing attributes that can only be used with other attributes which would be especially undesirable for `__Memoize(KeyedByIC)` * We could conceivably allow `__MakeICInaccessible` to be used standalone. However, at the moment, we do not see a legitimate use for it without an accompanying `__Memoize`. ## Naming "KeyedByIC" uses "Keyed" which references the fact that the IC is incorporated into the key used in the memoization cache. We could also possibly use imperative "Key" vs past participle "Keyed." Possible alternatives to the verb "key:" * "Shard" - original verbiage from "PolicyShardedMemoize" but noted possible incorrectly inferred association with database sharding * "Split" * "Partition" "MakeICInaccessible" describes how the IC cannot be accessed. A previously proposed name used the verbiage "clear IC," however this created a distinction between a state where the IC was "cleared" vs one where the IC was never set. Primary concerns with this name are aesthetic: "inaccessible" is long and may be awkward to say and spell. A name like <imperative verb> + "IC" may be preferable, but verbs like "prohibit" or "ban" may incorrectly imply immediate exceptional behavior of the function with the attribute instead of restrictions on the function's dependencies. "Soft" has analogous meaning in the `__Soft` attribute for typehints where behavior that would normally throw exceptions results in logs instead which can be used to eventually move code to the "hard" throwing behavior. “IC” as an abbreviation for “Implicit Context” was chosen for brevity and lack of more attractive options. We concluded that brevity was valuable given expected prevalent usage of these attributes and that the disadvantage of possible ambiguity of “IC” would be offset by the fact that the full symbols names would be sufficiently unique. Other alternatives that were considered: * “IArg” as in “Implicit Argument” — This primary issue with this option is that “implicit arguments” is a feature in other languages with a different meaning. Using this term would both set incorrect expectations for readers with experience in those languages as well as be problematic should we want Hack to adopt a similar feature. * “ICtx” (using “ctx” as an alternative abbreviation for “context”) — The primary objection to this was that while we use “ctx” as an abbreviation for “context” in other features of the language, in those cases, “ctx” refers to a coeffects “context,” which, while there are some tie-ins, the “contexts” in each case are distinct concepts. * “ImplicitContext” — This was considered too long, especially in `__Memoize(#SoftMakeImplicitContextInaccessible)`. * “Ctx” or “Context” (without “implicit”) — This was considered insufficiently disambiguated as “context” is already an overloaded name. A developer may reasonably, but incorrectly, assume that “KeyedByContext” would mean “keyed by the coeffects context.” * Other names: “Implicit Value” or “IVal,” “ScopedValue,” “ContextValue” or “CVal” or “CtxVal” ## Multiple Implicit Contexts The current implementation of Implicit Contexts allows for multiple IC “flavors.” You create a flavor by defining a class implementing the native `HH\ImplicitContext` class. This presents the question for how the above features should work when there is more than one IC flavor. We have identified a few options: 1. **Only allow a single flavor and require any further division of the value to be done in userland.** This has the benefit of simplifying the semantics. This also inherently requires coupling among all flavors, but unless you parameterize `KeyedByIC` and `MakeICInaccessible` features by flavor, the flavors are already tightly coupled since they will need to agree on when these attributes ought to be used. Coupling is also introduced by sharing related coeffects and the backdoor functions. 2. **Track an IC state per flavor and allow individual setting.** Each flavor’s state could be set individual by `runWith` and `soft_run_with` calls, but `MakeICInaccesible` would set all flavors’ state to `inaccessible`. This would likely require more checks at runtime resulting in worsened performance. 3. **Only track flavors in the value state.** Setting one flavor from the `inaccessible` state would resulting in implicitly setting all other flavors’ value to the initial null state. Our recommendation is that we take Option 3 which is closest to the current implementation of Implicit Contexts but require in userland that there is at most a single child of `HH\ImplicitContext`. This effectively means choosing Option 1 from the perspective of the user. This compromise allows us to make fewer changes to the runtime in the near term. We can choose to simplify the runtime to not support multiple flavors at a later date.
Markdown
hhvm/hphp/hack/doc/HIPs/ownership_and_linearity.md
Title: Ownership and Linearity Tracking Start Date: June 26 2020 Status: Postponed ## Summary A system for tracking and enforcement of ownership for Objects, specifically via linearity. ## Feature motivation There are multiple existing or future features for which ownership tracking is required for soundness. The major usecase of this is the Purity project, which will have its own HIP in the coming weeks. However, there are other features, such as const classes and disposables, for which language-level ownership tracking is necessary for soundness. We expect there to be additional future features that can make use of this system. Additional benefits include: 1. HHVM can produce optimizations based on the guarantees described below when utilizing these features. 2. Provability that an API requesting a unique value is actually given one ## User experience ### The Four States of Ownership There are four states of ownership: 1. Unowned (The default) 2. Owned 3. Borrowed 4. MaybeOwned (temp name, looking for alternatives). The main differences between each state are the operations allowed on an object of that state. Ownership is a property of the linearity of an object. Owned and Borrowed objects are enforceably linear, Unowned objects are not, though they may be naturally, and MaybeOwned may or may not be forcibly linear. Described in terms of the operations allowed on them, the states are as follows: 1. Unowned - The default state in hack. May already have aliases (i.e. be nonlinear). May be freely aliased. 2. Borrowed - Cannot be aliased and is a non-owner of the object. The owner of the object is a (possibly indirect) caller, so no other code with a reference to this object can run until this function returns (or further lends the object to a more deeply nested callee). Because of this restriction, we consider the object to still be linear in this state. If the caller did not opt in to stricter tracking aliases may already exist, but the borrowing code will not make new ones. See the next section for more details 3. Owned - Does not have aliases and cannot be aliased. May be lent to a (synchronous or immediately awaited async) callee, which preserves the invariant that at most one runnable frame has a reference. Can transfer ownership and can release ownership, moving the object into the unowned state. 4. MaybeOwned - May be an object in any of the previous 3 states. This state is distinct from Borrowed because some features built on ownership tracking (purity and const classes) need to allow mutations only on linear (i.e. Owned or Borrowed) values. Functions that only need to read from an object will be more widely reusable if they receive objects in this state rather than Borrowed. See the next section for more details As a Table, where LHS is current state, and Column is whether they have a specific capability: | | Has alias | May alias | May move/disown | |:----------:|:---------:|:---------:|:---------------:| | Unowned | maybe | yes | no | | Owned | no | no | yes | | Borrowed | maybe* | no | no | | MaybeOwned | maybe | no | no | \* This is a choice for the caller. If they opt in to stricter tracking, then Borrowed cannot have an alias. See next section. Described in terms of what parameters they may be passed to given that the parameter is defined to be a specific state: 1. Unowned - Can be passed to Unowned or MaybeOwned. Whether it can pass to borrowed depends on whether the caller opts in to stricter tracking. See the next section for more details. 2. Owned - Can be passed to Borrowed or MaybeOwned, or may transfer ownership to Owned. 3. Borrowed - Can be passed to Borrowed or MaybeOwned. 4. MaybeOwned - Can be passed to MaybeOwned. As a Table, where LHS is current state and Column is whether they can be passed to a param of that state (or used as the $this in a method invocation, when otherwise permitted): | | Unowned | Owned | Borrowed | MaybeOwned | |:----------:|:-------:|:-----:|:--------:|:---------:| | Unowned | yes | no | maybe* | yes | | Owned | no | moved | yes | yes | | Borrowed | no | no | yes | yes | | MaybeOwned | no | no | no | yes | \* This is a choice for the caller. If they opt in to stricter tracking, then Borrowed cannot have an alias. See next section. #### Unowned and Borrowed The choice of whether or not unowned may flow into borrowed is a subtle one - one that developers will never have to consider under this proposal. The usecase for not being able to pass unowned into borrowed is enabling of mutations on linear objects (when they'd be banned on nonlinear ones). Consider Rust. They have locally mutable values, which are analogous to our Owned values, and `mut &`s and `&`s, respectively analogous to our Borrowed and MaybeOwned. The key is that rust does not have an unowned state - all values are owned by a single reference. When a system requires linearity to enable mutability, passing an unowned value into the equivalent to a `mut &` is obviously unsafe, as that would result in mutations happening to nonlinear values. Under this proposal, systems that require linearity for the purpose of tracked mutations (such as Const Classes and Purity), would implicitly disallow passing unowned values to parameters etc marked as borrowed. Developers would get an error specifically about this telling them why and they will merely need to conform to these restrictions, often via use of the MaybeOwned state. One may note that this is in fact the main reason for the existence of the otherwise quite similar Borrowed and MaybeOwned state. For systems that don't require this stricter ruleset, those states are functionally identical (although still not interchangeable). For the most part, developers should not need to know or care about this. #### Concurrent uses of tracked objects Borrowed, Owned, and MaybeOwned values may not be used multiple times in the same statement or concurrent block as this creates implicit aliases, breaking linearity. Further, objects of those states may not be passed to async functions if they are not immediately awaited. ``` function takes_borrowed(borrowed Foo $b): void {...} async function gen_takes_borrowed(borrowed Foo $b): Awaitable<void> {...} function takes_two_borrowed(borrowed Foo $b, borrowed Foo $c): void {...} function example(owned Foo $x): void { takes_borrowed($x); // fine takes_two_borrowed($x, $x); // banned // this might be fine because takes_borrowed($x) is finished before bar is called, but banned in V1 to be safe takes_two_borrowed(takes_borrowed($x), $x); takes_two_borrowed($x, takes_borrowed($x)); // as previous // as previous. This might be fine because foo($x) is run synchronously, but banned in V1 to be safe takes_two_borrowed(takes_borrowed($x), takes_borrowed($x)); takes_two_borrowed(await gen_takes_borrowed($x), await gen_takes_borrowed($x)); // banned gen_takes_borrowed($x); // banned - must await immediately } ``` For the above, any use of a local counts as a borrow and the same logic applies for concurrent blocks as these individual statements. Note that invocations like `foo($x)` cannot be returning `$x` internally as that would require aliasing a borrowed value. ### Declaring Objects as Tracked You will note below that there is no way to explicitly state that a value is unowned. There is no usecase we could determine for which this was a useful designation. Note that only one of the following may be used per method object, parameter, and return value, but multiple may occur in the same declaration header. #### Parameters Parameters may be declared to be any of Unowned, Owned, Borrowed, and MaybeOwned ``` public function foo(IFoo $foo): Foo { return new Foo(); } public function foo(owned IFoo $foo): Foo { return new Foo(); } public function foo(borrowed IFoo $foo): Foo { return new Foo(); } public function foo(maybeowned IFoo $foo): Foo { return new Foo(); } ``` #### Return Types Return values may be declared as either unowned or Owned ``` public function foo(IFoo $foo): Foo { return new Foo(); } public function foo(IFoo $foo): owned Foo { return new Foo(); } ``` Returning a Borrowed/MaybeOwned value is forbidden, as doing so would create an alias. Returning an owned value implicitly transfers ownership to the caller. #### Method Objects The object on which a method is called may be declared as Unowned, Borrowed, or MaybeOwned ``` public function foo(IFoo $foo): Foo { return new Foo(); } public borrowed function foo(IFoo $foo): Foo { return new Foo(); } public maybeowned function foo(IFoo $foo): Foo { return new Foo(); } ``` While it is logically sound for $this to be owned, with ownership transferred to the method call, this is not permitted due to runtime considerations. There are major issues with `$this` being available via things like stack traces rather than just within the method itself. Further, unsetting `$this` is not something the runtime can support at present. ### Moving Between States #### Creating Owned Values When an object is created it must explicitly opt in to the owned state by using the `own` keyword, e.g. `$x = own new Foo();`. Any object that is not explicitly created as such is unowned. #### Transferring Owned Values For those who have used C++ and Rust, transferring ownership will be somewhat familiar. Consider the following functions, one that requires to be given an Owned value and the other that creates one as above: ``` function takes_owned(owned Foo $foo): void {...} function creates_owned(): void { $f = own new Foo(); // would like to give ownership of $f to `takes_owned` } ``` Ownership transference is done via the `move` keyword ``` function creates_owned(): void { $f = own new Foo(); takes_owned(move $f); } ``` In order to maintain linear ownership, after `move`ing a value, the variable initially containing that value is unset (i.e. KindOfUninit). In the previous example, attempting to use $f after invoking `takes_owned` would fail. Additionally, as you would expect, attempting to `move` the same value twice in the same statement/concurrent block is illegal. Note that the `move` keyword isn't allowed on the result of an `own` expression. Rather, it is always implicit when necessary e.g. in `takes_owned(own new Foo());`. The other location of ownership transfer is at the return site of a function marked as returning an owned value, as in the following ``` function returns_owned(): owned Foo { $f = own new Foo(); return $f; } ``` Note that the `move` keyword is not required here, as it is trivially determinable from the signature of the enclosing function that an ownership transfer is required. The `own` keyword may be used to receive an owned value from a function marked as returning an owned value. Additionally, if the expression being returned is one on which `own` can be used, `own` is also not required, and, in order to remain consistent, disallowed: ``` function returns_owned(): owned Foo { return new Foo(); } function returns_owned2(): owned Foo { return returns_owned(); } function returns_foo(): owned Foo { return new Foo(); } function creates_owned_foo(): void { $f = own returns_foo(); } ``` Note that it is possible to return an owned value in an async function. In order to receive that owned value, the caller must immediately `await` and `own` the result: ``` async function gen_returns_foo(IFoo $foo): owned Awaitable<Foo> { return new Foo(); } async function gen_creates_owned_foo(): Awaitable<void> { $f = own await gen_returns_foo(); } ``` `Awaitable` is the only situation in which the ownership declaration does not apply directly to the item following it. In this way, it is similar to `__Soft`. Conditionally `move`ing values is currently disallowed. If, in a future version, we change the `move`d variable to be null instead of unset, it is possible we can allow this. As a reminder, any value that _may_ be `own`ed but isn't is implicitly disowned. #### Disowning Values It is sometimes desired to disown a value midway through a function. This is done via the `disown` keyword. ``` function foo(owned Foo $foo): void { // cannot alias $foo here $unowned_foo = disown $foo; // $unowned_foo is unowned. $foo is unset } ``` Note that similarly to `move`ing a value, `disown`ing one unsets the `disown`ed variable. In the same vein, a variable may not be conditionally disowned. #### Linearly Lending Values Owned values may be lent to other functions promising to maintain linearity, and borrowed values may be lent to further functions. This is handled without requiring additional keywords. ``` class Foo { public borrowed function borrow(): void {} } function foo(owned Foo $foo): void { borrow($foo); $foo->borrow(); } function borrow(borrowed Foo $foo): void { borrow_again($foo); $foo->borrow(); } function borrow_again(borrowed Foo $foo): void {} ``` ### Additional information #### Interactions with `null` `null` is a valid value in any state, as it is not actually an object but rather the lack of one. #### Hierarchical requirements Logically, the subtyping rules for the states can be thought of as follows, where (|) is subtyping and ~~> is coercion: ``` MaybeOwned / \ Borrowed <~~ UnOwned | Owned ``` For simplicity, however, the initial implementation will require that hierarchies be invariant in their usages of ownership states. It seems likely that we can enable owned return positions to be subtypes of unmarked return positions, but the rules for, and usefulness of, subtyping relationships for parameters becomes less clear. This includes the usage of the `__Unownable` and `__ReturnsBorrowedThis` attributes, to be described below. #### Properties of objects cannot be owned. At present, properties (including container contents) are always unowned. It is possible that this may be implementable in a future version. #### Preservation of Single Ownership Type Per Variable Name In order to enable performant tracking by HHVM, while retaining a reasonably simple implementation within the emitter, variables may be used to reference at most one ownership state. However, a single variable may be used to reference multiple objects of the same ownership state. ``` class Foo {} function my_function( owned Foo $owned, borrowed Foo $borrowed, maybeowned Foo $maybe, Foo $unowned, ): void { $owned = own new Foo(); // fine, still owned $disowned = disown $owned; // fine, new disowned variable $owned = own new Foo(); // fine, owned again $owned = $disowned; // error $borrowed = own new Foo(); // error $borrowed = $disowned; // error $maybe = own new Foo(); // error $maybe = $unowned // error; $unowned = own new Foo(); // error $owned = own new Foo(); // fine, still owned $disowned = own new Foo(); // error $disowned = new Foo(); // fine, creating implicitly unowned value $unowned = new Foo(); // fine, creating implicitly unowned value $new_unowned = new Foo(); // fine, creating implicitly unowned value } ``` #### Capturing values in closures Locals that contain Owned, Borrowed or MaybeOwned values cannot be captured as that creates an implicit alias, breaking linearity ``` class Foo { public int $foo = 0; public borrowed function capturesMutable(): void { $x = () ==> { $this; }; // error } public maybeowned function capturesMaybeMutable(): void { $x = () ==> { $this; }; // error } } function captures_owned( owned Foo $obj1 borrowed Foo $obj2, maybeowned Foo $obj3, ): void { $x = () ==> { // these are all errors $obj1; $obj2; $obj3; }; } ``` #### Ownership in Constructors Constructors pose something of an unique problem for ownership tracking. In order for tracking to work, one must be allowed to `own` the result of a constructor call. However, if linearity is broken *within* the constructor, then that no longer holds true. The solution landed upon is for constructors to be opt-out for linearity instead of opt-in. In the standard case, `$this` within a constructor is in the `borrowed` state. Following the termination of the constructor, the rules apply as stated above. The opt-out mechanism is via a new `__Unownable` attribute, which indicates that the result of that constructor may not be `own`ed. Additionally, hack errors triggered in a non-opted-out constructor will initially suggest opting out as a last resort after other standard suggestions. This conclusion resulted from analysis of patterns within the FB codebase. Of the very large number of constructors, <3% of them would need to be opted out if no further work was done. However, of that <3%, >95% of them are due to invoking a helper function on $this which is not accepting of a borrowed value. Upon inspection of a random sampling of those helper functions, a large majority of them are trivial to allow accepting borrowed values with no other changes (except for potentially marking a further function). Further, >4% of the problematic constructors arise from capturing $this in a closure, which may become legal in a future update (see Future possibilities section). Thus, only 1% of the problematic cases are ones which require more serious refactoring. The simplest solution for those are to convert them to a builder pattern in which the builder function invokes the constructor and then does any problematic behaviour following it. We may choose in the future to remove this method of opting out. #### Interactions with Memoize Memoized functions may not return values as owned, as doing so would necessarily allow creating multiple aliases to the same object. For objects implementing `IMemoizeParam`, the `getInstanceKey` method must be valid to invoke on the passed object for whichever state the parameter is marked. (e.g. if the param is borrowed, `getInstanceKey` must use a Borrowed or MaybeOwned `this`); Prior to rollout, we will determine whether this is actually necessary or if we can globally enforce a MaybeOwned `this` for getInstanceKey methods #### Interactions with inout An `inout` parameter can neither be Borrowed nor MaybeOwned as these are tantamount to returning such values, which is banned. For simplicity, an `inout` parameter may not be `owned`. It is possible that a future version of this feature will allow this if usecases arise. #### Interactions with the Mutable Builder Pattern The mutable builder pattern is one in which a class contains setters that modify a property and then return $this. This can then be used as a chain to "build up" the object. This becomes a problem when ownership tracking comes into play, as if $this is tracked, then the return statement creates an alias. The problem then becomes how to allow these objects to be built up in the case where the object is tracked while not diminishing the experience for unowned objects for general developers. The solution to this problem for this proposal takes the form of a temporary Hack. A function can be marked with the magic `__ReturnsBorrowedThis` attribute. In the presence of this attribute, the return value can only be used by the caller if the object the method is called on is unowned. Otherwise, the method may be called, but the return value must be thrown away. ``` class Foo { private ?int $val; private ?int $val2; <<__ReturnsBorrowedThis>> public borrowed function set1(int $val): this { $this->val = $val; return $this; } <<__ReturnsBorrowedThis>> public borrowed function set2(int $val): this { $this->val2 = $val; return $this; } } function useit(): void { // this is the standard chaining version $unowned = new Foo(); $unowned ->set1(42) ->set2(1234); // here, since return value cannot be used, must use multiple statements $owned = own new Foo(); $owned->set1(42); $owned->set2(1234); } ``` This is not ideal, but it is required for safety of tracking. We hope that in the future additional features can be added to the language obviating the need for this hack. See the discussion on void chaining linked below. Note that methods with this attribute must act on a borrowed `this` and return exactly `$this`. ## IDE experience The new keywords will be supported in a first class manner with respect to syntax highlighting. There will be a large number of new error types both in the typechecker and parser. Due to the nature of this system, most developers won't see any errors due to the inherent flexibility of the default state. When annotated code calls unannotated code, we can straightforwardly suggest how to annotate the unannotated code to facilitate progress. When annotated code calls annotated code, the error messages will be similar to standard type errors where they will explain why the different states are incompatible and it will be up to the user to fix them. ## Implementation details ### Interaction with other features The initial version of the feature will have no interactions with other hack features other than those explicitly expressed above. Following the rollout of this feature, we expect to utilize it for sound implementations of Purity, Const Classes, and Disposables. Note that the below sections are examples rather than confirmed decisions. It is possible that details about the interactions will change. #### Disposables Disposables currently have their own implemented version of ownership tracking wherein disposables are "owned" by their using statement, and may be lent or given to called functions. This is completely subsumed by this more complete proposal, however they will also have additional restrictions (such as prohibiting disowning them). As an example, here is what currently exists ``` class MyDisposable implements IDisposable { public function __dispose(): void {} } <<__ReturnDisposable>> function returns_disposable(): MyDisposable { using $foo = new MyDisposable(); // error: Variable from 'using' clause may only be used as receiver in method // invocation or passed to function with <<__AcceptDisposable>> parameter // attribute Hack(4180) // return $foo; return new MyDisposable(); } function accepts_disposable(<<__AcceptDisposable>> MyDisposable $md): void { // Parameter with <<__AcceptDisposable>> attribute may only be used as // receiver in method invocation or passed to another function with // <<__AcceptDisposable>> parameter attribute Hack(4188) // using ($md); // same error // return $md; } function takes_mixed(mixed $m): void {} // Parameter with type 'MyDisposable' must not implement IDisposable // or IAsyncDisposable. Please use <<__AcceptDisposable>> attribute or // create disposable object with 'using' statement instead. Hack(4190) // function illegal_param(MyDisposable $m): void {} function example(): void { // Disposable objects may only be created in a 'using' statement or // 'return' from function marked <<__ReturnDisposable>> Hack(4187) // $x = returns_disposable(); using ($x = returns_disposable()) { // Variable from 'using' clause may only be used as receiver in // method invocation or passed to function with <<__AcceptDisposable>> // parameter attribute Hack(4180) // takes_mixed($x); } // Variable $x is undefined, or not always defined Hack(2050) // echo $x; } ``` and how it would look using ownership management (note that all error messages are examples): ``` class MyDisposable implements IDisposable { // won't require `borrowed` on __dispose method because it's always the case. public function __dispose(): void {} } function returns_disposable(): owned MyDisposable { using $foo = new MyDisposable(); // here $foo is borrowed // error: may not return borrowed values // objects in a using block are always borrowed // return $foo; return new MyDisposable(); } function accepts_disposable(borrowed MyDisposable $md): void { // error: may not `use` borrowed values (or must `use` owned values) // using ($md); // error: may not return borrowed values // return $md; } function takes_mixed(mixed $m): void {} // Disposable Parameters must always be Borrowed. // function illegal_param(MyDisposable $m): void {} function example(): void { // Disposable objects may not be disowned // returns_disposable returns an owned value // this value is implicitly disowned here // $x = returns_disposable(); // Disposable objects may not be explicitly owned // they must be used by a `using` block // $x = own returns_disposable(); using ($x = returns_disposable()) { // here $x is borrowed // cannot pass borrowed object to function expecting unowned // takes_mixed($x); } // here $x is destroyed following lending itself to __dispose // Variable $x is undefined, or not always defined Hack(2050) // echo $x; } ``` However, when using ownership management it becomes possible to implement things like potentially transferring ownership of disposables into called functions that must then `use` them. There are a handful of more powerful features required by the HSL IO library in order to make its implementation disposable. Having them powered by ownership allows for these potential additions. Given that they are never unowned, it is illegal to have a typehint of a disposable type without an ownership annotation, typically `borrowed` or `owned`. Conceptually, the object is "owned" by the using statement and is lent to the block scope. #### Purity We're not going to go into too much detail on purity as it is still an experimental feature, and we don't want to have discussions on its merits or decisions at this location. This is another example of the discussion above regarding requiring linearity for the purpose of mutability. In the experimental version, there are 4 states of mutability: 1. Immutable (the default) - an immutable nonlinear value 2. Owned Mutable - an owned linear value that is mutable 3. Borrowed Mutable - a borrowed linear value that is mutable 4. Maybe Mutable - a value that may or may not be linear, so is immutable but also must be treated as if it was linear. The states of this proposal can replace the previous states 1-1: Immutable -> unowned Owned Mutable -> owned Borrowed Mutable -> borrowed Maybe Mutable -> MaybeOwned If Purity is rewritten to use the ownership annotations, it must only add the 2 rules, everything else directly falls out of this proposal. 1. Only Owned or Borrowed objects may be mutated. 2. Value types may always be mutated. One might note that it's possible to pass an unowned value into the system from impure code calling pure code, but that is no different than the current state of the feature. To be completely clear, this will completely replace the experimental mutability annotations added by the reactivity project. #### Const Classes The design for const classes prior to this proposal worked fairly simply. They can be modified within the constructor as well as from within private methods called by the constructor, however once the constructor finishes, the classes "lock" and become immutable. However, this has a pretty unfortunate typehole: ``` const class MyConstClass { private int $x = 0; public function __construct() { $this->can_mutate(); } private function can_mutate(): void { $this->x = 42; } private function my_unrelated_method(): void { // do stuff } public function oops(): void { $this->my_unrelated_method(); $this->can_mutate(); // uhh.... } } function example(): void { $cc = new MyConstClass(); $cc->oops(); // explode } ``` This problem is solvable via a combination of ownership management and making const classes more powerful. The solution is simple: opt const classes into the stricter ownership tracking and making them immutable when unowned. ``` const class MyConstClass { private int $x = 0; public int $even_more = 42; public function __construct() { $this->can_mutate(); } private borrowed function can_mutate(): void { $this->x = 42; } private function my_unrelated_method(): void { // do stuff } public function oops(): void { $this->my_unrelated_method(); // error: cannot call function with borrowed $this // $this here is unowned // $this->can_mutate(); } } function example(): void { $ncc = own new MyConstClass(); $ncc->even_more++; $cc = disown $cc; $cc->oops(); // safe! } ``` In this system, all instances or typehints of a const class will be opted-in to the stricter tracking. Further, const classes can now make use of the extended constructor pattern! ### HHVM Support This feature will have full HHVM support and enforcement. Objects may only be used as described above or else they will throw an exception. For cross-function boundaries the enforcement will work similarly to type enforcement. ### Codemodding The only major codemod required for this feature is the interaction with constructors described above to insert the `__Unownable` attribute where necessary. Other than that, no codemodding for this will be done except to convert the current Disposables and temporary Mutability tracking feature to this complete one. In that case, we will first do a static transformation from the old attributes to the new system to confirm everything still typechecks. ## Revert Plan If, following rollout of this feature, we decide to remove it, reversion will simply be a codemodded removal of the associated keywords. However, if used within Purity, Const classes, and other major features, it becomes increasingly difficult to roll back without exposing major soundness holes in the language. Note, however, that the initial plan is to have the system implicitly back both disposables and the experimental Reactivity/Purity syntax under the hood, so we should hopefully know prior to full rollout if revert is necessary. ## Design rationale and alternatives This design was created under a few basic principles: 1. Opt-in feeling: It is important for a large codebase that this need not be the default 2. Usability: The states are not conceptually difficult and hack-errors can be used to direct newcomers towards correct patterns, as situations of the form "You are doing A, which is wrong, but B would be OK" are common. 3. HHVM Enforceability and efficiency: In order to be used for optimizations, HHVM must be confident of the guarantees. Therefore, it must be enforceable. Therefore, it must be efficient. This is a completely new segment of the language such that attempting to do this via existing features is a nonstarter. Not doing this prevents multiple projects, either via soundness issues or simply lack of required featureset. See above for examples. ### Alternative designs There are multiple minor tweaks considered to the above syntax. Instead of `public borrowed function foo(): void {...}`, we considered `public function foo(): void where this is borrowed {...}`. We decided against this as, while it makes it clear we're referring to `this`, it requires modification of function-level where clauses and is extremely verbose. It is worthwhile to note that `static` appears in the same location and is a modifier that describes the state of `$this` We considered the keyword `owned` instead of `own` for marking a value as owned, but don't believe the extra two letters add anything. We considered referring to the unowned state as disowned, but this is confusing for things that are never owned. As an alternative to `__ReturnsBorrowedThis`, we would like to resurrect the [void chaining](https://fb.workplace.com/groups/1353587738066495/permalink/1690769081015024/) discussion. This allows us to use the fluid builder pattern on non-unowned code, but also allows for the potential to completely remove the pattern of functions that return $this for the purpose of chaining. An alternative to the `disown` keyword is to use `release`. Bikeshedding welcome. The __ReturnsBorrowedThis attribute is technically unnecessary as the emitter can infer when it would be required and handle the situation appropriately. We think it's better to be explicit here. When owning the result of an async function, should the `own` be before or after the `await`? We landed on before because you're `own`ing the wrapped value, not the Awaitable. Maybe there are arguments for the alternative? ## Drawbacks It is complicated and requires significant runtime and typechecker support. ## Prior art At present, there is only one major language implementing an ownership system. There are a handful of languages implementing Linearity systems, however that does not map particularly well to an imperative language like our own. Rust's ownership tracking is more robust and allows for nested ownership tracking (such as owned properties) and explicit lifetimes. This is made possible as they have an AoT compiler that can do enforcement and analysis. We have different constraints. Further, we do not require quite the same complexity. This can more simply be described as `borrowed T -> &mut T` and `own T -> T`. However, rust doesn't typically allow for unowned values. The closes it comes is `&T` immutable references. These are references to an owned value that is merely being utilized multiple times at once (and so must be immutable). In general, our requirements are flipped. They want everything owned. We want most things unowned with specific things being owned. Additionally, there a handful of other languages actively exploring this space: [Swift's ownership manifesto](https://github.com/apple/swift/blob/master/docs/OwnershipManifesto.md) is designed based on different constraints and purposes. Ours is mostly to unblock other features, while also enabling some performance gains. Their purposes are flipped. [Haskell](https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0111-linear-types.rst#id22) with [tech talk](https://www.youtube.com/watch?v=o0z-qlb5xbI&t=1s): Rather than discussing linearity of values, they describe linearity of functions, such that for a fn a -> b, if b is consumed exactly once, then a is consumed exactly once. They implement polymorphism by taking in closures and making the overall linearity of the function be polymorphic upon the linearity of the passed function. Further, they do not have the concept of borrowing linear values, which is extremely important to our system. [Clean](https://clean.cs.ru.nl/download/html_report/CleanRep.2.2_11.htm): Clean has a similar system to Haskell except that it's type-based rather than function based. It has some similar properties to our system, but considers non-unique <: unique because of its functional nature, such that you can pass uniq values into a function accepting non-uniq, but what you get out is nonuniq. In general, these all apply to consumed inputs, thus they don't have the borrowed state. They do have a generic on types to specify propagation of uniqueness, but again, this requires the move in -> move out scenario. [Idris](http://docs.idris-lang.org/en/latest/reference/uniqueness-types.html): They use dependent typing for this and have discovered the need for a borrowed state but have not yet handled the polymorphic MaybeOwned state. They have a representation for Owned V Unowned, but specifically note that it doesn't allow for representation of borrowed. It's more similar to Haskell's polymorphism due to its lack of a borrowed state. Also, from another paper or note: > Uniqueness types, in Idris, are being replaced by linear types #### Papers on the subject: [Islands: aliasing protection in object-oriented languages](https://dl.acm.org/doi/10.1145/117954.117975) (by John Hogg) (paper available upon request): The overall goal here is to create "islands" of objects in which they are, as a whole, only referenced via a single "bridge" such that all modifications to the island (or even access to it) must go through the bridge. Thus, they may handle things like side effects, which are nonissues for const objects and disposables, and general alias management and concept encapsulation. Three major concepts: `read` `unique` and `free` where `read` is similar to const, and the other two are about whether aliases are allowed. > A variable z many be unrestricted, read, unique, free, read and unique, or read and free. Interestingly, here 'unique' means that there is only one reference to an object via the heap (such as instance properties), and the rest are stack-based, and `free` means there are no heap-based references to the object (even if the object itself is on the heap). A unique object is most often used via lending it out on the stack, similar to our `borrowed` parameters. They don't need two keywords because `unique` appears on things like instance properties to imply its the only heap-based reference and on parameters to mean that it's a reference to a `unique` object. However, in many ways, their `free` is similar to our `owned`. You can create a `free` reference by destructively reading a `unique` heap-based reference. Further, `free` references can only be accessed via destructive reads (creating another `free` refence or assigned into an `unique` one). I honestly, don't understand this restriction and description. > If a method receiver is unique, then every parameter and the result must be > read or unique or free. > Unique is a transitive property. If an object’s acquaintances are aliased, > then the observable state of the object may be unexpectedly changed, even if > there is no aliasing of the object itself. Therefore, an object being accessed > as unique must not import or export any unprotected references. An unprotected > parameter could be retained by the object, however. This doesn't apply to `free` receivers, because it doesn't matter. This is an interesting approach for allowing tracking of members. However, this doesn't solve our problem with the `unique` object being referenced from within an `unrestricted` object, which they don't talk about as far as I can tell. As a side note, they don't cover practical problems of code deduplication and/or polymorphic states, which are the main problems we generally struggle with. They do generally seem to have an opt-in system, however, in that that outside an "island" everything can just be unrestricted, and only when interacting with an island must things be annotated. [Alias burying: Unique variables without destructive reads](http://www.cs.uwm.edu/faculty/boyland/papers/unique-preprint.ps) (by Boyland) > Alias burying: when a unique field is read, any existing aliases are > required to be dead. Together with restrictions on aliasing across procedure > calls, alias burying can be checked by a static analysis in a modular fashion. Their main goal is to be able to track mutations for safe concurrent reads, which, while not identical to our goals, is more or less translatable. They concur on our decision to mark misbehaved constructors > A constructor can keep a reference to the object it is creating in a globally > accessible location; not all constructors create unshared objects. Thus a > constructor that does create an unshared object should be declared as such. > ... > Constructors in Java are not responsible for creating an object, just > initializing it. Therefore constructors that “return” unique objects are > annotated as having borrowed receiver Their system of ownership and borrowing seems *very* similar to our own > An alias of a variable for our purposes is a variable that refers to the same > object as the first variable. This definition is nonstandard, but is convenient > for languages such as Java that do not have explicit dereferencing > A static alias is a field variable; a dynamic alias is a receiver, parameter, > local variable, or return value alias > A dynamic alias of an otherwise unique variable is also known as a “non-consumable,” > “uncaptured,” or “limited” variable. > Such a variable may be used for computation and copied into other local > variables or parameters (which become dynamic aliases) but must never be stored in a > field. In this paper, we refer to variables whose values may never be stored > (or returned) as borrowed variables. They recommend using `borrowed` to refer to a value that may either by a dynamic alias to an owned object or an unowned object. However, they further recognize that the existence of a union state of this description results in issues with tracking mutations. > Weakening a uniqueness variant to admit dynamic aliases makes it easier to > program with unique variables than with destructive reads alone, but this > weakening comes with a cost. One main purpose in avoiding aliasing was to make > it easier to isolate mutations; dynamic aliases make it harder to track down > all mutations. They allow for unique static aliases (our borrowed) similarly to Hogg, above. In general, their states are Unique, Unrestricted, and Borrowed. As far as I can tell this works in a system that cares only about aliasing and not restricting mutations to linear values because you don't need dynamic aliases that are required to be references to unique objects. They allow modifications to Borrowed objects. This seems to generally safe only because they mark mutating methods as `synchronized`, which alleviates any interleaving concerns automagically. I'm not quite clear on how that works, however, given that reads can happen in nonsynchronized methods. > When a unique field of an object is read, all aliases of the field are made undefined. > If we can determine statically that no alias is ‘buried alive’, no dynamic > checks will be necessary. Their goal is to statically prove that this invariant holds true such that unique properties _must_ actually be unique dynamically. We prove that via a combination of static and dynamic checks (because we can't trust types, therefor disallowing us to trust that function invocations comply). Their hierarchy of states is Unique/Owned <: Owned/Shared <: Borrowed/Shared <: undefined Unique/Owned: only allows for explicitly unique values and they must be moved in destructively. Owned/Shared: allows for either unique or shared values and generally can treat them as shared. After passing a unique value to this, one can no longer presume uniqueness Borrowed/Shared: May be unique or shared, but my not generate new aliases except to pass to other borrowed notated states. > A shared (that is, not unique) parameter may be declared borrowed This sentence in isolation is somewhat inscrutable. Based on context and later descriptions, I believe this is noting that a shared value may pass into a parameter declared as accepting borrowed. This seems *potentially* fine considering it's specifically stricter, but it doesn't allow making any assumptions about borrowed parameters > a unique value may be passed to a procedure expecting a shared parameter, but > a borrowed value cannot be This explicitly allows for passing unique values into params expecting shared. This seems like a tenuous assertion if you want to statically prove unique objects aren't leaking refs. They further note that > The analysis also uses an annotation on procedures that indicates which variables it may read but then never mention this again. I believe this is specifically related to fields on passed in objects. > The interface annotations may be read as obligations and dual privileges: > > **unique parameters** The caller of a procedure must ensure that parameters declared unique are indeed > unaliased. A procedure may assume unique parameters are unaliased. > > **borrowed parameters** A procedure must ensure that a borrowed parameter is not further aliased when > it returns. A caller may assume that a borrowed actual parameter will not be further aliased when > the procedure returns. > > **unique return values** A procedure must ensure that a return value declared unique is indeed > unaliased. A caller may assume that a unique return value is unaliased. > > **unique on proc entry** The caller of a procedure must ensure that any unique field read or written by > the procedure (or by a procedure it calls, recursively) is unaliased at the point of call. A procedure > may assume that the first time it reads or writes a unique field, the field has no (live) aliases. > > **unique on proc exit** A procedure must ensure that any unique field it reads or writes during its > execution is unaliased upon procedure exit, and that no fields have been made undefined. A > caller may assume that a procedure does not create any aliases of unique fields or make fields > undefined > > If all procedures fulfill these responsibilities, then the only potentially live variables that may be made > undefined due to alias burying in a procedure are variables set by this procedure. Thus assuming we > can check a procedure, we can check a program From what I can tell, the first three have to do with annotations on params/return values and the last 2 are just general invariants all methods must adhere to. How they assert that this magically allows for static assertion of correctness is beyond me. They certainly don't explain it. In general, their restrictions on unique and borrowed are identical to ours. Having their shared state be a supertype of unique and a subtype of borrowed is somewhat baffling. If we consider our lack of unique member variables, the last two restrictions become moot, but the ability to pass unique references to effectively unrestricted params accepting shared values is confusing. > Of course, accessing unique fields of possibly shared objects must still be properly > synchronized in order to prevent race conditions. When the lock is released, > the unique field must be uncompromised and have no live aliases. If a language > has asynchronous calls (Java does not), then we must add the rule that > borrowed values cannot be passed in such calls Not accepting borrowed inside async calls is an interesting concept, but seriously limits the usability in our system. All in all, this system strongly resembles our own, but takes a hard left turn at a crucial fork and ends up in a place that doesn't quite solve our problems [Linear Haskell: Practical Linearity in a Higher-Order Polymorphic Language](https://arxiv.org/pdf/1710.09756.pdf) A relevant quote: > Seen as a system of constraints, uniqueness typing is a non-aliasing analysis > while linear typing provides a cardinality analysis....The former aims at > in-place updates and related optimisations, the latter at inlining and fusion. In general, their system does not neatly correlate to our needs for the above reasons. [Promises: Limited specifications for analysis and manipulation](https://courses.cs.washington.edu/courses/cse590p/00wi/promises.pdf) (By Chan, Boyland, Scherlis) Their system of uniqueness management generally seems to mirror our own. They consider both the general concept of unique references and the issue of ill-behaved constructors before noting that being able to pass unique references to parameters that promise not to store lasting aliases do not cause additional problems. They refer to these as `limited`. They, too, consider `limited` to be a promise rather than a requirement. This is contrasted with `unique` parameters that *require* the object passed in to be unique (and consumed upon passing). This is similar to the concepts by Boyland in his above paper (which actually came later than this one). > Since the caller’s copy of the reference cannot be accessed during the dynamic > context of the call, one can pass a unique reference as a limited unique > reference instead (as long as the reference isn’t passed as more than that one parameter). > Limited unique parameters are unaliased within a certain dynamic context and > have the properties of both unique and limited parameters Their `unique` is obviously analogous to our `owned`. limited` is generally analogous to our MaybeOwned with `limited unique` being their borrowed. They additionally consider the possibility of storing unique values within other objects: > `Unshared fields` are really no more than a form of unique variable, except > allocated in the store as part of an object. Similarly static unshared fields > hold unique references associated with the class object. > A problem with unshared fields is that they invalidate the assumption that a > variable, and thus the reference it contains, is only accessible from a single > frame. For instance, suppose that within a class with an unshared field, we > call a method with the reference from this field as a parameter. Since there > is no guarantee that the object with the unshared field is itself unique, we > cannot assume the field will be inaccessible during the call. > A simple solution to this is to use a promise that guarantees that the code > being called will not access that field. Thus, we only allow an unshared field > to be an actual parameter if it is passed as limited and the method to which > it is passed does not read or modify the region for that field. As a > consequence, if we have existing code that does need to access that region, we > may have to nullify the unshared field during the call. All in all, their description of this system is given in relatively short order, but is quite analogous to our own. [Deny Capabilities for Safe, Fast Actors](https://www.ponylang.io/media/papers/fast-cheap.pdf) The overall goal of this system is to allow statically checkable safe shared memory. Their system is interesting. It is effectively a matrix of whether local/global/both aliases are allow to read and/or write to a reference. They make the interesting choice to note receiver state between the fn keyword and the fn name. This seems unenforceable statically (box being disallows global writes): > If an actor has a box reference to an object, no alias can be used by other > actors to write to that object. This means that other actors may be able to > read the object, and aliases in the same actor may be able to write to it > (although not both: if the actor can write to the object, other actors cannot > read from it) Like us, they separate between methods that can be run asynchronously and ones that don't. It's not safe to give a `box` to a method that can run asynchronously, because the caller can retain a locally mutable instance, so the async method could read while the caller does some writes. We ban this via strict limits on borrowed objects in concurrently executed statements. They note that passing an owned value to another async method is safe because it is destroyed in the caller. They suggest that `tag` (all aliases allowed) cannot be read/written, but may have further async methods invoked upon them. Those async methods may see `this` as `ref` (no global aliases, all local aliases). They consider `tag` objects to be `actor`s (the objects on which async methods are invoked). I don't understand why this distinction makes mutating their inner state safe. Apparently you can store tag reference to an otherwise iso (global deny, local allow) reference > a newly created alias of an iso reference must be neither readable nor writeable (i.e. a tag). At this point, I decided that the system described was significantly more complicated than our own with questionable applications to our problemspace. I skimmed the rest of the paper and determined that I was correct. [Ownership types for flexible alias protection](http://janvitek.org/pubs/ecoop98.pdf) (by Clarke, Vitek, Potter, Noble) (this won "the most influential paper of the last decade" at OOPSLA'16) The overall goal of this paper is to statically ensure abstraction implementation encapsulation such that given an abstraction A exposed via an API on object B implemented on classes C...N, the internals of the implementation of the abstraction A via C...N cannot be referenced outside of B and the API must be utilized to realize the abstraction. They note that value types don't require tracking because they're immutable (or in our cases, sometimes COW). They suggest the concept of splitting the workings of a container into two pieces: mutable state that is visible only internally, and immutable state that is fine to expose (and even potentially share between multiple containers). It is further possible that for nested containers, the exposed immutable state may actually be the inner mutable state for an inclosing container. In this way, it is noted that the immutabile set of an object is only immutable to that object, but not necessarily to the outside. They consider the concept of "roles", which map to the different set types. This is used for the purpose of more abstractly separating (and keeping separate) of sets. An important quote that also applies to our own system: > Note that although they are similar, aliasing mode checking and type checking > are completely orthogonal. An expression’s aliasing mode correctness implies > nothing about its type correctness, and vice versa. > The aliasing mode system comprises the following modes: arg, rep, free, var, > and val. These modes are/work as follows: arg: The state visible externally. > only provide access to the immutable interface of the objects to which they > refer. There are no restrictions upon the transfer or use of arg expressions > around a program rep: The state invisible externally. > Can change and be changed, can be stored and retrieved from internal containers > but can never be exported from the object to which they belong free: Objects with a reference count of exactly 1 (such as recently created objects). var: "provides a loophole for auxiliary objects which provide weaker aliasing guarantees" Works like the default semantics of non-alias checking languages except for the assignment compatibility constraints. > a mutable object which may be aliased. Expressions with mode var may be changed > freely, may change asynchronously, and can be passed into or returned from > messages sent to objects val: Value types. The following is because their value types are truly immutable rather than COW: > has the same semantics as the arg mode, however, we have introduced a separate > val mode so that explicit arg roles are not required for value types Arg and Rep modes can be further tagged with Roles to ensure that two object of the same mode but designed for different purposes cannot intermingle. None of these modes are assignment compatible except for `free` which can be used for any of the others. They note that depending on the overall API of an object, it may or may not be aliased in different ways. > For example, if an object uses only modes arg, free, and val, it will be a > “clean” immutable object, that is, it will implement a referentially transparent > value type. If all of an object’s method’s parameters and return values (except > the implicit self parameter) are restricted to arg, free, or val, the object will be > an alias-protected container with flexible alias protection, and if in addition it > has no variables of arg mode, the object will provide full alias encapsulation. All in all, this is an interesting system, but one that is designed around different and incompatible restraints from our own. This can potentially be mimicked via something like considering pure contexts rather than pure functions, but that doesn't allow for the solutions to other language requirements. [Gradual Ownership Types](https://ilyasergey.net/papers/gradual-esop12.pdf) (By Ilya Sergey and Dave Clarke) The overall goal of this paper is to explain a system by which ownership annotations can incrementally be added to a system, similarly to how an untyped program can have types added to it incrementally. They focus primarily on the situations involving nested ownership, which results in being less applicable to our usecase. Further, their goals are mostly related to proving soundness of the overall system. They spend the vast majority of the paper laying out the precise proofs and mathematical properties of the system, which has less obvious applications to us. It might be useful to have someone with a better theoretical background take a look at this. [An object-oriented effects system](https://www.researchgate.net/publication/221496521_An_Object-Oriented_Effects_System) (By Greenhouse and Boyland) The overall goal of this paper is to describe a system by which two method calls can ensure that neither mutates state available to the other, allowing things like better interleaving. This is an obvious corollary with our goals in doing ownership tracking to ensure sound purity enforcement. They define "regions", which can be thought of as similar to namespaces except that they are defined within classes and their contents can be one or more properties. When defining a property, the region they are within is specified. Lack of specification implies the `Instance` region, which lives inside the global `All` region. They also include the concept of static regions containing static members (and doesn't live inside the Instance region). Following this, methods specify which regions (if any) they act (read and/or write) on. The typechecker guarantees both that these are true statements locally and that they are transitively true. Overall, this is effectively another layer of private/public/protected specifiers that typically exist for more fine control over encapsulation layers. They additionally allow for members to be marked as `unshared`, stating that referring to the object requires going through that member, as well as `unique` on parameters and return values, allowing for ensuring that those objects have a ref-count of 1. `Unshared` is entirely used for the purpose of promising that internals are not shared. They note that `Unique` and newly created objects don't require effects tracking due to their linearity. All in all, this system is powerful and fascinating, but doesn't handle issues arising from dealing with the relative capabilities of non-members (such as parameters) in a way that is ergonomic. I can certainly see such a system being generally beneficial for the purpose of encapsulation of different concepts described within members of a class, but for the purpose of generalized ownership/uniqueness (and the benefits it yields), this doesn't satisfy our constraints. [Capabilities for uniqueness and borrowing](https://link.springer.com/content/pdf/10.1007%2F978-3-642-14107-2.pdf) (By Haller and Odersky) [Kilim: Isolation-typed actors for java](https://www.malhar.net/sriram/kilim/kilim_ecoop08.pdf) (By Srinivasan and Mycroft) [Uniqueness and reference immutability for safe parallelism](https://www.cs.drexel.edu/~csgordon/papers/oopsla12.pdf) (By Gordon, Parkinson, Parsons, Bromfield, and Duffy) [Copying, sharing, and aliasing](https://www.researchgate.net/publication/2821935_Copying_Sharing_and_Aliasing) (By Grogono and Chalin) ## Unresolved Questions Do we want to elide `own` in return statements as described above or we rather it be explicit? e.g. in a function that is marked as returning owned, do we have `return own new Foo()` or `return new Foo()`? Note this also applies if instead of `new Foo()` we were invoking another function that returning an owned value. For the initial rollout, should we only allow usage of this feature in the presence of cases that require the feature (i.e. const classes, disposables, and Pure/Rx)? This would ensure a tighter rollout that wouldn't affect quite as many developers. Would we want something like class-level where clauses to mark that *all* methods on a class required, for example, borrowed `$this`? Is `own $f = new Foo();` a viable alternative for creating a newly owned value? The major problems are for things like this: `function foo(own Foo $f): void { }` `foo(own new Foo());` We could potentially elide `own` on constructed objects being passed directly to things requiring an owned/borrowed/etc object. However, this doesn't work quite well for functions that return owned values. Should we require specifically that params etc with ownership notations have types (in the runtime)? Should we require (in hack) that the types of params etc with ownership notations be a class or interface? (this would be changed if we want to track value types) Should we ban using ownership notations with mixed, dynamic, unbounded generics, etc? ### The general question of naming Suggestion: rename "Borrowed" to "Uniquely Borrowed", or "Unaliased" Suggestion: rename "UnKnowed" to "Shared" as it's similar to C++ use cases for shared_ptr. Suggestion: rename "MaybeOwned" to "Restricted". ``` function foo(restricted Foo $f): void {} public restricted function foo(): void {} ``` From the user perspective, it is nonobvious what restricted means here. Further, we can imagine that restricted is a bit too vague considering potential restrictions other than ownership. Suggestion: rename "UnOwned" to '_' or '_&'. MaybeOwned feels similar in concept to a polymorphic type/generic, and it works out to being roughly the same as a "top" type. The problem for this is similar to the above reasoning for restricted. Without context, it's unclear what this refers to. Suggestion: rename "Unowned" to "NonLinear". Looking at the hierarchy, it's clearly not linear and "MaybeOwned" behaves like a wildcard type. Then we have the following taxonomy: Linear: Borrowed, Owned Nonlinear: Unowned->NonLinear Either (exclusive): MaybeOwned Should we generally re-describe this from `ownership` to `uniqueness`? Something like Old -> New, Keyword Owned -> uniq, `uniq` Borrowed -> uniq ref, `uniq&` / `&uniq` MaybeOwned -> maybe uniq ref, `uniq?&` / `?uniq&` / `?&uniq` etc unowned -> nonuniq ref, still no keyword with the state-changing operations being `move`, `uniq`, and `share`. The new version of MaybeOwned feels a bit soupy. Maybe just `?uniq` or `uniq?`? Suggestion: unowned -> Shared, Owned -> Uniq, MaybeOwned -> MaybeUniq, Borrowed -> Borrowed Suggestion: MaybeOwned -> top/mixedref? ## Future possibilities Mostly discussed in the interaction section above. We may want to allow lambdas to close over owned/borrowed values as long as they are specially marked and themselves treated as borrowed values. ``` function foobar(vec<int> $v): vec<int> { $f = own new Foo(); return Vec\filter($v, borrowed ($i) ==> $i < $f->num); } ``` Potentially relax some restrictions on using borrowed/owned values multiple times in the same statement if/when we can prove soundness. Could we have some way of marking an arbitrary class/hierarchy as required to always be linear? Useful for things like disposables but also generators, where trying to iterate them more than once goes badly. Maybe promote to keyword later? Should we have an annotation to generally opt-in whole functions to the stricter tracking for those who want to utilize the stricter system? This would probably utilize the coeffects system to enforce transitivity Hack Native has specifically requested we don't close the door on the possibility of utilizing this system to globally track Arrays and strings in order to avoid the need for refcounting them. The major blocker for this is that for that to work, those types would need to *never* be unowned, which would result in a huge usability degradation. ### Deeper Tracking We could potentially allow properties of objects to be tracked as well. This area has not been too deeply explored due to our lack of obvious need for it. However, were we to add this, here are some considerations: Some options: 1. We'd have to do something special when you disown the containing object such as recursively disowning any properties. 2. Ban disowning such objects (linear forever) 3. When disowning objects, if they have any props marked as containing owned, assert they're null or throw. That would work in the runtime but it would be difficult for the typechecker to enforce (since it would have to keep track of if every owned prop is null or not). Note that we'd have to extend the "passing multiple refs" rule to include referencing a prop and the outer object at the same time. ## FAQ There are a handful of questions that don't fit in the above HIP, but were themes among feedback received. **Q** Should we consider making the unowned -> borrowed conversion opt-in via an <<__AllowUnowned>> attribute on the function decl header? This makes the system strict _unless_ explicitly opted out. **A** This makes the system more complicated and is probably the wrong default. **Q** Do we need a __Soft equivalent? **A** Since unowned can flow into most things, a __Soft doesn't buy much. **Q** HHVM can produce optimizations based on the guarantees described below when utilizing these features. Can I break these guarantees with HH_FIXME, typeholes, or abusing erased generics? If so, what happens? **A** No. While we're likely to require types while using this feature, the assertions made here are fully enforced by the runtime. The ownership concept is fully reified regardless of the static types themselves. **Q** what guarantees are we trying to provide via ownership system, and specifically the "borrowed" state? More specifically, how does this apply when mixing normal objects and disposables? **A** A combination of strong and weak lifetime guarantees. The important piece is that these objects don't get mixed. Const classes and disposables are perma-opted-in to stricter tracking, so they get "strong" lifetime guarantees. Further, anything in the `owned` state has a strong guarantee. The only weak guarantee comes into play with the borrowed state, since that can actually be nonlinear, but the guarantee there is from that point on it will stay linear. **Q** can `own` be implied by `new` or is the `own` keyword just there for clarity? **A** no. Not all created objects are tracked and owned. Many objects are never logically owned. **Q** why `$f = own new Foo();` instead of `own $f = new Foo();`? **A** The problem comes into play for things like this: ``` function foo(own Foo $f): void { } foo(own new Foo()); ``` For runtime enforcement, we need to correctly forward `owned`ness across function boundaries. This may be possible in the case of an explicit `new`, but becomes even more complicated in the presence of functions returning owned **Q** Can you disown a value received from a function invocation? Would there be any advantage to doing something like that rather than let it implicitly become unowned? **A** You cannot, and at present there isn't an advantage. **Q** Will most code need to use these annotations? **A** We generally expect the majority of code not to need to deal with ownership at all. **Q** Why would a developer want to use this feature? What patterns should they look for in their code that will make them want to track ownership? **A** We don't expect most developers to want to generally opt in their codebase. We give most of the "worry free" parallelism rust gives by using an asynchronous model rather a true parallel one. There will likely be rare cases where users want to maintain linearity for the lifetime of an object, in which case this can be used to give them type-and-runtime level guarantees. The most likely scenario for use will be very hot code that uses these annotations to tell the runtime that it may safely elide reference counts and do other optimizations. **Q** Would the design be different if we had types in compilation? What would be different? Would it require fewer annotations to the code? **A** Types in compilation enable a handful of more powerful features such as more deep tracking. However, as with typing, we would still need the declarations to contain the developer intent. It is possible that some of the function-local restrictions such as single-flavour-per-local could be relaxed. It is also possible that more inference about the function-local state of objects could be inferred rather than requiring explicit owning and disowning. See below about lambdas. **Q** Same question as previous but with just declaration level information **A** Declarations in compilation unfortunately do not yield much useful information for this feature. We could be smarter about handling named top-level functions, but that doesn't buy us much. **Q** How should I think about this ownership system. It isn't a type right? So it wouldn't make sense to write say `type OwnedC = owned C`? How about `vec<owned C>`? **A** ownership is conceptually a parallel concept to typing in most cases. Ownership is an attribute of an object the same way the type is, but ownership state isn't a type. It's possible we could implement aliases, but because we rely strongly on compile-time guarantees for efficiency, that has not been investigated for the first iteration of this feature. `vec<owned C>` doesn't make sense because we only have shallow ownership tracking. If we some day allow for deep tracking, we will likely revisit this. **Q** How will this interact with lambdas? Will ownership annotations need to be placed on parameters? Can they be inferred? **A** Ownership annotations will be required. From the perspective of this feature, they are equivalent to any other function declaration. Types in compilation may allow us to avoid this requirement. **Q** How does this relate to projects like Co-Effects? **A** This is mostly orthogonal to Co-effects. There will likely be some co-effects that add/remove capabilities based on ownership state (such as mutability in pure code), but otherwise one does not depend on the other. Co-effects are about function-level contexts and ownership tracking is object/instance/variable specific.
Markdown
hhvm/hphp/hack/doc/HIPs/pure_functions.md
# Purity ### Feature Name: Pure Functions ### Start Date: August 28, 2020 ### Status: Candidate # Summary: Hack functions that are deterministic, idempotent, and do not result in side effects. Feature motivation: Fixing codegen is a major initiative within Facebook. There are two currently unsolved problems: 1. Some major uses of codegen require dependency tracking in order to determine when to regenerate code. If the dependencies aren’t pure, then running codegen may have different results without reflecting changes in the file system, meaning the dependencies aren’t statically trackable. 2. A common pattern of codegen is to compute a large map and then store it to disk to avoid constantly recomputing it. Using creative automatic dependency tracking, HHVM can maintain a server-local cache of these maps that only gets recomputed when an underlying dependency changes (which is when codegen would need to run anyway). In this way, we can avoid writing these maps to disk as codegen. # User Experience: Pure functions will utilize the coeffects framework. As such, the way to mark a function as pure is simply this: `<<__Pure>> function my_fn(): RetType {...}` There are a few relatively simple restrictions on what is allowed within pure functions. ## Pure Transitivity Pure functions may only invoke other pure functions, though may be invoked by impure functions. This all falls out naturally from the coeffects system. ``` function my_impure_fn(): void {/* terribly impure things */} <<__Pure>> function my_pure_fn() void { my_impure_function(); // whoops } function my_other_impure_fn(): void { my_pure_fn(); // fine } ``` ## No Accessing Global State Writing to global state results in side effects. Reading from global state results in the loss of idempotency. As such, accessing global state is simply wholesale banned in pure functions. This includes such things as superglobals and static members. ``` class Foo { public static int $foo; private static int $bar; <<__Pure>> private static function getBar(): int { // Static property cannot be used in a pure context. (Typing[4228]) return self::$bar; } } <<__Pure>> function rx_func(): void { // Static property cannot be used in a pure context. (Typing[4228]) Foo::$foo; // Superglobal $_GET cannot be used in pure function. (NastCheck[3041]) $_GET; } ``` ## No IO IO is effectively an example of accessing global state. The only way to do IO in hack is to utilize functions exposed by HHVM or via an intrinsics such as `echo`. The former will simply not be exposed as pure and the latter are banned operations within pure functions. ``` <<__Pure>> function pure(): void { // `echo` or `print` are not allowed in pure functions. Hack(4226) echo 'foo'; // `echo` or `print` are not allowed in pure functions. Hack(4226) print 'par'; // Pure functions can only call other pure functions. Hack(4200) fgets(STDIN); } ``` ## No Modifying Local Objects By default, hack objects can have multiple references to them, including those potentially stored outside of the pure context or simply visible to another frame of execution. Due to this, modifications of objects is illegal and all objects are considered immutable within pure functions. This restriction is relaxed only for the `$this` object within constructors. Note that this means that functions on Hack Collections modifying the collection are necessarily impure. ``` class Foo { private int $bar; // both explicit and implicit assignments here are fine <<__Pure>> public function __construct(int $bar, public string $baz) { $this->bar = $bar; } <<__Pure>> public function setBar(): void { // This object's property is being mutated(used as an lvalue) // You cannot set object properties in pure functions (Typing[4202]) $this->bar = 42; // This object's property is being mutated(used as an lvalue) // You cannot set object properties in pure functions (Typing[4202]) $this->bar += 17; } } <<__Pure>> function some_pure_fn( Foo $foo, Vector<string> $vector, Map<string, int> $map, Set<int> $set, ): void { // This object's property is being mutated(used as an lvalue) // You cannot set object properties in pure functions (Typing[4202]) $foo->baz = 'monkeys'; // Cannot append to a Hack Collection object in a pure context. (Typing[4201]) $vector[] = 'apples'; // Cannot assign to element of Hack Collection object via [] in a pure context. (Typing[4201]) $vector[0] = 'bananas'; // Pure functions can only call other pure functions. Hack(4200) $vector->set(0, 'bananas'); // Cannot append to a Hack Collection object in a pure context (Typing[4201]) $set[] = 11; // Cannot assign to element of Hack Collection object via [] in a pure context. (Typing[4201]) $map['pajamas'] = 42; } ``` Values types, however, may be "modified", as these modifications are necessarily not visible outside the current frame of execution. ``` <<__Pure>> function some_pure_fn( vec<string> $vec, dict<string, int> $dict, keyset<int> $keyset, ): void { $vec[] = 'apples'; $vec[0] = 'bananas'; $keyset[] = 11; $dict['pajamas'] = 42; } ``` An exception made to the above rule is memoization using the `__Memoize` attribute. ## Enforced Determinism Non-determinism is prohibited as it invalidates computational consistency. By design, these operations must utilize HHVM builtins at some point in their execution, and those builtins are not able to be pure due to their innate side-effects. Typical examples are functions such as rand and time. While it would be possible to implement a pseudo-random number generator completely without using HHVM builtins, this function would either need to be deterministic or store internal state to produce changing results. The former would result in code that is acceptable within a pure function, but not particularly useful, and the latter is illegal for reasons other than issues with determinism. Due to the inherent non-determinism caused by Hack's asynchronous execution model, all asynchronous functions must be immediately `await`ed. `Awaitables` are only legal as the result of a function call and must be immediately unwrapped into their resultant type. Concurrent blocks are permissible. In order to avoid issues arising from suspension of execution, it is banned for the common cases asynchronous execution and generators. HHVM will enforce that we never suspend execution of a pure function due to usage of `await`. `yield` and friends are banned syntactically within pure functions. However, an exception is made specifically for the error handler that is invoked due to notices triggered by HHVM. For the sake of execution of the overall program, we are considering the error handler to be pure in that it will not affect state visible to the context. Once the error handler is moved into HHVM, this will become even more true. It is possible that we will delay the error handler being invoked until after leaving the pure context. # IDE experience: The IDE experience is as above in the user experience. Users will get descriptive error messages when attempting to do illegal operations within pure functions. # Implementation details: See the proposal for coeffects. This is fully enforced within HHVM. The illegal operations within a function are banned at the opcode level and will fail to emit. The transitivity requirement is enforced by calling conventions, including polymorphically-pure functions as described in the coeffects proposal. # Design rationale and alternatives: The major additional feature considered on top of this involves some way to add safe mutations that are tracked such that they do not result in side effects or nondeterminism. This will be discussed in more detail in a followup document. # Drawbacks: The lack of mutable state combined with the other restrictions of this system make it more difficult to write idiomatic hack code, and make it impossible to represent certain structures requiring generally mutable state. # Prior art: `constexpr` in C++. `const fn`s in rust. `comptime` in Zig `noSideEffect` in Nim Purity in more than a handful of functional languages. # Unresolved questions: Do we want some way to do print-debugging within pure code in sandbox mode? What about the interactive debugger? Does stepping through a pure function and modifying values cause problems? # Future possibilities: We can potentially add multiple different kinds of optimizations based on the knowledge that the code isn’t side-effectful as well as idempotent and deterministic. An additional major benefit to this work is the potential to use Pure functions in constant initializer positions. This is currently a major source of unsoundness. Additionally, there are very practical applications of this to the upcoming Enum Classes feature. ## Coeffects Once the coeffects feature is shipped, pure contexts will be integrated within it. As such the syntax will change from `<<__pure>> function(): void {...}` to `function()[pure]: void {...}` or similar, depending on the finalized version of the coeffects proposal.
Markdown
hhvm/hphp/hack/doc/HIPs/sound_dynamic.md
# HIP: Sound `dynamic` type ## Motivation The `dynamic` type was created to type legacy PHP code where types are optional: ``` // before function f($a) { return 3; } // after function f(dynamic $a): dynamic { return 3; } ``` The dynamic type admits any operation (subscripting, member access, etc.) and does not have any direct subtypes or supertypes beyond `nothing` and `mixed`. Its semantics are defined by a non-transitive relation called *coercion*. Any type can coerce to dynamic at enforcement points, and dynamic is allowed to coerce to types that are enforced at runtime: ``` function f(dynamic $d): int { return $d; /* ok */ } ``` Unfortunately, coercion to dynamic is unsound for arbitrary values. Consider a simple generic Box class: ``` class Box<T> { public function __construct(private T $t) {} public function set(T $t): void { $this->t = $t; } public function get(): T { return $this->t; } } function evil(dynamic $d1, dynamic $d2): void { $x = $d1->get(); // $x: dynamic $d1->set($d2); } function expect_int(int $i): void {} function test(): void { $b = new Box(4); $an_int = $b->get(); // $an_int: int = 3 evil($b, "hello"); $not_an_int = $b->get(); // $not_an_int: int = "hello" (!!!) expect_int($not_an_int); // TypeHintViolationException } ``` We allow the `Box<int>` to coerce to `dynamic`, but this is unsafe because the function writes a `string` into the boxed value without our knowledge. This means that the `$not_an_int` variable has the wrong type, and we get an exception in a program that has no Hack errors. With a sound dynamic type, we can fully eliminate error suppression in Hack, have trustworthy types, and perform global analysis to constrain the level of dynamism in the codebase. As it has global effect, which makes per-file experimental gating impractical, the sound dynamic feature is controlled by `.hhconfig` flag `enable_sound_dynamic_type`. ## Proposal We propose the following changes to the `dynamic` type to make it so that any value typed `dynamic` safely supports dynamic operations. First, we eliminate coercion entirely, requiring operations with `dynamic` to use subtyping instead. Next, we define a covariant type constructor `~` (pronounced "like") such that `~T` represents the union of `dynamic` and `T`. To describe types that support dynamic, we define ``` newtype supportdyn<+T> as T = (T & dynamic); ``` and introduce a new subtyping relation called *dynamic-aware subtyping* (written `<D:`), which adds the following simple rule: ``` ----------------------------- supportdyn<mixed> <D: dynamic ``` We also introduce the `upcast` expression to allow us to take values into `dynamic`. Its typing rule is ``` e : U U <D: T ---------------- e upcast T : T ``` Finally, we define normal subtyping (written `<:`) rules for `supportdyn<T>`. ### Like types These are the simplest part of the proposal. We use `~T` to signal that a value may have type `T`, but it may also be a dynamic value. Due to standard union rules, a `~T` only supports operations that are valid for `T` (`dynamic` admits any operation). For example, it is a type error to call a method on `~string`, even if the call would succeed at runtime. Many PHP builtins counterintuitively return `false` in exceptional cases, and a value otherwise, e.g. `file_get_contents`. If we were to type the function return as `(string | bool)`, every use site must now statically check this union, even if the overwhelming majority of callsites to not observe `false`. A less invasive approach is to give the function a type `~string`. Users are now aware that they may not be holding a `string`, but they have a choice in whether to check. The rest of the proposal describes how like types are used to remove lying types like the one observed in the introduction. Like types are transparent to the runtime, enforced as their inner type. A function that expects a `~string` will throw if you pass it a `float`. We have also considered a variant where like types are not enforced -- none of the semantics of `dynamic` require enforcement. However, we expect to mainly be weakening ill-typed code rather than adding types to untyped code, so this approach preserves existing enforcement behavior. ### Upcast Hack has an unsafe cast feature that can cast a value to any type. Its purpose is to aid in the elimination of error-suppression comments in Hack: ``` enum E: int { A = 1; } function f(int $i): E { /* HH_FIXME[4110] trust me */ return $i; } ==> function f(int $i): E { return HH\FIXME\UNSAFE_CAST<int, E>($i); } ``` With sound dynamic, we can replace `UNSAFE_CAST<T1, T2>(e)` with `e upcast ~T2`. Dynamic-aware subtyping is defined naturally for unions, so this is equivalent to asking if `int <D: dynamic` (more on that in the following section). To complete the example, we must weaken `f`'s return type. ``` function f(int $i): ~E { return $i upcast ~E; } ``` A consequence of this is we constrain any value that had flowed into an unsafe cast to support dynamic. Further, it is not legal to unsafe cast arbitrary `mixed` values, because `mixed` is not a dynamic-aware subtype of `dynamic`. Instead, the value's type may be at most `supportdyn<mixed>`. ``` function f(mixed $m1, supportdyn<mixed> $m2): void { $m1 upcast ~int; // error $m2 upcast ~int; // ok } ``` Also, since we eliminated coercion, technically all non-dynamic values must be upcast to dynamic in order to flow into dynamic positions. However, for ergonomics, we allow implicit upcasting when the target type is exactly `dynamic` ``` function f(): dynamic { return 4; // ok } function g(): ~string { return 4; // not ok return 4 upcast dynamic; // ok return 4 upcast ~string; // also ok } ``` The same applies to parameters and properties. Upcast expressions are erased at compile time. ### <<__SupportDynamicType>> The type `supportdyn<T>` means: the set of all values that are belong to `T` and support dynamic operations. Alternatively, this can be read as the *intersection* of the sets of values represented by `T` and `dynamic`. Naturally, this means that ``` ---------------------------- dynamic <: supportdyn<mixed> ``` > Note: `supportdyn<mixed>` and `dynamic` represent **the exact same set of values!** Unlike dynamic values, however, a value with type `supportdyn<mixed>` does *not* support arbitrary operations, just as the `mixed` type does not. What does it mean for a value to support dynamic? Above, we showed an example of calling a method with an arbitrary `dynamic` value. We may also use the returned value of any operation that succeeds as dynamic: ``` function f(dynamic $d): void { $d1 = $d->someMethod(); $d2 = $d->someProp; $d3 = $d[0]; // etc } ``` The main idea here is to prevent users from getting a `dynamic` reference to anything that does not protect its invariants. Primitives like numbers, `string`, `null`, and booleans all support dynamic trivially. Their values are immutable and their runtime properties cannot be changed by dynamic operations. Tuples and closed shapes support dynamic if their components do. *Open* shapes do not support dynamic, as we cannot be confident the unspecified fields contain values that support dynamic. To upcast an open shape to dynamic, it must be wrapped as `supportdyn<shape(...)>`, which requires that the remaining fields support dynamic. `mixed` and `nonnull` similarly do not support dynamic. ### Functions Consider an arbitrary function `f`: ``` // current code function f(int $i): string { <body> } function evil(dynamic $d1, dynamic $d2): dynamic { $x = $d1($d2); // $x: dynamic return $x; } function test(dynamic $d): void { $y = evil(f<>, $d); // $y: dynamic } ``` Forget passing a dynamic value to `f`, we can get a handle to the whole function as dynamic and do as we please! Therefore, to ensure `f` can be safely used in a dynamic context, we must require that it is still type-safe when all of its parameters are dynamic, and that its return value may be used dynamically. We introduce a new attribute `<<__SupportDynamicType>>`: ``` <<__SupportDynamicType>> function ff(T1 $t1): T2 { <body> } ``` that works by checking an overloaded definition of `ff` with a dynamic signature: ``` function ff(T1 $t1): T2 { <body> // typechecks } function ff(dynamic $t1): dynamic { <body> // must also typecheck } ``` The type of `ff` is `supportdyn<(function (int): string)>`, or alternatively `(function (int): string) & (function(dynamic): dynamic)`. That is, if you call `ff` with an `int`, you will get back a `string`. If you call `ff` with `dynamic`, you get back `dynamic`. Finally, if you call `ff` with a `~int`, by the application of the intersection, you will get back a `~string`. Of course, if the body of `ff` has an error when we check it with a dynamic signature, then you get an error that `ff` cannot be marked `<<__SupportDynamicType>>`. More precisely, a function type `function(T1, ..., Tn): Tr <: supportdyn<mixed>` if `dynamic <D: T1 & ... & dynamic <D: Tn` and `Tr <D: dynamic`. ### Classes Recall the previous `Box` example, with the constructor ommitted for clarity: ``` class Box<T> { private T $t; public function set(T $t): void { $this->t = $t; } public function get(): T { return $this->t; } } ``` If a `Box` is to support being used as a dynamic value, then - all of its methods (incl. inherited) must support dynamic - any public properties must support dynamic writing and reading - any class that extends `Box` must also support dynamic Consider the `set` method: ``` public function set(T $t): void { $this->t = $t; } public function set(dynamic $t): dynamic { $this->t = $t; // type error! } ``` In its dynamic version, we are writing a `dynamic` value to the property `t`, so we will get a type error unless we weaken its type ``` private ~T $t; ``` and consequently weaken the `get` method ``` public function get(): ~T { ``` Now let's consider the `get` method: ``` public function get(): ~T { return $this->t; } public function get(): dynamic { return $this->t; // type error! } ``` The result of the `get` method must be a valid value that can be typed `dynamic`, so `get`'s return type `~T` must be be a dynamic-aware subtype of `dynamic`. We can achieve this by constraining the type parameter ``` class Box<T as supportdyn<mixed>> { ``` and we are finally done. ``` <<__SupportDynamicType>> class Box<T as supportdyn<mixed>> { private ~T $t; public function set(T $t): void { $this->t = $t; } public function get(): ~T { return $this->t; } } ``` For any valid `Box<T>`, we now have `Box<T> <: supportdyn<Box<T>>` and therefore `Box<T> <D: dynamic`. Now let's bring back the original example: ``` function evil(dynamic $d1, dynamic $d2): void { ... } <<__SupportDynamicType>> function expect_int(int $i): void {} function test(): void { $b = new Box(4); $an_int = $b->get(); // $an_int: ~int = 3 evil( $b /* upcast dynamic */, "hello" /* upcast dynamic */ ); $not_an_int = $b->get(); // $not_an_int: ~int = "hello" (ok) expect_int($not_an_int); // TypeHintViolationException } ``` We are no longer lying to the user that `get` only returns `int`s. The call to `expect_int` will still throw, but this is the price of dynamism. However, if the user sees a non-dynamic type `int`, they can now be confident that its runtime value is actually an integer. ### Pessimisation The process of weakening and constraining types in a codebase to enable `<<__SupportDynamicType>>` and admit existing use of legacy `dynamic` is called *pessimisation*. Users are free to pessimise their code however they like. For example, we could have instead pessimised the `Box` example as ``` <<__SupportDynamicType>> class Box<T> { private dynamic $t; public function set(dynamic $t): void { $this->t = $t; } public function get(): dynamic { return $this->t; } } ``` We also allow enforced types to behave as like types when writing so that we do not need to weaken them: ``` <<__SupportDynamicType>> class IntBox { private int $t; public function set(int $t): void { $this->t = $t; // we're acting like `t` has type `~int` for the dynamic pass's assignment } public function get(): int { return $this->t; } } ``` ## Conditionally-dynamic classes The restriction of `<T as supportdyn<mixed>>` in our `Box` is particularly onerous for library classes. For example, it precludes Hack containers from instantiation with classes that do not support dynamic. ``` <<__Sealed(KeyedContainer::class), __SupportDynamicType>> interface Container<+Tv as supportdyn<mixed>> extends Traversable<Tv> { ``` The Shack formalization of dynamic allows for arbitrary constraints on classes to support dynamic provided that the core requirements for reading and writing hold under those constraints. We propose an instance of this by allowing ``` <<__SupportDynamicType>> class C<T> {} ``` where `C<T> <D: dynamic` if `T <D: dynamic`. With this constraint, we can now write the `Box` example without constraining `T`. ``` class Box<T> { private ~T $t; public function set(T $t): void { $this->t = $t; } public function get(): ~T { return $this->t; } } ``` The method `get` passes the `<<__SupportDynamicType>>` check because we can now assume `T` was instantiated with a subtype of `dynamic`, so the return requirement `~T <D: dynamic` holds. ## Inheritance To aid in the transition of untyped hierarchies that leverage error suppression, we allow methods that return any `T` to override methods that return dynamic, provided that `T <D: dynamic`. This is similar to the automatic upcasting to dynamic shown above. ``` <<__SupportDynamicType>> class A1 { public function f(): ~string { ... } } <<__SupportDynamicType>> class A2 extends A1 { public function f(): dynamic { ... } } <<__SupportDynamicType>> class A3 extends A2 { public function f(): int { ... } } ``` even though `int </: dynamic` under regular subtyping. This allowance is not transitive, and so the following is an error ``` <<__SupportDynamicType>> class B1 { public function f(): ~string { ... } } <<__SupportDynamicType>> class B2 extends B1 { public function f(): int { ... } // error } ``` Note that it would be perfectly sound to allow ``` <<__SupportDynamicType>> class C1 { public function f(): ~string { ... } } <<__SupportDynamicType>> class C2 extends C1 { <<__Override>> public function f(): ~int { ... } } ``` This is again because `~string` and `~int` represent the exact same set of values. In fact, `~T1` is semantically equivalent to `~T2` for all types where `T1 <D: dynamic` and `T2 <D: dynamic`. However, this is not very ergonomic, so we propose an alternative ``` <<__SupportDynamicType>> class D1 { public function f(): ~string { ... } } <<__SupportDynamicType>> class D2 extends D1 { <<__Override, __DynamicOverride>> public function f(): ~int { ... } } ``` The strictest option is to require regular `<:` subtyping for overrides, in which case the example above must be weakened to ``` <<__SupportDynamicType>> class E1 { public function f(): ~arraykey { ... } } <<__SupportDynamicType>> class E2 extends E1 { public function f(): ~int { ... } } <<__SupportDynamicType>> class E3 extends E2 { public function f(): int { ... } } ``` # Future ## Runtime dynamism Classes and methods can still be referenced via strings in the runtime, which creates a blind spot for `<<__SupportDynamicType>>`. In general, it is not safe to say that a class does not support dynamic if there exist runtime dynamic references to it. We would like to extend the concept of `<<__DynamicallyCallable>>` to cover these cases, and tie it to `<<__SupportDynamicType>>`. This would make it so that all dynamically referenced functions/classes support dynamic, and those that do not would fatal on dynamic reference. ## Mocking Function mocking for tests heavily depends on dynamism. We would like to avoid a situation where a function is only marked `<<__SupportDynamicType>>` so that it can be used dynamically in a test, and otherwise has fully static usage. With this in mind, we are considering some restricted primitives to get `dynamic` handles on non-dynamic targets for testing. # Decision points - General syntax - Which parts of sound dynamic will we ship? - `~T` vs. `HH\FIXME\POISON_MARKER<T>` - `supportdyn<T>` vs. `HH\FIXME\SUPPORTDYN_MARKER<T>` - `e upcast T` vs. `HH\FIXME\UNSAFE_CAST<_, T>` (like types only) - naming of `<<__SupportDynamicType>>` - Inheritance behavior - Proposed behavior - Lints? - Required `<<__DynamicOverride>>` - Only regular subtyping
Markdown
hhvm/hphp/hack/doc/HIPs/type-refinements.md
Start Date: April 19, 2022 Stage: DRAFT ## Summary This feature, referred to as _type refinements_, adds the ability to specify structural constraints on a type. The type subject to the constraints is said to be _refined_. In this HIP, type refinements can only constrain type and context constants of a class/interface. The constraints on such constants can be either _exact_ or _loose_. An exact constraint fully specifies the constant while a loose constraint is a combination of lower and/or upper bounds that may match multiple concrete constants. In the future, type refinements could be further extended to apply other constraints to other types. We now give an example use of the feature. Assuming the following interface definition ``` interface Box { abstract const type T; const ctx C super [defaults]; } ``` type refinements would allow writing types such as: * `Box with { type T = int; ctx C super [globals]; }` * `Box with { type T as arraykey }` ## Feature motivation Type refinements is a feature that is present in the Scala programming language where it was proved to be useful and safe. It would enhance Hack in 3 key areas: * _expressiveness_ -- __complementing where-constraints__; some useful constraints cannot be expressed with where constraints, but can be expressed with type refinements; e.g., constraints on type constants of class-level generic parameters, or constraints on an existentially quantified return type. * _soundness_ -- __more principled basis for type accesses__; offering a limited form of dependent types that can help replace unsafe where constraints with type accesses and needed to soundly model polymorphic contexts, for example. * _convenience_ -- __reduces boilerplate Hack code__; no intermediate interfaces/classes need to be introduced to merely refine the constraints on type/context constants. ### Increased expressiveness Considering the following definitions ``` interface ReadonlyBox { abstract const type T; public function get(): this::T; } interface TBox extends ReadonlyBox { public function set(this::T $val): void; } ``` suppose we want to write a delegator class that exposes the box's content type via a generic parameter and also provides a getter function returning a ReadonlyBox; using type refinements, we can write ``` class SafeBoxDelegator<Tref> { public __construct(private Box with { type T = Tref } $w) {} public function set(Tref $val): void { $this->b->set($val); } public function get(): ReadonlyBox with { type T = Tref } { … } } ``` The above example is currently inexpressible in Hack for two reasons. First, the refinement in the constructor would require class-level where clauses, which are not available today and would in this case include one occurrence of poorly-supported type accesses on generic variables. Second, a common attempt to use where-clauses to type the getter function fails: ``` class SafeBoxDelegator<Tref> { ... public function get<TIB as ReadonlyBox>(): TIB where TIB::T = Tref { … } ``` This function prototype, while usable, is not practically implementable. To implement it, the programmer has to write code that returns an object that is in _all_ subtypes of ReadonlyBox that satisfy the where constraint. This is not the intent of the programmer, who likely meant to return _one_ subtype of ReadonlyBox satisfying the constraint. In terms of type theory, `TIB` is universally quantified when the intent was to existentially quantify it. ### Replacement for unsound projections One might attempt to work around the existing limitations of where clauses by changing the interface of `SafeBoxDelegator` to accept the Box as a class generic, i.e.: ``` class SafeBoxDelegator<TBox as Box> { public __construct(private TBox $w) {} public function set(TBox::T $val): void { … } // error: ^^^^^^^ public get(): ReadonlyBox with { type T = TBox::T } { … } … // error: ^^^^^^^ } ``` However, the definition above is rejected by Hack because type accesses on generics are not permitted as type hints. More generally, type accesses on generics are poorly supported by the language; for example, the typechecker does not prevent instantiating generics with class types that have abstract type constants, leading to unsoundness. With refinements, it is possible to constrain a class-level generic parameter to define a type constant of interest. For example ``` class SafeBoxDelegator<TinBox, TBox as Box with { type T = TinBox }> { public __construct(private TBox $w) {} public function set(TInBox $val): void { $this->b->set($val); } public function get(): ReadonlyBox with { type T = TInBox } { … } } ``` Currently, Hack does allow one way to express a limited form of dependent typing (i.e., a function where the type of one parameter depends on the type of another one) ``` function setBox<T1, TBox as Box>(Tbox $b, T1 $v): void where T1 = TBox::T ``` However, the boilerplate required in the accepted prototype is a common source of confusion for users and, as explained above, is only very weakly shielding them from unsound code. Using type refinements we write ``` function setBox<T1>(Box with { type T = T1; } $b, T1 $v): void ``` And the function `setBox` can no longer recieve as first argument a value of a type for which we do not precisely know what the associated type constant is. As a final benefit, type refinements would serve as a more solid intermediate representation for dependent context constants in the typechecker. E.g. ``` interface BoxWithCtx extends Box { const ctx C; } function useBox(BoxWithCtx $b)[$b::C]: void { … } ``` would be internally represented via refinement of context constant `C` (which is then further desugared into a type) ``` function useBox<TC>( BoxWithCtx with { ctx C = [TC] } $b )[Ctx]: void ``` this new internal representation would replace the current desugaring into where-clauses, generics, and projections of questionable soundness. As a final remark about soundness, we will point out that unlike projections off types, the type refinements feature has been well studied in the context of Scala's core [DOT calculus](http://lampwww.epfl.ch/~amin/dot/fool.pdf) [3,4]. ### Less definition boilerplate In the special case where a type refinement involves only concrete type and context constants, it is possible to replace the refinement with an additional subtyping constraint involving an interface that represents the `with { … }` refinement component. Such interfaces may look like ``` interface LoggedBox extends BoxWithCtx { abstract ctx C super [globals]; } interface NumericBox extends Box { abstract const type T as num; } interface LoggedNumericBox extends LoggedBox, NumericBox {} interface LoggedIntBox extends LoggedBox { const type T = int; } interface VecNumericBoxPure extends Box { abstract const type T as vec<num>; const ctx C = []; } ``` However, this nominal encoding of refinements does not scale: it leads to an exponential number of artificial interfaces with combinations of constraints, significantly cluttering code and namespaces. In a sense, we allow the use of some form of anonymous interfaces. ## Feature definition We now expose in more details the specifics of type refinements. This section aims to provide enough foundational information to successfully complete an implementation of the feature. ### Syntax A type refinement would be written as `Classish<…> with { … }` where `{ … }` refines one or more type and context constants. An example is a function signature that returns a `Box` whose type constant `T` is fixed to `int` (the new syntax is overlined): ``` _____________________ function getIntBox(): (Box with { type T = int }) ``` Each refinement inside `{ … }` should be a valid type/context constraint, it must contain either an exact `=` constraint or an arbitrary combination of one or more `as`/`super` bounds. #### EBNF notation Add rules: ``` TypeRefinement ::= TypeSpecifier `with` `{` Refinement [`;`] `}` ; Refinement ::= RefineType | RefineCtx | Refinement `;` Refinement ; RefineType ::= `type` QualifiedName ( `=` TypeSpecifier | RefineTypeBounds ) ; RefineTypeBounds ::= ( `as` | `super` ) TypeSpecifier RefineTypeBounds | ( `as` | `super` ) TypeSpecifier ; RefineCtx ::= `ctx` QualifiedName ( `=` CtxList | RefineCtxBounds ) ; RefineTypeBounds ::= ( `as` | `super` ) CtxList RefineTypeBounds | ( `as` | `super` ) CtxList ; ``` Extend rule: ``` TypeSpecifier ::= (* new *) TypeRefinement | (* old syntax *) … ; ``` Note: Our draft implementation does not allow multiple sequenced refinements and instead suggests to the user to merge them into a single refinement. ### Well-formedness In a refinement `Classish<…> with { … }`, the left-hand side classish must be a fully applied interface, class, or type alias that recursively expands to an interface or a class. This constraint means that we currently do not support refining opaque types aliases (newtype), the this type, or generics. There is no constraint on the bounds of a refinement. In particular, we may well have an unsatisfiable loose refinement. We will see in the semantics section that the result of such a refinement is simply an empty type equivalent to the bottom type nothing. There is no requirement that the type/context constants in the refinement are defined in the classish they refine. However, in this case, a linter (TAST check) could warn the user and suggest constants appearing in the classish with similar names. ### Typing rules We only give typing rules for type constant refinements, context constant refinements are handled very similarly. First, we modify the type access expansion algorithm to have the following new clauses: ``` taccess((C<…> with { type T = t'; … }), 'T') = t' taccess((C<…> with { … }), 'T') = taccess(C<…>, 'T') ... (* old clauses *) ``` These additional rules guarantee that any existing typing logic will successfully take exact refinements into account. Since type accesses on abstract type constants are poorly handled in general, we suggest to not implement any specific rules about loose refinements in the type access expansion logic. We define a new type member lookup unit. The goal is to eventually have this unit take care of all the type access expansion logic. Throughout the transition, we take care to keep this type member lookup principled and stick to well-understood accesses. ``` lookupty(/*class*/ C, 'T') = if 'T' is Abstract(lowerBnd,upperBnd) in C: BOUNDED(lowerBnd,upperBnd) else if 'T' is Concrete(ty) in C: BOUNDED(ty,ty) else ERROR lookupty((/*class*/ C with { R }), 'T') = if R['T'] is (super lowerBnd as upperBnd): merge(lookupty(C, 'T'), BOUNDED(lowerBnd,upperBnd)) else if R['T'] is (= ty): merge(lookupty(C, 'T'), BOUNDED(ty,ty)) else lookupty(C, 'T') // Merge two lookup results merge(ERROR,other) = other merge(other,ERROR) = other merge(BOUNDED(lo1,up1),BOUNDED(lo2,up2)) = BOUNDED((lo1|lo2),(up1&up2)) ``` We also modify the subtyping algorithm so that it applies the following rules. The rules are listed by order of precendence. ``` t ⊢ R t <: C<…> (<:1) ------------------------ t <: C<…> with { R } C<…> <: t (<:2) ------------------------ C<…> with { … } <: t ``` Thinking about inference, we note that it is important to apply the rule (<:1) before applying any rule that goes looking up into the bounds or extends/implements of the type on the left-hand side of a subtype query. This ensures that we have the best information possible when looking up type constants. The first typing rule uses a new judgement that we define below. ``` lookupty(C,'T') = BOUNDED(lo,up) lo' <: lo up <: up' C ⊢ { R } (⊢l) -------------------------------------- C ⊢ { type T super lo' as up'; R } lookupty(C,'T') = BOUNDED(lo,up) ty <: lo up <: ty C ⊢ { R } (⊢e) -------------------------------------- C ⊢ { type T = ty; R } (⊢[]) ----------- C ⊢ { } ``` ### Semantics In the spirit of the [Shack](https://github.com/facebookresearch/shack) project that interprets Hack types as sets of values, we give a semantics for type refinements by defining the interpretation of refinements ``` [[ C with { type T cstr } ]]Σ = [[ C ]]Σ ∩ { l ∈ loc | l ↦ (tag, phi); [[ class_def[tag].T ]]_ ⊢ [[ cstr ]]Σ } ``` That is, the constrained class type is all the objects in the class type of C that, additionally, have a type member that satisfies the constraint in the type. It is noteworthy that the semantics interpret the type refinements as an intersection type. The interpretation function [[ . ]]Σ is parameterized by Σ an environment that contains the interpretation for ambient generic parameters. When interpreting a type constant obtained from the class definition this environment is irrelevant because type constants are currently required to be independent from all generic parameters. The constraint in the refinement, on the other hand, is interpreted using the ambient generic parameters. One unknown is that the current typechecker implementation allows using the 'this' type in type constant definition, and 'this' has not been formalized in Shack yet. Another shortcoming of these semantics is the lack of account for Hack's parallel object model where classname values are used as singleton objects for final abstract classes. This lack of precision in the semantics sheds doubts about the interaction of type refinements with classname values and their associated capabilities (call to static methods). ## IDE experience: ### Auto-suggested type refinements It would be useful if IDE could detect if a user attempts to use a certain type/context constants with implicit assumptions in mind that a quick-fix appears “Refine type member that belongs to …”, e.g.: ``` function reads_box_T_as_int(Box $b): int { return $b->get(); } ``` would ideally suggest “Refine type member in the type associated with parameter $b”, and accepting the quick-fix would refactor the above as: ``` function reads_box_T_as_int(Box with { type T as int; } $b): int { return $b->get(); } ``` ### Good assistance if with keyword is forgotten Users familiar with languages such as Scala that implement this feature with a similar syntax may accidentally write the following: ``` abstract function getIntBox(): Box { type T = int; } ``` which may misparse as a non-abstract function with a body containing a type definition: ``` abstract function getIntBox(): Box { type T = int; // hardly distinguishable from a body } ``` If not the parser itself, the IDE should ideally suggest: “Did you mean Box with { … }?” ## Implementation details: ### Parser After careful refactoring, most of the core parsing logic used by type and context constants is _reusable_. The only modified execution path is when a type specifier (hint) is parsed; the parser must check if `with` is the next token. The performance impact is therefore negligible, albeit it requires a lookahead of size 1 only when parsing XHP attributes as they can comprise multiple tokens (e.g., `attribute Type with-token2`). ### ASTs TODO ### Typing TODO ### HHVM This feature is type-checker only because it does not provide a means of declaring anything new. Refinements merely give additional “hints” about the types associated with them (i.e., types before the `with` keyword), and are used by type inference only -- nothing can fail at run-time. Therefore, HackC can simply ignore the entire refinement after a type. This is true even when a type refinement appear in an aliases or a type constant, e.g.: ``` type IntBox = Box with { type T = int } ``` will be bytecode-compiled identical to: ``` type IntBox = Box ``` which is sound for run-time because type aliases are not enforced, and neither are type constants. ## Design rationale and alternatives: ### Alternative syntax One might argue why we need the `with` keyword before the braces unlike languages such as Scala where the syntax avoids the extra keyword. While this would be more compact, it would require tricks or very complicated lookahead and/or special-casing when parsing return types to discriminate between refinement and the function body (see section _IDE experience_ for an example). There have also been wishes that the syntax was less verbose potential alternatives, e.g.: ``` Box[ T=int, C as[globals]super[zoned] ] ``` However, this would add significant parsing overhead as the parser would need to backtrack: * parse a series of bounds with _context list_ if possible, otherwise * parse a series of bounds with _type_. If we want to prioritize reducing verbosity, there is hope that it can be done if we _unify representations_ of types and contexts -- at least for the purposes of type refinements, which is easier because this feature and syntax is invisible to HHVM as it doesn’t affect the runtime. Since context lists are already internally represented as types in the typechecker, we could express the above as follows: ``` Box[ T=int, C as CtxGlobal super CtxZoned ] ``` ### Smarter where-clauses TODO ### DOT-like object model Generalizing Hack’s object model by basing it on the Dependend Object Types (DOT) calculus [3,4] is being actively considered as well, but it is a much larger undertaking. DOT-style path projections are _instance-based_ (`$obj.TypeOrCtx`) and would serve as a sound and more powerful substitute for type projections (`Type#TypeOrCtx`). Nonetheless, even languages that support instance-based projections (e.g., Scala) do offer refinements of types, attesting to the value added by this feature alone. ## Drawbacks This feature does not strip away or change existing functionality, so this section is largely inapplicable. Nonetheless, it is a valid question to ask how Hack users are going to be educated and what assistance will be provided to help them choose between generics vs type constants with refinements. For example, if the definition of `Box` above was written using generics, we would *not* need refinements but *would* end up hitting other limitations imposed by generics. Until we better unify the notions of generics and type constants, we need to make the design intuitive in order to avoid confusing Hack users with seemingly interchangeable sets of features. ## Prior art ### Type refinements in Scala Scala 2 refers to the syntactic piece `TypeSpecifier with { … }` as _compound type_ (see [Sec 3.2.9](https://www.scala-lang.org/files/archive/spec/2.13/03-types.html#compound-types) of the official specification), whereas the `{ … }` is also called _refinement_. The `with` keyword is used for intersecting two types, which is superseded by the `&` operator that denotes _type intersection_ in Scala 3. Interestingly, Scala allows any sort of structural typing * adding a new _value_ definition such as a method or field; * adding a new _type_ definition that can contain equal or lower/upper bounds. Notably, Scala allows introduction of _new_ types/values in refinements and thus offers a mechanism for _structural type_ refinements. E.g., we could declare an interface that accepts any subtype of Box that defines a new method: ``` def accepts_any_object_settable_to_int( box: AnyRef with { def set(v: Int): Unit } ) ``` Nonetheless, cyclic or self-referential accesses are prohibited in the refinement: ``` def all_args_are_invalid( box0: Box with { type T2 <: this.T }, // ERROR box1: Box with { def set(v: this.T): Unit }, // ERROR // ----- self-ref disallowed box2: Box with { def set(v: box2.T): Unit }, // ERROR ) ``` even when they come from an outer object: ``` trait Outer { self => // refer to `Outer.this` as `self` type B = Box with { type T >: self.type } // ERROR } ``` ### References [1] Scala 2.13 Specification, [Sec 3.2.9 (Compound Types)](https://www.scala-lang.org/files/archive/spec/2.13/03-types.html#compound-types) [2] [EBNF notation](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) [3] paper: [Dependent Object Types](http://lampwww.epfl.ch/~amin/dot/fool.pdf) [4] video: [Dependent Object Types](https://www.youtube.com/watch?v=b7AokpvwzgI) [5] HIP: [context and coeffects](https://www.internalfb.com/code/fbsource/[a56b675db21fb8c075f735721a3147fe4e660822]/fbcode/hphp/hack/doc/HIPs/contexts_and_coeffects.md) [6] [Shack](https://github.com/facebookresearch/shack), formal semantics for Hack types ## Unresolved questions: TODO ## Future possibilities TODO
Markdown
hhvm/hphp/hack/doc/HSL_design/io.md
# HSL IO Key Design Decisions # Status: Fully implemented in Hack code (https://github.com/hhvm/hsl-experimental and Facebook WWW); widely used externally by most CLI applications in Hack, including HHAST’s LSP support. Originally derived from HHAST LSP server’s async IO implementation. Used in Facebook www in limited places due to ‘experimental’ status. # Summary: HSL IO aims: * to be a 100% replacement for PHP IO builtins functions and and related resources (files, sockets, stdio, etc); it is meant to unblock their removal (among other things), so a 90% solution is not acceptable. * to replace or reduce the need for additional HHVM extensions when async clients for network services are needed * be a true ‘async-first’ design * use the type system for as much safety as possible. For example, files opened read-only do not have ‘write’ methods; this is comparable to Java exposing separate InputBuffer and OutputBuffers. It is composed of several new namespaces: * `HH\Lib\OS`: this is a thin layer exposing the traditional C File-Descriptor-based APIs; minimal changes are made to the C APIs. * Direct usage is *strongly* discouraged: no attempt is made to make APIs hard-to-misuse. For example, if `OS\write("foo")` only writes 1 character, this is considered success, not a failure, and users must check for it - just like in C. * `HH\Lib\{File, Unix, TCP}`: functions, classes, and interfaces that are specific to a particular kind of IO ‘handle’. * `HH\Lib\{IO, Network}`: functions, classes, and interfaces that are shared or reusable between multiple kinds of IO handles ## Why a design document: * While this is not a language change, it will be part of a fundamental change to how Hack programs work: it should eventually replace `php://input`, `php://output`, `print()`, etc. See ‘Future Work’ for details. * there are some contentious design issues; **the primary contentious issue is that the user-facing APIs are not ‘disposable-first’.** This document is **not** intended to be a full API design review of the library; however, for completeness, the full APIs can be reviewed in the documentation at https://docs.hhvm.com/hsl-experimental/reference/ # Feature motivation: The primary motivations are: * async support: this is already needed by projects such as HHAST, and is desired externally to allow replacing the PHP redis extension with an async library. * portable, reliable error detection and handling. The PHP builtins return false and log a warning, while `posix_get_last_error()` , `posix_errno()`, and `socket_last_error()` are unreliable, especially when async or CLI server mode is being used; they also depend on mutable global state. * it is a necessary step in the removal of PHP `resource` types; file/stream/socket resources have observable destructor-like behavior Additional motivations are: * type system: with current PHP APIs, files, mysql connections, streams, curl handles all share the same `resource` type * type system: `T | false` return types are prevalent and not supported by the Hack type system. * consistency: sockets are sometimes stream resources, sometimes socket resources, depending on how they are created. Each has different limitations ## Prioritization factors: Making HSL IO built-in will unblock work on: * removing PHP IO primitives * redesigning the entrypoint API - for example, removing `STDIN`, `STDOUT`, `php://input`, `php://output` * this in turn currently blocks removal of PHP globals * this is a soft-blocker on adding a friendly, type-safe alternative to the current xbox parallelism APIs # User experience: ```Hack $file = File\open_write_only( '/tmp/foo.txt', File\WriteMode::OPEN_OR_CREATE, // optional 0644 // optional ); // Close the file handle on scope exit: using $file->closeWhenDisposed(); $conn = await TCP\connect_async( 'localhost', 8080, shape( // optional 'timeout_ns' => 123, 'ip_version' => Network\IPProtocolBehavior::PREFER_IPV6, ), ); using $conn->closeWhenDisposed(); // Write "foo\n" or throw: await $file->writeAllAsync("foo\n"); // Ditto: await $conn->writeAllAsync("foo\n"); // the OS\write()/POSIX behavior: await $conn->writeAllowPartialSuccessAsync("foo\n"); $conn->close(); // Line- and character-based operations $br = new IO\BufferedReader($file); $line = await $br->readLinexAsync(); foreach ($br->linesIterator() await as $line) { // do stuff with each line, without awaiting in a loop } $chunk = await $br->readUntilAsync("\nMARK\n"); // Escape hatch in case you have an edge case we don't have a // high-level API for: $fd = $file->getFileDescriptor(); invariant(!OS\isatty($fd), '/tmp/foo.txt is a tty?!'); $stdin = OS\request_input(); if ($stdin is IO\FDHandle) { // probably CLI mode if (OS\isatty($stdin->getFileDescriptor())) { // do interactive things } else { // Maybe `myapp < /tmp/foo.txt` or `someotherapp | myapp` ? // do non-interactive things } } else { // probably POST data, and $stdin->getFileDescriptor() would be a type // error. Equivalent to `php://input` thing, which may or may not be // backed by a real FD; it isn't when using proxygen. } ``` `$file` is a `File\CloseableWriteHandle`; in turn, this is an `IO\CloseableSeekableWriteHandle` and: * an `IO\Handle`: this is an empty base interface * an `IO\CloseableHandle`: an `IO\Handle` with `close()`; currently, all concrete `IO\Handle`s are closeable, but others have been suggested in the past; e.g. a `IO\server_error()` handle returning process STDERR; an individual request should not be able to close HHVM server stderr. * a `IO\WritableHandle` and an `IO\SeekableHandle` * an `IO\FDHandle`: this is the integration point with the `OS\` namespace: this means that: * `$file->getFileDescriptor()` is available and returns an `OS\FileDescriptor` * The majority of operations (e.g. writing) are implemented using `OS\` functions, e.g. `writeAllAsync()` is implemented with `OS\write()` and `OS\poll_async()` `$conn` is also a `Closeable`, `Writable`, and `FileDescriptor` Handle, but it is not a `Seekable` handle. These interfaces are best thought of as intersections: a FooBarBazHandle is a FooBarHandle, FooBazHandle, BarBazHandle, FooHandle, BarHandle, and BazHandle. Concretely, a CloseableReadWriteHandle is a CloseableHandle, a ReadHandle, a WriteHandle, a ReadWriteHandle, a CloseableReadHandle, and CloseableWriteHandle. Function authors should aim to describe what functionality they need when restricting input types, and take less specific interface possible - for example, if a function only needs to call `writeAllAsync()`, it should take an `IO\WriteHandle`, not a `File\WriteHandle` `IO\Handle`s are not disposables; they must manually be closed, or `closeWhenDisposed()` should be called to get a disposable that will close on exit. This disposable is not itself an `IO\Handle`. # Implementation details: The majority of `IO\Handle`s are `IO\FDHandles`, built on top of an `OS\FileDescriptor`. This is a native object which is a thin wrapper around the C int file descriptor concept, which ensures that: * file descriptors are not left open at the end of the request. Refcounting is not observable - if not explicitly closed, file descriptors are closed at the end of the request. * they are transferred between the client and server correctly in CLI server mode * if a closed FD number is re-used, operations on the original handle will fail, instead of working on the new FD with the same number. This is essential for correctness in a multi-request single-process environment. For example, a `writeAllowPartialSuccessAsync()` call ends up being a call to `OS\write($this->fd)`. `OS\write()` is a very thin Hack wrapper around the native builtin `HH\Lib\_Private\_OS\write()`; the separation of responsibilities is that: * native functions are responsible for cross-request correctness/isolation * everything else is the responsibility of the Hack code For example, `_OS\write()` may throw an `_OS\ErrnoException()`, and `OS\write()` may catch this and instead throw an `OS\FileNotFoundException`; as user-facing exception hierarchy is a very subjective and opinionated area, it is left for the Hack code. Async support for IO`\FDHandle` is built on `O_NONBLOCK`, and libevent/libevent2’s FD support. The current exception hierarchy is based on Python 3’s work, which appears well received. Concretely, there is: * `OS\ErrnoException`: this is both a base class, and instantiable when there is not a more specific exception * many subclasses for failures that frequently caught, e.g. `OS\AlreadyExistsException`, `OS\IsADirectoryException`, `OS\IsNotADirectoryException` While `catch (OS\ErrnoException $e) { switch ($e->getErrno()) { /* ... */ }}` is possible, the hierarchy aims to make this an antipattern in the common case. ### Required Changes Implementing this HIP would require moving the relevant code from Facebook’s www repository and the github hsl-experimental repository to HHVM builtins, and adding appropriate HHIs. # Design rationale and alternatives: ## API is not Disposable-based There were previously strong opinions that all IO handles should be Disposable, and closed when disposed. ### Context: current usage of *“PHP IO”* features is not representative of IO as a whole The vast majority of PHP IO usage in Facebook WWW should be using Disposable-based APIs, specifically APIs focussed on temporary files. However, the majority of IO does not go through PHP IO, or things we usually think of as “the IO library” - it uses dedicated extensions, such as: * Thrift * McRouter * MySQL * Various FB-proprietary extensions We aim for HSL IO to be usable for implementing clients instead of extensions for other services that are not currently supported (for example, gRPC, Redis) but solve similar use cases; as such, we should be asking ourselves: “would this design choice prevent us from reimplementing McRouter in Hack using HSL IO?”. I do not believe that disposable-only Thrift/McRouter/MySQL/<censored> APIs would be practical for Facebook for the same reasons that I believe that HSL IO can not be disposable-only, detailed below. ### Non-composability makes Disposables unsuitable for “100%” solutions Alternatively: Disposable is a ban on encapsulation. * this makes them impossible to use as a hidden implementation detail of a higher-level API * as such, they can never be an essential part of an API that we expect others to build on If HSL IO was Disposable-based, and a 100% replacement: * a pure Hack async Redis client could not contain a `TCP\Socket` as an implementation detail. Instead, either: * it would need to be passed around to every function, and could not be hidden in a ‘Connection’ object or similar * every operation on Redis would need to open a new TCP connection. This is unacceptable from a performance perspective. * TLS/SSL can not be implemented as a wrapper around TCP or Unix IO handles, or other transports. Users would need to explicitly wait for events on the socket handle, pass them (and the socket) on to the TLS handler, and see if any post-TLS state change was observable. * `interface Logger { public function logAsync(string $message): Awaitable<void> }` could be implemented in three ways, none of which are practical: * Open and close the file descriptor inside that method every time `logAsync()` is called; this is unacceptable performance-wise even for local files, and definitely for networked logging services. * Take any necessary IO handles as `<<__AcceptDisposable>> IO\WriteHandle` parameters. This is bad for usability, prevents implementation hiding, and requires a codemod to add an extra arg to every callsite if we ever want to log to two places (e.g. when migrating logging frameworks). * Discard the log message, without displaying or saving ### ‘Virality’ I mean this in a similar sense to ‘viral licenses’: if one thing is Disposable, everything that touches it must also be Disposable, recursively. Using the previous `Logger` example: if we make the IO handle a parameter, any component that could possibly want to log - or use another component that may want to log - would need to take an `<<__AcceptDisposable>> $logTo` parameter. If the common ‘controller’ pattern is used: * due to the composition restrictions, this must be an explicit parameter to every single method * if those composition restrictions were weakened to allow disposables to contain other disposables, there seem to be two approaches: * add a disposable ‘callcontext’ parameter to every method instead of needing the IO handle to be its’ own parameter * make every controller disposable, and likely the majority of the call stack in both directions; store the ‘callcontext’ as a property * both are substantial changes to code structure, and will lead to a large amount of boilerplate For some use cases (e.g. live stream uploads), it *must* be possible to access raw IO streams for POST data; this means that the web controller stack would have similar needs to the hypothetical logger case. ### An alternative: special cases Instead of making it so that STDERR or similar is passed through the application, we could keep it accessible via a free function. The next immediate problem is that the first function that logs to STDERR will acquire it as a disposable, and automatically close it when that function exits. We could address this by special-casing the STDIO handles to not actually close on exit, or by making them global constants similar to the existing STDIN/STDOUT/STDERR constants (which would require allowing constants that are objects, and that implement IDisposable). The major shortcoming here is that replacing “log to STDERR” with “log to file”, “log to syslog”, or “log to my favorite SAAS logging provider” becomes a massive challenge requiring refactoring of every logging callsite. It also is itself a breach of encapsulation, as a `IO\WriteHandle` parameter without `<<__AcceptDisposable>>` will effectively be the same thing as an `STDIOWriteHandle`. This could be avoided by implementing a special API to ‘strip’ d ### An alternative: ‘leases’ Instead of the disposable actually controlling open/close, it could be an indirect reference to the *real* IO handle (similar to a shared_ptr). This would address: * the ‘every method call needs a reconnect/reopen’ problem * the ‘pass stderr/a log device to every function’ problem * the ‘if I don’t get passed stderr, but get it from a global accessor, a disposable for stderr in my function, and it’s disposed, have I just closed it for every other function?’ problem This is not actually a solution for Disposable-based IO handles: it is equivalent to “not Disposable-based” as it requires there to be an underlying non-disposable IO handle backing this, and requires it to be possible to acquire one from a disposable, removing the desired safety. ## No locking/queuing This is undefined behavior: ```Hack concurrent { await $f->writeAllAsync('FooBar'); await $f->writeAllAsync('HerpDerp'); } ``` As `OS\write()` can partially succeed, even with a single thread, this can result in `FooHerpBarDerp` or many other sequences. In an early experimental version of HSL IO, write operations were queued, meaning that “FooBarHerpDerp” and “HerpDerpFooBar” would be the only possible results from the above code. This queueing was removed when callers were added that were essentially: ```Hack concurrent { await async { await $f->seekAsync(123); $data = await $f->writeAllAsync("foo"); }; await $f->writeAllAsync("barbaz\n"); } ``` This was similarly undefined behavior; additionally, there is no guarantee that the “foo” write is the next write after the seek. This queuing was removed as the only way to make multiple writers actually safe is to add application-level locking/queuing that spans multiple IO operations (such as `Async\Semaphore`, or linked-list-of-awaitable-style queues). Removing this built-in queuing also removed the need for methods like `seek()` and `close()` to be async. ## Exception Hierarchy HSL IO/OS’s exception hierarchy is heavily influenced by Python 3; this is a substantial change from Python 2, described in https://www.python.org/dev/peps/pep-3151/. These tend to indicate the cause of failure, rather than what went wrong. For example, opening a file may fail with a FileNotFoundError, not a FileOpenError. The primary goal for HSL IO was for the exception type to be sufficient to determine the appropriate action; in particular, we did not want this to become a common pattern: ``` try { ... } catch (IO\Exception $e) { switch ($e->getErrno()) { case ENOENT: ... ... } } ``` Instead, we wanted most code to look like this: ``` try { ... } catch (OS\FileNotFoundException $e) { ... } ``` This difference is very similar to the change that has been made between Python 2 and 3, and the Python 3 hierarchy meets HSL IO’s design goals, and is well received by the Python community. While the first form is still possible (and necessary for some rare cases), it is not the usual pattern. Java and Ruby take a similar approach. There is a more in depth discussion and cross-language comparison at https://github.com/hhvm/hsl-experimental/issues/37 ## “ReadWrite” handles vs separate read and write handles An early version of HSL IO did not have read-write handles; instead, you could have both a read and write handle for the same file. This would have reduced the number of interfaces significantly, and resolved some of the issues that the locking/queuing were also meant to address, assuming the two handles operated independently. This feature was removed and replaced with ReadWrite handles as there is not adequate portable support in libc: * opening the resource twice, in different modes, is not possible for some kinds of FDs * if split with the C `dup()` call, they are not truly independent, and behavior various by platform. For example, a `seek()` on the ‘read’ FD may also seek the ‘write’ FD. # Prior art: ## Disposable API Rust, Python, and the Qt C++ library all provide disposable-like behavior, however it is either optional, or additional language features (pointers, borrowing) or weaker restrictions (e.g. composability) address the problems. `File`s and `Socket`s in Rust have Disposable-like behavior/restrictions, however the “borrowing” language feature provides a clean way to avoid the issues raised previously. In Python, `with` is strongly encouraged, but is optional. This provides safety for simple cases, but allows the flexibility needed to address others (e.g. composition is permitted). QIODevice, QFile, and QTCPSocket classes in the Qt library for C++ are non-copyable like disposables, close on destruct, however pointers and composition are permitted, avoiding the problems above. ## Implementation based on File Descriptors Rust and Python take a similar approach to HSL IO: common operations are provided via high-level classes - however the raw file descriptor is available for niche operations. HSL IO differs in that an object wrapper is used (`OS\FileDescriptor`) instead of directly exposing the int. The wrapper object is needed for correctness in CLI-server mode, and in a multi-request environment. ## BufferedReader as a separate class Buffered reading was split out to a separate class as mixing buffered and unbuffered reads leads to undefined and unintuitive behavior; for example, `readByteAsync()` may have read and cached 1024 bytes but only returned the first 1. Unbuffered reads need to remain possible for packet-based network protocols. Rust (`std::io::BufReader`), Java (`java.io.BufferedReader`), and Python (`io.BufferedReader`) all take the same solution to this problem. Python also offers implicit buffering when opening a file, however this makes all operations buffered - it does not mix them. ## Read and Write in the type system In Rust, `Read` and `Write` are distinct interfaces - however, `File::open()` always returns a `File`, which implements both, regardless of the open mode. This allows functions to specify that a parameter only needs to be readable, but it remains possible to pass a write-only file to such a function. Java IO is similar to HSL IO for handling of read (via `InputStream`), write (via `OutputStream`), and read write (`ByteChannel`) for files - however these are created via separate functions/methods, and are not part of a `File` or `Socket` object. For example, a `Socket` does not extend `OutputStream`, but provides `getInputStream` and `getOutputStream` methods. This design encourages APIs to take `InputStream` or `OutputStream` parameters instead of `Socket`s, providing similar benefits to HSL IO’s `IO\ReadHandle` and `IO\WriteHandle` separation. # Unresolved questions: - `var_dump()`, `print_r()`, etc: setting `O_NONBLOCK` on stderr breaks a lot of debugging utilities, especially with large outputs. Should they set `O_NONBLOCK off temporarily, or should they be async, or hidden `HH\Asio\join`? - What do we ‘encourage’ in www, e.g. via namespace aliasing? * `IO\`: yes, especially the interfaces * `OS\`: yes: while the functions in this namespace should very rarely be used directly, the exception classes should, and this is the correct place for them * `File\`: maybe; we may want to only encourage wrappers instead, e.g. restricting what paths can be opened. * `TCP\`, `Unix\`, `Network\`: yes: these will be rarely used, but are so niche that it is unlikely that general-purpose wrappers will be written. # Future possibilities: ## Entrypoint API In order to remove the PHP STDIN, STDOUT, STDERR constants, $_POST, $_GET and similar, we need to define a replacement. This should be built on HSL IO, and will effectively tie all Hack programs to some aspects of HSL IO’s design - in particular, if HSL IO handles were disposable, this would apply severe constraints to the design of Hack programs. Suggestions have included: ``` <<__CLIEntryPoint>> async function main( vec<string> $argv, vec<string> $envp, IO\ReadHandle $stdin, IO\WriteHandle $stdout, IO\WriteHandle $stderr, ): Awaitable<void> {} <<__CLIEntryPoint>> function main(CLIRequestContext $ctx): void { $argv = $argv->getArgv(); $stdin = $ctx->getStdin(); } <<__WebEntryPoint>> function main(WebRequestContext $ctx): void {} <<__EntryPoint>> function main(): Awaitable<void> { $argv = OS\argv(); $envp = OS\envp(); $stdin = OS\stdin(); // an IO\CloseableReadFDHandle or throw $input = OS\request_input(); // CLI STDIN or HTTP POST data (php://input) } ``` While the specific API does not matter at this point, this both constrains - and is constrained by - HSL IO’s design, especially if Disposables were used. If Disposables were used, the ‘virality’ issues above will be severe for every Hack program that does any form of IO, including sending HTML to the browser. ## Remove PHPisms IO `resource`s inherited from PHP are: * one of the remaining cases of observable refcounting/destructor-like behavior * poorly typed: it should be a type error to pass a file resource to curl_exec when a curl handle is expected Once HSL IO is built-in, we can start to remove these. * removing the PHP builtin STDIN, STDOUT, STDERR constants will be possible when a new entrypoint API is agreed on; that will potentially allow complete removal of the ‘PlainFile’ resource type too * removing further resource types will be possible as HSL IO is extended, in particular with TLS and subprocess support. ## Denotable intersection types There are various operations that are only appropriate for some handles, e.g.: * read() * write() * seek() * getpeername() Each set of related operations is represented by an interface, e.g.: * `IO\ReadHandle` * `IO\WriteHandle` * `IO\SeekableHandle` * `Network\Socket` As mentioned in ‘user experience’, each combination needs its’ own interface in order to be usable as a parameter type; for example, if a function needs to read, write, and seek, it takes an `IO\SeekableReadWriteHandle`. Early versions of HSL IO contained manual definitions of the ‘reasonable’ combinations, but this was a frequent source of bugs due to oversights. Now the interfaces are generated, which means that if any new interface is added, the number of generated interfaces roughly doubles. Currently, there are 26. There have been requests/suggestions for additional interfaces, e.g.: * TruncatableHandle * RewindableHandle as distinct to Seekable * DisposableHandle If these (or any other 3) were added, there would be 245 generated interfaces; if 5 were added, we’d get to 1010. This is not scalable. We will either need to be extremely selective about what new interfaces are added, or we will need a new way to represent these types. Denotable intersection types are the clearest fit, as these empty interfaces are effectively defining intersections: ``` - interface ReadWriteHandle extends ReadHandle, WriteHandle {} + type ReadWriteHandle = ReadHandle & WriteHandle; ``` The main advantage is that the intersections do not need to be predefined: currently, if a function needs to `read()` and `seek()`, it should take an `IO\SeekableReadHandle`, which must have been predefined in the HSL, and implemented by the concrete handle being passed. If denotable intersection types were supported: * if `IO\SeekableReadHandle` was defined as an intersection, it would not need to be explicitly present in the type hierarchy of the concrete implementations * `IO\SeekableReadHandle` does not need to be predefined: a function could take a `IO\SeekableHandle & IO\ReadHandle` parameter instead. This would: * greatly simplify the type hierarchy (below) * allow decisions about interfaces to be made purely on the usability/correctness merits ### The type hierarchy of a read-write file handle without denotable intersection types ![Type hierarchy with 64 interfaces](io_without_intersection_types.png) ### The type hierarchy of a read-write file handle using denotable intersection types ![Type hierarchy with 7 interfaces](io_with_intersection_types.png) ## Disposable IO API While a non-disposable IO API is essential as a building block for higher-level libraries (e.g. redis clients), a Disposable API is highly desirable for operations we commonly think of as IO, like opening files and directly interacting with a TCP socket. This can be built on top of a non-Disposable API, but a non-Disposable API can not be built on top of a Disposable API. Some ways this could be implemented: ### Wrappers A `File\DisposableReadWriteHandle` could wrap a `File\ReadWriteHandle`; functions should aim to specify their parameters as `<<__AcceptDisposable>>` wherever possible. This requires another interface (and the corresponding doubling of generated interfaces), and hand-written wrappers for each instantiable handle class. ### Add an “optionally disposable” language feature The user experience would be similar to Python’s `with`: ```Hack class File implements ..., IOptionallyDisposable { // ... public function __dispose() { $this->close(); } } // No `using`, __dispose is simply not called: $f = new File('/tmp/foo'); // ... so must manually close: $f->close(); using $f = new File('/tmp/bar'); // automatically closed - but you can call `$f->close()` earlier if you want ``` This should be a separate HIP, but I believe it would be the best approach: * no need for 2x the classes/interfaces: good for maintainability and discoverability * good for discoverability: only one API There is one major issue with this concept though: ```Hack function takes_rh(IO\ReadHandle $_): void {} function takes_drh(<<__AcceptDisposable>> IO\ReadHandle): void {} takes_rh(new File('/tmp/foo')); // No error using $f = new File('/tmp/foo'); takes_drh($f); // No error takes_rh($f); // error? ``` Error: it is being used as a disposable, so should act like one No error: IOptionallyDisposable would primarily be useful for convenience; it should not be considered an ‘ownership’ model. As such, it is likely that `__dispose()` calls another public method (like `close()`), so if something keeps hold of the handle after __dispose was called, it may be in a bad state, but this state would be reachable even if it wasn’t disposable.
OCaml
hhvm/hphp/hack/doc/pharser/driver.ml
(* * Copyright (c) 2020, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module I = Phparser.MenhirInterpreter let last_pos = ref 0 let get_line pos ic = let max_sz = in_channel_length ic in seek_in ic (max 0 (pos - 80)); let text = really_input_string ic (min (pos + 160) max_sz - pos + 80) in let min_bound = ref 0 in let rec find_newline i = match String.index_from text i '\n' with | exception Not_found -> String.length text | i when i < 80 -> min_bound := (i + 1); find_newline (i + 1) | i -> i in let max_bound = find_newline 0 in let ofs = pos - max 0 (pos - 80) in String.sub text !min_bound (max_bound - !min_bound) ^ "\n" ^ String.make (max 0 (ofs - !min_bound)) ' ' ^ "^" let () = let new_state () = Phlexer.new_state ~strict_lexer:false ~verbose_lexer:false ~case_sensitive:false ~xhp_builtin:true ~facebook_lang_extensions:true () in let trace state lexbuf = let token = Phlexer.token state lexbuf in let offset = lexbuf.Lexing.lex_abs_pos in let startp = offset + lexbuf.Lexing.lex_start_pos in let endp = offset + lexbuf.Lexing.lex_curr_pos in Printf.printf "%s %d-%d @ %s\n" (Phparser_driver.token_to_string token) startp endp (Phlexer.dump_modes state); token in let dummy f lexbuf = let rec loop () = match f lexbuf with | Phparser.EOF -> () | _ -> loop () in loop () in let action = match if Array.length Sys.argv >= 2 then Sys.argv.(1) else "" with | "debug-lex" -> (fun name -> dummy (trace (new_state ()))) | "debug-parse" -> (fun name -> let state = new_state () in let rec filter lexbuf = let offset = lexbuf.Lexing.lex_abs_pos in let pos = offset + lexbuf.Lexing.lex_curr_pos in last_pos := pos; match trace state lexbuf with | Phparser.OPEN_TAG | Phparser.COMMENT | Phparser.DOC_COMMENT | Phparser.SPACES | Phparser.NEWLINE -> filter lexbuf | result -> result in fun lexbuf -> try Phparser_driver.parse ~verbose:true filter lexbuf with exn -> raise Exit ) | "lex" -> (fun name -> dummy (Phlexer.token (new_state ()))) | "parse" -> (fun name -> let state = new_state () in let rec filter lexbuf = let offset = lexbuf.Lexing.lex_abs_pos in let pos = offset + lexbuf.Lexing.lex_curr_pos in last_pos := pos; match Phlexer.token state lexbuf with | Phparser.OPEN_TAG | Phparser.COMMENT | Phparser.DOC_COMMENT | Phparser.SPACES | Phparser.NEWLINE -> filter lexbuf | result -> result in fun lexbuf -> Phparser_driver.parse ~verbose:true filter lexbuf ) | "silent-parse" -> (fun name -> let state = new_state () in let rec filter lexbuf = let offset = lexbuf.Lexing.lex_abs_pos in let pos = offset + lexbuf.Lexing.lex_curr_pos in last_pos := pos; match Phlexer.token state lexbuf with | Phparser.OPEN_TAG | Phparser.COMMENT | Phparser.DOC_COMMENT | Phparser.SPACES | Phparser.NEWLINE -> filter lexbuf | result -> result in fun lexbuf -> Phparser_driver.parse ~verbose:false filter lexbuf ) | _ -> prerr_endline "driver [lex | parse | debug-lex | debug-parse]"; exit 1 in if Array.length Sys.argv = 2 then let lexbuf = Lexing.from_channel stdin in lexbuf.Lexing.lex_start_p <- Lexing.dummy_pos; action "-" lexbuf else for i = 2 to Array.length Sys.argv - 1 do let ic = open_in_bin Sys.argv.(i) in begin try action Sys.argv.(i) (Lexing.from_channel ic); close_in_noerr ic; print_endline ("successful " ^ Sys.argv.(i)) with | Exit -> let text = get_line !last_pos ic in close_in_noerr ic; print_endline ("failed " ^ Sys.argv.(i) ^ ":" ^ string_of_int !last_pos); print_endline text; exit 1 | exn -> let text = get_line !last_pos ic in close_in_noerr ic; print_endline ("failed " ^ Sys.argv.(i) ^ ":" ^ string_of_int !last_pos); print_endline text; (*reraise exn*) end; done
hhvm/hphp/hack/doc/pharser/dune
(menhir (flags --explain --table --cmly) (modules phparser)) ; (ocamllex (modules phlexer)) (rule (targets phlexer.ml) (deps phlexer.mll) (action (chdir %{workspace_root} (run %{bin:ocamllex} -ml -q -o %{targets} %{deps})))) (rule (targets describe.ml) (deps phparser.cmly) (action (with-stdout-to %{targets} (run %{exe:process.exe} %{deps})))) (executable (name process) (flags (:standard -w -A)) (libraries menhirSdk) (modules process)) (executable (name driver) (flags (:standard -w -A)) (libraries menhirLib) (modules driver describe phlexer phparser phparser_driver))
OCaml Interface
hhvm/hphp/hack/doc/pharser/phlexer.mli
(* * Copyright (c) 2020, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type state exception Error of string val new_state : strict_lexer:bool -> verbose_lexer:bool -> case_sensitive:bool -> xhp_builtin:bool -> facebook_lang_extensions:bool -> unit -> state val token : state -> Lexing.lexbuf -> Phparser.token val dump_modes : state -> string
hhvm/hphp/hack/doc/pharser/phlexer.mll
{ (* Yoann Padioleau * * Copyright (C) 2009-2012 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Phparser (* Lexer State * =========== * In most languages the lexer has no state and all strings are always * encoded in the same way, in the same token, wherever the string is * located in the file (except for strings inside comments). In PHP * some characters, e.g. "'", as in "I don't like you" or "'foo'" can * mean different things. Indeed the PHP language in fact supports * multiple languages or "modes" inside the same script (which also * make emacs mode for such language harder to define). * * Inside the PHP script code part, the quote is the start of a string * and there must be a corresponding quote ending the string. Inside * the HTML part of a PHP file it's just a character like any other * character. Inside heredocs (the '<<<XXX' construct) it is again * considered as any other character. In the same way some strings such * as 'if' can again mean different things; when they are preceded by a * '->' they correspond to the possible name of a field, otherwise * they are special PHP keywords. * * Because all of this, the lexer has multiple states which are * represented below and adjusted via some push/pop_mode function * below. Depending on the state the lexer behaves differently. *) type state_mode = (* aka HTML mode *) | ST_INITIAL (* started with <?php or <?, finished by ?> *) | ST_IN_SCRIPTING (* started with <?=, finished by ?> *) | ST_IN_SCRIPTING2 (* handled by using ocamllex ability to define multiple lexers * ST_COMMENT | ST_DOC_COMMENT | ST_ONE_LINE_COMMENT *) (* started with ", finished with ". In most languages strings * are a single tokens but PHP allow interpolation which means * a string can contain nested PHP variables or expressions. *) | ST_DOUBLEQUOTE (* started with "`", finished with "`" *) | ST_BACKQUOTE (* started with ->, finished after reading one fieldname *) | ST_LOOKING_FOR_PROPERTY (* started with ${ *) | ST_LOOKING_FOR_VARNAME (* started with $xxx[ *) | ST_VAR_OFFSET (* started with <<<XXX, finished by XXX; *) | ST_START_HEREDOC of string (* started with <<<'XXX', finished by XXX; *) | ST_START_NOWDOC of string (* started with <xx when preceded by a certain token (e.g. 'return' '<xx'), * finished by '>' by transiting to ST_IN_XHP_TEXT, or really finished * by '/>'. *) | ST_IN_XHP_TAG of string list (* the current tag, e,g, ["x";"frag"] *) (* started with the '>' of an opening tag, finished when '</x>' *) | ST_IN_XHP_TEXT of string list (* the current tag *) (* Prelude * ======= * The PHP lexer. * * There are a few tricks to go around ocamllex restrictions * because PHP has different lexing rules depending on some "contexts" * (this is similar to Perl, e.g. the <<<END context). *) type state = { strict_lexer: bool; verbose_lexer: bool; case_sensitive: bool; xhp_builtin: bool; facebook_lang_extensions: bool; mutable last_non_whitespace_like_token: token; mutable mode_stack : state_mode list; mutable lexeme_stack_resume_pos : int; mutable lexeme_stack : (token * int * int) list; } let return st lexbuf (token, startp, endp) = assert (st.lexeme_stack_resume_pos = -1); st.lexeme_stack_resume_pos <- lexbuf.Lexing.lex_curr_pos; lexbuf.Lexing.lex_start_pos <- startp; lexbuf.Lexing.lex_curr_pos <- endp; token let return_many st lexbuf = function | [] -> invalid_arg "return_many: empty list" | x :: xs -> st.lexeme_stack <- xs; return st lexbuf x let error_lexeme () lexbuf = Lexing.lexeme lexbuf let join_tag () tags = String.concat ":" tags let lexeme lexbuf ?(s=0) ?(e=0) token = let start_pos = lexbuf.Lexing.lex_start_pos in let curr_pos = lexbuf.Lexing.lex_curr_pos in let startp = if s >= 0 then start_pos + s else curr_pos + s in let endp = if e <= 0 then curr_pos + e else start_pos + e in (token, startp, endp) (*****************************************************************************) (* Helpers *) (*****************************************************************************) exception Error of string let error st fmt = let strict_k s = raise (Error s) in let verbose_k s = prerr_endline ("LEXER: " ^ s) in if st.strict_lexer then Printf.ksprintf strict_k fmt else if st.verbose_lexer then Printf.ksprintf verbose_k fmt else Printf.ifprintf () fmt let unlex_characters buf n = ( let open Lexing in if n < 0 then invalid_arg "unlex_characters: offset should be positive"; if n > buf.lex_curr_pos - buf.lex_start_pos then invalid_arg "unlex_characters: offset larger than lexeme"; buf.lex_curr_pos <- buf.lex_curr_pos - n; if buf.lex_curr_p != Lexing.dummy_pos then buf.lex_curr_p <- {buf.lex_start_p with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos}; ) let set_lexeme_length buf n = ( let open Lexing in if n < 0 then invalid_arg "set_lexeme_length: offset should be positive"; if n > buf.lex_curr_pos - buf.lex_start_pos then invalid_arg "set_lexeme_length: offset larger than lexeme"; buf.lex_curr_pos <- buf.lex_start_pos + n; if buf.lex_curr_p != Lexing.dummy_pos then buf.lex_curr_p <- {buf.lex_start_p with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos}; ) let string_split char str = let rec loop str from char = match String.index_from str from char with | exception Not_found -> let len = String.length str in [String.sub str from (len - from)] | delim -> let s = String.sub str from (delim - from) in s :: loop str (delim + 1) char in match String.index str char with | exception Not_found -> [str] | delim -> let s = String.sub str 0 delim in s :: loop str (delim + 1) char (* all string passed to IDENT or VARIABLE should go through case_str *) (* An implementation of String.lowercase that does not allocate * if not necessary. *) let lowercase = ( let rec loop bytes len i = if i < len then let c = Bytes.unsafe_get bytes i in Bytes.unsafe_set bytes i (Char.lowercase c); loop bytes len (i + 1) else Bytes.unsafe_to_string bytes in let rec check str len i = if i < len then let c = String.unsafe_get str i in if c = Char.lowercase c then check str len (i + 1) else loop (Bytes.of_string str) len i else str in fun str -> check str (String.length str) 0 ) [@ocaml.warning "-3"] let case_str st lexeme = if st.case_sensitive then lexeme else lowercase lexeme let xhp_or_t_ident st ~f lexeme = if st.xhp_builtin then f lexeme else IDENT (case_str st lexeme) let lang_ext_or_t_ident st ~f lexeme = if st.facebook_lang_extensions then f lexeme else IDENT (case_str st lexeme) (* Keywords * ======== * opti: less convenient, but using a hash is faster than using a match. * Note that PHP allows those keywords to be used in certain places, * for instance as object fields as in $o->while, so the transformation * from a LABEL to those keywords is done only in a few cases. * * note: PHP is case insensitive so this hash table is used on * a lowercased string so don't put strings in uppercase below because * such keyword would never be reached! * * coupling: if you add a new keyword, don't forget to also modify * the xhp_attr_name_atom grammar rule in parser_php.mly * * http://php.net/manual/en/reserved.keywords.php * * todo: callable, goto *) type keyword_kind = | Lang_Normal | Lang_XHP | Lang_Facebook | Lang_FB_sensitive let keyword_table = let of_list l = let table = Hashtbl.create (List.length l) in List.iter (fun (k, v) -> assert (k = String.lowercase_ascii k); Hashtbl.add table k v; ) l; table in of_list [ "while" , (Lang_Normal, WHILE) ; "do" , (Lang_Normal, DO) ; "for" , (Lang_Normal, FOR) ; "foreach" , (Lang_Normal, FOREACH) (* ; "endwhile" , (Lang_Normal, ENDWHILE) ; "endfor" , (Lang_Normal, ENDFOR) ; "endforeach" , (Lang_Normal, ENDFOREACH) *) (* Those tokens were not in the original PHP lexer. This allowed to * have "self"/"parent" to be used at more places, e.g. as a function * name which is tolerated by PHP but should not IMHO. Those idents * have a special meaning and this should be reflected in the lexer, * especially since PHP 5.3 which allows static:: in addition to * self::, parent::. 'static' is a keyword so there is no reason * to not make self/parent keywords too. * * todo: should do something similar for $this. *) ; "self" , (Lang_Normal, SELF) ; "parent" , (Lang_Normal, PARENT) ; "if" , (Lang_Normal, IF) ; "else" , (Lang_Normal, ELSE) ; "elseif" , (Lang_Normal, ELSEIF) ; "break" , (Lang_Normal, BREAK) ; "continue" , (Lang_Normal, CONTINUE) ; "switch" , (Lang_Normal, SWITCH) ; "case" , (Lang_Normal, CASE) ; "default" , (Lang_Normal, DEFAULT) ; "return" , (Lang_Normal, RETURN) ; "try" , (Lang_Normal, TRY) ; "catch" , (Lang_Normal, CATCH) ; "finally" , (Lang_Normal, FINALLY) ; "throw" , (Lang_Normal, THROW) ; "exit" , (Lang_Normal, EXIT) ; "die" , (Lang_Normal, EXIT) ; "array" , (Lang_FB_sensitive, ARRAY) ; "darray" , (Lang_FB_sensitive, ARRAY) ; "varray" , (Lang_FB_sensitive, ARRAY) ; "vec" , (Lang_FB_sensitive, ARRAY) ; "dict" , (Lang_FB_sensitive, ARRAY) ; "keyset" , (Lang_FB_sensitive, ARRAY) ; "list" , (Lang_FB_sensitive, LIST) (* used for traits too *) ; "as" , (Lang_Normal, AS) ; "include" , (Lang_Normal, INCLUDE) ; "include_once" , (Lang_Normal, INCLUDE_ONCE) ; "require" , (Lang_Normal, REQUIRE) ; "require_once" , (Lang_Normal, REQUIRE_ONCE) ; "class" , (Lang_Normal, CLASS) ; "interface" , (Lang_Normal, INTERFACE) ; "extends" , (Lang_Normal, EXTENDS) ; "implements" , (Lang_Normal, IMPLEMENTS) ; "new" , (Lang_Normal, NEW) ; "clone" , (Lang_Normal, CLONE) ; "instanceof" , (Lang_Normal, INSTANCEOF) (* php 5.4 traits ('use' and 'as' are used for traits and other things) *) ; "trait" , (Lang_Normal, TRAIT) ; "insteadof" , (Lang_Normal, INSTEADOF) (* php 5.3 namespace *) ; "namespace" , (Lang_Normal, NAMESPACE) (* used for traits and namespace *) ; "use" , (Lang_Normal, USE) ; "abstract" , (Lang_Normal, ABSTRACT) ; "final" , (Lang_Normal, FINAL) ; "public" , (Lang_Normal, PUBLIC) ; "protected" , (Lang_Normal, PROTECTED) ; "private" , (Lang_Normal, PRIVATE) ; "echo" , (Lang_Normal, ECHO) ; "print" , (Lang_Normal, PRINT) ; "eval" , (Lang_Normal, EVAL) ; "global" , (Lang_Normal, GLOBAL) ; "function" , (Lang_Normal, FUNCTION) ; "empty" , (Lang_Normal, EMPTY) ; "const" , (Lang_Normal, CONST) ; "var" , (Lang_Normal, VAR) ; "declare" , (Lang_Normal, DECLARE) ; "static" , (Lang_Normal, STATIC) ; "unset" , (Lang_Normal, UNSET) ; "isset" , (Lang_Normal, ISSET) ; "__line__" , (Lang_Normal, LINE) ; "__file__" , (Lang_Normal, FILE) ; "__dir__" , (Lang_Normal, DIR) ; "__function__" , (Lang_Normal, FUNC_C) ; "__method__" , (Lang_Normal, METHOD_C) ; "__class__" , (Lang_Normal, CLASS_C) ; " __trait__" , (Lang_Normal, TRAIT_C) ; "__namespace__" , (Lang_Normal, NAMESPACE_C) (* was called NS_C *) (* ; "endif" , (Lang_Normal, ENDIF) ; "endswitch" , (Lang_Normal, ENDSWITCH) ; "enddeclare" , (Lang_Normal, ENDDECLARE); *) (* old: ; "__halt_compiler", HALT_COMPILER; *) ; "async" , (Lang_FB_sensitive, ASYNC) ; "super" , (Lang_FB_sensitive, SUPER) ; "coroutine" , (Lang_FB_sensitive, COROUTINE) ; "suspend" , (Lang_FB_sensitive, SUSPEND) (* php-facebook-ext: *) ; "yield" , (Lang_Facebook, YIELD) ; "await" , (Lang_Facebook, AWAIT) ; "using" , (Lang_Facebook, USING) ; "concurrent" , (Lang_FB_sensitive, CONCURRENT) (* php-facebook-ext: *) ; "type" , (Lang_FB_sensitive, TYPE) ; "newtype" , (Lang_Facebook, NEWTYPE) ; "shape" , (Lang_FB_sensitive, SHAPE) ; "is" , (Lang_Facebook, IS) ; "inout" , (Lang_Facebook, INOUT) ; "where" , (Lang_FB_sensitive, WHERE) (* xhp: having those XHP keywords handled here could mean they can not * be used for entities like functions or class names. We could * avoid this by introducing some lexer/parser hacks so that those * keywords are recognized only in certain contexts (e.g. just after * the '{' of a class) but that complicates the full parser (note * also that IMHO it's better to not let the user overload those * special names). A simpler solution, instead of extending the lexer, * is to extend the grammar by having a 'ident:' rule that allows * the regular IDENT as well as those XHP tokens. See parser_php.mly. *) ; "attribute" , (Lang_XHP, XHP_ATTRIBUTE) ; "children" , (Lang_XHP, XHP_CHILDREN) ; "category" , (Lang_XHP, XHP_CATEGORY) (* for attribute declarations and Hack first class enums *) ; "enum" , (Lang_FB_sensitive, ENUM) (* for children declarations *) ; "any" , (Lang_XHP, XHP_ANY) (* "empty" is already a PHP keyword, see EMPTY *) ; "pcdata" , (Lang_XHP, XHP_PCDATA) (* obsolete: now that use hphp instead of xdebug for coverage analysis ; "class_xdebug", (fun ii -> CLASS_XDEBUG ii) ; "resource_xdebug", (fun ii -> RESOURCE_XDEBUG ii) *) ] let ident_or_keyword st lexeme = let lexeme' = case_str st lexeme in match Hashtbl.find keyword_table lexeme' with | Lang_Normal, token -> token | Lang_XHP, token when st.xhp_builtin && lexeme = lexeme' -> token | Lang_Facebook, token when st.facebook_lang_extensions -> token | Lang_FB_sensitive, token when st.facebook_lang_extensions && lexeme = lexeme' -> token | _ -> IDENT lexeme | exception Not_found -> IDENT lexeme (* The logic to modify _last_non_whitespace_like_token is in the * caller of the lexer, that is in Parse_php.tokens. * Used for XHP. *) let last_non_whitespace_like_token st = st.last_non_whitespace_like_token let new_state ~strict_lexer ~verbose_lexer ~case_sensitive ~xhp_builtin ~facebook_lang_extensions () = { strict_lexer; verbose_lexer; case_sensitive; xhp_builtin; facebook_lang_extensions; mode_stack = [ST_INITIAL]; last_non_whitespace_like_token = EOF; lexeme_stack_resume_pos = -1; lexeme_stack = []; } let current_mode st = match st.mode_stack with | mode :: _ -> mode | [] -> error st "mode_stack is empty, defaulting to ST_INITIAL"; st.mode_stack <- [ST_INITIAL]; ST_INITIAL let push_mode st mode = st.mode_stack <- mode :: st.mode_stack let pop_mode st = match st.mode_stack with | [] -> () | x :: xs -> st.mode_stack <- xs let set_mode st mode = let (_ :: xs | ([] as xs)) = st.mode_stack in st.mode_stack <- mode :: xs let protect_start_pos fn st lexbuf = let start_pos = lexbuf.Lexing.lex_start_pos in let result = fn st lexbuf in lexbuf.Lexing.lex_start_pos <- start_pos; result (* Here is an example of state transition. Given a php file like: * * <?php return <x>foo<y>bar</y></x>; ?> * * we start with the stack in [ST_INITIAL]. The transitions are then: * * '<?php' -> [IN_SCRIPTING], via set_mode() * ' ' -> [IN_SCRIPTING] * 'return' -> [IN_SCRIPTING] * '<x' -> [IN_XHP_TAG "x"; IN_SCRIPTING], via push_mode() * '>' -> [IN_XHP_TEXT "x"; IN_SCRIPTING], via set_mode() * 'foo' -> [IN_XHP_TEXT "x"; IN_SCRIPTING] * '<y' -> [IN_XHP_TAG "y";IN_XHP_TEXT "x"; IN_SCRIPTING], via push_mode() * '>' -> [IN_XHP_TEXT "y"; IN_XHP_TEXT "x";IN_SCRIPTING], via set_mode() * 'bar' -> [IN_XHP_TEXT "y"; IN_XHP_TEXT "x"; IN_SCRIPTING] * '</y>' -> [IN_XHP_TEXT "x"; IN_SCRIPTING], via pop_mode() * '</x>' -> [IN_SCRIPTING], via pop_mode() * ';' -> [IN_SCRIPTING] * ' ' -> [IN_SCRIPTING] * '?> -> [INITIAL], via set_mode() * *) (* xhp: the function below is used to disambiguate the use * of ":" and "%" as either a way to start an XHP identifier or as * a binary operator. Note that we use a whitelist approach * for detecting ':' as a binary operator whereas HPHP and * XHPAST use a whitelist approach for detecting ':' as the * start of an XHP identifier. * * How to know the following lists of tokens is correct ? * We should compute FOLLOW(lexeme) for all tokens and check * if "%" or ":" can be in it ? *) let is_in_binary_operator_position st = match st.last_non_whitespace_like_token with (* if we are after a number or any kind of scalar, then it's ok to have a * binary operator *) | LNUMBER _ | DNUMBER _ | CONSTANT_ENCAPSED_STRING _ | DOUBLEQUOTE | BACKQUOTE (* same for ']' or ')'; anything that "terminates" an expression *) | RBRACKET | RPAREN | IDENT _ | VARIABLE _ -> true | _ -> false (* ugly: in code like 'function foo( (function(string):string) $callback){}' * we want to parse the '(string)' not as a STRING_CAST but * as an open paren followed by other tokens. The right fix would * be to not have those ugly lexing rules for cast, but this would * lead to some grammar ambiguities or require other parsing hacks anyway. *) let lang_ext_or_cast st lexbuf token = if st.facebook_lang_extensions then match st.last_non_whitespace_like_token with | FUNCTION -> (* just keep the open parenthesis *) set_lexeme_length lexbuf 1; LPAREN | _ -> token else token } (*****************************************************************************) (* Regexps aliases *) (*****************************************************************************) let ANY_CHAR = (_ | ['\n'] ) (* \x7f-\xff ???*) let WHITESPACE = [' ' '\n' '\r' '\t'] let TABS_AND_SPACES = [' ''\t']* let NEWLINE = ("\r"|"\n"|"\r\n") let LABEL0 = ['a'-'z''A'-'Z''_'] let LABEL = LABEL0 ['a'-'z''A'-'Z''0'-'9''_']* let LNUM = ['0'-'9']+ let DNUM = (['0'-'9']*['.']['0'-'9']+) | (['0'-'9']+['.']['0'-'9']* ) let EXPONENT_DNUM = ((LNUM|DNUM)['e''E']['+''-']?LNUM) let HEXNUM = ("0x" | "0X")['0'-'9''a'-'f''A'-'F']+ let BINNUM = "0b"['0'-'1']+ (*/* * LITERAL_DOLLAR matches unescaped $ that aren't followed by a label character * or a { and therefore will be taken literally. The case of literal $ before * a variable or "${" is handled in a rule for each string type * * TODO: \x7f-\xff */ *) let DOUBLE_QUOTES_LITERAL_DOLLAR = ("$"+([^'a'-'z''A'-'Z''_''$''"''\\' '{']|('\\' ANY_CHAR))) let BACKQUOTE_LITERAL_DOLLAR = ("$"+([^'a'-'z''A'-'Z''_''$''`''\\' '{']|('\\' ANY_CHAR))) (*/* * CHARS matches everything up to a variable or "{$" * {'s are matched as long as they aren't followed by a $ * The case of { before "{$" is handled in a rule for each string type * * For heredocs, matching continues across/after newlines if/when it's known * that the next line doesn't contain a possible ending label */ *) let DOUBLE_QUOTES_CHARS = ("{"*([^'$''"''\\''{']| ("\\" ANY_CHAR))| DOUBLE_QUOTES_LITERAL_DOLLAR) let BACKQUOTE_CHARS = ("{"*([^'$' '`' '\\' '{']|('\\' ANY_CHAR))| BACKQUOTE_LITERAL_DOLLAR) let XHPLABEL = LABEL let XHPTAG = XHPLABEL ([':''-'] XHPLABEL)* let XHPATTR = XHPTAG (*****************************************************************************) (* Rule in script *) (*****************************************************************************) rule st_in_scripting st = parse (* ----------------------------------------------------------------------- *) (* spacing/comments *) (* ----------------------------------------------------------------------- *) | "/*" { protect_start_pos st_comment st lexbuf; COMMENT } | "/**/" { COMMENT } | "/**" { protect_start_pos st_comment st lexbuf; DOC_COMMENT } | ("#" | "//") { protect_start_pos st_one_line_comment st lexbuf; COMMENT } (* old: | WHITESPACE { WHITESPACE } *) | [' ' '\t']+ { SPACES } | ['\n' '\r'] { NEWLINE } (* ----------------------------------------------------------------------- *) (* Symbols *) (* ----------------------------------------------------------------------- *) | '+' { PLUS } | '-' { MINUS } | '*' { MUL } | '/' { DIV } | '%' { MOD } | "++" { INC } | "--" { DEC } | "=" { EQUAL } | "+=" { PLUS_EQUAL } | "-=" { MINUS_EQUAL } | "*=" { MUL_EQUAL } | "/=" { DIV_EQUAL } | "%=" { MOD_EQUAL } | "&=" { AND_EQUAL } | "|=" { OR_EQUAL } | "^=" { XOR_EQUAL } | "<<=" { SHL_EQUAL } | ">>=" { SHR_EQUAL } | ".=" { CONCAT_EQUAL } | "==" { IS_EQUAL } | "!=" { IS_NOT_EQUAL } | "===" { IS_IDENTICAL } | "!==" { IS_NOT_IDENTICAL } | "<>" { IS_NOT_EQUAL } | "<=>" { SPACESHIP } | "<=" { IS_SMALLER_OR_EQUAL } | ">=" { IS_GREATER_OR_EQUAL } | "<" { LANGLE } | ">" { RANGLE } | "&&" { BOOLEAN_AND } | "||" { BOOLEAN_OR } | "|>" { PIPE_ANGLE } | "<<" { SHL } | ">>" { set_lexeme_length lexbuf 1; SHR_PREFIX } | "**" { POW } | "**=" { POW_EQUAL } | "&" { AND } | "|" { OR } | "^" { XOR } | "OR" { LOGICAL_OR } | "AND" { LOGICAL_AND } | "XOR" { LOGICAL_XOR } | "or" { LOGICAL_OR } | "and" { LOGICAL_AND } | "xor" { LOGICAL_XOR } (* Flex/Bison allow to use single characters directly as-is in the grammar * by adding this in the lexer: * * <ST_IN_SCRIPTING>{TOKENS} { return yytext[0];} * * We don't, so we have transformed all those tokens in proper tokens with * a name in the parser, and return them in the lexer. *) | '.' { CONCAT } | ',' { COMMA } | '@' { AT } (* was called DOUBLE_ARROW but we actually now have a real ==> *) | "=>" { DOUBLE_ARROW } | "~" { TILDE } | ";" { SEMICOLON } | "!" { BANG } | "::" { COLONCOLON } (* was called T_PAAMAYIM_NEKUDOTAYIM *) | "\\" { ANTISLASH } (* was called T_NS_SEPARATOR *) | '(' { LPAREN } | ')' { RPAREN } | '[' { LBRACKET } | ']' { RBRACKET } | ":" { COLON } | "?" { QUESTION } | ":" { COLON } | "??" { QUESTION_QUESTION } | "??=" { QUESTION_QUESTION_EQUAL } (* semantic grep or var args extension *) | "..." { ELLIPSIS } (* facebook-ext: short lambdas *) | "==>" { LONG_DOUBLE_ARROW } (* we may come from a st_looking_for_xxx context, like in string * interpolation, so seeing a } we pop_mode! *) | '}' { pop_mode st; RBRACE } | '{' { push_mode st ST_IN_SCRIPTING; LBRACE } (*| (("->" | "?->") as sym) (WHITESPACE* as white) (LABEL as label) { (* todo: use yyback() instead of using pending_token with push_token. * buggy: push_mode st ST_LOOKING_FOR_PROPERTY; *) push_token st (IDENT (case_str st label, lblinfo)); (* todo: could be newline ... *) push_token st (SPACES (whiteinfo)); OBJECT_OPERATOR(syminfo) }*) | "->" { ARROW } | "?->" { QUESTION_ARROW } (* see also VARIABLE below. lex use longest matching strings so this * rule is used only in a last resort, for code such as $$x, ${, etc *) | "$" { DOLLAR } | "$$" { DOLLARDOLLAR } (* XHP "elements". * * In XHP the ":" and "%" characters are used to identify * XHP tags, e.g. :x:frag. There is some possible ambiguity though * with their others use in PHP: ternary expr and cases for ":" and * the modulo binary operator for "%". It is legal in PHP to do * e?1:null; or case 1:null. We thus can not blindly considerate ':null' * as a single token. Fortunately it's not too hard * to disambiguate by looking at the token before and see if ":" or "%" * is used as a unary or binary operator. * * An alternative would be to return the same token in both cases * (TCOLON) and let the grammar disambiguate and build XHP tags * from multiple tokens (e.g. [TCOLON ":"; IDENT "x"; TCOLON ":"; * TIDENT "frag"]). But this would force in the grammar to check * if there is no space between those tokens. This would also add * extra rules for things that really should be more handled at a * lexical level. *) | ":" (XHPTAG as tag) { if st.xhp_builtin && not (is_in_binary_operator_position st) then XHP_COLONID_DEF (string_split ':' tag) else (set_lexeme_length lexbuf 1; COLON) } | "%" (XHPTAG as tag) { if st.xhp_builtin && not (is_in_binary_operator_position st) then XHP_PERCENTID_DEF (string_split ':' tag) else (set_lexeme_length lexbuf 1; MOD) } (* xhp: we need to disambiguate the different use of '<' to know whether * we are in a position where an XHP construct can be started. Knowing * what was the previous token seems enough; no need to hack the * grammar to have a global shared by the lexer and parser. * * We could maybe even return a LANGLE in both cases and still * not generate any conflict in the grammar, but it feels cleaner to * generate a different token, because we will really change the lexing * mode when we will see a '>' which makes the parser enter in the * ST_IN_XHP_TEXT state where it's ok to write "I don't like you" * in which the quote does not need to be ended. * * note: no leading ":" for the tag when in "use" position. *) | "<" (XHPTAG as tag) { match st.last_non_whitespace_like_token with (* todo? How to compute the correct list of tokens that * are possibly before a XHP construct ? trial-and-error ? * Usually having a '<' after a punctuation means XHP. * Indeed '<' is a binary operator which excepts scalar. * * RPAREN? no, because it's ok to do (1) < (2)! *) | LPAREN | ECHO | PRINT | CLONE | SEMICOLON | COMMA | LBRACE | RBRACE | RETURN | YIELD | AWAIT | EQUAL | LBRACKET | CONCAT_EQUAL | DOUBLE_ARROW | LONG_DOUBLE_ARROW | QUESTION | COLON | QUESTION_QUESTION | QUESTION_QUESTION_EQUAL | PIPE_ANGLE | IS_NOT_IDENTICAL | IS_IDENTICAL | EOF (* when in sgrep/spatch mode, < is the first token, and last_non_whitespace_like_token defaults to EOF *) when st.xhp_builtin -> let xs = string_split ':' tag in push_mode st (ST_IN_XHP_TAG xs); XHP_OPEN_TAG xs | _ -> set_lexeme_length lexbuf 1; LANGLE } | "@required" { if st.xhp_builtin then XHP_REQUIRED else (set_lexeme_length lexbuf 1; AT) } (* Keywords and ident * ------------------ * ugly: 'self' and 'parent' should be keywords forbidden to be used * as regular identifiers. But PHP is case insensitive and does not * consider self/parent or SELF/PARENT as keywords. I think it's * bad so I now consider self/parent as keywords, but still allow * at least the uppercase form to be used as identifier, hence those * two rules below. *) | "SELF" { IDENT (case_str st "SELF") } | "PARENT" { IDENT (case_str st "PARENT") } (* ugly: some code is using ASYNC as a constant, so one way to fix * the conflict is to return the ASYNC only when it's used * as lowercase. Note that because some code is using 'async' * as a method we then need to extend ident_method_name * in parser_php.mly. The alternative would be to lex * "async" as a ASYNC only when it's followed by a FUNCTION * but this is also ugly. *) | "async" { ASYNC } | LABEL { match st.last_non_whitespace_like_token with | ARROW | ANTISLASH (*| LONG_DOUBLE_ARROW*) -> IDENT (Lexing.lexeme lexbuf) | _ -> ident_or_keyword st (Lexing.lexeme lexbuf) } (* Could put a special rule for "$this", but there are multiple places here * where we can generate a VARIABLE, and we can have even expressions * like ${this}, so it is simpler to do the "this-analysis" in the grammar, * later when we generate a Var or This. *) | "$" (LABEL as s) { VARIABLE (case_str st s) } | "$$" LABEL0 { set_lexeme_length lexbuf 1; DOLLAR } (* Constant -------- *) | LNUM | BINNUM | HEXNUM { (* more? cf original lexer *) let s = Lexing.lexeme lexbuf in match int_of_string s with | _ -> LNUMBER s | exception Failure _ -> DNUMBER s } | DNUM | EXPONENT_DNUM { DNUMBER (Lexing.lexeme lexbuf) } (* Strings * ------- * * The original PHP lexer does a few things to make the * difference at parsing time between static strings (which do not * contain any interpolation) and dynamic strings. So some regexps * below are quite hard to understand ... but apparently it works. * When the lexer thinks it's a dynamic strings, it let the grammar * do most of the hard work. See the rules using DOUBLEQUOTE in the grammar * (and here in the lexer). * * The optional 'b' at the beginning is for binary strings. * * /* * ("{"*|"$"* ) handles { or $ at the end of a string (or the entire * contents) * * * int bprefix = (yytext[0] != '"') ? 1 : 0; * zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' * TSRMLS_CC); */ *) (* static strings *) | 'b'? (['"'] ((DOUBLE_QUOTES_CHARS* ("{"*|"$"* )) as s) ['"']) { CONSTANT_ENCAPSED_STRING s } | 'b'? (['\''] (([^'\'' '\\']|('\\' ANY_CHAR))* as s) ['\'']) { (* more? cf original lexer *) CONSTANT_ENCAPSED_STRING s } (* dynamic strings *) | '"' { push_mode st ST_DOUBLEQUOTE; DOUBLEQUOTE } | '`' { push_mode st ST_BACKQUOTE; BACKQUOTE } | 'b'? "<<<" TABS_AND_SPACES (LABEL as s) NEWLINE { set_mode st (ST_START_HEREDOC s); START_HEREDOC } | 'b'? "<<<" TABS_AND_SPACES "'" (LABEL as s) "'" NEWLINE { set_mode st (ST_START_NOWDOC s); (* could use another token, but simpler to reuse *) START_HEREDOC } | "re\"" (* regular expression literal *) { push_mode st ST_DOUBLEQUOTE; DOUBLEQUOTE } (* Misc * ---- * ugly: the cast syntax in PHP is newline and even comment sensitive. Hmm. * You cannot write for instance '$o = (int/*comment*/) foo();'. * We would really like to have different tokens for '(', space, * idents, and a grammar rule like 'expr: LPAREN TIdent RPAREN' * but then the grammar would be ambiguous with 'expr: LPAREN expr RPAREN' * unless like in C typenames have a special token type and you can * have a rule like 'expr: LPAREN TTypename RPAREN. * This could have been done in PHP if those typenames were reserved * tokens, but PHP allows to have functions or methods called e.g. * string(). So what they have done is this ugly lexing hack. *) | "(" WHITESPACE* ("int"|"integer") WHITESPACE* ")" { lang_ext_or_cast st lexbuf INT_CAST } | "(" WHITESPACE* ("real"|"double"|"float") WHITESPACE* ")" { lang_ext_or_cast st lexbuf DOUBLE_CAST } | "(" WHITESPACE* "string" WHITESPACE* ")" { lang_ext_or_cast st lexbuf STRING_CAST } | "(" WHITESPACE* "binary" WHITESPACE* ")" { lang_ext_or_cast st lexbuf STRING_CAST } | "(" WHITESPACE* (['v' 'd']? "array"|"vec"|"dict"|"keyset") WHITESPACE* ")" { lang_ext_or_cast st lexbuf ARRAY_CAST } | "(" WHITESPACE* "object" WHITESPACE* ")" { lang_ext_or_cast st lexbuf OBJECT_CAST } | "(" WHITESPACE* ("bool"|"boolean") WHITESPACE* ")" { lang_ext_or_cast st lexbuf BOOL_CAST } (* PHP is case insensitive for many things *) | "(" WHITESPACE* "Array" WHITESPACE* ")" { lang_ext_or_cast st lexbuf ARRAY_CAST } | "(" WHITESPACE* "Object" WHITESPACE* ")" { lang_ext_or_cast st lexbuf OBJECT_CAST } | "(" WHITESPACE* ("Bool"|"Boolean") WHITESPACE* ")" { lang_ext_or_cast st lexbuf BOOL_CAST } | "(" WHITESPACE* ("unset") WHITESPACE* ")" { lang_ext_or_cast st lexbuf UNSET_CAST } | "?>" { (* because of XHP and my token merger: old: | "</script" WHITESPACE * ">" NEWLINE? see tests/xhp/pb_cant_merge2.php *) match current_mode st with | ST_IN_SCRIPTING -> set_mode st ST_INITIAL; (* implicit ';' at php-end tag todo? ugly, could instead generate a FakeToken or ExpandedToken, but then some code later may assume right now that all tokens from the lexer are origin tokens, so may be hard to change. old: (CLOSE_TAG) note that CLOSE_TAG was skipped anyway in Parse_php.parse_php *) CLOSE_TAG (*SEMICOLON*) | ST_IN_SCRIPTING2 -> set_mode st ST_INITIAL; CLOSE_TAG_OF_ECHO | _ -> assert false } (* ----------------------------------------------------------------------- *) | eof { EOF } | _ { error st "unrecognised symbol, in token rule: %a" error_lexeme lexbuf; UNKNOWN } (*****************************************************************************) (* Rule initial (html) *) (*****************************************************************************) and initial st = parse | "<?php" ([' ' '\t']|NEWLINE) (* php-facebook-ext: fbstrict extensions *) | "<?hh" ([' ' '\t']|NEWLINE) { (* I now do a yyback to not eat the newline which is more consistent with how I treat newlines elsewhere *) unlex_characters lexbuf 1; set_mode st ST_IN_SCRIPTING; OPEN_TAG } | "<?hh//" { unlex_characters lexbuf 2; set_mode st ST_IN_SCRIPTING; OPEN_TAG } | "<?PHP"([' ''\t'] | NEWLINE) | "<?Php"([' ''\t'] | NEWLINE) { (* "BAD USE OF <PHP at initial state, replace by <?php"; *) set_mode st ST_IN_SCRIPTING; OPEN_TAG } | ([^'<'] | "<" [^ '?' '%' 's' '<'])+ | "<s" | "<" { (* more? cf original lexer *) INLINE_HTML (Lexing.lexeme lexbuf) } | "<?=" { (* less: if short_tags normally, otherwise INLINE_HTML *) set_mode st ST_IN_SCRIPTING2; (* todo? ugly, may be better ot generate a real ECHO token with maybe a * FakeToken or ExpandedToken. *) OPEN_TAG_WITH_ECHO } | "<?" | "<script" WHITESPACE+ "language" WHITESPACE* "=" WHITESPACE* ("php"|"\"php\""|"\'php\'") WHITESPACE* ">" { (* XXX if short_tags normally otherwise INLINE_HTML *) (* pr2 "BAD USE OF <? at initial state, replace by <?php"; *) set_mode st ST_IN_SCRIPTING; OPEN_TAG; } (*------------------------------------------------------------------------ *) | eof { EOF } | _ (* ANY_CHAR *) { error st "unrecognised symbol, in token rule: %a" error_lexeme lexbuf; UNKNOWN } (*****************************************************************************) (* Rule looking_for_xxx *) (*****************************************************************************) and st_looking_for_property st = parse | "->" { ARROW } | "?->" { QUESTION_ARROW } | LABEL { pop_mode st; IDENT (case_str st (Lexing.lexeme lexbuf)) } (* | ANY_CHAR { (* XXX yyback(0) ?? *) pop_mode(); } *) and st_looking_for_varname st = parse | LABEL { set_mode st ST_IN_SCRIPTING; VARNAME (Lexing.lexeme lexbuf) } | _ { unlex_characters lexbuf 1; set_mode st ST_IN_SCRIPTING; st_in_scripting st lexbuf } (*****************************************************************************) and st_var_offset st = parse | LNUM | HEXNUM | BINNUM { (* /* Offset must be treated as a string */ *) NUM_STRING (Lexing.lexeme lexbuf) } | "$" (LABEL as s) { VARIABLE (case_str st s) } | LABEL { IDENT (case_str st (Lexing.lexeme lexbuf)) } | "]" { pop_mode st; RBRACKET } | eof { EOF } | _ { error st "unrecognised symbol, in st_var_offset rule: %a" error_lexeme lexbuf; UNKNOWN } (*****************************************************************************) (* Rule strings *) (*****************************************************************************) and st_double_quotes st = parse | DOUBLE_QUOTES_CHARS+ { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } (* todo? was in original scanner ? *) | "{" { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | "$" (LABEL as s) { VARIABLE (case_str st s) } | "$" (LABEL as s) "[" { push_mode st ST_VAR_OFFSET; return_many st lexbuf [ lexeme lexbuf ~e:(-1) (VARIABLE (case_str st s)); lexeme lexbuf ~s:(-1) LBRACKET; ] } (* bugfix: can have strings like "$$foo$" *) | "$" { ENCAPSED_AND_WHITESPACE "$" } | "{$" { unlex_characters lexbuf 1; push_mode st ST_IN_SCRIPTING; CURLY_OPEN; } | "${" { push_mode st ST_LOOKING_FOR_VARNAME; DOLLAR_OPEN_CURLY_BRACES; } | '"' { (* was originally set_mode st ST_IN_SCRIPTING, but with XHP * the context for a double quote may not be anymore always * ST_IN_SCRIPTING *) pop_mode st; DOUBLEQUOTE } | eof { EOF } | _ { error st "unrecognised symbol, in st_double_quotes rule: %a" error_lexeme lexbuf; UNKNOWN } (* ----------------------------------------------------------------------- *) (* mostly copy paste of st_double_quotes; just the end regexp is different *) and st_backquote st = parse | BACKQUOTE_CHARS+ { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | "$" (LABEL as s) { VARIABLE (case_str st s) } | "$" (LABEL as s) "[" { push_mode st ST_VAR_OFFSET; return_many st lexbuf [ lexeme lexbuf ~e:(-1) (VARIABLE s); lexeme lexbuf ~s:(-1) LBRACKET; ] } (* bugfix: can have strings like "$$foo$" *) | "$" { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | "{$" { unlex_characters lexbuf 1; push_mode st ST_IN_SCRIPTING; CURLY_OPEN } | "${" { push_mode st ST_LOOKING_FOR_VARNAME; DOLLAR_OPEN_CURLY_BRACES } | '`' { set_mode st ST_IN_SCRIPTING; BACKQUOTE } | eof { EOF } | _ { error st "unrecognised symbol, in st_backquote rule: %a" error_lexeme lexbuf; UNKNOWN } (* ----------------------------------------------------------------------- *) (* As heredoc have some of the semantic of double quote strings, again some * rules from st_double_quotes are copy pasted here. * * todo? the rules below are not what was in the original Zend lexer, * but the original lexer was doing very complicated stuff ... *) and st_start_heredoc st stopdoc = parse | (LABEL as s) ['\n' '\r'] { if s = stopdoc then ( set_mode st ST_IN_SCRIPTING; return_many st lexbuf [ lexeme lexbuf ~e:(-1) END_HEREDOC; lexeme lexbuf ~s:(-1) NEWLINE ] ) else ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | (LABEL as s) ";" ['\n' '\r'] { if s = stopdoc then ( set_mode st ST_IN_SCRIPTING; return_many st lexbuf [ lexeme lexbuf ~e:(-2) END_HEREDOC; lexeme lexbuf ~s:(-2) ~e:(-1) SEMICOLON; lexeme lexbuf ~s:(-1) NEWLINE; ] ) else ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | [^ '\n' '\r' '$' '{' '\\']+ { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | "\\" ANY_CHAR { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | "$" (LABEL as s) { VARIABLE (case_str st s) } | "$" (LABEL as s) "[" { push_mode st ST_VAR_OFFSET; return_many st lexbuf [ lexeme lexbuf ~e:(-1) (VARIABLE (case_str st s)); lexeme lexbuf ~s:(-1) LBRACKET; ] } (* bugfix: can have strings like "$$foo$", or {{$foo}} *) | "$" { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | "{" { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | ['\n' '\r'] { NEWLINE } | "{$" { unlex_characters lexbuf 1; push_mode st ST_IN_SCRIPTING; CURLY_OPEN; } | "${" { push_mode st ST_LOOKING_FOR_VARNAME; DOLLAR_OPEN_CURLY_BRACES; } | eof { EOF } | _ { error st "unrecognised symbol, in st_start_heredoc rule: %a" error_lexeme lexbuf; UNKNOWN } (* ----------------------------------------------------------------------- *) (* todo? this is not what was in the original lexer, but the original lexer * does complicated stuff ... *) and st_start_nowdoc st stopdoc = parse | (LABEL as s) ['\n' '\r'] { if s = stopdoc then ( set_mode st ST_IN_SCRIPTING; return_many st lexbuf [ lexeme lexbuf ~e:(-1) END_HEREDOC; lexeme lexbuf ~s:(-1) NEWLINE ] ) else ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | (LABEL as s) ";" ['\n' '\r'] { if s = stopdoc then ( set_mode st ST_IN_SCRIPTING; return_many st lexbuf [ lexeme lexbuf ~e:(-2) END_HEREDOC; lexeme lexbuf ~s:(-2) ~e:(-1) SEMICOLON; lexeme lexbuf ~s:(-1) NEWLINE; ] ) else ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | [^ '\n' '\r']+ { ENCAPSED_AND_WHITESPACE (Lexing.lexeme lexbuf) } | ['\n' '\r'] { NEWLINE } | eof { EOF } | _ { error st "unrecognised symbol, in st_start_nowdoc rule: %a" error_lexeme lexbuf; UNKNOWN } (*****************************************************************************) (* Rules for XHP *) (*****************************************************************************) (* XHP lexing states and rules *) and st_in_xhp_tag st current_tag = parse (* The original XHP parser have some special handlings of * whitespace and enforce to use certain whitespace at * certain places. Not sure I need to enforce this too. * Simpler to ignore whitespaces. * * todo? factorize with st_in_scripting rule? *) | [' ' '\t']+ { SPACES } | ['\n' '\r'] { NEWLINE } | "/*" { protect_start_pos st_comment st lexbuf; COMMENT } | "/**/" { COMMENT } | "/**" { (* RESET_DOC_COMMENT(); *) protect_start_pos st_comment st lexbuf; DOC_COMMENT } | "//" { protect_start_pos st_one_line_comment st lexbuf; COMMENT } (* attribute management *) | XHPATTR { XHP_ATTR (Lexing.lexeme lexbuf) } | "=" { EQUAL } (* not sure if XHP strings needs the interpolation support *) | '"' { push_mode st ST_DOUBLEQUOTE; DOUBLEQUOTE } | "{" { push_mode st ST_IN_SCRIPTING; LBRACE } (* a singleton tag *) | "/>" { pop_mode st; XHP_SLASH_GT } (* When we see a ">", it means it's just the end of * the opening tag. Transit to IN_XHP_TEXT. *) | ">" { set_mode st (ST_IN_XHP_TEXT current_tag); XHP_GT } | eof { EOF } | _ { error st "unrecognised symbol, in XHP tag: %a" error_lexeme lexbuf; UNKNOWN } (* ----------------------------------------------------------------------- *) and st_in_xhp_text st current_tag = parse (* a nested xhp construct *) | "<" (XHPTAG as tag) { let xs = string_split ':' tag in push_mode st (ST_IN_XHP_TAG xs); XHP_OPEN_TAG xs } | "</" (XHPTAG as tag) ' '* ">" { let xs = string_split ':' tag in if (xs <> current_tag) then error st "XHP: wrong closing tag for, %a != %a" join_tag xs join_tag current_tag; pop_mode st; XHP_CLOSE_TAG (Some xs) } (* shortcut for closing tag ? *) | "</>" { (* no check :( *) pop_mode st; XHP_CLOSE_TAG None } | "<!--" { protect_start_pos st_xhp_comment st lexbuf; (* less: make a special token XHP_COMMENT? *) COMMENT } (* PHP interpolation. How the user can produce a { ? &;something ? *) | "{" { push_mode st ST_IN_SCRIPTING; LBRACE } (* opti: *) | [^'<' '{']+ { XHP_TEXT (Lexing.lexeme lexbuf) } | eof { EOF } | _ { error st "unrecognised symbol, in XHP text: %a" error_lexeme lexbuf; UNKNOWN } and st_xhp_comment st = parse | "-->" { () } | [^'-']+ { st_xhp_comment st lexbuf } | "-" { st_xhp_comment st lexbuf } | eof { error st "end of file in xhp comment" } | _ { error st "unrecognised symbol in xhp comment: %a" error_lexeme lexbuf; st_xhp_comment st lexbuf } (*****************************************************************************) (* Rule comment *) (*****************************************************************************) and st_comment st = parse | "*/" { () } (* noteopti: *) | ([^'*']+ | '*') { st_comment st lexbuf } | eof { error st "end of file in comment" } | (_ as c) { error st "unrecognised symbol in comment: %c" c; st_comment st lexbuf } and st_one_line_comment st = parse | ['?' '%' '>'] { st_one_line_comment st lexbuf } | [^'\n' '\r' '?' '%' '>']* (ANY_CHAR as x) { match x with | '?' | '%' | '>' -> unlex_characters lexbuf 1; st_one_line_comment st lexbuf (* end of recursion when new line or other character *) | '\n' -> (* don't want the newline to be part of the comment *) unlex_characters lexbuf 1 | _ -> () } | NEWLINE { (* don't want the newline to be part of the comment *) unlex_characters lexbuf 1 } | "?>" { (* "%>" is only when use asp_tags *) unlex_characters lexbuf 2 } | eof { error st "end of file in comment" } | _ { error st "unrecognised symbol, in st_one_line_comment rule: %a" error_lexeme lexbuf } { let token st lexbuf = match st.lexeme_stack with | (token, startp, endp) :: xs -> lexbuf.Lexing.lex_start_pos <- startp; lexbuf.Lexing.lex_curr_pos <- endp; st.lexeme_stack <- xs; token | [] -> if st.lexeme_stack_resume_pos > -1 then ( lexbuf.Lexing.lex_curr_pos <- st.lexeme_stack_resume_pos; st.lexeme_stack_resume_pos <- -1; ); match current_mode st with | ST_INITIAL -> initial st lexbuf | ST_IN_SCRIPTING | ST_IN_SCRIPTING2 -> st_in_scripting st lexbuf | ST_DOUBLEQUOTE -> st_double_quotes st lexbuf | ST_BACKQUOTE -> st_backquote st lexbuf | ST_LOOKING_FOR_PROPERTY -> st_looking_for_property st lexbuf | ST_LOOKING_FOR_VARNAME -> st_looking_for_varname st lexbuf | ST_VAR_OFFSET -> st_var_offset st lexbuf | ST_START_HEREDOC s -> st_start_heredoc st s lexbuf | ST_START_NOWDOC s -> st_start_nowdoc st s lexbuf | ST_IN_XHP_TAG tag -> assert st.xhp_builtin; st_in_xhp_tag st tag lexbuf | ST_IN_XHP_TEXT tag -> assert st.xhp_builtin; st_in_xhp_text st tag lexbuf let token st lexbuf = match token st lexbuf with | COMMENT | DOC_COMMENT | SPACES | NEWLINE as result -> result | result -> st.last_non_whitespace_like_token <- result; result let string_of_list item lst = "[" ^ String.concat "; " (List.map item lst) ^ "]" let string_of_state_mode = function | ST_INITIAL -> "ST_INITIAL" | ST_IN_SCRIPTING -> "ST_IN_SCRIPTING" | ST_IN_SCRIPTING2 -> "ST_IN_SCRIPTING2" | ST_DOUBLEQUOTE -> "ST_DOUBLEQUOTE" | ST_BACKQUOTE -> "ST_BACKQUOTE" | ST_LOOKING_FOR_PROPERTY -> "ST_LOOKING_FOR_PROPERTY" | ST_LOOKING_FOR_VARNAME -> "ST_LOOKING_FOR_VARNAME" | ST_VAR_OFFSET -> "ST_VAR_OFFSET" | ST_START_HEREDOC str -> Printf.sprintf "ST_START_HEREDOC %S" str | ST_START_NOWDOC str -> Printf.sprintf "ST_START_NOWDOC %S" str | ST_IN_XHP_TAG strs -> Printf.sprintf "ST_IN_XHP_TAG %s" (string_of_list (Printf.sprintf "%S") strs) | ST_IN_XHP_TEXT strs -> Printf.sprintf "ST_IN_XHP_TEXT %s" (string_of_list (Printf.sprintf "%S") strs) let dump_modes st = string_of_list string_of_state_mode st.mode_stack }
hhvm/hphp/hack/doc/pharser/phparser.mly
(* * Copyright (c) 2020, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) %{ %} (* Tokens *) %token EOF (* end of file *) %token INCLUDE (* include *) %token INCLUDE_ONCE (* include_once *) %token EVAL (* eval *) %token REQUIRE (* require *) %token REQUIRE_ONCE (* require_once *) %token LOGICAL_OR (* or *) %token LOGICAL_XOR (* xor *) %token LOGICAL_AND (* and *) %token PRINT (* print *) %token YIELD (* yield *) %token YIELD_FROM (* yield from *) %token PLUS_EQUAL (* += *) %token MINUS_EQUAL (* -= *) %token MUL_EQUAL (* *= *) %token DIV_EQUAL (* /= *) %token CONCAT_EQUAL (* .= *) %token MOD_EQUAL (* %= *) %token AND_EQUAL (* &= *) %token OR_EQUAL (* |= *) %token XOR_EQUAL (* ^= *) %token SHL_EQUAL (* <<= *) %token SHR_EQUAL (* >>= *) %token BOOLEAN_OR (* || *) %token BOOLEAN_AND (* && *) %token IS_EQUAL (* == *) %token IS_NOT_EQUAL (* != *) %token IS_IDENTICAL (* === *) %token IS_NOT_IDENTICAL (* !== *) %token IS_SMALLER_OR_EQUAL (* <= *) %token IS_GREATER_OR_EQUAL (* >= *) %token SPACESHIP (* <=> *) %token SHL (* << *) %token SHR_PREFIX (* >> (SHR_PREFIX RANGLE) *) %token INSTANCEOF (* instanceof *) %token INC (* ++ *) %token DEC (* -- *) %token INT_CAST (* (int) *) %token DOUBLE_CAST (* (double) *) %token STRING_CAST (* (string) *) %token ARRAY_CAST (* (array) *) %token OBJECT_CAST (* (object) *) %token BOOL_CAST (* (bool) *) %token UNSET_CAST (* (unset) *) %token NEW (* new *) %token CLONE (* clone *) %token EXIT (* exit *) %token IF (* if *) %token ELSEIF (* elseif *) %token ELSE (* else *) %token ENDIF (* endif *) %token ECHO (* echo *) %token DO (* do *) %token WHILE (* while *) %token FOR (* for *) %token FOREACH (* foreach *) %token DECLARE (* declare *) %token AS (* as *) %token SWITCH (* switch *) %token CASE (* case *) %token DEFAULT (* default *) %token BREAK (* break *) %token CONTINUE (* continue *) %token GOTO (* goto *) %token FUNCTION (* function *) %token CONST (* const *) %token RETURN (* return *) %token TRY (* try *) %token CATCH (* catch *) %token FINALLY (* finally *) %token THROW (* throw *) %token USE (* use *) %token INSTEADOF (* insteadof *) %token GLOBAL (* global *) %token STATIC (* static *) %token ABSTRACT (* abstract *) %token FINAL (* final *) %token PRIVATE (* private *) %token PROTECTED (* protected *) %token PUBLIC (* public *) %token VAR (* var *) %token UNSET (* unset *) %token ISSET (* isset *) %token EMPTY (* empty *) %token HALT_COMPILER (* __halt_compiler *) %token CLASS (* class *) %token TRAIT (* trait *) %token ENUM (* enum *) %token INTERFACE (* interface *) %token EXTENDS (* extends *) %token IMPLEMENTS (* implements *) %token ARROW (* -> *) %token QUESTION_ARROW (* ?-> *) %token DOUBLE_ARROW (* => *) %token LONG_DOUBLE_ARROW (* ==> *) %token LIST (* list *) %token ARRAY (* array *) %token CALLABLE (* callable *) %token LINE (* __LINE__ *) %token FILE (* __FILE__ *) %token DIR (* __DIR__ *) %token CLASS_C (* __CLASS__ *) %token TRAIT_C (* __TRAIT__ *) %token METHOD_C (* __METHOD__ *) %token FUNC_C (* __FUNCTION__ *) %token COMMENT (* comment *) %token DOC_COMMENT (* doc comment *) %token OPEN_TAG (* open tag *) %token OPEN_TAG_WITH_ECHO (* open tag with echo *) %token CLOSE_TAG (* close tag *) %token CLOSE_TAG_OF_ECHO (* close tag *) %token SPACES NEWLINE (* whitespace *) %token START_HEREDOC (* heredoc start *) %token END_HEREDOC (* heredoc end *) %token DOLLAR_OPEN_CURLY_BRACES (* ${ *) %token CURLY_OPEN (* {$ *) %token COLONCOLON (* :: *) %token NAMESPACE (* namespace *) %token NAMESPACE_C (* __NAMESPACE__ *) %token ANTISLASH (* \\ *) %token ELLIPSIS (* ... *) %token COALESCE (* ?? *) %token POW (* ** *) %token POW_EQUAL (* **= *) %token EQUAL (* '=' *) %token CONCAT (* '.' *) %token PLUS (* '+' *) %token COMMA (* ',' *) %token QUESTION (* '?' *) %token COLON (* ':' *) %token OR (* '|' *) %token MINUS (* '-' *) %token MUL (* '*' *) %token DIV (* '/' *) %token MOD (* '%' *) %token BANG (* '!' *) %token LPAREN (* '(' *) %token RPAREN (* ')' *) %token LBRACKET (* '[' *) %token RBRACKET (* ']' *) %token LBRACE (* '{' *) %token RBRACE (* '}' *) %token LANGLE (* '<' *) %token RANGLE (* '>' *) %token XOR (* '^' *) %token AND (* '&' *) %token SEMICOLON (* ';' *) %token AT (* '@' *) %token BACKQUOTE (* '`' *) %token DOUBLEQUOTE (* '"' *) %token DOLLAR (* '$' *) %token DOLLARDOLLAR (* '$$' *) %token TILDE (* '~' *) (* Extensions *) %token SELF PARENT ASYNC AWAIT TYPE NEWTYPE SHAPE PIPE_ANGLE UNKNOWN XHP_ATTRIBUTE XHP_CHILDREN XHP_CATEGORY XHP_ANY XHP_PCDATA XHP_REQUIRED XHP_SLASH_GT XHP_GT FORK IS (* is *) INOUT (* inout *) QUESTION_QUESTION (* '??' *) QUESTION_QUESTION_EQUAL (* '??=' *) USING CONCURRENT FOREACH_AS (*FIXME*) WHERE SUPER COROUTINE SUSPEND %token<bool ref> FORK_LANGLE %token<string> XHP_ATTR XHP_TEXT %token<string list> XHP_COLONID_DEF XHP_PERCENTID_DEF XHP_OPEN_TAG %token<string list option> XHP_CLOSE_TAG %left INCLUDE INCLUDE_ONCE REQUIRE REQUIRE_ONCE %left LOGICAL_OR %left LOGICAL_XOR %left LOGICAL_AND %right PRINT SUSPEND %right YIELD %right DOUBLE_ARROW LONG_DOUBLE_ARROW PIPE_ANGLE (*%right YIELD_FROM*) %left EQUAL PLUS_EQUAL MINUS_EQUAL MUL_EQUAL DIV_EQUAL CONCAT_EQUAL MOD_EQUAL AND_EQUAL OR_EQUAL XOR_EQUAL SHL_EQUAL SHR_EQUAL POW_EQUAL QUESTION_QUESTION_EQUAL %nonassoc pre_COLONCOLON %left COLONCOLON %nonassoc ARROW QUESTION_ARROW LBRACKET %nonassoc LPAREN LBRACE %left IS AS QUESTION (*SUPER*) QUESTION_QUESTION COLON (*%right COALESCE*) %left BOOLEAN_OR %left BOOLEAN_AND %left OR %left XOR %left AND %nonassoc IS_EQUAL IS_NOT_EQUAL IS_IDENTICAL SPACESHIP %right IS_NOT_IDENTICAL %right LANGLE %right RANGLE %nonassoc IS_SMALLER_OR_EQUAL IS_GREATER_OR_EQUAL %left SHL SHR_PREFIX %left PLUS MINUS CONCAT %left MUL DIV MOD %right BANG %nonassoc INSTANCEOF %right OBJECT_CAST BOOL_CAST UNSET_CAST INT_CAST DOUBLE_CAST STRING_CAST ARRAY_CAST TILDE INC DEC AT AWAIT (*ASYNC*) %right POW %nonassoc CLONE (*CONCURRENT*) %left pre_ELSE %left ELSEIF %left ELSE %token <string> LNUMBER (* integer number 42 (LNUMBER) *) %token <string> DNUMBER (* floating-point number 42.00 (DNUMBER) *) %token <string> IDENT (* identifier "foo" (IDENT) *) %token <string> VARIABLE (* variable "$foo" (VARIABLE) *) %token <string> INLINE_HTML %token <string> ENCAPSED_AND_WHITESPACE (* quoted-string and whitespace (ENCAPSED_AND_WHITESPACE) *) %token <string> CONSTANT_ENCAPSED_STRING (* quoted-string (CONSTANT_ENCAPSED_STRING) *) %token <string> VARNAME (* ${ varname } (VARNAME) *) %token <string> NUM_STRING (* number (NUM_STRING) *) %start<unit> start %start<unit> dummy %% (* Rules *) start: | top_statement* EOF { () } ; top_statement: | statement { () } | declaration { () } | HALT_COMPILER LPAREN RPAREN SEMICOLON { () } | NAMESPACE namespace_name SEMICOLON { () } | NAMESPACE namespace_name LBRACE top_statement* RBRACE { () } | NAMESPACE LBRACE top_statement* RBRACE { () } | USE NAMESPACE? mixed_group_use_declaration SEMICOLON { () } | USE NAMESPACE? use_modifier group_use_declaration SEMICOLON { () } | USE NAMESPACE? comma_list(use_declaration) SEMICOLON { () } | USE NAMESPACE? use_modifier comma_list(use_declaration) SEMICOLON { () } | CONST comma_list(constant_declaration) SEMICOLON { () } ; (* Identifiers *) identifier: | IDENT { () } | XHP_COLONID_DEF { () } | semi_reserved { () } ; name: | namespace_name { () } | NAMESPACE ANTISLASH namespace_name { () } | ANTISLASH namespace_name { () } | xhp_reserved { () } ; namespace_name: | IDENT { () } | XHP_COLONID_DEF { () } | namespace_name ANTISLASH IDENT { () } ; class_special_name: | STATIC { () } | SELF { () } | PARENT { () } | SHAPE { () } | ARRAY { () } ; unparametrized_class_name: | STATIC { () } | SELF { () } | PARENT { () } | name { () } ; class_name: | unparametrized_class_name { () } | unparametrized_class_name type_arguments { () } ; type_name: | CALLABLE { () } | SELF { () } | PARENT { () } | ARRAY { () } | name { () } ; (* Attributes *) attribute: | ANTISLASH attribute { () } | IDENT { () } | IDENT COLON attribute { () } | IDENT LPAREN comma_list_trailing(expr) RPAREN { () } ; attributes: | SHL nonempty_comma_list_trailing(attribute) SHR_PREFIX RANGLE { () } ; (* Declarations *) declaration: | attributes { () } | declare_function { () } | declare_class { () } | declare_trait { () } | declare_interface { () } | declare_enum { () } | declare_type { () } ; declare_function: | ASYNC declare_function { () } | COROUTINE declare_function { () } | FUNCTION AND? identifier [@doc_comment] type_parameters? LPAREN comma_list_trailing(parameter) RPAREN return_type? [@fn_flags] where_constraints? LBRACE statement_inner* RBRACE [@fn_flags] { () } ; where_constraints: | WHERE comma_list_trailing(where_constraint) { () } ; where_constraint: | type_expr EQUAL type_expr { () } | type_expr AS type_expr { () } | type_expr SUPER type_expr { () } ; declare_class: | class_modifier* CLASS identifier type_parameters? preceded(EXTENDS,class_name)? preceded(IMPLEMENTS, comma_list(class_name))? [@doc_comment] LBRACE statement_class* RBRACE { () } ; class_modifier: | ABSTRACT { () } | FINAL { () } ; declare_trait: | TRAIT identifier type_parameters? preceded(IMPLEMENTS, comma_list(class_name))? [@doc_comment] LBRACE statement_class* RBRACE { () } ; declare_interface: | INTERFACE identifier type_parameters? preceded(EXTENDS, comma_list(class_name))? [@doc_comment] LBRACE statement_class* RBRACE { () } ; declare_enum: | ENUM IDENT COLON type_expr preceded(AS, type_expr)? LBRACE lseparated_list_trailing(SEMICOLON, enum_member) RBRACE { () } ; enum_member: | identifier EQUAL expr { () } ; declare_type: | TYPE identifier type_parameters? preceded(AS, type_expr)? EQUAL type_expr SEMICOLON { () } | NEWTYPE identifier type_parameters? preceded(AS, type_expr)? EQUAL type_expr SEMICOLON { () } ; (* Statements *) statement: | LBRACE statement_inner* RBRACE { () } | statement_if { () } | WHILE LPAREN expr RPAREN statement { () } | DO statement WHILE LPAREN expr RPAREN SEMICOLON { () } | FOR LPAREN comma_list(expr) SEMICOLON comma_list(expr) SEMICOLON comma_list(expr) RPAREN statement { () } | SWITCH LPAREN expr RPAREN switch_body { () } | BREAK expr? SEMICOLON { () } | CONTINUE expr? SEMICOLON { () } | RETURN attributes? expr? SEMICOLON { () } | GLOBAL comma_list(expr_variable) SEMICOLON { () } | STATIC comma_list(initializable_variable) SEMICOLON { () } | ECHO comma_list(expr) SEMICOLON { () } | INLINE_HTML { () } | expr SEMICOLON { () } | UNSET LPAREN nonempty_comma_list_trailing(expr) RPAREN SEMICOLON { () } | FOREACH LPAREN expr ioption(AWAIT) FOREACH_AS foreach_variable RPAREN statement { () } | FOREACH LPAREN expr ioption(AWAIT) FOREACH_AS foreach_variable DOUBLE_ARROW foreach_variable RPAREN statement { () } | DECLARE LPAREN comma_list(constant_declaration) RPAREN statement { () } | SEMICOLON (* empty statement *) { () } | TRY LBRACE statement_inner* RBRACE try_catch* try_finally? { () } | THROW expr SEMICOLON { () } | GOTO IDENT SEMICOLON { () } | IDENT COLON { () } | AWAIT? USING LPAREN expr_pair_list RPAREN SEMICOLON { () } | AWAIT? USING LPAREN expr_pair_list RPAREN LBRACE statement_inner* RBRACE { () } | AWAIT? USING expr_without_parenthesis SEMICOLON { () } | CONCURRENT LBRACE statement_inner* RBRACE { () } ; statement_inner: | statement { () } | declare_function { () } | declare_class { () } | declare_trait { () } | declare_interface { () } | HALT_COMPILER LPAREN RPAREN SEMICOLON { () } ; initializable_variable: | VARIABLE preceded(EQUAL,expr)? [@doc_comment] { () } ; try_catch: | CATCH LPAREN separated_list(OR, name) VARIABLE RPAREN LBRACE statement_inner* RBRACE { () } ; try_finally: | FINALLY LBRACE statement_inner* RBRACE { () } ; foreach_variable: | expr { () } | AND expr_assignable { () } | LIST LPAREN expr_pair_list RPAREN { () } ; switch_body: | LBRACE SEMICOLON? switch_case* RBRACE { () } ; switch_case: | CASE expr switch_case_separator statement_inner* { () } | DEFAULT switch_case_separator statement_inner* { () } ; switch_case_separator: | COLON { () } | SEMICOLON { () } ; statement_if: | if_without_else %prec pre_ELSE { () } | if_without_else ELSE statement { () } ; if_without_else: | IF LPAREN expr RPAREN statement { () } | if_without_else ELSEIF LPAREN expr RPAREN statement { () } ; parameter: | attributes? parameter_visibility INOUT? type_expr? AND? parameter_core { () } ; parameter_visibility: | (* empty *) { () } | PUBLIC { () } | PRIVATE { () } | PROTECTED { () } ; parameter_core: | VARIABLE preceded(EQUAL, expr)? { () } | ELLIPSIS VARIABLE { () } | ELLIPSIS { () } ; statement_class: | USE comma_list(class_name) SEMICOLON { () } | USE comma_list(class_name) LBRACE trait_adaptation* RBRACE { () } | class_variable_modifiers type_expr? comma_list(initializable_variable) SEMICOLON { () } | class_member_modifier* CONST comma_list(constant_declaration) SEMICOLON { () } | class_member_modifier* COROUTINE? FUNCTION AND? identifier [@doc_comment] type_parameters? LPAREN comma_list_trailing(parameter) RPAREN return_type? where_constraints? [@fn_flags] class_method_body [@fn_flags] { () } | REQUIRE EXTENDS class_name SEMICOLON { () } | REQUIRE IMPLEMENTS class_name SEMICOLON { () } (* const type extension *) | class_member_modifier* CONST TYPE name preceded(AS, type_expr)? preceded(EQUAL, type_expr)? SEMICOLON { () } (* xhp extension *) | XHP_ATTRIBUTE comma_list_trailing(xhp_attribute_decl) SEMICOLON { () } | XHP_CHILDREN xhp_children_decl SEMICOLON { () } | XHP_CATEGORY comma_list_trailing(XHP_PERCENTID_DEF) SEMICOLON { () } ; class_method_body: | SEMICOLON (* abstract method *) { () } | LBRACE statement_inner* RBRACE { () } ; %inline class_variable_modifiers: | class_member_modifier+ { () } | VAR { () } ; class_member_modifier: | PUBLIC { () } | PROTECTED { () } | PRIVATE { () } | STATIC { () } | ABSTRACT { () } | FINAL { () } | ASYNC { () } | attributes { () } ; trait_adaptation: | trait_precedence SEMICOLON { () } | trait_method_reference AS trait_alias SEMICOLON { () } ; trait_precedence: | name COLONCOLON identifier INSTEADOF comma_list(name) { () } ; trait_alias: | IDENT { () } | reserved_non_modifiers { () } | class_member_modifier identifier? { () } ; trait_method_reference: | identifier { () } | name COLONCOLON identifier { () } ; constant_declaration: | type_expr identifier preceded(EQUAL,expr)? [@doc_comment] { () } | identifier preceded(EQUAL,expr)? [@doc_comment] { () } ; (* USE statements *) use_modifier: | FUNCTION { () } | CONST { () } | TYPE { () } ; group_use_declaration: | namespace_name ANTISLASH LBRACE nonempty_comma_list_trailing(unprefixed_use_declaration) RBRACE { () } | ANTISLASH namespace_name ANTISLASH LBRACE nonempty_comma_list_trailing(unprefixed_use_declaration) RBRACE { () } ; mixed_group_use_declaration: | namespace_name ANTISLASH LBRACE nonempty_comma_list_trailing(inline_use_declaration) RBRACE { () } | ANTISLASH namespace_name ANTISLASH LBRACE nonempty_comma_list_trailing(inline_use_declaration) RBRACE { () } ; inline_use_declaration: | unprefixed_use_declaration { () } | use_modifier unprefixed_use_declaration { () } ; unprefixed_use_declaration: | namespace_name { () } | namespace_name AS IDENT { () } ; use_declaration: | ioption(ANTISLASH) unprefixed_use_declaration { () } ; (* Type expressions *) type_expr: | QUESTION type_expr { () } | AT type_expr { () } | simple_type_expr %prec pre_COLONCOLON { () } ; simple_type_expr: | type_name { () } | simple_type_expr type_arguments { () } | simple_type_expr COLONCOLON type_name { () } | SHAPE LPAREN comma_list_trailing(shape_field) RPAREN { () } | LPAREN nonempty_comma_list_trailing(type_expr) RPAREN { () } | LPAREN COROUTINE? FUNCTION LPAREN comma_list_trailing(type_expr_parameter) RPAREN return_type RPAREN { () } (* ad-hoc tokens for (type) *) | INT_CAST { () } (* (int) *) | DOUBLE_CAST { () } (* (double) *) | STRING_CAST { () } (* (string) *) | OBJECT_CAST { () } (* (object) *) | BOOL_CAST { () } (* (bool) *) | ARRAY_CAST { () } (* (array/dict/...) *) ; %inline rangle: | RANGLE { () } | SHR_PREFIX { () } ; type_arguments: | FORK_LANGLE comma_list_trailing(type_expr) rangle { $1 := true } ; type_parameters: | FORK_LANGLE comma_list_trailing(type_parameter) rangle { $1 := true } ; type_variance: | (* empty *) { () } | PLUS { () } | MINUS { () } ; type_parameter: | type_variance type_name type_constraint { () } ; type_constraint: | (* empty *) { () } | type_constraint AS type_expr { () } | type_constraint SUPER type_expr { () } ; type_expr_parameter: | type_expr { () } | INOUT type_expr { () } | ELLIPSIS { () } | type_expr ELLIPSIS { () } ; return_type: | COLON type_expr { () } ; (* Expressions *) expr: | open_expr(expr) { () } | LPAREN expr RPAREN { () } | LPAREN attributes expr RPAREN { () } ; expr_without_parenthesis: | open_expr(expr_without_parenthesis) { () } ; open_expr(left): | LNUMBER { () } | DNUMBER { () } | LINE { () } | FILE { () } | DIR { () } | TRAIT_C { () } | METHOD_C { () } | FUNC_C { () } | NAMESPACE_C { () } | CLASS_C { () } | BANG expr { () } | AWAIT expr { () } | TILDE expr { () } | CLONE expr { () } | AT expr { () } | PRINT expr { () } | EXIT { () } | SUSPEND expr { () } | INCLUDE expr { () } | INCLUDE_ONCE expr { () } | REQUIRE expr { () } | REQUIRE_ONCE expr { () } | EMPTY LPAREN expr RPAREN { () } | EVAL LPAREN expr RPAREN { () } | ISSET LPAREN nonempty_comma_list_trailing(expr) RPAREN { () } | name type_arguments? { () } | left COLONCOLON property_name type_arguments? { () } | class_special_name COLONCOLON property_name type_arguments? { () } | left arrow property_name type_arguments? { () } | expr_assignable { () } | DOUBLEQUOTE encaps* DOUBLEQUOTE { () } | START_HEREDOC encaps* END_HEREDOC { () } | PLUS expr %prec INC { () } | MINUS expr %prec INC { () } | left expr_argument_list { () } | left BOOLEAN_AND expr { () } | left IS_IDENTICAL expr { () } | left IS_NOT_IDENTICAL expr { () } | left SPACESHIP expr { () } | left EQUAL attributes? expr { () } | left EQUAL AND expr { () } | left IS_EQUAL expr { () } | left IS_NOT_EQUAL expr { () } | left LANGLE expr { () } | left RANGLE expr { () } | left IS_SMALLER_OR_EQUAL expr { () } | left IS_GREATER_OR_EQUAL expr { () } | NEW expr_class_reference { () } | structured_literal { () } | INT_CAST expr { () } | DOUBLE_CAST expr { () } | STRING_CAST expr { () } | ARRAY_CAST expr { () } | OBJECT_CAST expr { () } | BOOL_CAST expr { () } | UNSET_CAST expr { () } | left BOOLEAN_OR expr { () } | left LOGICAL_OR expr { () } | left LOGICAL_AND expr { () } | left LOGICAL_XOR expr { () } | left OR expr { () } | left AND expr { () } | left XOR expr { () } | left CONCAT expr { () } | left PLUS expr { () } | left MINUS expr { () } | left MUL expr { () } | left POW expr { () } | left DIV expr { () } | left MOD expr { () } | left SHL expr { () } | left PIPE_ANGLE expr { () } | VARIABLE LONG_DOUBLE_ARROW lambda_body { () } | FORK LPAREN comma_list_trailing(parameter) RPAREN return_type? LONG_DOUBLE_ARROW lambda_body { () } | ASYNC LPAREN comma_list_trailing(parameter) RPAREN return_type? LONG_DOUBLE_ARROW lambda_body { () } | ASYNC VARIABLE LONG_DOUBLE_ARROW lambda_body { () } | ASYNC LBRACE statement_inner* RBRACE { () } | COROUTINE LPAREN comma_list_trailing(parameter) RPAREN return_type? LONG_DOUBLE_ARROW lambda_body { () } | COROUTINE VARIABLE LONG_DOUBLE_ARROW lambda_body { () } | COROUTINE LBRACE statement_inner* RBRACE { () } | left LBRACKET expr_pair_list RBRACKET { () } | left INC { () } | INC expr { () } | left DEC { () } | DEC expr { () } | left PLUS_EQUAL expr { () } | left MINUS_EQUAL expr { () } | left MUL_EQUAL expr { () } | left POW_EQUAL expr { () } | left DIV_EQUAL expr { () } | left CONCAT_EQUAL expr { () } | left MOD_EQUAL expr { () } | left AND_EQUAL expr { () } | left OR_EQUAL expr { () } | left XOR_EQUAL expr { () } | left SHL_EQUAL expr { () } | left SHR_EQUAL expr { () } | left QUESTION_QUESTION_EQUAL expr { () } | left SHR_PREFIX RANGLE expr { () } | left IS type_expr { () } | left AS type_expr { () } | left INSTANCEOF expr_class_reference { () } | left QUESTION AS type_expr { () } | left QUESTION COLON expr { () } | left QUESTION expr COLON expr { () } | left QUESTION_QUESTION expr { () } | LIST LPAREN expr_pair_list RPAREN EQUAL expr { () } | xhp_html { () } | function_expr { () } | YIELD { () } | YIELD expr { () } | YIELD expr DOUBLE_ARROW expr { () } | YIELD BREAK { () } (*| YIELD_FROM expr { () }*) ; function_expr: | STATIC function_expr | ASYNC function_expr | COROUTINE function_expr | FUNCTION AND? [@doc_comment] LPAREN comma_list_trailing(parameter) RPAREN return_type? lexical_vars? [@fn_flags] LBRACE statement_inner* RBRACE [@fn_flags] { () } ; lexical_vars: | USE LPAREN comma_list_trailing(preceded(AND?,VARIABLE)) RPAREN { () } ; %inline lambda_body: | expr { () } | LBRACE statement_inner* RBRACE { () } ; expr_argument_list: | LPAREN comma_list_trailing(expr_argument) RPAREN { () } | LBRACE expr_pair_list RBRACE { () } ; expr_argument: | expr { () } | AND expr { () } | INOUT expr { () } | ELLIPSIS expr { () } | attributes expr_argument { () } ; expr_pair_list: | nonempty_comma_list(expr_array_pair?) { $1 } ; expr_array_pair: | expr DOUBLE_ARROW expr { () } | expr { () } | expr DOUBLE_ARROW AND expr_assignable { () } | AND expr_assignable { () } | expr DOUBLE_ARROW LIST LPAREN expr_pair_list RPAREN { () } | LIST LPAREN expr_pair_list RPAREN { () } | ELLIPSIS expr { () } ; property_name: | identifier { () } | LBRACE expr RBRACE { () } | expr_variable { () } ; (*expr: | name { () } | class_name { () } | LBRACKET expr_pair_list RBRACKET EQUAL expr { () } | NEW expr_class_reference expr_argument_list? { () } | NEW CLASS expr_argument_list? class_desc { () } | expr COALESCE expr { () } | BACKQUOTE encaps* BACKQUOTE { () } | function_expr { () } | expr arrow property_name type_arguments expr_argument_list { () } | expr arrow property_name { () } | expr COLONCOLON property_name { () } | expr COLONCOLON property_name type_arguments expr_argument_list { () } | expr expr_argument_list { () } | expr LBRACKET expr_pair_list RBRACKET { () } | LPAREN expr RPAREN { () } ; simple_function_call: | name ioption(type_arguments) expr_argument_list { () } | class_name LBRACE expr_pair_list RBRACE { () } | class_name COLONCOLON member_name expr_argument_list { () } ; %inline lambda_body: | expr { () } | LBRACE statement_inner* RBRACE { () } | LBRACE statement_inner* RBRACE expr_argument_list { () } (* FIXME *) ; *) expr_class_reference: | class_name { () } | expr_variable { () } | LPAREN expr RPAREN { () } ; structured_literal: | ARRAY ioption(type_arguments) LPAREN expr_pair_list RPAREN { () } | SHAPE ioption(type_arguments) LPAREN expr_pair_list RPAREN { () } | LBRACKET expr_pair_list RBRACKET { () } | ARRAY ioption(type_arguments) LBRACKET expr_pair_list RBRACKET { () } | CONSTANT_ENCAPSED_STRING { () } ; expr_assignable: | expr_variable { () } (*| name ioption(type_arguments) expr_argument_list { () } | class_name LBRACE expr_pair_list RBRACE { () } | expr_assignable expr_argument_list { () } | LPAREN expr RPAREN expr_argument_list { () } | structured_literal expr_argument_list { () } ;*) expr_variable: | VARIABLE { () } | DOLLAR LBRACE expr RBRACE { () } | DOLLAR expr_variable { () } | DOLLARDOLLAR { () } ; (* member_name: | identifier ioption(type_arguments) { () } | LBRACE expr RBRACE { () } | expr_variable { () } ; property_name: | identifier { () } | LBRACE expr RBRACE { () } | expr_variable { () } | XHP_COLONID_DEF { () } ; *) encaps: | ENCAPSED_AND_WHITESPACE { () } | encaps_var { () } ; encaps_var: | VARIABLE { () } | VARIABLE LBRACKET encaps_var_offset RBRACKET { () } | VARIABLE arrow IDENT { () } | DOLLAR_OPEN_CURLY_BRACES expr RBRACE { () } | DOLLAR_OPEN_CURLY_BRACES VARNAME RBRACE { () } | DOLLAR_OPEN_CURLY_BRACES VARNAME LBRACKET expr RBRACKET RBRACE { () } | CURLY_OPEN expr RBRACE { () } ; encaps_var_offset: | IDENT { () } | NUM_STRING { () } | MINUS NUM_STRING { () } | VARIABLE { () } ; (* XHP *) xhp_html: | XHP_OPEN_TAG xhp_attribute* XHP_GT xhp_child* XHP_CLOSE_TAG { () } | XHP_OPEN_TAG xhp_attribute* XHP_SLASH_GT { () } ; xhp_child: | XHP_TEXT { () } | xhp_html { () } | LBRACE expr RBRACE { () } ; xhp_attribute: | XHP_ATTR EQUAL xhp_attribute_value { () } | LBRACE ELLIPSIS? expr RBRACE { () } ; xhp_attribute_value: | DOUBLEQUOTE encaps* DOUBLEQUOTE { () } | LBRACE expr RBRACE { () } | XHP_ATTR { () } ; xhp_attribute_decl: | XHP_COLONID_DEF { () } | xhp_attribute_decl_type xhp_attr_name preceded(EQUAL, expr)? XHP_REQUIRED? { () } ; xhp_attribute_decl_type: | ENUM LBRACE comma_list_trailing(expr) RBRACE | VAR | type_expr { () } ; xhp_attr_name: | identifier | xhp_attr_name MINUS identifier | xhp_attr_name COLON identifier { () } ; xhp_children_decl: | XHP_ANY | EMPTY | xhp_children_paren_expr { () } ; xhp_children_paren_expr: | LPAREN xhp_children_decl_exprs RPAREN | LPAREN xhp_children_decl_exprs RPAREN MUL | LPAREN xhp_children_decl_exprs RPAREN QUESTION | LPAREN xhp_children_decl_exprs RPAREN PLUS { () } ; xhp_children_decl_expr: | xhp_children_paren_expr { () } | xhp_children_decl_tag { () } | xhp_children_decl_tag MUL { () } | xhp_children_decl_tag QUESTION { () } | xhp_children_decl_tag PLUS { () } ; xhp_children_decl_exprs: | xhp_children_decl_expr { () } | xhp_children_decl_exprs COMMA xhp_children_decl_expr { () } | xhp_children_decl_exprs OR xhp_children_decl_expr { () } ; xhp_children_decl_tag: | XHP_ANY { () } | XHP_PCDATA { () } | XHP_COLONID_DEF { () } | XHP_PERCENTID_DEF { () } | IDENT { () } ; (* Shapes *) shape_field: | QUESTION? expr DOUBLE_ARROW type_expr { () } | ELLIPSIS { () } ; %inline arrow: | ARROW { () } | QUESTION_ARROW { () } ; (* Using keywords as identifiers *) xhp_reserved: | XHP_ATTRIBUTE { "attribute" } | XHP_CATEGORY { "category" } | XHP_CHILDREN { "children" } | XHP_ANY { "any" } | XHP_PCDATA { "pcdata" } ; reserved_non_modifiers: | xhp_reserved { $1 } | INCLUDE { "include" } | INCLUDE_ONCE { "include_once" } | EVAL { "eval" } | REQUIRE { "require" } | REQUIRE_ONCE { "require_once" } | LOGICAL_OR { "or" } | LOGICAL_XOR { "xor" } | LOGICAL_AND { "and" } | INSTANCEOF { "instanceof" } | INOUT { "inout" } | IS { "is" } | NEW { "new" } | CLONE { "clone" } | EXIT { "exit" } | IF { "if" } | ELSEIF { "elseif" } | ELSE { "else" } | ENDIF { "endif" } | ECHO { "echo" } | DO { "do" } | WHILE { "while" } | FOR { "for" } | FOREACH { "foreach" } | DECLARE { "declare" } | AS { "as" } | TRY { "try" } | CATCH { "catch" } | FINALLY { "finally" } | THROW { "throw" } | USE { "use" } | INSTEADOF { "insteadof" } | GLOBAL { "global" } | VAR { "var" } | UNSET { "unset" } | ISSET { "isset" } | EMPTY { "empty" } | CONTINUE { "continue" } | GOTO { "goto" } | FUNCTION { "function" } | CONST { "const" } | RETURN { "return" } | PRINT { "print" } | YIELD { "yield" } | LIST { "list" } | SWITCH { "switch" } | CASE { "case" } | DEFAULT { "default" } | BREAK { "break" } | ARRAY { "array" } | CALLABLE { "callable" } | EXTENDS { "extends" } | IMPLEMENTS { "implements" } | NAMESPACE { "namespace" } | TRAIT { "trait" } | INTERFACE { "interface" } | CLASS { "class" } | TYPE { "type" } | ENUM { "enum" } | LINE { "__LINE__" } | FILE { "__FILE__" } | DIR { "__DIR__" } | CLASS_C { "__CLASS__" } | TRAIT_C { "__TRAIT__" } | METHOD_C { "__METHOD__" } | FUNC_C { "__FUNCTION__" } | NAMESPACE_C { "__NAMESPACE__" } | PARENT { "parent" } | SELF { "self" } | WHERE { "where" } | SHAPE { "shape" } | USING { "using" } | COROUTINE { "coroutine" } | SUSPEND { "suspend" } | NEWTYPE { "newtype" } ; semi_reserved: | reserved_non_modifiers { $1 } | STATIC { "STATIC" } | ABSTRACT { "ABSTRACT" } | FINAL { "FINAL" } | PRIVATE { "PRIVATE" } | PROTECTED { "PROTECTED" } | PUBLIC { "PUBLIC" } | ASYNC { "async" } | SUPER { "super" } ; (* To silence some warnings *) dummy: | (* Tokens that are expected to be unused *) COMMENT DOC_COMMENT NEWLINE SPACES UNKNOWN OPEN_TAG OPEN_TAG_WITH_ECHO CLOSE_TAG CLOSE_TAG_OF_ECHO { () } | (* Tokens that are expected to be used in final grammar *) AND_EQUAL BACKQUOTE BANG BOOLEAN_AND BOOLEAN_OR COALESCE CONCAT CONCAT_EQUAL CURLY_OPEN DEC DIV DIV_EQUAL DNUMBER DOLLAR_OPEN_CURLY_BRACES DOUBLEQUOTE ENCAPSED_AND_WHITESPACE END_HEREDOC FORK INC IS_EQUAL IS_GREATER_OR_EQUAL IS_IDENTICAL IS_NOT_EQUAL IS_SMALLER_OR_EQUAL LANGLE LONG_DOUBLE_ARROW MINUS_EQUAL MOD MOD_EQUAL MUL MUL_EQUAL NUM_STRING OR_EQUAL PIPE_ANGLE PLUS_EQUAL POW POW_EQUAL QUESTION_QUESTION QUESTION_QUESTION_EQUAL SHL_EQUAL SHR_EQUAL SPACESHIP START_HEREDOC TILDE UNSET_CAST VARNAME XHP_ATTR XHP_CLOSE_TAG XHP_GT XHP_OPEN_TAG XHP_PCDATA XHP_PERCENTID_DEF XHP_REQUIRED XHP_SLASH_GT XHP_TEXT XOR XOR_EQUAL YIELD_FROM { () } ; (* Generic definitions *) %inline lnonempty_list(X): | X llist_aux(X) { $1 :: List.rev $2 } ; %inline llist(X): | llist_aux(X) { List.rev $1 } ; llist_aux(X): | (* empty *) { [] } | llist_aux(X) X { $2 :: $1 } ; %inline lseparated_list(sep, X): | (* empty *) { [] } | lseparated_nonempty_list(sep, X) { $1 } ; %inline lseparated_list_trailing(sep, X): | (* empty *) { [] } | lseparated_nonempty_list(sep, X) sep? { $1 } ; %inline lseparated_nonempty_list(sep, X): | lseparated_nonempty_list_aux(sep, X) { List.rev $1 }; ; lseparated_nonempty_list_aux(sep, X): | X { [$1] } | lseparated_nonempty_list_aux(sep, X) sep X { $3 :: $1 } ; %inline comma_list(X): | lseparated_list(COMMA, X) { $1 } ; %inline comma_list_trailing(X): | lseparated_list_trailing(COMMA, X) { $1 } ; %inline nonempty_comma_list(X): | lseparated_nonempty_list(COMMA, X) { $1 } ; %inline nonempty_comma_list_trailing(X): | lseparated_nonempty_list(COMMA, X) COMMA? { $1 } ; (* Some interesting conflicts: * * T::K < U > x * is ((T::K) < U) > x * or T::K<U> x; * * bla ? ($x) : foo * is a ternary * or the beginning of lambda binding $x and returning a value of type foo * * foreach (<expr> as $x * does as belong to foreach * or as is a sub-typing constraint on <expr> and ... ? * * <expr> as <type>->foo * should be parsed as (<expr> as <type>)->foo * * what about: * <expr> as <type>::bar ? * both: <expr> as (<type>::bar) * and: (<expr> as <type>)::bar * make sense. The former is more intuitive taken alone, but it is the opposite * interpretation of the first one. *)
OCaml
hhvm/hphp/hack/doc/pharser/phparser_driver.ml
(* * Copyright (c) 2020, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) let token_to_string (tok : Phparser.token) = match tok with | Phparser.YIELD_FROM -> "YIELD_FROM" | Phparser.YIELD -> "YIELD" | Phparser.XOR_EQUAL -> "XOR_EQUAL" | Phparser.XOR -> "XOR" | Phparser.XHP_TEXT _ -> "XHP_TEXT _" | Phparser.XHP_SLASH_GT -> "XHP_SLASH_GT" | Phparser.XHP_REQUIRED -> "XHP_REQUIRED" | Phparser.XHP_PERCENTID_DEF _ -> "XHP_PERCENTID_DEF _" | Phparser.XHP_PCDATA -> "XHP_PCDATA" | Phparser.XHP_OPEN_TAG _ -> "XHP_OPEN_TAG _" | Phparser.XHP_GT -> "XHP_GT" | Phparser.XHP_COLONID_DEF _ -> "XHP_COLONID_DEF _" | Phparser.XHP_CLOSE_TAG _ -> "XHP_CLOSE_TAG _" | Phparser.XHP_CHILDREN -> "XHP_CHILDREN" | Phparser.XHP_CATEGORY -> "XHP_CATEGORY" | Phparser.XHP_ATTRIBUTE -> "XHP_ATTRIBUTE" | Phparser.XHP_ATTR _ -> "XHP_ATTR _" | Phparser.XHP_ANY -> "XHP_ANY" | Phparser.WHILE -> "WHILE" | Phparser.VARNAME _ -> "VARNAME _" | Phparser.VARIABLE _ -> "VARIABLE _" | Phparser.VAR -> "VAR" | Phparser.USE -> "USE" | Phparser.UNSET_CAST -> "UNSET_CAST" | Phparser.UNSET -> "UNSET" | Phparser.UNKNOWN -> "UNKNOWN" | Phparser.TYPE -> "TYPE" | Phparser.TRY -> "TRY" | Phparser.TRAIT_C -> "TRAIT_C" | Phparser.TRAIT -> "TRAIT" | Phparser.TILDE -> "TILDE" | Phparser.THROW -> "THROW" | Phparser.SWITCH -> "SWITCH" | Phparser.STRING_CAST -> "STRING_CAST" | Phparser.STATIC -> "STATIC" | Phparser.START_HEREDOC -> "START_HEREDOC" | Phparser.SPACESHIP -> "SPACESHIP" | Phparser.SPACES -> "SPACES" | Phparser.SHR_EQUAL -> "SHR_EQUAL" | Phparser.SHR_PREFIX -> "SHR_PREFIX" | Phparser.SHL_EQUAL -> "SHL_EQUAL" | Phparser.SHL -> "SHL" | Phparser.SHAPE -> "SHAPE" | Phparser.SEMICOLON -> "SEMICOLON" | Phparser.SELF -> "SELF" | Phparser.RPAREN -> "RPAREN" | Phparser.RETURN -> "RETURN" | Phparser.REQUIRE_ONCE -> "REQUIRE_ONCE" | Phparser.REQUIRE -> "REQUIRE" | Phparser.RBRACKET -> "RBRACKET" | Phparser.RBRACE -> "RBRACE" | Phparser.RANGLE -> "RANGLE" | Phparser.QUESTION_ARROW -> "QUESTION_ARROW" | Phparser.QUESTION -> "QUESTION" | Phparser.PUBLIC -> "PUBLIC" | Phparser.PROTECTED -> "PROTECTED" | Phparser.PRIVATE -> "PRIVATE" | Phparser.PRINT -> "PRINT" | Phparser.POW_EQUAL -> "POW_EQUAL" | Phparser.POW -> "POW" | Phparser.PLUS_EQUAL -> "PLUS_EQUAL" | Phparser.PLUS -> "PLUS" | Phparser.PIPE_ANGLE -> "PIPE_ANGLE" | Phparser.PARENT -> "PARENT" | Phparser.OR_EQUAL -> "OR_EQUAL" | Phparser.OR -> "OR" | Phparser.OPEN_TAG_WITH_ECHO -> "OPEN_TAG_WITH_ECHO" | Phparser.OPEN_TAG -> "OPEN_TAG" | Phparser.OBJECT_CAST -> "OBJECT_CAST" | Phparser.NUM_STRING _ -> "NUM_STRING _" | Phparser.NEWTYPE -> "NEWTYPE" | Phparser.NEWLINE -> "NEWLINE" | Phparser.NEW -> "NEW" | Phparser.NAMESPACE_C -> "NAMESPACE_C" | Phparser.NAMESPACE -> "NAMESPACE" | Phparser.MUL_EQUAL -> "MUL_EQUAL" | Phparser.MUL -> "MUL" | Phparser.MOD_EQUAL -> "MOD_EQUAL" | Phparser.MOD -> "MOD" | Phparser.MINUS_EQUAL -> "MINUS_EQUAL" | Phparser.MINUS -> "MINUS" | Phparser.METHOD_C -> "METHOD_C" | Phparser.LPAREN -> "LPAREN" | Phparser.LONG_DOUBLE_ARROW -> "LONG_DOUBLE_ARROW" | Phparser.LOGICAL_XOR -> "LOGICAL_XOR" | Phparser.LOGICAL_OR -> "LOGICAL_OR" | Phparser.LOGICAL_AND -> "LOGICAL_AND" | Phparser.LNUMBER _ -> "LNUMBER _" | Phparser.LIST -> "LIST" | Phparser.LINE -> "LINE" | Phparser.LBRACKET -> "LBRACKET" | Phparser.LBRACE -> "LBRACE" | Phparser.LANGLE -> "LANGLE" | Phparser.IS_SMALLER_OR_EQUAL -> "IS_SMALLER_OR_EQUAL" | Phparser.IS_NOT_IDENTICAL -> "IS_NOT_IDENTICAL" | Phparser.IS_NOT_EQUAL -> "IS_NOT_EQUAL" | Phparser.IS_IDENTICAL -> "IS_IDENTICAL" | Phparser.IS_GREATER_OR_EQUAL -> "IS_GREATER_OR_EQUAL" | Phparser.IS_EQUAL -> "IS_EQUAL" | Phparser.ISSET -> "ISSET" | Phparser.INT_CAST -> "INT_CAST" | Phparser.INTERFACE -> "INTERFACE" | Phparser.INSTEADOF -> "INSTEADOF" | Phparser.INSTANCEOF -> "INSTANCEOF" | Phparser.INLINE_HTML _ -> "INLINE_HTML _" | Phparser.INCLUDE_ONCE -> "INCLUDE_ONCE" | Phparser.INCLUDE -> "INCLUDE" | Phparser.INC -> "INC" | Phparser.IMPLEMENTS -> "IMPLEMENTS" | Phparser.IF -> "IF" | Phparser.IDENT s -> Printf.sprintf "IDENT %S" s | Phparser.HALT_COMPILER -> "HALT_COMPILER" | Phparser.GOTO -> "GOTO" | Phparser.GLOBAL -> "GLOBAL" | Phparser.FUNC_C -> "FUNC_C" | Phparser.FUNCTION -> "FUNCTION" | Phparser.FOREACH -> "FOREACH" | Phparser.FOR -> "FOR" | Phparser.FINALLY -> "FINALLY" | Phparser.FINAL -> "FINAL" | Phparser.FILE -> "FILE" | Phparser.EXTENDS -> "EXTENDS" | Phparser.EXIT -> "EXIT" | Phparser.EVAL -> "EVAL" | Phparser.EQUAL -> "EQUAL" | Phparser.EOF -> "EOF" | Phparser.ENUM -> "ENUM" | Phparser.END_HEREDOC -> "END_HEREDOC" | Phparser.ENDIF -> "ENDIF" | Phparser.ENCAPSED_AND_WHITESPACE _ -> "ENCAPSED_AND_WHITESPACE _" | Phparser.EMPTY -> "EMPTY" | Phparser.ELSEIF -> "ELSEIF" | Phparser.ELSE -> "ELSE" | Phparser.ELLIPSIS -> "ELLIPSIS" | Phparser.ECHO -> "ECHO" | Phparser.DOUBLE_CAST -> "DOUBLE_CAST" | Phparser.DOUBLE_ARROW -> "DOUBLE_ARROW" | Phparser.DOUBLEQUOTE -> "DOUBLEQUOTE" | Phparser.DOLLAR_OPEN_CURLY_BRACES -> "DOLLAR_OPEN_CURLY_BRACES" | Phparser.DOLLARDOLLAR -> "DOLLARDOLLAR" | Phparser.DOLLAR -> "DOLLAR" | Phparser.DOC_COMMENT -> "DOC_COMMENT" | Phparser.DO -> "DO" | Phparser.DNUMBER _ -> "DNUMBER _" | Phparser.DIV_EQUAL -> "DIV_EQUAL" | Phparser.DIV -> "DIV" | Phparser.DIR -> "DIR" | Phparser.DEFAULT -> "DEFAULT" | Phparser.DECLARE -> "DECLARE" | Phparser.DEC -> "DEC" | Phparser.CURLY_OPEN -> "CURLY_OPEN" | Phparser.CONTINUE -> "CONTINUE" | Phparser.CONSTANT_ENCAPSED_STRING _ -> "CONSTANT_ENCAPSED_STRING _" | Phparser.CONST -> "CONST" | Phparser.CONCAT_EQUAL -> "CONCAT_EQUAL" | Phparser.CONCAT -> "CONCAT" | Phparser.COMMENT -> "COMMENT" | Phparser.COMMA -> "COMMA" | Phparser.COLONCOLON -> "COLONCOLON" | Phparser.COLON -> "COLON" | Phparser.COALESCE -> "COALESCE" | Phparser.CLOSE_TAG_OF_ECHO -> "CLOSE_TAG_OF_ECHO" | Phparser.CLOSE_TAG -> "CLOSE_TAG" | Phparser.CLONE -> "CLONE" | Phparser.CLASS_C -> "CLASS_C" | Phparser.CLASS -> "CLASS" | Phparser.CATCH -> "CATCH" | Phparser.CASE -> "CASE" | Phparser.CALLABLE -> "CALLABLE" | Phparser.BREAK -> "BREAK" | Phparser.BOOL_CAST -> "BOOL_CAST" | Phparser.BOOLEAN_OR -> "BOOLEAN_OR" | Phparser.BOOLEAN_AND -> "BOOLEAN_AND" | Phparser.BANG -> "BANG" | Phparser.BACKQUOTE -> "BACKQUOTE" | Phparser.AWAIT -> "AWAIT" | Phparser.AT -> "AT" | Phparser.ASYNC -> "ASYNC" | Phparser.AS -> "AS" | Phparser.ARROW -> "ARROW" | Phparser.ARRAY_CAST -> "ARRAY_CAST" | Phparser.ARRAY -> "ARRAY" | Phparser.ANTISLASH -> "ANTISLASH" | Phparser.AND_EQUAL -> "AND_EQUAL" | Phparser.AND -> "AND" | Phparser.ABSTRACT -> "ABSTRACT" | Phparser.QUESTION_QUESTION -> "QUESTION_QUESTION" | Phparser.QUESTION_QUESTION_EQUAL -> "QUESTION_QUESTION_EQUAL" | Phparser.IS -> "IS" | Phparser.INOUT -> "INOUT" | Phparser.USING -> "USING" | Phparser.CONCURRENT -> "CONCURRENT" | Phparser.FORK -> "FORK" | Phparser.WHERE -> "WHERE" | Phparser.SUPER -> "SUPER" | Phparser.SUSPEND -> "SUSPEND" | Phparser.FOREACH_AS -> "FOREACH_AS" | Phparser.COROUTINE -> "COROUTINE" | Phparser.FORK_LANGLE _ -> "FORK_LANGLE" let token_to_string tok = try token_to_string tok with _ -> "FIX token_to_string" module I = Phparser.MenhirInterpreter let rec normalize = function | (I.Shifting _ | I.AboutToReduce _) as cp -> normalize (I.resume cp) | cp -> cp type t = | Normal of { state: unit I.checkpoint; rest: t; } | Fork of { state: unit I.checkpoint; tokens: (Phparser.token * Lexing.position * Lexing.position) list; branch_point: (bool ref * unit I.checkpoint); rest: t; } | Done exception Accept let verbose = ref false let rec concat a b = match a with | Normal r -> Normal {r with rest = concat r.rest b} | Fork r -> Fork {r with rest = concat r.rest b} | Done -> b let concat a = function | Done -> a | b -> concat a b let prepare_after_fork tokens = let rec aux acc = function | [] -> assert false | [Phparser.FORK_LANGLE reduced, startp, endp] -> assert (not !reduced); (Phparser.LANGLE, startp, endp) :: acc | token :: tokens -> aux (token :: acc) tokens in aux [] tokens let rec progress token = function | Done -> Done | Normal { state; rest } -> begin match normalize (I.offer state token) with | I.Accepted () -> raise Accept | I.HandlingError _ | I.Rejected -> progress token rest | (I.InputNeeded _) as cp -> Normal { state = cp; rest = progress token rest } end | Fork { state; tokens; branch_point; rest } -> begin match normalize (I.offer state token) with | I.Accepted () -> raise Accept | I.Rejected -> assert false | I.HandlingError env -> let reduced, state' = branch_point in if !reduced then progress token rest else let resumed = List.fold_left (fun a (tok, _, _ as b) -> match a with | Done -> (*print_endline "replaying failed!";*) Done | a -> (*print_endline ("replaying: " ^ token_to_string tok);*) progress b a) (Normal { state = state'; rest = Done }) (prepare_after_fork (token :: tokens)) in concat resumed (progress token rest) | (I.InputNeeded _) as cp -> let reduced, _ = branch_point in if !reduced then Normal { state = cp; rest = progress token rest } else Fork { state = cp; tokens = token :: tokens; branch_point; rest = progress token rest } end let rec fork reduced = function | Normal { state; rest } | Fork { state; rest; branch_point = ({contents = true}, _); _ } -> Fork { state; tokens = []; branch_point = (reduced, state); rest = fork reduced rest } | Fork r -> Fork {r with rest = fork reduced r.rest } | Done -> Done let progress token parser = let parser = match token with | Phparser.LPAREN, startp, _ -> concat parser (progress (Phparser.FORK, startp, startp) parser) | _ -> parser in match token with | Phparser.AS, startp, endp -> begin match progress (Phparser.FOREACH_AS, startp, endp) parser with | Done -> progress token parser | result -> result end | Phparser.LANGLE, startp, endp -> let reduced = ref false in let parser = fork reduced parser in progress (Phparser.FORK_LANGLE reduced, startp, endp) parser | Phparser.CLOSE_TAG, _, _ -> parser | _ -> progress token parser let state_number = function | I.InputNeeded env -> let rec pop = function | _, None | 0, _ -> [] | n, Some env -> let x = I.current_state_number env in x :: pop (n - 1, I.pop env) in pop (-1, Some env) | _ -> assert false let rec take n = function | x :: xs when n > 0 -> x :: take (n - 1) xs | _ -> [] let dump_parser = function | Normal r -> let state = state_number r.state in "Normal " ^ String.concat "," (List.map string_of_int state) ^ ":\n\n" ^ String.concat "\n" (List.map Describe.describe_state (take 2 state)) | Fork r -> let state = state_number r.state in "Fork " ^ String.concat "," (List.map string_of_int state) ^ ":\n\n" ^ String.concat "\n" (List.map Describe.describe_state (take 2 state)) | Done -> assert false let rec get_parsers = function | Normal r as parser -> parser :: get_parsers r.rest | Fork r as parser -> parser :: get_parsers r.rest | Done -> [] let parse ~verbose token lexbuf = let rec aux parser = let tok = token lexbuf in let tok = (tok, lexbuf.Lexing.lex_start_p, lexbuf.Lexing.lex_curr_p) in match progress tok parser with | Done -> (* No continuation: parsing failed, FIXME: produce error message *) if verbose then ( let parsers = get_parsers parser in print_endline ("Status: " ^ String.concat "; " (List.map dump_parser parsers)); ); raise Phparser.Error | parser' -> aux parser' in try aux (Normal { state = Phparser.Incremental.start lexbuf.Lexing.lex_start_p; rest = Done }) with | Accept -> ()
OCaml
hhvm/hphp/hack/doc/pharser/process.ml
(* * Copyright (c) 2020, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open MenhirSdk module G = Cmly_read.Read(struct let filename = Sys.argv.(1) end) (*let rec list_filter_map f = function | [] -> [] | x :: xs -> match f x with | None -> list_filter_map f xs | Some x' -> x' :: list_filter_map f xs let reductions = G.Lr1.tabulate (fun lr1 -> lr1 |> G.Lr1.reductions |> List.map snd |> List.flatten |> List.sort_uniq compare ) let items offset lr1 = list_filter_map (fun prod -> let rhs = G.Production.rhs prod in let dot = Array.length rhs - offset in if dot < 0 then None else Some (prod, dot) ) (reductions lr1) let rec all_reductions offset lr1 = G.Lr1. if offset < 5 then List.flatten @@ reductions offset lr1 :: List.map (fun (_sym, lr1) -> all_reductions (offset + 1) lr1) (G.Lr1.transitions lr1) else []*) let () = Printf.printf "let describe_state = function\n"; G.Lr1.iter begin fun lr1 -> Printf.printf " | %d -> %S\n" (G.Lr1.to_int lr1) (Format.asprintf "%a" G.Print.itemset (G.Lr0.items (G.Lr1.lr0 lr1))) end; Printf.printf " | _ -> assert false\n"
hhvm/hphp/hack/doc/type_system/.gitignore
facebook/hack_typing.pdf facebook/hack_typing.tex hack_typing.ml hack_typing.out hack_typing.pdf hack_typing.tex hack_typing.v
OCaml
hhvm/hphp/hack/doc/type_system/flowtypes.ml
(* flowtypes.ml experimental toy model of a flow-sensitive typechecker *) type mytype = | Tint | Tbool | Tstring let mytype_tostring t = match t with | Tint -> "int" | Tbool -> "bool" | Tstring -> "string" (* this represents a disjunction of primitive types *) module TypeSet = Set.Make (struct type t = mytype let compare = compare end) type dtype = | D of TypeSet.t | Top let bottype = D TypeSet.empty let onetype t = D (TypeSet.singleton t) let booltype = onetype Tbool let inttype = onetype Tint let stringtype = onetype Tstring let rec tltostring tl = match tl with | [] -> "F" | [t] -> mytype_tostring t | t :: rest -> mytype_tostring t ^ "|" ^ tltostring rest let dtype_tostring dt = match dt with | Top -> "T" | D ts -> tltostring (TypeSet.elements ts) let entails dt1 dt2 = match (dt2, dt1) with | (Top, _) -> true | (_, Top) -> false | (D ds2, D ds1) -> TypeSet.for_all (fun t1 -> TypeSet.mem t1 ds2) ds1 let equaltype dt1 dt2 = entails dt1 dt2 && entails dt2 dt1 let typejoin dt1 dt2 = match (dt1, dt2) with | (Top, _) -> Top | (_, Top) -> Top | (D ds1, D ds2) -> D (TypeSet.union ds1 ds2) type vname = string module VMap = Map.Make (struct type t = vname let compare = compare end) (* Used for Gamma *) type env = | M of dtype VMap.t | Botenv (* maps every variable to top, so classifies any environment *) let topenv = M VMap.empty (* an environment type mapping any variable to bottype is Botenv *) let normenv e = match e with | Botenv -> Botenv | M e -> if VMap.exists (fun v t -> entails t bottype) e then Botenv else M e (* this is an over-approximation of the union of e1 and e2 *) let envjoin e1 e2 = match (normenv e1, normenv e2) with | (Botenv, e2) -> e2 | (e1, Botenv) -> e1 | (M e1, M e2) -> M (VMap.union (fun v ty1 ty2 -> Some (typejoin ty1 ty2)) e1 e2) let envupdate e v t = match e with | Botenv -> Botenv | M e -> normenv (M (VMap.add v t e)) let env_tostring e = match e with | Botenv -> "Botenv" | M e -> "<" ^ VMap.fold (fun v t s -> v ^ ":" ^ dtype_tostring t ^ "," ^ s) e "" ^ ">" (* record type for deltas *) type delta = { skip: env; break: env; continue: env; } let delta_tostring d = "{skip=" ^ env_tostring d.skip ^ " break=" ^ env_tostring d.break ^ " continue=" ^ env_tostring d.continue ^ "}" let lookup v e = match normenv e with | Botenv -> bottype | M e -> begin match VMap.find_opt v e with | None -> Top | Some dt -> dt end (* have to be careful about tops for missing vars so do something simple but a bit expensive *) let enventails e1 e2 = match (normenv e1, normenv e2) with | (Botenv, _) -> true | (_, Botenv) -> false | (M e1m, M e2m) -> VMap.for_all (fun v t1 -> entails t1 (lookup v e2)) e1m && VMap.for_all (fun v t2 -> entails (lookup v e1) t2) e2m type exp = | Ev of vname | Etrue | Efalse | En of int | Es of string | Eplus of exp * exp | Egreater of exp * exp type com = | Cskip | Cseq of com * com | Cass of vname * exp | Cif of exp * com * com | Cloop of com | Cbreak | Ccontinue | Cifistype of vname * dtype * com * com let rec infer_exp e t = match t with | Ev s -> lookup s e | Etrue | Efalse -> booltype | En _ -> inttype | Es _ -> stringtype | Eplus (t1, t2) -> let ty1 = infer_exp e t1 in let ty2 = infer_exp e t2 in if entails ty1 inttype && entails ty2 inttype then inttype else failwith "plus expression" | Egreater (t1, t2) -> let ty1 = infer_exp e t1 in let ty2 = infer_exp e t2 in if entails ty1 inttype && entails ty2 inttype then booltype else failwith "greater expression" (* approximate difference of types *) let tyminus dt1 dt2 = match dt2 with | Top -> bottype | D ds2 -> begin match dt1 with | Top -> Top (* hopelessly weak, but will do for now *) | D ds1 -> D (TypeSet.diff ds1 ds2) end let tyintersect dt1 dt2 = match (dt1, dt2) with | (Top, _) -> dt2 | (_, Top) -> dt1 (* TODO: This is NOT generally right - relies on primitive types being disjoint *) | (D ds1, D ds2) -> D (TypeSet.inter ds1 ds2) let rec infer_com e c = match c with | Cskip -> { skip = e; break = Botenv; continue = Botenv } | Cseq (c1, c2) -> let { skip = envs1; break = envb1; continue = envc1 } = infer_com e c1 in let { skip = envs2; break = envb2; continue = envc2 } = infer_com envs1 c2 in { skip = envs2; break = envjoin envb1 envb2; continue = envjoin envc1 envc2; } | Cass (v, ex) -> let ety = infer_exp e ex in { skip = envupdate e v ety; break = Botenv; continue = Botenv } | Cif (ex, c1, c2) -> if entails (infer_exp e ex) booltype then let { skip = envs1; break = envb1; continue = envc1 } = infer_com e c1 in let { skip = envs2; break = envb2; continue = envc2 } = infer_com e c2 in { skip = envjoin envs1 envs2; break = envjoin envb1 envb2; continue = envjoin envc1 envc2; } else failwith "non bool in conditional" | Cloop c1 -> let { skip = envs; break = envb; continue = envc } = infer_com e c1 in if enventails envs e && enventails envc e then { skip = envb; break = Botenv; continue = Botenv } else infer_com (envjoin (envjoin e envs) envc) c | Cbreak -> { skip = Botenv; break = e; continue = Botenv } | Ccontinue -> { skip = Botenv; break = Botenv; continue = e } | Cifistype (v, t, c1, c2) -> let vty = lookup v e in let yesvty = tyintersect vty t in let novty = tyminus vty t in let { skip = envs1; break = envb1; continue = envc1 } = infer_com (envupdate e v yesvty) c1 in let { skip = envs2; break = envb2; continue = envc2 } = infer_com (envupdate e v novty) c2 in { skip = envjoin envs1 envs2; break = envjoin envb1 envb2; continue = envjoin envc1 envc2; } (* slightly feeble testing *) let teste e = dtype_tostring (infer_exp topenv e) let testc c = delta_tostring (infer_com topenv c) let e1 = Eplus (En 1, En 2) (* skip=<x:int> *) let c1 = Cass ("x", e1) (* skip=<y:int,x:bool> *) let c2 = Cseq (c1, Cseq (Cass ("y", Ev "x"), Cass ("x", Etrue))) (* skip=<x:int> *) let c3 = Cloop (Cseq (c1, Cbreak)) (* skip=<x:bool> *) let c4 = Cseq (c1, Cifistype ("x", inttype, Cass ("x", Etrue), Cass ("y", En 6))) (* this one ends up with skip:=<x:bool,y:int> *) let c5 = Cseq ( Cif (Etrue, Cass ("x", Etrue), Cass ("x", En 4)), Cifistype ("x", inttype, Cass ("x", Etrue), Cass ("y", En 6)) ) (* thing that @catg observed was wrong before the thing after the break is type incorrect, but we shouldn't care and get skip=<x:bool> *) let c6 = Cloop (Cseq (Cseq (Cass ("x", Etrue), Cbreak), Cass ("y", Eplus (Ev "x", En 1)))) (* example needing fixpoints, due to @ajk $x = 0; $y = 1; $z = 2; for ($i = 0; $i < 3; $i++) { $x = $y; $y = $z; $z = true; } yields: {skip=<z:int|bool,y:int|bool,x:int|bool,i:int,> break=Botenv continue=Botenv} *) let thebody = Cif ( Egreater (En 4, Ev "i"), Cbreak, Cseq ( Cseq (Cseq (Cass ("x", Ev "y"), Cass ("y", Ev "z")), Cass ("z", Etrue)), Cass ("i", Eplus (Ev "i", En 1)) ) ) let theloop = Cloop thebody let theprequel = Cseq ( Cseq (Cseq (Cass ("x", En 0), Cass ("y", En 1)), Cass ("z", En 2)), Cass ("i", En 0) ) let c7 = Cseq (theprequel, theloop)
hhvm/hphp/hack/doc/type_system/hack_typing.ott
%% GOTCHAS with LateX output: %% In free-standing {{ com }} blocks you must use math-mode around [[]] embed {{ coq Require Import String. }} embed {{ tex-preamble \usepackage{longtable} \renewcommand{\ottgrammartabular}[1]{\begin{longtable}{llclllllp{6.5cm} }#1\end{longtable} } \renewcommand{\ottmetavartabular}[1]{\begin{longtable}{ll}#1\end{longtable} } \renewcommand{\ottcom}[1]{\parbox[t]{6.5cm}{#1} } \renewcommand{\arraystretch}{1.2} \newcommand{\kwd}[1]{\mathtt{#1} } }} embed {{ tex-wrap-pre \documentclass[11pt,a4paper]{memoir} \title{Hack type system} % standard packages, some relied upon by the generated Ott code \usepackage{amsmath,amssymb} \usepackage[left=1cm, right=1cm, top=2cm, bottom=1cm]{geometry} \usepackage{ifthen} \usepackage{alltt} \usepackage{color} \usepackage[bookmarks,bookmarksopen,bookmarksdepth=2]{hyperref} }} embed {{ tex-wrap-post \begin{document}{ % Workaround for Latex issue with newlines (note tildes) \ottmetavars~\\[0pt] \ottgrammar~\\[5.0mm] \ottdefnss } \end{document} }} metavar string_literal ::= {{ coq string }} {{ com string literal }} {{ lex Alphanum }} {{ ocaml string }} metavar integer_literal ::= {{ coq nat }} {{ com integer literal }} {{ lex numeral }} {{ ocaml int }} metavar sfn ::= {{ coq string }} {{ com shape field name }} {{ lex Alphanum }} {{ ocaml string }} metavar f {{ ocaml field_id }} ::= {{ coq string }} {{ com field identifier }} {{ ocaml string }} metavar x {{ ocaml lvar_id }} ::= {{ coq string }} {{ com local variable identifier }} {{ ocaml string }} metavar typeid ::= {{ lex Alphanum }} {{ coq string }} {{ com identifier }} {{ ocaml string }} metavar userid ::= {{ lex alphanum }} {{ coq string }} {{ com identifier }} {{ ocaml string }} metavar T {{ ocaml typaram_id }} ::= {{ coq string }} {{ com type parameter, different from other identifiers for simplicity }} {{ ocaml string }} indexvar i, j, m, n ::= {{ coq nat }} {{ com natural number indices }} {{ ocaml int}} grammar %% Symbolic names for types %% We need to know about three special interfaces for special subtyping %% rules for array types b :: 'bool_' ::= {{ com booleans }} | True :: :: True | False :: :: False N, C, I :: 'typename_' ::= {{ com named types }} {{ coq string }} | ` typeid ` :: :: User {{ com user type name }} {{ tex {\kwd{[[typeid]]} } }} {{ coq "[[typeid]]"%string }} id :: 'id_' ::= {{ com identifiers }} % Just do this so we can get underscores displayed properly! | is_bool :: :: is_bool {{ tex {\kwd{is\_bool} } }} | is_int :: :: is_int {{ tex {\kwd{is\_int} } }} | is_float :: :: is_float {{ tex {\kwd{is\_float} } }} | is_string :: :: is_string {{ tex {\kwd{is\_string} } }} | is_vec :: :: is_vec {{ tex {\kwd{is\_vec} } }} | is_dict :: :: is_dict {{ tex {\kwd{is\_dict} } }} | is_keyset :: :: is_keyset {{ tex {\kwd{is\_keyset} } }} | is_array :: :: is_array {{ tex {\kwd{is\_array} } }} | is_null :: :: is_null {{ tex {\kwd{is\_null} } }} | ` userid ` :: :: user {{ com user identifier }} {{ tex {\kwd{[[userid]]} } }} %% Keys {{ com \subhead{Syntax of keys} }} sk {{ ocaml Shape_key }} :: 'SF' ::= {{ com shape keys }} | sfn :: :: requiredkey {{ com required key }} | ? sfn :: :: optionalkey {{ com optional key }} %% Types {{ com \subhead{Syntax of types} }} {{ com Implicit below is a well-formedness conditions for shapes stating that all shape field names must be disjoint. In particular, the unset shape field names, which are listed on the right of $[[\]]$ in the open shape syntax, must not occur as shape field names of the shape field types on the left of $[[\]]$. }} t, u {{ ocaml ty }} :: 'ty_' ::= {{ com syntax of types }} | nothing :: :: nothing {{ com bottom type }} | mixed :: :: mixed {{ com top type }} | nonnull :: :: nonnull {{ com nonnull type }} | null :: :: null {{ com null type }} | int :: :: int {{ com integer }} | float :: :: float {{ com floating point }} | num :: :: num {{ com number }} | string :: :: string {{ com string }} | arraykey :: :: arraykey {{ com array key }} | bool :: :: bool {{ com boolean type }} | void :: :: void {{ com void return type }} | dynamic :: :: dynamic {{ com dynamic type }} | T :: :: typeparam {{ com generic type parameter }} | N inst :: :: classish {{ com possibly-instantiated named type }} | # N inst :: :: exact {{ com exact named type }} | this :: :: this {{ com this type }} | ? t :: :: option {{ com nullable }} | t1 '|' t2 :: :: union {{ com union type }} | t1 & t2 :: :: intersection {{ com intersection type }} | ( t ) :: S :: paren {{ coq [[t]] }} {{ com parentheses }} {{ ocaml [[t]] }} | ( t1 , .... , tn ) :: :: tuple {{ com tuple }} | shape ( sft1 , .. , sftn ) :: :: shape {{ com closed shape (all field names are assumed to be disjoint) }} | shape ( sft1 , .. , sftn , vardots \ sfn1 , .. , sfnm ) :: :: openshape {{ com open shape (all field names are assumed to be disjoint) }} | function ( t1 , .. , tn ) : t :: :: function {{ com function type }} | function ( t1 , .. , tn , t0 vardots ) : t :: :: variadicfunction {{ com variadic function type }} | vec < t > :: :: vec {{ com vector }} | dict < t1 , t2 > :: :: dict {{ com dictionary }} | keyset < t > :: :: keyset {{ com key set }} | { t1 / T1 , .. , tn / Tn } t :: M :: Tsub {{ com substitution (meta-operation) }} {{ coq [[t]] }} % TODO {{ ocaml [[t]] }} % TODO | { u / this } t :: M :: Tsub_this {{ com substitution (meta-operation) for this }} {{ coq [[t]] }} % TODO {{ ocaml [[t]] }} % TODO sft :: '' ::= {{ com shape field type }} | sk => t :: :: shape_field_type {{ com shape field type }} inst :: '' ::= {{ com vector of type arguments }} | :: :: emptyinst {{ com no type arguments }} | < t1 , .. , tn > :: :: mkinst {{ com some type arguments }} U {{ ocaml updatel }} {{ tex \Upsilon }} :: U_ ::= {{ com list of context updates }} | x1 := t1 , .. , xn := tn :: :: update_list | U1 [ U2 ] :: :: update_override {{ com update list $[[U1]]$ overridden or extended with $[[U2]]$ }} Gitem :: 'lenv_' ::= {{ com entry in locals environment }} | x : t :: :: lvar {{ com local typing }} | t <: t' :: :: sub {{ com subtype assumption }} | t ~> t' :: :: coerce {{ com coercion assumption }} G {{ ocaml lenv }} {{ coq lenv }} {{ tex \Gamma }} :: 'lenv_' ::= {{ com subtype assumptions and typing of locals }} | { Gitem1 , .. , Gitemn } :: :: env | G , Gitem :: :: add {{ com extend }} | G [ U ] :: :: update {{ com update environment $[[G]]$ with assignments $[[U]]$ }} Kitem :: 'kenv_' ::= {{ com entry in continuation environment }} | contkind : G :: :: make {{ com continuation typing }} %% WORKAROUND: can't inline this into definition of Cont_update %% as Coq output does not include correct specialized list Kupdate :: 'kenv_' ::= {{ com update to continuation environment }} | contkind := G :: :: delta %% Model updates and extensions as bits of syntax rather than operations K {{ ocaml cont_env }} {{ tex \Delta }} :: Cont_ ::= {{ com typing of continuations }} | { Kitem1 , .. , Kitemn } :: :: env {{ com explicit continuation environment }} | K , Kitem :: :: add | K [ Kupdate1 , .. , Kupdaten ] :: :: update %%% Type parameter declarations var {{ ocaml variance }} :: '' ::= {{ com variance annotation }} | + :: :: covariant {{ com covariant }} | - :: :: contravariant {{ com contravariant }} | :: :: invariant {{ com invariant }} typaram :: '' ::= {{ com generic type parameter declaration }} | var T constraint :: :: typaram_make {{ com generic type parameter with variance }} typarams :: 'typarams_' ::= {{ com generic type parameters declaration }} | :: :: empty {{ com no type parameters }} | < typaram1 , .. , typaramn > :: :: nonempty {{ com some type parameters }} constraint :: 'constraint_' ::= {{ com type parameter constraint }} | as t :: :: as {{ com as constraint }} | super t :: :: super {{ com super constraint }} | :: :: none {{ com no constraint }} %%% Class extends and implements declarations cextends :: 'class_' ::= {{ com class extends declaration }} | extends t :: :: extends {{ com extends a class }} | :: :: noextends {{ com does not extend a class }} cimpls :: 'class_' ::= {{ com class implements declaration }} | implements t1 , ... , tn :: :: implements {{ com implements some interfaces }} | :: :: noimplements {{ com does not implement any interfaces }} %%% Interface extends declaration iextends :: 'interface_' ::= {{ com interface extends declaration }} | extends t1 , ... , tn :: :: extends {{ com extends some interfaces }} | :: :: noextends {{ com does not extend any interfaces }} %%% Enum or newtype as declaration asdecl :: 'type_' ::= {{ com as declaration }} | as t :: :: as {{ com has supertype }} | :: :: noas {{ com has no supertype }} %%% Kind of continuations, used in typing rules contkind :: 'Cont_' ::= {{ com Continuation kinds }} | break :: :: Break {{ com break from loop or switch }} | continue :: :: Continue {{ com continue to head of loop }} | catch :: :: Catch {{ com exception handler }} | return :: :: Return {{ com return }} | skip :: :: Skip {{ com next statement }} %%% Elements of class definitions member :: 'member_' ::= {{ com property or method definition }} | t $ x ; :: :: instance_property {{ com instance property }} {{ tex [[t]]\;\$[[x]]; }} | static t $ x ; :: :: static_property {{ com static property }} {{ tex [[static]]\;[[t]]\;\$[[x]]; }} | function id F block :: :: instance_method {{ com instance method }} | static function id F block :: :: static_method {{ com static method }} members :: 'members_' ::= {{ com non-constructor members of a class }} | member1 .. membern :: :: list classbody :: 'class_' ::= {{ com class body }} | { constructor members } :: :: body constructor :: 'constructor_' ::= {{ com constructor definition }} | function __construct funparams block :: :: constructor {{ com constructor }} %%% Top level declaration decl :: 'decl_' ::= {{ com top level declarations }} | class C typarams cextends cimpls classbody :: :: classdef {{ com class declaration }} | interface I typarams iextends :: :: interfacedef {{ com interface declaration }} | enum N : t asdecl :: :: enumdef | type N < T1 , .. , Tn > = t :: :: alias {{ com type alias }} | newtype N < T1 , .. , Tn > asdecl = t :: :: opaque {{ com opaque type definition }} | function id F block :: :: function {{ com top-level function definition }} lvar :: '' ::= {{ com local variable }} | $ x :: :: lvar_id {{ com local variable }} {{ tex { \$ [[x]] } }} e {{ ocaml expr }} :: 'e_' ::= {{ com expressions }} | null :: :: null {{ com null value }} | true :: :: true {{ com true value }} | false :: :: false {{ com false value }} | string_literal :: :: string {{ com string literal }} | integer_literal :: :: int {{ com integer literal }} | sfn :: :: sfn {{ com shape field name }} | i :: :: tuple_index {{ com tuple index }} | $this :: :: this {{ com this value }} {{ tex \mathtt{\$this} }} | lvar :: :: lvar {{ com local variable }} | id :: :: id {{ com top-level function }} | e -> x :: :: obj_get {{ com property access }} | e -> id ( args ) :: :: method_call {{ com method call }} | e ?-> x :: :: nullsafe_obj_get {{ com nullsafe property access }} | e ?-> id ( args ) :: :: nullsafe_method_call {{ com nullsafe method call }} | N '::' x :: :: class_get {{ com static property access }} | N '::' id ( args ) :: :: static_method_call {{ com static method call }} | e1 [ e2 ] :: :: array_get {{ com array indexing }} | e [] :: :: array_append {{ com array appending }} | tuple ( e1 , ... , en ) :: :: tuple {{ com tuple }} | list ( e1 , ... , en ) :: :: list {{ com list destructuring }} | e ( args ) :: :: call {{ com function or method call }} | ( e ) :: S :: parens {{ ocaml [[e]] }} {{ coq [[e]] }} | e1 bop e2 :: :: binop {{ com binary operation }} | uop e :: :: unop {{ com unary operation }} | e1 ? e2 : e3 :: :: eif {{ com conditional expression }} | e1 ?? e2 :: :: nullCoalesce {{ com null coalesce }} | new C ( args ) :: :: new {{ com object creation }} | lamparams lamreturn ==> lambody :: :: lambda {{ com lambda }} | await e :: :: await {{ com await expression }} args {{ ocaml args }} :: 'args_' ::= {{ com argument list }} | e1 , .. , en :: :: args {{ com arguments }} | e1 , .. , en , vardots e :: :: args_splat {{ com arguments with splat }} isvariadic :: 'is_variadic_' ::= {{ com optional variadic }} | :: :: no {{ com not variadic parameter }} | vardots :: :: yes {{ com variadic parameter }} funparam :: 'function_' ::= {{ com function or method parameter }} | t isvariadic lvar :: :: param funparams :: 'function_' ::= {{ com function or method parameters }} | ( funparam1 , .. , funparamn ) :: :: params {{ com list }} F {{ ocaml funsig }} :: 'function_' ::= {{ com function or method signature }} | funparams : t :: :: sig lamparam :: 'lambda_param_' ::= {{ com lambda parameter }} | isvariadic lvar :: :: notype {{ com without type }} | t isvariadic lvar :: :: type {{ com with type }} lamreturn :: 'lambda_return_' ::= {{ com lambda return }} | :: :: notype {{ com without type }} | : t :: :: type {{ com with type }} lambody :: 'lambda_body_' ::= {{ com lambda body }} | e :: :: expr {{ com expression }} | block :: :: block {{ com block }} lamparams :: 'lambda_' ::= {{ com lambda parameters }} | ( lamparam1 , .. , lamparamn ) :: :: params {{ com list }} ae {{ ocaml as_expr }} :: 'ae_' ::= {{ com as expressions }} | e :: :: value {{ com as value }} | e1 => e2 :: :: key_value {{ com as key-value pair }} s {{ ocaml st }} :: 's_' ::= {{ com statements }} | break ; :: :: break {{ com break out of loop or switch }} | continue ; :: :: continue {{ com continue in loop }} | throw e ; :: :: throw {{ com throw exception }} | return e ; :: :: return {{ com return from function }} | return ; :: :: return_void {{ com return from void function }} | ; :: :: skip {{ com empty statement }} | if ( e ) s1 else s2 :: :: if {{ com conditional statement }} | if ( e ) s :: :: if_then {{ com one-armed conditional }} | do s while ( e ) :: :: do {{ com do loop }} | while ( e ) s :: :: while {{ com while loop }} | for ( e1 ; e2 ; e3 ) s :: :: for {{ com for loop }} | foreach ( e as ae ) s :: :: foreach {{ com foreach loop }} | try s1 cc1 .. ccn finally s2 :: :: try {{ com try catch }} | switch (e) cases :: :: switch {{ com switch }} | e ; :: :: expr {{ com expression as statement }} | block :: :: block {{ com block as statement }} block {{ ocaml block }} :: 'block_' ::= {{ com block }} | { s1 .. sn } :: :: statements {{ com sequence of statements }} cc {{ ocaml catch }}:: 'cc_' ::= {{ com catch clause }} | catch ( C lvar ) s :: :: catch {{ com catch clause }} uop :: '' ::= {{ com unary operations }} | '~' :: :: Utild {{ com tilde }} {{ tex \kwd{\sim} }} | ! :: :: Unot {{ com not }} {{ tex \kwd{!} }} | + :: :: Uplus {{ com unary plus }} {{ tex \kwd{+} }} | - :: :: Uminus {{ com unary negation }} {{ tex \kwd{-} }} | (++) :: :: Uincr {{ com increment }} {{ tex \kwd{++} }} | (--) :: :: Udecr {{ com decrement }} {{ tex \kwd{--} }} bop :: '' ::= {{ com binary operations }} | + :: :: Plus {{ com addition }} {{ tex \kwd{+} }} | - :: :: Minus {{ com subtraction }} {{ tex \kwd{-} }} | * :: :: Star {{ com multiplication }} {{ tex \kwd{*} }} | / :: :: Slash {{ com division }} {{ tex \kwd{/} }} | == :: :: Eqeq {{ com equality }} {{ tex \kwd{==} }} | === :: :: Eqeqeq {{ com equality }} {{ tex \kwd{===} }} | ** :: :: Starstar {{ com exponentiation }} {{ tex \kwd{**} }} | != :: :: Diff {{ com dis-equality }} {{ tex \kwd{!=} }} | !== :: :: Diff2 {{ com dis-equality }} {{ tex \kwd{!==} }} | && :: :: Ampamp {{ com logical and }} {{ tex \kwd{\&\&} }} | '||' :: :: Barbar {{ com logical or }} {{ tex \kwd{||} }} | xor :: :: LogXor {{ com logical xor }} {{ tex \kwd{xor} }} | < :: :: Lt {{ com less than }} {{ tex \kwd{<} }} | <= :: :: Lte {{ com less than or equal }} {{ tex \kwd{<=} }} | > :: :: Gt {{ com greater than }} {{ tex \kwd{>} }} | >= :: :: Gte {{ com greater than or equal }} {{ tex \kwd{>=} }} | '.' :: :: Dot {{ com string concatenation }} {{ tex \kwd{.} }} | & :: :: Amp {{ com bitwise and }} {{ tex \kwd{\&} }} | '|' :: :: Bar {{ com bitwise or }} {{ tex \kwd{|} }} | << :: :: Ltlt {{ com shift left }} {{ tex \kwd{<<} }} | >> :: :: Gtgt {{ com shift right }} {{ tex \kwd{>>} }} | % :: :: Percent {{ com remainder }} {{ tex \kwd{\%} }} | ^ :: :: Xor {{ com bitwise xor }} %{{ tex \kwd{\^{} } }} | <=> :: :: Cmp {{ com spaceship comparison operator }} {{ tex \kwd{<=>} }} | = :: :: Eq {{ com assignment }} % Generic terminals with pretty TeX terminals :: terminals_ ::= | --> :: :: longrightarrow {{ tex \longrightarrow }} | -> :: :: rightarrow {{ tex \rightarrow }} | ?-> :: :: qrightarrow {{ tex ?\rightarrow}} | => :: :: Rightarrow {{ tex \Rightarrow }} | |-> :: :: mapsto {{ tex \mapsto }} | |- :: :: vdash {{ tex \vdash }} | <:: :: :: derives {{ tex <:: }} | < :: :: langle {{ tex \langle }} | > :: :: rangle {{ tex \rangle }} | :> :: :: supertype {{ tex :> }} | == :: :: eqtype {{ tex \equiv }} | ~> :: :: leadsto {{ tex \leadsto }} | ~ :: :: tilde {{ tex \sim }} | truthy :: :: truthy {{ tex \Downarrow }} | vardots :: :: variadicrest {{ tex \underline{\mathtt{...} } }} | __construct :: :: construct {{ tex \mathtt{\_\_construct} }} | \ :: :: setminus {{ tex \setminus }} formula :: 'formula_' ::= | judgement :: :: judgement | formula1 .. formulan :: :: dots | not formula :: M :: not {{ tex \neg [[formula]] }} {{ ocaml not [[ formula ]] }} {{ coq ~ [[ formula ]] }} | ( formula ) :: M :: brackets {{ tex ([[formula]]\!) }} {{ ocaml [[ formula ]] }} {{ coq [[formula]] }} | formula \/ formula' :: M :: or {{ tex [[formula]] \vee [[formula']] }} {{ ocaml [[formula]] && [[formula']] }} {{ coq [[formula]] /\ [[formula']] }} | formula /\ formula' :: M :: and {{ tex [[formula]] \wedge [[formula']] }} {{ ocaml [[formula]] || [[formula']] }} {{ coq [[formula]] \/ [[formula']] }} | local N :: :: local {{ com definition of $[[N]]$ is in the current file }} {{ tex \textit{local}([[N]]) }} {{ ocaml true }} % TODO {{ coq True }} % TODO | decl :: :: decl {{ coq True }} % TODO | T freshfor G :: M :: fresh {{ tex [[T]] \textrm{ fresh for } [[G]] }} {{ ocaml true }} % TODO {{ coq True }} % TODO defns TySys :: '' ::= defn t1 <:: t2 :: :: derives ::'derives_' {{ com $[[t1]]$ extends or implements $[[t2]]$ }} by {{ com \section*{Inheritance and implementation} }} {{ com \addcontentsline{toc}{section}{Inheritance and implementation} }} {{ com We define a separate relation (`derives from') for the transitive closure of extending a class or implementing an interface. Subtyping adds the substitution of the \texttt{this} type, which is not handled by the derives relation. \\\\ }} class C < var1 T1 constraint1, .. , varn Tn constraintn > extends t cimpls classbody ------------------------------------------------------ :: extends C < t1 , .. , tn > <:: { t1 / T1 , .. , tn / Tn } t class C < var1 T1 constraint1, .. , varn Tn constraintn > cextends implements u1 , .. , um classbody -------------------------------------------------------------------- :: implements C < t1 , .. , tn > <:: { t1 / T1 , .. , tn / Tn } ui t1 <:: t2 t2 <:: t3 ------------------- :: trans t1 <:: t3 {{ com \section*{Subtyping} }} {{ com \addcontentsline{toc}{section}{Subtyping} }} defn G |- t1 <: t2 :: :: tysub ::'sub_' {{ com $[[t1]]$ is a subtype of $[[t2]]$ under assumptions $[[G]]$ }} by {{ com \subsection*{General subtyping rules} }} {{ com Subtyping is reflexive and transitive. This is always true of subtyping; but it takes some care to ensure that the algorithm for checking subtypes actually ensures it. }} ------------ :: refl G |- t <: t G |- t1 <: t2 G |- t2 <: t3 ------------------- :: trans G |- t1 <: t3 {{ com \subsection{Using subtype assumptions} }} -------------------------- :: assume G , t <: t' |- t <: t' {{ com \subsection{Union} }} {{ com Hack has union types, though at the moment there is no syntax for them. In general, they are n-ary, but it's easier to present in binary form. }} {{ com Any type can be widened to a larger union. (Unions are upper bounds.) }} ------------------ :: union_upper1 G |- t1 <: t1 | t2 ------------------ :: union_upper2 G |- t2 <: t1 | t2 {{ com The next rule states that union is the \emph{least} upper bound. }} G |- t1 <: t G |- t2 <: t ------------------ :: union_least G |- t1 | t2 <: t {{ com Other properties are consequences of these rules. For example, commutativity follows by applying all three. }} {{ com \subsection{Intersection} }} {{ com Hack has intersection types, though at the moment there is no syntax for them. In general, they are n-ary, but it's easier to present in binary form. }} {{ com Any intersection type can be widened to one of its components. (Intersections are lower bounds.) }} ------------------ :: intersect_lower1 G |- t1 & t2 <: t1 ------------------ :: intersect_lower2 G |- t1 & t2 <: t1 {{ com The next rule states that intersection is the \emph{greatest} lower bound. }} G |- t <: t1 G |- t <: t2 ------------------ :: intersect_greatest G |- t <: t1 & t2 {{ com Other properties are consequences of these rules. For example, commutativity follows by applying all three. }} {{ com Intersection distributes over union. One direction of this is the rule below; the other direction is a consequence of other rules. Distributivity of union over intersection is also derivable. }} -------------------------------------------- :: intersect_distr_union G |- t1 & (t2 | t3) <: (t1 & t2) | (t1 & t3) {{ com Intersection interacts with function types according to the following rules. }} -------------------------------------------------------------------------------------------------------------- :: intersect_distr_function G |- (function(t1 , .. , tn) : t) & (function(u1 , .. , un) : u) <: function(t1|u1 , .. , tn | un) : (t & u) -------------------------------------------------------------------------------------------------------------- :: intersect_distr_variadic_function G |- (function(t1 , .. , tn, t vardots) : t) & (function(u1 , .. , un , u vardots) : u) <: function(t1|u1 , .. , tn | un , t0|u0 vardots) : (t & u) {{ com \subsection{Nullable types} }} {{ com Hack has nullable (or option) types. For any type $[[t]]$, $[[? t]]$ is syntactic sugar for $[[t | null]]$. The following properties of nullable types are corollaries of this definition and the typing rules for unions. }} {{ com Any type can be \emph{widened} to include null. }} ------------- :: nullable_widen G |- t <: ? t {{ com The nullable type behaves covariantly. }} G |- t1 <: t2 ----------------- :: nullable_sub G |- ? t1 <: ? t2 {{ com In Caml and Haskell the \texttt{option} and \texttt{Maybe} type constructors can be nested. But in Hack, there is a single \texttt{null} value, and so applying the nullable type constructor $[[? t]]$ more than once makes no difference: it is idempotent. Note that the converse rule to the one below is a consequence of the two rules above. }} ----------------- :: nullable_cancel G |- ? ? t <: ? t {{ com \subsection{Primitives} }} {{ com Hack has a top type. }} ---------------- :: as_mixed G |- t <: mixed {{ com There is a special type $[[num]]$ that behaves exactly as if defined to be $[[int | float]]$. }} --------------- :: int_as_num G |- int <: num ------------------ :: float_as_num G |- float <: num ------------------------ :: num_as_int_or_float G |- num <: int | float {{ com There is a special type $[[arraykey]]$ which includes all key types, that is, $[[int]]$, $[[string]]$ and any enumeration type. }} --------------------- :: int_as_arraykey G |- int <: arraykey ------------------------ :: string_as_arraykey G |- string <: arraykey enum N : t asdecl ---------------------- :: enum_as_arraykey G |- N <: arraykey {{ com \subsection{Nothing} }} {{ com Hack has a bottom type. }} ------------------ :: nothing_bottom G |- nothing <: t {{ com Note that this makes $[[nothing]]$ a neutral element with respect to union. }} {{ com \subsection{Nonnull} }} {{ com Primitive types except $[[mixed]]$ and $[[void]]$ are subtypes of $[[nonnull]]$: }} ------------------- :: int_as_nonnull G |- int <: nonnull --------------------- :: float_as_nonnull G |- float <: nonnull ---------------------- :: string_as_nonnull G |- string <: nonnull ------------------------ :: arraykey_as_nonnull G |- arraykey <: nonnull -------------------- :: bool_as_nonnull G |- bool <: nonnull {{ com We don't need a separate rule for $[[num]]$ because $[[ G |- num <: nonnull ]]$ follows from \ottdrulename{sub\_int\_as\_nonnull}, \ottdrulename{sub\_float\_as\_nonnull}, \ottdrulename{sub\_num\_as\_int\_or\_float}, and \ottdrulename{sub\_union\_least}. }} {{ com User-defined types are subtypes of $[[nonnull]]$: }} class C<var1 T1 constraint1, .., varn Tn constraintn> cextends cimpls classbody ------------------------------------------------------------------------------- :: class_as_nonnull G |- C<t1, .., tn> <: nonnull interface I<var1 T1 constraint1, .., varn Tn constraintn> iextends ------------------------------------------------------------------ :: interface_as_nonnull G |- I<t1, .., tn> <: nonnull {{ com Rules \ottdrulename{sub\_arraykey\_as\_nonnull}, \ottdrulename{sub\_enum\_as\_arraykey}, and \ottdrulename{sub\_trans} imply that any enum type $N$ is a subtype of $[[nonnull]]$. }} {{ com A type alias is a subtype of $[[nonnull]]$ if and only if the type it stands for is a subtype of $[[nonnull]]$. This follows from \ottdrulename{sub\_alias\_as} (``if'') and \ottdrulename{sub\_alias\_super} (``only if''), and transitivity of subtyping. }} {{ com An opaque type is a subtype of $[[nonnull]]$ if it is constrained by a type that is a subtype of $[[nonnull]]$. This follows from \ottdrulename{sub\_opaque\_as} and transitivity of subtyping. In the file in which the type is defined it is a subtype of $[[nonnull]]$ if and only if the wrapped type is a subtype of $[[nonnull]]$. This follows from \ottdrulename{sub\_opaque\_local\_as} (``if'') and \ottdrulename{sub\_opaque\_local\_super} (``only if''), and transitivity of subtyping. }} {{ com Because legacy arrays are $\kwd{KeyedContainer}$ it follows by transitivity of subtyping and \ottdrulename{sub\_class\_as\_nonnull} that arrays are subtypes of $[[nonnull]]$. Do we need separate rules for Hack arrays, shapes, and tuples, or should we make them $\kwd{KeyedContainer}$ too? }} {{ com Function types are subtypes of $[[nonnull]]$: }} ---------------------------------------- :: function_as_nonnull G |- function(t1, .., tn) : t <: nonnull {{ com Finally, $[[mixed]]$ is a subtype of $[[nonnull | null]]$: }} ---------------------------- :: mixed_as_nullable_nonnull G |- mixed <: nonnull | null {{ com Together with \ottdrulename{sub\_as\_mixed} this implies $[[G |- mixed == nonnull | null]]$. }} {{ com \subsection{Tuples} }} {{ com Tuples are covariant }} G |- t1 <: u1 .. G |- tn <: un ---------------------------- :: tuple_co G |- ( t1,..,tn ) <: (u1,..,un) {{ com A tuple collapses if any of its types is the bottom type $[[nothing]]$ }} ------------------------------------------------------ :: tuple_nothing G |- (t1 , .. , tm , nothing , t1', .. , tn') <: nothing {{ com \subsection{Hack arrays} }} {{ com Vecs, dicts, and keysets are covariant in all parameters }} G |- t <: u ----------------- :: vec_co G |- vec<t> <: vec<u> G |- t1 <: u1 G |- t2 <: u2 --------------------------- :: dict_co G |- dict <t1,t2> <: dict<u1,u2> G |- t <: u ---------------------- :: keyset_co G |- keyset<t> <: keyset<u> {{ com Vecs, dicts, and keysets are KeyedContainer }} --------------------------------- :: vec_as_KeyedContainer G |- vec<t> <: `KeyedContainer`<int, t> --------------------------------------- :: dict_as_KeyedContainer G |- dict<t1, t2> <: `KeyedContainer`<t1, t2> ---------------------------------- :: keyset_as_KeyedContainer G |- keyset<t> <: `KeyedContainer`<t, t> {{ com \subsection{Functions} }} {{ com Function types are somewhat complicated: there are multiple parameters, zero or one results, and an additional type for \emph{variadic} parameters. }} {{ com Arguments behave contravariantly, results behave covariantly. }} G |- u1 <: t1 .. G |- un <: tn G |- t <: u ---------------------------------------------------- :: function G |- function ( t1,..,tn ):t <: function ( u1, .., un ):u {{ com Variadic against non-variadic: a function that accepts \emph{at least} $n$ parameters also accepts $n+m$ parameters. }} G |- u1 <: t1 .. G |- un <: tn G |- u1' <: t' .. G |- um' <: t' G |- t <: u --------------------------------------------------------------------------------------------- :: function_variadic1 G |- function (t1 , .. , tn , t' vardots ) : t <: function ( u1 , .. , un , u1', .. , um') : u {{ com Variadic against variadic: a function that accepts at least $n$ parameters also accepts at least $n+m$ parameters. }} G |- u1 <: t1 .. G |- un <: tn G |- u1' <: t' .. G |- um' <: t' G |- u' <: t' G |- t <: u --------------------------------------------------------------------------------------------------------- :: function_variadic2 G |- function (t1 , .. , tn , t' vardots ) : t <: function ( u1 , .. , un , u1', .. , um' , u' vardots ) : u {{ com \subsection{Shapes} }} {{ com Depth subtyping on closed shapes: types of fields behave covariantly }} G |- sft1 <: sft1' .. G |- sftn <: sftn' -------------------------------------------------- :: closed_shape_co G |- shape ( sft1 , .. , sftn ) <: shape ( sft1' , .. , sftn' ) {{ com Width subtyping on closed shapes: optional fields can be introduced }} -------------------------------------------------- :: closed_shape_widen G |- shape ( sft1 , .. , sftm ) <: shape ( sft1 , .. , sftm , ?sfn1' => t1' , .. , ?sfnn' => tn' ) {{ com Width subtyping on closed shapes: optional fields of type $[[nothing]]$ can be dropped }} -------------------------------------------------- :: closed_shape_narrow G |- shape ( sft1 , .. , sftm , ?sfn1' => nothing , .. , ?sfnn' => nothing ) <: shape ( sft1 , .. , sftm ) {{ com A closed shape collapses if any of its required field types is $[[nothing]]$ }} -------------------------------------------------- :: closed_shape_empty G |- shape ( sft1 , .. , sftm , sfn => nothing , sft1' , .. , sftn') <: nothing {{ com Closed shapes can be opened }} -------------------------------------------------- :: shape_open G |- shape ( sft1 , .. , sftn ) <: shape ( sft1 , .. , sftn , vardots \ ) {{ com Depth subtyping on open shapes: types of fields behave covariantly }} G |- sft1 <: sft1' .. G |- sftn <: sftn' -------------------------------------------------- :: open_shape_co G |- shape ( sft1 , .. , sftn , vardots \ sfn1 , .. , sfnm ) <: shape ( sft1' , .. , sftn' , vardots \ sfn1 , .. , sfnm ) {{ com Width subtyping on open shapes: fields can be forgotten }} -------------------------------------------------- :: open_shape_narrow G |- shape ( sft1 , .. , sfti , sft1' , .. , sftj', vardots \ sfn1 , .. , sfnm ) <: shape ( sft1 , .. , sfti , vardots \ sfn1 , .. , sfnm ) {{ com Width subtyping on open shapes: optional fields of type $[[mixed]]$ can be introduced }} -------------------------------------------------- :: open_shape_widen G |- shape ( sft1 , .. , sfti , vardots \ sfn1 , .. , sfnm ) <: shape (sft1 , .. , sfti , ?sfn1' => mixed , .. , ?sfnj' => mixed , vardots \ sfn1 , .. , sfnm ) {{ com Width subtyping on open shapes: unset fields can be set again }} -------------------------------------------------- :: open_shape_set_unset G |- shape ( sft1 , .. , sftn , vardots \ sfn1 , .. , sfni , sfn , sfn1' , .. , sfnj' ) <: shape ( sft1 , .. , sftn , vardots \ sfn1 , .. , sfni , sfn1' , .. , sfnj' ) {{ com An open shape collapses if any of its required field types is $[[nothing]]$ }} -------------------------------------------------- :: open_shape_empty G |- shape ( sft1 , .. , sftm , sfn => nothing , sft1' , .. , sftn' , vardots \ ) <: nothing {{ com \subsection{Class and interface inheritance} }} class C < var1 T1 constraint1, .. , varn Tn constraintn > cextends cimpls classbody G |- t1 <: var1 :> u1 .. G |- tn <: varn :> un ----------------------------------------------------- :: exact_variance G |- # C < t1 , .. , tn > <: # C < u1 , .. , un > class C < var1 T1 constraint1, .. , varn Tn constraintn > cextends cimpls classbody G |- t1 <: var1 :> u1 .. G |- tn <: varn :> un ----------------------------------------------------- :: class_variance G |- C < t1 , .. , tn > <: C < u1 , .. , un > class C < var1 T1 constraint1, .. , varn Tn constraintn > extends t cimpls classbody ------------------------------------------------- :: exact G |- # C < t1 , .. , tn > <: C < t1 , .. , tn > G |- t1 <: t2 t2 <:: t3 ---------------------------- :: derives G |- t1 <: { t1 / this } t3 {{ com \subsection{Enumerations} }} enum N : t as u ---------------- :: enum_as G |- N <: u {{ com \subsection{Type aliases} }} type N < T1, .. , Tn > = t ------------------------------------------------- :: alias_as G |- N < t1 , .. , tn > <: { t1 / T1, .. , tn / Tn } t type N < T1, .. , Tn > = t ------------------------------------------------- :: alias_super G |- { t1 / T1, .. , tn / Tn } t <: N < t1 , .. , tn > {{ com Opaque types }} newtype N < T1 , .. , Tn > as u = t -------------------------------------------------- :: opaque_as G |- N < t1 , .. , tn > <: { t1 / T1, .. , tn / Tn } u newtype N < T1 , .. , Tn > as u = t local N ------------------------------------------------------------------------ :: opaque_local_as G |- N < t1 , .. , tn > <: { t1 / T1, .. , tn / Tn } t newtype N < T1 , .. , Tn > as u = t local N ------------------------------------------------------------------------ :: opaque_local_super G |- { t1 / T1, .. , tn / Tn } t <: N < t1 , .. , tn > {{ com \section*{Subtyping on shape field types} }} {{ com \addcontentsline{toc}{section}{Subtyping on shape field types} }} defn G |- sft1 <: sft2 :: ::fssub::'shape_field_' {{ com shape field type $[[sft1]]$ is a subtype of shape field type $[[sft2]]$ under assumptions $[[G]]$ }} by {{ com \par Shapes behave covariantly in field types. }} G |- t1 <: t2 -------------------- :: co G |- sk => t1 <: sk => t2 {{ com Shapes can drop optional fields. }} G |- t1 <: t2 -------------------- :: narrow G |- sfn => t1 <: ?sfn => t2 {{ com \section*{Type equivalence} }} {{ com \addcontentsline{toc}{section}{Type equivalence} }} defn G |- t1 == t2 :: ::tyeq::'' {{ com $[[t1]]$ is equivalent to $[[t2]]$ under assumptions $[[G]]$ }} by {{ com It's useful to define type equivalence as both-ways subtyping. }} G |- t1 <: t2 G |- t2 <: t1 ------------- :: ty_equiv G |- t1 == t2 {{ com \section*{Subtyping wrt variance} }} {{ com \addcontentsline{toc}{section}{Subtyping wrt variance} }} defn G |- t1 <: var :> t2 :: ::argsub::'' {{ com $[[t1]]$ is related to $[[t2]]$ by variance $[[var]]$ under assumptions $[[G]]$ }} by G |- t1 <: t2 ------------- :: variance_co G |- t1 <: + :> t2 G |- t2 <: t1 ------------- :: variance_contra G |- t1 <: - :> t2 G |- t1 == t2 ------------------- :: variance_inv G |- t1 <: :> t2 {{ com \\\section*{Lambda signature expansion} }} {{ com In order to type lambdas, we need to know the types of the parameters and the return type. Unlike functions and methods, these can be omitted even in strict mode. So we define a relation that fills in types when they are omitted. It's the type inference engine's job to determine types under which the program can be type checked. \\\\ }} defn lamparam ~> funparam :: :: lambda_param_expand :: 'lambda_param_expand_' {{ com declaration $[[lamparam]]$ rewrites to typed parameter $[[funparam]]$ }} by -------------------------------------- :: type t isvariadic lvar ~> t isvariadic lvar ------------------------------------ :: notype isvariadic lvar ~> t isvariadic lvar {{ com \\\\ }} defn lamparams lamreturn ~> funparams lamreturn' :: :: lambda_return_expand :: 'lambda_return_expand_' {{ com declarations $[[lamparams]]$ $[[lamreturn]]$ rewrite to typed declarations $[[funparams]]$ $[[lamreturn']]$ }} by lamparam1 ~> funparam1 .. lamparamn ~> funparamn ------------------------------------------------------------------------- :: type ( lamparam1 , .. , lamparamn) : t ~> ( funparam1 , .. , funparamn ) : t lamparam1 ~> funparam1 .. lamparamn ~> funparamn ------------------------------------------------------------------------- :: notype ( lamparam1 , .. , lamparamn) ~> ( funparam1 , .. , funparamn ) : t {{ com \\\section*{Implicit coercion} }} defn G |- t1 ~> t2 :: :: coerce :: 'coerce_' {{ com Values of type $[[t1]]$ implicitly coerce to type $[[t2]]$ }} by ------------------ :: dynamic G |- t ~> dynamic G |- t1 <: t2 -------------------------- :: subtype G |- t1 ~> t2 G |- t ~> t2 ------------------ :: option G |- t ~> ?t2 defn G ; K |- e ~ t :: :: exprimplicitty :: 'expr_' {{ com Expression $[[e]]$ has implicit coercion to type $[[t]]$ under locals $[[G]]$ and continuations $[[K]]$ }} by G ; K |- e : t1 G |- t1 ~> t2 -------------------------- :: coercion G ; K |- e ~ t2 {{ com \\\section*{Expression sequencing} }} {{ com It's useful to have an n-ary auxiliary form that captures the requirement for sequencing of updates to the locals. \\ }} defn G ; K |- < e1 : t1 , ... , en : tn > :: :: exprsty :: 'exprs_' {{ com Expressions can be executed in sequence under locals $[[G]]$ and continuations $[[K]]$ }} by G ; K |- e : t ----------------------- :: expr G ; K |- < e : t > G ; K [skip := G'] |- e : t G' ; K |- < e1 : t1 , .. , en : tn > --------------------------------------- :: seq G ; K |- < e : t , e1 : t1 , .. , en : tn > defn G ; K |- < e1 ~ t1 , ... , en ~ tn > :: :: exprsimplicitty :: 'exprsimplicit_' {{ com Expressions can be executed in sequence under locals $[[G]]$ and continuations $[[K]]$ }} by G ; K |- e ~ t ----------------------- :: expr G ; K |- < e ~ t > G ; K [skip := G'] |- e ~ t G' ; K |- < e1 ~ t1 , .. , en ~ tn > --------------------------------------- :: seq G ; K |- < e ~ t , e1 ~ t1 , .. , en ~ tn > {{ com \section*{Expression typing} }} {{ com \addcontentsline{toc}{section}{Expression typing} }} defn G ; K |- e : t :: :: exprty :: 'expr_' {{ com Expression $[[e]]$ of type $[[t]]$ can be executed under locals $[[G]]$ and continuations $[[K]]$ }} by {{ com It should also be noted that throughout this section, left rules have complementary right rules that are omitted for brevity. }} {{ com \subsection{General rules} }} {{ com It should be the case that subtyping can be applied at any point. Doing this also saves us from introducing special ``merge'' logic in conditionals etc. It is commonly known as the rule of \emph{subsumption}. }} G ; K |- e : t G |- t <: t' ------------------------------ :: sub G ; K |- e : t' {{ com \subsection{Literals} }} -------------------- :: null G ; K |- null : null --------------------- :: true G ; K |- true : bool ---------------------- :: false G ; K |- false : bool --------------------------------- :: string G ; K |- string_literal : string ------------------------------- :: int G ; K |- integer_literal : int {{ com \subsection{Tuples} }} G ; K |- < e1 : t1 , .. , en : tn > --------------------------------------------------------------------- :: tuple G ; K |- tuple (e1 , .. , en) : (t1 , .. , tn) {{ com \subsection{Locals} }} --------------------- :: lvar G , x:t ; K |- $x : t {{ com \subsection{Assignment} }} {{ com Assignment is surprisingly complex. Evaluation is left-to-right, within the lvalue $[[e_1]]$ and then within $[[e_2]]$. }} G ; K , skip : G' |- e1 := t , U G' ; K , skip : G'' |- e2 : t ------------------------------------- :: assign G ; K , skip : G''[U] |- e1 = e2 : t {{ com \subsection{Addition} }} G ; K |- < e1 : float , e2 : num|dynamic > ---------------------------------------------- :: add_float_left G ; K |- e1 + e2 : float G ; K |- < e1 : int , e2 : int > -------------------------------- :: add_int G ; K |- e1 + e2 : int G ; K |- < e1 : num , e2 : num|dynamic > ----------------------------------------- :: add_num_left G ; K |- e1 + e2 : num {{ com The case below cannot gain the typing of num, as the runtime allows adding arrays to get arrays. Taking two arrays for dynamic parameters, adding them, and treating the resultant array as a num can cause crashing later. It could safely be $[[ num|array<dynamic>|array<dynamic,dynamic>]]$ instead, but this typing is confusing to users. }} G ; K |- < e1 : dynamic , e2 : dynamic > ------------------------------------ :: add_dynamic G ; K |- e1 + e2 : dynamic {{ com \subsection{Subtraction and Multiplication} }} {{ com These differ from addition only in how they handle the case of two dynamic types. Multiplication is omitted, but is similar to subtraction. }} G ; K |- < e1 : dynamic , e2 : dynamic > ---------------------------------------------------- :: sub_dynamic G ; K |- e1 - e2 : num {{ com \subsection{Division and Exponentiation} }} {{ com Exponentiation is omitted, but is similar to division. }} G ; K , skip:G', catch:G' |- < e1 : float , e2 : num|dynamic > --------------------------------------------------- :: div_float_left G ; K , skip:G', catch:G' |- e1 / e2 : float {{ com When int operations do not perfectly yield an int, the result is a float. Thus num is the tightest typing. }} G ; K , skip:G', catch:G' |- < e1 : num|dynamic , e2 : num|dynamic > ------------------------------------------------- :: div_num G ; K , skip:G', catch:G' |- e1 / e2 : num {{ com \subsection{Remainder and Shifts} }} {{ com Same rules for shift left and shift right }} G ; K |- < e1 : int|dynamic , e2 : int|dynamic > ------------------------------------------------ :: mod G ; K |- e1 % e2 : int {{ com \subsection{Negation} }} {{ com Same rules for + }} G ; K |- e : int -------------------------------- :: neg_int G ; K |- - e : int G ; K |- e : float -------------------------------- :: neg_float G ; K |- - e : float G ; K |- e : num|dynamic -------------------------------- :: neg_num G ; K |- - e : num {{ com \subsection{Binary Bitwise} }} {{ com Same rules for bitwise xor and and }} G ; K |- < e1 : int , e2 : int|dynamic > -------------------------------- :: or_int_left G ; K |- e1 | e2 : int {{ com The case below cannot gain the typing of int, as the runtime allows bitwise operations on strings. Taking two strings for dynamic parameters, bitwise or-ing them, and treating the resultant string as an int can cause crashing later. It could safely be $[[int|string]]$ = $[[arraykey]]$ instead, but this typing is confusing to users. }} G ; K |- < e1 : dynamic , e2 : dynamic > -------------------------------------- :: or_dynamic G ; K |- e1 | e2 : dynamic {{ com \subsection{Bitwise Not} }} G ; K |- e : int -------------------------------- :: bitnot G ; K |- ~ e : int {{ com For the same reason as the binary case, unary bitwise operations on dynamic parameters yield dynamic. }} G ; K |- e : dynamic -------------------------------- :: bitnot_dynamic G ; K |- ~ e : dynamic {{ com \subsection{Concatenation} }} {{ com The type t here must be Stringish, containing any primitive type and objects that implement underscore underscore toString. }} G ; K |- < e1 : t|dynamic , e2 : t|dynamic > -------------------------------------------- :: concat G ; K |- e1 . e2 : string {{ com \subsection{Equality} }} {{ com Same rules for === and !==. }} G ; K |- < e1 : t1 , e2 : t2 > ------------------------------ :: equals G ; K |- e1 == e2 : bool G ; K |- < e1 : t1 , e2 : t2 > ------------------------------ :: disequals G ; K |- e1 != e2 : bool {{ com \subsection{Comparison operators} }} {{ com Similar for $\kwd{>}$, $\kwd{<=}$, and $\kwd{>=}$ }} G ; K |- < e1 : num , e2 : num > -------------------------------- :: lt_num G ; K |- e1 < e2 : bool G ; K |- < e1 : string , e2 : string > ----------------------------------- :: lt_string G ; K |- e1 < e2 : bool G ; K |- < e1 : `DateTime` , e2 : `DateTime` > ------------------------------------------ :: lt_datetime G ; K |- e1 < e2 : bool G ; K |- < e1 : dynamic , e2 : ((num|string)|`DateTime`)|dynamic > -------------------------------- :: lt_dynamic_left G ; K |- e1 < e2 : bool {{ com Also similar for $\kwd{<=>}$ except the type bool is replaced with int. }} {{ com \subsection{Conditionals and logical operators} }} {{ com The condition in a conditional expression can be used to refine the types of locals in both true and false branches. The current rule in Hack is unsound; the one below is sound. }} G ; K , skip : G1 |- e truthy G ; K , skip : G2 |- !e truthy G1 ; K |- e1 : t G2 ; K |- e2 : t ---------------------------------------- :: if G ; K |- (e ? e1 : e2) : t G ; K , skip : G1 |- e1 truthy G ; K , skip : G2 |- !e1 truthy G1 ; K , skip : G2 |- e2 : t ------------------------------- :: and G ; K , skip : G2 |- e1 && e2 : bool G ; K , skip : G1 |- !e1 truthy G ; K , skip : G2 |- e1 truthy G1 ; K , skip : G2 |- e2 : t ----------------------------- :: or G ; K , skip : G2 |- e1 || e2 : bool G ; K |- e : t ------------------ :: not G ; K |- !e : bool {{ com \subsection{Lambda} }} {{ com Lambda expressions inherit the locals environment from their enclosing scope, together with types for their parameters. But the continuation environment is initially empty, except for the return continuation (for statement bodies), which accepts anything. For void functions with statement bodies, we support implicit return by including a skip continuation. }} {{ com TBC variadics }} lamparams lamreturn ~> ( t1 $x1 , .. , tn $xn) : t ( t1 $x1 , .. , tn $xn) : t ; G [x1 := t1 , .. , xn := tn ] ; { return : G' } |- block ------------------------------------------------------------------------ :: lambda_stmt G ; K |- lamparams lamreturn ==> block : function(t1,..,tn):t lamparams lamreturn ~> ( t1 $x1 , .. , tn $xn) : void ( t1 $x1 , .. , tn $xn) : void ; G [ x1 := t1 , .. , xn := tn ] ; { return : G', skip : G' } |- block ------------------------------------------------------------------------ :: lambda_void G ; K |- lamparams lamreturn ==> block : function(t1,..,tn):void lamparams lamreturn ~> ( t1 $x1 , .. , tn $xn ) : t G [ x1 := t1 , .. , xn := tn ]; { } |- e : t ---------------------------------------------------------- :: lambda_expr G ; K |- lamparams lamreturn ==> e : function(t1,..,tn):t {{ com \subsection{Object creation} }} {{ com To do: constraint satisfaction }} G ; K |- < e1 : { t1 / T1 , .. , tm / Tm } u1 , .. , en : { t1 / T1 , .. , tm / Tm } un > class C < var1 T1 constraint1, .. , varm Tm constraintm > cextends cimpls { function __construct (u1 lvar1 , .. , un lvarn) block members } --------------------------------------------------------------- :: new G ; K |- new C ( e1 , .. , en ) : # C < t1 , .. , tm > {{ com \subsection{Property access} }} G ; K |- e : u u -> x : t ------------------- :: property_access G ; K |- e -> x : t G ; K |- e : ? u u -> x : t ---------------------- :: nullsafe_property_access G ; K |- e ?-> x : ? t {{ com \subsection{Static property access} }} C declares static x : t ----------------------- :: static_property_access G ; K |- C :: x : t {{ com \subsection{Array/shape/tuple indexing} }} G ; K |- e1 : t1 G ; K |- t1 [ e2 ] : t ---------------------- :: indexing G ; K |- e1 [ e2 ] : t {{ com \subsection{Function application} }} {{ com Function application is complicated by the possibility of (a) a variadic function type and (b) use of the splat operator at the call site. Fortunately variadics are already handled by subtyping rules. }} {{ com The basic rule simply says that an expression of function type can be applied to arguments with matching types. When combined with rule \ottdrulename{sub\_function\_variadic} it supports application of variadic functions to a known number of arguments. }} G ; K[skip := G'] |- e : function(t1,..,tn):t G' ; K |- <e1 ~ t1 , .. , en ~ tn > ----------------------------------- :: apply G ; K |- e ( e1 , .. , en ) : t {{ com If there is a splat argument with unbounded length, then we require that the function type is variadic. }} G ; K[skip := G'] |- e : function(t1,..,tn,t0 vardots ):t G' ; K |- <e1 ~ t1 , .. , en ~ tn , e' ~ `Traversable`<t0> > ------------------------------------------------------------ :: apply_splat G ; K |- e ( e1 , .. , en , vardots e' ) : t {{ com Finally, splat can be used on an expression with known tuple type, as if the components of the tuple are additional arguments. Again, this can be combined with rule \ottdrulename{sub\_function\_variadic}. }} G ; K[skip := G'] |- e : function(t1,..,tn,t1',..,tm'):t G' ; K |- < e1 ~ t1 , .. , en ~ tn , e' ~ (t1', .. , tm') > ----------------------------------------------------------- :: apply_splat_tuple G ; K |- e ( e1 , .. , en , vardots e' ) : t {{ com We are also allowed to use an expression of dynamic type as a function. We don't care about the types of the arguments, but do need to check that the splat argument is a traversable or a tuple. }} G ; K[skip := G'] |- e : dynamic G' ; K |- < e1 : t1 , .. , en : tn > ------------------------------------ :: apply_dynamic G ; K |- e ( e1 , .. , en) : dynamic G ; K[skip := G'] |- e : dynamic G' ; K |- < e1 : t1 , .. , en : tn , e' : `Traversable`<t0> > ------------------------------------------------------------- :: apply_dynamic_splat G ; K |- e ( e1 , .. , en , vardots e') : dynamic G ; K[skip := G'] |- e : dynamic G' ; K |- < e1 : t1 , .. , en : tn , e' : (t1', .. , tm') > ----------------------------------------------------------- :: apply_dynamic_splat_tuple G ; K |- e ( e1 , .. , en , vardots e') : dynamic {{ com \subsection{Special function application} }} G ; K |- < e1 : ? `KeyedContainer` < t , u > , e2 : ? t > -------------------------------------------------- :: idx G ; K |- `idx` ( e1 , e2 ) : ? u G ; K |- < e1 : ? `KeyedContainer` < t , u > , e2 : ? t , e3 : u > -------------------------------------------------- :: idx_default G ; K |- `idx` ( e1 , e2 , e3 ) : u G ; K |- e : ? shape ( ?sfn => t , vardots \ sfn1 , .. , sfnm ) -------------------------------------------------- :: shapes_idx_optional G ; K |- `Shapes` :: `idx` ( e , sfn ) : ? t G ; K |- < e1 : ? shape ( ?sfn => t , vardots \ sfn1 , .., sfnm ) , e2 : t > -------------------------------------------------- :: shapes_idx_default G ; K |- `Shapes` :: `idx` ( e1 , sfn , e2 ) : t G ; K |- e : shape ( sfn => t , vardots \ sfn1 , .. , sfnm ) -------------------------------------------------- :: shapes_at_required G ; K |- `Shapes` :: `at` ( e , sfn ) : t G ; K |- e : shape ( ?sfn => t , vardots \ sfn1 , .. , sfnm ) -------------------------------------------------- :: shapes_at_optional G ; K |- `Shapes` :: `at` ( e , sfn ) : t G ; K |- e : shape ( sft1 , .. , sfti , ?sfn => t , sft1' , .. , sftj' ) -------------------------------------------------- :: shapes_remove_key_closed G ; K |- `Shapes` :: `removeKey` ( e , sfn ) : shape( sft1 , .. , sfti , sft1' , .. , sftj' ) G ; K |- e : shape ( sft1 , .. , sfti , ? sfn => t , sft1' , .. , sftj' , vardots \ sfn1 , .. , sfnm ) -------------------------------------------------- :: shapes_remove_key_open_set G ; K |- `Shapes` :: `removeKey` ( e , sfn ) : shape ( sft1 , .. , sfti , sft1' , .. , sftj' , vardots \ sfn1 , .. , sfnm , sfn ) G ; K |- e : shape ( sft1 , .. , sftn , vardots \ sfn1 , .. , sfni, sfn , sfn1' , .. , sfnj' ) -------------------------------------------------- :: shapes_remove_key_open_unset G ; K |- `Shapes` :: `removeKey` ( e , sfn ) : shape ( sft1 , .. , sftn , vardots \ sfn1 , .. , sfni , sfn , sfn1' , .. , sfnj' ) {{ com \subsection{Await} }} G ; K |- e : t t awaits t' ---------------------------------- :: await G ; K |- await e : t' {{ com \section*{Awaitable types} }} {{ com \addcontentsline{toc}{section}{Awaitable types} }} defn t awaits t' :: :: awaits :: 'awaits_' {{ com awaiting on $[[t]]$ produces a $[[t']]$ }} by ----------------------- :: awaitable `Awaitable`<t> awaits t t awaits t' ------------------ :: nullable ?t awaits ?t' t1 awaits t1' t2 awaits t2' ------------------------------- :: union t1 | t2 awaits t1' | t2' {{ com \section*{Property declarations} }} {{ com \addcontentsline{toc}{section}{Property declarations} }} defn u declares x : t :: :: declares :: 'declares_' {{ com type $[[u]]$ declares a property $[[x]]$ of type $[[t]]$ }} by class C < var1 T1 constraint1 , .. , varm Tm constraintm > cextends cimpls { constructor t $ x ; member1 .. membern } ----------------------------------------------------------- :: exact_class # C < t1 , .. , tm > declares x : { t1 / T1 , .. , tm / Tm } { # C < t1 , .. , tm > / this } t defn u -> x : t :: :: property :: 'property_' {{ com type $[[u]]$ has a property $[[x]]$ of type $[[t]]$ }} by u declares x : t ---------------- :: declaration u -> x : t u1 -> x : t1 u2 -> x : t2 ------------------------------- :: union ( u1 | u2 ) -> x : t1 | t2 {{ com TODO: use of $[[this]]$ type in the type of a property }} {{ com \section*{Static property declarations} }} {{ com \addcontentsline{toc}{section}{Static property declarations} }} defn C declares static x : t :: :: declares_static :: 'declares_static_' {{ com class $[[C]]$ declares a static property $[[x]]$ of type $[[t]]$ }} by C' inst' <:: C inst class C typarams cextends cimpls { constructor static t $ x ; member1 .. membern } ---------------------------------------------------------------------------------- :: derived C' declares static x : t {{ com \section*{Types supporting indexing} }} {{ com \addcontentsline{toc}{section}{Types supporting indexing} }} defn G ; K |- u [ e ] : t :: :: indexing :: 'indexing_' {{ com type $[[u]]$ supports indexing at a value $[[e]]$ producing the result of type $[[t]]$ under environment $[[G]]$ and continuations $[[K]]$ }} by G ; K |- e : t1 | dynamic ------------------------------------------ :: KeyedContainer G ; K |- `KeyedContainer` < t1 , t2 > [ e ] : t2 ------------------------------------------------- :: shape G ; K |- shape ( sfn => t , vardots \ sfn1 , .. , sfnm ) [ sfn ] : t ------------------------------------------------------- :: tuple G ; K |- (t1 , .. , ti , t , t1' , .. , tj' ) [ i ] : t G ; K |- u1 [ e ] : t1 G ; K |- u2 [ e ] : t2 ------------------------------------ :: union G ; K |- ( u1 | u2 ) [ e ] : t1 | t2 {{ com \section*{Expression refinement} }} {{ com \addcontentsline{toc}{section}{Expression refinement} }} defn G ; K |- e truthy :: :: truthy :: 'cond_' {{ com $[[e]]$ evaluating to truthy value is valid under environment $[[G]]$ and continuations $[[K]]$ }} by {{ com \subsection{Primitive type tests} }} {{ com Similar for boolean, string, float }} -------------------------------------------------------- :: is_int G , x : t ; K , skip : G , x: int |- is_int ( $x ) truthy {{ com \subsection{Collection type tests} }} {{ com For these tests, we generate fresh abstract types for the parameters. TBC: constraints on type parameter. }} T freshfor G --------------------------------------------------- :: is_vec G , x : t ; K, skip : G , x : vec<T> |- is_vec ( $x ) truthy T freshfor G ------------------------------------------------------------- :: is_keyset G , x : t ; K , skip : G , T <: arraykey , x : keyset<T> |- is_keyset ( $x ) truthy T1 freshfor G T2 freshfor G ------------------------------------------------- :: is_dict G , x : t ; K , skip : G , T1 <: arraykey , x : dict < T1, T2 > |- is_dict ( $x ) truthy {{ com \subsection{Null tests} }} {{ com Similar for $[[$x != null]]$ and $[[!($x === null)]]$ and $[[!(is_null($x))]]$. }} ------------------------------------------------------ :: neq_null G, x : ?t ; K , skip : G , x : t |- $x !== null truthy {{ com \subsection{Composition of refinements} }} G ; K , skip : G1 |- e1 truthy G ; K , skip : G2 |- ! e1 truthy G1 ; K , skip : G2 |- e2 truthy ------------------------------------------------------- :: and G ; K , skip : G2 |- e1 && e2 truthy G ; K , skip : G1 |- !e1 truthy G ; K , skip : G2 |- e1 truthy G1 ; K , skip : G2 |- !e2 truthy -------------------------------------------- :: not_or G ; K , skip : G2 |- !(e1 || e2) truthy G ; K |- e truthy ---------------------- :: not_not G ; K |- !(!e) truthy G ; K |- e : t ---------------- :: id G ; K |- e truthy {{ com \section*{Assignment typing} }} {{ com \addcontentsline{toc}{section}{Assignment typing} }} defn G ; K |- e := t , U :: :: assign :: 'assign_' {{ com a value of type $[[t]]$ can be assigned to lvalue $[[e]]$ under locals $[[G]]$ and continuations $[[K]]$, yielding new type updates $[[U]]$}} by ------------------------------------ :: local G ; K |- $x := t , x := t G ; K , skip : G' |- e1 := t1 , U1 G' ; K , skip : G'' |- e2 := t2 , U2 ---------------------------------------------- :: pair G ; K , skip : G'' |- list ( e1 , e2 ) := `Pair` < t1 , t2> , U1[U2] G ; K |- e : t1 G |- t1 [] := t2 => t1' G ; K |- e := t1' , U ----------------------- :: array_append G ; K |- e [] := t2 , U G ; K |- e : u G |- u -> x := t ---------------------- :: property G ; K |- e -> x := t , C declares static x : t ----------------------- :: static_property G ; K |- C :: x := t , G ; K , skip : G' |- e1 : t1 is_hack_collection t1 = False G' ; K , skip : G'' |- t1 [ e2 ] := t => t1' G'' ; K , skip : G''' |- e1 := t1' , U -------------------------------------------------- :: indexing_non_hack_collection G ; K , skip : G''' |- e1 [ e2 ] := t , U G ; K , skip : G' |- e1 : t1 is_hack_collection t1 = True G' ; K , skip : G'' |- t1 [ e2 ] := t => t1' -------------------------------------------------- :: indexing_hack_collection G ; K , skip : G'' |- e1 [ e2 ] := t , {{ com In the last rule, one could replace $[[t1']]$ with $[[t1]]$ because $$ [[is_hack_collection t1 = True]] $$ and $$ [[G ; K |- t1 [ e2 ] := t => t1']] $$ imply $[[G |- t1 == t1']]$ (the proof is by induction on the derivation of the former judgement). }} {{ com \subsection*{Array append} }} {{ com \addcontentsline{toc}{subsection}{Array append} }} defn G |- t1 [] := t2 => t1' :: :: array_append :: 'array_append_' {{ com under locals $[[G]]$, a value of type $[[t2]]$ can be appended to an lvalue of type $[[t1]]$ and the result is of type $[[t1']]$ }} by G |- u1 <: t1 G |- u2 <: t2 G |- t1 [] := t2 => t1' -------------------------------------------------- :: sub G |- u1 [] := u2 => t1' G |- t' ~> t -------------------------------------------------- :: vec G |- vec < t > [] := t' => vec < t > G |- t' ~> t -------------------------------------------------- :: keyset G |- keyset < t > [] := t' => keyset < t > G |- t' ~> t -------------------------------------------------- :: vector G |- `Vector` < t > [] := t' => `Vector` < t > G |- t' ~> t -------------------------------------------------- :: set G |- `Set` < t > [] := t' => `Set` < t > G |- t1' ~> t1 G |- t2' ~> t2 -------------------------------------------------- :: map G |- `Map` < t1 , t2 > [] := `Pair` < t1' , t2' > => `Map` < t1 , t2 > G |- t1[] := t => t1' G |- t2[] := t => t2' -------------------------------------------------- :: union G |- (t1 | t2) [] := t => t1' | t2' {{ com \subsection*{Array/shape/tuple element} }} {{ com \addcontentsline{toc}{subsection}{Array/shape/tuple element} }} defn G ; K |- t1 [ e2 ] := t => t1' :: :: array_get :: 'array_get_' {{ com value $[[e2]]$ is a valid index into values of type $[[t1]]$ and assignment of a value of type $[[t]]$ to the element at that index produces a value of type $[[t1']]$ under environment $[[G]]$ and continuations $[[K]]$ }} by G |- u1 <: t1 G |- u <: t G ; K |- t1 [ e2 ] := t => t1' -------------------------------------------------- :: sub G ; K |- u1 [ e2 ] := u => t1' G ; K |- e : int | dynamic -------------------------------------------------- :: vec G ; K |- vec < t > [ e ] := t => vec < t > G ; K |- e : t1 | dynamic -------------------------------------------------- :: dict G ; K |- dict < t1 , t2 > [ e ] := t2 => dict < t1 , t2 > G ; K |- e : int | dynamic -------------------------------------------------- :: vector G ; K |- `Vector` < t > [ e ] := t => `Vector` < t > G ; K |- e : t1 | dynamic -------------------------------------------------- :: map G ; K |- `Map` < t1 , t2 > [ e1 ] := t2 => `Map` < t1 , t2 > -------------------------------------------------- :: closed_set G ; K |- shape ( sft1 , .. , sftn , ?sfn => t , sft1' , .. , sftm' ) [sfn] := t' => shape ( sft1 , .. , sftn , sfn => t' , sft1' , .. , sftm' ) -------------------------------------------------- :: open_set G ; K |- shape ( sft1 , .. , sfti , ?sfn => t , sft1' , .. , sftj' , vardots \ sfn1 , .. , sfnm ) [ sfn ] := t' => shape ( sft1 , .. , sfti , sfn => t' , sft1' , .. , sftj' , vardots \ sfn1 , .. , sfnm ) -------------------------------------------------- :: open_set_unset G ; K |- shape ( sft1 , .. , sftn , vardots \ sfn1 , .. , sfni , sfn , sfn1' , .. , sfnj' ) [ sfn ] := t' => shape ( sft1 , .. , sftn , sfn => t' , vardots \ sfn1 , .. , sfni , sfn1' , .. , sfnj' ) {{ com The above two rules imply that not only can we reassign an existing field, but also we can set a new field, because a shape that doesn't have a field $[[sfn]]$ is a subtype of a shape that does have it and in which $[[sfn]]$ is optional. For open shapes the type of the field must be $[[mixed]]$, but for closed shapes it can be anything. This follows from rules \ottdrulename{sub\_closed\_shape\_widen} and \ottdrulename{sub\_open\_shape\_widen}. }} -------------------------------------------------- :: tuple G ; K |- ( t1 , .. , ti , t , t1' , .. , tj' ) [ i ] := t' => ( t1 , .. , ti , t' , t1' , .. , tj' ) G ; K |- t1 [ e ] := t => t1' G ; K |- t2 [ e ] := t => t2' -------------------------------------------------- :: union G ; K |- (t1 | t2) [ e ] := t => t1' | t2' {{ com \subsection*{Property} }} {{ com \addcontentsline{toc}{subsection}{Property} }} defn G |- u -> x := t :: :: property_assignment :: 'property_assignment_' {{ com under locals $[[G]]$, a value of type $[[t]]$ can be assigned to a property $[[x]]$ of a value of type $[[u]]$ }} by G |- u -> x := t G |- t' ~> t ----------------- :: sub G |- u -> x := t' u declares x : t ---------------- :: declaration G |- u -> x := t G |- u1 -> x := t G |- u2 -> x := t ------------------- :: union G |- (u1 | u2) -> x := t {{ com \subsection*{Hack collections} }} {{ com \addcontentsline{toc}{subsection}{Hack collections} }} defn is_hack_collection t = b :: :: is_hack_collection :: 'is_hack_collection_' {{ com Is type $[[t]]$ a Hack collection? }} {{ tex \kwd{is\_hack\_collection}\;[[t]] = [[b]] }} by -------------------------------------------------- :: vector is_hack_collection ( `Vector` < t > ) = True -------------------------------------------------- :: map is_hack_collection ( `Map` < t1 , t2 > ) = True -------------------------------------------------- :: set is_hack_collection ( `Set` < t > ) = True is_hack_collection t1 = True is_hack_collection t2 = True -------------------------------------------------- :: union_true is_hack_collection ( t1 | t2 ) = True -------------------------------------------------- :: vec is_hack_collection ( vec < t > ) = False -------------------------------------------------- :: dict is_hack_collection ( dict < t1 , t2 > ) = False -------------------------------------------------- :: keyset is_hack_collection ( keyset < t > ) = False -------------------------------------------------- :: closed_shape is_hack_collection ( shape ( sft1 , .. , sftn ) ) = False -------------------------------------------------- :: open_shape is_hack_collection ( shape ( sft1 , .. , sftn , vardots \ sfn1 , .. , sfnm ) ) = False -------------------------------------------------- :: tuple is_hack_collection ( t1 , .. , tn ) = False is_hack_collection t1 = False -------------------------------------------------- :: union_left_false is_hack_collection ( t1 | t2 ) = False is_hack_collection t2 = False -------------------------------------------------- :: union_right_false is_hack_collection ( t1 | t2 ) = False {{ com \section*{Statements} }} {{ com \addcontentsline{toc}{section}{Statements} }} defn F ; G ; K |- s :: :: st :: 'st_' {{ com statement $[[s]]$ can be executed under locals $[[G]]$ and continuations $[[K]]$ with enclosing function signature $[[F]]$ }} by G ; K[skip:=G1] |- e truthy G ; K[skip:=G2] |- !e truthy F ; G1; K |- s1 F ; G2; K |- s2 ------------------------------------- :: if F ; G ; K |- if ( e ) s1 else s2 F ; G ; K |- if ( e ) s else { } -------------------------------- :: if_then F ; G ; K |- if ( e ) s {{ com Break and continue just require that the continuation exists and accepts the current state. }} --------------------------- :: break F ; G ; K , break : G |- break ; -------------------------------- :: continue F ; G ; K, continue : G |- continue ; {{ com A return statement without expression is allowed only if the explicit return type of the enclosing function is void. }} --------------------------------------------------------------------- :: return_void funparams : void ; G ; K, return : G |- return ; {{ com If there is an expression, its type must coerce to the explicit return type of the enclosing function. }} G ; K |- e ~ t --------------------------------------------- :: return funparams : t ; G; K, return : G |- return e ; {{ com To simplify rules for while, we define a primitive rule for infinite loops. }} F ; G ; K [continue := G, break := G', skip := G] |- s --------------------------------------------------------- :: while_true F ; G ; K, skip : G' |- while ( true ) s {{ com All looping constructs are defined in terms of this infinite loop rule. }} F ; G ; K |- while ( true ) { if ( ! e ) break; s; } ---------------------------------------------------------- :: while F ; G ; K |- while ( e ) s F ; G ; K |- while ( true ) { s ; if ( ! e ) break ; } ---------------------------------------------------- :: do F ; G ; K |- do s while ( e ) F ; G ; K |- { e1 ; while ( e2 ) { s ; e3 ; } } ------------------------------------------------------------ :: for F ; G ; K |- for ( e1 ; e2 ; e3 ) s G ; K |- e : `Traversable` < t > F ; G ; K , skip : G[x := t] |- while ( true ) s -------------------------------------------------- :: foreach_value F ; G ; K |- foreach ( e as $x ) s G ; K |- e : `KeyedTraversable` < t1 , t2 > F ; G ; K , skip : G[x1 := t1, x2 := t2] |- while (true) s ------------------------------------------------------ :: foreach_key_value F ; G ; K |- foreach ( e as $x1 => $x2 ) s {{ com Exception handling }} {{ com The control flow can arrive to the finally block from any break, continue or return statement in the try block, so we need to union them all. }} {{ com If the premise does not have the required continuations, we would use ST\textunderscore CONTINUATION\textunderscore EXTENSION to add the appropriate ones. }} F ; G ; { skip : G1, break : G1, continue : G1, return : G1 , catch : G2 } |- s F ; G2 , x : C1 ; K [ skip := G1, break := G1, continue := G1, return := G1 ] |- s1 .. F ; G2 , x : Cn ; K [ skip := G1, break := G1, continue := G1, return := G1 ] |- sn F ; G1 ; K' |- s' ---------------------------------------------------- :: try_catch F ; G ; K' |- try s catch ( C1 $x1 ) s1 .. catch ( Cn $xn ) sn finally s' G ; K |- e : t ---------------------------------- :: expr F ; G ; K |- e ; ---------------------------- :: block_empty F ; G ; K , skip : G |- { } {{ com Sequencing just threads the environment. This is just the Composition rule from program logic, written in a continuation-passing style }} F ; G ; K [ skip := G' ] |- s F ; G' ; K |- { s1 .. sn } ------------------------------- :: seq F ; G ; K |- { s s1 .. sn } {{ com \section*{Top level declarations} }} {{ com \addcontentsline{toc}{section}{Top level declarations} }} defn |- decl :: :: decl_ok :: 'decl_ok_' {{ com a declaration $[[decl]]$ is valid }} by {{ com \\\\ Top-level functions are typed under an initial typing for locals that provides types for their parameters. The continuation environment is initially empty, except for the return continuation, which accepts anything. For void functions, we support implicit return by including a skip continuation. }} ( t1 $x1 , .. , tn $xn ) : t ; { x1 : t1 , .. , xn : tn } ; { return : G } |- block ------------------------------------------------------------------------------------------ :: function |- function id ( t1 $x1 , .. , tn $xn ) : t block ( t1 $x1 , .. , tn $xn ) : void ; { x1 : t1 , .. , xn : tn } ; { return : G, skip : G } |- block --------------------------------------------------------------- :: function_void |- function id ( t1 $x1 , .. , tn $xn ) : void block |- function id ( t1 $x1 , .. , tn $xn , vec<t0> $x0 ) : t block ----------------------------------------------------------- :: function_variadic |- function id ( t1 $x1 , .. , tn $xn , t0 vardots $x0 ) : t block
hhvm/hphp/hack/doc/type_system/Makefile
OTT=ott OTT_OPTIONS=-signal_parse_errors true all: \ hack_typing.ml \ hack_typing.v \ hack_typing.pdf hack_typing.tex: hack_typing.ott $(OTT) $(OTT_OPTIONS) -i hack_typing.ott -o hack_typing.tex hack_typing.ml: hack_typing.ott $(OTT) $(OTT_OPTIONS) -i hack_typing.ott -o hack_typing.ml hack_typing.v: hack_typing.ott $(OTT) $(OTT_OPTIONS) -i hack_typing.ott -o hack_typing.v hack_typing.pdf: hack_typing.tex pdflatex hack_typing.tex clean: rm -rf *~ rm -rf hack_typing.tex hack_typing.ml hack_typing.v hack_typing.pdf rm -rf hack_typing.aux hack_typing.log
Markdown
hhvm/hphp/hack/doc/vision_docs/tracking_effects_and_coeffects.md
Title: **Tracking effects and coeffects** via capabilities Start date: July 7, 2020 Status: DRAFT # Summary The purpose of this proposal is twofold: * unify and systematically model reasoning about *effects,* including reactivity (all flavors), purity, determinism, global state; and * build a sound foundation for contextual properties, formally known as *coeffects,* such as (implicit) viewer contexts or environments The proposed *capability-based* approach has the unique benefit that it can model both effects and coeffects. The main idea is to enhance the typechecker with a limited form of *implicit parameters* (a simple coeffect type system) and desugar into and pass capabilities that act as permissions for effects or resource/context access. It has very little impact on the Hack syntax and almost no impact to the users. Although capabilities have been employed in many security systems since the last century, it wasn’t until 2015-16 that this idea was welcomed in the programming languages (PL) community to solve a larger problem of (co)effects. Around that time, two independent PL research labs have not only formalized their interestingly similar capability-based type systems; they also implemented it as a *small* language extension/plug-in of Scala and shown that the approach scales to large & complex code base of 100K+ lines (Scala Standard Library). See section “Prior art” for details. To be clear, this proposal is not about exposing the feature of implicit parameters to the Hack users (yet); it is about building a *typechecker primitive* that enables other complex features (both existing and upcoming) to be modeled elegantly and soundly in the typechecker, thus enabling Hack to be more expressive. For example, the (conditional) reactivity/purity would not each require special context-propagation logic and subtyping and conformance (caller-callee) rules — everything would simply just “fall out” from the typing rules with only a minor addition — a capability type is read from an additional context carried along with regular typing context. A similar desired behavior can be achieved for contexts such as normal/experimental by mapping them into implicitly passed capabilities that statically prevent unsafe calls from non-experimental code into experimental code (for stability and future compatibility). # Motivation As outlined in the Summary, this would provide a reusable mechanism to neatly and soundly express existing features: * reactivity & recently introduced purity, * *conditional* context propagation / treatment of effects in general and in addition it would enable to easily start tracking a new kind of effect, such as IO, non-determinism, etc. For that, a new capability *domain* is to be introduced, with the appropriate subtyping relationship. E.g., to track input/output that can be further refined into disk-based and network-based I/O, the subtyping of capabilities would be: ``` CanDisk <: CanStdIO // capability for accessing local disk CanNet <: CanStdIO // capability for access network/Internet CanIO <: (CanNet | CanDisk) // ~bottom type for effect domain IO ``` Now the basic idea is to require that an appropriate capability (or a subtype) is available in scope, either via being: * required by a so-called *stoic* function/method; or * captured from a *contextful* (potentially effectful/impure) function. The prominent way to propagate these capabilities is to treat them as *implicit* parameters, as section Prior Art explains. ***Note***: The syntax `@{Capability1, ...}` below is just a **desugaring** and to illustrate how typechecker would see a function signature; it is intentionally chosen to resemble the standard “Γ **@ C**” notation for coeffects (as opposed to “T ! E” of effects). Comment `/*{Capability}*/` denotes capabilities that are filled in by the typechecker, which is akin to passing implicit arguments as it has no implications on the user code. ``` // 2 stoic functions that require different capabilities function log2disk(string $message)@{CanDisk}: void { ... } function publish_paste(string $text)@{CanNet}: void { ... } function log_and_publish_as_paste(string $msg)@{CanIO} log2disk($message)/*{CanIO}*/; // ok: CanIO <: CanDisk publish_paste($message)/*{CanIO}*/; // ok: CanIO <: CanNet } ``` ## Effect polymorphism Effect polymorphism is the property that enables writing a single definition for a function/method whose effect can vary depending on the arguments passed. Contexts and associated capabilities can be seen as (co)effects. E.g.: ``` function handle_messages( vec<string> $msgs, // denoted by: => in [FLiu’16-17] // @local in [OOPSLA'16] <<__Contextful>> (function(string): void) $log ): void { ... } function pure_context(): void { handle_messages(vec["a", "b"], // no capability flows in (string $msg) ==> {}); } function disk_context()@{CanDisk}: void { handle_messages(vec["a", "b"], // lambda captures the capability from outer scope (string $msg) ==> log2disk($msg)/*{CanDisk}*/ ); } ``` The new attribute `<<__Contextful>>` will be described shortly; its idea is to allow passing *both*: * functions that *not* capture/require context (e.g., pure ones), and * contextful functions that capture some context, which enables effect polymorphism. This *by design* solves the *conditional* context propagation, which is just a specific instance of effect polymorphism (with reactivity being considered as effect). For convenience, we could also support desugaring of `log2disk` into the explicitly written lambda in the last function above. ***Note***: `<<__Contextful>>` is can be internally desugared from the existing syntax for most use cases such as reactivity, as it will be explained later. Compared to desugaring into generics, distinguishing between the two kinds of functions at the type level provides benefits similar to the ones explained in [Rytz'14]§2.2 and [ECOOP'12]. First, it enables a clean mapping from a lightweight user syntax (considered in a separate HIP) and type-checking errors does not involve mismatches of inferred types. Second and more important, provides a means to accept a function that makes arbitrary effects in *any* domain without impact on the user syntax. For example, adding a new effect domain (e.g., what exception is thrown, whether it is deterministic, what type of IO, etc.) would require: - inferring the new capability in existing code for every call site, essentially regressing type-checking whenever a new effect domain is added; - new syntax to be placed whenever we want to account for the new domain. The classic example is Java, where in order to consider a new domain of effects such as Exceptions, you need to add a new version of function parameterized by additional generic `E` as follows: ``` <E> void handle_messages( Vector<String> msgs, FunctionThatThrows<String, Void, E> log ) { ... } // NOTE: N+1 definitions needed for N domains of effects void handle_messages( Vector<String> msgs, Function<String, Void> log ) { ... } ``` Therefore, the generics-based mapping does not scale well; this is further explained later on and in materials listed under section Prior art. Fortunately, only a handful of functions, namely higher-order functions, will surface this distinction, so the impact of the semantics and syntax is very limited compared to the clear benefits it provides for the users, as well as the soundness and performance of the typechecker. ### Current ad-hoc *conditional* effects Without the proposed way of supporting effect polymorphism, the above snippet would need to be expressed like this: ``` <<__CanIO, __AtMostIOAsArgs>> function handle_messages( vec<string> $msgs, <<__CanDisk, __AtMostIOAsFunc>> (function(string): void) $log ): void { ... } ``` Besides annotation burden, this clearly does not scale in terms of implementation effort because each use case of capability *Cap* necessitates special handling of a brand new set of attributes such as: *AtMost{Cap}AsArgs, AtMost{Cap}AsFunc, Only{Cap}IfImpl*, etc. If encoded with the old (current) system, the same challenge applies for every new effect domain or contextual information propagation. ## Subtyping Current use cases that would be superseded by capabilities, notably reactivity/purity, specially type-check function calls and methods, by checking if a function (or method) can soundly call another (or override, respectively). This challenge is often phrased as “calling conventions”. With the newly proposed system, one could also instead rely solely on the subtyping of capabilities, considering implicit parameters are in *covariant* position. The desired behavior would simply “fall out” from normal typing rules, provided that capabilities are treated as the last/first argument in the typechecker: ``` function handle_messages( vec<string> $msgs, (function(string)@{CanIO}: void) $log ): void { ... } function pure_context(): void { handle_messages(vec["a", "b"], // absence of capability is same as top type // note: {} is equivalent to {CanNothing} (string $msg)/*@{}*/ ==> {}); } function disk_context()@{CanDisk}: void { handle_messages(vec["a", "b"], // ok: function(string){CanDisk}:void <: function(string){CanIO} // because CanIO <: CanDisk log2disk); } ``` However, such *monomorphic* handling is *not* fine-grained — it doesn’t tell much about what precise effects the `handle_messages` function can make besides “any IO effect”, which is equivalent bottom type for this particular capability lattice of IO effects. Introducing generics for capabilities would not only complicate inference without solving the problem, but it would also introduce a large cognitive overhead & burden for the Hack users, as section Prior art (and associated literature) confirm: ``` function handle_messages<C super CanIO>(vec<string> $msgs, (function(string)@{C}: void) $log ): void { ... } ``` # User experience ## Syntax This proposal by itself doesn’t require any changes to the parser. The `<<__Contextful>>` attribute would just be specially interpreted by the typechecker. The rest are just typechecker changes that impact the developers of Hack. To decouple this proposal from others, this proposal uses a self-contained *desugared* syntax as explained above. To repeat, the `@{Capability}` part is *not* the user syntax and neither is the `__Contextful` attribute — it is just the way how typechecker sees the signatures of functions and methods. All syntax used in this proposal is for explanatory purposes and a future HIPs on contexts and reactivity/purity will explain the *new* syntax and how it maps to the implicit capabilities in this proposal. ## Semantics The Hack users will need to be aware that capturing a capability from a lambda makes it more restrictive. In the [FLiu’16-17] such *contextful* functions are referred to as non-stoic/free/impure. Conversely, stoic functions cannot capture a capability but *can* require some. In [OOPSLA’16], contextful functions are treated as 2nd-class, similar to procedures in Algol and Pascal but still less restrictive. This proposal calls for distinguishing stoic/monomorphic functions vs contextful/polymorphic functions at the *type* *level*. E.g.: ``` function higherOrder( (function(): int) $monoStoicAndPure, (function()@{CanThrow}: int) $monoStoic, <<__Contextful>> (function(): int) $poly, <<__Contextful>> (function()@{CanNonDet}: int) $poly2, ): void ``` While the syntax can be massaged so that this distinction is opaque at a syntactic level, users do need to be aware of the semantics. The first 2 argument functions are stoic, meaning that they cannot close over (capture) a capability. The last 2 argument functions are not; they are effect-polymorphic in a sense that they represent a computation created with *arbitrary context*, thus capturing any number of capabilities. Here is an example of passing each kind of argument function: ``` function throwingIOstuff()@{CanThrow,CanIO}: void { higherOrder( /*$monoStoicAndPure=*/() ==> 42, /*$monoStoic=*/ ()@{CanThrow} ==> throw/*{CanThrow}*/ new Exception(), /*$poly=*/() ==> fopen("/non/existing/file")/*{CanThrow}*/ ->readInt()/*{CanIO}*/, /*$poly2=*/()@{CanNonDet} ==> randomUpTo(2)/*{CanNonDet}*/ + Console\readInt()/*{CanIO}*/, ); ) ``` In fact, implicitly passed capabilities are a restricted form of *coeffects.* ### Implicit arguments as coeffects To understand the need for imposing restrictions on capability-capturing lambdas, it helps to illustrate how implicit parameters behave. They can be bound at either *declaration* site and *call* site, e.g.: ``` function nondeterministic_context()@{NonDet}: void { // capability captured by the lambda that has no context $decl_site_bound = () ==> randomUpTo(1)/*{NonDet}*/ } function deterministic_context()@{}: void { // capability required at each call site $call_site_bound = ()@{NonDet} ==> randomUpTo(2)/*{NonDet}*/ ... } ``` The former may be fine for certain (future) use cases, perhaps environments, but requires careful consideration. If we allowed this for effect capabilities, this could lose track of effects if the capability escapes: ``` function wrap_random_as_deterministic( )@{NonDet}: (function(): int) { return () ==> randomUpTo(1)/*{NonDet}*/ } void nondeterministic_context(...)@{NonDet}: void { $some_class->property = wrap_random_as_deterministic() } void deterministic_context(...): void { ($some_class->property)() // leak } ``` but the soundness ultimately depends on whether: * capabilities can ever be introduced “out of thin air” akin to *unsafe* blocks in Rust or *FIXMEs* in Hack; and * lifetime of a capability can be extended beyond declaring *scope.* ### Implicit capabilities as effects Therefore, capability-based effect systems implemented in a host language where capabilities are first-class, i.e., regularly typed variable, need to reintroduce some restrictions. Two such systems are [FLiu’16-17] and [OOPSLA’16] as the section Prior arts explains. The former is a simpler but more restrictive option, quoting key bits from Section 3: > we need to change the definition of the function pure to **exclude > free function types from the pure environment**. This restriction is > important, because there’s no way to know what side effects there > might be inside free functions. **If stoic functions have access to > free functions, we’ll loose the ability to track the effects of > stoic functions in the type system.** Porting the former system to Hack would mean treating all functions as non-stoic/impure initially, allowing them to capture capabilities. The latter system is implemented in Scala, with capability being represented as implicit parameters, therefore it reimposes a *2nd-class* value discipline (the challenge is also known as the [funarg problem](https://en.wikipedia.org/wiki/Funarg_problem)) on such capabilities as well as capability-capturing functions. The [[OOPSLA’16]](https://dl.acm.org/doi/pdf/10.1145/2983990.2984009) paper describes the rationale on pages 1-2: > Second-class values in the sense of ALGOL have the benefit of > following a strict stack discipline (“downward funargs”), i.e., they > cannot escape their defining scope. This makes them **cheaper to > implement** ... Since **first-class object**s may escape their > defining scope, they **cannot be used to represent static > capabilities** or access tokens – a task that second-class values > are ideally suited to because they have bounded lifetimes and they > have to “show up in person”. Porting that to Hack would mean: * treating capability-capturing lambdas (e.g., `$decl_site_bound`) as 2nd-class, preventing them from being: * stored in a property; or * returned (to be reconsidered, see end of previous subsection). (Some of these restrictions are reconsidered under Unresolved questions.) In either porting direction, we would need to: * gradually change some functions to track effects via capabilities desugared from the old attribute syntax or the new context syntax; * work around restrictions reimposed for soundness by over-approximating effects, e.g., implicitly desugaring some attributes or functions to have `CanEverything` capability. As the following snippet demonstrates, this latter approach is more expressive in a sense that we can still pass around such contextful (impure) function. ``` function nondeterministic_context()@{NonDet nondet}: void { // note: $get_int is no longer 1st-class $get_int = () ==> randomIntUpTo(5){nondet}; // it can still be passed around safely nonetheless eagerly_call($get_int); } function eagerly_call(<<__Contextful>> (function(): int) $f) { $f(); ... } ``` However, the treatment of capabilities as non-1st-class (`<<_Contextful>>`) correctly disallows untracked effects. ``` new Store($get_int) // ERROR: expected stoic but got contextful ... class Store { function __construct(public (function():int) $callback) { ... } // note: omitting the attribute wouldn't allow passing a stoic function function store(<<__Contextful>> (function(): int) $f) { this->$callback = $f; // ERROR: expected stoic got contextful fun. } } ``` Note that we do not need to expose the 2nd-class terminology to the users, we can just explain how contextful functions are different from stoic functions, which is needed for adopting either of the two approaches! # Implementation details For most use cases, we wouldn’t require support in the runtime. As an example, reactivity and purity of functions is already tracked with a special bit in HHVM, so they don’t need to rely on having runtime values for implicit capabilities/contexts. Consequently, capabilities can be tracked purely *statically*, and the run-time does not need to know about the existence of implicit parameters — unless we decide to unify it with a pending HHVM proposal on implicit contexts. The feature can be implemented in the typechecker in several mostly *non-overlapping* phases: 1. implement distinction between regular (stoic) lambdas and effect-polymorphic/contextful ones (the distinction is also needed for alternative #1) 2. implement desugaring of contextful functions (those that can capture capabilities) passed to *higher-order* functions as 2nd-class or impure/non-stoic: 1. either via an existing attribute syntax 2. or a new *contexts* syntax, to be proposed in a separate HIP; 3. modify the typechecker environment to also carry capabilities (multiple, or a single one using an intersection type) 4. modify the typing rule for function application to check if the required capability is available in the (implicit) context; Once phase 2 is finished, we should add these annotations to WWW, which would allow for smoke-testing phases 3.-4. (as well as 1.). As a part of phase 2, we may need to implement a subset of functionality of 2nd-class values, but this is a relatively easy task: * built in 2 days during a Hackathon (even with user syntax that is not needed here); * also implemented and tested in another language, Scala in *only* [**400 lines**](https://github.com/losvald/scala/blob/3070ee4931f0429a80a517a0c167028ed3e5865d/src/compiler/scala/tools/nsc/typechecker/EscLocal.scala#L65) in typechecker & [10 lines](https://github.com/losvald/scala/blob/9495ebca55f712ae3459fe5eb86ffab2477fde8a/src/library/scala/Esc.scala) in standard library (see section Prior art for details) For prototyping & unit-testing, we actually also modified the parser to support parsing Concrete Syntax Tree directly into capabilities, but that should obviously be gated so that WWW cannot use it / be aware of this exploit. ### Encoding multiple capabilities Multiple capabilities that express permissions to make effect in multiple domains (e.g., determinism, exceptions, reactivity, etc.), are encoded via an intersection type. E.g., `NonDet & Throwing` represents having *both* the capability for non-deterministic execution as well as the one for throwing exceptions, respectively. Since `NonDet & Throwing <: NonDet`, it satisfies the requirement of / privilege for non-deterministic execution. Intuitively, intersection gives the caller more privilege (not less) and soundly approximates multiple capabilities. Unannotated functions in Hack should implicitly have some default set of capabilities, at the very least the capability to call into non-deterministic code (including other unannotated functions or methods) and permit untracked mutation (such as global state), neither of which is allowed in reactive/pure code. Considering this simplified scenario, we encode this set of capabilities and give it a name using an intersection type. ``` type CanDefaults = (CanNonDet & CanMutateUntracked); ``` The benefit of using intersection type as opposed to interface inheritance is apparent considering a hypothetical call site that passes each of the comprising capabilities *separately*, e.g.: ``` // implicitly @{CanNonDet,CanMutateUntracked}=CanDefaults function randomBool(): bool { ... } class CachedNonDetFactory { private static ?seed = null; function withNonDetBool<T>()@{CanMutateUntracked}( (function ( <<__Contextful>> function()@{CanNonDet}: bool ): T) $continuation ) { return $continuation(()@{CanNonDet} ==> { // captures the outer capability: required for mutating $seed self::$seed ??=/*{CanMutateUntracked}*/ currentUnixTime(); // passes the explicit as well as the captured capability randomBool()/*{(CanNonDet & CanMutateUntracked)}*/ }); } } ``` Conversely, if we relied on *nominal subtyping* and defined ``` interface CanDefaults extends CanNonDet, CanMutateUntracked {} ``` then the call to `randomBool` would result in a typing error because `CanNonDet & CanMutateUntracked` would *not* be a subtype of `CanDefaults` anymore. ### Default capabilities as an unsound migration mechanism The capability passing as described so far is essentially the same as implicit parameter passing in several other languages. ``` function randomUpTo(int $n)@{CanNonDet}: int ``` would be modeled in Scala as follows: ``` def randomUpTo(n: Int)(implicit $_: CanNonDet): Int ``` An interesting question arises: what if we make some capabilities optional; i.e., provide a default for the corresponding implicit parameter? This is surely unsound for effect tracking as the capability is no longer required at the call site; in fact, it is a means of obtaining the corresponding privilege "out of thin air". In a language with *default* implicit parameters such as Scala, this would be written as: ``` def randomBoolUnsafe()(implicit $_: CanNonDet = new CanNonDet {}): Int ``` In Hack, we express this using by enhancing our prototypical syntax as follows: ``` // requires: {} (no capability, i.e., can always be called) // provides: {CanNonDet} function randomBoolUnsafe()@{ +CanNonDet}: void { ... } ``` where the part following `+` in the braced list (`{}`) after `@` denotes the *unsafe* (i.e., provided but not required) capability. ## Feature interactions This feature would supersede the special-cased (ad-hoc) logic for type-checking reactive and pure functions. ### Dependent types The expressibility would be greater if Hack adopted path-dependent types, see Unresolved questions below. ### Reification & HHVM implicit contexts Ideally, this should influence the design of HHVM’s proposed but put “on hold” feature of implicit contexts because it would be nice if we could one day unify these two via reification: * non-reified capabilities → only static enforcement in the typechecker; * reified capabilities → also run-time inspection/retrieval of the corresponding context. See the section Future possibilities for more details. # Design rationale and alternatives Implicit parameters offer expressiveness that can be hardly surpassed by any other feature. Therefore, it’s better to compare alternatives for problems solvable via implicit parameters, most notably effects. ### Alternative #0: special tags + ad-hoc typechecking logic This is mostly similar the how the current typechecker reasons about reactivity. There is an extra step in typing functions and their call sites, which examines the tags and validates the rules. However, this means that subtyping, for example, needs to be special-cased for each of these reactivity-like tags. Second, many attributes behave specially and have to be carefully handled at several stages in parsing & type-checking. Third, this is complicated by fact that we support what is known as *conditional* reactivity, i.e., a function is reactive only if its argument function is reactive or a subclasses are known to be reactive. This clearly doesn’t scale in terms of implementation and complexity (due to special cases) as soon as one introduces new form(s) of “context” — essentially new (co)effects: * purity — cannot call `Rx\IS_ENABLED`, but otherwise stricter than `Rx`; * IO (e.g., from data source / or to sinks); * non-determinism and parallelism; * async, as well as sync (immediately awaited async call); * contexts that restrict the flow of (sensitive) data; * exceptions? There is a general consensus to move away from this verbose and overly restrictive syntax. For the alternatives below, the new syntax for reactivity and purity — or *contexts* in general — would be *desugared* into more *reusable and well-known primitives*. This would solve the major challenge of the current approach — each “domain” of (conditional) context needs a special type-checking logic that is not well-integrated with the rest of the type system, as well as propagation through different stages (bug-prone and inflexible). ### Alternative #1: type-and-effects systems This is the oldest and most common way of encoding effects. Some early paper(s) point out different challenges in sound and not overly restrictive approximation of runtime behavior (especially using constraint-based solvers?). The main disadvantage of this approach is that it is *quite invasive* — nearly every typing rule would need to be modified — and effects carried in the typechecker. The latter may lead to significant performance overhead, and the former is also less than ideal in terms of implementation cost & maintenance effort, as well as overall complexity, of the typechecker code. The current proposal requires far *fewer* modification to typing rules; *only* function call needs to read from the (implicit) capability context, and *only* function declarations add to it. Conversely, type-and-effect systems require a type in *every* position to be associated with an effect (as it can potentially be a function that makes an effect). The trade-off is somewhat similar to that of virtual dispatch via: - vtable (context per class) -> additional capability context is looked up per each function call; - [fat pointer](https://en.wikipedia.org/wiki/Dynamic_dispatch#Fat_pointer) (every pointer is *doubled* in size) -> encoding of a type is bloated by being *paired* with an effect. Since virtual dispatch in languages with a virtual machine and JIT has negligible performance overhead (unlike statically compiled ones), the performance impact on the typechecking is expected to be minimal. ### Alternative #2: monad-based encoding In [POPL’18], Martin Odersky et al have found that monadic encoding of “freer” monad suffered [5x performance hit](https://dl.acm.org/doi/pdf/10.1145/3158130#page=22) compared to encoding via implicit parameters. This was done in Scala, where implicit arguments carry slight run-time overhead, meaning that implementing a subset of implicit parameters functionality that doesn’t require run-time mechanism in Hack would lead to even bigger performance wins compared to wrapping types in monads. ### Alternative #3: algebraic effects Based on my high-level understanding of the relatively few papers that talk about it: * `+` provide a modular way for customizing effect handling * `-` not rigorously verified via large case studies for usability & performance; * `-` requires special treatment in [IR](https://dl.acm.org/doi/pdf/10.1145/3341643)/VM to efficiently do [CPS translation](https://dl.acm.org/doi/pdf/10.1145/1291151.1291179) (not so practical without invading into HHVM internals) Even if we invested a lot into building the support for *efficient* translation to Continuation Passing Style (CPS), which does not look trivial at all (see Andrew’s [ICFP’07] paper), we would need to perform more “testing in the wild” as these approaches do not have comparable user & performance studies, unlike capability-based (co)effect systems. Finally, the most well-known approach, published in [ICFP’13](https://dl.acm.org/doi/pdf/10.1145/2500365.2500581), is *not* entirely static and require dependent types; and another practical candidate ([Effekt @ Scala’17](https://dl.acm.org/doi/pdf/10.1145/3136000.3136007)) requires multi-prompt delimited continuations, which would in turn be inefficient as delimited continuations correspond to monads (see above why monads are inefficient). Fortunately, representing effects using a type lattice is both flexible and modular. Please refer to above examples and read details can be found in [ECOOP’12] and [OOPSLA’16] papers in section Prior Art. ## Impact to Hack users & WWW This proposal does *not* expose implicit arguments as 1st-class language feature; so Hack users: * *cannot* pass arbitrary values/contexts implicitly; * do *not* need to know that contexts, such as (shallowly/locally) reactive or deterministic, would be from a type-checking perspective propagated just like implicit arguments. Nonetheless, it does help to create a mental model behind each use case, by generally describing that: * contexts internally map to capabilities/permissions to do stuff; * they are propagated in a similar fashion as implicit arguments in Scala and Haskell. The latter would actually help Hack developers with some experience in either programming language. Impact to the average WWW developer is negligible, but power users may want to know: 1. the rationale for effect-polymorphic functions, explicable to Hack developers using “conditional” effect examples; 2. that the syntax for reactive/pure contexts internally desugars to implicit parameters; 3. *optional*: new “capability type” if we need to support advanced use variable-context class hierarchies (see section Unresolved questions). (1.) is a small price to pay that would allow us to eliminate annotation boilerplate present. However, this is something that even alternative approaches require (see section Prior art). Regardless of the implementation direction (i.e., whether capability capturing is restricted or requires 2nd-class treatment), we will need to translate user-facing annotations on higher-order functions into either effect-polymorphic/2nd-class or monomorphic functions. As of June 2020, it seems that only about a thousand function signatures involve higher-order functions that would require this new type of annotation(s). Verified via bunnylol: `tbgs (function(` *Only* the Hack developers will care about: * capability lattice that enforces *calling convention* for each types of contexts such as reactive, non-deterministic, etc., (each type corresponds to a use case of implicit arguments internally); # Drawbacks I think we should support a foundation for capability-tracking (co)effects, but the question is how many of the subfeatures should be present: * for prototyping, exposing the syntax for ad-hoc in Concrete Syntax Tree but gating that parser feature; * exposing capabilities as types in user code (see section Unresolved questions); * 2nd-class treatment of capability-capturing functions vs disallow capturing capabilities from stoic functions (the former is similar to how functions in Pascal/Algol behave, see [OOPSLA’16]). # Prior art Implicit parameters are a concrete instance of a [coeffect](http://tomasp.net/academic/papers/coeffects/coeffects-icalp.pdf#page=3) system, and coeffects are more general than effects (mathematically, they correspond to indexed comonads as opposed to monads, see [ICALP’13, JENTCS’08]). They have been widely accepted as an essential feature of Scala; in fact a study show that >90% repositories on GitHub use them (see [Conclusion in [POPL’18]](https://dl.acm.org/doi/pdf/10.1145/3158130#page=26)). Haskell also supports them ([link](https://www.haskell.org/hugs/pages/users_guide/implicit-parameters.html)), albeit in a somewhat more restricted form. In [ScalaDays’15], M. Odersky, the designer of Scala (and a top-notch PL researcher), pioneered the idea of using implicit *capabilities* for modeling *permissions*. Implicit parameters are already a feature in Scala since v2, and overhead of using implicits has been evaluated on a large corpus of real-world code in [POPL’18], shown to perform **5x faster than monads**. Leo's [OOPSLA’16] work has won the Distinguished Artifact Award; it designs, machine-proves and implements a *capability-based (co)effect* system using second-class values (they give more expressiveness compared to the similar approach of Fengyun Liu). It also evaluates the annotation burden — relevant for our code-mod — showing that **<2% of code changed** in Scala Standard Library has to be changed to propagate effects (checked exceptions, parallelism). The second author of [OOPSLA’16], G. Essertel has machine-proved in Coq: * [Simply-Typed Lambda Calculus (STLC) with 2nd-class values (1/2)](https://github.com/TiarkRompf/scala-escape/tree/master/coq#coq-proofs-for-stlc-12); * [System D **with subtyping** (~Scala\{DOT}) and 2nd-class values](https://github.com/TiarkRompf/scala-escape/tree/master/coq#coq-proofs-for-dsub-12). (System D with subtyping has been proven sound by Tiark Rompf and Nada Amin in [*another* OOPSLA’16 paper](https://dl.acm.org/doi/pdf/10.1145/3022671.2984008).) Fengyun Liu has built a similar but somewhat simpler capability-based effect system in his PhD dissertation [FLiu’16-17]. The two simplifications compared to [OOPSLA’16] are (the analogy is parenthesized): * *effect-tracking* (non-stoic) lambdas *cannot capture* capabilities (as opposed to being treated 2nd-class); * capability parameters are *explicit* (less practical for users & code mod); He also machine-proved in Coq his approach generalized to STLC, System F and System D on [GitHub](https://github.com/liufengyun/stoic#stoic). The common practical challenge of effect systems is known as *effect polymorphism*, initially described in [POPL’88]. Papers [ECOOP’12, RytzOdersky’12] show how to encode effects as lattice in a modular way, and more importantly show how to *annotate higher-order* functions in a lightweight way that supports effect polymorphism. The importance of providing effect polymorphism without heavyweight annotations has been reiterated by a recent work on *gradual* polymorphic effects in [OOPSLA’15]: > effect polymorphism, which is crucial for handling common > higher-order abstractions with enough precision who implemented [Effscript](https://pleiad.cl/research/software/effscript) as a Scala plug-in after extending the theory of [ECOOP’12] (also implemented as a Scala plug-in). Annotating signatures of higher-order functions is “**common denominator**” to all of the approaches above that support effect polymorphism, namely: [OOPSLA’16], [FLiu’16-17], [ECOOP’12], [RytzOdersky’12]. This is also consistent with Hack’s more verbose solution for conditional reactivity, which is just a verbose version of effect polymorphism for the reactivity effect (or in coeffect sense, a capability for accessing reactive backend). One of the most practical promising alternative to this proposal, which is along the lines of [OOPSLA’16] and [FLiu’16-17], is the type-and-effect system presented in [RytzOdersky’12] and [Rytz’14], implemented in [EffScript’15], with the idea original idea originating from [ECOOP’12]. However, the ergonomic treatment of “relative declaration” requires *dependent* function types as [[Rytz’14] §3.2](https://lrytz.github.io/download/thesis-rytz.pdf#page=54) points out, and its implementation is quite complexed judging from [EffScript’15]. Fortunately, *both* the current proposal and their approach require the **distinction between** *effect-polymorphic* vs *monomorphic* functions, which confirms that this should be a milestone on its own. [ImplicitsRevisited'19] explains design mistakes of Scala 2 implicits and reveals how they are being fixed in Dotty and soon in Scala 3. The current proposals avoids a lot of these by not exposing the feature as a first-class language construct and instead ports only a *tiny* subset of the Scala's behavior specifically suited for passing contextual information and enforcing calling conventions (but *not* for type classes). ## References: Most related work was implemented as extensions of Scala, but there’s also Haskell and others (E-lang, EffScript). * ScalaSpec: [Scala Language Specification](https://www.scala-lang.org/files/archive/spec/2.11/) (M. Odersky et al.) * **ScalaDays’15**: [**Scala** - where it came from, where it is going](https://www.slideshare.net/Odersky/scala-days-san-francisco-45917092) (M. Odersky), pages 44-46 * **POPL’18**: [Simplicitly](https://dl.acm.org/doi/pdf/10.1145/3158130) (M. Odersky et al.) * **OOPSLA’16**: [...Affordable 2nd-Class Values for Fun and **(Co-)Effect**](https://dl.acm.org/doi/pdf/10.1145/2983990.2984009) (Leo Osvald et al.) * https://www.dropbox.com/s/iag4gho34ewzk57/OOPSLA16-coeffects_code-changes%2Bresults_README.pdf?dl=1 * https://github.com/losvald/scala/compare/2.11.x...losvald:esc#files_bucket * https://github.com/TiarkRompf/scala-escape/tree/master/coq#coq-proofs-for-dsub-12 * **FLiu’16-17**: [A Study of Capability-Based Effect Systems](https://infoscience.epfl.ch/record/219173?ln=en) (Fengyun Liu), PhD dissertation * https://github.com/liufengyun/stoic#stoic * https://github.com/liufengyun/stoic/tree/master/2017 * **Haskell’16**: [Effect capabilities for Haskell](https://www.sciencedirect.com/science/article/pii/S0167642315004062#br0170) (Figueroa, Tabareau, Tanter) * Elang‘98: [The E language](http://erights.org/elang/index.html) (M.S. Miller) * EffScript’15: [EffScript](https://pleiad.cl/research/software/effscript) (authors of [OOPSLA’15] below) * ImplicitsRevisited'19: [Lambda World 2019 - Implicits Revisited](https://www.youtube.com/watch?v=uPd9kJq-Z8o) (M. Odersky) * **SID-1**: [Scala Named and Default arguments](https://docs.scala-lang.org/sips/named-and-default-arguments.html) (L. Rytz), subsection Implicit parameters * **ECOOP’12**: [Lightweight Polymorphic Effects](http://www.lirmm.fr/~ducour/Doc-objets/ECOOP2012/ECOOP/ecoop/258.pdf) (Rytz, Odersky, Haller) * RytzOdersky’12: [Relative Effect Declarations for Lightweight Effect-Polymorphism](http://infoscience.epfl.ch/record/175546/files/rel-eff_1.pdf) (L. Rytz & M. Odersky) * Rytz’14: [A **Practical** Effect System for Scala](https://lrytz.github.io/download/thesis-rytz.pdf) (L. Rytz), PhD dissertation * OOPSLA’15: [Customizable **Gradual** Polymorphic Effects for Scala](https://dl.acm.org/doi/pdf/10.1145/2858965.2814315) (Toro & Tanter) * **ICALP’13**: [Coeffects: Unified static analysis of context-dependence](http://tomasp.net/academic/papers/coeffects/coeffects-icalp.pdf) (T. Petricek, D. Orchard, A. Mycroft) * ICFP’14: [Coeffects: A calculus of context-dependent computation](http://tomasp.net/academic/papers/structural/coeffects-icfp.pdf) (T. Petricek, D. Orchard, A. Mycroft) * OrchardTalk’14: [Coeffects: contextual effects / the dual of effects](https://www.cs.kent.ac.uk/people/staff/dao7/talks/coeffects-dundee2014.pdf) (D. Orchard, T. Petricek, A. Mycroft) * OrchardPhD’14: [Programming contextual computations](https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-854.pdf) (Dominic Orchard), PhD dissertation * ICFP’07: [Compiling with Continuations, Continued](https://dl.acm.org/doi/pdf/10.1145/1291151.1291179) (Andrew Kennedy) * ICFP’19: [Compiling with Continuations, or without? Whatever.](https://dl.acm.org/doi/pdf/10.1145/3341643) (Y. Cong, Leo Osvald, G. Essertel, T. Rompf) * Scala’17: [Effekt: Extensible Algebraic Effects in Scala](https://dl.acm.org/doi/pdf/10.1145/3136000.3136007) (Brachthäuser & Schuster) * ICFP’13: [Programming and Reasoning with Algebraic Effects and Dependent Types](https://dl.acm.org/doi/pdf/10.1145/2500365.2500581) (E. Brady) * DOT’16: [Type Soundness for Dependent Object Types](https://www.cs.purdue.edu/homes/rompf/papers/rompf-oopsla16.pdf) (Tiark Rompf, Nada Amin) * POPL’88: [Polymorphic Effect Systems](https://dl.acm.org/doi/pdf/10.1145/73560.73564) (Lucassen & Gifford) * Talpin‘94: [Type and Effect Discipline](https://www.sciencedirect.com/science/article/pii/S0890540184710467) (Talpin & Jouvelot) * JENTCS’08: [**Comonad**ic notions of computation](https://www.sciencedirect.com/science/article/pii/S1571066108003435) (Uustalu & Vene) # Unresolved questions ## Encoding capabilities as (dependent) types This is something that would be needed to cleanly model partially reactive class hierarchies (see Future possibilities). ``` class SometimesContextful { type CanDo function do()@{CanDo}: void } class NeverRequiresContext extends SometimesContextful { type CanDo function do()@{}: void { ... } } class AlwaysContextful extends SometimesContextful { <<__Override>> type CanDo = CanStdIO function do()@{CanDo}: void { print("stdout")/*{CanStdio}*/; // ok: CanDo <: CanStdio } } ``` However, dispatching on such partially contextful class hierarchies requires dependent types: ``` // generic T would be exposed to users, unfortunately function maybe_contextful_do<T as SometimesContextful>( T $maybe_contextful )@{ C = $maybe_contextful::CanDo // path-dependent (OK) // C = T::CanDo // error, no way to prove that type C is matching }: void { maybe_contextful->do() } ``` It seems that this could be modeled via Pocket universes, which offer enum-dependent types, albeit that would require the capability definitions to be expressed via corresponding enum fields for each class in the hierarchies, which may not be practical at all. **Q: Considering such uses cases are fairly common in WWW, should we generalize dependent types and/or pocket universes?** ## Interaction with lazy collections This is somewhat related to the above, and has been extensively studied in [OOPSLA’16] (see Prior Art). The gist of it is shown by the following snippet: ``` class Iterable<T> { type MaybeContextful; // used as meta-attribute function map<T, U>( <<MaybeContextful>> (function(T): U) $f): Iterable<U> } class Vector<T> extends Iterable<T> { type MaybeContextful = __Contextful; <<__Override>> function map<T, U>( <<MaybeContextful>> // = __Contextful (function(T): U) $f): Iterable<U> } class Iterator<T> extends Iterable<T> { type MaybeContextful = Nothing; <<__Override>> function map<T, U>( // = no attribute (accepts pure functions only!) (function(T): U) $f): Iterable<U> } ``` Note that lazy collections such as subtypes of `Iterator` don’t call argument function `$f` immediately, they could delay effects, therefore we don’t want to permit capturing capabilities in their argument functions passed to `map`. E.g.: ``` function would_hide_effect( Iterator<int> $iter )@{CanNonDet}: Iterator<int> { return $iter->map( // error: expected contextless (stoic) function // but the passed lambda captures a capability (int $x) ==> $x + randomUpTo(1)/*{CanNonDet}*/ ); } ``` **Q: Is this a better way, or we should stick with alternatives by exposing capabilities as generics (see previous subsection)?** ## 2nd-class/restricted treatment of closures One can argue that we may not actually need to treat capability-capturing closures as 2nd-class. The supporting argument could go along these lines: * a context (requiring a capability) that once exists cannot disappear; e.g.: * the (sub)request has access to reactive backend or it doesn’t * execution context is either deterministic or non-deterministic * a function *cannot* introduce new permissions, it can just opt-out of certain permissions by not requiring certain capabilities; * there is no scope-like facility to introduces a capability type; * capabilities are not exposed as user types; The last 2 points were the primary motivation for a conservative treatment of capability-capturing closures as 2nd-class in [OOPSLA’16] or impure in [FLiu’16-17] , and also makes the system more generic (if the first 2 points do not hold). **Q: Is semi 1st-class treatment of capabilities sound and sufficiently general for our *all* our use cases?** # Future possibilities Implicit parameters are one of the simplest forms of coeffects; i.e., a “flat” type-and-coeffect system as introduced in the [ICALP’13 paper](http://tomasp.net/academic/papers/coeffects/coeffects-icalp.pdf#page=3). The prefix co- stands for **co**ntextual properties and it’s also essentially a dual of effects (see [slides](https://www.cs.kent.ac.uk/people/staff/dao7/talks/coeffects-dundee2014.pdf#page=8)). That means that other language features could be expressed using implicit arguments under the hood, notably: * reactive and pure **contexts** * generic **effects** (by limiting the escaping of capabilities through declaration site, see above) * **modules & features** (contextual by definition): (non-)experimental and opt-in features ## Remodel reactivity flavors There is a one-to-many mapping between reactivity (including purity) attributes and implicit parameters, e.g.: * `<<__Pure>>` → `@{CanThrow}` or `@{mixed}` if exceptions untracked * `<<__Rx>>` → `@{CanRx}` * `<<__RxShallow>>` → `@{CanRxShallow, ...}` The *calling conventions* are enforced by design if these capabilities are organized into a type lattice as follows: ``` CanRxShallow <: CanRx <: CanThrow ``` Intuitively, the more specific the capability type, the higher the privilege; also some examples: ``` function rx_context()@{CanRx}: void {} function rx_calling_into_others()@{CanRx}: void { // ok: CanRxLocal <: CanRxShallow rx_context()/*{CanRx}*/ // error: CanRxShallow not a subtype of CanRx rx_shallow_context()/*{CanRx}*/ pure_context(); // ok: capability either not passed (mixed) or pure_context()/*{CanRxLocal}*/ // passed as a subtype of CanThrow } ``` Treating pure functions as not having implicit arguments is attractive from a performance standpoint (typechecker doesn’t need to do extra work for pure functions), but it is too conservative because pure functions in the reactive sense do allow certain other kind of non-conflicting effects such as throwing an exception. ## HHVM’s implicit context as reified capability Ideally, this should somewhat influence the design of HHVM’s proposed but postponed because it would be nice if we could one day unify these two via reification. Some contexts are reified by default such as reactive ones (tracked via a few bits at run-time), but we may want to start tracking certain kind of effects statically in the typechecker and avoid breaking changes to the run-time/VM. The way to do it mark some contexts/capabilities as non-reified (*internally* in the typechecker, since there is a finite number of them). E.g.: ``` function with_implicit_context()@{ ContextOrCapabilityForUseCase1, reify ContextOrCapabilityForUseCase2, }: void { // context $ctx2 is available at run-time } ``` The main benefit of such unification include: * reified capabilities are *always* part of memoization key (since they are available at run-time); * non-reified capabilities are *never* part of the memoization key; which hopefully neatly solves the dilemma about impact on performance and/or correctness of memoization, unblocking the path to finalize the semantics of implicit contexts. E.g.: ``` <<__Memoize>> function contextless(): void <<__Memoize>> // NOT part of memo. key as it isn't reified function throwing()@{CanThrowException}: void // exceptions aren't tracked at run-time <<__Memoize>> // IS part of memo. key as it is reified function reactive()@{reify CanRxIsEnabled}: void if (RX\IS_ENABLED/*{CanRxIsEnabled}*/) { ... } else { ... } } ``` In the last function, the `RX\IS_ENABLED` would require implicit capability when type-checking. Moreover, that capability should be reified as the function can run both within a disabled and enabled reactivity backend, therefore its result depends is dependent on the context. ## Modules & features Further, we could enforce some encapsulated code such as experimental cannot be called from a normal *module*, by desugaring these modules into capabilities: ``` // file1 module Normal; // Normal is a weaker capability than Experimental function calls_into_experimental()/*@{Normal}*/: void { // ERROR: the call requires capability: Experimental // but got capability: Normal // and Experimental is not a supertype of Normal // (i.e., the capability cannot be upcast) callee_in_experimental()/*{Normal}*/ } // file2 module Experimental; function callee_in_experimental()/*@{Experimental}*/ ``` with the following subtyping relationship for this domain of (co)effects: ``` Experimental <: Normal ``` Rules for which module can access which other module can be encoded by carefully organizing more capabilities into a subtyping, which allows for encapsulation similar to modules/packages in Scala/Java, respectively. Interestingly, fine-grained use of experimental features can also be enforced by requiring appropriate capabilities in a similar fashion, which is comparable to Rust's tracked usage of (unstable) features. For example, experimental features of union & intersection types would be modeled as requiring a file-local capability `CanUnionIntersection`, desugared from the file-level attribute: ``` <<file:__EnableUnstableFeatures('union_intersection_type_hints')>> ``` where the desugaring would simply inject the capability into the typing environment used when type-checking anything in that file (but not other files). ## Haskell-like type constraints From [[OrchardPhD’14] §6.5 (page 135+)](https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-854.pdf#page=135): > **Type constraints can be seen as a coeffect** describing the > contextual-requirements of an expression. ... This section goes > towards unifying coeffects and type constraints, which is used in > the next chapter to encode a coeffect system based on sets using > Haskell’s type class constraints. ... The coeffect approach > describes the implicit parameter requirements of a function as > latent coeffects, rather than constraints on the type in the > approach of Lewis et al.
HTML Help Workshop
hhvm/hphp/hack/hhi/attributes.hhi
<?hh // strict namespace HH { // class-like interface ClassLikeAttribute {} interface ClassAttribute extends ClassLikeAttribute {} interface ClassConstantAttribute {} interface EnumAttribute extends ClassLikeAttribute {} interface EnumClassAttribute extends ClassLikeAttribute {} interface TypeAliasAttribute {} // function-like interface FunctionAttribute {} interface MethodAttribute {} interface LambdaAttribute {} // modules interface ModuleAttribute {} // properties interface PropertyAttribute {} interface InstancePropertyAttribute extends PropertyAttribute {} interface StaticPropertyAttribute extends PropertyAttribute {} interface ParameterAttribute {} interface FileAttribute {} interface TypeParameterAttribute {} interface TypeConstantAttribute {} }
HTML Help Workshop
hhvm/hphp/hack/hhi/BuiltinEnum.hhi
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * BuiltinEnum contains the utility methods provided by enums. * Under the hood, an enum Foo will extend BuiltinEnum<Foo>. * * HHVM provides a native implementation for this class. The PHP class * definition below is not actually used at run time; it is simply * provided for the typechecker and for developer reference. */ abstract class BuiltinEnum<+T> { /** * Get the values of the public consts defined on this class, * indexed by the string name of those consts. * * @return darray['CONST_NAME' => $value, ...] */ <<__NoAutoDynamic>> final public static function getValues()[]: darray<string, T>; /** * Get the names of all the const values, indexed by value. Calls * invariant_exception if multiple constants have the same value. * * @return darray[$value => 'CONST_NAME', ...] */ <<__NoAutoDynamic>> final public static function getNames()[]: darray<T, string> where T as arraykey; /** * Returns whether or not the value is defined as a constant. */ <<__NoAutoDynamic>> final public static function isValid(mixed $value)[]: bool; /** * Coerce to a valid value or null. * This is useful for typing deserialized enum values. */ <<__NoAutoDynamic>> final public static function coerce(mixed $value)[]: ?T; /** * Coerce to valid value or throw UnexpectedValueException * This is useful for typing deserialized enum values. */ <<__NoAutoDynamic>> final public static function assert(mixed $value)[]: T; /** * Coerce all the values in a traversable. If the value is not an * array of valid items, an UnexpectedValueException is thrown */ <<__NoAutoDynamic, __SupportDynamicType>> final public static function assertAll( Traversable<mixed> $values, )[]: Container<T>; } type enumname<T> = classname<BuiltinEnum<T>>; const enumname<arraykey> BUILTIN_ENUM; /** * Wrapper for enum class */ newtype MemberOf<-TEnumClass, +TType> as TType = TType; /** * BuiltinAbstractEnumClass contains the utility methods provided by * abstract enum classes. * * HHVM provides a native implementation for this class. The PHP class * definition below is not actually used at run time; it is simply * provided for the typechecker and for developer reference. */ <<__EnumClass>> abstract class BuiltinAbstractEnumClass { final public static function nameOf<TType>( \HH\EnumClass\Label<this, TType> $label, )[]: string; } /** * BuiltinEnumClass contains the utility methods provided by enum classes. * Under the hood, an enum class Foo : Bar will extend * BuiltinEnumClass<HH\MemberOf<this, Bar>>. * * HHVM provides a native implementation for this class. The PHP class * definition below is not actually used at run time; it is simply * provided for the typechecker and for developer reference. */ <<__EnumClass>> abstract class BuiltinEnumClass<+T> extends BuiltinAbstractEnumClass { /** * Get the values of the public consts defined on this class, * indexed by the string name of those consts. * * @return array ('CONST_NAME' => $value, ....) */ final public static function getValues()[write_props]: darray<string, T>; final public static function valueOf<TEnum super this, TType>( \HH\EnumClass\Label<TEnum, TType> $label, )[write_props]: MemberOf<TEnum, TType>; } }
HTML Help Workshop
hhvm/hphp/hack/hhi/builtins_fb.hhi
<?hh /* -*- php -*- */ namespace { const int FB_UNSERIALIZE_NONSTRING_VALUE; const int FB_UNSERIALIZE_UNEXPECTED_END; const int FB_UNSERIALIZE_UNRECOGNIZED_OBJECT_TYPE; const int FB_UNSERIALIZE_UNEXPECTED_ARRAY_KEY_TYPE; const int FB_UNSERIALIZE_MAX_DEPTH_EXCEEDED; const int FB_SERIALIZE_HACK_ARRAYS; const int FB_SERIALIZE_HACK_ARRAYS_AND_KEYSETS; const int FB_SERIALIZE_VARRAY_DARRAY; const int FB_SERIALIZE_POST_HACK_ARRAY_MIGRATION; const int FB_COMPACT_SERIALIZE_FORCE_PHP_ARRAYS; const int SETPROFILE_FLAGS_ENTERS; const int SETPROFILE_FLAGS_EXITS; const int SETPROFILE_FLAGS_DEFAULT; const int SETPROFILE_FLAGS_FRAME_PTRS; const int SETPROFILE_FLAGS_CTORS; const int SETPROFILE_FLAGS_RESUME_AWARE; /* This flag enables access to $this upon instance method entry in the * setprofile handler. It *may break* in the future. */ const int SETPROFILE_FLAGS_THIS_OBJECT__MAY_BREAK; const int SETPROFILE_FLAGS_FILE_LINE; const int PREG_FB__PRIVATE__HSL_IMPL; <<__PHPStdLib>> function fb_serialize( HH\FIXME\MISSING_PARAM_TYPE $thing, int $options = 0, )[]: \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_unserialize( HH\FIXME\MISSING_PARAM_TYPE $thing, inout ?bool $success, int $options = 0, ): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_compact_serialize( HH\FIXME\MISSING_PARAM_TYPE $thing, int $options = 0, )[]: \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_compact_unserialize( HH\FIXME\MISSING_PARAM_TYPE $thing, inout ?bool $success, inout ?int $errcode, ): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_intercept2( string $name, HH\FIXME\MISSING_PARAM_TYPE $handler, ): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_rename_function( string $orig_func_name, string $new_func_name, ): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_utf8ize( inout string $input, ): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_utf8_strlen(string $input)[]: \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_utf8_substr( string $str, int $start, int $length = PHP_INT_MAX, )[]: \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_get_code_coverage(bool $flush): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_enable_code_coverage(): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_disable_code_coverage(): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_output_compression( bool $new_value, ): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_set_exit_callback( HH\FIXME\MISSING_PARAM_TYPE $function, ): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_get_last_flush_size(): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function fb_setprofile( HH\FIXME\MISSING_PARAM_TYPE $callback, int $flags = SETPROFILE_FLAGS_DEFAULT, vec<string> $functions = vec[], ): \HH\FIXME\MISSING_RETURN_TYPE; function fb_call_user_func_async( string $initialDoc, mixed $function, mixed ...$func_args ): resource; function fb_gen_user_func( string $initialDoc, mixed $function, mixed ...$func_args ): Awaitable<dynamic>; } // namespace namespace HH { <<__PHPStdLib>> function disable_code_coverage_with_frequency( ): \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function non_crypto_md5_upper(string $str)[]: int; <<__PHPStdLib>> function non_crypto_md5_lower(string $str)[]: int; /** Returns the overflow part of multiplying two ints, as if they were unsigned. * In other words, this returns the upper 64 bits of the full product of * (unsigned)$a and (unsigned)$b. (The lower 64 bits is just `$a * $b` * regardless of signed/unsigned). */ function int_mul_overflow(int $a, int $b): int; /** Returns the overflow part of multiplying two ints plus another int, as if * they were all unsigned. Specifically, this returns the upper 64 bits of * full (unsigned)$a * (unsigned)$b + (unsigned)$bias. $bias can be used to * manipulate rounding of the result. */ function int_mul_add_overflow(int $a, int $b, int $bias): int; function enable_function_coverage(): \HH\FIXME\MISSING_RETURN_TYPE; function collect_function_coverage(): \HH\FIXME\MISSING_RETURN_TYPE; /** * Sets product attribution id into the caller's frame in order to be fetched * later down the call stack. */ function set_product_attribution_id(int $id)[]: void; /** * Same as the above `set_product_attribution_id` function except it takes a * lambda that returns the attribution id to be called before fetching the value */ function set_product_attribution_id_deferred((function()[leak_safe]: int) $fn)[]: void; /** * Fetches the closest product attribution id. * If no value is set, returns null. */ function get_product_attribution_id()[leak_safe]: ?int; /** * Propagates the current product ID attribution into a lambda so that attempts * to retrieve attribution inside the lambda will return the creator's * attribution instead of the eventual caller's attribution. */ function embed_product_attribution_id_in_closure<T>( (function ()[defaults]: T) $f, )[leak_safe]: (function ()[defaults]: T); /** * Propagates the current product ID attribution into an async lambda so that * attempts to retrieve attribution inside the lambda will return the creator's * attribution instead of the eventual caller's attribution. */ function embed_product_attribution_id_in_async_closure<T>( (function ()[defaults]: Awaitable<T>) $f, )[leak_safe]: (function ()[defaults]: Awaitable<T>); } // HH namespace
HTML Help Workshop
hhvm/hphp/hack/hhi/classes.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of PHP's predefined classes * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace { <<__SupportDynamicType>> final class Generator<+Tk, +Tv, -Ts> implements KeyedIterator<Tk, Tv> { public function getOrigFuncName(): string {} public function current(): Tv {} public function key(): Tk {} public function valid(): bool {} public function next(): void {} public function send(?Ts $v): void {} public function raise(Exception $e): void {} public function rewind(): void {} } final class stdClass {} } // namespace namespace HH { /** * Async generators are similar to * [PHP Generators](http://php.net/manual/en/language.generators.overview.php), * except that we are combining async with generators. * * An async generator is just like a normal generator with the addition of * allowing `await` statements in it because getting to the next yielded value * involves getting and awaiting on an `Awaitable`. * * WHILE THIS CLASS EXPOSES 3 METHODS, 99.9% OF THE TIME YOU WILL NOT USE THIS * CLASS DIRECTLY. INSTEAD, YOU WILL USE `await as` IN THE CODE USING YOUR * ASYNC GENERATOR. PLEASE READ THE GUIDE REFERENCED IN THIS API DOCUMENTATION * FOR MORE INFORMATION. However, we document these methods for completeness in * case you have a use case for them. * * There are three type parameters associated with an AsyncGenerator: * - `Tk`: The type of key returned by the generator * - `Tv`: The type of value returned by the generator * - `Ts`: The type that will be passed on a call to `send()` * * @guide /hack/asynchronous-operations/generators */ final class AsyncGenerator<+Tk, +Tv, -Ts> implements AsyncKeyedIterator<Tk, Tv> { /** * Return the `Awaitable` associated with the next key/value tuple in the * async generator, or `null`. * * You should always `await` the returned `Awaitable` to get the actual * key/value tuple. * * If `null` is returned, that means you have reached the end of iteration. * * You cannot call `next()` without having the value returned from a previous * call to `next()`, `send()`, `raise()`, having first `await`ed. * * @return - The `Awaitable` that produced the next key/value tuple in the * generator. What is returned is a tuple or `null`. */ public function next(): Awaitable<?(Tk, Tv)> {} /** * Send a value to the async generator and resumes execution of the generator. * * You should always `await` the returned `Awaitable` to get the actual * key/value tuple. * * If `null` is returned, that means you have reached the end of iteration. * * You cannot call `send()` without having the value returned from a previous * call to `send()`, `next()`, `raise()`, having first `await`ed. * * If you pass `null` to `send()`, that is equivalent to calling `next()`, * but you still need an initial `next()` call before calling `send(null)`. * * @param $v - The value to send to the async generator. * * @return - The `Awaitable` that produced the yielded key/value tuple in * the generator. What is returned is a tuple or `null`. */ public function send(?Ts $v): Awaitable<?(Tk, Tv)> {} /** * Raise an exception to the async generator. * * You should always `await` the returned `Awaitable` to get the actual * key/value tuple. * * If `null` is returned, that means you have reached the end of iteration. * * You cannot call `raise()` without having the value returned from a previous * call to `raise()`, `next()`, `send()`, having first `await`ed. * * @param $e - The exception to raise on the async generator. * * @return - The `Awaitable` that produced the yielded key/value tuple after * the exception is processed. What is returned is a tuple or * `null`. */ public function raise(\Exception $e): Awaitable<?(Tk, Tv)> {} } << __Sealed( AwaitAllWaitHandle::class, ConcurrentWaitHandle::class, ConditionWaitHandle::class, ExternalThreadEventWaitHandle::class, RescheduleWaitHandle::class, ResumableWaitHandle::class, SleepWaitHandle::class, ), __SupportDynamicType, >> abstract class WaitableWaitHandle<+T> extends Awaitable<T> { } <<__SupportDynamicType>> final class StaticWaitHandle<+T> extends Awaitable<T> { } <<__SupportDynamicType>> final class AsyncFunctionWaitHandle<+T> extends ResumableWaitHandle<T> { } <<__SupportDynamicType>> final class AsyncGeneratorWaitHandle< +Tk, +Tv, > extends ResumableWaitHandle<?(Tk, Tv)> { } /** * An `Awaitable` value represents a value that is fetched * asynchronously, such as a database access. `Awaitable` values are * usually returned by `async` functions. * * Use `await` to wait for a single `Awaitable` value. If you have * multiple `Awaitable`s and you want to wait for all of them * together, use `concurrent` or helper functions like * `Vec\map_async`. * * `Awaitable` is not multithreading. Hack is single threaded, so * `Awaitable` allows you to wait for multiple external results at * once, rather than sequentially. */ << __Sealed(StaticWaitHandle::class, WaitableWaitHandle::class), __SupportDynamicType, >> abstract class Awaitable<+T> { public static function setOnIOWaitEnterCallback( ?(function(): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public static function setOnIOWaitExitCallback( ?(function(?WaitableWaitHandle<mixed>): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public static function setOnJoinCallback( ?(function(WaitableWaitHandle<mixed>): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} } << __Sealed(AsyncFunctionWaitHandle::class, AsyncGeneratorWaitHandle::class), __SupportDynamicType, >> abstract class ResumableWaitHandle<+T> extends WaitableWaitHandle<T> { public static function setOnCreateCallback( ?(function( AsyncFunctionWaitHandle<mixed>, WaitableWaitHandle<mixed>, ): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public static function setOnAwaitCallback( ?(function( AsyncFunctionWaitHandle<mixed>, WaitableWaitHandle<mixed>, ): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public static function setOnSuccessCallback( ?(function(AsyncFunctionWaitHandle<mixed>, mixed): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public static function setOnFailCallback( ?(function(AsyncFunctionWaitHandle<mixed>, \Exception): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} } <<__SupportDynamicType>> final class AwaitAllWaitHandle extends WaitableWaitHandle<void> { public static function fromDict( dict<arraykey, Awaitable<mixed>> $deps, )[]: Awaitable<void>; public static function fromVec( vec<Awaitable<mixed>> $deps, )[]: Awaitable<void>; public static function setOnCreateCallback( ?(function(AwaitAllWaitHandle, vec<WaitableWaitHandle<mixed>>): void) $callback, ): void {} } <<__SupportDynamicType>> final class ConcurrentWaitHandle extends WaitableWaitHandle<void> { public static function setOnCreateCallback( ?(function(ConcurrentWaitHandle, vec<WaitableWaitHandle<mixed>>): void) $callback, ): void {} } << __SupportDynamicType, >> // TODO: determine whether it's safe to mark this as unconditionally supporting dynamic final class ConditionWaitHandle<T> extends WaitableWaitHandle<T> { public static function create( Awaitable<void> $child, ): ConditionWaitHandle<T> {} public static function setOnCreateCallback( ?(function( ConditionWaitHandle<T>, WaitableWaitHandle<void>, ): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public function succeed(T $result): void {} public function fail(\Exception $exception): void {} } <<__SupportDynamicType>> final class RescheduleWaitHandle extends WaitableWaitHandle<void> { const int QUEUE_DEFAULT; const int QUEUE_NO_PENDING_IO; public static function create( int $queue, int $priority, )[]: RescheduleWaitHandle {} } <<__SupportDynamicType>> final class SleepWaitHandle extends WaitableWaitHandle<void> { public static function create(int $usecs): SleepWaitHandle {} public static function setOnCreateCallback( ?(function(SleepWaitHandle): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public static function setOnSuccessCallback( ?(function(SleepWaitHandle): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} } <<__SupportDynamicType>> final class ExternalThreadEventWaitHandle<+T> extends WaitableWaitHandle<T> { public static function setOnCreateCallback( ?(function(ExternalThreadEventWaitHandle<mixed>): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public static function setOnSuccessCallback( ?(function(ExternalThreadEventWaitHandle<mixed>, mixed): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} public static function setOnFailCallback( ?(function( ExternalThreadEventWaitHandle<mixed>, \Exception, ): void) $callback, ): \HH\FIXME\MISSING_RETURN_TYPE {} } function is_class(mixed $arg)[]: bool; } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/classname.hhi
<?hh namespace HH { /** * The constant ::class works for types besides classes, including type defs. * For any type def TypeDef, TypeDef::class creates a typename<TypeDef>. Unlike * classname, typename does not support invoking static method or the new * operator, only that it is string representing the name of a type. */ <<__NoAutoDynamic>> newtype typename<+T> as string = string; /** * For any class C, C::class creates a classname<C>. Due to the properties * of opaque types, C::class is the only way of obtaining a classname. */ <<__NoAutoDynamic>> newtype classname<+T> as typename<T> = typename<T>; /** * Creates a classname<mixed> (LazyClass) from input $classname. It does not eagerly * verify that the $classname is in fact a valid class or perform modularity * checks. Should only be used in rare cases to cast a known string that represents * some class to a classname. The preferred method to optain a classname should be using * the C::class syntax. */ function classname_from_string_unsafe(string $classname)[]: classname<mixed>; } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/constants.hhi
<?hh /** * Copyright (c) 2014, 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. * */ const string PHP_EOL; const string PHP_OS; const string PHP_VERSION; const int PHP_MAJOR_VERSION; const int PHP_MINOR_VERSION; const int PHP_RELEASE_VERSION; const int PHP_VERSION_ID; const string PHP_EXTRA_VERSION; const string HHVM_VERSION; const string HHVM_COMPILER_ID; const int HHVM_COMPILER_TIMESTAMP; // typechecker placeholder, see runtime const string HHVM_REPO_SCHEMA; const int HHVM_VERSION_ID; const int HHVM_VERSION_MAJOR; const int HHVM_VERSION_MINOR; const int HHVM_VERSION_PATCH; const int PHP_INT_MAX; const int PHP_INT_MIN; const int PHP_INT_SIZE; const int DEBUG_BACKTRACE_PROVIDE_OBJECT; const int DEBUG_BACKTRACE_IGNORE_ARGS; const int DEBUG_BACKTRACE_PROVIDE_METADATA; const int E_ERROR; const int E_WARNING; const int E_PARSE; const int E_NOTICE; const int E_CORE_ERROR; const int E_CORE_WARNING; const int E_COMPILE_ERROR; const int E_COMPILE_WARNING; const int E_USER_ERROR; const int E_USER_WARNING; const int E_USER_NOTICE; const int E_RECOVERABLE_ERROR; const int E_DEPRECATED; const int E_USER_DEPRECATED; const int E_ALL; const int E_STRICT; // Built in pseudoconstants const int __LINE__; const string __CLASS__; const string __TRAIT__; const string __FILE__; const string __DIR__; const string __FUNCTION__; const string __METHOD__; const string __NAMESPACE__; const string __COMPILER_FRONTEND__; const FunctionCredential __FUNCTION_CREDENTIAL__;
HTML Help Workshop
hhvm/hphp/hack/hhi/container_functions.hhi
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of PHP's predefined functions * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace { <<__PHPStdLib>> function array_key_exists( readonly mixed $key, readonly ?KeyedContainer<arraykey, mixed> $search, )[]: bool; <<__PHPStdLib>> function array_sum/*<T>*/( readonly /*Container<T>*/ HH\FIXME\MISSING_PARAM_TYPE $input, )[]/*: num*/: \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_product/*<T>*/( readonly /*Container<T>*/ HH\FIXME\MISSING_PARAM_TYPE $input, )[]/*: num*/: \HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function sort<T as Container<mixed>>( inout T $arg, int $sort_flags = SORT_REGULAR, )[]: bool; <<__PHPStdLib>> function rsort<T as Container<mixed>>( inout T $arg, int $sort_flags = SORT_REGULAR, )[]: bool; <<__PHPStdLib>> function asort<Tk as arraykey, Tv>( inout KeyedContainer<Tk, Tv> $arg, int $sort_flags = SORT_REGULAR, )[]: bool; <<__PHPStdLib>> function arsort<Tk as arraykey, Tv>( inout KeyedContainer<Tk, Tv> $arg, int $sort_flags = SORT_REGULAR, )[]: bool; <<__PHPStdLib>> function ksort<T as KeyedContainer<arraykey, mixed>>( inout T $arg, int $sort_flags = SORT_REGULAR, )[]: bool; <<__PHPStdLib>> function krsort<Tk as arraykey, Tv>( inout KeyedContainer<Tk, Tv> $arg, int $sort_flags = SORT_REGULAR, )[]: bool; <<__PHPStdLib>> function usort<Tv, T as Container<Tv>>( inout T $arg, (function(Tv, Tv)[_]: num) $c, )[ctx $c]: bool; <<__PHPStdLib>> function uasort<Tk as arraykey, Tv>( inout KeyedContainer<Tk, Tv> $arg, (function(Tv, Tv)[_]: num) $c, )[ctx $c]: bool; <<__PHPStdLib>> function uksort<Tk as arraykey, Tv>( inout KeyedContainer<Tk, Tv> $arg, (function(Tk, Tk)[_]: num) $c, )[ctx $c]: bool; } namespace HH { /** * Creates a `dict` from a `KeyedTraversable`, preserving keys and order. */ <<__NoAutoLikes>> function dict<<<__NoAutoBound>> Tk as arraykey, Tv>( KeyedTraversable<Tk, Tv> $arr, )[]: dict<Tk, Tv>; /** * Creates a `vec` from a `Traversable`, preserving order. Keys are not * preserved. */ <<__NoAutoLikes>> function vec<Tv>(Traversable<Tv> $arr)[]: vec<Tv>; /** * Create a `keyset` from a `Traversable` of strings or ints, preserving order. * Keys are not preserved. */ <<__NoAutoLikes>> function keyset<<<__NoAutoBound>> Tv as arraykey>(Traversable<Tv> $arr)[]: keyset<Tv>; <<__NoAutoLikes>> function darray<<<__NoAutoBound>> Tk as arraykey, Tv>( KeyedTraversable<Tk, Tv> $arr, )[]: darray<Tk, Tv>; <<__NoAutoLikes>> function varray<Tv>(Traversable<Tv> $arr)[]: varray<Tv>; function is_php_array(readonly mixed $input)[]: bool; function is_vec_or_varray(readonly mixed $input)[]: bool; function is_dict_or_darray(readonly mixed $input)[]: bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/dyn_func_pointers.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, 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. * */ namespace HH { <<__NoAutoDynamic>> function dynamic_fun(string $func_name)[]: dynamic; function dynamic_class_meth(string $cls_name, string $meth_name)[]: dynamic; function dynamic_meth_caller(string $cls_name, string $meth_name)[]: dynamic; }
HTML Help Workshop
hhvm/hphp/hack/hhi/exceptions.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of PHP's predefined classes * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace { <<__Sealed(Error::class, Exception::class)>> interface Throwable { public function getMessage(): string; // Documented as 'int' in PHP docs, but not actually guaranteed; // subclasses (e.g. PDO) can do what they want. public function getCode()[]: mixed; public function getFile()[]: string; public function getLine()[]: int; public function getTrace()[]: Container<mixed>; public function getTraceAsString()[]: string; public function getPrevious()[]: ?Throwable; public function __toString(): string; public function toString(): string; } class Error implements Throwable { protected string $message; protected mixed $code; protected string $file; protected int $line; /* Methods */ public function __construct( string $message = "", int $code = 0, ?Throwable $previous = null, )[]; final public function getMessage()[]: string; final public function getPrevious()[]: ?Throwable; final public function getCode()[]: mixed; final public function getFile()[]: string; final public function getLine()[]: int; final public function getTrace()[]: varray<mixed>; final public function getTraceAsString()[]: string; public function __toString(): string; public function toString(): string; private function __clone(): void; } class ArithmeticError extends Error {} class ArgumentCountError extends Error {} class AssertionError extends Error {} class DivisionByZeroError extends Error {} class ParseError extends Error {} class TypeError extends Error {} interface IExceptionWithPureGetMessage { require extends Exception; public function getMessage()[]: string; } trait ExceptionWithPureGetMessageTrait implements IExceptionWithPureGetMessage { require extends Exception; public function getMessage()[]: string; } class ExceptionWithPureGetMessage extends Exception { use ExceptionWithPureGetMessageTrait; } class Exception implements Throwable { protected int $code; protected string $file; protected int $line; private varray<mixed> $trace; public function __construct( protected string $message = '', int $code = 0, protected ?Exception $previous = null, )[]; /** * This method isn't pure. Consider using IExceptionWithPureGetMessage */ public function getMessage()[defaults]: string; final public function getPrevious()[]: ?Exception; public final function setPrevious(Exception $previous)[write_props]: void; public function getCode()[]: int; final public function getFile()[]: string; final public function getLine()[]: int; final public function getTrace()[]: varray<mixed>; final protected function __prependTrace( Container<mixed> $trace, )[write_props]: void; final public function getTraceAsString()[]: string; public function __toString(): string; public function toString(): string; private function __clone(): void; final public static function getTraceOptions( )[read_globals]: \HH\FIXME\MISSING_RETURN_TYPE; final public static function setTraceOptions( HH\FIXME\MISSING_PARAM_TYPE $opts, )[globals]: \HH\FIXME\MISSING_RETURN_TYPE; /** * Actually defined on \__SystemLib\BaseException */ final protected static function toStringFromGetMessage( \Throwable $throwable, (function(\Throwable)[_]: string) $get_message, )[ctx $get_message]: string; public static function toStringPure( Exception $e, ?(function(Throwable)[]: string) $fallback = null, )[]: string; } class ErrorException extends Exception { use ExceptionWithPureGetMessageTrait; public function __construct( HH\FIXME\MISSING_PARAM_TYPE $message = "", int $code = 0, protected int $severity = 0, string $filename = '' /* __FILE__ */, int $lineno = 0 /* __LINE__ */, ?Exception $previous = null, )[]; public final function getSeverity()[]: int; } class LogicException extends Exception { use ExceptionWithPureGetMessageTrait; } class BadFunctionCallException extends LogicException {} class BadMethodCallException extends BadFunctionCallException {} class DomainException extends LogicException {} class InvalidArgumentException extends LogicException {} class LengthException extends LogicException {} class OutOfRangeException extends LogicException {} final class InvalidCallbackArgumentException extends LogicException {} final class InvalidForeachArgumentException extends LogicException {} final class TypecastException extends LogicException {} final class UndefinedPropertyException extends LogicException {} final class UndefinedVariableException extends LogicException {} final class AccessPropertyOnNonObjectException extends LogicException {} final class ReadonlyViolationException extends LogicException {} final class CoeffectViolationException extends LogicException {} final class ModuleBoundaryViolationException extends LogicException {} class RuntimeException extends Exception { use ExceptionWithPureGetMessageTrait; } class OutOfBoundsException extends RuntimeException {} class OverflowException extends RuntimeException {} class RangeException extends RuntimeException {} class UnderflowException extends RuntimeException {} class UnexpectedValueException extends RuntimeException {} final class TypeAssertionException extends RuntimeException {} class DivisionByZeroException extends Exception { use ExceptionWithPureGetMessageTrait; } } // namespace namespace HH { class InvariantException extends \Exception { use \ExceptionWithPureGetMessageTrait; } } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/experimental_parser_utils.hhi
<?hh namespace HH\ExperimentalParserUtils; newtype FunctionNode = darray<string, mixed>; function find_all_functions(\HH\ParseTree $json)[]: dict<int, FunctionNode>; function body_bounds(FunctionNode $function)[]: ((int, int), (int, int)); newtype ShapeNode = darray<string, mixed>; function find_single_shape_type_alias( \HH\ParseTree $json, string $name, )[]: ?(string, ShapeNode); function extract_shape_comments(ShapeNode $shape)[]: dict<string, vec<string>>; newtype ClassBodyNode = darray<string, mixed>; function find_class_body(\HH\ParseTree $json, string $name)[]: ?ClassBodyNode; function find_class_shape_type_constant( ClassBodyNode $class_body, string $name, )[]: ?ShapeNode; function find_class_method_shape_return_type( ClassBodyNode $class_body, string $name, )[]: ?ShapeNode; newtype MethodParametersNode = darray<string, mixed>; function find_method_parameters( \HH\ParseTree $json, string $method_name, int $line_number, )[]: MethodParametersNode; function extract_parameter_comments( MethodParametersNode $params, )[]: dict<string, vec<string>>; newtype EnumBodyNode = darray<string, mixed>; function find_enum_body(\HH\ParseTree $json, string $name)[]: ?EnumBodyNode; function extract_enum_comments( EnumBodyNode $enumerators, )[]: dict<string, vec<string>>; function extract_type_of_only_shape_type_alias( \HH\ParseTree $json, )[]: dict<string, (string, bool)>;
HTML Help Workshop
hhvm/hphp/hack/hhi/ext_facts.hhi
<?hh namespace HH\Facts { /** * Used to communicate whether a symbol string is the name of a type, function, * constant, or type alias. * * Replicated as `AutoloadMap::KindOf` in `autoload-map.h` */ enum SymbolKind: int { K_TYPE = 1; K_FUNCTION = 2; K_CONSTANT = 3; K_MODULE = 4; } enum TypeKind: string { K_CLASS = 'class'; K_ENUM = 'enum'; K_INTERFACE = 'interface'; K_TRAIT = 'trait'; K_TYPE_ALIAS = 'typeAlias'; } /** * The two forms of inheritance supported by Hack. */ enum DeriveKind: string { // Includes `implements` and `use` K_EXTENDS = 'extends'; // Includes `require implements` K_REQUIRE_EXTENDS = 'require extends'; } type TypeAttributeFilter = shape( 'name' => classname<\HH\ClassLikeAttribute>, 'parameters' => dict<int, dynamic>, ); type DeriveFilters = shape( ?'kind' => keyset<TypeKind>, ?'derive_kind' => keyset<DeriveKind>, ?'attributes' => vec<TypeAttributeFilter>, ); /** * True iff native facts are available * * If this returns false, any other operations in the HH\Facts namespace will * throw InvalidOperationException if called. */ function enabled()[]: bool; /** * Return the DB path corresponding to the given directory of Hack code. * * The given directory must be a valid path containing a `.hhvmconfig.hdf` * file at its root, and this `.hhvmconfig.hdf` file must contain either the * `Autoload.TrustedDBPath` or the `Autoload.Query` setting. Otherwise, this * function will return `null`. * * If the `Autoload.TrustedDBPath` setting points to a valid path, this * function will just return that path. * * Otherwise, if the `Autoload.Query` setting exists, this function calculates * the DB's location for that repo based on the query, path, version, and Unix * user. */ function db_path(string $root)[]: ?string; /** * Return the schema version in use by this hhvm binary. */ function schema_version()[]: int; /** * Blocks until Facts is synchronized as of when the call was intiated. */ function sync(): void; /** * Return the only path defining a given symbol. * * Return `null` if the symbol is not defined, or is defined in more than one * place. * * Throw InvalidOperationException if Facts is not enabled. */ function type_to_path(string $type_name)[]: ?string; function function_to_path(string $function_name)[]: ?string; function constant_to_path(string $constant_name)[]: ?string; function type_alias_to_path(string $type_alias_name)[]: ?string; function type_or_type_alias_to_path(string $type_name)[]: ?string; /** * Return all the symbols defined in the given path. * * Throw InvalidOperationException if Facts is not enabled. */ function path_to_modules(string $path)[]: vec<string>; function path_to_types(string $path)[]: vec<classname<nonnull>>; function path_to_functions(string $path)[]: vec<string>; function path_to_constants(string $path)[]: vec<string>; function path_to_type_aliases(string $path)[]: vec<string>; /** * Resolve a string into a classname that's properly capitalized and properly * typed. * * Return `null` if the classname does not exist in the codebase, even with * different capitalization. * * Throw InvalidOperationException if Facts is not enabled. */ function type_name(string $classname)[]: ?classname<nonnull>; /** * Return a string enum representing whether the given type is, for example, a * class, interface, or trait. * * If the given type doesn't have a unique definition or isn't a * `classname<mixed>`, return `null`. */ function kind(classname<mixed> $type)[]: ?TypeKind; /** * True iff the given type cannot be constructed. */ function is_abstract(classname<mixed> $type)[]: bool; /** * True iff the given type cannot be inherited. */ function is_final(classname<mixed> $type)[]: bool; /** * Get all types which extend, implement, or use the given base type. * * Throws InvalidOperationException if Facts is not enabled. */ function subtypes<T>( classname<T> $base_type, ?DeriveFilters $filters = null, )[]: vec<classname<T>>; /** * Get all types which the given type extends, implements, or uses. * * Throws InvalidOperationException if Facts is not enabled. */ function supertypes( classname<mixed> $derived_type, ?DeriveFilters $filters = null, )[]: vec<classname<mixed>>; /** * Get all types matching the given filters. * * Throws InvalidOperationException if Facts is not enabled. */ function types_with_attribute( classname<\HH\ClassLikeAttribute> $attribute, )[]: vec<classname<mixed>>; /** * Get all type aliases matching the given filters. * * Throws InvalidOperationException if Facts is not enabled. */ function type_aliases_with_attribute( classname<\HH\TypeAliasAttribute> $attribute, )[]: vec<string>; /** * Get all methods matching the given filters. * * Throws InvalidOperationException if Facts is not enabled. * Throws a RuntimeException if querying for an attribute that's not listed * in the `Autoload.IndexedMethodAttributes` setting in this repo's * `.hhvmconfig.hdf` file. */ function methods_with_attribute( classname<\HH\MethodAttribute> $attribute, )[]: vec<(classname<nonnull>, string)>; /** * Get all files matching the given filters. * * Throws InvalidOperationException if Facts is not enabled. */ function files_with_attribute( classname<\HH\FileAttribute> $attribute, )[]: vec<string>; /** * Get all attributes on the given type. * * Return an empty vec if the given type doesn't exist or is defined in more * than one file. * * Throw InvalidOperationException if Facts is not enabled. */ function type_attributes( classname<mixed> $type, )[]: vec<classname<\HH\ClassLikeAttribute>>; /** * Get all attributes on the given type alias. * * Throw InvalidOperationException if Facts is not enabled. */ function type_alias_attributes( string $type_alias, )[]: vec<classname<\HH\TypeAliasAttribute>>; /** * Get all attributes on the given method. * * Return an empty vec if the method does not exist. * * Throw InvalidOperationException if Facts is not enabled. */ function method_attributes( classname<mixed> $type, string $method, )[]: vec<classname<\HH\MethodAttribute>>; /** * Get all attributes on the given file. * * Throw InvalidOperationException if Facts is not enabled. */ function file_attributes(string $file)[]: vec<classname<\HH\FileAttribute>>; /** * Get all parameters for the given attribute on the given type. * * Return an empty vec if the given type doesn't exist or doesn't have the * given attribute. * * Throw InvalidOperationException if Facts is not enabled. */ function type_attribute_parameters( classname<mixed> $type, classname<\HH\ClassLikeAttribute> $attribute, )[]: vec<dynamic>; /** * Get all parameters for the given attribute on the given type alias. * * Return an empty vec if the type alias doesn't exist or doesn't have the * given attribute. * * Throw InvalidOperationException if Facts is not enabled. */ function type_alias_attribute_parameters( string $type_alias, classname<\HH\TypeAliasAttribute> $attribute, )[]: vec<dynamic>; /** * Get all parameters for the given attribute on the given method. * * Return an empty vec if the method doesn't exist or doesn't have the * given attribute. * * Throw InvalidOperationException if Facts is not enabled. */ function method_attribute_parameters( classname<mixed> $type, string $method, classname<\HH\MethodAttribute> $attribute, )[]: vec<dynamic>; /** * Get all parameters for the given attribute on the given file. * * Return an empty vec if the given file doesn't exist or doesn't have the * given attribute. * * Throw InvalidOperationException if Facts is not enabled. */ function file_attribute_parameters( string $file, classname<\HH\FileAttribute> $attribute, )[]: vec<dynamic>; } // namespace HH\Facts
HTML Help Workshop
hhvm/hphp/hack/hhi/ext_rqtrace.hhi
<?hh namespace HH\rqtrace { /** * Enable request tracing */ function force_enable(): void; function is_enabled(): bool; /** * @return Dict * ( * [EVENT_NAME] => Dict * ( * [duration] => int (microseconds) * [count] => int * ) * ... * ) */ function all_request_stats(): dict<string, dict<string, int>>; function all_process_stats(): dict<string, dict<string, int>>; /** * @return Dict * ( * [duration] => int (microseconds) * [count] => int * ) */ function request_event_stats(string $event_name): dict<string, int>; function process_event_stats(string $event_name): dict<string, int>; } // namespace HH\rqtrace
HTML Help Workshop
hhvm/hphp/hack/hhi/ext_sodium.hhi
<?hh final class SodiumException extends Exception {} ///// utilities <<__PHPStdLib>> function sodium_bin2hex(string $binary): string; <<__PHPStdLib>> function sodium_hex2bin(string $hex, ?string $ignore = null): string; <<__PHPStdLib>> function sodium_memzero(inout mixed $buffer): void; <<__PHPStdLib>> function sodium_increment(inout mixed $buffer): void; <<__PHPStdLib>> function sodium_add(inout mixed $value, string $add): void; <<__PHPStdLib>> function sodium_memcmp(string $a, string $b): int; <<__PHPStdLib>> function sodium_compare(string $a, string $b): int; <<__PHPStdLib>> function sodium_crypto_scalarmult(string $n, string $p): string; ///// Hashing (not for passwords or keys) <<__PHPStdLib>> function sodium_crypto_generichash_keygen(): string; <<__PHPStdLib>> function sodium_crypto_generichash( string $msg, ?string $key = null, ?int $length = null, ): string; <<__PHPStdLib>> function sodium_crypto_generichash_init( ?string $key = null, ?int $length = null, ): string; <<__PHPStdLib>> function sodium_crypto_generichash_update( inout mixed $state, string $msg, ): bool; <<__PHPStdLib>> function sodium_crypto_generichash_final( inout mixed $state, ?int $length = null, ): string; <<__PHPStdLib>> function sodium_crypto_shorthash_keygen(): string; <<__PHPStdLib>> function sodium_crypto_shorthash(string $message, string $key): string; ///// Key derivation (kdf) <<__PHPStdLib>> function sodium_crypto_pwhash( int $output_length, string $password, string $salt, int $opslimit, int $memlimit, ): string; <<__PHPStdLib>> function sodium_crypto_pwhash_scryptsalsa208sha256( int $output_length, string $password, string $salt, int $opslimit, int $memlimit, ): string; <<__PHPStdLib>> function sodium_crypto_kdf_derive_from_key( int $subkey_length, int $subkey_id, string $context, string $key, ): string; <<__PHPStdLib>> function sodium_crypto_core_hchacha20( string $in, string $k, ?string $c = null, ): string; ///// Password hashing for storage <<__PHPStdLib>> function sodium_crypto_pwhash_str( string $password, int $opslimit, int $memlimit, ): string; <<__PHPStdLib>> function sodium_crypto_pwhash_str_verify(string $hash, string $password): bool; <<__PHPStdLib>> function sodium_crypto_pwhash_scryptsalsa208sha256_str( string $password, int $opslimit, int $memlimit, ): string; <<__PHPStdLib>> function sodium_crypto_pwhash_scryptsalsa208sha256_str_verify( string $hash, string $password, ): bool; ///// MACs <<__PHPStdLib>> function sodium_crypto_auth_keygen(): string; <<__PHPStdLib>> function sodium_crypto_auth(string $message, string $key): string; <<__PHPStdLib>> function sodium_crypto_auth_verify( string $signature, string $message, string $key, ): bool; ///// Symmetric (PSK) encryption <<__PHPStdLib>> function sodium_crypto_secretbox_keygen(): string; <<__PHPStdLib>> function sodium_crypto_secretbox( string $plaintext, string $nonce, string $key, ): string; <<__PHPStdLib>> function sodium_crypto_secretbox_open( string $ciphertext, string $nonce, string $key, ): mixed /* string | false */; ///// Asymetric (public-key) encryption key management <<__PHPStdLib>> function sodium_crypto_box_keypair(): string; <<__PHPStdLib>> function sodium_crypto_box_seed_keypair(string $seed): string; <<__PHPStdLib>> function sodium_crypto_box_keypair_from_secretkey_and_publickey( string $secretkey, string $publickey, ): string; <<__PHPStdLib>> function sodium_crypto_box_publickey(string $keypair): string; <<__PHPStdLib>> function sodium_crypto_box_secretkey(string $keypair): string; <<__PHPStdLib>> function sodium_crypto_box_publickey_from_secretkey(string $key): string; <<__PHPStdLib>> function sodium_crypto_scalarmult_base(string $key): string; <<__PHPStdLib>> function sodium_crypto_kx_keypair(): string; <<__PHPStdLib>> function sodium_crypto_kx_seed_keypair(string $seed): string; <<__PHPStdLib>> function sodium_crypto_kx_secretkey(string $keypair): string; <<__PHPStdLib>> function sodium_crypto_kx_publickey(string $keypair): string; <<__PHPStdLib>> function sodium_crypto_kx_client_session_keys( string $client_keypair, string $server_pubkey, ): (string, string); <<__PHPStdLib>> function sodium_crypto_kx_server_session_keys( string $server_keypair, string $client_pubkey, ): (string, string); ///// Unauthenticated asymetric (PSK) encryption (you probably don't want this) <<__PHPStdLib>> function sodium_crypto_stream(int $length, string $nonce, string $key): string; <<__PHPStdLib>> function sodium_crypto_stream_xor( string $message, string $nonce, string $key, ): string; ///// Asymetric (public-key) encryption <<__PHPStdLib>> function sodium_crypto_box( string $plaintext, string $nonce, string $keypair, ): string; <<__PHPStdLib>> function sodium_crypto_box_open( string $ciphertext, string $nonce, string $key, ): mixed; <<__PHPStdLib>> function sodium_crypto_box_seal(string $plaintext, string $publickey): string; <<__PHPStdLib>> function sodium_crypto_box_seal_open( string $ciphertext, string $keypair, ): mixed; ///// Asymetric (public key) signature key management <<__PHPStdLib>> function sodium_crypto_sign_keypair(): string; <<__PHPStdLib>> function sodium_crypto_sign_seed_keypair(string $seed): string; <<__PHPStdLib>> function sodium_crypto_sign_publickey_from_secretkey(string $secretkey): string; <<__PHPStdLib>> function sodium_crypto_sign_keypair_from_secretkey_and_publickey( string $secretkey, string $publickey, ): string; <<__PHPStdLib>> function sodium_crypto_sign_publickey(string $keypair): string; <<__PHPStdLib>> function sodium_crypto_sign_secretkey(string $keypair): string; <<__PHPStdLib>> function sodium_crypto_sign_ed25519_pk_to_curve25519(string $eddsakey): string; <<__PHPStdLib>> function sodium_crypto_sign_ed25519_sk_to_curve25519(string $eddsakey): string; ///// Ed25519 primitives. <<__PHPStdLib>> function sodium_crypto_core_ed25519_scalar_reduce(string $scalar): string; <<__PHPStdLib>> function sodium_crypto_core_ed25519_scalar_add(string $scalar_a, string $scalar_b): string; <<__PHPStdLib>> function sodium_crypto_core_ed25519_scalar_mul(string $scalar_a, string $scalar_b): string; <<__PHPStdLib>> function sodium_crypto_scalarmult_ed25519_base(string $scalar): string; <<__PHPStdLib>> function sodium_crypto_scalarmult_ed25519_base_noclamp(string $scalar): string; ///// Asymetric (public key) signatures <<__PHPStdLib>> function sodium_crypto_sign(string $message, string $secretkey): string; <<__PHPStdLib>> function sodium_crypto_sign_open(string $signed, string $publickey): mixed; <<__PHPStdLib>> function sodium_crypto_sign_detached( string $message, string $secretkey, ): string; <<__PHPStdLib>> function sodium_crypto_sign_verify_detached( string $signature, string $message, string $publickey, ): bool; ///// AEAD functions <<__PHPStdLib>> function sodium_crypto_aead_aes256gcm_is_available(): bool; <<__PHPStdLib>> function sodium_crypto_aead_aes256gcm_decrypt( string $ciphertext, string $ad, string $pnonce, string $key, ): mixed; <<__PHPStdLib>> function sodium_crypto_aead_aes256gcm_encrypt( string $plaintext, string $ad, string $pnonce, string $key, ): string; <<__PHPStdLib>> function sodium_crypto_aead_chacha20poly1305_decrypt( string $ciphertext, string $ad, string $pnonce, string $key, ): mixed; <<__PHPStdLib>> function sodium_crypto_aead_chacha20poly1305_encrypt( string $plaintext, string $ad, string $pnonce, string $key, ): string; <<__PHPStdLib>> function sodium_crypto_aead_chacha20poly1305_ietf_decrypt( string $ciphertext, string $ad, string $pnonce, string $key, ): mixed; <<__PHPStdLib>> function sodium_crypto_aead_chacha20poly1305_ietf_encrypt( string $plaintext, string $ad, string $pnonce, string $key, ): string; <<__PHPStdLib>> function sodium_crypto_aead_xchacha20poly1305_ietf_decrypt( string $ciphertext, string $ad, string $pnonce, string $key, ): mixed; <<__PHPStdLib>> function sodium_crypto_aead_xchacha20poly1305_ietf_encrypt( string $plaintext, string $ad, string $pnonce, string $key, ): string; ///// AEAD functions for stream <<__PHPStdLib>> function sodium_crypto_secretstream_xchacha20poly1305_keygen(): string; <<__PHPStdLib>> function sodium_crypto_secretstream_xchacha20poly1305_init_push( string $key, ): (string, string); /* state, header */ <<__PHPStdLib>> function sodium_crypto_secretstream_xchacha20poly1305_push( inout mixed $state, string $plaintext, string $ad, int $tag, ): string; <<__PHPStdLib>> function sodium_crypto_secretstream_xchacha20poly1305_init_pull( string $key, string $header, ): string; <<__PHPStdLib>> function sodium_crypto_secretstream_xchacha20poly1305_pull( inout mixed $state, string $ciphertext, string $ad, ): (string, int); /* plaintext, tag */ <<__PHPStdLib>> function sodium_crypto_secretstream_xchacha20poly1305_rekey( inout mixed $state, ): void; ///// Ristretto <<__PHPStdLib>> function sodium_crypto_core_ristretto255_from_hash(string $r): string; <<__PHPStdLib>> function sodium_crypto_scalarmult_ristretto255(string $n, string $p): string; <<__PHPStdLib>> function sodium_crypto_core_ristretto255_scalar_reduce(string $s): string; <<__PHPStdLib>> function sodium_crypto_core_ristretto255_scalar_random(): string; <<__PHPStdLib>> function sodium_crypto_core_ristretto255_scalar_invert(string $s): string; <<__PHPStdLib>> function sodium_crypto_core_ristretto255_scalar_negate(string $s): string; <<__PHPStdLib>> function sodium_crypto_core_ristretto255_scalar_complement(string $s): string; <<__PHPStdLib>> function sodium_crypto_core_ristretto255_scalar_add( string $x, string $y, ): string; <<__PHPStdLib>> function sodium_crypto_core_ristretto255_scalar_sub( string $x, string $y, ): string; <<__PHPStdLib>> function sodium_crypto_core_ristretto255_scalar_mul( string $x, string $y, ): string; ///// Always-defined constants const string SODIUM_LIBRARY_VERSION; const int SODIUM_LIBRARY_MAJOR_VERSION; const int SODIUM_LIBRARY_MINOR_VERSION; const int SODIUM_CRYPTO_SCALARMULT_BYTES; const int SODIUM_CRYPTO_SCALARMULT_SCALARBYTES; const int SODIUM_CRYPTO_GENERICHASH_KEYBYTES; const int SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN; const int SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX; const int SODIUM_CRYPTO_SHORTHASH_BYTES; const int SODIUM_CRYPTO_SHORTHASH_KEYBYTES; const string SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX; const int SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES; const int SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE; const int SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE; const int SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE; const int SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE; const int SODIUM_CRYPTO_AUTH_BYTES; const int SODIUM_CRYPTO_AUTH_KEYBYTES; const int SODIUM_CRYPTO_SECRETBOX_KEYBYTES; const int SODIUM_CRYPTO_SECRETBOX_MACBYTES; const int SODIUM_CRYPTO_SECRETBOX_NONCEBYTES; const int SODIUM_CRYPTO_BOX_SECRETKEYBYTES; const int SODIUM_CRYPTO_BOX_PUBLICKEYBYTES; const int SODIUM_CRYPTO_BOX_KEYPAIRBYTES; const int SODIUM_CRYPTO_BOX_MACBYTES; const int SODIUM_CRYPTO_BOX_NONCEBYTES; const int SODIUM_CRYPTO_BOX_SEEDBYTES; const int SODIUM_CRYPTO_SIGN_BYTES; const int SODIUM_CRYPTO_SIGN_SEEDBYTES; const int SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES; const int SODIUM_CRYPTO_SIGN_SECRETKEYBYTES; const int SODIUM_CRYPTO_SIGN_KEYPAIRBYTES; const int SODIUM_CRYPTO_STREAM_NONCEBYTES; const int SODIUM_CRYPTO_STREAM_KEYBYTES; const int SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES; const int SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES; const int SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES; const int SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES; const int SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES; const int SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES; const int SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES; const int SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX; const int SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE; const int SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH; const int SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY; const int SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL; ///// Conditionally-defined constants (depends on libsodium build options) const int SODIUM_CRYPTO_PWHASH_SALTBYTES; const string SODIUM_CRYPTO_PWHASH_STRPREFIX; const int SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE; const int SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE; const int SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE; const int SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE; const int SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE; const int SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE; const int SODIUM_CRYPTO_BOX_SEALBYTES; const int SODIUM_CRYPTO_AEAD_AES245GCM_KEYBYTES; const int SODIUM_CRYPTO_AEAD_AES245GCM_NSECBYTES; const int SODIUM_CRYPTO_AEAD_AES245GCM_NPUBBYTES; const int SODIUM_CRYPTO_AEAD_AES245GCM_ABYTES; const int SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES; const int SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES; const int SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES; const int SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES; const int SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES; const int SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NSECBYTES; const int SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES; const int SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES; const int SODIUM_CRYPTO_KDF_BYTES_MIN; const int SODIUM_CRYPTO_KDF_BYTES_MAX; const int SODIUM_CRYPTO_KDF_BYTES_CONTEXTBYTES; const int SODIUM_CRYPTO_KDF_BYTES_KEYBYTES; const int SODIUM_CRYPTO_CORE_HCHACHA20_INPUTBYTES; const int SODIUM_CRYPTO_CORE_HCHACHA20_KEYBYTES; const int SODIUM_CRYPTO_CORE_HCHACHA20_OUTPUTBYTES; const int SODIUM_CRYPTO_CORE_HCHACHA20_CONSTBYTES; const int SODIUM_CRYPTO_KX_PUBLICKEYBYTES; const int SODIUM_CRYPTO_KX_SESSIONKEYBYTES; const int SODIUM_CRYPTO_KX_SECRETKEYBYTES; const int SODIUM_CRYPTO_KX_KEYPAIRBYTES; const int SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES; const int SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES; const int SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES; const int SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES; const int SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES; const int SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES;
HTML Help Workshop
hhvm/hphp/hack/hhi/ext_watchman.hhi
<?hh namespace HH { function watchman_run( string $json_query, ?string $socket_name = null, ): Awaitable<string>; type WatchmanResult = shape( 'version' => string, ?'buildinfo' => string, ?'capabilities' => dict<string, bool>, ?'clock' => mixed, ?'config' => shape( ?'content_hash_max_items' => bool, ?'content_hash_warming' => bool, ?'enforce_root_files' => bool, ?'fsevents_latency' => num, ?'fsevents_try_resync' => bool, ?'gc_age_seconds' => int, ?'gc_interval_seconds' => int, ?'hint_num_dirs' => int, ?'hint_num_files_per_dir' => int, ?'idle_reap_age_seconds' => int, ?'illegal_fstypes' => vec<string>, ?'illegal_fstypes_advice' => string, ?'ignore_dirs' => vec<string>, ?'ignore_vcs' => vec<string>, ?'prefer_split_fsevents_watcher' => bool, ?'root_files' => vec<string>, ?'root_restrict_files' => vec<string>, ?'settle' => int, ?'suppress_recrawl_warnings' => bool, ... ), ?'debug' => shape( ... ), ?'dropped' => vec<string>, ?'error' => string, ?'files' => vec<shape( ?'cclock' => string, ?'content.sha1hex' => mixed, ?'ctime' => int, ?'dev' => int, ?'exists' => bool, ?'gid' => int, ?'ino' => int, ?'mode' => int, ?'mtime' => int, ?'name' => string, ?'nlink' => int, ?'oclock' => string, ?'size' => int, ?'uid' => int, ... )>, ?'is_fresh_instance' => bool, ?'metadata' => mixed, ?'named_pipe' => string, ?'no_sync_needed' => vec<string>, ?'root' => string, ?'roots' => vec<string>, ?'sockname' => string, ?'subscription' => string, ?'state-enter' => string, ?'synced' => vec<string>, ?'unix_domain' => string, ?'warning' => string, ... ); function watchman_query( mixed $json_query, ?string $socket_name = null, ): Awaitable<WatchmanResult>; function watchman_subscribe( string $json_query, string $path, string $sub_name, string $callback, ?string $socket_name = null, ): Awaitable<void>; function watchman_check_sub(string $sub_name): bool; function watchman_sync_sub( string $sub_name, int $timeout_ms = 0, ): Awaitable<bool>; function watchman_unsubscribe(string $sub_name): Awaitable<string>; function ext_watchman_version(): int; } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/functions.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of PHP's predefined functions * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace { // <<__PHPStdLib>> function array_fill<T>( int $start_index, int $num, T $value, )[]: varray_or_darray<T>; // TODO make non-nullable once Thrift files are fixed <<__PHPStdLib>> function chr(int $ascii)[]: string; <<__PHPStdLib>> function count( readonly mixed $x, int $mode = COUNT_NORMAL, )[]: int; // count takes Countable or array. We'll need to hardcode this... <<__PHPStdLib>> function dechex(int $number)[]: string; <<__PHPStdLib>> function implode( string $glue, readonly HH\FIXME\MISSING_PARAM_TYPE $pieces, )[]: string; // could be Container<Stringish> <<__PHPStdLib>> function explode( string $delimiter, string $str, int $limit = 0x7FFFFFFF, )[]: varray<string>; // : array<string> & false for '' delimiter } namespace HH { function is_vec(readonly mixed $arg)[]: bool; function is_dict(readonly mixed $arg)[]: bool; function is_keyset(readonly mixed $arg)[]: bool; /** * @returns True if `$arg` is a `varray`, `darray`, `dict`, `vec`, or `keyset`. * Otherwise returns false. */ function is_any_array(readonly mixed $arg)[]: bool; } namespace { <<__PHPStdLib>> function ord(string $string)[]: int; <<__PHPStdLib>> function strip_tags(string $str, string $allowable_tags = ''): string; <<__PHPStdLib>> function intval(HH\FIXME\MISSING_PARAM_TYPE $v, int $base = 10)[]: int; <<__PHPStdLib>> function doubleval(HH\FIXME\MISSING_PARAM_TYPE $v)[]: float; <<__PHPStdLib>> function floatval(HH\FIXME\MISSING_PARAM_TYPE $v)[]: float; <<__PHPStdLib>> function strval(HH\FIXME\MISSING_PARAM_TYPE $v)[]: string; <<__PHPStdLib>> function boolval(HH\FIXME\MISSING_PARAM_TYPE $v)[]: bool; <<__PHPStdLib>> function get_class_constants(string $class_name)[]: darray<string, mixed>; } namespace HH { // autoload-map function could_include(\HH\FIXME\MISSING_PARAM_TYPE $file): bool; function autoload_is_native(): bool; /** * Get the path which uniquely defines the given symbol. * * Returns an absolute canonical path with all symlinks dereferenced. * * Throws InvalidOperationException if native autoloading is disabled. */ function autoload_type_to_path(string $type): ?string; function autoload_function_to_path(string $function): ?string; function autoload_constant_to_path(string $constant): ?string; function autoload_module_to_path(string $module): ?string; function autoload_type_alias_to_path(string $type_alias): ?string; /** * Get the types defined in the given path. * * The path may be relative to the repo root or absolute. But this function * will not dereference symlinks for you, so providing a path with symlinks * may cause this function to return an empty vec when you expected results. * * Throws InvalidOperationException if native autoloading is disabled. */ function autoload_path_to_types(string $path): vec<classname<mixed>>; function autoload_path_to_functions(string $path): vec<string>; function autoload_path_to_constants(string $path): vec<string>; function autoload_path_to_modules(string $path): vec<string>; function autoload_path_to_type_aliases(string $path): vec<string>; newtype ParseTree = darray<string, mixed>; function ffp_parse_string(string $program)[]: ParseTree; function clear_static_memoization(?string $cls, ?string $func = null): bool; function clear_lsb_memoization(string $cls, ?string $func = null): bool; function clear_instance_memoization(\HH\FIXME\MISSING_PARAM_TYPE $obj): bool; function is_list_like(readonly mixed $arg)[]: bool; function is_meth_caller(readonly mixed $arg)[]: bool; function is_fun(readonly mixed $arg)[]: bool; function set_frame_metadata(mixed $metadata)[]: void; // Code coverage function enable_per_file_coverage(keyset<string> $files): void; function disable_per_file_coverage(keyset<string> $files): void; function get_files_with_coverage(): keyset<string>; function get_coverage_for_file(string $file): vec<int>; function clear_coverage_for_file(string $file): void; function disable_all_coverage(): void; function get_all_coverage_data(): dict<string, vec<int>>; function clear_all_coverage_data(): void; function prefetch_units(keyset<string> $paths, bool $hint): void; }
HTML Help Workshop
hhvm/hphp/hack/hhi/func_pointers.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, 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. * */ namespace HH { // The functions in this file are defined in HHVM and known to the // typechecker. There's no typechecker annotation syntax capable of // describing how they are used to infer type info; these .hhi declarations // are strictly for documentation purposes. /** * Create a function reference to an instance method that can be called on any * instance of the same type * * The global function `meth_caller('cls_name', 'meth_name')` creates a reference * to an instance method on the specified class. This method can then be used * to execute across a collection of objects of that class. * * To identify the class for the function, use a class reference of the format * `MyClassName::class`. * * Hack provides a variety of methods that allow you to construct references to * methods for delegation. The methods in this group are: * * - [`class_meth`](/hack/reference/function/HH.class_meth/) for static methods on a class * - [`fun`](/hack/reference/function/HH.fun/) for global functions * - [`inst_meth`](/hack/reference/function/HH.inst_meth/) for instance methods on a single object * - [`meth_caller`](/hack/reference/function/HH.meth_caller/) for an instance method where the instance will be determined later * - Or use anonymous code within a [lambda](/hack/lambdas/introduction) expression. * * # Example * * ``` * <?hh // strict * $v = Vector { Vector { 1, 2, 3 }, Vector { 1, 2 }, Vector { 1 } }; * * // Each result returns Vector { 3, 2, 1 }; * $result2 = $v->map(meth_caller(Vector::class, 'count')); * $result3 = $v->map($x ==> $x->count()); * ``` * @param $cls_name A constant string with the name of the class, or * a class reference using `FullClassName::class`. * @param $meth_name A constant string with the name of the instance method. * @return $func_ref A fully typed function reference to the instance method. */ function meth_caller( string $cls_name, string $meth_name, ): \HH\FIXME\MISSING_RETURN_TYPE; // becomes: // function meth_caller(C::class or 'C', 'method') // : (function(C): <the return type of C::method>) /** * Call `invariant_violation` if the condition is false. * * ``` * invariant($x >= 0, "Value cannot be negative: %d", $x); * ``` * * See http://docs.hhvm.com/hack/reference/function/HH.invariant/ */ function invariant( \HH\FIXME\MISSING_PARAM_TYPE $condition, FormatString<\PlainSprintf> $f, mixed ...$f_args )[]: void; // becomes: // if (!(<condition>)) { // an Exception is thrown // invariant_violation('sprintf format: %s', 'string', ...); // } // <condition> is known to be true in the code below /** * See * http://docs.hhvm.com/hack/reference/function/HH.invariant_callback_register/ */ function invariant_callback_register( (function(string, mixed...): void) $callback, )[globals]: void {} } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/hackarray.hhi
<?hh // partial /** * 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. * */ namespace HH { /** * The parent class for all array types (containers that are values). * This currently includes both Hack Arrays (vec, dict, keyset) and Legacy * Arrays (varray, darray). */ <<__Sealed(dict::class, keyset::class, vec::class), __SupportDynamicType>> abstract class AnyArray< <<__NoAutoBound>> +Tk as arraykey, <<__NoAutoBound>> +Tv, > implements KeyedContainer<Tk, Tv>, \XHPChild { } /** * A dict is an ordered, key-value data structure. * * `dict` is a value type, so any mutation produces a new value. */ <<__SupportDynamicType>> abstract final class dict< <<__NoAutoBound>> +Tk as arraykey, <<__NoAutoBound>> +Tv, > extends AnyArray<Tk, Tv> {} /** * A `keyset` is an ordered data structure without duplicates. `keyset`s can only contain `arraykey` values. * * `keyset` is a value type, so any mutation produces a new value. */ <<__SupportDynamicType>> abstract final class keyset<<<__NoAutoBound>> +T as arraykey> extends AnyArray<T, T> {} /** * A `vec` is an ordered, iterable data structure. The name is short for 'vector'. * * `vec` is a value type, so any mutation produces a new value. */ <<__SupportDynamicType>> abstract final class vec<<<__NoAutoBound>> +T> extends AnyArray<int, T> {} } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/idx.hhi
<?hh /** * Copyright (c) 2014, 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. * */ namespace HH { // NB: the typechecker relies on the exact format of this signature and rewrites // parts of it in place during each call. Changes to the signature need to be // done in tandem with changes to the ocaml code that munges it. // // Calls to `idx` are rewritten by the typechecker depending on their arity. It // can have two signatures: // // idx<Tk, Tv>(?KeyedContainer<Tk, ?Tv> $collection, ?Tk $index): ?Tv // idx<Tk, Tv>(?KeyedContainer<Tk, Tv> $collection, ?Tk $index, Tv $default): Tv /** * Index into the given KeyedContainer using the provided key. * * If the key doesn't exist, the key is `null`, or the collection is `null`, * return the provided default value instead, or `null` if no default value was * provided. If the key is `null`, the default value will be returned even if * `null` is a valid key in the container. */ function idx<Tk as arraykey, Tv>( ?KeyedContainer<Tk, Tv> $collection, ?Tk $index, \HH\FIXME\MISSING_PARAM_TYPE $default = null, )[]: Tv {} function idx_readonly<Tk as arraykey, Tv>( readonly ?KeyedContainer<Tk, Tv> $collection, ?Tk $index, \HH\FIXME\MISSING_PARAM_TYPE $default = null, )[]: readonly Tv {} }
HTML Help Workshop
hhvm/hphp/hack/hhi/implicit_context.hhi
<?hh namespace HH { namespace ImplicitContext { async function soft_run_with_async<Tout>( (function()[_]: Awaitable<Tout>) $f, string $key, )[zoned, ctx $f]: Awaitable<Tout>; function soft_run_with<Tout>( (function()[_]: Tout) $f, string $key, )[zoned, ctx $f]: Tout; /** * Captures the current IC state and returns a new closure that calls the * input closure using that state. * * Use this when deferring or batching closures under a different IC state * than when they may be executed. */ function embed_implicit_context_state_in_closure<T>( (function ()[defaults]: T) $f, )[zoned]: (function ()[defaults]: T); /** * Variation of embed_implicit_context_state_in_closure * specifically for async closures */ function embed_implicit_context_state_in_async_closure<T>( (function ()[defaults]: Awaitable<T>) $f, )[zoned]: (function ()[defaults]: Awaitable<T>); } // namespace ImplicitContext abstract class ImplicitContext { abstract const type T as nonnull; protected static async function runWithAsync<Tout>( this::T $context, (function()[_]: Awaitable<Tout>) $f, )[zoned, ctx $f]: Awaitable<Tout>; protected static function runWith<Tout>( this::T $context, (function()[_]: Tout) $f, )[zoned, ctx $f]: Tout; protected static function get()[zoned]: ?this::T; } /** * Options for memoization to be used with dynamically enforced implicit * context */ enum class MemoizeOption: string { /** * Incorporate the Implicit Context state into the memoization cache key. */ string KeyedByIC = 'KeyedByIC'; /** * Do not incorporate the Implicit Context state into the memoization cache * key. * Attempting to fetch the Implicit Context in this function or a recursive * callee will result in an exception. * Calling an "uncategorized" memoized function including one using * #SoftMakeICInaccessible will result in an exception. */ string MakeICInaccessible = 'MakeICInaccessible'; /** * Will throw if called with an Implicit Context value. * Do not incorporate the Implicit Context state into the memoization cache * key. * Behaviors that would result in an exception under #MakeICInaccessible * will log instead. */ string SoftMakeICInaccessible = 'SoftMakeICInaccessible'; /** * Default option for memoization attributes. * Will throw if called with an Implicit Context value. * Do not incorporate the Implicit Context state into the memoization cache * key. */ string Uncategorized = 'Uncategorized'; } /** * States obtainable via get_state_unsafe */ enum State: string as string { NULL = 'NULL'; VALUE = 'VALUE'; SOFT_SET = 'SOFT_SET'; INACCESSIBLE = 'INACCESSIBLE'; SOFT_INACCESSIBLE = 'SOFT_INACCESSIBLE'; } } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/interfaces.hhi
<?hh // partial /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of PHP's predefined interfaces * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * Represents an entity that can be iterated over using `foreach`, without * requiring a key. * * The iteration variable will have a type of `T`. * * In addition to Hack collections, PHP `array`s and anything that implement * `Iterator` are `Traversable`. * * In general, if you are implementing your own Hack class, you will want to * implement `Iterable` instead of `Traversable` since `Traversable` is more * of a bridge for PHP `array`s to work well with Hack collections. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed( Container::class, \Imagick::class, Iterator::class, \IteratorAggregate::class, KeyedTraversable::class, \ResourceBundle::class, \SplHeap::class, )>> interface Traversable<<<__NoAutoBound>> +Tv> { } /** * Represents an entity that can be iterated over using `foreach`, allowing * a key. * * The iteration variables will have a type of `Tk` for the key and `Tv` for the * value. * * In addition to Hack collections, PHP `array`s and anything that implement * `KeyedIterator` are `KeyedTraversable`. * * In general, if you are implementing your own Hack class, you will want to * implement `KeyedIterable` instead of `KeyedTraversable` since * `KeyedTraversable` is more of a bridge for PHP `array`s to work well with * Hack collections. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed( \ArrayIterator::class, \AsyncMysqlRowBlock::class, \DOMNamedNodeMap::class, \ImagickPixelIterator::class, \IntlBreakIterator::class, KeyedContainer::class, KeyedIterable::class, KeyedIterator::class, \MysqlRow::class, )>> interface KeyedTraversable<+Tk, <<__NoAutoBound>> +Tv> extends Traversable<Tv> {} /** * Represents an entity that can be iterated over using `foreach`, without * requiring a key, except it does not include objects that implement * `Iterator`. * * The iteration variable will have a type of `T`. * * In addition to Hack collections, PHP `array`s are `Container`s. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(KeyedContainer::class)>> interface Container<<<__NoAutoBound>> +Tv> extends Traversable<Tv> { } /** * `KeyedContainer` allows you to do `(foreach $value as $k => $v, $value[$key])` and is an * interface used by both Hack arrays (vec/dict/keyset) and Hack collections (Vector/Map/Set). * * If you need to iterate over an array / collection with keys, use KeyedContainer; otherwise, use Container. * Without iterating, you can access keys directly: `$keyed_container[$key]`. * * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces * @guide /hack/collections/read-write */ <<__Sealed( \ConstVector::class, \ConstMap::class, \ConstSet::class, AnyArray::class, )>> interface KeyedContainer<<<__NoAutoBound>> +Tk as arraykey, <<__NoAutoBound>> +Tv> extends Container<Tv>, KeyedTraversable<Tk, Tv> {} /** * For those entities that are `Traversable`, the `Iterator` interfaces provides * the methods of iteration. * * If a class implements `Iterator`, then it provides the infrastructure to be * iterated over using a `foreach` loop. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces * * @link http://php.net/manual/en/class.iterator.php */ interface Iterator<+Tv> extends Traversable<Tv> { /** * Return the current value at the current iterator position. * * @return - The current value of type `Tv`. */ public function current(): Tv; /** * Returns the current key that the iterator points to. */ public function key(): mixed; /** * Move the iterator position to the next element. * */ public function next(): void; /** * Rewind the iterator position to its beginning. * * This rewinds back to the first element of the `Iterator`. */ public function rewind(): void; /** * Checks to see if the current iterator position is valid. * * This method is called after `rewind()` and `next()` to check if the * current iterator position is valid. * * @return - `true` if the position is valid; `false` otherwise. */ public function valid(): bool; } /** * Allows for the iteration over the values provided by an `async` function. * * If an `async` function returns an `AsyncIterator<T>`, then you can iterate * over the `T` values returned from that function. * * ``` * async function countdown(int $start): AsyncIterator<int> { ... } * * async function use_countdown(): Awaitable<void> { * $async_iter = countdown(100); * foreach ($async_iter await as $value) { ... } * } * ``` * * @guide /hack/async/introduction * @guide /hack/async/guidelines */ interface AsyncIterator<+Tv> { /** * Move the async iterator to the next `Awaitable` position. * * ``` * foreach ($async_iter await $async_iter->next() $value) * ``` * * The above is the longhand syntax for `await as $value`. * * @return - The next `Awaitable` in the iterator sequence. */ public function next(): Awaitable<?(mixed, Tv)>; } /** * Allows for the iteration over the keys and values provided by an `async` * function. * * If an `async` function returns an `AsyncIterator<Tk, Tv>`, then you can * iterate over the `Tk` and `Tv` values returned from that function. * * ``` * async function countdown(int $start): AsyncIterator<int, string> { ... } * * async function use_countdown(): Awaitable<void> { * $async_iter = countdown(100); * foreach ($async_gen await as $num => $str) { ... } * } * ``` * * @guide /hack/async/introduction * @guide /hack/async/guidelines */ interface AsyncKeyedIterator<+Tk, +Tv> extends AsyncIterator<Tv> { /** * Move the async iterator to the next `Awaitable` position. * * ``` * foreach ($async_iter await $async_iter->next() $key=>$value) * ``` * * The above is the longhand syntax for `await as $key=>$value`. * * @return - The next `Awaitable` in the iterator sequence. */ public function next(): Awaitable<?(Tk, Tv)>; } /** * For those entities that are `KeyedTraversable`, the `KeyedIterator` * interfaces provides the methods of iteration, included being able to get * the key. * * If a class implements `KeyedIterator`, then it provides the infrastructure * to be iterated over using a `foreach` loop. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ interface KeyedIterator<+Tk, +Tv> extends KeyedTraversable<Tk, Tv>, Iterator<Tv> { /** * Return the current key at the current iterator position. * * @return - The current key of type `Tk`. */ public function key(): Tk; } } // namespace HH namespace { /** * Represents objects that can produce an `Iterator` object to iterate over * their contents using `foreach`. * * Normally, this interface won't be used in type annotations; rather `Iterable` * or `Traversable` will be the better interface. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces * * @link http://php.net/manual/en/class.iteratoraggregate.php */ interface IteratorAggregate<+Tv> extends Traversable<Tv> { /** * Returns an iterator to be used to iterate over the object's elements. * * @return - An `Iterator` for iteration. */ public function getIterator(): Iterator<Tv>; } } // namespace namespace HH { /** * Represents any entity that can be iterated over using something like * `foreach`. The entity does not necessarily have to have a key, just values. * * `Iterable` does not include `array`s. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ interface Iterable<+Tv> extends \IteratorAggregate<Tv> { /** * Returns an iterator that points to beginning of the current `Iterable`. * * @return - An `Iterator` that allows you to traverse the current `Iterable`. */ public function getIterator(): Iterator<Tv>; /** * Returns an `array` with the values from the current `Iterable`. * * The keys in the current `Iterable` are discarded and replaced with integer * indices, starting with 0. * * @return - an `array` containing the values from the current `Iterable`. */ public function toValuesArray(): varray<Tv>; /** * Returns an immutable vector (`ImmVector`) converted from the current * `Iterable`. * * Any keys in the current `Iterable` are discarded and replaced with integer * indices, starting with 0. * * @return - an `ImmVector` converted from the current `Iterable`. */ public function toImmVector(): ImmVector<Tv>; /** * Returns an immutable set (`ImmSet`) converted from the current `Iterable`. * * Any keys in the current `Iterable` are discarded. * * @return - an `ImmSet` converted from the current `Iterable`. */ public function toImmSet(): ImmSet<Tv> where Tv as arraykey; /** * Returns a lazy, access elements only when needed view of the current * `Iterable`. * * Normally, memory is allocated for all of the elements of the `Iterable`. * With a lazy view, memory is allocated for an element only when needed or * used in a calculation like in `map()` or `filter()`. * * @return - an `Iterable` representing the lazy view into the current * `Iterable`. * * @guide /hack/collections/examples */ public function lazy(): Iterable<Tv>; /** * Returns an `Iterable` containing the current `Iterable`'s values. * * Any keys are discarded. * * @return An `Iterable` with the values of the current `Iterable`. */ public function values(): Iterable<Tv>; /** * Returns an `Iterable` containing the values of the current `Iterable` that * meet a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The callback containing the condition to apply to the * `Itearble` values. * * @return - an `Iterable` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: Iterable<Tv>; /** * Returns an `Iterable` where each element is a `Pair` that combines the * element of the current `Iterable` and the provided `Traversable`. * * If the number of elements of the `Iterable` are not equal to the number of * elements in the `Traversable`, then only the combined elements up to and * including the final element of the one with the least number of elements * is included. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `Iterable`. * * @return - The `Iterable` that combines the values of the current * `Itearable` with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, ): Iterable<Pair<Tv, Tu>>; /** * Returns an `Iterable` containing the first `n` values of the current * `Iterable`. * * The returned `Iterable` will always be a proper subset of the current * `Iterable`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the returned * `Iterable`. * * @return - An `Iterable that is a proper subset of the current `Iterable` * up to `n` elements. */ public function take(int $n): Iterable<Tv>; /** * Returns an `Iterable` containing the values of the current `Iterable` up * to but not including the first value that produces `false` when passed to * the specified callback. * * The returned `Iterable` will always be a proper subset of the current * `Iterable`. * * @param $fn - The callback that is used to determine the stopping * condition. * * @return - An `Iterable` that is a proper subset of the current `Iterable` * up until the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: Iterable<Tv>; /** * Returns an `Iterable` containing the values after the `n`-th element of the * current `Iterable`. * * The returned `Iterable` will always be a proper subset of the current * `Iterable`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be * the first one in the returned `Iterable`. * * @return - An `Iterable` that is a proper subset of the current `Iterable` * containing values after the specified `n`-th element. */ public function skip(int $n): Iterable<Tv>; /** * Returns an `Iterable` containing the values of the current `Iterable` * starting after and including the first value that produces `true` when * passed to the specified callback. * * The returned `Iterable` will always be a proper subset of the current * `Iterable`. * * @param $fn - The callback used to determine the starting element for the * returned `Iterable`. * * @return - An `Iterable` that is a proper subset of the current `Iterable` * starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: Iterable<Tv>; /** * Returns a subset of the current `Iterable` starting from a given key up * to, but not including, the element at the provided length from the * starting key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `Iterable` will always be a proper subset of the current * `Iterable`. * * @param $start - The starting key of the current `Iterable` to begin the * returned `Iterable`. * @param $len - The length of the returned `Iterable`. * * @return - An `Iterable` that is a proper subset of the current `Iterable` * starting at `$start` up to but not including the element * `$start + $len`. */ public function slice(int $start, int $len): Iterable<Tv>; /** * Returns an `Iterable` that is the concatenation of the values of the * current `Iterable` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `Iterable` to produce the returned `Iterable`. * * @param $traversable - The `Traversable` to concatenate to the current * `Iterable`. * * @return - The concatenated `Iterable`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, ): Iterable<Tu>; /** * Returns the first value in the current `Iterable`. * * @return - The first value in the current `Iterable`, or `null` if the * current `Iterable` is empty. */ public function firstValue(): ?Tv; /** * Returns the last value in the current `Iterable`. * * @return - The last value in the current `Iterable`, or `null` if the * current `Iterable` is empty. */ public function lastValue(): ?Tv; } /** * Represents any entity that can be iterated over using something like * `foreach`. The entity is required to have a key in addition to values. * * `KeyedIterable` does not include `array`s. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ interface KeyedIterable<Tk, +Tv> extends KeyedTraversable<Tk, Tv>, Iterable<Tv> { /** * Returns an iterator that points to beginning of the current * `KeyedIterable`. * * @return - A `KeyedIterator` that allows you to traverse the current * `KeyedIterable`. */ public function getIterator(): KeyedIterator<Tk, Tv>; /** * Returns an `array` with the keys from the current `KeyedIterable`. * * @return - an `array` containing the values from the current * `KeyedIterable`. */ public function toKeysArray(): varray<Tk>; /** * Returns an immutable map (`ImmMap`) based on the keys and values of the * current `KeyedIterable`. * * @return - an `ImmMap` that has the keys and associated values of the * current `KeyedIterable`. */ public function toImmMap(): ImmMap<Tk, Tv> where Tk as arraykey; /** * Returns a lazy, access elements only when needed view of the current * `KeyedIterable`. * * Normally, memory is allocated for all of the elements of the * `KeyedIterable`. With a lazy view, memory is allocated for an element only * when needed or used in a calculation like in `map()` or `filter()`. * * @return - a `KeyedIterable` representing the lazy view into the current * `KeyedIterable`. * * @guide /hack/collections/examples */ public function lazy(): KeyedIterable<Tk, Tv>; /** * Returns an `Iterable` containing the current `KeyedIterable`'s values. * * Any keys are discarded. * * @return An `Iterable` with the values of the current `KeyedIterable`. */ public function values(): Iterable<Tv>; /** * Returns an `Iterable` containing the current `KeyedIterable`'s keys. * * Any values are discarded. * * @return An `Iterable` with the keys of the current `KeyedIterable`. */ public function keys(): Iterable<Tk>; /** * Returns a `KeyedIterable` containing the values of the current * `KeyedIterable` that meet a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The callback containing the condition to apply to the * `KeyedItearble` values. * * @return - a `KeyedIterable` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; /** * Returns a `KeyedIterable` containing the values of the current * `KeyedIterable` that meet a supplied condition applied to its keys and * values. * * Only keys and values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * @param $fn - The callback containing the condition to apply to the * `KeyedIterable` keys and values. * * @return - a `KeyedIterable` containing the values after a user-specified * condition is applied to the keys and values of the current * `KeyedIterable`. * */ public function filterWithKey( (function(Tk, Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; /** * Returns a `KeyedIterable` where each element is a `Pair` that combines the * element of the current `KeyedIterable` and the provided `Traversable`. * * If the number of elements of the `KeyedIterable` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `KeyedIterable`. * * @return - The `KeyedIterable` that combines the values of the current * `KeyedItearable` with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, ): KeyedIterable<Tk, Pair<Tv, Tu>>; /** * Returns a `KeyedIterable` containing the first `n` values of the current * `KeyedIterable`. * * The returned `KeyedIterable` will always be a proper subset of the current * `Iterable`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the returned * `KeyedIterable`. * * @return - A `KeyedIterable that is a proper subset of the current * `KeyedIterable` up to `n` elements. */ public function take(int $n): KeyedIterable<Tk, Tv>; /** * Returns a `KeyedIterable` containing the values of the current * `KeyedIterable` up to but not including the first value that produces * `false` when passed to the specified callback. * * The returned `KeyedIterable` will always be a proper subset of the current * `KeyedIterable`. * * @param $fn - The callback that is used to determine the stopping * condition. * * @return - A `KeyedIterable` that is a proper subset of the current * `KeyedIterable` up until the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; /** * Returns a `KeyedIterable` containing the values after the `n`-th element * of the current `KeyedIterable`. * * The returned `KeyedIterable` will always be a proper subset of the current * `KeyedIterable`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be * the first one in the returned `KeyedIterable`. * * @return - A `KeyedIterable` that is a proper subset of the current * `KeyedIterable` containing values after the specified `n`-th * element. */ public function skip(int $n): KeyedIterable<Tk, Tv>; /** * Returns a `KeyedIterable` containing the values of the current * `KeyedIterable` starting after and including the first value that produces * `true` when passed to the specified callback. * * The returned `KeyedIterable` will always be a proper subset of the current * `KeyedIterable`. * * @param $fn - The callback used to determine the starting element for the * returned `KeyedIterable`. * * @return - A `KeyedIterable` that is a proper subset of the current * `KeyedIterable` starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; /** * Returns a subset of the current `KeyedIterable` starting from a given key * up to, but not including, the element at the provided length from the * starting key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `KeyedIterable` will always be a proper subset of the current * `KeyedIterable`. * * @param $start - The starting key of the current `KeyedIterable` to begin * the returned `KeyedIterable`. * @param $len - The length of the returned `KeyedIterable`. * * @return - A `KeyedIterable` that is a proper subset of the current * `KeyedIterable` starting at `$start` up to but not including the * element `$start + $len`. */ public function slice(int $start, int $len): KeyedIterable<Tk, Tv>; /** * Returns an `Iterable` that is the concatenation of the values of the * current `KeyedIterable` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `KeyedIterable` to produce the returned `Iterable`. * * @param $traversable - The `Traversable` to concatenate to the current * `KeyedIterable`. * * @return - The concatenated `Iterable`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, ): Iterable<Tu>; /** * Returns the first value in the current `KeyedIterable`. * * @return - The first value in the current `KeyedIterable`, or `null` if the * current `KeyedIterable` is empty. */ public function firstValue(): ?Tv; /** * Returns the first key in the current `KeyedIterable`. * * @return - The first key in the current `KeyedIterable`, or `null` if the * current `KeyedIterable` is empty. */ public function firstKey(): ?Tk; /** * Returns the last value in the current `KeyedIterable`. * * @return - The last value in the current `KeyedIterable`, or `null` if the * current `KeyedIterable` is empty. */ public function lastValue(): ?Tv; /** * Returns the last key in the current `KeyedIterable`. * * @return - The last key in the current `KeyedIterable`, or `null` if the * current `KeyedIterable` is empty. */ public function lastKey(): ?Tk; } } // namespace HH namespace { interface Serializable { public function serialize(): string; public function unserialize(string $serialized): void; } interface Countable { public function count(): int; } interface RecursiveIterator<+Tv> extends Iterator<Tv> { // see RecursiveDirectoryIterator public function getChildren(): ?HH\FIXME\POISON_MARKER<this>; public function hasChildren(): bool; } interface SeekableIterator<+Tv> extends Iterator<Tv> { public function seek(int $position): void; } interface OuterIterator<+Tv> extends Iterator<Tv> { public function getInnerIterator(): Iterator<Tv>; } interface ArrayAccess<Tk, Tv> { public function offsetExists(Tk $key): bool; public function offsetGet(Tk $key): Tv; public function offsetSet(Tk $key, Tv $val): void; public function offsetUnset(Tk $key): void; } /** * @see http://www.php.net/manual/en/jsonserializable.jsonserialize.php */ interface JsonSerializable { /** * Return data which can be serialized with json_encode. */ public function jsonSerialize(): mixed; } /** * XHPChild is the base type of values that can be children of XHP elements. * Most primitive types implement XHPChild: string, int, float, and array. * * Classes that implement XHPChild must do so by implementing the XHPChildClass * subinterface. */ interface XHPChild {} /** * Stringish is a type that matches strings as well as string-convertible * objects: that is, objects that provide the __toString method */ <<__Sealed(StringishObject::class)>> interface Stringish extends XHPChild {} /** * StringishObject represents values of Stringish that are specifically objects */ interface StringishObject extends Stringish { public function __toString(): string; } interface IZonedStringishObject extends StringishObject { public function __toString()[zoned]: string; } interface ILeakSafeStringishObject extends IZonedStringishObject { public function __toString()[leak_safe]: string; } interface IPureStringishObject extends ILeakSafeStringishObject { public function __toString()[]: string; } } // namespace namespace HH { /** * Classes that implement `IMemoizeParam` may be used as parameters on * `<<__Memoize>>` functions. * * @guide /hack/attributes/introduction * @guide /hack/attributes/special */ interface IMemoizeParam { abstract const ctx CMemoParam = [defaults]; /** * Serialize this object to a string that can be used as a * dictionary key to differentiate instances of this class. */ public function getInstanceKey(): string; } /* * Unsafe marker interface for an IMemoizeParam used to override * typechecker check that IMemoizeParam objects are only used as parameters * on functions that have access to globals. * Singleton classes are allowed to be passed into pure memoized functions because there can't * be a data leak associated with them. * TODO: enforce SingletonMemoizeParam in some way in runtime/typechecker */ interface UNSAFESingletonMemoizeParam extends IMemoizeParam { public function getInstanceKey(): string; } } // namespace HH namespace { /** * Objects that implement `IDisposable` may be used in `using` statements. */ interface IDisposable { /** * This method is invoked exactly once at the end of the scope of the * `using` statement, unless the program terminates with a fatal error. */ public function __dispose(): void; } /** * Objects that implement `IAsyncDisposable` may be used in `using` * statements with `await`. */ interface IAsyncDisposable { /** * This method is invoked exactly once at the end of the scope of the * `using` statement, unless the program terminates with a fatal error. */ public function __disposeAsync(): Awaitable<void>; } } // namespace
HTML Help Workshop
hhvm/hphp/hack/hhi/InvalidOperationException.hhi
<?hh /** * Copyright (c) 2014, 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. * */ class InvalidOperationException extends RuntimeException implements StringishObject {}
HTML Help Workshop
hhvm/hphp/hack/hhi/Label.hhi
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH\EnumClass { /** * Type of enum class labels */ newtype Label<-TEnumClass, TType> = mixed; }
HTML Help Workshop
hhvm/hphp/hack/hhi/NumberFormatter.hhi
<?hh /** * Copyright (c) 2014, 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. * */ class NumberFormatter { const int PATTERN_DECIMAL; const int DECIMAL; const int CURRENCY; const int PERCENT; const int SCIENTIFIC; const int SPELLOUT; const int ORDINAL; const int DURATION; const int PATTERN_RULEBASED; const int IGNORE; const int DEFAULT_STYLE; const int ROUND_CEILING; const int ROUND_FLOOR; const int ROUND_DOWN; const int ROUND_UP; const int ROUND_HALFEVEN; const int ROUND_HALFDOWN; const int ROUND_HALFUP; const int PAD_BEFORE_PREFIX; const int PAD_AFTER_PREFIX; const int PAD_BEFORE_SUFFIX; const int PAD_AFTER_SUFFIX; const int PARSE_INT_ONLY; const int GROUPING_USED; const int DECIMAL_ALWAYS_SHOWN; const int MAX_INTEGER_DIGITS; const int MIN_INTEGER_DIGITS; const int INTEGER_DIGITS; const int MAX_FRACTION_DIGITS; const int MIN_FRACTION_DIGITS; const int FRACTION_DIGITS; const int MULTIPLIER; const int GROUPING_SIZE; const int ROUNDING_MODE; const int ROUNDING_INCREMENT; const int FORMAT_WIDTH; const int PADDING_POSITION; const int SECONDARY_GROUPING_SIZE; const int SIGNIFICANT_DIGITS_USED; const int MIN_SIGNIFICANT_DIGITS; const int MAX_SIGNIFICANT_DIGITS; const int LENIENT_PARSE; const int POSITIVE_PREFIX; const int POSITIVE_SUFFIX; const int NEGATIVE_PREFIX; const int NEGATIVE_SUFFIX; const int PADDING_CHARACTER; const int CURRENCY_CODE; const int DEFAULT_RULESET; const int PUBLIC_RULESETS; const int DECIMAL_SEPARATOR_SYMBOL; const int GROUPING_SEPARATOR_SYMBOL; const int PATTERN_SEPARATOR_SYMBOL; const int PERCENT_SYMBOL; const int ZERO_DIGIT_SYMBOL; const int DIGIT_SYMBOL; const int MINUS_SIGN_SYMBOL; const int PLUS_SIGN_SYMBOL; const int CURRENCY_SYMBOL; const int INTL_CURRENCY_SYMBOL; const int MONETARY_SEPARATOR_SYMBOL; const int EXPONENTIAL_SYMBOL; const int PERMILL_SYMBOL; const int PAD_ESCAPE_SYMBOL; const int INFINITY_SYMBOL; const int NAN_SYMBOL; const int SIGNIFICANT_DIGIT_SYMBOL; const int MONETARY_GROUPING_SEPARATOR_SYMBOL; const int TYPE_DEFAULT; const int TYPE_INT32; const int TYPE_INT64; const int TYPE_DOUBLE; const int TYPE_CURRENCY; public function __construct( string $locale, int $style, string $pattern = "#,##0.###", ); public function formatCurrency(float $value, string $currency)[]: string; public function format( mixed $value, int $type = NumberFormatter::TYPE_DEFAULT, )[]: string; public function getAttribute(int $attr)[]: int; public function getErrorCode()[]: int; public function getErrorMessage()[]: string; public function getLocale(int $type = Locale::ACTUAL_LOCALE)[]: string; public function getPattern()[]: string; public function getSymbol(int $attr)[]: string; public function getTextAttribute(int $attr)[]: string; public function parseCurrency( string $value, inout string $currency, inout int $position, ): float; public function parse( string $value, int $type = NumberFormatter::TYPE_DOUBLE, ): mixed; public function parseWithPosition( string $value, int $type, inout int $position, ): mixed; public function setAttribute(int $attr, int $value)[]: bool; public function setPattern(string $pattern)[]: bool; public function setSymbol(int $attr, string $value)[]: bool; public function setTextAttribute(int $attr, string $value)[]: bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/printf.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, 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. * */ namespace { /** * This type has some magic behavior: whenever it appears as a * function parameter (in a function with varargs), the argument must * be a static string, and will be parsed for % formatting specifiers * (which will determine the type of the varargs). * * T is treated as a state machine. After the first %, each character * causes the corresponding method in T to be looked up. For example, * '%b' will "call" the method * * function format_b(int $s) : string; * * and consume an 'int' from the argument list. * * Hex escapes are used for non-alphabetic characters. The '%%' * pseudo-specifier consumes nothing and appears as * * function format_0x25() : string; * * Modifiers and multi-char entries can be encoded by return a new * formatter instead of a string: * * function format_upcase_l() : ListFormatter; * function format_0x2a(int $s) : PaddingFormatter; * * Note that you *could* use an actual instance of T to do the * formatting. We don't; T is only here to provide the types. * * For another example on how to implement your own format string interface, * see \HH\Lib\Str\SprintfFormat in the HSL. */ interface PlainSprintf { // Technically %d should only take ints, but we don't. public function format_d(mixed $s)[]: string; public function format_s(?arraykey $s)[]: string; public function format_u(?int $s)[]: string; public function format_b(int $s)[]: string; // bit strings // Technically %f is locale-dependent (and thus wrong), but we don't. public function format_f(mixed $s)[]: string; public function format_g(?float $s)[]: string; public function format_upcase_f(?float $s)[]: string; public function format_upcase_e(?float $s)[]: string; public function format_e(?float $s)[]: string; public function format_x(mixed $s)[]: string; public function format_o(?int $s)[]: string; public function format_c(?int $s)[]: string; public function format_upcase_x(?int $s)[]: string; // %% takes no arguments public function format_0x25()[]: string; // %'(char) public function format_0x27()[]: SprintfQuote; // Modifiers that don't change the type public function format_l()[]: PlainSprintf; public function format_0x20()[]: PlainSprintf; // ' ' public function format_0x2b()[]: PlainSprintf; // '+' public function format_0x2d()[]: PlainSprintf; // '-' public function format_0x2e()[]: PlainSprintf; // '.' public function format_0x30()[]: PlainSprintf; // '0' public function format_0x31()[]: PlainSprintf; // ... public function format_0x32()[]: PlainSprintf; public function format_0x33()[]: PlainSprintf; public function format_0x34()[]: PlainSprintf; public function format_0x35()[]: PlainSprintf; public function format_0x36()[]: PlainSprintf; public function format_0x37()[]: PlainSprintf; public function format_0x38()[]: PlainSprintf; public function format_0x39()[]: PlainSprintf; // '9' } interface SprintfQuote { public function format_wild()[]: PlainSprintf; } /** * sprintf uses PlainSprintf as its format string. * This type is very wide and will allow many incorrect calls to typecheck. * If possible, upgrade to \HH\Lib\Str\format(). * This uses the far stricter \HH\Lib\Str\SprintfFormat type. */ <<__PHPStdLib>> function sprintf( \HH\FormatString<PlainSprintf> $fmt, HH\FIXME\MISSING_PARAM_TYPE ...$fmt_args )[]: string; /** * printf uses PlainSprintf as its format string. * This type is very wide and will allow many incorrect calls to typecheck. * If possible, upgrade to \HH\Lib\Str\format(). * This uses the far stricter \HH\Lib\Str\SprintfFormat type. */ <<__PHPStdLib>> function printf( \HH\FormatString<PlainSprintf> $fmt, HH\FIXME\MISSING_PARAM_TYPE ...$fmt_args ): int; } namespace HH { // Results in an \HH\InvariantException whose message is the result of // calling sprintf with the arguments given this function. // Equivalent to invariant(false, $fmt, ...$fmt_args). function invariant_violation( FormatString<\PlainSprintf> $fmt, mixed ...$fmt_args )[]: noreturn; }
HTML Help Workshop
hhvm/hphp/hack/hhi/pseudofunctions.hhi
<?hh // Copyright (c) 2022, Meta, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. // The functions in this file only *look* like functions to static analysis, // but are compiled to bespoke bytecodes by HackC. namespace { /** * Determines whether or not a variable is "set." This can take a subscript * expression and checks whether a given index exists, e.g.: * ``` * // Returns `false` if 42 doesn't exist at all, or maps to `null` * isset($d[42]); * ``` */ function isset(mixed $x)[]: bool; /** * Used to remove keys from arrays: * * ``` * $d = dict[42 => true]; * unset($d[42]); * var_dump($d); // prints an empty dict * ``` * * Also can be used to unset object properties and variables, but this behavior * is disallowed by Hack. */ function unset(mixed $x)[]: void; } namespace HH { /** * Checks whether the input is a native class method pointer. * ``` * HH\is_class_meth(Foo::bar<>); // true * HH\is_class_meth(bing<>); // false * ``` */ function is_class_meth(readonly mixed $arg)[]: bool; }
Text
hhvm/hphp/hack/hhi/readme.txt
Hack for HipHop interface files. These files provide type information for some of PHP's predefined classes, interfaces and functions.
HTML Help Workshop
hhvm/hphp/hack/hhi/reflection.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ interface Reflector extends IPureStringishObject { public function __toString()[]: string; } class Reflection { public static function getModifierNames( HH\FIXME\MISSING_PARAM_TYPE $modifiers, )[]: HH\FIXME\MISSING_RETURN_TYPE; public static function export( Reflector $reflector, HH\FIXME\MISSING_PARAM_TYPE $return = false, ): HH\FIXME\MISSING_RETURN_TYPE; } class ReflectionClass implements Reflector { const int IS_IMPLICIT_ABSTRACT; const int IS_EXPLICIT_ABSTRACT; const int IS_FINAL; /** * This field is read-only */ public string $name; public function __construct(mixed $argument)[]; public static function export(mixed $argument, bool $return = false): ?string; public function getConstant(string $name)[]: mixed; public function getConstants()[]: darray<string, mixed>; public function getAbstractConstantNames()[]: darray<string, string>; public function getTypeConstant(string $name)[]: ReflectionTypeConstant; public function getTypeConstants()[]: varray<ReflectionTypeConstant>; public function getConstructor()[]: ?ReflectionMethod; public function getDefaultProperties()[]: darray<string, mixed>; /** * Returns string or false */ public function getDocComment()[]: mixed; public function getEndLine()[]: int; public function getExtension()[]: ?ReflectionExtension; public function getExtensionName()[]: string; /** * Returns string or false */ public function getFileName()[]: mixed; public function getFile()[]: ReflectionFile; public function getInterfaceNames()[]: varray<string>; public function getInterfaces()[]: darray<string, ReflectionClass>; final public function getAttributes()[]: darray<string, varray<mixed>>; final public function hasAttribute(string $name)[]: bool; final public function getAttribute(string $name)[]: ?varray<mixed>; final public function getAttributeClass<T as HH\ClassLikeAttribute>( classname<T> $c, )[]: ?T; public function getMethod(string $name)[]: ReflectionMethod; public function getMethods(?int $filter = null)[]: varray<ReflectionMethod>; public function getModifiers()[]: int; public function getName()[]: string; public function getNamespaceName()[]: string; public function isInternalToModule()[]: bool; public function getModule()[]: ?string; /** * Returns ReflectionClass or false */ public function getParentClass()[]: mixed; public function getProperties( int $filter = 0xFFFF, )[]: varray<ReflectionProperty>; public function getProperty(string $name)[]: ReflectionProperty; public function getRequirementNames()[]: varray<string>; public function getRequirements()[]: darray<string, ReflectionClass>; public function getShortName()[]: string; public function getStartLine()[]: int; public function getStaticProperties(): darray<string, mixed>; public function getStaticPropertyValue( string $name, mixed $def_value = null, ): mixed; public function getTraitNames()[]: varray<string>; public function getTraits()[]: darray<string, ReflectionClass>; public function hasConstant(string $name)[]: bool; public function hasMethod(string $name)[]: bool; public function hasProperty(string $name)[]: bool; public function hasTypeConstant(string $name)[]: bool; public function implementsInterface(string $interface)[]: bool; public function inNamespace()[]: bool; public function isAbstract()[]: bool; public function isCloneable()[]: bool; public function isFinal()[]: bool; public function isInstance(mixed $object)[]: bool; public function isInstantiable()[]: bool; public function isInterface()[]: bool; public function isEnum()[]: bool; public function getEnumUnderlyingType()[]: string; public function isInternal()[]: bool; public function isIterateable()[]: bool; /** * $class is string or ReflectionClass */ public function isSubclassOf(mixed $class)[]: bool; public function isTrait()[]: bool; public function isUserDefined()[]: bool; public function newInstance( HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; public function newInstanceArgs( Traversable<mixed> $args = varray[], )[defaults]: HH\FIXME\MISSING_RETURN_TYPE; public function newInstanceWithoutConstructor( )[]: HH\FIXME\MISSING_RETURN_TYPE; public function setStaticPropertyValue(string $name, mixed $value): void; public function __toString()[]: string; public function getReifiedTypeParamInfo()[]: varray<shape( 'is_reified' => bool, 'is_soft' => bool, 'is_warn' => bool, )>; } class ReflectionObject extends ReflectionClass {} class ReflectionException extends Exception { use ExceptionWithPureGetMessageTrait; } abstract class ReflectionFunctionAbstract implements Reflector { public HH\FIXME\MISSING_PROP_TYPE $name = ''; // Methods public function getName()[]: string; public function inNamespace()[]: bool; public function getNamespaceName()[]: string; public function getShortName()[]: string; public function isHack()[]: bool; public function isInternal()[]: bool; public function isClosure()[]: bool; public function isGenerator()[]: bool; public function returnsReadonly()[]: bool; public function isAsync()[]: bool; public function isVariadic()[]: bool; public function isUserDefined()[]: bool; public function getFileName()[]: mixed; // string | false public function getFile()[]: ReflectionFile; public function getStartLine()[]: mixed; // int | false public function getEndLine()[]: mixed; // int | false public function getDocComment()[]: mixed; // string | false public function getReturnTypeText()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getModule()[]: ?string; public function isInternalToModule()[]: bool; final public function getAttributes()[]: darray<string, varray<mixed>>; final public function hasAttribute(string $name)[]: bool; final public function getAttribute(string $name)[]: ?varray<mixed>; public function getNumberOfParameters()[]: int; public function getParameters()[]: varray<ReflectionParameter>; public function getNumberOfRequiredParameters( )[]: HH\FIXME\MISSING_RETURN_TYPE; public function isDeprecated()[]: bool; public function getExtension()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getExtensionName()[]: HH\FIXME\MISSING_RETURN_TYPE; private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; public function hasReturnType()[]: bool; public function getReturnType()[]: ?ReflectionType; public function getReifiedTypeParamInfo()[]: varray<darray<string, bool>>; public function getCoeffects()[]: vec<string>; } class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector { public HH\FIXME\MISSING_PROP_TYPE $name = ''; public function __construct(HH\FIXME\MISSING_PARAM_TYPE $name)[]; public function __toString()[]: string; public static function export( HH\FIXME\MISSING_PARAM_TYPE $name, HH\FIXME\MISSING_PARAM_TYPE $return = null, ): HH\FIXME\MISSING_RETURN_TYPE; public function isDisabled()[]: HH\FIXME\MISSING_RETURN_TYPE; public function invoke(mixed ...$args): HH\FIXME\MISSING_RETURN_TYPE; public function invokeArgs(vec<mixed> $args): HH\FIXME\MISSING_RETURN_TYPE; public function getClosure(): HH\FIXME\MISSING_RETURN_TYPE; final public function getAttributeClass<T as HH\FunctionAttribute>( classname<T> $c, )[]: ?T; } class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector { // Constants const int IS_STATIC; const int IS_PUBLIC; const int IS_PROTECTED; const int IS_PRIVATE; const int IS_ABSTRACT; const int IS_FINAL; public HH\FIXME\MISSING_PROP_TYPE $name = ''; public HH\FIXME\MISSING_PROP_TYPE $class = ''; public static function export( string $class, string $name, bool $return = false, ): HH\FIXME\MISSING_RETURN_TYPE; public function __construct( HH\FIXME\MISSING_PARAM_TYPE $class, HH\FIXME\MISSING_PARAM_TYPE $name = null, )[]; public function __toString()[]: string; public function isPublic()[]: bool; public function isPrivate()[]: bool; public function isProtected()[]: bool; public function isAbstract()[]: bool; public function isFinal()[]: bool; public function isStatic()[]: bool; public function isReadonly()[]: bool; public function isConstructor()[]: bool; public function getClosure( mixed $object = null, ): HH\FIXME\MISSING_RETURN_TYPE; public function getModifiers()[]: int; public function invoke( mixed $object, mixed ...$args ): HH\FIXME\MISSING_RETURN_TYPE; public function invokeArgs( mixed $object, vec<mixed> $args, ): HH\FIXME\MISSING_RETURN_TYPE; public function getDeclaringClass()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getOriginalClassname()[]: string; public function getPrototype()[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> public function setAccessible(bool $accessible)[write_props]: void; final public function getAttributeClass<T as HH\MethodAttribute>( classname<T> $c, )[]: ?T; } class ReflectionParameter implements Reflector { public HH\FIXME\MISSING_PROP_TYPE $name = ''; private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; public static function export( HH\FIXME\MISSING_PARAM_TYPE $function, HH\FIXME\MISSING_PARAM_TYPE $parameter, HH\FIXME\MISSING_PARAM_TYPE $return = null, ): HH\FIXME\MISSING_RETURN_TYPE; public function __construct( HH\FIXME\MISSING_PARAM_TYPE $function, HH\FIXME\MISSING_PARAM_TYPE $parameter, HH\FIXME\MISSING_PARAM_TYPE $info = null, )[]; public function __toString()[]: string; public function getName()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isPassedByReference()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isInOut()[]: bool; public function isReadonly()[]: bool; public function canBePassedByValue()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getDeclaringFunction()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getDeclaringClass()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getClass()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isArray()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isCallable()[]: HH\FIXME\MISSING_RETURN_TYPE; public function allowsNull()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getPosition()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isOptional()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isDefaultValueAvailable()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getDefaultValue()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isDefaultValueConstant()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getDefaultValueConstantName()[]: HH\FIXME\MISSING_RETURN_TYPE; /** * This is the "type constraint" that is used for enforcement. For example, * if the parameter's type hint is a type constant, this will return empty string. */ public function getTypehintText()[]: HH\FIXME\MISSING_RETURN_TYPE; /** * This is the "user type" of the parameter, which is meant to represent the * literal type the user has written in the source. <<__Soft>> is rendered * as "@" by this function. */ public function getTypeText()[]: string; public function getDefaultValueText()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isVariadic()[]: HH\FIXME\MISSING_RETURN_TYPE; public function hasType()[]: bool; public function getType()[]: ?ReflectionType; final public function hasAttribute(string $name)[]: bool; final public function getAttribute(string $name)[]: ?varray<mixed>; final public function getAttributeClass<T as HH\ParameterAttribute>( classname<T> $c, )[]: ?T; final public function getAttributes()[]: darray<string, varray<mixed>>; } class ReflectionProperty implements Reflector { const int IS_STATIC; const int IS_PUBLIC; const int IS_PROTECTED; const int IS_PRIVATE; public HH\FIXME\MISSING_PROP_TYPE $name = ''; public HH\FIXME\MISSING_PROP_TYPE $class = ''; private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; public static function export( HH\FIXME\MISSING_PARAM_TYPE $class, HH\FIXME\MISSING_PARAM_TYPE $name, HH\FIXME\MISSING_PARAM_TYPE $return = null, ): HH\FIXME\MISSING_RETURN_TYPE; public function __construct( HH\FIXME\MISSING_PARAM_TYPE $class, string $name, )[]; public function __toString()[]: string; public function getName()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getValue( HH\FIXME\MISSING_PARAM_TYPE $obj = null, )[read_globals]: HH\FIXME\MISSING_RETURN_TYPE; public function setValue( HH\FIXME\MISSING_PARAM_TYPE $obj, HH\FIXME\MISSING_PARAM_TYPE $value = null, )[globals, write_props]: HH\FIXME\MISSING_RETURN_TYPE; public function isPublic()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isPrivate()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isProtected()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isStatic()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isReadonly()[]: HH\FIXME\MISSING_RETURN_TYPE; public function isDefault()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getModifiers()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getDeclaringClass()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getDocComment()[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> public function setAccessible(bool $accessible)[write_props]: void; public function getTypeText()[]: HH\FIXME\MISSING_RETURN_TYPE; final public function getAttributes()[]: darray<string, varray<mixed>>; final public function hasAttribute(string $name)[]: bool; final public function getAttribute(string $name)[]: ?varray<mixed>; } class ReflectionExtension implements Reflector { public HH\FIXME\MISSING_PROP_TYPE $name = ''; private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; public static function export( HH\FIXME\MISSING_PARAM_TYPE $name, HH\FIXME\MISSING_PARAM_TYPE $return = false, ): HH\FIXME\MISSING_RETURN_TYPE; public function __construct(HH\FIXME\MISSING_PARAM_TYPE $name)[]; public function __toString()[]: string; public function getName()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getVersion()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getFunctions()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getConstants()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getINIEntries()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getClasses()[]: HH\FIXME\MISSING_RETURN_TYPE; public function getClassNames()[]: HH\FIXME\MISSING_RETURN_TYPE; public function info()[]: HH\FIXME\MISSING_RETURN_TYPE; } class ReflectionTypeConstant implements Reflector { private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; public static function export( HH\FIXME\MISSING_PARAM_TYPE $class, string $name, HH\FIXME\MISSING_PARAM_TYPE $return = null, ): HH\FIXME\MISSING_RETURN_TYPE; public function __construct( HH\FIXME\MISSING_PARAM_TYPE $class, string $name, )[]; public function __toString()[]: string; public function getName()[]: string; public function isAbstract()[]: bool; public function getDeclaringClass()[]: ReflectionClass; public function getClass()[]: ReflectionClass; public function getAssignedTypeText()[]: ?string; public function getTypeStructure()[]: darray<arraykey, mixed>; } class ReflectionTypeAlias implements Reflector { private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; final public function __construct(string $name)[]; public function __toString()[]: string; public function getTypeStructure()[]: darray<arraykey, mixed>; public function getResolvedTypeStructure()[]: darray<arraykey, mixed>; public function getAssignedTypeText()[]: string; public function getName()[]: string; public function getFileName()[]: string; public function getFile()[]: ReflectionFile; final public function getAttributes()[]: darray<string, varray<mixed>>; final public function hasAttribute(string $name)[]: bool; final public function getAttribute(string $name)[]: ?varray<mixed>; final public function getAttributeClass<T as HH\TypeAliasAttribute>( classname<T> $c, )[]: ?T; } class ReflectionType implements IPureStringishObject { private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; public function __construct( ?Reflector $param_or_ret = null, darray<arraykey, mixed> $type_hint_info = darray[], ); public function allowsNull()[]: bool; public function isBuiltin()[]: bool; public function __toString()[]: string; } class ReflectionFile implements Reflector { private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; final public function __construct(string $name)[]; public function __toString()[]: string; public function getName()[]: string; final public function getAttributes()[]: darray<string, varray<mixed>>; final public function hasAttribute(string $name)[]: bool; final public function getAttribute(string $name)[]: ?varray<mixed>; final public function getAttributeClass<T as HH\FileAttribute>( classname<T> $c, )[]: ?T; } class ReflectionModule implements Reflector { private function __clone(): HH\FIXME\MISSING_RETURN_TYPE; final public function __construct(string $name)[]; public function __toString()[]: string; public function getName()[]: string; final public function getAttributes()[]: darray<string, varray<mixed>>; final public function hasAttribute(string $name)[]: bool; final public function getAttribute(string $name)[]: ?varray<mixed>; final public function getAttributeClass<T as HH\ModuleAttribute>( classname<T> $c, )[]: ?T; }
HTML Help Workshop
hhvm/hphp/hack/hhi/reified_generics.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, 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. * */ namespace HH\ReifiedGenerics; /** * Returns the type structure representation of the reified type */ function get_type_structure<reify T>()[]: TypeStructure<T>; /** * Returns the name of the class represented by this reified type. * If this type does not represent a class, throws an exception */ function get_classname<reify T>()[]: classname<T>;
HTML Help Workshop
hhvm/hphp/hack/hhi/Shapes.hhi
<?hh /** * Copyright (c) 2014, 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. * */ namespace HH { abstract final class Shapes { /** * Use `Shapes::idx` to retrieve a field value in a shape, when the key may or may not exist. * If `$index` does not exist in the shape, the default value will be returned (`$default`), if one has been set. * It behaves similarily to `idx()` for Collections. * * A few examples: * * `Shapes::idx(shape('x' => 123), 'x') // 123` * * `Shapes::idx(shape('x' => 123), 'y') // null` * * `Shapes::idx(shape('x' => 123), 'y', 456) // 456` * * * `Shapes::idx(null, 'y', 456) // 456` * * Use `Shapes::idx` when the key in your shape is optional (e.g., `?x`, in `shape(?'x' => int`). * If the key in your shape is always present, access the value directly: `$my_shape['x']`. * * The second argument, `$index` must always be a literal. * * @param shape(...) $shape - shape to search for $index. * @param arraykey $index - Key ($index) to search. Must be a literal! * @param mixed $default - Default value to return if $index does not exist. By default, returns `null`. * * @return $value - Value at $index, if it exists, or $default. * */ <<__NoAutoDynamic, __SupportDynamicType>> public static function idx<Tv>( ?shape(...) $shape, arraykey $index, ?Tv $default = null, )[]: Tv; /** * Check if a field in shape exists. * Similar to array_key_exists, but for shapes. */ <<__NoAutoDynamic, __SupportDynamicType>> public static function keyExists( readonly shape(...) $shape, arraykey $index, )[]: bool; /** * Removes the $index field from the $shape (passed in as an inout argument). * As with all inout arguments, it can only be used with local variables. */ <<__NoAutoDynamic, __SupportDynamicType>> public static function removeKey<T as shape(...)>( inout T $shape, arraykey $index, )[]: void; <<__NoAutoLikes>> public static function toArray( shape(...) $shape, )[]: darray<arraykey, mixed>; <<__NoAutoLikes>> public static function toDict( shape(...) $shape )[]: dict<arraykey, mixed>; /** * Returns the value of the field $index of $shape, * throws if the field is missing. * Use this to access optional fields on shapes. */ <<__NoAutoDynamic, __SupportDynamicType>> public static function at<Tv>( shape(...) $shape, arraykey $index, )[]: Tv; } } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/soundness.hhi
<?hh namespace HH\FIXME; /** * `UNSAFE_CAST` allows you to lie to the type checker. **This is almost * always a bad idea**. You might get an exception, or you might get an * unexpected value. Even scarier, you might cause an exception in a * totally different part of the codebase. * * ``` * UNSAFE_CAST<Dog, Cat>($my_dog, 'my reason here')->meow() * ``` * * In this example, the type checker will accept the code, but the code * will still crash when you run it (no such method "meow" on "Dog"). * * `UNSAFE_CAST` has no runtime effect. It only affects the type * checker. The above example will run the same as `$my_dog->meow()`. * * ## You can fix it! * * It is always possible to write code without `UNSAFE_CAST` and without * `HH_FIXME`. This usually requires changing type signatures and some * refactoring. Your code will be more reliable, the type checker can * help you, and future changes will be less scary. * * `UNSAFE_CAST` is still better than `HH_FIXME`, because `HH_FIXME` * applies to the entire next line, and `UNSAFE_CAST` applies to a single * expression. */ function UNSAFE_CAST<<<__Explicit>> Tin, <<__Explicit>> Tout>( Tin $t, ?\HH\FormatString<nothing> $msg = null, )[]: Tout; /** * `UNSAFE_NONNULL_CAST` allows you to lie to the type checker and * pretend that a value is never `null`. **This is almost always a bad * idea**. It can lead to exceptions that the type checker would have * prevented. * * If you're sure a value is never null, use `$my_value as nonnull`. The * type checker understands this, and the runtime checks the value. * * If you're not sure whether a value is null, check for null first. * * ``` * if ($my_value is null) { ... } else { ... } * ``` */ function UNSAFE_NONNULL_CAST<T as nonnull>( ?T $t, ?\HH\FormatString<nothing> $msg = null, )[]: T; /* Acts as Tany under current semantics, and T under sound dynamic */ type TANY_MARKER<+T> = T; /* Acts as T under current semantics, and ~T under sound dynamic */ type POISON_MARKER<+T> = T; /** * We haven't written the type for every property in the codebase yet. * Properties which are missing their types have this placeholder instead. */ type MISSING_PROP_TYPE = TANY_MARKER<dynamic>; /** * We haven't written the type for every parameter to every function in the * codebase yet. Function parameters which are missing their types have this * placeholder instead. */ type MISSING_PARAM_TYPE = mixed; /** * We haven't written the return type for every function in the codebase yet. * Functions which are still missing return types have this placeholder * instead. */ type MISSING_RETURN_TYPE = TANY_MARKER<dynamic>;
HTML Help Workshop
hhvm/hphp/hack/hhi/string_coercions.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, 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. * */ namespace HH; <<__PHPStdLib>> function str_number_coercible(string $str)[]: bool; <<__PHPStdLib>> function str_to_numeric(string $str)[]: ?num;
HTML Help Workshop
hhvm/hphp/hack/hhi/supportdynamic.hhi
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. <<file: __EnableUnstableFeatures('union_intersection_type_hints')>> namespace HH { newtype supportdyn<+T> as T = (T & dynamic); }
HTML Help Workshop
hhvm/hphp/hack/hhi/traits.hhi
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of PHP's predefined interfaces * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ trait StrictIterable<+Tv> implements Iterable<Tv> { public function toValuesArray(): varray<Tv>; public function toImmVector(): ImmVector<Tv>; public function toImmSet(): ImmSet<Tv> where Tv as arraykey; public function lazy(): Iterable<Tv>; public function values(): Iterable<Tv>; public function map<Tu>((function(Tv)[_]: Tu) $fn)[ctx $fn]: Iterable<Tu>; public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: Iterable<Tv>; public function zip<Tu>(Traversable<Tu> $traversable): Iterable<Pair<Tv, Tu>>; public function take(int $n): Iterable<Tv>; public function takeWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: Iterable<Tv>; public function skip(int $n): Iterable<Tv>; public function skipWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: Iterable<Tv>; public function slice(int $start, int $len): Iterable<Tv>; public function concat<Tu super Tv>( Traversable<Tu> $traversable, ): Iterable<Tu>; public function firstValue(): ?Tv; public function lastValue(): ?Tv; } trait StrictKeyedIterable<Tk, +Tv> implements KeyedIterable<Tk, Tv> { public function toValuesArray(): varray<Tv>; public function toKeysArray(): varray<Tk>; public function toImmVector(): ImmVector<Tv>; public function toImmMap(): ImmMap<Tk, Tv> where Tk as arraykey; public function toImmSet(): ImmSet<Tv> where Tv as arraykey; public function lazy(): KeyedIterable<Tk, Tv>; public function values(): Iterable<Tv>; public function keys(): Iterable<Tk>; public function map<Tu>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: KeyedIterable<Tk, Tu>; public function mapWithKey<Tu>( (function(Tk, Tv)[_]: Tu) $fn, )[ctx $fn]: KeyedIterable<Tk, Tu>; public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; public function filterWithKey( (function(Tk, Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; public function zip<Tu>( Traversable<Tu> $traversable, ): KeyedIterable<Tk, Pair<Tv, Tu>>; public function take(int $n): KeyedIterable<Tk, Tv>; public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; public function skip(int $n): KeyedIterable<Tk, Tv>; public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; public function slice(int $start, int $len): KeyedIterable<Tk, Tv>; public function concat<Tu super Tv>( Traversable<Tu> $traversable, ): Iterable<Tu>; public function firstValue(): ?Tv; public function firstKey(): ?Tk; public function lastValue(): ?Tv; public function lastKey(): ?Tk; } trait LazyIterable<+Tv> implements Iterable<Tv> { public function toValuesArray(): varray<Tv>; public function toImmVector(): ImmVector<Tv>; public function toImmSet(): ImmSet<Tv> where Tv as arraykey; public function lazy(): Iterable<Tv>; public function values(): Iterable<Tv>; public function map<Tu>((function(Tv)[_]: Tu) $fn)[ctx $fn]: Iterable<Tu>; public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: Iterable<Tv>; public function zip<Tu>( Traversable<Tu> $traversable, )[]: Iterable<Pair<Tv, Tu>>; public function take(int $n): Iterable<Tv>; public function takeWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: Iterable<Tv>; public function skip(int $n): Iterable<Tv>; public function skipWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: Iterable<Tv>; public function slice(int $start, int $len): Iterable<Tv>; public function concat<Tu super Tv>( Traversable<Tu> $traversable, ): Iterable<Tu>; public function firstValue(): ?Tv; public function lastValue(): ?Tv; } trait LazyKeyedIterable<Tk, +Tv> implements KeyedIterable<Tk, Tv> { public function toValuesArray(): varray<Tv>; public function toKeysArray(): varray<Tk>; public function toImmVector(): ImmVector<Tv>; public function toImmMap(): ImmMap<Tk, Tv> where Tk as arraykey; public function toImmSet(): ImmSet<Tv> where Tv as arraykey; public function lazy(): KeyedIterable<Tk, Tv>; public function values(): Iterable<Tv>; public function keys(): Iterable<Tk>; public function map<Tu>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: KeyedIterable<Tk, Tu>; public function mapWithKey<Tu>( (function(Tk, Tv)[_]: Tu) $fn, )[ctx $fn]: KeyedIterable<Tk, Tu>; public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; public function filterWithKey( (function(Tk, Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; public function zip<Tu>( Traversable<Tu> $traversable, ): KeyedIterable<Tk, Pair<Tv, Tu>>; public function take(int $n): KeyedIterable<Tk, Tv>; public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; public function skip(int $n): KeyedIterable<Tk, Tv>; public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: KeyedIterable<Tk, Tv>; public function slice(int $start, int $len): KeyedIterable<Tk, Tv>; public function concat<Tu super Tv>( Traversable<Tu> $traversable, ): Iterable<Tu>; public function firstValue(): ?Tv; public function firstKey(): ?Tk; public function lastValue(): ?Tv; public function lastKey(): ?Tk; }
HTML Help Workshop
hhvm/hphp/hack/hhi/typestructure.hhi
<?hh /** * Copyright (c) 2014, 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. * */ namespace HH { /* * The following enum values are defined in * hphp/runtime/ext/reflection/ext_reflection-classes.php */ enum TypeStructureKind: int { OF_VOID = 0; OF_INT = 0; OF_BOOL = 0; OF_FLOAT = 0; OF_STRING = 0; OF_RESOURCE = 0; OF_NUM = 0; OF_ARRAYKEY = 0; OF_NORETURN = 0; OF_MIXED = 0; OF_TUPLE = 0; OF_FUNCTION = 0; OF_ARRAY = 0; OF_GENERIC = 0; OF_SHAPE = 0; OF_CLASS = 0; OF_INTERFACE = 0; OF_TRAIT = 0; OF_ENUM = 0; OF_DICT = 0; OF_VEC = 0; OF_KEYSET = 0; OF_VEC_OR_DICT = 0; OF_NONNULL = 0; OF_DARRAY = 0; OF_VARRAY = 0; OF_VARRAY_OR_DARRAY = 0; OF_NULL = 0; OF_NOTHING = 0; OF_DYNAMIC = 0; OF_UNRESOLVED = 0; OF_XHP = 0; } // Note: Nullable fields in shapes of this type may not be present, and so // should be considered optional. Additionally, shapes of this type may contain // additional fields other than those specified here. newtype TypeStructure<T> as shape( 'nullable' => ?bool, 'kind' => TypeStructureKind, 'name' => ?string, 'classname' => ?classname<T>, 'elem_types' => ?varray<mixed>, 'return_type' => mixed, 'param_types' => ?varray<mixed>, 'generic_types' => ?varray<mixed>, 'root_name' => ?string, 'access_list' => ?varray<string>, 'fields' => ?darray<arraykey, mixed>, 'allows_unknown_fields' => ?bool, 'is_cls_cns' => ?bool, 'optional_shape_field' => ?bool, 'value' => mixed, 'typevars' => ?string, 'alias' => ?string, ?'exact' => bool, ?'like' => bool, ) = shape( 'nullable' => ?bool, 'kind' => TypeStructureKind, // name for generics (type variables) 'name' => ?string, // classname for classes, interfaces, enums, or traits 'classname' => ?classname<T>, // for tuples 'elem_types' => ?varray<mixed>, // for functions 'return_type' => mixed, 'param_types' => ?varray<mixed>, // for arrays, classes 'generic_types' => ?varray<mixed>, 'root_name' => ?string, 'access_list' => ?varray<string>, // for shapes 'fields' => ?darray<arraykey, mixed>, 'allows_unknown_fields' => ?bool, 'is_cls_cns' => ?bool, 'optional_shape_field' => ?bool, 'value' => mixed, // Comma-separated string 'typevars' => ?string, // for type aliases 'alias' => ?string, // if the type is exact (i.e., not a subtype) ?'exact' => bool, // if the type is a like-type ?'like' => bool, ); /* * returns the shape associated with the type constant. */ function type_structure( mixed $cls_or_obj, string $cns_name, )[]: \HH\FIXME\MISSING_RETURN_TYPE; // becomes: // type_structure(C::class or new C, 'type_const_name') // : TypeStructure /* * Retrieves the TypeStructure for a type alias. */ function type_structure_for_alias<T>( typename<T> $cls_or_obj, )[]: TypeStructure<T>; } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/weakref.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ final class WeakRef<T> { public function __construct(T $object)[]; public function acquire()[write_props]: bool; public function get()[]: ?T; public function release()[write_props]: bool; public function valid()[]: bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/XMLReader.hhi
<?hh /** * Copyright (c) 2014, 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. * */ class XMLReader { const int NONE; const int ELEMENT; const int ATTRIBUTE; const int TEXT; const int CDATA; const int ENTITY_REF; const int ENTITY; const int PI; const int COMMENT; const int DOC; const int DOC_TYPE; const int DOC_FRAGMENT; const int NOTATION; const int WHITESPACE; const int SIGNIFICANT_WHITESPACE; const int END_ELEMENT; const int END_ENTITY; const int XML_DECLARATION; const int LOADDTD; const int DEFAULTATTRS; const int VALIDATE; const int SUBST_ENTITIES; public int $attributeCount; public string $baseURI; public int $depth; public bool $hasAttributes; public bool $hasValue; public bool $isDefault; public bool $isEmptyElement; public string $localName; public string $name; public string $namespaceURI; public int $nodeType; public string $prefix; public string $value; public string $xmlLang; public function __construct(); public function open( string $uri, ?string $encoding = null, int $options = 0, ): mixed; public function XML( string $source, ?string $encoding = null, int $options = 0, ): bool; public function close(): bool; public function read(): bool; public function next(?string $localname = null): bool; public function readString(): string; public function readInnerXML(): string; public function readOuterXML(): string; public function moveToNextAttribute(): bool; public function getAttribute(string $name): mixed; public function getAttributeNo(int $index): mixed; public function getAttributeNs(string $name, string $namespaceURI): mixed; public function moveToAttribute(string $name): bool; public function moveToAttributeNo(int $index): bool; public function moveToAttributeNs(string $name, string $namespaceURI): bool; public function moveToElement(): bool; public function moveToFirstAttribute(): bool; public function isValid(): bool; public function getParserProperty(int $property): bool; public function lookupNamespace(string $prefix): mixed; public function setSchema(string $source): bool; public function setParserProperty(int $property, bool $value): bool; public function setRelaxNGSchema(string $filename): mixed; public function setRelaxNGSchemaSource(string $source): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/coeffect/capabilities.hhi
<?hh /** * Copyright (c) 2020, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This namespace contains pseudo-types that represent capabilities. * To establish calling conventions (i.e., which function/method can * be safely called from certain contexts), the typechecker desugars * each context into a set of capabilities in this namespace. * * (A set of) capabilities act as a permission for enforcing permitted * combination of caller/callee contexts while type-checking. * In layman's terms, an active capability can be converted to * any of its supertypes (but not subtypes), and a function/method * call type-checks if and only if: * - for every capability required by the callee, there is * a matching capability present at the call site (i.e., caller), * where a capability of caller may be reused and converted to * any of its supertype capabilities multiple times in order to * match each capability required by the caller. * * From a formal standpoint, a set of capabilities is represented as * a single intersection type between the constituent capabilities, * and the only requirement is that the caller's capability type is * a subtype of the callee's capability type. */ namespace HH\Capabilities { <<__Sealed(AccessGlobals::class)>> interface ReadGlobals {} <<__Sealed()>> interface AccessGlobals extends ReadGlobals {} <<__Sealed()>> interface IO {} <<__Sealed()>> interface WriteProperty {} <<__Sealed(SystemShallow::class)>> interface System {} <<__Sealed(SystemLocal::class)>> interface SystemShallow extends System {} <<__Sealed()>> interface SystemLocal extends SystemShallow {} <<__Sealed(ImplicitPolicyOf::class, ImplicitPolicyShallow::class)>> interface ImplicitPolicy {} <<__Sealed(ImplicitPolicyOfShallow::class, ImplicitPolicyLocal::class)>> interface ImplicitPolicyShallow extends ImplicitPolicy {} <<__Sealed(ImplicitPolicyOfLocal::class)>> interface ImplicitPolicyLocal extends ImplicitPolicyShallow {} <<__Sealed(ImplicitPolicyOfShallow::class)>> interface ImplicitPolicyOf<T> extends ImplicitPolicy {} <<__Sealed(ImplicitPolicyOfLocal::class)>> interface ImplicitPolicyOfShallow<T> extends ImplicitPolicyOf<T>, ImplicitPolicyShallow {} <<__Sealed()>> interface ImplicitPolicyOfLocal<T> extends ImplicitPolicyOfShallow<T>, ImplicitPolicyLocal {} /** * The core capability present in every reactive context. * Each weaker level of reactive context has additional privileges, * thus the respective capabilities are subtypes of this one. */ <<__Sealed(RxShallow::class)>> interface Rx {} <<__Sealed(RxLocal::class)>> interface RxShallow extends Rx {} <<__Sealed()>> interface RxLocal extends RxShallow {} }
HTML Help Workshop
hhvm/hphp/hack/hhi/coeffect/contexts.hhi
<?hh /** * Copyright (c) 2020, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * # Contexts and Capabilities * * See full documentation at * https://docs.hhvm.com/hack/contexts-and-capabilities/introduction * * Capabilities describe what a function in Hack is allowed to do. * * Capabilities are grouped into sets called contexts. You can mark your * functions with contexts, and Hack will ensure that you have all the * capabilities required. * * ``` * function birthday_good(Person $p)[write_props]: void { * $p->age += 1; * } * * function birthday_bad(Person $p)[]: void { * // Type checker error: this function isn't allowed to write properties. * $p->age += 1; * } * ``` * * `birthday_good` has the `write_props` context, but `birthday_bad` has * the pure context (no capabilities). The type checker is checking that * `birthday_bad` is a pure function. * * A function may have more than one context. * * ``` * function example()[globals, write_props]: void { * // You can do things with static or instance properties here. * } * ``` */ // We represent a context as an intersection type of all the // capabilities it includes, so enable the `&` type syntax. <<file: __EnableUnstableFeatures('union_intersection_type_hints')>> /** * This namespace defines all the contexts available in HHVM, the Hack * runtime. When your code runs, HHVM will check that your functions have * the necessary capabilities in their contexts. */ namespace HH\Contexts { /** * The default set of capabilities. If you don't specify a context on * your function, it's the same as writing `[defaults]`. * * `defaults` includes almost all capabilities, including: * * * writing to stdout (e.g. `echo $foo`) * * modifying instance properties (e.g. `$p->age += 1`) * * accessing static properties (e.g. `MySingleton::$activeInstance`) * * calling other functions that use any of these capabilities * * `defaults` functions may call into `zoned` functions, but not the * other way around. * * `defaults` also excludes the capabilities required to call (or be called * from) `zoned_with` functions. */ type defaults = ( \HH\Capabilities\WriteProperty & \HH\Capabilities\AccessGlobals & \HH\Capabilities\RxLocal & \HH\Capabilities\SystemLocal & \HH\Capabilities\ImplicitPolicyLocal & \HH\Capabilities\IO & ); /** * The `write_props` context allows your function to write to instance * variables. * * `write_props` is not necessary on `__construct` methods that only * write to `$this`. */ type write_props = \HH\Capabilities\WriteProperty; // TODO(cipp): deal with not giving it WriteProperty (or some other mechanism of turning on IFC) /** * The `leak_safe` context ensures that your function cannot leak data by * writing to global state. * * `leak_safe` functions can only return data by passing it as a return * value or writing it to arguments. */ type leak_safe = ( \HH\Capabilities\WriteProperty & \HH\Capabilities\ReadGlobals & \HH\Capabilities\System & ); /** * The `leak_safe_shallow` context is a less restricted form of the * `leak_safe` context, to help with gradual migration to `leak_safe`. * * Functions with the `leak_shallow` context have the same * restrictions as `leak_safe` for internal operations (e.g. no mutating * static variables). They are also allowed to call `leak_safe_local` or * `leak_safe_shallow` functions. * * See also `leak_safe_local`. */ type leak_safe_shallow = ( \HH\Capabilities\WriteProperty & \HH\Capabilities\ReadGlobals & \HH\Capabilities\SystemShallow & ); /** * The `leak_safe_local` context is the least restricted form of the * `leak_safe` context, to help with gradual migration to `leak_safe`. * * Functions with the `leak_safe_local` context have the same restrictions * as `leak_safe` for internal operations (e.g. no mutating static * variables). They are also allowed to call `leak_safe_local` or * `leak_safe_shallow` functions and their leak-safe counterparts, * and even `defaults` functions. However, they cannot call * functions with the `zoned_with` context nor its shallow/local variant. */ type leak_safe_local = ( \HH\Capabilities\WriteProperty & \HH\Capabilities\ReadGlobals & \HH\Capabilities\SystemLocal & ); /** * `zoned` includes all the capabilities of `leak_safe`, but also allows * accessing the current zone policy. * * `zoned` functions may be called from either `defaults` functions or * `zoned_with` functions. `zoned` is more restrictive, so it cannot call * into `defaults` or `zoned_with` functions. */ type zoned = ( \HH\Capabilities\WriteProperty & \HH\Capabilities\ReadGlobals & \HH\Capabilities\ImplicitPolicy & \HH\Capabilities\System & ); /** * The `zoned_shallow` context is a less restricted form of the `zoned` * context, to help with gradual migration to `zoned`. * * Functions with the `zoned_shallow` context have the same * restrictions as `zoned` for internal operations (e.g. no mutating * static variables). They are also allowed to call `zoned_local` or * `zoned_shallow` functions, as well as `leak_safe_shallow` functions. * * See also `zoned_local`. */ type zoned_shallow = ( \HH\Capabilities\WriteProperty & \HH\Capabilities\ReadGlobals & \HH\Capabilities\ImplicitPolicyShallow & \HH\Capabilities\SystemShallow & ); /** * The `zoned_local` context is the least restricted form of the * `zoned` context, to help with gradual migration to `zoned`. * * Functions with the `zoned_local` context have the same restrictions * as `zoned` for internal operations (e.g. no mutating static * variables). They are also allowed to call `zoned_local` or * `zoned_shallow` functions and their leak-safe counterparts, * and even `defaults` functions. Notably, they cannot call * functions with the `zoned_with` context nor its shallow/local variant. */ type zoned_local = ( \HH\Capabilities\WriteProperty & \HH\Capabilities\ReadGlobals & \HH\Capabilities\ImplicitPolicyLocal & \HH\Capabilities\SystemLocal & ); /** * The `zoned_with<Foo>` context allows your function to be used with * other `zoned_with<Foo>` functions. * * This is similar to `zoned`, but allows you define multiple distinct * zones. * * `zoned_with` functions require a special entry point, and cannot be * called from `defaults` functions. */ type zoned_with<T> = ( \HH\Capabilities\WriteProperty & \HH\Capabilities\ReadGlobals & \HH\Capabilities\ImplicitPolicyOf<T> & \HH\Capabilities\System & ); /** * The `read_globals` context gives your function the capability to read * global state, such as static properties on classes. * * To avoid mutating static properties, functions using this context can * only access static properties using `readonly`. * * See also `globals`. */ type read_globals = \HH\Capabilities\ReadGlobals; /** * The `globals` context gives your function the capability to read * and write global state, such as static properties on classes. * * See `read_globals` if you only need to read global state. */ type globals = \HH\Capabilities\AccessGlobals; type rx = (\HH\Capabilities\Rx & \HH\Capabilities\WriteProperty); // type rx_shallow = (\HH\Capabilities\RxShallow & rx); type rx_shallow = (\HH\Capabilities\RxShallow & \HH\Capabilities\WriteProperty); // type rx_local = (\HH\Capabilities\RxLocal & rx_shallow); type rx_local = (\HH\Capabilities\RxLocal & \HH\Capabilities\WriteProperty); }
HTML Help Workshop
hhvm/hphp/hack/hhi/coeffect/unsafe_contexts.hhi
<?hh /** * Copyright (c) 2020, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ // see contexts.hhi for more details <<file: __EnableUnstableFeatures('union_intersection_type_hints')>> /** * As an unsafe extension and for the purpose of top-level migration, * we additionally map certain contexts to a (set of) capabilities that * are provided but not required by a function (i.e., they are unsafe). * This namespace contains mapping to such capabilities using * same-named contexts. More precisely, the function/method with context * `ctx` has the following type of capability in its body: * \HH\Capabilities\ctx & \HH\Capabilities\Unsafe\ctx * where safe contexts have `\Unsafe\ctx = mixed`. The function signature's * capability remains: * \HH\Capabilities\ctx * for the purposes of subtyping and calling. */ namespace HH\Contexts\Unsafe { type defaults = mixed; type write_props = mixed; type read_globals = mixed; type globals = mixed; type leak_safe = mixed; type leak_safe_shallow = \HH\Capabilities\SystemLocal; type leak_safe_local = \HH\Contexts\defaults; type zoned = mixed; type zoned_shallow = (\HH\Capabilities\ImplicitPolicyLocal & \HH\Capabilities\SystemLocal &); type zoned_local = \HH\Contexts\defaults; type zoned_with<T> = mixed; type rx = \HH\Contexts\defaults; type rx_shallow = \HH\Contexts\defaults; type rx_local = \HH\Contexts\defaults; }
HTML Help Workshop
hhvm/hphp/hack/hhi/collections/ImmMap.hhi
<?hh /** * Copyright (c) 2014, 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. * */ <<file: __EnableUnstableFeatures('readonly')>> /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * `ImmMap` is an immutable `Map`. HHVM provides a native implementation for * this class. The PHP class definition below is not actually used at run time; * it is simply provided for the typechecker and for developer reference. * * A `ImmMap` cannot be mutated. No elements can be added or removed from it, * nor can elements be overwritten using assignment (i.e. `$c[$k] = $v` is * not allowed). * * Construct it with a `Traversable`: * * ``` * $a = dict['a' => 1, 'b' => 2]; * $fm = new ImmMap($a); * ``` * * or use the literal syntax * * ``` * $fm = ImmMap {'a' => 1, 'b' => 2}; * ``` * * @guide /hack/collections/introduction * @guide /hack/collections/classes */ final class ImmMap< Tk as arraykey, +Tv, > implements \ConstMap<Tk, Tv> { /** * Creates an `ImmMap` from the given `KeyedTraversable`, or an empty * `ImmMap` if `null` is passed. * * @param $it - any `Traversable` object from which to create an `ImmMap` * (e.g., `array`). If `null`, then an empty `ImmMap` is created. */ public function __construct(?KeyedTraversable<Tk, Tv> $it)[]; /** * Returns an `array` containing the values from the current `ImmMap`. * * @return - an integer-indexed `array` containing the values from the * current `ImmMap`. */ public function toValuesArray()[]: varray<Tv>; /** * Returns an `array` whose values are the keys of the current `ImmMap`. * * @return - an integer-indexed `array` where the values are the keys from * the current `ImmMap`. */ public function toKeysArray()[]: varray<Tk>; /** * Returns an immutable vector (`ImmVector`) with the values of the current * `ImmMap`. * * @return - an `ImmVector` that contains the values of the current `ImmMap`. */ public function toImmVector()[]: ImmVector<Tv>; /** * Returns an immutable copy (`ImmMap`) of the current `ImmMap`. * * @return - an `ImmMap` that is a copy of the current `ImmMap`. */ public function toImmMap()[]: ImmMap<Tk, Tv>; /** * Returns an immutable set (`ImmSet`) based on the values of the current * `ImmMap`. * * @return - an `ImmSet` with the current values of the current `ImmMap`. */ public function toImmSet()[]: ImmSet<Tv> where Tv as arraykey; /** * Returns an immutable copy (`ImmMap`) of the current `ImmMap`. * * This method is interchangeable with `toImmMap()`. * * @return - an `ImmMap` representing a copy of the current `ImmMap`. */ public function immutable()[]: ImmMap<Tk, Tv>; /** * Returns a lazy, access elements only when needed view of the current * `ImmMap`. * * Normally, memory is allocated for all of the elements of an `ImmMap`. With * a lazy view, memory is allocated for an element only when needed or used * in a calculation like in `map()` or `filter()`. * * @return - a `KeyedIterable` representing the lazy view into the current * `ImmMap`. * * @guide /hack/collections/examples */ public function lazy()[]: KeyedIterable<Tk, Tv>; /** * Returns an ImmVector containing the values of the current `ImmMap`. * * This method is interchangeable with toImmVector(). * * @return - an ImmVector containing the values of the current `ImmMap`. */ public function values()[]: ImmVector<Tv>; /** * Returns an ImmVector containing, as values, the keys of the current `ImmMap`. * * @return - an ImmVector containing, as values, the keys of the current * `ImmMap`. */ public readonly function keys()[]: ImmVector<Tk>; /** * Returns an `ImmMap` after an operation has been applied to each value in * the current `ImmMap`. * * Every value in the current `ImmMap` is affected by a call to `map()`, * unlike `filter()` where only values that meet a certain criteria are * affected. * * The keys will remain unchanged from this `ImmMap` to the returned `ImmMap`. * * @param $fn - The callback containing the operation to apply to the * current `ImmMap` values. * * @return - an `ImmMap` containing key/value pairs after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu>((function(Tv)[_]: Tu) $fn)[ctx $fn]: ImmMap<Tk, Tu>; /** * Returns an `ImmMap` after an operation has been applied to each key and * value in current `ImmMap`. * * Every key and value in the current `ImmMap` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * The keys will remain unchanged from the current `ImmMap` to the returned * `ImmMap`. The keys are only used to help in the operation. * * @param $fn - The callback containing the operation to apply to the * current `ImmMap` keys and values. * * @return - an `ImmMap` containing the values after a user-specified * operation on the current `ImmMap`'s keys and values is applied. */ public function mapWithKey<Tu>( (function(Tk, Tv)[_]: Tu) $fn, )[ctx $fn]: ImmMap<Tk, Tu>; /** * Returns an `ImmMap` containing the values of the current `ImmMap` that * meet a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * The keys associated with the current `ImmMap` remain unchanged in the * returned `Map`. * * @param $fn - The callback containing the condition to apply to the * current `ImmMap` values. * * @return - an `ImmMap` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ImmMap<Tk, Tv>; /** * Returns an `ImmMap` containing the values of the current `ImmMap` that * meet a supplied condition applied to its keys and values. * * Only keys and values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * The keys associated with the current `ImmMap` remain unchanged in the * returned `ImmMap`; the keys will be used in the filtering process only. * * @param $fn - The callback containing the condition to apply to the * current `ImmMap` keys and values. * * @return - an `ImmMap` containing the values after a user-specified * condition is applied to the keys and values of the current * `ImmMap`. * */ public function filterWithKey( (function(Tk, Tv)[_]: bool) $fn, )[ctx $fn]: ImmMap<Tk, Tv>; /** * Returns an `ImmMap` where each value is a `Pair` that combines the value * of the current `ImmMap` and the provided `Traversable`. * * If the number of values of the current `ImmMap` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * The keys associated with the current `ImmMap` remain unchanged in the * returned `ImmMap`. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `ImmMap`. * * @return - The `ImmMap` that combines the values of the current `ImmMap` * with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: ImmMap<Tk, Pair<Tv, Tu>>; /** * Returns an `ImmMap` containing the first `n` key/values of the current * `ImmMap`. * * The returned `ImmMap` will always be a proper subset of the current * `ImmMap`. * * `n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the returned * `ImmMap`. * * @return - An `ImmMap` that is a proper subset of the current `ImmMap` up * to `n` elements. */ public function take(int $n)[]: ImmMap<Tk, Tv>; /** * Returns an `ImmMap` containing the keys and values of the current `ImmMap` * up to but not including the first value that produces `false` when passed * to the specified callback. * * The returned `ImmMap` will always be a proper subset of the current * `ImmMap`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - An `ImmMap` that is a proper subset of the current `ImmMap` up * until when the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ImmMap<Tk, Tv>; /** * Returns an `ImmMap` containing the values after the `n`-th element of the * current `ImmMap`. * * The returned `ImmMap` will always be a proper subset of the current * `ImmMap`. * * `n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `ImmMap`. * * @return - An `ImmMap` that is a proper subset of the current `ImmMap` * containing values after the specified `n`-th element. */ public function skip(int $n)[]: ImmMap<Tk, Tv>; /** * Returns an `ImmMap` containing the values of the current `ImmMap` starting * after and including the first value that produces `true` when passed to * the specified callback. * * The returned `ImmMap` will always be a proper subset of the current * `ImmMap`. * * @param $fn - The callback used to determine the starting element for the * `ImmMap`. * * @return - An `ImmMap` that is a proper subset of the current `ImmMap` * starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ImmMap<Tk, Tv>; /** * Returns a subset of the current `ImmMap` starting from a given key * location up to, but not including, the element at the provided length from * the starting key location. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * keys and values at key location 0 and 1. * * The returned `ImmMap` will always be a proper subset of the current * `ImmMap`. * * @param $start - The starting key location of the current `ImmMap` for the * returned `ImmMap`. * @param $len - The length of the returned `ImmMap`. * * @return - An `ImmMap` that is a proper subset of the current `ImmMap` * starting at `$start` up to but not including the element * `$start + $len`. */ public function slice(int $start, int $len)[]: ImmMap<Tk, Tv>; /** * Returns an ImmVector that is the concatenation of the values of the * current `ImmMap` and the values of the provided `Traversable`. * * The provided `Traversable` is concatenated to the end of the current * `ImmMap` to produce the returned `ImmVector`. * * @param $traversable - The `Traversable` to concatenate to this `ImmMap`. * * @return - The integer-indexed concatenated `ImmVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: ImmVector<Tu>; /** * Returns the first value in the current `ImmMap`. * * @return - The first value in the current `ImmMap`, or `null` if the current * `ImmMap` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first key in the current `ImmMap`. * * @return - The first key in the current `ImmMap`, or `null` if the current * `ImmMap` is empty. */ public readonly function firstKey()[]: ?Tk; /** * Returns the last value in the current `ImmMap`. * * @return - The last value in the current `ImmMap`, or `null` if the current * `ImmMap` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last key in the current `ImmMap`. * * @return - The last key in the current `ImmMap`, or `null` if the current * `ImmMap` is empty. */ public readonly function lastKey()[]: ?Tk; /** * Checks if the current `ImmMap` is empty. * * @return - `true` if the current `ImmMap` is empty; `false` otherwise. */ public readonly function isEmpty()[]: bool; /** * Provides the number of elements in the current `ImmMap`. * * @return - The number of elements in current `ImmMap`. */ public readonly function count()[]: int; /** * Returns the value at the specified key in the current `ImmMap`. * * If the key is not present, an exception is thrown. If you don't want an * exception to be thrown, use `get()` instead. * * `$v = $map->at($k)` is semantically equivalent to `$v = $map[$k]`. * * @param $k - the key from which to retrieve the value. * * @return - The value at the specified key; or an exception if the key does * not exist. */ public function at(Tk $k)[]: Tv; /** * Returns the value at the specified key in the current `ImmMap`. * * If the key is not present, null is returned. If you would rather have an * exception thrown when a key is not present, then use `at()`. * * @param $k - the key from which to retrieve the value. * * @return - The value at the specified key; or `null` if the key does not * exist. */ public function get(Tk $k)[]: ?Tv; /** * Determines if the specified key is in the current `ImmMap`. * * This function is interchangeable with `containsKey()`. * * @param $k - The key to check. * * @return - `true` if the specified key is present in the current `ImmMap`; * `false` otherwise. * * @guide /hack/generics/constraints */ public readonly function contains(mixed $k)[]: bool; /** * Determines if the specified key is in the current `ImmMap`. * * This function is interchangeable with `contains()`. * * @param $k - The key to check. * * @return - `true` if the specified key is present in the current `ImmMap`; * `false` otherwise. * * @guide /hack/generics/constraints */ public readonly function containsKey(mixed $k)[]: bool; /** * Returns a new `ImmMap` with the keys that are in the current `ImmMap`, but * not in the provided `KeyedTraversable`. * * @param $traversable - The `KeyedTraversable` on which to compare the keys. * * @return - An `ImmMap` containing the keys (and associated values) of the * current `ImmMap` that are not in the `KeyedTraversable`. */ public function differenceByKey( KeyedTraversable<mixed, mixed> $traversable, )[]: ImmMap<Tk, Tv>; /** * Returns an iterator that points to beginning of the current `ImmMap`. * * @return - A `KeyedIterator` that allows you to traverse the current * `ImmMap`. */ public function getIterator()[]: KeyedIterator<Tk, Tv>; /** * Creates an `ImmMap` from the given `Traversable`, or an empty `ImmMap` * if `null` is passed. * * This is the static method version of the `ImmMap::__construct()` * constructor. * * @param $items - any Traversable object from which to create an `ImmMap` * (e.g., `array`). If `null`, then an empty `ImmMap` is * created. * * @return - An `ImmMap` with the key/value pairs from the `Traversable`; or * an empty `ImmMap` if the `Traversable` is `null`. */ public static function fromItems( ?Traversable<Pair<Tk, Tv>> $items, )[]: ImmMap<Tk, Tv>; /** * Returns the `string` version of the current `ImmMap`, which is `"ImmMap"`. * * @return - The `string` `"ImmMap"`. */ public function __toString()[]: string; /** * Returns an `Iterable` view of the current `ImmMap`. * * The `Iterable` returned is one that produces the key/values from the * current `ImmMap`. * * @return - The `Iterable` view of the current `ImmMap`. */ public function items()[]: Iterable<Pair<Tk, Tv>>; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<Tk, Tv>; } } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/collections/ImmSet.hhi
<?hh /** * Copyright (c) 2014, 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. * */ <<file: __EnableUnstableFeatures('readonly')>> /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * `ImmSet` is an immutable, ordered set-style collection. HHVM provides a * native implementation for this class. The PHP class definition below is not * actually used at run time; it is simply provided for the typechecker and * for developer reference. * * An `ImmSet` cannot be mutated. No elements can be added or removed from it, * nor can elements be overwritten using assignment (i.e. `$s[$k] = $v` is * not allowed). * * Construct it with a `Traversable`: * * ``` * $a = vec[1, 2]; * $s = new ImmSet($a); * ``` * * or use the literal syntax: * * ``` * $s = ImmSet {1, 2}; * ``` * * @guide /hack/collections/introduction * @guide /hack/collections/classes */ final class ImmSet<+Tv as arraykey> implements \ConstSet<Tv> { /** * Creates an `ImmSet` from the given `Traversable`, or an empty `ImmSet` if * `null` is passed. * * @param $it - any `Traversable` object from which to create the `ImmSet` * (e.g., `array`). If `null`, then an empty `ImmSet` is created. */ public function __construct(?Traversable<Tv> $it)[]; /** * Checks if the current `ImmSet` is empty. * * @return - `true` if the current `ImmSet` is empty; `false` otherwise. */ public readonly function isEmpty()[]: bool; /** * Provides the number of elements in the current `ImmSet`. * * @return - The number of elements in the current `ImmSet`. */ public readonly function count()[]: int; /** * Determines if the specified value is in the current `ImmSet`. * * @param $v - The value to check. * @return - `true` if the specified value is present in the current `ImmSet`; * `false` otherwise. */ public readonly function contains(arraykey $k)[]: bool; /** * Returns an `array` containing the values from the current `ImmSet`. * * `Set`s don't have keys. So this method just returns the values. * * This method is interchangeable with `toValuesArray()`. * * @return - an integer-indexed `array` containing the values from the * current `ImmSet`. */ public function toKeysArray()[]: varray<Tv>; /** * Returns an `array` containing the values from the current `ImmSet`. * * This method is interchangeable with `toKeysArray()`. * * @return - an integer-indexed `array` containing the values from the * current `ImmSet`. */ public function toValuesArray()[]: varray<Tv>; /** * Returns an iterator that points to beginning of the current `ImmSet`. * * The keys and values when iterating through the `KeyedIterator` will be * identical since `ImmSet`s have no keys, the values are used as keys. * * @return - A `KeyedIterator` that allows you to traverse the current * `ImmSet`. */ public function getIterator()[]: KeyedIterator<arraykey, Tv>; /** * Creates an `ImmSet` from the given `Traversable`, or an empty `ImmSet` if * `null` is passed. * * This is the static method version of the `ImmSet::__construct()` * constructor. * * @param $items - any `Traversable` object from which to create an `ImmSet` * (e.g., `array`). If `null`, then an empty `ImmSet` is * created. * * @return - An `ImmSet` with the values from the `Traversable`; or an empty * `ImmSet` if the `Traversable` is `null`. */ public static function fromItems(?Traversable<Tv> $items)[]: ImmSet<Tv>; /** * Returns an `ImmSet` containing all the values from the specified * `array`(s). * * @param ...$argv - The `array`(s) to convert to an `ImmSet`. * * @return - An `ImmSet` with the values from the passed `array`(s). */ public static function fromArrays( \HH\FIXME\MISSING_PARAM_TYPE ...$argv )[]: ImmSet<Tv>; /** * Creates an `ImmSet` from the keys of the specified container. * * The keys of the container will be the values of the `ImmSet`. * * @param $container - The container with the keys used to create the * `ImmSet`. * * @return - An `ImmSet` built from the keys of the specified container. */ public static function fromKeysOf<Tk as arraykey>( ?KeyedContainer<Tk, mixed> $container, )[]: ImmSet<Tk>; /** * Returns the `string` version of this `ImmSet`, which is `"ImmSet"`. * * @return - The `string` `"ImmSet"`. */ public function __toString()[]: string; /** * Returns an immutable vector (`ImmVector`) with the values of the current * `ImmSet`. * * @return - an `ImmVector` (integer-indexed) with the values of the current * `ImmSet`. */ public function toImmVector()[]: ImmVector<Tv>; /** * Returns an immutable map (`ImmMap`) based on the values of the current * `ImmSet`. * * Each key of the `Map` will be the same as its value. * * @return - an `ImmMap` that that contains the values of the current * `ImmSet`, with each key of the `ImmMap` being the same as its * value. */ public function toImmMap()[]: ImmMap<arraykey, Tv>; /** * Returns an immutable copy (`ImmSet`) of the current `ImmSet`. * * This function is interchangeable with `immutable()`. * * @return - an `ImmSet` that is a copy of the current `ImmSet`. */ public function toImmSet()[]: ImmSet<Tv>; /** * Returns an immutable copy (`ImmSet`) of the current `ImmSet`. * * This method is interchangeable with `toImmSet()`. * * @return - an `ImmSet` that is a copy of the current `ImmSet`. */ public function immutable()[]: ImmSet<Tv>; /** * Returns an Iterable view of the current `ImmSet`. * * The `Iterable` returned is one that produces the values from the current * `ImmSet`. * * @return - The `Iterable` view of the current `ImmSet`. */ public function items()[]: Iterable<Tv>; /** * Returns an `ImmVector` containing the values of the current `ImmSet`. * * This method is interchangeable with `toImmVector()` and `keys()`. * * @return - an `ImmVector` containing the values of the current `ImmSet`. */ public function values()[]: ImmVector<Tv>; /** * Returns an `ImmVector` containing the values of this `ImmSet`. * * `ImmSet`s don't have keys, so this will return the values. * * This method is interchangeable with `toImmVector()` and `values()`. * * @return - an `ImmVector` containing the values of the current `ImmSet`. */ public readonly function keys()[]: ImmVector<arraykey>; /** * Returns a lazy, access elements only when needed view of the current * `ImmSet`. * * Normally, memory is allocated for all of the elements of an `ImmSet`. With * a lazy view, memory is allocated for an element only when needed or used * in a calculation like in `map()` or `filter()`. * * @return - an `KeyedIterable` representing the lazy view into the current * `ImmSet`, where the keys are the same as the values. * * @guide /hack/collections/examples */ public function lazy()[]: KeyedIterable<arraykey, Tv>; /** * Returns an `ImmSet` containing the values after an operation has been * applied to each value in the current `ImmSet`. * * Every value in the current `ImmSet` is affected by a call to `map()`, * unlike `filter()` where only values that meet a certain criteria are * affected. * * @param $fn - The callback containing the operation to apply to the * current `ImmSet` values. * * @return - a `ImmSet` containing the values after a user-specified operation * is applied. * * @guide /hack/collections/examples */ public function map<Tu as arraykey>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: ImmSet<Tu>; /** * Returns an `ImmSet` containing the values after an operation has been * applied to each "key" and value in the current `ImmSet`. * * Since `ImmSet`s don't have keys, the callback uses the values as the keys * as well. * * Every value in the current `ImmSet` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * @param $fn - The callback containing the operation to apply to the * current `ImmSet` keys and values. * * @return - an `ImmSet` containing the values after a user-specified * operation on the current `ImmSet`'s values is applied. */ public function mapWithKey<Tu as arraykey>( (function(arraykey, Tv)[_]: Tu) $fn, )[ctx $fn]: ImmSet<Tu>; /** * Returns an `ImmSet` containing the values of the current `ImmSet` that * meet a supplied condition applied to each value. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The callback containing the condition to apply to the * current `ImmSet` values. * * @return - an `ImmSet` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: ImmSet<Tv>; /** * Returns an `ImmSet` containing the values of the current `ImmSet` that * meet a supplied condition applied to its "keys" and values. * * Since `ImmSet`s don't have keys, the callback uses the values as the keys * as well. * * Only values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * @param $fn - The callback containing the condition to apply to the * current `ImmSet` keys and values. * * @return - an `ImmSet` containing the values after a user-specified * condition is applied to the values of the current `ImmSet`. * */ public function filterWithKey( (function(arraykey, Tv)[_]: bool) $fn, )[ctx $fn]: ImmSet<Tv>; /** * Throws an exception unless the current `ImmSet` or the `Traversable` is * empty. * * Since `ImmSet`s only support integers or strings as values, we cannot * have a `Pair` as an `ImmSet` value. So in order to avoid an * `InvalidArgumentException`, either the current `ImmSet` or the * `Traversable` must be empty so that we actually return an empty `ImmSet`. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `ImmSet`. * * @return - The `ImmSet` that combines the values of the current `ImmSet` * with the provided `Traversable`; one of these must be empty or * an exception is thrown. */ public function zip<Tu>(Traversable<Tu> $traversable)[]: ImmSet<nothing>; /** * Returns an `ImmSet` containing the first n values of the current `ImmSet`. * * The returned `ImmSet` will always be a proper subset of the current * `ImmSet`. * * `n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the returned * `ImmSet`. * * @return - An `ImmSet` that is a proper subset of the current `ImmSet` up * to `n` elements. */ public function take(int $n)[]: ImmSet<Tv>; /** * Returns an `ImmSet` containing the values of the current `ImmSet` up to * but not including the first value that produces `false` when passed to the * specified callback. * * The returned `ImmSet` will always be a proper subset of the current * `ImmSet`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - An `ImmSet` that is a proper subset of the current `ImmSet` up * until the callback returns `false`. */ public function takeWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: ImmSet<Tv>; /** * Returns an `ImmSet` containing the values after the `n`-th element of the * current `ImmSet`. * * The returned `ImmSet` will always be a proper subset of the current * `ImmSet`. * * `n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `ImmSet`. * * @return - An `ImmSet` that is a proper subset of the current `ImmSet` * containing values after the specified `n`-th element. */ public function skip(int $n)[]: ImmSet<Tv>; /** * Returns an `ImmSet` containing the values of the current `ImmSet` starting * after and including the first value that produces `true` when passed to * the specified callback. * * The returned `ImmSet` will always be a proper subset of the current * `ImmSet`. * * @param $fn - The callback used to determine the starting element for the * `ImmSet`. * * @return - An `ImmSet` that is a proper subset of the current `ImmSet` * starting after the callback returns `true`. */ public function skipWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: ImmSet<Tv>; /** * Returns a subset of the current `ImmSet` starting from a given key up to, * but not including, the element at the provided length from the starting * key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `ImmSet` will always be a proper subset of the current * `ImmSet`. * * @param $start - The starting value in the current `ImmSet` for the * returned `ImmSet`. * @param $len - The length of the returned `ImmSet`. * * @return - An `ImmSet` that is a proper subset of the current `ImmSet` * starting at `$start` up to but not including the element * `$start + $len`. */ public function slice(int $start, int $len)[]: ImmSet<Tv>; /** * Returns an `ImmVector` that is the concatenation of the values of the * current `ImmSet` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `ImmSet` to produce the returned `ImmVector`. * * @param $traversable - The `Traversable` to concatenate to the current * `ImmSet`. * * @return - The concatenated `ImmVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: ImmVector<Tu>; /** * Returns the first value in the current `ImmSet`. * * This method is interchangeable with `firstKey()`. * * @return - The first value in the current `ImmSet`, or `null` if the * current `ImmSet` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first "key" in the current `ImmSet`. * * Since `ImmSet`s do not have keys, it returns the first value. * * This method is interchangeable with `firstValue()`. * * @return - The first value in the current `ImmSet`, or `null` if the * current `ImmSet` is empty. */ public readonly function firstKey()[]: ?arraykey; /** * Returns the last value in the current `ImmSet`. * * This method is interchangeable with `lastKey()`. * * @return - The last value in the current `ImmSet`, or `null` if the current * `ImmSet` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last "key" in the current `ImmSet`. * * Since `ImmSet`s do not have keys, it returns the last value. * * This method is interchangeable with `lastValue()`. * * @return - The last value in the current `ImmSet`, or `null` if the current * `ImmSet` is empty. */ public readonly function lastKey()[]: ?arraykey; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<Tv, Tv>; } } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/collections/ImmVector.hhi
<?hh /** * Copyright (c) 2014, 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. * */ <<file: __EnableUnstableFeatures('readonly')>> /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * `ImmVector` is an immutable `Vector`. HHVM provides a native implementation * for this class. The PHP class definition below is not actually used at run * time; it is simply provided for the typechecker and for developer reference. * * An `ImmVector` cannot be mutated. No elements can be added to it or removed * from it, nor can elements be overwritten using assignment (i.e. `$c[$k] = $v` * is not allowed). * * ``` * $v = Vector {1, 2, 3}; * $fv = $v->toImmVector(); * ``` * * construct it with a `Traversable`: * * ``` * $a = vec[1, 2, 3]; * $fv = new ImmVector($a); * ``` * * or use the literal syntax: * * ``` * $fv = ImmVector {1, 2, 3}; * ``` * * @guide /hack/collections/introduction * @guide /hack/collections/classes */ final class ImmVector<+Tv> implements \ConstVector<Tv> { /** * Creates an `ImmVector` from the given `Traversable`, or an empty * `ImmVector` if `null` is passed. * * @param $it - Any `Traversable` object from which to create the `ImmVector` * (e.g., `array`). If `null`, then an empty `ImmVector` is * created. */ public function __construct(?Traversable<Tv> $it)[]; /** * Checks if the current `ImmVector` is empty. * * @return - `true` if the current `ImmVector` is empty; `false` otherwise. */ public readonly function isEmpty()[]: bool; /** * Returns the number of elements in the current `ImmVector`. * * @return - The number of elements in the current `ImmVector`. */ public readonly function count()[]: int; /** * Returns the value at the specified key in the current `ImmVector`. * * If the key is not present, an exception is thrown. If you don't want an * exception to be thrown, use `get()` instead. * * `$v = $vec->at($k)` is semantically equivalent to `$v = $vec[$k]`. * * @param $k - The key for which to retrieve the value. * * @return - The value at the specified key; or an exception if the key does * not exist. */ public function at(int $k)[]: Tv; /** * Returns the value at the specified key in the current `ImmVector`. * * If the key is not present, `null` is returned. If you would rather have an * exception thrown when a key is not present, then use `at()`. * * @param $k - The key for which to retrieve the value. * * @return - The value at the specified key; or `null` if the key does not * exist. */ public function get(int $k)[]: ?Tv; /** * Determines if the specified key is in the current `ImmVector`. * * @return - `true` if the specified key is present in the current * `ImmVector`; `false` otherwise. * * @guide /hack/generics/constraints */ public readonly function containsKey(mixed $k)[]: bool; /** * Returns an `array` containing the values from the current `ImmVector`. * * This method is interchangeable with `toArray()`. * * @return - An `array` containing the values from the current `ImmVector`. */ public function toValuesArray()[]: varray<Tv>; /** * Returns an `array` whose values are the keys from the current `ImmVector`. * * @return - An `array` with the integer keys from the current `ImmVector`. */ public readonly function toKeysArray()[]: varray<int>; /** * Returns an iterator that points to beginning of the current `ImmVector`. * * @return - A `KeyedIterator` that allows you to traverse the current * `ImmVector`. */ public function getIterator()[]: KeyedIterator<int, Tv>; /** * Returns the index of the first element that matches the search value. * * If no element matches the search value, this function returns -1. * * @param $search_value - The value that will be searched for in the current * `ImmVector`. * * @return - The key (index) where that value is found; -1 if it is not found. * * @guide /hack/generics/constraints */ public readonly function linearSearch(mixed $search_value)[]: int; /** * Creates an `ImmVector` from the given `Traversable`, or an empty * `ImmVector` if `null` is passed. * * This is the static method version of the `ImmVector::__construct()` * constructor. * * @param $items - Any `Traversable` object from which to create an * `ImmVector` (e.g., `array`). If `null`, then an empty * `ImmVector` is created. * * @return - An `ImmVector` with the values from the `Traversable`; or an * empty `ImmVector` if the `Traversable` is `null`. */ public static function fromItems(?Traversable<Tv> $items)[]: ImmVector<Tv>; /** * Creates an `ImmVector` from the keys of the specified container. * * Every key in the provided `KeyedContainer` will appear sequentially in the * returned `ImmVector`, with the next available integer key assigned to each. * * @param $container - The container with the keys used to create the * current `ImmVector`. * * @return - An `ImmVector` built from the keys of the specified container. */ public static function fromKeysOf<Tk as arraykey>( ?KeyedContainer<Tk, mixed> $container, )[]: ImmVector<Tk>; /** * Returns the `string` version of the current `ImmVector`, which is * `"ImmVector"`. * * @return - The `string` `"ImmVector"`. */ public function __toString()[]: string; /** * Returns an `Iterable` view of the current `ImmVector`. * * The `Iterable` returned is one that produces the values from the current * `ImmVector`. * * @return - The `Iterable` view of the current `ImmVector`. */ public function items()[]: Iterable<Tv>; /** * Returns the current `ImmVector`. * * Unlike `Vector`'s `toVector()` method, this does not actually return a copy * of the current `ImmVector`. Since `ImmVector`s are immutable, there is no * reason to pay the cost of creating a copy of the current `ImmVector`. * * This method is interchangeable with `immutable()`. * * This method is NOT interchangeable with `values()`. `values()` returns a * new `ImmVector` that is a copy of the current `ImmVector`, and thus incurs * both the cost of copying the current `ImmVector`, and the memory space * consumed by the new `ImmVector`. This may be significant, for large * `ImmVector`s. * * @return - The current `ImmVector`. */ public function toImmVector()[]: ImmVector<Tv>; /** * Returns an immutable integer-keyed Map (`ImmMap`) based on the elements of * the current `ImmVector`. * * The keys are `0... count() - 1`. * * @return - An integer-keyed `ImmMap` with the values of the current * `ImmVector`. */ public function toImmMap()[]: ImmMap<int, Tv>; /** * Returns an immutable Set (`ImmSet`) with the values of the current * `ImmVector`. * * @return - An `ImmSet` with the current values of the current `ImmVector`. */ public function toImmSet()[]: ImmSet<Tv> where Tv as arraykey; /** * Returns the current `ImmVector`. * * Unlike `Vector`'s `toVector()` method, this does not actually return a copy * of the current `ImmVector`. Since `ImmVector`s are immutable, there is no * reason to pay the cost of creating a copy of the current `ImmVector`. * * This method is interchangeable with `toImmVector()`. * * This method is NOT interchangeable with `values()`. `values()` returns a * new `ImmVector` that is a copy of the current `ImmVector`, and thus incurs * both the cost of copying the current `ImmVector`, and the memory space * consumed by the new `ImmVector`. This may be significant, for large * `ImmVector`s. * * @return - The current `ImmVector`. */ public function immutable()[]: ImmVector<Tv>; /** * Returns a lazy, access-elements-only-when-needed view of the current * `ImmVector`. * * Normally, memory is allocated for all of the elements of an `ImmVector`. * With a lazy view, memory is allocated for an element only when needed or * used in a calculation like in `map()` or `filter()`. * * @return - An integer-keyed `KeyedIterable` representing the lazy view into * the current `ImmVector`. * * @guide /hack/collections/examples */ public function lazy()[]: KeyedIterable<int, Tv>; /** * Returns a new `ImmVector` containing the values of the current `ImmVector`; * that is, a copy of the current `ImmVector`. * * This method is NOT interchangeable with `toImmVector()` and `immutable()`. * `toImmVector()` and `immutable()` return the current `ImmVector`, and do * not incur the cost of copying the current `ImmVector`, or the memory space * consumed by the new `ImmVector`. This may be significant, for large * `ImmVector`s. * * @return - A new `ImmVector` containing the values of the current * `ImmVector`. */ public function values()[]: ImmVector<Tv>; /** * Returns an `ImmVector` containing the keys, as values, of the current * `ImmVector`. * * @return - An `ImmVector` containing, as values, the integer keys of the * current `ImmVector`. */ public readonly function keys()[]: ImmVector<int>; /** * Returns an `ImmVector` containing the results of applying an operation to * each value in the current `ImmVector`. * * `map()`'s result contains a value for every value in the current * `ImmVector`; unlike `filter()`, where only values that meet a certain * criterion are included in the resulting `ImmVector`. * * @param $fn - The callback containing the operation to apply to the * current `ImmVector`'s values. * * @return - An `ImmVector` containing the results of applying a user-specified * operation to each value of the current `ImmVector` in turn. * * @guide /hack/collections/examples */ public function map<Tu>((function(Tv)[_]: Tu) $fn)[ctx $fn]: ImmVector<Tu>; /** * Returns an `ImmVector` containing the results of applying an operation to * each key/value pair in the current `ImmVector`. * * `mapWithKey()`'s result contains a value for every key/value pair in the * current `ImmVector`; unlike `filterWithKey()`, where only values whose * key/value pairs meet a certain criterion are included in the resulting * `ImmVector`. * * @param $fn - The callback containing the operation to apply to the * current `ImmVector`'s key/value pairs. * * @return - An `ImmVector` containing the results of applying a * user-specified operation to each key/value pair of the current * `ImmVector` in turn. */ public function mapWithKey<Tu>( (function(int, Tv)[_]: Tu) $fn, )[ctx $fn]: ImmVector<Tu>; /** * Returns a `ImmVector` containing the values of the current `ImmVector` that * meet a supplied condition. * * `filter()`'s result contains only values that meet the provided criterion; * unlike `map()`, where a value is included for each value in the original * `ImmVector`. * * @param $fn - The callback containing the condition to apply to the * current `ImmVector` values. * * @return - An `ImmVector` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: ImmVector<Tv>; /** * Returns an `ImmVector` containing the values of the current `ImmVector` * that meet a supplied condition applied to its keys and values. * * `filterWithKey()`'s result contains only values whose key/value pairs * satisfy the provided criterion; unlike `mapWithKey()`, which contains * results derived from every key/value pair in the original `ImmVector`. * * @param $fn - The callback containing the condition to apply to the * `ImmVector`'s key/value pairs. For each key/value pair, * the key is passed as the first parameter to the * callback, and the value is passed as the second * parameter. * * @return - An `ImmVector` containing the values of the current `ImmVector` * for which a user-specified test condition returns true when * applied to the corresponding key/value pairs. * */ public function filterWithKey( (function(int, Tv)[_]: bool) $fn, )[ctx $fn]: ImmVector<Tv>; /** * Returns an `ImmVector` where each element is a `Pair` that combines the * element of the current `ImmVector` and the provided `Traversable`. * * If the number of elements of the current `ImmVector` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `ImmVector`. * * @return - An `ImmVector` that combines the values of the current * `ImmVector` with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: ImmVector<Pair<Tv, Tu>>; /** * Returns an `ImmVector` containing the first `$n` values of the current * `ImmVector`. * * The returned `ImmVector` will always be a subset (but not necessarily a * proper subset) of the current `ImmVector`. If `$n` is greater than the * length of the current `ImmVector`, the returned `ImmVector` will contain * all elements of the current `ImmVector`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the returned * `ImmVector`. * * @return - An `ImmVector` that is a subset of the current `ImmVector` up to * `$n` elements. */ public function take(int $n)[]: ImmVector<Tv>; /** * Returns an `ImmVector` containing the values of the current `ImmVector` up * to but not including the first value that produces `false` when passed to * the specified callback. That is, takes the continuous prefix of values in * the current `ImmVector` for which the specified callback returns `true`. * * The returned `ImmVector` will always be a subset (but not necessarily a * proper subset) of the current `ImmVector`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - An `ImmVector` that is a subset of the current `ImmVector` up * until when the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ImmVector<Tv>; /** * Returns an `ImmVector` containing the values after the `$n`-th element of * the current `ImmVector`. * * The returned `ImmVector` will always be a subset (but not necessarily a * proper subset) of the current `ImmVector`. If `$n` is greater than or equal * to the length of the current `ImmVector`, the returned `ImmVector` will * contain no elements. If `$n` is negative, the returned `ImmVector` will * contain all elements of the current `ImmVector`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `ImmVector`. * * @return - An `ImmVector` that is a subset of the current `ImmVector` * containing values after the specified `$n`-th element. */ public function skip(int $n)[]: ImmVector<Tv>; /** * Returns an `ImmVector` containing the values of the current `ImmVector` * starting after and including the first value that produces `false` when * passed to the specified callback. That is, skips the continuous prefix of * values in the current `ImmVector` for which the specified callback returns * `true`. * * The returned `ImmVector` will always be a subset (but not necessarily a * proper subset) of the current `ImmVector`. * * @param $fn - The callback used to determine the starting element for the * returned `ImmVector`. * * @return - An `ImmVector` that is a subset of the current `ImmVector` * starting with the value for which the callback first returns * `false`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ImmVector<Tv>; /** * Returns a subset of the current `ImmVector` starting from a given key up * to, but not including, the element at the provided length from the * starting key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `ImmVector` will always be a subset (but not necessarily a * proper subset) of the current `ImmVector`. If `$start` is greater than or * equal to the length of the current `Vector`, the returned `Vector` will * contain no elements. If `$start` + `$len` is greater than or equal to the * length of the current `Vector`, the returned `Vector` will contain the * elements from `$start` to the end of the current `Vector`. * * If either `$start` or `$len` is negative, an exception is thrown. * * @param $start - The starting key of the current `ImmVector` at which to * begin the returned `ImmVector`. * @param $len - The length of the returned `ImmVector`. * * @return - An `ImmVector` that is a subset of the current `ImmVector` * starting at `$start` up to but not including the element * `$start + $len`. */ public function slice(int $start, int $len)[]: ImmVector<Tv>; /** * Returns an `ImmVector` that is the concatenation of the values of the * current `ImmVector` and the values of the provided `Traversable`. * * The returned `ImmVector` is created from the values of the current * `ImmVector`, followed by the values of the provided `Traversable`. * * The returned `ImmVector` is a new object; the current `ImmVector` is * unchanged. * * @param $traversable - The `Traversable` to concatenate to the current * `ImmVector`. * * @return - A new `ImmVector` containing the values from `$traversable` * concatenated to the values from the current `ImmVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: ImmVector<Tu>; /** * Returns the first value in the current `ImmVector`. * * @return - The first value in the current `ImmVector`, or `null` if the * current `ImmVector` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first key in the current `ImmVector`. * * @return - The first key (an integer) in the current `ImmVector`, or `null` * if the current `ImmVector` is empty. */ public readonly function firstKey()[]: ?int; /** * Returns the last value in the current `ImmVector`. * * @return - The last value in the current `ImmVector`, or `null` if the * current `ImmVector` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last key in the current `ImmVector`. * * @return - The last key (an integer) in the current `ImmVector`, or `null` * if the current `ImmVector` is empty. */ public readonly function lastKey()[]: ?int; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<int, Tv>; } } // namespace HH
HTML Help Workshop
hhvm/hphp/hack/hhi/collections/interfaces.hhi
<?hh <<file: __EnableUnstableFeatures('readonly')>> namespace { /** * The base interface implemented for a collection type so that base information * such as count and its items are available. Every concrete class indirectly * implements this interface. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces * */ <<__Sealed( Collection::class, ConstMap::class, ConstSet::class, ConstVector::class, )>> interface ConstCollection<+Te> extends Countable, IPureStringishObject { /** * Is the collection empty? * * @return - Returns `true` if the collection is empty; `false` * otherswise. */ public readonly function isEmpty()[]: bool; /** * Get the number of items in the collection. Cannot be negative. * * @return - Returns the number of items in the collection */ public readonly function count()[]: int; /** * Get access to the items in the collection. Can be empty. * * @return - Returns an `Iterable` with access to all of the items in * the collection. */ public function items()[]: HH\Iterable<Te>; public function toVArray( )[]: varray<mixed>; public function toDArray( )[]: darray<arraykey, mixed>; } /** * The interface implemented for a mutable collection type so that values can * be added to it. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces * */ <<__Sealed(Collection::class)>> interface OutputCollection<-Te> { /** * Add a value to the collection and return the collection itself. * * It returns the current collection, meaning changes made to the current * collection will be reflected in the returned collection. * * @param $e - The value to add. * * @return - The updated collection itself. */ public function add(Te $e)[write_props]: this; /** * For every element in the provided `Traversable`, append a value into the * current collection. * * It returns the current collection, meaning changes made to the current * collection will be reflected in the returned collection. * * @param $traversable - The `Traversable` with the new values to set. If * `null` is provided, no changes are made. * * @return - Returns itself. */ public function addAll(?Traversable<Te> $traversable)[write_props]: this; } } // namespace namespace HH { /** * `Collection` is the primary collection interface for mutable collections. * * Assuming you want the ability to clear out your collection, you would * implement this (or a child of this) interface. Otherwise, you can implement * `OutputCollection` only. If your collection to be immutable, implement * `ConstCollection` only instead. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(\MutableMap::class, \MutableSet::class, \MutableVector::class)>> interface Collection<Te> extends \ConstCollection<Te>, \OutputCollection<Te> { /** * Removes all items from the collection. */ public function clear()[write_props]: this; } } // namespace HH namespace { /** * The interface for all `Set`s to enable access its values. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(ConstMapAccess::class, SetAccess::class, ConstSet::class)>> interface ConstSetAccess<+Tm as arraykey> { /** * Checks whether a value is in the current `Set`. * * @return - `true` if the value is in the current `Set`; `false` otherwise. */ public readonly function contains(arraykey $m)[]: bool; } /** * * The interface for mutable `Set`s to enable removal of its values. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(MapAccess::class, MutableSet::class)>> interface SetAccess<Tm as arraykey> extends ConstSetAccess<Tm> { /** * Removes the provided value from the current `Set`. * * If the value is not in the current `Set`, the `Set` is unchanged. * * It the current `Set`, meaning changes made to the current `Set` will be * reflected in the returned `Set`. * * @param $m - The value to remove. * * @return - Returns itself. */ public function remove(Tm $m)[write_props]: this; } /** * The interface for all keyed collections to enable access its values. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(ConstMapAccess::class, IndexAccess::class, ConstVector::class)>> interface ConstIndexAccess<Tk, +Tv> { /** * Returns the value at the specified key in the current collection. * * If the key is not present, an exception is thrown. If you don't want an * exception to be thrown, use `get()` instead. * * `$v = $vec->at($k)` is semantically equivalent to `$v = $vec[$k]`. * * @param $k - the key from which to retrieve the value. * * @return - The value at the specified key; or an exception if the key does * not exist. */ public function at(Tk $k)[]: Tv; /** * Returns the value at the specified key in the current collection. * * If the key is not present, `null` is returned. If you would rather have an * exception thrown when a key is not present, then use `at()`. * * @param $k - the key from which to retrieve the value. * * @return - The value at the specified key; or `null` if the key does not * exist. */ public function get(Tk $k)[]: ?Tv; /** * Determines if the specified key is in the current collection. * * @return - `true` if the specified key is present in the current collection; * `false` otherwise. * * @guide /hack/generics/constraints */ public readonly function containsKey(mixed $k)[]: bool; } /** * The interface for mutable, keyed collections to enable setting and removing * keys. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(MapAccess::class, MutableVector::class)>> interface IndexAccess<Tk, Tv> extends ConstIndexAccess<Tk, Tv> { /** * Stores a value into the current collection with the specified key, * overwriting the previous value associated with the key. * * If the key is not present, an exception is thrown. If you want to add * a value even if a key is not present, use `add()`. * * `$coll->set($k,$v)` is semantically equivalent to `$coll[$k] = $v` * (except that `set()` returns the current collection). * * It returns the current collection, meaning changes made to the current * collection will be reflected in the returned collection. * * @param $k - The key to which we will set the value. * @param $v - The value to set. * * @return - Returns itself. */ public function set(Tk $k, Tv $v)[write_props]: this; /** * For every element in the provided `Traversable`, stores a value into the * current collection associated with each key, overwriting the previous value * associated with the key. * * If a key is not present the current Vector that is present in the * `Traversable`, an exception is thrown. If you want to add a value even if a * key is not present, use `addAll()`. * * It the current collection, meaning changes made to the current collection * will be reflected in the returned collection. * * @param $traversable - The `Traversable` with the new values to set. If * `null` is provided, no changes are made. * * @return - Returns itself. */ public function setAll( ?KeyedTraversable<Tk, Tv> $traversable, )[write_props]: this; /** * Removes the specified key (and associated value) from the current * collection. * * If the key is not in the current collection, the current collection is * unchanged. * * It the current collection, meaning changes made to the current collection * will be reflected in the returned collection. * * @param $k - The key to remove. * * @return - Returns itself. */ public function removeKey(Tk $k)[write_props]: this; } /** * The interface for enabling access to the `Map`s values. * * This interface provides no new methods as all current access for `Map`s are * defined in its parent interfaces. But you could theoretically use this * interface for parameter and return type annotations. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(ConstMap::class, MapAccess::class)>> interface ConstMapAccess<Tk as arraykey, +Tv> extends ConstSetAccess<Tk>, ConstIndexAccess<Tk, Tv> { } /** * The interface for setting and removing `Map` keys (and associated values). * * This interface provides no new methods as all current access for `Map`s are * defined in its parent interfaces. But you could theoretically use this * interface for parameter and return type annotations. * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(MutableMap::class)>> interface MapAccess<Tk as arraykey, Tv> extends ConstMapAccess<Tk, Tv>, SetAccess<Tk>, IndexAccess<Tk, Tv> { } /** * Represents a read-only (immutable) sequence of values, indexed by integers * (i.e., a vector). * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(ImmVector::class, MutableVector::class, Pair::class)>> interface ConstVector<+Tv> extends KeyedContainer<int, Tv>, ConstCollection<Tv>, ConstIndexAccess<int, Tv>, HH\KeyedIterable<int, Tv> { /** * Returns a `ConstVector` containing the values of the current * `ConstVector`. Essentially a copy of the current `ConstVector`. * * This method is interchangeable with `toVector()`. * * @return - a `ConstVector` containing the values of the current * `ConstVector`. */ public function values()[]: ConstVector<Tv>; /** * Returns a `ConstVector` containing the keys of the current `ConstVector`. * * @return - a `ConstVector` containing the integer keys of the current * `ConstVector`. */ public function keys()[]: ConstVector<int>; /** * Returns a `ConstVector` containing the values after an operation has been * applied to each value in the current `ConstVector`. * * Every value in the current `ConstVector` is affected by a call to `map()`, * unlike `filter()` where only values that meet a certain criteria are * affected. * * @param $fn - The callback containing the operation to apply to the * `ConstVector` values. * * @return - a `ConstVector` containing the values after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: ConstVector<Tu>; /** * Returns a `ConstVector` containing the values after an operation has been * applied to each key and value in the current `ConstVector`. * * Every key and value in the current `ConstVector` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * @param $fn - The callback containing the operation to apply to the * `ConstVector` keys and values. * * @return - a `ConstVector` containing the values after a user-specified * operation on the current Vector's keys and values is applied. */ public function mapWithKey<Tu>( (function(int, Tv)[_]: Tu) $fn, )[ctx $fn]: ConstVector<Tu>; /** * Returns a `ConstVector` containing the values of the current `ConstVector` * that meet a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The $fn containing the condition to apply to the * `ConstVector` values. * * @return - a `ConstVector` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ConstVector<Tv>; /** * Returns a `ConstVector` containing the values of the current `ConstVector` * that meet a supplied condition applied to its keys and values. * * Only keys and values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * @param $fn - The callback containing the condition to apply to the * `ConstVector` keys and values. * * @return - a `ConstVector` containing the values after a user-specified * condition is applied to the keys and values of the current * `ConstVector`. */ public function filterWithKey( (function(int, Tv)[_]: bool) $fn, )[ctx $fn]: ConstVector<Tv>; /** * Returns a `ConstVector` where each element is a `Pair` that combines the * element of the current `ConstVector` and the provided `Traversable`. * * If the number of elements of the `ConstVector` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * @param $traversable - The `Traversable` to use to combine with the * elements of this `ConstVector`. * * @return - The `ConstVector` that combines the values of the current * `ConstVector` with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: ConstVector<Pair<Tv, Tu>>; /** * Returns a `ConstVector` containing the first `n` values of the current * `ConstVector`. * * The returned `ConstVector` will always be a proper subset of the current * `ConstVector`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the returned * `ConstVector`. * * @return - A `ConstVector` that is a proper subset of the current * `ConstVector` up to `n` elements. */ public function take(int $n)[]: ConstVector<Tv>; /** * Returns a `ConstVector` containing the values of the current `ConstVector` * up to but not including the first value that produces `false` when passed * to the specified callback. * * The returned `ConstVector` will always be a proper subset of the current * `ConstVector`. * * @param $fn - The callback that is used to determine the stopping * condition. * * @return - A `ConstVector` that is a proper subset of the current * `ConstVector` up until the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ConstVector<Tv>; /** * Returns a `ConstVector` containing the values after the `n`-th element of * the current `ConstVector`. * * The returned `ConstVector` will always be a proper subset of the current * `ConstVector`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the $n+1 element will be the * first one in the returned `ConstVector`. * * @return - A `ConstVector` that is a proper subset of the current * `ConstVector` containing values after the specified `n`-th * element. */ public function skip(int $n)[]: ConstVector<Tv>; /** * Returns a `ConstVector` containing the values of the current `ConstVector` * starting after and including the first value that produces `true` when * passed to the specified callback. * * The returned `ConstVector` will always be a proper subset of the current * `ConstVector`. * * @param $fn - The callback used to determine the starting element for the * returned `ConstVector`. * * @return - A `ConstVector` that is a proper subset of the current * `ConstVector` starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ConstVector<Tv>; /** * Returns a subset of the current `ConstVector` starting from a given key up * to, but not including, the element at the provided length from the starting * key. * * `$start` is 0-based. $len is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `ConstVector` will always be a proper subset of this * `ConstVector`. * * @param $start - The starting key of this Vector to begin the returned * `ConstVector`. * @param $len - The length of the returned `ConstVector`. * * @return - A `ConstVector` that is a proper subset of the current * `ConstVector` starting at `$start` up to but not including the * element `$start + $len`. */ public function slice(int $start, int $len)[]: ConstVector<Tv>; /** * Returns a `ConstVector` that is the concatenation of the values of the * current `ConstVector` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `ConstVector` to produce the returned `ConstVector`. * * @param $traversable - The `Traversable` to concatenate to the current * `ConstVector`. * * @return - The concatenated `ConstVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: ConstVector<Tu>; /** * Returns the first value in the current `ConstVector`. * * @return - The first value in the current `ConstVector`, or `null` if the * current `ConstVector` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first key in the current `ConstVector`. * * @return - The first key in the current `ConstVector`, or `null` if the * current `ConstVector` is empty. */ public readonly function firstKey()[]: ?int; /** * Returns the last value in the current `ConstVector`. * * @return - The last value in the current `ConstVector`, or `null` if the * current `ConstVector` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last key in the current `ConstVector`. * * @return - The last key in the current `ConstVector`, or `null` if the * current `ConstVector` is empty. */ public readonly function lastKey()[]: ?int; /** * Returns the index of the first element that matches the search value. * * If no element matches the search value, this function returns -1. * * @param $search_value - The value that will be search for in the current * `ConstVector`. * * @return - The key (index) where that value is found; -1 if it is not found. * * @guide /hack/generics/constraints */ public readonly function linearSearch(mixed $search_value)[]: int; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<int, Tv>; } /** * Represents a write-enabled (mutable) sequence of values, indexed by integers * (i.e., a vector). * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(Vector::class)>> interface MutableVector<Tv> extends ConstVector<Tv>, Collection<Tv>, IndexAccess<int, Tv> { /** * Returns a `MutableVector` containing the values of the current * `MutableVector`. Essentially a copy of the current `MutableVector`. * * This method is interchangeable with `toVector()`. * * @return - a `MutableVector` containing the values of the current * `MutableVector`. */ public function values()[]: MutableVector<Tv>; /** * Returns a `MutableVector` containing the keys of the current * `MutableVector`. * * @return - a `MutableVector` containing the integer keys of the current * `MutableVector`. */ public readonly function keys()[]: MutableVector<int>; /** * Returns a `MutableVector` containing the values after an operation has been * applied to each value in the current `MutableVector`. * * Every value in the current `MutableVector` is affected by a call to * `map()`, unlike `filter()` where only values that meet a certain criteria * are affected. * * @param $fn - The callback containing the operation to apply to the * `MutableVector` values. * * @return - a `MutableVector` containing the values after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: MutableVector<Tu>; /** * Returns a `MutableVector` containing the values after an operation has been * applied to each key and value in the current `MutableVector`. * * Every key and value in the current `MutableVector` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * @param $fn - The callback containing the operation to apply to the * `MutableVector` keys and values. * * @return - a `MutableVector` containing the values after a user-specified * operation on the current Vector's keys and values is applied. */ public function mapWithKey<Tu>( (function(int, Tv)[_]: Tu) $fn, )[ctx $fn]: MutableVector<Tu>; /** * Returns a `MutableVector` containing the values of the current * `MutableVector` that meet a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The $fn containing the condition to apply to the * `MutableVector` values. * * @return - a `MutableVector` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableVector<Tv>; /** * Returns a `MutableVector` containing the values of the current * `MutableVector` that meet a supplied condition applied to its keys and * values. * * Only keys and values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * @param $fn - The callback containing the condition to apply to the * `MutableVector` keys and values. * * @return - a `MutableVector` containing the values after a user-specified * condition is applied to the keys and values of the current * `MutableVector`. * */ public function filterWithKey( (function(int, Tv)[_]: bool) $fn, )[ctx $fn]: MutableVector<Tv>; /** * Returns a `MutableVector` where each element is a `Pair` that combines the * element of the current `MutableVector` and the provided `Traversable`. * * If the number of elements of the `MutableVector` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * @param $traversable - The `Traversable` to use to combine with the * elements of this `MutableVector`. * * @return - The `MutableVector` that combines the values of the current * `MutableVector` with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: MutableVector<Pair<Tv, Tu>>; /** * Returns a `MutableVector` containing the first `n` values of the current * `MutableVector`. * * The returned `MutableVector` will always be a proper subset of the current * `MutableVector`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the returned * `MutableVector`. * * @return - A `MutableVector` that is a proper subset of the current * `MutableVector` up to `n` elements. */ public function take(int $n)[]: MutableVector<Tv>; /** * Returns a `MutableVector` containing the values of the current * `MutableVector` up to but not including the first value that produces * `false` when passed to the specified callback. * * The returned `MutableVector` will always be a proper subset of the current * `MutableVector`. * * @param $fn - The callback that is used to determine the stopping * condition. * * @return - A `MutableVector` that is a proper subset of the current * `MutableVector` up until the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableVector<Tv>; /** * Returns a `MutableVector` containing the values after the `n`-th element of * the current `MutableVector`. * * The returned `MutableVector` will always be a proper subset of the current * `MutableVector`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the $n+1 element will be the * first one in the returned `MutableVector`. * * @return - A `MutableVector` that is a proper subset of the current * `MutableVector` containing values after the specified `n`-th * element. */ public function skip(int $n)[]: MutableVector<Tv>; /** * Returns a `MutableVector` containing the values of the current * `MutableVector` starting after and including the first value that produces * `true` when passed to the specified callback. * * The returned `MutableVector` will always be a proper subset of the current * `MutableVector`. * * @param $fn - The callback used to determine the starting element for the * returned `MutableVector`. * * @return - A `MutableVector` that is a proper subset of the current * `MutableVector` starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableVector<Tv>; /** * Returns a subset of the current `MutableVector` starting from a given key * up to, but not including, the element at the provided length from the * starting key. * * `$start` is 0-based. $len is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `MutableVector` will always be a proper subset of this * `MutableVector`. * * @param $start - The starting key of this Vector to begin the returned * `MutableVector`. * @param $len - The length of the returned `MutableVector`. * * @return - A `MutableVector` that is a proper subset of the current * `MutableVector` starting at `$start` up to but not including the * element `$start + $len`. */ public function slice(int $start, int $len)[]: MutableVector<Tv>; /** * Returns a `MutableVector` that is the concatenation of the values of the * current `MutableVector` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `MutableVector` to produce the returned `MutableVector`. * * @param $traversable - The `Traversable` to concatenate to the current * `MutableVector`. * * @return - The concatenated `MutableVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: MutableVector<Tu>; /** * Returns the first value in the current `MutableVector`. * * @return - The first value in the current `MutableVector`, or `null` if the * current `MutableVector` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first key in the current `MutableVector`. * * @return - The first key in the current `MutableVector`, or `null` if the * current `MutableVector` is empty. */ public readonly function firstKey()[]: ?int; /** * Returns the last value in the current `MutableVector`. * * @return - The last value in the current `MutableVector`, or `null` if the * current `MutableVector` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last key in the current `MutableVector`. * * @return - The last key in the current `MutableVector`, or `null` if the * current `MutableVector` is empty. */ public readonly function lastKey()[]: ?int; /** * Returns the index of the first element that matches the search value. * * If no element matches the search value, this function returns -1. * * @param $search_value - The value that will be search for in the current * `MutableVector`. * * @return - The key (index) where that value is found; -1 if it is not found. * * @guide /hack/generics/constraints */ public readonly function linearSearch(mixed $search_value)[]: int; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<int, Tv>; } /** * Represents a read-only (immutable) sequence of key/value pairs, (i.e. a map). * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(ImmMap::class, MutableMap::class)>> interface ConstMap<Tk as arraykey, +Tv> extends KeyedContainer<Tk, Tv>, ConstCollection<Pair<Tk, Tv>>, ConstMapAccess<Tk, Tv>, HH\KeyedIterable<Tk, Tv> { /** * Returns a `ConstVector` containing the values of the current `ConstMap`. * * The indices of the `ConstVector will be integer-indexed starting from 0, * no matter the keys of the `ConstMap`. * * @return - a `ConstVector` containing the values of the current `ConstMap`. */ public function values()[]: ConstVector<Tv>; /** * Returns a `ConstVector` containing the keys of the current `ConstMap`. * * @return - a `ConstVector` containing the keys of the current `ConstMap`. */ public readonly function keys()[]: ConstVector<Tk>; /** * Returns a `ConstMap` after an operation has been applied to each value in * the current `ConstMap`. * * Every value in the current Map is affected by a call to `map()`, unlike * `filter()` where only values that meet a certain criteria are affected. * * The keys will remain unchanged from the current `ConstMap` to the returned * `ConstMap`. * * @param $fn - The callback containing the operation to apply to the current * `ConstMap` values. * * @return - a `ConstMap` containing key/value pairs after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: ConstMap<Tk, Tu>; /** * Returns a `ConstMap` after an operation has been applied to each key and * value in the current `ConstMap`. * * Every key and value in the current `ConstMap` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * The keys will remain unchanged from this `ConstMap` to the returned * `ConstMap`. The keys are only used to help in the mapping operation. * * @param $fn - The callback containing the operation to apply to the current * `ConstMap` keys and values. * * @return - a `ConstMap` containing the values after a user-specified * operation on the current `ConstMap`'s keys and values is applied. */ public function mapWithKey<Tu>( (function(Tk, Tv)[_]: Tu) $fn, )[ctx $fn]: ConstMap<Tk, Tu>; /** * Returns a `ConstMap` containing the values of the current `ConstMap` that * meet a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * The keys associated with the current `ConstMap` remain unchanged in the * returned `ConstMap`. * * @param $fn - The callback containing the condition to apply to the current * `ConstMap` values. * * @return - a Map containing the values after a user-specified condition * is applied. * * @guide /hack/collections/examples */ public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ConstMap<Tk, Tv>; /** * Returns a `ConstMap` containing the values of the current `ConstMap` that * meet a supplied condition applied to its keys and values. * * Only keys and values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * The keys associated with the current `ConstMap` remain unchanged in the * returned `ConstMap`; the keys will be used in the filtering process only. * * @param $fn - The callback containing the condition to apply to the current * `ConstMap` keys and values. * * @return - a `ConstMap` containing the values after a user-specified * condition is applied to the keys and values of the current * `ConstMap`. */ public function filterWithKey( (function(Tk, Tv)[_]: bool) $fn, )[ctx $fn]: ConstMap<Tk, Tv>; /** * Returns a `ConstMap` where each value is a `Pair` that combines the value * of the current `ConstMap` and the provided `Traversable`. * * If the number of values of the current `ConstMap` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * The keys associated with the current `ConstMap` remain unchanged in the * returned `ConstMap`. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `ConstMap`. * * @return - The `ConstMap` that combines the values of the current * `ConstMap` with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: ConstMap<Tk, Pair<Tv, Tu>>; /** * Returns a `ConstMap` containing the first `n` key/values of the current * `ConstMap`. * * The returned `ConstMap` will always be a proper subset of the current * `ConstMap`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the `ConstMap`. * * @return - A `ConstMap` that is a proper subset of the current `ConstMap` * up to `n` elements. */ public function take(int $n)[]: ConstMap<Tk, Tv>; /** * Returns a `ConstMap` containing the keys and values of the current * `ConstMap` up to but not including the first value that produces `false` * when passed to the specified callback. * * The returned `ConstMap` will always be a proper subset of the current * `ConstMap`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - A `ConstMap` that is a proper subset of the current `ConstMap` * up until the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ConstMap<Tk, Tv>; /** * Returns a `ConstMap` containing the values after the `n`-th element of the * current `ConstMap`. * * The returned `ConstMap` will always be a proper subset of the current * `ConstMap`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `ConstMap`. * * @return - A `ConstMap` that is a proper subset of the current `ConstMap` * containing values after the specified `n`-th element. */ public function skip(int $n)[]: ConstMap<Tk, Tv>; /** * Returns a `ConstMap` containing the values of the current `ConstMap` * starting after and including the first value that produces `true` when * passed to the specified callback. * * The returned `ConstMap` will always be a proper subset of the current * `ConstMap`. * * @param $fn - The callback used to determine the starting element for the * current `ConstMap`. * * @return - A `ConstMap` that is a proper subset of the current `ConstMap` * starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ConstMap<Tk, Tv>; /** * Returns a subset of the current `ConstMap` starting from a given key * location up to, but not including, the element at the provided length from * the starting key location. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * keys and values at key location 0 and 1. * * The returned `ConstMap` will always be a proper subset of the current * `ConstMap`. * * @param $start - The starting key location of the current `ConstMap` for the * returned `ConstMap`. * @param $len - The length of the returned `ConstMap`. * * @return - A `ConstMap` that is a proper subset of the current `ConstMap` * starting at `$start` up to but not including the element * `$start + $len`. */ public function slice(int $start, int $len)[]: ConstMap<Tk, Tv>; /** * Returns a `ConstVector` that is the concatenation of the values of the * current `ConstMap` and the values of the provided `Traversable`. * * The provided `Traversable` is concatenated to the end of the current * `ConstMap` to produce the returned `ConstVector`. * * @param $traversable - The `Traversable` to concatenate to the current * `ConstMap`. * * @return - The integer-indexed concatenated `ConstVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: ConstVector<Tu>; /** * Returns the first value in the current `ConstMap`. * * @return - The first value in the current `ConstMap`, or `null` if the * `ConstMap` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first key in the current `ConstMap`. * * @return - The first key in the current `ConstMap`, or `null` if the * `ConstMap` is empty. */ public readonly function firstKey()[]: ?Tk; /** * Returns the last value in the current `ConstMap`. * * @return - The last value in the current `ConstMap`, or `null` if the * `ConstMap` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last key in the current `ConstMap`. * * @return - The last key in the current `ConstMap`, or null if the `ConstMap` * is empty. */ public readonly function lastKey()[]: ?Tk; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<Tk, Tv>; } /** * Represents a write-enabled (mutable) sequence of key/value pairs * (i.e. a map). * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(Map::class)>> interface MutableMap<Tk as arraykey, Tv> extends ConstMap<Tk, Tv>, Collection<Pair<Tk, Tv>>, MapAccess<Tk, Tv> { /** * Returns a `MutableVector` containing the values of the current * `MutableMap`. * * The indices of the `MutableVector will be integer-indexed starting from 0, * no matter the keys of the `MutableMap`. * * @return - a `MutableVector` containing the values of the current * `MutableMap`. */ public function values()[]: MutableVector<Tv>; /** * Returns a `MutableVector` containing the keys of the current `MutableMap`. * * @return - a `MutableVector` containing the keys of the current * `MutableMap`. */ public readonly function keys()[]: MutableVector<Tk>; /** * Returns a `MutableMap` after an operation has been applied to each value * in the current `MutableMap`. * * Every value in the current Map is affected by a call to `map()`, unlike * `filter()` where only values that meet a certain criteria are affected. * * The keys will remain unchanged from the current `MutableMap` to the * returned `MutableMap`. * * @param $fn - The callback containing the operation to apply to the current * `MutableMap` values. * * @return - a `MutableMap` containing key/value pairs after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: MutableMap<Tk, Tu>; /** * Returns a `MutableMap` after an operation has been applied to each key and * value in the current `MutableMap`. * * Every key and value in the current `MutableMap` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * The keys will remain unchanged from this `MutableMap` to the returned * `MutableMap`. The keys are only used to help in the mapping operation. * * @param $fn - The callback containing the operation to apply to the current * `MutableMap` keys and values. * * @return - a `MutableMap` containing the values after a user-specified * operation on the current `MutableMap`'s keys and values is * applied. */ public function mapWithKey<Tu>( (function(Tk, Tv)[_]: Tu) $fn, )[ctx $fn]: MutableMap<Tk, Tu>; /** * Returns a `MutableMap` containing the values of the current `MutableMap` * that meet a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * The keys associated with the current `MutableMap` remain unchanged in the * returned `MutableMap`. * * @param $fn - The callback containing the condition to apply to the current * `MutableMap` values. * * @return - a Map containing the values after a user-specified condition * is applied. * * @guide /hack/collections/examples */ public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableMap<Tk, Tv>; /** * Returns a `MutableMap` containing the values of the current `MutableMap` * that meet a supplied condition applied to its keys and values. * * Only keys and values that meet a certain criteria are affected by a call * to `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * The keys associated with the current `MutableMap` remain unchanged in the * returned `MutableMap`; the keys will be used in the filtering process only. * * @param $fn - The callback containing the condition to apply to the current * `MutableMap` keys and values. * * @return - a `MutableMap` containing the values after a user-specified * condition is applied to the keys and values of the current * `MutableMap`. */ public function filterWithKey( (function(Tk, Tv)[_]: bool) $fn, )[ctx $fn]: MutableMap<Tk, Tv>; /** * Returns a `MutableMap` where each value is a `Pair` that combines the * value of the current `MutableMap` and the provided `Traversable`. * * If the number of values of the current `MutableMap` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * The keys associated with the current `MutableMap` remain unchanged in the * returned `MutableMap`. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `MutableMap`. * * @return - The `MutableMap` that combines the values of the current * `MutableMap` with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: MutableMap<Tk, Pair<Tv, Tu>>; /** * Returns a `MutableMap` containing the first `n` key/values of the current * `MutableMap`. * * The returned `MutableMap` will always be a proper subset of the current * `MutableMap`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the `MutableMap`. * * @return - A `MutableMap` that is a proper subset of the current * `MutableMap` up to `n` elements. */ public function take(int $n)[]: MutableMap<Tk, Tv>; /** * Returns a `MutableMap` containing the keys and values of the current * `MutableMap` up to but not including the first value that produces `false` * when passed to the specified callback. * * The returned `MutableMap` will always be a proper subset of the current * `MutableMap`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - A `MutableMap` that is a proper subset of the current * `MutableMap` up until the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableMap<Tk, Tv>; /** * Returns a `MutableMap` containing the values after the `n`-th element of * the current `MutableMap`. * * The returned `MutableMap` will always be a proper subset of the current * `MutableMap`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `MutableMap`. * * @return - A `MutableMap` that is a proper subset of the current * `MutableMap` containing values after the specified `n`-th * element. */ public function skip(int $n)[]: MutableMap<Tk, Tv>; /** * Returns a `MutableMap` containing the values of the current `MutableMap` * starting after and including the first value that produces `true` when * passed to the specified callback. * * The returned `MutableMap` will always be a proper subset of the current * `MutableMap`. * * @param $fn - The callback used to determine the starting element for the * current `MutableMap`. * * @return - A `MutableMap` that is a proper subset of the current * `MutableMap` starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableMap<Tk, Tv>; /** * Returns a subset of the current `MutableMap` starting from a given key * location up to, but not including, the element at the provided length from * the starting key location. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * keys and values at key location 0 and 1. * * The returned `MutableMap` will always be a proper subset of the current * `MutableMap`. * * @param $start - The starting key location of the current `MutableMap` for * the feturned `MutableMap`. * @param $len - The length of the returned `MutableMap`. * * @return - A `MutableMap` that is a proper subset of the current * `MutableMap` starting at `$start` up to but not including the * element `$start + $len`. */ public function slice(int $start, int $len)[]: MutableMap<Tk, Tv>; /** * Returns a `MutableVector` that is the concatenation of the values of the * current `MutableMap` and the values of the provided `Traversable`. * * The provided `Traversable` is concatenated to the end of the current * `MutableMap` to produce the returned `MutableVector`. * * @param $traversable - The `Traversable` to concatenate to the current * `MutableMap`. * * @return - The integer-indexed concatenated `MutableVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: MutableVector<Tu>; /** * Returns the first value in the current `MutableMap`. * * @return - The first value in the current `MutableMap`, or `null` if the * `MutableMap` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first key in the current `MutableMap`. * * @return - The first key in the current `MutableMap`, or `null` if the * `MutableMap` is empty. */ public readonly function firstKey()[]: ?Tk; /** * Returns the last value in the current `MutableMap`. * * @return - The last value in the current `MutableMap`, or `null` if the * `MutableMap` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last key in the current `MutableMap`. * * @return - The last key in the current `MutableMap`, or null if the * `MutableMap` is empty. */ public readonly function lastKey()[]: ?Tk; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<Tk, Tv>; } /** * Represents a read-only (immutable) set of values, with no keys * (i.e., a set). * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(ImmSet::class, MutableSet::class)>> interface ConstSet<+Tv as arraykey> extends KeyedContainer<Tv, Tv>, ConstCollection<Tv>, ConstSetAccess<Tv>, HH\KeyedIterable<arraykey, Tv> { /** * Returns a `ConstVector` containing the values of the current `ConstSet`. * * This method is interchangeable with `keys()`. * * @return - a `ConstVector` (integer-indexed) containing the values of the * current `ConstSet`. */ public function values()[]: ConstVector<Tv>; /** * Returns a `ConstVector` containing the values of the current `ConstSet`. * * Sets don't have keys, so this will return the values. * * This method is interchangeable with `values()`. * * @return - a `ConstVector` (integer-indexed) containing the values of the * current `ConstSet`. */ public readonly function keys()[]: ConstVector<arraykey>; /** * Returns a `ConstSet` containing the values after an operation has been * applied to each value in the current `ConstSet`. * * Every value in the current `ConstSet` is affected by a call to `map()`, * unlike `filter()` where only values that meet a certain criteria are * affected. * * @param $fn - The callback containing the operation to apply to the * current `ConstSet` values. * * @return - a `ConstSet` containing the values after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu as arraykey>((function(Tv)[_]: Tu) $fn)[ctx $fn]: ConstSet<Tu>; /** * Returns a `ConstSet` containing the values after an operation has been * applied to each "key" and value in the current Set. * * Since sets don't have keys, the callback uses the values as the keys * as well. * * Every value in the current `ConstSet` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * @param $fn - The callback containing the operation to apply to the * current `ConstSet` "keys" and values. * * @return - a `ConstSet` containing the values after a user-specified * operation on the current `ConstSet`'s values is applied. */ public function mapWithKey<Tu as arraykey>((function(arraykey, Tv)[_]: Tu) $fn)[ctx $fn]: ConstSet<Tu>; /** * Returns a `ConstSet` containing the values of the current `ConstSet` that * meet a supplied condition applied to each value. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The callback containing the condition to apply to the * current `ConstSet` values. * * @return - a `ConstSet` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: ConstSet<Tv>; /** * Returns a `ConstSet` containing the values of the current `ConstSet` that * meet a supplied condition applied to its "keys" and values. * * Since sets don't have keys, the callback uses the values as the keys * as well. * * Only values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * @param $fn - The callback containing the condition to apply to the * current `ConstSet` "keys" and values. * * @return - a `ConstSet` containing the values after a user-specified * condition is applied to the values of the current `ConstSet`. */ public function filterWithKey( (function(arraykey, Tv)[_]: bool) $fn, )[ctx $fn]: ConstSet<Tv>; /** * Returns a `ConstSet` where each value is a `Pair` that combines the value * of the current `ConstSet` and the provided `Traversable`. * * If the number of values of the current `ConstMap` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * Note that some implementations of sets only support certain types of keys * (e.g., only `int` or `string` values allowed). In that case, this method * could thrown an exception since a `Pair` wouldn't be supported/ * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `ConstSet`. * * @return - The `ConstSet` that combines the values of the current * `ConstSet` with the provided `Traversable`. */ public function zip<Tu>(Traversable<Tu> $traversable)[]: ConstSet<nothing>; /** * Returns a `ConstSet` containing the first `n` values of the current * `ConstSet`. * * The returned `ConstSet` will always be a proper subset of the current * `ConstSet`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the `ConstSet`. * * @return - A `ConstSet` that is a proper subset of the current `ConstSet` * up to `n` elements. */ public function take(int $n)[]: ConstSet<Tv>; /** * Returns a `ConstSet` containing the values of the current `ConstSet` up to * but not including the first value that produces `false` when passed to the * specified callback. * * The returned `ConstSet` will always be a proper subset of the current * `ConstSet`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - A `ConstSet` that is a proper subset of the current `ConstSet` * up until the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ConstSet<Tv>; /** * Returns a `ConstSet` containing the values after the `n`-th element of the * current `ConstSet`. * * The returned `ConstSet` will always be a proper subset of the current * `ConstSet`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `ConstSet`. * * @return - A `ConstSet` that is a proper subset of the current `ConstSet` * containing values after the specified `n`-th element. */ public function skip(int $n)[]: ConstSet<Tv>; /** * Returns a `ConstSet` containing the values of the current `ConstSet` * starting after and including the first value that produces `true` when * passed to the specified callback. * * The returned `ConstSet` will always be a proper subset of the current * `ConstSet`. * * @param $fn - The callback used to determine the starting element for the * `ConstSet`. * * @return - A `ConstSet` that is a proper subset of the current `ConstSet` * starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: ConstSet<Tv>; /** * Returns a subset of the current `ConstSet` starting from a given key up * to, but not including, the element at the provided length from the * starting key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `ConstSet` will always be a proper subset of the current * `ConstSet`. * * @param $start - The starting value in the current `ConstSet` for the * returned `ConstSet`. * @param $len - The length of the returned `ConstSet`. * * @return - A `ConstSet` that is a proper subset of the current `ConstSet` * starting at `$start` up to but not including the element * `$start + $len`. */ public function slice(int $start, int $len)[]: ConstSet<Tv>; /** * Returns a `ConstVector` that is the concatenation of the values of the * current `ConstSet` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `ConstSet` to produce the returned `ConstVector`. * * @param $traversable - The `Traversable` to concatenate to the current * `ConstSet`. * * @return - The concatenated `ConstVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: ConstVector<Tu>; /** * Returns the first value in the current `ConstSet`. * * @return - The first value in the current `ConstSet`, or `null` if the * `ConstSet` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first "key" in the current `ConstSet`. * * Since sets do not have keys, it returns the first value. * * This method is interchangeable with `firstValue()`. * * @return - The first value in the current `ConstSet`, or `null` if the * `ConstSet` is empty. */ public readonly function firstKey()[]: ?arraykey; /** * Returns the last value in the current `ConstSet`. * * @return - The last value in the current `ConstSet`, or `null` if the * current `ConstSet` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last "key" in the current `ConstSet`. * * Since sets do not have keys, it returns the last value. * * This method is interchangeable with `lastValue()`. * * @return - The last value in the current `ConstSet`, or `null` if the * current `ConstSet` is empty. */ public readonly function lastKey()[]: ?arraykey; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<Tv, Tv>; } /** * Represents a write-enabled (mutable) set of values, not indexed by keys * (i.e. a set). * * @guide /hack/collections/introduction * @guide /hack/collections/interfaces */ <<__Sealed(Set::class)>> interface MutableSet<Tv as arraykey> extends ConstSet<Tv>, Collection<Tv>, SetAccess<Tv> { /** * Returns a `MutableVector` containing the values of the current * `MutableSet`. * * This method is interchangeable with `keys()`. * * @return - a `MutableVector` (integer-indexed) containing the values of the * current `MutableSet`. */ public function values()[]: MutableVector<Tv>; /** * Returns a `MutableVector` containing the values of the current * `MutableSet`. * * Sets don't have keys, so this will return the values. * * This method is interchangeable with `values()`. * * @return - a `MutableVector` (integer-indexed) containing the values of the * current `MutableSet`. */ public readonly function keys()[]: MutableVector<arraykey>; /** * Returns a `MutableSet` containing the values after an operation has been * applied to each value in the current `MutableSet`. * * Every value in the current `MutableSet` is affected by a call to `map()`, * unlike `filter()` where only values that meet a certain criteria are * affected. * * @param $fn - The callback containing the operation to apply to the * current `MutableSet` values. * * @return - a `MutableSet` containing the values after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu as arraykey>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: MutableSet<Tu>; /** * Returns a `MutableSet` containing the values after an operation has been * applied to each "key" and value in the current Set. * * Since sets don't have keys, the callback uses the values as the keys * as well. * * Every value in the current `MutableSet` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * @param $fn - The callback containing the operation to apply to the * current `MutableSet` "keys" and values. * * @return - a `MutableSet` containing the values after a user-specified * operation on the current `MutableSet`'s values is applied. */ public function mapWithKey<Tu as arraykey>( (function(arraykey, Tv)[_]: Tu) $fn, )[ctx $fn]: MutableSet<Tu>; /** * Returns a `MutableSet` containing the values of the current `MutableSet` * that meet a supplied condition applied to each value. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The callback containing the condition to apply to the * current `MutableSet` values. * * @return - a `MutableSet` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableSet<Tv>; /** * Returns a `MutableSet` containing the values of the current `MutableSet` * that meet a supplied condition applied to its "keys" and values. * * Since sets don't have keys, the callback uses the values as the keys * as well. * * Only values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * @param $fn - The callback containing the condition to apply to the * current `MutableSet` "keys" and values. * * @return - a `MutableSet` containing the values after a user-specified * condition is applied to the values of the current `MutableSet`. */ public function filterWithKey( (function(arraykey, Tv)[_]: bool) $fn, )[ctx $fn]: MutableSet<Tv>; /** * Returns a `MutableSet` where each value is a `Pair` that combines the * value of the current `MutableSet` and the provided `Traversable`. * * If the number of values of the current `ConstMap` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * Note that some implementations of sets only support certain types of keys * (e.g., only `int` or `string` values allowed). In that case, this method * could thrown an exception since a `Pair` wouldn't be supported/ * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `MutableSet`. * * @return - The `MutableSet` that combines the values of the current * `MutableSet` with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: MutableSet<nothing>; /** * Returns a `MutableSet` containing the first `n` values of the current * `MutableSet`. * * The returned `MutableSet` will always be a proper subset of the current * `MutableSet`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the `MutableSet`. * * @return - A `MutableSet` that is a proper subset of the current * `MutableSet` up to `n` elements. */ public function take(int $n)[]: MutableSet<Tv>; /** * Returns a `MutableSet` containing the values of the current `MutableSet` * up to but not including the first value that produces `false` when passed * to the specified callback. * * The returned `MutableSet` will always be a proper subset of the current * `MutableSet`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - A `MutableSet` that is a proper subset of the current * `MutableSet` up until the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableSet<Tv>; /** * Returns a `MutableSet` containing the values after the `n`-th element of * the current `MutableSet`. * * The returned `MutableSet` will always be a proper subset of the current * `MutableSet`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `MutableSet`. * * @return - A `MutableSet` that is a proper subset of the current * `MutableSet` containing values after the specified `n`-th * element. */ public function skip(int $n)[]: MutableSet<Tv>; /** * Returns a `MutableSet` containing the values of the current `MutableSet` * starting after and including the first value that produces `true` when * passed to the specified callback. * * The returned `MutableSet` will always be a proper subset of the current * `MutableSet`. * * @param $fn - The callback used to determine the starting element for the * `MutableSet`. * * @return - A `MutableSet` that is a proper subset of the current * `MutableSet` starting after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: MutableSet<Tv>; /** * Returns a subset of the current `MutableSet` starting from a given key up * to, but not including, the element at the provided length from the * starting key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `MutableSet` will always be a proper subset of the current * `MutableSet`. * * @param $start - The starting value in the current `MutableSet` for the * returned `MutableSet`. * @param $len - The length of the returned `MutableSet`. * * @return - A `MutableSet` that is a proper subset of the current * `MutableSet` starting at `$start` up to but not including the * element `$start + $len`. */ public function slice(int $start, int $len)[]: MutableSet<Tv>; /** * Returns a `MutableVector` that is the concatenation of the values of the * current `MutableSet` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `MutableSet` to produce the returned `MutableVector`. * * @param $traversable - The `Traversable` to concatenate to the current * `MutableSet`. * * @return - The concatenated `MutableVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: MutableVector<Tu>; /** * Returns the first value in the current `MutableSet`. * * @return - The first value in the current `MutableSet`, or `null` if the * `MutableSet` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first "key" in the current `MutableSet`. * * Since sets do not have keys, it returns the first value. * * This method is interchangeable with `firstValue()`. * * @return - The first value in the current `MutableSet`, or `null` if the * `MutableSet` is empty. */ public readonly function firstKey()[]: ?arraykey; /** * Returns the last value in the current `MutableSet`. * * @return - The last value in the current `MutableSet`, or `null` if the * current `MutableSet` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last "key" in the current `MutableSet`. * * Since sets do not have keys, it returns the last value. * * This method is interchangeable with `lastValue()`. * * @return - The last value in the current `MutableSet`, or `null` if the * current `MutableSet` is empty. */ public readonly function lastKey()[]: ?arraykey; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<Tv, Tv>; } } // namespace
HTML Help Workshop
hhvm/hphp/hack/hhi/collections/Map.hhi
<?hh /** * Copyright (c) 2014, 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. * */ <<file: __EnableUnstableFeatures('readonly')>> /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * `Map` is an ordered dictionary-style collection. HHVM provides a native * implementation for this class. The PHP class definition below is not * actually used at run time; it is simply provided for the typechecker and for * developer reference. * * Like all objects in PHP, `Map`s have reference-like semantics. When a caller * passes a `Map` to a callee, the callee can modify the `Map` and the caller * will see the changes. `Map`s do not have "copy-on-write" semantics. * * `Map`s preserve insertion order of key/value pairs. When iterating over a * `Map`, the key/value pairs appear in the order they were inserted. Also, * `Map`s do not automagically convert integer-like `string` keys (ex. `"123"`) * into integer keys. * * `Map`s only support `int` keys and `string` keys. If a key of a different * type is used, an exception will be thrown. * * `Map`s support `$m[$k]` style syntax for getting and setting values by key. * `Map`s also support `isset($m[$k])` and `empty($m[$k])` syntax, and they * provide similar semantics as arrays. Adding an element with square bracket * syntax `[]` is supported either by providing a key between the brackets or * a `Pair` on the right-hand side. e.g., * `$m[$k] = $v` is supported * `$m[] = Pair {$k, $v}` is supported * `$m[] = $v` is not supported. * * `Map`s do not support iterating while new keys are being added or elements * are being removed. When a new key is added or an element is removed, all * iterators that point to the `Map` shall be considered invalid. * * @guide /hack/collections/introduction * @guide /hack/collections/classes */ final class Map<Tk as arraykey, Tv> implements \MutableMap<Tk, Tv> { /** * Creates a `Map` from the given `KeyedTraversable`, or an empty `Map` if * `null` is passed. * * @param $it - any `Traversable` object from which to create a `Map` * (e.g., `array`). If `null`, then an empty `Map` is created. */ public function __construct(?KeyedTraversable<Tk, Tv> $it)[]; /** * Returns an `array` containing the values from the current `Map`. * * @return - an integer-indexed `array` containing the values from the * current `Map`. */ public function toValuesArray()[]: varray<Tv>; /** * Returns an `array` whose values are the keys of the current `Map`. * * @return - an integer-indexed `array` containing the keys from the current * `Map`. */ public function toKeysArray()[]: varray<Tk>; /** * Returns a `Vector` with the values of the current `Map`. * * @return - a `Vector` that contains the values of the current `Map`. */ public function toVector()[]: Vector<Tv>; /** * Returns an immutable vector (`ImmVector`) with the values of the current * `Map`. * * @return - an `ImmVector` that is an immutable copy of the current `Map`. */ public function toImmVector()[]: ImmVector<Tv>; /** * Returns a deep copy of the current `Map`. * * @return - a `Map` that is a deep copy of the current `Map`. */ public function toMap()[]: Map<Tk, Tv>; /** * Returns a deep, immutable copy (`ImmMap`) of the current `Map`. * * @return - an `ImmMap` that is a copy of this `Map`. */ public function toImmMap()[]: ImmMap<Tk, Tv>; /** * Returns a `Set` based on the values of the current `Map`. * * @return - a `Set` with the current values of the current `Map`. */ public function toSet()[]: Set<Tv> where Tv as arraykey; /** * Returns an immutable set (`ImmSet`) based on the values of the current * `Map`. * * @return - an `ImmSet` with the current values of the current `Map`. */ public function toImmSet()[]: ImmSet<Tv> where Tv as arraykey; /** * Returns a deep, immutable copy (`ImmMap`) of this `Map`. * * This method is interchangeable with `toImmMap()`. * * @return - an `ImmMap` that is a deep copy of this `Map`. */ public function immutable()[]: ImmMap<Tk, Tv>; /** * Returns a lazy, access elements only when needed view of the current * `Map`. * * Normally, memory is allocated for all of the elements of the `Map`. With * a lazy view, memory is allocated for an element only when needed or used * in a calculation like in `map()` or `filter()`. * * @return - a `KeyedIterable` representing the lazy view into the current * `Map`. * * @guide /hack/collections/examples */ public function lazy()[]: KeyedIterable<Tk, Tv>; /** * Returns a `Vector` containing the values of the current `Map`. * * This method is interchangeable with `toVector()`. * * @return - a `Vector` containing the values of the current `Map`. */ public function values()[]: Vector<Tv>; /** * Returns a `Vector` containing the keys of the current `Map`. * * @return - a `Vector` containing the keys of the current `Map`. */ public readonly function keys()[]: Vector<Tk>; /** * Returns a `Map` after an operation has been applied to each value in the * current `Map`. * * Every value in the current `Map` is affected by a call to `map()`, unlike * `filter()` where only values that meet a certain criteria are affected. * * The keys will remain unchanged from the current `Map` to the returned * `Map`. * * @param $fn - The callback containing the operation to apply to the * current `Map` values. * * @return - a `Map` containing key/value pairs after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu>((function(Tv)[_]: Tu) $fn)[ctx $fn]: Map<Tk, Tu>; /** * Returns a `Map` after an operation has been applied to each key and * value in the current `Map`. * * Every key and value in the current `Map` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * The keys will remain unchanged from the current `Map` to the returned * `Map`. The keys are only used to help in the mapping operation. * * @param $fn - The callback containing the operation to apply to the * current `Map` keys and values. * * @return - a `Map` containing the values after a user-specified operation * on the current `Map`'s keys and values is applied. */ public function mapWithKey<Tu>( (function(Tk, Tv)[_]: Tu) $fn, )[ctx $fn]: Map<Tk, Tu>; /** * Returns a `Map` containing the values of the current `Map` that meet * a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * The keys associated with the current `Map` remain unchanged in the returned * `Map`. * * @param $fn - The callback containing the condition to apply to the * current `Map` values. * * @return - a `Map` containing the values after a user-specified condition * is applied. * * @guide /hack/collections/examples */ public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: Map<Tk, Tv>; /** * Returns a `Map` containing the values of the current `Map` that meet * a supplied condition applied to its keys and values. * * Only keys and values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * The keys associated with the current `Map` remain unchanged in the * returned `Map`; the keys will be used in the filtering process only. * * @param $fn - The callback containing the condition to apply to the * current `Map` keys and values. * * @return - a `Map` containing the values after a user-specified condition * is applied to the keys and values of the current `Map`. * */ public function filterWithKey( (function(Tk, Tv)[_]: bool) $fn, )[ctx $fn]: Map<Tk, Tv>; /** * Returns a `Map` where each value is a `Pair` that combines the value * of the current `Map` and the provided `Traversable`. * * If the number of values of the current `Map` are not equal to the number * of elements in the `Traversable`, then only the combined elements up to * and including the final element of the one with the least number of * elements is included. * * The keys associated with the current `Map` remain unchanged in the * returned `Map`. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `Map`. * * @return - The `Map` that combines the values of the current `Map` with * the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: Map<Tk, Pair<Tv, Tu>>; /** * Returns a `Map` containing the first `n` key/values of the current `Map`. * * The returned `Map` will always be a proper subset of the current `Map`. * * `n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the `Map`. * * @return - A `Map` that is a proper subset of this `Map` up to `n` elements. */ public function take(int $n)[]: Map<Tk, Tv>; /** * Returns a `Map` containing the keys and values of the current `Map` up to * but not including the first value that produces `false` when passed to the * specified callback. * * The returned `Map` will always be a proper subset of the current `Map`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - A `Map` that is a proper subset of the current `Map` up until * the callback returns `false`. */ public function takeWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: Map<Tk, Tv>; /** * Returns a `Map` containing the values after the `n`-th element of the * current `Map`. * * The returned `Map` will always be a proper subset of the current `Map`. * * `n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `Map`. * * @return - A `Map` that is a proper subset of the current `Map` containing * values after the specified `n`-th element. */ public function skip(int $n)[]: Map<Tk, Tv>; /** * Returns a `Map` containing the values of the current `Map` starting after * and including the first value that produces `true` when passed to the * specified callback. * * The returned `Map` will always be a proper subset of this `Map`. * * @param $fn - The callback used to determine the starting element for the * current `Map`. * * @return - A `Map` that is a proper subset of the current `Map` starting * after the callback returns `true`. */ public function skipWhile( (function(Tv)[_]: bool) $fn, )[ctx $fn]: Map<Tk, Tv>; /** * Returns a subset of the current `Map` starting from a given key location * up to, but not including, the element at the provided length from the * starting key location. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * keys and values at key location 0 and 1. * * The returned `Map` will always be a proper subset of the current `Map`. * * @param $start - The starting key location of the current `Map` for the * returned `Map`. * @param $len - The length of the returned `Map`. * * @return - A `Map` that is a proper subset of the current `Map` starting at * `$start` up to but not including the element `$start + $len`. */ public function slice(int $start, int $len)[]: Map<Tk, Tv>; /** * Returns a `Vector` that is the concatenation of the values of the current * `Map` and the values of the provided `Traversable`. * * The provided `Traversable` is concatenated to the end of the current `Map` * to produce the returned `Vector`. * * @param $traversable - The `Traversable` to concatenate to the current * `Map`. * * @return - The integer-indexed concatenated `Vector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: Vector<Tu>; /** * Returns the first value in the current `Map`. * * @return - The first value in the current `Map`, or `null` if the `Map` is * empty. */ public function firstValue()[]: ?Tv; /** * Returns the first key in the current `Map`. * * @return - The first key in the current `Map`, or `null` if the `Map` is * empty. */ public readonly function firstKey()[]: ?Tk; /** * Returns the last value in the current `Map`. * * @return - The last value in the current `Map`, or `null` if the `Map` is * empty. */ public function lastValue()[]: ?Tv; /** * Returns the last key in the current `Map`. * * @return - The last key in the current `Map`, or `null` if the `Map` is * empty. */ public readonly function lastKey()[]: ?Tk; /** * Checks if the current `Map` is empty. * * @return - `true` if the current `Map` is empty; `false` otherwise. */ public readonly function isEmpty()[]: bool; /** * Provides the number of elements in the current `Map`. * * @return - The number of elements in the current `Map`. */ public readonly function count()[]: int; /** * Returns the value at the specified key in the current `Map`. * * If the key is not present, an exception is thrown. If you don't want an * exception to be thrown, use `get()` instead. * * `$v = $map->at($k)` is equivalent to `$v = $map[$k]`. * * @param $k - the key from which to retrieve the value. * * @return - The value at the specified key; or an exception if the key does * not exist. */ public function at(Tk $k)[]: Tv; /** * Returns the value at the specified key in the current `Map`. * * If the key is not present, `null` is returned. If you would rather have an * exception thrown when a key is not present, then use `at()`. * * @param $k - the key from which to retrieve the value. * * @return - The value at the specified key; or `null` if the key does not * exist. */ public function get(Tk $k)[]: ?Tv; /** * Stores a value into the current `Map` with the specified key, overwriting * the previous value associated with the key. * * This method is equivalent to `Map::add()`. If the key to set does not exist, * it is created. This is inconsistent with, for example, `Vector::set()` * where if the key is not found, an exception is thrown. * * `$map->set($k,$v)` is equivalent to `$map[$k] = $v` (except that `set()` * returns the current `Map`). * * Future changes made to the current `Map` ARE reflected in the returned * `Map`, and vice-versa. * * @param $k - The key to which we will set the value. * @param $v - The value to set. * * @return - Returns itself. */ public function set(Tk $k, Tv $v)[write_props]: Map<Tk, Tv>; /** * For every element in the provided `Traversable`, stores a value into the * current `Map` associated with each key, overwriting the previous value * associated with the key. * * This method is equivalent to `Map::addAll()`. If a key to set does not * exist in the Map that does exist in the `Traversable`, it is created. This * is inconsistent with, for example, the method `Vector::setAll()` where if * a key is not found, an exception is thrown. * * Future changes made to the current `Map` ARE reflected in the returned * `Map`, and vice-versa. * * @param $k - The `Traversable` with the new values to set. If `null` is * provided, no changes are made. * * @return - Returns itself. */ public function setAll( ?KeyedTraversable<Tk, Tv> $it, )[write_props]: Map<Tk, Tv>; /** * Remove all the elements from the current `Map`. * * Future changes made to the current `Map` ARE reflected in the returned * `Map`, and vice-versa. * * @return - Returns itself. */ public function clear()[write_props]: Map<Tk, Tv>; /** * Determines if the specified key is in the current `Map`. * * This function is interchangeable with `containsKey()`. * * @param $k - The key to check. * * @return - `true` if the specified key is present in the current `Map`; * returns `false` otherwise. * * @guide /hack/generics/constraints */ public readonly function contains(mixed $k)[]: bool; /** * Determines if the specified key is in the current `Map`. * * This function is interchangeable with `contains()`. * * @param $k - The key to check. * * @return - `true` if the specified key is present in the current `Map`; * returns `false` otherwise. * * @guide /hack/generics/constraints */ public readonly function containsKey(mixed $k)[]: bool; /** * Add a key/value pair to the end of the current `Map`. * * This method is equivalent to `Map::set()`. If the key in the `Pair` * exists in the `Map`, the value associated with it is overwritten. * * `$map->add($p)` is equivalent to both `$map[$k] = $v` and * `$map[] = Pair {$k, $v}` (except that `add()` returns the `Map`). * * Future changes made to the current `Map` ARE reflected in the returned * `Map`, and vice-versa. * * @param $p - The key/value Pair to add to the current `Map`. * * @return - Returns itself. */ public function add(Pair<Tk, Tv> $p)[write_props]: Map<Tk, Tv>; /** * For every element in the provided `Traversable`, add a key/value pair into * the current `Map`. * * This method is equivalent to `Map::setAll()`. If a key in the `Traversable` * exists in the `Map`, then the value associated with that key in the `Map` * is overwritten. * * Future changes made to the current `Map` ARE reflected in the returned * `Map`, and vice-versa. * * @param $k - The `Traversable` with the new key/value `Pair` to set. If * `null` is provided, no changes are made. * * @return - Returns itself. */ public function addAll( ?Traversable<Pair<Tk, Tv>> $it, )[write_props]: Map<Tk, Tv>; /** * Reserves enough memory to accommodate a given number of elements. * * Reserves enough memory for `sz` elements. If `sz` is less than or * equal to the current capacity of this `Map`, this method does nothing. * * @param $sz - The pre-determined size you want for the current `Map`. */ public function reserve(int $sz)[]: void; /** * Removes the specified key (and associated value) from the current `Map`. * * This method is interchangeable with `removeKey()`. * * Future changes made to the current `Map` ARE reflected in the returned * `Map`, and vice-versa. * * @param $k - The key to remove. * * @return - Returns itself. */ public function remove(Tk $k)[]: Map<Tk, Tv>; /** * Removes the specified key (and associated value) from the current `Map`. * * This method is interchangeable with `remove()`. * * Future changes made to the current `Map` ARE reflected in the returned * `Map`, and vice-versa. * * @param $k - The key to remove. * * @return - Returns itself. */ public function removeKey(Tk $k)[]: Map<Tk, Tv>; /** * Returns a new `Map` with the keys that are in the current `Map`, but not * in the provided `KeyedTraversable`. * * @param $traversable - The `KeyedTraversable` on which to compare the keys. * * @return - A `Map` containing the keys (and associated values) of the * current `Map` that are not in the `KeyedTraversable`. */ public function differenceByKey( KeyedTraversable<Tk, Tv> $traversable, )[]: Map<Tk, Tv>; /** * Returns an iterator that points to beginning of the current `Map`. * * @return - A `KeyedIterator` that allows you to traverse the current `Map`. */ public function getIterator()[]: KeyedIterator<Tk, Tv>; /** * Returns a `Map` containing the key/value pairs from the specified `array`. * * This function is deprecated. Use `new `Map`($arr)` instead. * * @param $arr - The `array` to convert to a `Map`. * * @return - A `Map` with the key/value pairs from the provided `array`. */ <<__Deprecated('Use `new Map($arr)` instead.')>> public static function fromArray(darray<Tk, Tv> $arr): Map<Tk, Tv>; /** * Creates a `Map` from the given `Traversable`, or an empty `Map` if * `null` is passed. * * This is the static method version of the `Map::__construct()` constructor. * * @param $items - any `Traversable` object from which to create a `Map` * (e.g., `array`). If `null`, then an empty `Map` is created. * * @return - A `Map` with the key/value pairs from the `Traversable`; or an * empty `Map` if the `Traversable` is `null`. */ public static function fromItems( ?Traversable<Pair<Tk, Tv>> $items, )[]: Map<Tk, Tv>; /** * Returns the `string` version of the current `Map`, which is `"Map"`. * * @return - The `string` `"Map"`. */ public function __toString()[]: string; /** * Returns an `Iterable` view of the current `Map`. * * The `Iterable` returned is one that produces the key/values from the * current `Map`. * * @return - The `Iterable` view of the current `Map`. */ public function items()[]: Iterable<Pair<Tk, Tv>>; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<Tk, Tv>; } } // namespace HH namespace { /** * @internal * * Methods and functions should take and return the KeyedIterator interface. */ class MapIterator<Tk, +Tv> implements HH\KeyedIterator<Tk, Tv> { public function __construct()[]; public function current()[]: Tv; public function key()[]: Tk; public function valid()[]: bool; public function next()[write_props]: void; public function rewind()[write_props]: void; } } // namespace
HTML Help Workshop
hhvm/hphp/hack/hhi/collections/Pair.hhi
<?hh /** * Copyright (c) 2014, 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. * */ <<file: __EnableUnstableFeatures('readonly', 'union_intersection_type_hints')>> /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * `Pair` is an immutable, fixed-size collection with exactly two elements * (possibly of different types). HHVM provides a native implementation for * this class. The Hack class definition below is not actually used at run * time; it is simply provided for the typechecker and for developer reference. * * Like all objects in PHP, `Pair`s have reference-like semantics. The elements * of a `Pair` cannot be mutated (i.e. you can't assign to the elements of a * `Pair`) though `Pair`s may contain mutable objects. * * `Pair`s only support integer keys. If a non-integer key is used, an * exception will be thrown. * * `Pair`s support `$m[$k]` style syntax for getting values by key. `Pair`s * also support `isset($m[$k])` and `empty($m[$k])` syntax, and they provide * similar semantics as arrays. * * `Pair` keys are always 0 and 1, respectively. * * You may notice that many methods affecting the instace of `Pair` return an * `ImmVector` -- `Pair`s are essentially backed by 2-element `ImmVector`s. * * @guide /hack/collections/introduction * @guide /hack/collections/classes */ final class Pair<+Tv1, +Tv2> implements \ConstVector<(Tv1 | Tv2)> { /** * @internal * * Pairs must be constructed with "Pair {$first, $second}". */ private function __construct()[]; /** * Returns an `array` containing the values from the current `Pair`. * * This method is interchangeable with `toArray()`. * * @return - an `array` containing the values from the current `Pair`. */ public function toValuesArray()[]: varray<(Tv1 | Tv2)>; /** * Returns an `array` whose values are the keys from the current `Pair`. * * @return - an `array` with the integer keys from the current `Pair`. */ public readonly function toKeysArray()[]: varray<int>; /** * Returns a `Vector` containing the elements of the current `Pair`. * * The returned `Vector` will, of course, be mutable. * * @return - a `Vector` with the elements of the current `Pair`. */ public function toVector()[]: Vector<mixed>; /** * Returns an immutable vector (`ImmVector`) containing the elements of the * current `Pair`. * * @return - an `ImmVector` with the elements of the current `Pair`. */ public function toImmVector()[]: ImmVector<(Tv1 | Tv2)>; /** * Returns an integer-keyed `Map` based on the elements of the current `Pair`. * * The keys are 0 and 1. * * @return - an integer-keyed `Map` with the values of the current `Pair`. */ public function toMap()[]: Map<int, mixed>; /** * Returns an immutable, integer-keyed map (`ImmMap`) based on the elements of * the current `Pair`. * * The keys are 0 and 1. * * @return - an `ImmMap` with the values of the current `Pair`. */ public function toImmMap()[]: ImmMap<int, (Tv1 | Tv2)>; /** * Returns a `Set` with the values of the current `Pair`. * * @return - a `Set` with the current values of the current `Pair`. */ public function toSet()[]: Set<arraykey> where Tv1 as arraykey, Tv2 as arraykey; /** * Returns an immutable set (`ImmSet`) with the values of the current `Pair`. * * @return - an `ImmSet` with the current values of the current `Pair`. */ public function toImmSet()[]: ImmSet<(Tv1 | Tv2)> where Tv1 as arraykey, Tv2 as arraykey; /** * Returns a lazy, access elements only when needed view of the current * `Pair`. * * Normally, memory is allocated for all of the elements of the `Pair`. * With a lazy view, memory is allocated for an element only when needed or * used in a calculation like in `map()` or `filter()`. * * That said, `Pair`s only have two elements. So the performance impact on * a `Pair` will be not be noticeable in the real world. * * @return - an integer-keyed KeyedIterable representing the lazy view into * the current `Pair`. * * @guide /hack/collections/examples */ public function lazy()[]: KeyedIterable<int, (Tv1 | Tv2)>; /** * Returns an `ImmVector` containing the values of the current `Pair`. * * This method is interchangeable with `toImmVector()`. * * @return - an `ImmVector` containing the values of the current `Pair`. */ public function values()[]: ImmVector<(Tv1 | Tv2)>; /** * Returns an `ImmVector` with the values being the keys of the current * `Pair`. * * This method will return an `ImmVector` with keys 0 and 1, and values 0 and * 1, since the keys of a `Pair` are 0 and 1. * * @return - an `ImmVector` containing the integer keys of the current * `Pair` as values. */ public readonly function keys()[]: ImmVector<int>; /** * Returns an `ImmVector` containing the values after an operation has been * applied to each value in the current `Pair`. * * Every value in the current Pair is affected by a call to `map()`, unlike * `filter()` where only values that meet a certain criteria are affected. * * @param $fn - The callback containing the operation to apply to the * current `Pair` values. * * @return - an `ImmVector` containing the values after a user-specified * operation is applied. * * @guide /hack/collections/examples */ public function map<Tu>( (function((Tv1 | Tv2))[_]: Tu) $fn, )[ctx $fn]: ImmVector<Tu>; /** * Returns an `ImmVector` containing the values after an operation has been * applied to each key and value in the current `Pair`. * * Every key and value in the current `Pair` is affected by a call to * `mapWithKey()`, unlike `filterWithKey()` where only values that meet a * certain criteria are affected. * * @param $fn - The $allback containing the operation to apply to the * current `Pair` keys and values. * * @return - an `ImmVector` containing the values after a user-specified * operation on the current `Pair`'s keys and values is applied. */ public function mapWithKey<Tu>( (function(int, (Tv1 | Tv2))[_]: Tu) $fn, )[ctx $fn]: ImmVector<Tu>; /** * Returns a `ImmVector` containing the values of the current `Pair` that * meet a supplied condition. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The callback containing the condition to apply to the * current `Pair` values. * * @return - an `ImmVector` containing the values after a user-specified * condition is applied. * * @guide /hack/collections/examples */ public function filter( (function((Tv1 | Tv2))[_]: bool) $fn, )[ctx $fn]: ImmVector<(Tv1 | Tv2)>; /** * Returns an `ImmVector` containing the values of the current `Pair` that * meet a supplied condition applied to its keys and values. * * Only keys and values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * @param $fn - The callback containing the condition to apply to the * current `Pair` keys and values. * * @return - an `ImmVector` containing the values after a user-specified * condition is applied to the keys and values of the current * `Pair`. */ public function filterWithKey( (function(int, (Tv1 | Tv2))[_]: bool) $fn, )[ctx $fn]: ImmVector<(Tv1 | Tv2)>; /** * Returns an `ImmVector` where each element is a `Pair` that combines each * element of the current `Pair` and the provided `Traversable`. * * If the number of elements of the current `Pair` are not equal to the * number of elements in the `Traversable`, then only the combined elements * up to and including the final element of the one with the least number of * elements is included. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `Pair`. * * @return - The `ImmVector` that combines the values of the current `Pair` * with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: ImmVector<Pair<(Tv1 | Tv2), Tu>>; /** * Returns an `ImmVector` containing the first `n` values of the current * `Pair`. * * `n` is 1-based. So the first element is 1, the second 2. There is no * element 3 in a `Pair`, but if you specify an element greater than 2, it * will just return all elements in the `Pair`. * * @param $n - The last element that will be included in the current `Pair`. * * @return - An `ImmVector` containing the first `n` values of the current * `Pair`. */ public function take(int $n)[]: ImmVector<(Tv1 | Tv2)>; /** * Returns an `ImmVector` containing the values of the current `Pair` up to * but not including the first value that produces `false` when passed to the * specified callback. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - An `ImmVector` that contains the values of the current `Pair` up * until the callback returns `false`. */ public function takeWhile( (function((Tv1 | Tv2))[_]: bool) $fn, )[ctx $fn]: ImmVector<(Tv1 | Tv2)>; /** * Returns an `ImmVector` containing the values after the `n`-th element of * the current `Pair`. * * `n` is 1-based. So the first element is 1, the second 2, etc. There is no * element 3 in a `Pair`, but if you specify an element greater than or equal * to 2, it will just return empty. If you specify 0, it will return all the * elements in the `Pair`. * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `ImmVector`. * * @return - An `ImmVector` that contains values after the specified `n`-th * element in the current `Pair`. */ public function skip(int $n)[]: ImmVector<(Tv1 | Tv2)>; /** * Returns an `ImmVector` containing the values of the current `Pair` starting * after and including the first value that produces `true` when passed to * the specified callback. * * @param $fn - The callback used to determine the starting element for the * `ImmVector`. * * @return - An `ImmVector` that contains the values of the current `Pair` * starting after the callback returns `true`. */ public function skipWhile( (function((Tv1 | Tv2))[_]: bool) $fn, )[ctx $fn]: ImmVector<(Tv1 | Tv2)>; /** * Returns a subset of the current `Pair` starting from a given key up to, * but not including, the element at the provided length from the starting * key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1 (all of the current `Pair` elements). * * @param $start - The starting key of the current `Pair` to begin the * returned `ImmVector`. * @param $len - The length of the returned `ImmVector`. * * @return - An `ImmVector` with values from the current `Pair` starting at * `$start` up to but not including the element `$start + $len`. */ public function slice(int $start, int $len)[]: ImmVector<(Tv1 | Tv2)>; /** * Returns an `ImmVector` that is the concatenation of the values of the * current `Pair` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `Pair` to produce the returned `ImmVector`. * * @param $traversable - The `Traversable` to concatenate to the current * `Pair`. * * @return - The concatenated `ImmVector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv1 super Tv2>( Traversable<Tu> $traversable, )[]: ImmVector<Tu>; /** * Returns the first value in the current `Pair`. * * @return - The first value in the current `Pair`. */ public function firstValue()[]: Tv1; /** * Returns the first key in the current `Pair`. * * The return will always be 0 since a `Pair` only has two keys, 0 and 1. * * @return - 0 */ public readonly function firstKey()[]: int; /** * Returns the last value in the current `Pair`. * * @return - The last value in the current `Pair`. */ public function lastValue()[]: Tv2; /** * Returns the last key in the current `Pair`. * * The return will always be 1 since a `Pair` only has two keys, 0 and 1. * * @return - 1 */ public readonly function lastKey()[]: int; /** * Returns the index of the first element that matches the search value. * * If no element matches the search value, this function returns -1. * * @param $search_value - The value that will be search for in the current * `Pair`. * * @return - The key (index) where that value is found; -1 if it is not found. * * @guide /hack/generics/constraints */ public readonly function linearSearch(mixed $search_value)[]: int; /** * Returns `false`; a `Pair` cannot be empty. * * @return - `false` */ public readonly function isEmpty()[]: bool; /** * Returns 2; a `Pair` always has two values. * * @return - 2 */ public readonly function count()[]: int; /** * Returns an `Iterable` view of the current `Pair`. * * The `Iterable` returned is one that produces the values from the current * `Pair`. * * @return - The `Iterable` view of the current `Pair`. */ public function items()[]: Iterable<(Tv1 | Tv2)>; /** * Returns the value at the specified key in the current `Pair`. * * If the key is not present, an exception is thrown. This essentially means * if you specify a key other than 0 or 1, you will get an exception. If you * don't want an exception to be thrown, use `get()` instead. * * $v = $p->at($k)" is semantically equivalent to `$v = $p[$k]`. * * @param $k - the key from which to retrieve the value. * * @return - The value at the specified key; or an exception if the key does * not exist. */ public function at(int $k)[]: (Tv1 | Tv2); /** * Returns the value at the specified key in the current `Pair`. * * If the key is not present, `null` is returned. If you would rather have an * exception thrown when a key is not present, then use `at()`. * * @param $k - the key from which to retrieve the value. * * @return - The value at the specified key; or `null` if the key does not * exist. */ public function get(int $k)[]: ?(Tv1 | Tv2); /** * Checks whether a provided key exists in the current `Pair`. * * This will only return `true` for provided keys of 0 and 1 since those are * the only two keys that can exist in a `Pair`. * * @param $k - the key to check existence for in the `Pair`. * * @return - `true` if the provided key exists in the `Pair`; `false` * otherwise. This will only return `true` if the provided key is * 0 or 1. */ public readonly function containsKey(mixed $k)[]: bool; /** * Returns an iterator that points to beginning of the current `Pair`. * * @return - A `KeyedIterator` that allows you to traverse the current `Pair`. */ public function getIterator()[]: KeyedIterator<int, (Tv1 | Tv2)>; /** * Returns the `string` version of the current `Pair`, which is `"Pair"`. * * @return - The `string` "Pair". */ public function __toString()[]: string; public function toVArray()[]: varray<(Tv1 | Tv2)>; public function toDArray()[]: darray<int, (Tv1 | Tv2)>; } } // namespace HH namespace { /** * @internal * * Methods and functions should take and return the KeyedIterator interface. */ class PairIterator implements HH\KeyedIterator<int, mixed> { public function __construct()[]; public function current()[]: mixed; public function key()[]: int; public function valid()[]: bool; public function next()[]: void; public function rewind()[]: void; } } // namespace
HTML Help Workshop
hhvm/hphp/hack/hhi/collections/Set.hhi
<?hh /** * Copyright (c) 2014, 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. * */ <<file: __EnableUnstableFeatures('readonly')>> /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * `Set` is an ordered set-style collection. HHVM provides a native * implementation for this class. The PHP class definition below is not * actually used at run time; it is simply provided for the typechecker and * for developer reference. * * Like all objects in PHP, `Set`s have reference-like semantics. When a caller * passes a `Set` to a callee, the callee can modify the `Set` and the caller * will see the changes. `Set`s do not have "copy-on-write" semantics. * * `Set`s preserve insertion order of the elements. When iterating over a * `Set`, the elements appear in the order they were inserted. Also, `Set`s do * not automagically convert integer-like strings (ex. "123") into integers. * * `Set`s only support `int` values and `string` values. If a value of a * different type is used, an exception will be thrown. * * In general, Sets do not support `$c[$k]` style syntax. Adding an element * using `$c[] = ..` syntax is supported. * * `Set` do not support iteration while elements are being added or removed. * When an element is added or removed, all iterators that point to the `Set` * shall be considered invalid. * * @guide /hack/collections/introduction * @guide /hack/collections/classes */ final class Set<Tv as arraykey> implements \MutableSet<Tv> { /** * Creates a `Set` from the given `Traversable`, or an empty `Set` if `null` * is passed. * * @param $it - any `Traversable` object from which to create the `Set` * (e.g., `array`). If `null`, then an empty `Set` is created. */ public function __construct(?Traversable<Tv> $it)[]; /** * Returns an `array` containing the values from the current `Set`. * * `Set`s don't have keys. So this method just returns the values. * * This method is interchangeable with `toValuesArray()`. * * @return - an integer-indexed `array` containing the values from the * current `Set`. */ public function toKeysArray()[]: varray<Tv>; /** * Returns an `array` containing the values from the current `Set`. * * This method is interchangeable with `toKeysArray()`. * * @return - an integer-indexed `array` containing the values from the * current `Set`. */ public function toValuesArray()[]: varray<Tv>; /** * Returns a `Vector` of the current `Set` values. * * @return - a `Vector` (integer-indexed) that contains the values of the * current `Set`. */ public function toVector()[]: Vector<Tv>; /** * Returns an immutable vector (`ImmVector`) with the values of the current * `Set`. * * @return - an `ImmVector` (integer-indexed) with the values of the current * `Set`. */ public function toImmVector()[]: ImmVector<Tv>; /** * Returns a `Map` based on the values of the current `Set`. * * Each key of the `Map` will be the same as its value. * * @return - a `Map` that that contains the values of the current `Set`, with * each key of the `Map` being the same as its value. */ public function toMap()[]: Map<arraykey, Tv>; /** * Returns an immutable map (`ImmMap`) based on the values of the current * `Set`. * * Each key of the `Map` will be the same as its value. * * @return - an `ImmMap` that that contains the values of the current `Set`, * with each key of the Map being the same as its value. */ public function toImmMap()[]: ImmMap<arraykey, Tv>; /** * Returns a deep copy of the current `Set`. * * @return - a `Set` that is a deep copy of the current `Set`. */ public function toSet()[]: Set<Tv>; /** * Returns an immutable (`ImmSet`), deep copy of the current `Set`. * * This method is interchangeable with `immutable()`. * * @return - an `ImmSet` that is a deep copy of the current `Set`. */ public function toImmSet()[]: ImmSet<Tv>; /** * Returns an immutable (`ImmSet`), deep copy of the current `Set`. * * This method is interchangeable with `toImmSet()`. * * @return - an `ImmSet` that is a deep copy of the current `Set`. */ public function immutable()[]: ImmSet<Tv>; /** * Returns a lazy, access elements only when needed view of the current * `Set`. * * Normally, memory is allocated for all of the elements of the `Set`. With * a lazy view, memory is allocated for an element only when needed or used * in a calculation like in `map()` or `filter()`. * * @return - an `KeyedIterable` representing the lazy view into the current * `Set`, where the keys are the same as the values. * * @guide /hack/collections/examples */ public function lazy()[]: KeyedIterable<arraykey, Tv>; /** * Returns a `Vector` containing the values of the current `Set`. * * This method is interchangeable with `toVector()` and `keys()`. * * @return - a `Vector` (integer-indexed) containing the values of the * current `Set`. */ public function values()[]: Vector<Tv>; /** * Returns a `Vector` containing the values of the current `Set`. * * `Set`s don't have keys, so this will return the values. * * This method is interchangeable with `toVector()` and `values()`. * * @return - a `Vector` (integer-indexed) containing the values of the * current `Set`. */ public readonly function keys()[]: Vector<arraykey>; /** * Returns a `Set` containing the values after an operation has been applied * to each value in the current `Set`. * * Every value in the current `Set` is affected by a call to `map()`, unlike * `filter()` where only values that meet a certain criteria are affected. * * @param $fn - The callback containing the operation to apply to the * current `Set` values. * * @return - a `Set` containing the values after a user-specified operation * is applied. * * @guide /hack/collections/examples */ public function map<Tu as arraykey>( (function(Tv)[_]: Tu) $fn, )[ctx $fn]: Set<Tu>; /** * Returns a `Set` containing the values after an operation has been applied * to each "key" and value in the current `Set`. * * Since `Set`s don't have keys, the callback uses the values as the keys * as well. * * Every value in the current `Set` is affected by a call to `mapWithKey()`, * unlike `filterWithKey()` where only values that meet a certain criteria are * affected. * * @param $fn - The callback containing the operation to apply to the * current `Set` keys and values. * * @return - a `Set` containing the values after a user-specified operation * on the current `Set`'s values is applied. */ public function mapWithKey<Tu as arraykey>( (function(arraykey, Tv)[_]: Tu) $fn, )[ctx $fn]: Set<Tu>; /** * Returns a `Set` containing the values of the current `Set` that meet * a supplied condition applied to each value. * * Only values that meet a certain criteria are affected by a call to * `filter()`, while all values are affected by a call to `map()`. * * @param $fn - The callback containing the condition to apply to the * current `Set` values. * * @return - a `Set` containing the values after a user-specified condition * is applied. * * @guide /hack/collections/examples */ public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: Set<Tv>; /** * Returns a `Set` containing the values of the current `Set` that meet * a supplied condition applied to its "keys" and values. * * Since `Set`s don't have keys, the callback uses the values as the keys * as well. * * Only values that meet a certain criteria are affected by a call to * `filterWithKey()`, while all values are affected by a call to * `mapWithKey()`. * * @param $fn - The callback containing the condition to apply to the * current `Set` keys and values. * * @return - a `Set` containing the values after a user-specified condition * is applied to the values of the current `Set`. * */ public function filterWithKey( (function(arraykey, Tv)[_]: bool) $fn, )[ctx $fn]: Set<Tv>; /** * Alters the current `Set` so that it only contains the values that meet a * supplied condition on each value. * * This method is like `filter()`, but mutates the current `Set` too in * addition to returning the current `Set`. * * Future changes made to the current `Set` ARE reflected in the returned * `Set`, and vice-versa. * * @param $fn - The callback containing the condition to apply to the * current `Set` values. * * @return - Returns itself. */ public function retain( (function(Tv)[_]: bool) $fn, )[ctx $fn, write_props]: Set<Tv>; /** * Alters the current `Set` so that it only contains the values that meet a * supplied condition on its "keys" and values. * * `Set`s don't have keys, so the `Set` values are used as the key in the * callback. * * This method is like `filterWithKey()`, but mutates the current `Set` too * in addition to returning the current `Set`. * * Future changes made to the current `Set` ARE reflected in the returned * `Set`, and vice-versa. * * @param $fn - The callback containing the condition to apply to the * current `Set` values. * * @return - Returns itself. */ public function retainWithKey( (function(arraykey, Tv)[_]: bool) $fn, )[ctx $fn, write_props]: Set<Tv>; /** * Throws an exception unless the current `Set` or the `Traversable` is * empty. * * Since `Set`s only support integers or strings as values, we cannot have * a `Pair` as a `Set` value. So in order to avoid an * `InvalidArgumentException`, either the current `Set` or the `Traversable` * must be empty so that we actually return an empty `Set`. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `Set`. * * @return - The `Set` that combines the values of the current `Set` with * the provided `Traversable`; one of these must be empty or an * exception is thrown. */ public function zip<Tu>(Traversable<Tu> $traversable)[]: Set<nothing>; /** * Returns a `Set` containing the first `n` values of the current `Set`. * * The returned `Set` will always be a proper subset of the current `Set`. * * `n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the `Set`. * * @return - A `Set` that is a proper subset of the current `Set` up to `n` * elements. */ public function take(int $n)[]: Set<Tv>; /** * Returns a `Set` containing the values of the current `Set` up to but not * including the first value that produces `false` when passed to the * specified callback. * * The returned `Set` will always be a proper subset of the current `Set`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - A `Set` that is a proper subset of the current `Set` up until * the callback returns `false`. */ public function takeWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: Set<Tv>; /** * Returns a `Set` containing the values after the `n`-th element of the * current `Set`. * * The returned `Set` will always be a proper subset of the current `Set`. * * `n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be * the first one in the returned `Set`. * * @return - A `Set` that is a proper subset of the current `Set` containing * values after the specified `n`-th element. */ public function skip(int $n)[]: Set<Tv>; /** * Returns a `Set` containing the values of the current `Set` starting after * and including the first value that produces `true` when passed to the * specified callback. * * The returned `Set` will always be a proper subset of the current `Set`. * * @param $fn - The callback used to determine the starting element for the * `Set`. * * @return - A `Set` that is a proper subset of the current `Set` starting * after the callback returns `true`. */ public function skipWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: Set<Tv>; /** * Returns a subset of the current `Set` starting from a given key up to, but * not including, the element at the provided length from the starting key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at key 0 and 1. * * The returned `Set` will always be a proper subset of the current `Set`. * * @param $start - The starting value in the current `Set` for the returned * `Set`. * @param $len - The length of the returned `Set`. * * @return - A `Set` that is a proper subset of the current `Set` starting at * `$start` up to but not including the element `$start + $len`. */ public function slice(int $start, int $len)[]: Set<Tv>; /** * Returns a `Vector` that is the concatenation of the values of the current * `Set` and the values of the provided `Traversable`. * * The values of the provided `Traversable` is concatenated to the end of the * current `Set` to produce the returned `Vector`. * * @param $traversable - The `Traversable` to concatenate to the current * `Set`. * * @return - The concatenated `Vector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: Vector<Tu>; /** * Returns the first value in the current `Set`. * * @return - The first value in the current `Set`, or `null` if the `Set` is * empty. */ public readonly function firstValue()[]: ?Tv; /** * Returns the first "key" in the current `Set`. * * Since `Set`s do not have keys, it returns the first value. * * This method is interchangeable with `firstValue()`. * * @return - The first value in the current `Set`, or `null` if the `Set` is * empty. */ public readonly function firstKey()[]: ?arraykey; /** * Returns the last value in the current `Set`. * * @return - The last value in the current `Set`, or `null` if the current * `Set` is empty. */ public readonly function lastValue()[]: ?Tv; /** * Returns the last "key" in the current `Set`. * * Since `Set`s do not have keys, it returns the last value. * * This method is interchangeable with `lastValue()`. * * @return - The last value in the current `Set`, or `null` if the current * `Set` is empty. */ public readonly function lastKey()[]: ?arraykey; /** * Checks if the current `Set` is empty. * * @return - `true` if the current `Set` is empty; `false` otherwise. */ public readonly function isEmpty()[]: bool; /** * Provides the number of elements in the current `Set`. * * @return - The number of elements in the current `Set`. */ public readonly function count()[]: int; /** * Remove all the elements from the current `Set`. * * Future changes made to the current `Set` ARE reflected in the returned * `Set`, and vice-versa. * * @return - Returns itself. */ public function clear()[write_props]: Set<Tv>; /** * Determines if the specified value is in the current `Set`. * * @param $v - The value to check. * @return - `true` if the specified value is present in the current `Set`; * `false` otherwise. */ public readonly function contains(arraykey $v)[]: bool; /** * Add the value to the current `Set`. * * `$set->add($v)` is semantically equivalent to `$set[] = $v` (except that * `add()` returns the `Set`). * * Future changes made to the current `Set` ARE reflected in the returned * `Set`, and vice-versa. * * @param $v - The value to add to the current `Set` * * @return - Returns itself. */ public function add(Tv $v)[write_props]: Set<Tv>; /** * For every element in the provided `Traversable`, add the value into the * current `Set`. * * Future changes made to the original `Set` ARE reflected in the returned * `Set`, and vice-versa. * * @param $k - The `Traversable` with the new values to add. If `null` is * provided, no changes are made. * * @return - Returns itself. */ public function addAll(?Traversable<Tv> $it)[write_props]: Set<Tv>; /** * Adds the keys of the specified container to the current `Set` as new * values. * * Future changes made to the current `Set` ARE reflected in the returned * `Set`, and vice-versa. * * @param $container - The container with the new keys to add. * * @return - Returns itself. */ public function addAllKeysOf( ?KeyedContainer<Tv, mixed> $container, )[write_props]: Set<Tv>; /** * Reserves enough memory to accommodate a given number of elements. * * Reserves enough memory for `sz` elements. If `sz` is less than or equal * to the current capacity of this `Set`, this method does nothing. * * @param $sz - The pre-determined size you want for the current `Set`. */ public function reserve(int $sz)[]: void; /** * Removes the specified value from the current `Set`. * * Future changes made to the current `Set` ARE reflected in the returned * `Set`, and vice-versa. * * @param $v - The value to remove. * * @return - Returns itself. */ public function remove(Tv $v)[write_props]: Set<Tv>; /** * Removes the values in the current `Set` that are also in the `Traversable`. * * If a value in the `Traversable` doesn't exist in the current `Set`, that * value in the `Traversable` is ignored. * * Future changes made to the current `Set` ARE reflected in the returned * `Set`, and vice-versa. * * @param $other - The `Traversable` containing values that will be removed * from the `Set`. * * @return - Returns itself. */ public function removeAll(Traversable<Tv> $other)[write_props]: Set<Tv>; /** * Returns an iterator that points to beginning of the current `Set`. * * @return - A `KeyedIterator` that allows you to traverse the current `Set`. */ public function getIterator()[]: KeyedIterator<arraykey, Tv>; /** * Returns a `Set` containing the values from the specified `array`. * * This function is deprecated. Use `new Set ($arr)` instead. * * @param $arr - The `array` to convert to a `Set`. * * @return - A `Set` with the values from the provided `array`. */ <<__Deprecated('Use `new Set($arr)` instead.')>> public static function fromArray(darray<arraykey, Tv> $arr): Set<Tv>; /** * Returns a `Set` containing all the values from the specified `array`(s). * * @param ...$argv - The `array`s to convert to a `Set`. * * @return - A `Set` with the values from the passed `array`(s). */ public static function fromArrays( \HH\FIXME\MISSING_PARAM_TYPE ...$argv )[]: Set<Tv>; /** * Creates a `Set` from the given `Traversable`, or an empty `Set` if `null` * is passed. * * This is the static method version of the `Set::__construct()` constructor. * * @param $items - any `Traversable` object from which to create a `Set` * (e.g., `array`). If `null`, then an empty `Set` is created. * * @return - A `Set` with the values from the `Traversable`; or an empty `Set` * if the `Traversable` is `null`. */ public static function fromItems(?Traversable<Tv> $items)[]: Set<Tv>; /** * Creates a `Set` from the keys of the specified container. * * The keys of the container will be the values of the `Set`. * * @param $container - The container with the keys used to create the `Set`. * * @return - A `Set` built from the keys of the specified container. */ public static function fromKeysOf<Tk as arraykey>( ?KeyedContainer<Tk, mixed> $container, )[]: Set<Tk>; /** * Returns the `string` version of the current `Set`, which is `"Set"`. * * @return - The `string` `"Set"`. */ public function __toString()[]: string; /** * Returns an `Iterable` view of the current `Set`. * * The `Iterable` returned is one that produces the values from the current * `Set`. * * @return - The `Iterable` view of the current `Set`. */ public function items()[]: Iterable<Tv>; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<Tv, Tv>; } } // namespace HH namespace { /** * @internal * * Methods and functions should take and return the KeyedIterator interface. */ class SetIterator<+Tv> implements HH\KeyedIterator<arraykey, Tv> { public function __construct()[]; public function current()[]: Tv; public function key()[]: arraykey; public function valid()[]: bool; public function next()[write_props]: void; public function rewind()[write_props]: void; } } // namespace
HTML Help Workshop
hhvm/hphp/hack/hhi/collections/Vector.hhi
<?hh /** * Copyright (c) 2014, 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. * */ <<file: __EnableUnstableFeatures('readonly')>> /** * This file provides type information for some of HHVM's builtin classes. * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ namespace HH { /** * `Vector` is a stack-like collection. HHVM provides a native implementation * for this class. The PHP class definition below is not actually used at run * time; it is simply provided for the typechecker and for developer reference. * * Like all objects in PHP, `Vector`s have reference-like semantics. When a * caller passes a `Vector` to a callee, the callee can modify the `Vector` and * the caller will see the changes. `Vector`s do not have "copy-on-write" * semantics. * * `Vector`s only support integer keys. If a non-integer key is used, an * exception will be thrown. * * `Vector`s support `$m[$k]` style syntax for getting and setting values by * key. `Vector`s also support `isset($m[$k])` and `empty($m[$k])` syntax, and * they provide similar semantics as arrays. Elements can be added to a * `Vector` using `$m[] = ..` syntax. * * `Vector`s do not support iterating while new elements are being added or * elements are being removed. When a new element is added or removed, all * iterators that point to the `Vector` shall be considered invalid. * * @guide /hack/collections/introduction * @guide /hack/collections/classes */ final class Vector<Tv> implements \MutableVector<Tv> { /** * Creates a `Vector` from the given `Traversable`, or an empty `Vector` * if `null` is passed. * * @param $it - Any `Traversable` object from which to create * the `Vector` (e.g., `array`). If `null`, then an empty * `Vector` is created. */ public function __construct(?Traversable<Tv> $it)[]; /** * Returns an `array` containing the values from the current `Vector`. * * This method is interchangeable with `toArray()`. * * @return - An `array` containing the values from the current `Vector`. */ public function toValuesArray()[]: varray<Tv>; /** * Returns an `array` whose values are the keys from the current `Vector`. * * @return - An `array` with the integer keys from the current `Vector`. */ <<__NoAutoLikes>> public readonly function toKeysArray()[]: varray<int>; /** * Returns a copy of the current `Vector`. * * @return - A `Vector` that is a copy of the current `Vector`. */ <<__NoAutoLikes>> public function toVector()[]: Vector<Tv>; /** * Returns an immutable copy (`ImmVector`) of the current `Vector`. * * @return - A `Vector` that is an immutable copy of the current `Vector`. */ <<__NoAutoLikes>> public function toImmVector()[]: ImmVector<Tv>; /** * Returns an integer-keyed `Map` based on the values of the current `Vector`. * * @return - A `Map` that has the integer keys and associated values of the * current `Vector`. */ <<__NoAutoLikes>> public function toMap()[]: Map<int, Tv>; /** * Returns an immutable, integer-keyed map (`ImmMap`) based on the values of * the current `Vector`. * * @return - An `ImmMap` that has the integer keys and associated values * of the current `Vector`. */ <<__NoAutoLikes>> public function toImmMap()[]: ImmMap<int, Tv>; /** * Returns a `Set` based on the values of the current `Vector`. * * @return - A `Set` containing the unique values of the current `Vector`. */ <<__NoAutoLikes>> public function toSet()[]: Set<Tv> where Tv as arraykey; /** * Returns an immutable set (`ImmSet`) based on the values of the current * `Vector`. * * @return - An `ImmSet` containing the unique values of the current `Vector`. */ <<__NoAutoLikes>> public function toImmSet()[]: ImmSet<Tv> where Tv as arraykey; /** * Returns an immutable copy (`ImmVector`) of the current `Vector`. * * This method is interchangeable with `toImmVector()`. * * @return - An `ImmVector` copy of the current `Vector`. */ <<__NoAutoLikes>> public function immutable()[]: ImmVector<Tv>; /** * Returns a lazy, access-elements-only-when-needed view of the current * `Vector`. * * Normally, memory is allocated for all of the elements of the `Vector`. * With a lazy view, memory is allocated for an element only when needed or * used in a calculation like in `map()` or `filter()`. * * @return - An integer-keyed `KeyedIterable` representing the lazy view into * the current `Vector`. * * @guide /hack/collections/examples */ public function lazy()[]: KeyedIterable<int, Tv>; /** * Returns a `Vector` containing the values of the current `Vector`. * Essentially a copy of the current `Vector`. * * This method is interchangeable with `toVector()`. * * @return - A `Vector` containing the values of the current `Vector`. */ <<__NoAutoLikes>> public function values()[]: Vector<Tv>; /** * Returns a `Vector` containing the keys of the current `Vector`. * * @return - A `Vector` containing the integer keys of the current `Vector`. */ <<__NoAutoLikes>> public readonly function keys()[]: Vector<int>; /** * Returns a `Vector` containing the results of applying an operation to each * value in the current `Vector`. * * `map()`'s result contains a value for every value in the current `Vector`; * unlike `filter()`, where only values that meet a certain criterion are * included in the resulting `Vector`. * * @param $fn - The callback containing the operation to apply to the * current `Vector`'s values. * * @return - A `Vector` containing the results of applying a user-specified * operation to each value of the current `Vector` in turn. * * @guide /hack/collections/examples */ public function map<Tu>((function(Tv)[_]: Tu) $fn)[ctx $fn]: Vector<Tu>; /** * Returns a `Vector` containing the results of applying an operation to each * key/value pair in the current `Vector`. * * `mapWithKey()`'s result contains a value for every key/value pair in the * current `Vector`; unlike `filterWithKey()`, where only values whose * key/value pairs meet a certain criterion are included in the resulting * `Vector`. * * @param $fn - The callback containing the operation to apply to the * current `Vector`'s key/value pairs. * * @return - A `Vector` containing the results of applying a user-specified * operation to each key/value pair of the current `Vector` in turn. */ public function mapWithKey<Tu>( (function(int, Tv)[_]: Tu) $fn, )[ctx $fn]: Vector<Tu>; /** * Returns a `Vector` containing the values of the current `Vector` that meet * a supplied condition. * * `filter()`'s result contains only values that meet the provided criterion; * unlike `map()`, where a value is included for each value in the original * `Vector`. * * @param $fn - The callback containing the condition to apply to the * `Vector` values. * * @return - A `Vector` containing the values after a user-specified condition * is applied. * * @guide /hack/collections/examples */ public function filter((function(Tv)[_]: bool) $fn)[ctx $fn]: Vector<Tv>; /** * Returns a `Vector` containing the values of the current `Vector` that meet * a supplied condition applied to its keys and values. * * `filterWithKey()`'s result contains only values whose key/value pairs * satisfy the provided criterion; unlike `mapWithKey()`, which contains * results derived from every key/value pair in the original `Vector`. * * @param $fn - The callback containing the condition to apply to the * `Vector`'s key/value pairs. For each key/value pair, * the key is passed as the first parameter to the * callback, and the value is passed as the second * parameter. * * @return - A `Vector` containing the values of the current `Vector` for * which a user-specified test condition returns true when applied * to the corresponding key/value pairs. * */ public function filterWithKey( (function(int, Tv)[_]: bool) $fn, )[ctx $fn]: Vector<Tv>; /** * Returns a `Vector` where each element is a `Pair` that combines the * element of the current `Vector` and the provided `Traversable`. * * If the number of elements of the `Vector` are not equal to the number of * elements in the `Traversable`, then only the combined elements up to and * including the final element of the one with the least number of elements * is included. * * @param $traversable - The `Traversable` to use to combine with the * elements of the current `Vector`. * * @return - A `Vector` that combines the values of the current `Vector` * with the provided `Traversable`. */ public function zip<Tu>( Traversable<Tu> $traversable, )[]: Vector<Pair<Tv, Tu>>; /** * Returns a `Vector` containing the first `$n` values of the current * `Vector`. * * The returned `Vector` will always be a subset (but not necessarily a * proper subset) of the current `Vector`. If `$n` is greater than the length * of the current `Vector`, the returned `Vector` will contain all elements of * the current `Vector`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element that will be included in the returned * `Vector`. * * @return - A `Vector` that is a subset of the current `Vector` up to `$n` * elements. */ public function take(int $n)[]: Vector<Tv>; /** * Returns a `Vector` containing the values of the current `Vector` up to but * not including the first value that produces `false` when passed to the * specified callback. That is, takes the continuous prefix of values in * the current `Vector` for which the specified callback returns `true`. * * The returned `Vector` will always be a subset (but not necessarily a * proper subset) of the current `Vector`. * * @param $fn - The callback that is used to determine the stopping condition. * * @return - A `Vector` that is a subset of the current `Vector` up until the * callback returns `false`. */ public function takeWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: Vector<Tv>; /** * Returns a `Vector` containing the values after the `$n`-th element of the * current `Vector`. * * The returned `Vector` will always be a subset (but not necessarily a * proper subset) of the current `Vector`. If `$n` is greater than or equal to * the length of the current `Vector`, the returned `Vector` will contain no * elements. If `$n` is negative, the returned `Vector` will contain all * elements of the current `Vector`. * * `$n` is 1-based. So the first element is 1, the second 2, etc. * * @param $n - The last element to be skipped; the `$n+1` element will be the * first one in the returned `Vector`. * * @return - A `Vector` that is a subset of the current `Vector` containing * values after the specified `$n`-th element. */ public function skip(int $n)[]: Vector<Tv>; /** * Returns a `Vector` containing the values of the current `Vector` starting * after and including the first value that produces `false` when passed to * the specified callback. That is, skips the continuous prefix of values in * the current `Vector` for which the specified callback returns `true`. * * The returned `Vector` will always be a subset (but not necessarily a * proper subset) of the current `Vector`. * * @param $fn - The callback used to determine the starting element for the * returned `Vector`. * * @return - A `Vector` that is a subset of the current `Vector` starting * with the value for which the callback first returns `false`. */ public function skipWhile((function(Tv)[_]: bool) $fn)[ctx $fn]: Vector<Tv>; /** * Returns a subset of the current `Vector` starting from a given key up to, * but not including, the element at the provided length from the starting key. * * `$start` is 0-based. `$len` is 1-based. So `slice(0, 2)` would return the * elements at keys 0 and 1. * * The returned `Vector` will always be a subset (but not necessarily a * proper subset) of the current `Vector`. If `$start` is greater than or * equal to the length of the current `Vector`, the returned `Vector` will * contain no elements. If `$start` + `$len` is greater than or equal to the * length of the current `Vector`, the returned `Vector` will contain the * elements from `$start` to the end of the current `Vector`. * * If either `$start` or `$len` is negative, an exception is thrown. * * @param $start - The starting key of the current `Vector` at which to begin * the returned `Vector`. * @param $len - The length of the returned `Vector`. * * @return - A `Vector` that is a subset of the current `Vector` starting * at `$start` up to but not including the element `$start + $len`. */ public function slice(int $start, int $len)[]: Vector<Tv>; /** * Returns a `Vector` that is the concatenation of the values of the current * `Vector` and the values of the provided `Traversable`. * * The returned `Vector` is created from the values of the current `Vector`, * followed by the values of the provided `Traversable`. * * The returned `Vector` is a new object; the current `Vector` is unchanged. * Future changes to the current `Vector` will not affect the returned * `Vector`, and future changes to the returned `Vector` will not affect the * current `Vector`. * * @param $traversable - The `Traversable` to concatenate with the current * `Vector`. * * @return - A new `Vector` containing the values from `$traversable` * concatenated to the values from the current `Vector`. * * @guide /hack/generics/constraints */ public function concat<Tu super Tv>( Traversable<Tu> $traversable, )[]: Vector<Tu>; /** * Returns the first value in the current `Vector`. * * @return - The first value in the current `Vector`, or `null` if the * `Vector` is empty. */ public function firstValue()[]: ?Tv; /** * Returns the first key in the current `Vector`. * * @return - The first key (an integer) in the current `Vector`, or `null` if * the `Vector` is empty. */ public readonly function firstKey()[]: ?int; /** * Returns the last value in the current `Vector`. * * @return - The last value in the current `Vector`, or `null` if the current * `Vector` is empty. */ public function lastValue()[]: ?Tv; /** * Returns the last key in the current `Vector`. * * @return - The last key (an integer) in the current `Vector`, or `null` if * the `Vector` is empty. */ public readonly function lastKey()[]: ?int; /** * Checks if the current `Vector` is empty. * * @return - `true` if the current `Vector` is empty; `false` otherwise. */ public readonly function isEmpty()[]: bool; /** * Returns the number of elements in the current `Vector`. * * @return - The number of elements in the current `Vector`. */ public readonly function count()[]: int; /** * Returns the value at the specified key in the current `Vector`. * * If the key is not present, an exception is thrown. If you don't want an * exception to be thrown, use `get()` instead. * * `$v = $vec->at($k)` is semantically equivalent to `$v = $vec[$k]`. * * @param $k - The key for which to retrieve the value. * * @return - The value at the specified key; or an exception if the key does * not exist. */ public function at(int $k)[]: Tv; /** * Returns the value at the specified key in the current `Vector`. * * If the key is not present, null is returned. If you would rather have an * exception thrown when a key is not present, use `at()` instead. * * @param $k - The key for which to retrieve the value. * * @return - The value at the specified key; or `null` if the key does not * exist. */ public function get(int $k)[]: ?Tv; /** * Stores a value into the current `Vector` with the specified key, * overwriting the previous value associated with the key. * * If the key is not present, an exception is thrown. If you want to add * a value even if the key is not present, use `add()`. * * `$vec->set($k,$v)` is semantically equivalent to `$vec[$k] = $v` (except * that `set()` returns the current `Vector`). * * Future changes made to the current `Vector` ARE reflected in the * returned `Vector`, and vice-versa. * * @param $k - The key to which we will set the value. * @param $v - The value to set. * * @return - Returns itself. */ public function set(int $k, Tv $v)[write_props]: Vector<Tv>; /** * For every element in the provided `Traversable`, stores a value into the * current `Vector` associated with each key, overwriting the previous value * associated with the key. * * If a key is not present the current `Vector` that is present in the * `Traversable`, an exception is thrown. If you want to add a value even if a * key is not present, use `addAll()`. * * Future changes made to the current `Vector` ARE reflected in the * returned `Vector`, and vice-versa. * * @param $k - The `Traversable` with the new values to set. If `null` is * provided, no changes are made. * * @return - Returns itself. */ public function setAll( ?KeyedTraversable<int, Tv> $it, )[write_props]: Vector<Tv>; /** * Removes all the elements from the current `Vector`. * * Future changes made to the current `Vector` ARE reflected in the * returned `Vector`, and vice-versa. * * @return - Returns itself. */ <<__NoAutoLikes>> public function clear()[write_props]: Vector<Tv>; /** * Determines if the specified key is in the current `Vector`. * * @return - `true` if the specified key is present in the current `Vector`; * returns `false` otherwise. * * @guide /hack/generics/constraints */ public readonly function containsKey(mixed $k)[]: bool; /** * Appends a value to the end of the current `Vector`, assigning it the next * available integer key. * * If you want to overwrite the value for an existing key, use `set()`. * * `$vec->add($v)` is semantically equivalent to `$vec[] = $v` (except that * `add()` returns the current `Vector`). * * Future changes made to the current `Vector` ARE reflected in the * returned `Vector`, and vice-versa. * * If `$v` is an object, future changes to the added element ARE reflected in * `$v`, and vice versa. * * @param $v - The value to add to the end of the current `Vector` * * @return - Returns itself. */ public function add(Tv $value)[write_props]: Vector<Tv>; /** * For every element in the provided `Traversable`, append a value into this * `Vector`, assigning the next available integer key for each. * * If you want to overwrite the values for existing keys, use `setAll()`. * * Future changes made to the current `Vector` ARE reflected in the * returned `Vector`, and vice-versa. * * @param $k - The `Traversable` with the new values to set. If `null` or an * empty `Traversable` are provided, no changes are made. * * @return - Returns itself. */ public function addAll(?Traversable<Tv> $it)[write_props]: Vector<Tv>; /** * Adds the keys of the specified container to the current `Vector`. * * For every key in the provided `KeyedContainer`, append that key into * the current `Vector`, assigning the next available integer key for each. * * Future changes made to the current `Vector` ARE reflected in the * returned `Vector`, and vice-versa. * * @param $container - The `KeyedContainer` with the new keys to add. * * @return - Returns itself. */ <<__NoAutoLikes>> public function addAllKeysOf( ?KeyedContainer<Tv, mixed> $container, )[write_props]: Vector<Tv> where Tv as arraykey; /** * Removes the key/value pair with the specified key from the current * `Vector`. * * This will cause elements with higher keys to be assigned a new key that is * one less than their previous key. That is, values with keys `$k + 1` to * `n - 1` will be given new keys `$k` to `n - 2`, where n is the length of * the current `Vector` before the call to `removeKey()`. * * If `$k` is negative, or `$k` is greater than the largest key in the current * `Vector`, no changes are made. * * Future changes made to the current `Vector` ARE reflected in the * returned `Vector`, and vice-versa. * * @param $k - The key of the key/value pair to remove. * * @return - Returns itself. */ public function removeKey(int $k)[write_props]: Vector<Tv>; /** * Remove the last element of the current `Vector` and return it. * * This function throws an exception if the current `Vector` is empty. * * The current `Vector` will have `n - 1` elements after this operation, where * `n` is the number of elements in the current `Vector` prior to the call to * `pop()`. * * @return - The value of the last element. */ public function pop()[write_props]: Tv; /** * Resize the current `Vector`. * * Resize the current `Vector` to contain `$sz` elements. If `$sz` is smaller * than the current size of the current `Vector`, elements are removed from * the end of the current `Vector`. If `$sz` is greater than the current size * of the current `Vector`, the current `Vector` is extended by appending as * many copies of `$value` as needed to reach a size of `$sz` elements. * * `$value` can be `null`. * * If `$sz` is less than zero, an exception is thrown. * * @param $sz - The desired size of the current `Vector`. * @param $value - The value to use as the filler if we are increasing the * size of the current `Vector`. */ public function resize(int $sz, Tv $value)[write_props]: void; /** * Reserves enough memory to accommodate a given number of elements. * * Reserves enough memory for `$sz` elements. If `$sz` is less than or * equal to the current capacity of the current `Vector`, this method does * nothing. * * If `$sz` is less than zero, an exception is thrown. * * @param $sz - The pre-determined size you want for the current `Vector`. */ public function reserve(int $sz)[]: void; /** * Returns an iterator that points to beginning of the current `Vector`. * * @return - A `KeyedIterator` that allows you to traverse the current * `Vector`. */ public function getIterator()[]: KeyedIterator<int, Tv>; /** * Reverse the elements of the current `Vector` in place. */ public function reverse()[write_props]: void; /** * Splice the current `Vector` in place. * * This function provides the functionality of * [`array_splice()`](http://php.net/manual/en/function.array-splice.php) * for `Vector`s (except that `splice()` does not permit specifying * replacement values. If a third ("replacement values") parameter is * specified, an exception is thrown. * * * * Note that this function modifies the current `Vector` in place. * * @param $offset - The (0-based) key at which to begin the splice. If * negative, then it starts that far from the end of the * current `Vector`. * @param $len - The length of the splice. If `null`, then the current * `Vector` is spliced until its end. * * @link http://php.net/manual/en/function.array-splice.php */ public function splice(int $offset, ?int $len = null)[write_props]: void; /** * Returns the index of the first element that matches the search value. * * If no element matches the search value, this function returns -1. * * @param $search_value - The value that will be searched for in the current * `Vector`. * * @return - The key (index) where that value is found; -1 if it is not found. * * @guide /hack/generics/constraints */ public readonly function linearSearch(mixed $search_value)[]: int; /** * Shuffles the values of the current `Vector` randomly in place. */ public function shuffle()[leak_safe]: void; /** * Returns a `Vector` containing the values from the specified `array`. * * This function is deprecated. Use `new Vector($arr)` instead. * * @param $arr - The `array` to convert to a `Vector`. * * @return - A `Vector` with the values from the provided `array`. */ <<__Deprecated('Use `new Vector($arr)` instead.'), __NoAutoLikes>> public static function fromArray(darray<arraykey, Tv> $arr): Vector<Tv>; /** * Creates a `Vector` from the given `Traversable`, or an empty `Vector` if * `null` is passed. * * This is the static method version of the `Vector::__construct()` * constructor. * * @param $items - Any `Traversable` object from which to create a `Vector` * (e.g., `array`). If `null`, then an empty `Vector` is * created. * * @return - A `Vector` with the values from the `Traversable`; or an empty * `Vector` if the `Traversable` is `null`. */ <<__NoAutoLikes>> public static function fromItems(?Traversable<Tv> $items)[]: Vector<Tv>; /** * Creates a `Vector` from the keys of the specified container. * * Every key in the provided `KeyedContainer` will appear sequentially in the * returned `Vector`, with the next available integer key assigned to each. * * @param $container - The container with the keys used to create the * `Vector`. * * @return - A `Vector` built from the keys of the specified container. */ <<__NoAutoLikes>> public static function fromKeysOf<Tk as arraykey>( ?KeyedContainer<Tk, mixed> $container, )[]: Vector<Tk>; /** * Returns the `string` version of the current `Vector`, which is `"Vector"`. * * @return - The string `"Vector"`. */ public function __toString()[]: string; /** * Returns an `Iterable` view of the current `Vector`. * * The `Iterable` returned is one that produces the values from the current * `Vector`. * * @return - The `Iterable` view of the current `Vector`. */ public function items()[]: Iterable<Tv>; public function toVArray()[]: varray<Tv>; public function toDArray()[]: darray<int, Tv>; } } // namespace HH namespace { /** * @internal * * Methods and functions should take and return the KeyedIterator interface. */ class VectorIterator<+Tv> implements HH\KeyedIterator<int, Tv> { public function __construct()[]; public function current()[]: Tv; public function key()[]: int; public function valid()[]: bool; public function next()[write_props]: void; public function rewind()[write_props]: void; } } // namespace
Text
hhvm/hphp/hack/hhi/experimental/readme.txt
Hack for HipHop interface files for experimental hack features. To enable these, enable_experimental_tc_features must be enabled in your hhconfig. Warning: These features are experimental and not supported so count on your code breaking.
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_hsl_io_private.hhi
<?hh /** * 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. * */ namespace HH\Lib\_Private\_IO; function response_write(string $data): int; function response_flush(): void; function request_read(int $max_bytes): string;
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_hsl_locale.hhi
<?hh /** * 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. * */ namespace HH\Lib\Locale { final class InvalidLocaleException extends \Exception {} } namespace HH\Lib\_Private\_Locale { final class Locale { private function __construct() {} public function __debugInfo(): dict<arraykey, mixed>; } function get_c_locale()[]: Locale; function get_environment_locale()[read_globals]: Locale; function get_request_locale()[read_globals]: Locale; function set_request_locale(Locale $loc)[globals]: void; /** Behaves like `newlocale()`, taking a mask of categories, e.g. LC_CTYPE_MASK */ function newlocale_mask( int $mask, string $locale, Locale $base, )[read_globals]: Locale; /** Take a single category, e.g. `LC_TYPE` */ function newlocale_category( int $category, string $locale, Locale $base, )[read_globals]: Locale; /** Create a new locale object using the specified locale for all categories. * * This function will throw if a 'magic' locale is passed, e.g. * `"0"` (fetch current locale) or `""` (environment locale). */ function newlocale_all(string $locale)[]: Locale; // --- platform-specific constants --- // more are defined for every platform, but the HHI is only including ones that // are defined on every supported platform const int LC_ALL; const int LC_COLLATE; const int LC_CTYPE; const int LC_MONETARY; const int LC_NUMERIC; const int LC_TIME; // required by POSIX, but not by C standard. Not supported by MSVC, but we don't // support that (yet?). const int LC_MESSAGES; const int LC_ALL_MASK; const int LC_COLLATE_MASK; const int LC_CTYPE_MASK; const int LC_MONETARY_MASK; const int LC_NUMERIC_MASK; const int LC_TIME_MASK; const int LC_MESSAGES_MASK; } // namespace HH\Lib\_Private\_Locale
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_hsl_os.hhi
<?hh /** * 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. * */ namespace HH\Lib\OS; newtype FileDescriptor = mixed;
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_hsl_os_fds.hhi
<?hh /** * 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. * */ // we anticipate raising a new error, similar to __Deprecated, for calling // 'private' builtins; despite the fact they shouldn't be called by anything // except the HSL, we're defining an HHI so the HSL itself can be type-safe: // suppressing "this should not be called" is better than making a completely // untyped call. namespace HH\Lib\_Private\_OS; use type HH\Lib\OS\FileDescriptor; // Actual values are platform-specific const int E2BIG; const int EACCES; const int EADDRINUSE; const int EADDRNOTAVAIL; const int EAFNOSUPPORT; const int EAGAIN; const int EALREADY; const int EBADF; const int EBADMSG; const int EBUSY; const int ECANCELED; const int ECHILD; const int ECONNABORTED; const int ECONNREFUSED; const int ECONNRESET; const int EDEADLK; const int EDESTADDRREQ; const int EDOM; const int EDQUOT; const int EEXIST; const int EFAULT; const int EFBIG; const int EHOSTDOWN; const int EHOSTUNREACH; const int EIDRM; const int EILSEQ; const int EINPROGRESS; const int EINTR; const int EINVAL; const int EIO; const int EISCONN; const int EISDIR; const int ELOOP; const int EMFILE; const int EMLINK; const int EMSGSIZE; const int EMULTIHOP; const int ENAMETOOLONG; const int ENETDOWN; const int ENETRESET; const int ENETUNREACH; const int ENFILE; const int ENOBUFS; const int ENODATA; const int ENODEV; const int ENOENT; const int ENOEXEC; const int ENOLCK; const int ENOLINK; const int ENOMEM; const int ENOMSG; const int ENOPROTOOPT; const int ENOSPC; const int ENOSR; const int ENOSTR; const int ENOSYS; const int ENOTBLK; const int ENOTCONN; const int ENOTDIR; const int ENOTEMPTY; const int ENOTSOCK; const int ENOTSUP; const int ENOTTY; const int ENXIO; const int EOPNOTSUPP; const int EOVERFLOW; const int EPERM; const int EPFNOSUPPORT; const int EPIPE; const int EPROTO; const int EPROTONOSUPPORT; const int EPROTOTYPE; const int ERANGE; const int EROFS; const int ESHUTDOWN; const int ESOCKTNOSUPPORT; const int ESPIPE; const int ESRCH; const int ESTALE; const int ETIME; const int ETIMEDOUT; const int ETXTBSY; const int EUSERS; const int EXDEV; const int O_RDONLY; const int O_WRONLY; const int O_RDWR; const int O_NONBLOCK; const int O_APPEND; const int O_CREAT/*E < you dropped this*/ ; const int O_TRUNC; const int O_EXCL; const int O_NOFOLLOW; const int O_CLOEXEC; const int SEEK_SET; const int SEEK_CUR; const int SEEK_END; const int SEEK_HOLE; const int SEEK_DATA; const int STDIN_FILENO; const int STDOUT_FILENO; const int STDERR_FILENO; final class ErrnoException extends \Exception {} function poll_async( FileDescriptor $fd, int $events, int $timeout_ns, ): Awaitable<int>; function open(string $path, int $flags, int $mode = 0): FileDescriptor; function request_stdio_fd(int $stdio_fileno): FileDescriptor; function mkdtemp(string $template): string; function mkostemps( string $template, int $suffixlen, int $flags, ): (FileDescriptor, string); function read(FileDescriptor $fd, int $max_to_read): string; function write(FileDescriptor $fd, string $data): int; function close(FileDescriptor $fd): void; function dup(FileDescriptor $fd): FileDescriptor; function pipe(): (FileDescriptor, FileDescriptor); const int AF_UNSPEC; const int AF_UNIX; const int AF_INET; const int AF_INET6; const int AF_MAX; // Same as AF_ const int PF_UNSPEC; const int PF_UNIX; const int PF_INET; const int PF_INET6; const int PF_MAX; const int SUN_PATH_LEN; const int INADDR_ANY; const int INADDR_LOOPBACK; const int INADDR_BROADCAST; const int INADDR_NONE; const int SOCK_STREAM; const int SOCK_DGRAM; const int SOCK_RAW; const int F_GETFD; const int F_GETFL; const int F_GETOWN; const int F_SETFD; const int F_SETFL; const int F_SETOWN; const int FD_CLOEXEC; const int LOCK_SH; const int LOCK_EX; const int LOCK_NB; const int LOCK_UN; const int SOL_SOCKET; // the constant formerly known as SOL_TCP const int IPPROTO_TCP; const int SO_BROADCAST; const int SO_DEBUG; const int SO_DONTROUTE; const int SO_ERROR; const int SO_KEEPALIVE; const int SO_LINGER; const int SO_OOBINLINE; const int SO_RCVBUF; const int SO_RCVLOWAT; const int SO_REUSEADDR; const int SO_REUSEPORT; const int SO_SNDBUF; const int SO_SNDLOWAT; const int SO_TYPE; const int TCP_FASTOPEN; const int TCP_KEEPCNT; const int TCP_KEEPINTVL; const int TCP_MAXSEG; const int TCP_NODELAY; const int TCP_NOTSENT_LOWAT; type uint32_t = int; type sa_family_t = int; type in_port_t = int; class sockaddr { public function __construct(public sa_family_t $sa_family) {} // Intentionally not including "data": // - it's a placeholder // - it can be thought of as a union of the data of all the others // - may include pointers that can't be dealt with. } final class sockaddr_in extends sockaddr { public function __construct( public in_port_t $sin_port, public uint32_t $sin_addr, ) { parent::__construct(namespace\AF_INET); } } final class sockaddr_in6 extends sockaddr { public function __construct( public in_port_t $sin6_port, public uint32_t $sin6_flowinfo, public string $sin6_addr, public uint32_t $sin6_scope_id, ) { parent::__construct(namespace\AF_INET6); } } abstract class sockaddr_un extends sockaddr { public function __construct() { parent::__construct(namespace\AF_UNIX); } } final class sockaddr_un_pathname extends sockaddr_un { public function __construct(public string $sun_path) { parent::__construct(); } } final class sockaddr_un_unnamed extends sockaddr_un { } function getpeername(FileDescriptor $fd): sockaddr; function getsockname(FileDescriptor $fd): sockaddr; function socketpair( int $domain, int $type, int $protocol, ): (FileDescriptor, FileDescriptor); function fcntl(FileDescriptor $fd, int $cmd, mixed $arg = null): mixed; function getsockopt_int(FileDescriptor $fd, int $level, int $option): int; function setsockopt_int( FileDescriptor $fd, int $level, int $option, int $value, ): void; function socket(int $domain, int $type, int $protocol): FileDescriptor; function connect(FileDescriptor $socket, sockaddr $addr): void; function bind(FileDescriptor $socket, sockaddr $addr): void; function listen(FileDescriptor $socket, int $backlog): void; function accept(FileDescriptor $socket): (FileDescriptor, sockaddr); function lseek(FileDescriptor $fd, int $offset, int $whence): int; function ftruncate(FileDescriptor $fd, int $length): void; function flock(FileDescriptor $fd, int $operation): void; function isatty(FileDescriptor $fd): bool; function ttyname(FileDescriptor $fd): string;
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_hsl_os_subprocesses.hhi
<?hh /** * 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. * */ namespace HH\Lib\_Private\_OS; use type HH\Lib\OS\FileDescriptor; type ForkAndExecveOptions = shape( ?'cwd' => string, ?'setsid' => bool, ?'execvpe' => bool, ?'setpgid' => int, ); function fork_and_execve( string $path, vec<string> $argv, vec<string> $envp, dict<int, FileDescriptor> $fds, ForkAndExecveOptions $options, ): int;
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_hsl_str.hhi
<?hh // decl /* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ namespace HH\Lib\_Private\_Str { use type HH\Lib\_Private\_Locale\Locale; function strlen_l(string $str, ?Locale $loc = null)[]: int; function uppercase_l(string $str, ?Locale $loc = null)[]: string; function lowercase_l(string $str, ?Locale $loc = null)[]: string; function titlecase_l(string $str, ?Locale $loc = null)[]: string; function foldcase_l(string $str, ?Locale $loc = null)[]: string; function strcoll_l(string $a, string $b, ?Locale $loc = null)[]: int; function strcasecmp_l(string $a, string $b, ?Locale $loc = null)[]: int; function starts_with_l( string $str, string $prefix, ?Locale $loc = null, )[]: bool; function starts_with_ci_l( string $str, string $prefix, ?Locale $loc = null, )[]: bool; function ends_with_l( string $str, string $suffix, ?Locale $loc = null, )[]: bool; function ends_with_ci_l( string $str, string $suffix, ?Locale $loc = null, )[]: bool; function strip_prefix_l( string $str, string $prefix, ?Locale $loc = null, )[]: string; function strip_suffix_l( string $str, string $prefix, ?Locale $loc = null, )[]: string; function strpos_l( string $haystack, string $needle, int $offset, ?Locale $loc = null, )[]: int; function strrpos_l( string $haystack, string $needle, int $offset, ?Locale $loc = null, )[]: int; function stripos_l( string $haystack, string $needle, int $offset, ?Locale $loc = null, )[]: int; function strripos_l( string $haystack, string $needle, int $offset, ?Locale $loc = null, )[]: int; function chunk_l(string $str, int $size, ?Locale $loc = null)[]: vec<string>; function slice_l( string $str, int $offset, int $length, ?Locale $loc = null, )[]: string; function splice_l( string $str, string $replacement, int $offset, ?int $length = null, ?Locale $loc = null, )[]: string; function split_l( string $string, string $delimiter, ?int $limit = null, ?Locale $loc = null, )[]: vec<string>; function reverse_l(string $str, ?Locale $loc = null)[]: string; function vsprintf_l(?Locale $loc, string $fmt, vec<mixed> $args)[]: string; function pad_left_l( string $str, int $length, string $pad_str = ' ', ?Locale $loc = null, )[]: string; function pad_right_l( string $str, int $length, string $pad_str = ' ', ?Locale $loc = null, )[]: string; function trim_l(string $str, ?string $what, ?Locale $loc = null)[]: string; function trim_left_l( string $str, ?string $what, ?Locale $loc = null, )[]: string; function trim_right_l( string $str, ?string $what, ?Locale $loc = null, )[]: string; function replace_l( string $haystack, string $needle, string $replacement, ?Locale $loc = null, )[]: string; function replace_ci_l( string $haystack, string $needle, string $replacement, ?Locale $loc = null, )[]: string; function replace_every_l( string $haystack, dict<string, string> $replacements, ?Locale $loc = null, )[]: string; function replace_every_ci_l( string $haystack, dict<string, string> $replacements, ?Locale $loc = null, )[]: string; function replace_every_nonrecursive_l( string $haystack, dict<string, string> $replacements, ?Locale $loc = null, )[]: string; function replace_every_nonrecursive_ci_l( string $haystack, dict<string, string> $replacements, ?Locale $loc = null, )[]: string; } // namespace HH\Lib\_Private\_Str
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_random.hhi
<?hh /** * Copyright (c) 2014, 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. * */ namespace HH\Lib\_Private\Native { function pseudorandom_int( int $min = \PHP_INT_MIN, int $max = \PHP_INT_MAX, )[leak_safe]: int; function pseudorandom_seed(int $seed): void; function random_int( int $min = \PHP_INT_MIN, int $max = \PHP_INT_MAX, )[leak_safe]: int; }
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_regex.hhi
<?hh /** * 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. * */ namespace HH\Lib\Regex { /** * Example usage of a Match: * * $match = Regex\first_match( * $some_string, * re"/^(positional)and(?<named>foo)$/" * ); * * if ($match is nonnull) { * $match[0]; // OK, full matched string * $match[1]; // OK, first positional group * $match['named']; // OK, named group * $match['nonexistent']; // ERROR: The field nonexistent is undefined (Typing[4108]) * // (that field is not given by T, the specific * // instantiation of the Pattern<T>. * } */ type Match = shape(...); /** * Example usage of a Pattern<T>: * * $pattern = re"/^(positional)and(?<named>foo)$/"; * * The 're' prefix with a double-quoted string is interpreted by the Hack * server which will extract information such as the number and names of * positional arguments. This can then be used with various Regex\ functions, * the results of which represent a Match. */ newtype Pattern<+T as Match> = string; } namespace HH\Lib\_Private\_Regex { /** * Tries to match $pattern in $haystack (starting at $offset). If it matches * then $offset is updated to the start of the match, and a 2-tuple with * the matches and a null error is returned. If it does not match but there * is no error, a 2-tuple with 2 nulls is returned. If there is an error, a * 2-tuple with the error number in the second position is returned. */ function match<T as \HH\Lib\Regex\Match>( string $haystack, \HH\Lib\Regex\Pattern<T> $pattern, inout int $offset, )[]: (?T, ?int); /** * Tries to match $pattern in $haystack, replacing any matches with * $replacement (with backreference support in the replacement). On success * a 2-tuple with the resulting string and a null error is returned (no * match is a success and returns the $haystack unmodified). On error, a * 2-tuple with the error number in the second position is returned. */ function replace( string $haystack, \HH\Lib\Regex\Pattern<\HH\Lib\Regex\Match> $pattern, string $replacement, )[]: (?string, ?int); }
HTML Help Workshop
hhvm/hphp/hack/hhi/hsl/ext_time.hhi
<?hh /** * Copyright (c) 2014, 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. * */ namespace HH\Lib\_Private\Native { function request_time_ns(): int; }
HTML Help Workshop
hhvm/hphp/hack/hhi/imagick/Imagick.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class Imagick implements Countable, Iterator<Imagick>, Traversable<Imagick> { // Constants const int COMPOSITE_MODULUSSUBTRACT; const int COMPOSITE_DARKENINTENSITY; const int COMPOSITE_LIGHTENINTENSITY; const int IMGTYPE_COLORSEPARATIONMATTE; const int IMGTYPE_PALETTEBILEVELMATTE; const int RESOLUTION_PIXELSPERINCH; const int RESOLUTION_PIXELSPERCENTIMETER; const int COMPRESSION_LOSSLESSJPEG; const int NOISE_MULTIPLICATIVEGAUSSIAN; const int METRIC_MEANABSOLUTEERROR; const int METRIC_PEAKABSOLUTEERROR; const int METRIC_PEAKSIGNALTONOISERATIO; const int METRIC_ROOTMEANSQUAREDERROR; const int EVALUATE_MULTIPLICATIVENOISE; const int VIRTUALPIXELMETHOD_UNDEFINED; const int VIRTUALPIXELMETHOD_BACKGROUND; const int VIRTUALPIXELMETHOD_CONSTANT; const int VIRTUALPIXELMETHOD_MIRROR; const int VIRTUALPIXELMETHOD_TRANSPARENT; const int VIRTUALPIXELMETHOD_BLACK; const int VIRTUALPIXELMETHOD_WHITE; const int VIRTUALPIXELMETHOD_HORIZONTALTILE; const int VIRTUALPIXELMETHOD_VERTICALTILE; const int VIRTUALPIXELMETHOD_HORIZONTALTILEEDGE; const int VIRTUALPIXELMETHOD_VERTICALTILEEDGE; const int VIRTUALPIXELMETHOD_CHECKERTILE; const int RENDERINGINTENT_UNDEFINED; const int RENDERINGINTENT_SATURATION; const int RENDERINGINTENT_PERCEPTUAL; const int RENDERINGINTENT_ABSOLUTE; const int RENDERINGINTENT_RELATIVE; const int PATHUNITS_USERSPACEONUSE; const int PATHUNITS_OBJECTBOUNDINGBOX; const int LAYERMETHOD_COMPARECLEAR; const int LAYERMETHOD_COMPAREOVERLAY; const int LAYERMETHOD_OPTIMIZEPLUS; const int LAYERMETHOD_OPTIMIZETRANS; const int LAYERMETHOD_OPTIMIZEIMAGE; const int DISTORTION_AFFINEPROJECTION; const int DISTORTION_PERSPECTIVEPROJECTION; const int DISTORTION_SCALEROTATETRANSLATE; const int DISTORTION_BARRELINVERSE; const int DISTORTION_BILINEARFORWARD; const int DISTORTION_BILINEARREVERSE; const int DISTORTION_CYLINDER2PLANE; const int DISTORTION_PLANE2CYLINDER; const int ALPHACHANNEL_TRANSPARENT; const int SPARSECOLORMETHOD_UNDEFINED; const int SPARSECOLORMETHOD_BARYCENTRIC; const int SPARSECOLORMETHOD_BILINEAR; const int SPARSECOLORMETHOD_POLYNOMIAL; const int SPARSECOLORMETHOD_SPEPARDS; const int SPARSECOLORMETHOD_VORONOI; const int INTERPOLATE_NEARESTNEIGHBOR; const int DITHERMETHOD_FLOYDSTEINBERG; const int COLOR_BLACK; const int COLOR_BLUE; const int COLOR_CYAN; const int COLOR_GREEN; const int COLOR_RED; const int COLOR_YELLOW; const int COLOR_MAGENTA; const int COLOR_OPACITY; const int COLOR_ALPHA; const int COLOR_FUZZ; const int DISPOSE_UNRECOGNIZED; const int DISPOSE_UNDEFINED; const int DISPOSE_NONE; const int DISPOSE_BACKGROUND; const int DISPOSE_PREVIOUS; const int COMPOSITE_DEFAULT; const int COMPOSITE_UNDEFINED; const int COMPOSITE_NO; const int COMPOSITE_ADD; const int COMPOSITE_ATOP; const int COMPOSITE_BLEND; const int COMPOSITE_BUMPMAP; const int COMPOSITE_CLEAR; const int COMPOSITE_COLORBURN; const int COMPOSITE_COLORDODGE; const int COMPOSITE_COLORIZE; const int COMPOSITE_COPYBLACK; const int COMPOSITE_COPYBLUE; const int COMPOSITE_COPY; const int COMPOSITE_COPYCYAN; const int COMPOSITE_COPYGREEN; const int COMPOSITE_COPYMAGENTA; const int COMPOSITE_COPYOPACITY; const int COMPOSITE_COPYRED; const int COMPOSITE_COPYYELLOW; const int COMPOSITE_DARKEN; const int COMPOSITE_DSTATOP; const int COMPOSITE_DST; const int COMPOSITE_DSTIN; const int COMPOSITE_DSTOUT; const int COMPOSITE_DSTOVER; const int COMPOSITE_DIFFERENCE; const int COMPOSITE_DISPLACE; const int COMPOSITE_DISSOLVE; const int COMPOSITE_EXCLUSION; const int COMPOSITE_HARDLIGHT; const int COMPOSITE_HUE; const int COMPOSITE_IN; const int COMPOSITE_LIGHTEN; const int COMPOSITE_LUMINIZE; const int COMPOSITE_MINUS; const int COMPOSITE_MODULATE; const int COMPOSITE_MULTIPLY; const int COMPOSITE_OUT; const int COMPOSITE_OVER; const int COMPOSITE_OVERLAY; const int COMPOSITE_PLUS; const int COMPOSITE_REPLACE; const int COMPOSITE_SATURATE; const int COMPOSITE_SCREEN; const int COMPOSITE_SOFTLIGHT; const int COMPOSITE_SRCATOP; const int COMPOSITE_SRC; const int COMPOSITE_SRCIN; const int COMPOSITE_SRCOUT; const int COMPOSITE_SRCOVER; const int COMPOSITE_SUBTRACT; const int COMPOSITE_THRESHOLD; const int COMPOSITE_XOR; const int COMPOSITE_CHANGEMASK; const int COMPOSITE_LINEARLIGHT; const int COMPOSITE_DIVIDE; const int COMPOSITE_DISTORT; const int COMPOSITE_BLUR; const int COMPOSITE_PEGTOPLIGHT; const int COMPOSITE_VIVIDLIGHT; const int COMPOSITE_PINLIGHT; const int COMPOSITE_LINEARDODGE; const int COMPOSITE_LINEARBURN; const int COMPOSITE_MATHEMATICS; const int COMPOSITE_MODULUSADD; const int COMPOSITE_MINUSDST; const int COMPOSITE_DIVIDEDST; const int COMPOSITE_DIVIDESRC; const int COMPOSITE_MINUSSRC; const int MONTAGEMODE_FRAME; const int MONTAGEMODE_UNFRAME; const int MONTAGEMODE_CONCATENATE; const int STYLE_NORMAL; const int STYLE_ITALIC; const int STYLE_OBLIQUE; const int STYLE_ANY; const int FILTER_UNDEFINED; const int FILTER_POINT; const int FILTER_BOX; const int FILTER_TRIANGLE; const int FILTER_HERMITE; const int FILTER_HANNING; const int FILTER_HAMMING; const int FILTER_BLACKMAN; const int FILTER_GAUSSIAN; const int FILTER_QUADRATIC; const int FILTER_CUBIC; const int FILTER_CATROM; const int FILTER_MITCHELL; const int FILTER_LANCZOS; const int FILTER_BESSEL; const int FILTER_SINC; const int FILTER_KAISER; const int FILTER_WELSH; const int FILTER_PARZEN; const int FILTER_LAGRANGE; const int FILTER_SENTINEL; const int FILTER_BOHMAN; const int FILTER_BARTLETT; const int FILTER_JINC; const int FILTER_SINCFAST; const int FILTER_ROBIDOUX; const int FILTER_LANCZOSSHARP; const int FILTER_LANCZOS2; const int FILTER_LANCZOS2SHARP; const int IMGTYPE_UNDEFINED; const int IMGTYPE_BILEVEL; const int IMGTYPE_GRAYSCALE; const int IMGTYPE_GRAYSCALEMATTE; const int IMGTYPE_PALETTEMATTE; const int IMGTYPE_TRUECOLOR; const int IMGTYPE_TRUECOLORMATTE; const int IMGTYPE_COLORSEPARATION; const int IMGTYPE_OPTIMIZE; const int IMGTYPE_PALETTE; const int RESOLUTION_UNDEFINED; const int COMPRESSION_UNDEFINED; const int COMPRESSION_NO; const int COMPRESSION_BZIP; const int COMPRESSION_FAX; const int COMPRESSION_GROUP4; const int COMPRESSION_JPEG; const int COMPRESSION_JPEG2000; const int COMPRESSION_LZW; const int COMPRESSION_RLE; const int COMPRESSION_ZIP; const int COMPRESSION_DXT1; const int COMPRESSION_DXT3; const int COMPRESSION_DXT5; const int COMPRESSION_ZIPS; const int COMPRESSION_PIZ; const int COMPRESSION_PXR24; const int COMPRESSION_B44; const int COMPRESSION_B44A; const int COMPRESSION_LZMA; const int COMPRESSION_JBIG1; const int COMPRESSION_JBIG2; const int PAINT_POINT; const int PAINT_REPLACE; const int PAINT_FLOODFILL; const int PAINT_FILLTOBORDER; const int PAINT_RESET; const int GRAVITY_NORTHWEST; const int GRAVITY_NORTH; const int GRAVITY_NORTHEAST; const int GRAVITY_WEST; const int GRAVITY_CENTER; const int GRAVITY_EAST; const int GRAVITY_SOUTHWEST; const int GRAVITY_SOUTH; const int GRAVITY_SOUTHEAST; const int STRETCH_NORMAL; const int STRETCH_ULTRACONDENSED; const int STRETCH_CONDENSED; const int STRETCH_SEMICONDENSED; const int STRETCH_SEMIEXPANDED; const int STRETCH_EXPANDED; const int STRETCH_EXTRAEXPANDED; const int STRETCH_ULTRAEXPANDED; const int STRETCH_ANY; const int ALIGN_UNDEFINED; const int ALIGN_LEFT; const int ALIGN_CENTER; const int ALIGN_RIGHT; const int DECORATION_NO; const int DECORATION_UNDERLINE; const int DECORATION_OVERLINE; const int DECORATION_LINETROUGH; const int NOISE_UNIFORM; const int NOISE_GAUSSIAN; const int NOISE_IMPULSE; const int NOISE_LAPLACIAN; const int NOISE_POISSON; const int NOISE_RANDOM; const int CHANNEL_UNDEFINED; const int CHANNEL_RED; const int CHANNEL_GRAY; const int CHANNEL_CYAN; const int CHANNEL_GREEN; const int CHANNEL_MAGENTA; const int CHANNEL_BLUE; const int CHANNEL_YELLOW; const int CHANNEL_ALPHA; const int CHANNEL_OPACITY; const int CHANNEL_MATTE; const int CHANNEL_BLACK; const int CHANNEL_INDEX; const int CHANNEL_ALL; const int CHANNEL_DEFAULT; const int CHANNEL_TRUEALPHA; const int CHANNEL_RGBS; const int CHANNEL_SYNC; const int CHANNEL_COMPOSITES; const int METRIC_UNDEFINED; const int METRIC_MEANSQUAREERROR; const int PIXEL_CHAR; const int PIXEL_DOUBLE; const int PIXEL_FLOAT; const int PIXEL_INTEGER; const int PIXEL_LONG; const int PIXEL_QUANTUM; const int PIXEL_SHORT; const int EVALUATE_UNDEFINED; const int EVALUATE_ADD; const int EVALUATE_AND; const int EVALUATE_DIVIDE; const int EVALUATE_LEFTSHIFT; const int EVALUATE_MAX; const int EVALUATE_MIN; const int EVALUATE_MULTIPLY; const int EVALUATE_OR; const int EVALUATE_RIGHTSHIFT; const int EVALUATE_SET; const int EVALUATE_SUBTRACT; const int EVALUATE_XOR; const int EVALUATE_POW; const int EVALUATE_LOG; const int EVALUATE_THRESHOLD; const int EVALUATE_THRESHOLDBLACK; const int EVALUATE_THRESHOLDWHITE; const int EVALUATE_GAUSSIANNOISE; const int EVALUATE_IMPULSENOISE; const int EVALUATE_LAPLACIANNOISE; const int EVALUATE_POISSONNOISE; const int EVALUATE_UNIFORMNOISE; const int EVALUATE_COSINE; const int EVALUATE_SINE; const int EVALUATE_ADDMODULUS; const int EVALUATE_MEAN; const int EVALUATE_ABS; const int EVALUATE_EXPONENTIAL; const int EVALUATE_MEDIAN; const int COLORSPACE_UNDEFINED; const int COLORSPACE_RGB; const int COLORSPACE_GRAY; const int COLORSPACE_TRANSPARENT; const int COLORSPACE_OHTA; const int COLORSPACE_LAB; const int COLORSPACE_XYZ; const int COLORSPACE_YCBCR; const int COLORSPACE_YCC; const int COLORSPACE_YIQ; const int COLORSPACE_YPBPR; const int COLORSPACE_YUV; const int COLORSPACE_CMYK; const int COLORSPACE_SRGB; const int COLORSPACE_HSB; const int COLORSPACE_HSL; const int COLORSPACE_HWB; const int COLORSPACE_REC601LUMA; const int COLORSPACE_REC709LUMA; const int COLORSPACE_LOG; const int COLORSPACE_CMY; const int VIRTUALPIXELMETHOD_EDGE; const int VIRTUALPIXELMETHOD_TILE; const int VIRTUALPIXELMETHOD_MASK; const int VIRTUALPIXELMETHOD_GRAY; const int PREVIEW_UNDEFINED; const int PREVIEW_ROTATE; const int PREVIEW_SHEAR; const int PREVIEW_ROLL; const int PREVIEW_HUE; const int PREVIEW_SATURATION; const int PREVIEW_BRIGHTNESS; const int PREVIEW_GAMMA; const int PREVIEW_SPIFF; const int PREVIEW_DULL; const int PREVIEW_GRAYSCALE; const int PREVIEW_QUANTIZE; const int PREVIEW_DESPECKLE; const int PREVIEW_REDUCENOISE; const int PREVIEW_ADDNOISE; const int PREVIEW_SHARPEN; const int PREVIEW_BLUR; const int PREVIEW_THRESHOLD; const int PREVIEW_EDGEDETECT; const int PREVIEW_SPREAD; const int PREVIEW_SOLARIZE; const int PREVIEW_SHADE; const int PREVIEW_RAISE; const int PREVIEW_SEGMENT; const int PREVIEW_SWIRL; const int PREVIEW_IMPLODE; const int PREVIEW_WAVE; const int PREVIEW_OILPAINT; const int PREVIEW_CHARCOALDRAWING; const int PREVIEW_JPEG; const int INTERLACE_UNDEFINED; const int INTERLACE_NO; const int INTERLACE_LINE; const int INTERLACE_PLANE; const int INTERLACE_PARTITION; const int INTERLACE_GIF; const int INTERLACE_JPEG; const int INTERLACE_PNG; const int FILLRULE_UNDEFINED; const int FILLRULE_EVENODD; const int FILLRULE_NONZERO; const int PATHUNITS_UNDEFINED; const int PATHUNITS_USERSPACE; const int LINECAP_UNDEFINED; const int LINECAP_BUTT; const int LINECAP_ROUND; const int LINECAP_SQUARE; const int LINEJOIN_UNDEFINED; const int LINEJOIN_MITER; const int LINEJOIN_ROUND; const int LINEJOIN_BEVEL; const int RESOURCETYPE_UNDEFINED; const int RESOURCETYPE_AREA; const int RESOURCETYPE_DISK; const int RESOURCETYPE_FILE; const int RESOURCETYPE_MAP; const int RESOURCETYPE_MEMORY; const int LAYERMETHOD_UNDEFINED; const int LAYERMETHOD_COALESCE; const int LAYERMETHOD_COMPAREANY; const int LAYERMETHOD_DISPOSE; const int LAYERMETHOD_OPTIMIZE; const int LAYERMETHOD_COMPOSITE; const int LAYERMETHOD_REMOVEDUPS; const int LAYERMETHOD_REMOVEZERO; const int LAYERMETHOD_MERGE; const int LAYERMETHOD_FLATTEN; const int LAYERMETHOD_MOSAIC; const int LAYERMETHOD_TRIMBOUNDS; const int ORIENTATION_UNDEFINED; const int ORIENTATION_TOPLEFT; const int ORIENTATION_TOPRIGHT; const int ORIENTATION_BOTTOMRIGHT; const int ORIENTATION_BOTTOMLEFT; const int ORIENTATION_LEFTTOP; const int ORIENTATION_RIGHTTOP; const int ORIENTATION_RIGHTBOTTOM; const int ORIENTATION_LEFTBOTTOM; const int DISTORTION_UNDEFINED; const int DISTORTION_AFFINE; const int DISTORTION_ARC; const int DISTORTION_BILINEAR; const int DISTORTION_PERSPECTIVE; const int DISTORTION_POLYNOMIAL; const int DISTORTION_POLAR; const int DISTORTION_DEPOLAR; const int DISTORTION_BARREL; const int DISTORTION_SHEPARDS; const int DISTORTION_SENTINEL; const int DISTORTION_RESIZE; const int ALPHACHANNEL_ACTIVATE; const int ALPHACHANNEL_DEACTIVATE; const int ALPHACHANNEL_RESET; const int ALPHACHANNEL_SET; const int ALPHACHANNEL_UNDEFINED; const int ALPHACHANNEL_COPY; const int ALPHACHANNEL_EXTRACT; const int ALPHACHANNEL_OPAQUE; const int ALPHACHANNEL_SHAPE; const int FUNCTION_UNDEFINED; const int FUNCTION_POLYNOMIAL; const int FUNCTION_SINUSOID; const int FUNCTION_ARCSIN; const int FUNCTION_ARCTAN; const int INTERPOLATE_UNDEFINED; const int INTERPOLATE_AVERAGE; const int INTERPOLATE_BICUBIC; const int INTERPOLATE_BILINEAR; const int INTERPOLATE_FILTER; const int INTERPOLATE_INTEGER; const int INTERPOLATE_MESH; const int INTERPOLATE_SPLINE; const int DITHERMETHOD_UNDEFINED; const int DITHERMETHOD_NO; const int DITHERMETHOD_RIEMERSMA; // Methods public function count(): int; public function key(): int; public function next(): void; public function rewind(): void; public function adaptiveBlurImage( float $radius, float $sigma, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function adaptiveResizeImage( int $columns, int $rows, bool $bestfit = false, ): bool; public function adaptiveSharpenImage( float $radius, float $sigma, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function adaptiveThresholdImage( int $width, int $height, int $offset, ): bool; public function addImage(Imagick $source): bool; public function addNoiseImage( int $noise_type, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function affineTransformImage(ImagickDraw $matrix): bool; public function animateImages(string $x_server): bool; public function annotateImage( ImagickDraw $draw_settings, float $x, float $y, float $angle, string $text, ): bool; public function appendImages(bool $stack = false): Imagick; public function averageImages(): Imagick; public function blackThresholdImage( HH\FIXME\MISSING_PARAM_TYPE $threshold, ): bool; public function blurImage( float $radius, float $sigma, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function borderImage( HH\FIXME\MISSING_PARAM_TYPE $bordercolor, int $width, int $height, ): bool; public function charcoalImage(float $radius, float $sigma): bool; public function chopImage(int $width, int $height, int $x, int $y): bool; public function clear(): bool; public function clipImage(): bool; public function clipPathImage(string $pathname, bool $inside): bool; public function __clone(): void; public function clutImage( Imagick $lookup_table, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function coalesceImages(): Imagick; public function colorFloodfillImage( HH\FIXME\MISSING_PARAM_TYPE $fill, float $fuzz, HH\FIXME\MISSING_PARAM_TYPE $bordercolor, int $x, int $y, ): bool; public function colorizeImage( HH\FIXME\MISSING_PARAM_TYPE $colorize, HH\FIXME\MISSING_PARAM_TYPE $opacity, ): bool; public function combineImages(int $channelType): Imagick; public function commentImage(string $comment): bool; public function compareImageChannels( Imagick $image, int $channelType, int $metricType, ): varray<mixed>; public function compareImageLayers(int $method): Imagick; public function compareImages(Imagick $compare, int $metric): varray<mixed>; public function compositeImage( Imagick $composite_object, int $composite, int $x, int $y, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function __construct(HH\FIXME\MISSING_PARAM_TYPE $files = null); public function contrastImage(bool $sharpen): bool; public function contrastStretchImage( float $black_point, float $white_point, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function convolveImage( varray<mixed> $kernel, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function cropImage(int $width, int $height, int $x, int $y): bool; public function cropThumbnailImage(int $width, int $height): bool; public function current(): Imagick; public function cycleColormapImage(int $displace): bool; public function decipherImage(string $passphrase): bool; public function deconstructImages(): Imagick; public function deleteImageArtifact(string $artifact): bool; public function deskewImage(float $threshold): bool; public function despeckleImage(): bool; public function destroy(): bool; public function displayImage(string $servername): bool; public function displayImages(string $servername): bool; public function distortImage( int $method, varray<mixed> $arguments, bool $bestfit, ): bool; public function drawImage(ImagickDraw $draw): bool; public function edgeImage(float $radius): bool; public function embossImage(float $radius, float $sigma): bool; public function encipherImage(string $passphrase): bool; public function enhanceImage(): bool; public function equalizeImage(): bool; public function evaluateImage( int $op, float $constant, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function exportImagePixels( int $x, int $y, int $width, int $height, string $map, int $storage, ): varray<int>; public function extentImage(int $width, int $height, int $x, int $y): bool; public function flattenImages(): Imagick; public function flipImage(): bool; public function floodFillPaintImage( HH\FIXME\MISSING_PARAM_TYPE $fill, float $fuzz, HH\FIXME\MISSING_PARAM_TYPE $target, int $x, int $y, bool $invert, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function flopImage(): bool; public function frameImage( HH\FIXME\MISSING_PARAM_TYPE $matte_color, int $width, int $height, int $inner_bevel, int $outer_bevel, ): bool; public function functionImage( int $function, varray<mixed> $arguments, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function fxImage( string $expression, int $channel = \Imagick::CHANNEL_ALL, ): Imagick; public function gammaImage( float $gamma, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function gaussianBlurImage( float $radius, float $sigma, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function getColorspace(): int; public function getCompression(): int; public function getCompressionQuality(): int; public static function getCopyright(): string; public function getFilename(): string; public function getFont(): string; public function getFormat(): string; public function getGravity(): int; public static function getHomeURL(): string; public function getImage(): Imagick; public function getImageAlphaChannel(): int; public function getImageArtifact(string $artifact): string; public function getImageBackgroundColor(): ImagickPixel; public function getImageBlob(): string; public function getImageBluePrimary(): darray<arraykey, mixed>; public function getImageBorderColor(): ImagickPixel; public function getImageChannelDepth(int $channel): int; public function getImageChannelDistortion( Imagick $reference, int $channel, int $metric, ): float; public function getImageChannelDistortions( Imagick $reference, int $metric, int $channel = \Imagick::CHANNEL_DEFAULT, ): float; public function getImageChannelExtrema(int $channel): darray<arraykey, mixed>; public function getImageChannelKurtosis( int $channel = \Imagick::CHANNEL_DEFAULT, ): darray<arraykey, mixed>; public function getImageChannelMean(int $channel): darray<arraykey, mixed>; public function getImageChannelRange(int $channel): darray<arraykey, mixed>; public function getImageChannelStatistics(): darray<arraykey, mixed>; public function getImageClipMask(): Imagick; public function getImageColormapColor(int $index): ImagickPixel; public function getImageColors(): int; public function getImageColorspace(): int; public function getImageCompose(): int; public function getImageCompression(): int; public function getImageDelay(): int; public function getImageDepth(): int; public function getImageDispose(): int; /** HHVM doesn't support MagickWand: public function getImageDistortion( MagickWand $reference, int $metric, ): float; */ public function getImageExtrema(): darray<arraykey, mixed>; public function getImageFilename(): string; public function getImageFormat(): string; public function getImageGamma(): float; public function getImageGeometry(): darray<string, int>; public function getImageGravity(): int; public function getImageGreenPrimary(): darray<arraykey, mixed>; public function getImageHeight(): int; public function getImageHistogram(): varray<ImagickPixel>; public function getImageIndex(): int; public function getImageInterlaceScheme(): int; public function getImageInterpolateMethod(): int; public function getImageIterations(): int; public function getImageLength(): int; public function getImageMatte(): bool; public function getImageMatteColor(): ImagickPixel; public function getImageMimeType(): string; public function getImageOrientation(): int; public function getImagePage(): darray<arraykey, mixed>; public function getImagePixelColor(int $x, int $y): ImagickPixel; public function getImageProfile(string $name): string; public function getImageProfiles( string $pattern = "*", bool $with_values = true, ): varray_or_darray<arraykey, mixed>; public function getImageProperties( string $pattern = "*", bool $with_values = true, ): varray_or_darray<arraykey, mixed>; public function getImageProperty(string $name): string; public function getImageRedPrimary(): darray<arraykey, mixed>; public function getImageRegion( int $width, int $height, int $x, int $y, ): Imagick; public function getImageRenderingIntent(): int; public function getImageResolution(): darray<string, float>; public function getImagesBlob(): string; public function getImageScene(): int; public function getImageSignature(): string; public function getImageSize(): int; public function getImageTicksPerSecond(): int; public function getImageTotalInkDensity(): float; public function getImageType(): int; public function getImageUnits(): int; public function getImageVirtualPixelMethod(): int; public function getImageWhitePoint(): darray<arraykey, mixed>; public function getImageWidth(): int; public function getInterlaceScheme(): int; public function getIteratorIndex(): int; public function getNumberImages(): int; public function getOption(string $key): string; public static function getPackageName(): string; public function getPage(): darray<arraykey, mixed>; public function getPixelIterator(): ImagickPixelIterator; public function getPixelRegionIterator( int $x, int $y, int $columns, int $rows, ): ImagickPixelIterator; public function getPointSize(): float; public static function getQuantumDepth(): darray<arraykey, mixed>; public static function getQuantumRange(): darray<arraykey, mixed>; public static function getReleaseDate(): string; public static function getResource(int $type): int; public static function getResourceLimit(int $type): int; public function getSamplingFactors(): varray<mixed>; public function getSize(): darray<arraykey, mixed>; public function getSizeOffset(): int; public static function getVersion(): darray<arraykey, mixed>; public function haldClutImage( Imagick $clut, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function hasNextImage(): bool; public function hasPreviousImage(): bool; public function identifyImage(bool $appendRawOutput = false): darray<arraykey, mixed>; public function implodeImage(float $radius): bool; public function importImagePixels( int $x, int $y, int $width, int $height, string $map, int $storage, varray<mixed> $pixels, ): bool; public function labelImage(string $label): bool; public function levelImage( float $blackPoint, float $gamma, float $whitePoint, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function linearStretchImage( float $blackPoint, float $whitePoint, ): bool; public function liquidRescaleImage( int $width, int $height, float $delta_x, float $rigidity, ): bool; public function magnifyImage(): bool; public function mapImage(Imagick $map, bool $dither): bool; public function matteFloodfillImage( float $alpha, float $fuzz, HH\FIXME\MISSING_PARAM_TYPE $bordercolor, int $x, int $y, ): bool; public function medianFilterImage(float $radius): bool; public function mergeImageLayers(int $layer_method): Imagick; public function minifyImage(): bool; public function modulateImage( float $brightness, float $saturation, float $hue, ): bool; public function montageImage( ImagickDraw $draw, string $tile_geometry, string $thumbnail_geometry, int $mode, string $frame, ): Imagick; public function morphImages(int $number_frames): Imagick; public function mosaicImages(): Imagick; public function motionBlurImage( float $radius, float $sigma, float $angle, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function negateImage( bool $gray, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function newImage( int $cols, int $rows, HH\FIXME\MISSING_PARAM_TYPE $background, string $format = "", ): bool; public function newPseudoImage( int $columns, int $rows, string $pseudoString, ): bool; public function nextImage(): bool; public function normalizeImage(int $channel = \Imagick::CHANNEL_ALL): bool; public function oilPaintImage(float $radius): bool; public function opaquePaintImage( HH\FIXME\MISSING_PARAM_TYPE $target, HH\FIXME\MISSING_PARAM_TYPE $fill, float $fuzz, bool $invert, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function optimizeImageLayers(): Imagick; public function orderedPosterizeImage( string $threshold_map, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function paintFloodfillImage( HH\FIXME\MISSING_PARAM_TYPE $fill, float $fuzz, HH\FIXME\MISSING_PARAM_TYPE $bordercolor, int $x, int $y, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function paintOpaqueImage( HH\FIXME\MISSING_PARAM_TYPE $target, HH\FIXME\MISSING_PARAM_TYPE $fill, float $fuzz, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function paintTransparentImage( HH\FIXME\MISSING_PARAM_TYPE $target, float $alpha, float $fuzz, ): bool; public function pingImage(string $filename): bool; public function pingImageBlob(string $image): bool; public function pingImageFile(resource $filehandle, string $fileName): bool; public function polaroidImage(ImagickDraw $properties, float $angle): bool; public function posterizeImage(int $levels, bool $dither): bool; public function previewImages(int $preview): Imagick; public function previousImage(): bool; public function profileImage(string $name, string $profile): bool; public function quantizeImage( int $numberColors, int $colorspace, int $treedepth, bool $dither, bool $measureError, ): bool; public function quantizeImages( int $numberColors, int $colorspace, int $treedepth, bool $dither, bool $measureError, ): bool; public function queryFontMetrics( ImagickDraw $properties, string $text, HH\FIXME\MISSING_PARAM_TYPE $multiline = null, ): darray<arraykey, mixed>; public static function queryFonts(string $pattern = "*"): varray<mixed>; public static function queryFormats(string $pattern = "*"): varray<mixed>; public function radialBlurImage( float $angle, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function raiseImage( int $width, int $height, int $x, int $y, bool $raise, ): bool; public function randomThresholdImage( float $low, float $high, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function readImage(string $filename): bool; public function readImageBlob(string $image, string $filename = ""): bool; public function readImageFile( resource $filehandle, string $fileName = "", ): bool; public function readImages(varray<mixed> $files): bool; public function recolorImage(varray<mixed> $matrix): bool; public function reduceNoiseImage(float $radius): bool; public function remapImage(Imagick $replacement, int $dither): bool; public function removeImage(): bool; public function removeImageProfile(string $name): string; public function resampleImage( float $x_resolution, float $y_resolution, int $filter, float $blur, ): bool; public function resetImagePage(string $page): bool; public function resizeImage( int $columns, int $rows, int $filter, float $blur, bool $bestfit = false, ): bool; public function rollImage(int $x, int $y): bool; public function rotateImage( HH\FIXME\MISSING_PARAM_TYPE $background, float $degrees, ): bool; public function roundCorners( float $x_rounding, float $y_rounding, float $stroke_width = 10.0, float $displace = 5.0, float $size_correction = -6.0, ): bool; public function roundCornersImage( float $x_rounding, float $y_rounding, float $stroke_width = 10.0, float $displace = 5.0, float $size_correction = -6.0, ): bool; public function sampleImage(int $columns, int $rows): bool; public function scaleImage(int $cols, int $rows, bool $bestfit = false): bool; public function segmentImage( int $COLORSPACE, float $cluster_threshold, float $smooth_threshold, bool $verbose = false, ): bool; public function separateImageChannel(int $channel): bool; public function sepiaToneImage(float $threshold): bool; public function setBackgroundColor( HH\FIXME\MISSING_PARAM_TYPE $background, ): bool; public function setColorspace(int $COLORSPACE): bool; public function setCompression(int $compression): bool; public function setCompressionQuality(int $quality): bool; public function setFilename(string $filename): bool; public function setFirstIterator(): bool; public function setFont(string $font): bool; public function setFormat(string $format): bool; public function setGravity(int $gravity): bool; public function setImage(Imagick $replace): bool; public function setImageAlphaChannel(int $mode): bool; public function setImageArtifact(string $artifact, string $value): bool; public function setImageBackgroundColor( HH\FIXME\MISSING_PARAM_TYPE $background, ): bool; public function setImageBias(float $bias): bool; public function setImageBluePrimary(float $x, float $y): bool; public function setImageBorderColor( HH\FIXME\MISSING_PARAM_TYPE $border, ): bool; public function setImageChannelDepth(int $channel, int $depth): bool; public function setImageClipMask(Imagick $clip_mask): bool; public function setImageColormapColor( int $index, HH\FIXME\MISSING_PARAM_TYPE $color, ): bool; public function setImageColorspace(int $colorspace): bool; public function setImageCompose(int $compose): bool; public function setImageCompression(int $compression): bool; public function setImageCompressionQuality(int $quality): bool; public function setImageDelay(int $delay): bool; public function setImageDepth(int $depth): bool; public function setImageDispose(int $dispose): bool; public function setImageExtent(int $columns, int $rows): bool; public function setImageFilename(string $filename): bool; public function setImageFormat(string $format): bool; public function setImageGamma(float $gamma): bool; public function setImageGravity(int $gravity): bool; public function setImageGreenPrimary(float $x, float $y): bool; public function setImageIndex(int $index): bool; public function setImageInterlaceScheme(int $interlace_scheme): bool; public function setImageInterpolateMethod(int $method): bool; public function setImageIterations(int $iterations): bool; public function setImageMatte(bool $matte): bool; public function setImageMatteColor(HH\FIXME\MISSING_PARAM_TYPE $matte): bool; public function setImageOpacity(float $opacity): bool; public function setImageOrientation(int $orientation): bool; public function setImagePage(int $width, int $height, int $x, int $y): bool; public function setImageProfile(string $name, string $profile): bool; public function setImageProperty(string $name, string $value): bool; public function setImageRedPrimary(float $x, float $y): bool; public function setImageRenderingIntent(int $rendering_intent): bool; public function setImageResolution( float $x_resolution, float $y_resolution, ): bool; public function setImageScene(int $scene): bool; public function setImageTicksPerSecond(int $ticks_per_second): bool; public function setImageType(int $image_type): bool; public function setImageUnits(int $units): bool; public function setImageVirtualPixelMethod(int $method): bool; public function setImageWhitePoint(float $x, float $y): bool; public function setInterlaceScheme(int $interlace_scheme): bool; public function setIteratorIndex(int $index): bool; public function setLastIterator(): bool; public function setOption(string $key, string $value): bool; public function setPage(int $width, int $height, int $x, int $y): bool; public function setPointSize(float $point_size): bool; public function setResolution(float $x_resolution, float $y_resolution): bool; public static function setResourceLimit(int $type, int $limit): bool; public function setSamplingFactors(varray<mixed> $factors): bool; public function setSize(int $columns, int $rows): bool; public function setSizeOffset(int $columns, int $rows, int $offset): bool; public function setType(int $image_type): bool; public function shadeImage( bool $gray, float $azimuth, float $elevation, ): bool; public function shadowImage( float $opacity, float $sigma, int $x, int $y, ): bool; public function sharpenImage( float $radius, float $sigma, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function shaveImage(int $columns, int $rows): bool; public function shearImage( HH\FIXME\MISSING_PARAM_TYPE $background, float $x_shear, float $y_shear, ): bool; public function sigmoidalContrastImage( bool $sharpen, float $alpha, float $beta, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function sketchImage(float $radius, float $sigma, float $angle): bool; public function solarizeImage(int $threshold): bool; public function sparseColorImage( int $SPARSE_METHOD, varray<mixed> $arguments, int $channel = \Imagick::CHANNEL_DEFAULT, ): bool; public function spliceImage(int $width, int $height, int $x, int $y): bool; public function spreadImage(float $radius): bool; public function steganoImage(Imagick $watermark_wand, int $offset): Imagick; public function stereoImage(Imagick $offset_wand): Imagick; public function stripImage(): bool; public function swirlImage(float $degrees): bool; public function textureImage(Imagick $texture_wand): Imagick; public function thresholdImage( float $threshold, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function thumbnailImage( int $columns, int $rows, bool $bestfit = false, bool $fill = false, ): bool; public function tintImage( HH\FIXME\MISSING_PARAM_TYPE $tint, HH\FIXME\MISSING_PARAM_TYPE $opacity, ): bool; public function transformImage(string $crop, string $geometry): Imagick; public function transparentPaintImage( HH\FIXME\MISSING_PARAM_TYPE $target, float $alpha, float $fuzz, bool $invert, ): bool; public function transposeImage(): bool; public function transverseImage(): bool; public function trimImage(float $fuzz): bool; public function uniqueImageColors(): bool; public function unsharpMaskImage( float $radius, float $sigma, float $amount, float $threshold, int $channel = \Imagick::CHANNEL_ALL, ): bool; public function valid(): bool; public function vignetteImage( float $blackPoint, float $whitePoint, int $x, int $y, ): bool; public function waveImage(float $amplitude, float $length): bool; public function whiteThresholdImage( HH\FIXME\MISSING_PARAM_TYPE $threshold, ): bool; public function writeImage(string $filename = ""): bool; public function writeImageFile( resource $filehandle, string $format = "", ): bool; public function writeImages(string $filename, bool $adjoin): bool; public function writeImagesFile( resource $filehandle, string $format = "", ): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/imagick/ImagickDraw.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class ImagickDraw { // Methods public function affine(darray<arraykey, mixed> $affine): bool; public function annotation(float $x, float $y, string $text): bool; public function arc( float $sx, float $sy, float $ex, float $ey, float $sd, float $ed, ): bool; public function bezier(varray<mixed> $coordinates): bool; public function circle(float $ox, float $oy, float $px, float $py): bool; public function clear(): bool; public function __clone(): void; public function color(float $x, float $y, int $paintMethod): bool; public function comment(string $comment): bool; public function composite( int $compose, float $x, float $y, float $width, float $height, Imagick $compositeWand, ): bool; public function __construct(); public function destroy(): bool; public function ellipse( float $ox, float $oy, float $rx, float $ry, float $start, float $end, ): bool; public function getClipPath(): string; public function getClipRule(): int; public function getClipUnits(): int; public function getFillColor(): ImagickPixel; public function getFillOpacity(): float; public function getFillRule(): int; public function getFont(): string; public function getFontFamily(): string; public function getFontSize(): float; public function getFontStretch(): int; public function getFontStyle(): int; public function getFontWeight(): int; public function getGravity(): int; public function getStrokeAntialias(): bool; public function getStrokeColor(): ImagickPixel; public function getStrokeDashArray(): varray<mixed>; public function getStrokeDashOffset(): float; public function getStrokeLineCap(): int; public function getStrokeLineJoin(): int; public function getStrokeMiterLimit(): int; public function getStrokeOpacity(): float; public function getStrokeWidth(): float; public function getTextAlignment(): int; public function getTextAntialias(): bool; public function getTextDecoration(): int; public function getTextEncoding(): string; public function getTextUnderColor(): ImagickPixel; public function getVectorGraphics(): string; public function line(float $sx, float $sy, float $ex, float $ey): bool; public function matte(float $x, float $y, int $paintMethod): bool; public function pathClose(): bool; public function pathCurveToAbsolute( float $x1, float $y1, float $x2, float $y2, float $x, float $y, ): bool; public function pathCurveToQuadraticBezierAbsolute( float $x1, float $y1, float $x, float $y, ): bool; public function pathCurveToQuadraticBezierRelative( float $x1, float $y1, float $x, float $y, ): bool; public function pathCurveToQuadraticBezierSmoothAbsolute( float $x, float $y, ): bool; public function pathCurveToQuadraticBezierSmoothRelative( float $x, float $y, ): bool; public function pathCurveToRelative( float $x1, float $y1, float $x2, float $y2, float $x, float $y, ): bool; public function pathCurveToSmoothAbsolute( float $x2, float $y2, float $x, float $y, ): bool; public function pathCurveToSmoothRelative( float $x2, float $y2, float $x, float $y, ): bool; public function pathEllipticArcAbsolute( float $rx, float $ry, float $x_axis_rotation, bool $large_arc_flag, bool $sweep_flag, float $x, float $y, ): bool; public function pathEllipticArcRelative( float $rx, float $ry, float $x_axis_rotation, bool $large_arc_flag, bool $sweep_flag, float $x, float $y, ): bool; public function pathFinish(): bool; public function pathLineToAbsolute(float $x, float $y): bool; public function pathLineToHorizontalAbsolute(float $x): bool; public function pathLineToHorizontalRelative(float $x): bool; public function pathLineToRelative(float $x, float $y): bool; public function pathLineToVerticalAbsolute(float $y): bool; public function pathLineToVerticalRelative(float $y): bool; public function pathMoveToAbsolute(float $x, float $y): bool; public function pathMoveToRelative(float $x, float $y): bool; public function pathStart(): bool; public function point(float $x, float $y): bool; public function polygon(varray<mixed> $coordinates): bool; public function polyline(varray<mixed> $coordinates): bool; public function pop(): bool; public function popClipPath(): bool; public function popDefs(): bool; public function popPattern(): bool; public function push(): bool; public function pushClipPath(string $clip_mask_id): bool; public function pushDefs(): bool; public function pushPattern( string $pattern_id, float $x, float $y, float $width, float $height, ): bool; public function rectangle(float $x1, float $y1, float $x2, float $y2): bool; public function render(): bool; public function rotate(float $degrees): bool; public function roundRectangle( float $x1, float $y1, float $x2, float $y2, float $rx, float $ry, ): bool; public function scale(float $x, float $y): bool; public function setClipPath(string $clip_mask): bool; public function setClipRule(int $fill_rule): bool; public function setClipUnits(int $clip_units): bool; public function setFillAlpha(float $opacity): bool; public function setFillColor(HH\FIXME\MISSING_PARAM_TYPE $fill_pixel): bool; public function setFillOpacity(float $fillOpacity): bool; public function setFillPatternURL(string $fill_url): bool; public function setFillRule(int $fill_rule): bool; public function setFont(string $font_name): bool; public function setFontFamily(string $font_family): bool; public function setFontSize(float $pointsize): bool; public function setFontStretch(int $fontStretch): bool; public function setFontStyle(int $style): bool; public function setFontWeight(int $font_weight): bool; public function setGravity(int $gravity): bool; public function setResolution(float $x, float $y): bool; public function setStrokeAlpha(float $opacity): bool; public function setStrokeAntialias(bool $stroke_antialias): bool; public function setStrokeColor( HH\FIXME\MISSING_PARAM_TYPE $stroke_pixel, ): bool; public function setStrokeDashArray(varray<mixed> $dashArray): bool; public function setStrokeDashOffset(float $dash_offset): bool; public function setStrokeLineCap(int $linecap): bool; public function setStrokeLineJoin(int $linejoin): bool; public function setStrokeMiterLimit(int $miterlimit): bool; public function setStrokeOpacity(float $stroke_opacity): bool; public function setStrokePatternURL(string $stroke_url): bool; public function setStrokeWidth(float $stroke_width): bool; public function setTextAlignment(int $alignment): bool; public function setTextAntialias(bool $antiAlias): bool; public function setTextDecoration(int $decoration): bool; public function setTextEncoding(string $encoding): bool; public function setTextUnderColor( HH\FIXME\MISSING_PARAM_TYPE $under_color, ): bool; public function setVectorGraphics(string $xml): bool; public function setViewbox(int $x1, int $y1, int $x2, int $y2): bool; public function skewX(float $degrees): bool; public function skewY(float $degrees): bool; public function translate(float $x, float $y): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/imagick/ImagickException.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class ImagickException extends RuntimeException implements StringishObject {}
HTML Help Workshop
hhvm/hphp/hack/hhi/imagick/ImagickPixel.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class ImagickPixel { // Methods public function clear(): bool; public function __construct(string $color = ""); public function destroy(): bool; public function getColor(bool $normalized = false): darray<string, num>; public function getColorAsString(): string; public function getColorCount(): int; public function getColorValue(int $color): float; public function getHSL(): darray<arraykey, mixed>; public function isPixelSimilar( HH\FIXME\MISSING_PARAM_TYPE $color, float $fuzz, ): bool; public function isSimilar( HH\FIXME\MISSING_PARAM_TYPE $color, float $fuzz, ): bool; public function setColor(string $color): bool; public function setColorValue(int $color, float $value): bool; public function setHSL( float $hue, float $saturation, float $luminosity, ): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/imagick/ImagickPixelIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class ImagickPixelIterator implements KeyedTraversable<int, varray<ImagickPixel>>, Iterator<varray<ImagickPixel>> { // Methods public static function getPixelIterator(Imagick $wand): ImagickPixelIterator; public static function getPixelRegionIterator( Imagick $wand, int $x, int $y, int $columns, int $rows, ): ImagickPixelIterator; public function current(): varray<ImagickPixel>; public function key(): int; public function next(): void; public function rewind(): void; public function valid(): bool; public function clear(): bool; public function __construct(Imagick $wand); public function destroy(): bool; public function getCurrentIteratorRow(): varray<ImagickPixel>; public function getIteratorRow(): int; public function getNextIteratorRow(): varray<ImagickPixel>; public function getPreviousIteratorRow(): varray<ImagickPixel>; public function newPixelIterator(Imagick $wand): bool; public function newPixelRegionIterator( Imagick $wand, int $x, int $y, int $columns, int $rows, ): bool; public function resetIterator(): bool; public function setIteratorFirstRow(): bool; public function setIteratorLastRow(): bool; public function setIteratorRow(int $row): bool; public function syncIterator(): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/ArrayIterator.hhi
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ /** * This file provides type information for some of PHP's predefined interfaces * * YOU SHOULD NEVER INCLUDE THIS FILE ANYWHERE!!! */ class ArrayIterator<T> implements KeyedIterator<arraykey, T>, KeyedTraversable<arraykey, T> /* Serializable - not implemented */ { public function __construct(mixed $array); public function current(): T; public function getFlags(): void; public function key(): arraykey; public function next(): void; public function rewind(): void; public function setFlags(string $flags): void; public function valid(): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/EmptyIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ final class EmptyIterator implements Iterator<nothing> { /* Both current() and key() on an EmptyIterator throw unconditionally */ public function current(): nothing; public function key(): nothing; public function next(): void; public function rewind(): void; public function valid(): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/FilesystemIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class FilesystemIterator extends DirectoryIterator { // Constants const int CURRENT_AS_PATHNAME; const int CURRENT_AS_FILEINFO; const int CURRENT_AS_SELF; const int CURRENT_MODE_MASK; const int KEY_AS_PATHNAME; const int KEY_AS_FILENAME; const int FOLLOW_SYMLINKS; const int KEY_MODE_MASK; const int NEW_CURRENT_AND_KEY; const int SKIP_DOTS; const int UNIX_PATHS; // Properties protected HH\FIXME\MISSING_PROP_TYPE $flags; // Methods public function __construct( HH\FIXME\MISSING_PARAM_TYPE $path, HH\FIXME\MISSING_PARAM_TYPE $flags = null, ); public function current(): HH\FIXME\POISON_MARKER<SplFileInfo>; public function getFlags(): HH\FIXME\MISSING_RETURN_TYPE; public function key(): HH\FIXME\MISSING_RETURN_TYPE; public function next(): void; public function rewind(): void; public function setFlags(int $flags): HH\FIXME\MISSING_RETURN_TYPE; public function seek(int $position): void; public function __toString(): string; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/FilterIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ abstract class FilterIterator<Tv> extends IteratorIterator<Tv> { // Methods public function __construct(Iterator<Tv> $it); public function rewind(): void; public abstract function accept(): bool; public function next(): void; public function valid(): bool; public function key(): HH\FIXME\MISSING_RETURN_TYPE; public function current(): HH\FIXME\POISON_MARKER<Tv>; protected function __clone(): HH\FIXME\MISSING_RETURN_TYPE; public function call__( HH\FIXME\MISSING_PARAM_TYPE $func, HH\FIXME\MISSING_PARAM_TYPE $params, ): HH\FIXME\MISSING_RETURN_TYPE; public function getInnerIterator(): Iterator<Tv>; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/IteratorIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class IteratorIterator<Tv> implements OuterIterator<HH\FIXME\POISON_MARKER<Tv>> { // Methods public function __construct(Traversable<Tv> $iterator); public function getInnerIterator(): Iterator<Tv>; public function valid(): bool; public function key(): HH\FIXME\MISSING_RETURN_TYPE; public function current(): HH\FIXME\POISON_MARKER<Tv>; public function next(): void; public function rewind(): void; public function call__( HH\FIXME\MISSING_PARAM_TYPE $func, HH\FIXME\MISSING_PARAM_TYPE $params, ): HH\FIXME\MISSING_RETURN_TYPE; protected function _fetch( HH\FIXME\MISSING_PARAM_TYPE $check, ): HH\FIXME\MISSING_RETURN_TYPE; protected function _getPosition(): HH\FIXME\MISSING_RETURN_TYPE; protected function _setPosition( HH\FIXME\MISSING_PARAM_TYPE $position, ): HH\FIXME\MISSING_RETURN_TYPE; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/RecursiveDirectoryIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class RecursiveDirectoryIterator extends FilesystemIterator implements RecursiveIterator<HH\FIXME\POISON_MARKER<SplFileInfo>> { // Constants const int FOLLOW_SYMLINKS; // Methods public function __construct( HH\FIXME\MISSING_PARAM_TYPE $path, HH\FIXME\MISSING_PARAM_TYPE $flags = null, ); public function hasChildren(): bool; // implementation can also return string or false public function getChildren(): HH\FIXME\POISON_MARKER<this>; public function getSubPath(): HH\FIXME\MISSING_RETURN_TYPE; public function getSubPathname(): HH\FIXME\MISSING_RETURN_TYPE; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/RecursiveFilterIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ abstract class RecursiveFilterIterator<Tv> extends FilterIterator<Tv> implements OuterIterator<HH\FIXME\POISON_MARKER<Tv>>, RecursiveIterator<HH\FIXME\POISON_MARKER<Tv>> { // Methods public function __construct(RecursiveIterator<Tv> $iterator); public function getChildren(): this; public function hasChildren(): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/RecursiveIteratorIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class RecursiveIteratorIterator<Tv> implements OuterIterator<Tv> { // Constants const int LEAVES_ONLY; const int SELF_FIRST; const int CHILD_FIRST; const int CATCH_GET_CHILD; const int STATE_NEXT; const int STATE_TEST; const int STATE_SELF; const int STATE_CHILD; const int STATE_START; const int NEXT_COMPLETE; const int NEXT_REPEAT; // Methods public function __construct( Traversable<Tv> $iterator, HH\FIXME\MISSING_PARAM_TYPE $mode = RecursiveIteratorIterator::LEAVES_ONLY, HH\FIXME\MISSING_PARAM_TYPE $flags = 0, ); public function getInnerIterator(): Iterator<Tv>; public function current(): Tv; public function key(): HH\FIXME\MISSING_RETURN_TYPE; public function next(): void; public function rewind(): void; public function valid(): bool; public function beginChildren(): HH\FIXME\MISSING_RETURN_TYPE; public function beginIteration(): HH\FIXME\MISSING_RETURN_TYPE; public function callGetChildren(): HH\FIXME\MISSING_RETURN_TYPE; public function callHasChildren(): HH\FIXME\MISSING_RETURN_TYPE; public function endChildren(): HH\FIXME\MISSING_RETURN_TYPE; public function endIteration(): HH\FIXME\MISSING_RETURN_TYPE; public function getDepth(): HH\FIXME\MISSING_RETURN_TYPE; public function getMaxDepth(): HH\FIXME\MISSING_RETURN_TYPE; public function getSubIterator( HH\FIXME\MISSING_PARAM_TYPE $level = null, ): HH\FIXME\MISSING_RETURN_TYPE; public function nextElement(): HH\FIXME\MISSING_RETURN_TYPE; public function setMaxDepth( HH\FIXME\MISSING_PARAM_TYPE $max_depth = -1, ): HH\FIXME\MISSING_RETURN_TYPE; public function call__( HH\FIXME\MISSING_PARAM_TYPE $func, HH\FIXME\MISSING_PARAM_TYPE $params, ): HH\FIXME\MISSING_RETURN_TYPE; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/RecursiveRegexIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class RecursiveRegexIterator<Tv> extends RegexIterator<Tv> implements RecursiveIterator<HH\FIXME\POISON_MARKER<Tv>> { // Methods public function __construct( RecursiveIterator<Tv> $iterator, string $regex, int $mode = \RecursiveRegexIterator::MATCH, int $flags = 0, int $preg_flags = 0, ); public function accept(): bool; public function getChildren(): this; public function hasChildren(): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/RegexIterator.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class RegexIterator<Tv> extends FilterIterator<Tv> { // Constants const int MATCH; const int GET_MATCH; const int ALL_MATCHES; const int SPLIT; const int REPLACE; const int USE_KEY; const int INVERT_MATCH; // Methods public function __construct( Iterator<Tv> $iterator, string $regex, int $mode = \RegexIterator::MATCH, int $flags = 0, int $preg_flags = 0, ); public function accept(): bool; public function getRegex(): HH\FIXME\MISSING_RETURN_TYPE; public function getMode(): int; public function getFlags(): int; public function getPregFlags(): int; public function setMode(int $mode): void; public function setFlags(int $flags): void; public function setPregFlags(int $preg_flags): void; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/SplHeap.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ abstract class SplHeap<T> implements Iterator<T>, Countable, Traversable<T> { // Methods public function __construct(); abstract protected function compare(T $value1, T $value2): int; public function extract(): T; public function insert(T $value): void; public function isEmpty(): bool; public function recoverFromCorruption(): void; public function count(): int; public function current(): T; public function key(): int; public function next(): void; public function rewind(): void; public function top(): T; public function valid(): bool; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/SplMaxHeap.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class SplMaxHeap<T> extends SplHeap<T> { // Methods protected function compare(T $value1, T $value2): int; }
HTML Help Workshop
hhvm/hphp/hack/hhi/spl/SplMinHeap.hhi
<?hh /* -*- mode: php -*- */ /** * Copyright (c) 2014, 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. * */ class SplMinHeap<T> extends SplHeap<T> { // Methods protected function compare(T $value1, T $value2): int; }
HTML Help Workshop
hhvm/hphp/hack/hhi/stdlib/builtins_apache.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, 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. * */ <<__PHPStdLib>> function apache_note( string $note_name, HH\FIXME\MISSING_PARAM_TYPE $note_value = "", ): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apache_notes(dict<string, string> $notes): void {} <<__PHPStdLib>> function apache_request_headers(): darray<string, string> {} <<__PHPStdLib>> function apache_response_headers(): darray<string, string> {} <<__PHPStdLib>> function apache_setenv( string $variable, string $value, bool $walk_to_top = false, ): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function getallheaders()[read_globals]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function virtual( HH\FIXME\MISSING_PARAM_TYPE $filename, ): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apache_get_config(): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apache_get_rewrite_rules(): HH\FIXME\MISSING_RETURN_TYPE {}
HTML Help Workshop
hhvm/hphp/hack/hhi/stdlib/builtins_apc.hhi
<?hh /** * Copyright (c) 2014, 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. * */ <<__PHPStdLib>> function apc_add( HH\FIXME\MISSING_PARAM_TYPE $key, HH\FIXME\MISSING_PARAM_TYPE $var, int $ttl = 0, int $bump_ttl = 0, )[defaults]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_add_with_pure_sleep( HH\FIXME\MISSING_PARAM_TYPE $key, HH\FIXME\MISSING_PARAM_TYPE $var, int $ttl = 0, int $bump_ttl = 0, )[globals]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function apc_store( HH\FIXME\MISSING_PARAM_TYPE $key, HH\FIXME\MISSING_PARAM_TYPE $var, int $ttl = 0, int $bump_ttl = 0, )[defaults]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_store_with_pure_sleep( HH\FIXME\MISSING_PARAM_TYPE $key, HH\FIXME\MISSING_PARAM_TYPE $var, int $ttl = 0, int $bump_ttl = 0, )[globals]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function apc_fetch( HH\FIXME\MISSING_PARAM_TYPE $key, inout ?bool $success, )[defaults]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_fetch_with_pure_wakeup( HH\FIXME\MISSING_PARAM_TYPE $key, inout ?bool $success, )[read_globals]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function apc_delete( HH\FIXME\MISSING_PARAM_TYPE $key, )[globals]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_cache_info( string $cache_type = "", bool $limited = false, )[read_globals]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_clear_cache(string $cache_id = "")[globals]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_sma_info(bool $limited = false)[]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_inc( string $key, int $step, inout ?bool $success, )[globals]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_dec( string $key, int $step, inout ?bool $success, )[globals]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_cas( string $key, int $old_cas, int $new_cas, )[globals]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_exists( HH\FIXME\MISSING_PARAM_TYPE $key, )[read_globals]: HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apc_extend_ttl(string $key, int $ttl)[globals]: bool; <<__PHPStdLib>> function apc_size(string $key)[read_globals]: ?int; // The following are php std lib functions not supported by HHVM: // //function apc_compile_file($filename, $atomic = true, $cache_id = 0) { } //function apc_define_constants($key, $constants, $case_sensitive = true, $cache_id = 0) { } //function apc_load_constants($key, $case_sensitive = true, $cache_id = 0) { } //function apc_filehits() { } //function apc_delete_file($keys, $cache_id = 0) { } //function apc_bin_dump($cache_id = 0, $filter = null) { } //function apc_bin_load($data, $flags = 0, $cache_id = 0) { } //function apc_bin_dumpfile($cache_id, $filter, $filename, $flags = 0, $context = null) { } //function apc_bin_loadfile($filename, $context = null, $flags = 0, $cache_id = 0) { }
HTML Help Workshop
hhvm/hphp/hack/hhi/stdlib/builtins_apd.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, 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. * */ <<__PHPStdLib>> function override_function( HH\FIXME\MISSING_PARAM_TYPE $name, HH\FIXME\MISSING_PARAM_TYPE $args, HH\FIXME\MISSING_PARAM_TYPE $code, ): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function rename_function( HH\FIXME\MISSING_PARAM_TYPE $orig_name, HH\FIXME\MISSING_PARAM_TYPE $new_name, ): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apd_set_browser_trace(): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apd_set_pprof_trace( HH\FIXME\MISSING_PARAM_TYPE $dumpdir = null, HH\FIXME\MISSING_PARAM_TYPE $frament = null, ): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apd_set_session_trace_socket( HH\FIXME\MISSING_PARAM_TYPE $ip_or_filename, HH\FIXME\MISSING_PARAM_TYPE $domain, HH\FIXME\MISSING_PARAM_TYPE $port, HH\FIXME\MISSING_PARAM_TYPE $mask, ): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apd_stop_trace(): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apd_breakpoint(): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apd_continue(): HH\FIXME\MISSING_RETURN_TYPE {} <<__PHPStdLib>> function apd_echo( HH\FIXME\MISSING_PARAM_TYPE $output, ): HH\FIXME\MISSING_RETURN_TYPE {}
HTML Help Workshop
hhvm/hphp/hack/hhi/stdlib/builtins_array.hhi
<?hh /* -*- php -*- */ /** * Copyright (c) 2014, 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. * */ // flags for array_change_key_case() const int CASE_LOWER; const int CASE_UPPER; // flags for array_multisort const int SORT_ASC; const int SORT_DESC; // flags for sort() family const int SORT_REGULAR; const int SORT_NUMERIC; const int SORT_STRING; const int SORT_LOCALE_STRING; const int SORT_NATURAL; const int SORT_FLAG_CASE; // flags for count() const int COUNT_NORMAL; const int COUNT_RECURSIVE; const int UCOL_DEFAULT; const int UCOL_PRIMARY; const int UCOL_SECONDARY; const int UCOL_TERTIARY; const int UCOL_DEFAULT_STRENGTH; const int UCOL_QUATERNARY; const int UCOL_IDENTICAL; const int UCOL_OFF; const int UCOL_ON; const int UCOL_SHIFTED; const int UCOL_NON_IGNORABLE; const int UCOL_LOWER_FIRST; const int UCOL_UPPER_FIRST; const int UCOL_FRENCH_COLLATION; const int UCOL_ALTERNATE_HANDLING; const int UCOL_CASE_FIRST; const int UCOL_CASE_LEVEL; const int UCOL_NORMALIZATION_MODE; const int UCOL_STRENGTH; const int UCOL_HIRAGANA_QUATERNARY_MODE; const int UCOL_NUMERIC_COLLATION; const int TAG_PROVENANCE_HERE_MUTATE_COLLECTIONS; <<__PHPStdLib>> function array_change_key_case<Tv>( KeyedContainer<arraykey, Tv> $input, int $upper = CASE_LOWER, )[]: darray<arraykey, Tv>; /** inner container will be a varray<mixed> or darray<arraykey, mixed> depending on $preserve_keys */ <<__PHPStdLib>> function array_chunk<Tv>( Container<Tv> $input, int $size, bool $preserve_keys = false, )[]: varray<Container<int>>; <<__PHPStdLib>> function array_combine<Tv1 as arraykey, Tv2>( Container<Tv1> $keys, Container<Tv2> $values, )[]: darray<Tv1, Tv2>; <<__PHPStdLib>> function array_count_values<Tv as arraykey>( Container<Tv> $input, )[]: darray<Tv, int>; <<__PHPStdLib>> function array_column<Tv>( Container<KeyedContainer<arraykey, Tv>> $array, ?arraykey $column_key, )[]: varray_or_darray<Tv>; <<__PHPStdLib>> function array_fill_keys<Tk as arraykey, Tv>( Container<Tk> $keys, Tv $value, )[]: darray<Tk, Tv>; /** * `array_filter` returns a `KeyedContainer<_, _>` with the items that match * the predicate. * * This function is deprecated; please use `Dict\filter` or `Vec\filter` * instead, or the respective `filter_nulls` variant. * * `array_filter` used to have special typing to indicate: * - Whether or not it preserved the input type * - How it removed nulls upon not providing a callback * * These typing behaviors are now split into the aforementioned four Hack * Standard Library functions. */ <<__PHPStdLib>> function array_filter<Tk as arraykey, Tv>( KeyedContainer<Tk, Tv> $input, ?(function(Tv): bool) $callback = null, ): KeyedContainer<Tk, Tv>; <<__PHPStdLib>> function array_flip( HH\FIXME\MISSING_PARAM_TYPE $trans, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function key_exists( HH\FIXME\MISSING_PARAM_TYPE $key, HH\FIXME\MISSING_PARAM_TYPE $search, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_keys<Tk as arraykey>( KeyedContainer<Tk, mixed> $input, )[]: varray<Tk>; /** * `array_map` previously had it's signature rewritten based on the arity of * the call, to match runtime behaviors including: * - Preserving the input container type * - Allowing for `N` args and accepting a function of the same arity * * This runtime behavior still exists but this function is deprecated in favor * of HSL functions like `Vec\map` or `Dict\map`. */ <<__PHPStdLib>> function array_map<Tk as arraykey, Tin, Tout>( (function(Tin): Tout) $callback, KeyedContainer<Tk, Tin> $arr, ): KeyedContainer<Tk, Tout>; <<__PHPStdLib>> function array_merge_recursive( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_merge( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_replace_recursive( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_replace( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort1(inout mixed $arg1): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort2( inout mixed $arg1, inout mixed $arg2, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort3( inout mixed $arg1, inout mixed $arg2, inout mixed $arg3, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort4( inout mixed $arg1, inout mixed $arg2, inout mixed $arg3, inout mixed $arg4, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort5( inout mixed $arg1, inout mixed $arg2, inout mixed $arg3, inout mixed $arg4, inout mixed $arg5, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort6( inout mixed $arg1, inout mixed $arg2, inout mixed $arg3, inout mixed $arg4, inout mixed $arg5, inout mixed $arg6, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort7( inout mixed $arg1, inout mixed $arg2, inout mixed $arg3, inout mixed $arg4, inout mixed $arg5, inout mixed $arg6, inout mixed $arg7, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort8( inout mixed $arg1, inout mixed $arg2, inout mixed $arg3, inout mixed $arg4, inout mixed $arg5, inout mixed $arg6, inout mixed $arg7, inout mixed $arg8, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_multisort9( inout mixed $arg1, inout mixed $arg2, inout mixed $arg3, inout mixed $arg4, inout mixed $arg5, inout mixed $arg6, inout mixed $arg7, inout mixed $arg8, inout mixed $arg9, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_pad( HH\FIXME\MISSING_PARAM_TYPE $input, int $pad_size, HH\FIXME\MISSING_PARAM_TYPE $pad_value, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_pop( inout HH\FIXME\MISSING_PARAM_TYPE $array, )[write_props]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_push( inout HH\FIXME\MISSING_PARAM_TYPE $array, HH\FIXME\MISSING_PARAM_TYPE $var, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_rand( HH\FIXME\MISSING_PARAM_TYPE $input, int $num_req = 1, )[leak_safe]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_reduce( HH\FIXME\MISSING_PARAM_TYPE $input, HH\FIXME\MISSING_PARAM_TYPE $callback, HH\FIXME\MISSING_PARAM_TYPE $initial = null, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_reverse( HH\FIXME\MISSING_PARAM_TYPE $array, bool $preserve_keys = false, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_search( HH\FIXME\MISSING_PARAM_TYPE $needle, HH\FIXME\MISSING_PARAM_TYPE $haystack, bool $strict = false, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_shift<T>(inout T $array)[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_slice( HH\FIXME\MISSING_PARAM_TYPE $array, int $offset, HH\FIXME\MISSING_PARAM_TYPE $length = null, bool $preserve_keys = false, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_splice( inout mixed $input, int $offset, mixed $length = null, mixed $replacement = null, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_unique( HH\FIXME\MISSING_PARAM_TYPE $array, int $sort_flags = 2, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_unshift<T>( inout T $array, HH\FIXME\MISSING_PARAM_TYPE $var, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_values<Tv>(Container<Tv> $input)[]: varray<Tv>; <<__PHPStdLib>> function shuffle<T>(inout T $array)[leak_safe]: void; << __Deprecated( 'Use count(), it does the same thing as sizeof() in PHP and '. 'doesn\'t suggest that it\'s counting bytes.', ), __PHPStdLib, >> function sizeof( HH\FIXME\MISSING_PARAM_TYPE $var, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function hphp_get_iterator( HH\FIXME\MISSING_PARAM_TYPE $iterable, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function in_array( HH\FIXME\MISSING_PARAM_TYPE $needle, HH\FIXME\MISSING_PARAM_TYPE $haystack, bool $strict = false, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function range( HH\FIXME\MISSING_PARAM_TYPE $low, HH\FIXME\MISSING_PARAM_TYPE $high, HH\FIXME\MISSING_PARAM_TYPE $step = 1, )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_diff( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_udiff( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $data_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_diff_assoc( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_diff_uassoc( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $key_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_udiff_assoc( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $data_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_udiff_uassoc( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $data_compare_func, HH\FIXME\MISSING_PARAM_TYPE $key_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_diff_key( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_diff_ukey( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $key_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_intersect( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_uintersect( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $data_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_intersect_assoc( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_intersect_uassoc( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $key_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_uintersect_assoc( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $data_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_uintersect_uassoc( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $data_compare_func, HH\FIXME\MISSING_PARAM_TYPE $key_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_intersect_key( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE ...$args )[]: HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function array_intersect_ukey( HH\FIXME\MISSING_PARAM_TYPE $array1, HH\FIXME\MISSING_PARAM_TYPE $array2, HH\FIXME\MISSING_PARAM_TYPE $key_compare_func, HH\FIXME\MISSING_PARAM_TYPE ...$args ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function natsort( inout HH\FIXME\MISSING_PARAM_TYPE $array, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function natcasesort( inout HH\FIXME\MISSING_PARAM_TYPE $array, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function i18n_loc_get_default(): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function i18n_loc_set_default(string $locale): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function i18n_loc_set_attribute( int $attr, int $val, ): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function i18n_loc_set_strength(int $strength): HH\FIXME\MISSING_RETURN_TYPE; <<__PHPStdLib>> function i18n_loc_get_error_code(): HH\FIXME\MISSING_RETURN_TYPE;