code_builder 0.1.3 copy "code_builder: ^0.1.3" to clipboard
code_builder: ^0.1.3 copied to clipboard

outdatedDart 1 only

A fluent API for generating Dart code

code_builder #

Build Status Coverage Status

code_builder is a fluent Dart API for generating valid Dart source code.

Code generation was traditionally done through a series of package-specific string concatenations which usually results in messy and sometimes invalid Dart code that is not easily readable and is very difficult to refactor.

code_builder uses the analyzer package to create real Dart language ASTs, which, while not guaranteed to be correct, always follows the analyzer's own understood format.

Experimental #

While code_builder is considered stable, the APIs are subject to frequent breaking change - a number of Dart language features are not yet implemented that make it unsuitable for all forms of code generation.

Contributions are welcome!

Usage #

Code builder has a narrow and user-friendly API.

For example creating a class with a method:

new ClassBuilder('Animal', extends: 'Organism')
  ..addMethod(new MethodBuilder.returnVoid('eat')
    ..setExpression(new ExpressionBuilder.invoke('print',
      positional: [new LiteralString('Yum!')])));

Outputs:

class Animal extends Organism {
  void eat() => print('Yum!');
}

Have a complicated set of dependencies for your generated code? code_builder supports automatic scoping of your ASTs to automatically use prefixes to avoid symbol conflicts:

var lib = new LibraryBuilder.scope()
      ..addDeclaration(new MethodBuilder(
        name: 'doThing',
        returns: new TypeBuilder(
          'Thing',
          importFrom: 'package:thing/thing.dart',
        ),
      ))
      ..addDeclaration(new MethodBuilder(
          name: 'doOtherThing',
          returns: new TypeBuilder(
            'Thing',
            importFrom: 'package:thing/alternative.dart',
          ))
        ..addParameter(new ParameterBuilder(
          'thing',
          type: new TypeBuilder(
            'Thing',
            importFrom: 'package:thing/thing.dart',
          ),
        )));

Outputs:

import 'package:thing/thing.dart' as _i1;
import 'package:thing/alternative.dart' as _i2;

_i1.Thing doThing() {}
_i2.Thing doOtherThing(_i1.Thing thing) {}