LCOV - code coverage report
Current view: top level - stack_trace-1.10.0/lib/src - trace.dart (source / functions) Hit Total Coverage
Test: lcov.info Lines: 59 114 51.8 %
Date: 2021-11-28 14:37:50 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
       2             : // for details. All rights reserved. Use of this source code is governed by a
       3             : // BSD-style license that can be found in the LICENSE file.
       4             : 
       5             : import 'dart:math' as math;
       6             : 
       7             : import 'chain.dart';
       8             : import 'frame.dart';
       9             : import 'lazy_trace.dart';
      10             : import 'unparsed_frame.dart';
      11             : import 'utils.dart';
      12             : import 'vm_trace.dart';
      13             : 
      14          33 : final _terseRegExp = RegExp(r'(-patch)?([/\\].*)?$');
      15             : 
      16             : /// A RegExp to match V8's stack traces.
      17             : ///
      18             : /// V8's traces start with a line that's either just "Error" or else is a
      19             : /// description of the exception that occurred. That description can be multiple
      20             : /// lines, so we just look for any line other than the first that begins with
      21             : /// three or four spaces and "at".
      22          33 : final _v8Trace = RegExp(r'\n    ?at ');
      23             : 
      24             : /// A RegExp to match indidual lines of V8's stack traces.
      25             : ///
      26             : /// This is intended to filter out the leading exception details of the trace
      27             : /// though it is possible for the message to match this as well.
      28           0 : final _v8TraceLine = RegExp(r'    ?at ');
      29             : 
      30             : /// A RegExp to match Firefox's eval and Function stack traces.
      31             : ///
      32             : /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack
      33             : ///
      34             : /// These stack traces looks like:
      35             : ///     anonymous/<@https://example.com/stuff.js line 693 > Function:3:40
      36             : ///     anonymous/<@https://example.com/stuff.js line 693 > eval:3:40
      37          33 : final _firefoxEvalTrace = RegExp(r'@\S+ line \d+ >.* (Function|eval):\d+:\d+');
      38             : 
      39             : /// A RegExp to match Firefox and Safari's stack traces.
      40             : ///
      41             : /// Firefox and Safari have very similar stack trace formats, so we use the same
      42             : /// logic for parsing them.
      43             : ///
      44             : /// Firefox's trace frames start with the name of the function in which the
      45             : /// error occurred, possibly including its parameters inside `()`. For example,
      46             : /// `.VW.call$0("arg")@https://example.com/stuff.dart.js:560`.
      47             : ///
      48             : /// Safari traces occasionally don't include the initial method name followed by
      49             : /// "@", and they always have both the line and column number (or just a
      50             : /// trailing colon if no column number is available). They can also contain
      51             : /// empty lines or lines consisting only of `[native code]`.
      52          33 : final _firefoxSafariTrace = RegExp(
      53             :     r'^'
      54             :     r'(' // Member description. Not present in some Safari frames.
      55             :     r'([.0-9A-Za-z_$/<]|\(.*\))*' // Member name and arguments.
      56             :     r'@'
      57             :     r')?'
      58             :     r'[^\s]*' // Frame URL.
      59             :     r':\d*' // Line or column number. Some older frames only have a line number.
      60             :     r'$',
      61             :     multiLine: true);
      62             : 
      63             : /// A RegExp to match this package's stack traces.
      64          22 : final _friendlyTrace =
      65          11 :     RegExp(r'^[^\s<][^\s]*( \d+(:\d+)?)?[ \t]+[^\s]+$', multiLine: true);
      66             : 
      67             : /// A stack trace, comprised of a list of stack frames.
      68             : class Trace implements StackTrace {
      69             :   /// The stack frames that comprise this stack trace.
      70             :   final List<Frame> frames;
      71             : 
      72             :   /// The original stack trace from which this trace was parsed.
      73             :   final StackTrace original;
      74             : 
      75             :   /// Returns a human-readable representation of [stackTrace]. If [terse] is
      76             :   /// set, this folds together multiple stack frames from the Dart core
      77             :   /// libraries, so that only the core library method directly called from user
      78             :   /// code is visible (see [Trace.terse]).
      79           0 :   static String format(StackTrace stackTrace, {bool terse = true}) {
      80           0 :     var trace = Trace.from(stackTrace);
      81           0 :     if (terse) trace = trace.terse;
      82           0 :     return trace.toString();
      83             :   }
      84             : 
      85             :   /// Returns the current stack trace.
      86             :   ///
      87             :   /// By default, the first frame of this trace will be the line where
      88             :   /// [Trace.current] is called. If [level] is passed, the trace will start that
      89             :   /// many frames up instead.
      90          11 :   factory Trace.current([int level = 0]) {
      91          11 :     if (level < 0) {
      92           0 :       throw ArgumentError('Argument [level] must be greater than or equal '
      93             :           'to 0.');
      94             :     }
      95             : 
      96          22 :     var trace = Trace.from(StackTrace.current);
      97          22 :     return LazyTrace(() {
      98             :       // JS includes a frame for the call to StackTrace.current, but the VM
      99             :       // doesn't, so we skip an extra frame in a JS context.
     100          55 :       return Trace(trace.frames.skip(level + (inJS ? 2 : 1)),
     101          22 :           original: trace.original.toString());
     102             :     });
     103             :   }
     104             : 
     105             :   /// Returns a new stack trace containing the same data as [trace].
     106             :   ///
     107             :   /// If [trace] is a native [StackTrace], its data will be parsed out; if it's
     108             :   /// a [Trace], it will be returned as-is.
     109          11 :   factory Trace.from(StackTrace trace) {
     110          11 :     if (trace is Trace) return trace;
     111          11 :     if (trace is Chain) return trace.toTrace();
     112          44 :     return LazyTrace(() => Trace.parse(trace.toString()));
     113             :   }
     114             : 
     115             :   /// Parses a string representation of a stack trace.
     116             :   ///
     117             :   /// [trace] should be formatted in the same way as a Dart VM or browser stack
     118             :   /// trace. If it's formatted as a stack chain, this will return the equivalent
     119             :   /// of [Chain.toTrace].
     120          11 :   factory Trace.parse(String trace) {
     121             :     try {
     122          11 :       if (trace.isEmpty) return Trace(<Frame>[]);
     123          22 :       if (trace.contains(_v8Trace)) return Trace.parseV8(trace);
     124          11 :       if (trace.contains('\tat ')) return Trace.parseJSCore(trace);
     125          22 :       if (trace.contains(_firefoxSafariTrace) ||
     126          22 :           trace.contains(_firefoxEvalTrace)) {
     127           0 :         return Trace.parseFirefox(trace);
     128             :       }
     129          11 :       if (trace.contains(chainGap)) return Chain.parse(trace).toTrace();
     130          22 :       if (trace.contains(_friendlyTrace)) {
     131           0 :         return Trace.parseFriendly(trace);
     132             :       }
     133             : 
     134             :       // Default to parsing the stack trace as a VM trace. This is also hit on
     135             :       // IE and Safari, where the stack trace is just an empty string (issue
     136             :       // 11257).
     137          11 :       return Trace.parseVM(trace);
     138           0 :     } on FormatException catch (error) {
     139           0 :       throw FormatException('${error.message}\nStack trace:\n$trace');
     140             :     }
     141             :   }
     142             : 
     143             :   /// Parses a string representation of a Dart VM stack trace.
     144          33 :   Trace.parseVM(String trace) : this(_parseVM(trace), original: trace);
     145             : 
     146          11 :   static List<Frame> _parseVM(String trace) {
     147             :     // Ignore [vmChainGap]. This matches the behavior of
     148             :     // `Chain.parse().toTrace()`.
     149             :     var lines = trace
     150          11 :         .trim()
     151          22 :         .replaceAll(vmChainGap, '')
     152          11 :         .split('\n')
     153          33 :         .where((line) => line.isNotEmpty);
     154             : 
     155          11 :     if (lines.isEmpty) {
     156           0 :       return [];
     157             :     }
     158             : 
     159             :     var frames = lines
     160          33 :         .take(lines.length - 1)
     161          33 :         .map((line) => Frame.parseVM(line))
     162          11 :         .toList();
     163             : 
     164             :     // TODO(nweiz): Remove this when issue 23614 is fixed.
     165          22 :     if (!lines.last.endsWith('.da')) {
     166          33 :       frames.add(Frame.parseVM(lines.last));
     167             :     }
     168             : 
     169             :     return frames;
     170             :   }
     171             : 
     172             :   /// Parses a string representation of a Chrome/V8 stack trace.
     173           0 :   Trace.parseV8(String trace)
     174           0 :       : this(
     175             :             trace
     176           0 :                 .split('\n')
     177           0 :                 .skip(1)
     178             :                 // It's possible that an Exception's description contains a line
     179             :                 // that looks like a V8 trace line, which will screw this up.
     180             :                 // Unfortunately, that's impossible to detect.
     181           0 :                 .skipWhile((line) => !line.startsWith(_v8TraceLine))
     182           0 :                 .map((line) => Frame.parseV8(line)),
     183             :             original: trace);
     184             : 
     185             :   /// Parses a string representation of a JavaScriptCore stack trace.
     186           0 :   Trace.parseJSCore(String trace)
     187           0 :       : this(
     188             :             trace
     189           0 :                 .split('\n')
     190           0 :                 .where((line) => line != '\tat ')
     191           0 :                 .map((line) => Frame.parseV8(line)),
     192             :             original: trace);
     193             : 
     194             :   /// Parses a string representation of an Internet Explorer stack trace.
     195             :   ///
     196             :   /// IE10+ traces look just like V8 traces. Prior to IE10, stack traces can't
     197             :   /// be retrieved.
     198           0 :   Trace.parseIE(String trace) : this.parseV8(trace);
     199             : 
     200             :   /// Parses a string representation of a Firefox stack trace.
     201           0 :   Trace.parseFirefox(String trace)
     202           0 :       : this(
     203             :             trace
     204           0 :                 .trim()
     205           0 :                 .split('\n')
     206           0 :                 .where((line) => line.isNotEmpty && line != '[native code]')
     207           0 :                 .map((line) => Frame.parseFirefox(line)),
     208             :             original: trace);
     209             : 
     210             :   /// Parses a string representation of a Safari stack trace.
     211           0 :   Trace.parseSafari(String trace) : this.parseFirefox(trace);
     212             : 
     213             :   /// Parses a string representation of a Safari 6.1+ stack trace.
     214           0 :   @Deprecated('Use Trace.parseSafari instead.')
     215           0 :   Trace.parseSafari6_1(String trace) : this.parseSafari(trace);
     216             : 
     217             :   /// Parses a string representation of a Safari 6.0 stack trace.
     218           0 :   @Deprecated('Use Trace.parseSafari instead.')
     219             :   Trace.parseSafari6_0(String trace)
     220           0 :       : this(
     221             :             trace
     222           0 :                 .trim()
     223           0 :                 .split('\n')
     224           0 :                 .where((line) => line != '[native code]')
     225           0 :                 .map((line) => Frame.parseFirefox(line)),
     226             :             original: trace);
     227             : 
     228             :   /// Parses this package's string representation of a stack trace.
     229             :   ///
     230             :   /// This also parses string representations of [Chain]s. They parse to the
     231             :   /// same trace that [Chain.toTrace] would return.
     232           0 :   Trace.parseFriendly(String trace)
     233           0 :       : this(
     234           0 :             trace.isEmpty
     235           0 :                 ? []
     236             :                 : trace
     237           0 :                     .trim()
     238           0 :                     .split('\n')
     239             :                     // Filter out asynchronous gaps from [Chain]s.
     240           0 :                     .where((line) => !line.startsWith('====='))
     241           0 :                     .map((line) => Frame.parseFriendly(line)),
     242             :             original: trace);
     243             : 
     244             :   /// Returns a new [Trace] comprised of [frames].
     245          11 :   Trace(Iterable<Frame> frames, {String? original})
     246          11 :       : frames = List<Frame>.unmodifiable(frames),
     247          11 :         original = StackTrace.fromString(original ?? '');
     248             : 
     249             :   /// Returns a VM-style [StackTrace] object.
     250             :   ///
     251             :   /// The return value's [toString] method will always return a string
     252             :   /// representation in the Dart VM's stack trace format, regardless of what
     253             :   /// platform is being used.
     254           0 :   StackTrace get vmTrace => VMTrace(frames);
     255             : 
     256             :   /// Returns a terser version of [this].
     257             :   ///
     258             :   /// This is accomplished by folding together multiple stack frames from the
     259             :   /// core library or from this package, as in [foldFrames]. Remaining core
     260             :   /// library frames have their libraries, "-patch" suffixes, and line numbers
     261             :   /// removed. If the outermost frame of the stack trace is a core library
     262             :   /// frame, it's removed entirely.
     263             :   ///
     264             :   /// This won't do anything with a raw JavaScript trace, since there's no way
     265             :   /// to determine which frames come from which Dart libraries. However, the
     266             :   /// [`source_map_stack_trace`][source_map_stack_trace] package can be used to
     267             :   /// convert JavaScript traces into Dart-style traces.
     268             :   ///
     269             :   /// [source_map_stack_trace]: https://pub.dev/packages/source_map_stack_trace
     270             :   ///
     271             :   /// For custom folding, see [foldFrames].
     272           0 :   Trace get terse => foldFrames((_) => false, terse: true);
     273             : 
     274             :   /// Returns a new [Trace] based on [this] where multiple stack frames matching
     275             :   /// [predicate] are folded together.
     276             :   ///
     277             :   /// This means that whenever there are multiple frames in a row that match
     278             :   /// [predicate], only the last one is kept. This is useful for limiting the
     279             :   /// amount of library code that appears in a stack trace by only showing user
     280             :   /// code and code that's called by user code.
     281             :   ///
     282             :   /// If [terse] is true, this will also fold together frames from the core
     283             :   /// library or from this package, simplify core library frames, and
     284             :   /// potentially remove the outermost frame as in [Trace.terse].
     285          11 :   Trace foldFrames(bool Function(Frame) predicate, {bool terse = false}) {
     286             :     if (terse) {
     287             :       var oldPredicate = predicate;
     288          11 :       predicate = (frame) {
     289             :         if (oldPredicate(frame)) return true;
     290             : 
     291          11 :         if (frame.isCore) return true;
     292          22 :         if (frame.package == 'stack_trace') return true;
     293             : 
     294             :         // Ignore async stack frames without any line or column information.
     295             :         // These come from the VM's async/await implementation and represent
     296             :         // internal frames. They only ever show up in stack chains and are
     297             :         // always surrounded by other traces that are actually useful, so we can
     298             :         // just get rid of them.
     299             :         // TODO(nweiz): Get rid of this logic some time after issue 22009 is
     300             :         // fixed.
     301          22 :         if (!frame.member!.contains('<async>')) return false;
     302           0 :         return frame.line == null;
     303             :       };
     304             :     }
     305             : 
     306          11 :     var newFrames = <Frame>[];
     307          33 :     for (var frame in frames.reversed) {
     308          11 :       if (frame is UnparsedFrame || !predicate(frame)) {
     309          11 :         newFrames.add(frame);
     310          22 :       } else if (newFrames.isEmpty || !predicate(newFrames.last)) {
     311          66 :         newFrames.add(Frame(frame.uri, frame.line, frame.column, frame.member));
     312             :       }
     313             :     }
     314             : 
     315             :     if (terse) {
     316          22 :       newFrames = newFrames.map((frame) {
     317          11 :         if (frame is UnparsedFrame || !predicate(frame)) return frame;
     318          33 :         var library = frame.library.replaceAll(_terseRegExp, '');
     319          33 :         return Frame(Uri.parse(library), null, null, frame.member);
     320          11 :       }).toList();
     321             : 
     322          33 :       if (newFrames.length > 1 && predicate(newFrames.first)) {
     323          11 :         newFrames.removeAt(0);
     324             :       }
     325             :     }
     326             : 
     327          44 :     return Trace(newFrames.reversed, original: original.toString());
     328             :   }
     329             : 
     330           0 :   @override
     331             :   String toString() {
     332             :     // Figure out the longest path so we know how much to pad.
     333             :     var longest =
     334           0 :         frames.map((frame) => frame.location.length).fold(0, math.max);
     335             : 
     336             :     // Print out the stack trace nicely formatted.
     337           0 :     return frames.map((frame) {
     338           0 :       if (frame is UnparsedFrame) return '$frame\n';
     339           0 :       return '${frame.location.padRight(longest)}  ${frame.member}\n';
     340           0 :     }).join();
     341             :   }
     342             : }

Generated by: LCOV version 1.14