facebook/hack-codegen

There is no license information available for the latest version (v4.5.1) of this package.

Hack Codegen is a library for programmatically generating Hack code

Installs: 537 043

Dependents: 7

Suggesters: 0

Security: 0

Stars: 341

Watchers: 67

Forks: 93

Open Issues: 7

Language:Hack

v4.5.1 2022-06-06 17:05 UTC

README

Hack Codegen is a library for easily generating Hack code and writing it into signed files that prevent undesired modifications. The idea behind writing code that writes code is to raise the level of abstraction and reduce coupling. You can use your own way of describing a problem and generate the corresponding code. E.g. see examples/dorm. In this example, we use a schema to describe the structure of the data, and we use Hack Codegen to write the matching code.

Examples

The DORM example shows how to use the different aspects of the code generation in a simplified real-life example. The included tests also exemplify the usage of the different components.

Requirements

Hack Codegen requires:

  • HHVM
  • Composer

Installing Hack Codegen

This package can be installed via composer:

composer require facebook/hack-codegen

Usage

Include the autoload file generated by composer and you are ready to start using it. For example:

<?hh
require 'vendor/autoload.php';

use Facebook\HackCodegen\HackCodegenFactory;

$cg = new HackCodegenFactory(new HackCodegenConfig());

echo $cg->codegenFile('HelloWorld.php')
  ->addClass(
    $cg->codegenClass('HelloWorld')
      ->addMethod(
        $cg->codegenMethod('sayHi')
          ->setReturnType('void')
          ->setBody(
            $cg->codegenHackBuilder()
              ->addAssignment(
                '$some_vector',
                Vector { 1, 2, 3 },
                HackBuilderValues::vector(
                  HackBuilderValues::export(),
                ),
              )
              ->addAssignment(
                '$debug_info',
                Map { 'file' => '__FILE__', 'line' => '__LINE__' },
                HackBuilderValues::map(
                  HackBuilderKeys::export(),
                  HackBuilderValues::literal(),
                ),
              )
              ->addAssignment(
                '$some_vector_of_vectors',
                Vector { Vector { 1, 2, 3 }, Vector { 4, 5, 6 } },
                HackBuilderValues::vector(
                  HackBuilderValues::vector(
                    HackBuilderValues::export(),
                  ),
                ),
              )
              ->addLine('echo "hello world\n";')
              ->getCode();
          );
      )
  )->save();

Configuration

You can configure some options such as the maximum line width, spacing and headers by implementing IHackCodegenConfig and passing an instance to HackCodegenFactory's constructor.

License

Hack Codegen is MIT-licensed.