Add a library for manipulating stack traces.

Review URL: https://codereview.chromium.org//13102003

git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart/pkg/stack_trace@20582 260f80e4-7a28-3924-810f-c04153c831b5
diff --git a/pkgs/stack_trace/README.md b/pkgs/stack_trace/README.md
new file mode 100644
index 0000000..6a8112a
--- /dev/null
+++ b/pkgs/stack_trace/README.md
@@ -0,0 +1,57 @@
+This library provides the ability to parse, inspect, and manipulate stack traces
+produced by the underlying Dart implementation. It also provides functions to
+produce string representations of stack traces in a more readable format than
+the native [StackTrace] implementation.
+
+`Trace`s can be parsed from native [StackTrace]s using `Trace.from`, or captured
+using `Trace.current`. Native [StackTrace]s can also be directly converted to
+human-readable strings using `Trace.format`.
+
+[StackTrace]: http://api.dartlang.org/docs/releases/latest/dart_core/StackTrace.html
+
+Here's an example native stack trace from debugging this library:
+
+    #0      Object.noSuchMethod (dart:core-patch:1884:25)
+    #1      Trace.terse.<anonymous closure> (file:///usr/local/google-old/home/goog/dart/dart/pkg/stack_trace/lib/src/trace.dart:47:21)
+    #2      IterableMixinWorkaround.reduce (dart:collection:29:29)
+    #3      List.reduce (dart:core-patch:1247:42)
+    #4      Trace.terse (file:///usr/local/google-old/home/goog/dart/dart/pkg/stack_trace/lib/src/trace.dart:40:35)
+    #5      format (file:///usr/local/google-old/home/goog/dart/dart/pkg/stack_trace/lib/stack_trace.dart:24:28)
+    #6      main.<anonymous closure> (file:///usr/local/google-old/home/goog/dart/dart/test.dart:21:29)
+    #7      _CatchErrorFuture._sendError (dart:async:525:24)
+    #8      _FutureImpl._setErrorWithoutAsyncTrace (dart:async:393:26)
+    #9      _FutureImpl._setError (dart:async:378:31)
+    #10     _ThenFuture._sendValue (dart:async:490:16)
+    #11     _FutureImpl._handleValue.<anonymous closure> (dart:async:349:28)
+    #12     Timer.run.<anonymous closure> (dart:async:2402:21)
+    #13     Timer.Timer.<anonymous closure> (dart:async-patch:15:15)
+
+and its human-readable representation:
+
+    dart:core-patch                             Object.noSuchMethod
+    pkg/stack_trace/lib/src/trace.dart 47:21    Trace.terse.<fn>
+    dart:collection                             IterableMixinWorkaround.reduce
+    dart:core-patch                             List.reduce
+    pkg/stack_trace/lib/src/trace.dart 40:35    Trace.terse
+    pkg/stack_trace/lib/stack_trace.dart 24:28  format
+    test.dart 21:29                             main.<fn>
+    dart:async                                  _CatchErrorFuture._sendError
+    dart:async                                  _FutureImpl._setErrorWithoutAsyncTrace
+    dart:async                                  _FutureImpl._setError
+    dart:async                                  _ThenFuture._sendValue
+    dart:async                                  _FutureImpl._handleValue.<fn>
+    dart:async                                  Timer.run.<fn>
+    dart:async-patch                            Timer.Timer.<fn>
+
+You can further clean up the stack trace using `Trace.terse`. This folds
+together multiple stack frames from the Dart core libraries, so that only the
+core library method that was directly called from user code is visible. For
+example:
+
+    dart:core                                   Object.noSuchMethod
+    pkg/stack_trace/lib/src/trace.dart 47:21    Trace.terse.<fn>
+    dart:core                                   List.reduce
+    pkg/stack_trace/lib/src/trace.dart 40:35    Trace.terse
+    pkg/stack_trace/lib/stack_trace.dart 24:28  format
+    test.dart 21:29                             main.<fn>
+    dart:async                                  Timer.Timer.<fn>
diff --git a/pkgs/stack_trace/lib/src/frame.dart b/pkgs/stack_trace/lib/src/frame.dart
new file mode 100644
index 0000000..fdf4fe0
--- /dev/null
+++ b/pkgs/stack_trace/lib/src/frame.dart
@@ -0,0 +1,88 @@
+// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library frame;
+
+import 'dart:uri';
+
+import 'package:pathos/path.dart' as path;
+
+import 'trace.dart';
+
+final _nativeFrameRegExp = new RegExp(
+    r'^#\d+\s+([^\s].*) \((.+):(\d+):(\d+)\)$');
+
+/// A single stack frame. Each frame points to a precise location in Dart code.
+class Frame {
+  /// The URI of the file in which the code is located.
+  ///
+  /// This URI will usually have the scheme `dart`, `file`, `http`, or `https`.
+  final Uri uri;
+
+  /// The line number on which the code location is located.
+  final int line;
+
+  /// The column number of the code location.
+  final int column;
+
+  /// The name of the member in which the code location occurs.
+  ///
+  /// Anonymous closures are represented as `<fn>` in this member string.
+  final String member;
+
+  /// Whether this stack frame comes from the Dart core libraries.
+  bool get isCore => uri.scheme == 'dart';
+
+  /// Returns a human-friendly description of the library that this stack frame
+  /// comes from.
+  ///
+  /// This will usually be the string form of [uri], but a relative path will be
+  /// used if possible.
+  String get library {
+    // TODO(nweiz): handle relative URIs here as well once pathos supports that.
+    if (uri.scheme != 'file') return uri.toString();
+    return path.relative(uri.path);
+  }
+
+  /// A human-friendly description of the code location.
+  ///
+  /// For Dart core libraries, this will omit the line and column information,
+  /// since those are useless for baked-in libraries.
+  String get location {
+    if (isCore) return library;
+    return '$library $line:$column';
+  }
+
+  /// Returns a single frame of the current stack.
+  ///
+  /// By default, this will return the frame above the current method. If
+  /// [level] is `0`, it will return the current method's frame; if [level] is
+  /// higher than `1`, it will return higher frames.
+  factory Frame.caller([int level=1]) {
+    if (level < 0) {
+      throw new ArgumentError("Argument [level] must be greater than or equal "
+          "to 0.");
+    }
+
+    return new Trace.current(level + 1).frames.first;
+  }
+
+  /// Parses a string representation of a stack frame.
+  ///
+  /// [frame] should be formatted in the same way as a native stack trace frame.
+  factory Frame.parse(String frame) {
+    var match = _nativeFrameRegExp.firstMatch(frame);
+    if (match == null) {
+      throw new FormatException("Couldn't parse stack trace line '$frame'.");
+    }
+
+    var uri = new Uri.fromString(match[2]);
+    var member = match[1].replaceAll("<anonymous closure>", "<fn>");
+    return new Frame(uri, int.parse(match[3]), int.parse(match[4]), member);
+  }
+
+  Frame(this.uri, this.line, this.column, this.member);
+
+  String toString() => '$location in $member';
+}
diff --git a/pkgs/stack_trace/lib/src/trace.dart b/pkgs/stack_trace/lib/src/trace.dart
new file mode 100644
index 0000000..1ab7695
--- /dev/null
+++ b/pkgs/stack_trace/lib/src/trace.dart
@@ -0,0 +1,127 @@
+// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library trace;
+
+import 'dart:uri';
+
+import 'frame.dart';
+
+final _patchRegExp = new RegExp(r"-patch$");
+
+/// A stack trace, comprised of a list of stack frames.
+class Trace implements StackTrace {
+  // TODO(nweiz): make this read-only once issue 8321 is fixed.
+  /// The stack frames that comprise this stack trace.
+  final List<Frame> frames;
+
+  /// Returns a human-readable representation of [stackTrace]. If [terse] is
+  /// set, this folds together multiple stack frames from the Dart core
+  /// libraries, so that only the core library method directly called from user
+  /// code is visible (see [Trace.terse]).
+  static String format(StackTrace stackTrace, {bool terse: true}) {
+    var trace = new Trace.from(stackTrace);
+    if (terse) trace = trace.terse;
+    return trace.toString();
+  }
+
+  /// Returns the current stack trace.
+  ///
+  /// By default, the first frame of this trace will be the line where
+  /// [Trace.current] is called. If [level] is passed, the trace will start that
+  /// many frames up instead.
+  factory Trace.current([int level=0]) {
+    if (level < 0) {
+      throw new ArgumentError("Argument [level] must be greater than or equal "
+          "to 0.");
+    }
+
+    try {
+      throw '';
+    } catch (_, nativeTrace) {
+      var trace = new Trace.from(nativeTrace);
+      return new Trace(trace.frames.skip(level + 1));
+    }
+  }
+
+  /// Returns a new stack trace containing the same data as [trace].
+  ///
+  /// If [trace] is a native [StackTrace], its data will be parsed out; if it's
+  /// a [Trace], it will be returned as-is.
+  factory Trace.from(StackTrace trace) {
+    if (trace is Trace) return trace;
+    return new Trace.parse(trace.fullStackTrace);
+  }
+
+  /// Parses a string representation of a stack trace.
+  ///
+  /// [trace] should be formatted in the same way as native stack traces.
+  Trace.parse(String trace)
+      : this(trace.trim().split("\n").map((line) => new Frame.parse(line)));
+
+  /// Returns a new [Trace] comprised of [frames].
+  Trace(Iterable<Frame> frames)
+      : frames = frames.toList();
+
+  // TODO(nweiz): Keep track of which [Frame]s are part of the partial stack
+  // trace and only print them.
+  /// Returns a string representation of this stack trace.
+  ///
+  /// This is identical to [toString]. It will not be formatted in the manner of
+  /// native stack traces.
+  String get stackTrace => toString();
+
+  /// Returns a string representation of this stack trace.
+  ///
+  /// This is identical to [toString]. It will not be formatted in the manner of
+  /// native stack traces.
+  String get fullStackTrace => toString();
+
+  /// Returns a terser version of [this]. This is accomplished by folding
+  /// together multiple stack frames from the core library. If multiple such
+  /// frames appear in a row, only the last (the one directly called by user
+  /// code) is kept. Core library patches are also renamed to remove their
+  /// `-patch` suffix.
+  Trace get terse {
+    var newFrames = <Frame>[];
+    for (var frame in frames.reversed) {
+      if (!frame.isCore) {
+        newFrames.add(frame);
+      } else if (newFrames.isEmpty || !newFrames.last.isCore) {
+        var library = frame.library.replaceAll(_patchRegExp, '');
+        newFrames.add(new Frame(
+            Uri.parse(library), frame.line, frame.column, frame.member));
+      }
+    }
+
+    return new Trace(newFrames.reversed);
+  }
+
+  /// Returns a human-readable string representation of [this].
+  String toString() {
+    if (frames.length == '') return '';
+
+    // Figure out the longest path so we know how much to pad.
+    var longest = frames.map((frame) => frame.location.length).max();
+
+    // Print out the stack trace nicely formatted.
+    return frames.map((frame) {
+      return '${_padRight(frame.location, longest)}  ${frame.member}\n';
+    }).join();
+  }
+}
+
+/// Returns [string] with enough spaces added to the end to make it [length]
+/// characters long.
+String _padRight(String string, int length) {
+  if (string.length >= length) return string;
+
+  var result = new StringBuffer();
+  result.write(string);
+  for (var i = 0; i < length - string.length; i++) {
+    result.write(' ');
+  }
+
+  return result.toString();
+}
diff --git a/pkgs/stack_trace/lib/stack_trace.dart b/pkgs/stack_trace/lib/stack_trace.dart
new file mode 100644
index 0000000..455dd57
--- /dev/null
+++ b/pkgs/stack_trace/lib/stack_trace.dart
@@ -0,0 +1,11 @@
+// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library stack_trace;
+
+import 'src/trace.dart';
+import 'src/frame.dart';
+
+export 'src/trace.dart';
+export 'src/frame.dart';
diff --git a/pkgs/stack_trace/pubspec.yaml b/pkgs/stack_trace/pubspec.yaml
new file mode 100644
index 0000000..3a679a8
--- /dev/null
+++ b/pkgs/stack_trace/pubspec.yaml
@@ -0,0 +1,11 @@
+name: stack_trace
+author: "Dart Team <misc@dartlang.org>"
+homepage: http://www.dartlang.org
+description: >
+  A package for manipulating stack traces and printing them readably.
+
+dependencies:
+  pathos: any
+
+dev_dependencies:
+  unittest: any
diff --git a/pkgs/stack_trace/test/frame_test.dart b/pkgs/stack_trace/test/frame_test.dart
new file mode 100644
index 0000000..66dee6a
--- /dev/null
+++ b/pkgs/stack_trace/test/frame_test.dart
@@ -0,0 +1,159 @@
+// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library frame_test;
+
+import 'dart:uri';
+
+import 'package:pathos/path.dart' as path;
+import 'package:stack_trace/stack_trace.dart';
+import 'package:unittest/unittest.dart';
+
+String getStackFrame() {
+  try {
+    throw '';
+  } catch (_, stackTrace) {
+    return stackTrace.toString().split("\n").first;
+  }
+}
+
+Frame getCaller([int level]) {
+  if (level == null) return new Frame.caller();
+  return new Frame.caller(level);
+}
+
+Frame nestedGetCaller(int level) => getCaller(level);
+
+void main() {
+  test('parses a stack frame correctly', () {
+    var frame = new Frame.parse("#1      Foo._bar "
+        "(file:///home/nweiz/code/stuff.dart:42:21)");
+    expect(frame.uri,
+        equals(new Uri.fromString("file:///home/nweiz/code/stuff.dart")));
+    expect(frame.line, equals(42));
+    expect(frame.column, equals(21));
+    expect(frame.member, equals('Foo._bar'));
+  });
+
+  test('parses a real stack frame correctly', () {
+    var frame = new Frame.parse(getStackFrame());
+    // TODO(nweiz): use URL-style paths when such a thing exists.
+    var builder = new path.Builder(style: path.Style.posix);
+    expect(builder.basename(frame.uri.path), equals('frame_test.dart'));
+    expect(frame.line, equals(15));
+    expect(frame.column, equals(5));
+    expect(frame.member, equals('getStackFrame'));
+  });
+
+  test('converts "<anonymous closure>" to "<fn>"', () {
+    String parsedMember(String member) =>
+        new Frame.parse('#0 $member (foo:0:0)').member;
+
+    expect(parsedMember('Foo.<anonymous closure>'), equals('Foo.<fn>'));
+    expect(parsedMember('<anonymous closure>.<anonymous closure>.bar'),
+        equals('<fn>.<fn>.bar'));
+  });
+
+  test('throws a FormatException for malformed frames', () {
+    expect(() => new Frame.parse(''), throwsFormatException);
+    expect(() => new Frame.parse('#1'), throwsFormatException);
+    expect(() => new Frame.parse('#1      Foo'), throwsFormatException);
+    expect(() => new Frame.parse('#1      Foo (dart:async)'),
+        throwsFormatException);
+    expect(() => new Frame.parse('#1      Foo (dart:async:10)'),
+        throwsFormatException);
+    expect(() => new Frame.parse('#1      (dart:async:10:15)'),
+        throwsFormatException);
+    expect(() => new Frame.parse('Foo (dart:async:10:15)'),
+        throwsFormatException);
+  });
+
+  test('only considers dart URIs to be core', () {
+    bool isCore(String library) =>
+      new Frame.parse('#0 Foo ($library:0:0)').isCore;
+
+    expect(isCore('dart:core'), isTrue);
+    expect(isCore('dart:async'), isTrue);
+    expect(isCore('bart:core'), isFalse);
+    expect(isCore('sdart:core'), isFalse);
+    expect(isCore('darty:core'), isFalse);
+  });
+
+  group('.caller()', () {
+    test('with no argument returns the parent frame', () {
+      expect(getCaller().member, equals('main.<fn>.<fn>'));
+    });
+
+    test('at level 0 returns the current frame', () {
+      expect(getCaller(0).member, equals('getCaller'));
+    });
+
+    test('at level 1 returns the current frame', () {
+      expect(getCaller(1).member, equals('main.<fn>.<fn>'));
+    });
+
+    test('at level 2 returns the grandparent frame', () {
+      expect(nestedGetCaller(2).member, equals('main.<fn>.<fn>'));
+    });
+
+    test('throws an ArgumentError for negative levels', () {
+      expect(() => new Frame.caller(-1), throwsArgumentError);
+    });
+  });
+
+  group('.library', () {
+    test('returns the URI string for non-file URIs', () {
+      expect(new Frame.parse('#0 Foo (dart:async:0:0)').library,
+          equals('dart:async'));
+      expect(new Frame.parse('#0 Foo '
+              '(http://dartlang.org/stuff/thing.dart:0:0)').library,
+          equals('http://dartlang.org/stuff/thing.dart'));
+    });
+
+    test('returns the relative path for file URIs', () {
+      var absolute = path.absolute(path.join('foo', 'bar.dart'));
+      expect(new Frame.parse('#0 Foo (file://$absolute:0:0)').library,
+          equals(path.join('foo', 'bar.dart')));
+    });
+  });
+
+  group('.location', () {
+    test('returns the library and line/column numbers for non-core '
+        'libraries', () {
+      expect(new Frame.parse('#0 Foo '
+              '(http://dartlang.org/thing.dart:5:10)').location,
+          equals('http://dartlang.org/thing.dart 5:10'));
+      var absolute = path.absolute(path.join('foo', 'bar.dart'));
+      expect(new Frame.parse('#0 Foo (file://$absolute:1:2)').location,
+          equals('${path.join('foo', 'bar.dart')} 1:2'));
+    });
+
+    test('just returns the library for core libraries', () {
+      expect(new Frame.parse('#0 Foo (dart:core:5:10)').location,
+          equals('dart:core'));
+      expect(new Frame.parse('#0 Foo (dart:async-patch:1:2)').location,
+          equals('dart:async-patch'));
+    });
+  });
+
+  group('.toString()', () {
+    test('returns the library and line/column numbers for non-core '
+        'libraries', () {
+      expect(new Frame.parse('#0 Foo (http://dartlang.org/thing.dart:5:10)')
+              .toString(),
+          equals('http://dartlang.org/thing.dart 5:10 in Foo'));
+    });
+
+    test('just returns the library for core libraries', () {
+      expect(new Frame.parse('#0 Foo (dart:core:5:10)').toString(),
+          equals('dart:core in Foo'));
+    });
+
+    test('converts "<anonymous closure>" to "<fn>"', () {
+      expect(new Frame.parse('#0 Foo.<anonymous closure> (dart:core:5:10)')
+              .toString(),
+          equals('dart:core in Foo.<fn>'));
+    });
+  });
+}
diff --git a/pkgs/stack_trace/test/trace_test.dart b/pkgs/stack_trace/test/trace_test.dart
new file mode 100644
index 0000000..711a412
--- /dev/null
+++ b/pkgs/stack_trace/test/trace_test.dart
@@ -0,0 +1,134 @@
+// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library trace_test;
+
+import 'dart:uri';
+
+import 'package:pathos/path.dart' as path;
+import 'package:stack_trace/stack_trace.dart';
+import 'package:unittest/unittest.dart';
+
+String getStackTraceString() {
+  try {
+    throw '';
+  } catch (_, stackTrace) {
+    return stackTrace.toString();
+  }
+}
+
+StackTrace getStackTraceObject() {
+  try {
+    throw '';
+  } catch (_, stackTrace) {
+    return stackTrace;
+  }
+}
+
+Trace getCurrentTrace([int level]) => new Trace.current(level);
+
+Trace nestedGetCurrentTrace(int level) => getCurrentTrace(level);
+
+void main() {
+  test('parses a stack trace correctly', () {
+    var trace = new Trace.parse('''
+#0      Foo._bar (file:///home/nweiz/code/stuff.dart:42:21)
+#1      zip.<anonymous closure>.zap (dart:async:0:2)
+#2      zip.<anonymous closure>.zap (http://pub.dartlang.org/thing.dart:1:100)
+''');
+
+    expect(trace.frames[0].uri,
+        equals(new Uri.fromString("file:///home/nweiz/code/stuff.dart")));
+    expect(trace.frames[1].uri, equals(new Uri.fromString("dart:async")));
+    expect(trace.frames[2].uri,
+        equals(new Uri.fromString("http://pub.dartlang.org/thing.dart")));
+  });
+
+  test('parses a real stack trace correctly', () {
+    var trace = new Trace.parse(getStackTraceString());
+    // TODO(nweiz): use URL-style paths when such a thing exists.
+    var builder = new path.Builder(style: path.Style.posix);
+    expect(builder.basename(trace.frames.first.uri.path),
+        equals('trace_test.dart'));
+    expect(trace.frames.first.member, equals('getStackTraceString'));
+  });
+
+  test('converts from a native stack trace correctly', () {
+    var trace = new Trace.from(getStackTraceObject());
+    // TODO(nweiz): use URL-style paths when such a thing exists.
+    var builder = new path.Builder(style: path.Style.posix);
+    expect(builder.basename(trace.frames.first.uri.path),
+        equals('trace_test.dart'));
+    expect(trace.frames.first.member, equals('getStackTraceObject'));
+  });
+
+  group('.current()', () {
+    test('with no argument returns a trace starting at the current frame', () {
+      var trace = new Trace.current();
+      expect(trace.frames.first.member, equals('main.<fn>.<fn>'));
+    });
+
+    test('at level 0 returns a trace starting at the current frame', () {
+      var trace = new Trace.current(0);
+      expect(trace.frames.first.member, equals('main.<fn>.<fn>'));
+    });
+
+    test('at level 1 returns a trace starting at the parent frame', () {
+      var trace = getCurrentTrace(1);
+      expect(trace.frames.first.member, equals('main.<fn>.<fn>'));
+    });
+
+    test('at level 2 returns a trace starting at the grandparent frame', () {
+      var trace = nestedGetCurrentTrace(2);
+      expect(trace.frames.first.member, equals('main.<fn>.<fn>'));
+    });
+
+    test('throws an ArgumentError for negative levels', () {
+      expect(() => new Trace.current(-1), throwsArgumentError);
+    });
+  });
+
+  test('.toString() nicely formats the stack trace', () {
+    var absolute = path.absolute(path.join('foo', 'bar.dart'));
+    var trace = new Trace.parse('''
+#0      Foo._bar (file://$absolute:42:21)
+#1      zip.<anonymous closure>.zap (dart:async:0:2)
+#2      zip.<anonymous closure>.zap (http://pub.dartlang.org/thing.dart:1:100)
+''');
+
+    expect(trace.toString(), equals('''
+${path.join('foo', 'bar.dart')} 42:21                        Foo._bar
+dart:async                                zip.<fn>.zap
+http://pub.dartlang.org/thing.dart 1:100  zip.<fn>.zap
+'''));
+  });
+
+  test('.stackTrace forwards to .toString()', () {
+    var trace = new Trace.current();
+    expect(trace.stackTrace, equals(trace.toString()));
+  });
+
+  test('.fullStackTrace forwards to .toString()', () {
+    var trace = new Trace.current();
+    expect(trace.fullStackTrace, equals(trace.toString()));
+  });
+
+  test('.terse folds core frames together bottom-up', () {
+    var trace = new Trace.parse('''
+#0 notCore (foo.dart:42:21)
+#1 top (dart:async:0:2)
+#2 bottom (dart:core:1:100)
+#3 alsoNotCore (bar.dart:10:20)
+#4 top (dart:io:5:10)
+#5 bottom (dart:async-patch:9:11)
+''');
+
+    expect(trace.terse.toString(), equals('''
+foo.dart 42:21  notCore
+dart:core       bottom
+bar.dart 10:20  alsoNotCore
+dart:async      bottom
+'''));
+  });
+}