language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Markdown
hhvm/hphp/hack/manual/hack/02-source-code-fundamentals/31-variables.md
A variable is a named area of data storage that has a type and a value. Distinct variables may have the same name provided they are in different [scopes](scope.md). A [constant](constants.md) is a variable that, once initialized, its value cannot be changed. Based on the context in which it is declared, a variable has a scope. The following kinds of variable may exist in a script: - [Local variable](#local-variables) - [Array element](#array-elements) - [Instance property](#instance-properties) - [Static property](#static-properties) - [Class and interface constant](#class-and-interface-constants) ## Local Variables Except for function parameters, a local variable is never defined explicitly; instead, it is created when it is first assigned a value. A local variable can be assigned to as a parameter in the parameter list of a function definition or inside any compound statement. It has function scope. Consider the following example: ```Hack function do_it(bool $p1): void { $count = 10; // ... if ($p1) { $message = "Can't open file."; // ... } // ... } function call_it(): void { do_it(true); } ``` Here, the parameter `$p1` (which is a local variable) takes on the value `true` when `do_it` is called. The local variables `$count` and `$message` take on the type of the respective value being assigned to them. Consider the following example: ```hack function f(): void { $lv = 1; echo "\$lv = $lv\n"; ++$lv; } <<__EntryPoint>> function main(): void { for ($i = 1; $i <= 3; ++$i) f(); } ``` In this example, the value of the local variable `$lv` is not preserved between the function calls, so this function `f` outputs "`$lv = 1`" each time. ## Array Elements An array is created via a vec-literal, a dict-literal, a keyset-literal. At the same time, one or more elements may be created for that array. New elements are inserted into an existing array via the [simple-assignment](../expressions-and-operators/assignment.md) operator in conjunction with the [subscript `[]`](../expressions-and-operators/subscript.md) operator. The scope of an array element is the same as the scope of that array's name. ```Hack $colors1 = vec["green", "yellow"]; // create a vec of two elements $colors1[] = "blue"; // add element 2 with value "blue" $colors2 = dict[]; // create an empty dict $colors2[4] = "black"; // create element 4 with value "black" ``` ## Instance Properties These are described in the [class instance properties](../classes/properties.md) section. They have class scope. ## Static Properties These are described in the [class static properties](../classes/properties.md) section. They have class scope. ## Class and Interface Constants These are described in the [class constants](../classes/constants.md) section. They have class or interface scope.
Markdown
hhvm/hphp/hack/manual/hack/02-source-code-fundamentals/34-script-inclusion.md
When creating large applications or building component libraries, it is useful to be able to break up the source code into small, manageable pieces each of which performs some specific task, and which can be shared somehow, and tested, maintained, and deployed individually. For example, a programmer might define a series of useful constants and use them in numerous and possibly unrelated applications. Likewise, a set of class definitions can be shared among numerous applications needing to create objects of those types. An *include file* is a file that is suitable for *inclusion* by another file. The file doing the including is the *including file*, while the one being included is the *included file*. A file can be either an including file or an included file, both, or neither. The recommended way to approach this is to [use an autoloader](/hack/getting-started/starting-a-real-project#starting-a-real-project__autoloading) - however, first you need to include the autoloader itself. The `require_once()` directive is used for this: ``` namespace MyProject; require_once(__DIR__.'/../vendor/autoload.hack'); <<__EntryPoint>> function main(): void { \Facebook\AutoloadMap\initialize(); someFunction(); } ``` The name used to specify an include file may contain an absolute or relative path; absolute paths are *strongly* recommended, using the `__DIR__` constant to resolve paths relative to the current file. `require_once()` will raise an error if the file can not be loaded (e.g. if it is inaccessible or does not exist) , and will only load the file once, even if `require_once()` is used multiple times with the same file. ## Future Changes We expect to make autoloading fully-automatic, and remove inclusion directives from the language. ## Legacy Issues For relative paths, the configuration directive [`include_path`](https://docs.hhvm.com/hhvm/configuration/INI-settings#supported-php-ini-settings) is used to resolve the include file's location. It is currently possible (though strongly discoraged) for top-level code to exist in a file, without being in a function. In this cases, including a file may execute code, not just import definitions. Several additional directives exist, but are strongly discouraged: - `require()`: like `require_once()`, but will potentially include a file multiple times - `include()`: like `require()`, but does not raise an error if the file is inaccessible - `include_once()`: like `require_once()`, but does not raise an error if the file is inaccessible.
Markdown
hhvm/hphp/hack/manual/hack/02-source-code-fundamentals/37-namespaces.md
A ***namespace*** is a container for a set of (typically related) definitions of classes, interfaces, traits, functions, and constants. When the same namespace is declared across multiple scripts, and those scripts are combined into the same program, the resulting namespace is the union of all of the namespaces' individual components. ## The Root Namespace In the absence of any namespace definition, the names of subsequent classes, interfaces, traits, functions, and constants are in the ***root namespace***, which is not named. Some types, such as `Exception`, and constants, and library functions (such as `sqrt`) are inherited from PHP and, as such, are also defined outside a namespace. Prefix a backslash (`\`) to refer to these types or functions; for example: `\Exception`, `\sqrt`. ## Sub-Namespaces A namespace can have ***sub-namespaces***, where a sub-namespace name shares a common prefix with another namespace. For example, the namespace `Graphics` can have sub-namespaces `Graphics\TwoD` and `Graphics\ThreeD`, for two- and three-dimensional facilities, respectively. Apart from their common prefix, a namespace and its sub-namespaces have no special relationship. For example, `NS1\Sub` can exist without `NS1`. A named top-level namespace does not need to exist for a sub-namespace to exist. ## Reserved Namespaces The namespaces `HH`, `PHP`, `php`, and sub-namespaces beginning with those prefixes are reserved for use by Hack. ## XHP and the `HTML` Namespace As of HHVM 4.73 and XHP-Lib v4, standard XHP elements like `<p>` are defined in `Facebook\XHP\HTML` (for this example, specifically `Facebook\XHP\HTML\p`). For more information, see [XHP Namespace Syntax](/hack/XHP/basic-usage#namespace-syntax). ## Special Constants When debugging, use the predefined constant [`__NAMESPACE__`](/hack/source-code-fundamentals/constants#context-dependent-constants) to access the name of the current namespace. ## Declaring a Namespace Namespace declarations can be file-scoped with `namespace MyNS;`, or block-scoped with `namespace MyNS { ... }`. With semicolons, a namespace extends until the end of the script, or until the next namespace declaration, whichever is first. ```Hack namespace NS1; // ... // __NAMESPACE__ is "NS1" namespace NS3\Sub1; // ... // __NAMESPACE__ is "NS3\Sub1" ``` With brace delimiters, a namespace extends from the opening brace to the closing brace. ```Hack namespace NS1 { // __NAMESPACE__ is "NS1" } namespace { // __NAMESPACE__ is "" } namespace NS3\Sub1 { // __NAMESPACE__ is "NS3\Sub1" } ``` ## Importing from other Namespaces With the `use` keyword, a namespace can import one or more member names into a scope, optionally giving them each an alias. When importing many names, use `{ ... }`. ```Hack no-extract use namespace NS1\{C, I, T}; // instead of `NS1\C, NS1\I, NS1\T` ``` Imported names can designate a namespace, a sub-namespace, a class or interface or trait, a function, or any built-in type. If an imported name introduces ambiguity, you can refer to name `foo` with `namespace\foo`—using the the actual word `namespace`. For example, if you're importing a function `bar()`, but also want to call the `bar()` function from within your own namespace, refer to the one native to your namespace with `namespace\bar()`. ```Hack namespace NS1 { const int CON1 = 100; function f(): void { echo "In ".__FUNCTION__."\n"; } class C { const int C_CON = 200; public function f(): void { echo "In ".__NAMESPACE__."...".__METHOD__."\n"; } } interface I { const int I_CON = 300; } trait T { public function f(): void { echo "In ".__TRAIT__."...".__NAMESPACE__."...".__METHOD__."\n"; } } } namespace NS2 { use type NS1\{C, I, T}; class D extends C implements I { use T; } function f(): void { $d = new D(); echo "CON1 = ".\NS1\CON1."\n"; \NS1\f(); } } ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/01-introduction.md
When combined, operators evaluate according to their associativity. For more information, see [Operator Precedence](/hack/expressions-and-operators/operator-precedence). ## Assignment Operators * [Assignment](/hack/expressions-and-operators/assignment) (`=`, `+=`, and more) * [Coalescing Assignment](/hack/expressions-and-operators/coalesce#coalescing-assignment-operator) (`??=`) ## Comparison Operators * [Comparison](/hack/expressions-and-operators/comparisons) (`>`, `>=`,`<`,`<=`) * [Equality Comparison](/hack/expressions-and-operators/equality) (`==`, `!=`, `===`,`!==`) * [Logical Comparison](/hack/expressions-and-operators/logical-operators) (`&&`, `||`, `!`) * [Spaceship Comparator](/hack/expressions-and-operators/equality#the-spaceship-operator) (`<=>`) ## Arithmetic Operators * [Arithmetic](/hack/expressions-and-operators/arithmetic) (`+`, `-`, `*`, `/`, and more) * [Increment](/hack/expressions-and-operators/incrementing-and-decrementing) (`++`) * [Decrement](/hack/expressions-and-operators/incrementing-and-decrementing) (`--`) ## Bitwise and Bit Shift Operators * [Bitwise](/hack/expressions-and-operators/bitwise-operators) (`&`, `|`, `^`, `<<`, `>>`, `~`) ## Class and Member Operators * [Access Instance Properties and Methods](/hack/expressions-and-operators/member-selection) (`->`, `?->`) * [Access Static Properties and Methods](/hack/expressions-and-operators/scope-resolution) (`::`) * [Access XHP Attributes](/hack/expressions-and-operators/XHP-attribute-selection) (`->:`) * [Create an Object](/hack/expressions-and-operators/new) (`new`) ## Built-in Type Operators * [Cast/Convert Types](/hack/expressions-and-operators/casting) (`(int)`, `(string)`, and more) * [Check Types](/hack/expressions-and-operators/type-assertions#checking-types-with-is) (`is`) * [Enforce Types](/hack/expressions-and-operators/type-assertions#enforcing-types-with-as-and-as) (`as`, `?as`) * [Index into Hack Arrays and Strings](/hack/expressions-and-operators/subscript) (`[]`) * [String Concatenation](/hack/expressions-and-operators/string-concatenation) (`.`) * [Unpack Types](/hack/expressions-and-operators/list) (`list`) ## Error Control Operators * [Check / Assert an invariant](/hack/expressions-and-operators/invariant) (`invariant`) * [Suppress Errors](/hack/expressions-and-operators/error-control) (`@`) ## Other Function Operators * [Async: Suspend Execution](/hack/expressions-and-operators/await) (`await`) * [Coalesce: Non-Null Evaluation](/hack/expressions-and-operators/coalesce) (`??`) * [Echo: Write to Standard Output](/hack/expressions-and-operators/echo) (`echo`) * [Exit: Terminate a Function](/hack/expressions-and-operators/exit) (`exit`) * [Pipe: Chain Function Calls](/hack/expressions-and-operators/pipe) (`|>` then stored in `$$`) * [Ternary: Alternative `If` Evaluation](/hack/expressions-and-operators/ternary) (`? :`, `?:`) * [Yield: Define a Generator](/hack/expressions-and-operators/yield) (`yield`)
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/07-operator-precedence.md
The precedence of Hack operators is shown in the table below. Operators higher in the table have a higher precedence (binding more tightly). Binary operators on the same row are evaluated according to their associativity. Operator | Description | Associativity ------------ | --------- | --------- `\` | [Namespace separator](/hack/source-code-fundamentals/namespaces) | Left `::` | [Scope resolution](/hack/expressions-and-operators/scope-resolution) | Left `[]` | [Index resolution](/hack/expressions-and-operators/subscript) for Hack Arrays and Strings | Left `->`, `?->` | [Property selection](/hack/expressions-and-operators/member-selection) and [null-safe property selection](/hack/expressions-and-operators/member-selection#null-safe-member-access) | Left `new` | [Object creation & Memory allocation](/hack/expressions-and-operators/new) | None `#`, `()` | [Enum class labels](/hack/built-in-types/enum-class-label) and [Function calling](/hack/functions/introduction) | Left `clone` | Object cloning (shallowly, not deeply) | None `readonly`, `await`, `++` `--` (postfix) | [Using readonly](/hack/readonly/explicit-readonly-keywords), [Suspending an async function](/hack/expressions-and-operators/await), and [Incrementing / Decrementing](/hack/expressions-and-operators/incrementing-and-decrementing) (postfix) | Right `(int)` `(float)` `(string)`, `**`, `@`, `++` `--` (prefix) | [Casting](/hack/expressions-and-operators/casting), [Exponentiation](/hack/expressions-and-operators/arithmetic#exponent), [Suppressing errors](/hack/expressions-and-operators/error-control), and [Incrementing / Decrementing](/hack/expressions-and-operators/incrementing-and-decrementing) (prefix) | Right `is`, `as` `?as` |[Type checks / Type assertions](/hack/expressions-and-operators/type-assertions) | Left `!`, `~`, `+` `-` (one argument) | [Logical negation](/hack/expressions-and-operators/logical-operators), [Bitwise negation](/hack/expressions-and-operators/bitwise-operators#bitwise-negation), and [Unary Addition / Subtraction](/hack/expressions-and-operators/arithmetic) | Right `*` `/` `%` | [Multiplication, Division, and Modulo](/hack/expressions-and-operators/arithmetic) | Left `.`, `+` `-` (two arguments) | [String concatenation](/hack/expressions-and-operators/string-concatenation) and [Addition / Subtraction](/hack/expressions-and-operators/arithmetic) | Left `<<` `>>` | [Bitwise shifting](/hack/expressions-and-operators/bitwise-operators) (left and right) | Left `<` `<=` `>` `>=`, `<=>` | [Comparison operators](/hack/expressions-and-operators/comparisons) and [Spaceship operator](/hack/expressions-and-operators/equality#the-spaceship-operator) | None `===` `!==` `==` `!=` | [Equality operators](/hack/expressions-and-operators/equality) | None `&` | [Bitwise AND](/hack/expressions-and-operators/bitwise-operators) | Left `^` | [Bitwise XOR](/hack/expressions-and-operators/bitwise-operators) | Left `\|` | [Bitwise OR](/hack/expressions-and-operators/bitwise-operators) | Left `&&` | [Logical AND](/hack/expressions-and-operators/logical-operators) | Left `\|\|` | [Logical OR](/hack/expressions-and-operators/logical-operators) | Left `??` | [Coalesce operator](/hack/expressions-and-operators/coalesce) | Right `?` `:`, `?:` | [Ternary evaluation](/hack/expressions-and-operators/ternary) and [Elvis operator](/hack/expressions-and-operators/ternary#elvis-operator) | Left `\|>` | [Pipe / Chain function calls](/hack/expressions-and-operators/pipe) | Left `=` `+=` `-=` `.=` `*=` `/=` `%=` `<<=` `>>=` `&=` `^=` `\|=`, `??=` | [Assignment operators](/hack/expressions-and-operators/assignment) and [Coalescing assignment operator](/hack/expressions-and-operators/coalesce#coalescing-assignment-operator) | Right `echo` | [Write to standard output](/hack/expressions-and-operators/echo) | Right `include` `require` | [Include or Require a script](/hack/source-code-fundamentals/script-inclusion)| Left
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/09-echo.md
This intrinsic function converts the value of an expression to `string` (if necessary) and writes the string to standard output. For example: ```Hack $v1 = true; $v2 = 123.45; echo '>>'.$v1.'|'.$v2."<<\n"; // outputs ">>1|123.45<<" $v3 = "abc{$v2}xyz"; echo "$v3\n"; ``` For a discussion of value substitution in strings, see [string literals](../source-code-fundamentals/literals.md#string-literals__double-quoted-string-literals). For conversion to strings, see [type conversion](../types/type-conversion.md#converting-to-string).
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/10-exit.md
This intrinsic function terminates the current script, optionally specifying an *exit value* that is returned to the execution environment. For example: ```Hack exit ("Closing down\n"); exit (1); ``` If the exit value is a string, that string is written out. If the exit value is an integer, that represents the script's *exit status code*, which must be in range 0-254. Value 255 is reserved by Hack. Value 0 represents *success*. `exit` performs the following operations, in order: - Writes an optional string to standard output. - Calls any functions registered via the library function [`register_shutdown_function`](http://www.php.net/register_shutdown_function) in their order of registration.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/12-invariant.md
This intrinsic function behaves like a function with a `void` return type. It is intended to indicate a programmer error for a condition that should never occur. For example: ```Hack no-extract invariant($obj is B, "Object must have type B"); invariant(!$p is null, "Value can't be null"); $max = 100; invariant(!$p is null && $p <= $max, "\$p's value %d must be <= %d", $p, $max); ``` If the first argument value tests true, the program continues execution; otherwise, the library function `invariant_violation` is called. That function does not return; instead, it either throws an exception of type `\HH\InvariantException`, or calls the handler previously registered by the library function `invariant_callback_register`. The first argument is a boolean expression. The second argument is a string that can contain text and/or optional formatting information as understood by the library function `Str\format`. The optional comma-separated list of values following the string must match the set of types expected by the optional formatting information inside that string.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/13-list.md
`list()` is special syntax for unpacking tuples. It looks like a function, but it isn't one. It can be used in positions that you would assign into. ```Hack $tuple = tuple('one', 'two', 'three'); list($one, $two, $three) = $tuple; echo "1 -> {$one}, 2 -> {$two}, 3 -> {$three}\n"; ``` The `list()` will consume the `tuple` on the right and assign the variables inside of itself in turn. If the types of the tuple elements differ, the `list()` syntax will make sure that the type information is preserved. ```Hack <<__EntryPoint>> function main(): void { $tuple = tuple('string', 1, false); list($string, $int, $bool) = $tuple; takes_string($string); takes_int($int); takes_bool($bool); echo 'The typechecker understands the types of list().'; } function takes_string(string $_): void {} function takes_int(int $_): void {} function takes_bool(bool $_): void {} ``` You can use the special `$_` variable to ignore certain elements of the `tuple`. You can use `$_` multiple times in one assignment and have the types be different. You **MUST** use `$_` if you want to ignore the elements at the end. You are not allowed to use a `list()` with fewer elements than the length of the `tuple`. ```Hack $tuple = tuple('a', 'b', 'c', 1, 2, 3); list($_, $b, $c, $_, $two, $_) = $tuple; echo "b -> {$b}, c -> {$c}, two -> {$two}\n"; ``` If the RHS and the LHS of a `list()` are referring to the same variables, the behavior is undefined. As of hhvm 4.46, the typechecker will **NOT** warn you when you make this mistake! HHVM will also not understand what you mean. Do **NOT** do this. ```Hack $a = tuple(1, 2); // BAD, since $a is used on the right and on the left! list($a, $b) = $a; ``` You may also use `list()` on a `vec<T>`, but it is not recommended. `list()` can be nested inside of another `list()` to unpack `tuples` from within `tuples`. ```Hack $tuple = tuple('top level', tuple('inner', 'nested')); list($top_level, list($inner, $nested)) = $tuple; echo "top level -> {$top_level}, inner -> {$inner}, nested -> {$nested}\n"; ``` My personal favorite place to put a `list()` is inside a `foreach($vec_of_tuples as list($one, $two, $three))`. ```Hack $vec_of_tuples = vec[ tuple('A', 'B', 'C'), tuple('a', 'b', 'c'), tuple('X', 'Y', 'Z'), ]; foreach ($vec_of_tuples as list($first, $second, $third)) { echo "{$first} {$second} {$third}\n"; } ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/21-new.md
The `new` operator allocates memory for an object that is an instance of the specified class. The object is initialized by calling the class's [constructor](../classes/constructors.md) passing it the optional argument list, just like a function call. If the class has no constructor, the constructor that class inherits (if any) is used. For example: ```Hack class Point { private static int $pointCount = 0; // static property with initializer private float $x; // instance property private float $y; // instance property public function __construct(num $x = 0, num $y = 0) { // instance method $this->x = (float)$x; // access instance property $this->y = (float)$y; // access instance property ++Point::$pointCount; // include new Point in Point count } } function main(): void { $p1 = new Point(); // create Point(0.0, 0.0) $p2 = new Point(5, 6.7); // create Point(5.0, 6.7) } ``` The result is an object of the type specified. The `new` operator may also be used to allocate memory for an instance of a [classname](../built-in-types/classname.md) type; for example: ```Hack final class C {} function f(classname<C> $clsname): void { $w = new $clsname(); } ``` Any one of the keywords `parent`, `self`, and `static` can be used between the `new` and the constructor call, as follows. From within a method, the use of `static` corresponds to the class in the inheritance context in which the method is called. The type of the object created by an expression of the form `new static` is [`this`](../built-in-types/this.md). See [scope resolution](scope-resolution.md) for a discussion of `parent`, `self`, and `static` in this context.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/25-subscript.md
The subscript operator, `[...]` is used to designate an element of a string, a vec, a dict, or a keyset. The element key is designated by the expression contained inside the brackets. For a string or vec, the key must have type `int`, while dict and keyset also allow `string`. The type and value of the result is the type and value of the designated element. For example: ```Hack $text = "Hello"; $e = $text[4]; // designates the element with key 4 value "o" $text[1] = "?"; // changes the element with key 1 from "e" to "?" $v = vec[10, 25, -6]; $e = $v[1]; // designates the element with key 1 value 25 $v[2] = 44; // changes the element with key 2 from -6 to 44 $d = dict["red" => 4, "white" =>12, "blue" => 3]; $e = $d["white"]; // designates the element with key "white" value 12 $d["red"] = 9; // changes the element with key "red" from 4 to 9 ``` For a vec, the brackets can be empty, provided the subscript expression is the destination of an assignment. This results in a new element being inserted at the right-hand end. The type and value of the result is the type and value of the new element. For example: ```Hack $v = vec[10, 25, -6]; $v[] = 99; // creates new element with key 3, value 99 ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/29-member-selection.md
The operator `->` is used to access instance properties and instance methods on objects. ```Hack file:intbox.hack class IntBox { private int $x; public function __construct(int $x) { $this->x = $x; // Assigning to property. } public function getX(): int { return $this->x; // Accessing property. } } <<__EntryPoint>> function main(): void { $ib = new IntBox(42); $x = $ib->getX(); // Calling instance method. } ``` ## Null Safe Member Access The operator `?->` allows access to objects that [may be null](../types/nullable-types.md). If the value is null, the result is null. Otherwise, `?->` behaves like `->`. ```Hack file:intbox.hack function my_example(?IntBox $ib): ?int { return $ib?->getX(); } ``` Note that arguments are always evaluated, even if the object is null. `$x?->foo(bar())` will call `bar()` even if `$x` is null. ## XHP Attribute Access The [operator `->:`](/hack/expressions-and-operators/XHP-attribute-selection) is used for accessing XHP attributes.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/33-scope-resolution.md
When the left-hand operand of operator `::` is an enumerated type, the right-hand operand must be the name of an enumeration constant within that type. For example: ```Hack enum ControlStatus: int { Stopped = 0; Stopping = 1; Starting = 2; Started = 3; } function main(ControlStatus $p1): void { switch ($p1) { case ControlStatus::Stopped: // ... break; case ControlStatus::Stopping: // ... break; default: break; } } ``` From inside or outside a class or interface, operator `::` allows the selection of a constant. From inside or outside a class, this operator allows the selection of a static property, static method, or instance method. For example: ```Hack final class MathLibrary { const PI = 3.1415926; public static function sin(float $val): float { return 0.0; // stub } } function use_it(): void { $radius = 3.4; $area = MathLibrary::PI * $radius * $radius; $v = MathLibrary::sin(2.34); } ``` From within a class, `::` also allows the selection of an overridden property or method. From within a class, `self::m` refers to the member `m` in that class. For example: ```Hack class Point { private static int $pointCount = 0; public static function getPointCount(): int { return self::$pointCount; } } ``` From within a class, `parent::m` refers to the closest member `m` in the base-class hierarchy, not including the current class. For example: ```Hack class MyRangeException extends Exception { public function __construct(string $message) { parent::__construct('MyRangeException: '.$message); } } ``` From within a method, `static::m` refers to the static member `m` in the class that corresponds to the class inheritance context in which the method is called. This allows *late static binding*. Consider the following scenario: ```Hack class Base { public function b(): void { static::f(); // calls the most appropriate f() } public static function f(): void { //... } } class Derived extends Base { public static function f(): void { // ... } } function demo(): void { $b1 = new Base(); $b1->b(); // as $b1 is an instance of Base, Base::b() calls Base::f() $d1 = new Derived(); $d1->b(); // as $d1 is an instance of Derived, Base::b() calls Derived::f() } ``` The value of a scope-resolution expression ending in `::class` is a string containing the fully qualified name of the current class, which for a static qualifier, means the current class context. A variable name followed by `::` and a name results in a constant whose value has the [`classname` type](../built-in-types/classname.md) for the variable name's type. For example: ```Hack namespace NS_cn; class C1 { // ... } class C2 { public static classname<C1> $p1 = C1::class; public static function f(?classname<C1> $p): void {} public static vec<classname<C1>> $p2 = vec[C1::class]; } ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/37-incrementing-and-decrementing.md
Hack provides `++` and `--` syntax for incrementing and decrementing numbers. The following are equivalent: ```Hack no-extract $i = $i + 1; $i += 1; $i++; ++$i; ``` Similarly for decrement: ```Hack no-extract $i = $i - 1; $i -= 1; $i--; --$i; ``` This is typically used in for loops: ```Hack for ($i = 1; $i <= 10; $i++) { // ... } ``` Note that `++` and `--` are statements, not expressions. They cannot be used in larger expressions. ```Hack error $x = 0; $y = $x++; // Parse error. ``` Instead, the above code must be written as statements. ```Hack $x = 0; $y = $x + 1; $x++; ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/47-error-control.md
The operator `@` suppresses any error messages generated by the evaluation of the expression that follows it. For example: ```Hack $infile = @fopen("NoSuchFile.txt", 'r'); ``` On open failure, the value returned by `fopen` is `false`, which you can use to handle the error. There is no need to have any error message displayed. If a custom error-handler has been established using the library function [`set_error_handler`](https://www.php.net/manual/en/function.set-error-handler.php) that handler is still called. This syntax can be disabled with the `disallow_silence` option in `.hhconfig`.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/49-casting.md
Casts in Hack convert values to different types. To assert a type without changing its value, see [type assertions](type-assertions.md). ``` Hack (float)1; // 1.0 (int)3.14; // 3, rounds towards zero (bool)0; // false (string)false; // "" ``` Casts are only supported for `bool`, `int`, `float` and `string`. See [type conversions](../types/type-conversion.md) to understand what value will be produced.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/51-await.md
`await` suspends the execution of an async function until the result of the asynchronous operation represented by the expression that follows this keyword, is available. See [awaitables](../asynchronous-operations/awaitables.md) for details of `await`, and [async](../asynchronous-operations/introduction.md) for a general discussion of asynchronous operations.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/52-type-assertions.md
Hack provides the `is` and `as` operators for inspecting types at runtime. To convert primitive types, see [casting](casting.md). The type checker also understands `is` and `as`, so it will infer precise types. ## Checking Types with `is` The `is` operator checks whether a value has the type specified, and returns a boolean result. ```Hack 1 is int; // true 'foo' is int; // false 1 is num; // true 1.5 is num; // true 'foo' is num; // false ``` The type checker understands `is` and [refines values](../types/type-refinement.md) inside conditionals or after `invariant` calls. ```Hack no-extract function transport(Vehicle $v): void { if ($v is Car) { $v->drive(); } else if ($v is Plane) { $v->fly(); } else { invariant($v is Boat, "Expected a boat"); $v->sail(); } } ``` A common pattern with `is` refinement is to use `nonnull` rather than an explicit type. ``` Hack no-extract function transport(?Car $c): void { if ($c is nonnull) { // Infers that $c is Car, but saves us // repeating the name of the type. $c->drive(); } } ``` ### Enums For enums, `is` also checks that the value is valid. ```Hack enum MyEnum: int { FOO = 1; } function demo(): void { 1 is MyEnum; // true 42 is MyEnum; // false 'foo' is MyEnum; // false } ``` ### Generics Since `is` provides a runtime check, it cannot be used with erased generics. For generic types, you must use `_` placeholders for type parameters. ``` $v = vec[1, 2, 3]; // We can't use `is vec<int>` here. $v is vec<_>; // true ``` If you need to check inner types at runtime, consider using reified generics instead. ### Tuples For tuples and shapes, `is` validates the size and recursively validates every field in the value. ```Hack $x = tuple(1, 2.0, null); $x is (int, float, ?bool); // true $y = shape('foo' => 1); $y is shape('foo' => int); // true ``` ### Aliases `is` also works with type aliases and type constants, by testing against the underlying runtime type. ``` Hack type myint = int; function demo(): void { 1 is myint; // true } ``` ## Enforcing Types with `as` and `?as` `as` performs the same checks as `is`. However, it throws `TypeAssertionException` if the value has a different type. The type checker understands that the value must have the type specified afterwards, so it [refines](../types/type-refinement.md) the value. ```Hack 1 as int; // 1 'foo' as int; // TypeAssertionException ``` `as` enables you to narrow a type. ```Hack no-extract // Normally you'd want to make transport take a Vehicle // directly, so you can check when you call the function. function transport(mixed $m): void { // Exception if not a Vehicle. $v = $m as Vehicle; if ($v is Car) { $v->drive(); } else { // Exception if $v is not a Boat. $v as Boat; $v->sail(); } } ``` Hack also provides `?as`, which returns `null` if the type does not match. ```Hack 1 ?as int; // 1 'foo' ?as int; // null ``` Note that `as` can also be used in type signatures when using generics. ## Legacy Type Predicates Hack also provides type predicate functions `is_int`, `is_bool` and so on. You should use `is` instead.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/58-arithmetic.md
Hack provides the standard arithmetic operators. These only operate on numeric types: `int` or `float`. ## Addition The operator `+` produces the sum of its operands. If both operands have type `int`, the result is `int`. Otherwise, the operands are converted to `float` and the result is `float`. ```Hack -10 + 100; // int with value 90 100 + -3.4e2; // float with value -240 9.5 + 23.444; // float with value 32.944 ``` ## Subtraction The operator `-` produces the difference of its operands. If both operands have type `int`, the result is `int`. Otherwise, the operands are converted to `float` and the result is `float`. ```Hack -10 - 100; // int with value -110 100 - -3.4e2; // float with value 440 9.5 - 23.444; // float with value -13.944 ``` ## Multiplication The operator `*` produces the product of its operands. If both operands have type `int`, the result is `int`. Otherwise, the operands are converted to `float` and the result is `float`. ```Hack -10 * 100; // int result with value -1000 100 * -3.4e10; // float result with value -3400000000000.0 ``` ## Division The operator `/` produces the quotient from dividing the left-hand operand by the right-hand one. Dividing by `0` will produce an exception. If both operands have type `int`, and the result can be represented exactly as an `int`, then the result is an `int`. Otherwise, the result is `float`. ```Hack 300 / 100; // int result with value 3 100 / 123; // float result with value 0.8130081300813 12.34 / 2.3; // float result with value 5.3652173913043 ``` ## Modulo The operator `%` produces the `int` remainder from dividing the left-hand `int` operand by the right-hand `int` operand. If the right hand side is 0, an exception is thrown. ```Hack 5 % 2; // int result with value 1 ``` ## Exponent The operator `**` produces the result of raising the value of its left-hand operand to the power of the right-hand one. If both operands have non-negative integer values and the result can be represented as an `int`, the result has type `int`; otherwise, the result has type `float`. ```Hack 2 ** 3; // int with value 8 2 ** 3.0; // float with value 8.0 2.0 ** 3.0; // float with value 8.0 ``` ## Unary Plus The unary plus operator `+` requires an `int` or `float` value, but has no effect. It exists for symmetry. The following are equivalent: ```Hack $v = +10; $v = 10; ``` ## Unary Minus The unary minus operator `-` requires an `int` or `float` value, and returns the negated value. ```Hack $v = 10; $x = -$v; // $x has value -10 ``` Note that due to underflow, negating the smallest negative value produces the same value.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/69-string-concatenation.md
The binary operator `.` creates a string that is the concatenation of the left-hand operand and the right-hand operand, in that order. If either or both operands have types other than `string`, their values are converted to type `string`. Consider the following example: ```Hack "foo"."bar"; // "foobar" ``` Here are some more examples, which all involve conversion to `string`: ```Hack -10 . NAN; // string result with value "-10NAN" INF . "2e+5"; // string result with value "INF2e+5" true . null; // string result with value "1" ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/70-bitwise-operators.md
Hack provides a range of bitwise operators. These assume that their operands are `int`. ## Bitwise AND The operator `&` performs a bitwise AND on its two `int` operands and produces an `int`. For example: ```Hack 0b101111 & 0b101; // result is 0b101 $lcase_letter = 0x73; // lowercase letter 's' $ucase_letter = $lcase_letter & ~0x20; // clear the 6th bit to make uppercase letter 'S' ``` ## Bitwise OR The operator `|` performs a bitwise OR on its two `int` operands and produces an `int`. For example: ```Hack 0b101111 | 0b101; // result is 0b101111 $ucase_letter = 0x41; // uppercase letter 'A' $lcase_letter = $ucase_letter | 0x20; // set the 6th bit to make lowercase 'a' ``` ## Bitwise XOR The operator `^` performs a bitwise XOR on its two `int` operands and produces an `int`. For example: ```Hack 0b101111 ^ 0b101; // result is 0b101010 ``` ## Shifting The operator `<<` performs a bitwise left shift. It takes two `int` operands and produces an `int`. `e1 << e2` shifts `e1` left by `e2` bits, zero extending the value. ```Hack 0b101 << 2; // result is 0b10100 10 << 3; // result is 80 ``` The operator `>>` performs a bitwise right shift. ``` Hack 0b1011 >> 2; // result is 0b10 100 >> 2; // result is 25 ``` Note that right shifts extend the sign bit: ```Hack (1 << 63) >> 63; // result is -1 ``` This is because `1 << 63` is 0x8000000000000000, or -9223372036854775808. ## Bitwise Negation The operator `~` performs a bitwise negation on its `int` operand and produces an `int`. For example: ```Hack $lLetter = 0x73; // lowercase letter 's' $uLetter = $lLetter & ~0b100000; // clear the 6th bit to make uppercase letter 'S' ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/72-logical-operators.md
Hack provides the conventional boolean operations. ## Logical AND `&&` The operator `&&` calculates the boolean AND operation of its two operands. ```Hack no-extract if (youre_happy() && you_know_it()) { clap_your_hands(); } ``` If either operand does not have a boolean type, it is converted to a boolean first. The result is always a boolean. `&&` is short circuiting, so it stops evaluation on the first `false` result. ```Hack no-extract $x = one() && two() && three(); ``` The function `three` will not be called if `one()` or `two()` evaluate to `false`. ## Logical OR `||` The operator `||` calculates the boolean OR operation of its two operands. ```Hack no-extract if ($weekday === 6 || $weekday === 7) { echo "It's a weekend"; } ``` If either operand does not have a boolean type, it is converted to a boolean first. The result is always a boolean. `||` is short circuiting, so it stops evaluation on the first `true` result. ```Hack no-extract $x = one() || two() || three(); ``` The function `three` will not be called if `one()` or `two()` evaluate to `true`. ## Logical NOT `!` The operator `!` calculate the boolean negation of its operand. If the operand does not have a boolean type, it is converted to a boolean first. The result is always a boolean. ```Hack no-extract while (!is_connected()) { connect(); } ``` If the operand has type `num`, `!$v` is equivalent to `$v === 0 || $v === 0.0`.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/75-comparisons.md
Hack provides comparison operators. They operate on two operands and return `bool`. * `<`, which represents *less-than* * `>`, which represents *greater-than* * `<=`, which represents *less-than-or-equal-to* * `>=`, which represents *greater-than-or-equal-to* The type of the result is `bool`. Comparison operators are typically used with numbers: ``` Hack 1 < 2; // true 1.0 <= 1.5; // true ``` However, comparisons also work on strings. This uses a lexicographic ordering unless both strings are numeric, in which case the numeric values are used: ``` Hack "a" < "b"; // true "ab" < "b"; // true "01" < "1"; // false (1 == 1) ``` ## The Spaceship Operator Often referred to as the *spaceship operator*, the binary operator `<=>` compares the values of its operands and returns an `int` result. If the left-hand value is less than the right-hand value, the result is some unspecified negative value; else, if the left-hand value is greater than the right-hand value, the result is some unspecified positive value; otherwise, the values are equal and the result is zero. For example: ```Hack 1 <=> 1; // 0; equal 1 <=> 2; // negative; 1 < 2 2 <=> 1; // positive; 2 > 1 "a" <=> "a"; // 0; same length and content "a" <=> "b"; // negative; a is lower than b in the collating sequence "b" <=> "a"; // positive; b is higher than a in the collating sequence "a" <=> "A"; // positive; lowercase a is higher than uppercase A "a" <=> "aa"; // negative; same leading part, but a is shorter than aa "aa" <=> "a"; // positive; same leading part, but aa is longer than a "aa" <=> "aa"; // 0; same length and content ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/77-equality.md
There are two equality operators in Hack: `===` (recommended) and `==`. They also have not-equal equivalents, which are `!==` and `!=`. ```Hack 1 === 2; // false 1 !== 2; // true ``` ## `===` Equality `===` compares objects by reference. ```Hack file:object.hack class MyObject {} ``` ```Hack file:object.hack $obj = new MyObject(); // Different references aren't equal. $obj === new MyObject(); // false // The same reference is equal. $obj === $obj; // true ``` `===` compares primitives types by value. ```Hack 1 === 1; // true vec[1, 2] === vec[1, 2]; // true ``` Items of different primitive types are never equal. ```Hack 0 === null; // false vec[1] === keyset[1]; // false // Tip: if you want to compare an integer with a float, // convert the integer value: (float)1 === 1.0; // true ``` `vec`, `keyset`, `dict` and `shape` values are equal if their items are `===` equal and if the items are in the same order. ```Hack vec[1, 2] === vec[1, 2]; // true vec[1] === vec[2]; // false keyset[1, 2] === keyset[1, 2]; // true keyset[1, 2] === keyset[2, 1]; // false dict[0 => null, 1 => null] === dict[0 => null, 1 => null]; // true dict[1 => null, 0 => null] === dict[0 => null, 1 => null]; // false // Tip: Use Keyset\equal and Dict\equal if you // want to ignore order: Keyset\equal(keyset[1, 2], keyset[2, 1]); // true Dict\equal(dict[1 => null, 0 => null], dict[0 => null, 1 => null]); // true ``` `!==` returns the negation of `===`. ```Hack 1 !== 2; // true 2 !== 2; // false ``` ## `==` Equality **If in doubt, prefer `===` equality.** `==` compares objects by comparing each property, producing a structural equality. ```Hack file:wrapper.hack class MyWrapper { public function __construct(private mixed $m) {} } ``` ```Hack file:wrapper.hack new MyWrapper(1) == new MyWrapper(1); // true new MyWrapper(1) == new MyWrapper(2); // false ``` Items of different type are never equal with `==`, the same as `===`. ```Hack 1 == 1.0; // false 0 == null; // false "" == 0; // false ``` `==` ignores the order when comparing `keyset`, `dict` and `shape` values. Items within these collections are compared with `==` recursively. ```Hack keyset[1, 2] == keyset[2, 1]; // true dict[1 => null, 2 => null] == dict[2 => null, 1 => null]; // true // Note that vec comparisons always care about order. vec[1, 2] == vec[2, 1]; // false ``` `!=` returns the negation of `==`. ```Hack 1 != 2; // true 1 != 1; // false ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/89-ternary.md
The ternary operator `?` `:` is a shorthand for `if` statements. It is an expression, so it evaluates to a value. For example: ```Hack no-extract $days_in_feb = is_leap_year($year) ? 29 : 28; ``` It takes three operands `e1 ? e2 : e3`. If `e1` evaluates to a truthy value, then the result is the evaluation of `e2`. Otherwise the result is the evaluation of `e3`. ## Elvis Operator There is also a two operand version `?:`, sometimes called the "elvis operator". This results in the first operand if it evaluates to a truthy value. For example: ``` Hack no-extract $x = foo() ?: bar(); // Is equivalent to: $tmp = foo(); $x = $tmp ? $tmp : bar(); ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/91-coalesce.md
Given the expression `e1 ?? e2`, if `e1` is defined and not `null`, then the result is `e1`. Otherwise, `e2` is evaluated, and its value becomes the result. There is a sequence point after the evaluation of `e1`. ```Hack $nully = null; $nonnull = 'a string'; \print_r(vec[ $nully ?? 10, // 10 as $nully is `null` $nonnull ?? 10, // 'a string' as $nonnull is `nonnull` ]); $arr = dict['black' => 10, 'white' => null]; \print_r(vec[ $arr['black'] ?? -100, // 10 as $arr['black'] is defined and not null $arr['white'] ?? -200, // -200 as $arr['white'] is null $arr['green'] ?? -300, // -300 as $arr['green'] is not defined ]); ``` It is important to note that the right-hand side of the `??` operator will be conditionally evaluated. If the left-hand side is defined and not `null`, the right-hand side will not be evaluated. ```Hack no-extract $nonnull = 4; // The `1 / 0` will never be evaluated and no Exception is thrown. $nonnull ?? 1 / 0; // The function_with_sideeffect is never invoked. $nonnull ?? function_with_sideeffect(); ``` ## `??` and `idx()` The `??` operator is similar to the built-in function `idx()`. However, an important difference is that `idx()` only falls back to the specified default value if the given key does not exist, while `??` uses the fallback value even if a key exists but has `null` value. Compare these examples to the ones above: ```Hack $arr = dict['black' => 10, 'white' => null]; \print_r(vec[ idx($arr, 'black', -100), // 10 idx($arr, 'white', -200), // null idx($arr, 'green', -300), // -300 idx($arr, 'green'), // null ]); ``` ## Coalescing assignment operator A coalescing [assignment](https://docs.hhvm.com/hack/expressions-and-operators/assignment) operator `??=` is also available. The `??=` operator can be used for conditionally writing to a variable if it is null, or to a collection if the specified key is not present or has `null` value. This is similar to `e1 = e1 ?? e2`, with the important difference that `e1` is only evaluated once. The `??=` operator is very useful for initializing elements of a collection: ```Hack function get_counts_by_value(Traversable<string> $values): dict<string, int> { $counts_by_value = dict[]; foreach ($values as $value) { $counts_by_value[$value] ??= 0; ++$counts_by_value[$value]; } return $counts_by_value; } function get_people_by_age( KeyedTraversable<string, int> $ages_by_name, ): dict<int, vec<string>> { $people_by_age = dict[]; foreach ($ages_by_name as $name => $age) { $people_by_age[$age] ??= vec[]; $people_by_age[$age][] = $name; } return $people_by_age; } <<__EntryPoint>> function main(): void { $values = vec['foo', 'bar', 'foo', 'baz', 'bar', 'foo']; \print_r(get_counts_by_value($values)); $people = dict[ 'Arthur' => 35, 'Ford' => 110, 'Trillian' => 35, 'Zaphod' => 120, ]; \print_r( get_people_by_age($people) |> Dict\map($$, $names ==> Str\join($names, ', ')) ); } ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/93-pipe.md
The binary pipe operator, `|>`, evaluates the result of a left-hand expression and stores the result in `$$`, the pre-defined pipe variable. The right-hand expression *must* contain at least one occurrence of `$$`. ## Basic Usage With the pipe operator, you can chain function calls, as shown in the code below. ``` Hack $x = vec[2,1,3] |> Vec\map($$, $a ==> $a * $a) // $$ with value vec[2,1,3] |> Vec\sort($$); // $$ with value vec[4,1,9] ``` Written in another way, the code above is syntactically equivalent to: ``` Hack Vec\sort(Vec\map(vec[2, 1, 3], $a ==> $a * $a)); // Evaluates to vec[1,4,9] ``` ## Await and the Binary Pipe `Await` cannot be used as an expression to the right of the pipe operator.
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/97-assignment.md
The assignment operator `=` assigns the value of the right-hand operand to the left-hand operand. For example: ```Hack $a = 10; ``` ## Element Assignment We can assign to array elements, as follows: ```Hack $v = vec[1, 2, 3]; $v[0] = 42; // $v is now vec[42, 2, 3] $v = dict[0 => 10, 1 => 20, 2 => 30]; $v[1] = 22; // change the value of the element with key 1 $v[-10] = 19; // insert a new element with key -10 ``` For `vec`, indexes must be within the range of the existing values. Use `$v[] = new_value;` to append new values. For `dict`, we can insert at arbitrary keys. ``` Hack $d = dict['x' => 1]; $d['y'] = 42; // $d is now dict['x' => 1, 'y' => 42] ``` Strings can also be assigned like arrays. However, it is possible to assign beyond the end of the string. The string will be extended with spaces as necessary. ``` Hack $s = "ab"; $s[0] = "x"; // in bounds $s[3] = "y"; // $s is now "xb y" ``` ## Compound Assignments Infix operators in Hack have a corresponding compound assignment operator. For example, `+` has compound assignment operator `+=`. ``` Hack no-extract $x += 10; // Equivalent to: $tmp = $x + 10; $x = $tmp; ``` The complete set of compound-assignment operators is: `**=`, `*=`, `/=`, `%=`, `+=`, `-=`, `.=`, `<<=`, `>>=`, `&=`, `^=`, `|=`, and [`??=`](https://docs.hhvm.com/hack/expressions-and-operators/coalesce#coalescing-assignment-operator).
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/98-yield.md
Any function containing the `yield` operator is a *generator function*. A generator function generates a collection of zero or more key/value pairs where each pair represents the next element in some series. For example, a generator might yield random numbers or the series of Fibonacci numbers. When a generator function is called explicitly, it returns an object of type `Generator`, which implements the interface `Iterator`. As such, that object can be iterated over using the `foreach` statement. During each iteration, the runtime calls the generator function implicitly to get the element. Then the runtime saves the state of the generator for subsequent element-fetch requests. Consider the following example: ```Hack function series( int $start, int $end, int $incr = 1, ): \Generator<int, int, void> { for ($i = $start; $i <= $end; $i += $incr) { yield $i; } } <<__EntryPoint>> function main(): void { foreach (series(5, 15, 2) as $key => $val) { echo "key: $key, value: $val\n"; } echo "-----------------\n"; foreach (series(25, 20, 3) as $key => $val) { echo "key: $key, value: $val\n"; } echo "-----------------\n"; } ``` Function `series` returns an instance of the generic type `Generator`, in which the first two type arguments are the element's key- and value-type, respectively. (We won't discuss the third type argument here; it is `void` in all the examples below.) Note that the function does **not** contain any `return` statement. Instead, elements are *returned* as directed by the `yield` expression. As shown, the function yields element values, one per loop iteration. In `main`, we call `series` to generate the collection, and then we iterate over that collection from 5-15 in steps of 2, and simply display the next element's key and value. However, when we use the range 25-20 in steps of 3, the resulting collection is empty, as 25 is already greater than 20. In its simplest form, `yield` is followed by the value of the next element with that value's key being an `int` whose value starts at zero for each collection. This is demonstrated in the output, which has keys 0-5. `yield` can also specify the value of a key; for example: ```Hack function squares( int $start, int $end, string $keyPrefix = "", ): Generator<string, int, void> { for ($i = $start; $i <= $end; ++$i) { yield $keyPrefix.$i => $i * $i; // specify a key/value pair } } <<__EntryPoint>> function main(): void { foreach (squares(-2, 3, "X") as $key => $val) { echo "key: $key, value: $val\n"; } } ``` By using the same syntax as that to initialize a dict element, we can provide both the key and associated value. Of course, the return type of `squares` now uses `string` as the first generic type argument, as the element type has a key of type `string`. The following example uses `yield` to generate a collection of strings, each of which is a record from a text file: ```Hack function getTextFileLines(string $filename): Generator<int, string, void> { $infile = fopen($filename, 'r'); if ($infile === false) { // handle file-open failure } try { while (true) { $textLine = fgets($infile); if ($textLine === false) { break; } $textLine = rtrim($textLine, "\r\n"); // strip off line terminator yield $textLine; } } finally { fclose($infile); } } ```
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/99-XHP-attribute-selection.md
When working with [XHP](/hack/XHP/introduction), use the `->:` operator to retrieve an XHP class [attribute](/hack/XHP/basic-usage#attributes) value. The operator can also be used on arbitrary expressions that resolve to an XHP object (e.g. `$a ?? $b)->:`). ```Hack no-extract use namespace Facebook\XHP\Core as x; final xhp class user_info extends x\element { attribute int userid @required; attribute string name = ""; protected async function renderAsync(): Awaitable<x\node> { return <x:frag>User with id {$this->:userid} has name {$this->:name}</x:frag>; } } ```
Markdown
hhvm/hphp/hack/manual/hack/04-statements/01-introduction.md
**Topics covered in this section** * [break/continue](/hack/statements/break-and-continue) * [do/while](/hack/statements/do) * [for](/hack/statements/for) * [foreach](/hack/statements/foreach) * [if/else if/else](/hack/statements/if) * [return](/hack/statements/return) * [switch](/hack/statements/switch) * [throw/try/catch/finally](/hack/statements/try) * [use](/hack/statements/use) * [using](/hack/statements/using) * [while](/hack/statements/while)
Markdown
hhvm/hphp/hack/manual/hack/04-statements/02-break-and-continue.md
## `continue` A `continue` statement terminates the execution of the innermost enclosing `do`, `for`, `foreach`, or `while` statement. For example: ```Hack for ($i = 1; $i <= 10; ++$i) { if (($i % 2) === 0) { continue; } echo "$i is odd\n"; } ``` Although a `continue` statement must not attempt to break out of a finally block, a `continue` statement can terminate a loop that is fully contained within a finally block. ## `break` A `break` statement can be used to interrupt the iteration of a loop statement and to break-out to the statement immediately following that loop statement. For example: ```Hack no-extract while (true) { // ... if ($done) { break; // break out of the while loop } // ... } ``` Sometimes it is useful to have an infinite loop from which we can escape when the right condition occurs. Although a `break` statement must not attempt to break out of a finally block, a `break` statement can break out of a construct that is fully contained within a finally block. A `break` statement can also affect a non-looping context; it terminates a case in a `switch` statement.
Markdown
hhvm/hphp/hack/manual/hack/04-statements/03-do.md
The general format of a `do` statement is `do` *statement* `while (` *expression* `);` The *single* statement is executed. If the expression tests `true`, the process is repeated. If the expression tests `false`, control transfers to the point immediately following the end of the `do` statement. The loop body (that is, the single statement) is executed one or more times. Consider the following: ```Hack $i = 1; do { echo "$i\t".($i * $i)."\n"; // output a table of squares ++$i; } while ($i <= 10); ``` The execution of a `do` statement is impacted by a subordinate [`break` or `continue`](break-and-continue.md). The controlling expression must have type `bool` or a type that can be converted implicitly to `bool`. For example, in `do` ... `while (1);` `do` ... `while (123);` and `do` ... `while (-1.234e24)`, in each case, the value of the expression is non-zero, which is implicitly converted to `true`. Only zero-values are converted to `false`. The `do` statement behaves slightly differently than `while` in that the former executes the loop body *before* it tests the controlling expression, whereas `while` executes it after.
Markdown
hhvm/hphp/hack/manual/hack/04-statements/04-for.md
The `for` statement is typically used to step through a range of values in ascending or descending increments, performing some set of operations on each value. For example: ```Hack for ($i = 1; $i <= 5; ++$i) { echo "$i\t".($i * $i)."\n"; // output a table of squares } $i = 1; for (; $i <= 5; ) { echo "$i\t".($i * $i)."\n"; // output a table of squares ++$i; } $i = 1; for (; ; ) { if ($i > 5) break; echo "$i\t".($i * $i)."\n"; // output a table of squares ++$i; } ``` In the first `for` loop above, let's call `$i = 1` the *for-initializer*, `$i <= 10` the *for-control*, and `++$i` the *for-end-of-loop-action*. Each of these three parts can contain a comma-separated list of expressions. For example: ```Hack no-extract for ($i = 1, $j = 10; f($i), $i <= 10; $i = $i + 2, --$j) { // ... } ``` The group of expressions in *for-initializer* is evaluated once, left-to-right, for their side-effects only. Then the group of expressions in *for-control* is evaluated left-to-right (with all but the right-most one for their side-effects only), with the right-most expression's value being tested. If that tests `true`, the loop body is executed, and the group of expressions in *for-end-of-loop-action* is evaluated left-to-right, for their side-effects only. Then the process is repeated starting with *for-control*. If the right-most expression in *for-control* tests `false`, control transfers to the point immediately following the end of the for statement. The loop body is executed zero or more times. The controlling expression&mdash;the right-most expression in *for-control*---must have type `bool` or be implicitly convertible to that type. Any or all of the three parts of the first line of a for statement can be omitted, as shown. If *for-initializer* is omitted, no action is taken at the start of the loop processing. If *for-control* is omitted, this is treated as if *for-control* was an expression with the value `true`. If *for-end-of-loop-action* is omitted, no action is taken at the end of each iteration.
Markdown
hhvm/hphp/hack/manual/hack/04-statements/05-foreach.md
The `foreach` statement iterates over the set of elements in a given collection, starting at the beginning, executing a single statement each iteration. On each iteration, the value of the current element is assigned to the corresponding variable, as specified. The loop body is executed zero or more times. For example: ```Hack $colors = vec["red", "white", "blue"]; foreach ($colors as $color) { // ... } ``` Here, we iterate over a collection of three strings in a vec of `string`. Inside the loop body, `$color` takes on the value of the current string. As each array element has an index as well as a value, we can access both. For example: ```Hack $colors = vec["red", "white", "blue"]; foreach ($colors as $key => $color) { // ... } ``` The `as` clause gives us access to the array key. We can cause each element's value to be ignored, using `$_`, as follows: ```Hack $a = dict['a' => 10, 'f' => 30]; foreach ($a as $key => $_) { // 10 and 30 are ignored // ... } ``` We can also use `list()` here `foreach($vec_of_tuples as list($here, $there))` and here `foreach($vec_of_tuples as $key => list($here, $there))`. For more information about lists, see [list](../expressions-and-operators/list.md).
Markdown
hhvm/hphp/hack/manual/hack/04-statements/06-if.md
An `if` statement will execute code if a condition is true. If it's false, an `else` block can execute. ```Hack $count = 11; if ($count < 10) { echo "small"; } else if ($count < 20) { echo "medium"; } else { echo "large"; } ``` Conditions must have type `bool` or be implicitly convertible to `bool`. If the condition evaluates to to `true`, the `if` block is executed. Otherwise, `else if` conditions are evaluated in order until one evaluates to `true`, then its block is executed. If none of the conditions evaluate to `true`, and an `else` block is present, that will be executed instead. ## Without Braces Braces allow you to have multiple statements inside an `if` statement. Braces are recommended, but they are optional. ```Hack no-extract if ($count < 10) echo "small"; else echo "big"; ``` When no braces are present, an `else` clause is associated with the lexically nearest preceding `if` or `else if`. ```Hack no-extract if ($x) echo "x is true"; if ($y) echo "y is true"; else // Associated with the second if. echo "y is not true"; ``` The above code is equivalent to: ```Hack no-extract if ($x) { echo "x is true"; } if ($y) { echo "y is true"; } else { echo "y is not true"; } ```
Markdown
hhvm/hphp/hack/manual/hack/04-statements/07-return.md
A `return` statement can only occur inside a function, in which case, it causes that function to terminate normally. The function can optionally return a single value (but one which could contain other values, as in a tuple, a shape, or an object of some user-defined type), whose type must be compatible with the function's declared return type. If the `return` statement contains no value, or there is no `return` statement (in which case, execution drops into the function's closing brace), no value is returned. For example: ```Hack function average_float(float $p1, float $p2): float { return ($p1 + $p2) / 2.0; } type IdSet = shape('id' => ?string, 'url' => ?string, 'count' => int); function get_IdSet(): IdSet { return shape('id' => null, 'url' => null, 'count' => 0); } class Point { private float $x; private float $y; public function __construct(num $x = 0, num $y = 0) { $this->x = (float)$x; // sets private property $x $this->y = (float)$y; // sets private property $y } // no return statement public function move(num $x = 0, num $y = 0): void { $this->x = (float)$x; // sets private property $x $this->y = (float)$y; // sets private property $y return; // return nothing } // ... } ``` However, for an async function having a `void` return type, an object of type `Awaitable<void>` is returned. For an async function, the value having a non-`void` return type, the return value is wrapped in an object of type `Awaitable<T>` (where `T` is the type of the return value), which is returned. Returning from a constructor behaves just like returning from a function having a return type of `void`. The value returned by a [generator function](../expressions-and-operators/yield.md) must be the literal `null`. A `return` statement inside a generator function causes the generator to terminate. A return statement must not occur in a finally block or in a function declared [`noreturn`](../built-in-types/noreturn.md).
Markdown
hhvm/hphp/hack/manual/hack/04-statements/08-switch.md
A `switch` statement typically consists of a controlling expression, some case labels, and optionally a default label. Based on the value of the controlling expression, execution passes to one of the case labels, the default label, or to the statement immediately following the switch statement. For example: ```Hack no-extract enum Bank: int { DEPOSIT = 1; WITHDRAWAL = 2; TRANSFER = 3; } function processTransaction(Transaction $t): void { $trType = ...; // get the transaction type as an enum value switch ($trType) { case Bank::TRANSFER: // ... break; case Bank::DEPOSIT: // ... break; case Bank::WITHDRAWAL: // ... break; } } ``` The `switch` has case labels for each of the possible value of `enum Bank`, where a case label is the keyword `case` followed by an expression, followed by `:`, followed by zero or more statements. Note that the so-called body of a case label need *not* be made a compound statement; the set of statements associated with a particular case label ends with a `break` statement or the closing brace (`}`) of the `switch` statement. A default label is used as a catch-all. In the enumerated-type example above, assuming all possible values of type `enum Bank` have corresponding case labels, no default label is needed, as no other values can exist! However, that is not true when the switch controlling expression has type `int`. Here, we're unlikely to have case labels cover the complete range of `int` values, so a default label might be necessary. For example: ```Hack $v = 100; switch ($v) { case 20: // ... break; case 10: // ... break; case 30: // ... break; default: // ... break; } ``` A default label is the keyword `default`, followed by `:`, followed by zero or more statements. Note that the so-called body of a default label need *not* be made a compound statement; the set of statements associated with a particular default label ends with a `break` statement or the closing brace (`}`) of the `switch` statement. If a `switch` contains more than one case label whose values compare equal to the controlling expression, the first in lexical order is considered the match. An arbitrary number of statements can be associated with any case or default label. In the absence of a `break` statement at the end of a set of such statements, control drops through into any following case or default label. Thus, if all cases and the default end in `break` and there are no duplicate-valued case labels, the order of case and default labels is insignificant. If no `break` statement is seen for a case or default before a subsequent case label, default label, or the switch-terminating `}` is encountered, an implementation might issue a warning. However, such a warning can be suppressed by placing a source line containing the special comment `// FALLTHROUGH`, at the end of that case or default statement group. ```Hack $v = 10; switch ($v) { case 10: // ... // FALLTHROUGH case 30: // ... // Handle 10 or 30 break; default: // ... break; } ``` Case-label values can be runtime expressions, and the types of sibling case-label values need not be the same. **Note switch uses `==` equality for comparing the value with the different cases.**. See [equality](../expressions-and-operators/equality.md) for more details. ```Hack $v = 30; switch ($v) { case 30.0: // <===== this case matches with 30 // ... break; default: // ... break; } ```
Markdown
hhvm/hphp/hack/manual/hack/04-statements/09-try.md
An *exception* is some unusual condition in that it is outside the ordinary expected behavior. (Examples include dealing with situations in which a critical resource is needed, but is unavailable, and detecting an out-of-range value for some computation.) As such, exceptions require special handling. Whenever some exceptional condition is detected at runtime, an exception is thrown using [`throw`](throw.md). A designated exception handler can *catch* the thrown exception and service it. Among other things, the handler might recover from the situation completely (allowing the script to continue execution), it might perform some recovery and then throw an exception to get further help, or it might perform some cleanup action and terminate the script. Exceptions may be thrown on behalf of the runtime or by explicit code source code in the script. A `throw` statement throws an exception immediately and unconditionally. Control never reaches the statement immediately following the throw. For example: ```Hack class MyException extends Exception {} function demo(): void { throw new MyException(); } ``` The type of the exception must be `Throwable` or a subclass of `Throwable`. Exception handling involves the use of the following keywords: * `try`, which allows a *try-block* of code containing one or more possible exception generations, to be tried * `catch`, which defines a handler for a specific type of exception thrown from the corresponding try-block or from some function it calls * `finally`, which allows the *finally-block* of a try-block to be executed (to perform some cleanup, for example), whether or not an exception occurred within that try-block * `throw`, which generates an exception of a given type, from a place called a *throw point*. Consider the following: ```Hack function do_it(int $x, int $y): void { try { $result = $x / $y; echo "\$result = $result\n"; // ... } catch (DivisionByZeroException $ex) { echo "Caught a DivisionByZeroException\n"; // ... } catch (Exception $ex) { echo "Caught an Exception\n"; // ... } } ``` Here, we put the statement that might lead to an exception inside a try-block, which has associated with it one or more catch-blocks. If and only an exception of that type is thrown, is the catch handler code executed. Consider the following hierarchy of exception-class types: ```Hack class DeviceException extends Exception { /*...*/ } class DiskException extends DeviceException { /*...*/ } class RemovableDiskException extends DiskException { /*...*/ } class FloppyDiskException extends RemovableDiskException { /*...*/ } function process(): void { throw new DeviceException(); } <<__EntryPoint>> function main(): void { try { process(); // call a function that might generate a disk-related exception } catch (FloppyDiskException $fde) { echo "In handler for FloppyDiskException\n"; // ... } catch (RemovableDiskException $rde) { echo "In handler for RemovableDiskException\n"; // ... } catch (DiskException $de) { echo "In handler for DiskException\n"; // ... } catch (DeviceException $dve) { echo "In handler for DeviceException\n"; // ... } finally { echo "In finally block\n"; // perform some cleanup } } ``` The order of the catch-blocks is important; they are in decreasing order of type specialization. The optional finally-clause is executed **whether or not** an exception is caught. In a catch-clause, the variable-name (such as `$fde` and `$rde` above) designates an exception variable passed in by value. This variable corresponds to a local variable with a scope that extends over the catch-block. During execution of the catch-block, the exception variable represents the exception currently being handled. Once an exception is thrown, the runtime searches for the nearest catch-block that can handle the exception. The process begins at the current function level with a search for a try-block that lexically encloses the throw point. All catch-blocks associated with that try-block are considered in lexical order. If no catch-block is found that can handle the run-time type of the exception, the function that called the current function is searched for a lexically enclosing try-block that encloses the call to the current function. This process continues until a catch-block is found that can handle the current exception. If a matching catch-block is located, the runtime prepares to transfer control to the first statement of that catch-block. However, before execution of that catch-block can start, the runtime first executes, in order, any finally-blocks associated with try-blocks nested more deeply than the one that caught the exception. If no matching catch-block is found, the behavior is implementation-defined.
Markdown
hhvm/hphp/hack/manual/hack/04-statements/10-use.md
The `use` statement permits names defined in one namespace to be introduced into another namespace, so they can be referenced there by their simple name rather than their (sometimes very long) fully qualified name. The `use` statement can only be present at the top level. Consider the following: ```Hack file:use.hack namespace UseNS { const int CON = 100; function f(): void { echo "In function ".__FUNCTION__."\n"; } class C { public function f(): void { echo "In method ".__METHOD__."\n"; } } class D {} class E {} } namespace Hack\UserDocumentation\Statements\use\Examples\XXX { const int CON2 = 500; function f(): void { echo "In function ".__FUNCTION__."\n"; } } namespace Hack\UserDocumentation\Statements\use\Examples\test { use const UseNS\CON; use function UseNS\f; //use function Hack\UserDocumentation\Statements\use\Examples\XXX\f; // Error: name f already declared use type UseNS\C; use type UseNS\{D, E}; use namespace Hack\UserDocumentation\Statements\use\Examples\XXX; <<__EntryPoint>> function main(): void { // access const CON by fully qualified and abbreviated names echo "CON = ".\UseNS\CON."\n"; echo "CON = ".CON."\n"; // access function f by fully qualified and abbreviated names \UseNS\f(); f(); // access type C by fully qualified and abbreviated names $c = new \UseNS\C(); $c->f(); $c = new C(); $c->f(); // access type D by fully qualified and abbreviated names $d = new \UseNS\D(); $d = new D(); // access name f by fully qualified and abbreviated names \Hack\UserDocumentation\Statements\use\Examples\XXX\f(); XXX\f(); // access name CON2 by fully qualified and abbreviated names echo "XXX\CON2 = ". \Hack\UserDocumentation\Statements\use\Examples\XXX\CON2. "\n"; echo "XXX\\CON2 = ".XXX\CON2."\n"; } } ``` Namespace `UseNS` contains a definition for a constant `CON`. From within namespace `Hack\UserDocumentation\Statements\use\Examples\test`, we can access that constant by its fully qualified name, `\UseNS\CON`, as shown in `main`. However, if we write `use const UseNS\CON;`, we can access that constant's name simply as `CON`. In the same manner, we can have `use type` and `use function` introduce type and function names, respectively. And as we can see with `use type UseNS\{D, E};`, we can introduce a comma-separated list of names of the same kind in a single statement. Note that we have two functions called `f`, defined in separate namespaces. If we attempt to introduce the same name from more than one namespace, references to that name would be ambiguous, so this is disallowed. In the case of `use namespace`, we can implicitly reference names inside the given namespace by using a prefix that is the right-most part of the fully qualified name. For example, once ```Hack file:use.hack namespace { use namespace Hack\UserDocumentation\Statements\use\Examples\XXX; } ``` has been seen, we can access `CON2` via the abbreviated `XXX\CON2`. Note that names in `use` statements are always fully qualified, they don't need to be prefixed with `\`.
Markdown
hhvm/hphp/hack/manual/hack/04-statements/11-using.md
A `using` statement is used to enforce [object disposal](../classes/object-disposal.md). It has two forms: block and non-block. Here is an example of the block form: ```Hack no-extract using ($f1 = new TextFile("file1.txt", "rw")) { // ... work with the file } // __dispose is called here ``` The type of the expression inside the parentheses must implement either `IDisposable` (or `IAsyncDisposable`). The scope of `$f1` is the `using` block, and at the end of that scope, `__dispose` (or `__disposeAsync`) is called. If the assignment (as in, `$f1 = `) is omitted, we cannot access the object directly inside the block. Within the block, there are limits to what we can do with `$f1`. Specifically, we *cannot* assign to it again or make copies of it. And to pass it to a function, we must mark the function's corresponding parameter with the [attribute __AcceptDisposable](../attributes/predefined-attributes.md#__AcceptDisposable). We can also call methods on the object that `$f1` designates. Consider the following: ```Hack no-extract using ($f1 = new TextFile("file1.txt", "rw")) { // echo "\$f1 is >" . $f1 . "<\n"; // usage not permitted echo "\$f1 is >" . $f1->__toString() . "<\n"; // ... } ``` Note the commented-out trace statement at the start of the block. Under the hood, we're trying to pass a copy of a TextFile to `echo`, but `echo` doesn't know anything about TextFile's object cleanup, so that is rejected. We can, however, directly call a method on that object, which is why `__toString` is called explicitly in the statement following. Here is an example of the non-block form: ```Hack no-extract function foo(): void { using $f4 = TextFile::open_TextFile("file4.txt", "rw"); using $f5 = new TextFile("file5.txt", "rw"); // ... work with both files } // __dispose is called here for both $f4 and $f5 ``` The difference here is that no parentheses are required around the controlling expression, we use a trailing semicolon instead of a block, and the scope of the assigned-to variables ends at the end of the parent block, which avoids the need to use nested `using` statements. See [object disposal](../classes/object-disposal) for a detailed example of the use of both forms.
Markdown
hhvm/hphp/hack/manual/hack/04-statements/12-while.md
The general format of a `while` statement is `while (` *expression* ` )` *statement* If the expression tests `true`, the *single* statement that follows is executed, and the process is repeated. If the expression tests `false`, control transfers to the point immediately following the end of the `while` statement. The loop body (that is, the single statement) is executed zero or more times. Consider the following: ```Hack $i = 1; while ($i <= 10) { echo "$i\t".($i * $i)."\n"; // output a table of squares ++$i; } ``` The execution of a `while` statement is impacted by a subordinate [`break` or `continue`](break-and-continue.md). The controlling expression is often a combination of relational, equality, and logical expressions. For example: ```Hack no-extract while (($i <= 10 && $j !== 0) || !getStatus()) { // ... } ``` The controlling expression must have type `bool` or a type that can be implicitly converted to `bool`. For example, in `while (1)` ..., `while (123)` ..., and `while (-1.234e24)` ..., in each case, the value of the expression is non-zero, which is implicitly converted to `true`. Only zero-values are converted to `false`. The `do`/`while` statement behaves slightly differently than `while` in that the former executes the loop body *before* it tests the controlling expression, whereas `while` executes it after.
Markdown
hhvm/hphp/hack/manual/hack/05-functions/01-introduction.md
The `function` keyword defines a global function. ```Hack function add_one(int $x): int { return $x + 1; } ``` The `function` keyword can also be used to define [methods](/hack/classes/methods). ## Default Parameters Hack supports default values for parameters. ```Hack function add_value(int $x, int $y = 1): int { return $x + $y; } ``` This function can take one or two arguments. `add_value(3)` returns 4. Required parameters must come before optional parameters, so the following code is invalid: ```Hack error function add_value_bad(int $x = 1, int $y): int { return $x + $y; } ``` ## Variadic Functions You can use `...` to define a function that takes a variable number of arguments. ```Hack file:sumints.hack function sum_ints(int $val, int ...$vals): int { $result = $val; foreach ($vals as $v) { $result += $v; } return $result; } ``` This function requires at least one argument, but has no maximum number of arguments. ```Hack file:sumints.hack // Passing positional arguments. sum_ints(1, 2, 3); // You can also pass a collection into a variadic parameter. $args = vec[1, 2, 3]; sum_ints(0, ...$args); ``` ## Function Types Functions are values in Hack, so they can be passed as arguments too. ```Hack function apply_func(int $v, (function(int): int) $f): int { return $f($v); } function usage_example(): void { $x = apply_func(0, $x ==> $x + 1); } ``` Variadic functions can also be passed as arguments. ```Hack function takes_variadic_fun((function(int...): void) $f): void { $f(1, 2, 3); $args = vec[1, 2, 3]; $f(0, ...$args); } ```
Markdown
hhvm/hphp/hack/manual/hack/05-functions/02-anonymous-functions.md
Hack supports anonymous functions. In the example below, the anonymous function, `$f`, evaluates to a function that returns the value of `$x + 1`. ``` Hack $f = $x ==> $x + 1; $two = $f(1); // result of 2 ``` To create an anonymous function with more than one parameter, surround the parameter list with parentheses: ``` Hack $f = ($x, $y) ==> $x + $y; $three = $f(1, 2); // result of 3 ``` Anonymous functions pass _by value_, not by reference. This is also true for any [object property](../expressions-and-operators/member-selection) passed to an anonymous function. ``` Hack $x = 5; $f = $x ==> $x + 1; $six = $f($x); // pass by value echo($six); // result of 6 echo("\n"); echo($x); // $x is unchanged; result of 5 ``` If you need to mutate the reference, use the HSL `Ref` class. ## Type Inference Unlike named functions, type annotations are optional on anonymous functions. You can still add explicit types if you wish. ``` Hack $f = (int $x): int ==> $x + 1; ``` HHVM will enforce type annotations if they are provided. If typechecking cannot infer a type for a function, it will show an error, and you will need to provide a type. Adding explicit type annotations can also help the typechecker run faster. ## Fat Arrow Syntax `==>` defines an anonymous function in Hack. An anonymous function can be a single expression, or a block. ``` Hack $f1 = $x ==> $x + 1; $f2 = $x ==> { return $x + 1; }; ``` ## Legacy PHP-Style Syntax Hack also supports an anonymous function syntax similar to PHP. These are less flexible, so we recommend using fat arrow syntax. ``` Hack $f = function($x) { return $x + 1; }; ``` PHP-style lambdas require an explicit `{ ... }` block. PHP-style lambdas also require `use` to refer to enclosing variables. Fat arrow lambdas do not require this. ``` Hack $y = 1; $f = function($x) use($y) { return $x + $y; }; ``` PHP-style lambdas can also specify parameter and return types. ``` Hack $y = 1; $f = function(int $x): int use($y) { return $x + $y; }; ``` Note that this syntax is not the same as PHP 7 lambdas, which put `use` before the return type.
Markdown
hhvm/hphp/hack/manual/hack/05-functions/03-type-enforcement.md
HHVM does a runtime type check for function arguments and return values. ```Hack error function takes_int(int $_): void {} function check_parameter(): void { takes_int("not an int"); // runtime error. } function check_return_value(): int { return "not an int"; // runtime error. } ``` If a type is wrong, HHVM will raise a fatal error. This is controlled with the HHVM option `CheckReturnTypeHints`. Setting it to 0 or 1 will disable this.
Markdown
hhvm/hphp/hack/manual/hack/05-functions/05-format-strings.md
The Hack typechecker checks that format strings are being used correctly. ## Quickstart ```Hack error // Correct. Str\format("First: %d, second: %s", 1, "foo"); // Typechecker error: Too few arguments for format string. Str\format("First: %d, second: %s", 1); ``` This requires that the format string argument is a string literal, not a variable. ```Hack error $string = "Number is: %d"; // Typechecker error: Only string literals are allowed here. Str\format($string, 1); ``` ## Defining Functions with Format Strings You can define your own functions with format string arguments too. ```Hack function takes_format_string( \HH\FormatString<\PlainSprintf> $format, mixed ...$args ): void {} function use_it(): void { takes_format_string("First: %d, second: %s", 1, "foo"); } ``` `HH\FormatString<PlainSprintf>` will check that you've used the right number of arguments. `HH\FormatString<Str\SprintfFormat>` will also check that arguments match the type in the format string. ## Format Specifiers See `PlainSprintf` for in-depth information on all format specifiers. | Specifier | Expected Input | Expected Output | |-----------|----------------|---------------------------------------------------------------------------------------------------------------------| | b | int | Binary (`63` => `111111`) | | c | int | ASCII character (`63` => `?`) | | d | int | Signed int (`-1` => `-1`) | | u | int | Unsigned int (`-1` => `18446744073709551615`) | | e | float | Scientific Notation, as lowercase (`0.34` => `3.4e`) | | E | float | Scientific Notation, as uppercase (`0.34` => `3.4E`) | | f | float | Locale Floating Point Number | | F | float | Non-Locale Floating Point Number | | g | float | Locale Floating Point Number or Scientific Notation (`3.141592653` => `3.14159`, `3141592653` => `3.1415e+9`). | | o | int | Octal (`63` => `77`) | | s | string | string | | x | int | Hexadecimal, as lowercase (`63` => `3f`) | | X | int | Hexadecimal, as uppercase (`63` => `3F`) |
Markdown
hhvm/hphp/hack/manual/hack/05-functions/20-inout-parameters.md
Hack functions normally pass arguments by value. `inout` provides "copy-in, copy-out" arguments, which allow you to modify the variable in the caller. ```Hack function takes_inout(inout int $x): void { $x = 1; } function call_it(): void { $num = 0; takes_inout(inout $num); // $num is now 1. } ``` This is similar to copy-by-reference, but the copy-out only happens when the function returns. If the function throws an exception, no changes occur. ```Hack function takes_inout(inout int $x): void { $x = 1; throw new Exception(); } <<__EntryPoint>> function call_it(): void { $num = 0; try { takes_inout(inout $num); } catch (Exception $_) { } // $num is still 0. } ``` `inout` must be written in both the function signature and the function call. This is enforced in the typechecker and at runtime. ## Indexing with `inout` In addition to local variables, `inout` supports indexes in value types. ```Hack function set_to_value(inout int $item, int $value): void { $item = $value; } function use_it(): void { $items = vec[10, 11, 12]; $index = 1; set_to_value(inout $items[$index], 42); // $items is now vec[10, 42, 12]. } ``` This works for any value type: `vec`, `dict`, `keyset` or `array`. You can also do nested access e.g. `inout $foo[$y][z()]['stuff']`. ## Dynamic Usage `inout` is a different calling convention, so dynamic calls will not work with `inout` parameters. For example, you cannot use `meth_caller`, `call_user_func` or `ReflectionFunction::invoke`. `unset` on a `inout` parameter will set the value to `null`. This is not recommended, and will raise a warning when the function returns.
Markdown
hhvm/hphp/hack/manual/hack/05-functions/30-function-references.md
It is often useful to refer to a function (or a [method](https://docs.hhvm.com/hack/classes/methods)) without actually calling it&mdash;for example, as an argument for functions like `Vec\map`. **Note:** The following syntax is only supported since HHVM 4.79. For older HHVM versions, see [old syntax](#old-syntax) below. To refer to a top-level (global) function named `foo`, you can write: ```Hack no-extract foo<>; // a reference to global function 'foo' ``` You can think of it like it’s a function call with empty generics, but the list of arguments has been omitted (the missing parentheses). The following example stores a function reference in a variable and later calls the function. Note that the type checker keeps track of the [function's type](/hack/built-in-types/function) and correctly checks all calls. ```Hack no-extract function foo(string $x): bool { ... } $x = foo<>; // $x:(function(string): bool) $y = $x('bar'); // $y:bool $_ = $x(-1); // error! ``` This syntax supports namespaced names the same way you would refer to them as part of a function call, so the following function references are all equivalent: ```Hack no-extract $fun = \Foo\Bar\Baz\derp<>; ``` ```Hack no-extract namespace Foo; $fun = Bar\Baz\derp<>; ``` ```Hack no-extract use namespace Foo\Bar\Baz; $fun = Baz\derp<>; ``` ```Hack no-extract use function Foo\Bar\Baz\derp; $fun = derp<>; ``` ## Static methods Similarly, you can refer to a static method `bar` on a class `MyClass` by using the familiar method call syntax, without providing the call arguments. Just append type arguments (like `<>`) to the function call receiver (like `MyClass::bar`). ```Hack no-extract MyClass::bar<>; // a reference to static method 'MyClass::bar' ``` - **Private/protected** methods can be referenced using this syntax as long as they are accessible to you in your local scope (the scope where the reference is created). The returned reference can then be called from any scope. - **Abstract** static methods cannot be referenced. Such methods cannot be called, for they have no implementation. Invoking a hypothetical reference to one would also be an error, so we simply don’t allow a reference to be created. - In traits and other classes that are not marked `final`, you cannot use `self::` in a reference. This is to avoid ambiguity and confusion around what `self` actually refers to when the method is called (it depends on the static context of a call, whereas function references can never receive the context information because the target is only resolved once). - Also, `parent::` is never supported. ## Generics If you wish to pass along explicit generic arguments, either as a hint to the type checker, or in the case of a function with reified type parameters when they are required, that is also supported: ```Hack no-extract i_am_erased<int, _>; // erased generics (note wildcard) i_am_reified<C<string>>; // a reified generic ``` - Keep in mind that generics, if any, still must be provided at the location where the function reference is created, rather than where it is used/invoked. - The arity of the type argument list, if it is non-empty (i.e. not `<>`), must match the declaration, just like for an ordinary function call. - The special wildcard specifier `_` may be provided in place of any or all erased (non-reified) generic arguments if you want Hack to infer a type automatically based on the type parameter’s constraints. Again this is the same as for ordinary function calls. Example with erased generics: ```Hack no-extract function fizz<Ta as num, Tb>(Ta $a, Tb $b): mixed { ... } $x = fizz<int, string>; // OK $x(4, 'hello'); $x(-1, false); // error! $y = fizz<>; $y(3.14, new C()); // also OK $y('yo', derp()); // error! // OK as well $z = fizz<int, _>; $z = fizz<_, string>; $z = fizz<_, _>; // these all have errors! fizz<_>; fizz<string, _>; fizz<string, int>; ``` Example with [reified generics](/hack/generics/reified-generics): ```Hack no-extract function buzz<reify T as arraykey>(T $x): mixed { ... } $w = buzz<int>; // OK $w(42); $w("goodbye"); // error! // these all have errors! buzz<>; buzz<_>; buzz<mixed>; ``` ## Introspection Function references can be cached in APC (the name will be resolved again when they are retrieved) or passed to memoized functions. However, other serialization formats are not supported. Internally, function/method references are represented using special data types that are intended to be opaque. This means they cannot (or should not) be cast directly to a string or another type, or be accessed in any other way besides calling them. If you need to determine what a function reference is pointing to, e.g. for use in logging messages, and you know enough about the expected input and output formats, HHVM provides the following helpers (but note they are not well supported and may change): * `HH\is_fun` * `HH\fun_get_function` * `HH\is_class_meth` * `HH\class_meth_get_class` * `HH\class_meth_get_method` Be very careful and deliberate when using these, as they are loosely typed but will throw exceptions for bad arguments. <span data-nosnippet class="fbOnly fbIcon">In Meta's WWW repository, prefer using higher level wrappers such as the `HackCallable` class, or `ReflectionFunctionProdUtils` outside of intern code.</span> ## Old syntax Before HHVM 4.79, there was no special syntax for function references. However, the built-in functions `fun` and `class_meth` can be used for the same purpose. For HHVM versions that support both options, the returned function references are identical, e.g. `foo<>` is equivalent to `fun('foo')`. There is also no equivalent syntax for referencing non-static methods. For those, use the built-in functions `inst_meth` and `meth_caller`, or use an [anonymous function](anonymous-functions) instead: ```Hack no-extract class C { public function foo(): void {} } $obj = new C(); $fun1 = inst_meth($obj, 'foo'); $fun2 = () ==> $obj->foo(); // calling $fun1() is equivalent to calling $fun2() ```
Markdown
hhvm/hphp/hack/manual/hack/06-classes/01-introduction.md
Classes provide a way to group functionality and state together. To define a class, use the `class` keyword. ```Hack class Counter { private int $i = 0; public function increment(): void { $this->i += 1; } public function get(): int { return $this->i; } } ``` To create an instance of a class, use [`new`](../expressions-and-operators/new.md), e.g. `new Counter();`.
Markdown
hhvm/hphp/hack/manual/hack/06-classes/03-methods.md
A method is a function defined in a class. ```Hack file:person.hack class Person { public string $name = "anonymous"; public function greeting(): string { return "Hi, my name is ".$this->name; } } ``` To call an instance method, use `->`. ```Hack file:person.hack $p = new Person(); echo $p->greeting(); ``` You can access the current instance with `$this` inside a method. ## Static Methods A static method is a function in a class that is called without an instance. Since there's no instance, `$this` is not available. ```Hack file:person2.hack class Person { public static function typicalGreeting(): string { return "Hello"; } } ``` To call a static method, use `::`. ```Hack file:person2.hack echo Person::typicalGreeting(); ```
Markdown
hhvm/hphp/hack/manual/hack/06-classes/05-properties.md
A property is a variable defined inside a class. ```Hack file:intbox.hack class IntBox { public int $value = 0; } ``` Instance properties are accessed with `->`. Every instance has a separate value for an instance property. ```Hack file:intbox.hack $b = new IntBox(); $b->value = 42; ``` Note that there is no `$` used when accessing `->value`. ## Initializing Properties Properties in Hack must be initialized. You can provide a default value, or assign to them in the constructor. ```Hack class HasDefaultValue { public int $i = 0; } class SetInConstructor { public int $i; public function __construct() { $this->i = 0; } } ``` Properties with nullable types do not require initial values. They default to `null` if not set. ```Hack class MyExample { public mixed $m; public ?string $s; } ``` ## Static Properties A static property is a property that is shared between all instances of a class. ```Hack file:example.hack class Example { public static int $val = 0; } ``` Static properties are accessed with `::`. ```Hack file:example.hack Example::$val; ``` If your property never changes value, you might want to use a class constant instead. ## The Property Namespace Properties and methods are in different namespaces. It's possible to have a method and a property with the same name. ```Hack file:intbox_prop.hack class IntBox { public int $value = 0; public function value(): int { return $this->value; } } ``` (Reusing a name like this is usually confusing. We recommend you use separate names.) If there are parentheses, Hack knows it's a method call. ```Hack file:intbox_prop.hack $b = new IntBox(); $b->value(); // method call $b->value; // property access ``` If you have a callable value in a property, you will need to be explicit that you're accessing the property. ```Hack file:funbox.hack class FunctionBox { public function __construct(public (function(): void) $value) {} } ``` Use parentheses to access and call the wrapped function. ```Hack file:funbox.hack $b = new FunctionBox(() ==> { echo "hello"; }); ($b->value)(); ```
Markdown
hhvm/hphp/hack/manual/hack/06-classes/06-inheritance.md
Hack supports single inheritance between classes. ``` Hack class IntBox { public function __construct(protected int $value) {} public function get(): int { return $this->value; } } class MutableIntBox extends IntBox { public function set(int $value): void { $this->value = $value; } } ``` Classes can access things defined in the parent class, unless they are `private`. ## Overriding Methods You can override methods in subclasses by defining a method with the same name. ``` Hack class IntBox { public function __construct(protected int $value) {} public function get(): int { return $this->value; } } class IncrementedIntBox extends IntBox { <<__Override>> public function get(): int { return $this->value + 1; } } ``` If a method is intended to override a method in a parent class, you should annotate it with `<<__Override>>`. This has no runtime effect, but ensures you get a type error if the parent method is removed. Hack does not support method overloading. Subclasses methods must have a return type, parameters and visibility that is compatible with the parent class. ``` Hack class NumBox { public function __construct(protected num $value) {} protected function get(): num { return $this->value; } } class FloatBox extends NumBox { <<__Override>> public function get(): float { return (float)$this->value; } } ``` The only exception is constructors, which may have incompatible signatures with the parent class. You can use `<<__ConsistentConstruct>>` to require subclasses to have compatible types. ``` Hack class User { // This constructor takes one argument. public function __construct(protected string $name) {} } class Player extends User { // But this constructor takes two arguments. <<__Override>> public function __construct(protected int $score, string $name) { parent::__construct($name); } } ``` ## Calling Overridden Methods You can use `parent::` to call an overridden method in the parent class. ``` Hack class IntBox { public function __construct(protected int $value) {} public function get(): int { return $this->value; } } class IncrementedIntBox extends IntBox { <<__Override>> public function get(): int { return parent::get() + 1; } } ``` This also works for static methods. ``` Hack class MyParent { public static function foo(): int { return 0; } } class MyChild extends MyParent { <<__Override>> public static function foo(): int { return parent::foo() + 1; } } ``` ## Abstract Classes An abstract class cannot be instantiated. ``` Hack abstract class Animal { public abstract function greet(): string; } class Dog extends Animal { <<__Override>> public function greet(): string { return "woof!"; } } ``` This allows `new Dog()` but not `new Animal()`. Abstract classes are similar to [interfaces](implementing-an-interface.md), but they can include implementations of methods. ## Final Classes A final class cannot have subclasses. ``` Hack final class Dog { public function greet(): string { return "woof!"; } } ``` If your class has subclasses, but you want to prevent additional subclasses, use `<<__Sealed>>`. If you want to inherit from a final class for testing, use `<<__MockClass>>`. You can also combine `final` and `abstract` on classes. This produces a class that cannot be instantiated or have subclasses. The class is effectively a namespace of grouped functionality. ``` Hack abstract final class Example { public static function callMe(int $i): int { return static::helper($i); } private static function helper(int $i): int { return $i + 1; } } ``` ## Final Methods A `final` method cannot be overridden in subclasses. ``` Hack class IntBox { public function __construct(protected int $value) {} final public function get(): int { return $this->value; } } ```
Markdown
hhvm/hphp/hack/manual/hack/06-classes/16-constructors.md
A constructor is a specially named instance method that is used to initialize the instance immediately after it has been created. A constructor is called by the [`new` operator](../expressions-and-operators/new.md). For example: ```Hack class Point { private static int $pointCount = 0; // static property with initializer private float $x; // instance property private float $y; // instance property public function __construct(num $x = 0, num $y = 0) { // instance method $this->x = (float)$x; // access instance property $this->y = (float)$y; // access instance property ++Point::$pointCount; // include new Point in Point count } } function demo(): void { $p1 = new Point(2.3); } ``` A constructor has the name `__construct`. As such, a class can have only one constructor. (Hack does *not* support method overloading.) When `new Point` causes the constructor to be called, the argument 2.3 maps to the parameter `$x`, and the default value 0 is mapped to the parameter `$y`. The constructor body is then executed, which results in the instance properties being initialized and the Point count being incremented. Note that a constructor may call any *private* method in its class, but no public methods. A constructor does not require a return type, but if one is included, it must be `void`. ## Constructor parameter promotion If you have created a class in Hack, you have probably seen a pattern like this: ```Hack final class User { private int $id; private string $name; public function __construct( int $id, string $name, ) { $this->id = $id; $this->name = $name; } } ``` The class properties are essentially repeated multiple times: at declaration, in the constructor parameters and in the assignment. This can be quite cumbersome. With *constructor parameter promotion*, all that repetitive boilerplate is removed. ```Hack final class User { public function __construct( private int $id, private string $name, ) {} } ``` All you do is put a visibility modifier in front of the constructor parameter and everything else in the previous example is done automatically, including the actual creation of the property. **Note:** Promotion can only be used for constructor parameters with name and type that exactly match the respective class property. For example, we couldn't use it in the `Point` class above because we wanted the properties to have type `float`, so any arithmetic coordinate value can be represented, yet we wanted the constructor parameters to have type `num`, so either integer or floating-point values can be passed in. Don't hesitate to &ldquo;un-promote&rdquo; a constructor parameter if it later turns out that a different internal data representation would be better. For example, if we later decided to store `$name` in a structured form instead of a string, we could easily make that change while keeping the public-facing constructor parameters unchanged (and therefore backwards-compatible). ```Hack no-extract final class User { private ParsedName $name; public function __construct( private int $id, string $name, ) { $this->name = parse_name($name); } } ``` ### Rules * A modifier of `private`, `protected` or `public` must precede the parameter declaration in the constructor. * Other, non-class-property parameters may also exist in the constructor, as normal. * Type annotations must go between the modifier and the parameter's name. * The parameters can have a default value. * Other code in the constructor is run **after** the parameter promotion assignment. ```Hack final class User { private static dict<int, User> $allUsers = dict[]; private int $age; public function __construct( private int $id, private string $name, // Promoted parameters can be combined with regular non-promoted parameters. int $birthday_year, ) { $this->age = \date('Y') - $birthday_year; // The constructor parameter promotion assignments are done before the code // inside the constructor is run, so we can use $this->id here. self::$allUsers[$this->id] = $this; } } ```
Markdown
hhvm/hphp/hack/manual/hack/06-classes/18-constants.md
A class can contain definitions for named constants. Because a class constant belongs to the class as a whole, it is implicitly `static`. For example: ```Hack class Automobile { const DEFAULT_COLOR = "white"; // ... } <<__EntryPoint>> function main(): void { $col = Automobile::DEFAULT_COLOR; // or: $col = self::DEFAULT_COLOR; echo "\$col = $col\n"; } ``` ## Visibility Class constants are always public, and can not be explicitly declared as `public`, `protected`, or `private`. ## Selection Inside a parent class, use `self::foo` to access a named constant `foo`. Outside a parent class, a class constant's name must be fully qualified with the class and constant name (e.g. `Bar::foo`). For more information, see [scope-resolution operator, `::`](/hack/expressions-and-operators/scope-resolution). ## Type Inference If a class constant's type is omitted, it can be inferred. For example: * the inferred type of `const DEFAULT_COLOR = "white"` is `string`, * the inferred type of `const DEFAULT_VALUE = 42` is `int`. * the inferred type of `const DEFAULT_FOODS = vec["apple", "orange", "banana"]` is `vec`. ## Limitations Constants can not be assigned to legacy container types like `Vector`, `Map`, `Set`, et al., and closures. Instead, create constants with equivalent types like `array`, `vec`, `dict`, and `set`. When using these types, all subinitializers must resolve to constant expressions.
Markdown
hhvm/hphp/hack/manual/hack/06-classes/19-type-constants.md
Type constants provide a way to abstract a type name. However, type constants only make sense in the context of interfaces and inheritance hierarchies, so they are discussed under those topics. For now, the declaration of a type constant involves the keywords `const type`. Without explanation, here's an example: ```Hack abstract class CBase { abstract const type T; // ... } class CString extends CBase { const type T = string; // ... } ``` A type constant has public visibility and is implicitly static. By convention, type constant names begin with an uppercase `T`. See [inheritance](inheritance.md) and [type constants revisited](type-constants-revisited.md) for more information.
Markdown
hhvm/hphp/hack/manual/hack/06-classes/21-object-disposal.md
Modern programming languages allow resources to be allocated at runtime, under programmer control. However, in the case where explicit action must be taken to free such resources, different languages have different approaches. Some languages use a *destructor* for cleanup, while others use a *finalizer*, which is called by a garbage collector, sometime, maybe! Hack uses a *dispose* approach, which is tied to object scope. In the following example, we define and use type `TextFile` to encapsulate a text file. When we are done with such a file, we need to make sure that output buffers are flushed, among other things. Let us call these tasks *object cleanup*. (The example is skeletal; it has only the minimal machinery needed to demonstrate object disposal.) ```Hack class TextFile implements \IDisposable { private ?int $fileHandle = null; private bool $openFlag = false; private string $fileName; private string $openMode; public function __construct(string $fileName, string $openMode) { $this->fileHandle = 55; // open file somehow and store handle $this->openFlag = true; // file is open $this->fileName = $fileName; $this->openMode = $openMode; } public function close(): void { if ($this->openFlag === false) { return; } // ... somehow close the file $this->fileHandle = null; $this->openFlag = false; echo "Closed file $this->fileName\n"; } public function __toString(): string { return 'fileName: '. $this->fileName. ', openMode: '. $this->openMode. ', fileHandle: '. (($this->fileHandle === null) ? "null" : $this->fileHandle). ', openFlag: '. (($this->openFlag) ? "True" : "False"); } public function __dispose(): void { echo "Inside __dispose\n"; $this->close(); } <<__ReturnDisposable>> public static function open_TextFile( string $fileName, string $openMode, ): TextFile { return new TextFile($fileName, $openMode); } public function is_same_TextFile(<<__AcceptDisposable>> TextFile $t): bool { return $this->fileHandle === $t->fileHandle; } // other methods, such as read and write } <<__EntryPoint>> function main(): void { using ($f1 = new TextFile("file1.txt", "rw")) { // echo "\$f1 is >" . $f1 . "<\n"; // usage not permitted echo "\$f1 is >".$f1->__toString()."<\n"; // work with the file $f1->close(); // close explicitly $f1->close(); // try to close again } // dispose called here using ($f2 = new TextFile("file2.txt", "rw")) { echo "\$f2 is >".$f2->__toString()."<\n"; // work with the file // no explicit close } // dispose called here using ($f3 = TextFile::open_TextFile("file3.txt", "rw")) { echo "\$f3 is >".$f3->__toString()."<\n"; // work with the file // no explicit close } // dispose called here using $f4 = TextFile::open_TextFile("file4.txt", "rw"); echo "\$f4 is >".$f4->__toString()."<\n"; using $f5 = new TextFile("file5.txt", "rw"); echo "\$f5 is >".$f5->__toString()."<\n"; // work with both files // no explicit close } // dispose called here for both $f4 and $f5 ``` A class for which we wish to provide cleanup *must* implement the interface `IDisposable`, which requires that class to define a public method called `__dispose`, with the signature as shown. As expected, the constructor initializes the new object's state. (Note that because the physical-file open details have been omitted, each instance gets the hard-coded handle value of 55 rather than a unique value.) Method `close` provides a way to do cleanup under programmer control, **presuming the programmer remembers to do that!** However, we provide a mechanism via the `openFlag` property to be sure we're not trying to cleanup more than once. Let's look at the `using` block at the start of function `main`. The expression controlling that construct *must* have a type that implements the interface `IDisposable`, and the scope of the local variable `$f1` is the using block. Note the commented-out trace statement at the start of the block. Under the hood, we're trying to pass a copy of a TextFile to `echo`, but `echo` doesn't know anything about TextFile's object cleanup, so that is rejected. We can, however, call a method on that object, which is why `__toString` is called explicitly in the statement following. (Later, we'll show how to allow copying of objects needing cleanup.) When we are done with the file, we call `close`, which performs the necessary cleanup. Then if/when we call `close` again, no new work is done. Finally, at the end of the `using` block, `$f1` goes out of scope and the runtime calls `$f1->__dispose`, which, in our case, simply calls `close`. The second `using` block is much like the first except it doesn't call `close`. Of course, the implicit call to `__dispose` does that, and the cleanup is performed then. Rather than calling the constructor to create a new instance, the third `using` block calls what is known as a *factory method*, `open_TextFile`. The challenge here is that method is returning an object with associated resources, and the consumer of that object must be ready to handle that object's cleanup or pass it on to someone who can. To allow such a method call, we must declare that it is okay to return an object subject to cleanup; we do with by marking the method with the attribute `<<__ReturnDisposable>>`, as shown. Note that once we've marked a class as implementing `IDisposable`, we can *only* instantiate that class in a `using` clause's controlling expression or in an appropriately annotated factory method. Thus far, we've processed one file at a time, but what if we wish to work with multiple text files at the same time? The fourth and fifth `using` clauses involving `$f4` and `$f5` show how. Instead of having an associated block to limit the scope, these statements end in a semicolon. As such, their local variables go out of scope at the end of their parent block, in this case, at the end of `main`, at which time, `__dispose` is called for each of them. Note carefully though, that the order in which these two calls are made is unspecified. Earlier, we discussed the problem of making copies of objects needing cleanup. Consider the method `is_same_TextFile`, which is called on one TextFile and is explicitly passed a second TextFile. By marking the parameter with the attribute `<<__AcceptDisposable>>`, we promise that we've taken care of cleanup elsewhere. That is, when the copy goes out of scope, `__dispose` must **not** be called. If classes in a class hierarchy need cleanup, it is the responsibility of the dispose method at each level to call the dispose in its base class explicitly. For objects of a class type to be used in an asynchronous context, that type must implement interface `IAsyncDisposable` instead, which requires a public method called `__disposeAsync`, like this: ```Hack class Example implements IAsyncDisposable { public async function __disposeAsync(): Awaitable<void> { // Cleanup here. } } ``` Now, related `using` clauses *must* be preceded by `await`.
Markdown
hhvm/hphp/hack/manual/hack/06-classes/31-type-constants-revisited.md
Imagine that you have a class, and some various `extends` to that class. ```Hack abstract class User { public function __construct(private int $id) {} public function getID(): int { return $this->id; } } trait UserTrait { require extends User; } interface IUser { require extends User; } class AppUser extends User implements IUser { use UserTrait; } <<__EntryPoint>> function run(): void { $au = new AppUser(-1); \var_dump($au->getID()); } ``` Now imagine that you realize that sometimes the ID of a user could be a `string` as well as an `int`. But you know that the concrete classes of `User` will know exactly what type will be returned. While this situation could be handled by using generics, an alternate approach is to use type constants. Instead of types being declared as parameters directly on the class itself, type constants allow the type to be declared as class member constants instead. ```Hack abstract class User { abstract const type T as arraykey; public function __construct(private this::T $id) {} public function getID(): this::T { return $this->id; } } trait UserTrait { require extends User; } interface IUser { require extends User; } // We know that AppUser will only have int ids class AppUser extends User implements IUser { const type T = int; use UserTrait; } class WebUser extends User implements IUser { const type T = string; use UserTrait; } class OtherUser extends User implements IUser { const type T = arraykey; use UserTrait; } <<__EntryPoint>> function run(): void { $au = new AppUser(-1); \var_dump($au->getID()); $wu = new WebUser('-1'); \var_dump($wu->getID()); $ou1 = new OtherUser(-1); \var_dump($ou1->getID()); $ou2 = new OtherUser('-1'); \var_dump($ou2->getID()); } ``` Notice the syntax `abstract const type <name> [ as <constraint> ];`. All type constants are `const` and use the keyword `type`. You specify a name for the constant, along with any possible [constraints](/hack/generics/type-constraints) that must be adhered to. ## Using Type Constants Given that the type constant is a first-class constant of the class, you can reference it using `this`. As a type annotation, you annotate a type constant like: ``` this::<name> ``` e.g., ``` this::T ``` You can think of `this::` in a similar manner as the [`this` return type](../built-in-types/this.md). This example shows the real benefit of type constants. The property is defined in `Base`, but can have different types depending on the context of where it is being used. ```Hack abstract class Base { abstract const type T; protected this::T $value; } class Stringy extends Base { const type T = string; public function __construct() { // inherits $value in Base which is now setting T as a string $this->value = "Hi"; } public function getString(): string { return $this->value; // property of type string } } class Inty extends Base { const type T = int; public function __construct() { // inherits $value in Base which is now setting T as an int $this->value = 4; } public function getInt(): int { return $this->value; // property of type int } } <<__EntryPoint>> function run(): void { $s = new Stringy(); $i = new Inty(); \var_dump($s->getString()); \var_dump($i->getInt()); } ``` ## Examples Here are some examples of where type constants may be useful: ### Referencing Type Constants Referencing type constants is as easy as referencing a static class constant. ```Hack abstract class UserTC { abstract const type Ttc as arraykey; public function __construct(private this::Ttc $id) {} public function getID(): this::Ttc { return $this->id; } } class AppUserTC extends UserTC { const type Ttc = int; } function get_id_from_userTC(AppUserTC $uc): AppUserTC::Ttc { return $uc->getID(); } <<__EntryPoint>> function run(): void { $autc = new AppUserTC(10); \var_dump(get_id_from_userTC($autc)); } ``` ### Type Constants and Instance Methods You can use type constants as inputs to class instance methods. ```Hack abstract class Box { abstract const type T; public function __construct(private this::T $value) {} public function get(): this::T { return $this->value; } public function set(this::T $val): this { $this->value = $val; return $this; } } class IntBox extends Box { const type T = int; } <<__EntryPoint>> function run(): void { $ibox = new IntBox(10); \var_dump($ibox); $ibox->set(123); \var_dump($ibox); } ```
Markdown
hhvm/hphp/hack/manual/hack/06-classes/33-methods-with-predefined-semantics.md
If a class contains a definition for a method having one of the following names, that method must have the prescribed visibility, signature, and semantics: Method Name | Description ------------|------------- [`__construct`](constructors.md) | A constructor [`__dispose`](#method-__dispose) | Performs object-cleanup [`__disposeAsync`](#method-__disposeasync) | Performs object-cleanup [`__toString`](#method-__tostring) | Returns a string representation of the instance on which it is called ## Method __construct See [Constructors](constructors.md). ## Method __dispose This public instance method is required if the class implements the interface `IDisposable`; the method is intended to perform object cleanup. The method's signature is, as follows: ```Hack class Example implements IDisposable { public function __dispose(): void {} } ``` This method is called implicitly by the runtime when the instance goes out of scope, provided the attributes `<<__ReturnDisposable>>` and `<<__AcceptDisposable>>` are *not* present. See [object disposal](object-disposal.md) for an example of its use and a discussion of these attributes. ## Method __disposeAsync This public instance method is required if the class implements the interface `IAsyncDisposable`; the method is intended to perform object cleanup. The method's signature is as follows: ```Hack no-extract public async function __disposeAsync(): Awaitable<void>; ``` This method is called implicitly by the runtime when the instance goes out of scope, provided the attributes `<<__ReturnDisposable>>` and `<<__AcceptDisposable>>` are *not* present. See [object disposal](object-disposal.md) for a discussion of disposal and these attributes.
Markdown
hhvm/hphp/hack/manual/hack/07-traits-and-interfaces/01-introduction.md
**Topics covered in this section** * [Using a Trait](using-a-trait.md) * [Implementing an Interface](implementing-an-interface.md) * [Trait and Interface Requirements](trait-and-interface-requirements.md)
Markdown
hhvm/hphp/hack/manual/hack/07-traits-and-interfaces/02-implementing-an-interface.md
A class can implement a *contract* through an interface, which is a set of required method declarations and constants. Note that the methods are only declared, not defined; that is, an interface defines a type consisting of *abstract* methods, where those methods are implemented by client classes as they see fit. An interface allows unrelated classes to implement the same facilities with the same names and types without requiring those classes to share a common base class. For example: ```Hack interface MyCollection { const MAX_NUMBER_ITEMS = 1000; public function put(int $item): void; public function get(): int; } class MyList implements MyCollection { public function put(int $item): void { /* implement method */ } public function get(): int { /* implement method */ return 0; } // ... } class MyQueue implements MyCollection { public function put(int $item): void { /* implement method */ } public function get(): int { /* implement method */ return 0; } // ... } function process_collection(MyCollection $p1): void { /* can process any object whose class implements MyCollection */ $p1->put(123); } <<__EntryPoint>> function main(): void { process_collection(new MyList()); process_collection(new MyQueue()); } ``` In this example, we define an interface type called `MyCollection` that contains an implicitly static [constant](../classes/constants.md) and two implicitly abstract methods. Note how these methods have no bodies; their declarations end in a semicolon, which makes them abstract. Next, we define two classes that each implement this interface. Note carefully that the parameter type of `process_collection` is an interface type. As such, when that function is called, the argument can have any type that implements that interface type. As we add new collection types that implement that interface, we can plug them into the application without impacting existing code. An interface can extend another interface; for example: ```Hack no-extract interface Iterator<Tv> extends Traversable<Tv> { // ... } ``` The library interface generic type `Iterator<...>` inherits the members of the interface generic type `Traversable<...>`. The `extends` clause allows a comma-separated list of base interfaces, so an interface can have multiple base interfaces. As such, the members of an interface are those specified by its own declaration, and the members inherited from its base interfaces. Interfaces are designed to support classes; an interface cannot be instantiated directly. An interface can have usage requirements placed on it; see [interface requirements](trait-and-interface-requirements.md) for more information.
Markdown
hhvm/hphp/hack/manual/hack/07-traits-and-interfaces/03-using-a-trait.md
Traits are a mechanism for code reuse that overcomes some limitations of Hack single inheritance model. In its simplest form a trait defines properties and method declarations. A trait cannot be instantiated with `new`, but it can be _used_ inside one or more classes, via the `use` clause. Informally, whenever a trait is used by a class, the property and method definitions of the trait are inlined (copy/pasted) inside the class itself. The example below shows a simple trait defining a method that returns even numbers. The trait is used by two, unrelated, classes. ```Hack trait T { public int $x = 0; public function return_even() : int { invariant($this->x % 2 == 0, 'error, not even\n'); $this->x = $this->x + 2; return $this->x; } } class C1 { use T; public function foo() : void { echo "C1: " . $this->return_even() . "\n"; } } class C2 { use T; public function bar() : void { echo "C2: " . $this->return_even() . "\n"; } } <<__EntryPoint>> function main() : void { (new C1()) -> foo(); (new C2()) -> bar(); } ``` A class can use multiple traits, and traits themselves can use one or more traits. The example below uses three traits, to generate even numbers, to generate odd numbers given a generator of even numbers, and to test if a number is odd: ```Hack trait T1 { public int $x = 0; public function return_even() : int { invariant($this->x % 2 == 0, 'error, not even\n'); $this->x = $this->x + 2; return $this->x; } } trait T2 { use T1; public function return_odd() : int { return $this->return_even() + 1; } } trait T3 { public static function is_odd(int $x) : bool { if ($x % 2 == 1) { return true; } else { return false; } } } class C { use T2; use T3; public function foo() : void { echo static::is_odd($this->return_odd()) . "\n"; } } <<__EntryPoint>> function main() : void { (new C()) -> foo(); } ``` Traits can contain both instance and static members. If a trait defines a static property, then each class using the trait has its own instance of the static property. A trait can access methods and properties of the class that uses it, but these dependencies must be declared using [trait requirements](trait-and-interface-requirements.md). ### Resolution of naming conflicts A trait can insert arbitrary properties, constants, and methods inside a class, and naming conflicts may arise. Conflict resolution rules are different according to whether the conflict concerns a property, constant, or method. If a class uses multiple traits that define the same property, say `$x`, then every trait must define the property `$x` with the same type, visibility modifier, and initialization value. The class itself may, or not, define again the property `$x`, subject to the same conditions as above. Beware that at runtime all the instances of the multiply defined property `$x` are _aliased_. This might be source of unexpected interference between traits implementing unrelated services: in the example below the trait `T2` breaks the invariant of trait `T1` whenever both are used by the same class. ```Hack trait T1 { public static int $x = 0; public static function even() : void { invariant(static::$x % 2 == 0, 'error, not even\n'); static::$x = static::$x + 2; } } trait T2 { public static int $x = 0; public static function inc() : void { static::$x = static::$x + 1; } } class C { use T1; use T2; public static function foo() : void { static::inc(); static::even(); } } <<__EntryPoint>> function main() : void { try { C::foo(); } catch (\Exception $ex) { echo "Caught an exception\n"; } } ``` For methods, a rule of thumb is "traits provide a method implementation if the class itself does not". If the class implements a method `m`, then traits used by the class can define methods named `m` provided that their interfaces are compatible (more precisely _super types_ of the type of the method defined in the class. At runtime methods inserted by traits are ignored, and dispatch selects the method defined in the class. If multiple traits used by a class define the same method `m`, and a method named `m` is not defined by the class itself, then the code is rejected altogether, independently of the method interfaces. Traits inherited along multiple paths (aka. "diamond traits") are rejected by Hack and HHVM whenever they define methods. However the experimental `<<__EnableMethodTraitDiamond>>` attribute can be specified on the base class (or trait) to enable support for diamond traits that define methods, provided that method resolution remains unambiguous. For instance, in the example below the invocation of `(new C())->foo()` unambiguously resolves to the method `foo` defined in trait `T`: ```Hack <<file:__EnableUnstableFeatures('method_trait_diamond')>> trait T { public function foo(): void { echo "I am T"; } } trait T1 { use T; } trait T2 { use T; } <<__EnableMethodTraitDiamond>> class C { use T1, T2; } <<__EntryPoint>> function main() : void { (new C())->foo(); } ``` ```.ini hhvm.diamond_trait_methods=1 ``` Since the `<<__EnableMethodTraitDiamond>>` attribute is specified on the class `C`, the example is accepted by Hack and HHVM. _Remark_: a diamond trait cannot define properties if it is used by a class via the `<<__EnableMethodTraitDiamond>>` attribute. For constants, constants inherited from the parent class take precedence over constants inherited from traits. ```Hack trait T { const FOO = 'trait'; } class B { const FOO = 'parent'; } class A extends B { use T; } <<__EntryPoint>> function main() : void { \var_dump(A::FOO); } ``` If multiple used traits declare the same constant, the constant inherited from the first trait is used. ```Hack trait T1 { const FOO = 'one'; } trait T2 { const FOO = 'two'; } class A { use T1, T2; } <<__EntryPoint>> function main() : void { \var_dump(A::FOO); } ``` Finally, constants inherited from interfaces declared on the class conflict with other inherited constants, including constants declared on traits. ```Hack error trait T { const FOO = 'trait'; } interface I { const FOO = 'interface'; } class A implements I { use T; } <<__EntryPoint>> function main() : void { \var_dump(A::FOO); } ``` The single exception to this rule are constants inherited from traits via interfaces, as these will lose silently upon conflict. ```Hack interface I1 { const FOO = 'one'; } trait T implements I1 {} interface I { const FOO = 'two'; } class A implements I { use T; } <<__EntryPoint>> function main() : void { \var_dump(A::FOO); } ```
Markdown
hhvm/hphp/hack/manual/hack/07-traits-and-interfaces/04-trait-and-interface-requirements.md
Trait and interface requirements allow you to restrict the use of these constructs by specifying what classes may actually use a trait or implement an interface. This can simplify long lists of `abstract` method requirements, and provide a hint to the reader as to the intended use of the trait or interface. ## Syntax To introduce a trait requirement, you can have one or more of the following in your trait: ```Hack no-extract require extends <class name>; require implements <interface name>; ``` *Note:* the experimental `require class <class name>;` trait constraint is discussed [below](#traits__the-require-class-trait-constraints-experimental). To introduce an interface requirement, you can have one or more of following in your interface: ```Hack no-extract require extends <class name>; ``` ## Traits Here is an example of a trait that introduces a class and interface requirement, and shows a class that meets the requirement: ```Hack abstract class Machine { public function openDoors(): void { return; } public function closeDoors(): void { return; } } interface Fliers { public function fly(): bool; } trait Plane { require extends Machine; require implements Fliers; public function takeOff(): bool { $this->openDoors(); $this->closeDoors(); return $this->fly(); } } class AirBus extends Machine implements Fliers { use Plane; public function fly(): bool { return true; } } <<__EntryPoint>> function run(): void { $ab = new AirBus(); \var_dump($ab); \var_dump($ab->takeOff()); } ``` Here is an example of a trait that introduces a class and interface requirement, and shows a class that *does not* meet the requirement: ```Hack error abstract class Machine { public function openDoors(): void { return; } public function closeDoors(): void { return; } } interface Fliers { public function fly(): bool; } trait Plane { require extends Machine; require implements Fliers; public function takeOff(): bool { $this->openDoors(); $this->closeDoors(); return $this->fly(); } } // Having this will not only cause a typechecker error, but also cause a fatal // error in HHVM since we did not meet the trait requirement. class Paper implements Fliers { use Plane; public function fly(): bool { return false; } } <<__EntryPoint>> function run(): void { // This code will not run in HHVM because of the problem mentioned above. $p = new Paper(); \var_dump($p); \var_dump($p->takeOff()); } ``` **NOTE**: `require extends` should be taken literally. The class *must* extend the required class; thus the actual required class **does not** meet that requirement. This is to avoid some subtle circular dependencies when checking requirements. #### The `require class` trait constraints (experimental) A `require class <class name>;` trait constraint in a trait specifies that the trait can only be used by the _non-generic, _final_, class `<class name>`. This contrasts with the `require extends t;` constraints that allow the trait to be used by an arbitrary _strict_ subtype of `t`. By relaxing the strict subtype constraint of `require extends`, `require class` constraints allow splitting the implementation of a class into a class and one (or multiple) traits, as in the following: ```Hack <<file:__EnableUnstableFeatures('require_class')>> trait T { require class C; public function foo(): void { $this->bar(); } } final class C { use T; public function bar(): void {} } ``` ## Interfaces Here is an example of an interface that introduces a class requirement, and shows a class that meets the requirement: ```Hack abstract class Machine { public function openDoors(): void { return; } public function closeDoors(): void { return; } } interface Fliers { require extends Machine; public function fly(): bool; } class AirBus extends Machine implements Fliers { public function takeOff(): bool { $this->openDoors(); $this->closeDoors(); return $this->fly(); } public function fly(): bool { return true; } } <<__EntryPoint>> function run(): void { $ab = new AirBus(); \var_dump($ab); \var_dump($ab->takeOff()); } ``` Here is an example of an interface that introduces a class requirement, and shows a class that *does not* meet the requirement: ```Hack error abstract class Machine { public function openDoors(): void { return; } public function closeDoors(): void { return; } } interface Fliers { require extends Machine; public function fly(): bool; } // Having this will not only cause a typechecker error, but also cause a fatal // error in HHVM since we did not meet the interface requirement (extending // Machine). class Paper implements Fliers { public function fly(): bool { return false; } } <<__EntryPoint>> function run(): void { // This code will actually not run in HHVM because of the fatal mentioned // above. $p = new Paper(); \var_dump($p); \var_dump($p->takeOff()); } ``` **NOTE**: trait cannot be used as a type, comparing to some other languages. Only class and interface are types. For example, ```Hack no-extract trait T {} class C { use T; } $a = new C(); $j = ($a is C); $k = ($a is T); # error! ``` leads to error ``` Hit fatal : "is" and "as" operators cannot be used with a trait #0 at [:1] #1 include(), called at [:1] #2 include(), called at [:0] Hit fatal : "is" and "as" operators cannot be used with a trait Failed to evaluate expression ```
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/01-introduction.md
Hack includes diverse range of array-like data structures. Hack arrays are value types for storing iterable data. The types available are [`vec`](/hack/arrays-and-collections/vec-keyset-and-dict#vec), [`dict`](/hack/arrays-and-collections/vec-keyset-and-dict#dict) and [`keyset`](/hack/arrays-and-collections/vec-keyset-and-dict#keyset). **When in doubt, use Hack arrays**. Collections are object types for storing iterable data. The types available include `Vector`, `Map`, `Set`, `Pair` and helper interfaces. ## Quickstart You can create Hack arrays as follows: ```Hack $v = vec[2, 1, 2]; $k = keyset[2, 1]; $d = dict['a' => 1, 'b' => 3]; ``` ## The Hack Standard Library There are many helpful functions in the `C`, `Vec`, `Keyset` and `Dict` namespaces, which are a part of the [Hack Standard Library (HSL)](/hsl/reference). For more information on included HSL namespaces, see [Hack Standard Library: Namespaces](/hack/getting-started/the-hack-standard-library#hsl-namespaces). ```Hack // The C namespace contains generic functions that are relevant to // all array and collection types. C\count(vec[]); // 0 C\is_empty(keyset[]); // true // The Vec, Keyset and Dict namespaces group functions according // to their return type. Vec\keys(dict['x' => 1]); // vec['x'] Keyset\keys(dict['x' => 1]); // keyset['x'] Vec\map(keyset[1, 2], $x ==> $x + 1); // vec[2, 3] ``` ## Arrays Cheat Sheet | Operation| `vec` | `dict` | `keyset` | |----------|----------|----------|----------| | Initialize empty | `$v = vec[];` | `$d = dict[];` | `$k = keyset[];` | | Literal | `$v = vec[1, 2, 3];` | `$d = dict['foo' => 1];` | `$k = keyset['foo', 'bar'];` | | From Another Container* | `$v = vec($container);` | `$d = dict($keyed_container);` | `$k = keyset($container);` | | Keys from Container* | `$v = Vec\keys($container);` | N/A | `$k = Keyset\keys($container);`| | Add Elements | `$v[] = 4;` | `$d['baz'] = 2;` | `$k[] = 'baz';` | | Bulk Add Elements | `$v = Vec\concat($t1, $t2)` | `$d = Dict\merge($kt1, $kt2)` | `$k = Keyset\union($t1, $t2)` | | Remove Elements | Remove-at-index is unsupported; `Vec\drop($v,$n)`, `Vec\take($v,$n)`; `$first=C\pop_front(inout $x)`, `$last=C\pop_back(inout $x)` | `unset($d['baz']);` | `unset($k['baz']);`| | Key Existence | `C\contains_key($v, 1)` | `C\contains_key($d, 'foo')` | `C\contains_key($k, 'foo')` | | Value Existence | `C\contains($v, 3)` | `C\contains($d, 2)` | Use `C\contains_key($k, 'foo')`| | Equality (Order-Dependent) | `$v1 === $v2` | `$d1 === $d2` | `$k1 === $k2` | | Equality (Order-Independent) | N/A | `Dict\equal($d1, $d2)` | `Keyset\equal($k1, $k2)` | | Count Elements (i.e., length, size of array) | `C\count($v)` | `C\count($d)` | `C\count($k)` | | Type Signature | `vec<Tv>` | `dict<Tk, Tv>` | `keyset<Tk>` | | Type Refinement | `$v is vec<_>` | `$d is dict<_, _>` | `$k is keyset<_>` | | `Awaitable` Consolidation | `Vec\from_async($v)` | `Dict\from_async($d)` | `Keyset\from_async($x)` | \* `$container` can be a Hack Array or Hack Collection ## Arrays Conversion Cheat sheet Prefer to use Hack arrays whenever possible. When interfacing with legacy APIs that expect older Containers, it may be easier to convert. Here's how: | Converting | To `Vector`| To `Map` | To `Set` | |------------|------------|------------|------------| | `dict` | N/A | `new Map($d)` | N/A | | `dict` keys | `Vector::fromKeysOf($d)` | N/A | `Set::fromKeysOf($d)` | | `dict` values | `new Vector($d)` | N/A | `new Set($d)` | | `vec` | `new Vector($v)` | `new Map($v)` | `new Set($v)` | | `keyset` | `new Vector($k)` | `new Map($k)` | `new Set($k)` |
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/05-vec-keyset-and-dict.md
`vec`, `keyset` and `dict` are value types. Any mutation produces a new value, and does not modify the original value. These types are referred to as 'Hack arrays'. Prefer using these types whenever you're unsure. ## `vec` A `vec` is an ordered, iterable data structure. It is created with the `vec[]` syntax. ```Hack // Creating a vec. function get_items(): vec<string> { $items = vec['a', 'b', 'c']; return $items; } ``` `vec`s can be accessed with the following syntax. ```Hack $items = vec['a', 'b', 'c']; // Accessing items by index. $items[0]; // 'a' $items[3]; // throws OutOfBoundsException // Accessing items that might be out-of-bounds. idx($items, 0); // 'a' idx($items, 3); // null idx($items, 3, 'default'); // 'default' // Modifying items. These operations set $items // to a modified copy, and do not modify the original value. $items[0] = 'xx'; // vec['xx', 'b', 'c'] $items[] = 'd'; // vec['xx', 'b', 'c', 'd'] // Getting the length. C\count($items); // 4 // Seeing if a vec contains a value or index. C\contains($items, 'a'); // true C\contains_key($items, 2); // true // Iterating. foreach ($items as $item) { echo $item; } // Iterating with the index. foreach ($items as $index => $item) { echo $index; // e.g. 0 echo $item; // e.g. 'a' } // Equality checks. Elements are recursively compared with ===. vec[1] === vec[1]; // true vec[1, 2] === vec[2, 1]; // false // Combining vecs. Vec\concat(vec[1], vec[2, 3]); // vec[1, 2, 3] // Removing items at an index. $items = vec['a', 'b', 'c']; $n = 1; Vec\concat(Vec\take($items, $n), Vec\drop($items, $n + 1)); // vec['a', 'c'] // Converting from an Iterable. vec(keyset[10, 11]); // vec[10, 11] vec(Vector { 20, 21 }); // vec[20, 21] vec(dict['key1' => 'value1']); // vec['value1'] // Type checks. $items is vec<_>; // true ``` ## `keyset` A `keyset` is an ordered data structure without duplicates. It is created with the `keyset[]` syntax. A `keyset` can only contain `string` or `int` values. ```Hack // Creating a keyset. function get_items(): keyset<string> { $items = keyset['a', 'b', 'c']; return $items; } ``` `keyset`s can be accessed with the following syntax. ```Hack $items = keyset['a', 'b', 'c']; // Checking if a keyset contains a value. C\contains($items, 'a'); // true // Adding/removing items. These operations set $items to a modified copy, // and do not modify the original value. $items[] = 'd'; // keyset['a', 'b', 'c', 'd'] $items[] = 'a'; // keyset['a', 'b', 'c', 'd'] unset($items['b']); // keyset['a', 'c', 'd'] // Getting the length. C\count($items); // 3 // Iterating. foreach ($items as $item) { echo $item; } // Equality checks. === returns false if the order does not match. keyset[1] === keyset[1]; // true keyset[1, 2] === keyset[2, 1]; // false Keyset\equal(keyset[1, 2], keyset[2, 1]); // true // Combining keysets. Keyset\union(keyset[1, 2], keyset[2, 3]); // keyset[1, 2, 3] // Converting from an Iterable. keyset(vec[1, 2, 1]); // keyset[1, 2] keyset(Vector { 20, 21 }); // keyset[20, 21] keyset(dict['key1' => 'value1']); // keyset['value1'] // Type checks. $items is keyset<_>; // true ``` ## `dict` A `dict` is an ordered key-value data structure. It is created with the `dict[]` syntax. Keys must be `string`s or `int`s. `dict`s are ordered according to the insertion order. ```Hack // Creating a dict. function get_items(): dict<string, int> { $items = dict['a' => 1, 'b' => 3]; return $items; } ``` `dicts`s can be accessed with the following syntax. ```Hack $items = dict['a' => 1, 'b' => 3]; // Accessing items by key. $items['a']; // 1 $items['foo']; // throws OutOfBoundsException // Accessing keys that may be absent. idx($items, 'a'); // 1 idx($items, 'z'); // null idx($items, 'z', 'default'); // 'default' // Inserting, updating or removing values in a dict. These operations // set $items to a modified copy, and do not modify the original value. $items['a'] = 42; // dict['a' => 42, 'b' => 3] $items['z'] = 100; // dict['a' => 42, 'b' => 3, 'z' => 100] unset($items['b']); // dict['a' => 42, 'z' => 100] // Getting the keys. Vec\keys(dict['a' => 1, 'b' => 3]); // vec['a', 'b'] // Getting the values. vec(dict['a' => 1, 'b' => 3]); // vec[1, 3] // Getting the length. C\count($items); // 2 // Checking if a dict contains a key or value. C\contains_key($items, 'a'); // true C\contains($items, 3); // true // Iterating values. foreach ($items as $value) { echo $value; // e.g. 1 } // Iterating keys and values. foreach ($items as $key => $value) { echo $key; // e.g. 'a' echo $value; // e.g. 1 } // Equality checks. === returns false if the order does not match. dict[] === dict[]; // true dict[0 => 10, 1 => 11] === dict[1 => 11, 0 => 10]; // false Dict\equal(dict[0 => 10, 1 => 11], dict[1 => 11, 0 => 10]); // true // Combining dicts (last item wins). Dict\merge(dict[10 => 1, 20 => 2], dict[30 => 3, 10 => 0]); // dict[10 => 0, 20 => 2, 30 => 3]; // Converting from an Iterable. dict(vec['a', 'b']); // dict[0 => 'a', 1 => 'b'] dict(Map {'a' => 5}); // dict['a' => 5] // Type checks. $items is dict<_, _>; // true ``` If you want different keys to have different value types, or if you want a fixed set of keys, consider using a `shape` instead.
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/10-object-collections.md
The collection object types are `Vector`, `ImmVector`, `Map`, `ImmMap`, `Set`, `ImmSet` and `Pair`. There are also a range of helper interfaces, discussed below. Hack Collection types are objects. They have reference semantics, so they can be mutated. Collections define a large number of methods you can use. They also support array style syntax. Idiomatic Hack prefers array access syntax over methods, e.g. `$v[0]` is better than `$v->at(0)`. This page focuses on the core operations available, which all have array access syntax. Consult the reference pages (e.g. [Vector](/hack/reference/class/HH.Vector/)) for the full list of methods. ## `Vector` and `ImmVector` *Where possible, we recommend using `vec` instead.* A `Vector` is a mutable ordered data structure. It is created with the `Vector {}` syntax. ```Hack // Creating a Vector. function get_items(): Vector<string> { $items = Vector {'a', 'b', 'c'}; return $items; } ``` `Vector`s can be accessed with the following syntax. ```Hack $items = Vector {'a', 'b', 'c'}; // Accessing items by index. $items[0]; // 'a' $items[3]; // throws OutOfBoundsException // Accessing items that might be out-of-bounds. idx($items, 0); // 'a' idx($items, 3); // null idx($items, 3, 'default'); // 'default' // Modifying items. This mutates the Vector in place. $items[0] = 'xx'; // Vector {'xx', 'b', 'c'} $items[] = 'd'; // Vector {'xx', 'b', 'c', 'd'} // Getting the length. C\count($items); // 4 // Iterating. foreach ($items as $item) { echo $item; } // Iterating with the index. foreach ($items as $index => $item) { echo $index; // e.g. 0 echo $item; // e.g. 'a' } // Equality checks compare references. $items === $items; // true Vector {} === Vector {}; // false // Converting from an Iterable. new Vector(vec[1, 2]); // Vector {1, 2} new Vector(Set {1, 2}); // Vector {1, 2} new Vector(dict['key1' => 'value1']); // Vector {'value1'} // Type checks $items is Vector<_>; // true ``` `ImmVector` is an immutable version of `Vector`. ``` Hack // Creating an ImmVector. function get_items(): ImmVector<string> { $items = ImmVector {'a', 'b', 'c'}; return $items; } ``` ## `Set` and `ImmSet` *Where possible, we recommend using `keyset` instead.* A `Set` is a mutable, ordered, data structure without duplicates. It is created with the `Set {}` syntax. A `Set` can only contain `string` or `int` values. ```Hack // Creating a Set. function get_items(): Set<string> { $items = Set {'a', 'b', 'c'}; return $items; } ``` `Set`s can be accessed with the following syntax. ```Hack $items = Set {'a', 'b', 'c'}; // Checking if a Set contains a value. C\contains_key($items, 'a'); // true // Modifying items. This mutates the Set in place. $items[] = 'd'; // Set {'a', 'b', 'c', 'd'} $items[] = 'a'; // Set {'a', 'b', 'c', 'd'} // Getting the length. C\count($items); // 4 // Iterating. foreach ($items as $item) { echo $item; } // Equality checks compare references. $items === $items; // true Set {} === Set {}; // false // Converting from an Iterable. new Set(vec[1, 2, 1]); // Set {1, 2} new Set(Vector {20, 21}); // Set {20, 21} new Set(dict['key1' => 'value1']); // Set {'value1'} // Type checks. $items is Set<_>; // true ``` `ImmSet` is an immutable version of `Set`. ``` Hack // Creating an ImmSet. function get_items(): ImmSet<string> { $items = ImmSet {'a', 'b', 'c'}; return $items; } ``` ## `Map` and `ImmMap` *Where possible, we recommend using `dict` instead.* A `Map` is a mutable, ordered, key-value data structure. It is created with the `Map {}` syntax. Keys must be `string`s or `int`s. ```Hack // Creating a Map. function get_items(): Map<string, int> { $items = Map {'a' => 1, 'b' => 3}; return $items; } ``` `Map`s can be accessed with the following syntax. ```Hack $items = Map {'a' => 1, 'b' => 3}; // Accessing items by key. $items['a']; // 1 $items['z']; // throws OutOfBoundsException // Accessing keys that may be absent. idx($items, 'a'); // 1 idx($items, 'z'); // null idx($items, 'z', 'default'); // 'default' // Modifying items. This mutates the Map in place. $items['a'] = 42; // Map {'a' => 42, 'b' => 3} $items['z'] = 100; // Map {'a' => 42, 'b' => 3, 'z' => 100} // Getting the keys. Vec\keys(Map {'a' => 1, 'b' => 3}); // vec['a', 'b'] // Getting the values. vec(Map {'a' => 1, 'b' => 3}); // vec[1, 3] // Getting the length. C\count($items); // 3 // Iterating values. foreach ($items as $value) { echo $value; } // Iterating keys and values. foreach ($items as $key => $value) { echo $key; echo $value; } // Equality checks compare references. $items === $items; // true Map {} === Map {}; // false // Converting from an Iterable. new Map(dict['key1' => 'value1']); // Map { 'key1' => 'value1'} new Map(vec['a', 'b']); // Map {0 => 'a', 1 => 'b'} // Type checks $items is Map<_, _>; // true ``` `ImmMap` is an immutable version of `Map`. ``` Hack // Creating an ImmMap. function get_items(): ImmMap<string, int> { $items = ImmMap {'a' => 1, 'b' => 3}; return $items; } ``` ## `Pair` *Where possible, we recommend using `tuple` instead.* A `Pair` is an immutable data structure with two items. It is created with the `Pair {}` syntax. ``` Hack function get_items(): Pair<int, string> { $items = Pair {42, 'foo'}; return $items; } ``` `Pair`s can be accessed with the following syntax. ```Hack $items = Pair {42, 'foo'}; // Destructuring a Pair value. list($x, $y) = $items; // $x: 42, $y: 'foo' // Accessing elements by index. $items[0]; // 42 $items[1]; // 'foo' ``` ## Interfaces Hack Collections implement a range of helper interfaces, so your code can handle multiple Hack Collection types. If you want to handle both Hack arrays and Hack Collections, use `Traversable`. If you want to read and write a Hack Collection, use `Collection`. If you only want to read a Hack Collection, use `ConstCollection`. The `ConstCollection` interface represents Hack Collections that be can read from. ```text ConstCollection +-- ConstVector | +-- ImmVector | +-- Pair +-- ConstSet | +-- ImmSet +-- ConstMap | +-- ImmMap +-- Collection +-- MutableVector | +-- Vector +-- MutableMap | +-- Map +-- MutableSet +-- Set ``` The `OutputCollection` interface represents Hack Collections that be can written to. ```text OutputCollection +-- Collection +-- MutableVector | +-- Vector +-- MutableMap | +-- Map +-- MutableSet +-- Set ```
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/15-varray-and-darray.md
**`varray`, `darray` and `varray_or_darray` are legacy value types for storing iterable data.**. They are also called 'PHP arrays' and will eventually be removed. PHP arrays are immutable value types, just like Hack arrays. Unlike Hack arrays, they include legacy behaviors from PHP that can hide bugs. For example, in HHVM 4.36, invalid array keys are accepted and silently coerced to an `arraykey`. ```Hack no-extract $x = darray[false => 123]; var_dump(array_keys($x)[0]); // int(0), not `bool(false)` ``` ## `varray` #### Use Hack Arrays As of [HHVM 4.103](https://hhvm.com/blog/2021/03/31/hhvm-4.103.html), `varray` is aliased to `vec`. Use [`vec`](https://docs.hhvm.com/hack/arrays-and-collections/hack-arrays#vec). #### Working with varrays A `varray` is an ordered, iterable data structure. ```Hack no-extract // Creating a varray. function get_items(): varray<string> { $items = varray['a', 'b', 'c']; return $items; } // Accessing items by index. $items[0]; // 'a' $items[3]; // throws OutOfBoundsException // Accessing items that might be out-of-bounds. idx($items, 0); // 'a' idx($items, 3); // null idx($items, 3, 'default'); // 'default' // Modifying items. These operations set $items // to a modified copy, and do not modify the original value. $items[0] = 'xx'; // varray['xx', 'b', 'c'] $items[] = 'd'; // varray['xx', 'b', 'c', 'd'] // Getting the length. C\count($items); // 4 // Iterating. foreach ($items as $item) { echo $item; } // Iterating with the index. foreach ($items as $index => $item) { echo $index; // e.g. 0 echo $item; // e.g. 'a' } // Equality checks. varray[1] === varray[1]; // true varray[1, 2] === varray[2, 1]; // false // Converting from an Iterable. varray(vec[10, 11]); // varray[10, 11] varray(keyset[10, 11]); // varray[10, 11] ``` ## `darray` #### Use Hack Arrays As of [HHVM 4.103](https://hhvm.com/blog/2021/03/31/hhvm-4.103.html), `darray` is aliased to `dict`. Use [`dict`](https://docs.hhvm.com/hack/arrays-and-collections/hack-arrays#dict). #### Working with darrays A `darray` is an ordered key-value data structure. ```Hack no-extract // Creating a darray. function get_items(): darray<string, int> { $items = darray['a' => 1, 'b' => 3]; return $items; } // Accessing items by key. $items['a']; // 1 $items['foo']; // throws OutOfBoundsException // Accessing keys that may be absent. idx($items, 'a'); // 1 idx($items, 'z'); // null idx($items, 'z', 'default'); // 'default' // Inserting, updating or removing values in a darray. These operations // set $items to a modified copy, and do not modify the original value. $items['a'] = 42; // darray['a' => 42, 'b' => 3] $items['z'] = 100; // darray['a' => 42, 'b' => 3, 'z' => 100] unset($items['b']); // darray['a' => 42, 'z' => 100] // Getting the keys. Vec\keys(darray['a' => 1, 'b' => 3]); // vec['a', 'b'] // Getting the values. vec(darray['a' => 1, 'b' => 3]); // vec[1, 3] // Getting the length. C\count($items); // 2 // Checking if a dict contains a key or value. C\contains_key($items, 'a'); // true C\contains($items, 3); // true // Iterating values. foreach ($items as $value) { echo $value; // e.g. 1 } // Iterating keys and values. foreach ($items as $key => $Value) { echo $key; // e.g. 'a' echo $value; // e.g. 1 } // Equality checks. === returns false if the order does not match. darray[] === darray[]; // true darray[0 => 10, 1 => 11] === darray[1 => 11, 0 => 10]; // false // Converting from an Iterable. darray(vec['a', 'b']); // darray[0 => 'a', 1 => 'b'] darray(Map {'a' => 5}); // darray['a' => 5] ``` ## `varray_or_darray` A `varray_or_darray` is type that can be either a `varray` or `darray`. It exists to help gradually migrate code to more specific types, and should be avoided when possible. ```Hack function get_items(bool $b): varray_or_darray<int, string> { if ($b) { return varray['a', 'b']; } else { return darray[5 => 'c']; } } ``` ## Runtime options In HHVM version 4.62 and earlier, by default, `varray` and `darray` are interchangeable at runtime; this can be changed, as can some legacy PHP array behaviors, depending on the HHVM version. The available runtime options change frequently; to get an up-to-date list, search `ini_get_all()` for settings beginning with `hhvm.hack_arr`; in general: - a value of `0` means no logging - `1` means a warning or notice is raised - `2` means a recoverable error is raised The `hhvm.hack_arr_compat_notices` option must be set to true for any of the `hhvm.hack_arr_` options to have an effect. Individual runtime settings are documented [here](/hack/built-in-types/darray-varray-runtime-options.md).
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/20-mutating-values.md
Hack arrays are value types. This makes your code easier to reason about, faster (no work required on a fresh web request), and well suited for caches. If you really need mutation, Hack provides you with several options. ## Updating value types Updating an element in a value type creates a new copy. ``` Hack function update_value(vec<int> $items): vec<int> { // Both of these operations set $items a modified copy of the // original value. $items[0] = 42; $items[] = 100; return $items; } function demo(): void { $v = vec[1, 2]; // $v is unaffected by this function call. $v2 = update_value($v); var_dump($v); // vec[1, 2] var_dump($v2); // vec[42, 2, 100] } ``` Value types are shallow. A mutable type inside a value type is mutated by reference. ``` Hack class Person { public function __construct(public string $name) {} } function update_person(vec<Person> $items): void { $items[0]->name = "new"; } function demo(): void { $v = vec[new Person("old")]; update_person($v); var_dump($v); // vec[Person { name: "new" }] } ``` ## Using `inout` to simulate mutability You can often use `inout` parameters instead of mutation. This copies the modified parameters back to the locals of the caller. ``` Hack function update_value(inout vec<int> $items): void { $items[0] = 42; $items[] = 100; } function demo(): void { $v = vec[1, 2]; update_value(inout $v); var_dump($v); // vec[42, 2, 100] } ``` ## Using `Ref` for shallow mutability The `Ref` class provides a single value that can be mutated. ```Hack no-extract function update_value(Ref<vec<int>> $items): void { $inner = $items->get(); $inner[0] = 42; $inner[] = 100; $items->set($inner); } function demo(): void { $v = new Ref(vec[1, 2]); update_value($v); var_dump($v->get()); // vec[42, 2, 100] } ``` ## Using Collections for mutability All the Collection classes are mutable. We recommend using Hack arrays wherever possible, but you can use `Vector`, `Set` or `Map` if you really need to. ``` Hack function update_value(Vector<int> $items): void { $items[0] = 42; $items[] = 100; } function demo(): void { $v = Vector {1, 2}; update_value($v); var_dump($v); // Vector {42, 2, 100} } ```
Markdown
hhvm/hphp/hack/manual/hack/10-types/01-introduction.md
Hack includes a strong static type system. This section covers the basic features of the type checker. See also the [`is` operator](../expressions-and-operators/is.md) for checking the type of a value, and the [`as` operator](../expressions-and-operators/as.md) for asserting types. **Topics covered in this section** * [Subtyping](supertypes-and-subtypes.md) * [Soft Types](soft-types.md) * [Nullable Types](nullable-types.md) * [Type Aliases (`newtype` and `type`)](type-aliases.md) * [Type Conversion](type-conversion.md) * [Type Inferencing](type-inferencing.md) * [Type Refinement](type-refinement.md) * [Generic Types](generic-types.md)
Markdown
hhvm/hphp/hack/manual/hack/10-types/45-soft-types.md
A soft type hint `<<__Soft>> Foo` allows you to add types to code without crashing if you get the type wrong. ```Hack function probably_int(<<__Soft>> int $x): @int { return $x + 1; } function definitely_int(int $x): int { return $x + 1; } ``` Calling `definitely_int("foo")` will produce an error at runtime, whereas `probably_int("foo")` will only log a warning. The type checker treats both `definitely_int` and `probably_int` the same way. Code completion and type checks are identical. Soft type hints are useful when migrating partial code or very dynamic code to strict mode. Once you've fixed your code, and you're not seeing any more warnings, then you can remove the `<<__Soft>>`. Previous versions of Hack used `@Foo` syntax instead of `<<__Soft>> Foo`.
Markdown
hhvm/hphp/hack/manual/hack/10-types/46-generic-types.md
Hack contains a mechanism to define generic&mdash;that is, type-less&mdash;classes, interfaces, and traits, and to create type-specific instances of them via type parameters. Consider the following example in which `Stack` is a generic class having one type parameter, `T`, and that implements a stack: ```Hack file:stack.hack class StackUnderflowException extends Exception {} class Stack<T> { private vec<T> $stack; private int $stackPtr; public function __construct() { $this->stackPtr = 0; $this->stack = vec[]; } public function push(T $value): void { $this->stack[] = $value; $this->stackPtr++; } public function pop(): T { if ($this->stackPtr > 0) { $this->stackPtr--; return $this->stack[$this->stackPtr]; } else { throw new StackUnderflowException(); } } } ``` As shown, the type parameter `T` (specified in `Stack<T>`) is used as a placeholder in the declaration of the instance property `$stack`, as the parameter type of the instance method `push`, and as the return type of the instance method `pop`. Note that although `push` and `pop` use the type parameter, they are not themselves generic methods. ```Hack file:stack.hack function use_int_stack(Stack<int> $stInt): void { $stInt->push(10); $stInt->push(20); $stInt->push(30); echo 'pop => '.$stInt->pop()."\n"; } ``` Assuming we construct an instance for a `Stack` of `int`s, we can pass that to function `use_int_stack`, which can push values onto, and pop values off, that stack, as shown. And in the same or different programs, we can have stacks of `string`, stacks of `?(int, float)`, stacks of `Employee`, and so on, without have to write type-specific code for each kind of stack. For more information, see [generic types overview](../generics/introduction.md).
Markdown
hhvm/hphp/hack/manual/hack/10-types/67-nullable-types.md
A type `?Foo` is either a value of type `Foo`, or `null`. ``` Hack function takes_nullable_str(?string $s): string { if ($s is null){ return "default"; } else { return $s; } } ``` `nonnull` is any value except `null`. You can use it to check if a value is not `null`: ``` Hack function takes_nullable_str2(?string $s): string { if ($s is nonnull){ return $s; } else { return "default"; } } ``` This is slightly better than writing `$s is string`, as you don't need to repeat the type name. `nonnull` is also useful when using generics. ``` Hack function my_filter_nulls<T as nonnull>(vec<?T> $items): vec<T> { $result = vec[]; foreach ($items as $item) { if ($item is null) { // Discard it. } else { $result[] = $item; } } return $result; } ```
Markdown
hhvm/hphp/hack/manual/hack/10-types/76-type-conversion.md
In a few situations (documented in the following sections) the values of operands are implicitly converted from one type to another. Explicit conversion is performed using the [cast operator](../expressions-and-operators/casting.md). If an expression is converted to its own type, the type and value of the result are the same as the type and value of the expression. When an expression of type `num` is converted, if that expression is currently an `int`, then `int` conversion rules apply; otherwise, `float` conversion rules apply. When an expression of type `arraykey` is converted, if that expression is currently an `int`, then `int` conversion rules apply; otherwise, `string` conversion rules apply. ## Conversion to `bool` No non-`bool` type can be converted implicitly to `bool`. All other conversions must be explicit. If the source type is `int` or `float`, then if the source value tests equal to 0, the result value is `false`; otherwise, the result value is `true`. If the source value is `null`, the result value is `false`. If the source is an empty string or the string "0", the result value is `false`; otherwise, the result value is `true`. If the source is an array with zero elements, the result value is `false`; otherwise, the result value is `true`. If the source is an object, the result value is `true`, with some legacy exceptions: - `SimpleXMLElement` can be false if there are no child elements - The legacy Hack Collection classes `Vector`, `Map`, `Set` and their immutable variants can be false if there are no elements in the collection. We strongly recommend not depending on these behaviors. If the source is a resource, the result value is `false`. The library function `boolval` allows values to be converted to `bool`. ## Conversion to `int` No non-`int` type can be converted implicitly to `int`. All other conversions must be explicit. If the source type is `bool`, then if the source value is `false`, the result value is 0; otherwise, the result value is 1. If the source type is `float`, for the values `INF`, `-INF`, and `NAN`, the result value is implementation-defined. For all other values, if the precision can be preserved, the fractional part is rounded towards zero and the result is well defined; otherwise, the result is undefined. If the source value is `null`, the result value is 0. If the source is a [numeric string or leading-numeric string](../built-in-types/string.md) having integer format, if the precision can be preserved the result value is that string's integer value; otherwise, the result is undefined. If the source is a numeric string or leading-numeric string having floating-point format, the string's floating-point value is treated as described above for a conversion from `float`. The trailing non-numeric characters in leading-numeric strings are ignored. For any other string, the result value is 0. If the source is an array with zero elements, the result value is 0; otherwise, the result value is 1. If the source is a resource, the result is the resource's unique ID. The library function `intval` allows values to be converted to `int`. ## Converting to `float` No non-`float` type can be converted implicitly to `float`. All other conversions must be explicit. If the source type is `int`, if the precision can be preserved the result value is the closest approximation to the source value; otherwise, the result is undefined. If the source is a [numeric string or leading-numeric string](../built-in-types/string.md) having integer format, the string's integer value is treated as described above for a conversion from `int`. If the source is a numeric string or leading-numeric string having floating-point format, the result value is the closest approximation to the string's floating-point value. The trailing non-numeric characters in leading-numeric strings are ignored. For any other string, the result value is 0. If the source is an array with zero elements, the result value is 0.0; otherwise, the result value is 1.0. If the source is a resource, the result is the resource's unique ID. The library function `floatval` allows values to be converted to float. ## Converting to `num` The only implicit conversions to type `num` are from the types `int` and `float`. There is no change in representation during such conversions. There are no explicit conversions. ## Converting to `string` Except for the type [`classname`](../built-in-types/classname.md), no non-`string` type can be converted implicitly to `string`. All other conversions must be explicit. If the source type is `bool`, then if the source value is `false`, the result value is the empty string; otherwise, the result value is "1". If the source type is `int` or `float`, then the result value is a string containing the textual representation of the source value (as specified by the library function `sprintf`). If the source value is `null`, the result value is an empty string. If the source is an object, then if that object's class has a [`__toString` method](../classes/methods-with-predefined-semantics.md#method-__toString), the result value is the string returned by that method; otherwise, the conversion is invalid. If the source is a resource, the result value is an implementation-defined string. If the source type is the [`classname` type](../built-in-types/classname.md), the result value is a string containing the corresponding fully qualified class or interface name without any leading `\`. The library function `strval` allows values to be converted to `string`. ## Converting to `arraykey` The only implicit conversions to type `arraykey` are from the types `int` and `string`. There is no change in representation during such conversions. There are no explicit conversions. ## Converting to an Object Type An object type can be converted implicitly to any object type from which the first object type is derived directly or indirectly. There are no other implicit or explicit conversions. ## Converting to an Interface Type An object type can be converted implicitly to any interface type that object type implements directly or indirectly. An interface type can be converted implicitly to any interface type from which the first interface type is derived directly or indirectly. There are no other implicit or explicit conversions. ## Converting to Resource Type Standard IO streams returned by [file stream functions](../built-in-types/resources.md) `HH\\stdin()`, `HH\\stdout()`, and `HH\\stderr()`, can be converted implicitly to resource. No other non-resource type can be so converted. No explicit conversions exist. ## Converting to Mixed Type Any type can be converted implicitly to `mixed`. No explicit conversions exist.
Markdown
hhvm/hphp/hack/manual/hack/10-types/79-type-aliases.md
We can create an alias name for a type, and it is common to do so for non-trivial tuple and shape types. Once such a type alias has been defined, that alias can be used in almost all contexts in which a type specifier is permitted. Any given type can have multiple aliases, and a type alias can itself have aliases. ## Quickstart A type alias can be created in two ways: using `type` and `newtype`. ```Hack type Complex = shape('real' => float, 'imag' => float); newtype Point = (float, float); ``` A type alias can include [Generics](/hack/generics/introduction) as parameters. ## Using `type` An alias created using `type` (such as `Complex` above) is a *transparent type alias*. For a given type, that type and all transparent aliases to that type are all the same type and can be freely interchanged. There are no restrictions on where a transparent type alias can be defined, or which source code can access its underlying implementation. ## Using `newtype` An alias created using `newtype` (such as `Point` above) is an *opaque type alias*. In the absence of a type-constraint (see `Counter` example below), each opaque alias type is distinct from its underlying type and from any other types aliasing it or its underlying type. Only source code in the file that contains the definition of the opaque type alias is allowed access to the underlying implementation. As such, opaque type aliasing is an abstraction mechanism. Consider the following file, which contains an opaque alias definition for a tuple that mimics a point: ```Hack newtype Point = (float, float); function create_Point(float $x, float $y): Point { return tuple($x, $y); } function distance(Point $p1, Point $p2): float { $dx = $p1[0] - $p2[0]; $dy = $p1[1] - $p2[1]; return sqrt($dx*$dx + $dy*$dy); } ``` ## Choosing between `type` and `newtype` Looking at the earlier example, being in the same source file as the alias definition, the functions `create_Point` and `distance` have direct access to the `float` fields in any `Point`'s tuple. However, other files will not have this same access. Similarly, if a source file defines the following opaque alias... ```Hack newtype Widget = int; ``` ...any file that includes this file has no knowledge that a `Widget` is really an integer, so that the including file cannot perform any integer-like operations on a `Widget`. Consider a file that contains the following opaque type definition: ```Hack newtype Counter = int; ``` Any file that includes this file has no knowledge that a Counter is really an integer, meaning the including file *cannot* perform any integer-like operations on that type. This is a major limitation, as the supposedly well-chosen name for the abstract type, Counter, suggests that its value could increase and/or decrease. We can fix this by adding a type constraint to the alias's definition, as follows: ```Hack newtype Counter as int = int; ``` The presence of the type constraint `as int` allows the opaque type to be treated as if it had the type specified by that type constraint, which removes some of the alias' opaqueness. Although the presence of a constraint allows the alias type to be converted implicitly to the constraint type, no conversion is defined in the opposite direction. In this example, this means that a Counter may be implicitly converted into an `int`, but not the other way around. Consider the following: ```Hack no-extract class C { const type T2 as arraykey = int; // ... } ``` Here, we have a class-specific type constant that is an alias, which allows a value of type `T2` to be used in any context an `arraykey` is expected. After all, any `int` value is also an `arraykey` value.
Markdown
hhvm/hphp/hack/manual/hack/10-types/82-supertypes-and-subtypes.md
The set of built-in and user-defined types in Hack can be thought of as a type hierarchy of *supertypes* and *subtypes* in which a variable of some type can hold the values of any of its subtypes. For example, `int` and `float` are subtypes of `num`. A supertype can have one or more subtypes, and a subtype can have one or more supertypes. A supertype can be a subtype of some other supertype, and a subtype can be a supertype of some other subtype. The relationship between a supertype and any of its subtypes involves the notion of substitutability. Specifically, if *T2* is a subtype of *T1*, program elements designed to operate on *T1* can also operate on *T2*. For types in Hack, the following rules apply: * The root of the type hierarchy is the type `mixed`; as such, every type is a subtype of that type. * Any type is a subtype of itself. * `int` and `float` are subtypes of `num`. * `int` and `string` are subtypes of `arraykey`. * For each type *T*, *T* is a subtype of the nullable type `?`*T*. * For each type *T*, the null type is a subtype of all nullable types `?`*T*. * `string` is a subtype of `Stringish`. * The predefined types `vec`, `dict`, and `keyset` are subtypes of `Container`, `KeyedContainer`, `KeyedTraversable`, and `Traversable`. * If *A* is an alias for a type *T* created using `type`, then *A* is a subtype of *T*, and *T* is a subtype of *A*. * If *A* is an alias for a type *T* created using `newtype`, inside the file containing the `newtype` definition, A is a subtype of *T*, and *T* is a subtype of *A*. Outside that file, *A* and *T* have no relationship, except that given `newtype A as C = T`, outside the file with the `newtype` definition, *A* is a subtype of *C*. * Any class, interface, or trait, having a public instance method `__toString` taking no arguments and returning string, is a subtype of `Stringish`. * A class type is a subtype of all its direct and indirect base-class types. * A class type is a subtype of all the interfaces it and its direct and indirect base-class types implement. * An interface type is a subtype of all its direct and indirect base interfaces. * A shape type *S2* whose field set is a superset of that in shape type *S1*, is a subtype of *S1*. * Although [`noreturn`](../built-in-types/noreturn.md) is not a type, per se, it is regarded as a subtype of all other types, and a supertype of none.
Markdown
hhvm/hphp/hack/manual/hack/10-types/85-type-refinement.md
A supertype has one or more subtypes, and while any operation permitted on a value of some supertype is also permitted on a value of any of its subtypes, the reverse is not true. For example, the type `num` is a supertype of `int` and `float`, and while addition and subtraction are well defined for all three types, bit shifting requires integer operands. As such, a `num` cannot be bit-shifted directly. (Similar situations occur with `arraykey` and its subtypes `int` and `string`, with nullable types and their subtypes, and with `mixed` and its subtypes.) Certain program elements are capable of changing the type of an expression using what is called *type refinement*. Consider the following: ```Hack function f1(?int $p): void { // $x = $p % 3; // rejected; % not defined for ?int if ($p is int) { // type refinement occurs; $p has type int $x = $p % 3; // accepted; % defined for int } } ``` When the function starts execution, `$p` contains `null` or some `int`. However, the type of the expression `$p` is not known to be `int`, so it is not safe to allow the `%` operator to be applied. When the test `is int` is applied to `$p`, a type refinement occurs in which the type of the expression `$p` is changed to `int` **for the true path of the `if` statement only**. As such, the `%` operator can be applied. However, once execution flows out of the `if` statement, the type of the expression `$p` is `?int`. Consider the following: ```Hack function f2(?int $p): void { if ($p is null) { // type refinement occurs; $p has type null // $x = $p % 3; // rejected; % not defined for null } else { // type refinement occurs; $p has type int $x = $p % 3; // accepted; % defined for int } } ``` The first assignment is rejected, not because we don't know `$p`'s type, but because we know its type is not `int`. See how an opposite type refinement occurs with the `else`. Similarly, we can write the following: ```Hack function f3(?int $p): void { if (!$p is null) { // type refinement occurs; $p has type int $x = $p % 3; // accepted; % defined for int } if ($p is nonnull) { // type refinement occurs; $p has type int $x = $p % 3; // accepted; % defined for int } } ``` Consider the following example that contains multiple selection criteria: ```Hack function f4(?num $p): void { if (($p is int) || ($p is float)) { // $x = $p**2; // rejected } } ``` **An implementation is not required to produce the correct type refinement when using multiple criteria directly.** The following constructs involve type refinement: * When used as the controlling expression in an `if`, `while`, or `for` statement, the operators `==`, `!=`, `===`, and `!==` when used with one operand of `null`, `is`, and simple assignment `=`. [Note that if `$x` is an expression of some nullable type, the logical test `if ($x)` is equivalent to `if ($x is nonnull)`.] * The operators `&&`, `||`, and `?:`. * The intrinsic function `invariant`. * Some built-in functions like `Shapes::keyExists()` and `\HH\is_any_array()` have special typechecking rules, but others, like `is_string()` and `is_null()` don't. Thus far, all the examples use the value of an expression that designates a parameter (which is a local variable). Consider the following case, which involves a property: ```Hack class C { private ?int $p = 8; // holds an int, but type is ?int public function m(): void { if ($this->p is int) { // type refinement occurs; $this->p is int $x = $this->p << 2; // allowed; type is int $this->n(); // could involve a permanent type refinement on $p // $x = $this->p << 2; // disallowed; might no longer be int } } public function n(): void { /* ... */ } } ``` Inside the true path of the `if` statement, even though we know that `$this->p` is an `int` to begin with, once any method in this class is called, the implementation must assume that method could have caused a type refinement on anything currently in scope. As a result, the second attempt to left shift is rejected.
Markdown
hhvm/hphp/hack/manual/hack/10-types/86-with-refinement.md
Besides `is`-expressions, Hack supports another form of type refinements, which we refer to as `with`-refinements in this section. This feature allows more precise typing of classes/interfaces/traits in a way that specific _type_ or _context_ constant(s) are more specific (i.e., refined). For example, given the definition ```Hack file:box-with-type+ctx.hack interface Box { abstract const type T; abstract const ctx C super [defaults]; public function get()[this::C]: this::T; } ``` one can write a function for which Hack statically guarantees the returned `Set` is [valid](https://docs.hhvm.com/hack/reference/class/HH.Set/), i.e., it only contains integers and/or strings, and not objects of any other type: ```Hack file:box-with-type+ctx.hack function unwrap_as_singleton_set<Tb as arraykey>( Box with { type T = Tb } $int_or_string_box ): Set<Tb> { return Set { $int_or_string_box->get() }; } ``` Independently, one can constrain context `C` in `Box`. For example, to work with `Box` subtypes which implement the `get` method in a pure way (without side effects), `with`-refinements can be used as follows: ```Hack file:box-with-type+ctx.hack function unwrap_pure<Tb>( Box with { ctx C = []; type T = Tb } $box, )[]: Tb { return $box->get(); // OK (type-checker knows `get` must have the empty context list) } ``` A notable use case unlocked by this feature is that a `with`-refinement can appear in return positions, e.g.: ```Hack file:box-with-type+ctx.hack // API function wrap_number(num $x): Box with { type T = num } { return new IntBox($x); } // implementation details (subject to change): class IntBox implements Box { const type T = num; const ctx C = []; public function __construct(private this::T $v) {} public function get()[]: this::T { return $this->v; } } ``` This is something that is inexpressible with where-clauses. Loose (`as`, `super`) bounds on refined constants, such as `type T` and `context C`, are also supported. For example, you can write functions _statically_ safe functions such as: ```Hack file:box-with-type+ctx.hack function boxed_sum( Traversable<Box with { type T as num }> $numeric_boxes ): float { $sum = 0.0; foreach ($numeric_boxes as $nb) { $sum += $nb->get(); } return $sum; } ``` and avoid assertions that objects returned by Box’s `get` methods are numbers (`int` or `float`). Finally, you can also use [generics](https://docs.hhvm.com/hack/generics/introduction) in bounds; e.g., the above function could have signature ``` function boxed_sum_generic<T as num>( Traversable<Box with { type T = T }> $numeric_boxes ): T /* or float */ ``` ### Sound alternative to `TGeneric::TAbstract` This section shows how to improve type safety of existing Hack code that employs a common pattern in which the intent is to read the type constant associated with the function- or class-level generic that is bounded by an abstract class or interface. As an example, consider the following definition: ```Hack file:box-with-type+ctx.hack interface MeasuredBox extends Box { abstract const type TQuantity; public function getQuantity(): this::TQuantity; } ``` Projections off a generic at the function level, such as ```Hack file:box-with-type+ctx.hack function weigh_bulk_unsafe<TBox as MeasuredBox>(TBox $box): float where TBox::TQuantity = float { return $box->getQuantity(); } ``` can and should be translated into: ```Hack file:box-with-type+ctx.hack function weigh_bulk(MeasuredBox with { type TQuantity = float } $box): float { return $box->getQuantity(); } ``` Hack offers a means of _conditionally_ enabling specific methods via where-clauses. E.g., to define a method `unloadByQuantity` that is only callable on subclasses of `Box` where `TQuantity` is an integer (representing boxes with quantity that is countable exactly), one could write: ```Hack no-extract class Warehouse<TBox as Box> { public function unloadByCount(TBox $boxes): void where TBox::TQuantity = int { /* … */ } } ``` This can be translated to type refinements with a nuance: ```Hack no-extract class Warehouse<TBox as Box> { public function unloadByCount(TBox $boxes): int where TBox as Box with { type TQuantity = int } { /* … */ } } ``` #### **Migration note**: This is _stricter_ than the original version with where-clauses because it is actually sound. Notably, the migrated method, which now uses type refinements, is _uncallable_ from unmigrated methods that still use where-clauses. ```Hack no-extract function callee_that_now_errs<TBox as Box>( Warehouse<TBox> $warehouse, TBox $unknown_box, T $contents, ): void where TBox::T = T { $warehouse->unloadByCount($unknown_box); // ERROR /* … */ } ``` Therefore, while migrating code with pattern `TGeneric::TAbstractType` and where-clauses, you will need to migrate top-down in the callee graph. This process may also reveal some unsafe usages of the previous pattern, which is too permissive in theory and could allow reading abstract type (and thus fail at run-time). and Hack may chose to do so in the future, too.
Markdown
hhvm/hphp/hack/manual/hack/10-types/88-type-inferencing.md
While certain kinds of variables must have their type declared explicitly, others can have their type inferred by having the implementation look at the context in which those variables are used. For example: ```Hack function foo(int $i): void { $v = 100; } ``` As we can see, `$v` is implicitly typed as `int`, and `$i` is explicitly typed. In Hack, * Types **must be declared** for properties and for the parameters and the return type of named functions. * Types **must be inferred** for local variables, which includes function statics and parameters. * Types **can be declared or inferred** for constants and for the parameters and return type of unnamed functions. The process of type inferencing does not cross function boundaries. Here's an example involving a local variable: ```Hack file:c.hack function f(): void { $v = 'acb'; // $v has type string // ... $v = true; // $v has type bool // ... $v = dict['red' => 10, 'green' => 15]; // $v has type dict<string, int> // ... $v = new C(); // $v has type C } ``` For each assignment, the type of `$v` is inferred from the type of the expression on the right-hand side, as shown in the comments. The type of function statics is inferred in the same manner, as are function parameters. For example: ```Hack function g(int $p1 = -1): void { // on entry to the function, $p1 has the declared type int // ... $p1 = 23.56; // $p1 has type float // ... } ``` As a parameter, `$p1` is required to have a declared type, in this case, `int`. However, when used as an expression, `$p1`'s type can change, as shown. In the case of a class constant, if the type is omitted, it is inferred from the initializer: ```Hack file:c.hack class C { const C1 = 10; // type int inferred from initializer const string C2 = "red"; // type string declared } ``` Let's consider types in closures: ```Hack $doubler = $p ==> $p * 2; $doubler(3); ``` The type of the parameter `$p` and the function's return type have been omitted. These types are inferred each time the anonymous function is called through the variable `$doubler`. When `3` is passed, as that has type `int`, that is inferred as the type of `$p`. The literal `2` also has type `int`, so the type of the value returned is the type of `$p * 2`, which is `int`, and that becomes the function's return type. We can add partial explicit type information; the following all result in the same behavior: ```Hack $doubler = (int $p) ==> $p * 2; $doubler = ($p = 0) ==> $p * 2; $doubler = ($p): int ==> $p * 2; ``` In the first case, as `$p` has the declared type `int`, and `int * int` gives `int`, the return type is inferred as `int`. In the second case, as the default value `0` has type `int`, `$p` is inferred to also have that type, and `int * int` gives `int`, so the return type is inferred as `int`. In the third case, as the return type is declared as `int`, and `$p * 2` must have that type, the type of `$p` is inferred as `int`, so that must also be the type of the parameter. While all three of these cases allow a call such as `$doubler(3)`, none of them allow a call such as `$doubler(4.2)`. So, the fact that type information can be provided explicitly in these cases doesn't mean it's necessarily a good idea to do so.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/01-introduction.md
This section covers the different built-in types available in Hack. ## Primitive Types Hack has the following primitive types: [bool](/hack/built-in-types/bool), [int](/hack/built-in-types/int), [float](/hack/built-in-types/float), [string](/hack/built-in-types/string), and [null](/hack/built-in-types/null). ## Union Types Hack supports union types, like: * [num](/hack/built-in-types/num), where `int` and `float` are subtypes of `num`, and * [arraykey](/hack/built-in-types/arraykey), where `int` and `string` are subtypes of `arraykey`. ## The Super Type Hack's super type is [mixed](/hack/built-in-types/mixed), which represents any value. All other types are subtypes of `mixed`. A few things to know when working with `mixed` as a type: * The opposite of `mixed` is [nothing](/hack/built-in-types/nothing), a special type at the "bottom" of all other types. * `mixed` is equivalent to `?nonnull`. [nonnull](/hack/built-in-types/nonnull) is a type that represents any value except `null`. ## Hack Arrays There are three types of [Hack Arrays](/hack/arrays-and-collections/introduction). They are: [vec](/hack/arrays-and-collections/hack-arrays#vec), [keyset](/hack/arrays-and-collections/hack-arrays#keyset), and [dict](/hack/arrays-and-collections/hack-arrays#dict). Though not built-in as types, other alternatives exist in [Hack Collections](/hack/arrays-and-collections/collections). ## Other Built-In Types Hack has other built-in types too, like: [enum](/hack/built-in-types/enum) (with [enum class](/hack/built-in-types/enum-class) and [enum class labels](/hack/built-in-types/enum-class-label)), [shape](/hack/built-in-types/shapes), and [tuples](/hack/built-in-types/tuples). ## Function Return Types Other types like [noreturn](/hack/built-in-types/noreturn) and [void](/hack/built-in-types/void) are only valid as function return types . ## Special Types These last few types are special in their utility and/or versatility: [classname](/hack/built-in-types/classname), [dynamic](/hack/built-in-types/dynamic), and [this](/hack/built-in-types/this).
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/04-bool.md
The Boolean type `bool` can store two distinct values, which correspond to the Boolean values `true` and `false`, respectively. Consider the following example: ```Hack function is_leap_year(int $yy): bool { return ((($yy & 3) === 0) && (($yy % 100) !== 0)) || (($yy % 400) === 0); } <<__EntryPoint>> function main(): void { $result = is_leap_year(1900); echo "1900 is ".(($result === true) ? "" : "not ")."a leap year\n"; } ``` When called, function `is_leap_year` takes one argument, of type `int`, and returns a value of type `bool`. (A year is a leap year if it is a multiple of 4 but not a multiple of 100&mdash;for example, 1700, 1800, and 1900 were *not* leap years&mdash;or it's a multiple of 400. Some redundant grouping parentheses have been added to aid readability.) The equality operators `===` and `!==`, and the logical operators `&&` and `||`, all produce `bool` results, with the ultimate result of the large `bool` expression being returned from the function. As `is_leap_year` is explicitly typed to return a `bool`, the local variable `$result` is inferred as having type `bool`. (Unlike function parameters such as `$yy`, or a function return, a local variable *cannot* have an explicit type.) The value of `$result` is compared to the `bool` literal `true`, and the `bool` result is used as the controlling expression of the `?:` operator.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/07-int.md
The integer type `int` is signed and uses twos-complement representation for negative values. At least 64 bits are used, so the range of values that can be stored is at least [-9223372036854775808, 9223372036854775807]. Namespace HH\Lib\Math contains the following integer-related constants: `INT64_MAX`, `INT64_MIN`, `INT32_MAX`, `INT32_MIN`, `INT16_MAX`, `INT16_MIN`, and `UINT32_MAX`. Refer to your compiler's documentation to find the behavior when the largest `int` value is incremented, the smallest value is decremented, and the unary minus is applied to the smallest value. Consider the following example: ```Hack function is_leap_year(int $yy): bool { return ((($yy & 3) === 0) && (($yy % 100) !== 0)) || (($yy % 400) === 0); } <<__EntryPoint>> function main(): void { $year = 2001; $result = is_leap_year($year); echo "$year is ".(($result === true) ? "" : "not ")."a leap year\n"; } ``` When called, function `is_leap_year` takes one argument, of type `int`, and returns a value of type `bool`. (A year is a leap year if it is a multiple of 4 but not a multiple of 100&mdash;for example, 1700, 1800, and 1900 were *not* leap years&mdash;or it's a multiple of 400. Some redundant grouping parentheses have been added to aid readability.) The bitwise AND operator, `&`, and the remainder operator, `%`, require operands of type `int`. Like `3`, `0`, `100`, and `400`, `2001` is an `int` literal, so the local variable `$year` is inferred as having type `int`. (Unlike function parameters such as `$yy`, or a function return, a local variable *cannot* have an explicit type.) Then when `$year` is passed to `is_leap_year`, the compiler sees that an `int` was passed and an `int` was expected, so the call is well-formed.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/10-float.md
The floating-point type, `float`, allows the use of real numbers. It supports at least the range and precision of IEEE 754 64-bit double-precision representation, and includes the special values minus infinity, plus infinity, and Not-a-Number (NaN). Using predefined constant names, those values are written as `-INF`, `INF`, and `NAN`, respectively. The library functions `is_finite`, `is_infinite`, and `is_nan` indicate if a given floating-point value is finite, infinite, or a NaN, respectively. Consider the following example: ```Hack function average_float(float $p1, float $p2): float { return ($p1 + $p2) / 2.0; } <<__EntryPoint>> function main(): void { $val = 3e6; $result = average_float($val, 5.2E-2); echo "\$result is ".$result."\n"; } ``` When called, function `average_float` takes two arguments, of type `float`, and returns a value of type `float`. The literals `2.0`, `3e6`, and `5.2E-2` have type `float`, so the local variable `$val` is inferred as having type `float`. (Unlike function parameters such as `$p1` and `$p2`, or a function return, a local variable *cannot* have an explicit type.) Then when `$val` and `5.2E-2` are passed to `average_float`, the compiler sees that two `float`s were passed and two `float`s were expected, so the call is well-formed.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/13-num.md
The type `num` can represent any `int` or `float` value. This type can be useful when specifying the interface to a function. Consider the following function declarations from the math library: ```Hack no-extract function sqrt(num $arg): float; function log(num $arg, ?num $base = null): float; function abs<T as num>(T $number): T; function mean(Container<num> $numbers): ?float; ``` The square-root function `sqrt` takes a `num` and returns a `float`. The log-to-any-base function `log` takes a `num` and a nullable-of-`num` and returns a `float`. The generic absolute-value function `abs` has one type parameter, `T`, which is constrained to having type `num` or a subtype of `num`. `abs` takes an argument of type `T` and returns a value of the same type. The arithmetic-mean function `mean` takes a generic type `Container`-of-type-`num` and returns a nullable-of-`float`. Consider the following example: ```Hack class Point { private float $x; private float $y; public function __construct(num $x = 0, num $y = 0) { $this->x = (float)$x; $this->y = (float)$y; } public function move(num $x = 0, num $y = 0): void { $this->x = (float)$x; $this->y = (float)$y; } // ... } ``` Internally, class `Point` stores the x- and y-coordinates as `float`s, but, for convenience, it allows any combination of `int`s and `float`s to be passed to its constructor and method `move`. When given a `num` value, to find out what type of value that `num` actually contains, use the `is` operator. See the discussion of [type refinement](../types/type-refinement.md).
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/16-string.md
A `string` is a sequence of *bytes* - they are not required to be valid characters in any particular encoding, for example, they may contain null bytes, or invalid UTF-8 sequences. # Basic operations Concatenation and byte indexing are built-in operations; for example: - `"foo"."bar"` results in `"foobar"` - `"abc"[1]` is `"b"` - if the source code is UTF-8, `"a😀c"[1]` is byte `0xf0`, the first of the 4 bytes compromising the "😀" emoji in UTF-8 Other operations are supported by the `Str\` namespace in the [Hack Standard Library](/hsl/reference/), such as: - `Str\length("foo")` is 3 - `Str\length("foo\0")` is 4 - `Str\length("a😀c")` is 6 - `Str\join(vec['foo', 'bar', 'baz'], '!')` is `"foo!bar!baz"` # Converting to numbers Use `Str\to_int()` to convert strings to integers; this will raise errors if the input contains additional data, such as `.0` or other trailing characters. `(int)` and `(float)` are more permissive, but have undefined behavior for inputs containing similar trailing data. # Bytes vs characters Functions in the `Str\` namespace with an `_l` suffix such as `Str\length_l()` take a `Locale\Locale` object as the first parameter, which represents the language, region/country, and encoding (e.g. `en_US.UTF-8`); if a multibyte encoding such as UTF-8 is specified, the `_l()` functions operate on characters instead of bytes. For example: - `Str\length("a😀c")` is 6 - `Str\length_l(Locale\bytes(), "a😀c")` is 6 - `Str\length_l(Locale\create("en_US.UTF-8"), "a😀c")` is 3 - `Str\slice("a😀c", 2)` is `"a\xf0"` (2 bytes) - `Str\slice_l(Locale\create("en_US.UTF-8"), "a😀c", 2)` is `"a😀"` (5 bytes) In some encodings, the same character can be represented in multiple different ways, with multiple byte sequences; the `_l` functions will treat them as equivalent. For example, the letter `é` can be represented by either: - `"\u{00e9}"`, or "\xc3\xa9" ("LATIN SMALL LETTER E ACUTE") - `"\u{0065}\u{0301}"`, or `\x65\xcc\x81" ("LATIN SMALL LETTER E", followed by "COMBINING ACUTE ACCENT") This means that various comparison functions may report strings as equivalent, despite containing different byte sequences - so if the result of a character-based operation is used for another function, that function should also be character-based: ```Hack use namespace HH\Lib\{Locale,Str}; <<__EntryPoint>> function main(): void { $haystack = "abc\u{00e9}"; // ends with UTF-8 "LATIN SMALL LETTER E ACUTE" $needle = "\u{0065}\u{0301}"; // "LATIN SMALL LETTER E", "COMBINING ACUTE ACCENT" $locale = Locale\create("en_US.UTF-8"); \var_dump(dict[ 'Byte test' => Str\ends_with($haystack, $needle), // false 'Character test' => Str\ends_with_l($locale, $haystack, $needle), // true 'Strip byte suffix' => Str\strip_suffix($haystack, $needle), // no change 'Strip character suffix' => Str\strip_suffix_l($locale, $haystack, $needle), // removed ]); } ``` # Default encoding If a locale is specified without an encoding (e.g. `en_US`, compared to `en_US.UTF-8` or `en_US.ISO8859-1`), the system behavior will be followed. For example: - on most Linux systems, `en_US` uses a single-byte-per-character-encoding - on MacOS, `en_US` uses UTF-8 # The `Locale\bytes()` locale This locale is similar to the constant `"C"` or `"en_US_POSIX"` locale in other libraries and environments; we refer to it as the `bytes` locale to more clearly distinguish between this constant locale and the variable "active libc locale", and because the behavior is slightly different than libc both for performance, and to accomodate arbitrary byte sequences; for example, `Str\length("a\0b")` is 3, however, the libc `strlen` function returns 1 for the same input. While operations such as string formatting, uppercase, and lowercase are defined for this locale, they should only be used when localization is not a concern, for example when the output is intended to be machine-readable instead of human-readable, such as when generating code. # Functions without a locale parameter In HHVM 4.130 and above, the bytes locale is the default locale used by the `Str\` functions that do not take an explicit locale - that is, `Str\foo($bar)` is equivalent to `Str\foo_l(Locale\bytes(), $bar)`. In prior versions, the active native/libc locale would be used instead; `Str\foo_l(Locale\get_native(), $bar)` can be used to late the prior behavior. This behavior was changed as: - functions such as `Str\format()` were frequently used to to generate machine-readable strings, leading to subtle bugs when locale was changed. For example, `Str\format('%.2f', 1.23)` could return either '1.23' or '1,23'. - functions still operated on bytes rather than characters, even with `LC_CTYPE` was set to `UTF-8`. - users expect functions such as `Str\format()` and `Str\uppercase()` to be pure, however they can not be when they depend on the current locale, which is effectively a global variable. # Recommendations - use the non-`_l` variants of functions when generating strings intended for machines to read. - use the non-`_l` variants when looking for searching for or operating on specific byte sequences. - avoid using `setlocale()` or `Locale\set_native()`; instead, store/pass a `Locale\Locale` object for the viewer in a similar way to how you store/pass other information about the viewer, such as their ID. - prefer `Locale\set_native()` over `setlocale()`. - if setting a locale, always explicitly specify an encoding, unless you are matching the behavior of other local executables or native libraries - if either is necessary, restore the default locale with `Locale\set_native(Locale\bytes())`; while this can be functionally equivalent to various other locales (e.g. `"en_US"` or `"C"`), HHVM contains optimizations specifically for the `Locale\bytes()` locale. `setlocale()` and `Locale\set_native()` affect many C libraries and extension; in web requests, this can lead to error messages in logs being translated to the viewer rather than the log reader, though for CLI programs, this behavior can be desirable. # Supported encodings HHVM currently supports UTF-8, and single-byte encodings that are supported by the platform libc. Other encodings may be supported in the future, however `Locale\set_native()` is likely to be restricted to the current locales; for example, UTF-16 can not be supported by `Locale\set_native()`, as UTF-16 strings can contain null bytes. # Working with `Regex\` Functions in the `Regex\` namespace operate on bytes. If the string being inspected is UTF-8, use a pattern with the `u` flag. Failing to do so may result in one multi-byte character being interpreted as multiple characters. For example: - `Regex\replace("\u{1f600}", re"/./", 'Char')` is `CharCharCharChar` - `Regex\replace("\u{1f600}", re"/./u", 'Char')` is `Char`
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/19-void.md
The type `void` indicates the absence of a value. It is used to declare that a function does *not* return any value. As such, a void function can contain one or more `return` statements, provided none of them return a value. Consider the following example: ```Hack function draw_line(Point $p1, Point $p2): void { /* ... */ } class Point { private float $x; private float $y; public function __construct(num $x = 0, num $y = 0) { $this->x = (float)$x; $this->y = (float)$y; } public function move(num $x = 0, num $y = 0): void { $this->x = (float)$x; $this->y = (float)$y; } // ... } <<__EntryPoint>> function main(): void { draw_line(new Point(1.2, 3.3), new Point(6.2, -4.5)); } ``` As is often the case, a function like `draw_line` causes something to happen but does not need to return a result or success code, so its return type is `void`. Likewise, for method `move`. Here's another example, involving a generic stack type: ```Hack class Stack<T> { // ... public function push(T $value): void { /* ... */ } // ... } ``` The act of pushing a value on a stack does not require any value to be returned. However, method `push` could fail due to stack overflow; however, as that is an extreme situation, the method likely would throw an exception that is only handled when the condition occurs rather than returning a success/failure code that would have to be checked on every call.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/25-tuples.md
Suppose we wish to have a function return multiple values. We can do that by using a tuple containing two or more elements. A tuple is an *ordered* set of one or more elements, which can have different types. The number of elements in a particular tuple is fixed when that tuple is created. After a tuple has been created, no elements can be added or removed. A tuple is a mutable value type. This means that when you hand a tuple to a function or assign it to a local variable a logical copy is made. You can change the values at a given index by assigning using the subscript notation. This will change the type of the value stored in the variable accordingly when needed. However you can not assign to an index that did not exist when the tuple was created. Consider the case in which we want to have a pair of related values, one a string, the other an integer. For example: ```Hack no-extract $v = tuple("apples", 25); function process_pair((string, int) $pair): void { ... } function get_next_pair(): (string, int) { ... } ``` A tuple value has the form of a comma-separated list of values delimited with parentheses and preceded by `tuple`, as in `tuple("apples", 25)` above. As we can quickly deduce, that tuple has type *tuple of two elements, in the order `string` and `int`*, and that is the type of the argument expected by function `process_pair`, and returned by function `get_next_pair`. Note carefully that the tuple values `tuple("apples", 25)` and `tuple(25, "apples")` have *different and incompatible* types! Of course, `tuple("apples", 25)` and `tuple("peaches", 33)` have the same type. [Indeed, `tuple("horses", 3)` has the same type as well; there is nothing fruit- or animal-specific about this tuple type.] A tuple can be indexed with the subscript operator (`[]`); however, the index value must be an integer constant whose value is in the range of element indices. The index of the first element is zero, with subsequent elements having index values one more than their predecessor: ```Hack $t = tuple(10, true, 2.3); echo "\$t[2] = >" . $t[2] . "<"; // outputs "$t[2] = >2.3<" $t[0] = 99; // change 10 to 99 ``` Here is a more exotic example of a type involve a tuple: ```Hack no-extract ?(int, (string, float)) ``` This declares a nullable type for a tuple containing an `int` and a tuple, which in turn, contains a `string` and a `float`. For non-trivial tuple types, it can be cumbersome to write out the complete type. Fortunately, Hack provides type-aliasing via `newtype` (and `type`). For example: ```Hack newtype Point = (float, float); function create_point(float $x, float $y): Point { return tuple($x, $y); } function distance(Point $p1, Point $p2): float { $dx = $p1[0] - $p2[0]; $dy = $p1[1] - $p2[1]; return sqrt($dx * $dx + $dy * $dy); } ```
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/28-shape.md
A shape is a lightweight type with named fields. It's similar to structs or records in other programming languages. ```Hack $my_point = shape('x' => -3, 'y' => 6, 'visible' => true); ``` ## Shape Values A shape is created with the `shape` keyword, with a series of field names and values. ``` Hack $server = shape('name' => 'db-01', 'age' => 365); $empty = shape(); ``` Shape fields are accessed with array indexing syntax, similar to `dict`. Note that field names must be string literals. ```Hack no-extract // OK. $n = $server['name']; // Not OK (type error). $field = 'name'; $n = $server[$field]; ``` Shapes are copy-on-write. ``` Hack $s1 = shape('name' => 'db-01', 'age' => 365); $s2 = $s1; $s2['age'] = 42; // $s1['age'] is still 365. ``` A shape can be constructed incrementally. The type checker will infer a different type after each assignment. ``` Hack // $s has type shape(). $s = shape(); // $s now has type shape('name' => string). $s['name'] = 'db-01'; // $s now has type shape('name' => string, 'age' => int). $s['age'] = 365; ``` Shapes have the same runtime representation as `darray`, although this is considered an implementation detail. This representation means that shape order is observable. ``` Hack $s1 = shape('name' => 'db-01', 'age' => 365); $s2 = shape('age' => 365, 'name' => 'db-01'); $s1 === $s2; // false ``` ## Shape Types Shape type declarations use a similar syntax to values. ``` Hack function takes_server(shape('name' => string, 'age' => int) $s): void { // ... } ``` Unlike classes, declaring a shape type is optional. You can start using shapes without defining any types. ``` Hack no-extract function uses_shape_internally(): void { $server = shape('name' => 'db-01', 'age' => 365); print_server_name($server['name']); print_server_age($server['age']); } ``` For large shapes, it is often convenient to define a type alias. This is useful because it promotes code re-use and when the same type is being used, and provides a descriptive name for the type. ```Hack type Server = shape('name' => string, 'age' => int); // Equivalent to the previous takes_server function. function takes_server(Server $s): void { // ... return; } ``` Any shape value that has all of the required fields (and no undefined fields - unless the shape permits them) is considered a value of type `Server`; the type is not specified when creating the value. ```Hack error function takes_server(Server $s): void { return; } function test(): void { $args = shape('name' => 'hello', 'age' => 10); takes_server($args); // no error $args = shape('name' => null, 'age' => 10); takes_server($args); // type error: field type mismatch $args = shape('name' => 'hello', 'age' => 10, 'error' => true); takes_server($args); // type error: extra field } ``` Since shapes are copy-on-write, updates can change the type. ```Hack // $s has type shape('name' => string, 'age' => int). $s = shape('name' => 'db-01', 'age' => 365); // $s now has type shape('name' => string, 'age' => string). $s['age'] = '1 year'; ``` **Two shapes have the same type if they have the same fields and types**. This makes shapes convenient to create, but can cause surprises. This is called 'structural subtyping'. ```Hack type Server = shape('name' => string, 'age' => int); type Pet = shape('name' => string, 'age' => int); function takes_server(Server $_): void {} function takes_pet(Pet $p): void { // No error here. takes_server($p); } ``` ## Open and Closed Shapes Normally, the type checker will enforce that you provide exactly the fields specified. This is called a 'closed shape'. ```Hack error function takes_named(shape('name' => string) $_): void {} function demo(): void { takes_named(shape('name' => 'db-01', 'age' => 365)); // type error } ``` Shape types may include `...` to indicate that additional fields are permitted. This is called an 'open shape'. ```Hack function takes_named(shape('name' => string, ...) $_): void {} // OK. function demo(): void { takes_named(shape('name' => 'db-01', 'age' => 365)); } ``` To access the additional fields in an open shape, you can use `Shapes::idx`. ```Hack function takes_named(shape('name' => string, ...) $n): void { // The value in the shape, or null if field is absent. $nullable_age = Shapes::idx($n, 'age'); // The value in the shape, or 0 if field is absent. $age_with_default = Shapes::idx($n, 'age', 0); } ``` ## Optional Fields A shape type may declare fields as optional. ```Hack function takes_server(shape('name' => string, ?'age' => int) $s): void { $age = Shapes::idx($s, 'age', 0); } function example_usage(): void { takes_server(shape('name' => 'db-01', 'age' => 365)); takes_server(shape('name' => 'db-02')); } ``` `takes_server` takes a closed shape, so any additional fields will be an error. The `age` field is optional though. Optional fields can be tricky to reason about, so your code may be clearer with nullable fields or open shapes. ```Hack function takes_server2(shape('name' => string, 'age' => ?int) $s): void { $age = $s['age'] ?? 0; } function takes_server3(shape('name' => string, ...) $s): void { $age = Shapes::idx($s, 'age', 0) as int; } ``` ## Type Enforcement HHVM will check that arguments are shapes, but it will not deeply check fields. ```Hack error // This produces a typehint violation at runtime. function returns_int_instead(): shape('x' => int) { return 1; } // No runtime error. function returns_wrong_shape(): shape('x' => int) { return shape('y' => 1); } ``` ## Converting Shapes Converting shapes to containers is strongly discouraged, however is necessary, this can be done with `Shapes::toDict()`. On older versions of HHVM, Shapes can also be converted to darrays with `Shapes::toArray()`; this should be avoided in new code, as darrays are currently an alias for the dict type, and will be removed from the language. ## Limitations Some limitations of shapes include only being able to index it using literal expressions (you can't index on a shape using a variable or dynamically formed string, for example), or to provide run-time typechecking, because it is actually just a `dict` at runtime (or `darray` on older versions).
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/31-arraykey.md
The type `arraykey` can represent any integer or string value. For example: ```Hack function process_key(arraykey $p): void { if ($p is int) { // we have an int } else { // we have a string } } ``` Values of array or collection type can be indexed by `int` or `string`. Suppose, for example, an operation was performed on an array to extract the keys, but we didn't know the type of the key. As such, we are left with using `mixed` (which is way too loose) or doing some sort of duplicative code. Instead, we can use `arraykey`. See the discussion of [type refinement](../types/type-refinement.md).
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/34-enum.md
Use an enum (enumerated type) to create a set of named, constant, immutable values. In Hack, enums are limited to `int` or `string` (as an [`Arraykey`](/hack/built-in-types/arraykey)), or other `enum` values. ## Quickstart To access an enum's value, use its full name, as in `Colors::Blue` or `Permission::Read`. ```Hack enum Colors: int { Red = 3; Green = 5; Blue = 10; Default = 3; // duplicate value is okay } ``` ```Hack enum Permission: string { Read = 'R'; Write = 'W'; Execute = 'E'; Delete = 'D'; } ``` Additionally, by using the [`as`](/hack/expressions-and-operators/type-assertions#enforcing-types-with-as-and-as) operator to enforce type, you can initialize your enum with static expressions that reference other enum values. ```Hack enum BitFlags: int as int { F1 = 1; // value 1 F2 = BitFlags::F1 << 1; // value 2 F3 = BitFlags::F2 << 1; // value 4 F4 = 4 + 3; // value 7 } ``` ## Full Example With an enum, we can create a placement-direction system with names like `Top`, `Bottom`, `Left`, `Right`, and `Center`, then direct output accordingly to write text to the top, bottom, left, right, or center of a window. ```Hack enum Position: int { Top = 0; Bottom = 1; Left = 2; Right = 3; Center = 4; } function writeText(string $text, Position $pos): void { switch ($pos) { case Position::Top: // ... break; case Position::Center: // ... break; case Position::Right: // ... break; case Position::Left: // ... break; case Position::Bottom: // ... break; } } <<__EntryPoint>> function main(): void { writeText("Hello", Position::Bottom); writeText("Today", Position::Left); } ``` ## Library Methods All enums implement these public static methods. ### `getValues()` / `getNames()` Returns a `dict` of enum constant values and their names. * `getValues()` returns a `dict` where the keys are the enum names and the values are the enum constant values. * In the example below, the keys/values would be: `"Top" => 0`, `"Bottom" => 1`, etc. * `getNames()` returns a `dict`, but is flipped: the keys are the enum constant values and the values are the enum's named constants. * Following the same example, the keys/values would be: `0 => "Top"`, `1 => "Bottom"`, etc. * Because a `dict` *can not* contain duplicate keys, when you call `getNames()`—the static method that returns a `dict` and flips an enum's constant values *to* keys—there is a possiblity of creating a `dict` with duplicates, resulting in an `HH\InvariantException`. In this situation, one safe option for discarding duplicates (and keeping the most recent of every duplicate) is `Dict\flip`. ```Hack enum Position: int { Top = 0; Bottom = 1; Left = 2; Right = 3; Center = 4; } <<__EntryPoint>> function main(): void { $names = Position::getNames(); echo " Position::getNames() ---\n"; foreach ($names as $key => $value) { echo "\tkey >$key< has value >$value<\n"; } $values = Position::getValues(); echo "Position::getValues() ---\n"; foreach ($values as $key => $value) { echo "\tkey >$key< has value >$value<\n"; } Dict\flip(Position::getValues()); // safe flip of values as keys } ``` ### `assert()` / `coerce()` `assert($value)` checks if a value exists in an enum, and if it does, returns the value; if the value does not exist, throws an `UnexpectedValueException`. `coerce($value)` checks if a value exists in an enum, and if it does, returns the value; if the value does not exist, returns `null`. ```Hack enum Bits: int { B1 = 2; B2 = 4; B3 = 8; } <<__EntryPoint>> function main(): void { Bits::assert(2); // 2 Bits::assert(16); // UnexpectedValueException Bits::coerce(2); // 2 Bits::coerce(2.0); // null Bits::coerce(16); // null } ``` **Note:** Both library methods will, when no exact match is found, attempt to do a cast to the other `arraykey` type. If the cast is not reversible / lossless, or the resulting value is still not a member of the enum after the cast, the failure result occurs, where a failure for assert is throwing an `UnexpectedValueException` and a failure for `coerce` is returning null. ### `assertAll()` `assertAll($traversable)` calls `assert($value)` on every element of the traversable (e.g. [Hack Arrays](/hack/arrays-and-collections/hack-arrays)); if at least one value does not exist, throws an `UnexpectedValueException`. ```Hack enum Bits: int { B1 = 2; B2 = 4; B3 = 8; } <<__EntryPoint>> function main(): void { $all_values = vec[2, 4, 8]; $some_values = vec[2, 4, 16]; $no_values = vec[32, 64, 128]; Bits::assertAll($all_values); // vec[2, 4, 8] Bits::assertAll($some_values); // throws on 16, UnexpectedValueException Bits::assertAll($no_values); // throws on 32, UnexpectedValueException } ``` ### `isValid()` `isValid($value)` checks if a value exists in an enum, and if it does, returns `true`; if the value does not exist, it returns `false`. ```Hack enum Bits: int { B1 = 2; B2 = 4; B3 = 8; } <<__EntryPoint>> function main(): void { \var_dump(Bits::isValid(2)); \var_dump(Bits::isValid(2.0)); \var_dump(Bits::isValid("2.0")); \var_dump(Bits::isValid(8)); } ``` ## `is` / `as` The operators [`is`](/hack/expressions-and-operators/type-assertions#checking-types-with-is) and [`as`/`?as`](/hack/expressions-and-operators/type-assertions#enforcing-types-with-as-and-as) behave similarly, but not exactly, to `isValid()` (similar to `is`) and `assert()`/`coerce()` (similar to `as`/`?as`). For `is`/`as`/`?as` refinement, the operators validate that a value is a part of a given enum. **Caution:** These operators may perform implicit int/string coercion of enum values to preserve compatibility with `isValid()`. ```Hack enum MyEnum: int { FOO = 1; } <<__EntryPoint>> function main(): void { 1 is MyEnum; // true 1 as MyEnum; // 1 42 is MyEnum; // false 42 as MyEnum; // TypeAssertionException 'foo' is MyEnum; // false 'foo' as MyEnum; // TypeAssertionException '1' is MyEnum; // CAUTION - true '1' as MyEnum; // CAUTION - '1' } ``` ## Enum Inclusion You can define an enum to include all of the constants of another enum with the `use` keyword. In the following example, `enum` `F` contains all of the constants of `enum` `E1` and `enum` `E2`. ```Hack enum E1: int as int { A = 0; } enum E2: int as int { B = 1; } enum F: int { // same-line alternative: use E1, E2; use E1; use E2; C = 2; } ``` Enum Inclusion is subject to a few restrictions: * **Order**: All `use` statements must precede enum constant declarations. * **Uniqueness**: All constant names across all enums must be unique. * **Subtype Relation**: In the above example, `E1` and `E2` are not considered subtypes of `F`; that is, the Hack Typechecker rejects passing `E1::A` or `E2::B` to a function that expects an argument of type `F`. **Note:** Library functions like `getNames()` and `getValues()` perform a post-order traversal of all included enums.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/35-enum-class.md
In comparison to [enumerated types (enums)](/hack/built-in-types/enum), enum classes are not restricted to int and string values. ## Enum types v. Enum class Built-in enum types limit the base type of an enum to `arraykey` -- an integer or string -- or another enum. The base type of an _enum class_ can be any type: they are not required to be constant expressions and objects are valid values. However, with Generics, if an enum has type `T` as a base type, its enum values are bound to values whose type are a subtype of `T`. ## Declaring a new enum class Enum classes are syntactically different from [enum types](/hack/built-in-types/enum), as they require: * the `enum class` keyword rather than the `enum` keyword * that each value is annotated with its precise type: for example, `string` in `string s = ...` ### Example: Simple declarations ```Hack // Enum class where we allow any type enum class Random: mixed { int X = 42; string S = 'foo'; } // Enum class that mimics a normal enum (only allowing ints) enum class Ints: int { int A = 0; int B = 10; } ``` ### Example: Interface as a Base Type ```Hack file:hasname.hack // Some class definitions to make a more involved example interface IHasName { public function name(): string; } class HasName implements IHasName { public function __construct(private string $name)[] {} public function name(): string { return $this->name; } } class ConstName implements IHasName { public function name(): string { return "bar"; } } // enum class which base type is the IHasName interface: each enum value // can be any subtype of IHasName, here we see HasName and ConstName enum class Names: IHasName { HasName Hello = new HasName('hello'); HasName World = new HasName('world'); ConstName Bar = new ConstName(); } ``` ## Accessing values Once declared, enum values are accessed using the `::` operator: `Names::Hello`, `Names::Bar`, ... ### Control over enum values Using [coeffects](../contexts-and-capabilities/introduction.md), you can have control over which expressions are allowed as enum class constants. By default, all enum classes are under the `write_props` context. It is not possible to override this explicitly. ## Extending an Existing enum class (Inheritance) Enum classes can be composed together, as long as they implement the same base type: ```Hack file:extend.hack interface IBox {} class Box<T> implements IBox { public function __construct(public T $data)[] {} } enum class Boxes: IBox { Box<int> Age = new Box(42); Box<string> Color = new Box('red'); Box<int> Year = new Box(2021); } function get<T>(\HH\MemberOf<Boxes, Box<T>> $box): T { return $box->data; } function test0(): void { get(Boxes::Age); // ok, of type int, returns 42 get(Boxes::Color); // ok, of type string, returns 'red' get(Boxes::Year); // ok, of type int, returns 2021 } ``` ```Hack file:extend.hack enum class EBase: IBox { Box<int> Age = new Box(42); } enum class EExtend: IBox extends EBase { Box<string> Color = new Box('red'); } ``` In this example, `EExtend` inherits `Age` from `EBase`, which means that `EExtend::Age` is defined. As with ordinary class extension, using the `extends` keyword will create a subtype relation between the enums: `EExtend <: EBase`. Enum classes support multiple inheritance as long as there is no ambiguity in value names, and that each enum class uses the same base type: ```Hack file:extend.hack enum class E: IBox { Box<int> Age = new Box(42); } enum class F: IBox { Box<string> Name = new Box('foo'); } enum class X: IBox extends E, F { } // ok, no ambiguity enum class E0: IBox extends E { Box<int> Color = new Box(0); } enum class E1: IBox extends E { Box<string> Color = new Box('red'); } // enum class Y: IBox extends E0, E1 { } // type error, Y::Color is declared twice, in E0 and in E1 // only he name is use for ambiguity ``` ### Diamond shape scenarios Enum classes support diamond shaped inheritance as long as there is no ambiguity, like in: ```Hack file:extend.hack enum class DiamondBase: IBox { Box<int> Age = new Box(42); } enum class D1: IBox extends DiamondBase { Box<string> Name1 = new Box('foo'); } enum class D2: IBox extends DiamondBase { Box<string> Name2 = new Box('bar'); } enum class D3: IBox extends D1, D2 {} <<__EntryPoint>> function main(): void { echo D3::Age->data; } ``` Here there is no ambiguity: the constant `Age` is inherited from `DiamondBase`, and only from there. The `main` function will echo `42` as expected. If either `D1`, `D2` or `D3` tries to define a constant named `Age`, there will be an error. ### Control over inheritance Though the `final` keyword is not supported, Enum classes support the [`__Sealed`](../attributes/predefined-attributes#__sealed) attribute. Using `__Sealed`, you can specify which other enum classes, if any, are allowed to extend from your enum class. ## Abstract enum classes Like regular classes, enum classes come in two flavors: concrete and abstract. An abstract enum class can declare abstract members (constants), where only their type and name are provided. ```Hack file:hasname.hack // abstract enum class with some abstract members abstract enum class AbstractNames: IHasName { abstract HasName Foo; HasName Bar = new HasName('bar'); } ``` Abstract members do not support default values, and can't be accessed directly. They only map a name to a type. You must extend your abstract enum class into a concrete one with implementations of all abstract members to safely access members defined as abstract. ```Hack file:hasname.hack enum class ConcreteNames: IHasName extends AbstractNames { HasName Foo = new HasName('foo'); // one must provide all the abstract members // Bar is inherited from AbstractNames } ``` All concrete members are inherited, and can't be overriden. ## Defining a Function that expects an enum class When defining a function that expects an enum class value (e.g. `Foo::BAR`), you need to define the expected parameter appropriately with `HH\MemberOf` or you will run into errors. ```Hack error enum class Foo: string { string BAR = 'BAZ'; } function do_stuff(Foo $value): void { var_dump($value); } function main(): void { do_stuff(Foo::BAR); // expected Foo but got string } ``` However, if we instead define `do_stuff()` as receiving `HH\MemberOf<Foo, string>`, then we can use `Foo::Bar` with no issues. ```Hack enum class Foo: string { string BAR = 'BAZ'; } function do_stuff(HH\MemberOf<Foo, string> $value): void { var_dump($value); } function main(): void { do_stuff(Foo::BAR); // ok } ``` ## Accessing enum class types **An enum class type is more informative than a traditional built-in enum type.** Let's examine `enum E` v. `enum class EC`. ```Hack enum E: int { A = 42; } ``` ```Hack enum class EC: int { int A = 42; } ``` The built-in enum type of `E::A` is just `E`. All we know is that value `A` is declared within the enum: we know nothing of its underlying type. But if we look at the enum class `EC::A` its type is `HH\MemberOf<EC, int>`. We know that it's declared within the enum class `EC`, with type `int`. ## Declaring type constants in an enum class Like normal classes, enum classes can declare type constants. Abstract type constants are also supported: ```Hack interface IGet<+T> { public function get(): T; } class Box<T> implements IGet<T> { public function __construct(private T $data)[] {} public function get(): T { return $this->data; } public function set(T $data): void { $this->data = $data; } } abstract enum class E : IGet<mixed> { abstract const type T; abstract Box<this::T> A; Box<int> B = new Box(42); } enum class F : IGet<mixed> extends E { const type T = string; Box<this::T> A = new Box('zuck'); } ``` ## Full Example: Dependent Dictionary First, a couple of general Hack definitions: ```Hack file:dep_dict.hack function expect_string(string $str): void { echo 'expect_string called with: '.$str."\n"; } interface IKey { public function name(): string; } abstract class Key<T> implements IKey { public function __construct(private string $name)[] {} public function name(): string { return $this->name; } public abstract function coerceTo(mixed $data): T; } class IntKey extends Key<int> { public function coerceTo(mixed $data): int { return $data as int; } } class StringKey extends Key<string> { public function coerceTo(mixed $data): string { // random logic can be implemented here $s = $data as string; // let's make everything in caps return Str\capitalize($s); } } ``` Now let’s create the base definitions for our dictionary ```Hack file:dep_dict.hack enum class EKeys: IKey { // here are a default key, but this could be left empty Key<string> NAME = new StringKey('NAME'); } abstract class DictBase { // type of the keys, left abstract for now abstract const type TKeys as EKeys; // actual data storage private dict<string, mixed> $raw_data = dict[]; // generic code written once which enforces type safety public function get<T>(\HH\MemberOf<this::TKeys, Key<T>> $key): ?T { $name = $key->name(); $raw_data = idx($this->raw_data, $name); // key might not be set if ($raw_data is nonnull) { $data = $key->coerceTo($raw_data); return $data; } return null; } public function set<T>(\HH\MemberOf<this::TKeys, Key<T>> $key, T $data): void { $name = $key->name(); $this->raw_data[$name] = $data; } } ``` Now one just need to provide a set of keys and extends `DictBase`: ```Hack file:dep_dict.hack class Foo { /* user code in here */ } class MyKeyType extends Key<Foo> { public function coerceTo(mixed $data): Foo { // user code validation return $data as Foo; } } enum class MyKeys: IKey extends EKeys { Key<int> AGE = new IntKey('AGE'); MyKeyType BLI = new MyKeyType('BLI'); } class MyDict extends DictBase { const type TKeys = MyKeys; } ``` ```Hack file:dep_dict.hack <<__EntryPoint>> function main(): void { $d = new MyDict(); $d->set(MyKeys::NAME, 'tony'); $d->set(MyKeys::BLI, new Foo()); // $d->set(MyKeys::AGE, new Foo()); // type error expect_string($d->get(MyKeys::NAME) as nonnull); } ```
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/36-enum-class-label.md
## Values v. Bindings With [enum types](/hack/built-in-types/enum) and [enum classes](/hack/built-in-types/enum-class), most of the focus is given to their values. Expressions like `E::A` denote the value of `A` in `E`, but the fact that `A` was used to access it is lost. ```Hack enum E: int { A = 42; B = 42; } function f(E $value): void { switch($value) { case E::A: echo "A "; break; case E::B: echo "B "; break; } echo $value . "\n"; } ``` In this example, both `f(E::A)` and `f(E::B)` will echo `A 42` because `E::A` and `E::B` are effectively the value `42` and nothing more. ## Enum Class Labels Sometimes, the binding that was used to access a value from an enumeration is as important as the value itself. We might want to know that `A` was used to access `E::A`. Enum types provides a partial solution to this with the `getNames` static method, but it is only safe to call if all the values of the enumeration are distinct. Enum classes provides a way to do this by using the newly introduced *Enum Class Label* expressions. For each value defined in an enum class, a corresponding label is defined. A label is a handle to access the related value. Think of it as an indirect access. Consider the following example: ```Hack file:label.hack // We are using int here for readability but it works for any type enum class E: int { int A = 42; int B = 42; } ``` This enum class defines two constants: - `E::A` of type `HH\MemberOf<E, int>` - `E::B` of type `HH\MemberOf<E, int>` The main addition of labels is a new **opaque** type: `HH\EnumClasslabel`. Let's first recall its full definition: ```Hack newtype Label<-TEnumClass, TType> = mixed; ``` This type has two generic arguments which are the same as `HH\MemberOf`: - the first one is the enum class where the label is defined - the second one is the data type indexed by the label As an example, `HH\EnumClass\Label<E, int>` means that the label is from the enum class `E` and points to a value of type `int`. Let us go back to our enum class `E`. Labels add more definitions to the mix: - `E#A: HH\EnumClass\Label<E, int>` is the label to access `E::A` - `E#B: HH\EnumClass\Label<E, int>` is the label to access `E::B` - `E::nameOf` is a static method expecting a label and returning its string representation: `E::nameOf(E#A) === "A"` - `E::valueOf` is a static method expecting a label and returning its value: `E::valueOf(E#A) === E::A` So we can rewrite the earlier example in a more resilient way: ```Hack file:label.hack function full_print(\HH\EnumClass\Label<E, int> $label): void { echo E::nameOf($label) . " "; echo E::valueOf($label) . "\n"; } function partial_print(\HH\MemberOf<E, int> $value): void { echo $value . "\n"; } ``` Now, `full_print(E#A)` will echo `A 42` and `full_print(E#B)` will echo `B 42`. ## Full v. Short Labels We refer to labels like `E#A` as *fully qualified* labels: the programmer wrote the full enum class name. However there are some situations where Hack can infer the class name; for example, the previous calls could be written as `full_print(#A)` and `full_print(#B)`, leaving `E` implicit. This is only allowed when there is enough type information to infer the right enum class name. For example, `$x = #A` is not allowed and will result in a type error. ## Equality testing Enum class labels can be tested for equality using the `===` operator or a switch statement: ```Hack file:label.hack function test_eq(\HH\EnumClass\Label<E, int> $label): void { if ($label === E#A) { echo "label is A\n"; } switch ($label) { case E#A: break; case E#B: break; } } ``` Because the runtime doesn’t have all the typing information available, these tests only check the name component of a label. It means that for any two enum classes `E` and `F`, `E#A === F#A` will be true despite being from different enum classes. Also the support type (int in the case of the enum class `E`) is not taken into account either. ```Hack class Foo {} enum class F: Foo { Foo A = new Foo(); } // E#A === E#B is false // E#A === F#A is true ``` ## Enum class labels and abstract enum classes Abstract enum classes support labels like any other enum class. The main difference is that an abstract enum class only provides the `nameOf` static method. Since some of its members may be abstracted away, abstract enum classes do no provide the `valueOf()` or `getValues()` static methods. ## Known corner cases ### The `#` character is no longer a single-line comment This feature relies on the fact that Hack and HHVM no longer consider the character `#` as a single-line comment. Please use `//` for such purpose. ### Labels and values cannot be exchanged If a method is expecting a label, one cannot pass in a value, and vice versa: `full_print(E::A)` will result in a type error and so will `partial_print(E#A)`. ### `MemberOf` is covariant, `Label` is invariant Let’s recall the definition of `HH\MemberOf` and `HH\EnumClass\Label` along with some basic definitions: ```Hack newtype MemberOf<-TEnumClass, +TType> as TType = TType; newtype Label<-TEnumClass, TType> = mixed; class A {} class B extends A {} enum class G: A { A X = new A(); B Y = new B(); } ``` Firstly, `HH\MemberOf` has a `as TType` constraint. It means that since `G::X` is of type `HH\MemberOf<G, A>`, it is also of type `A`. For the same reasons, `G::Y` is of type `HH\MemberOf<G, B>` and `B`. Secondly, `HH\MemberOf` is covariant in `TType`. Since `B extends A`, it means that `G::Y` is also of type `HH\MemberOf<G, A>`. And because of all of that, `G::Y` is also of type `A`. Enum class values behave just like the underlying data they are set to. On the other hand, `HH\EnumClass\Label` is invariant in `TType`. It means that while `G#Y` is of type `HH\EnumClass\Label<G, B>`, it is not of type `HH\EnumClass\Label<G, A>`. Labels are opaque handles to access data; you can think about them as maps from names to types. Their typing has to be more strict, especially if we want to be able to extend this concept to other parts of a class (reflection like access to methods, properties, …). To make sure these possible extensions remain possible, we enforce a stricter typing for labels than for values.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/49-this.md
The type name `this` refers to *the current class type at run time*. As such, it can only be used from within a class, an interface, or a trait. (The type name `this` should not be confused with [`$this`](../source-code-fundamentals/names.md), which refers to *the current instance*, whose type is `this`.) For example: ```Hack interface I1 { abstract const type T1 as arraykey; public function get_ID(): this::T1; } ``` Here, the function `get_ID` returns a value whose type is based on the type of the class that implements this interface type. Strictly speaking, `this` is *not* a new type name, just an alias for an existing one.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/55-classname.md
For the most part, we deal with class types directly via their names. For example: ```Hack no-extract class Employee { // ... } $emp = new Employee(); ``` However, in some applications, it is useful to be able to abstract a class' name rather than to hard-code it. Consider the following: ```Hack file:employee.hack <<__ConsistentConstruct>> class Employee { // ... } function f(classname<Employee> $clsname): void { $w = new $clsname(); // create an object whose type is passed in } ``` This function can be called with the name of the class `Employee` or any of its subclasses. ```Hack no-extract class Intern extends Employee { // ... } function demo(): void { f(Employee::class); // will call: new Employee(); f(Intern::class); // will call: new Intern(); f(Vector::class); // typechecker error! } ``` In Hack code, the class names must be specified using "`::class` literals" (`SomeClassName::class`). At runtime, these are regular strings (`SomeClassName::class === 'SomeClassName'`). The value of an expression of a classname type can be converted implicitly or explicitly to `string`.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/56-darray-varray-runtime-options.md
As of [HHVM 4.103](https://hhvm.com/blog/2021/03/31/hhvm-4.103.html), `darray` / `varray` are aliased to `dict` / `vec` respectively. Use [Hack arrays](/hack/arrays-and-collections/hack-arrays). ## WARNING WARNING WARNING _These runtime options are a migrational feature. This means that they come and go when new hhvm versions are released. Before relying on them, it is recommended to run the given example code. If this does not raise a "Hack Arr Compat Notice" this option is not available in your version of HHVM._ If you notice that an option doesn't apply anymore and you are running a very modern version of HHVM, please open an issue or pull request against this repository. We'll mark the EOL date of that given runtime option in the documentation. We thank you in advance. The [runtime options](arrays.md#php-arrays-array-varray-and-darray__runtime-options) were briefly introduced in the article on [arrays](arrays.md). This article builds upon the information given there. You can get a list of the runtime options that your current hhvm recognizes from this script. This relies on the settings being in your `server.ini`. The output will look something like this. ```hack function get_all_runtime_options( ): dict<string, shape( 'global_value' => string, 'local_value' => string, 'access' => string, )> { return \ini_get_all() |> Dict\filter_keys($$, $name ==> Str\contains($name, 'hack_arr')); } <<__EntryPoint>> async function main_async(): Awaitable<void> { foreach (get_all_runtime_options() as $name => $values) { echo Str\format( "%s> global_value(%s), local_value(%s), access(%s)\n", Str\pad_right($name, 60, '-'), $values['global_value'], $values['local_value'], $values['access'], ); } } ``` *Example output (HHVM 4.115)* ``` hhvm.hack_arr_is_shape_tuple_notices------------------------> global_value(), local_value(), access(4) hhvm.hack_arr_dv_arrs---------------------------------------> global_value(1), local_value(1), access(4) hhvm.hack_arr_dv_arr_var_export-----------------------------> global_value(), local_value(), access(4) hhvm.hack_arr_compat_cast_marked_array_notices--------------> global_value(), local_value(), access(4) hhvm.hack_arr_compat_compact_serialize_notices--------------> global_value(), local_value(), access(4) hhvm.hack_arr_compat_serialize_notices----------------------> global_value(), local_value(), access(4) hhvm.hack_arr_compat_is_vec_dict_notices--------------------> global_value(), local_value(), access(4) hhvm.hack_arr_compat_intish_cast_notices--------------------> global_value(), local_value(), access(4) hhvm.hack_arr_compat_fb_serialize_hack_arrays_notices-------> global_value(), local_value(), access(4) hhvm.hack_arr_compat_check_compare--------------------------> global_value(), local_value(), access(4) hhvm.hack_arr_compat_notices--------------------------------> global_value(), local_value(), access(4) ``` An important note: These settings will not work when you set them at runtime using ini_set(). You must set these in your configuration file or pass them in using the `-dsettinghere=valuehere` command line argument when invoking your script from the command line. ## Check implicit varray append Fullname: hhvm.hack_arr_compat_check_implicit_varray_append **WARNING: This option was removed in HHVM 4.64. It is now always a fatal error.** Before HHVM 4.64, this setting will raise a notice under the following condition. If it does not raise a warning, this option is not available in your version of hhvm. ```hack no-extract <<__EntryPoint>> async function main_async(): Awaitable<void> { using _Private\print_short_errors(); $varray = varray[ 'HHVM', 'HACK', ]; $varray[2] = <<<EOF Writing to the first unused key of a varray. Varray's behave differently here than vecs. EOF; } ``` *Output (before HHVM 4.64)* ``` E_NOTICE "Hack Array Compat: Implicit append to varray" in file "hack_arr_compat_check_implicit_varray_append.php" at line 19 ``` **(fatal error in HHVM 4.64 or newer)** A `vec<_>` does not support implicitly appending. You can only append using an empty subscript operator `$x[] = ''` and update using a keyed subscript operator `$x[2] = ''`. The runtime will throw when you use the updating syntax in order to append. `'OutOfBoundsException' with message 'Out of bounds vec access: invalid index 2'`. A `varray<_>` will, before HHVM 4.64, accept you implicitly appending a key. It will remain a `varray<_>`. This is the only case where writing to a non existent index in a `varray<_>` will not cause the `varray<_>` to escalate to a `darray<_, _>`. More information about array escalation can be found below. ## Check varray promote Fullname: hhvm.hack_arr_compat_check_varray_promote **WARNING: This option was removed in HHVM 4.64. It is now always a fatal error.** Before HHVM 4.64, this setting will raise a notice under the following condition. If it does not raise a warning, this option is not available in your version of hhvm. ```hack no-extract <<__EntryPoint>> async function main_async(): Awaitable<void> { using _Private\print_short_errors(); $varray = varray[ 'HHVM', 'HACK', ]; $varray[3] = <<<EOF Writing to a key that is not already in use nor the first unused key. A vec<_> would throw an exception here. EOF; $varray = varray[ 'HHVM', 'HACK', ]; /*HH_IGNORE_ERROR[4135] This is banned in strict mode, but needs to be illustated.*/ unset($varray[0]); // Using unset on an index that is not the greatest index. $varray = varray[ 'HHVM', 'HACK', ]; /*HH_IGNORE_ERROR[4324] This is banned in Hack, but needs to be illustated.*/ $varray['string'] = <<<EOF Writing to a string key in a will escalate it to a darray<_, _>. A vec would throw an exception here. EOF; } ``` *Output (before HHVM 4.64)* ``` E_NOTICE "Hack Array Compat: varray promoting to darray: out of bounds key 3" in file "hack_arr_compat_check_varray_promote.php" at line 19 E_NOTICE "Hack Array Compat: varray promoting to darray: removing key" in file "hack_arr_compat_check_varray_promote.php" at line 30 E_NOTICE "Hack Array Compat: varray promoting to darray: invalid key: expected int, got string" in file "hack_arr_compat_check_varray_promote.php" at line 39 ``` **(fatal error in HHVM 4.64 or newer)** These situations are sadly very common in grandfathered PHP code. The first situation, writing to a key out of bounds, is not permitted on a `vec<_>`. It throws and `OutOfBoundsException`. A `vec<_>` will always maintain the keys 0, 1, 2, ... and will therefore have to refuse to create the new index on the fly. There are two distinct intents that the programmer may have had when writing this code. - The keys are actually useful data. - The keys are meant to be indexes 0, 1, 2 and the programmer assumed that he or she was writing in-bounds. The first case is usually pretty easy to fix. If it looks like the keys are userids, timestamps, or alike, `varray<_>` isn't the right type. Migrate the code to use `darray<_, current_value_type>`. You'll have to figure out the keytype from context. The second case is far less easy to give a clear fix for. - Chances are that there is a nearby `C\count()` doing a bounds check that might be defective. - Is the array being filled out of order? Are all the indexes between 0 and the greatest index used after this procedure? You might be tempted to make the fill happen in order, but that will change the order that the elements are iterated over in a foreach. The second situation, calling unset on an element of a `varray<_>`, can have multiple intends too. - If the T is a nullable type, the programmer might have meant to write `null` to the index. This is more common in code written before hhvm4. - The programmer does not care about the keys. The array is merely a meant to be used as a `KeyedContainer<not_important, T>` and he or she just meant to remove the value from the `KeyedContainer<_, _>`. - The programmer intended to unset the last index. The first case is most likely a confusion caused by a removed behavior of all legacy arrays. Before hhvm 4 accessing an key that wasn't present would log a notice and return null. An unset on an array would under these circumstances act very similarly to explicitly setting to value to null. This is however quite tricky to do right if this array is being passed around the program a lot. An unset key is actually removed from the array. This means that `C\contains_key()` will return `false`, `idx()` will return its default argument, and `??` will evaluate to the RHS. However, explicitly setting the value to `null` does not remove the key from the array. This means that `C\contains_key()` returns `true`, `idx()` will return the `null`, but `??` will be unaffected. The second usecase is not met by Hack arrays. There is no `Container<_>` type that allows you to append to the end and remove things by index (except for `keyset<_>`, but that has a constraint value type). You can however emulate this behavior using a `varray<_>` or `vec<_>`. Removing the first key can be done using `Vec\drop($x, 1)`. Removing the last key can be done using `\array_pop()` <span data-nosnippet class="fbonly apiAlias">`C\fb\pop_back`</span>. Removing a key from the middle can be done with the slightly unwieldy `Vec\filter_with_key($x, ($key, $_) ==> $key === 1)`. All of these will rekey the array. Any values after the key will be shifted down. This does however have a computational complexity of `O(n)`. If you need to remove a lot of keys from the middle that are next to each other, use `Vec\slice()` to save some resources. If you need to remove a ton of arbitrary keys, at different points of your function it might be better to `dict($x)`, unset on the `dict<_, _>` and rekey it back to a `varray<_>` using `varray()` or `array_values()` depending on your hhvm version. The third usecase used to be valid Hack. Unsetting the last index of a `varray<_>` or `vec<_>` was allowed and acted like an `\array_pop()`<span data-nosnippet class="fbonly apiAlias">`C\fb\pop_back`</span>. This will currently not generate a warning, but it is unclear to me if this will continue to be allowed. The typechecker already raises a typeerror when you use unset on a non dictionary/hashmap like array type. The third situation, writing to a string key, is always a mistake. If this is a string literal, the actual type is most likely `darray<_, _>`. If this is an intergral string coming from an untyped function, it is worth investigating casting the value to an int. ## Runtime typetests of shapes and tuples In HHVM 4.102 or older, shapes and tuples were implemented with `darray` and `varray`. In HHVM 4.103 and newer, they are `dict` and `vec`; this means that the following checks would fail before HHVM 4.103, but now pass&mdash;for this reason, in HHVM 4.102 or older, the `hhvm.hack_arr_is_shape_tuple_notices` runtime option could be used to raise notices for these type tests: ```hack $_ = dict[] is shape(); $_ = vec[42] is /*tuple*/(int); ``` *Output (before HHVM 4.103)* ``` Notice: Hack Array Compat: dict is shape in /home/example/hack_arr_is_shape_tuple_notices.hack on line 10 Notice: Hack Array Compat: vec is tuple in /home/example/hack_arr_is_shape_tuple_notices.hack on line 11 ``` ## Check array key cast Fullname: hhvm.hack_arr_compat_check_array_key_cast **WARNING: This option was removed in HHVM 4.66. It is now always a fatal error.** Before HHVM 4.66, this setting will raise a notice under the following condition. If it does not raise a warning, this option is not available in your version of hhvm. ```hack no-extract <<__EntryPoint>> async function main_async(): Awaitable<void> { using _Private\print_short_errors(); $varray = varray[]; /*HH_IGNORE_ERROR[4324]*/ $varray[1.1] = 'A float?!?'; /*HH_IGNORE_ERROR[4324]*/ $varray[true] = 'A bool?!?'; /*HH_IGNORE_ERROR[4324]*/ $varray[null] = 'null?!?'; $darray = darray[]; /*HH_IGNORE_ERROR[4371]*/ $darray[1.1] = 'A float?!?'; /*HH_IGNORE_ERROR[4371]*/ $darray[true] = 'A bool?!?'; /*HH_IGNORE_ERROR[4371]*/ $darray[null] = 'null?!?'; } ``` *Output (before HHVM 4.66)* ``` E_NOTICE "Hack Array Compat: Implicit conversion of double to array key" in file "hack_arr_compat_check_array_key_cast.php" at line 17 E_NOTICE "Hack Array Compat: Implicit conversion of bool to array key" in file "hack_arr_compat_check_array_key_cast.php" at line 19 E_NOTICE "Hack Array Compat: Implicit conversion of null to array key" in file "hack_arr_compat_check_array_key_cast.php" at line 21 E_NOTICE "Hack Array Compat: Implicit conversion of double to array key" in file "hack_arr_compat_check_array_key_cast.php" at line 26 E_NOTICE "Hack Array Compat: Implicit conversion of bool to array key" in file "hack_arr_compat_check_array_key_cast.php" at line 28 E_NOTICE "Hack Array Compat: Implicit conversion of null to array key" in file "hack_arr_compat_check_array_key_cast.php" at line 30 ``` **(fatal error in HHVM 4.66 or newer)** A `vec<_>` and a `dict<_, _>` only allow `arraykey` keys. Because of legacy, the (d/v)array family needed to support non arraykey keys being set and read from. When you set `$varray[true] = 4;`, before HHVM 4.66, hhvm will cast your `true` to a valid arraykey `1`. The rules of casting were as follows: - floats are cast to ints using an `(int)` cast. - `true` becomes 1 and `false` becomes 0. - `null` becomes empty string. Deciding on the best course of action relies on context. If the value is coming from an untyped function, it is worth investigating if the returned type might have been a mistake. Keep in mind that a function that reaches the closing `}` before hitting a `return` statement returns `null`. If you want this error to go away, but you'd like to keep the current behavior (not recommended) you can use `HH\array_key_cast()`.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/58-resources.md
A resource is a descriptor to some sort of external entity. (Examples include files, databases, and sockets.) Resources are only created or consumed by the implementation; they are never created or consumed by Hack code. Each distinct resource has a unique ID of some unspecified form. When scripts execute in a mode having a command-line interface, the following resources that correspond to file streams are automatically opened at program start-up: - `HH\\stdin()` or `HH\\try_stdin()`, which map to standard input - `HH\\stdout()` or `HH\\try_stdout()`, which map to standard output - `HH\\stderr()` or `HH\\try_stderr()`, which map to standard error These streams have some unspecified type, which behaves like a subtype of type `resource`. The `try` variants return null when executed without a command-line interface, while the non-`try` functions throw an exception. **Resources are a carryover from PHP, and their use is discouraged in Hack code.**
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/61-null.md
The `null` type has only one possible value, the value `null`. You can use the `null` type when refining with `is`. ```Hack function number_or_default(?int $x): int { if ($x is null) { return 42; } else { return $x; } } ``` See [nullable types](../types/nullable-types.md) for a discussion of `?T` types. The `null` type is also useful when writing generics. Suppose you want to define a generic interface with a 1-argument function, but some instances don't need an argument. ```Hack file:traversefrom.hack // A toy interface that allows you to iterate over something, // setting a start point. interface TraverseFrom<Tv, Ti> { public function startAt(Ti $_): Traversable<Tv>; } ``` You can use `null` to define a class implementing this interface, making it clear that you don't care about the argument to `startAt`. ```Hack file:traversefrom.hack class TraverseIntsFromStart implements TraverseFrom<int, null> { public function __construct(private vec<int> $items) {} public function startAt(null $_): Traversable<int> { return $this->items; } } ```
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/70-mixed.md
The `mixed` type represents any value at all in Hack. For example, the following function can be passed anything. ```Hack no-extract function takes_anything(mixed $m): void {} function call_it(): void { takes_anything("foo"); takes_anything(42); takes_anything(new MyClass()); } ``` `mixed` is equivalent to `?nonnull`. `nonnull` represents any value except `null`. We recommend you avoid using `mixed` whenever you can use a more specific type.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/71-dynamic.md
**This type is intended to help with code being transitioned from untyped mode to strict mode.** Although `dynamic` can be used as the type of a class constant or property, or a function return type, its primary use is as a parameter type. This special type is used to help capture dynamism in the existing codebase in typed code, in a more manageable manner than `mixed`. With `dynamic`, the presence of dynamism in a function is local to the function, and dynamic behaviors cannot leak into code that does not know about it. Consider the following: ```Hack function f(dynamic $x) : void { $n = $x + 5; // $n is a num $s = $x . "hello!"; // $s is a string $y = $x->anyMethod(); // $y is dynamic } ``` A value of type `dynamic` can be used in most local operations: like untyped expressions, we can treat it like a `num` and add it, or a `string` and concatenate it, or call any method on it, as shown above. When using a dynamic type in an operation, the type checker infers the best possible type with the information it has. For example, using a dynamic in an arithmetic operation like + or - result in a `num`, using a dynamic in a string operation result in a `string`, but calling a method on a dynamic, results in another dynamic. `dynamic` allows calls, property access, and bracket access without a null-check, but it can throw if the runtime value is null. # Coercion The `dynamic` type sits outside the normal type hierarchy. It is a supertype only of the bottom type `nothing` and a subtype only of the top type `mixed`. The type interfaces with other types via coercion (`~>` in the examples). All types coerce to `dynamic`, which allows callers to pass any type into a function that expects dynamic. Also, any type coerces to its supertypes. Coercion points include function calls, return statements, and property assignment. ```Hack function f(dynamic $d): void {} function g(arraykey $a): void {} function caller(int $i): void { f($i); // int ~> dynamic g($i); // int ~> arraykey by subtyping } ``` The runtime enforces a set of types by throwing `TypeHintViolationException` when an incorrect type is provided. This set includes - primitive types - classes without generics, or with reified generics - reified generics with the `<<__Enforceable>>` attribute - transparent type aliases to enforceable types Hack approximates this runtime behavior by allowing values of type `dynamic` to coerce to enforceable types at coercion points. ```Hack error function enforced(int $i): void {} function notEnforced(shape('a' => int) $s): void {} function caller(dynamic $d): void { enforced($d); // dynamic ~> int, runtime will throw if $d is not an int notEnforced($d); // Hack error, dynamic ~/> shape('a' => int), runtime will not throw if $d is not a shape } ```.hhconfig coercion_from_dynamic = true ``` Unions with dynamic are also allowed to coerce to enforceable types provided that each element of the union can coerce. ```hack error function expect_int(int $i): void {} function expect_string(string $s): void {} function choose(bool $b, dynamic $d, int $i): void { if ($b) { $x = $d; } else { $x = $i; } expect_int($x); // (dynamic | int) ~> int // dynamic ~> int because int is enforced // int ~> int because int <: int expect_string($x); // Hack error, (dynamic | int) ~/> string because int ~/> string } ```.hhconfig coercion_from_dynamic = true coercion_from_union = true complex_coercion = true ``` Notably, unlike subtyping, coercion is *not* transitive, meaning that `int ~> dynamic` and `dynamic ~> string` does not imply that `int ~> string`.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/73-noreturn.md
A function that never returns a value can be annotated with the `noreturn` type. A `noreturn` function either loops forever, throws an an error, or calls another `noreturn` function. ```Hack function something_went_wrong(): noreturn { throw new Exception('something went wrong'); } ``` `invariant_violation` is an example of a library function with a `noreturn` type. `noreturn` informs the typesystem that code execution can not continue past a certain line. In combination with a conditional, you can refine variables, since the typesystem will take note. This is actually how [invariant](../expressions-and-operators/invariant) is [implemented](/hack/reference/function/HH.invariant). ```Hack <<__EntryPoint>> async function main_async(): Awaitable<void> { $nullable_int = '_' ? 0 : null; if (!($nullable_int is nonnull)) { invariant_violation('$nullable_int must not be null'); } // If we didn't fall into the if above, $nullable_int must be an int. takes_int($nullable_int); } function takes_int(int $int): void { echo $int; } ``` If you want to, you can also use [nothing](./nothing) instead. This allows you use the return value of the function. This makes it more explicit to the reader of your code that you are depending on the fact that this function influences typechecking. ```Hack function i_am_a_noreturn_function(): noreturn { throw new Exception('stop right here'); } function i_return_nothing(): nothing { i_am_a_noreturn_function(); } const ?int NULLABLE_INT = 0; async function main_async(): Awaitable<void> { example_noreturn(); example_nothing(); } function example_noreturn(): int { $nullable_int = NULLABLE_INT; if ($nullable_int is null) { i_am_a_noreturn_function(); } return $nullable_int; } function example_nothing(): int { $nullable_int = NULLABLE_INT; if ($nullable_int is null) { return i_return_nothing(); } return $nullable_int; } ``` In this example the `noreturn` function is named very plain, so you can understand that this refines. However in the `nothing` version you don't need to know the signature of `i_return_nothing()` to understand that `$nullable_int` will not be null after the if, since you can see the `return`.
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/74-nothing.md
The type `nothing` is the bottom type in the Hack typesystem. This means that there is no way to create a value of the type `nothing`. `nothing` only exists in the typesystem, not in the runtime. The concept of a bottom type is quite difficult to grasp, so I'll first compare it to the supertype of everything `mixed`. `mixed` is the most general thing you can imagine within the hack typesystem. Everything "extends" `mixed` if you will. `nothing` is the exact opposite of that. Let's work out the hierarchy of scalar types. Forget about nullable types and `dynamic` for the moment, they would make this example far more complex without adding much value. - `mixed` is at the top. Everything is a subtype of `mixed`, either directly (types that have no other supertypes) or indirectly (via their supertypes). - `num` is a subtype of `mixed`. - `arraykey` is a subtype of `mixed`. - `bool` is a subtype of `mixed`. - `int` is a subtype of `num` and `arraykey`. - `float` is a subtype of `num`. - `string` is a subtype of `arraykey`. - `nothing` is a subtype of `int`, `float`, `string`, and `bool`. The important thing to note here is that `nothing` is never between two types. `nothing` only shows up right below a type with no other subtypes. ## Usages When defining a function that will never return (it either throws, loops forever, or terminates the request) you can use `nothing` for the return type. This gives more information to the caller than `void` and is more flexible than [noreturn](./noreturn). `nothing` can be used in expressions (like `nullable T ?? nothing`) and it will typecheck "as if it wasn't there", since `(T | nothing)` is _just_ `T`. `nothing` can be used to create a `throw` expression in this way. ```Hack function throw_as_an_expression(\Throwable $t): nothing { throw $t; } function returns_an_int(?int $nullable_int): int { // You can not use a `throw` statement in an expression bodied lambda. // You need to add curly braces to allow a `throw` statement. $throwing_lambda = () ==> { throw new \Exception(); }; $throwing_expr_lambda = () ==> throw_as_an_expression(new \Exception()); // You can't write a statement on the RHS of an operator, because it operates on expressions. // The type of the `??` operator is `(nothing | int)`, which simplifies to `int`, // so this return statement is valid. return $nullable_int ?? throw_as_an_expression(new \Exception()); } <<__EntryPoint>> async function main_async(): Awaitable<void> { echo returns_an_int(1); } ``` <hr> When writing a new bit of functionality, you may need to pass a value to a function you can't produce without a lot of work. `nothing` can be used as a placeholder value in place of any type without causing type errors. The typechecker will continue checking the rest of your program and the runtime will throw if this code path gets executed. I have called this function `undefined`, as an homage to Haskell [undefined](https://wiki.haskell.org/Undefined). ```Hack file:undefined.hack type undefined = nothing; function undefined(): undefined { throw new Exception('NOT IMPLEMENTED: `undefined` cannot be produced.'); } ``` And here is how to use it ```Hack file:undefined.hack interface MyInterface { public function isAmazed(): bool; } function do_something(MyInterface $my_interface): bool { return $my_interface->isAmazed(); } <<__EntryPoint>> async function main_async(): Awaitable<void> { $my_interface = undefined(); // We won't ever reach this line, since `undefined()` will halt the program by throwing. // We can't produce a MyInterface just yet, since there are no classes which implement it. // `undefined` is a placeholder for now. // We can continue writing our business logic and come back to this later. if (do_something($my_interface)) { // Write the body first, worry about the condition later. } } ``` You could make your staging environment remove the file which declared the `undefined()` function. That way you'll get a typechecker error when you accidentally push code that has these placeholders in it. This prevents you from accidentally deploying unfinished code to production. <hr> When making a new / empty `Container<T>`, Hack will infer its type to be `Container<nothing>`. It is not that there are actual value of type `nothing` in the `Container<T>`, it is just that this is a very nice way of modeling empty `Container<T>`s. Should you be able to pass an empty vec where a `vec<string>` is expected? Yes, there is no element inside that is not a `string`, so that should be fine. You can even pass the same vec into a function that takes a `vec<bool>` since there are no elements that are not of type `bool`. What are you allowed to do with the `$nothing` of this foreach? Well, you can do anything to it. Since nothing is a subtype of everything, you can pass it to any method and do all the things you want to. ```Hack function takes_vec_of_strings(vec<string> $_): void {} function takes_vec_of_bools(vec<bool> $_): void {} <<__EntryPoint>> async function main_async(): Awaitable<void> { $empty_vec = vec[]; takes_vec_of_bools($empty_vec); takes_vec_of_strings($empty_vec); foreach ($empty_vec as $nothing) { $nothing->whatever(); takes_vec_of_strings($nothing); } } ``` <hr> To make an interface that requires that you implement a method, without saying anything about its types. This does still make a requirement about the amount of parameters that are required parameters. ```Hack interface DontForgetToImplementShipIt { public function shipIt(nothing $_): mixed; } abstract class Software implements DontForgetToImplementShipIt { } class HHVM extends Software { public function shipIt(string $version): string { return 'Shipping HHVM version '.$version.'!'; } } class HSL extends Software { private function __construct(public bool $has_new_functions) { } public function shipIt(bool $has_new_functions): HSL { return new HSL($has_new_functions); } } class HHAST extends Software { public function shipIt(Container<string> $linters): void { foreach ($linters as $linter) { invariant( Str\ends_with($linter, 'Linter'), 'Linter %s does not have a name that ends in "Linter"!', $linter, ); } } } ``` It is important to note that `Software::shipIt()` is not directly callable without knowing what subtype of `Software` you have. <hr> Contravariant generic types can use `nothing` to allow all values to be passed. This acts in a similar way that `mixed` acts of covariant generics, such as `vec<mixed>`. ```Hack final class MyClass<-T> { public function consume(T $value): void {} public function someOtherMethod(): void {} } // We don't use the `T` from `->consume(T): void` in the function, // so we can use `nothing` for the generic and accept any and all MyClass instances. function some_function(MyClass<nothing> $a, MyClass<nothing> $b): void { if ($a !== $b) { $b->someOtherMethod(); echo "different\n"; } } <<__EntryPoint>> async function main_async(): Awaitable<void> { $my_class_int = new MyClass<int>(); $my_class_string = new MyClass<string>(); some_function($my_class_int, $my_class_string); } ```
Markdown
hhvm/hphp/hack/manual/hack/12-generics/01-introduction.md
Certain types (classes, interfaces, and traits) and their methods can be *parameterized*; that is, their declarations can have one or more placeholder names---called *type parameters*---that are associated with types via *type arguments* when a class is instantiated, or a method is called. A type or method having such placeholder names is called a *generic type* or *generic method*, respectively. Top-level functions can also be parameterized giving rise to *generic functions*. Generics allow programmers to write a class or method with the ability to be parameterized to any set of types, all while preserving type safety. Consider the following example in which `VecStack` is a generic class having one type parameter, `T`: ```Hack file:stack.hack use namespace HH\Lib\{C, Vec}; interface StackLike<T> { public function isEmpty(): bool; public function push(T $element): void; public function pop(): T; } class StackUnderflowException extends \Exception {} class VecStack<T> implements StackLike<T> { private int $stackPtr; public function __construct(private vec<T> $elements = vec[]) { $this->stackPtr = C\count($elements) - 1; } public function isEmpty(): bool { return $this->stackPtr === -1; } public function push(T $element): void { $this->stackPtr++; if (C\count($this->elements) === $this->stackPtr) { $this->elements[] = $element; } else { $this->elements[$this->stackPtr] = $element; } } public function pop(): T { if ($this->isEmpty()) { throw new StackUnderflowException(); } $element = $this->elements[$this->stackPtr]; $this->elements[$this->stackPtr] = $this->elements[0]; $this->stackPtr--; return $element; } } ``` As shown, the type parameter `T` is used in the declaration of the instance property `$elements`, as a parameter for `push()`, and as a return type for `pop()`. ```Hack file:stack.hack function useIntStack(StackLike<int> $stInt): void { $stInt->push(10); $stInt->push(20); echo 'pop => '.$stInt->pop()."\n"; // 20 $stInt->push(30); echo 'pop => '.$stInt->pop()."\n"; // 30 echo 'pop => '.$stInt->pop()."\n"; // 10 // $stInt->push(10.5); // rejected as not being type-safe } ``` The line commented-out, attempts to call push with a non-`int` argument. This is rejected, because `$stInt` is a stack of `int`. The *arity* of a generic type or method is the number of type parameters declared for that type or method. As such, class `Stack` has arity 1. Here is an example of a generic function, `swap`, having one type parameter, `T`: ```Hack function swap<T>(inout T $i1, inout T $i2): void { $temp = $i1; $i1 = $i2; $i2 = $temp; } <<__EntryPoint>> function main(): void { $v1 = -10; $v2 = 123; echo "\$v1 = ".$v1.", \$v2 = ".$v2."\n"; swap(inout $v1, inout $v2); echo "\$v1 = ".$v1.", \$v2 = ".$v2."\n"; $v3 = "red"; $v4 = "purple"; echo "\$v3 = ".$v3.", \$v4 = ".$v4."\n"; swap(inout $v3, inout $v4); echo "\$v3 = ".$v3.", \$v4 = ".$v4."\n"; } ``` The function swaps the two arguments passed to it. In the case of the call with two `int` arguments, `int` is inferred as the type corresponding to the type parameter `T`. In the case of the call with two `string` arguments, `string` is inferred as the type corresponding to the type parameter `T`.