<commit_before>import 'dart:async';

import 'package:analyzer/dart/element/element.dart';
// TODO(https://github.com/dart-lang/sdk/issues/32454):
// ignore: implementation_imports
import 'package:analyzer/src/dart/element/element.dart';
import 'package:build/build.dart' as build;
import 'package:meta/meta.dart';
import 'package:source_gen/source_gen.dart';
import 'package:source_span/source_span.dart';
import 'package:stack_trace/stack_trace.dart';

import 'messages.dart';

/// Executes the provided [fn], capturing [BuildError]s and forwarding to logs.
///
/// * [showInternalTraces]: If `true`, [BuildError.stackTrace] is printed.
Future<T> runBuildZoned<T>(
  Future<T> Function() fn, {
  bool showInternalTraces = false,
}) {
  final completer = Completer<T>.sync();
  runZoned(
    () {
      fn().then((result) {
        if (!completer.isCompleted) {
          completer.complete(result);
        }
      });
    },
    onError: (e, s) {
      if (e is BuildError) {
        build.log.severe(
          e.message,
          null,
          showInternalTraces ? e.stackTrace : null,
        );
      } else if (e is UnresolvedAnnotationException) {
        final elementSpan = spanForElement(e.annotatedElement);
        final annotation = e.annotationSource.text;
        final buffer = StringBuffer()
          ..writeln(elementSpan.message('Could not resolve "$annotation"'))
          ..writeln(messages.analysisFailureReasons);
        build.log.severe(buffer, null, showInternalTraces ? s : null);
      } else {
        build.log.severe(
          'Unhandled exception in the AngularDart compiler!\n\n'
              'Please report a bug: ${messages.urlFileBugs}',
          e,
          s,
        );
      }
      if (!completer.isCompleted) {
        completer.complete();
      }
    },
    zoneSpecification: ZoneSpecification(
      print: (_, __, ___, line) => build.log.fine(line),
    ),
  );
  return completer.future;
}

/// Base error type for all fatal errors encountered while compiling.
///
/// There is _intentionally_ not a `logFailure` function, as all failures should
/// be a result of throwing an [BuildError] or an error that extends from
/// [BuildError]. This guarantees that the build is exited as a result of the
/// failure.
class BuildError extends Error {
  /// Message describing the build error.
  final String message;

  @override
  final Trace stackTrace;

  BuildError([this.message, Trace trace])
      : stackTrace = trace ?? Trace.current();

  // TODO: Remove internal API once ElementAnnotation has source information.
  // https://github.com/dart-lang/sdk/issues/32454
  static SourceSpan _getSourceSpanFrom(ElementAnnotation annotation) {
    final internals = annotation as ElementAnnotationImpl;
    final astNode = internals.annotationAst;
    final contents = annotation.source.contents.data;
    final start = astNode.offset;
    final end = start + astNode.length;
    return SourceSpan(
      SourceLocation(start, sourceUrl: annotation.source.uri),
      SourceLocation(end, sourceUrl: annotation.source.uri),
      contents.substring(start, end),<commit_msg>fix(Compiler): fix line and column numbers for `BuildError.throwForAnnotation`<commit_after>import 'dart:async';

import 'package:analyzer/dart/element/element.dart';
// TODO(https://github.com/dart-lang/sdk/issues/32454):
// ignore: implementation_imports
import 'package:analyzer/src/dart/element/element.dart';
import 'package:build/build.dart' as build;
import 'package:meta/meta.dart';
import 'package:source_gen/source_gen.dart';
import 'package:source_span/source_span.dart';
import 'package:stack_trace/stack_trace.dart';

import 'messages.dart';

/// Executes the provided [fn], capturing [BuildError]s and forwarding to logs.
///
/// * [showInternalTraces]: If `true`, [BuildError.stackTrace] is printed.
Future<T> runBuildZoned<T>(
  Future<T> Function() fn, {
  bool showInternalTraces = false,
}) {
  final completer = Completer<T>.sync();
  runZoned(
    () {
      fn().then((result) {
        if (!completer.isCompleted) {
          completer.complete(result);
        }
      });
    },
    onError: (e, s) {
      if (e is BuildError) {
        build.log.severe(
          e.message,
          null,
          showInternalTraces ? e.stackTrace : null,
        );
      } else if (e is UnresolvedAnnotationException) {
        final elementSpan = spanForElement(e.annotatedElement);
        final annotation = e.annotationSource.text;
        final buffer = StringBuffer()
          ..writeln(elementSpan.message('Could not resolve "$annotation"'))
          ..writeln(messages.analysisFailureReasons);
        build.log.severe(buffer, null, showInternalTraces ? s : null);
      } else {
        build.log.severe(
          'Unhandled exception in the AngularDart compiler!\n\n'
              'Please report a bug: ${messages.urlFileBugs}',
          e,
          s,
        );
      }
      if (!completer.isCompleted) {
        completer.complete();
      }
    },
    zoneSpecification: ZoneSpecification(
      print: (_, __, ___, line) => build.log.fine(line),
    ),
  );
  return completer.future;
}

/// Base error type for all fatal errors encountered while compiling.
///
/// There is _intentionally_ not a `logFailure` function, as all failures should
/// be a result of throwing an [BuildError] or an error that extends from
/// [BuildError]. This guarantees that the build is exited as a result of the
/// failure.
class BuildError extends Error {
  /// Message describing the build error.
  final String message;

  @override
  final Trace stackTrace;

  BuildError([this.message, Trace trace])
      : stackTrace = trace ?? Trace.current();

  // TODO: Remove internal API once ElementAnnotation has source information.
  // https://github.com/dart-lang/sdk/issues/32454
  static SourceSpan _getSourceSpanFrom(ElementAnnotation annotation) {
    final internals = annotation as ElementAnnotationImpl;
    final lineInfo = internals.compilationUnit.lineInfo;
    final astNode = internals.annotationAst;
    final contents = annotation.source.contents.data;
    final start = astNode.offset;
    final startInfo = lineInfo.getLocation(start);
    final end = start + astNode.length;
    final endInfo = lineInfo.getLocation(end);
    return SourceSpan(
      SourceLocation(
        start,
        sourceUrl: annotation.source.uri,
        line: startInfo.lineNumber,
        column: startInfo.columnNumber,
      ),
      SourceLocation(
        end,
        sourceUrl: annotation.source.uri,
        line: endInfo.lineNumber,
        column: endInfo.columnNumber,
      ),
      contents.substring(start, end),
{'fraction_non_alphanumeric': 0.11754122938530735, 'fraction_numerical': 0.0029985007496251873, 'mean_word_length': 3.0017996400719857, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5649234', 'n_tokens_mistral': 1968, 'n_tokens_neox': 1907, 'n_words': 483}