GithubHelp home page GithubHelp logo

jhipster / prettier-java Goto Github PK

View Code? Open in Web Editor NEW
1.0K 23.0 101.0 9.68 MB

Prettier Java Plugin

Home Page: http://www.jhipster.tech/prettier-java/

License: Apache License 2.0

JavaScript 30.21% Shell 0.05% Java 39.26% HTML 0.47% CSS 1.49% TypeScript 28.43% MDX 0.09%
prettier java

prettier-java's Introduction

Github Actions Build Status

Prettier Java

Prettier Java Banner Prettier Java Banner

Intro

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

How it works

A Prettier plugin must first parse the source code of the target language into a traversable data structure (Usually an Abstract Syntax Tree) and then print out that data structure in a "pretty" style.

Prettier-Java uses a Java-Parser implemented in JavaScript using the Chevrotain Parser Building Toolkit for JavaScript. What this means is that unlike many other Prettier plugins, prettier-java has no additional runtime pre-requisites (e.g: Python executable). It could even be used inside a browser.

Subpackages

This project contains 2 packages:

Install

Pre-requirements

Install Prettier and Prettier-Java plugin

# Local installation
npm install prettier-plugin-java --save-dev

# Or globally
npm install -g prettier prettier-plugin-java

or with yarn:

# Local installation
yarn add prettier-plugin-java --dev

# Or globally
yarn global add prettier prettier-plugin-java

Note: If you want to install the prettier-plugin-java globally, you should also install the prettier package globally.

Usage

To reformat all your Java files, you first need to create .prettierrc.yaml with following content:

plugins:
  - prettier-plugin-java

Then run:

# If you have installed the package locally
npx prettier --write "**/*.java"

# Or globally
prettier --write "**/*.java"

To see an advanced usage: please go to the Advanced Usage section

Maven plugin

A neat maven plugin for prettier-java was made by developers from HubSpot.
Add it to the plugins section of your build configuration

<build>
  <plugins>
    <plugin>
      <groupId>com.hubspot.maven.plugins</groupId>
        <artifactId>prettier-maven-plugin</artifactId>
        <!-- Find the latest version at https://github.com/jhipster/prettier-java/releases -->
        <version>0.8</version>
    </plugin>
  </plugins>
</build>

If you would like to use this plugin, we recommend you to check their project as is it well documented.

Organize imports

Prettier-java is currently sorting imports according to the Google Java Style guide.

If you are using an IDE such as IntelliJ, you might want to configure it to match with Prettier-java.

For IntelliJ, you can use this configuration: IntelliJ config

You can also import the Checkstyle configuration provided in the next section.

For VSCode with Language Support for Java, you can use this configuration (settings.json):

{
  "java.completion.importOrder": ["#"]
}

Checkstyle configuration

You can use Prettier in combination with other linter, like Checkstyle.

Here is one Checkstyle Prettier compatible configuration you can use to start with !

You can directly import the config into IntelliJ Idea for instance:

Import Checkstyle configuration

Indent configuration

In .prettierrc.yaml, you can configure the indent:

For using four spaces:

tabWidth: 4

For more configuration options such as using tabs, maximum line length, and more see https://prettier.io/docs/en/configuration.html.

Contributing

Contributions are very welcome. See the contribution guide to get started. And the Help Wanted issues.

Credits

Special thanks to @thorbenvh8 for creating the original prettier-java plugin and the associated Java Parser implemented in JavaScript.

We would also like to thank the Chevrotain and Prettier contributors which made this possible.

prettier-java's People

Contributors

austin-scott avatar azz avatar bd82 avatar bjornjaspers avatar clementdessoude avatar danielfran avatar dependabot[bot] avatar derkoe avatar fauxfaux avatar graham42 avatar hawkurane avatar iamandrewluca avatar jdubois avatar jhaber avatar jhipster-bot avatar jtkiesel avatar koppor avatar lipis avatar magic-akari avatar max-schaefer avatar maxfie1d avatar mshima avatar pascalgrimaud avatar rnorth avatar ruddell avatar shaolans avatar shepherdjerred avatar sudharakap avatar victornoel avatar yannick-paz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prettier-java's Issues

After formatting comments disappear

The parser currenlty only acknowledges comments ( //, /* ... */ ) but doesn't add them to the AST.
Fixing this problem probably by moving the jsjavaparser java language definition into this project and updating it.

enum body is deleted

It looks like only the values of enums are preserved; other code in the enum's body gets deleted.

This:

public enum Enum {

    THIS_IS_GOOD,
    THIS_IS_FINE;

    public static final String thisWillBeDeleted = "DELETED";

    public String toString() {
        return "STRING";
    }

}

turns into this:

public enum Enum {

    THIS_IS_GOOD,
    THIS_IS_FINE;

}

Break long function calls, not able to parse breaked long function calls

Break this:

public class BreakLongFunctionCall {
	public void doSomething() {
		return new Object().something().more().blub().and().that().as().well();
	}
}

Can't parse the following

public class BreakLongFunctionCall {
	public void doSomething() {
		return new Object()
                      .something()
                      .more()
                      .blub()
                      .and()
                      .that()
                      .as()
                      .well();
	}
}

package-info.java not parsed/supported

[error] ~~snip~~/package-info.java: Error: Sad sad panda, parsing errors detected in line: 2, column: 1!
[error] Expecting: one of these possible Token sequences:
[error]   1. ['class']
[error]   2. ['enum']
[error]   3. ['interface']
[error]   4. ['@']
[error] but found: 'package'
[error]     at Object.parse (~~node_modules/chevrotain-java/src/index.js:20:11)
[error]     at Object.parse (~~node_modules/prettier-plugin-java/src/parser.js:6:25)
[error]     at Object.parse$3 [as parse] (~~node_modules/prettier/bin-prettier.js:23712:19)
[error]     at formatWithCursor (~~node_modules/prettier/bin-prettier.js:29396:27)
~~snip~~

Example contents:

@MyImmutableStyle
package com.mypackage;

try/with resources wakes up the sad sad panda

Hi,

I have some code using the try/with resource pattern (see https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) and I got the following error:

[error] Test.java: Error: Sad sad panda, parsing errors detected in line: 12, column: 5!
[error] Expecting: one of these possible Token sequences:
[error]   1. ['catch']
[error]   2. ['finally']
[error] but found: '}'

The content

import java.io.IOException;
import java.io.InputStream;

public class Test {
    public void test() throws IOException {
        try (InputStream s = getClass().getResourceAsStream("test")) {
            // do something
        }
    }
}

Lambda not working

do(x -> System.out.println(x));
do((x, y) -> System.out.println(x, y));
do((x, y) -> {
  System.out.println(x);
  System.out.println(y);
});

Strange wrapping

  @Override
  public SegmentationChart jsonable(
    FactorisedSelection selection
  ) {List<ThingsInformation> dbThingsInformations = new DbThingsInformations(context,
    things,
    new FactorisedFilterCondition(schema,
    selection)).list();
    return new DefaultChart(dbThingsInformations,
    rowLabels,
    rowCumulativePercentThresholds,
    columnLabels,
    columnCumulativePercentThresholds);
  }

I suppose this is not normal:

  • the assignment being on the same line as the {
  • the one-parameter method being wrapped (I suppose it is a side effect of the first bullet)

I would have expected (on top of #37):

  @Override
  public DefaultChart jsonable(FactorisedSelection selection) {
    List<ThingsInformation> dbThingsInformations = new DbThingsInformations(context,
    things,
    new FactorisedFilterCondition(schema,
    selection)).list();
    return new DefaultChart(dbThingsInformations,
    rowLabels,
    rowCumulativePercentThresholds,
    columnLabels,
    columnCumulativePercentThresholds);
  }

Doesn't handle class declared inside a method

Sample code:

public class MyTest {
    public void testMethod() throws Exception {
        class MyLocalThing {
        }
    }
}

Output:

Unknown Java node: { type: 'LOCAL_TYPE_DECLARATION',
  modifiers: [],
  declaration:
   { type: 'CLASS_DECLARATION',
     name: { type: 'IDENTIFIER', value: 'MyLocalThing' },
     typeParameters: undefined,
     extends: undefined,
     implements: undefined,
     body: { type: 'CLASS_BODY', declarations: [] } } }
public class MyTest {

  public void testMethod() throws Exception {
  }

}

P.S. I know this is probably strange. ๐Ÿ˜‰ But I'm trying to run prettier-java against a large existing Java code base.

Broken for axis1-java

I get a stacktrace when trying to format apache/axis1-java
(https://github.com/apache/axis1-java/)

Steps:

  1. git clone https://github.com/apache/axis1-java.git
  2. prettier --parser=java --write 'axis1-java/**/*.java'

Stacktrace:

axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/axis/AdminClientTask.java 83ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/axis/RunAxisFunctionalTestsTask.java 29ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/foreach/ForeachTask.java 27ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/foreach/ParamItem.java 6ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/foreach/ParamSet.java 17ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/ComplexType.java 6ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/Java2WsdlAntTask.java 46ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/Mapper.java 7ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/MappingSet.java 4ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/NamespaceMapping.java 10ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/TypeMappingVersionEnum.java 2ms
axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/Wsdl2javaAntTask.java
[error] axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/Wsdl2javaAntTask.java: Error: Sad sad panda, parsing errors detected in line: 135, column: 23!
[error] Expecting: one of these possible Token sequences:
[error]   1. ['this']
[error]   2. ['super']
[error]   3. ['DecimalLiteral']
[error]   4. ['HexLiteral']
[error]   5. ['OctLiteral']
[error]   6. ['BinaryLiteral']
[error]   7. ['FloatLiteral']
[error]   8. ['HexFloatLiteral']
[error]   9. ['CharLiteral']
[error]   10. ['StringLiteral']
[error]   11. ['true']
[error]   12. ['false']
[error]   13. ['null']
[error]   14. ['@']
[error]   15. [Identifier]
[error]   16. ['boolean']
[error]   17. ['char']
[error]   18. ['byte']
[error]   19. ['short']
[error]   20. ['int']
[error]   21. ['long']
[error]   22. ['float']
[error]   23. ['double']
[error]   24. ['?']
[error]   25. ['(']
[error] but found: '-'
[error]     at Object.parse (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/index.js:20:11)
[error]     at Object.parse (/home/grahamm/<snipped-project-dir>/node_modules/prettier-plugin-java/src/parser.js:6:25)
[error]     at Object.parse$3 [as parse] (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:23712:19)
[error]     at formatWithCursor (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:29396:27)
[error]     at Object.formatWithCursor (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:29697:12)
[error]     at format$1 (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:35857:21)
[error]     at eachFilename (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:36082:16)
[error]     at filePaths.forEach.filePath (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:36022:7)
[error]     at Array.forEach (<anonymous>)
[error]     at eachFilename (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:36021:15)
[error]     at Object.formatFiles (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:36038:3)
[error]     at Object.run (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:36663:14)
[error]     at Object.<anonymous> (/home/grahamm/.nvm/versions/node/v8.11.1/lib/node_modules/prettier/bin-prettier.js:36678:5)
[error]     at Module._compile (module.js:652:30)
[error]     at Object.Module._extensions..js (module.js:663:10)
[error]     at Module.load (module.js:565:32)
axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant/wsdl/CustomGeneratorFactoryTest.java 3ms
axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant/wsdl/MyGeneratorFactory.java 3ms
axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant/wsdl/MyServiceImplWriter.java 3ms
axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant/wsdl/MyServiceWriter.java 3ms
axis1-java/axis-ant/src/test/java/test/wsdl/extra/Extra.java 3ms
axis1-java/axis-ant/src/test/java/test/wsdl/extra/MyService.java 2ms
axis1-java/axis-ant/src/test/java/test/wsdl/groups/GroupsTestCase.java 3ms
axis1-java/axis-ant/src/test/java/test/wsdl/qname/foo.java 1ms
axis1-java/axis-ant/src/test/java/test/wsdl/qname/MyServiceImpl.java 4ms
axis1-java/axis-ant/src/test/java/test/wsdl/qname/MyServiceInterface.java 3ms
axis1-java/axis-ant/src/test/java/test/wsdl/schemaImport/foo.java 1ms
axis1-java/axis-ant/src/test/java/test/wsdl/schemaImport/foobar.java 2ms
axis1-java/axis-ant/src/test/java/test/wsdl/schemaImport/SchemaImportTestCase.java 6ms
axis1-java/axis-ant/src/test/java/test/wsdl/split/MyPortType.java 2ms
axis1-java/axis-ant/src/test/java/test/wsdl/split/SplitTestCase.java 4ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/DuplicateFileException.java 2ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/Emitter.java 44ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/FactoryProperty.java 4ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/GeneratedFileInfo.java 11ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBeanFaultWriter.java 6ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBeanHelperWriter.java 26ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBeanWriter.java 115ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBindingWriter.java 11ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBuildFileWriter.java 10ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaClassWriter.java 10ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaDefinitionWriter.java 16ms
axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaDeployWriter.java
[error] Unable to expand glob patterns: axis1-java/**/*.java !**/node_modules/** !./node_modules/**
[error] Cannot read property 'stack' of undefined

[Parser] assert statement not recognized

Sample code

public class MyTest {
    public void testMethod(String myVar) {
        assert(myVar != null);
    }
}

Output

Unknown Java node: { type: 'ASSERT_STATEMENT',
  expressions: [ { type: 'PAR_EXPRESSION', expression: [Object] } ] }

Error parsing Java packages

I'm testing with prettier-java:0.0.2 with a specific patch for handling #31

I have lots of parsing errors, it looks like Java packages are not correctly parsed, here is one example:

[error] src/main/java/io/jhipster/demo/aop/logging/LoggingAspect.java: SyntaxError: ';' expected. (1:9)
[error] > 1 | package io.jhipster.demo.aop.logging;
[error]     |         ^
[error]   2 |
[error]   3 | import io.github.jhipster.config.JHipsterConstants;
[error]   4 |

In order to give you a full project, which might also have more issues, please have a look at the attached Zip file.: tmp.zip

This is a @jhipster application, made from the current master branch (which passes our test suite, so it should be quite good).

You need to run yarn prettier:format and it should format all .ts and .java files. It should be pretty comprehensive, so hopefully it will help you catch more issues.

Line break is incorrectly removed

input:

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class FilterTest {

    @Test
    public void testTopNewsFilter() {
        TopNewsFilter filter = new TopNewsFilter();
        Map<String, Double> topics = new HashMap<>();
    }

}

output:

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class FilterTest {

    @Test
    public void testTopNewsFilter() {
        TopNewsFilter filter = new TopNewsFilter();Map<String, Double> topics = new HashMap<>();
    }

}

Make class extends and implements prettier by fitting to line width

https://github.com/thorbenvh8/prettier-java/blob/master/PREVIEW.md#extends_abstract_class_and_implements_interfaces

public class ExtendsAbstractClassAndImplementsInterfaces extends AbstractClass implements Interface1, Interface2 {
It's just a line right now, when doesn't fit line, it should look like this? (open for discussion @azz)

public class ExtendsAbstractClassAndImplementsInterfaces
indent extends AbstractClass
indent implements Interface1,
same pos as Inter1 Interface2
{`
(formatting code in an issue is hard?!)

Parser breaks with a comment inside if condition

Thank you for your patience while I submit more bizarre cases.

Sample code:

public class MyTest {
    public void testMethod() throws Exception {
        String x;
        if (true
                // this is a sample comment
                || true)
            x = "foo";
    }
}

Stacktrace:

[error] MyTest.java: TypeError: Cannot create property 'comments' on string '||'
[error]     at SQLToAstVisitor.addComment (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:3741:26)
[error]     at node.map.n (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:3724:28)
[error]     at Array.map (<anonymous>)
[error]     at SQLToAstVisitor.addCommentsToAst (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:3724:14)
[error]     at SQLToAstVisitor.visit (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:3716:10)
[error]     at SQLToAstVisitor.operatorExpressionRest (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:2676:27)
[error]     at SQLToAstVisitor.visit (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain/lib/src/parse/cst/cst_visitor.js:52:42)
[error]     at SQLToAstVisitor.visit (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:3714:29)
[error]     at SQLToAstVisitor.expression (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:2428:45)
[error]     at SQLToAstVisitor.visit (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain/lib/src/parse/cst/cst_visitor.js:52:42)
[error]     at SQLToAstVisitor.visit (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:3714:29)
[error]     at SQLToAstVisitor.ifStatement (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:1768:28)
[error]     at SQLToAstVisitor.visit (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain/lib/src/parse/cst/cst_visitor.js:52:42)
[error]     at SQLToAstVisitor.visit (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:3714:29)
[error]     at SQLToAstVisitor.statementWithStartingToken (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain-java/src/visitor.js:1705:19)
[error]     at SQLToAstVisitor.visit (/home/grahamm/<snipped-project-dir>/node_modules/chevrotain/lib/src/parse/cst/cst_visitor.js:52:42)

Not printing Array creation

This following code is not being printed.
new Object[] { "abc", "def", "ghi" }

Create a test case and then let printer.js print the node. :)

Crash on enum declaration

Sample code

public class MyTest {
    public static enum VALID_THINGS {
        FIRST,
        SECOND
    }
}

Stacktrace:

[error] MyTest.java: TypeError: Cannot read property 'declarations' of undefined
[error]     at printEnumDeclaration (/home/grahamm/<snipped-project-dir>/node_modules/prettier-plugin-java/src/printer.js:528:17)
[error]     at printNode (/home/grahamm/<snipped-project-dir>/node_modules/prettier-plugin-java/src/printer.js:2237:14)
[error]     at Object.genericPrint [as print] (/home/grahamm/<snipped-project-dir>/node_modules/prettier-plugin-java/src/printer.js:2631:10)
[error]     at genericPrint$6 (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:23998:18)
[error]     at comments.printComments.p (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:23936:14)
[error]     at Object.printComments (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:8252:19)
[error]     at printGenerically (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:23934:22)
[error]     at FastPath.call (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:21082:18)
[error]     at printClassBodyMemberDeclaration (/home/grahamm/<snipped-project-dir>/node_modules/prettier-plugin-java/src/printer.js:368:18)
[error]     at printNode (/home/grahamm/<snipped-project-dir>/node_modules/prettier-plugin-java/src/printer.js:2225:14)
[error]     at Object.genericPrint [as print] (/home/grahamm/<snipped-project-dir>/node_modules/prettier-plugin-java/src/printer.js:2631:10)
[error]     at genericPrint$6 (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:23998:18)
[error]     at comments.printComments.p (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:23936:14)
[error]     at Object.printComments (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:8252:19)
[error]     at printGenerically (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:23934:22)
[error]     at FastPath.map (/home/grahamm/<snipped-project-dir>/node_modules/prettier/bin-prettier.js:21136:19)

Printing should be call path.call or path.map

๐Ÿ‘‹ @thorbenvh8,

Great work on this so far! I've just raised a couple of minor issues but this is the main one ๐Ÿ˜‰

I noticed you're not preserving the FastPath data structure. You should preserve this structure as it gives you a lot of stuff for free, like being able to read ancestor nodes, getting comment support, and embedding support.

Here's an example from Prettier HTML:

https://github.com/prettier/prettier/blob/5e2e7a2881d07ff0aa4b4673becc9cb4ce2f6cae/src/language-html/printer-htmlparser2.js#L97-L104

function printAttributes(path, print) {
  const node = path.getValue();

  return concat([
    node.attributes.length ? " " : "",
    indent(join(line, path.map(print, "attributes")))
  ]);
}

Note that instead of node.attributes.map(printAttribute), it is path.map(print, "attributes"). This way each AST node enters the main genericPrint switch block.

There's more info here: prettier/plugin-php#12 and we'll document this better soon.

As a side note, you should also delete _util-from-prettier.js and update the heading in the README :)

Investigate Performance of Printer

The Parser is fast enough.
I've measured > 40,000 lines a second on a 2015 MacBook Pro.
This could most likely be improve farther, but it does not seem to be the bottleneck at this time.

We need to examine the performance of the printer that generates the output formatted text.

Examples:
Many new arrays created by concat.
https://github.com/thorbenvh8/prettier-java/blob/88145f841adc0af287388145c5a4d0a1e2f0cb06/src/printer.js#L1892-L1896

The process of building the new text seems to go through an intermediate form of arrays. which may be inefficient
https://github.com/thorbenvh8/prettier-java/blob/88145f841adc0af287388145c5a4d0a1e2f0cb06/src/printer.js#L1796-L1811

Docs for IDE integration

I think the most common current Java IDEs are probably IntelliJ and Eclipse. If there is integration with these editors, it would be awesome to have it documented so people coming from the Java world (perhaps very unfamiliar with JavaScritpt) can try this project out.

SEMI_COLON_STATEMENT tests

just ';' will be removed, but we need to check if empty lines are correctly removed and keepts the correct empty lines

special but accepted characters in method names break parsing

Hi,

The following code:

         public TestSteps create_a_range_from_$_to_$(LocalDate from, LocalDate to) {
            try {
                resultPeriod = new DateRange(from, to);
            } catch (Exception e) {
                thrown = e;
            }
            return this;
        }

gives me the following error:

[error] Expecting: one of these possible Token sequences:
[error]   1. ['[']
[error]   2. ['=']
[error]   3. [',']
[error]   4. [';']
[error]   5. [';']
[error]   6. ['(']
[error] but found: 'to_'

Using $ (and I guess other characters) are accepted in methods name. For the record, in this case it is a classic naming scheme used with JGiven.

Not printing throws

Add a test case for printing throw/-s

... something() throws SomeException { throw new SomeException(); }

Then fix it in printer.js :)

Config option for member_chain/builder pattern

Currently the member_chain/builder/fluent pattern is unreadable (obviously in my opinion).

Instead of

public void doSomethingLongNew() {
        return something().more().and().that().as().well().but().not(

        ).something().something();
    }

I much prefer

public void doSomethingLongNew() {
        return something()
                             .more()
                             .and()
                             .that()
                             .as()
                             .well()
                             .but()
                             .not(

                             )
                             .something()
                             .something();
    }

I am very much willing to trade vertical real estate for readability. This is especially true for nested builder patterns like:

return Foo.newBuilder()
                   .setA(a)
                   .setBar(Bar.newBuilder()
                             .setB(b)
                             .setZoo(Zoo.newBuilder()
                                     .setC(c)
                                     .build())
                             .build())
                    .build();

Currently there is no ability to configure the output of the printer in general. To what extent is configuration planned for in the current roadmap?

Groovy

My understanding is that groovy and java are quite similar, curious if this project could also be used to format groovy?
If not, perhaps you could comment on what work would be needed for a prettier-groovy formatter?

Thanks ๐Ÿ™‚

Enums are stripped from their values

Hello,
Thanks for this great plugin, can't wait to put it all over the codebase.
Although I have an issue with enums. There are stripped of their values:

Input

public enum MyEnum {
    GREAT_ENUM("greatValue");
}

gives

Output

public enum MyEnum {
    GREAT_ENUM;
}

Also, I get this stacktrace for the file (not sure if directly related)

TypeError: Cannot read property 'declarations' of undefined
[error]     at printEnumDeclaration (/usr/local/lib/node_modules/prettier-plugin-java/src/printer.js:498:17)
[error]     at printNode (/usr/local/lib/node_modules/prettier-plugin-java/src/printer.js:2250:14)
[error]     at Object.genericPrint [as print] (/usr/local/lib/node_modules/prettier-plugin-java/src/printer.js:2652:10)
[error]     at genericPrint$6 (/usr/local/lib/node_modules/prettier/bin-prettier.js:23998:18)
[error]     at comments.printComments.p (/usr/local/lib/node_modules/prettier/bin-prettier.js:23936:14)
[error]     at Object.printComments (/usr/local/lib/node_modules/prettier/bin-prettier.js:8252:19)
[error]     at printGenerically (/usr/local/lib/node_modules/prettier/bin-prettier.js:23934:22)
[error]     at FastPath.call (/usr/local/lib/node_modules/prettier/bin-prettier.js:21082:18)
[error]     at printTypeDeclaration (/usr/local/lib/node_modules/prettier-plugin-java/src/printer.js:97:18)
[error]     at printNode (/usr/local/lib/node_modules/prettier-plugin-java/src/printer.js:2211:14)
[error]     at Object.genericPrint [as print] (/usr/local/lib/node_modules/prettier-plugin-java/src/printer.js:2652:10)
[error]     at genericPrint$6 (/usr/local/lib/node_modules/prettier/bin-prettier.js:23998:18)
[error]     at comments.printComments.p (/usr/local/lib/node_modules/prettier/bin-prettier.js:23936:14)
[error]     at Object.printComments (/usr/local/lib/node_modules/prettier/bin-prettier.js:8252:19)
[error]     at printGenerically (/usr/local/lib/node_modules/prettier/bin-prettier.js:23934:22)
[error]     at FastPath.map (/usr/local/lib/node_modules/prettier/bin-prettier.js:21136:19)
```

Doesn't handle hex literals

Sample code:

public class MyTest {
	public static final int	MY_HEX_THING = 0x0000;
}

Output:

$ prettier  MyTest.java
Unknown Java node: { type: 'HEX_LITERAL', value: '0x0000' }
public class MyTest {
  public static final int MY_HEX_THING = ;
}

Annotations are not sorted

printAnnotations had some logic regarding the sorting, but because we get a prettier doc back as the name now, its not that easy to sort out of the box

Ugly object instantiation (and maybe other method calls?)

Hi, prettier-java gives me this:

  @Override
  public ScatterChart scatterChart(
    DbCategorisationLevel grouping,
    FactorisedSelection selection,
    double marginRateTarget
  ) {
    return new DbScatterChart(context,
    x,
    y,
    grouping,
    new FactorisedFilterCondition(schema,
    selection),
    marginRateTarget);
  }

I would have expected something like this:

  @Override
  public ScatterChart scatterChart(
    DbCategorisationLevel grouping,
    FactorisedSelection selection,
    double marginRateTarget
  ) {
    return new DbScatterChart( // if some of the parameters are wrapped, then all should even the first one
      context, // the parameters should be indented of one indentation
      x,
      y,
      grouping,
      new FactorisedFilterCondition( // idem
        schema, // idem
        selection
      ), // I find it really easier to read with the parenthesis to the line when parameters are wrapped
      marginRateTarget
   ); // idem
  }

Or if there was enough space:

  @Override
  public ScatterChart scatterChart(
    DbCategorisationLevel grouping,
    FactorisedSelection selection,
    double marginRateTarget
  ) {
    return new DbScatterChart(
      context,
      x,
      y,
      grouping,
      new FactorisedFilterCondition(schema, selection),
      marginRateTarget
   );
  }

MemberChain functions look ugly

The problem is the parser is generating a reversed AST Tree.
Example:
System.out.println()
becomes

{
  value: "println"
  expression: {
     value: "out",
     expression: {
        value: "System"
     }
  }
}

So we won't to add an indent after the last Node, which is hard like this.

We need to change the parser create the ast tree the otherway around

MethodReference not working

Type Example Syntax
1. Reference to a static method ContainingClass::staticMethodName Class::staticMethodName
2. Reference to a constructor ClassName::new ClassName::new
3. Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName Class::instanceMethodName
4. Reference to an instance method of a particular object containingObject::instanceMethodName object::instanceMethodName

Ugly wrapped generics

I got the following (inside a class)

  private final Map<Integer,
  DbCategorisationLevel> levels = new HashMap<>();

While Iย would have expected:

  private final Map<Integer, DbCategorisationLevel> levels = new HashMap<>();

Not Java 8 ready

The parser only supports Java 7.
Fixing this problem probably by moving the jsjavaparser java language definition into this project and updating it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.