For loop metadata (#1406)

* Add DelimitedListBuilder.addLeftBracket().

The existing leftBracket() method takes a couple of optional parameters
to build up a Piece in different ways. But an upcoming change also adds
yet another way that the left bracket Piece might need to be
constructed.

Instead of adding yet another optional parameter, I just made a separate
addLeftBracket() method that takes a complete Piece made any way you
want and then changed the existing callsites to use that unless they
only need a single token.

* Change the Piece structure for Object patterns.

This change is mainly to ensure that every outermost Piece for a pattern
that can be block-formatted is a ListPiece. That will be needed in a
later commit so that when a pattern appears to the left of an `=`, we
can constrain it to block split sometimes.

But this change also slightly changes the formatting of object patterns
in a way that I think looks better: if the type arguments in an object
pattern split, it forces the fields to split too.

* Turn createForLoopParts() into createFor().

The only two calls createForLoopParts() are in visitForStatement() and
visitForElement() and those two are very similar. In a future commit,
they will have more code to share, so reorganizing now to make it easier
to share it.

* Move the operator in AssignPiece to a separate child piece.

Prior to this change, the operator was directly attached to either the
LHS piece (for ` =`) or the RHS (for `in `). This pulls it out to its
own piece. The formatting is unchanged by this commit.

In a future commit, we'll use this to be able to constrain the LHS
child piece without the operator getting in the way.

* Rework AssignPiece formatting.

Formatting assignments is complex because LHS can be block split, or
expression split, or not split. Likewise with the RHS, and thus all nine
combinations. Even figuring out what the formatting should be is tricky.

The "in" clause of a for-in loop also uses the same formatting logic,
which adds more complexity because now it's nested inside a surrounding
statement-like form and parentheses.

It gets even weirder when you have metadata before the variable (which
isn't in this commit).

This change tweaks the formatting rules to, as best as I can tell, make
the edge cases look as nice as I can get. It also adds more tests for
corners that weren't covered. The main changes are:

- If the RHS of an `in` expression splits, then go ahead and split
  before the `in` too. It's pretty rare for splits in `in` to occur in
  the wild, but when they do, the Flutter tends to keep it tightly
  packed with the rest the for loop variable. The initial style tried
  to follow that. But it gets really weird if you happen to have
  metadata in there. I also don't love how it looks. Usually, when a
  split occurs in an operand or clause, we split at the preceding
  operator or keyword too.

  This commit does that. If an expression split occurs to the right of
  `in`, it splits before the `in` too.

- Tweak the relative priority between block splitting on the LHS of an
  assignment versus at the operator itself. The main way this is visible
  is that `=>` function bodies (which also use AssignPiece) now prefer
  to split after the `=>` instead of in the parameter list. I think
  that looks better.

- If the LHS *can* block split but chooses not to, then don't allow the
  RHS to expression split. This is the most important tweak. Before
  this change, the formatter could produce:

      for (var [i] in veryLongIterator +
          longExpression) {
        ;
      }

  That was never intended. The `in` shouldn't get buried in the middle
  of a line like that. This change fixes that by having the AssignPiece
  explicitly constrain the LHS to split when it's a block and it's
  going to allow the RHS to expression split.

* Format metadata on for loop variables.

This is the actual *new* syntax supported by this PR.

* Allow splitting between the type and name in a for loop variable.

This was an oversight. All other type annotated variables allow
splitting between the type and name (even though it's rare).

* Consistently call buildPiece() directly in the argument to
addLeftBracket().

The other callsites all do, so may as well do so here too.
16 files changed
tree: 53b4c8c4deaa9d95ce43f909ccaa537ce59a1f05
  1. .github/
  2. benchmark/
  3. bin/
  4. dist/
  5. example/
  6. lib/
  7. test/
  8. tool/
  9. .gitignore
  10. analysis_options.yaml
  11. AUTHORS
  12. CHANGELOG.md
  13. LICENSE
  14. pubspec.yaml
  15. README.md
README.md

The dart_style package defines an automatic, opinionated formatter for Dart code. It replaces the whitespace in your program with what it deems to be the best formatting for it. Resulting code should follow the Dart style guide but, moreso, should look nice to most human readers, most of the time.

The formatter handles indentation, inline whitespace, and (by far the most difficult) intelligent line wrapping. It has no problems with nested collections, function expressions, long argument lists, or otherwise tricky code.

The formatter turns code like this:

// BEFORE formatting
if (tag=='style'||tag=='script'&&(type==null||type == TYPE_JS
      ||type==TYPE_DART)||
  tag=='link'&&(rel=='stylesheet'||rel=='import')) {}

into:

// AFTER formatting
if (tag == 'style' ||
  tag == 'script' &&
      (type == null || type == TYPE_JS || type == TYPE_DART) ||
  tag == 'link' && (rel == 'stylesheet' || rel == 'import')) {}

The formatter will never break your code—you can safely invoke it automatically from build and presubmit scripts.

Style fixes

The formatter can also apply non-whitespace changes to make your code consistently idiomatic. You must opt into these by passing either --fix which applies all style fixes, or any of the --fix--prefixed flags to apply specific fixes.

For example, running with --fix-named-default-separator changes this:

greet(String name, {String title: "Captain"}) {
  print("Greetings, $title $name!");
}

into:

greet(String name, {String title = "Captain"}) {
  print("Greetings, $title $name!");
}

Using the formatter

The formatter is part of the unified dart developer tool included in the Dart SDK, so most users get it directly from there. That has the latest version of the formatter that was available when the SDK was released.

IDEs and editors that support Dart usually provide easy ways to run the formatter. For example, in WebStorm you can right-click a .dart file and then choose Reformat with Dart Style.

Here's a simple example of using the formatter on the command line:

$ dart format test.dart

This command formats the test.dart file and writes the result to the file.

dart format takes a list of paths, which can point to directories or files. If the path is a directory, it processes every .dart file in that directory or any of its subdirectories.

By default, it formats each file and write the formatting changes to the files. If you pass --output show, it prints the formatted code to stdout.

You may pass a -l option to control the width of the page that it wraps lines to fit within, but you're strongly encouraged to keep the default line length of 80 columns.

Validating files

If you want to use the formatter in something like a presubmit script or commit hook, you can pass flags to omit writing formatting changes to disk and to update the exit code to indicate success/failure:

$ dart format --output=none --set-exit-if-changed .

Running other versions of the formatter CLI command

If you need to run a different version of the formatter, you can globally activate the package from the dart_style package on pub.dev:

$ pub global activate dart_style
$ pub global run dart_style:format ...

Using the dart_style API

The package also exposes a single dart_style library containing a programmatic API for formatting code. Simple usage looks like this:

import 'package:dart_style/dart_style.dart';

main() {
  final formatter = DartFormatter();

  try {
    print(formatter.format("""
    library an_entire_compilation_unit;

    class SomeClass {}
    """));

    print(formatter.formatStatement("aSingle(statement);"));
  } on FormatterException catch (ex) {
    print(ex);
  }
}

Other resources

  • Before sending an email, see if you are asking a frequently asked question.

  • Before filing a bug, or if you want to understand how work on the formatter is managed, see how we track issues.