From bb775f9816440be91d808cc16c8639f56669f135 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Wed, 8 Sep 2021 18:48:04 +0200 Subject: [PATCH 01/62] Add basic lexer --- .../formatter/tokenizer/Lexer.java | 48 ++++++++++ .../formatter/tokenizer/Token.java | 13 +++ .../formatter/tokenizer/TokenType.java | 87 +++++++++++++++++++ .../tokenizer/TokenizationException.java | 7 ++ 4 files changed, 155 insertions(+) create mode 100644 src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java create mode 100644 src/main/java/org/togetherjava/formatter/tokenizer/Token.java create mode 100644 src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java create mode 100644 src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java diff --git a/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java new file mode 100644 index 0000000000..224a629574 --- /dev/null +++ b/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -0,0 +1,48 @@ +package org.togetherjava.formatter.tokenizer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.stream.Collectors; + +public class Lexer { + private static final Lexer instance = new Lexer(); + + public static Lexer getInstance() { + return instance; + } + + public List tokenize(String input) { + return tokenize(Arrays.asList(input.split("\n"))); + } + + public List tokenize(List lines) { + return lines.stream().map(line -> { + List tokens = new ArrayList<>(); + int index = 0; + String content; + + while (!(content = line.substring(index)).isEmpty()) { + tokenCheck: { + for (TokenType token : TokenType.values()) { + Matcher matcher = token.getRegex().matcher(content); + + if (matcher.find()) { + String found = matcher.group(); + + tokens.add(new Token(found, token)); + index += found.length(); + + break tokenCheck; + } + } + + throw new TokenizationException("Token not found for '" + content + "'"); + } + } + + return tokens; + }).flatMap(List::stream).collect(Collectors.toList()); + } +} diff --git a/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/src/main/java/org/togetherjava/formatter/tokenizer/Token.java new file mode 100644 index 0000000000..b547ed3c91 --- /dev/null +++ b/src/main/java/org/togetherjava/formatter/tokenizer/Token.java @@ -0,0 +1,13 @@ +package org.togetherjava.formatter.tokenizer; + +import java.util.List; + +public record Token(String content, TokenType type) { + private static final List displayTypes = + List.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING); + + @Override + public String toString() { + return type().name() + (displayTypes.contains(type()) ? "(" + content() + ")" : ""); + } +} diff --git a/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java new file mode 100644 index 0000000000..95458f3f2e --- /dev/null +++ b/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -0,0 +1,87 @@ +package org.togetherjava.formatter.tokenizer; + +import java.util.regex.Pattern; + +public enum TokenType { + // keywords + CLASS("class"), + ENUM("enum"), + RECORD("record"), + INTERFACE("interface"), + IMPORT("import"), + IF("if"), + FOR("for"), + WHILE("while"), + NULL("null"), + EXTENDS("extends"), + IMPLEMENTS("implements"), + NEW("new"), + RETURN("return"), + PACKAGE("package"), + THIS("this"), + // access modifiers + PUBLIC("public"), + PRIVATE("private"), + PROTECTED("protected"), + STATIC("static"), + SEALED("sealed"), + NON_SEALED("non-sealed"), + FINAL("final"), + ABSTRACT("abstract"), + // primitive types + VOID("void"), + INT("int"), + LONG("long"), + SHORT("short"), + BYTE("byte"), + BOOLEAN("boolean"), + FLOAT("float"), + DOUBLE("double"), + CHAR("char"), + // general tokens + OPEN_PARENTHESIS("("), + CLOSE_PARANTHESIS(")"), + OPEN_BRACES("{"), + CLOSE_BRACES("}"), + OPEN_BRACKETS("["), + CLOSE_BRACKETS("]"), + OPEN_DIAMOND("<"), + CLOSE_DIAMOND(">"), + SEMICOLON(";"), + COLON(":"), + COMMA(","), + EQUALS("=="), + NOT_EQUALS("!="), + BIGGER_OR_EQUALS(">="), + BIGGER(">"), + SMALLER_OR_EQUALS("<="), + SMALLER("<"), + NOT("!"), + ASSIGN("="), + PLUS("+"), + MINUS("-"), + DIVIDE("/"), + MULTIPLY("*"), + DOT("."), + // other + ANNOTATION(Pattern.compile("^@[a-zA-Z][a-zA-Z0-9_]*")), + NUMBER(Pattern.compile("^(0[xb])?\\d+[dDfFlL]?")), + STRING(Pattern.compile("^\"[^\"]*\"")), + IDENTIFIER(Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]*")), + WHITSPACE(Pattern.compile("^\s+")), + UNKNOWN(Pattern.compile("^.")); + + private final Pattern regex; + + TokenType(Pattern regex) { + this.regex = regex; + } + + TokenType(String spattern) { + this(Pattern.compile("^\\Q" + spattern + "\\E")); + } + + public Pattern getRegex() { + return regex; + } +} diff --git a/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java b/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java new file mode 100644 index 0000000000..ca2c90663a --- /dev/null +++ b/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java @@ -0,0 +1,7 @@ +package org.togetherjava.formatter.tokenizer; + +public class TokenizationException extends RuntimeException { + public TokenizationException(String message) { + super(message); + } +} From e27355cbee584aa381ad4d7d60f3d62746bb0c89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Radosavljevi=C4=87?= Date: Thu, 9 Sep 2021 08:32:30 +0200 Subject: [PATCH 02/62] Improve gradle structure (6aafd67500ea0196e24703a2d349f506948a7d83) --- application/build.gradle | 31 ++++++++++++++ .../formatter/tokenizer/Lexer.java | 0 .../formatter/tokenizer/Token.java | 0 .../formatter/tokenizer/TokenType.java | 0 .../tokenizer/TokenizationException.java | 0 .../org/togetherjava/tjbot/Application.java | 40 +++++++++++++++++++ .../togetherjava/tjbot/PingPongListener.java | 0 .../org/togetherjava/tjbot/package-info.java | 2 +- .../src}/main/resources/log4j2.xml | 0 .../togetherjava/tjbot/ApplicationTest.java | 10 ++--- build.gradle | 25 +----------- settings.gradle | 2 +- .../java/org/togetherjava/tjbot/Main.java | 40 ------------------- 13 files changed, 80 insertions(+), 70 deletions(-) create mode 100644 application/build.gradle rename {src => application/src}/main/java/org/togetherjava/formatter/tokenizer/Lexer.java (100%) rename {src => application/src}/main/java/org/togetherjava/formatter/tokenizer/Token.java (100%) rename {src => application/src}/main/java/org/togetherjava/formatter/tokenizer/TokenType.java (100%) rename {src => application/src}/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java (100%) create mode 100644 application/src/main/java/org/togetherjava/tjbot/Application.java rename {src => application/src}/main/java/org/togetherjava/tjbot/PingPongListener.java (100%) rename {src => application/src}/main/java/org/togetherjava/tjbot/package-info.java (76%) rename {src => application/src}/main/resources/log4j2.xml (100%) rename src/test/java/org/togetherjava/tjbot/MainTest.java => application/src/test/java/org/togetherjava/tjbot/ApplicationTest.java (50%) delete mode 100644 src/main/java/org/togetherjava/tjbot/Main.java diff --git a/application/build.gradle b/application/build.gradle new file mode 100644 index 0000000000..0d8e9a241d --- /dev/null +++ b/application/build.gradle @@ -0,0 +1,31 @@ +plugins { + id 'application' +} + +group 'org.togetherjava' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() + maven { + name 'm2-dv8tion' + url 'https://m2.dv8tion.net/releases' + } +} + +dependencies { + implementation 'net.dv8tion:JDA:4.3.0_324' + implementation 'org.apache.logging.log4j:log4j-api:2.14.1' + implementation 'org.apache.logging.log4j:log4j-core:2.14.1' + implementation 'org.apache.logging.log4j:log4j-slf4j18-impl:2.14.1' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.2' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.2' +} + +application { + mainClass = 'org.togetherjava.tjbot.Application' +} + +test { + useJUnitPlatform() +} diff --git a/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/application/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java similarity index 100% rename from src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java rename to application/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java diff --git a/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/application/src/main/java/org/togetherjava/formatter/tokenizer/Token.java similarity index 100% rename from src/main/java/org/togetherjava/formatter/tokenizer/Token.java rename to application/src/main/java/org/togetherjava/formatter/tokenizer/Token.java diff --git a/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/application/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java similarity index 100% rename from src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java rename to application/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java diff --git a/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java b/application/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java similarity index 100% rename from src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java rename to application/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java diff --git a/application/src/main/java/org/togetherjava/tjbot/Application.java b/application/src/main/java/org/togetherjava/tjbot/Application.java new file mode 100644 index 0000000000..f561ae7753 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/Application.java @@ -0,0 +1,40 @@ +package org.togetherjava.tjbot; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.JDABuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.security.auth.login.LoginException; + +public enum Application { + ; + + private static final Logger logger = LoggerFactory.getLogger(Application.class); + + /** + * Starts the application. + * + * @param args One argument - the token of the bot + */ + public static void main(final String[] args) { + if (args.length != 1) { + throw new IllegalArgumentException("Expected one argument but " + args.length + + " arguments were provided. The argument must be the token of the bot."); + } + String token = args[0]; + + logger.info("Starting bot..."); + try { + JDA jda = JDABuilder.createDefault(token) + .addEventListeners(new PingPongListener()) + .build(); + jda.awaitReady(); + logger.info("Bot is ready"); + } catch (LoginException e) { + logger.error("Failed to login", e); + } catch (InterruptedException e) { + logger.error("Interrupted while waiting for setup to complete", e); + } + } +} diff --git a/src/main/java/org/togetherjava/tjbot/PingPongListener.java b/application/src/main/java/org/togetherjava/tjbot/PingPongListener.java similarity index 100% rename from src/main/java/org/togetherjava/tjbot/PingPongListener.java rename to application/src/main/java/org/togetherjava/tjbot/PingPongListener.java diff --git a/src/main/java/org/togetherjava/tjbot/package-info.java b/application/src/main/java/org/togetherjava/tjbot/package-info.java similarity index 76% rename from src/main/java/org/togetherjava/tjbot/package-info.java rename to application/src/main/java/org/togetherjava/tjbot/package-info.java index 24878c8084..6f2a062850 100644 --- a/src/main/java/org/togetherjava/tjbot/package-info.java +++ b/application/src/main/java/org/togetherjava/tjbot/package-info.java @@ -1,4 +1,4 @@ /** - * Entry package for the TJ-Bot. See {@link org.togetherjava.tjbot.Main} to get started. + * Entry package for the TJ-Bot. See {@link org.togetherjava.tjbot.Application} to get started. */ package org.togetherjava.tjbot; \ No newline at end of file diff --git a/src/main/resources/log4j2.xml b/application/src/main/resources/log4j2.xml similarity index 100% rename from src/main/resources/log4j2.xml rename to application/src/main/resources/log4j2.xml diff --git a/src/test/java/org/togetherjava/tjbot/MainTest.java b/application/src/test/java/org/togetherjava/tjbot/ApplicationTest.java similarity index 50% rename from src/test/java/org/togetherjava/tjbot/MainTest.java rename to application/src/test/java/org/togetherjava/tjbot/ApplicationTest.java index d4213768ac..be85659c03 100644 --- a/src/test/java/org/togetherjava/tjbot/MainTest.java +++ b/application/src/test/java/org/togetherjava/tjbot/ApplicationTest.java @@ -3,9 +3,9 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public final class MainTest { - @Test - void testFoo() { - Assertions.assertTrue(true); - } +public final class ApplicationTest { + @Test + void testFoo() { + Assertions.assertTrue(true); + } } diff --git a/build.gradle b/build.gradle index 756b9ef247..f5887212ba 100644 --- a/build.gradle +++ b/build.gradle @@ -1,34 +1,13 @@ plugins { id 'java' id "com.diffplug.spotless" version "5.15.0" + id "name.remal.sonarlint" version "1.5.0" } -group 'org.togetherjava' -version '1.0-SNAPSHOT' - sourceCompatibility = JavaVersion.VERSION_16 targetCompatibility = JavaVersion.VERSION_16 -repositories { - mavenCentral() - maven { - name 'm2-dv8tion' - url 'https://m2.dv8tion.net/releases' - } -} - -dependencies { - implementation 'net.dv8tion:JDA:4.3.0_324' - implementation 'org.apache.logging.log4j:log4j-api:2.14.1' - implementation 'org.apache.logging.log4j:log4j-core:2.14.1' - implementation 'org.apache.logging.log4j:log4j-slf4j18-impl:2.14.1' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.2' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.2' -} - -test { - useJUnitPlatform() -} +compileJava.dependsOn 'spotlessApply' spotless { java { diff --git a/settings.gradle b/settings.gradle index cbcfd19187..09c28a6a7f 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,2 @@ rootProject.name = 'TJ-Bot' - +include('application') \ No newline at end of file diff --git a/src/main/java/org/togetherjava/tjbot/Main.java b/src/main/java/org/togetherjava/tjbot/Main.java deleted file mode 100644 index 4fe7095a4d..0000000000 --- a/src/main/java/org/togetherjava/tjbot/Main.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.togetherjava.tjbot; - -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.JDABuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.security.auth.login.LoginException; - -public enum Main { - ; - - private static final Logger logger = LoggerFactory.getLogger(Main.class); - - /** - * Starts the application. - * - * @param args One argument - the token of the bot - */ - public static void main(final String[] args) { - if (args.length != 1) { - throw new IllegalArgumentException("Expected one argument but " + args.length - + " arguments were provided. The argument must be the token of the bot."); - } - String token = args[0]; - - logger.info("Starting bot..."); - try { - JDA jda = JDABuilder.createDefault(token) - .addEventListeners(new PingPongListener()) - .build(); - jda.awaitReady(); - logger.info("Bot is ready"); - } catch (LoginException e) { - logger.error("Failed to login", e); - } catch (InterruptedException e) { - logger.error("Interrupted while waiting for setup to complete", e); - } - } -} From 02d02b3c56444ec1308cd494a41a5a24caa7878e Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:05:01 +0200 Subject: [PATCH 03/62] Create a module for the formatter and move all related packages to it --- .../main/java/org/togetherjava/formatter/tokenizer/Lexer.java | 0 .../main/java/org/togetherjava/formatter/tokenizer/Token.java | 0 .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 0 .../formatter/tokenizer/TokenizationException.java | 0 settings.gradle | 4 +++- 5 files changed, 3 insertions(+), 1 deletion(-) rename {application => formatter}/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java (100%) rename {application => formatter}/src/main/java/org/togetherjava/formatter/tokenizer/Token.java (100%) rename {application => formatter}/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java (100%) rename {application => formatter}/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java (100%) diff --git a/application/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java similarity index 100% rename from application/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java rename to formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java diff --git a/application/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java similarity index 100% rename from application/src/main/java/org/togetherjava/formatter/tokenizer/Token.java rename to formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java diff --git a/application/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java similarity index 100% rename from application/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java rename to formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java diff --git a/application/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java similarity index 100% rename from application/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java rename to formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java diff --git a/settings.gradle b/settings.gradle index 09c28a6a7f..c42ed7ace8 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,4 @@ rootProject.name = 'TJ-Bot' -include('application') \ No newline at end of file + +include 'application' +include 'formatter' \ No newline at end of file From 5a5c8c36bc1dca3746b3938445883851594c1162 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:08:05 +0200 Subject: [PATCH 04/62] Use built-in toList instead of collecting --- .../main/java/org/togetherjava/formatter/tokenizer/Lexer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index 224a629574..bec6dff0e0 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -43,6 +43,6 @@ public List tokenize(List lines) { } return tokens; - }).flatMap(List::stream).collect(Collectors.toList()); + }).flatMap(List::stream).toList(); } } From 084fa550a2cf656b7dde7b34434ac10fa9b75d40 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:08:42 +0200 Subject: [PATCH 05/62] Add yield keyword --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 1 + 1 file changed, 1 insertion(+) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 95458f3f2e..99dcc7cfdb 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -19,6 +19,7 @@ public enum TokenType { RETURN("return"), PACKAGE("package"), THIS("this"), + YIELD("yield"), // access modifiers PUBLIC("public"), PRIVATE("private"), From c042035b0ce5bccf97b370743f075145e9229f18 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:10:42 +0200 Subject: [PATCH 06/62] Fix number pattern --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 99dcc7cfdb..4cdaeae7fc 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -66,7 +66,7 @@ public enum TokenType { DOT("."), // other ANNOTATION(Pattern.compile("^@[a-zA-Z][a-zA-Z0-9_]*")), - NUMBER(Pattern.compile("^(0[xb])?\\d+[dDfFlL]?")), + NUMBER(Pattern.compile("^(0[xb])?[0-9_]*(\\.\\d*)?[dDfFlL]?")), STRING(Pattern.compile("^\"[^\"]*\"")), IDENTIFIER(Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]*")), WHITSPACE(Pattern.compile("^\s+")), From 1f6f104fc728f231d7c360734175f28bd23bbf59 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:14:20 +0200 Subject: [PATCH 07/62] Split code into separate method --- .../formatter/tokenizer/Lexer.java | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index bec6dff0e0..a06f039156 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -18,31 +18,36 @@ public List tokenize(String input) { } public List tokenize(List lines) { - return lines.stream().map(line -> { - List tokens = new ArrayList<>(); - int index = 0; - String content; + return lines.stream() + .map(this::tokenizeLine) + .flatMap(List::stream) + .toList(); + } - while (!(content = line.substring(index)).isEmpty()) { - tokenCheck: { - for (TokenType token : TokenType.values()) { - Matcher matcher = token.getRegex().matcher(content); + private List tokenizeLine(String line) { + List tokens = new ArrayList<>(); + int index = 0; + String content; - if (matcher.find()) { - String found = matcher.group(); + while (!(content = line.substring(index)).isEmpty()) { + tokenCheck: { + for (TokenType token : TokenType.values()) { + Matcher matcher = token.getRegex().matcher(content); - tokens.add(new Token(found, token)); - index += found.length(); + if (matcher.find()) { + String found = matcher.group(); - break tokenCheck; - } - } + tokens.add(new Token(found, token)); + index += found.length(); - throw new TokenizationException("Token not found for '" + content + "'"); + break tokenCheck; + } } + + throw new TokenizationException("Token not found for '" + content + "'"); } + } - return tokens; - }).flatMap(List::stream).toList(); + return tokens; } } From d17dc023b061e7cb9e8742189ea5e1e7d2040697 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:15:01 +0200 Subject: [PATCH 08/62] Remove singleton pattern --- .../java/org/togetherjava/formatter/tokenizer/Lexer.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index a06f039156..d8c8c177be 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -7,12 +7,6 @@ import java.util.stream.Collectors; public class Lexer { - private static final Lexer instance = new Lexer(); - - public static Lexer getInstance() { - return instance; - } - public List tokenize(String input) { return tokenize(Arrays.asList(input.split("\n"))); } From 0b8428547b39ecda3a4e8a547bb3119804dc4930 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:16:03 +0200 Subject: [PATCH 09/62] Put ternary into separate method --- .../org/togetherjava/formatter/tokenizer/Token.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java index b547ed3c91..4eaf604ed1 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java @@ -8,6 +8,14 @@ public record Token(String content, TokenType type) { @Override public String toString() { - return type().name() + (displayTypes.contains(type()) ? "(" + content() + ")" : ""); + return type().name() + displayMe(); + } + + private String displayMe() { + if (displayTypes.contains(type())) { + return "(" + content() + ")"; + } + + return ""; } } From 9cd96998369385dccf1a2eed9887ee99dfc859ea Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:31:31 +0200 Subject: [PATCH 10/62] Remove unused import --- .../main/java/org/togetherjava/formatter/tokenizer/Lexer.java | 1 - 1 file changed, 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index d8c8c177be..19223fe4ec 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -4,7 +4,6 @@ import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; -import java.util.stream.Collectors; public class Lexer { public List tokenize(String input) { From fe5be0f063cd0bf8747afcda55d07b348be1874e Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:34:01 +0200 Subject: [PATCH 11/62] Add build.gradle file --- formatter/build.gradle | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 formatter/build.gradle diff --git a/formatter/build.gradle b/formatter/build.gradle new file mode 100644 index 0000000000..bab715720b --- /dev/null +++ b/formatter/build.gradle @@ -0,0 +1,6 @@ +plugins { + id 'java' +} + +group 'org.togetherjava' +version '1.0-SNAPSHOT' \ No newline at end of file From 1bf6c47c38717f4b8a7ef6fa4218bf45ca8c6640 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 16:46:42 +0200 Subject: [PATCH 12/62] Fix the number regex --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 4cdaeae7fc..c665f414b8 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -66,7 +66,7 @@ public enum TokenType { DOT("."), // other ANNOTATION(Pattern.compile("^@[a-zA-Z][a-zA-Z0-9_]*")), - NUMBER(Pattern.compile("^(0[xb])?[0-9_]*(\\.\\d*)?[dDfFlL]?")), + NUMBER(Pattern.compile("^(0[xb])?([0-9_]+|[0-9_]*(\\.\\d*))[dDfFlL]?")), STRING(Pattern.compile("^\"[^\"]*\"")), IDENTIFIER(Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]*")), WHITSPACE(Pattern.compile("^\s+")), From 7f1bdb3f77683b44b088874aa9b82dce0d21c4dc Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 17:17:18 +0200 Subject: [PATCH 13/62] Fix typo (CLOSE_PARANTHESIS -> CLOSE_PARENTHESIS) --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index c665f414b8..5e8088d6fb 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -41,7 +41,7 @@ public enum TokenType { CHAR("char"), // general tokens OPEN_PARENTHESIS("("), - CLOSE_PARANTHESIS(")"), + CLOSE_PARENTHESIS(")"), OPEN_BRACES("{"), CLOSE_BRACES("}"), OPEN_BRACKETS("["), From 36a3648f5fc413391380003de247f75aaf8ee76b Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 17:36:55 +0200 Subject: [PATCH 14/62] Add comment token --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 5e8088d6fb..0c0a2672bf 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -61,6 +61,10 @@ public enum TokenType { ASSIGN("="), PLUS("+"), MINUS("-"), + + // this has to be other DIVIDE or else it'll be seen as two divides + COMMENT(Pattern.compile("^//.*")), + DIVIDE("/"), MULTIPLY("*"), DOT("."), From 444b9c630f6ef0b96a5fbaa98a699b1a7d909659 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 17:43:38 +0200 Subject: [PATCH 15/62] Add comment token to the display types --- .../main/java/org/togetherjava/formatter/tokenizer/Token.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java index 4eaf604ed1..171ad62663 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java @@ -4,7 +4,7 @@ public record Token(String content, TokenType type) { private static final List displayTypes = - List.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING); + List.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING, TokenType.COMMENT); @Override public String toString() { From e4fea635a9e6e0349b756b19bd7072df941b7d75 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 17:43:51 +0200 Subject: [PATCH 16/62] Add ++ and -- tokens --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 0c0a2672bf..7e886b8a98 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -59,7 +59,9 @@ public enum TokenType { SMALLER("<"), NOT("!"), ASSIGN("="), + PLUSPLUS("++"), PLUS("+"), + MINUSMINUS("--"), MINUS("-"), // this has to be other DIVIDE or else it'll be seen as two divides From 8606d3847bf64251c25432d7ada4cc4b436ecbe5 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 9 Sep 2021 18:10:35 +0200 Subject: [PATCH 17/62] Fix lexer picking up wrong tokens (e.g. it picks up 'format' as 'for' and 'mat') --- .../formatter/tokenizer/Lexer.java | 2 +- .../formatter/tokenizer/TokenType.java | 99 +++++++++++-------- 2 files changed, 59 insertions(+), 42 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index 19223fe4ec..ca192ead16 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -28,7 +28,7 @@ private List tokenizeLine(String line) { Matcher matcher = token.getRegex().matcher(content); if (matcher.find()) { - String found = matcher.group(); + String found = matcher.group(1); tokens.add(new Token(found, token)); index += found.length(); diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 7e886b8a98..fe356563a7 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -4,41 +4,41 @@ public enum TokenType { // keywords - CLASS("class"), - ENUM("enum"), - RECORD("record"), - INTERFACE("interface"), - IMPORT("import"), - IF("if"), - FOR("for"), - WHILE("while"), - NULL("null"), - EXTENDS("extends"), - IMPLEMENTS("implements"), - NEW("new"), - RETURN("return"), - PACKAGE("package"), - THIS("this"), - YIELD("yield"), + CLASS("class", true), + ENUM("enum", true), + RECORD("record", true), + INTERFACE("interface", true), + IMPORT("import", true), + IF("if", true), + FOR("for", true), + WHILE("while", true), + NULL("null", true), + EXTENDS("extends", true), + IMPLEMENTS("implements", true), + NEW("new", true), + RETURN("return", true), + PACKAGE("package", true), + THIS("this", true), + YIELD("yield", true), // access modifiers - PUBLIC("public"), - PRIVATE("private"), - PROTECTED("protected"), - STATIC("static"), - SEALED("sealed"), - NON_SEALED("non-sealed"), - FINAL("final"), - ABSTRACT("abstract"), + PUBLIC("public", true), + PRIVATE("private", true), + PROTECTED("protected", true), + STATIC("static", true), + SEALED("sealed", true), + NON_SEALED("non-sealed", true), + FINAL("final", true), + ABSTRACT("abstract", true), // primitive types - VOID("void"), - INT("int"), - LONG("long"), - SHORT("short"), - BYTE("byte"), - BOOLEAN("boolean"), - FLOAT("float"), - DOUBLE("double"), - CHAR("char"), + VOID("void", true), + INT("int", true), + LONG("long", true), + SHORT("short", true), + BYTE("byte", true), + BOOLEAN("boolean", true), + FLOAT("float", true), + DOUBLE("double", true), + CHAR("char", true), // general tokens OPEN_PARENTHESIS("("), CLOSE_PARENTHESIS(")"), @@ -65,30 +65,47 @@ public enum TokenType { MINUS("-"), // this has to be other DIVIDE or else it'll be seen as two divides - COMMENT(Pattern.compile("^//.*")), + COMMENT(Pattern.compile("^(//.*)")), DIVIDE("/"), MULTIPLY("*"), DOT("."), // other - ANNOTATION(Pattern.compile("^@[a-zA-Z][a-zA-Z0-9_]*")), - NUMBER(Pattern.compile("^(0[xb])?([0-9_]+|[0-9_]*(\\.\\d*))[dDfFlL]?")), - STRING(Pattern.compile("^\"[^\"]*\"")), - IDENTIFIER(Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]*")), - WHITSPACE(Pattern.compile("^\s+")), - UNKNOWN(Pattern.compile("^.")); + ANNOTATION(Pattern.compile("^(@[a-zA-Z][a-zA-Z0-9_]*)")), + NUMBER(Pattern.compile("^((0[xb])?([0-9_]+|[0-9_]*(\\.\\d*))[dDfFlL]?)")), + STRING(Pattern.compile("^(\"[^\"]*\")")), + IDENTIFIER(Pattern.compile("^([a-zA-Z][a-zA-Z0-9_]*)")), + WHITSPACE(Pattern.compile("^(\s+)")), + UNKNOWN(Pattern.compile("^(.)")); private final Pattern regex; + private final boolean isKeyword; + + TokenType(String spattern, boolean isKeyword) { + if (!isKeyword) { + this.regex = Pattern.compile("^(\\Q" + spattern + "\\E)"); + } else { + this.regex = Pattern.compile("^(\\Q" + spattern + "\\E)[^a-z]"); + } + + this.isKeyword = isKeyword; + } TokenType(Pattern regex) { this.regex = regex; + this.isKeyword = false; } TokenType(String spattern) { - this(Pattern.compile("^\\Q" + spattern + "\\E")); +// this(Pattern.compile("^(\\Q" + spattern + "\\E)")); + this(spattern, false); } public Pattern getRegex() { return regex; } + + public boolean isKeyword() { + return isKeyword; + } } From f31efdad3c575e614de7f966d951f9e1c6d6f062 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 14:46:40 +0200 Subject: [PATCH 18/62] Add CATCH and TRY keywords & remove OPEN_DIAMOND and CLOSE_DIAMOND in favor of SMALLER AND BIGGER --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index fe356563a7..8b9f8d33c3 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -20,6 +20,8 @@ public enum TokenType { PACKAGE("package", true), THIS("this", true), YIELD("yield", true), + CATCH("catch", true), + TRY("try", true), // access modifiers PUBLIC("public", true), PRIVATE("private", true), @@ -46,8 +48,6 @@ public enum TokenType { CLOSE_BRACES("}"), OPEN_BRACKETS("["), CLOSE_BRACKETS("]"), - OPEN_DIAMOND("<"), - CLOSE_DIAMOND(">"), SEMICOLON(";"), COLON(":"), COMMA(","), From 225b35096d06863b16e9abb249761ef86e4af5e8 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 15:30:41 +0200 Subject: [PATCH 19/62] Fix multiline comments (somewhat) --- .../togetherjava/formatter/tokenizer/Lexer.java | 17 ++++++++++++++++- .../formatter/tokenizer/TokenType.java | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index ca192ead16..a7671476cd 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -4,10 +4,13 @@ import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; +import java.util.regex.Pattern; public class Lexer { + private static final Pattern commentPatcherRegex = Pattern.compile("(/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)"); + public List tokenize(String input) { - return tokenize(Arrays.asList(input.split("\n"))); + return tokenize(Arrays.asList(patchComments(input).split("\n"))); } public List tokenize(List lines) { @@ -43,4 +46,16 @@ private List tokenizeLine(String line) { return tokens; } + + private String patchComments(String input) { + Matcher matcher = commentPatcherRegex.matcher(input); + + while (matcher.find()) { + String s = matcher.group(); + + input = input.replace(s, s.replace("\n", " ")); + } + + return input; + } } diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 8b9f8d33c3..4c821fa9e3 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -65,7 +65,7 @@ public enum TokenType { MINUS("-"), // this has to be other DIVIDE or else it'll be seen as two divides - COMMENT(Pattern.compile("^(//.*)")), + COMMENT(Pattern.compile("^(//.*|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)")), DIVIDE("/"), MULTIPLY("*"), From b05486702fdeb89122ad8bf7af4712d307615f4e Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 15:41:25 +0200 Subject: [PATCH 20/62] Add some more tokens --- .../org/togetherjava/formatter/tokenizer/TokenType.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 4c821fa9e3..a017a98486 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -49,8 +49,16 @@ public enum TokenType { OPEN_BRACKETS("["), CLOSE_BRACKETS("]"), SEMICOLON(";"), + METHOD_REFERENCE("::"), COLON(":"), COMMA(","), + PLUS_EQUALS("+="), + MINUS_EQUALS("-="), + MULTIPLY_EQUALS("*="), + DIVIDE_EQUALS("/="), + MODULO_EQUALS("%="), + AND_EQUALS("&="), + OR_EQUALS("|="), EQUALS("=="), NOT_EQUALS("!="), BIGGER_OR_EQUALS(">="), From 7d49cd187c4f2ccc35c8d55f2d5eb7092e4aae0f Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 15:57:57 +0200 Subject: [PATCH 21/62] Add ELSE_IF, BOOL_AND and BOOL_OR tokens & fix keywords --- .../org/togetherjava/formatter/tokenizer/TokenType.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index a017a98486..58ee17de20 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -22,6 +22,7 @@ public enum TokenType { YIELD("yield", true), CATCH("catch", true), TRY("try", true), + ELSE_IF("else if", true), // not really a keyword but required for formatting // access modifiers PUBLIC("public", true), PRIVATE("private", true), @@ -71,6 +72,8 @@ public enum TokenType { PLUS("+"), MINUSMINUS("--"), MINUS("-"), + BOOL_AND("&&"), + BOOL_OR("||"), // this has to be other DIVIDE or else it'll be seen as two divides COMMENT(Pattern.compile("^(//.*|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)")), @@ -93,7 +96,7 @@ public enum TokenType { if (!isKeyword) { this.regex = Pattern.compile("^(\\Q" + spattern + "\\E)"); } else { - this.regex = Pattern.compile("^(\\Q" + spattern + "\\E)[^a-z]"); + this.regex = Pattern.compile("^(\\Q" + spattern + "\\E)[^a-zA-Z]"); } this.isKeyword = isKeyword; @@ -105,7 +108,6 @@ public enum TokenType { } TokenType(String spattern) { -// this(Pattern.compile("^(\\Q" + spattern + "\\E)")); this(spattern, false); } From 34b3a7562e38cf14018f2aa7edfaf18d29d57032 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 15:58:57 +0200 Subject: [PATCH 22/62] Initial commit of the formatter --- .../org/togetherjava/formatter/Formatter.java | 228 ++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 formatter/src/main/java/org/togetherjava/formatter/Formatter.java diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java new file mode 100644 index 0000000000..eff28827fb --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -0,0 +1,228 @@ +package org.togetherjava.formatter; + +import org.togetherjava.formatter.tokenizer.Token; +import org.togetherjava.formatter.tokenizer.TokenType; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class Formatter { + public String format(List tokens) { + List
sections = sectionize(indexTokens(tokens)); + StringBuilder result = new StringBuilder(); + + for (Section section : sections) { + if (section.isCodeSection()) { + result.append("```java\n").append(writeCodeSection(section.tokens())).append("\n```"); + } else { + result.append(revert(section.tokens())); + } + } + + return result.toString(); + } + + private String revert(List tokens) { + return tokens.stream().map(Token::content).collect(Collectors.joining()); + } + + private StringBuilder writeCodeSection(List tokens) { + purgeWhitespaces(tokens = makeMutable(tokens)); + + TokenType lastToken = TokenType.UNKNOWN; + StringBuilder result = new StringBuilder(); + boolean lastNewLine = false; + int indentation = 0; + boolean forClosed = true; + int forClosingLevel = 0; + + for (Token token : tokens) { + TokenType type = token.type(); + + if (lastNewLine && type != TokenType.CLOSE_BRACES) { + putIndentation(indentation, result); + } + + lastNewLine = false; + + iteration: { + if (type == TokenType.OPEN_BRACES) { + if (lastToken == TokenType.CLOSE_PARENTHESIS || lastToken == TokenType.IDENTIFIER || lastToken == TokenType.TRY) { + result.append(" "); + } + + append(result, token); + + result.append("\n"); + + lastNewLine = true; + indentation++; + + break iteration; + } else if (lastToken == TokenType.CLOSE_BRACKETS && type != TokenType.SEMICOLON) { + result.append(" "); + + append(result, token); + + break iteration; + } else if (type == TokenType.CLOSE_BRACES) { + result.append("\n"); + + putIndentation(--indentation, result); + + append(result, token); + + result.append("\n"); + + lastNewLine = true; + + break iteration; + } else if (type == TokenType.IDENTIFIER && (lastToken == TokenType.CLOSE_BRACES || lastToken == TokenType.OPEN_BRACES || lastToken == TokenType.SEMICOLON)) { + append(result, token); + + break iteration; + } else if (type == TokenType.COMMENT || type == TokenType.SEMICOLON || type == TokenType.ANNOTATION) { + if (type == TokenType.COMMENT) { + result.append(" "); + } + + append(result, token); + + if (forClosed) { + result.append("\n"); + + lastNewLine = true; + } + + break iteration; + } else if ( + (type == TokenType.OPEN_PARENTHESIS && lastToken != TokenType.IDENTIFIER && lastToken != TokenType.NOT && lastToken != TokenType.BIGGER && lastToken != TokenType.OPEN_PARENTHESIS) || + lastToken == TokenType.PUBLIC || + lastToken == TokenType.PRIVATE || + lastToken == TokenType.PROTECTED || + (lastToken == TokenType.BIGGER && type != TokenType.OPEN_PARENTHESIS) || + lastToken == TokenType.RETURN || + lastToken == TokenType.COMMA || + lastToken == TokenType.CATCH || + (lastToken == TokenType.CLOSE_PARENTHESIS && type != TokenType.CLOSE_PARENTHESIS && type != TokenType.DOT && type != TokenType.COMMA) || + lastToken == TokenType.PACKAGE + ) { + result.append(" "); + } + + if (!forClosed) { + if (type == TokenType.OPEN_PARENTHESIS) { + forClosingLevel++; + } else if (type == TokenType.CLOSE_PARENTHESIS) { + forClosingLevel--; + } + + if (forClosingLevel == 0) { + forClosed = true; + } + } + + if (type == TokenType.FOR) { + forClosed = false; + } + + List check = List.of( + TokenType.DOT, + TokenType.SEMICOLON, + TokenType.NOT, + TokenType.OPEN_PARENTHESIS, + TokenType.CLOSE_PARENTHESIS, + TokenType.OPEN_BRACKETS, + TokenType.CLOSE_BRACKETS, + TokenType.SMALLER, + TokenType.BIGGER, + TokenType.COMMA, + TokenType.FOR, + TokenType.IF, + TokenType.WHILE, + TokenType.PLUSPLUS, + TokenType.MINUSMINUS, + TokenType.RETURN, + TokenType.THIS, + TokenType.PUBLIC, + TokenType.PROTECTED, + TokenType.PRIVATE, + TokenType.TRY, + TokenType.CATCH, + TokenType.PACKAGE, + TokenType.METHOD_REFERENCE, + TokenType.ELSE_IF + ); + + if (!(check.contains(type) || check.contains(lastToken))) { + result.append(" "); + } + + append(result, token); + } + + lastToken = type; + } + + return new StringBuilder(result.toString().replaceAll("([;}])\n\n", "$1\n")); + } + + private void putIndentation(int indentation, StringBuilder sb) { + IntStream.range(0, indentation).forEach(n -> sb.append("\t")); + } + + private void append(StringBuilder sb, Token token) { + sb.append(token.content()); + } + + private List makeMutable(List in) { + return new ArrayList<>(in); + } + + private void purgeWhitespaces(List tokens) { + tokens.removeIf(t -> t.type() == TokenType.WHITSPACE); + } + + private List indexTokens(List tokens) { + List result = new ArrayList<>(); + + for (Token token : tokens) { + result.add(new IndexedToken(token, isCodeToken(token))); + } + + return result; + } + + private boolean isCodeToken(Token token) { + return token.type() != TokenType.UNKNOWN; + } + + private List
sectionize(List indexedTokens) { + IndexedToken first = indexedTokens.get(0); + Section currSec = new Section(new ArrayList<>(), first.isCode()); + List
result = new ArrayList<>(); + + currSec.tokens().add(first.token()); + + for (int i = 1; i < indexedTokens.size(); i++) { + IndexedToken next = indexedTokens.get(i); + + if (currSec.isCodeSection() != next.isCode()) { + result.add(currSec); + + currSec = new Section(new ArrayList<>(), next.isCode()); + } + + currSec.tokens().add(next.token()); + } + + result.add(currSec); + + return result; + } + + private static record Section(List tokens, boolean isCodeSection) {} + private static record IndexedToken(Token token, boolean isCode) {} +} From 52c3be324475f89ec7af3e4384f5d4b208b89189 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 16:12:46 +0200 Subject: [PATCH 23/62] Added javadoc --- .../org/togetherjava/formatter/Formatter.java | 85 +++++++++++++++++++ .../formatter/tokenizer/Lexer.java | 35 +++++++- .../formatter/tokenizer/Token.java | 11 +++ .../formatter/tokenizer/TokenType.java | 5 ++ .../tokenizer/TokenizationException.java | 5 ++ 5 files changed, 140 insertions(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index eff28827fb..aff7f9083a 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -8,7 +8,19 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +/** + * Formatter which can format a given string into a string which contains code blocks etc + * + * @author illuminator3 + */ public class Formatter { + /** + * Formats the given tokens + * + * @param tokens tokens to format + * @return resulting code + * @author illuminator3 + */ public String format(List tokens) { List
sections = sectionize(indexTokens(tokens)); StringBuilder result = new StringBuilder(); @@ -24,10 +36,24 @@ public String format(List tokens) { return result.toString(); } + /** + * Reverts the tokens into the "original state" before the tokenization occurred + * + * @param tokens tokens to revert + * @return original state + * @author illuminator3 + */ private String revert(List tokens) { return tokens.stream().map(Token::content).collect(Collectors.joining()); } + /** + * Writes and formats a given code section (in form of a list of tokens) into a StringBuilder + * + * @param tokens tokens to write + * @return written code sections + * @author illuminator3 + */ private StringBuilder writeCodeSection(List tokens) { purgeWhitespaces(tokens = makeMutable(tokens)); @@ -169,22 +195,56 @@ private StringBuilder writeCodeSection(List tokens) { return new StringBuilder(result.toString().replaceAll("([;}])\n\n", "$1\n")); } + /** + * Puts the needed indentation into a StringBuilder + * + * @param indentation indentation level + * @param sb string builder + * @author illuminator3 + */ private void putIndentation(int indentation, StringBuilder sb) { IntStream.range(0, indentation).forEach(n -> sb.append("\t")); } + /** + * Appends a token to a StringBuilder + * + * @param sb string builder + * @param token token to append + * @author illuminator3 + */ private void append(StringBuilder sb, Token token) { sb.append(token.content()); } + /** + * Makes a list mutable + * + * @param in (im)mutable list + * @return mutable list + * @author illuminator3 + */ private List makeMutable(List in) { return new ArrayList<>(in); } + /** + * Removes every whitespace from a given list of tokens + * + * @param tokens tokens to remove whitesapces from + * @author illuminator3 + */ private void purgeWhitespaces(List tokens) { tokens.removeIf(t -> t.type() == TokenType.WHITSPACE); } + /** + * Indexes tokens to contain information about whether they are code tokens or not + * + * @param tokens not-indexed tokens + * @return indexed tokens + * @author illuminator3 + */ private List indexTokens(List tokens) { List result = new ArrayList<>(); @@ -195,10 +255,24 @@ private List indexTokens(List tokens) { return result; } + /** + * Checks if a given token is a code token + * + * @param token token to check + * @return true if it's a code token, false if not + * @author illuminator3 + */ private boolean isCodeToken(Token token) { return token.type() != TokenType.UNKNOWN; } + /** + * Sectionizes a given list of tokens into sections who are code sections and sections who are not + * + * @param indexedTokens indexed tokens + * @return list of sections + * @author illuminator3 + */ private List
sectionize(List indexedTokens) { IndexedToken first = indexedTokens.get(0); Section currSec = new Section(new ArrayList<>(), first.isCode()); @@ -223,6 +297,17 @@ private List
sectionize(List indexedTokens) { return result; } + /** + * Section POJR + * + * @author illuminator3 + */ private static record Section(List tokens, boolean isCodeSection) {} + + /** + * IndexedToken POJR + * + * @author illuminator3 + */ private static record IndexedToken(Token token, boolean isCode) {} } diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index a7671476cd..f17378d7f2 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -6,13 +6,32 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +/** + * Tokenizer that can turn a list of strings (or a string) into a list of tokens + * + * @author illuminator3 + */ public class Lexer { private static final Pattern commentPatcherRegex = Pattern.compile("(/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)"); + /** + * Tokenizes the given input by tokenizing each line individually (splitting by \n) + * + * @param input input to tokenize + * @return resulting tokens + * @author illuminator3 + */ public List tokenize(String input) { return tokenize(Arrays.asList(patchComments(input).split("\n"))); } + /** + * Tokenizes the given input line by line + * + * @param lines input to tokenize + * @return resulting tokens + * @author illuminator3 + */ public List tokenize(List lines) { return lines.stream() .map(this::tokenizeLine) @@ -20,6 +39,13 @@ public List tokenize(List lines) { .toList(); } + /** + * Tokenizes a single line using regex + * + * @param line input to tokenize + * @return resulting tokens + * @author illuminator3 + */ private List tokenizeLine(String line) { List tokens = new ArrayList<>(); int index = 0; @@ -47,7 +73,14 @@ private List tokenizeLine(String line) { return tokens; } - private String patchComments(String input) { + /** + * Replaces multi-line comments in a given string by single-line comments + * + * @param input input to patch + * @return resulting string + * @author illuminator3 + */ + private String patchComments(String input) { // fix this, you shouldn't need this! Matcher matcher = commentPatcherRegex.matcher(input); while (matcher.find()) { diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java index 171ad62663..21842c8703 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java @@ -2,6 +2,11 @@ import java.util.List; +/** + * Class representing a Token with a given content and a type + * + * @author illuminator3 + */ public record Token(String content, TokenType type) { private static final List displayTypes = List.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING, TokenType.COMMENT); @@ -11,6 +16,12 @@ public String toString() { return type().name() + displayMe(); } + /** + * Returns a non-empty string if this token has something to display + * + * @return the displayed value + * @author illuminator3 + */ private String displayMe() { if (displayTypes.contains(type())) { return "(" + content() + ")"; diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 58ee17de20..7460e9ab9e 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -2,6 +2,11 @@ import java.util.regex.Pattern; +/** + * Represents every possible token that can be lexed by the lexer + * + * @author illuminator3 + */ public enum TokenType { // keywords CLASS("class", true), diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java index ca2c90663a..25a822ba97 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java @@ -1,5 +1,10 @@ package org.togetherjava.formatter.tokenizer; +/** + * Exception that can occur when lexing + * + * @author illuminator3 + */ public class TokenizationException extends RuntimeException { public TokenizationException(String message) { super(message); From 26733a51758392b5af9200c39f515cdc39a68aca Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 16:24:27 +0200 Subject: [PATCH 24/62] Apply formatting (by spotless) --- .../org/togetherjava/formatter/Formatter.java | 87 +++++++++---------- .../formatter/tokenizer/Lexer.java | 8 +- 2 files changed, 42 insertions(+), 53 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index aff7f9083a..e4ce021e36 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -14,6 +14,17 @@ * @author illuminator3 */ public class Formatter { + /** + * List of tokens who should not be put after a space + */ + private static final List NON_SPACE_TOKENS = List.of(TokenType.DOT, + TokenType.SEMICOLON, TokenType.NOT, TokenType.OPEN_PARENTHESIS, + TokenType.CLOSE_PARENTHESIS, TokenType.OPEN_BRACKETS, TokenType.CLOSE_BRACKETS, + TokenType.SMALLER, TokenType.BIGGER, TokenType.COMMA, TokenType.FOR, TokenType.IF, + TokenType.WHILE, TokenType.PLUSPLUS, TokenType.MINUSMINUS, TokenType.RETURN, + TokenType.THIS, TokenType.PUBLIC, TokenType.PROTECTED, TokenType.PRIVATE, TokenType.TRY, + TokenType.CATCH, TokenType.PACKAGE, TokenType.METHOD_REFERENCE, TokenType.ELSE_IF); + /** * Formats the given tokens * @@ -27,7 +38,9 @@ public String format(List tokens) { for (Section section : sections) { if (section.isCodeSection()) { - result.append("```java\n").append(writeCodeSection(section.tokens())).append("\n```"); + result.append("```java\n") + .append(writeCodeSection(section.tokens())) + .append("\n```"); } else { result.append(revert(section.tokens())); } @@ -75,7 +88,8 @@ private StringBuilder writeCodeSection(List tokens) { iteration: { if (type == TokenType.OPEN_BRACES) { - if (lastToken == TokenType.CLOSE_PARENTHESIS || lastToken == TokenType.IDENTIFIER || lastToken == TokenType.TRY) { + if (lastToken == TokenType.CLOSE_PARENTHESIS + || lastToken == TokenType.IDENTIFIER || lastToken == TokenType.TRY) { result.append(" "); } @@ -105,11 +119,14 @@ private StringBuilder writeCodeSection(List tokens) { lastNewLine = true; break iteration; - } else if (type == TokenType.IDENTIFIER && (lastToken == TokenType.CLOSE_BRACES || lastToken == TokenType.OPEN_BRACES || lastToken == TokenType.SEMICOLON)) { + } else if (type == TokenType.IDENTIFIER && (lastToken == TokenType.CLOSE_BRACES + || lastToken == TokenType.OPEN_BRACES + || lastToken == TokenType.SEMICOLON)) { append(result, token); break iteration; - } else if (type == TokenType.COMMENT || type == TokenType.SEMICOLON || type == TokenType.ANNOTATION) { + } else if (type == TokenType.COMMENT || type == TokenType.SEMICOLON + || type == TokenType.ANNOTATION) { if (type == TokenType.COMMENT) { result.append(" "); } @@ -123,18 +140,17 @@ private StringBuilder writeCodeSection(List tokens) { } break iteration; - } else if ( - (type == TokenType.OPEN_PARENTHESIS && lastToken != TokenType.IDENTIFIER && lastToken != TokenType.NOT && lastToken != TokenType.BIGGER && lastToken != TokenType.OPEN_PARENTHESIS) || - lastToken == TokenType.PUBLIC || - lastToken == TokenType.PRIVATE || - lastToken == TokenType.PROTECTED || - (lastToken == TokenType.BIGGER && type != TokenType.OPEN_PARENTHESIS) || - lastToken == TokenType.RETURN || - lastToken == TokenType.COMMA || - lastToken == TokenType.CATCH || - (lastToken == TokenType.CLOSE_PARENTHESIS && type != TokenType.CLOSE_PARENTHESIS && type != TokenType.DOT && type != TokenType.COMMA) || - lastToken == TokenType.PACKAGE - ) { + } else if ((type == TokenType.OPEN_PARENTHESIS && lastToken != TokenType.IDENTIFIER + && lastToken != TokenType.NOT && lastToken != TokenType.BIGGER + && lastToken != TokenType.OPEN_PARENTHESIS) || lastToken == TokenType.PUBLIC + || lastToken == TokenType.PRIVATE || lastToken == TokenType.PROTECTED + || (lastToken == TokenType.BIGGER && type != TokenType.OPEN_PARENTHESIS) + || lastToken == TokenType.RETURN || lastToken == TokenType.COMMA + || lastToken == TokenType.CATCH + || (lastToken == TokenType.CLOSE_PARENTHESIS + && type != TokenType.CLOSE_PARENTHESIS && type != TokenType.DOT + && type != TokenType.COMMA) + || lastToken == TokenType.PACKAGE) { result.append(" "); } @@ -154,35 +170,7 @@ private StringBuilder writeCodeSection(List tokens) { forClosed = false; } - List check = List.of( - TokenType.DOT, - TokenType.SEMICOLON, - TokenType.NOT, - TokenType.OPEN_PARENTHESIS, - TokenType.CLOSE_PARENTHESIS, - TokenType.OPEN_BRACKETS, - TokenType.CLOSE_BRACKETS, - TokenType.SMALLER, - TokenType.BIGGER, - TokenType.COMMA, - TokenType.FOR, - TokenType.IF, - TokenType.WHILE, - TokenType.PLUSPLUS, - TokenType.MINUSMINUS, - TokenType.RETURN, - TokenType.THIS, - TokenType.PUBLIC, - TokenType.PROTECTED, - TokenType.PRIVATE, - TokenType.TRY, - TokenType.CATCH, - TokenType.PACKAGE, - TokenType.METHOD_REFERENCE, - TokenType.ELSE_IF - ); - - if (!(check.contains(type) || check.contains(lastToken))) { + if (!(NON_SPACE_TOKENS.contains(type) || NON_SPACE_TOKENS.contains(lastToken))) { result.append(" "); } @@ -267,7 +255,8 @@ private boolean isCodeToken(Token token) { } /** - * Sectionizes a given list of tokens into sections who are code sections and sections who are not + * Sectionizes a given list of tokens into sections who are code sections and sections who are + * not * * @param indexedTokens indexed tokens * @return list of sections @@ -302,12 +291,14 @@ private List
sectionize(List indexedTokens) { * * @author illuminator3 */ - private static record Section(List tokens, boolean isCodeSection) {} + private static record Section(List tokens, boolean isCodeSection) { + } /** * IndexedToken POJR * * @author illuminator3 */ - private static record IndexedToken(Token token, boolean isCode) {} + private static record IndexedToken(Token token, boolean isCode) { + } } diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index f17378d7f2..75c81a4db5 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -12,7 +12,8 @@ * @author illuminator3 */ public class Lexer { - private static final Pattern commentPatcherRegex = Pattern.compile("(/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)"); + private static final Pattern commentPatcherRegex = + Pattern.compile("(/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)"); /** * Tokenizes the given input by tokenizing each line individually (splitting by \n) @@ -33,10 +34,7 @@ public List tokenize(String input) { * @author illuminator3 */ public List tokenize(List lines) { - return lines.stream() - .map(this::tokenizeLine) - .flatMap(List::stream) - .toList(); + return lines.stream().map(this::tokenizeLine).flatMap(List::stream).toList(); } /** From c05aa32bc0d7af0b44e2010863d5bfe9d40c413a Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 20:08:07 +0200 Subject: [PATCH 25/62] Add else keyword --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 1 + 1 file changed, 1 insertion(+) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 7460e9ab9e..bb0bc49395 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -28,6 +28,7 @@ public enum TokenType { CATCH("catch", true), TRY("try", true), ELSE_IF("else if", true), // not really a keyword but required for formatting + ELSE("else", true), // access modifiers PUBLIC("public", true), PRIVATE("private", true), From 139461e7c98dec4ebaa78bf50db38b7a1b8ff743 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 21:28:32 +0200 Subject: [PATCH 26/62] Add utility method --- .../java/org/togetherjava/formatter/Formatter.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index e4ce021e36..60e8a905bd 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -1,5 +1,6 @@ package org.togetherjava.formatter; +import org.togetherjava.formatter.tokenizer.Lexer; import org.togetherjava.formatter.tokenizer.Token; import org.togetherjava.formatter.tokenizer.TokenType; @@ -49,6 +50,18 @@ public String format(List tokens) { return result.toString(); } + /** + * Formats the given string using a given lexer + * + * @param input input to format + * @param lexer lexer to use + * @return resulting code + * @author illuminator3 + */ + public String format(String input, Lexer lexer) { + return format(lexer.tokenize(input)); + } + /** * Reverts the tokens into the "original state" before the tokenization occurred * From 1d6198a8940e7930227f89c8acc3b641470d4200 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 21:36:55 +0200 Subject: [PATCH 27/62] Change tab to 4 spaces --- .../src/main/java/org/togetherjava/formatter/Formatter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index 60e8a905bd..29d251afc6 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -204,7 +204,7 @@ private StringBuilder writeCodeSection(List tokens) { * @author illuminator3 */ private void putIndentation(int indentation, StringBuilder sb) { - IntStream.range(0, indentation).forEach(n -> sb.append("\t")); + IntStream.range(0, indentation).forEach(n -> sb.append(" ")); } /** From f942e8a943778933bc5e3bc9331d04db77903c5a Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 21:40:59 +0200 Subject: [PATCH 28/62] Fix else not formatting properly --- .../main/java/org/togetherjava/formatter/Formatter.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index 29d251afc6..843ffc26d3 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -24,7 +24,8 @@ public class Formatter { TokenType.SMALLER, TokenType.BIGGER, TokenType.COMMA, TokenType.FOR, TokenType.IF, TokenType.WHILE, TokenType.PLUSPLUS, TokenType.MINUSMINUS, TokenType.RETURN, TokenType.THIS, TokenType.PUBLIC, TokenType.PROTECTED, TokenType.PRIVATE, TokenType.TRY, - TokenType.CATCH, TokenType.PACKAGE, TokenType.METHOD_REFERENCE, TokenType.ELSE_IF); + TokenType.CATCH, TokenType.PACKAGE, TokenType.METHOD_REFERENCE, TokenType.ELSE_IF, + TokenType.ELSE); /** * Formats the given tokens @@ -102,7 +103,7 @@ private StringBuilder writeCodeSection(List tokens) { iteration: { if (type == TokenType.OPEN_BRACES) { if (lastToken == TokenType.CLOSE_PARENTHESIS - || lastToken == TokenType.IDENTIFIER || lastToken == TokenType.TRY) { + || lastToken == TokenType.IDENTIFIER || lastToken == TokenType.TRY || lastToken == TokenType.ELSE) { result.append(" "); } @@ -134,7 +135,8 @@ private StringBuilder writeCodeSection(List tokens) { break iteration; } else if (type == TokenType.IDENTIFIER && (lastToken == TokenType.CLOSE_BRACES || lastToken == TokenType.OPEN_BRACES - || lastToken == TokenType.SEMICOLON)) { + || lastToken == TokenType.SEMICOLON + || lastToken == TokenType.UNKNOWN)) { append(result, token); break iteration; From 1e77938470fab9e6d360a9e0ecde55fb3404aff5 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 21:41:55 +0200 Subject: [PATCH 29/62] Add unit tests --- formatter/build.gradle | 15 ++- .../togetherjava/formatter/FormatterTest.java | 92 +++++++++++++++++++ .../formatter/tokenizer/LexerTest.java | 61 ++++++++++++ 3 files changed, 167 insertions(+), 1 deletion(-) create mode 100644 formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java create mode 100644 formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java diff --git a/formatter/build.gradle b/formatter/build.gradle index bab715720b..c5503d267e 100644 --- a/formatter/build.gradle +++ b/formatter/build.gradle @@ -3,4 +3,17 @@ plugins { } group 'org.togetherjava' -version '1.0-SNAPSHOT' \ No newline at end of file +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.2' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.2' +} + +test { + useJUnitPlatform() +} diff --git a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java new file mode 100644 index 0000000000..532bcaf695 --- /dev/null +++ b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java @@ -0,0 +1,92 @@ +package org.togetherjava.formatter; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.togetherjava.formatter.tokenizer.Lexer; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class FormatterTest { + Lexer lexer; + Formatter formatter; + + @BeforeAll + void init() { + lexer = new Lexer(); + formatter = new Formatter(); + } + + @Test + @DisplayName("Format Test #1") + void formatTest1() { + assertEquals(""" + ```java + public static void main(String[] args) { + System.out.println("Hello World!"); + } + + ```""", formatter.format("public static\nvoid main ( String [ ]args){ System.out. println( \"Hello World!\" );}", lexer)); + } + + @Test + @DisplayName("Format Test #2") + void formatTest2() { + assertEquals(""" + ```java + List input = new ArrayList<>(); + List result = new ArrayList<>(); + for (String s : input) { + result.add(s.trim()); + } + return result; + + ```""", formatter.format("Listinput=new ArrayList<>();List result=new ArrayList<>();for(String s:input){result.add(s.trim());}return result;", lexer)); + } + + @Test + @DisplayName("Format Test #3") + void formatTest3() { + assertEquals(""" + ```java + if () { + if () { + if () { + if () { + + ```""", formatter.format("if(){if(){if(){if(){", lexer)); + } + + @Test + @DisplayName("Format Test #4") + void formatTest4() { + assertEquals(""" + ```java + while (if () e) { + + } + } + + ```""", formatter.format("while(if()e){}}", lexer)); + } + + @Test + @DisplayName("Format Test #5") + void formatTest5() { + assertEquals(""" + ```java + if (1) { + + } + else if (2) { + + } + else { + + } + + ```""", formatter.format("if(1){}else if(2){}else{}", lexer)); + } +} diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java new file mode 100644 index 0000000000..0349992a9c --- /dev/null +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -0,0 +1,61 @@ +package org.togetherjava.formatter.tokenizer; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.util.ArrayList; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class LexerTest { + Lexer lexer; + + @BeforeAll + void init() { + lexer = new Lexer(); + } + + @Test + @DisplayName("Invalid input does throw an exception") + void testInvalidInput() { + assertThrows(TokenizationException.class, () -> lexer.tokenize("\r")); + } + + @Test + @DisplayName("Valid input does not throw an exception") + void testValidInput() { + assertDoesNotThrow(() -> lexer.tokenize("\n")); + } + + @Test + @DisplayName("Empty input does not throw an exception") + void testEmptyInput() { + assertDoesNotThrow(() -> lexer.tokenize("")); + } + + @Test + @DisplayName("Given input returns expected result") + void testInput() { + String testString = + "class enum record interface import if for while null extends implements new return package this yield catch try else if else public private protected static sealed non-sealed final abstract void int long short byte boolean float double char ( ) { } [ ] ; :: : , += -= *= /= %= &= |= == != >= > <= < ! = ++ + -- - && || /* a */ / * . @annotation 0 \"string\" identifier ` "; + List tokens = lexer.tokenize(testString).stream().map(Token::type).toList(), + expected = new ArrayList<>(); + + for (TokenType type : TokenType.values()) { + if (type == TokenType.UNKNOWN) { + System.out.println("hi"); + } + + if (type != TokenType.WHITSPACE) { + expected.add(type); + expected.add(TokenType.WHITSPACE); + } + } + + assertEquals(expected, tokens); + } +} From 36b85789d47c04e4eab79e28f16383d44f72cba9 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 23:48:06 +0200 Subject: [PATCH 30/62] Clean up stuff and fix typos --- .../org/togetherjava/formatter/Formatter.java | 69 ++++++++++++------- .../formatter/tokenizer/Lexer.java | 28 ++++---- .../formatter/tokenizer/Token.java | 10 +-- .../formatter/tokenizer/TokenType.java | 10 +-- .../formatter/tokenizer/LexerTest.java | 4 +- 5 files changed, 74 insertions(+), 47 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index 843ffc26d3..b3289c55f3 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -6,8 +6,8 @@ import java.util.ArrayList; import java.util.List; +import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.IntStream; /** * Formatter which can format a given string into a string which contains code blocks etc @@ -16,9 +16,35 @@ */ public class Formatter { /** - * List of tokens who should not be put after a space + * Set of tokens who should not be put after a space:
+ * - DOT
+ * - SEMICOLON
+ * - NOT
+ * - OPEN_PARENTHESIS
+ * - CLOSE_PARENTHESIS
+ * - OPEN_BRACKETS
+ * - CLOSE_BRACKETS
+ * - SMALLER
+ * - BIGGER
+ * - COMMA
+ * - FOR
+ * - IF
+ * - WHILE
+ * - PLUSPLUS
+ * - MINUSMINUS
+ * - RET URN
+ * - THIS
+ * - PUBLIC
+ * - PROTECTED
+ * - PRIVATE
+ * - TRY
+ * - CATCH
+ * - PACKAGE
+ * - METHOD_REFERENCE
+ * - ELSE_IF
+ * - ELSE
*/ - private static final List NON_SPACE_TOKENS = List.of(TokenType.DOT, + private static final Set NON_SPACE_TOKENS = Set.of(TokenType.DOT, TokenType.SEMICOLON, TokenType.NOT, TokenType.OPEN_PARENTHESIS, TokenType.CLOSE_PARENTHESIS, TokenType.OPEN_BRACKETS, TokenType.CLOSE_BRACKETS, TokenType.SMALLER, TokenType.BIGGER, TokenType.COMMA, TokenType.FOR, TokenType.IF, @@ -44,7 +70,7 @@ public String format(List tokens) { .append(writeCodeSection(section.tokens())) .append("\n```"); } else { - result.append(revert(section.tokens())); + result.append(joinTokens(section.tokens())); } } @@ -64,13 +90,13 @@ public String format(String input, Lexer lexer) { } /** - * Reverts the tokens into the "original state" before the tokenization occurred + * Joins given tokens together and normalizes whitespaces * - * @param tokens tokens to revert - * @return original state + * @param tokens tokens to join + * @return joined form of the tokens * @author illuminator3 */ - private String revert(List tokens) { + private String joinTokens(List tokens) { return tokens.stream().map(Token::content).collect(Collectors.joining()); } @@ -82,7 +108,9 @@ private String revert(List tokens) { * @author illuminator3 */ private StringBuilder writeCodeSection(List tokens) { - purgeWhitespaces(tokens = makeMutable(tokens)); + List normalizedTokens = makeMutable(tokens); + + purgeWhitespaces(normalizedTokens); TokenType lastToken = TokenType.UNKNOWN; StringBuilder result = new StringBuilder(); @@ -91,7 +119,7 @@ private StringBuilder writeCodeSection(List tokens) { boolean forClosed = true; int forClosingLevel = 0; - for (Token token : tokens) { + for (Token token : normalizedTokens) { TokenType type = token.type(); if (lastNewLine && type != TokenType.CLOSE_BRACES) { @@ -206,7 +234,7 @@ private StringBuilder writeCodeSection(List tokens) { * @author illuminator3 */ private void putIndentation(int indentation, StringBuilder sb) { - IntStream.range(0, indentation).forEach(n -> sb.append(" ")); + sb.append(" ".repeat(indentation)); } /** @@ -238,7 +266,7 @@ private List makeMutable(List in) { * @author illuminator3 */ private void purgeWhitespaces(List tokens) { - tokens.removeIf(t -> t.type() == TokenType.WHITSPACE); + tokens.removeIf(t -> t.type() == TokenType.WHITESPACE); } /** @@ -249,29 +277,24 @@ private void purgeWhitespaces(List tokens) { * @author illuminator3 */ private List indexTokens(List tokens) { - List result = new ArrayList<>(); - - for (Token token : tokens) { - result.add(new IndexedToken(token, isCodeToken(token))); - } - - return result; + return tokens.stream() + .map(token -> new IndexedToken(token, isTokenPartOfCode(token))) + .toList(); } /** - * Checks if a given token is a code token + * Checks if a given token could be part of code * * @param token token to check * @return true if it's a code token, false if not * @author illuminator3 */ - private boolean isCodeToken(Token token) { + private boolean isTokenPartOfCode(Token token) { return token.type() != TokenType.UNKNOWN; } /** - * Sectionizes a given list of tokens into sections who are code sections and sections who are - * not + * Sectionizes a given list of tokens into sections who are code sections and sections who are not * * @param indexedTokens indexed tokens * @return list of sections diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java index 75c81a4db5..b066924481 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -12,6 +12,9 @@ * @author illuminator3 */ public class Lexer { + /** + * Regex to match multi-line Java comments (including Javadoc) + */ private static final Pattern commentPatcherRegex = Pattern.compile("(/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)"); @@ -50,25 +53,26 @@ private List tokenizeLine(String line) { String content; while (!(content = line.substring(index)).isEmpty()) { - tokenCheck: { - for (TokenType token : TokenType.values()) { - Matcher matcher = token.getRegex().matcher(content); + Token token = findToken(content); - if (matcher.find()) { - String found = matcher.group(1); + index += token.content().length(); - tokens.add(new Token(found, token)); - index += found.length(); + tokens.add(token); + } - break tokenCheck; - } - } + return tokens; + } + + private Token findToken(String content) { + for (TokenType type : TokenType.values()) { + Matcher matcher = type.getRegex().matcher(content); - throw new TokenizationException("Token not found for '" + content + "'"); + if (matcher.find()) { + return new Token(matcher.group(1), type); } } - return tokens; + throw new TokenizationException("Token not found for '" + content + "'"); } /** diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java index 21842c8703..e924af3985 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java @@ -1,6 +1,6 @@ package org.togetherjava.formatter.tokenizer; -import java.util.List; +import java.util.Set; /** * Class representing a Token with a given content and a type @@ -8,12 +8,12 @@ * @author illuminator3 */ public record Token(String content, TokenType type) { - private static final List displayTypes = - List.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING, TokenType.COMMENT); + private static final Set displayTypes = + Set.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING, TokenType.COMMENT); @Override public String toString() { - return type().name() + displayMe(); + return type().name() + formatForDisplay(); } /** @@ -22,7 +22,7 @@ public String toString() { * @return the displayed value * @author illuminator3 */ - private String displayMe() { + private String formatForDisplay() { if (displayTypes.contains(type())) { return "(" + content() + ")"; } diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index bb0bc49395..9dc71a04e5 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -81,7 +81,7 @@ public enum TokenType { BOOL_AND("&&"), BOOL_OR("||"), - // this has to be other DIVIDE or else it'll be seen as two divides + // this has to be over DIVIDE or else it'll be seen as 2x DIVIDE COMMENT(Pattern.compile("^(//.*|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)")), DIVIDE("/"), @@ -92,17 +92,17 @@ public enum TokenType { NUMBER(Pattern.compile("^((0[xb])?([0-9_]+|[0-9_]*(\\.\\d*))[dDfFlL]?)")), STRING(Pattern.compile("^(\"[^\"]*\")")), IDENTIFIER(Pattern.compile("^([a-zA-Z][a-zA-Z0-9_]*)")), - WHITSPACE(Pattern.compile("^(\s+)")), + WHITESPACE(Pattern.compile("^(\s+)")), UNKNOWN(Pattern.compile("^(.)")); private final Pattern regex; private final boolean isKeyword; - TokenType(String spattern, boolean isKeyword) { + TokenType(String pattern, boolean isKeyword) { if (!isKeyword) { - this.regex = Pattern.compile("^(\\Q" + spattern + "\\E)"); + this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")"); } else { - this.regex = Pattern.compile("^(\\Q" + spattern + "\\E)[^a-zA-Z]"); + this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")[^a-zA-Z]"); } this.isKeyword = isKeyword; diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java index 0349992a9c..e14bf44c00 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -50,9 +50,9 @@ void testInput() { System.out.println("hi"); } - if (type != TokenType.WHITSPACE) { + if (type != TokenType.WHITESPACE) { expected.add(type); - expected.add(TokenType.WHITSPACE); + expected.add(TokenType.WHITESPACE); } } From d38aa28832275b0fab2803f0d7101a20c7629278 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Fri, 10 Sep 2021 23:52:09 +0200 Subject: [PATCH 31/62] Rename "IndexedToken" to "CheckedToken" --- .../org/togetherjava/formatter/Formatter.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index b3289c55f3..6617f05968 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -276,9 +276,9 @@ private void purgeWhitespaces(List tokens) { * @return indexed tokens * @author illuminator3 */ - private List indexTokens(List tokens) { + private List indexTokens(List tokens) { return tokens.stream() - .map(token -> new IndexedToken(token, isTokenPartOfCode(token))) + .map(token -> new CheckedToken(token, isTokenPartOfCode(token))) .toList(); } @@ -296,19 +296,19 @@ private boolean isTokenPartOfCode(Token token) { /** * Sectionizes a given list of tokens into sections who are code sections and sections who are not * - * @param indexedTokens indexed tokens + * @param checkedTokens indexed tokens * @return list of sections * @author illuminator3 */ - private List
sectionize(List indexedTokens) { - IndexedToken first = indexedTokens.get(0); + private List
sectionize(List checkedTokens) { + CheckedToken first = checkedTokens.get(0); Section currSec = new Section(new ArrayList<>(), first.isCode()); List
result = new ArrayList<>(); currSec.tokens().add(first.token()); - for (int i = 1; i < indexedTokens.size(); i++) { - IndexedToken next = indexedTokens.get(i); + for (int i = 1; i < checkedTokens.size(); i++) { + CheckedToken next = checkedTokens.get(i); if (currSec.isCodeSection() != next.isCode()) { result.add(currSec); @@ -337,6 +337,6 @@ private static record Section(List tokens, boolean isCodeSection) { * * @author illuminator3 */ - private static record IndexedToken(Token token, boolean isCode) { + private static record CheckedToken(Token token, boolean isCode) { } } From e5a6caa7623498107a67c9bd973d9a1eccdfee59 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sat, 11 Sep 2021 13:14:25 +0200 Subject: [PATCH 32/62] Change test display name --- .../java/org/togetherjava/formatter/tokenizer/LexerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java index e14bf44c00..85680709e1 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -38,7 +38,7 @@ void testEmptyInput() { } @Test - @DisplayName("Given input returns expected result") + @DisplayName("All tokens get tokenized correctly") void testInput() { String testString = "class enum record interface import if for while null extends implements new return package this yield catch try else if else public private protected static sealed non-sealed final abstract void int long short byte boolean float double char ( ) { } [ ] ; :: : , += -= *= /= %= &= |= == != >= > <= < ! = ++ + -- - && || /* a */ / * . @annotation 0 \"string\" identifier ` "; From 7ec3e9a992197a7106540c31d760f9c042dd0769 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sat, 11 Sep 2021 13:18:11 +0200 Subject: [PATCH 33/62] Remove debug statement --- .../java/org/togetherjava/formatter/tokenizer/LexerTest.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java index 85680709e1..194beb1f9d 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -46,10 +46,6 @@ void testInput() { expected = new ArrayList<>(); for (TokenType type : TokenType.values()) { - if (type == TokenType.UNKNOWN) { - System.out.println("hi"); - } - if (type != TokenType.WHITESPACE) { expected.add(type); expected.add(TokenType.WHITESPACE); From 4237e97418fb9e0d028a2cab7ecb3668b8544f2c Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sat, 11 Sep 2021 19:49:14 +0200 Subject: [PATCH 34/62] Add test case --- .../org/togetherjava/formatter/tokenizer/LexerTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java index 194beb1f9d..8da4cfefb0 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -54,4 +54,10 @@ void testInput() { assertEquals(expected, tokens); } + + @Test + @DisplayName("Identifier doesn't get recognized as keyword") + void testIdentifierKeyword() { + assertEquals(TokenType.IDENTIFIER, lexer.tokenize("format").get(0).type()); + } } From 21c5560dca0b4ce4e887112cef703b0ad1c77567 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sat, 11 Sep 2021 21:18:43 +0200 Subject: [PATCH 35/62] Fix keywords not getting recognized if at the EOL --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 9dc71a04e5..df0bc8bc39 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -102,7 +102,7 @@ public enum TokenType { if (!isKeyword) { this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")"); } else { - this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")[^a-zA-Z]"); + this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")(?![^a-zA-Z])"); } this.isKeyword = isKeyword; From 801432cbfcb6ab1db550a8ffe286d559779a9c9b Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sat, 11 Sep 2021 21:19:15 +0200 Subject: [PATCH 36/62] Fix a typo --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index df0bc8bc39..e86fb7e59d 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -102,7 +102,7 @@ public enum TokenType { if (!isKeyword) { this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")"); } else { - this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")(?![^a-zA-Z])"); + this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")(?![a-zA-Z])"); } this.isKeyword = isKeyword; From 46271bb83e659202b8f43f472c89c9ccbc1b5072 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sun, 12 Sep 2021 21:02:23 +0200 Subject: [PATCH 37/62] Add operator option --- .../formatter/tokenizer/TokenType.java | 126 +++++++++--------- 1 file changed, 66 insertions(+), 60 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index e86fb7e59d..d333743c31 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -9,45 +9,45 @@ */ public enum TokenType { // keywords - CLASS("class", true), - ENUM("enum", true), - RECORD("record", true), - INTERFACE("interface", true), - IMPORT("import", true), - IF("if", true), - FOR("for", true), - WHILE("while", true), - NULL("null", true), - EXTENDS("extends", true), - IMPLEMENTS("implements", true), - NEW("new", true), - RETURN("return", true), - PACKAGE("package", true), - THIS("this", true), - YIELD("yield", true), - CATCH("catch", true), - TRY("try", true), - ELSE_IF("else if", true), // not really a keyword but required for formatting - ELSE("else", true), + CLASS("class", true, false), + ENUM("enum", true, false), + RECORD("record", true, false), + INTERFACE("interface", true, false), + IMPORT("import", true, false), + IF("if", true, false), + FOR("for", true, false), + WHILE("while", true, false), + NULL("null", true, false), + EXTENDS("extends", true, false), + IMPLEMENTS("implements", true, false), + NEW("new", true, false), + RETURN("return", true, false), + PACKAGE("package", true, false), + THIS("this", true, false), + YIELD("yield", true, false), + CATCH("catch", true, false), + TRY("try", true, false), + ELSE_IF("else if", true, false), // not really a keyword but required for formatting + ELSE("else", true, false), // access modifiers - PUBLIC("public", true), - PRIVATE("private", true), - PROTECTED("protected", true), - STATIC("static", true), - SEALED("sealed", true), - NON_SEALED("non-sealed", true), - FINAL("final", true), - ABSTRACT("abstract", true), + PUBLIC("public", true, false), + PRIVATE("private", true, false), + PROTECTED("protected", true, false), + STATIC("static", true, false), + SEALED("sealed", true, false), + NON_SEALED("non-sealed", true, false), + FINAL("final", true, false), + ABSTRACT("abstract", true, false), // primitive types - VOID("void", true), - INT("int", true), - LONG("long", true), - SHORT("short", true), - BYTE("byte", true), - BOOLEAN("boolean", true), - FLOAT("float", true), - DOUBLE("double", true), - CHAR("char", true), + VOID("void", true, false), + INT("int", true, false), + LONG("long", true, false), + SHORT("short", true, false), + BYTE("byte", true, false), + BOOLEAN("boolean", true, false), + FLOAT("float", true, false), + DOUBLE("double", true, false), + CHAR("char", true, false), // general tokens OPEN_PARENTHESIS("("), CLOSE_PARENTHESIS(")"), @@ -59,33 +59,33 @@ public enum TokenType { METHOD_REFERENCE("::"), COLON(":"), COMMA(","), - PLUS_EQUALS("+="), - MINUS_EQUALS("-="), - MULTIPLY_EQUALS("*="), - DIVIDE_EQUALS("/="), - MODULO_EQUALS("%="), - AND_EQUALS("&="), - OR_EQUALS("|="), - EQUALS("=="), - NOT_EQUALS("!="), - BIGGER_OR_EQUALS(">="), - BIGGER(">"), - SMALLER_OR_EQUALS("<="), - SMALLER("<"), + PLUS_EQUALS("+=", false, true), + MINUS_EQUALS("-=", false, true), + MULTIPLY_EQUALS("*=", false, true), + DIVIDE_EQUALS("/=", false, true), + MODULO_EQUALS("%=", false, true), + AND_EQUALS("&=", false, true), + OR_EQUALS("|=", false, true), + EQUALS("==", false, true), + NOT_EQUALS("!=", false, true), + BIGGER_OR_EQUALS(">=", false, true), + BIGGER(">", false, true), + SMALLER_OR_EQUALS("<=", false, true), + SMALLER("<", false, true), NOT("!"), - ASSIGN("="), + ASSIGN("=", false, true), PLUSPLUS("++"), - PLUS("+"), + PLUS("+", false, true), MINUSMINUS("--"), - MINUS("-"), - BOOL_AND("&&"), - BOOL_OR("||"), + MINUS("-", false, true), + BOOL_AND("&&", false, true), + BOOL_OR("||", false, true), // this has to be over DIVIDE or else it'll be seen as 2x DIVIDE COMMENT(Pattern.compile("^(//.*|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)")), - DIVIDE("/"), - MULTIPLY("*"), + DIVIDE("/", false, true), + MULTIPLY("*", false, true), DOT("."), // other ANNOTATION(Pattern.compile("^(@[a-zA-Z][a-zA-Z0-9_]*)")), @@ -96,9 +96,9 @@ public enum TokenType { UNKNOWN(Pattern.compile("^(.)")); private final Pattern regex; - private final boolean isKeyword; + private final boolean isKeyword, isOperator; - TokenType(String pattern, boolean isKeyword) { + TokenType(String pattern, boolean isKeyword, boolean isOperator) { if (!isKeyword) { this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")"); } else { @@ -106,15 +106,17 @@ public enum TokenType { } this.isKeyword = isKeyword; + this.isOperator = isOperator; } TokenType(Pattern regex) { this.regex = regex; this.isKeyword = false; + this.isOperator = false; } TokenType(String spattern) { - this(spattern, false); + this(spattern, false, false); } public Pattern getRegex() { @@ -124,4 +126,8 @@ public Pattern getRegex() { public boolean isKeyword() { return isKeyword; } + + public boolean isOperator() { + return isOperator; + } } From 5298990827b96d8432e626de13eb570d735e51ef Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sun, 12 Sep 2021 22:33:20 +0200 Subject: [PATCH 38/62] Make colon an operator --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index d333743c31..2436c8503a 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -57,7 +57,7 @@ public enum TokenType { CLOSE_BRACKETS("]"), SEMICOLON(";"), METHOD_REFERENCE("::"), - COLON(":"), + COLON(":", false, true), // technically not a "real" operator but used in an enhanced for loop COMMA(","), PLUS_EQUALS("+=", false, true), MINUS_EQUALS("-=", false, true), From 2de58b417eadfb5192087c6ab95bce24407111f0 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sun, 12 Sep 2021 22:33:48 +0200 Subject: [PATCH 39/62] Add super keyword --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 1 + 1 file changed, 1 insertion(+) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 2436c8503a..bf205ecc52 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -29,6 +29,7 @@ public enum TokenType { TRY("try", true, false), ELSE_IF("else if", true, false), // not really a keyword but required for formatting ELSE("else", true, false), + SUPER("super", true, false), // access modifiers PUBLIC("public", true, false), PRIVATE("private", true, false), From 22398bce49c68a6277f956a26680e79ba90588dc Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sun, 12 Sep 2021 22:34:22 +0200 Subject: [PATCH 40/62] Add wildcard token --- .../java/org/togetherjava/formatter/tokenizer/TokenType.java | 1 + 1 file changed, 1 insertion(+) diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index bf205ecc52..9975fc4d79 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -89,6 +89,7 @@ public enum TokenType { MULTIPLY("*", false, true), DOT("."), // other + WILDCARD("?"), ANNOTATION(Pattern.compile("^(@[a-zA-Z][a-zA-Z0-9_]*)")), NUMBER(Pattern.compile("^((0[xb])?([0-9_]+|[0-9_]*(\\.\\d*))[dDfFlL]?)")), STRING(Pattern.compile("^(\"[^\"]*\")")), From e56a4cadff6cae1d51db6b9373e119c2bc86661d Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sun, 12 Sep 2021 23:01:10 +0200 Subject: [PATCH 41/62] Initial commit of the new formatting system --- .../formatter/CodeSectionFormatter.java | 224 ++++++++++++++++++ .../org/togetherjava/formatter/Formatter.java | 127 +--------- .../formatter/LookaheadArrayDeque.java | 49 ++++ .../formatter/LookaheadQueue.java | 12 + .../SkippableLookaheadArrayDeque.java | 43 ++++ .../formatter/SkippableLookaheadQueue.java | 7 + .../togetherjava/formatter/FormatterTest.java | 59 ++++- 7 files changed, 393 insertions(+), 128 deletions(-) create mode 100644 formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java create mode 100644 formatter/src/main/java/org/togetherjava/formatter/LookaheadArrayDeque.java create mode 100644 formatter/src/main/java/org/togetherjava/formatter/LookaheadQueue.java create mode 100644 formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadArrayDeque.java create mode 100644 formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadQueue.java diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java new file mode 100644 index 0000000000..608b950707 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -0,0 +1,224 @@ +package org.togetherjava.formatter; + +import org.togetherjava.formatter.tokenizer.Token; +import org.togetherjava.formatter.tokenizer.TokenType; + +import java.util.*; + +class CodeSectionFormatter { + private final StringBuilder result = new StringBuilder(); + private final SkippableLookaheadQueue queue; + + private int indentation; + private boolean applyIndentation; + private int forLevel; + private int genericDepth; + private int enhancedLevel = -1; + + CodeSectionFormatter(List tokens) { + this(new SkippableLookaheadArrayDeque<>(tokens)); + } + + CodeSectionFormatter(SkippableLookaheadQueue queue) { + this.queue = queue; + + purgeWhitespaces(this.queue); + } + + private static void purgeWhitespaces(Queue queue) { + queue.removeIf(t -> t.type() == TokenType.WHITESPACE); + } + + void format() { + Token next; + + while (!queue.isEmpty() && (next = queue.remove()) != null) { + updateIndentation(next.type()); + applyIndentation(); + consume(next); + } + } + + private void consume(Token token) { + TokenType type = token.type(); + + if (checkGeneric(type)) { + result.append(token.content()); + + return; + } + + if (genericDepth != 0) { + if (type == TokenType.EXTENDS || type == TokenType.SUPER) { + result.append(' '); + } + + result.append(token.content()); + + if (type == TokenType.COMMA || type == TokenType.WILDCARD || type == TokenType.EXTENDS || type == TokenType.SUPER) { + result.append(' '); + } + + //------------------------------------------------ + + switch (type) { + case SMALLER -> genericDepth++; + case BIGGER -> genericDepth--; + } + + if (genericDepth == 0 && !queue.isEmpty() && queue.peek().type() != TokenType.OPEN_PARENTHESIS) { // last closing except if there's an opening parenthesis after it + result.append(' '); + } + } else { + if (isIndexedForLoop(type)) { // if it's a for int loop then set the forLevel to 2 + forLevel = 2; + } else if (isEnhancedForLoop(type)) { + enhancedLevel = 0; + } + + //------------------------------------------------ + + if (enhancedLevel != -1) { + switch (type) { + case OPEN_PARENTHESIS -> enhancedLevel++; + case CLOSE_PARENTHESIS -> enhancedLevel--; + } + } + + //------------------------------------------------ + + if (isOperator(token)) { // apply space before an operator (like +, - and *) + result.append(' '); + } + + result.append(token.content()); + + if (isKeyword(token) || isOperator(token) || isParenthesisRule(token) || type == TokenType.CLOSE_BRACKETS) { // put a space after e.g. 'try' or 'else' and ] or if it's an operator + result.append(' '); + } else if (shouldPutNewLineAfter(type)) { // put a new line after { and ; and } and comments and annotations + appendNewLine(); + + if (type == TokenType.SEMICOLON) { + forLevel--; + } + + applyIndentation = true; + } + + if (type == TokenType.IDENTIFIER && enhancedLevel != -1 && !queue.isEmpty() && queue.peek().type() == TokenType.IDENTIFIER) { + result.append(' '); + } + } + } + + private boolean checkGeneric(TokenType type) { + if (type == TokenType.SMALLER) { + int depth = 1; + + for (int i = 0;; i++) { + Token next = queue.peek(i); + + if (next == null || depth == 0) { + break; + } + + TokenType nextType = next.type(); + + if (!isValidGeneric(nextType)) { + return false; + } + + switch (nextType) { + case SMALLER -> depth++; + case BIGGER -> depth--; + } + } + + genericDepth = 1; + + return true; + } + + return false; + } + + private boolean isValidGeneric(TokenType type) { + return type == TokenType.WILDCARD || type == TokenType.SMALLER || type == TokenType.BIGGER || type == TokenType.COMMA || type == TokenType.DOT || type == TokenType.EXTENDS || type == TokenType.SUPER || type == TokenType.IDENTIFIER; + } + + private boolean shouldPutNewLineAfter(TokenType type) { + return type == TokenType.OPEN_BRACES || type == TokenType.SEMICOLON || type == TokenType.CLOSE_BRACES || type == TokenType.COMMENT || type == TokenType.ANNOTATION; + } + + private boolean isIndexedForLoop(TokenType type) { + return type == TokenType.FOR && !internalEnhancedFor(); + } + + private boolean isEnhancedForLoop(TokenType type) { + return type == TokenType.FOR && internalEnhancedFor(); + } + + private boolean internalEnhancedFor() { + return queue.peek(3, t -> { + TokenType ttype = t.type(); + + return ttype == TokenType.ANNOTATION || ttype == TokenType.FINAL; + }).type() == TokenType.COLON; + } + + /** + * Parenthesis rule: append a space after a closing parenthesis if the next token isn't another closing parenthesis, an operator or a semicolon + */ + private boolean isParenthesisRule(Token token) { + if (queue.isEmpty()) { + return false; + } + + Token next = queue.peek(); + TokenType nextType = next.type(); + + return token.type() == TokenType.CLOSE_PARENTHESIS && nextType != TokenType.CLOSE_PARENTHESIS && nextType != TokenType.SEMICOLON && !isOperator(next); + } + + /** + * Appends a new line if there's more in the token queue + * + * @author illuminator3 + */ + private void appendNewLine() { + if (!queue.isEmpty()) { + if (forLevel <= 0) { + result.append('\n'); + } else { + result.append(' '); // put a space after a ; in a for loop + } + } + } + + private boolean isKeyword(Token token) { + return token.type().isKeyword(); + } + + private boolean isOperator(Token token) { + return token.type().isOperator(); + } + + private void updateIndentation(TokenType type) { + switch (type) { + case OPEN_BRACES -> indentation++; + case CLOSE_BRACES -> indentation--; + } + } + + private void applyIndentation() { + if (applyIndentation) { + result.append(" ".repeat(Math.max(0, indentation))); + + applyIndentation = false; + } + } + + StringBuilder result() { + return result; + } +} diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index 6617f05968..ee23988a94 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -67,8 +67,8 @@ public String format(List tokens) { for (Section section : sections) { if (section.isCodeSection()) { result.append("```java\n") - .append(writeCodeSection(section.tokens())) - .append("\n```"); + .append(writeCodeSection(section.tokens())) + .append("\n```"); } else { result.append(joinTokens(section.tokens())); } @@ -101,129 +101,18 @@ private String joinTokens(List tokens) { } /** - * Writes and formats a given code section (in form of a list of tokens) into a StringBuilder + * Writes and formats a given code section (in form of a list of tokens) into a StringBuilder using a {@link CodeSectionFormatter} * * @param tokens tokens to write * @return written code sections * @author illuminator3 */ private StringBuilder writeCodeSection(List tokens) { - List normalizedTokens = makeMutable(tokens); + CodeSectionFormatter formatter = new CodeSectionFormatter(tokens); - purgeWhitespaces(normalizedTokens); + formatter.format(); - TokenType lastToken = TokenType.UNKNOWN; - StringBuilder result = new StringBuilder(); - boolean lastNewLine = false; - int indentation = 0; - boolean forClosed = true; - int forClosingLevel = 0; - - for (Token token : normalizedTokens) { - TokenType type = token.type(); - - if (lastNewLine && type != TokenType.CLOSE_BRACES) { - putIndentation(indentation, result); - } - - lastNewLine = false; - - iteration: { - if (type == TokenType.OPEN_BRACES) { - if (lastToken == TokenType.CLOSE_PARENTHESIS - || lastToken == TokenType.IDENTIFIER || lastToken == TokenType.TRY || lastToken == TokenType.ELSE) { - result.append(" "); - } - - append(result, token); - - result.append("\n"); - - lastNewLine = true; - indentation++; - - break iteration; - } else if (lastToken == TokenType.CLOSE_BRACKETS && type != TokenType.SEMICOLON) { - result.append(" "); - - append(result, token); - - break iteration; - } else if (type == TokenType.CLOSE_BRACES) { - result.append("\n"); - - putIndentation(--indentation, result); - - append(result, token); - - result.append("\n"); - - lastNewLine = true; - - break iteration; - } else if (type == TokenType.IDENTIFIER && (lastToken == TokenType.CLOSE_BRACES - || lastToken == TokenType.OPEN_BRACES - || lastToken == TokenType.SEMICOLON - || lastToken == TokenType.UNKNOWN)) { - append(result, token); - - break iteration; - } else if (type == TokenType.COMMENT || type == TokenType.SEMICOLON - || type == TokenType.ANNOTATION) { - if (type == TokenType.COMMENT) { - result.append(" "); - } - - append(result, token); - - if (forClosed) { - result.append("\n"); - - lastNewLine = true; - } - - break iteration; - } else if ((type == TokenType.OPEN_PARENTHESIS && lastToken != TokenType.IDENTIFIER - && lastToken != TokenType.NOT && lastToken != TokenType.BIGGER - && lastToken != TokenType.OPEN_PARENTHESIS) || lastToken == TokenType.PUBLIC - || lastToken == TokenType.PRIVATE || lastToken == TokenType.PROTECTED - || (lastToken == TokenType.BIGGER && type != TokenType.OPEN_PARENTHESIS) - || lastToken == TokenType.RETURN || lastToken == TokenType.COMMA - || lastToken == TokenType.CATCH - || (lastToken == TokenType.CLOSE_PARENTHESIS - && type != TokenType.CLOSE_PARENTHESIS && type != TokenType.DOT - && type != TokenType.COMMA) - || lastToken == TokenType.PACKAGE) { - result.append(" "); - } - - if (!forClosed) { - if (type == TokenType.OPEN_PARENTHESIS) { - forClosingLevel++; - } else if (type == TokenType.CLOSE_PARENTHESIS) { - forClosingLevel--; - } - - if (forClosingLevel == 0) { - forClosed = true; - } - } - - if (type == TokenType.FOR) { - forClosed = false; - } - - if (!(NON_SPACE_TOKENS.contains(type) || NON_SPACE_TOKENS.contains(lastToken))) { - result.append(" "); - } - - append(result, token); - } - - lastToken = type; - } - - return new StringBuilder(result.toString().replaceAll("([;}])\n\n", "$1\n")); + return formatter.result(); } /** @@ -278,8 +167,8 @@ private void purgeWhitespaces(List tokens) { */ private List indexTokens(List tokens) { return tokens.stream() - .map(token -> new CheckedToken(token, isTokenPartOfCode(token))) - .toList(); + .map(token -> new CheckedToken(token, isTokenPartOfCode(token))) + .toList(); } /** diff --git a/formatter/src/main/java/org/togetherjava/formatter/LookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/formatter/LookaheadArrayDeque.java new file mode 100644 index 0000000000..31dd4bf00e --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/LookaheadArrayDeque.java @@ -0,0 +1,49 @@ +package org.togetherjava.formatter; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * A {@link LookaheadQueue} implementation that is based on an {@link ArrayDeque} + * + * @author illuminator3 + */ +public class LookaheadArrayDeque extends ArrayDeque implements LookaheadQueue { + public LookaheadArrayDeque() { + super(); + } + + public LookaheadArrayDeque(int numElements) { + super(numElements); + } + + public LookaheadArrayDeque(Collection c) { + super(c); + } + + /** + * {@inheritDoc} + * + * @author illuminator3 + */ + @Override + public E peek(int n) { + List tmp = new ArrayList<>(); + + while (n != 0 && !isEmpty()) { + tmp.add(0, remove()); + + n--; + } + + E result = peek(); + + for (E element : tmp) { + addFirst(element); + } + + return result; + } +} diff --git a/formatter/src/main/java/org/togetherjava/formatter/LookaheadQueue.java b/formatter/src/main/java/org/togetherjava/formatter/LookaheadQueue.java new file mode 100644 index 0000000000..5f081baa60 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/LookaheadQueue.java @@ -0,0 +1,12 @@ +package org.togetherjava.formatter; + +import java.util.Queue; + +public interface LookaheadQueue extends Queue { + /** + * Peeks into the "future", peek(0) would be the equivalent to peek() + * + * @author illuminator3 + */ + E peek(int n); +} diff --git a/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadArrayDeque.java new file mode 100644 index 0000000000..957845e70f --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadArrayDeque.java @@ -0,0 +1,43 @@ +package org.togetherjava.formatter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Predicate; + +public class SkippableLookaheadArrayDeque extends LookaheadArrayDeque implements SkippableLookaheadQueue { + public SkippableLookaheadArrayDeque() { + super(); + } + + public SkippableLookaheadArrayDeque(int numElements) { + super(numElements); + } + + public SkippableLookaheadArrayDeque(Collection c) { + super(c); + } + + @Override + public E peek(int n, Predicate skip) { + List tmp = new ArrayList<>(); + + while (n != 0 && !isEmpty()) { + E current = remove(); + + tmp.add(0, current); + + if (!skip.test(current)) { + n--; + } + } + + E result = peek(); + + for (E element : tmp) { + addFirst(element); + } + + return result; + } +} diff --git a/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadQueue.java b/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadQueue.java new file mode 100644 index 0000000000..4906585f11 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadQueue.java @@ -0,0 +1,7 @@ +package org.togetherjava.formatter; + +import java.util.function.Predicate; + +public interface SkippableLookaheadQueue extends LookaheadQueue { + E peek(int n, Predicate skip); +} diff --git a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java index 532bcaf695..f19ed55a24 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java @@ -27,7 +27,6 @@ void formatTest1() { public static void main(String[] args) { System.out.println("Hello World!"); } - ```""", formatter.format("public static\nvoid main ( String [ ]args){ System.out. println( \"Hello World!\" );}", lexer)); } @@ -42,7 +41,6 @@ void formatTest2() { result.add(s.trim()); } return result; - ```""", formatter.format("Listinput=new ArrayList<>();List result=new ArrayList<>();for(String s:input){result.add(s.trim());}return result;", lexer)); } @@ -55,7 +53,6 @@ void formatTest3() { if () { if () { if () { - ```""", formatter.format("if(){if(){if(){if(){", lexer)); } @@ -65,10 +62,8 @@ void formatTest4() { assertEquals(""" ```java while (if () e) { - } } - ```""", formatter.format("while(if()e){}}", lexer)); } @@ -78,15 +73,61 @@ void formatTest5() { assertEquals(""" ```java if (1) { - } else if (2) { - } else { - } - ```""", formatter.format("if(1){}else if(2){}else{}", lexer)); } + + @Test + @DisplayName("For int loop working correctly") + void testForInt() { + assertEquals(""" + ```java + for (int i = 0; i < 3; i++) { + } + ```""", formatter.format("for(int i=0;i<3;i++){}", lexer)); + } + + @Test + @DisplayName("Diamond operator rendering correctly") + void testDiamondOperator() { + assertEquals(""" + ```java + List list = new ArrayList<>(); + ```""", formatter.format("Listlist=new ArrayList < > ( ) ;", lexer)); + } + + @Test + @DisplayName("BIGGER and SMALLER rendering correctly") + void testBiggerAndSmaller() { + assertEquals(""" + ```java + 3 < 2 && 2 > 3 + ```""", formatter.format("3<2&&2>3", lexer)); + } + + @Test + @DisplayName("Comment renders correctly") + void testComment() { + assertEquals(""" + ```java + // this is a comment + void foo() { + } + ```""", formatter.format("// this is a comment\nvoid foo() {}", lexer)); + } + + @Test + @DisplayName("Annotation renders correctly") + void testAnnotation() { + assertEquals(""" + ```java + @MyAnnotation + void foo() { + } + ```""", formatter.format("@MyAnnotation\nvoid foo() {}", lexer)); + } } From 0f787a5711557225e460f1c966575c3c6aab30ac Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 17:34:37 +0200 Subject: [PATCH 42/62] Split into multiple methods --- .../formatter/CodeSectionFormatter.java | 102 ++++++++++-------- 1 file changed, 59 insertions(+), 43 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 608b950707..88a794a83c 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -49,65 +49,81 @@ private void consume(Token token) { } if (genericDepth != 0) { - if (type == TokenType.EXTENDS || type == TokenType.SUPER) { - result.append(' '); - } + handleGeneric(token); - result.append(token.content()); + return; + } - if (type == TokenType.COMMA || type == TokenType.WILDCARD || type == TokenType.EXTENDS || type == TokenType.SUPER) { - result.append(' '); - } + checkFor(type); + updateEnhancedLevel(type); + put(token); + } - //------------------------------------------------ + private void put(Token token) { + TokenType type = token.type(); - switch (type) { - case SMALLER -> genericDepth++; - case BIGGER -> genericDepth--; - } + if (isOperator(token)) { // apply space before an operator (like +, - and *) + result.append(' '); + } - if (genericDepth == 0 && !queue.isEmpty() && queue.peek().type() != TokenType.OPEN_PARENTHESIS) { // last closing except if there's an opening parenthesis after it - result.append(' '); - } - } else { - if (isIndexedForLoop(type)) { // if it's a for int loop then set the forLevel to 2 - forLevel = 2; - } else if (isEnhancedForLoop(type)) { - enhancedLevel = 0; - } + result.append(token.content()); - //------------------------------------------------ + if (isKeyword(token) || isOperator(token) || isParenthesisRule(token) || type == TokenType.CLOSE_BRACKETS) { // put a space after e.g. 'try' or 'else' and ] or if it's an operator + result.append(' '); + } else if (shouldPutNewLineAfter(type)) { // put a new line after { and ; and } and comments and annotations + appendNewLine(); - if (enhancedLevel != -1) { - switch (type) { - case OPEN_PARENTHESIS -> enhancedLevel++; - case CLOSE_PARENTHESIS -> enhancedLevel--; - } + if (type == TokenType.SEMICOLON) { + forLevel--; } - //------------------------------------------------ + applyIndentation = true; + } + + if (type == TokenType.IDENTIFIER && enhancedLevel != -1 && !queue.isEmpty() && queue.peek().type() == TokenType.IDENTIFIER) { + result.append(' '); + } + } - if (isOperator(token)) { // apply space before an operator (like +, - and *) - result.append(' '); + private void updateEnhancedLevel(TokenType type) { + if (enhancedLevel != -1) { + switch (type) { + case OPEN_PARENTHESIS -> enhancedLevel++; + case CLOSE_PARENTHESIS -> enhancedLevel--; } + } + } - result.append(token.content()); + private void checkFor(TokenType type) { + if (isIndexedForLoop(type)) { // if it's a for int loop then set the forLevel to 2 + forLevel = 2; + } else if (isEnhancedForLoop(type)) { + enhancedLevel = 0; + } + } - if (isKeyword(token) || isOperator(token) || isParenthesisRule(token) || type == TokenType.CLOSE_BRACKETS) { // put a space after e.g. 'try' or 'else' and ] or if it's an operator - result.append(' '); - } else if (shouldPutNewLineAfter(type)) { // put a new line after { and ; and } and comments and annotations - appendNewLine(); + private void handleGeneric(Token token) { + TokenType type = token.type(); - if (type == TokenType.SEMICOLON) { - forLevel--; - } + if (type == TokenType.EXTENDS || type == TokenType.SUPER) { + result.append(' '); + } - applyIndentation = true; - } + result.append(token.content()); - if (type == TokenType.IDENTIFIER && enhancedLevel != -1 && !queue.isEmpty() && queue.peek().type() == TokenType.IDENTIFIER) { - result.append(' '); - } + if (type == TokenType.COMMA || type == TokenType.WILDCARD || type == TokenType.EXTENDS || type == TokenType.SUPER) { + result.append(' '); + } + + //------------------------------------------------ + + switch (type) { + case SMALLER -> genericDepth++; + case BIGGER -> genericDepth--; + } + + if (genericDepth == 0 && !queue.isEmpty() && queue.peek().type() != TokenType.OPEN_PARENTHESIS) { // last closing except if there's an opening parenthesis after it + result.append(' '); } } From a01ba7b7d53ca8a4ac2bf9ec524714936205cf3f Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 17:35:21 +0200 Subject: [PATCH 43/62] Remove unused things --- .../org/togetherjava/formatter/Formatter.java | 81 ------------------- 1 file changed, 81 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index ee23988a94..2640986acb 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -15,44 +15,6 @@ * @author illuminator3 */ public class Formatter { - /** - * Set of tokens who should not be put after a space:
- * - DOT
- * - SEMICOLON
- * - NOT
- * - OPEN_PARENTHESIS
- * - CLOSE_PARENTHESIS
- * - OPEN_BRACKETS
- * - CLOSE_BRACKETS
- * - SMALLER
- * - BIGGER
- * - COMMA
- * - FOR
- * - IF
- * - WHILE
- * - PLUSPLUS
- * - MINUSMINUS
- * - RET URN
- * - THIS
- * - PUBLIC
- * - PROTECTED
- * - PRIVATE
- * - TRY
- * - CATCH
- * - PACKAGE
- * - METHOD_REFERENCE
- * - ELSE_IF
- * - ELSE
- */ - private static final Set NON_SPACE_TOKENS = Set.of(TokenType.DOT, - TokenType.SEMICOLON, TokenType.NOT, TokenType.OPEN_PARENTHESIS, - TokenType.CLOSE_PARENTHESIS, TokenType.OPEN_BRACKETS, TokenType.CLOSE_BRACKETS, - TokenType.SMALLER, TokenType.BIGGER, TokenType.COMMA, TokenType.FOR, TokenType.IF, - TokenType.WHILE, TokenType.PLUSPLUS, TokenType.MINUSMINUS, TokenType.RETURN, - TokenType.THIS, TokenType.PUBLIC, TokenType.PROTECTED, TokenType.PRIVATE, TokenType.TRY, - TokenType.CATCH, TokenType.PACKAGE, TokenType.METHOD_REFERENCE, TokenType.ELSE_IF, - TokenType.ELSE); - /** * Formats the given tokens * @@ -115,49 +77,6 @@ private StringBuilder writeCodeSection(List tokens) { return formatter.result(); } - /** - * Puts the needed indentation into a StringBuilder - * - * @param indentation indentation level - * @param sb string builder - * @author illuminator3 - */ - private void putIndentation(int indentation, StringBuilder sb) { - sb.append(" ".repeat(indentation)); - } - - /** - * Appends a token to a StringBuilder - * - * @param sb string builder - * @param token token to append - * @author illuminator3 - */ - private void append(StringBuilder sb, Token token) { - sb.append(token.content()); - } - - /** - * Makes a list mutable - * - * @param in (im)mutable list - * @return mutable list - * @author illuminator3 - */ - private List makeMutable(List in) { - return new ArrayList<>(in); - } - - /** - * Removes every whitespace from a given list of tokens - * - * @param tokens tokens to remove whitesapces from - * @author illuminator3 - */ - private void purgeWhitespaces(List tokens) { - tokens.removeIf(t -> t.type() == TokenType.WHITESPACE); - } - /** * Indexes tokens to contain information about whether they are code tokens or not * From 2db9a1c639bc9585ad3f6cc9198e0c0b169d57a9 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 17:35:37 +0200 Subject: [PATCH 44/62] Fix javadoc --- .../src/main/java/org/togetherjava/formatter/Formatter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index 2640986acb..74edd235c8 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -141,7 +141,7 @@ private static record Section(List tokens, boolean isCodeSection) { } /** - * IndexedToken POJR + * CheckedToken POJR * * @author illuminator3 */ From 489698356898e4889255c05f6a2c1831468c41f1 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 17:36:50 +0200 Subject: [PATCH 45/62] Move lookahead queue related things to the util package --- .../java/org/togetherjava/formatter/CodeSectionFormatter.java | 2 ++ .../togetherjava/formatter/{ => util}/LookaheadArrayDeque.java | 2 +- .../org/togetherjava/formatter/{ => util}/LookaheadQueue.java | 2 +- .../formatter/{ => util}/SkippableLookaheadArrayDeque.java | 2 +- .../formatter/{ => util}/SkippableLookaheadQueue.java | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) rename formatter/src/main/java/org/togetherjava/formatter/{ => util}/LookaheadArrayDeque.java (95%) rename formatter/src/main/java/org/togetherjava/formatter/{ => util}/LookaheadQueue.java (84%) rename formatter/src/main/java/org/togetherjava/formatter/{ => util}/SkippableLookaheadArrayDeque.java (95%) rename formatter/src/main/java/org/togetherjava/formatter/{ => util}/SkippableLookaheadQueue.java (78%) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 88a794a83c..045f833340 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -2,6 +2,8 @@ import org.togetherjava.formatter.tokenizer.Token; import org.togetherjava.formatter.tokenizer.TokenType; +import org.togetherjava.formatter.util.SkippableLookaheadArrayDeque; +import org.togetherjava.formatter.util.SkippableLookaheadQueue; import java.util.*; diff --git a/formatter/src/main/java/org/togetherjava/formatter/LookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java similarity index 95% rename from formatter/src/main/java/org/togetherjava/formatter/LookaheadArrayDeque.java rename to formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java index 31dd4bf00e..f2f362e1c0 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/LookaheadArrayDeque.java +++ b/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter; +package org.togetherjava.formatter.util; import java.util.ArrayDeque; import java.util.ArrayList; diff --git a/formatter/src/main/java/org/togetherjava/formatter/LookaheadQueue.java b/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadQueue.java similarity index 84% rename from formatter/src/main/java/org/togetherjava/formatter/LookaheadQueue.java rename to formatter/src/main/java/org/togetherjava/formatter/util/LookaheadQueue.java index 5f081baa60..4ff34ced98 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/LookaheadQueue.java +++ b/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadQueue.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter; +package org.togetherjava.formatter.util; import java.util.Queue; diff --git a/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java similarity index 95% rename from formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadArrayDeque.java rename to formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java index 957845e70f..59871ca8f1 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadArrayDeque.java +++ b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter; +package org.togetherjava.formatter.util; import java.util.ArrayList; import java.util.Collection; diff --git a/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadQueue.java b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadQueue.java similarity index 78% rename from formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadQueue.java rename to formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadQueue.java index 4906585f11..ba4ed37361 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/SkippableLookaheadQueue.java +++ b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadQueue.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter; +package org.togetherjava.formatter.util; import java.util.function.Predicate; From ed304bf8cb7144f3c70c30de09a3e4095301939c Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 17:39:45 +0200 Subject: [PATCH 46/62] Apply spotless --- .../formatter/CodeSectionFormatter.java | 43 +++++++++++++------ .../org/togetherjava/formatter/Formatter.java | 14 +++--- .../util/SkippableLookaheadArrayDeque.java | 3 +- .../togetherjava/formatter/FormatterTest.java | 8 +++- .../formatter/tokenizer/LexerTest.java | 4 +- 5 files changed, 47 insertions(+), 25 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 045f833340..889ad69112 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -70,9 +70,12 @@ private void put(Token token) { result.append(token.content()); - if (isKeyword(token) || isOperator(token) || isParenthesisRule(token) || type == TokenType.CLOSE_BRACKETS) { // put a space after e.g. 'try' or 'else' and ] or if it's an operator + if (isKeyword(token) || isOperator(token) || isParenthesisRule(token) + || type == TokenType.CLOSE_BRACKETS) { // put a space after e.g. 'try' or 'else' and + // ] or if it's an operator result.append(' '); - } else if (shouldPutNewLineAfter(type)) { // put a new line after { and ; and } and comments and annotations + } else if (shouldPutNewLineAfter(type)) { // put a new line after { and ; and } and comments + // and annotations appendNewLine(); if (type == TokenType.SEMICOLON) { @@ -82,7 +85,8 @@ private void put(Token token) { applyIndentation = true; } - if (type == TokenType.IDENTIFIER && enhancedLevel != -1 && !queue.isEmpty() && queue.peek().type() == TokenType.IDENTIFIER) { + if (type == TokenType.IDENTIFIER && enhancedLevel != -1 && !queue.isEmpty() + && queue.peek().type() == TokenType.IDENTIFIER) { result.append(' '); } } @@ -90,7 +94,7 @@ private void put(Token token) { private void updateEnhancedLevel(TokenType type) { if (enhancedLevel != -1) { switch (type) { - case OPEN_PARENTHESIS -> enhancedLevel++; + case OPEN_PARENTHESIS -> enhancedLevel++; case CLOSE_PARENTHESIS -> enhancedLevel--; } } @@ -113,18 +117,22 @@ private void handleGeneric(Token token) { result.append(token.content()); - if (type == TokenType.COMMA || type == TokenType.WILDCARD || type == TokenType.EXTENDS || type == TokenType.SUPER) { + if (type == TokenType.COMMA || type == TokenType.WILDCARD || type == TokenType.EXTENDS + || type == TokenType.SUPER) { result.append(' '); } - //------------------------------------------------ + // ------------------------------------------------ switch (type) { case SMALLER -> genericDepth++; - case BIGGER -> genericDepth--; + case BIGGER -> genericDepth--; } - if (genericDepth == 0 && !queue.isEmpty() && queue.peek().type() != TokenType.OPEN_PARENTHESIS) { // last closing except if there's an opening parenthesis after it + if (genericDepth == 0 && !queue.isEmpty() + && queue.peek().type() != TokenType.OPEN_PARENTHESIS) { // last closing except if + // there's an opening + // parenthesis after it result.append(' '); } } @@ -148,7 +156,7 @@ private boolean checkGeneric(TokenType type) { switch (nextType) { case SMALLER -> depth++; - case BIGGER -> depth--; + case BIGGER -> depth--; } } @@ -161,11 +169,15 @@ private boolean checkGeneric(TokenType type) { } private boolean isValidGeneric(TokenType type) { - return type == TokenType.WILDCARD || type == TokenType.SMALLER || type == TokenType.BIGGER || type == TokenType.COMMA || type == TokenType.DOT || type == TokenType.EXTENDS || type == TokenType.SUPER || type == TokenType.IDENTIFIER; + return type == TokenType.WILDCARD || type == TokenType.SMALLER || type == TokenType.BIGGER + || type == TokenType.COMMA || type == TokenType.DOT || type == TokenType.EXTENDS + || type == TokenType.SUPER || type == TokenType.IDENTIFIER; } private boolean shouldPutNewLineAfter(TokenType type) { - return type == TokenType.OPEN_BRACES || type == TokenType.SEMICOLON || type == TokenType.CLOSE_BRACES || type == TokenType.COMMENT || type == TokenType.ANNOTATION; + return type == TokenType.OPEN_BRACES || type == TokenType.SEMICOLON + || type == TokenType.CLOSE_BRACES || type == TokenType.COMMENT + || type == TokenType.ANNOTATION; } private boolean isIndexedForLoop(TokenType type) { @@ -185,7 +197,8 @@ private boolean internalEnhancedFor() { } /** - * Parenthesis rule: append a space after a closing parenthesis if the next token isn't another closing parenthesis, an operator or a semicolon + * Parenthesis rule: append a space after a closing parenthesis if the next token isn't another + * closing parenthesis, an operator or a semicolon */ private boolean isParenthesisRule(Token token) { if (queue.isEmpty()) { @@ -195,7 +208,9 @@ private boolean isParenthesisRule(Token token) { Token next = queue.peek(); TokenType nextType = next.type(); - return token.type() == TokenType.CLOSE_PARENTHESIS && nextType != TokenType.CLOSE_PARENTHESIS && nextType != TokenType.SEMICOLON && !isOperator(next); + return token.type() == TokenType.CLOSE_PARENTHESIS + && nextType != TokenType.CLOSE_PARENTHESIS && nextType != TokenType.SEMICOLON + && !isOperator(next); } /** @@ -223,7 +238,7 @@ private boolean isOperator(Token token) { private void updateIndentation(TokenType type) { switch (type) { - case OPEN_BRACES -> indentation++; + case OPEN_BRACES -> indentation++; case CLOSE_BRACES -> indentation--; } } diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index 74edd235c8..ddaab627ae 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -29,8 +29,8 @@ public String format(List tokens) { for (Section section : sections) { if (section.isCodeSection()) { result.append("```java\n") - .append(writeCodeSection(section.tokens())) - .append("\n```"); + .append(writeCodeSection(section.tokens())) + .append("\n```"); } else { result.append(joinTokens(section.tokens())); } @@ -63,7 +63,8 @@ private String joinTokens(List tokens) { } /** - * Writes and formats a given code section (in form of a list of tokens) into a StringBuilder using a {@link CodeSectionFormatter} + * Writes and formats a given code section (in form of a list of tokens) into a StringBuilder + * using a {@link CodeSectionFormatter} * * @param tokens tokens to write * @return written code sections @@ -86,8 +87,8 @@ private StringBuilder writeCodeSection(List tokens) { */ private List indexTokens(List tokens) { return tokens.stream() - .map(token -> new CheckedToken(token, isTokenPartOfCode(token))) - .toList(); + .map(token -> new CheckedToken(token, isTokenPartOfCode(token))) + .toList(); } /** @@ -102,7 +103,8 @@ private boolean isTokenPartOfCode(Token token) { } /** - * Sectionizes a given list of tokens into sections who are code sections and sections who are not + * Sectionizes a given list of tokens into sections who are code sections and sections who are + * not * * @param checkedTokens indexed tokens * @return list of sections diff --git a/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java index 59871ca8f1..1e4ab47d8a 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java +++ b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java @@ -5,7 +5,8 @@ import java.util.List; import java.util.function.Predicate; -public class SkippableLookaheadArrayDeque extends LookaheadArrayDeque implements SkippableLookaheadQueue { +public class SkippableLookaheadArrayDeque extends LookaheadArrayDeque + implements SkippableLookaheadQueue { public SkippableLookaheadArrayDeque() { super(); } diff --git a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java index f19ed55a24..25bd7cdb93 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java @@ -27,7 +27,9 @@ void formatTest1() { public static void main(String[] args) { System.out.println("Hello World!"); } - ```""", formatter.format("public static\nvoid main ( String [ ]args){ System.out. println( \"Hello World!\" );}", lexer)); + ```""", formatter.format( + "public static\nvoid main ( String [ ]args){ System.out. println( \"Hello World!\" );}", + lexer)); } @Test @@ -41,7 +43,9 @@ void formatTest2() { result.add(s.trim()); } return result; - ```""", formatter.format("Listinput=new ArrayList<>();List result=new ArrayList<>();for(String s:input){result.add(s.trim());}return result;", lexer)); + ```""", formatter.format( + "Listinput=new ArrayList<>();List result=new ArrayList<>();for(String s:input){result.add(s.trim());}return result;", + lexer)); } @Test diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java index 8da4cfefb0..89916060e7 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -41,9 +41,9 @@ void testEmptyInput() { @DisplayName("All tokens get tokenized correctly") void testInput() { String testString = - "class enum record interface import if for while null extends implements new return package this yield catch try else if else public private protected static sealed non-sealed final abstract void int long short byte boolean float double char ( ) { } [ ] ; :: : , += -= *= /= %= &= |= == != >= > <= < ! = ++ + -- - && || /* a */ / * . @annotation 0 \"string\" identifier ` "; + "class enum record interface import if for while null extends implements new return package this yield catch try else if else public private protected static sealed non-sealed final abstract void int long short byte boolean float double char ( ) { } [ ] ; :: : , += -= *= /= %= &= |= == != >= > <= < ! = ++ + -- - && || /* a */ / * . @annotation 0 \"string\" identifier ` "; List tokens = lexer.tokenize(testString).stream().map(Token::type).toList(), - expected = new ArrayList<>(); + expected = new ArrayList<>(); for (TokenType type : TokenType.values()) { if (type != TokenType.WHITESPACE) { From cb5e09eed28a8bf30c40dbd92dddf5778a10ba3d Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 17:40:11 +0200 Subject: [PATCH 47/62] Fix javadoc --- .../src/main/java/org/togetherjava/formatter/Formatter.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index ddaab627ae..a9c6644e15 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -103,10 +103,9 @@ private boolean isTokenPartOfCode(Token token) { } /** - * Sectionizes a given list of tokens into sections who are code sections and sections who are - * not + * Sectionizes a given list of tokens * - * @param checkedTokens indexed tokens + * @param checkedTokens checked tokens * @return list of sections * @author illuminator3 */ From 571e740844913f95cd1fc55671002ae7d59d8792 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 17:48:16 +0200 Subject: [PATCH 48/62] Fix lambdas --- .../org/togetherjava/formatter/CodeSectionFormatter.java | 9 +++++++-- .../org/togetherjava/formatter/tokenizer/TokenType.java | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 889ad69112..47e2af016b 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -176,8 +176,13 @@ private boolean isValidGeneric(TokenType type) { private boolean shouldPutNewLineAfter(TokenType type) { return type == TokenType.OPEN_BRACES || type == TokenType.SEMICOLON - || type == TokenType.CLOSE_BRACES || type == TokenType.COMMENT - || type == TokenType.ANNOTATION; + || type == TokenType.COMMENT || type == TokenType.ANNOTATION + || (type == TokenType.CLOSE_BRACES && !queue.isEmpty() + && queue.peek().type() != TokenType.SEMICOLON); // don't put new lines after + // braces if they're part + // of a lambda: + // () -> { + // }; } private boolean isIndexedForLoop(TokenType type) { diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index 9975fc4d79..dced4bf5e2 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -60,6 +60,9 @@ public enum TokenType { METHOD_REFERENCE("::"), COLON(":", false, true), // technically not a "real" operator but used in an enhanced for loop COMMA(","), + ARROW("->", false, true), // used in lambdas + // I also wouldn't count this as an operator but again, it's required + // for formatting PLUS_EQUALS("+=", false, true), MINUS_EQUALS("-=", false, true), MULTIPLY_EQUALS("*=", false, true), From 2da98b6155dbc7684f3630fed408fc552d06c9e0 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 18:02:00 +0200 Subject: [PATCH 49/62] Fix multiarg method declarations --- .../formatter/CodeSectionFormatter.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 47e2af016b..ac64f12fa9 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -70,9 +70,7 @@ private void put(Token token) { result.append(token.content()); - if (isKeyword(token) || isOperator(token) || isParenthesisRule(token) - || type == TokenType.CLOSE_BRACKETS) { // put a space after e.g. 'try' or 'else' and - // ] or if it's an operator + if (shouldPutSpaceAfter(token)) { result.append(' '); } else if (shouldPutNewLineAfter(type)) { // put a new line after { and ; and } and comments // and annotations @@ -84,11 +82,19 @@ private void put(Token token) { applyIndentation = true; } + } - if (type == TokenType.IDENTIFIER && enhancedLevel != -1 && !queue.isEmpty() - && queue.peek().type() == TokenType.IDENTIFIER) { - result.append(' '); - } + private boolean shouldPutSpaceAfter(Token token) { + TokenType type = token.type(); + + return isKeyword(token) || isOperator(token) || isParenthesisRule(token) + || type == TokenType.CLOSE_BRACKETS // put a space after e.g. 'try' or 'else' and + // ] or if it's an operator + || type == TokenType.COMMA // for e.g. multiarg method calls or method parameters + || (type == TokenType.IDENTIFIER + && !queue.isEmpty() + && queue.peek().type() == TokenType.IDENTIFIER); // for double identifier + // in e.g. method declaration or enhanced for loops } private void updateEnhancedLevel(TokenType type) { From 43de148b29a7e760357549be4b06d8017d03f100 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 18:02:12 +0200 Subject: [PATCH 50/62] Add more test cases --- .../togetherjava/formatter/FormatterTest.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java index 25bd7cdb93..cf296ad2de 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java @@ -85,6 +85,25 @@ else if (2) { ```""", formatter.format("if(1){}else if(2){}else{}", lexer)); } + @Test + @DisplayName("Multiargument method invocation renders correctly") + void testMultiargMethodInvoc() { + assertEquals(""" + ```java + foo(1, 2, 3, b); + ```""", formatter.format("foo(1,2,3,b);", lexer)); + } + + @Test + @DisplayName("Method declaration renders correctly") + void testMethodDeclaration() { + assertEquals(""" + ```java + void foo(int a, int b, Object c) { + } + ```""", formatter.format("void foo(int a, int b, Object c){}", lexer)); + } + @Test @DisplayName("For int loop working correctly") void testForInt() { @@ -134,4 +153,48 @@ void foo() { } ```""", formatter.format("@MyAnnotation\nvoid foo() {}", lexer)); } + + @Test + @DisplayName("Lambda renders correctly") + void testLambda() { + assertEquals(""" + ```java + () -> { + System.out.println("Hello World"); + }; + ```""", formatter.format("()->{System.out.println(\"Hello World\");};", lexer)); + } + + @Test + @DisplayName("Lambda with parameters renders correctly") + void testLambdaParams() { + assertEquals(""" + ```java + (s, e, d) -> { + System.out.println("Hello World"); + }; + ```""", formatter.format("(s,e,d)->{System.out.println(\"Hello World\");};", lexer)); + } + + @Test + @DisplayName("Lambda with parenthesis parameter renders correctly") + void testLambdaNoParenParams() { + assertEquals(""" + ```java + s -> { + System.out.println("Hello World"); + }; + ```""", formatter.format("s->{System.out.println(\"Hello World\");};", lexer)); + } + + @Test + @DisplayName("Lambda with typed parameters renders correctly") + void testLambdaTypeParams() { + assertEquals(""" + ```java + (String s, Object b) -> { + System.out.println("Hello World"); + }; + ```""", formatter.format("(String s,Object b)->{System.out.println(\"Hello World\");};", lexer)); + } } From 2b8dd55b672b63ae0252eb59545f0fe65bdba1ad Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 18:17:20 +0200 Subject: [PATCH 51/62] Apply spotless --- .../org/togetherjava/formatter/CodeSectionFormatter.java | 9 +++++---- .../java/org/togetherjava/formatter/FormatterTest.java | 6 ++++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index ac64f12fa9..b5d1a9bb74 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -91,10 +91,11 @@ private boolean shouldPutSpaceAfter(Token token) { || type == TokenType.CLOSE_BRACKETS // put a space after e.g. 'try' or 'else' and // ] or if it's an operator || type == TokenType.COMMA // for e.g. multiarg method calls or method parameters - || (type == TokenType.IDENTIFIER - && !queue.isEmpty() - && queue.peek().type() == TokenType.IDENTIFIER); // for double identifier - // in e.g. method declaration or enhanced for loops + || (type == TokenType.IDENTIFIER && !queue.isEmpty() + && queue.peek().type() == TokenType.IDENTIFIER); // for double identifier + // in e.g. method + // declaration or enhanced + // for loops } private void updateEnhancedLevel(TokenType type) { diff --git a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java index cf296ad2de..0fbbeee2e1 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java @@ -173,7 +173,8 @@ void testLambdaParams() { (s, e, d) -> { System.out.println("Hello World"); }; - ```""", formatter.format("(s,e,d)->{System.out.println(\"Hello World\");};", lexer)); + ```""", + formatter.format("(s,e,d)->{System.out.println(\"Hello World\");};", lexer)); } @Test @@ -195,6 +196,7 @@ void testLambdaTypeParams() { (String s, Object b) -> { System.out.println("Hello World"); }; - ```""", formatter.format("(String s,Object b)->{System.out.println(\"Hello World\");};", lexer)); + ```""", formatter.format( + "(String s,Object b)->{System.out.println(\"Hello World\");};", lexer)); } } From f56e2e0e864642a5bfd148e1acad1d18d4f5a163 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 18:46:07 +0200 Subject: [PATCH 52/62] Add javadoc --- .../formatter/CodeSectionFormatter.java | 123 ++++++++++++++++++ .../org/togetherjava/formatter/Formatter.java | 1 - .../togetherjava/formatter/FormatterTest.java | 3 + .../formatter/tokenizer/LexerTest.java | 3 + 4 files changed, 129 insertions(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index b5d1a9bb74..489b011334 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -6,7 +6,13 @@ import org.togetherjava.formatter.util.SkippableLookaheadQueue; import java.util.*; +import java.util.function.Predicate; +/** + * Formatter which specifically formats code tokens (that are part of a section) + * + * @author illuminator3 + */ class CodeSectionFormatter { private final StringBuilder result = new StringBuilder(); private final SkippableLookaheadQueue queue; @@ -27,10 +33,21 @@ class CodeSectionFormatter { purgeWhitespaces(this.queue); } + /** + * Removes all whitespaces from the given queue + * + * @param queue the queue to remove whitespaces from + * @author illuminator3 + */ private static void purgeWhitespaces(Queue queue) { queue.removeIf(t -> t.type() == TokenType.WHITESPACE); } + /** + * Starts the formatting process + * + * @author illuminator3 + */ void format() { Token next; @@ -41,6 +58,12 @@ void format() { } } + /** + * Consumes the next token + * + * @param token token to consume + * @author illuminator3 + */ private void consume(Token token) { TokenType type = token.type(); @@ -61,6 +84,12 @@ private void consume(Token token) { put(token); } + /** + * Puts the next token into the result + * + * @param token token to put + * @author illuminator3 + */ private void put(Token token) { TokenType type = token.type(); @@ -84,6 +113,13 @@ private void put(Token token) { } } + /** + * Checks if a space should be put after a given token + * + * @param token token to check + * @return wether a space should be put after that token + * @author illuminator3 + */ private boolean shouldPutSpaceAfter(Token token) { TokenType type = token.type(); @@ -98,6 +134,12 @@ private boolean shouldPutSpaceAfter(Token token) { // for loops } + /** + * Updates the enhanced for loop level + * + * @param type current token type + * @author illuminator3 + */ private void updateEnhancedLevel(TokenType type) { if (enhancedLevel != -1) { switch (type) { @@ -107,6 +149,12 @@ private void updateEnhancedLevel(TokenType type) { } } + /** + * Checks if a given token type belongs to a for loop (uses {@link SkippableLookaheadQueue#peek(int, Predicate)} + * + * @param type current token type + * @author illuminator3 + */ private void checkFor(TokenType type) { if (isIndexedForLoop(type)) { // if it's a for int loop then set the forLevel to 2 forLevel = 2; @@ -115,6 +163,12 @@ private void checkFor(TokenType type) { } } + /** + * Handles the case of being inside a generic type declaration + * + * @param token current token + * @author illuminator3 + */ private void handleGeneric(Token token) { TokenType type = token.type(); @@ -144,6 +198,13 @@ private void handleGeneric(Token token) { } } + /** + * Checks if a given token type belongs to a generic type declaration (uses {@link org.togetherjava.formatter.util.LookaheadQueue#peek(int)} + * + * @param type current token type + * @return wether the token type belongs to a generic type declaration + * @author illuminator3 + */ private boolean checkGeneric(TokenType type) { if (type == TokenType.SMALLER) { int depth = 1; @@ -175,12 +236,26 @@ private boolean checkGeneric(TokenType type) { return false; } + /** + * Checks if a given token type would be valid inside a generic type declaration + * + * @param type token type to check + * @return wether it's valid inside a generic type declaration + * @author illuminator3 + */ private boolean isValidGeneric(TokenType type) { return type == TokenType.WILDCARD || type == TokenType.SMALLER || type == TokenType.BIGGER || type == TokenType.COMMA || type == TokenType.DOT || type == TokenType.EXTENDS || type == TokenType.SUPER || type == TokenType.IDENTIFIER; } + /** + * Checks if a new line should be put after a given token type + * + * @param type token type to check + * @return wether a new line should be put after that token + * @author illuminator3 + */ private boolean shouldPutNewLineAfter(TokenType type) { return type == TokenType.OPEN_BRACES || type == TokenType.SEMICOLON || type == TokenType.COMMENT || type == TokenType.ANNOTATION @@ -192,14 +267,34 @@ private boolean shouldPutNewLineAfter(TokenType type) { // }; } + /** + * Checks if there's an indexed for loop ahead (uses {@link SkippableLookaheadQueue#peek(int, Predicate)}) + * + * @param type current token type + * @return wether there's an indexed for loop or not + * @author illuminator3 + */ private boolean isIndexedForLoop(TokenType type) { return type == TokenType.FOR && !internalEnhancedFor(); } + /** + * Checks if there's an enhanced for loop ahead (uses {@link SkippableLookaheadQueue#peek(int, Predicate)}) + * + * @param type current token type + * @return wether there's an enhanced for loop or not + * @author illuminator3 + */ private boolean isEnhancedForLoop(TokenType type) { return type == TokenType.FOR && internalEnhancedFor(); } + /** + * Checks if there's an enhanced for loop ahead without checking the current token type + * + * @return wether there's an enhanced for loop ahead + * @author illuminator3 + */ private boolean internalEnhancedFor() { return queue.peek(3, t -> { TokenType ttype = t.type(); @@ -211,6 +306,9 @@ private boolean internalEnhancedFor() { /** * Parenthesis rule: append a space after a closing parenthesis if the next token isn't another * closing parenthesis, an operator or a semicolon + * + * @return wether a space should be put after the parenthesis + * @author illuminator3 */ private boolean isParenthesisRule(Token token) { if (queue.isEmpty()) { @@ -240,14 +338,34 @@ private void appendNewLine() { } } + /** + * Checks if a given token is a keyword using {@link TokenType#isKeyword()} + * + * @param token token to check + * @return wether the given token is a keyword + * @author illuminator3 + */ private boolean isKeyword(Token token) { return token.type().isKeyword(); } + /** + * Checks if a given token is an operator using {@link TokenType#isOperator()} + * + * @param token token to check + * @return wether the given token is an operator + * @author illuminator3 + */ private boolean isOperator(Token token) { return token.type().isOperator(); } + /** + * Updates the indentation based on the current token type + * + * @param type current token type + * @author illuminator3 + */ private void updateIndentation(TokenType type) { switch (type) { case OPEN_BRACES -> indentation++; @@ -255,6 +373,11 @@ private void updateIndentation(TokenType type) { } } + /** + * Applies the current indentation + * + * @author illuminator3 + */ private void applyIndentation() { if (applyIndentation) { result.append(" ".repeat(Math.max(0, indentation))); diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index a9c6644e15..16bbdd62d8 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Set; import java.util.stream.Collectors; /** diff --git a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java index 0fbbeee2e1..61f4d6a558 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java @@ -8,6 +8,9 @@ import org.junit.jupiter.api.TestInstance; import org.togetherjava.formatter.tokenizer.Lexer; +/** + * @author illuminator3 + */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class FormatterTest { Lexer lexer; diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java index 89916060e7..d8060b5f04 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -10,6 +10,9 @@ import java.util.ArrayList; import java.util.List; +/** + * @author illuminator3 + */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LexerTest { Lexer lexer; From 51e36c3080d54e6bac2df959652ac5c51f5f912a Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 18:59:31 +0200 Subject: [PATCH 53/62] Fix test --- .../java/org/togetherjava/formatter/tokenizer/LexerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java index d8060b5f04..d525caef24 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -44,7 +44,7 @@ void testEmptyInput() { @DisplayName("All tokens get tokenized correctly") void testInput() { String testString = - "class enum record interface import if for while null extends implements new return package this yield catch try else if else public private protected static sealed non-sealed final abstract void int long short byte boolean float double char ( ) { } [ ] ; :: : , += -= *= /= %= &= |= == != >= > <= < ! = ++ + -- - && || /* a */ / * . @annotation 0 \"string\" identifier ` "; + "class enum record interface import if for while null extends implements new return package this yield catch try else if else super public private protected static sealed non-sealed final abstract void int long short byte boolean float double char ( ) { } [ ] ; :: : , -> += -= *= /= %= &= |= == != >= > <= < ! = ++ + -- - && || /* a */ / * . ? @annotation 0 \"string\" identifier ` "; List tokens = lexer.tokenize(testString).stream().map(Token::type).toList(), expected = new ArrayList<>(); From e5af805c971d81800624119bda75771ac148cacc Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 19:02:06 +0200 Subject: [PATCH 54/62] Apply spotless --- .../togetherjava/formatter/CodeSectionFormatter.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 489b011334..8bb241ab15 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -150,7 +150,8 @@ private void updateEnhancedLevel(TokenType type) { } /** - * Checks if a given token type belongs to a for loop (uses {@link SkippableLookaheadQueue#peek(int, Predicate)} + * Checks if a given token type belongs to a for loop (uses + * {@link SkippableLookaheadQueue#peek(int, Predicate)} * * @param type current token type * @author illuminator3 @@ -199,7 +200,8 @@ private void handleGeneric(Token token) { } /** - * Checks if a given token type belongs to a generic type declaration (uses {@link org.togetherjava.formatter.util.LookaheadQueue#peek(int)} + * Checks if a given token type belongs to a generic type declaration (uses + * {@link org.togetherjava.formatter.util.LookaheadQueue#peek(int)} * * @param type current token type * @return wether the token type belongs to a generic type declaration @@ -268,7 +270,8 @@ private boolean shouldPutNewLineAfter(TokenType type) { } /** - * Checks if there's an indexed for loop ahead (uses {@link SkippableLookaheadQueue#peek(int, Predicate)}) + * Checks if there's an indexed for loop ahead (uses + * {@link SkippableLookaheadQueue#peek(int, Predicate)}) * * @param type current token type * @return wether there's an indexed for loop or not @@ -279,7 +282,8 @@ private boolean isIndexedForLoop(TokenType type) { } /** - * Checks if there's an enhanced for loop ahead (uses {@link SkippableLookaheadQueue#peek(int, Predicate)}) + * Checks if there's an enhanced for loop ahead (uses + * {@link SkippableLookaheadQueue#peek(int, Predicate)}) * * @param type current token type * @return wether there's an enhanced for loop or not From 84728a67114a608f12f27ee882b83ef63f6cce61 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 19:05:56 +0200 Subject: [PATCH 55/62] Change formatting config --- meta/formatting/google-style-eclipse.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/meta/formatting/google-style-eclipse.xml b/meta/formatting/google-style-eclipse.xml index 2764c4c931..c3fb303c9d 100644 --- a/meta/formatting/google-style-eclipse.xml +++ b/meta/formatting/google-style-eclipse.xml @@ -76,7 +76,7 @@ - + @@ -89,7 +89,7 @@ - + @@ -333,4 +333,4 @@ - + \ No newline at end of file From b98da4d1483d5b3b6fef48c58f9142dc2050e0c6 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Mon, 13 Sep 2021 19:06:21 +0200 Subject: [PATCH 56/62] Apply spotless --- .../main/java/org/togetherjava/formatter/Formatter.java | 8 ++++---- .../java/org/togetherjava/formatter/FormatterTest.java | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index 16bbdd62d8..b8e42a1735 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -28,8 +28,8 @@ public String format(List tokens) { for (Section section : sections) { if (section.isCodeSection()) { result.append("```java\n") - .append(writeCodeSection(section.tokens())) - .append("\n```"); + .append(writeCodeSection(section.tokens())) + .append("\n```"); } else { result.append(joinTokens(section.tokens())); } @@ -86,8 +86,8 @@ private StringBuilder writeCodeSection(List tokens) { */ private List indexTokens(List tokens) { return tokens.stream() - .map(token -> new CheckedToken(token, isTokenPartOfCode(token))) - .toList(); + .map(token -> new CheckedToken(token, isTokenPartOfCode(token))) + .toList(); } /** diff --git a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java index 61f4d6a558..bbb7ab6ad8 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java +++ b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java @@ -199,7 +199,7 @@ void testLambdaTypeParams() { (String s, Object b) -> { System.out.println("Hello World"); }; - ```""", formatter.format( - "(String s,Object b)->{System.out.println(\"Hello World\");};", lexer)); + ```""", formatter + .format("(String s,Object b)->{System.out.println(\"Hello World\");};", lexer)); } } From b3457c393456920ab10284696a78e833f02030d4 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Tue, 14 Sep 2021 18:06:04 +0200 Subject: [PATCH 57/62] Remove useless field --- .../formatter/CodeSectionFormatter.java | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 8bb241ab15..468b5a21e9 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -21,7 +21,6 @@ class CodeSectionFormatter { private boolean applyIndentation; private int forLevel; private int genericDepth; - private int enhancedLevel = -1; CodeSectionFormatter(List tokens) { this(new SkippableLookaheadArrayDeque<>(tokens)); @@ -80,7 +79,6 @@ private void consume(Token token) { } checkFor(type); - updateEnhancedLevel(type); put(token); } @@ -134,21 +132,6 @@ private boolean shouldPutSpaceAfter(Token token) { // for loops } - /** - * Updates the enhanced for loop level - * - * @param type current token type - * @author illuminator3 - */ - private void updateEnhancedLevel(TokenType type) { - if (enhancedLevel != -1) { - switch (type) { - case OPEN_PARENTHESIS -> enhancedLevel++; - case CLOSE_PARENTHESIS -> enhancedLevel--; - } - } - } - /** * Checks if a given token type belongs to a for loop (uses * {@link SkippableLookaheadQueue#peek(int, Predicate)} @@ -159,8 +142,6 @@ private void updateEnhancedLevel(TokenType type) { private void checkFor(TokenType type) { if (isIndexedForLoop(type)) { // if it's a for int loop then set the forLevel to 2 forLevel = 2; - } else if (isEnhancedForLoop(type)) { - enhancedLevel = 0; } } From 45296f0a2d63ba8c54948ecc2de3d76a906a30a5 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Tue, 14 Sep 2021 18:08:16 +0200 Subject: [PATCH 58/62] Rename currSec to currentSection --- .../java/org/togetherjava/formatter/Formatter.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index b8e42a1735..4e7cba73f0 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -110,24 +110,24 @@ private boolean isTokenPartOfCode(Token token) { */ private List
sectionize(List checkedTokens) { CheckedToken first = checkedTokens.get(0); - Section currSec = new Section(new ArrayList<>(), first.isCode()); + Section currentSection = new Section(new ArrayList<>(), first.isCode()); List
result = new ArrayList<>(); - currSec.tokens().add(first.token()); + currentSection.tokens().add(first.token()); for (int i = 1; i < checkedTokens.size(); i++) { CheckedToken next = checkedTokens.get(i); - if (currSec.isCodeSection() != next.isCode()) { - result.add(currSec); + if (currentSection.isCodeSection() != next.isCode()) { + result.add(currentSection); - currSec = new Section(new ArrayList<>(), next.isCode()); + currentSection = new Section(new ArrayList<>(), next.isCode()); } - currSec.tokens().add(next.token()); + currentSection.tokens().add(next.token()); } - result.add(currSec); + result.add(currentSection); return result; } From 5f1529c928ab94206782ac8a0025a3da35251a8c Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Tue, 14 Sep 2021 18:09:38 +0200 Subject: [PATCH 59/62] Better javadoc --- .../src/main/java/org/togetherjava/formatter/Formatter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index 4e7cba73f0..b7c000843e 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -102,7 +102,7 @@ private boolean isTokenPartOfCode(Token token) { } /** - * Sectionizes a given list of tokens + * Sectionizes a given list of tokens into sections who are either code sections or non-code sections. It decides so by using the internal {@code isTokenPartOfCode} method. * * @param checkedTokens checked tokens * @return list of sections From 2bf3f5c19d4b38639324947f3342b14aacceca2f Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Tue, 14 Sep 2021 18:11:57 +0200 Subject: [PATCH 60/62] Change token names --- .../togetherjava/formatter/CodeSectionFormatter.java | 12 ++++++------ .../togetherjava/formatter/tokenizer/TokenType.java | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 468b5a21e9..b9bc516ff2 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -168,8 +168,8 @@ private void handleGeneric(Token token) { // ------------------------------------------------ switch (type) { - case SMALLER -> genericDepth++; - case BIGGER -> genericDepth--; + case LESS_THAN -> genericDepth++; + case GREATER_THAN -> genericDepth--; } if (genericDepth == 0 && !queue.isEmpty() @@ -189,7 +189,7 @@ private void handleGeneric(Token token) { * @author illuminator3 */ private boolean checkGeneric(TokenType type) { - if (type == TokenType.SMALLER) { + if (type == TokenType.LESS_THAN) { int depth = 1; for (int i = 0;; i++) { @@ -206,8 +206,8 @@ private boolean checkGeneric(TokenType type) { } switch (nextType) { - case SMALLER -> depth++; - case BIGGER -> depth--; + case LESS_THAN -> depth++; + case GREATER_THAN -> depth--; } } @@ -227,7 +227,7 @@ private boolean checkGeneric(TokenType type) { * @author illuminator3 */ private boolean isValidGeneric(TokenType type) { - return type == TokenType.WILDCARD || type == TokenType.SMALLER || type == TokenType.BIGGER + return type == TokenType.WILDCARD || type == TokenType.LESS_THAN || type == TokenType.GREATER_THAN || type == TokenType.COMMA || type == TokenType.DOT || type == TokenType.EXTENDS || type == TokenType.SUPER || type == TokenType.IDENTIFIER; } diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java index dced4bf5e2..bdf49e28c3 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -72,10 +72,10 @@ public enum TokenType { OR_EQUALS("|=", false, true), EQUALS("==", false, true), NOT_EQUALS("!=", false, true), - BIGGER_OR_EQUALS(">=", false, true), - BIGGER(">", false, true), - SMALLER_OR_EQUALS("<=", false, true), - SMALLER("<", false, true), + GREATER_THAN_OR_EQUALS(">=", false, true), + GREATER_THAN(">", false, true), + LESS_THAN_OR_EQUALS("<=", false, true), + LESS_THAN("<", false, true), NOT("!"), ASSIGN("=", false, true), PLUSPLUS("++"), From 63754408d2690e72298d95a539cd4817cbcd1a34 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Tue, 14 Sep 2021 19:52:29 +0200 Subject: [PATCH 61/62] Change switch to if-elseif to satisfy sonar --- .../formatter/CodeSectionFormatter.java | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index b9bc516ff2..1003a0e130 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -167,9 +167,10 @@ private void handleGeneric(Token token) { // ------------------------------------------------ - switch (type) { - case LESS_THAN -> genericDepth++; - case GREATER_THAN -> genericDepth--; + if (type == TokenType.LESS_THAN) { + genericDepth++; + } else if (type == TokenType.GREATER_THAN) { + genericDepth--; } if (genericDepth == 0 && !queue.isEmpty() @@ -205,9 +206,10 @@ private boolean checkGeneric(TokenType type) { return false; } - switch (nextType) { - case LESS_THAN -> depth++; - case GREATER_THAN -> depth--; + if (nextType == TokenType.LESS_THAN) { + depth++; + } else if (nextType == TokenType.GREATER_THAN) { + depth--; } } @@ -352,9 +354,10 @@ private boolean isOperator(Token token) { * @author illuminator3 */ private void updateIndentation(TokenType type) { - switch (type) { - case OPEN_BRACES -> indentation++; - case CLOSE_BRACES -> indentation--; + if (type == TokenType.OPEN_BRACES) { + indentation++; + } else if (type == TokenType.CLOSE_BRACES) { + indentation--; } } From 905a68abf2fb4b2b69d3629329ab15a83e2027c7 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Tue, 14 Sep 2021 19:53:31 +0200 Subject: [PATCH 62/62] Apply spotless --- .../org/togetherjava/formatter/CodeSectionFormatter.java | 7 ++++--- .../main/java/org/togetherjava/formatter/Formatter.java | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java index 1003a0e130..ad3c321498 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -229,9 +229,10 @@ private boolean checkGeneric(TokenType type) { * @author illuminator3 */ private boolean isValidGeneric(TokenType type) { - return type == TokenType.WILDCARD || type == TokenType.LESS_THAN || type == TokenType.GREATER_THAN - || type == TokenType.COMMA || type == TokenType.DOT || type == TokenType.EXTENDS - || type == TokenType.SUPER || type == TokenType.IDENTIFIER; + return type == TokenType.WILDCARD || type == TokenType.LESS_THAN + || type == TokenType.GREATER_THAN || type == TokenType.COMMA + || type == TokenType.DOT || type == TokenType.EXTENDS || type == TokenType.SUPER + || type == TokenType.IDENTIFIER; } /** diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java index b7c000843e..4085b88dc8 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -102,7 +102,8 @@ private boolean isTokenPartOfCode(Token token) { } /** - * Sectionizes a given list of tokens into sections who are either code sections or non-code sections. It decides so by using the internal {@code isTokenPartOfCode} method. + * Sectionizes a given list of tokens into sections who are either code sections or non-code + * sections. It decides so by using the internal {@code isTokenPartOfCode} method. * * @param checkedTokens checked tokens * @return list of sections