Skip to content

Commit

Permalink
Merge pull request #280 from Workiva/optimize_builder
Browse files Browse the repository at this point in the history
CPLAT-5152: Optimize builder's use of asset reads to avoid unnecessary rebuilds
  • Loading branch information
rmconsole6-wk authored Apr 4, 2019
2 parents 8748f82 + 93d4593 commit 02ea76b
Show file tree
Hide file tree
Showing 77 changed files with 290 additions and 193 deletions.
13 changes: 5 additions & 8 deletions build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ targets:
exclude:
# This tests un-built behavior, and therefore should not be built
- "test/over_react/component_declaration/builder_helpers_test.dart"

over_react|overReactBuilder:
enabled: false

Expand All @@ -37,13 +38,9 @@ targets:
- "web/**"
exclude:
- "lib/src/builder/**"

build_web_compilers|entrypoint:
generate_for:
include:
- "example/**"
- "lib/*.dart"
- "test/*.dart"
- "web/*.dart"
exclude:
- "lib/src/builder/**"

- "example/**.dart"
- "test/*.browser_test.dart"
- "web/*.dart"
2 changes: 1 addition & 1 deletion example/builder/abstract_inheritance.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion example/builder/basic.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions example/builder/basic_library.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion example/builder/basic_with_state.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion example/builder/basic_with_type_params.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion example/builder/generic_inheritance_sub.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion example/builder/private_component.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion example/builder/props_mixin.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion example/builder/state_mixin.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

142 changes: 138 additions & 4 deletions lib/src/builder/builder.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,142 @@
import 'dart:async';

import 'package:analyzer/analyzer.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:dart_style/dart_style.dart';
import 'package:over_react/src/builder/generation/declaration_parsing.dart';
import 'package:over_react/src/builder/generation/impl_generation.dart';
import 'package:path/path.dart' as p;
import 'package:source_span/source_span.dart';

import './util.dart';
import './generator.dart';

Builder overReactBuilder(BuilderOptions options) =>
new PartBuilder([new OverReactGenerator()], outputExtension);
Builder overReactBuilder(BuilderOptions options) => new OverReactBuilder();

class OverReactBuilder extends Builder {
@override
Map<String, List<String>> get buildExtensions => {
'.dart': [outputExtension],
};

@override
FutureOr<void> build(BuildStep buildStep) async {
final source = await buildStep.readAsString(buildStep.inputId);
final libraryUnit = _tryParseCompilationUnit(source, buildStep.inputId);
if (libraryUnit == null) {
return;
}
if (isPart(libraryUnit)) {
return;
}

final outputs = <String>[];
void generateForFile(String source, AssetId id, CompilationUnit unit) {
if (!ParsedDeclarations.mightContainDeclarations(source)) {
return;
}
final sourceFile = new SourceFile.fromString(
source, url: idToPackageUri(id));
final declarations = new ParsedDeclarations(unit, sourceFile, log);
if (declarations.hasErrors) {
log.severe('There was an error parsing the file declarations for file: $id');
return;
}
final generator = new ImplGenerator(log, sourceFile)
..generate(declarations);
final generatedOutput = generator.outputContentsBuffer.toString().trim();
if (generatedOutput.isNotEmpty) {
outputs.add(generatedOutput);
}
}

// Collect all of the part files for this library.
final parts = libraryUnit.directives
.whereType<PartDirective>()
// Ignore all generated `.g.dart` parts.
.where((part) => !part.uri.stringValue.endsWith('.g.dart'));

// Generate over_react code for the input library.
generateForFile(source, buildStep.inputId, libraryUnit);

// Generate over_react code for each part file of the input library.
for (final part in parts) {
final partId = new AssetId.resolve(
part.uri.stringValue,
from: buildStep.inputId);
if (!await buildStep.canRead(partId)) {
continue;
}
final partSource = await buildStep.readAsString(partId);
final partUnit = _tryParseCompilationUnit(partSource, partId);
if (partUnit == null) {
continue;
}
generateForFile(partSource, partId, partUnit);
}

if (outputs.isNotEmpty) {
final outputId = buildStep.inputId.changeExtension(outputExtension);

// Verify that the library file has an `.over_react.g.dart` part.
final expectedPart = p.basename(outputId.path);
final partUris = libraryUnit.directives
.whereType<PartDirective>()
.map((p) => p.uri.stringValue);
if (!partUris.contains(expectedPart)) {
log.warning('Missing "part \'$expectedPart\';".');
}

await _writePart(buildStep, outputId, outputs);
}
}

static final _headerLine = '// '.padRight(77, '*');

static final _formatter = new DartFormatter();

static final RegExp _overReactPartDirective = new RegExp(
r'''['"].*\.over_react\.g\.dart['"]''',
);

static bool _mightContainDeclarations(String source) {
return ParsedDeclarations.mightContainDeclarations(source) ||
_overReactPartDirective.hasMatch(source);
}

static CompilationUnit _tryParseCompilationUnit(String source, AssetId id) {
try {
return parseCompilationUnit(
source,
name: id.path,
suppressErrors: false,
parseFunctionBodies: true);
} catch (error, stackTrace) {
log.severe('There was an error parsing the compilation unit for file: $id');
log.fine(error);
log.fine(stackTrace);
return null;
}
}

static FutureOr<void> _writePart(BuildStep buildStep, AssetId outputId, Iterable<String> outputs) async {
final partOf = "'${p.basename(buildStep.inputId.uri.toString())}'";

final buffer = new StringBuffer()
..writeln('// GENERATED CODE - DO NOT MODIFY BY HAND')
..writeln()
..writeln('part of $partOf;')
..writeln()
..writeln(_headerLine)
..writeln('// OverReactBuilder (package:over_react/src/builder.dart)')
..writeln(_headerLine);

for (final item in outputs) {
buffer
..writeln()
..writeln(item);
}

final output = _formatter.format(buffer.toString());
await buildStep.writeAsString(outputId, output);
}
}
73 changes: 0 additions & 73 deletions lib/src/builder/generator.dart

This file was deleted.

6 changes: 5 additions & 1 deletion lib/src/builder/util.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'dart:mirrors';

import 'package:analyzer/analyzer.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:path/path.dart' as p;
import 'package:build/build.dart' show AssetId;
import 'package:source_span/source_span.dart';
Expand Down Expand Up @@ -28,6 +28,10 @@ Uri idToPackageUri(AssetId id) {
path: p.url.join(id.package, id.path.replaceFirst('lib/', '')));
}

/// Returns true if the given compilation unit is a part file.
bool isPart(CompilationUnit unit) =>
unit.directives.any((directive) => directive is PartOfDirective);

/// Returns a string representing a [TypeParameterList], but type bounds removed.
///
/// Example:
Expand Down
4 changes: 2 additions & 2 deletions lib/src/component/abstract_transition.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions lib/src/component/abstract_transition_props.over_react.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 02ea76b

Please sign in to comment.