Saturday, August 30, 2014
Asynchronous Programming in Hack - Example Code

Asynchronous programming allows a script to run multiple tasks in parallel. These tasks are usually input/output operations that rely on operations that are run by separate servers or other OS processes.

Traditionally PHP executes those tasks and waits for them to finish before it returns the control to your script. This is called synchronous programming. Also, PHP has limited support for asynchronous programming, and it does not provide a clean and consistent solution.

With synchronous programming each task can only be started after the previous task has finished. Imagine a script that collects information from different sites. Each one will hold your script for as long as the servers take to respond. Thus, synchronous programming is often a waste of performance.

Hack made it easy to do asynchronous programming cleanly, and also without the pain of callbacks used by JavaScript solutions. It introduced the async keyword which you can assign to functions to tell that it can be executed asynchronously. There is also an await keyword, which is used to suspend the execution of the code that follows the statement, even if it is doing something asynchronous like waiting for some IOs or network connections etc.

This is a very elegant asynchronous programming solution because you do not have to be concerned with callbacks or internal event loops, to make your script hold in a certain position while parallel tasks keep running and do other things. This is definitely one of the best features of the Hack language.

class Foo {}

class Bar {
    public function getFoo(): Foo {
        return new Foo();
    }
}

async function gen_foo(int $a): Awaitable<?Foo>; {
    if ($a === 0) return null;

    $bar = await gen_bar($a);
    if ($bar !== null) {
        return $bar->getFoo();
    }

    return null;
}

async function gen_bar(int $a): Awaitable<?Bar> {
    if ($a === 0) return null;
    return new Bar();
}

gen_foo(4);



Facebook's HHVM is an open-source virtual machine designed for executing programs written in Hack and PHP. HHVM uses a just-in-time (JIT) compilation approach to achieve superior performance while maintaining the development flexibility that PHP provides.

The JIT Compiler

Rather than directly interpret or compile PHP code directly to C++, HHVM compiles Hack and PHP into an intermediate bytecode. This bytecode is then translated into x64 machine code dynamically at runtime by a just-in-time (JIT) compiler. This compilation process allows for all sorts of optimizations that cannot be made in a statically compiled binary, thus enabling higher performance of your Hack and PHP programs.

HHVM is intended to achieve both parity with the Zend Engine features and best possible performances. Facebook claims a 3x to 10x speed boost and 1/2 memory footprint by switching from PHP+APC to HHVM. But that is of course really application dependent (10x being for the FB code base).

Perfomance Optimization with Hack

Hack is an evolution of the PHP language designed to be safer, to enable better performance and to improve developer efficiency. Following are some of the areas where it has improved PHP to give us more performance-wise:

Type Annotations

Hack supports type annotation, which tells the runtime engine explicitly that a value is of a specific type. Run-time enforcement of return types and parameter types help HHVM's JIT produce more efficient code by making it safe to trust type annotations for optimization purposes.

Collections

Collections can hold values of the same type. HHVM can generate native machine code that is optimized for storing and retrieving collection values of a specific type from the collection, thus resulting in better performance.

Important Language Features of Hack: An Overview


Hack has introduced many new features that are used for different purposes, such as Error Prevention, Code Reuse, Performance Optimization etc. Following are some of the important language features of Hack:

Type Annotations

Type Annotations allow for PHP code to be explicitly typed on parameters, class member variables and return values. They are like type declarations, except they are optional.

class MyClass {
    const int MyConst = 0;
    private string $x = '';
    public function increment(int $x): int {
        $y = $x + 1;
        return $y;
    }
}

Nullable Types

Nullable types is an extension of type annotations used to specify that a value maybe of a certain type or NULL. They are supported by Hack through use of a question mark operator. This introduces a safer way to deal with nulls and is very useful for primitive types that don’t generally allow null as one of their values, such as bool and int. The operator can be used on any class or type.

function check_not_null(?int $x): int {
    if ($x === null) {
        return -1;
    } else {
        return $x;
    }
}

Collections

Collections enhance the experience of working with PHP arrays, by providing first class, built-in parameterized types such as Vector, Map, Set and Pair. Collections allow to detect attempts to set values to incorrect types due to application bugs.

/*  Like all objects, collections has "reference-like"
    semantics for assignment, parameter passing, and
    foreach. */

function foo($v) {
    $v[1] = 7;
}

function main() {
    $v1 = Vector {1, 2, 3};
    $v2 = $v1;
    foo($v2);
    var_dump($v1);
    echo "\n";
    foreach ($v1 as $key => $value) {
        echo $key . " => " . $value . "\n";
        if ($key == 0) {
            $v1[2] = 9;
        }
    }
}

main();

Generics

Generics allow classes and methods to be parameterized in the same way as statically type languages like Java and C#). Generics are basically code templates. This allows to create classes that perform the same operations using the same code on classes of different types (such as integers or floating point numbers etc.)

class Box<T> {
    protected T $data;

    public function __construct(T $data) {
        $this->data = $data;
    }

    public function getData(): T {
        return $this->data;
    }
}

There are other features too which include Shapes, Async support, Type Aliasing and much more.
Friday, August 29, 2014
What is Hack?


Hack is a new programming language based on PHP. It is developed by Facebook and was announced recently on March 20, 2014. The syntax is basically the same as PHP, but underneath the hood there are a lot of features such as static typing, native collections, generics and more which PHP has been lacking. Hack allows programmers to use both dynamic typing as well as static typing. Hack is not PHP, as it runs only on Facebook’s HipHop Virtual Machine (HHVM), a competitor to the traditional PHP Zend Engine.

Why was Hack born?

Much of the internal code of Facebook was first written in PHP, since the language is notoriously easy to learn and use. Also, Facebook uses PHP language largely to attract new talent and increase developers efficiency.

However, PHP could not perform as well at a scale as large as Facebook’s. Reason being that PHP is a loosely typed language and type-related errors are not recognized until runtime. In order to solve this and other such problems, Hack was born. Facebook added strict typing feature and runtime-enforcement of return types to the new language. Strict typing nullifies the need for a lot of type-related unit tests and encourages developers to catch type-related errors sooner in the development process.

New Features

Comparison of PHP and Hack
Hack introduced many new features which are not present in the current PHP version. Some of those features were proposed to PHP over time but they were never accepted. These new features include type annotations, nullable types, generics, collections, lambdas and more. Hack takes advantage of HHVM (HipHop Virtual Machine) to execute the code faster.

Most existing code of PHP will run on Facebook’s HHVM engine. This is necessary because Facebook’s existing codebase is largely existing PHP code.

Hack code can be mixed with regular PHP code. To convert a PHP class to a Hack class, change the leading <?php to <?hh. That’s literally all that is necessary. This allows smooth migration between PHP and Hack code, so you can take advantage of Hack's additional features.