visitLibrary method

  1. @override
StringSink visitLibrary(
  1. Library spec, [
  2. StringSink? output
])

Implementation

@override
StringSink visitLibrary(Library spec, [StringSink? output]) {
  output ??= StringBuffer();

  if (spec.comments.isNotEmpty) {
    spec.comments.map((line) => '// $line').forEach(output.writeln);
    output.writeln();
  }

  if (spec.generatedByComment != null) {
    output
      ..writeln('// ${spec.generatedByComment}')
      ..writeln();
  }

  if (spec.ignoreForFile.isNotEmpty) {
    final ignores = spec.ignoreForFile.toList()..sort();
    final lines = ['// ignore_for_file: ${ignores.first}'];
    for (var ignore in ignores.skip(1)) {
      if (lines.last.length + 2 + ignore.length > 80) {
        lines.add('// ignore_for_file: $ignore');
      } else {
        lines[lines.length - 1] = '${lines.last}, $ignore';
      }
    }
    lines.forEach(output.writeln);
    output.writeln();
  }

  // Process the body first in order to prime the allocators.
  final body = StringBuffer();
  for (final spec in spec.body) {
    spec.accept(this, body);
    if (spec is Method && _isLambdaMethod(spec)) {
      body.write(';');
    }
  }

  spec.docs.forEach(output.writeln);
  for (var a in spec.annotations) {
    visitAnnotation(a, output);
  }
  if (spec.name != null) {
    output.write('library ${spec.name!};');
  } else if (spec.annotations.isNotEmpty || spec.docs.isNotEmpty) {
    // An explicit _unnamed_ library directive is only required if there are
    // annotations or doc comments on the library.
    output.write('library;');
  }

  final directives = <Directive>[...allocator.imports, ...spec.directives];

  if (orderDirectives) {
    directives.sort();
  }

  Directive? previous;
  if (directives.any((d) => d.as?.startsWith('_') ?? false)) {
    output.writeln(
        '// ignore_for_file: no_leading_underscores_for_library_prefixes');
  }
  for (final directive in directives) {
    if (_newLineBetween(orderDirectives, previous, directive)) {
      // Note: dartfmt handles creating new lines between directives.
      // 2 lines are written here. The first one comes after the previous
      // directive `;`, the second is the empty line.
      output
        ..writeln()
        ..writeln();
    }
    directive.accept(this, output);
    previous = directive;
  }
  output.write(body);
  return output;
}