Update lints & Travis-CI (#786)
* Enable and fix all lints associated with dartfmt --fix
* Enable and fix pedantic lints
* Travis: run tests on oldest supported SDK
Bump minimum SDK to Dart 2.1.0
diff --git a/.travis.yml b/.travis.yml
index 8b6048d..2477385 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,9 @@
language: dart
-sudo: false
+
dart:
+ - 2.1.0
- dev
+
dart_task:
- test
- dartfmt
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 28b5d21..767a727 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
* Add support for spreads inside collections (#778).
* Add support for `if` and `for` elements inside collections (#779).
+* Require at least Dart 2.1.0.
# 1.2.4
diff --git a/analysis_options.yaml b/analysis_options.yaml
index e4b1b8f..14bcb12 100644
--- a/analysis_options.yaml
+++ b/analysis_options.yaml
@@ -1,3 +1,9 @@
+include: package:pedantic/analysis_options.yaml
linter:
rules:
+ - prefer_equal_for_default_values
+ - prefer_generic_function_type_aliases
+ - slash_for_doc_comments
- unawaited_futures
+ - unnecessary_const
+ - unnecessary_new
diff --git a/benchmark/benchmark.dart b/benchmark/benchmark.dart
index ab960f5..117558c 100644
--- a/benchmark/benchmark.dart
+++ b/benchmark/benchmark.dart
@@ -25,7 +25,7 @@
// Run the benchmark several times. This ensures the VM is warmed up and lets
// us see how much variance there is.
for (var i = 0; i <= NUM_TRIALS; i++) {
- var start = new DateTime.now();
+ var start = DateTime.now();
// For a single benchmark, format the source multiple times.
var result;
@@ -34,7 +34,7 @@
}
var elapsed =
- new DateTime.now().difference(start).inMilliseconds / FORMATS_PER_TRIAL;
+ DateTime.now().difference(start).inMilliseconds / FORMATS_PER_TRIAL;
// Keep track of the best run so far.
if (elapsed >= best) continue;
@@ -58,7 +58,7 @@
String loadFile(String name) {
var path = p.join(p.dirname(p.fromUri(Platform.script)), name);
- return new File(path).readAsStringSync();
+ return File(path).readAsStringSync();
}
void printResult(String label, double time) {
@@ -76,6 +76,6 @@
}
String formatSource() {
- var formatter = new DartFormatter();
+ var formatter = DartFormatter();
return formatter.format(source);
}
diff --git a/bin/format.dart b/bin/format.dart
index 04e4f0c..b90688e 100644
--- a/bin/format.dart
+++ b/bin/format.dart
@@ -18,7 +18,7 @@
const version = "1.2.4";
void main(List<String> args) {
- var parser = new ArgParser(allowTrailingOptions: true);
+ var parser = ArgParser(allowTrailingOptions: true);
parser.addSeparator("Common options:");
parser.addFlag("help",
@@ -131,11 +131,11 @@
}
if (argResults["profile"]) {
- reporter = new ProfileReporter(reporter);
+ reporter = ProfileReporter(reporter);
}
if (argResults["set-exit-if-changed"]) {
- reporter = new SetExitReporter(reporter);
+ reporter = SetExitReporter(reporter);
}
int pageWidth;
@@ -151,7 +151,7 @@
int indent;
try {
indent = int.parse(argResults["indent"]);
- if (indent < 0 || indent.toInt() != indent) throw new FormatException();
+ if (indent < 0 || indent.toInt() != indent) throw FormatException();
} on FormatException catch (_) {
usageError(
parser,
@@ -173,11 +173,11 @@
}
}
- if (argResults.wasParsed("stdin-name") && !argResults.rest.isEmpty) {
+ if (argResults.wasParsed("stdin-name") && argResults.rest.isNotEmpty) {
usageError(parser, "Cannot pass --stdin-name when not reading from stdin.");
}
- var options = new FormatterOptions(reporter,
+ var options = FormatterOptions(reporter,
indent: indent,
pageWidth: pageWidth,
followLinks: followLinks,
@@ -199,7 +199,7 @@
var coordinates = selection.split(":");
if (coordinates.length != 2) {
- throw new FormatException(
+ throw FormatException(
'Selection should be a colon-separated pair of integers, "123:45".');
}
@@ -216,15 +216,15 @@
selectionLength = selection[1];
}
- var input = new StringBuffer();
- stdin.transform(new Utf8Decoder()).listen(input.write, onDone: () {
- var formatter = new DartFormatter(
+ var input = StringBuffer();
+ stdin.transform(Utf8Decoder()).listen(input.write, onDone: () {
+ var formatter = DartFormatter(
indent: options.indent,
pageWidth: options.pageWidth,
fixes: options.fixes);
try {
options.reporter.beforeFile(null, name);
- var source = new SourceCode(input.toString(),
+ var source = SourceCode(input.toString(),
uri: name,
selectionStart: selectionStart,
selectionLength: selectionLength);
@@ -248,7 +248,7 @@
/// Formats all of the files and directories given by [paths].
void formatPaths(FormatterOptions options, List<String> paths) {
for (var path in paths) {
- var directory = new Directory(path);
+ var directory = Directory(path);
if (directory.existsSync()) {
if (!processDirectory(options, directory)) {
exitCode = 65;
@@ -256,7 +256,7 @@
continue;
}
- var file = new File(path);
+ var file = File(path);
if (file.existsSync()) {
if (!processFile(options, file)) {
exitCode = 65;
diff --git a/example/format.dart b/example/format.dart
index 6d3ea61..6edbfe0 100644
--- a/example/format.dart
+++ b/example/format.dart
@@ -35,7 +35,7 @@
void runFormatter(String source, int pageWidth, {bool isCompilationUnit}) {
try {
- var formatter = new DartFormatter(pageWidth: pageWidth);
+ var formatter = DartFormatter(pageWidth: pageWidth);
var result;
if (isCompilationUnit) {
@@ -61,7 +61,7 @@
/// Runs the formatter test starting on [line] at [path] inside the "test"
/// directory.
void runTest(String path, int line) {
- var indentPattern = new RegExp(r"^\(indent (\d+)\)\s*");
+ var indentPattern = RegExp(r"^\(indent (\d+)\)\s*");
// Locate the "test" directory. Use mirrors so that this works with the test
// package, which loads this suite into an isolate.
@@ -72,7 +72,7 @@
.path),
"../test");
- var lines = new File(p.join(testDir, path)).readAsLinesSync();
+ var lines = File(p.join(testDir, path)).readAsLinesSync();
// The first line may have a "|" to indicate the page width.
var pageWidth = 80;
@@ -121,8 +121,7 @@
var expected =
_extractSelection(expectedOutput, isCompilationUnit: isCompilationUnit);
- var formatter =
- new DartFormatter(pageWidth: pageWidth, indent: leadingIndent);
+ var formatter = DartFormatter(pageWidth: pageWidth, indent: leadingIndent);
var actual = formatter.formatSource(inputCode);
@@ -151,14 +150,14 @@
/// Given a source string that contains ‹ and › to indicate a selection, returns
/// a [SourceCode] with the text (with the selection markers removed) and the
/// correct selection range.
-SourceCode _extractSelection(String source, {bool isCompilationUnit: false}) {
+SourceCode _extractSelection(String source, {bool isCompilationUnit = false}) {
var start = source.indexOf("‹");
source = source.replaceAll("‹", "");
var end = source.indexOf("›");
source = source.replaceAll("›", "");
- return new SourceCode(source,
+ return SourceCode(source,
isCompilationUnit: isCompilationUnit,
selectionStart: start == -1 ? null : start,
selectionLength: end == -1 ? null : end - start);
diff --git a/lib/src/argument_list_visitor.dart b/lib/src/argument_list_visitor.dart
index c17264c..25bbb75 100644
--- a/lib/src/argument_list_visitor.dart
+++ b/lib/src/argument_list_visitor.dart
@@ -57,7 +57,7 @@
_arguments._blocks.isNotEmpty || _functions != null;
factory ArgumentListVisitor(SourceVisitor visitor, ArgumentList node) {
- return new ArgumentListVisitor.forArguments(
+ return ArgumentListVisitor.forArguments(
visitor, node.leftParenthesis, node.rightParenthesis, node.arguments);
}
@@ -147,14 +147,8 @@
if (functionsStart == null) {
// No functions, so there is just a single argument list.
- return new ArgumentListVisitor._(
- visitor,
- leftParenthesis,
- rightParenthesis,
- arguments,
- new ArgumentSublist(arguments, arguments),
- null,
- null);
+ return ArgumentListVisitor._(visitor, leftParenthesis, rightParenthesis,
+ arguments, ArgumentSublist(arguments, arguments), null, null);
}
// Split the arguments into two independent argument lists with the
@@ -163,14 +157,14 @@
var functions = arguments.sublist(functionsStart, functionsEnd);
var argumentsAfter = arguments.skip(functionsEnd).toList();
- return new ArgumentListVisitor._(
+ return ArgumentListVisitor._(
visitor,
leftParenthesis,
rightParenthesis,
arguments,
- new ArgumentSublist(arguments, argumentsBefore),
+ ArgumentSublist(arguments, argumentsBefore),
functions,
- new ArgumentSublist(arguments, argumentsAfter));
+ ArgumentSublist(arguments, argumentsAfter));
}
ArgumentListVisitor._(
@@ -370,7 +364,7 @@
blocks.clear();
}
- return new ArgumentSublist._(
+ return ArgumentSublist._(
allArguments, positional, named, blocks, leadingBlocks, trailingBlocks);
}
@@ -379,7 +373,7 @@
void visit(SourceVisitor visitor) {
if (_blocks.isNotEmpty) {
- _blockRule = new Rule(Cost.splitBlocks);
+ _blockRule = Rule(Cost.splitBlocks);
}
var rule = _visitPositional(visitor);
@@ -394,7 +388,7 @@
// Only count the blocks in the positional rule.
var leadingBlocks = math.min(_leadingBlocks, _positional.length);
var trailingBlocks = math.max(_trailingBlocks - _named.length, 0);
- var rule = new PositionalRule(_blockRule, leadingBlocks, trailingBlocks);
+ var rule = PositionalRule(_blockRule, leadingBlocks, trailingBlocks);
_visitArguments(visitor, _positional, rule);
return rule;
@@ -407,7 +401,7 @@
// Only count the blocks in the named rule.
var leadingBlocks = math.max(_leadingBlocks - _positional.length, 0);
var trailingBlocks = math.min(_trailingBlocks, _named.length);
- var namedRule = new NamedRule(_blockRule, leadingBlocks, trailingBlocks);
+ var namedRule = NamedRule(_blockRule, leadingBlocks, trailingBlocks);
// Let the positional args force the named ones to split.
if (positionalRule != null) {
diff --git a/lib/src/call_chain_visitor.dart b/lib/src/call_chain_visitor.dart
index b7289b0..936beee 100644
--- a/lib/src/call_chain_visitor.dart
+++ b/lib/src/call_chain_visitor.dart
@@ -157,7 +157,7 @@
// See if this call is a method call whose arguments are block formatted.
var isBlockCall = false;
if (call is MethodInvocation) {
- var args = new ArgumentListVisitor(visitor, call.argumentList);
+ var args = ArgumentListVisitor(visitor, call.argumentList);
isBlockCall = args.hasBlockArguments;
}
@@ -187,7 +187,7 @@
calls.remove(hangingCall);
}
- return new CallChainVisitor._(
+ return CallChainVisitor._(
visitor, target, properties, calls, blockCalls, hangingCall);
}
@@ -214,7 +214,7 @@
if (splitOnTarget) {
if (_properties.length > 1) {
- _propertyRule = new PositionalRule(null, 0, 0);
+ _propertyRule = PositionalRule(null, 0, 0);
_visitor.builder.startLazyRule(_propertyRule);
} else {
_enableRule(lazy: true);
@@ -230,7 +230,7 @@
_writeCall(_properties.single);
} else if (_properties.length > 1) {
if (!splitOnTarget) {
- _propertyRule = new PositionalRule(null, 0, 0);
+ _propertyRule = PositionalRule(null, 0, 0);
_visitor.builder.startRule(_propertyRule);
}
@@ -432,11 +432,11 @@
}
/// Creates a new method chain [Rule] if one is not already active.
- void _enableRule({bool lazy: false}) {
+ void _enableRule({bool lazy = false}) {
if (_ruleEnabled) return;
// If the properties split, force the calls to split too.
- var rule = new Rule();
+ var rule = Rule();
if (_propertyRule != null) _propertyRule.setNamedArgsRule(rule);
if (lazy) {
diff --git a/lib/src/chunk.dart b/lib/src/chunk.dart
index d1f33ca..5dfe201 100644
--- a/lib/src/chunk.dart
+++ b/lib/src/chunk.dart
@@ -225,7 +225,7 @@
/// Turns this chunk into one that can contain a block of child chunks.
void makeBlock(Chunk blockArgument) {
assert(_block == null);
- _block = new ChunkBlock(blockArgument);
+ _block = ChunkBlock(blockArgument);
}
/// Returns `true` if the block body owned by this chunk should be expression
diff --git a/lib/src/chunk_builder.dart b/lib/src/chunk_builder.dart
index c6cb303..20c7505 100644
--- a/lib/src/chunk_builder.dart
+++ b/lib/src/chunk_builder.dart
@@ -16,14 +16,14 @@
import 'whitespace.dart';
/// Matches if the last character of a string is an identifier character.
-final _trailingIdentifierChar = new RegExp(r"[a-zA-Z0-9_]$");
+final _trailingIdentifierChar = RegExp(r"[a-zA-Z0-9_]$");
/// Matches a JavaDoc-style doc comment that starts with "/**" and ends with
/// "*/" or "**/".
-final _javaDocComment = new RegExp(r"^/\*\*([^*/][\s\S]*?)\*?\*/$");
+final _javaDocComment = RegExp(r"^/\*\*([^*/][\s\S]*?)\*?\*/$");
/// Matches the leading "*" in a line in the middle of a JavaDoc-style comment.
-var _javaDocLine = new RegExp(r"^\s*\*(.*)");
+var _javaDocLine = RegExp(r"^\s*\*(.*)");
/// Takes the incremental serialized output of [SourceVisitor]--the source text
/// along with any comments and preserved whitespace--and produces a coherent
@@ -66,7 +66,7 @@
/// the hard split appears. For example, a hard split in a positional
/// argument list needs to force the named arguments to split too, but we
/// don't create that rule until after the positional arguments are done.
- final _hardSplitRules = new Set<Rule>();
+ final _hardSplitRules = Set<Rule>();
/// The list of rules that are waiting until the next whitespace has been
/// written before they start.
@@ -76,7 +76,7 @@
final _openSpans = <OpenSpan>[];
/// The current state.
- final _nesting = new NestingBuilder();
+ final _nesting = NestingBuilder();
/// The stack of nesting levels where block arguments may start.
///
@@ -438,7 +438,7 @@
///
/// Each call to this needs a later matching call to [endSpan].
void startSpan([int cost = Cost.normal]) {
- _openSpans.add(new OpenSpan(_currentChunkIndex, cost));
+ _openSpans.add(OpenSpan(_currentChunkIndex, cost));
}
/// Ends the innermost span.
@@ -450,7 +450,7 @@
if (openSpan.start == end) return;
// Add the span to every chunk that can split it.
- var span = new Span(openSpan.cost);
+ var span = Span(openSpan.cost);
for (var i = openSpan.start; i < end; i++) {
var chunk = _chunks[i];
if (!chunk.rule.isHardened) chunk.spans.add(span);
@@ -461,7 +461,7 @@
///
/// If omitted, defaults to a new [Rule].
void startRule([Rule rule]) {
- if (rule == null) rule = new Rule();
+ if (rule == null) rule = Rule();
// If there are any pending lazy rules, start them now so that the proper
// stack ordering of rules is maintained.
@@ -489,7 +489,7 @@
///
/// If [rule] is omitted, defaults to a new [Rule].
void startLazyRule([Rule rule]) {
- if (rule == null) rule = new Rule();
+ if (rule == null) rule = Rule();
_lazyRules.add(rule);
}
@@ -580,8 +580,7 @@
var chunk = _chunks.last;
chunk.makeBlock(argumentChunk);
- var builder =
- new ChunkBuilder._(this, _formatter, _source, chunk.block.chunks);
+ var builder = ChunkBuilder._(this, _formatter, _source, chunk.block.chunks);
// A block always starts off indented one level.
builder.indent();
@@ -653,7 +652,7 @@
debug.log();
}
- var writer = new LineWriter(_formatter, _chunks);
+ var writer = LineWriter(_formatter, _chunks);
var result = writer.writeLines(_formatter.indent,
isCompilationUnit: _source.isCompilationUnit);
@@ -671,7 +670,7 @@
selectionLength = selectionEnd - selectionStart;
}
- return new SourceCode(result.text,
+ return SourceCode(result.text,
uri: _source.uri,
isCompilationUnit: _source.isCompilationUnit,
selectionStart: selectionStart,
@@ -822,10 +821,10 @@
/// If [flushLeft] is `true`, then the split will always cause the next line
/// to be at column zero. Otherwise, it uses the normal indentation and
/// nesting behavior.
- void _writeHardSplit({bool isDouble, bool flushLeft, bool nest: false}) {
+ void _writeHardSplit({bool isDouble, bool flushLeft, bool nest = false}) {
// A hard split overrides any other whitespace.
_pendingWhitespace = null;
- _writeSplit(new Rule.hard(),
+ _writeSplit(Rule.hard(),
flushLeft: flushLeft, isDouble: isDouble, nest: nest);
}
@@ -843,8 +842,8 @@
return null;
}
- _chunks.last.applySplit(rule, _nesting.indentation,
- nest ? _nesting.nesting : new NestingLevel(),
+ _chunks.last.applySplit(
+ rule, _nesting.indentation, nest ? _nesting.nesting : NestingLevel(),
flushLeft: flushLeft, isDouble: isDouble, space: space);
if (_chunks.last.rule.isHardened) _handleHardSplit();
@@ -857,7 +856,7 @@
if (_chunks.isNotEmpty && _chunks.last.canAddText) {
_chunks.last.appendText(text);
} else {
- _chunks.add(new Chunk(text));
+ _chunks.add(Chunk(text));
}
}
diff --git a/lib/src/dart_formatter.dart b/lib/src/dart_formatter.dart
index 4a3950c..4824302 100644
--- a/lib/src/dart_formatter.dart
+++ b/lib/src/dart_formatter.dart
@@ -37,7 +37,7 @@
/// The number of characters of indentation to prefix the output lines with.
final int indent;
- final Set<StyleFix> fixes = new Set();
+ final Set<StyleFix> fixes = Set();
/// Creates a new formatter for Dart code.
///
@@ -69,17 +69,16 @@
} else if (uri is String) {
// Do nothing.
} else {
- throw new ArgumentError("uri must be `null`, a Uri, or a String.");
+ throw ArgumentError("uri must be `null`, a Uri, or a String.");
}
- return formatSource(
- new SourceCode(source, uri: uri, isCompilationUnit: true))
+ return formatSource(SourceCode(source, uri: uri, isCompilationUnit: true))
.text;
}
/// Formats the given [source] string containing a single Dart statement.
String formatStatement(String source) {
- return formatSource(new SourceCode(source, isCompilationUnit: false)).text;
+ return formatSource(SourceCode(source, isCompilationUnit: false)).text;
}
/// Formats the given [source].
@@ -87,14 +86,14 @@
/// Returns a new [SourceCode] containing the formatted code and the resulting
/// selection, if any.
SourceCode formatSource(SourceCode source) {
- var errorListener = new ErrorListener();
+ var errorListener = ErrorListener();
// Tokenize the source.
- var reader = new CharSequenceReader(source.text);
- var stringSource = new StringSource(source.text, source.uri);
- var scanner = new Scanner(stringSource, reader, errorListener);
+ var reader = CharSequenceReader(source.text);
+ var stringSource = StringSource(source.text, source.uri);
+ var scanner = Scanner(stringSource, reader, errorListener);
var startToken = scanner.tokenize();
- var lineInfo = new LineInfo(scanner.lineStarts);
+ var lineInfo = LineInfo(scanner.lineStarts);
// Infer the line ending if not given one. Do it here since now we know
// where the lines start.
@@ -112,7 +111,7 @@
errorListener.throwIfErrors();
// Parse it.
- var parser = new Parser(stringSource, errorListener);
+ var parser = Parser(stringSource, errorListener);
parser.enableOptionalNewAndConst = true;
parser.enableSetLiterals = true;
parser.enableSpreadCollections = true;
@@ -127,27 +126,27 @@
// Make sure we consumed all of the source.
var token = node.endToken.next;
if (token.type != TokenType.EOF) {
- var error = new AnalysisError(
+ var error = AnalysisError(
stringSource,
token.offset,
math.max(token.length, 1),
ParserErrorCode.UNEXPECTED_TOKEN,
[token.lexeme]);
- throw new FormatterException([error]);
+ throw FormatterException([error]);
}
}
errorListener.throwIfErrors();
// Format it.
- var visitor = new SourceVisitor(this, lineInfo, source);
+ var visitor = SourceVisitor(this, lineInfo, source);
var output = visitor.run(node);
// Sanity check that only whitespace was changed if that's all we expect.
if (fixes.isEmpty &&
!string_compare.equalIgnoringWhitespace(source.text, output.text)) {
- throw new UnexpectedOutputException(source.text, output.text);
+ throw UnexpectedOutputException(source.text, output.text);
}
return output;
diff --git a/lib/src/debug.dart b/lib/src/debug.dart
index 67322ce..ea04a41 100644
--- a/lib/src/debug.dart
+++ b/lib/src/debug.dart
@@ -67,7 +67,7 @@
// Show the spans as vertical bands over their range (unless there are too
// many).
- var spanSet = new Set<Span>();
+ var spanSet = Set<Span>();
addSpans(List<Chunk> chunks) {
for (var chunk in chunks) {
spanSet.addAll(chunk.spans);
@@ -167,14 +167,14 @@
addChunk(chunks, "", i);
}
- var rowWidths = new List.filled(rows.first.length, 0);
+ var rowWidths = List.filled(rows.first.length, 0);
for (var row in rows) {
for (var i = 0; i < row.length; i++) {
rowWidths[i] = math.max(rowWidths[i], row[i].length);
}
}
- var buffer = new StringBuffer();
+ var buffer = StringBuffer();
for (var row in rows) {
for (var i = 0; i < row.length; i++) {
var cell = row[i].padRight(rowWidths[i]);
@@ -223,7 +223,7 @@
/// It will determine how best to split it into multiple lines of output and
/// return a single string that may contain one or more newline characters.
void dumpLines(List<Chunk> chunks, int firstLineIndent, SplitSet splits) {
- var buffer = new StringBuffer();
+ var buffer = StringBuffer();
writeIndent(indent) => buffer.write(gray("| " * (indent ~/ 2)));
diff --git a/lib/src/error_listener.dart b/lib/src/error_listener.dart
index 19e4076..bceb91e 100644
--- a/lib/src/error_listener.dart
+++ b/lib/src/error_listener.dart
@@ -25,6 +25,6 @@
void throwIfErrors() {
if (_errors.isEmpty) return;
- throw new FormatterException(_errors);
+ throw FormatterException(_errors);
}
}
diff --git a/lib/src/exceptions.dart b/lib/src/exceptions.dart
index 5494183..c517f40 100644
--- a/lib/src/exceptions.dart
+++ b/lib/src/exceptions.dart
@@ -18,7 +18,7 @@
/// Creates a human-friendly representation of the analysis errors.
String message({bool color}) {
- var buffer = new StringBuffer();
+ var buffer = StringBuffer();
buffer.writeln("Could not format because the source could not be parsed:");
// In case we get a huge series of cascaded errors, just show the first few.
@@ -35,7 +35,7 @@
source += " " * (error.offset + error.length - source.length);
}
- var file = new SourceFile.fromString(source, url: error.source.fullName);
+ var file = SourceFile.fromString(source, url: error.source.fullName);
var span = file.span(error.offset, error.offset + error.length);
if (buffer.isNotEmpty) buffer.writeln();
buffer.write(span.message(error.message, color: color));
diff --git a/lib/src/formatter_options.dart b/lib/src/formatter_options.dart
index 1edb15a..2940b79 100644
--- a/lib/src/formatter_options.dart
+++ b/lib/src/formatter_options.dart
@@ -29,9 +29,9 @@
final Iterable<StyleFix> fixes;
FormatterOptions(this.reporter,
- {this.indent: 0,
- this.pageWidth: 80,
- this.followLinks: false,
+ {this.indent = 0,
+ this.pageWidth = 80,
+ this.followLinks = false,
this.fixes});
}
@@ -39,17 +39,17 @@
abstract class OutputReporter {
/// Prints only the names of files whose contents are different from their
/// formatted version.
- static final OutputReporter dryRun = new _DryRunReporter();
+ static final OutputReporter dryRun = _DryRunReporter();
/// Prints the formatted results of each file to stdout.
- static final OutputReporter print = new _PrintReporter();
+ static final OutputReporter print = _PrintReporter();
/// Prints the formatted result and selection info of each file to stdout as
/// a JSON map.
- static final OutputReporter printJson = new _PrintJsonReporter();
+ static final OutputReporter printJson = _PrintJsonReporter();
/// Overwrites each file with its formatted result.
- static final OutputReporter overwrite = new _OverwriteReporter();
+ static final OutputReporter overwrite = _OverwriteReporter();
/// Describe the directory whose contents are about to be processed.
void showDirectory(String path) {}
@@ -200,7 +200,7 @@
/// Called when [file] is about to be formatted.
void beforeFile(File file, String label) {
super.beforeFile(file, label);
- _ongoing[label] = new DateTime.now();
+ _ongoing[label] = DateTime.now();
}
/// Describe the processed file at [path] whose formatted result is [output].
@@ -208,7 +208,7 @@
/// If the contents of the file are the same as the formatted output,
/// [changed] will be false.
void afterFile(File file, String label, SourceCode output, {bool changed}) {
- var elapsed = new DateTime.now().difference(_ongoing.remove(label));
+ var elapsed = DateTime.now().difference(_ongoing.remove(label));
if (elapsed.inMilliseconds >= 10) {
_elapsed[label] = elapsed;
} else {
diff --git a/lib/src/io.dart b/lib/src/io.dart
index 28f1a71..40fc1f7 100644
--- a/lib/src/io.dart
+++ b/lib/src/io.dart
@@ -22,7 +22,7 @@
options.reporter.showDirectory(directory.path);
var success = true;
- var shownHiddenPaths = new Set<String>();
+ var shownHiddenPaths = Set<String>();
for (var entry in directory.listSync(
recursive: true, followLinks: options.followLinks)) {
@@ -67,12 +67,12 @@
bool processFile(FormatterOptions options, File file, {String label}) {
if (label == null) label = file.path;
- var formatter = new DartFormatter(
+ var formatter = DartFormatter(
indent: options.indent,
pageWidth: options.pageWidth,
fixes: options.fixes);
try {
- var source = new SourceCode(file.readAsStringSync(), uri: file.path);
+ var source = SourceCode(file.readAsStringSync(), uri: file.path);
options.reporter.beforeFile(file, label);
var output = formatter.formatSource(source);
options.reporter
diff --git a/lib/src/line_splitting/line_splitter.dart b/lib/src/line_splitting/line_splitter.dart
index 420c509..95d545a 100644
--- a/lib/src/line_splitting/line_splitter.dart
+++ b/lib/src/line_splitting/line_splitter.dart
@@ -119,7 +119,7 @@
/// This is sorted lowest-cost first. This ensures that as soon as we find a
/// solution that fits in the page, we know it will be the lowest cost one
/// and can stop looking.
- final _queue = new SolveStateQueue();
+ final _queue = SolveStateQueue();
/// The lowest cost solution found so far.
SolveState _bestSolution;
@@ -128,7 +128,7 @@
/// page width.
LineSplitter(this.writer, List<Chunk> chunks, int blockIndentation,
int firstLineIndent,
- {bool flushLeft: false})
+ {bool flushLeft = false})
: chunks = chunks,
// Collect the set of rules that we need to select values for.
rules = chunks
@@ -163,7 +163,7 @@
/// first line of output with.
SplitSet apply() {
// Start with a completely unbound, unsplit solution.
- _queue.add(new SolveState(this, new RuleSet(rules.length)));
+ _queue.add(SolveState(this, RuleSet(rules.length)));
var attempts = 0;
while (_queue.isNotEmpty) {
diff --git a/lib/src/line_splitting/rule_set.dart b/lib/src/line_splitting/rule_set.dart
index 714875d..7011393 100644
--- a/lib/src/line_splitting/rule_set.dart
+++ b/lib/src/line_splitting/rule_set.dart
@@ -18,7 +18,7 @@
class RuleSet {
List<int> _values;
- RuleSet(int numRules) : this._(new List(numRules));
+ RuleSet(int numRules) : this._(List(numRules));
RuleSet._(this._values);
@@ -53,7 +53,7 @@
}
/// Creates a new [RuleSet] with the same bound rule values as this one.
- RuleSet clone() => new RuleSet._(_values.toList(growable: false));
+ RuleSet clone() => RuleSet._(_values.toList(growable: false));
/// Binds [rule] to [value] then checks to see if that violates any
/// constraints.
@@ -137,7 +137,7 @@
int _cost;
/// Creates a new empty split set for a line with [numChunks].
- SplitSet(int numChunks) : _columns = new List(numChunks - 1);
+ SplitSet(int numChunks) : _columns = List(numChunks - 1);
/// Marks the line after chunk [index] as starting at [column].
void add(int index, int column) {
diff --git a/lib/src/line_splitting/solve_state.dart b/lib/src/line_splitting/solve_state.dart
index f77fe13..0ae7a70 100644
--- a/lib/src/line_splitting/solve_state.dart
+++ b/lib/src/line_splitting/solve_state.dart
@@ -63,7 +63,7 @@
/// There is one other set of rules that go in here. Sometimes a bound rule
/// in the solve state constrains some other unbound rule to split. In that
/// case, we also consider that active so we know to not leave it at zero.
- final _liveRules = new Set<Rule>();
+ final _liveRules = Set<Rule>();
/// The set of splits chosen for this state.
SplitSet get splits => _splits;
@@ -205,7 +205,7 @@
// Make sure we don't violate the constraints of the bound rules.
if (!valid) continue;
- var state = new SolveState(_splitter, boundRules);
+ var state = SolveState(_splitter, boundRules);
// If some unbound rules are constrained to split, remember that.
if (mustSplitRules != null) {
@@ -281,7 +281,7 @@
void _calculateSplits() {
// Figure out which expression nesting levels got split and need to be
// assigned columns.
- var usedNestingLevels = new Set<NestingLevel>();
+ var usedNestingLevels = Set<NestingLevel>();
for (var i = 0; i < _splitter.chunks.length - 1; i++) {
var chunk = _splitter.chunks[i];
if (chunk.rule.isSplit(getValue(chunk.rule), chunk)) {
@@ -294,7 +294,7 @@
nesting.refreshTotalUsedIndent(usedNestingLevels);
}
- _splits = new SplitSet(_splitter.chunks.length);
+ _splits = SplitSet(_splitter.chunks.length);
for (var i = 0; i < _splitter.chunks.length - 1; i++) {
var chunk = _splitter.chunks[i];
if (chunk.rule.isSplit(getValue(chunk.rule), chunk)) {
@@ -354,7 +354,7 @@
// The set of spans that contain chunks that ended up splitting. We store
// these in a set so a span's cost doesn't get double-counted if more than
// one split occurs in it.
- var splitSpans = new Set();
+ var splitSpans = Set();
// The nesting level of the chunk that ended the previous line.
var previousNesting;
@@ -454,9 +454,9 @@
void _ensureBoundRulesInUnboundLines() {
if (_boundRulesInUnboundLines != null) return;
- _boundRulesInUnboundLines = new Set<Rule>();
+ _boundRulesInUnboundLines = Set<Rule>();
- var boundInLine = new Set<Rule>();
+ var boundInLine = Set<Rule>();
var hasUnbound = false;
for (var i = 0; i < _splitter.chunks.length - 1; i++) {
@@ -488,8 +488,8 @@
void _ensureConstraints() {
if (_constraints != null) return;
- _unboundRules = new Set();
- _boundRules = new Set();
+ _unboundRules = Set();
+ _boundRules = Set();
for (var rule in _splitter.rules) {
if (_ruleValues.contains(rule)) {
@@ -553,7 +553,7 @@
}
if (disallowedValues == null) {
- disallowedValues = new Set<int>();
+ disallowedValues = Set<int>();
_unboundConstraints[unbound] = disallowedValues;
}
@@ -564,7 +564,7 @@
}
String toString() {
- var buffer = new StringBuffer();
+ var buffer = StringBuffer();
buffer.writeAll(_splitter.rules.map((rule) {
var valueLength = "${rule.fullySplitValue}".length;
diff --git a/lib/src/line_splitting/solve_state_queue.dart b/lib/src/line_splitting/solve_state_queue.dart
index 2247cb3..a22731a 100644
--- a/lib/src/line_splitting/solve_state_queue.dart
+++ b/lib/src/line_splitting/solve_state_queue.dart
@@ -25,7 +25,7 @@
LineSplitter _splitter;
/// List implementation of a heap.
- List<SolveState> _queue = new List<SolveState>(_INITIAL_CAPACITY);
+ List<SolveState> _queue = List<SolveState>(_INITIAL_CAPACITY);
/// Number of elements in queue.
/// The heap is implemented in the first [_length] entries of [_queue].
@@ -50,7 +50,7 @@
var newCapacity = _queue.length * 2 + 1;
if (newCapacity < _INITIAL_CAPACITY) newCapacity = _INITIAL_CAPACITY;
- var newQueue = new List<SolveState>(newCapacity);
+ var newQueue = List<SolveState>(newCapacity);
newQueue.setRange(0, _length, _queue);
_queue = newQueue;
}
diff --git a/lib/src/line_writer.dart b/lib/src/line_writer.dart
index 9fb5d39..2c6d103 100644
--- a/lib/src/line_writer.dart
+++ b/lib/src/line_writer.dart
@@ -13,7 +13,7 @@
/// Given a series of chunks, splits them into lines and writes the result to
/// a buffer.
class LineWriter {
- final _buffer = new StringBuffer();
+ final _buffer = StringBuffer();
final List<Chunk> _chunks;
@@ -75,13 +75,13 @@
///
/// When we format the anonymous lambda, [column] will be 2, not 4.
FormatResult formatBlock(Chunk chunk, int column) {
- var key = new _BlockKey(chunk, column);
+ var key = _BlockKey(chunk, column);
// Use the cached one if we have it.
var cached = _blockCache[key];
if (cached != null) return cached;
- var writer = new LineWriter._(
+ var writer = LineWriter._(
chunk.block.chunks, _lineEnding, pageWidth, column, _blockCache);
// TODO(rnystrom): Passing in an initial indent here is hacky. The
@@ -97,7 +97,7 @@
/// Since this is linear and line splitting is worse it's good to feed the
/// line splitter smaller lists of chunks when possible.
FormatResult writeLines(int firstLineIndent,
- {bool isCompilationUnit: false, bool flushLeft: false}) {
+ {bool isCompilationUnit = false, bool flushLeft = false}) {
// Now that we know what hard splits there will be, break the chunks into
// independently splittable lines.
var newlines = 0;
@@ -127,7 +127,7 @@
// Be a good citizen, end with a newline.
if (isCompilationUnit) _buffer.write(_lineEnding);
- return new FormatResult(
+ return FormatResult(
_buffer.toString(), totalCost, _selectionStart, _selectionEnd);
}
@@ -149,7 +149,7 @@
}
// Run the line splitter.
- var splitter = new LineSplitter(this, chunks, _blockIndentation, indent,
+ var splitter = LineSplitter(this, chunks, _blockIndentation, indent,
flushLeft: flushLeft);
var splits = splitter.apply();
diff --git a/lib/src/nesting_builder.dart b/lib/src/nesting_builder.dart
index 544ab57..bbae652 100644
--- a/lib/src/nesting_builder.dart
+++ b/lib/src/nesting_builder.dart
@@ -58,7 +58,7 @@
/// The current nesting, ignoring any pending nesting.
NestingLevel get nesting => _nesting;
- NestingLevel _nesting = new NestingLevel();
+ NestingLevel _nesting = NestingLevel();
/// The current nesting, including any pending nesting.
NestingLevel get currentNesting =>
diff --git a/lib/src/nesting_level.dart b/lib/src/nesting_level.dart
index 4e74983..3be1a83 100644
--- a/lib/src/nesting_level.dart
+++ b/lib/src/nesting_level.dart
@@ -48,7 +48,7 @@
/// Creates a new deeper level of nesting indented [spaces] more characters
/// that the outer level.
- NestingLevel nest(int spaces) => new NestingLevel._(this, spaces);
+ NestingLevel nest(int spaces) => NestingLevel._(this, spaces);
/// Clears the previously calculated total indent of this nesting level.
void clearTotalUsedIndent() {
diff --git a/lib/src/rule/combinator.dart b/lib/src/rule/combinator.dart
index 1d73031..29b2550 100644
--- a/lib/src/rule/combinator.dart
+++ b/lib/src/rule/combinator.dart
@@ -46,7 +46,7 @@
/// the beginning of the line.
class CombinatorRule extends Rule {
/// The set of chunks before the combinators.
- final Set<Chunk> _combinators = new Set();
+ final Set<Chunk> _combinators = Set();
/// A list of sets of chunks prior to each name in a combinator.
///
@@ -72,7 +72,7 @@
/// This must be called before adding any names.
void addCombinator(Chunk chunk) {
_combinators.add(chunk);
- _names.add(new Set());
+ _names.add(Set());
}
/// Adds a chunk prior to a name to the current combinator.
diff --git a/lib/src/rule/rule.dart b/lib/src/rule/rule.dart
index fdda621..acca87f 100644
--- a/lib/src/rule/rule.dart
+++ b/lib/src/rule/rule.dart
@@ -59,7 +59,7 @@
///
/// This contains all direct as well as transitive relationships. If A
/// contains B which contains C, C's outerRules contains both B and A.
- final Set<Rule> _implied = new Set<Rule>();
+ final Set<Rule> _implied = Set<Rule>();
/// Marks [other] as implied by this one.
///
@@ -172,7 +172,7 @@
rule.constrainedRules.forEach(visit);
}
- _allConstrainedRules = new Set();
+ _allConstrainedRules = Set();
visit(this);
}
diff --git a/lib/src/source_code.dart b/lib/src/source_code.dart
index a79c220..061a0f3 100644
--- a/lib/src/source_code.dart
+++ b/lib/src/source_code.dart
@@ -51,32 +51,32 @@
SourceCode(this.text,
{this.uri,
- this.isCompilationUnit: true,
+ this.isCompilationUnit = true,
this.selectionStart,
this.selectionLength}) {
// Must either provide both selection bounds or neither.
if ((selectionStart == null) != (selectionLength == null)) {
- throw new ArgumentError(
+ throw ArgumentError(
"Is selectionStart is provided, selectionLength must be too.");
}
if (selectionStart != null) {
if (selectionStart < 0) {
- throw new ArgumentError("selectionStart must be non-negative.");
+ throw ArgumentError("selectionStart must be non-negative.");
}
if (selectionStart > text.length) {
- throw new ArgumentError("selectionStart must be within text.");
+ throw ArgumentError("selectionStart must be within text.");
}
}
if (selectionLength != null) {
if (selectionLength < 0) {
- throw new ArgumentError("selectionLength must be non-negative.");
+ throw ArgumentError("selectionLength must be non-negative.");
}
if (selectionStart + selectionLength > text.length) {
- throw new ArgumentError("selectionLength must end within text.");
+ throw ArgumentError("selectionLength must end within text.");
}
}
}
diff --git a/lib/src/source_visitor.dart b/lib/src/source_visitor.dart
index 60a527f..15de0f7 100644
--- a/lib/src/source_visitor.dart
+++ b/lib/src/source_visitor.dart
@@ -23,7 +23,7 @@
import 'style_fix.dart';
import 'whitespace.dart';
-final _capitalPattern = new RegExp(r"^_?[A-Z].*[a-z]");
+final _capitalPattern = RegExp(r"^_?[A-Z].*[a-z]");
/// Visits every token of the AST and passes all of the relevant bits to a
/// [ChunkBuilder].
@@ -163,7 +163,7 @@
/// Initialize a newly created visitor to write source code representing
/// the visited nodes to the given [writer].
SourceVisitor(this._formatter, this._lineInfo, this._source) {
- builder = new ChunkBuilder(_formatter, _source);
+ builder = ChunkBuilder(_formatter, _source);
}
/// Runs the visitor on [node], formatting its contents.
@@ -216,7 +216,7 @@
/// 4. Split between one or more positional arguments, trying to keep as many
/// on earlier lines as possible.
/// 5. Split the named arguments each onto their own line.
- visitArgumentList(ArgumentList node, {bool nestExpression: true}) {
+ visitArgumentList(ArgumentList node, {bool nestExpression = true}) {
// Corner case: handle empty argument lists.
if (node.arguments.isEmpty) {
token(node.leftParenthesis);
@@ -238,7 +238,7 @@
}
if (nestExpression) builder.nestExpression();
- new ArgumentListVisitor(this, node).visit();
+ ArgumentListVisitor(this, node).visit();
if (nestExpression) builder.unnest();
}
@@ -261,7 +261,7 @@
if (node.message != null) arguments.add(node.message);
builder.nestExpression();
- var visitor = new ArgumentListVisitor.forArguments(
+ var visitor = ArgumentListVisitor.forArguments(
this, node.leftParenthesis, node.rightParenthesis, arguments);
visitor.visit();
builder.unnest();
@@ -274,7 +274,7 @@
var arguments = [node.condition];
if (node.message != null) arguments.add(node.message);
- var visitor = new ArgumentListVisitor.forArguments(
+ var visitor = ArgumentListVisitor.forArguments(
this, node.leftParenthesis, node.rightParenthesis, arguments);
visitor.visit();
});
@@ -439,8 +439,7 @@
// If the cascade sections have consistent names they can be broken
// normally otherwise they always get their own line.
if (splitIfOperandsSplit) {
- builder.startLazyRule(
- _allowInlineCascade(node) ? new Rule() : new Rule.hard());
+ builder.startLazyRule(_allowInlineCascade(node) ? Rule() : Rule.hard());
}
// If the target of the cascade is a method call (or chain of them), we
@@ -463,7 +462,7 @@
// ..cascade()
// ..cascade();
if (node.target is MethodInvocation) {
- new CallChainVisitor(this, node.target).visit(unnest: false);
+ CallChainVisitor(this, node.target).visit(unnest: false);
} else {
visit(node.target);
}
@@ -474,8 +473,7 @@
// If the cascade section shouldn't cause the cascade to split, end the
// rule early so it isn't affected by it.
if (!splitIfOperandsSplit) {
- builder
- .startRule(_allowInlineCascade(node) ? new Rule() : new Rule.hard());
+ builder.startRule(_allowInlineCascade(node) ? Rule() : Rule.hard());
}
zeroSplit();
@@ -598,7 +596,7 @@
visit(node.typeParameters);
visit(node.extendsClause);
- builder.startRule(new CombinatorRule());
+ builder.startRule(CombinatorRule());
visit(node.withClause);
visit(node.implementsClause);
builder.endRule();
@@ -627,7 +625,7 @@
visit(node.superclass);
- builder.startRule(new CombinatorRule());
+ builder.startRule(CombinatorRule());
visit(node.withClause);
visit(node.implementsClause);
builder.endRule();
@@ -977,7 +975,7 @@
_visitConfigurations(node.configurations);
- builder.startRule(new CombinatorRule());
+ builder.startRule(CombinatorRule());
visitNodes(node.combinators);
builder.endRule();
});
@@ -1054,7 +1052,7 @@
}
visitFormalParameterList(FormalParameterList node,
- {bool nestExpression: true}) {
+ {bool nestExpression = true}) {
// Corner case: empty parameter lists.
if (node.parameters.isEmpty) {
token(node.leftParenthesis);
@@ -1084,11 +1082,11 @@
if (nestExpression) builder.nestExpression();
token(node.leftParenthesis);
- _metadataRules.add(new MetadataRule());
+ _metadataRules.add(MetadataRule());
var rule;
if (requiredParams.isNotEmpty) {
- rule = new PositionalRule(null, 0, 0);
+ rule = PositionalRule(null, 0, 0);
_metadataRules.last.bindPositionalRule(rule);
builder.startRule(rule);
@@ -1120,7 +1118,7 @@
}
if (optionalParams.isNotEmpty) {
- var namedRule = new NamedRule(null, 0, 0);
+ var namedRule = NamedRule(null, 0, 0);
if (rule != null) rule.setNamedArgsRule(namedRule);
_metadataRules.last.bindNamedRule(namedRule);
@@ -1602,7 +1600,7 @@
visit(node.prefix);
}
- builder.startRule(new CombinatorRule());
+ builder.startRule(CombinatorRule());
visitNodes(node.combinators);
builder.endRule();
});
@@ -1816,7 +1814,7 @@
return;
}
- new CallChainVisitor(this, node).visit();
+ CallChainVisitor(this, node).visit();
}
visitMixinDeclaration(MixinDeclaration node) {
@@ -1838,7 +1836,7 @@
visit(node.onClause.superclassConstraints.single);
}
- builder.startRule(new CombinatorRule());
+ builder.startRule(CombinatorRule());
// If there are multiple superclass constraints, format them like the
// "implements" clause.
@@ -1923,7 +1921,7 @@
}
visitPrefixedIdentifier(PrefixedIdentifier node) {
- new CallChainVisitor(this, node).visit();
+ CallChainVisitor(this, node).visit();
}
visitPrefixExpression(PrefixExpression node) {
@@ -1947,7 +1945,7 @@
return;
}
- new CallChainVisitor(this, node).visit();
+ CallChainVisitor(this, node).visit();
}
visitRedirectingConstructorInvocation(RedirectingConstructorInvocation node) {
@@ -2158,7 +2156,7 @@
}
visitTypeParameterList(TypeParameterList node) {
- _metadataRules.add(new MetadataRule());
+ _metadataRules.add(MetadataRule());
_visitGenericList(node.leftBracket, node.rightBracket, node.typeParameters);
@@ -2347,7 +2345,7 @@
/// If [nest] is true, an extra level of expression nesting is added after
/// the "=".
void _visitAssignment(Token equalsOperator, Expression rightHandSide,
- {bool nest: false}) {
+ {bool nest = false}) {
space();
token(equalsOperator);
@@ -2364,7 +2362,7 @@
/// Visits a type parameter or type argument list.
void _visitGenericList(
Token leftBracket, Token rightBracket, List<AstNode> nodes) {
- var rule = new TypeArgumentRule();
+ var rule = TypeArgumentRule();
builder.startLazyRule(rule);
builder.startSpan();
builder.nestExpression();
@@ -2494,7 +2492,7 @@
builder.nestExpression();
// This rule is ended by visitExpressionFunctionBody().
- builder.startLazyRule(new Rule(Cost.arrow));
+ builder.startLazyRule(Rule(Cost.arrow));
}
_visitParameterSignature(typeParameters, parameters);
@@ -2630,13 +2628,13 @@
// on the same line all share an argument-list-like rule that allows
// splitting between zero, one, or all of them. This is faster in long
// lists than using individual splits after each element.
- lineRule = new TypeArgumentRule();
+ lineRule = TypeArgumentRule();
builder.startLazyRule(lineRule);
} else {
// Newlines aren't significant, so use a hard rule to split the elements.
// The parent chunk of the collection will handle the unsplit case, so
// this only comes into play when the collection is split.
- rule = new Rule.hard();
+ rule = Rule.hard();
builder.startRule(rule);
}
@@ -2650,7 +2648,7 @@
// Start a new rule for the new line.
builder.endRule();
- lineRule = new TypeArgumentRule();
+ lineRule = TypeArgumentRule();
builder.startLazyRule(lineRule);
} else {
lineRule.beforeArgument(split());
@@ -2696,10 +2694,10 @@
// Can't have a trailing comma if there are no parameters.
assert(parameters.parameters.isNotEmpty);
- _metadataRules.add(new MetadataRule());
+ _metadataRules.add(MetadataRule());
// Always split the parameters.
- builder.startRule(new Rule.hard());
+ builder.startRule(Rule.hard());
token(parameters.leftParenthesis);
@@ -2758,7 +2756,7 @@
/// Begins writing a formal parameter of any kind.
void _beginFormalParameter(FormalParameter node) {
- builder.startLazyRule(new Rule(Cost.parameterType));
+ builder.startLazyRule(Rule(Cost.parameterType));
builder.nestExpression();
modifier(node.covariantKeyword);
}
@@ -3027,7 +3025,7 @@
/// Writes the beginning of a brace-delimited body and handles indenting and
/// starting the rule used to split the contents.
- void _beginBody(Token leftBracket, {bool space: false}) {
+ void _beginBody(Token leftBracket, {bool space = false}) {
token(leftBracket);
// Indent the body.
@@ -3039,7 +3037,7 @@
}
/// Finishes the body started by a call to [_beginBody].
- void _endBody(Token rightBracket, {bool space: false}) {
+ void _endBody(Token rightBracket, {bool space = false}) {
token(rightBracket, before: () {
// Split before the closing bracket character.
builder.unindent();
@@ -3133,7 +3131,7 @@
/// Writes a single space split with its own rule.
Rule soloSplit([int cost]) {
- var rule = new Rule(cost);
+ var rule = Rule(cost);
builder.startRule(rule);
split();
builder.endRule();
@@ -3210,7 +3208,7 @@
if (comment == token.precedingComments) linesBefore = 2;
}
- var sourceComment = new SourceComment(text, linesBefore,
+ var sourceComment = SourceComment(text, linesBefore,
isLineComment: comment.type == TokenType.SINGLE_LINE_COMMENT,
flushLeft: flushLeft);
diff --git a/lib/src/style_fix.dart b/lib/src/style_fix.dart
index f15d7f6..b23f3b8 100644
--- a/lib/src/style_fix.dart
+++ b/lib/src/style_fix.dart
@@ -6,23 +6,22 @@
/// Enum-like class for the different syntactic fixes that can be applied while
/// formatting.
class StyleFix {
- static const docComments = const StyleFix._(
+ static const docComments = StyleFix._(
"doc-comments", 'Use triple slash for documentation comments.');
- static const functionTypedefs = const StyleFix._(
+ static const functionTypedefs = StyleFix._(
"function-typedefs", 'Use new syntax for function type typedefs.');
- static const namedDefaultSeparator = const StyleFix._(
- "named-default-separator",
+ static const namedDefaultSeparator = StyleFix._("named-default-separator",
'Use "=" as the separator before named parameter default values.');
- static const optionalConst = const StyleFix._(
+ static const optionalConst = StyleFix._(
"optional-const", 'Remove "const" keyword inside constant context.');
static const optionalNew =
- const StyleFix._("optional-new", 'Remove "new" keyword.');
+ StyleFix._("optional-new", 'Remove "new" keyword.');
- static const all = const [
+ static const all = [
docComments,
functionTypedefs,
namedDefaultSeparator,
diff --git a/lib/src/whitespace.dart b/lib/src/whitespace.dart
index c405063..aff33c1 100644
--- a/lib/src/whitespace.dart
+++ b/lib/src/whitespace.dart
@@ -26,33 +26,33 @@
/// encountered to avoid trailing whitespace.
class Whitespace {
/// No whitespace.
- static const none = const Whitespace._("none");
+ static const none = Whitespace._("none");
/// A single non-breaking space.
- static const space = const Whitespace._("space");
+ static const space = Whitespace._("space");
/// A single newline.
- static const newline = const Whitespace._("newline");
+ static const newline = Whitespace._("newline");
/// A single newline that takes into account the current expression nesting
/// for the next line.
- static const nestedNewline = const Whitespace._("nestedNewline");
+ static const nestedNewline = Whitespace._("nestedNewline");
/// A single newline with all indentation eliminated at the beginning of the
/// next line.
///
/// Used for subsequent lines in a multiline string.
- static const newlineFlushLeft = const Whitespace._("newlineFlushLeft");
+ static const newlineFlushLeft = Whitespace._("newlineFlushLeft");
/// Two newlines, a single blank line of separation.
- static const twoNewlines = const Whitespace._("twoNewlines");
+ static const twoNewlines = Whitespace._("twoNewlines");
/// A split or newline should be output based on whether the current token is
/// on the same line as the previous one or not.
///
/// In general, we like to avoid using this because it makes the formatter
/// less prescriptive over the user's whitespace.
- static const splitOrNewline = const Whitespace._("splitOrNewline");
+ static const splitOrNewline = Whitespace._("splitOrNewline");
/// A split or blank line (two newlines) should be output based on whether
/// the current token is on the same line as the previous one or not.
@@ -62,14 +62,14 @@
///
/// In general, we like to avoid using this because it makes the formatter
/// less prescriptive over the user's whitespace.
- static const splitOrTwoNewlines = const Whitespace._("splitOrTwoNewlines");
+ static const splitOrTwoNewlines = Whitespace._("splitOrTwoNewlines");
/// One or two newlines should be output based on how many newlines are
/// present between the next token and the previous one.
///
/// In general, we like to avoid using this because it makes the formatter
/// less prescriptive over the user's whitespace.
- static const oneOrTwoNewlines = const Whitespace._("oneOrTwoNewlines");
+ static const oneOrTwoNewlines = Whitespace._("oneOrTwoNewlines");
final String name;
diff --git a/pubspec.lock b/pubspec.lock
index fd338b7..ce76bf7 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -191,7 +191,7 @@
source: hosted
version: "1.6.2"
pedantic:
- dependency: transitive
+ dependency: "direct dev"
description:
name: pedantic
url: "https://pub.dartlang.org"
diff --git a/pubspec.yaml b/pubspec.yaml
index 7269f61..455a120 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -6,7 +6,7 @@
homepage: https://github.com/dart-lang/dart_style
environment:
- sdk: '>=2.0.0 <3.0.0'
+ sdk: '>=2.1.0 <3.0.0'
dependencies:
analyzer: '>=0.35.3 <0.36.0'
@@ -19,6 +19,7 @@
grinder: ^0.8.0
js: ^0.6.0
node_preamble: ^1.0.0
+ pedantic: ^1.0.0
pub_semver: ^1.2.3
test: ^1.2.0
test_descriptor: ^1.0.0
diff --git a/test/command_line_test.dart b/test/command_line_test.dart
index 14f39e0..daaa75d 100644
--- a/test/command_line_test.dart
+++ b/test/command_line_test.dart
@@ -66,7 +66,7 @@
var process = await runFormatter(["--version"]);
// Match something roughly semver-like.
- expect(await process.stdout.next, matches(new RegExp(r"\d+\.\d+\.\d+.*")));
+ expect(await process.stdout.next, matches(RegExp(r"\d+\.\d+\.\d+.*")));
await process.shouldExit(0);
});
diff --git a/test/formatter_test.dart b/test/formatter_test.dart
index bc0779a..18629d1 100644
--- a/test/formatter_test.dart
+++ b/test/formatter_test.dart
@@ -19,16 +19,16 @@
testDirectory("whitespace");
test("throws a FormatterException on failed parse", () {
- var formatter = new DartFormatter();
+ var formatter = DartFormatter();
expect(() => formatter.format('wat?!'),
- throwsA(new TypeMatcher<FormatterException>()));
+ throwsA(TypeMatcher<FormatterException>()));
});
test("FormatterException.message() does not throw", () {
// This is a regression test for #358 where an error whose position is
// past the end of the source caused FormatterException to throw.
try {
- new DartFormatter().format("library");
+ DartFormatter().format("library");
} on FormatterException catch (err) {
var message = err.message();
expect(message, contains("Could not format"));
@@ -37,7 +37,7 @@
test("FormatterException describes parse errors", () {
try {
- new DartFormatter().format("""
+ DartFormatter().format("""
var a = some error;
@@ -54,27 +54,25 @@
});
test("adds newline to unit", () {
- expect(new DartFormatter().format("var x = 1;"), equals("var x = 1;\n"));
+ expect(DartFormatter().format("var x = 1;"), equals("var x = 1;\n"));
});
test("adds newline to unit after trailing comment", () {
- expect(new DartFormatter().format("library foo; //zamm"),
+ expect(DartFormatter().format("library foo; //zamm"),
equals("library foo; //zamm\n"));
});
test("removes extra newlines", () {
- expect(
- new DartFormatter().format("var x = 1;\n\n\n"), equals("var x = 1;\n"));
+ expect(DartFormatter().format("var x = 1;\n\n\n"), equals("var x = 1;\n"));
});
test("does not add newline to statement", () {
- expect(new DartFormatter().formatStatement("var x = 1;"),
- equals("var x = 1;"));
+ expect(DartFormatter().formatStatement("var x = 1;"), equals("var x = 1;"));
});
test("fails if anything is after the statement", () {
try {
- new DartFormatter().formatStatement("var x = 1;;");
+ DartFormatter().formatStatement("var x = 1;;");
fail("Should throw.");
} on FormatterException catch (ex) {
@@ -84,7 +82,7 @@
});
test('preserves initial indent', () {
- var formatter = new DartFormatter(indent: 3);
+ var formatter = DartFormatter(indent: 3);
expect(
formatter.formatStatement('if (foo) {bar;}'),
equals(' if (foo) {\n'
@@ -99,27 +97,27 @@
// will throw an error if it accidentally makes non-whitespace changes
// as will occur
var lineEnding = "\t";
- expect(new DartFormatter(lineEnding: lineEnding).format("var i = 1;"),
+ expect(DartFormatter(lineEnding: lineEnding).format("var i = 1;"),
equals("var i = 1;\t"));
});
test('infers \\r\\n if the first newline uses that', () {
- expect(new DartFormatter().format("var\r\ni\n=\n1;\n"),
+ expect(DartFormatter().format("var\r\ni\n=\n1;\n"),
equals("var i = 1;\r\n"));
});
test('infers \\n if the first newline uses that', () {
- expect(new DartFormatter().format("var\ni\r\n=\r\n1;\r\n"),
+ expect(DartFormatter().format("var\ni\r\n=\r\n1;\r\n"),
equals("var i = 1;\n"));
});
test('defaults to \\n if there are no newlines', () {
- expect(new DartFormatter().format("var i =1;"), equals("var i = 1;\n"));
+ expect(DartFormatter().format("var i =1;"), equals("var i = 1;\n"));
});
test('handles Windows line endings in multiline strings', () {
expect(
- new DartFormatter(lineEnding: "\r\n").formatStatement(' """first\r\n'
+ DartFormatter(lineEnding: "\r\n").formatStatement(' """first\r\n'
'second\r\n'
'third""" ;'),
equals('"""first\r\n'
@@ -131,8 +129,8 @@
test('throws an UnexpectedOutputException on non-whitespace changes', () {
// Use an invalid line ending character to ensure the formatter will
// attempt to make non-whitespace changes.
- var formatter = new DartFormatter(lineEnding: '%');
+ var formatter = DartFormatter(lineEnding: '%');
expect(() => formatter.format("var i = 1;"),
- throwsA(new TypeMatcher<UnexpectedOutputException>()));
+ throwsA(TypeMatcher<UnexpectedOutputException>()));
});
}
diff --git a/test/io_test.dart b/test/io_test.dart
index acecf1b..95daf8a 100644
--- a/test/io_test.dart
+++ b/test/io_test.dart
@@ -17,17 +17,17 @@
import 'utils.dart';
void main() {
- var overwriteOptions = new FormatterOptions(OutputReporter.overwrite);
+ var overwriteOptions = FormatterOptions(OutputReporter.overwrite);
var followOptions =
- new FormatterOptions(OutputReporter.overwrite, followLinks: true);
+ FormatterOptions(OutputReporter.overwrite, followLinks: true);
test('handles directory ending in ".dart"', () async {
await d.dir('code.dart', [
d.file('a.dart', unformattedSource),
]).create();
- var dir = new Directory(d.sandbox);
+ var dir = Directory(d.sandbox);
processDirectory(overwriteOptions, dir);
await d.dir('code.dart', [
@@ -42,15 +42,15 @@
]).create();
DateTime modTime(String file) =>
- new File(p.join(d.sandbox, 'code', file)).statSync().modified;
+ File(p.join(d.sandbox, 'code', file)).statSync().modified;
var badBefore = modTime('bad.dart');
var goodBefore = modTime('good.dart');
// Wait a bit so the mod time of a formatted file will be different.
- await new Future.delayed(new Duration(seconds: 1));
+ await Future.delayed(Duration(seconds: 1));
- var dir = new Directory(p.join(d.sandbox, 'code'));
+ var dir = Directory(p.join(d.sandbox, 'code'));
processDirectory(overwriteOptions, dir);
// Should be touched.
@@ -67,7 +67,7 @@
d.dir('.skip', [d.file('a.dart', unformattedSource)])
]).create();
- var dir = new Directory(d.sandbox);
+ var dir = Directory(d.sandbox);
processDirectory(overwriteOptions, dir);
await d.dir('code', [
@@ -79,7 +79,7 @@
() async {
await d.dir('.code', [d.file('a.dart', unformattedSource)]).create();
- var dir = new Directory(p.join(d.sandbox, '.code'));
+ var dir = Directory(p.join(d.sandbox, '.code'));
processDirectory(overwriteOptions, dir);
await d.dir('.code', [d.file('a.dart', formattedSource)]).validate();
@@ -95,10 +95,10 @@
]).create();
// Create a link to the target directory in the code directory.
- new Link(p.join(d.sandbox, 'code', 'linked_dir'))
+ Link(p.join(d.sandbox, 'code', 'linked_dir'))
.createSync(p.join(d.sandbox, 'target_dir'));
- var dir = new Directory(p.join(d.sandbox, 'code'));
+ var dir = Directory(p.join(d.sandbox, 'code'));
processDirectory(overwriteOptions, dir);
await d.dir('code', [
@@ -119,10 +119,10 @@
]).create();
// Create a link to the target directory in the code directory.
- new Link(p.join(d.sandbox, 'code', 'linked_dir'))
+ Link(p.join(d.sandbox, 'code', 'linked_dir'))
.createSync(p.join(d.sandbox, 'target_dir'));
- var dir = new Directory(p.join(d.sandbox, 'code'));
+ var dir = Directory(p.join(d.sandbox, 'code'));
processDirectory(followOptions, dir);
await d.dir('code', [
@@ -141,7 +141,7 @@
Process.runSync("chmod", ["-w", p.join(d.sandbox, 'a.dart')]);
- var file = new File(p.join(d.sandbox, 'a.dart'));
+ var file = File(p.join(d.sandbox, 'a.dart'));
processFile(overwriteOptions, file);
// Should not have been formatted.
@@ -153,10 +153,10 @@
await d.file('target_file.dart', unformattedSource).create();
// Create a link to the target file in the code directory.
- new Link(p.join(d.sandbox, 'code', 'linked_file.dart'))
+ Link(p.join(d.sandbox, 'code', 'linked_file.dart'))
.createSync(p.join(d.sandbox, 'target_file.dart'));
- var dir = new Directory(p.join(d.sandbox, 'code'));
+ var dir = Directory(p.join(d.sandbox, 'code'));
processDirectory(overwriteOptions, dir);
await d.dir('code', [
@@ -169,10 +169,10 @@
await d.file('target_file.dart', unformattedSource).create();
// Create a link to the target file in the code directory.
- new Link(p.join(d.sandbox, 'code', 'linked_file.dart'))
+ Link(p.join(d.sandbox, 'code', 'linked_file.dart'))
.createSync(p.join(d.sandbox, 'target_file.dart'));
- var dir = new Directory(p.join(d.sandbox, 'code'));
+ var dir = Directory(p.join(d.sandbox, 'code'));
processDirectory(followOptions, dir);
await d.dir('code', [
diff --git a/test/source_code_test.dart b/test/source_code_test.dart
index a3e1169..6615768 100644
--- a/test/source_code_test.dart
+++ b/test/source_code_test.dart
@@ -9,44 +9,43 @@
import 'package:dart_style/dart_style.dart';
void main() {
- var selection =
- new SourceCode("123456;", selectionStart: 3, selectionLength: 2);
- var noSelection = new SourceCode("123456;");
+ var selection = SourceCode("123456;", selectionStart: 3, selectionLength: 2);
+ var noSelection = SourceCode("123456;");
group('constructor', () {
test('throws on negative start', () {
expect(() {
- new SourceCode("12345;", selectionStart: -1, selectionLength: 0);
+ SourceCode("12345;", selectionStart: -1, selectionLength: 0);
}, throwsArgumentError);
});
test('throws on out of bounds start', () {
expect(() {
- new SourceCode("12345;", selectionStart: 7, selectionLength: 0);
+ SourceCode("12345;", selectionStart: 7, selectionLength: 0);
}, throwsArgumentError);
});
test('throws on negative length', () {
expect(() {
- new SourceCode("12345;", selectionStart: 1, selectionLength: -1);
+ SourceCode("12345;", selectionStart: 1, selectionLength: -1);
}, throwsArgumentError);
});
test('throws on out of bounds length', () {
expect(() {
- new SourceCode("12345;", selectionStart: 2, selectionLength: 5);
+ SourceCode("12345;", selectionStart: 2, selectionLength: 5);
}, throwsArgumentError);
});
test('throws is start is null and length is not', () {
expect(() {
- new SourceCode("12345;", selectionStart: 0);
+ SourceCode("12345;", selectionStart: 0);
}, throwsArgumentError);
});
test('throws is length is null and start is not', () {
expect(() {
- new SourceCode("12345;", selectionLength: 1);
+ SourceCode("12345;", selectionLength: 1);
}, throwsArgumentError);
});
});
diff --git a/test/string_compare_test.dart b/test/string_compare_test.dart
index 52b2298..7b4e950 100644
--- a/test/string_compare_test.dart
+++ b/test/string_compare_test.dart
@@ -57,7 +57,7 @@
for (var rune in whitespaceRunes) {
expect(
equalIgnoringWhitespace(
- 'foo${new String.fromCharCode(rune)}bar', 'foo bar'),
+ 'foo${String.fromCharCode(rune)}bar', 'foo bar'),
isFalse);
}
});
diff --git a/test/utils.dart b/test/utils.dart
index 0d5f889..9405130 100644
--- a/test/utils.dart
+++ b/test/utils.dart
@@ -18,8 +18,8 @@
const unformattedSource = 'void main() => print("hello") ;';
const formattedSource = 'void main() => print("hello");\n';
-final _indentPattern = new RegExp(r"\(indent (\d+)\)");
-final _fixPattern = new RegExp(r"\(fix ([a-x-]+)\)");
+final _indentPattern = RegExp(r"\(indent (\d+)\)");
+final _fixPattern = RegExp(r"\(fix ([a-x-]+)\)");
/// Runs the command line formatter, passing it [args].
Future<TestProcess> runFormatter([List<String> args]) {
@@ -60,7 +60,7 @@
.uri
.toFilePath());
- var entries = new Directory(p.join(testDir, name))
+ var entries = Directory(p.join(testDir, name))
.listSync(recursive: true, followLinks: false);
entries.sort((a, b) => a.path.compareTo(b.path));
@@ -90,7 +90,7 @@
group("$name ${p.basename(path)}", () {
// Explicitly create a File, in case the entry is a Link.
- var lines = new File(path).readAsLinesSync();
+ var lines = File(path).readAsLinesSync();
// The first line may have a "|" to indicate the page width.
var pageWidth;
@@ -150,7 +150,7 @@
var expected = _extractSelection(expectedOutput,
isCompilationUnit: isCompilationUnit);
- var formatter = new DartFormatter(
+ var formatter = DartFormatter(
pageWidth: pageWidth, indent: leadingIndent, fixes: fixes);
var actual = formatter.formatSource(inputCode);
@@ -178,14 +178,14 @@
/// Given a source string that contains ‹ and › to indicate a selection, returns
/// a [SourceCode] with the text (with the selection markers removed) and the
/// correct selection range.
-SourceCode _extractSelection(String source, {bool isCompilationUnit: false}) {
+SourceCode _extractSelection(String source, {bool isCompilationUnit = false}) {
var start = source.indexOf("‹");
source = source.replaceAll("‹", "");
var end = source.indexOf("›");
source = source.replaceAll("›", "");
- return new SourceCode(source,
+ return SourceCode(source,
isCompilationUnit: isCompilationUnit,
selectionStart: start == -1 ? null : start,
selectionLength: end == -1 ? null : end - start);
diff --git a/tool/grind.dart b/tool/grind.dart
index 31938d1..5810053 100644
--- a/tool/grind.dart
+++ b/tool/grind.dart
@@ -11,7 +11,7 @@
import 'package:yaml/yaml.dart' as yaml;
/// Matches the version line in dart_style's pubspec.
-final _versionPattern = new RegExp(r"^version: .*$", multiLine: true);
+final _versionPattern = RegExp(r"^version: .*$", multiLine: true);
main(List<String> args) => grind(args);
@@ -19,7 +19,7 @@
@Task()
validate() async {
// Test it.
- await new TestRunner().testAsync();
+ await TestRunner().testAsync();
// Make sure it's warning clean.
Analyzer.analyze("bin/format.dart", fatalWarnings: true);
@@ -37,16 +37,16 @@
var fileName = 'index.js';
// Generate modified dart2js output suitable to run on node.
- var tempFile = new File('${Directory.systemTemp.path}/temp.js');
+ var tempFile = File('${Directory.systemTemp.path}/temp.js');
- Dart2js.compile(new File('tool/node_format_service.dart'),
+ Dart2js.compile(File('tool/node_format_service.dart'),
outFile: tempFile, categories: 'all');
var dart2jsOutput = tempFile.readAsStringSync();
- new File('$out/$fileName').writeAsStringSync('''${preamble.getPreamble()}
+ File('$out/$fileName').writeAsStringSync('''${preamble.getPreamble()}
self.exports = exports; // Temporary hack for Dart-JS Interop under node.
$dart2jsOutput''');
- new File('$out/package.json')
+ File('$out/package.json')
.writeAsStringSync(const JsonEncoder.withIndent(' ').convert({
"name": "dart-style",
"version": pubspec["version"],
@@ -99,7 +99,7 @@
// Read the version from the pubspec.
var pubspecFile = getFile("pubspec.yaml");
var pubspec = pubspecFile.readAsStringSync();
- var version = new Version.parse(yaml.loadYaml(pubspec)["version"]);
+ var version = Version.parse(yaml.loadYaml(pubspec)["version"]);
// Require a "-dev" version since we don't otherwise know what to bump it to.
if (!version.isPreRelease) throw "Cannot publish non-dev version $version.";
@@ -108,7 +108,7 @@
// user intended the "+4" to be discarded or not.
if (version.build.isNotEmpty) throw "Cannot publish build version $version.";
- var bumped = new Version(version.major, version.minor, version.patch);
+ var bumped = Version(version.major, version.minor, version.patch);
// Update the version in the pubspec.
pubspec = pubspec.replaceAll(_versionPattern, "version: $bumped");
@@ -117,7 +117,7 @@
// Update the version constant in bin/format.dart.
var binFormatFile = getFile("bin/format.dart");
var binFormat = binFormatFile.readAsStringSync().replaceAll(
- new RegExp(r'const version = "[^"]+";'), 'const version = "$bumped";');
+ RegExp(r'const version = "[^"]+";'), 'const version = "$bumped";');
binFormatFile.writeAsStringSync(binFormat);
// Update the version in the CHANGELOG.
diff --git a/tool/node_format_service.dart b/tool/node_format_service.dart
index d063a3d..cfc5cf1 100644
--- a/tool/node_format_service.dart
+++ b/tool/node_format_service.dart
@@ -21,11 +21,11 @@
void main() {
formatCode = allowInterop((String source) {
- var formatter = new DartFormatter();
+ var formatter = DartFormatter();
var exception;
try {
- return new FormatResult(code: new DartFormatter().format(source));
+ return FormatResult(code: DartFormatter().format(source));
} on FormatterException catch (err) {
// Couldn't parse it as a compilation unit.
exception = err;
@@ -33,7 +33,7 @@
// Maybe it's a statement.
try {
- return new FormatResult(code: formatter.formatStatement(source));
+ return FormatResult(code: formatter.formatStatement(source));
} on FormatterException catch (err) {
// There is an error when parsing it both as a compilation unit and a
// statement, so we aren't sure which one the user intended. As a
@@ -45,7 +45,7 @@
}
// If we get here, it couldn't be parsed at all.
- return new FormatResult(code: source, error: "$exception");
+ return FormatResult(code: source, error: "$exception");
});
}