| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2016, 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 'package:js/js.dart'; |
| 8 |
| 9 import 'package:dart_style/dart_style.dart'; |
| 10 |
| 11 @JS() |
| 12 @anonymous |
| 13 class FormatResult { |
| 14 external factory FormatResult({String code, String error}); |
| 15 external String get code; |
| 16 external String get error; |
| 17 } |
| 18 |
| 19 @JS('exports.formatCode') |
| 20 external set formatCode(Function formatter); |
| 21 |
| 22 void main() { |
| 23 formatCode = allowInterop((String source) { |
| 24 var formatter = new DartFormatter(); |
| 25 |
| 26 var exception; |
| 27 try { |
| 28 return new FormatResult(code: new DartFormatter().format(source)); |
| 29 } on FormatterException catch (err) { |
| 30 // Couldn't parse it as a compilation unit. |
| 31 exception = err; |
| 32 } |
| 33 |
| 34 // Maybe it's a statement. |
| 35 try { |
| 36 return new FormatResult(code: formatter.formatStatement(source)); |
| 37 } on FormatterException catch (err) { |
| 38 // There is an error when parsing it both as a compilation unit and a |
| 39 // statement, so we aren't sure which one the user intended. As a |
| 40 // heuristic, we'll choose that whichever one we managed to parse more of |
| 41 // before hitting an error is probably the right one. |
| 42 if (_firstOffset(exception) < _firstOffset(err)) { |
| 43 exception = err; |
| 44 } |
| 45 } |
| 46 |
| 47 // If we get here, it couldn't be parsed at all. |
| 48 return new FormatResult(code: source, error: "$exception"); |
| 49 }); |
| 50 } |
| 51 |
| 52 /// Returns the offset of the error nearest the beginning of the file out of |
| 53 /// all the errors in [exception]. |
| 54 int _firstOffset(FormatterException exception) => |
| 55 exception.errors.map((error) => error.offset).reduce(math.min); |
| OLD | NEW |