Skip to content

Library to programatically generate Hack code and write it to signed files

License

Notifications You must be signed in to change notification settings

wlin53/hack-codegen

 
 

Repository files navigation

Hack Codegen Build Status

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.

About

Library to programatically generate Hack code and write it to signed files

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Hack 99.8%
  • Shell 0.2%