Commit Graph

704 Commits (9b772cb4fd7d3b8033f11f4779ecb803c61e0d50)

Author SHA1 Message Date
Joseph Frazier d4217f5508 Unescape unnecessarily escaped characters in strings (#1575)
* Add test with unnecessarily escaped non-quote character

In 0b6d19db18,
I noticed that `makeString` doesn't unescape unnecessarily escaped
non-quote characters. This change simply adds a test for that.

* Fix test with unnecessarily escaped non-quote character

Unfortunately, this breaks a couple of other tests...

* Revert "Fix test with unnecessarily escaped non-quote character"

See https://github.com/prettier/prettier/pull/1575#issuecomment-300490172

This reverts commit d05652518fe7d4e2fb82ce48ffc922b153de5593.

* Unescape unnecessarily escaped characters in strings

* Add test for unnecessarily escaped character at not-beginning of string

* Fix test for unnecessarily escaped character at not-beginning of string

* Add test for multiple unnecessary escapes in strings

* Pass test for multiple unnecessary escapes in strings

* Add test for octal escapes in strings

See https://github.com/prettier/prettier/pull/1575#discussion_r115804065

* Pass test for octal escapes in strings

See https://github.com/prettier/prettier/pull/1575#discussion_r115804065

* Add test for unnecessarily escaped character preced by escaped backslash

See https://github.com/prettier/prettier/pull/1575#discussion_r115804065

* Pass test for unnecessarily escaped character preced by escaped backslash

This just allows an even number of backslashes to precede the
unnecessary one.

See https://github.com/prettier/prettier/pull/1575#discussion_r115804065

* Add test for unescaped character after escaped backslash in strings

* Add test for unescaped character preceded by two escaped backslashes in string

See https://github.com/prettier/prettier/pull/1575#discussion_r115808571

* Pass test for unescaped character preceded by two escaped backslashes in string

This breaks another test though...

See https://github.com/prettier/prettier/pull/1575#discussion_r115808571

* Update snapshot

It turns out the test wasn't broken, I had just flubbed the escaping in
the snapshot. The easiest way to see that this actually works is

```bash
$ cat | prettier --stdin
"hol\\a (the a is not escaped)" // press Control-D after the newline
"hol\\a (the a is not escaped)"; // press Control-D after the newline
```

* Prevent test strings from being parsed as directives

See https://github.com/prettier/prettier/pull/1575#discussion_r115820336

(cherry picked from commit 126e56ab2c79801cbf7fee22189212d8c93581df)

* Add test for consecutive unnecessarily escaped characters in strings

See https://github.com/prettier/prettier/pull/1575#discussion_r115822286

* Pass test for consecutive unnecessarily escaped characters in strings

See https://github.com/prettier/prettier/pull/1575#discussion_r115822286

This looping is hacky. We might be able to emulate lookbehind instead.

* Optimize (maybe?) string unescaping loop

Not sure how expensive string comparison is here...

See 2323c8c025 (commitcomment-22092267)

* Safeguard against string unescaping loop hanging

See https://github.com/prettier/prettier/pull/1575#discussion_r115827531

* Add more comprehensive tests for unnecessary string escapes

See https://github.com/prettier/prettier/pull/1575#discussion_r115798155

* Remove superfluous variables from makeString()

See https://github.com/prettier/prettier/pull/1575#discussion_r115834468

* Unescape unnecessary strings escapes without looping

* Unescape unnecessary string escapes while handling quotes

Kudos to @lydell for figuring this out! See
https://github.com/prettier/prettier/pull/1575/files#r115860741

* Test that unnecessary escapes remain in directive literals

See:
* https://github.com/prettier/prettier/pull/1575#discussion_r115820336
* https://github.com/prettier/prettier/pull/1575#issuecomment-300633277
2017-05-10 16:02:49 -07:00
Danny Martini 2c76bfe1e1 update typescript parser (#1578)
* update eslint-parser-typescript

* fix comment parsing

* disable all failing tests

* fix TSInterfaceDeclaration

* fix #1537

* only disable typescript tests for tests/function
2017-05-10 14:11:50 -07:00
Joseph Frazier 8cc38ad524 Preserve code unit sequence of directive literals (#1571)
* Print directive literals verbatim

This addresses https://github.com/prettier/prettier/issues/1555,
but doesn't seem to pass the AST_COMPARE=1 tests:

    AST_COMPARE=1 npm test -- tests/quotes -t strings

However, running `prettier --debug-check` on the relevant file *does*
work:

    prettier tests/quotes/strings.js --debug-check

* Change directive literal quotes if it doesn't contain quotes

This addresses https://github.com/prettier/prettier/pull/1560#discussion_r115396257

From https://github.com/prettier/prettier/issues/1555#issue-227206837:

> It's okay to change the type of quotation marks used, but only if
doing so does not require changing any characters within the directive.

* Don't change directive literal quotes if it contains a backslash

This passes the `--debug-check` tests again:

    prettier tests/quotes/strings.js --debug-check

* Try to add regression test for escaped directive literals

This seems not to work, despite the following command having the correct
output:

    echo "'\''" | prettier

You can use the following to get an idea of how flow/typescript parse
this:

    node -p "JSON.stringify(require('./src/parser').parse('\\'\\\\\'\\'', {parser: 'flow'}), null, 2)"
    node -p "JSON.stringify(require('./src/parser').parse('\\'\\\\\'\\'', {parser: 'typescript'}), null, 2)"

* WIP Disable Flow/Typescript for ./tests/directives

We don't yet handle escaped directives for them, but Babylon works.

(similar to 90bf93713c (diff-0de18284f37da79ab8af4e4690919abaR1))

* Revert "WIP Disable Flow/Typescript for ./tests/directives"

This reverts commit 2aba6231271f6985a395c31e3df9323e8f3da115.

* Prevent test strings from being parsed as directives

See https://github.com/prettier/prettier/pull/1560#issue-227225960

* Add more escaped directive tests

* Infer DirectiveLiterals from Flow parser

* Don't test TypeScript on directives

See https://github.com/prettier/prettier/pull/1560#issuecomment-300296221

* fixup! Infer DirectiveLiterals from Flow parser

* Don't fake objects that look like a DirectiveLiteral

Instead, add a flag to nodeStr() that deals with the Flow node
accordingly. See https://github.com/prettier/prettier/pull/1560#discussion_r115605758

* Print preferred quotes around escaped DirectiveLiteral when it doesn't contain quotes

See https://github.com/prettier/prettier/pull/1560#discussion_r115606122

* Simplify `canChangeDirectiveQuotes` logic

* Add directive test with unnecessarily escaped non-quote character

* Fix boolean logic error

I thought that this would result in the following if-block executing, as
needed to pass the test case in the previous commit. However, it appears
that it's not actually needed to pass the test case, since `makeString`
doesn't unescape unnecessarily escaped non-quote characters.
Nevertheless, I think we should leave that if-block (`if (canChangeDirectiveQuotes)`)
there, in case `makeString` is updated.

See https://github.com/prettier/prettier/pull/1571#discussion_r115658398

* Make isFlowDirectiveLiteral a separate argument to nodeStr()

See https://github.com/prettier/prettier/pull/1571#discussion_r115810988

* Simplify isFlowDirectiveLiteral logic by passing n.expression to nodeStr()

See https://github.com/prettier/prettier/pull/1571#discussion_r115811216
2017-05-10 12:15:27 -07:00
Christopher Chedeau 13f247aee3 Revert "Print directive literals verbatim (#1560)" (#1570)
This reverts commit 32d9d68154.
2017-05-09 14:19:03 -07:00
Joseph Frazier 32d9d68154 Print directive literals verbatim (#1560)
* Print directive literals verbatim

This addresses https://github.com/prettier/prettier/issues/1555,
but doesn't seem to pass the AST_COMPARE=1 tests:

    AST_COMPARE=1 npm test -- tests/quotes -t strings

However, running `prettier --debug-check` on the relevant file *does*
work:

    prettier tests/quotes/strings.js --debug-check

* Change directive literal quotes if it doesn't contain quotes

This addresses https://github.com/prettier/prettier/pull/1560#discussion_r115396257

From https://github.com/prettier/prettier/issues/1555#issue-227206837:

> It's okay to change the type of quotation marks used, but only if
doing so does not require changing any characters within the directive.

* Don't change directive literal quotes if it contains a backslash

This passes the `--debug-check` tests again:

    prettier tests/quotes/strings.js --debug-check

* Try to add regression test for escaped directive literals

This seems not to work, despite the following command having the correct
output:

    echo "'\''" | prettier

You can use the following to get an idea of how flow/typescript parse
this:

    node -p "JSON.stringify(require('./src/parser').parse('\\'\\\\\'\\'', {parser: 'flow'}), null, 2)"
    node -p "JSON.stringify(require('./src/parser').parse('\\'\\\\\'\\'', {parser: 'typescript'}), null, 2)"

* WIP Disable Flow/Typescript for ./tests/directives

We don't yet handle escaped directives for them, but Babylon works.

(similar to 90bf93713c (diff-0de18284f37da79ab8af4e4690919abaR1))

* Revert "WIP Disable Flow/Typescript for ./tests/directives"

This reverts commit 2aba6231271f6985a395c31e3df9323e8f3da115.

* Prevent test strings from being parsed as directives

See https://github.com/prettier/prettier/pull/1560#issue-227225960

* Add more escaped directive tests

* Infer DirectiveLiterals from Flow parser

* Don't test TypeScript on directives

See https://github.com/prettier/prettier/pull/1560#issuecomment-300296221

* fixup! Infer DirectiveLiterals from Flow parser
2017-05-09 17:17:29 -04:00
Lucas Azzola 44934da349 feat(typescript): add fallback for JSX detection (#1551) 2017-05-08 05:57:19 -07:00
Lucas Azzola eabff629dd chore(build): update snapshot test (#1549) 2017-05-07 20:04:32 -07:00
Lucas Azzola fa27e5838c feat(typescript): add TSTypeAssertionExpression and naive TSX detection (#1545) 2017-05-07 08:09:52 -07:00
Lucas Azzola 3471ce4584 feat(typescript): print semi instead of comma in TS interface (#1548) 2017-05-07 07:39:21 -07:00
Lucas Azzola f655233ba2 fix(typescript): handle declare global syntax (#1546) 2017-05-07 03:44:41 -07:00
Lucas Azzola 5cc7878902 fix(typescript): fix a handful of ast(prettier(input)) issues (#1544) 2017-05-06 22:34:47 -07:00
Lucas Azzola 92d5a57122 fix(typescript): add TSNamespaceFunctionDeclaration to ast-types (#1543) 2017-05-06 21:33:07 -07:00
Lucas Azzola 0fa38cce33 fix(typescript): remove extraneous newline with namespace exports (#1542) 2017-05-06 20:28:49 -07:00
Lucas Azzola e22bd00815 fix(typescript): ArrowFunctionExpression needs parens in TSAsExpression (#1541) 2017-05-06 20:03:17 -07:00
Lucas Azzola 5fd9cd01de test(typescript): do not fail debug check on Literal -> Identifier (#1540) 2017-05-06 19:39:19 -07:00
Lucas Azzola 3d45278ea7 fix(typescript): print readonly and ? tokens in TSMappedType (#1535) 2017-05-06 10:30:59 -07:00
Lucas Azzola 4629db6b0d TypeScript: improve handling of computed properties (#1532)
* fix(typescript): improve handling of computed properties

* test(typescript): add Symbol computed property test

* fix(typescript): do not print brackets for literals
2017-05-06 08:00:26 -07:00
Lucas Azzola c337c83043 fix(typescript): workaround eslint/typescript-eslint-parser#257 (#1533) 2017-05-06 06:19:33 -07:00
Lucas Azzola 11e3d8241f TypeScript: print modifiers on TSIndexSignature and TSPropertySignature (#1531)
* fix(typescript): print modifiers on TSIndexSignature

* fix(typescript): print modifiers on TSPropertySignature and reformat TSMappedType
2017-05-06 06:18:23 -07:00
Lucas Azzola 8a8a67b9fe fix(typescript): print typeArguments in TSExpressionWithTypeArguments (#1530) 2017-05-06 06:17:48 -07:00
Igor Oleinikov f51822c16d fix(TypeScript): define TSFunctionType AST node (#1529)
- fixes printing of comments inside function type node
2017-05-05 22:14:12 -07:00
Christopher Chedeau bb232d48a3 Inline chained conditionals inside of jsx attribute (#1519)
Fixes #1515
2017-05-05 21:44:50 -07:00
Christopher Chedeau c63e21b52b Do not put parens for single argument with end of line comment (#1518)
Fixes #1517
2017-05-05 21:44:42 -07:00
Christopher Chedeau 3d964b18bb Add parens around `as` (#1528)
I put it at the same place where `a in b` is handled.

Fixes #1524
2017-05-05 21:39:20 -07:00
Christopher Chedeau c8984f392a Fix TypeScript regex (#1527)
Turns out n.value is NaN for regexes in typescript, go figure. Just moving the two if statements is working to fix the issue.

Fixes #1526
2017-05-05 21:39:11 -07:00
Lucas Azzola b9a7549e47 TypeScript: correctly print nested namespaces (#1522)
* fix(typescript): correctly print nested namespaces

* test(typescript): update snapshots
2017-05-05 21:14:07 -07:00
Lucas Azzola b23c16d05d fix(typescript): print typeParameters on TSMethodSignature (#1523) 2017-05-05 21:11:13 -07:00
Lucas Azzola c689f2a0e7 Fix module block, add enum initializers and fix type parameters (#1501)
* fix(typescript): fix module block, add enum initializers and fix type parameters

* fix(typescript): use printStatementSequence for TSModuleBlock

* fix(type-params): move typeParameters out of printFunctionParams

* refactor(type-params): move typeParameters out of printArgumentList
2017-05-05 19:44:26 -07:00
Kevin Gibbons e290514a9e Parenthesize `new F(await a)` and `x[await a]` correctly (#1513) 2017-05-05 08:10:56 -07:00
Brian Ng ccf509abb6 Fix empty line with flow union (#1511) 2017-05-04 19:06:30 -07:00
Christopher Chedeau 1a1e6fc1dd Print empty member lookup (#1506)
I have no idea if it's even valid but it threw on 8 typescript tests, now it doesn't.

```js
TypeError: Cannot read property 'type' of null
at printMemberLookup (prettier/src/printer.js:3062:16)
```
2017-05-04 11:20:52 -07:00
Danny Arnold 1fca1eeddf add TSTypeParameter to typescript ast nodes (#1508) 2017-05-04 11:20:35 -07:00
Danny Arnold 14636947b6 add TSParameterProperty to typescript ast nodes (#1507) 2017-05-04 11:19:50 -07:00
Danny Arnold c1a8ee011d add TSAbstractKeyword (#1505) 2017-05-04 09:48:24 -07:00
Christopher Chedeau bdf6050434 Do not throw on an empty file with a ; (#1503)
Fixes "TypeError: Cannot read property 'replace' of undefined"

This was discovered by #1480 and also affects non-typescript
2017-05-04 09:40:11 -07:00
Danny Arnold e6eee0467d add TSConstKeyword (#1502) 2017-05-04 09:37:00 -07:00
Kevin Gibbons 886f70fcdf Put loop bodies on the same line when possible (#1498) 2017-05-03 15:50:48 -07:00
Christopher Chedeau 8613046fd2 Respect template inline-ness (#1497)
In 1.3.0, we shipped a change that makes template literal always inlined as single arguments of a function. The problem with template literals is that they whitespace is significant so we can't change it. There are two cases:

```js
call(`
  template
  template
`);
```

and

```js
call(
  `template
   template`
);
```

If you always make the same decision to inline, you're going to be wrong for the other use case. The solution that I found that works is to figure out if there's a `\n` before the backtick `` ` ``. If that's the case, then don't inline, otherwise do. We're trying to avoid looking at the source as much as possible but this is one example where we actually don't have a choice if we want to keep the output sane.

1.3.0 made the jest codebase significantly worse because of this. The issue is that once things have been moved, this heuristic won't be able to undo it. So people need to have this fix applied before they run 1.3.0, otherwise it's going to damage their codebase unless they manually change everything back, which is a pain. So I'm going to land this as a hotfix in 1.3.1.

Fixes #1492
2017-05-03 14:35:58 -07:00
Davy Duperron 9e345c8527 Drop htmlEscapeInsideAngleBracket function in favour of raw/extra.raw from Flow/Babylon parsers (#1165)
* Make slice simpler.

* Drop htmlEscapeInsideAngleBracket function.

Use child.extra.raw (Babylon) and child.raw (Flow) to get the value instead.

* Remove unused htmlEscapeInsideAngleBracket function.

* Update test cases accordingly.

* Fix merge conflict.

* Update tests via `npm test -- -u`.

* Fix multiple consecutive spaces preservation in printJSXChildren.

* Update tests accordingly.
2017-05-03 08:47:15 -07:00
Lucas Azzola aeeaffca35 Fix handling of new keyword and call signatures and improve type parameter formatting (#1491)
* fix(typescript): fix handling of new keyword

* fix(typescript): fix handling of call signatures

* feat(typescript): share type parameter formatting with flow
2017-05-03 08:01:45 -07:00
Lucas Azzola 59b348f550 Implement TypeScript keywords, namespace functions and class heritage (#1483)
* feat(typescript): #1480: implement *Keyword, namespace function and class heritage

* feat(typescript): add type params and modifiers to interfaces

* chore(style): add squigly wings to if/else blocks

* fix(typescript): remove hardline before declare
2017-05-02 17:06:25 -07:00
Danny Arnold e8a80ca0aa fix #1484 (#1487)
* don't print colon if there is no `typeAnnotation`
* print prefix also for empty interfaces
2017-05-02 16:03:51 -07:00
Danny Arnold 5cf1659acf add TSDecorator (#1488) 2017-05-02 16:03:23 -07:00
Christopher Chedeau 078572631f Inline template literals as arrow body (#1485)
Turns out I wrote the wrong one :(

Fixes #1465
2017-05-02 09:17:20 -07:00
Christopher Chedeau f59aeef865 Break inline object first in function arguments (#1453) (#1173)
This is getting subtle where the groups need to be in a precise position but that works :)

Fixes #1409
2017-05-01 19:12:53 -07:00
Christopher Chedeau 8f9bb3a223 Break inline object first in function arguments (#1453)
This is getting subtle where the groups need to be in a precise position but that works :)

Fixes #1409
2017-05-01 14:49:03 -07:00
Christopher Chedeau 54b8cac0a7 Reorder flow object props (#1451)
This is very sad, but we need to do this to get the correct result :(

Fixes #1448
2017-05-01 14:42:52 -07:00
Christopher Chedeau c99a877b9f Do not break on [0] (#1441)
In practice, we never want to break on `[0]`. By not doing that, it forces prettier to find a more suitable break placement.

Fixes #1418
2017-05-01 14:41:34 -07:00
Christopher Chedeau acfb14f577 Don't break on empty arrays and objects (#1440)
We never want to break on those at it looks very weird. The reason why I didn't add this yet is because whenever it triggered in the past, the root cause was something else and it helped identify things to fix. But now the remaining ones I'm seeing are no longer underlying issues and they're just about this breaking unnecessarily, so we should just fix it.
2017-05-01 14:41:18 -07:00
Christopher Chedeau bafd72418e Don't break for unparenthesised single argument flow function (#1452)
This has been reported internally. It looks --very-- weird to have it indented the way it was.
2017-05-01 14:39:46 -07:00
Christopher Chedeau a335c26253 Add space around `=` for flow generics default arguments (#1476)
We have a space for function arguments and it looks weird without.
2017-05-01 14:39:15 -07:00
Christopher Chedeau 4b7d265000 Fix windows line ending on template literals (#1439)
Fixes #1432
2017-05-01 14:39:03 -07:00
Christopher Chedeau e39209386c Only add parenthesis on ternaries inside of arrow functions if doesn't break (#1450)
This was added in order to follow some eslint rule but it's only confusing when it doesn't break, when it breaks the indentation makes it clear what is happening and you don't need parenthesis.

Fixes #1379
2017-05-01 14:32:52 -07:00
Christopher Chedeau 93cad97b14 Preserve inline comment as last argument (#1390)
We already had the logic but only applied it for comments on their own line, we should also do it if they are inline.

Fixes #1380
2017-05-01 14:29:03 -07:00
Christopher Chedeau 314e96322c Add parenthesis for unusual nested ternaries (#1386)
All of the discussions around ternaries are for the form

```js
cond1 ? elem1_if : cond2 ? elem2_if : elem_else
```

but some of them are for the form

```js
cond1 ? cond2 ? elem2_if : elem2_else : elem1_else
```

which is more rare and would be good to call out by adding parenthesis.

```js
cond1 ? (cond2 ? elem2_if : elem2_else) : elem1_else
```

Note that we only want parenthesis if it's written inline, otherwise the indentation is good enough to understand the flow:

```js
cond1
  ? cond2 ? elem2_if : elem2_else
  : elem1_else
```
2017-05-01 14:28:36 -07:00
Christopher Chedeau 13f05fb763 Proper indentation for template literals (#1385)
Right now, expressions inside of template literals are have the level of indentation of the start of the template literal. But oftentimes, expressions are nested inside of template literals and therefore the expression should have this level of nesting.

The heuristic i'm using to decide when to use the template literal nesting is if it's not the first line and if there isn't another expression before on the same line.
2017-05-01 14:28:11 -07:00
Christopher Chedeau c521406385 [RFC] Do not indent calls with a single template literal argument (#873)
I'm not sure that this is a good idea. A current workaround is to remove the parenthesis.

Fixes #786
2017-05-01 14:27:00 -07:00
Danny Arnold 5ee0385d79 [WIP] add TSNamespaceExportDeclaration (#1459)
* add TSNamespaceExportDeclaration

* extract ast-types/fork

* add TSEnumDeclaration and TSEnumMember

* add TSImportEqualsDeclaration and TSExternalModuleReference

* add TSInterfaceDeclaration and type annotation to TSMethodSignature

* add TSModuleDeclaration, TSDeclareKeyword, TSModuleBlock and fix TSNamespaceExportDeclaration

* remove workaround
2017-05-01 09:25:49 -07:00
Danny Arnold bff2d48aa8 update typescript snapshots to account for #1464 (#1470) 2017-05-01 07:22:05 -07:00
Alessandro Di Felice bfe3161762 Break class expression returned by arrow call (#1464) 2017-04-30 17:49:31 -07:00
Lucas Azzola 7d1e24ea7d Add supertype tests and add TSAbstractClassProperty (#1467)
* feat(typescript): add supertype tests and add TSAbstractClassProperty

* chore(typescript): bump parser version

* fix(flow): allow both variance and accessibility mods
2017-04-30 17:41:19 -07:00
Christopher Chedeau 3161bd0787 Upgrade flow parser to 0.45 (#1447)
This fixes all the unicode issues and spacing between elements in array.

Fixes #1336
Fixes #1427
Fixes #770
2017-04-27 14:59:18 -07:00
Kevin Gibbons e75d3a4af3 Require '(a || b).c++' to have a preceding ; in no-semi style (#1443) 2017-04-27 14:00:53 -07:00
Kevin Gibbons 10a5f68a12 Require '::a.b' to have a preceding ; in no-semi style (#1442) 2017-04-27 14:00:04 -07:00
Brian Ng b2a092bd17 Allow flow declarations to break on StringLiteralTypeAnnotations (#1437)
* Allow flow declarations to break on StringLiteralTypeAnnotations

* canBreak
2017-04-27 11:21:42 -07:00
Lucas Azzola 7a02e9ad27 feat(typescript): add delcare modifier support for vars, classes and functions (#1436) 2017-04-27 09:37:42 -07:00
Brian Ng 9c826c2ed5 Inline nullable in flow generics (#1426) 2017-04-26 09:27:06 -07:00
Lucas Azzola fff743024c Add TSParameterProperty, TSAbstractClassDeclaration and TSAbstractMethodDefnition (#1410)
* feat(typescript): implement TSParameterProperty

* test(typescript): add TypeScript's classes/constructorDeclarations/constructorParameters tests

* feat(typescript): implement TSAbstractClassDeclaration and TSAbstractMethodDefinition

* test(typescript): add TypeScript's classes/classDeclarations/classAbstractKeyword tests

* fix(build): use join instead of spread operator

* fix(typescript): fix semicolon handling

* fix(typescript): handle accessibility modfiers in TSAbstractMethodDefinition

* test(typescript): remove invalid test results

* test(typescript): remove unimplemented abstract properties from tests

* test(typescript): add snapshots for abstract keyword newline behavior
2017-04-26 09:25:58 -07:00
Danny Arnold 0a7e462ad7 add TSMethodSignature (#1416) 2017-04-25 14:15:33 -07:00
Danny Arnold 90762bb111 fix VariableDeclarator not printing type parameters (#1415) 2017-04-25 14:08:30 -07:00
Davy Duperron c609a5415a [experimental] Add linting step in test pipeline (#1172)
* Add eslint as dev dep, reorder scripts.

* Add tests & docs to eslintignore.

* Add eslintcache to gitignore.

* Update yarn lock file 😽.

* Add linting step in the test pipeline.

* Add a set of really basic rules for linting.

* Fix linting 🚀.

* No need for .jsx files to be linted...

* Reorder rules alphabetically.

* Refine rules: drop styling ones, only keep what provides dead code elimination.

* Add no-console rule to be consistent along with the no-debugger one.

* Remove empty line.

* Add eslint-disable-next-line no-console where console log/warn/error are allowed.

* Drop no-console rule.

* Remove eslint-disable-next-line no-console comments.

* Remove linting step in Travis CI.

* Fix linting after merging current master.

* Run `npm test -- -u` after noticing one test was out of sync.

* Drop eslint references from previous implementation.

* Revert yarn lock file.

* Revert scripts ordering.

* Fix incorrect yarn lock file.
2017-04-25 09:48:56 -07:00
Christopher Chedeau a7319dbbbb Fix optional flow parenthesis (#1357)
In #1251, we now have a proper whitelist of all the types that should have parenthesis. Turns out, it included NullableTypeAnnotation which is `?a`. For `?a => void` this wasn't needed but for `(?(a => b)) => c` it was! It's better to always put it anyway if it's not just a simple literal.

I've added tests for all the combinations I could think of, so we'll catch regressions if they happen.

Fixes #1353
2017-04-24 16:58:30 -04:00
Danny Arnold 6f0cc31fdb add TSIntersectionType (#1395)
* add TSIntersectionType

* use same print implementation for flow and typescript
2017-04-23 10:27:40 -07:00
Danny Arnold 5f5566e4ef fix TSFunctionType failing on TypeParameters (#1394) 2017-04-23 10:17:03 -07:00
Danny Arnold 44e55f7fa7 add TSMappedType and TSTypeParameter (#1393)
* add TSMappedType and TSTypeParameter

* respect bracketSpacing in TSMappedType
2017-04-23 10:16:25 -07:00
Danny Arnold 150c701191 fix TSTypeReference not printing typeArguments (#1392) 2017-04-23 08:31:50 -07:00
Danny Arnold 15df9abf81 add TSTypeOperator (#1396) 2017-04-23 08:25:25 -07:00
Danny Arnold 95d505843e parent decides how to print type annotations (#1391) 2017-04-22 18:09:53 -07:00
Vinh Le d0e8976af8 Fix empty line in block with EmptyStatement (#1375)
* Fix empty line in block with EmptyStatement

* Update code per review
2017-04-22 07:57:52 -07:00
Brian Ng c0a0bf46bc Fix missing trailing commas on flow generics (#1381) 2017-04-21 13:57:21 -07:00
lemon79 96e5c889e3 fix do-while break (#1373)
* fix do-while break

* added test for long while statement

* update snapshot

* merged with prev changes
2017-04-21 08:03:53 -07:00
Danny Arnold 99e4bae321 add TSConstructorType (#1367)
* add TSConstructorType

* combine condition

* combine strings
2017-04-21 07:57:26 -07:00
Danny Arnold 9002379b70 add TSLastTypeNode and TSIndexedAccessType (#1370) 2017-04-20 18:01:34 -07:00
Brian Ng 93f040a9ea Skip trailing commas with FlowShorthandWithOneArg (#1364) 2017-04-20 14:46:41 -07:00
Danny Arnold d823fe6fca add printer branches for some TypeScript nodes (#1331)
* add TSNeverKeyword

* add TSUndefinedKeyword

* add TSSymbolKeyword

* add TSNonNullExpression

* add TSThisType

* add tests for simple typescript nodes
2017-04-19 15:41:18 -07:00
Christopher Chedeau bae08d4e7e Only break for conditionals (#1350)
We only want to break for && and ||, not for ===
2017-04-19 13:18:01 -07:00
Christopher Chedeau 007cfd9179 Fix duplicate comments in classes (#1349)
Turns out, you can't blindly print this node. We need a deeper fix but let's revert this fix for now.

Fixes #1348
2017-04-19 11:59:23 -07:00
Christopher Chedeau 3dc7562743 Don't inline paren at right of arguments (#1345)
Fixes #1338
2017-04-19 10:44:00 -07:00
Christopher Chedeau aafcf5f381 Break if () if conditional inside breaks (#1344)
Fixes #868
2017-04-19 10:43:48 -07:00
Christopher Chedeau 042e603a6e Fix arrow function parenthesis with comments in flow (#1339)
`leadingComment` and `trailingComment` are babylon-specific, we should use `comments` which is what prettier adds.

Fixes #1335
2017-04-19 10:43:31 -07:00
Simon Lydell 938f0e3404 Improve regex printing (#1341)
- Print the raw regex for Flow, just like for Babylon.
- Sort regex flags.

Fixes #1334.
2017-04-19 10:24:13 -07:00
Danny Arnold cb79d82569 add printer branch for TSFirstTypeNode (#1332)
* add TSFirstTypeNode

* add test for TSFirstTypeNode
2017-04-19 09:03:55 -07:00
Kevin Gibbons 565106dd63 Add parentheses for assignment as body of arrow (#1326) 2017-04-18 13:28:33 -07:00
Christopher Chedeau 8d03423d17 Avoid breaking arguments for last arg expansion (#1305)
We've had this issue since the beginning and I tagged it as 1.0 but haven't managed to fix it by then. We shouldn't allow things to break in the argument list if we are in the last argument expansion mode. It turns out that we now have all the building blocks needed to fix this:
- have a special way to flag when we are printing the last argument expansion in the code that prints the argument list
- have a way to remove all the softlines from the argument list

Fixes #1301
2017-04-18 08:40:08 -07:00
Christopher Chedeau 5995af25a3 Bail when traversing === groups (#1294)
This is the second part of the fix for the performance regression seen in #1250. In #1217, for correctness reasons, we're now traversing all the conditional groups. This means that we're now in O(n^2). But, in practice, many of those groups are === between each others. So we only need to recurse through one of the instances to know if it's going to break.

This makes the first example go from not terminating to being instant. The second one going from not terminating to taking ~1s. We can also make it instant by tweaking the printing phase, but that's for another PR.
2017-04-18 08:39:47 -07:00
Christopher Chedeau 9cd4517a64 Fix template literal comments (#1296)
The implementation was checking if the comment was inside of the expression range, which seems like a good idea. Unfortunately, the expression range is not what's inside of `${}` but the actual AST node, which incidentally doesn't include comments. So the logic was off and returned `undefined` which threw afterwards.

Another solution is to find the first quasi where start is > comment start. This means that the comment appeared between the quasi before and this one... therefore in the expression before!

The flow parser has issues with unicode where it makes node location invalid, there are likely other places where node locations are off. So instead of throwing with a weird error, let's attach it to the first one if it doesn't work.

Fixes #1293
2017-04-17 11:35:12 -04:00
Janic Duplessis f3155c3fc1 Fix isPreviousLineEmpry on Windows (#1263) 2017-04-14 16:02:19 -07:00
Christopher Chedeau 17051ece2c [WIP] no-semi comments (#1257)
It doesn't yet work but I think it's close
2017-04-13 18:33:46 -07:00
Christopher Chedeau 6a259b60b5 Get rid of fixFaultyLocations code (#1252)
As I was debugging #1248, I found out that the code to fix was actually making things worse. The other two branches are for decorators and deleting some random value of a function. I ran all the tests and the flow object is actually now preserving empty lines and didn't change anything else.

I'd rather remove all those and if something comes up then fix it properly upstream than having those crutches that we don't know why they exist anymore.
2017-04-13 18:32:03 -07:00
Christopher Chedeau 9d616fc840 Remove trailing whitespace (#1259)
In #1257, I discovered that if there's a `""` doc at the end, it's not going to trim the previous one correctly. It also happens to fix a few existing things.
2017-04-13 18:31:49 -07:00
Jason Laster 2078225daa Fix flow union params (#1251) 2017-04-13 17:54:20 -07:00
Christopher Chedeau 97c662b87b Do not inline member expressions as part of assignments (#1256)
This is a regression from #1036 and #1188.

Fixes #1241
Fixes #1236
2017-04-13 20:09:00 -04:00
Christopher Chedeau 1a0067eae4 re-run tests 2017-04-13 09:26:36 -07:00
Christopher Chedeau fe7ebc0cf7 Fix edge cases triggered by newlines in arrow functions (#1217)
This one is pretty crazy. In #927, I changed

```js
concat(["(", join(concat([", "]), printed), ")"]),
```

into

```js
concat(["(", join(concat([", "]), printedLastArgExpanded), ")"]),
```

which makes the example in #1203 look ugly. The crazy thing is that `JSON.stringify(printed) === JSON.stringify(printedLastArgExpanded)`. So they are deep equal but not the same object. In a non-mutative world, this should cause any problem, but we actually mutate those to propagate breaks.

In the break propagation, we only looked at the first one in case of a conditional group. But, because the two were the same object then it also applied to the second one and happened to be the correct behavior! When I changed that piece of code to be two distinct objects, it no longer worked by accident and caused a bunch of weird issues where breaks didn't propagate correctly.

The solution for this case is to propagate the breaks on all the conditions. I'm pretty sure that this is the expected behavior, we want to deeply recurse in all of them, we don't propagate it up the boundary anyway.

The other use case for `traverseInDoc()` is `findInDoc()`, right now it searches for the first conditional group but it seems very arbitrary. I changed it to not search on any and none of the tests are failing, so I think it's safe(tm). If it triggers weird behavior, then it'll at least be expected and not randomly explode at us if we move groups around.

I tried to go through all the conditions for `findInDoc()` but it triggers a few failures (the output look bad). I'm not really sure why. https://gist.github.com/vjeux/5fb7566cc3d65974817d512d1ef6abe1

Fix #1203
2017-04-13 09:21:18 -07:00
Brian Ng 4d9edec4e1 Fix trailing comma for rest element in Babylon (#1230) 2017-04-13 07:10:08 -07:00
Brian Ng 4dfe92a76b Ensure JSXOpeningElement does not break with single text attr on Babylon (#1229) 2017-04-13 07:09:40 -07:00
Christopher Chedeau f68531a45d Fix overflow for last argument expansion (#1224)
In #847, I used a heuristic to find if the element was going to be expanded. But, it wasn't 100% accurate because we couldn't know in which conditionalGroup we would land. We added a way for the parent to tell that function if we should be in `expandLastArg`. By replacing the condition by this variable, it now fixes the issues!

This is so good that adding the right abstraction fixes problems across the board :)

Fixes #997
2017-04-12 20:24:50 -07:00
Christopher Chedeau 4a4e1817be Do not merge member chain if there's a comment in-between (#1218)
Fixes #1198
2017-04-12 17:26:58 -07:00
Christopher Chedeau 5d8ffd0c2e Fix own line last if comment (#1219)
Fixes #1205
2017-04-12 17:26:44 -07:00
Christopher Chedeau ee7cfa9501 Ignore empty statement in switch newline detection (#1220)
Fixes #1200
2017-04-12 17:26:31 -07:00
Brian Ng 3a7559be58 Preserve comment for last arg of ObjectMethod (#1216)
* Preserve comment after last arg of ObjectMethod

* Preserve comment after last arg with default value
2017-04-12 16:32:04 -07:00
Christopher Chedeau ea957ed64a Fix function trailing comment location (#1195)
It turns out that we can't reliably detect with the ast if a comment is before or after the ). In order to fix this same problem with `if` I added the `getNextNonSpaceNonCommentCharacter` function. We can use the same here to fix the problem.

Fixes #933
2017-04-12 14:18:29 -07:00
Brian Ng 32eecabc6d Stabilize comments on ObjectTypeAnnotation (#1214) 2017-04-12 14:13:34 -07:00
Jan Kassens b82220b20f Prittier printing of snapshots (#1190)
This uses a custom snapshot serializer to reduce escaping in snapshot files and
make them easier to read.

Snapshot serializers are documented here:
https://facebook.github.io/jest/docs/configuration.html#snapshotserializers-array-string
2017-04-12 13:41:51 -07:00
James Long 9a5b447c7f Propagate hard breaks within member expressions (fixes #1117) (#1193) 2017-04-12 09:26:27 -07:00
Alex Rattray 36bec87d17 Enable no-semi mode and protect against ASI failures (#1129) 2017-04-11 13:50:47 -07:00
Christopher Chedeau e3aa878187 Allow to break for member expressions after = (#1188)
This should address a concern of #1036
2017-04-11 11:37:46 -07:00
Christopher Chedeau 523f64ff14 Add ability to break for top member expression (#1036)
It turns out that the top member expression doesn't go through the member chain logic. Let's give it the ability to break for now.

Fixes #1031
2017-04-11 11:37:35 -07:00
Christopher Chedeau b6edf96cc4 Improve jsx output for style components (#1144)
* Hug template literals inside of JSXExpressionContainer

We already hug a bunch of things inside of `{}`. It seems that it's a good idea to do it for template literals as well. I don't think I've seen anyone actually indent them.

Fixes #1090

* Inline jsx elements with single template literal expression

If there is a single expression and a single template literal, then a lot of people in the jsx-style world inline it. I've also myself used this for markdown and printed it that way. So we probably should print it that way.

Note that I'm checking for children.length === 1, this means that if there's any whitespace, this is not going to be true and will not enter this case. So it WON'T reformat

```js
<style>
  {`
     color: red;
  `}
</style>
```

into

```js
<style>{`
    color: red;
`}</style>
```

which is great. You have to opt-in to the second style in order to get it.

Fixes #1090
2017-04-11 09:33:02 -07:00
Christopher Chedeau 2e63684ff5 Add parenthesis for no-confusing-arrow rule (#1182)
I'm unclear whether anyone was ever confused by this but the eslint page is kind of compelling

```js
// The intent is not clear
var x = a => 1 ? 2 : 3;
// Did the author mean this
var x = function (a) { return 1 ? 2 : 3 };
// Or this
var x = a <= 1 ? 2 : 3;
```

Adding a parenthesis makes it valid with `{"allowParens": true}` rule. Note that if this option is not enabled, the code would not pass lint in the first place.
2017-04-11 09:20:39 -07:00
Christopher Chedeau e0eb438e7b Add newline for bracket-less arrow functions that return calls (#927)
I've tried a lot of places where to fix this and this is the only one that gives correct results. This is likely not exhaustive but works for that use case. It's been reported twice in issues and I've seen it happen a few other times so we probably want to get it fixed.

Fixes #922
Fixes #797
2017-04-11 08:50:49 -07:00
Christopher Chedeau 636d1af19e Add parenthesis for binary operators (#1153)
Fixes #872
2017-04-10 18:31:52 -07:00
Christopher Chedeau da7c97e0bb Stabilize label comments (#1179)
Fixes #1160
2017-04-10 11:22:35 -07:00
Christopher Chedeau 45796601c4 Fix last comment of an if test (#1042)
This one sucks.

The range of the `test` of `if (a /* comment */) {}` is only `a` and doesn't include the comment nor parenthesis. This means that we have no way to know if the comment is placed before or after the `)` unless you look at the actual source and strip all the whitespace/comments characters to see if it's a `)`...

This happened on the babel source code twice and many times in the fb codebase. I think we need to fix it unfortunately :(

Fixes #867
2017-04-10 11:05:10 -07:00
Christopher Chedeau f51c5daacb Fix comment detection before comma (#1127)
We need to call the `skipToLineEnd` which skips `,` after an inline comment. So we have to put it inside of the while loop as you can have many comments, a comma and then many more comments.

Fixes #964
2017-04-10 11:03:35 -07:00
Christopher Chedeau 0669160adc Fix last argument comment for function declaration (#1176)
We already handle this but forgot to do it for FunctionDeclaration

Fixes #1166
2017-04-10 10:55:29 -07:00
Christopher Chedeau 11ee5529a5 Add parens around arrow function return type (#1152)
Fixes #1151
2017-04-10 10:51:31 -07:00
Christopher Chedeau 3d64e789b5 Improve printing of chained interesctions (#1155)
Now properly indents all the combinations of objects and non objects.

Fixes #1076
2017-04-10 10:50:38 -07:00
Christopher Chedeau 6bff3f2de8 Fix switch new lines (#1156)
.#1136 accidentally removed all the empty lines between statements inside of switch cases. I just brough back the logic and made sure to only use it for everything but the last line.
2017-04-10 10:50:02 -07:00
Christopher Chedeau 8cc5f22090 Fix parenthesis when call inside of new (#1169)
Fixes #1167
2017-04-10 10:49:13 -07:00
Christopher Chedeau 6552257ab0 Stabilize else comments (#1177)
In #544, I fixed it for all the cases but didn't check for else :(

Fixes #1161
2017-04-10 10:46:44 -07:00
Christopher Chedeau 3eda5fb885 Print return dangling comment (#1178)
Fixes #1157
2017-04-10 10:46:25 -07:00
Christopher Chedeau 0e2bc09409 Properly handle \r\n in JSXText (#1170)
Fixes #1168
2017-04-09 16:37:54 -07:00
Davy Duperron d1191adce6 Fix ampersand in jsx href and src (#1056)
* Add exceptions for html escape usage in href and src attributes.

* Add new test cases.

* Remove useless spaces.

* Do not escape if the parser does not do so.

* Implement a different heuristic for keeping along with the parser.

* Update tests.

* Forgot passing options as param.

* Experimental alternative implementation.

* Remove other function.

* Push test after merge.

* Update getJsXRawValue in order to return the unprocessed raw value.

Latest Babylon version includes a fix that allow us to directly
inject the unprocessed raw value available in the `extra.rawValue`
property of the node. A last transformation is applied by replacing
double quotes to `&quot;` entities.

* Drop unused htmlEscapeInsideDoubleQuote function.

* Move getJSXRawValue function logic to the its only call, drop it.

A simple check is performed to determine if the parser is babylon or
flow via `n.value.extra`. Thus, the corresponding raw value is
extracted. If we are converting a string from single quotes to
double quotes, we need to make sure that double quotes are converted
to &quot;.

* Remove ambiguous comment.

* Add Babylon parser.

* Update test cases accordingly, revert regression introduced previously.
2017-04-08 07:55:50 -07:00
Simon Lydell dc93bdc983 Sync the Flow tests (#1163)
* Extract custom tests from tests/flow/

Approach:

1. Remove all .js files in tests/flow except .snap.js files.
2. Copy over all .js files from tests/ in the flow repo.
3. Go through the diff looking for deletions.
   - It was easy to see which deletions were due to changes in the tests
     due to updates in the flow repo.
   - For the rest of the deletions, I used `git blame` to verify that
     they had been added by us since the flow tests were copied over.

This makes tests/flow/ simply a copy of the tests from the flow repo,
making it easier to sync with the upstream flow tests in the future.

* Add a script for syncing the flow tests

* Sync the flow tests
2017-04-08 07:52:38 -07:00
Christopher Chedeau 41dee70795 Allow to break after = for strings (#1142)
This is not a general fix but it solves some issues that people are seeing where prettier goes > 80 columns.

Fixes #1141
Also fixes part of #1110
2017-04-07 10:51:02 -07:00
Christopher Chedeau 6b806d4411 Re-run snapshot tests 2017-04-07 09:37:53 -07:00
Christopher Chedeau f69b26081f Stabilize VariableDeclarator comments (#1130)
Fixes #932
2017-04-07 07:57:44 -07:00
Brian Ng 651cce2066 Import new_spread flow tests (#1138) 2017-04-05 17:39:11 -07:00
Brian Ng 2e96574941 Switch to new test syntax for flow predicate tests (#1137) 2017-04-05 16:32:55 -07:00
Lucas Duailibe 8e9fb43841 Fix trailing comment on switch case (#1136)
* Fix trailing comment on switch case

* Use unshift and add another test case
2017-04-05 16:27:14 -07:00
Alex Rattray d0666c3da4 Fix leading comment inside returned SequenceExpression (#1133) 2017-04-05 13:41:35 -07:00
Joseph Savona fe5de43cd7 Fix printing of Flow type number literals (#1128) (#1132) 2017-04-05 13:22:23 -07:00
Lucas Duailibe 69879e23bc Print comment after key (#1131) 2017-04-05 13:10:10 -07:00
Christopher Chedeau 926f9c4dfb Handle unconventional newlines (#1050)
The `\r` test has had to be deleted because jest doesn't properly save and parse the snapshot back.

Fixes #883
2017-04-05 10:54:39 -07:00
Eric Clemmons 61ad2f1d34 "// prettier-ignore" position within comments doesn't matter (#1126)
* // prettier-ignore can be within any part of the comment block

* Add test for // prettier-ignore being anywhere within comments
2017-04-05 10:51:20 -07:00
Eric Clemmons def91efd16 Support "// prettier-ignore" in comment blocks (#1125)
* // prettier-ignore has to be last comment

* Add test for #1109
2017-04-05 10:08:08 -07:00
Christopher Chedeau b2c63b291d Fix spread snapshot test (#1119)
See https://github.com/prettier/prettier/pull/1064#discussion_r109787248
2017-04-04 18:44:48 -07:00
Christopher Chedeau 1578e180f4 Add support for flow type spread in .43 and babylon beta8 (#1064)
Fixes https://twitter.com/ryyppy/status/844116626467438592
2017-04-04 14:52:16 -07:00
Christopher Chedeau 6c9cb86a6d Ability for interface to break (#1060)
We break on `class` before `extends` but didn't for `interface`. Now we do in the same way. Also TIL that `interface` was an actual keyword in JavaScript :P
2017-04-04 14:25:17 -07:00
Brian Ng d9a4efcc35 Bump babylon to 7.0.0-beta.8 (#1118)
* Bump babylon version

* Enable flow predicate tests in babylon
2017-04-04 14:21:56 -07:00
Simon Lydell 96b0a33cff Fix printing of exact object flow type annotations (#1114)
Fixes #1089.
2017-04-03 10:24:36 -07:00
ChristianHersevoort 04c959d687 Feature/verify against same snapshot (#1087)
* Verify parsers against same snapshot

- Reworked run_spec, now accepts 3th optional array argument for
additional parsers to verify against
- Merged duplicate run_spec configs
- Removed duplicate snapshot data

* Formatted run_spec.js with prettier

* Fixed node4 incompatibility
2017-03-25 08:10:17 -07:00
Christopher Chedeau 60816af4ce Add support for currying (#1066)
If you write your code in a functional way where you have an arrow function for each argument, it looks better for them to be inline. I can't imagine any case where it would be used in a different way if we limit to a single argument.

Fixes #1065
2017-03-22 13:33:28 -07:00
Christopher Chedeau dd792a2b22 Fix tests 2017-03-22 10:20:42 -07:00
Christopher Chedeau dc0fbf7822 Special logic for flow intersection (#1018)
We started using the same logic for union and intersection but then added a special case for `a & {}`. It turns out that they should be handled completely differently in practice.

The heuristic i'm using is if you go from object to non-object or vis-versa, then inline, otherwise go to the next line and indent (like &&).

Fixes #864
Fixes #1017
2017-03-22 10:01:34 -07:00
Christopher Chedeau 04eba07aab Hug on single object destructuring function (#1022)
This is very common for stateful react functional components. It also matches last object expansion. I think that we should only do that for a single argument in function definitions though, unlike the last for function calls.

Fixes #1019
2017-03-22 09:58:33 -07:00
Brian Ng 42910424a1 Fix parsing flow variance on babylon 7 (#1069)
* Enable babylon on variance tests

* Fix parsing flow variance in babylon 7
2017-03-22 09:37:26 -07:00
Davy Duperron dfd42d8306 Fix class method comments (#1074)
* Add new helper function for printing ClassBody comments.

* Update tests.
2017-03-22 09:26:27 -07:00
Brian Ng 41977c293e Add support for ForOfStatement with await flag (#1073)
* Enable babylon on flow async_iteration tests

* Add support for ForOfStatement with await flag
2017-03-22 09:23:57 -07:00
Christopher Chedeau c3199359b0 Revert "Improve snapshot naming" (#1070)
* Revert "Remove mutation in `printBinaryishExpressions` (#1067)"

This reverts commit e7312ad7b2.

* Revert "Make it clear what parser was used in each snapshot (#1068)"

This reverts commit 4f7ae4815b.
2017-03-21 17:38:28 -07:00
ChristianHersevoort 4f7ae4815b Make it clear what parser was used in each snapshot (#1068) 2017-03-21 14:47:23 -07:00
Christopher Chedeau ce6e897950 [RFC] Fix comment location for binary expressions (#1043)
The root cause is that we're calling `printComments` with an empty string, meaning that the leading/trailing comments are not correctly inserted at the right location.

So, the way to fix it is to call `p => concat(parts)` but because we're mutating the array in place, it doesn't work. We need to mutate it and create a copy. But, the root call is actually checking the shape of the parts array which our code is now breaking...

```js
          // Don't include the initial expression in the indentation
          // level. The first item is guaranteed to be the first
          // left-most expression.
          parts.length > 0 ? parts[0] : "",
```

The consequence is that binary expressions are no longer indented if the first expression has a comment (but now it places the comment properly!), which seems like a good trade-off.

I'm not sure if we should merge this one or instead refactor this code such that it doesn't rely on mutation and looking at the shape of the printed tree. `printMemberChain` is a good thing to reference for inspiration.

Fixes #946
2017-03-21 12:13:13 -07:00
Davy Duperron 389d9d0fad Fix unstable comments in assignment pattern (#1055)
* Add handleAssignmentPatternComments print function.

* Add new test cases.
2017-03-20 18:49:42 -07:00
Christopher Chedeau 553966345a Fix comment sorting location (#1038)
Right now it's only doing one test for begin/end, but in the issue #1037, we have two nodes that have the same start but different end. The current implementation incorrectly sorts them and the identifier ends up being before the container and therefore the comment search doesn't recurse into it.

Fixes #1037
2017-03-20 10:21:54 -07:00
Christopher Chedeau 569791a57a Update babylon to 7.0.0-beta.4 (#1047)
Fixes #700
2017-03-20 12:46:31 -04:00
Christopher Chedeau b012f7531e Fix comments inside of ObjectPattern (#1045)
ast-types was missing a type, I sent a PR on ast-type ( https://github.com/benjamn/ast-types/pull/211 ) which was merged and released (thanks @benjamn for being super quick!). So I'm upgrading ast-types and add the test in this PR.

Fixes #1007
2017-03-20 12:42:07 -04:00
Christopher Chedeau a502bf9f45 Add ability for flow generics to break (#1041)
While looking at an instability on the React codebase ( ba1299acc2 (diff-2550aa3d377452ae29361f5e53c51c10) ), I realized that we don't let them break which makes the code look weird.

So I added the ability for them to break :)
2017-03-20 12:35:30 -04:00
Christopher Chedeau 82d6e0b4ab Unrestrict flow union comments check (#1040)
I was being very careful by checking all the surrounding types but it actually turns out we want this behavior all the time.

Fixes #931
2017-03-20 12:33:42 -04:00
Christopher Chedeau a9185cb30e Stabilize comment on member chain with three elements (#1039)
We already had a special case for it for a group of 2 elements but now that we are also going in this codepath for 3 if we merge, then we need to do the same here.

Fixes #930
2017-03-20 12:32:49 -04:00
Rasmus Eneman e41ed4955d [WIP] Add some typescript tests (#1033)
* Add some typescript tests

* fix: Remove extraneous colon in type parameter constraint

* style: Add missing newline at EOF in TS tests

* feat: Pretty print typescript object type annotations

* feat: Pretty print TSFunctionType

* fix: Type annotations was missing on class properties

* Add a new batch of tests

* Bump typescript-eslint-parser

* Add a new batch of tests and fix a syntax error in previous

* Bump typescript-eslint-parser
2017-03-19 08:06:52 -07:00
Christopher Chedeau c749ddd508 Add parens around return for binaryish expressions (#870)
It looks better when the first element is aligned with the rest and this is consistent with the way we render `if` test.

Fixes #866
2017-03-18 19:35:09 -07:00
Royce Townsend 9eb389b9f4 Group first arg for inline functions (#947)
* Group first arg for inline functions

* Group first arg. Unless there are comments.

* Group first arg. Allow second arg to be empty object/array.

This implementation has a side effect of disallowing empty objects/arrays in the should group last arg heuristic.
2017-03-18 11:20:07 -07:00
James Long eeae443b43 Separate `if` and `else` groups (fixes #616) (#1032) 2017-03-17 14:02:35 -07:00
Christopher Chedeau dc52a71923 Inline class expressions for bracket-less arrow functions (#1023)
I could go either way but it doesn't seem a big deal to inline them. I don't expect it to be very common anyway

Fixes #990
2017-03-17 14:01:17 -04:00
Christopher Chedeau 16ed595086 Preserve comment position for last arg or method (#1025)
In #856, it handled a bunch of cases but missed class methods

Fixes #905
2017-03-17 14:00:01 -04:00
Christopher Chedeau 35547993d4 Add breakParent support for willBreak (#674)
* Add breakParent support for willBreak

Fixes #615

* Update snapshots from previous commit
2017-03-17 13:51:22 -04:00
Davy Duperron 748dcbf70d Fix import declaration comments (#1030)
* Add handleImportDeclarationComments function.

* Fix indent.

* Update test cases accordingly.

* Implement better heuristic for adding comments.

* Make the test case more exhaustive.
2017-03-17 08:11:43 -07:00
Davy Duperron dde8463ad9 Fix additional empty line switch case comment (#936)
* Refactor condition in printStatementSequence, add new helper function.

* Add new test cases.

* Move logic in SwitchCase case.

* Revert unrelated changes, remove unecessary variables.

* Use util.getLast helper function.

* Move variables out of the loop.

* Simplify code.

* Fix mapping with mutated path.
2017-03-17 08:08:36 -07:00
Hampus Ohlsson 76e26f08a0 Fix dot notation in decorators (#1029) 2017-03-16 13:27:20 -07:00
Davy Duperron 915967b974 No parenthesis for Flow shorthand with one arg (#972)
* Implement checking for not printing the parens in this case.

* Add test case.

* Remove parent type checking.

* Fix test accordingly.

* Refactor to a better heuristic.

* Add new test cases.

* Fix implementation.

* Fix unnecessary function call.

* Add new test cases 🚀.

* Use isObjectTypePropertyAFunction and create isTypeAnnotationAFunction.

* Add missing space.

* Add new test cases.
2017-03-16 10:32:59 -07:00
Christopher Chedeau 3a80345e0c re-run snapshot tests 2017-03-15 18:54:34 -07:00
Brian Ng b8a7e5166b Add parens for ConditionalExpression inside JSXSpreadAttribute (#1015) 2017-03-15 18:52:31 -07:00
Davy Duperron c82bb4e003 Fix exports (#998)
* Fix printExportDeclaration function.

* Update tests accordingly.

* Remove commented line.

* Run npm test -- -u to update and fix tests.
2017-03-15 16:29:15 -07:00
Christopher Chedeau 7105f972b4 [RFC] Add softline to assignment of binary expressions (#871)
Printing the first line of a binary expression next to the `=` leads to weird cases where the first expression is parenthesised and doens't read well with chained conditionals as they don't align well. This makes it behave the same was as `if` tests.

Fixes #863
2017-03-15 09:45:40 -07:00
Dan Harper 332babe77d Fix single optional arrow param printing (#1002) 2017-03-15 09:38:13 -07:00
Brian Ng a2b560887c Add support for breaks in TupleTypeAnnotation (#1003) 2017-03-15 09:35:22 -07:00
Christopher Chedeau 36a1d12f47 Do not respect newlines for object destructuring pattern (#981)
This was intended for object expressions. I tried to remove it for ObjectTypeAnnotation but it changes a ton of stuff as it's used all over the place in many different contexts. We should clean it up but in a later PR :)

Fixes part of #975
2017-03-14 18:36:35 -07:00
David Hong 411f0fb6e7 Print line/mixed comments on new lines inside JSXEmptyExpression (#985) 2017-03-10 18:23:11 -08:00
Christopher Chedeau 0aa3617689 Fix for of/in comment on its own line around in/of (#901)
This is pretty edge case-y so i'm taking the easy way out.

Fixes #886
2017-03-09 11:10:55 -08:00
Brian Ng d034564481 Remove parens from chained assignments (#967) 2017-03-09 09:17:16 -08:00
Christopher Chedeau d39facc022 Only allow same-line arrow-less body for explicit nodes (#966)
In practice, trying to allow calls to be inlined is causing a lot of code to look very weird and unstable as seen by the four issues this is fixing. It also requires us to add a conditional group and do hackery around it.

Fixes #959
Fixes #760
Fixes #615
Fixes #625
2017-03-09 09:08:12 -08:00
Christopher Chedeau 9ef8c709bb fix_tests 2017-03-09 08:59:23 -08:00
Brian Ng b8bdb6c243 Inline BinaryExpressions inside JSXExpression (#965) 2017-03-09 07:59:53 -08:00
Christopher Chedeau 35bd29be2c Stabilize comment after object label (#958)
This is the largest firing unstability on the Facebook codebase.

Fixes #906
2017-03-09 07:55:35 -08:00
Christopher Chedeau ee1717e7b7 Make comments around empty parenthesis be inside (#957)
The logic was already implemented in #802 but for a single case. I just added all the cases added in the awesome @umidbekkarimov

Fixes #956
2017-03-09 07:55:18 -08:00
Christopher Chedeau c2aacae54c Fix `in` inside of a for in a nested way (#954)
Fixes #907
2017-03-08 17:09:37 -08:00
Alex Rattray 24c314da01 Recursively find leading comments inside ReturnStatements (#955) 2017-03-08 17:06:18 -08:00
Karl O'Keeffe 68a39454af Do not break long `describe` calls (#953)
This ensures that `describe` calls in test suites are whitelisted in the same way as `it` and `test` and never break across lines.
2017-03-08 13:24:28 -08:00
James Henry 72456bf06f [WIP] TypeScript Parser (#915)
* WIP immediate feedback

* typescript parser is drop-in replacement for flow parser

* Add new TypeScript Parser snapshots where drop-in replacement possible

* Snapshot updates after rebasing

* Remove unnecessary stripping of properties on TypeScript parser AST

* Remove annotated issues

* Move TS dependencies to dev for now
2017-03-08 13:18:13 -08:00
Kevin Gibbons dc2fa2cdd0 Fix #951: properly parenthesize ** expressions (#952) 2017-03-08 13:11:53 -08:00
Kevin Gibbons 7443f4cbd6 Parenthesize function expressions in expression position (#941)
* refactor needsParens for function expressions

* snapshots

* comment
2017-03-07 18:53:42 -08:00
Alex Rattray 50602aecbb [JSX] Break if opening element breaks (#942) 2017-03-07 17:19:05 -08:00
Kevin Gibbons 06987e9948 cleanup needsParens (#935) 2017-03-07 14:43:05 -08:00
Davy Duperron 1b6ddf9a7f Fix binary op as body in arrow expression (#921)
* Implement new logic for wrapping binary op in arrowFunctionExpression.

* Add new test cases.

* Reuse new helper function in order to fix #917.

* Add new test case.

* Extend heuristic to dive deeper into mixed types.

* Add new test.

* Enhance logic to cover more cases.

* Add new test cases.

* Disable Flow as it gets BindExpression as an unexpected token.

* Simplify getCombinedDeepest function.

* Add missing case.

* Extract all conditions in switch cases to one top level condition.

* Refactor implementation to make it cleaner and also handle ExpressionStatement.

* Update related test cases.

* Add new test case.

* Make condition less expensive.

* Clean up unecessary conditions, simplify condition involving startsWithOpenCurlyBrace.

* Update and add new test cases for better coverage.

* Remove unecessary condition, refactor canBeFirstInStatement to drop some useless parens.

* Update test cases accordingly 🚀.
2017-03-07 13:24:47 -08:00
Davy Duperron 008ac1c479 Fix files with comments only (#813)
* Add new handleOnlyComments function.

* Update tests.

* Update test as the printer forces a trailing newline if there were any contents.

* Implement a different heuristic.

* Update tests.

* Add directives checking in handleOnlyComments function.

* Add directives checking in handleOnlyComments function (amend to retrigger CI).

* Remove duplicate.
2017-03-07 11:02:45 -08:00
Kim Joar Bekkelund a5ad490467 Do not break long it/test calls when template literal (#893)
* Do not break long it/test calls when template literal

* expressions and newlines
2017-03-07 08:36:03 -08:00
Davy Duperron 4dde054bb3 Fix binary expression instanceof in arrow function expression (#913)
* Add fix for parens of BinaryExpression with instanceof op embedded into ArrowFunctionExpression.

* Add new test 🚀.
2017-03-06 03:44:48 -08:00
Simon Lydell b91d6384a6 Fix 0.5e0 (#911)
* Don't generate invalid scientific notation

Fixes #902.

* Remove unnecessary scientific notation (1e0)
2017-03-06 03:44:05 -08:00
Davy Duperron 3f6259554e Fix broken export comment (#899)
* Add new helper function to convert comments as blocks in ExportNamedDeclaration.

* Add new test.

* Switch to a leading position.

* Update test accordingly.
2017-03-05 21:49:07 -08:00
Brian Ng f6bbc2ed2e Fix bug with importing empty type (#904) 2017-03-05 19:08:42 -08:00
Davy Duperron c852d1631c Fix unprinted comments in destructuring (#898)
* Add handlePropertyComments printing function.

* Add new test.
2017-03-05 14:40:03 -08:00
Davy Duperron 2ef9896567 Fix object expression in arrow function expression (#897)
* Add new case for keeping parens around ObjectExpression in ArrowFunctionExpression.

* Add new test.
2017-03-05 13:04:50 -08:00
Brian Ng 860a9fd6d4 Ensure no parens for JSX inside of an ArrayExpression (#895) 2017-03-05 08:56:07 -08:00
Brian Ng 226fd85d8f Fix paren removal on UnionTypeAnnotation (#878) 2017-03-03 17:37:00 -08:00
Christopher Chedeau 7d24b0a1ff Fix flow union comments (#853)
The comments infra has been architected with trailing operators and fails for leading `|`. Instead of having leading comments, we can put trailing comments on the previous one and use the same technique as assignment to deal with the indentation.

Fixes #849
2017-03-03 13:54:45 -08:00
Christopher Chedeau 184382dd00 Do not break long it calls (#842)
This happens very frequently that naming a test makes the entire line go > 80 columns and requires to indent everything which takes a lot more space. We've had this being reported multiple times and it also affects a lot of tests inside of fb.

Fixes #159

(Note, this is built on-top of #841 but github doesn't handle stacked pull requests well...)
2017-03-03 16:48:29 -05:00
Christopher Chedeau fe38dab45a Fix comment for `call( // comment` (#858)
This is a pretty exotic way to put a comment and it's been a long time since I have seen prettier output be as broken :)

Fixes #857
2017-03-03 16:47:13 -05:00
Christopher Chedeau 735f07fa4f Do not put \n after label (#860)
This is a leftover from the recast prototype, it hasn't been touched since then. I have never seen anyone not put the label on the same line.

Fixes #859
2017-03-03 16:46:40 -05:00
Christopher Chedeau fa9dca362e Add parenthesis around assignments (#862)
This is a neat trick from the React codebase. It helps highlight the fact that this is an assignment and not a comparison which is subtle to realize.

Fixes #861
2017-03-03 16:46:11 -05:00
Christopher Chedeau 5523c4f56b Inline short expressions for boolean operators too (#826)
In #605 I restricted it to binary operations as I didn't know how it would affect boolean operations but it turns out the same technique solves problems that people are reporting. So doesn't make sense to restrict it.

Fixes #824
2017-03-02 22:45:26 -05:00
Christopher Chedeau 3649835ce0 Keep parenthesis on export default function (#844)
It turns out that my fix was not correct. We should not add parenthesis for FunctionDeclaration instead of checking if the function expression is named.

Fixes #819
2017-03-02 22:39:22 -05:00
Christopher Chedeau 211e18bed2 Inline last arg function arguments (#847)
```js
SuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLongCall((err, result) => {
  // comment
});
```

currently breaks into

```js
SuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLongCall((
  err,
  result,
) => {
  // comment
});
```

which looks bad, instead this PR makes it break

```js
SuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLongCall(
  (err, result) => {
    // comment
  }
);
```

which look better
2017-03-02 22:29:53 -05:00
Christopher Chedeau 4b237d331e Fix jsx expression comment that break (#852)
In #596, I fixed a bunch of jsx expression comment edge cases and happened to add a softline there. But it turns out that it's not needed and is actually harmful :)

Fixes #712
2017-03-02 22:27:08 -05:00
Christopher Chedeau 516f5900d8 Stabilize import as comments (#855)
Since this is extremely rare, I just took the easy way out and if you are adding a comment inside the "as" node, I just move it outside. We could be more fancy but that works.

Fixes #620
2017-03-02 22:22:33 -05:00
Christopher Chedeau 705ac7d3cf Do not break require calls (#841)
This has come up a couple times on the issue tracker on the react-native-web discussion about Twitter internals. It seems like there's a concensus that people don't break long require calls and they'd rather have it go > 80 columns.

Fixes #303
Fixes #752
2017-03-02 22:21:02 -05:00
Christopher Chedeau d90af427fb Fix comment after the last argument of a function (#856)
The issue is that the comment algorithm attaches it to the return type / value but we want to attach it to the previous one.

Fixes #612
2017-03-02 22:17:22 -05:00
Alex Rattray 475208d22a [JSX] Don't wrap JSX Elements in parentheses if they are inside JSX Expression Containers (#845) 2017-03-01 12:05:57 -08:00
Christopher Chedeau f1548e76bd re-run snapshot tests 2017-03-01 09:11:54 -08:00
Alex Rattray aef1ac61c9 [JSX] Break before and after jsx whitespace (#836) 2017-02-28 13:30:54 -08:00
Christopher Chedeau d6e3815c19 Allow breaking for logical expressions in member chains (#827)
I'm not really sure what a general rule is for those, but starting with LogicalExpressions should be good. Outside of identifiers, function calls and logical expressions, there aren't a lot of things you'd put there in real code anyway.

Fixes #822
2017-02-28 09:31:04 -08:00
Christopher Chedeau 61482662cc Migrate class comments to the beginning (#831)
Instead of trying to figure out a complicated way to preserve their correct position, it's easier to just migrate those comments before the class.

Fixes #693
Fixes #694
2017-02-28 11:23:15 -05:00
Christopher Chedeau 2ea1dbcb6a Fix indentation of a merged group (#828)
Printing a merged group indented was actually not the right fix. The right fix was to print them in a single line. It used to have this behavior when I was mutating the first group but now that I don't anymore I need to reproduce this condition.

Fixes #823
2017-02-28 10:55:32 -05:00
Christopher Chedeau c17bcabc0b Preserve new lines for comments after `=` (#830)
The `hasLeadingOwnLineComment` helper is going to be useful for other places where we just used `n.comments` as a proxy for it.

Fixes #660
2017-02-28 10:00:28 -05:00
Christopher Chedeau 4540f473e9 Put short body of arrow functions on the same line (#829)
By adding a group, we can avoid adding a newline if the expression fits in a single line.

Fixes #800
2017-02-27 17:18:43 -05:00
Christopher Chedeau 08b8a5f2e7 Do not put parenthesis around not named default export (#819)
We need to add parenthesis around function expressions if they are named otherwise the name leak, but if the function is not named then it's just superfluous.

The conditional change is due to a bad use of switch case where it would fall through the next one. We don't want parenthesis there.
2017-02-27 16:46:17 -05:00
Christopher Chedeau 443a5d6d66 Properly support `do` (#811)
The code that supported `do` was likely from some recast time and didn't work anymore.
2017-02-27 10:49:08 -05:00
Davy Duperron 04f09ddc80 Fix function call args (#809)
* Implement new heuristic for arguments in printArgumentsList function.

* Remove unwanted modification.

* Add new helper function.

* Update tests according.

* Add new tests for #682, #677, #253.

* Move heuristic in groupLastArg condition.

* Update tests.
2017-02-25 09:56:13 -08:00
Christopher Chedeau 1b9234a8c4 Update flow to 0.40 (#808)
This fixes the bug with comments swapped between `/*` and `//`

Fixes #755
2017-02-24 15:46:20 -08:00
Davy Duperron b32ace8934 Fix function declaration params comments (#802)
* Add new handleFunctionDeclarationComments function.

* Add dangling comments printing for function params.

* Add new test case.

* Update tests.

* Refactor handleFunctionDeclarationComments to only addDanglingComment when no params.

* Remove unecessary helper function, only attach dangling comments when no params.

* Reset flow tests, no more regression.
2017-02-24 07:26:30 -08:00
James Long cea254857a Eagerly evaluate `ifBreak` when processing template literals (fixes #795) (#798) 2017-02-23 21:21:13 -08:00
Davy Duperron c8c1875fc8 Fix extra parens for update expressions (#796)
* Remove parens around UpdateExpression when parent is CallExpression.

* Add new test case.
2017-02-23 11:54:06 -08:00
Christopher Chedeau 1d02ca7849 [RFC] Add parenthesis around && inside of || (#780)
It seems like precedence for this combination of operators is very unclear to people (myself included) and consistently adding parenthesis there would be good.

Fixes #773
2017-02-23 09:27:00 -08:00
Christopher Chedeau e50aaeccfb Introduce line-suffix-boundary (#750)
The idea is that if you reach the end of the `}` inside of a template literal, we have to flush the trailing comma, otherwise it would generate invalid code. We also need the same special case for JSX.

I don't like adding yet another type of document but it seems like the most elegant way to solve the problem.

Fixes #623
2017-02-23 09:26:26 -08:00
Davy Duperron 260a141dbe [WIP] Fix comments in template literals (#643)
* Add handleTemplateLiteralComment helper function.

* Fix handleTemplateLiteralComment function.

* Extend handleTemplateLiteralComment to deal with trailing comments 🚀.

* Add test.

* Make handle comments function naming more consistent, fix merge conflicts.

* Update tests.

* Add better comment injection in Template Literal.

* Pass options to attach function.

* Update tests to match new implementation.

* Fix let -> var in findExpressionIndexForComment for NodeJS v4.

* Reorder after merge conflicts.

* Drop old tests for dangling arrays.

* Replace redundant conditional by a boolean 🚀.

* Refactor implementation.
2017-02-23 09:23:56 -08:00
Christopher Chedeau ee0e839cb8 Do not put trailing commas for function declaration in es5 mode (#791)
Fixes #789
2017-02-23 09:01:19 -08:00
Brian Ng 543e62cd31 Revert babylon bump (#792) 2017-02-23 09:00:57 -08:00
James Long 5f78e78081 Do not format template literals (#749) 2017-02-23 09:00:29 -08:00
Christopher Chedeau 6b7aa83820 Group [0] at the end of the previous chain instead of beginning of next one (#784)
Fixes #775
2017-02-23 07:34:52 -08:00
Christopher Chedeau 694816517a Do not expand empty catch (#783)
I originally wanted to expand it but I think that it may not be a good decision because it's very common for them to be empty and you want it to take as little space as possible.

I tried to remove all those conditions but I think that there are valid places where we always want to expand like empty if/for/while loops.

Fixes #778
2017-02-23 07:29:05 -08:00