diff --git a/formatter/build.gradle b/formatter/build.gradle new file mode 100644 index 0000000000..c5503d267e --- /dev/null +++ b/formatter/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' +} + +group 'org.togetherjava' +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/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java new file mode 100644 index 0000000000..ad3c321498 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java @@ -0,0 +1,381 @@ +package org.togetherjava.formatter; + +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.*; +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; + + private int indentation; + private boolean applyIndentation; + private int forLevel; + private int genericDepth; + + CodeSectionFormatter(List tokens) { + this(new SkippableLookaheadArrayDeque<>(tokens)); + } + + CodeSectionFormatter(SkippableLookaheadQueue queue) { + this.queue = queue; + + 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; + + while (!queue.isEmpty() && (next = queue.remove()) != null) { + updateIndentation(next.type()); + applyIndentation(); + consume(next); + } + } + + /** + * Consumes the next token + * + * @param token token to consume + * @author illuminator3 + */ + private void consume(Token token) { + TokenType type = token.type(); + + if (checkGeneric(type)) { + result.append(token.content()); + + return; + } + + if (genericDepth != 0) { + handleGeneric(token); + + return; + } + + checkFor(type); + 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(); + + if (isOperator(token)) { // apply space before an operator (like +, - and *) + result.append(' '); + } + + result.append(token.content()); + + if (shouldPutSpaceAfter(token)) { + 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; + } + } + + /** + * 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(); + + 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 + } + + /** + * 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; + } + } + + /** + * 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(); + + 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(' '); + } + + // ------------------------------------------------ + + if (type == TokenType.LESS_THAN) { + genericDepth++; + } else if (type == TokenType.GREATER_THAN) { + 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(' '); + } + } + + /** + * 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.LESS_THAN) { + 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; + } + + if (nextType == TokenType.LESS_THAN) { + depth++; + } else if (nextType == TokenType.GREATER_THAN) { + depth--; + } + } + + genericDepth = 1; + + return true; + } + + 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.LESS_THAN + || type == TokenType.GREATER_THAN || 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 + || (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: + // () -> { + // }; + } + + /** + * 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(); + + 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 + * + * @return wether a space should be put after the parenthesis + * @author illuminator3 + */ + 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 + } + } + } + + /** + * 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) { + if (type == TokenType.OPEN_BRACES) { + indentation++; + } else if (type == TokenType.CLOSE_BRACES) { + indentation--; + } + } + + /** + * Applies the current indentation + * + * @author illuminator3 + */ + 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 new file mode 100644 index 0000000000..4085b88dc8 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/Formatter.java @@ -0,0 +1,151 @@ +package org.togetherjava.formatter; + +import org.togetherjava.formatter.tokenizer.Lexer; +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; + +/** + * 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(); + + for (Section section : sections) { + if (section.isCodeSection()) { + result.append("```java\n") + .append(writeCodeSection(section.tokens())) + .append("\n```"); + } else { + result.append(joinTokens(section.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)); + } + + /** + * Joins given tokens together and normalizes whitespaces + * + * @param tokens tokens to join + * @return joined form of the tokens + * @author illuminator3 + */ + private String joinTokens(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 + * using a {@link CodeSectionFormatter} + * + * @param tokens tokens to write + * @return written code sections + * @author illuminator3 + */ + private StringBuilder writeCodeSection(List tokens) { + CodeSectionFormatter formatter = new CodeSectionFormatter(tokens); + + formatter.format(); + + return formatter.result(); + } + + /** + * 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) { + return tokens.stream() + .map(token -> new CheckedToken(token, isTokenPartOfCode(token))) + .toList(); + } + + /** + * 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 isTokenPartOfCode(Token token) { + return token.type() != TokenType.UNKNOWN; + } + + /** + * 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 + * @author illuminator3 + */ + private List
sectionize(List checkedTokens) { + CheckedToken first = checkedTokens.get(0); + Section currentSection = new Section(new ArrayList<>(), first.isCode()); + List
result = new ArrayList<>(); + + currentSection.tokens().add(first.token()); + + for (int i = 1; i < checkedTokens.size(); i++) { + CheckedToken next = checkedTokens.get(i); + + if (currentSection.isCodeSection() != next.isCode()) { + result.add(currentSection); + + currentSection = new Section(new ArrayList<>(), next.isCode()); + } + + currentSection.tokens().add(next.token()); + } + + result.add(currentSection); + + return result; + } + + /** + * Section POJR + * + * @author illuminator3 + */ + private static record Section(List tokens, boolean isCodeSection) { + } + + /** + * CheckedToken POJR + * + * @author illuminator3 + */ + private static record CheckedToken(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 new file mode 100644 index 0000000000..b066924481 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java @@ -0,0 +1,96 @@ +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.regex.Pattern; + +/** + * Tokenizer that can turn a list of strings (or a string) into a list of tokens + * + * @author illuminator3 + */ +public class Lexer { + /** + * Regex to match multi-line Java comments (including Javadoc) + */ + 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).flatMap(List::stream).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; + String content; + + while (!(content = line.substring(index)).isEmpty()) { + Token token = findToken(content); + + index += token.content().length(); + + tokens.add(token); + } + + return tokens; + } + + private Token findToken(String content) { + for (TokenType type : TokenType.values()) { + Matcher matcher = type.getRegex().matcher(content); + + if (matcher.find()) { + return new Token(matcher.group(1), type); + } + } + + throw new TokenizationException("Token not found for '" + content + "'"); + } + + /** + * 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()) { + String s = matcher.group(); + + input = input.replace(s, s.replace("\n", " ")); + } + + return input; + } +} diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java new file mode 100644 index 0000000000..e924af3985 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java @@ -0,0 +1,32 @@ +package org.togetherjava.formatter.tokenizer; + +import java.util.Set; + +/** + * Class representing a Token with a given content and a type + * + * @author illuminator3 + */ +public record Token(String content, TokenType type) { + private static final Set displayTypes = + Set.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING, TokenType.COMMENT); + + @Override + public String toString() { + return type().name() + formatForDisplay(); + } + + /** + * Returns a non-empty string if this token has something to display + * + * @return the displayed value + * @author illuminator3 + */ + private String formatForDisplay() { + if (displayTypes.contains(type())) { + return "(" + content() + ")"; + } + + return ""; + } +} diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java new file mode 100644 index 0000000000..bdf49e28c3 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java @@ -0,0 +1,138 @@ +package org.togetherjava.formatter.tokenizer; + +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, 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), + SUPER("super", true, false), + // access modifiers + 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, 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(")"), + OPEN_BRACES("{"), + CLOSE_BRACES("}"), + OPEN_BRACKETS("["), + CLOSE_BRACKETS("]"), + SEMICOLON(";"), + 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), + DIVIDE_EQUALS("/=", false, true), + MODULO_EQUALS("%=", false, true), + AND_EQUALS("&=", false, true), + OR_EQUALS("|=", false, true), + EQUALS("==", false, true), + NOT_EQUALS("!=", 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("++"), + PLUS("+", false, true), + MINUSMINUS("--"), + 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("/", false, true), + 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("^(\"[^\"]*\")")), + IDENTIFIER(Pattern.compile("^([a-zA-Z][a-zA-Z0-9_]*)")), + WHITESPACE(Pattern.compile("^(\s+)")), + UNKNOWN(Pattern.compile("^(.)")); + + private final Pattern regex; + private final boolean isKeyword, isOperator; + + TokenType(String pattern, boolean isKeyword, boolean isOperator) { + if (!isKeyword) { + this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")"); + } else { + this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")(?![a-zA-Z])"); + } + + this.isKeyword = isKeyword; + this.isOperator = isOperator; + } + + TokenType(Pattern regex) { + this.regex = regex; + this.isKeyword = false; + this.isOperator = false; + } + + TokenType(String spattern) { + this(spattern, false, false); + } + + public Pattern getRegex() { + return regex; + } + + public boolean isKeyword() { + return isKeyword; + } + + public boolean isOperator() { + return isOperator; + } +} diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java new file mode 100644 index 0000000000..25a822ba97 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java @@ -0,0 +1,12 @@ +package org.togetherjava.formatter.tokenizer; + +/** + * Exception that can occur when lexing + * + * @author illuminator3 + */ +public class TokenizationException extends RuntimeException { + public TokenizationException(String message) { + super(message); + } +} diff --git a/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java new file mode 100644 index 0000000000..f2f362e1c0 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java @@ -0,0 +1,49 @@ +package org.togetherjava.formatter.util; + +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/util/LookaheadQueue.java b/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadQueue.java new file mode 100644 index 0000000000..4ff34ced98 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadQueue.java @@ -0,0 +1,12 @@ +package org.togetherjava.formatter.util; + +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/util/SkippableLookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java new file mode 100644 index 0000000000..1e4ab47d8a --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java @@ -0,0 +1,44 @@ +package org.togetherjava.formatter.util; + +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/util/SkippableLookaheadQueue.java b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadQueue.java new file mode 100644 index 0000000000..ba4ed37361 --- /dev/null +++ b/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadQueue.java @@ -0,0 +1,7 @@ +package org.togetherjava.formatter.util; + +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 new file mode 100644 index 0000000000..bbb7ab6ad8 --- /dev/null +++ b/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java @@ -0,0 +1,205 @@ +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; + +/** + * @author illuminator3 + */ +@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)); + } + + @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() { + 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)); + } + + @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)); + } +} 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..d525caef24 --- /dev/null +++ b/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java @@ -0,0 +1,66 @@ +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; + +/** + * @author illuminator3 + */ +@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("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 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<>(); + + for (TokenType type : TokenType.values()) { + if (type != TokenType.WHITESPACE) { + expected.add(type); + expected.add(TokenType.WHITESPACE); + } + } + + assertEquals(expected, tokens); + } + + @Test + @DisplayName("Identifier doesn't get recognized as keyword") + void testIdentifierKeyword() { + assertEquals(TokenType.IDENTIFIER, lexer.tokenize("format").get(0).type()); + } +} 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 diff --git a/settings.gradle b/settings.gradle index 09c28a6a7f..5003815b8a 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'