diff options
Diffstat (limited to 'core/src/test/java/coffee')
11 files changed, 1104 insertions, 1104 deletions
diff --git a/core/src/test/java/coffee/liz/abstractionengine/app/ui/editor/vim/VimEngineTest.java b/core/src/test/java/coffee/liz/abstractionengine/app/ui/editor/vim/VimEngineTest.java index 31d823a..5248904 100644 --- a/core/src/test/java/coffee/liz/abstractionengine/app/ui/editor/vim/VimEngineTest.java +++ b/core/src/test/java/coffee/liz/abstractionengine/app/ui/editor/vim/VimEngineTest.java @@ -13,566 +13,566 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class VimEngineTest { - private static class FakeBuffer implements EditorBuffer { - private String text; - private int cursor; - private int selectionStart; - private int selectionEnd; - private boolean hasSelection; + private static class FakeBuffer implements EditorBuffer { + private String text; + private int cursor; + private int selectionStart; + private int selectionEnd; + private boolean hasSelection; - private FakeBuffer(final String text, final int cursor) { - this.text = text; - this.cursor = Math.max(0, Math.min(cursor, text.length())); - this.selectionStart = 0; - this.selectionEnd = 0; - this.hasSelection = false; - } + private FakeBuffer(final String text, final int cursor) { + this.text = text; + this.cursor = Math.max(0, Math.min(cursor, text.length())); + this.selectionStart = 0; + this.selectionEnd = 0; + this.hasSelection = false; + } - @Override - public String getText() { - return text; - } + @Override + public String getText() { + return text; + } - @Override - public void setText(final String text) { - this.text = text; - this.cursor = Math.max(0, Math.min(cursor, text.length())); - if (hasSelection) { - this.selectionStart = Math.max(0, Math.min(selectionStart, text.length())); - this.selectionEnd = Math.max(0, Math.min(selectionEnd, text.length())); - this.hasSelection = selectionStart != selectionEnd; - } - } + @Override + public void setText(final String text) { + this.text = text; + this.cursor = Math.max(0, Math.min(cursor, text.length())); + if (hasSelection) { + this.selectionStart = Math.max(0, Math.min(selectionStart, text.length())); + this.selectionEnd = Math.max(0, Math.min(selectionEnd, text.length())); + this.hasSelection = selectionStart != selectionEnd; + } + } - @Override - public int getCursorPosition() { - return cursor; - } + @Override + public int getCursorPosition() { + return cursor; + } - @Override - public void setCursorPosition(final int cursorPosition) { - this.cursor = Math.max(0, Math.min(cursorPosition, text.length())); - } + @Override + public void setCursorPosition(final int cursorPosition) { + this.cursor = Math.max(0, Math.min(cursorPosition, text.length())); + } - @Override - public int getCursorLine() { - int line = 0; - for (int i = 0; i < Math.min(cursor, text.length()); i++) { - if (text.charAt(i) == '\n') { - line++; - } - } - return line; - } + @Override + public int getCursorLine() { + int line = 0; + for (int i = 0; i < Math.min(cursor, text.length()); i++) { + if (text.charAt(i) == '\n') { + line++; + } + } + return line; + } - @Override - public int getLines() { - if (text.isEmpty()) { - return 1; - } - int lines = 1; - for (int i = 0; i < text.length(); i++) { - if (text.charAt(i) == '\n') { - lines++; - } - } - return lines; - } + @Override + public int getLines() { + if (text.isEmpty()) { + return 1; + } + int lines = 1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '\n') { + lines++; + } + } + return lines; + } - @Override - public void moveCursorLine(final int line) { - final int targetLine = Math.max(0, Math.min(line, getLines() - 1)); - final int currentLineStart = findLineStartByNumber(getCursorLine()); - final int currentColumn = cursor - currentLineStart; - final int targetStart = findLineStartByNumber(targetLine); - final int targetEndExclusive = findLineEndExclusive(targetStart); - this.cursor = Math.min(targetStart + currentColumn, targetEndExclusive); - } + @Override + public void moveCursorLine(final int line) { + final int targetLine = Math.max(0, Math.min(line, getLines() - 1)); + final int currentLineStart = findLineStartByNumber(getCursorLine()); + final int currentColumn = cursor - currentLineStart; + final int targetStart = findLineStartByNumber(targetLine); + final int targetEndExclusive = findLineEndExclusive(targetStart); + this.cursor = Math.min(targetStart + currentColumn, targetEndExclusive); + } - @Override - public void setSelectionEndpoints(final int selectionStart, final int cursorPosition) { - final int clampedSelectionStart = Math.max(0, Math.min(selectionStart, text.length())); - this.cursor = Math.max(0, Math.min(cursorPosition, text.length())); - this.selectionStart = Math.min(clampedSelectionStart, this.cursor); - this.selectionEnd = Math.max(clampedSelectionStart, this.cursor); - this.hasSelection = this.selectionStart != this.selectionEnd; - } + @Override + public void setSelectionEndpoints(final int selectionStart, final int cursorPosition) { + final int clampedSelectionStart = Math.max(0, Math.min(selectionStart, text.length())); + this.cursor = Math.max(0, Math.min(cursorPosition, text.length())); + this.selectionStart = Math.min(clampedSelectionStart, this.cursor); + this.selectionEnd = Math.max(clampedSelectionStart, this.cursor); + this.hasSelection = this.selectionStart != this.selectionEnd; + } - @Override - public void clearSelection() { - this.hasSelection = false; - this.selectionStart = 0; - this.selectionEnd = 0; - } + @Override + public void clearSelection() { + this.hasSelection = false; + this.selectionStart = 0; + this.selectionEnd = 0; + } - private int findLineStartByNumber(final int targetLine) { - int line = 0; - int index = 0; - while (line < targetLine && index < text.length()) { - if (text.charAt(index) == '\n') { - line++; - } - index++; - } - return index; - } + private int findLineStartByNumber(final int targetLine) { + int line = 0; + int index = 0; + while (line < targetLine && index < text.length()) { + if (text.charAt(index) == '\n') { + line++; + } + index++; + } + return index; + } - private int findLineEndExclusive(final int lineStart) { - int index = lineStart; - while (index < text.length() && text.charAt(index) != '\n') { - index++; - } - return index; - } - } + private int findLineEndExclusive(final int lineStart) { + int index = lineStart; + while (index < text.length() && text.charAt(index) != '\n') { + index++; + } + return index; + } + } - @Test - public void visualSelectionAndEscapeRestoresCursorToSelectionStart() { - final FakeBuffer buffer = new FakeBuffer("abcdef\n", 1); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void visualSelectionAndEscapeRestoresCursorToSelectionStart() { + final FakeBuffer buffer = new FakeBuffer("abcdef\n", 1); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'v', 'l', 'l'); + type(controller, 'v', 'l', 'l'); - assertEquals(1, buffer.selectionStart); - assertEquals(3, buffer.selectionEnd); - assertEquals(3, buffer.getCursorPosition()); + assertEquals(1, buffer.selectionStart); + assertEquals(3, buffer.selectionEnd); + assertEquals(3, buffer.getCursorPosition()); - controller.handleKeyDown(Input.Keys.ESCAPE); + controller.handleKeyDown(Input.Keys.ESCAPE); - assertFalse(buffer.hasSelection); - assertEquals(1, buffer.getCursorPosition()); - } + assertFalse(buffer.hasSelection); + assertEquals(1, buffer.getCursorPosition()); + } - @Test - public void normalModeUsesBlockCursorAndRelativeLines() { - final FakeBuffer buffer = new FakeBuffer("abc", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void normalModeUsesBlockCursorAndRelativeLines() { + final FakeBuffer buffer = new FakeBuffer("abc", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - assertEquals(CursorStyle.BLOCK, controller.getRenderState().cursorStyle()); - assertEquals(LineNumberMode.RELATIVE, controller.getRenderState().lineNumberMode()); - } + assertEquals(CursorStyle.BLOCK, controller.getRenderState().cursorStyle()); + assertEquals(LineNumberMode.RELATIVE, controller.getRenderState().lineNumberMode()); + } - @Test - public void insertModeUsesCaretAndAbsoluteLines() { - final FakeBuffer buffer = new FakeBuffer("abc", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void insertModeUsesCaretAndAbsoluteLines() { + final FakeBuffer buffer = new FakeBuffer("abc", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'i'); + type(controller, 'i'); - assertEquals(CursorStyle.CARET, controller.getRenderState().cursorStyle()); - assertEquals(LineNumberMode.ABSOLUTE, controller.getRenderState().lineNumberMode()); - } + assertEquals(CursorStyle.CARET, controller.getRenderState().cursorStyle()); + assertEquals(LineNumberMode.ABSOLUTE, controller.getRenderState().lineNumberMode()); + } - @Test - public void enteringVisualModeDoesNotMoveCursor() { - final FakeBuffer buffer = new FakeBuffer("abcdef", 2); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void enteringVisualModeDoesNotMoveCursor() { + final FakeBuffer buffer = new FakeBuffer("abcdef", 2); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('v'); + controller.handleKeyTyped('v'); - assertEquals(2, buffer.getCursorPosition()); - } + assertEquals(2, buffer.getCursorPosition()); + } - @Test - public void visualModeCanMoveLeftToShrinkSelection() { - final FakeBuffer buffer = new FakeBuffer("abcdef", 1); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void visualModeCanMoveLeftToShrinkSelection() { + final FakeBuffer buffer = new FakeBuffer("abcdef", 1); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'v', 'l', 'l'); - assertEquals(1, buffer.selectionStart); - assertEquals(3, buffer.selectionEnd); + type(controller, 'v', 'l', 'l'); + assertEquals(1, buffer.selectionStart); + assertEquals(3, buffer.selectionEnd); - type(controller, 'h'); - assertEquals(1, buffer.selectionStart); - assertEquals(2, buffer.selectionEnd); - assertEquals(2, buffer.getCursorPosition()); - } + type(controller, 'h'); + assertEquals(1, buffer.selectionStart); + assertEquals(2, buffer.selectionEnd); + assertEquals(2, buffer.getCursorPosition()); + } - @Test - public void visualBackwardSelectionIncludesAnchorCharacter() { - final FakeBuffer buffer = new FakeBuffer("abcdef", 3); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void visualBackwardSelectionIncludesAnchorCharacter() { + final FakeBuffer buffer = new FakeBuffer("abcdef", 3); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'v', 'h'); + type(controller, 'v', 'h'); - assertTrue(buffer.hasSelection); - assertEquals("cd", buffer.getText().substring(buffer.selectionStart, buffer.selectionEnd)); - } + assertTrue(buffer.hasSelection); + assertEquals("cd", buffer.getText().substring(buffer.selectionStart, buffer.selectionEnd)); + } - @Test - public void visualZeroMotionBackwardIncludesAnchorCharacter() { - final FakeBuffer buffer = new FakeBuffer("abcdef", 3); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void visualZeroMotionBackwardIncludesAnchorCharacter() { + final FakeBuffer buffer = new FakeBuffer("abcdef", 3); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'v', '0'); + type(controller, 'v', '0'); - assertTrue(buffer.hasSelection); - assertEquals("abcd", buffer.getText().substring(buffer.selectionStart, buffer.selectionEnd)); - } + assertTrue(buffer.hasSelection); + assertEquals("abcd", buffer.getText().substring(buffer.selectionStart, buffer.selectionEnd)); + } - @Test - public void visualModeGgMovesToStartAndKeepsSelection() { - final FakeBuffer buffer = new FakeBuffer("one\ntwo\nthree", 7); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void visualModeGgMovesToStartAndKeepsSelection() { + final FakeBuffer buffer = new FakeBuffer("one\ntwo\nthree", 7); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'v', 'g', 'g'); + type(controller, 'v', 'g', 'g'); - assertEquals(0, buffer.getCursorPosition()); - assertTrue(buffer.hasSelection); - assertEquals("one\ntwo\n", buffer.getText().substring(buffer.selectionStart, buffer.selectionEnd)); - } + assertEquals(0, buffer.getCursorPosition()); + assertTrue(buffer.hasSelection); + assertEquals("one\ntwo\n", buffer.getText().substring(buffer.selectionStart, buffer.selectionEnd)); + } - @Test - public void visualLineSelectionWorksWithShiftV() { - final FakeBuffer buffer = new FakeBuffer("one\ntwo\nthree\n", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void visualLineSelectionWorksWithShiftV() { + final FakeBuffer buffer = new FakeBuffer("one\ntwo\nthree\n", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'V', 'j'); + type(controller, 'V', 'j'); - assertTrue(buffer.hasSelection); - assertEquals(0, buffer.selectionStart); - assertEquals(8, buffer.selectionEnd); - } + assertTrue(buffer.hasSelection); + assertEquals(0, buffer.selectionStart); + assertEquals(8, buffer.selectionEnd); + } - @Test - public void visualLineJThenKUpdatesSelectionAndCursorLine() { - final FakeBuffer buffer = new FakeBuffer("one\ntwo\nthree\n", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void visualLineJThenKUpdatesSelectionAndCursorLine() { + final FakeBuffer buffer = new FakeBuffer("one\ntwo\nthree\n", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'V', 'j'); - assertEquals(0, buffer.selectionStart); - assertEquals(8, buffer.selectionEnd); + type(controller, 'V', 'j'); + assertEquals(0, buffer.selectionStart); + assertEquals(8, buffer.selectionEnd); - type(controller, 'k'); - assertEquals(0, buffer.selectionStart); - assertEquals(4, buffer.selectionEnd); - assertEquals(0, buffer.getCursorLine()); - } + type(controller, 'k'); + assertEquals(0, buffer.selectionStart); + assertEquals(4, buffer.selectionEnd); + assertEquals(0, buffer.getCursorLine()); + } - @Test - public void visualLineModeDoesNotMoveCursorPastLastRealTrailingEmptyLine() { - final FakeBuffer buffer = new FakeBuffer("a\n\n\n", 2); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void visualLineModeDoesNotMoveCursorPastLastRealTrailingEmptyLine() { + final FakeBuffer buffer = new FakeBuffer("a\n\n\n", 2); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'V', 'j'); + type(controller, 'V', 'j'); - assertEquals(3, buffer.getCursorPosition()); - assertEquals(2, buffer.getCursorLine()); - } + assertEquals(3, buffer.getCursorPosition()); + assertEquals(2, buffer.getCursorLine()); + } - @Test - public void openLineBelowPlacesCursorOnNewLine() { - final FakeBuffer buffer = new FakeBuffer("abc\ndef", 1); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void openLineBelowPlacesCursorOnNewLine() { + final FakeBuffer buffer = new FakeBuffer("abc\ndef", 1); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('o'); + controller.handleKeyTyped('o'); - assertEquals("abc\n\ndef", buffer.getText()); - assertEquals(4, buffer.getCursorPosition()); - } + assertEquals("abc\n\ndef", buffer.getText()); + assertEquals(4, buffer.getCursorPosition()); + } - @Test - public void moveDownCanReachTrailingEmptyLines() { - final FakeBuffer buffer = new FakeBuffer("a\n\n\n", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void moveDownCanReachTrailingEmptyLines() { + final FakeBuffer buffer = new FakeBuffer("a\n\n\n", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'j', 'j', 'j'); + type(controller, 'j', 'j', 'j'); - assertEquals(3, buffer.getCursorPosition()); - } + assertEquals(3, buffer.getCursorPosition()); + } - @Test - public void openLineBelowOnTrailingEmptyLineMovesOneLineDown() { - final FakeBuffer buffer = new FakeBuffer("a\n\n\n", 2); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void openLineBelowOnTrailingEmptyLineMovesOneLineDown() { + final FakeBuffer buffer = new FakeBuffer("a\n\n\n", 2); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('o'); + controller.handleKeyTyped('o'); - assertEquals("a\n\n\n\n", buffer.getText()); - assertEquals(3, buffer.getCursorPosition()); - } + assertEquals("a\n\n\n\n", buffer.getText()); + assertEquals(3, buffer.getCursorPosition()); + } - @Test - public void gMovesToLastNavigableCharacter() { - final FakeBuffer buffer = new FakeBuffer("alpha\nbeta\n", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void gMovesToLastNavigableCharacter() { + final FakeBuffer buffer = new FakeBuffer("alpha\nbeta\n", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('G'); + controller.handleKeyTyped('G'); - assertEquals(9, buffer.getCursorPosition()); - } + assertEquals(9, buffer.getCursorPosition()); + } - @Test - public void ggMovesToTopOfFile() { - final FakeBuffer buffer = new FakeBuffer("alpha\nbeta\n", 9); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void ggMovesToTopOfFile() { + final FakeBuffer buffer = new FakeBuffer("alpha\nbeta\n", 9); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'g', 'g'); + type(controller, 'g', 'g'); - assertEquals(0, buffer.getCursorPosition()); - } + assertEquals(0, buffer.getCursorPosition()); + } - @Test - public void ddThenPastePlacesLineBelow() { - final FakeBuffer buffer = new FakeBuffer("a\nb", 2); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void ddThenPastePlacesLineBelow() { + final FakeBuffer buffer = new FakeBuffer("a\nb", 2); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'd', 'd', 'p'); + type(controller, 'd', 'd', 'p'); - assertEquals("a\nb\n", buffer.getText()); - } + assertEquals("a\nb\n", buffer.getText()); + } - @Test - public void yyThenPastePlacesLineBelow() { - final FakeBuffer buffer = new FakeBuffer("one\ntwo\n", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void yyThenPastePlacesLineBelow() { + final FakeBuffer buffer = new FakeBuffer("one\ntwo\n", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'y', 'y', 'p'); + type(controller, 'y', 'y', 'p'); - assertEquals("one\none\ntwo\n", buffer.getText()); - } + assertEquals("one\none\ntwo\n", buffer.getText()); + } - @Test - public void dwDeletesWord() { - final FakeBuffer buffer = new FakeBuffer("one two", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void dwDeletesWord() { + final FakeBuffer buffer = new FakeBuffer("one two", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'd', 'w'); + type(controller, 'd', 'w'); - assertEquals("two", buffer.getText()); - } + assertEquals("two", buffer.getText()); + } - @Test - public void dlDeletesExactlyOneCharacter() { - final FakeBuffer buffer = new FakeBuffer("abcd", 1); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void dlDeletesExactlyOneCharacter() { + final FakeBuffer buffer = new FakeBuffer("abcd", 1); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'd', 'l'); + type(controller, 'd', 'l'); - assertEquals("acd", buffer.getText()); - } + assertEquals("acd", buffer.getText()); + } - @Test - public void dlOnLastCharacterDeletesLastCharacter() { - final FakeBuffer buffer = new FakeBuffer("abcd", 3); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void dlOnLastCharacterDeletesLastCharacter() { + final FakeBuffer buffer = new FakeBuffer("abcd", 3); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'd', 'l'); + type(controller, 'd', 'l'); - assertEquals("abc", buffer.getText()); - assertEquals(2, buffer.getCursorPosition()); - } + assertEquals("abc", buffer.getText()); + assertEquals(2, buffer.getCursorPosition()); + } - @Test - public void undoRevertsLatestEdit() { - final FakeBuffer buffer = new FakeBuffer("abc", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void undoRevertsLatestEdit() { + final FakeBuffer buffer = new FakeBuffer("abc", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('x'); - assertEquals("bc", buffer.getText()); + controller.handleKeyTyped('x'); + assertEquals("bc", buffer.getText()); - controller.handleKeyTyped('u'); - assertEquals("abc", buffer.getText()); - assertEquals(0, buffer.getCursorPosition()); - } + controller.handleKeyTyped('u'); + assertEquals("abc", buffer.getText()); + assertEquals(0, buffer.getCursorPosition()); + } - @Test - public void ctrlRRedoesAfterUndo() { - final FakeBuffer buffer = new FakeBuffer("abc", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void ctrlRRedoesAfterUndo() { + final FakeBuffer buffer = new FakeBuffer("abc", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('x'); - controller.handleKeyTyped('u'); - controller.handleKeyDown(Input.Keys.R, true); + controller.handleKeyTyped('x'); + controller.handleKeyTyped('u'); + controller.handleKeyDown(Input.Keys.R, true); - assertEquals("bc", buffer.getText()); - } + assertEquals("bc", buffer.getText()); + } - @Test - public void keyDownMotionReturnsSuppressTypedAndMovesCursor() { - final FakeBuffer buffer = new FakeBuffer("abc\ndef", 1); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void keyDownMotionReturnsSuppressTypedAndMovesCursor() { + final FakeBuffer buffer = new FakeBuffer("abc\ndef", 1); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - final boolean handled = controller.onKeyDown(new KeyEvent(Input.Keys.J, Set.of())); + final boolean handled = controller.onKeyDown(new KeyEvent(Input.Keys.J, Set.of())); - assertTrue(handled); - assertEquals(5, buffer.getCursorPosition()); - } + assertTrue(handled); + assertEquals(5, buffer.getCursorPosition()); + } - @Test - public void keyDownShiftVStartsVisualLineMode() { - final FakeBuffer buffer = new FakeBuffer("one\ntwo\nthree\n", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void keyDownShiftVStartsVisualLineMode() { + final FakeBuffer buffer = new FakeBuffer("one\ntwo\nthree\n", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - final boolean handled = controller.onKeyDown(new KeyEvent(Input.Keys.V, Set.of(EditorModifier.SHIFT))); + final boolean handled = controller.onKeyDown(new KeyEvent(Input.Keys.V, Set.of(EditorModifier.SHIFT))); - assertTrue(handled); - assertEquals("-- VISUAL LINE --", controller.getStatusText()); - } + assertTrue(handled); + assertEquals("-- VISUAL LINE --", controller.getStatusText()); + } - @Test - public void controlCharacterRRedoesAfterUndo() { - final FakeBuffer buffer = new FakeBuffer("abc", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void controlCharacterRRedoesAfterUndo() { + final FakeBuffer buffer = new FakeBuffer("abc", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('x'); - controller.handleKeyTyped('u'); - controller.handleKeyTyped((char) 18); + controller.handleKeyTyped('x'); + controller.handleKeyTyped('u'); + controller.handleKeyTyped((char) 18); - assertEquals("bc", buffer.getText()); - } + assertEquals("bc", buffer.getText()); + } - @Test - public void searchAndNextFindMatches() { - final FakeBuffer buffer = new FakeBuffer("cat dog cat", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void searchAndNextFindMatches() { + final FakeBuffer buffer = new FakeBuffer("cat dog cat", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('/'); - controller.handleKeyTyped('c'); - controller.handleKeyTyped('a'); - controller.handleKeyTyped('t'); - controller.handleKeyTyped('\n'); + controller.handleKeyTyped('/'); + controller.handleKeyTyped('c'); + controller.handleKeyTyped('a'); + controller.handleKeyTyped('t'); + controller.handleKeyTyped('\n'); - assertEquals(8, buffer.getCursorPosition()); + assertEquals(8, buffer.getCursorPosition()); - controller.handleKeyTyped('n'); - assertEquals(0, buffer.getCursorPosition()); - } + controller.handleKeyTyped('n'); + assertEquals(0, buffer.getCursorPosition()); + } - @Test - public void countMotionAdvancesMultipleCharacters() { - final FakeBuffer buffer = new FakeBuffer("abcdef", 0); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void countMotionAdvancesMultipleCharacters() { + final FakeBuffer buffer = new FakeBuffer("abcdef", 0); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, '3', 'l'); + type(controller, '3', 'l'); - assertEquals(3, buffer.getCursorPosition()); - } + assertEquals(3, buffer.getCursorPosition()); + } - @Test - public void bStopsAtPunctuationWordBeforeSymbols() { - final FakeBuffer buffer = new FakeBuffer("let lambda = ", 12); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void bStopsAtPunctuationWordBeforeSymbols() { + final FakeBuffer buffer = new FakeBuffer("let lambda = ", 12); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'b'); + type(controller, 'b'); - assertEquals(11, buffer.getCursorPosition()); - } + assertEquals(11, buffer.getCursorPosition()); + } - @Test - public void wStopsAtPunctuationWordBeforeSymbols() { - final FakeBuffer buffer = new FakeBuffer("let lambda = ", 4); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void wStopsAtPunctuationWordBeforeSymbols() { + final FakeBuffer buffer = new FakeBuffer("let lambda = ", 4); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'w'); + type(controller, 'w'); - assertEquals(11, buffer.getCursorPosition()); - } + assertEquals(11, buffer.getCursorPosition()); + } - @Test - public void secondWFromPunctuationMovesToNextIdentifier() { - final FakeBuffer buffer = new FakeBuffer("let lambda = x", 4); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void secondWFromPunctuationMovesToNextIdentifier() { + final FakeBuffer buffer = new FakeBuffer("let lambda = x", 4); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'w', 'w'); + type(controller, 'w', 'w'); - assertEquals(13, buffer.getCursorPosition()); - } + assertEquals(13, buffer.getCursorPosition()); + } - @Test - public void secondBFromPunctuationMovesToPreviousIdentifier() { - final FakeBuffer buffer = new FakeBuffer("let lambda = ", 12); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void secondBFromPunctuationMovesToPreviousIdentifier() { + final FakeBuffer buffer = new FakeBuffer("let lambda = ", 12); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'b', 'b'); + type(controller, 'b', 'b'); - assertEquals(4, buffer.getCursorPosition()); - } + assertEquals(4, buffer.getCursorPosition()); + } - @Test - public void appendMovesPastCurrentCharacter() { - final FakeBuffer buffer = new FakeBuffer("abc", 1); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void appendMovesPastCurrentCharacter() { + final FakeBuffer buffer = new FakeBuffer("abc", 1); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('a'); - insertCharacter(buffer, 'X'); - controller.handleKeyDown(Input.Keys.ESCAPE); + controller.handleKeyTyped('a'); + insertCharacter(buffer, 'X'); + controller.handleKeyDown(Input.Keys.ESCAPE); - assertEquals("abXc", buffer.getText()); - } + assertEquals("abXc", buffer.getText()); + } - @Test - public void appendAtEndOfLineInsertsAfterLastCharacter() { - final FakeBuffer buffer = new FakeBuffer("abc", 2); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void appendAtEndOfLineInsertsAfterLastCharacter() { + final FakeBuffer buffer = new FakeBuffer("abc", 2); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - controller.handleKeyTyped('a'); - insertCharacter(buffer, 'X'); - controller.handleKeyDown(Input.Keys.ESCAPE); + controller.handleKeyTyped('a'); + insertCharacter(buffer, 'X'); + controller.handleKeyDown(Input.Keys.ESCAPE); - assertEquals("abcX", buffer.getText()); - } + assertEquals("abcX", buffer.getText()); + } - @Test - public void verticalMoveUsesCurrentColumnNotStaleColumn() { - final FakeBuffer buffer = new FakeBuffer("12345678\n12\n12345678\n", 6); - final VimEngine controller = new VimEngine(buffer, status -> { - }); + @Test + public void verticalMoveUsesCurrentColumnNotStaleColumn() { + final FakeBuffer buffer = new FakeBuffer("12345678\n12\n12345678\n", 6); + final VimEngine controller = new VimEngine(buffer, status -> { + }); - type(controller, 'j'); - assertEquals(10, buffer.getCursorPosition()); + type(controller, 'j'); + assertEquals(10, buffer.getCursorPosition()); - type(controller, 'h'); - assertEquals(9, buffer.getCursorPosition()); + type(controller, 'h'); + assertEquals(9, buffer.getCursorPosition()); - type(controller, 'k'); - assertEquals(0, buffer.getCursorPosition()); - } + type(controller, 'k'); + assertEquals(0, buffer.getCursorPosition()); + } - private static void type(final VimEngine controller, final char... chars) { - for (final char character : chars) { - controller.handleKeyTyped(character); - } - } + private static void type(final VimEngine controller, final char... chars) { + for (final char character : chars) { + controller.handleKeyTyped(character); + } + } - private static void insertCharacter(final FakeBuffer buffer, final char character) { - final int cursor = buffer.getCursorPosition(); - final String text = buffer.getText(); - buffer.setText(text.substring(0, cursor) + character + text.substring(cursor)); - buffer.setCursorPosition(cursor + 1); - } + private static void insertCharacter(final FakeBuffer buffer, final char character) { + final int cursor = buffer.getCursorPosition(); + final String text = buffer.getText(); + buffer.setText(text.substring(0, cursor) + character + text.substring(cursor)); + buffer.setCursorPosition(cursor + 1); + } } diff --git a/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridCollisionPropagatationSystemTest.java b/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridCollisionPropagatationSystemTest.java index 3743f3e..9f1ff41 100644 --- a/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridCollisionPropagatationSystemTest.java +++ b/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridCollisionPropagatationSystemTest.java @@ -25,164 +25,164 @@ import java.util.List; import java.util.Set; final class GridCollisionPropagatationSystemTest { - private static final Duration FRAME = Duration.ZERO; - private static final GridCollidable WALL_COLLIDABLE = (me, them) -> CollisionBehavior.builder() - .collisionBehaviorType(CollisionBehaviorType.WALL).priority(10).build(); - private static final GridCollidable PROPAGATE_COLLIDABLE = (me, them) -> CollisionBehavior.builder() - .collisionBehaviorType(CollisionBehaviorType.PROPAGATE).priority(0).build(); + private static final Duration FRAME = Duration.ZERO; + private static final GridCollidable WALL_COLLIDABLE = (me, them) -> CollisionBehavior.builder() + .collisionBehaviorType(CollisionBehaviorType.WALL).priority(10).build(); + private static final GridCollidable PROPAGATE_COLLIDABLE = (me, them) -> CollisionBehavior.builder() + .collisionBehaviorType(CollisionBehaviorType.PROPAGATE).priority(0).build(); - @Getter - private static class SwallowCollidable implements GridCollidable { - private final Set<Entity> swallowed = new HashSet<>(); - @Override - public <T> void onSwallow(final Entity them, final World<T> world) { - swallowed.add(them); - } + @Getter + private static class SwallowCollidable implements GridCollidable { + private final Set<Entity> swallowed = new HashSet<>(); + @Override + public <T> void onSwallow(final Entity them, final World<T> world) { + swallowed.add(them); + } - @Override - public CollisionBehavior getCollisionBehaviorBetween(final Entity me, final Entity them) { - return CollisionBehavior.builder().collisionBehaviorType(CollisionBehaviorType.SWALLOW).priority(0).build(); - } - } + @Override + public CollisionBehavior getCollisionBehaviorBetween(final Entity me, final Entity them) { + return CollisionBehavior.builder().collisionBehaviorType(CollisionBehaviorType.SWALLOW).priority(0).build(); + } + } - @Test - public void testPrioritization() { - final World<GridInputState> world = mockWorld(); - final GridIndexSystem indexSystem = mock(GridIndexSystem.class); - when(indexSystem.inBounds(any())).thenReturn(true); - when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); + @Test + public void testPrioritization() { + final World<GridInputState> world = mockWorld(); + final GridIndexSystem indexSystem = mock(GridIndexSystem.class); + when(indexSystem.inBounds(any())).thenReturn(true); + when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); - final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.EAST)) - .add(new GridPosition(Vec2i.ZERO)); - final Entity toPropagate = Entity.builder().id(2).build().add(PROPAGATE_COLLIDABLE) - .add(new GridPosition(Vec2i.EAST)); - final Entity wall = Entity.builder().id(3).build().add(WALL_COLLIDABLE).add(new GridPosition(Vec2i.EAST)); + final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.EAST)) + .add(new GridPosition(Vec2i.ZERO)); + final Entity toPropagate = Entity.builder().id(2).build().add(PROPAGATE_COLLIDABLE) + .add(new GridPosition(Vec2i.EAST)); + final Entity wall = Entity.builder().id(3).build().add(WALL_COLLIDABLE).add(new GridPosition(Vec2i.EAST)); - // Propagation takes priority because priority(0) is lower - when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) - .thenReturn(Set.of(pusher)); + // Propagation takes priority because priority(0) is lower + when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) + .thenReturn(Set.of(pusher)); - when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); - when(indexSystem.entitiesAt(Vec2i.EAST)).thenReturn(List.of(toPropagate, wall)); + when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); + when(indexSystem.entitiesAt(Vec2i.EAST)).thenReturn(List.of(toPropagate, wall)); - final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); - system.update(world, mock(GridInputState.class), FRAME); + final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); + system.update(world, mock(GridInputState.class), FRAME); - assertEquals(Vec2i.EAST, pusher.get(GridMomentum.class).getVelocity()); - assertEquals(Vec2i.EAST, toPropagate.get(GridMomentum.class).getVelocity()); - } + assertEquals(Vec2i.EAST, pusher.get(GridMomentum.class).getVelocity()); + assertEquals(Vec2i.EAST, toPropagate.get(GridMomentum.class).getVelocity()); + } - @Test - public void testWallCollisionHaltsRayMomentum() { - final World<GridInputState> world = mockWorld(); - final GridIndexSystem indexSystem = mock(GridIndexSystem.class); - when(indexSystem.inBounds(any())).thenReturn(true); - when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); + @Test + public void testWallCollisionHaltsRayMomentum() { + final World<GridInputState> world = mockWorld(); + final GridIndexSystem indexSystem = mock(GridIndexSystem.class); + when(indexSystem.inBounds(any())).thenReturn(true); + when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); - final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.EAST)) - .add(new GridPosition(Vec2i.ZERO)); - final Entity toPropagate = Entity.builder().id(2).build().add(PROPAGATE_COLLIDABLE) - .add(new GridMomentum(Vec2i.EAST)).add(new GridPosition(Vec2i.EAST)); - final Entity wall = Entity.builder().id(3).build().add(WALL_COLLIDABLE) - .add(new GridPosition(Vec2i.EAST.scale(2, 0))); + final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.EAST)) + .add(new GridPosition(Vec2i.ZERO)); + final Entity toPropagate = Entity.builder().id(2).build().add(PROPAGATE_COLLIDABLE) + .add(new GridMomentum(Vec2i.EAST)).add(new GridPosition(Vec2i.EAST)); + final Entity wall = Entity.builder().id(3).build().add(WALL_COLLIDABLE) + .add(new GridPosition(Vec2i.EAST.scale(2, 0))); - when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) - .thenReturn(Set.of(pusher, toPropagate)); + when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) + .thenReturn(Set.of(pusher, toPropagate)); - when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); - when(indexSystem.entitiesAt(Vec2i.EAST)).thenReturn(List.of(toPropagate)); - when(indexSystem.entitiesAt(Vec2i.EAST.scale(2, 0))).thenReturn(List.of(wall)); + when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); + when(indexSystem.entitiesAt(Vec2i.EAST)).thenReturn(List.of(toPropagate)); + when(indexSystem.entitiesAt(Vec2i.EAST.scale(2, 0))).thenReturn(List.of(wall)); - final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); - system.update(world, GridInputState.builder().build(), FRAME); + final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); + system.update(world, GridInputState.builder().build(), FRAME); - assertEquals(Vec2i.ZERO, pusher.get(GridMomentum.class).getVelocity()); - assertEquals(Vec2i.ZERO, toPropagate.get(GridMomentum.class).getVelocity()); - } + assertEquals(Vec2i.ZERO, pusher.get(GridMomentum.class).getVelocity()); + assertEquals(Vec2i.ZERO, toPropagate.get(GridMomentum.class).getVelocity()); + } - @Test - public void testGoingOutOfBoundsHaltsMomentum() { - final World<GridInputState> world = mockWorld(); - final GridIndexSystem indexSystem = mock(GridIndexSystem.class); + @Test + public void testGoingOutOfBoundsHaltsMomentum() { + final World<GridInputState> world = mockWorld(); + final GridIndexSystem indexSystem = mock(GridIndexSystem.class); - when(indexSystem.inBounds(any())).thenReturn(false); - when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); + when(indexSystem.inBounds(any())).thenReturn(false); + when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); - final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.EAST)) - .add(new GridPosition(Vec2i.ZERO)); + final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.EAST)) + .add(new GridPosition(Vec2i.ZERO)); - when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) - .thenReturn(Set.of(pusher)); + when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) + .thenReturn(Set.of(pusher)); - when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); + when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); - final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); - system.update(world, GridInputState.builder().build(), FRAME); + final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); + system.update(world, GridInputState.builder().build(), FRAME); - assertEquals(Vec2i.ZERO, pusher.get(GridMomentum.class).getVelocity()); - } + assertEquals(Vec2i.ZERO, pusher.get(GridMomentum.class).getVelocity()); + } - @Test - public void testZeroVelocity() { - final World<GridInputState> world = mockWorld(); - final GridIndexSystem indexSystem = mock(GridIndexSystem.class); + @Test + public void testZeroVelocity() { + final World<GridInputState> world = mockWorld(); + final GridIndexSystem indexSystem = mock(GridIndexSystem.class); - when(indexSystem.inBounds(any())).thenReturn(true); - when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); + when(indexSystem.inBounds(any())).thenReturn(true); + when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); - final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.ZERO)) - .add(new GridPosition(Vec2i.ZERO)); + final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.ZERO)) + .add(new GridPosition(Vec2i.ZERO)); - when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) - .thenReturn(Set.of(pusher)); + when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) + .thenReturn(Set.of(pusher)); - when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); + when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); - final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); - system.update(world, GridInputState.builder().build(), FRAME); + final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); + system.update(world, GridInputState.builder().build(), FRAME); - assertEquals(Vec2i.ZERO, pusher.get(GridMomentum.class).getVelocity()); - } + assertEquals(Vec2i.ZERO, pusher.get(GridMomentum.class).getVelocity()); + } - @Test - public void testSwallowInteraction() { - final World<GridInputState> world = mockWorld(); - final GridIndexSystem indexSystem = mock(GridIndexSystem.class); + @Test + public void testSwallowInteraction() { + final World<GridInputState> world = mockWorld(); + final GridIndexSystem indexSystem = mock(GridIndexSystem.class); - when(indexSystem.inBounds(any())).thenReturn(true); - when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); + when(indexSystem.inBounds(any())).thenReturn(true); + when(world.getSystem(GridIndexSystem.class)).thenReturn(indexSystem); - final SwallowCollidable swallowCollidable = new SwallowCollidable(); + final SwallowCollidable swallowCollidable = new SwallowCollidable(); - final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.EAST)) - .add(new GridPosition(Vec2i.ZERO)); + final Entity pusher = Entity.builder().id(1).build().add(PROPAGATE_COLLIDABLE).add(new GridMomentum(Vec2i.EAST)) + .add(new GridPosition(Vec2i.ZERO)); - final Entity swallower = Entity.builder().id(2).build().add(swallowCollidable) - .add(new GridPosition(Vec2i.EAST)); + final Entity swallower = Entity.builder().id(2).build().add(swallowCollidable) + .add(new GridPosition(Vec2i.EAST)); - when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) - .thenReturn(Set.of(pusher)); + when(world.query(Set.of(GridMomentum.class, GridPosition.class, GridCollidable.class))) + .thenReturn(Set.of(pusher)); - when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); - when(indexSystem.entitiesAt(Vec2i.EAST)).thenReturn(List.of(swallower)); + when(indexSystem.entitiesAt(Vec2i.ZERO)).thenReturn(List.of(pusher)); + when(indexSystem.entitiesAt(Vec2i.EAST)).thenReturn(List.of(swallower)); - final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); - system.update(world, GridInputState.builder().build(), FRAME); + final GridCollisionPropagatationSystem system = new GridCollisionPropagatationSystem(); + system.update(world, GridInputState.builder().build(), FRAME); - assertEquals(Vec2i.EAST, pusher.get(GridMomentum.class).getVelocity()); - assertFalse(swallower.has(GridMomentum.class)); + assertEquals(Vec2i.EAST, pusher.get(GridMomentum.class).getVelocity()); + assertFalse(swallower.has(GridMomentum.class)); - assertEquals(swallowCollidable.getSwallowed(), Set.of(pusher)); - } + assertEquals(swallowCollidable.getSwallowed(), Set.of(pusher)); + } - @Test - public void testDependencies() { - assertEquals(Set.of(GridMovementSystem.class, GridIndexSystem.class), - new GridCollisionPropagatationSystem().getDependencies()); - } + @Test + public void testDependencies() { + assertEquals(Set.of(GridMovementSystem.class, GridIndexSystem.class), + new GridCollisionPropagatationSystem().getDependencies()); + } - @SuppressWarnings("unchecked") - private static World<GridInputState> mockWorld() { - return (World<GridInputState>) mock(World.class); - } + @SuppressWarnings("unchecked") + private static World<GridInputState> mockWorld() { + return (World<GridInputState>) mock(World.class); + } } diff --git a/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridIndexSystemTest.java b/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridIndexSystemTest.java index d9afde5..f751927 100644 --- a/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridIndexSystemTest.java +++ b/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridIndexSystemTest.java @@ -17,54 +17,54 @@ import java.time.Duration; import java.util.Set; class GridIndexSystemTest { - @Test - public void testUpdateIndexesEntitiesIntoGridSlots() { - final GridIndexSystem system = new GridIndexSystem(new Vec2i(4, 4)); - final World<GridInputState> world = mockWorld(); - final Entity alpha = Entity.builder().id(11).build(); - alpha.add(new GridPosition(new Vec2i(1, 2))); - final Entity beta = Entity.builder().id(12).build(); - beta.add(new GridPosition(new Vec2i(0, 0))); - when(world.query(Set.of(GridPosition.class))).thenReturn(Set.of(alpha, beta)); + @Test + public void testUpdateIndexesEntitiesIntoGridSlots() { + final GridIndexSystem system = new GridIndexSystem(new Vec2i(4, 4)); + final World<GridInputState> world = mockWorld(); + final Entity alpha = Entity.builder().id(11).build(); + alpha.add(new GridPosition(new Vec2i(1, 2))); + final Entity beta = Entity.builder().id(12).build(); + beta.add(new GridPosition(new Vec2i(0, 0))); + when(world.query(Set.of(GridPosition.class))).thenReturn(Set.of(alpha, beta)); - system.update(world, GridInputState.builder().movement(Vec2i.NORTH).build(), Duration.ZERO); + system.update(world, GridInputState.builder().movement(Vec2i.NORTH).build(), Duration.ZERO); - assertTrue(system.entitiesAt(new Vec2i(1, 2)).contains(alpha)); - assertTrue(system.entitiesAt(new Vec2i(0, 0)).contains(beta)); - assertTrue(system.entitiesAt(new Vec2i(3, 3)).isEmpty()); - } + assertTrue(system.entitiesAt(new Vec2i(1, 2)).contains(alpha)); + assertTrue(system.entitiesAt(new Vec2i(0, 0)).contains(beta)); + assertTrue(system.entitiesAt(new Vec2i(3, 3)).isEmpty()); + } - @Test - public void testUpdateClearsPreviousIndexesBeforeRebuilding() { - final GridIndexSystem system = new GridIndexSystem(new Vec2i(2, 2)); - final World<GridInputState> world = mockWorld(); - final Entity moving = Entity.builder().id(77).build(); - moving.add(new GridPosition(Vec2i.ZERO)); - when(world.query(Set.of(GridPosition.class))).thenReturn(Set.of(moving)).thenReturn(Set.of()); + @Test + public void testUpdateClearsPreviousIndexesBeforeRebuilding() { + final GridIndexSystem system = new GridIndexSystem(new Vec2i(2, 2)); + final World<GridInputState> world = mockWorld(); + final Entity moving = Entity.builder().id(77).build(); + moving.add(new GridPosition(Vec2i.ZERO)); + when(world.query(Set.of(GridPosition.class))).thenReturn(Set.of(moving)).thenReturn(Set.of()); - system.update(world, GridInputState.builder().movement(Vec2i.EAST).build(), Duration.ZERO); - assertTrue(system.entitiesAt(Vec2i.ZERO).contains(moving)); + system.update(world, GridInputState.builder().movement(Vec2i.EAST).build(), Duration.ZERO); + assertTrue(system.entitiesAt(Vec2i.ZERO).contains(moving)); - system.update(world, GridInputState.builder().movement(Vec2i.NORTH).build(), Duration.ZERO); - assertTrue(system.entitiesAt(Vec2i.ZERO).isEmpty()); - } + system.update(world, GridInputState.builder().movement(Vec2i.NORTH).build(), Duration.ZERO); + assertTrue(system.entitiesAt(Vec2i.ZERO).isEmpty()); + } - @Test - public void testEntitiesAtReturnsEmptySetForOutOfBoundsQuery() { - final GridIndexSystem system = new GridIndexSystem(new Vec2i(2, 2)); + @Test + public void testEntitiesAtReturnsEmptySetForOutOfBoundsQuery() { + final GridIndexSystem system = new GridIndexSystem(new Vec2i(2, 2)); - assertEquals(Set.of(), system.entitiesAt(new Vec2i(-1, 0))); - assertEquals(Set.of(), system.entitiesAt(new Vec2i(2, 1))); - assertEquals(Set.of(), system.entitiesAt(new Vec2i(1, 2))); - } + assertEquals(Set.of(), system.entitiesAt(new Vec2i(-1, 0))); + assertEquals(Set.of(), system.entitiesAt(new Vec2i(2, 1))); + assertEquals(Set.of(), system.entitiesAt(new Vec2i(1, 2))); + } - @Test - public void testDependencies() { - assertEquals(Set.of(), new GridIndexSystem(Vec2i.ZERO).getDependencies()); - } + @Test + public void testDependencies() { + assertEquals(Set.of(), new GridIndexSystem(Vec2i.ZERO).getDependencies()); + } - @SuppressWarnings("unchecked") - private static World<GridInputState> mockWorld() { - return (World<GridInputState>) Mockito.mock(World.class); - } + @SuppressWarnings("unchecked") + private static World<GridInputState> mockWorld() { + return (World<GridInputState>) Mockito.mock(World.class); + } } diff --git a/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridMovementSystemTest.java b/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridMovementSystemTest.java index 8bd8ff3..2731a7b 100644 --- a/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridMovementSystemTest.java +++ b/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridMovementSystemTest.java @@ -18,31 +18,31 @@ import java.time.Duration; import java.util.Set; final class GridMovementSystemTest { - @Test - public void testUpdateAssignsMomentumToControllableEntities() { - final World<GridInputState> world = mockWorld(); - final Entity subject = Entity.builder().id(1).build(); - subject.add(new GridControllable()); - subject.add(new GridPosition(Vec2i.ZERO)); - final Set<Entity> controllableEntities = Set.of(subject); - when(world.query(Set.of(GridControllable.class, GridPosition.class))).thenReturn(controllableEntities); + @Test + public void testUpdateAssignsMomentumToControllableEntities() { + final World<GridInputState> world = mockWorld(); + final Entity subject = Entity.builder().id(1).build(); + subject.add(new GridControllable()); + subject.add(new GridPosition(Vec2i.ZERO)); + final Set<Entity> controllableEntities = Set.of(subject); + when(world.query(Set.of(GridControllable.class, GridPosition.class))).thenReturn(controllableEntities); - final GridInputState inputState = GridInputState.builder().movement(Vec2i.SOUTH).build(); - final GridMovementSystem system = new GridMovementSystem(); + final GridInputState inputState = GridInputState.builder().movement(Vec2i.SOUTH).build(); + final GridMovementSystem system = new GridMovementSystem(); - system.update(world, inputState, Duration.ofMillis(16)); + system.update(world, inputState, Duration.ofMillis(16)); - final GridMomentum appliedMomentum = subject.get(GridMomentum.class); - assertEquals(Vec2i.SOUTH, appliedMomentum.getVelocity()); - } + final GridMomentum appliedMomentum = subject.get(GridMomentum.class); + assertEquals(Vec2i.SOUTH, appliedMomentum.getVelocity()); + } - @Test - public void testDependencies() { - assertEquals(Set.of(), new GridMovementSystem().getDependencies()); - } + @Test + public void testDependencies() { + assertEquals(Set.of(), new GridMovementSystem().getDependencies()); + } - @SuppressWarnings("unchecked") - private static World<GridInputState> mockWorld() { - return (World<GridInputState>) Mockito.mock(World.class); - } + @SuppressWarnings("unchecked") + private static World<GridInputState> mockWorld() { + return (World<GridInputState>) Mockito.mock(World.class); + } } diff --git a/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridPhysicsSystemTest.java b/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridPhysicsSystemTest.java index c3bb01e..c6a0cfe 100644 --- a/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridPhysicsSystemTest.java +++ b/core/src/test/java/coffee/liz/abstractionengine/grid/system/GridPhysicsSystemTest.java @@ -18,29 +18,29 @@ import java.time.Duration; import java.util.Set; final class GridPhysicsSystemTest { - @Test - public void testUpdateMovesEntitiesByMomentumAndResetsVelocity() { - final World<GridInputState> world = mockWorld(); - final Entity body = Entity.builder().id(3).build(); - body.add(new GridPosition(Vec2i.ZERO)); - body.add(new GridMomentum(Vec2i.EAST)); - when(world.query(Set.of(GridMomentum.class, GridPosition.class))).thenReturn(Set.of(body)); + @Test + public void testUpdateMovesEntitiesByMomentumAndResetsVelocity() { + final World<GridInputState> world = mockWorld(); + final Entity body = Entity.builder().id(3).build(); + body.add(new GridPosition(Vec2i.ZERO)); + body.add(new GridMomentum(Vec2i.EAST)); + when(world.query(Set.of(GridMomentum.class, GridPosition.class))).thenReturn(Set.of(body)); - final GridPhysicsSystem system = new GridPhysicsSystem(); - system.update(world, GridInputState.builder().movement(Vec2i.NORTH).build(), Duration.ZERO); + final GridPhysicsSystem system = new GridPhysicsSystem(); + system.update(world, GridInputState.builder().movement(Vec2i.NORTH).build(), Duration.ZERO); - final Vec2<Integer> newPosition = body.get(GridPosition.class).getPosition(); - assertEquals(Vec2i.EAST, newPosition); - assertEquals(Vec2i.ZERO, body.get(GridMomentum.class).getVelocity()); - } + final Vec2<Integer> newPosition = body.get(GridPosition.class).getPosition(); + assertEquals(Vec2i.EAST, newPosition); + assertEquals(Vec2i.ZERO, body.get(GridMomentum.class).getVelocity()); + } - @Test - public void testDependencies() { - assertEquals(Set.of(GridCollisionPropagatationSystem.class), new GridPhysicsSystem().getDependencies()); - } + @Test + public void testDependencies() { + assertEquals(Set.of(GridCollisionPropagatationSystem.class), new GridPhysicsSystem().getDependencies()); + } - @SuppressWarnings("unchecked") - private static World<GridInputState> mockWorld() { - return (World<GridInputState>) Mockito.mock(World.class); - } + @SuppressWarnings("unchecked") + private static World<GridInputState> mockWorld() { + return (World<GridInputState>) Mockito.mock(World.class); + } } diff --git a/core/src/test/java/coffee/liz/ecs/DAGWorldTest.java b/core/src/test/java/coffee/liz/ecs/DAGWorldTest.java index a656d28..648745b 100644 --- a/core/src/test/java/coffee/liz/ecs/DAGWorldTest.java +++ b/core/src/test/java/coffee/liz/ecs/DAGWorldTest.java @@ -22,188 +22,188 @@ import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; final class DAGWorldTest { - @Test - public void queryReturnsEntitiesMatchingAllRequestedComponents() { - final DAGWorld<String> world = new DAGWorld<>(Map.of()); - final Entity matching = world.createEntity(); - matching.add(new PositionComponent()); - matching.add(new VelocityComponent()); - final Entity partial = world.createEntity(); - partial.add(new PositionComponent()); - final Entity nonMatching = world.createEntity(); - nonMatching.add(new VelocityComponent()); + @Test + public void queryReturnsEntitiesMatchingAllRequestedComponents() { + final DAGWorld<String> world = new DAGWorld<>(Map.of()); + final Entity matching = world.createEntity(); + matching.add(new PositionComponent()); + matching.add(new VelocityComponent()); + final Entity partial = world.createEntity(); + partial.add(new PositionComponent()); + final Entity nonMatching = world.createEntity(); + nonMatching.add(new VelocityComponent()); - world.update("state", Duration.ZERO); + world.update("state", Duration.ZERO); - final Set<Entity> results = world.query(Set.of(PositionComponent.class, VelocityComponent.class)); + final Set<Entity> results = world.query(Set.of(PositionComponent.class, VelocityComponent.class)); - assertEquals(Set.of(matching), results); - } + assertEquals(Set.of(matching), results); + } - @Test - public void queryWithoutComponentsReturnsAllEntities() { - final DAGWorld<String> world = new DAGWorld<>(Map.of()); - final Entity entityOne = world.createEntity(); - final Entity entityTwo = world.createEntity(); + @Test + public void queryWithoutComponentsReturnsAllEntities() { + final DAGWorld<String> world = new DAGWorld<>(Map.of()); + final Entity entityOne = world.createEntity(); + final Entity entityTwo = world.createEntity(); - final Set<Entity> results = world.query(List.<Class<? extends Component>>of()); + final Set<Entity> results = world.query(List.<Class<? extends Component>>of()); - assertEquals(Set.of(entityOne, entityTwo), results); - } + assertEquals(Set.of(entityOne, entityTwo), results); + } - @Test - public void updateExecutesSystemsInTopologicalOrder() { - final CopyOnWriteArrayList<String> executionLog = new CopyOnWriteArrayList<>(); + @Test + public void updateExecutesSystemsInTopologicalOrder() { + final CopyOnWriteArrayList<String> executionLog = new CopyOnWriteArrayList<>(); - final DAGWorld<String> world = new DAGWorld<>(Map.of(SystemC.class, new SystemC(executionLog), SystemA.class, - new SystemA(executionLog), SystemB.class, new SystemB(executionLog))); - world.update("state", Duration.ZERO); + final DAGWorld<String> world = new DAGWorld<>(Map.of(SystemC.class, new SystemC(executionLog), SystemA.class, + new SystemA(executionLog), SystemB.class, new SystemB(executionLog))); + world.update("state", Duration.ZERO); - assertEquals(List.of("A", "B", "C"), executionLog); - } + assertEquals(List.of("A", "B", "C"), executionLog); + } - @Test - public void updateRefreshesComponentCacheAfterEntityMutations() { - final DAGWorld<String> world = new DAGWorld<>(Map.of()); - final Entity subject = world.createEntity(); + @Test + public void updateRefreshesComponentCacheAfterEntityMutations() { + final DAGWorld<String> world = new DAGWorld<>(Map.of()); + final Entity subject = world.createEntity(); - world.update("state", Duration.ZERO); - assertTrue(world.query(Set.of(PositionComponent.class)).isEmpty()); + world.update("state", Duration.ZERO); + assertTrue(world.query(Set.of(PositionComponent.class)).isEmpty()); - subject.add(new PositionComponent()); - world.update("state", Duration.ZERO); - assertEquals(1, world.query(Set.of(PositionComponent.class)).size()); + subject.add(new PositionComponent()); + world.update("state", Duration.ZERO); + assertEquals(1, world.query(Set.of(PositionComponent.class)).size()); - subject.remove(PositionComponent.class); - world.update("state", Duration.ZERO); - assertTrue(world.query(Set.of(PositionComponent.class)).isEmpty()); - } + subject.remove(PositionComponent.class); + world.update("state", Duration.ZERO); + assertTrue(world.query(Set.of(PositionComponent.class)).isEmpty()); + } - @Test - public void queryFindsComponentsAddedByEarlierSystemInSameTick() { - final List<Set<Entity>> queryResults = new CopyOnWriteArrayList<>(); + @Test + public void queryFindsComponentsAddedByEarlierSystemInSameTick() { + final List<Set<Entity>> queryResults = new CopyOnWriteArrayList<>(); - final Map<Class<? extends System<String>>, System<String>> systems = new LinkedHashMap<>(); - systems.put(ComponentAdderSystem.class, new ComponentAdderSystem()); - systems.put(ComponentReaderSystem.class, new ComponentReaderSystem(queryResults)); - final DAGWorld<String> world = new DAGWorld<>(systems); + final Map<Class<? extends System<String>>, System<String>> systems = new LinkedHashMap<>(); + systems.put(ComponentAdderSystem.class, new ComponentAdderSystem()); + systems.put(ComponentReaderSystem.class, new ComponentReaderSystem(queryResults)); + final DAGWorld<String> world = new DAGWorld<>(systems); - final Entity entity = world.createEntity(); - entity.add(new PositionComponent()); + final Entity entity = world.createEntity(); + entity.add(new PositionComponent()); - world.update("state", Duration.ZERO); + world.update("state", Duration.ZERO); - assertEquals(1, queryResults.size()); - assertEquals(Set.of(entity), queryResults.getFirst()); - } + assertEquals(1, queryResults.size()); + assertEquals(Set.of(entity), queryResults.getFirst()); + } - @Test - public void circularDependencyDetectionThrowsIllegalStateException() { - final Map<Class<? extends System<String>>, System<String>> systems = new LinkedHashMap<>(); - final SystemCycleA systemA = new SystemCycleA(); - final SystemCycleB systemB = new SystemCycleB(); - systems.put(SystemCycleA.class, systemA); - systems.put(SystemCycleB.class, systemB); + @Test + public void circularDependencyDetectionThrowsIllegalStateException() { + final Map<Class<? extends System<String>>, System<String>> systems = new LinkedHashMap<>(); + final SystemCycleA systemA = new SystemCycleA(); + final SystemCycleB systemB = new SystemCycleB(); + systems.put(SystemCycleA.class, systemA); + systems.put(SystemCycleB.class, systemB); - assertThrows(IllegalStateException.class, () -> new DAGWorld<>(systems)); - } + assertThrows(IllegalStateException.class, () -> new DAGWorld<>(systems)); + } - private static final class PositionComponent implements Component { - } + private static final class PositionComponent implements Component { + } - private static final class VelocityComponent implements Component { - } + private static final class VelocityComponent implements Component { + } - @RequiredArgsConstructor - private abstract static class RecordingSystem implements System<String> { - private final List<String> log; - private final String label; + @RequiredArgsConstructor + private abstract static class RecordingSystem implements System<String> { + private final List<String> log; + private final String label; - @Override - public final void update(final World<String> world, final String state, final Duration duration) { - log.add(label); - } - } + @Override + public final void update(final World<String> world, final String state, final Duration duration) { + log.add(label); + } + } - private static final class SystemA extends RecordingSystem { - private SystemA(final List<String> log) { - super(log, "A"); - } + private static final class SystemA extends RecordingSystem { + private SystemA(final List<String> log) { + super(log, "A"); + } - @Override - public Collection<Class<? extends System<String>>> getDependencies() { - return List.of(); - } - } + @Override + public Collection<Class<? extends System<String>>> getDependencies() { + return List.of(); + } + } - private static final class SystemB extends RecordingSystem { - private SystemB(final List<String> log) { - super(log, "B"); - } + private static final class SystemB extends RecordingSystem { + private SystemB(final List<String> log) { + super(log, "B"); + } - @Override - public Collection<Class<? extends System<String>>> getDependencies() { - return Set.of(SystemA.class); - } - } + @Override + public Collection<Class<? extends System<String>>> getDependencies() { + return Set.of(SystemA.class); + } + } - private static final class SystemC extends RecordingSystem { - private SystemC(final List<String> log) { - super(log, "C"); - } + private static final class SystemC extends RecordingSystem { + private SystemC(final List<String> log) { + super(log, "C"); + } - @Override - public Collection<Class<? extends System<String>>> getDependencies() { - return Set.of(SystemB.class); - } - } + @Override + public Collection<Class<? extends System<String>>> getDependencies() { + return Set.of(SystemB.class); + } + } - private static final class SystemCycleA implements System<String> { - @Override - public Collection<Class<? extends System<String>>> getDependencies() { - return Set.of(SystemCycleB.class); - } + private static final class SystemCycleA implements System<String> { + @Override + public Collection<Class<? extends System<String>>> getDependencies() { + return Set.of(SystemCycleB.class); + } - @Override - public void update(final World<String> world, final String state, final Duration duration) { - } - } + @Override + public void update(final World<String> world, final String state, final Duration duration) { + } + } - private static final class SystemCycleB implements System<String> { - @Override - public Collection<Class<? extends System<String>>> getDependencies() { - return Set.of(SystemCycleA.class); - } + private static final class SystemCycleB implements System<String> { + @Override + public Collection<Class<? extends System<String>>> getDependencies() { + return Set.of(SystemCycleA.class); + } - @Override - public void update(final World<String> world, final String state, final Duration duration) { - } - } + @Override + public void update(final World<String> world, final String state, final Duration duration) { + } + } - private static final class ComponentAdderSystem implements System<String> { - @Override - public Collection<Class<? extends System<String>>> getDependencies() { - return List.of(); - } + private static final class ComponentAdderSystem implements System<String> { + @Override + public Collection<Class<? extends System<String>>> getDependencies() { + return List.of(); + } - @Override - public void update(final World<String> world, final String state, final Duration duration) { - world.query(Set.of(PositionComponent.class)).forEach(e -> e.add(new VelocityComponent())); - } - } + @Override + public void update(final World<String> world, final String state, final Duration duration) { + world.query(Set.of(PositionComponent.class)).forEach(e -> e.add(new VelocityComponent())); + } + } - @RequiredArgsConstructor - private static final class ComponentReaderSystem implements System<String> { - private final List<Set<Entity>> queryResults; + @RequiredArgsConstructor + private static final class ComponentReaderSystem implements System<String> { + private final List<Set<Entity>> queryResults; - @Override - public Collection<Class<? extends System<String>>> getDependencies() { - return Set.of(ComponentAdderSystem.class); - } + @Override + public Collection<Class<? extends System<String>>> getDependencies() { + return Set.of(ComponentAdderSystem.class); + } - @Override - public void update(final World<String> world, final String state, final Duration duration) { - queryResults.add(world.query(Set.of(VelocityComponent.class, PositionComponent.class))); - } - } + @Override + public void update(final World<String> world, final String state, final Duration duration) { + queryResults.add(world.query(Set.of(VelocityComponent.class, PositionComponent.class))); + } + } } diff --git a/core/src/test/java/coffee/liz/ecs/model/EntityTest.java b/core/src/test/java/coffee/liz/ecs/model/EntityTest.java index c9ce59a..a8fd1e3 100644 --- a/core/src/test/java/coffee/liz/ecs/model/EntityTest.java +++ b/core/src/test/java/coffee/liz/ecs/model/EntityTest.java @@ -18,80 +18,80 @@ import java.util.List; import java.util.stream.Stream; final class EntityTest { - @ParameterizedTest - @MethodSource("componentCombinationProvider") - public void hasAllReportsPresenceForComponentSets(final Collection<Class<? extends Component>> query, - final boolean expected) { - final Entity entity = Entity.builder().id(7).build(); - entity.add(new AlphaComponent("first")); - entity.add(new BetaComponent(3)); - entity.add(new GammaKeyedComponent()); + @ParameterizedTest + @MethodSource("componentCombinationProvider") + public void hasAllReportsPresenceForComponentSets(final Collection<Class<? extends Component>> query, + final boolean expected) { + final Entity entity = Entity.builder().id(7).build(); + entity.add(new AlphaComponent("first")); + entity.add(new BetaComponent(3)); + entity.add(new GammaKeyedComponent()); - assertEquals(expected, entity.hasAll(query)); - } + assertEquals(expected, entity.hasAll(query)); + } - private static Stream<Arguments> componentCombinationProvider() { - return Stream - .of(Arguments.of(List.of(AlphaComponent.class), true), Arguments.of(List.of(BetaComponent.class), true), - Arguments.of(List.of(AlphaComponent.class, BetaComponent.class, GammaComponent.class), true), - Arguments.of(List.of(AlphaComponent.class, BetaComponent.class, GammaKeyedComponent.class), - false), - Arguments.of(List.of(GammaComponent.class), true), - Arguments.of(List.of(GammaKeyedComponent.class), false)); - } + private static Stream<Arguments> componentCombinationProvider() { + return Stream + .of(Arguments.of(List.of(AlphaComponent.class), true), Arguments.of(List.of(BetaComponent.class), true), + Arguments.of(List.of(AlphaComponent.class, BetaComponent.class, GammaComponent.class), true), + Arguments.of(List.of(AlphaComponent.class, BetaComponent.class, GammaKeyedComponent.class), + false), + Arguments.of(List.of(GammaComponent.class), true), + Arguments.of(List.of(GammaKeyedComponent.class), false)); + } - @Test - public void getThrowsForMissingComponentsWithHelpfulMessage() { - final Entity entity = Entity.builder().id(99).build(); + @Test + public void getThrowsForMissingComponentsWithHelpfulMessage() { + final Entity entity = Entity.builder().id(99).build(); - final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, - () -> entity.get(AlphaComponent.class)); + final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, + () -> entity.get(AlphaComponent.class)); - assertTrue(thrown.getMessage().contains("AlphaComponent")); - assertTrue(thrown.getMessage().contains("99")); - } + assertTrue(thrown.getMessage().contains("AlphaComponent")); + assertTrue(thrown.getMessage().contains("99")); + } - @Test - public void addReplacesExistingComponentInstance() { - final Entity entity = Entity.builder().id(17).build(); - final AlphaComponent initial = new AlphaComponent("initial"); - entity.add(initial); + @Test + public void addReplacesExistingComponentInstance() { + final Entity entity = Entity.builder().id(17).build(); + final AlphaComponent initial = new AlphaComponent("initial"); + entity.add(initial); - final AlphaComponent replacement = new AlphaComponent("replacement"); - entity.add(replacement); + final AlphaComponent replacement = new AlphaComponent("replacement"); + entity.add(replacement); - assertSame(replacement, entity.get(AlphaComponent.class)); - } + assertSame(replacement, entity.get(AlphaComponent.class)); + } - @Test - public void removeClearsComponentPresence() { - final Entity entity = Entity.builder().id(45).build(); - entity.add(new BetaComponent(2)); - assertTrue(entity.has(BetaComponent.class)); + @Test + public void removeClearsComponentPresence() { + final Entity entity = Entity.builder().id(45).build(); + entity.add(new BetaComponent(2)); + assertTrue(entity.has(BetaComponent.class)); - entity.remove(BetaComponent.class); + entity.remove(BetaComponent.class); - assertFalse(entity.has(BetaComponent.class)); - assertTrue(entity.componentTypes().isEmpty()); - } + assertFalse(entity.has(BetaComponent.class)); + assertTrue(entity.componentTypes().isEmpty()); + } - private record AlphaComponent(String name) implements Component { - } + private record AlphaComponent(String name) implements Component { + } - private record BetaComponent(int level) implements Component { - } + private record BetaComponent(int level) implements Component { + } - @RequiredArgsConstructor - private class GammaComponent implements Component { - @Override - public Class<? extends Component> getKey() { - return GammaComponent.class; - } - } + @RequiredArgsConstructor + private class GammaComponent implements Component { + @Override + public Class<? extends Component> getKey() { + return GammaComponent.class; + } + } - private class GammaKeyedComponent extends GammaComponent { - } + private class GammaKeyedComponent extends GammaComponent { + } - private record ContextualComponent(int ownerId) implements Component { - } + private record ContextualComponent(int ownerId) implements Component { + } } diff --git a/core/src/test/java/coffee/liz/lambda/eval/InterpreterTest.java b/core/src/test/java/coffee/liz/lambda/eval/InterpreterTest.java index 4b63782..314f3bd 100644 --- a/core/src/test/java/coffee/liz/lambda/eval/InterpreterTest.java +++ b/core/src/test/java/coffee/liz/lambda/eval/InterpreterTest.java @@ -16,88 +16,88 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class InterpreterTest { - @Test - public void identity() { - final Value result = LambdaDriver.interpret(SourceCode.ofArrow("x -> x")); + @Test + public void identity() { + final Value result = LambdaDriver.interpret(SourceCode.ofArrow("x -> x")); - final Value.Closure closure = assertInstanceOf(Value.Closure.class, result); - assertEquals("x", closure.parameter()); - assertInstanceOf(IdentifierExpression.class, closure.body()); - } + final Value.Closure closure = assertInstanceOf(Value.Closure.class, result); + assertEquals("x", closure.parameter()); + assertInstanceOf(IdentifierExpression.class, closure.body()); + } - @Test - public void identityApplication() { - final Value result = LambdaDriver.interpret(SourceCode.ofArrow("(x -> x)(y)")); + @Test + public void identityApplication() { + final Value result = LambdaDriver.interpret(SourceCode.ofArrow("(x -> x)(y)")); - assertEquals(new Value.Free("y"), result); - } + assertEquals(new Value.Free("y"), result); + } - @Test - public void nestedApplication() { - final Value result = LambdaDriver.interpret(SourceCode.ofArrow("(f -> g -> x -> f(g)(x))(x -> x)(y -> y)(x)")); + @Test + public void nestedApplication() { + final Value result = LambdaDriver.interpret(SourceCode.ofArrow("(f -> g -> x -> f(g)(x))(x -> x)(y -> y)(x)")); - assertEquals(new Value.Free("x"), result); - } + assertEquals(new Value.Free("x"), result); + } - @Test - public void cons() { - final Value result = LambdaDriver.interpret(SourceCode.ofArrow(""" - let pair = a -> b -> f -> f(a)(b); - let second = x -> y -> y; - pair(x)(y)(second) - """)); + @Test + public void cons() { + final Value result = LambdaDriver.interpret(SourceCode.ofArrow(""" + let pair = a -> b -> f -> f(a)(b); + let second = x -> y -> y; + pair(x)(y)(second) + """)); - assertEquals(new Value.Free("y"), result); - } + assertEquals(new Value.Free("y"), result); + } - @Test - public void fibonacci() { - final String source = """ - let true = t -> f -> t; - let false = t -> f -> f; + @Test + public void fibonacci() { + final String source = """ + let true = t -> f -> t; + let false = t -> f -> f; - let pair = x -> y -> f -> f(x)(y); - let fst = p -> p(x -> y -> x); - let snd = p -> p(x -> y -> y); + let pair = x -> y -> f -> f(x)(y); + let fst = p -> p(x -> y -> x); + let snd = p -> p(x -> y -> y); - let 0 = f -> x -> x; - let 1 = f -> x -> f(x); + let 0 = f -> x -> x; + let 1 = f -> x -> f(x); - let succ = n -> f -> x -> f(n(f)(x)); - let plus = m -> n -> f -> x -> m(f)(n(f)(x)); - let next = p -> pair(snd(p))(succ(snd(p))); - let pred = n -> fst(n(next)(pair(0)(0))); + let succ = n -> f -> x -> f(n(f)(x)); + let plus = m -> n -> f -> x -> m(f)(n(f)(x)); + let next = p -> pair(snd(p))(succ(snd(p))); + let pred = n -> fst(n(next)(pair(0)(0))); - let iszero = n -> n(x -> false)(true); - let isone = n -> iszero(pred(n)); + let iszero = n -> n(x -> false)(true); + let isone = n -> iszero(pred(n)); - let y = f -> (x -> f(x(x)))(x -> f(x(x))); + let y = f -> (x -> f(x(x)))(x -> f(x(x))); - let fib = y(fib -> n -> - iszero(n) (0) - (isone(n) (1) - (plus - (fib(pred(n))) - (fib(pred(pred(n))))))); + let fib = y(fib -> n -> + iszero(n) (0) + (isone(n) (1) + (plus + (fib(pred(n))) + (fib(pred(pred(n))))))); - fib(ToChurch(13))(Tick)(dummy) - """; + fib(ToChurch(13))(Tick)(dummy) + """; - final Tick ticker = new Tick(); - final Value result = LambdaDriver.interpret(SourceCode.ofArrow(source), List.of(ticker, new ToChurch())); + final Tick ticker = new Tick(); + final Value result = LambdaDriver.interpret(SourceCode.ofArrow(source), List.of(ticker, new ToChurch())); - assertEquals(new Value.Free("dummy"), result); - assertEquals(233, ticker.getCounter().get()); - } + assertEquals(new Value.Free("dummy"), result); + assertEquals(233, ticker.getCounter().get()); + } - @Test - public void omegaCombinatorThrowsDepthExceeded() { - final LambdaProgram program = LambdaDriver.parse(SourceCode.ofArrow("(x -> x(x))(x -> x(x))")); - final Environment env = Environment.from(program.macros(), List.of()); + @Test + public void omegaCombinatorThrowsDepthExceeded() { + final LambdaProgram program = LambdaDriver.parse(SourceCode.ofArrow("(x -> x(x))(x -> x(x))")); + final Environment env = Environment.from(program.macros(), List.of()); - final EvaluationDepthExceededException exception = assertThrows(EvaluationDepthExceededException.class, - () -> NormalOrderEvaluator.evaluate(program.expression(), env, 100)); + final EvaluationDepthExceededException exception = assertThrows(EvaluationDepthExceededException.class, + () -> NormalOrderEvaluator.evaluate(program.expression(), env, 100)); - assertEquals(100, exception.getMaxDepth()); - } + assertEquals(100, exception.getMaxDepth()); + } } diff --git a/core/src/test/java/coffee/liz/lambda/eval/ThunkTest.java b/core/src/test/java/coffee/liz/lambda/eval/ThunkTest.java index 2a1d5e3..2b4215c 100644 --- a/core/src/test/java/coffee/liz/lambda/eval/ThunkTest.java +++ b/core/src/test/java/coffee/liz/lambda/eval/ThunkTest.java @@ -8,31 +8,31 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; public class ThunkTest { - @Test - public void testThunkNonNull() { - final AtomicInteger invok = new AtomicInteger(0); - final Supplier<Integer> i = () -> { - invok.incrementAndGet(); - return invok.get(); - }; - final Thunk<Integer> thunk = new Thunk<>(i); - Assertions.assertEquals(1, thunk.get()); - Assertions.assertEquals(1, thunk.get()); - Assertions.assertEquals(1, thunk.get()); - Assertions.assertEquals(1, invok.get()); - } + @Test + public void testThunkNonNull() { + final AtomicInteger invok = new AtomicInteger(0); + final Supplier<Integer> i = () -> { + invok.incrementAndGet(); + return invok.get(); + }; + final Thunk<Integer> thunk = new Thunk<>(i); + Assertions.assertEquals(1, thunk.get()); + Assertions.assertEquals(1, thunk.get()); + Assertions.assertEquals(1, thunk.get()); + Assertions.assertEquals(1, invok.get()); + } - @Test - public void testThunkNull() { - final AtomicInteger invok = new AtomicInteger(0); - final Supplier<Integer> i = () -> { - invok.incrementAndGet(); - return null; - }; - final Thunk<Integer> thunk = new Thunk<>(i); - Assertions.assertNull(thunk.get()); - Assertions.assertNull(thunk.get()); - Assertions.assertNull(thunk.get()); - Assertions.assertEquals(1, invok.get()); - } + @Test + public void testThunkNull() { + final AtomicInteger invok = new AtomicInteger(0); + final Supplier<Integer> i = () -> { + invok.incrementAndGet(); + return null; + }; + final Thunk<Integer> thunk = new Thunk<>(i); + Assertions.assertNull(thunk.get()); + Assertions.assertNull(thunk.get()); + Assertions.assertNull(thunk.get()); + Assertions.assertEquals(1, invok.get()); + } } diff --git a/core/src/test/java/coffee/liz/lambda/format/FormatterTest.java b/core/src/test/java/coffee/liz/lambda/format/FormatterTest.java index 111855f..1e9440c 100644 --- a/core/src/test/java/coffee/liz/lambda/format/FormatterTest.java +++ b/core/src/test/java/coffee/liz/lambda/format/FormatterTest.java @@ -12,42 +12,42 @@ import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; class FormatterTest { - @ParameterizedTest - @MethodSource("provideRoundTrip") - public void testRoundTrip(final String lambda, final String arrow) { - final String formattedLambda = format(SourceCode.ofArrow(arrow), Syntax.LAMBDA); - final String formattedArrow = format(SourceCode.ofLambda(lambda), Syntax.ARROW); - assertEquals(lambda, formattedLambda); - assertEquals(arrow, formattedArrow); - } + @ParameterizedTest + @MethodSource("provideRoundTrip") + public void testRoundTrip(final String lambda, final String arrow) { + final String formattedLambda = format(SourceCode.ofArrow(arrow), Syntax.LAMBDA); + final String formattedArrow = format(SourceCode.ofLambda(lambda), Syntax.ARROW); + assertEquals(lambda, formattedLambda); + assertEquals(arrow, formattedArrow); + } - public static Stream<Arguments> provideRoundTrip() { - return Stream.of(Arguments.of("λx.λy.x", "x -> y -> x"), Arguments.of("(λx.x) y", "(x -> x)(y)"), - Arguments.of("f x y z", "f(x)(y)(z)"), Arguments.of("f x y z -- Comment!", "f(x)(y)(z) -- Comment!"), - Arguments.of(""" - let id = λx.x; - let const = λx.λy.x; -- Inline comment! + public static Stream<Arguments> provideRoundTrip() { + return Stream.of(Arguments.of("λx.λy.x", "x -> y -> x"), Arguments.of("(λx.x) y", "(x -> x)(y)"), + Arguments.of("f x y z", "f(x)(y)(z)"), Arguments.of("f x y z -- Comment!", "f(x)(y)(z) -- Comment!"), + Arguments.of(""" + let id = λx.x; + let const = λx.λy.x; -- Inline comment! - -- Test comment - -- Another comment - id""", """ - let id = x -> x; - let const = x -> y -> x; -- Inline comment! + -- Test comment + -- Another comment + id""", """ + let id = x -> x; + let const = x -> y -> x; -- Inline comment! - -- Test comment - -- Another comment - id"""), Arguments.of(""" - -- The identity function - let id = λx.x; + -- Test comment + -- Another comment + id"""), Arguments.of(""" + -- The identity function + let id = λx.x; - id""", """ - -- The identity function - let id = x -> x; + id""", """ + -- The identity function + let id = x -> x; - id""")); - } + id""")); + } - private static String format(final SourceCode code, final Syntax syntax) { - return Formatter.emit(LambdaDriver.parse(code), syntax); - } + private static String format(final SourceCode code, final Syntax syntax) { + return Formatter.emit(LambdaDriver.parse(code), syntax); + } } diff --git a/core/src/test/java/coffee/liz/lambda/parser/ParserTest.java b/core/src/test/java/coffee/liz/lambda/parser/ParserTest.java index 0158003..6861811 100644 --- a/core/src/test/java/coffee/liz/lambda/parser/ParserTest.java +++ b/core/src/test/java/coffee/liz/lambda/parser/ParserTest.java @@ -16,163 +16,163 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf; class ParserTest { - @Test - public void testTrivial() { - final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("λx.x")); - final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("x -> x")); + @Test + public void testTrivial() { + final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("λx.x")); + final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("x -> x")); - assertStructurallyEqual(lambda, arrow); - assertEquals(0, lambda.macros().size()); - assertInstanceOf(AbstractionExpression.class, lambda.expression()); - assertEquals("x", ((AbstractionExpression) lambda.expression()).parameter()); - } + assertStructurallyEqual(lambda, arrow); + assertEquals(0, lambda.macros().size()); + assertInstanceOf(AbstractionExpression.class, lambda.expression()); + assertEquals("x", ((AbstractionExpression) lambda.expression()).parameter()); + } - @Test - public void testApplication() { - final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("(λx.x) y")); - final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("(x -> x)(y)")); + @Test + public void testApplication() { + final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("(λx.x) y")); + final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("(x -> x)(y)")); - assertStructurallyEqual(lambda, arrow); + assertStructurallyEqual(lambda, arrow); - final ApplicationExpression app = (ApplicationExpression) lambda.expression(); - assertInstanceOf(AbstractionExpression.class, app.applicable()); - assertInstanceOf(IdentifierExpression.class, app.argument()); - } + final ApplicationExpression app = (ApplicationExpression) lambda.expression(); + assertInstanceOf(AbstractionExpression.class, app.applicable()); + assertInstanceOf(IdentifierExpression.class, app.argument()); + } - @Test - public void testChainedLambdas() { - final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("λx.λy.λz.x")); - final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("x -> y -> z -> x")); + @Test + public void testChainedLambdas() { + final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("λx.λy.λz.x")); + final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("x -> y -> z -> x")); - assertStructurallyEqual(lambda, arrow); + assertStructurallyEqual(lambda, arrow); - final AbstractionExpression outer = (AbstractionExpression) lambda.expression(); - assertEquals("x", outer.parameter()); - final AbstractionExpression middle = (AbstractionExpression) outer.body(); - assertEquals("y", middle.parameter()); - final AbstractionExpression inner = (AbstractionExpression) middle.body(); - assertEquals("z", inner.parameter()); - } + final AbstractionExpression outer = (AbstractionExpression) lambda.expression(); + assertEquals("x", outer.parameter()); + final AbstractionExpression middle = (AbstractionExpression) outer.body(); + assertEquals("y", middle.parameter()); + final AbstractionExpression inner = (AbstractionExpression) middle.body(); + assertEquals("z", inner.parameter()); + } - @Test - public void testChainedApplication() { - final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("((f x) y) z")); - final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("f(x)(y)(z)")); + @Test + public void testChainedApplication() { + final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("((f x) y) z")); + final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("f(x)(y)(z)")); - assertStructurallyEqual(lambda, arrow); + assertStructurallyEqual(lambda, arrow); - final ApplicationExpression app1 = (ApplicationExpression) lambda.expression(); - assertEquals("z", ((IdentifierExpression) app1.argument()).name()); - final ApplicationExpression app2 = (ApplicationExpression) app1.applicable(); - assertEquals("y", ((IdentifierExpression) app2.argument()).name()); - final ApplicationExpression app3 = (ApplicationExpression) app2.applicable(); - assertEquals("f", ((IdentifierExpression) app3.applicable()).name()); - assertEquals("x", ((IdentifierExpression) app3.argument()).name()); - } + final ApplicationExpression app1 = (ApplicationExpression) lambda.expression(); + assertEquals("z", ((IdentifierExpression) app1.argument()).name()); + final ApplicationExpression app2 = (ApplicationExpression) app1.applicable(); + assertEquals("y", ((IdentifierExpression) app2.argument()).name()); + final ApplicationExpression app3 = (ApplicationExpression) app2.applicable(); + assertEquals("f", ((IdentifierExpression) app3.applicable()).name()); + assertEquals("x", ((IdentifierExpression) app3.argument()).name()); + } - @Test - public void testMacros() { - final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda(""" - let id = λx.x; - id - """)); - final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow(""" - let id = x -> x; - id - """)); + @Test + public void testMacros() { + final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda(""" + let id = λx.x; + id + """)); + final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow(""" + let id = x -> x; + id + """)); - assertStructurallyEqual(lambda, arrow); - assertEquals(1, lambda.macros().size()); - assertEquals("id", lambda.macros().getFirst().name()); - assertInstanceOf(IdentifierExpression.class, lambda.expression()); - } + assertStructurallyEqual(lambda, arrow); + assertEquals(1, lambda.macros().size()); + assertEquals("id", lambda.macros().getFirst().name()); + assertInstanceOf(IdentifierExpression.class, lambda.expression()); + } - @Test - public void testLineComments() { - final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda(""" - -- The identity function - let id = λx.x; -- returns its argument - id -- use it - """)); - final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow(""" - -- The identity function - let id = x -> x; -- returns its argument - id -- use it - """)); + @Test + public void testLineComments() { + final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda(""" + -- The identity function + let id = λx.x; -- returns its argument + id -- use it + """)); + final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow(""" + -- The identity function + let id = x -> x; -- returns its argument + id -- use it + """)); - assertStructurallyEqual(lambda, arrow); - assertEquals(1, lambda.macros().size()); - assertEquals("id", lambda.macros().getFirst().name()); - } + assertStructurallyEqual(lambda, arrow); + assertEquals(1, lambda.macros().size()); + assertEquals("id", lambda.macros().getFirst().name()); + } - @Test - public void testComplexProgram() { - final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda(""" - let zero = λf.λx.x; - let one = λf.λx.f x; - let succ = λn.λf.λx.f (n f x); - let add = λm.λn.λf.λx.m f (n f x); + @Test + public void testComplexProgram() { + final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda(""" + let zero = λf.λx.x; + let one = λf.λx.f x; + let succ = λn.λf.λx.f (n f x); + let add = λm.λn.λf.λx.m f (n f x); - succ (add one zero) - """)); + succ (add one zero) + """)); - final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow(""" - let zero = f -> x -> x; - let one = f -> x -> f(x); - let succ = n -> f -> x -> f(n(f)(x)); - let add = m -> n -> f -> x -> m(f)(n(f)(x)); + final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow(""" + let zero = f -> x -> x; + let one = f -> x -> f(x); + let succ = n -> f -> x -> f(n(f)(x)); + let add = m -> n -> f -> x -> m(f)(n(f)(x)); - succ(add(one)(zero)) - """)); + succ(add(one)(zero)) + """)); - assertStructurallyEqual(lambda, arrow); + assertStructurallyEqual(lambda, arrow); - assertEquals(4, lambda.macros().size()); - assertEquals("zero", lambda.macros().get(0).name()); - assertEquals("one", lambda.macros().get(1).name()); - assertEquals("succ", lambda.macros().get(2).name()); - assertEquals("add", lambda.macros().get(3).name()); - } + assertEquals(4, lambda.macros().size()); + assertEquals("zero", lambda.macros().get(0).name()); + assertEquals("one", lambda.macros().get(1).name()); + assertEquals("succ", lambda.macros().get(2).name()); + assertEquals("add", lambda.macros().get(3).name()); + } - @Test - public void testOmegaCombinator() { - final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("(λx.x x)(λx.x x)")); - final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("(x -> x(x))(x -> x(x))")); + @Test + public void testOmegaCombinator() { + final LambdaProgram lambda = LambdaDriver.parse(SourceCode.ofLambda("(λx.x x)(λx.x x)")); + final LambdaProgram arrow = LambdaDriver.parse(SourceCode.ofArrow("(x -> x(x))(x -> x(x))")); - assertStructurallyEqual(lambda, arrow); - } + assertStructurallyEqual(lambda, arrow); + } - private static void assertStructurallyEqual(final LambdaProgram expected, final LambdaProgram actual) { - assertEquals(expected.macros().size(), actual.macros().size(), "Macro count mismatch"); - for (int i = 0; i < expected.macros().size(); i++) { - assertStructurallyEqual(expected.macros().get(i), actual.macros().get(i)); - } - assertStructurallyEqual(expected.expression(), actual.expression()); - } + private static void assertStructurallyEqual(final LambdaProgram expected, final LambdaProgram actual) { + assertEquals(expected.macros().size(), actual.macros().size(), "Macro count mismatch"); + for (int i = 0; i < expected.macros().size(); i++) { + assertStructurallyEqual(expected.macros().get(i), actual.macros().get(i)); + } + assertStructurallyEqual(expected.expression(), actual.expression()); + } - private static void assertStructurallyEqual(final Macro expected, final Macro actual) { - assertEquals(expected.name(), actual.name(), "Macro name mismatch"); - assertEquals(expected.comment().map(SourceComment::text), actual.comment().map(SourceComment::text), - "Macro comment mismatch"); - assertStructurallyEqual(expected.expression(), actual.expression()); - } + private static void assertStructurallyEqual(final Macro expected, final Macro actual) { + assertEquals(expected.name(), actual.name(), "Macro name mismatch"); + assertEquals(expected.comment().map(SourceComment::text), actual.comment().map(SourceComment::text), + "Macro comment mismatch"); + assertStructurallyEqual(expected.expression(), actual.expression()); + } - private static void assertStructurallyEqual(final Expression expected, final Expression actual) { - assertEquals(expected.getClass(), actual.getClass(), "Expression type mismatch"); - assertEquals(expected.comment().map(SourceComment::text), actual.comment().map(SourceComment::text), - "Expression comment mismatch"); + private static void assertStructurallyEqual(final Expression expected, final Expression actual) { + assertEquals(expected.getClass(), actual.getClass(), "Expression type mismatch"); + assertEquals(expected.comment().map(SourceComment::text), actual.comment().map(SourceComment::text), + "Expression comment mismatch"); - switch (expected) { - case IdentifierExpression e -> - assertEquals(e.name(), ((IdentifierExpression) actual).name(), "Identifier name mismatch"); - case AbstractionExpression e -> { - assertEquals(e.parameter(), ((AbstractionExpression) actual).parameter(), "Parameter mismatch"); - assertStructurallyEqual(e.body(), ((AbstractionExpression) actual).body()); - } - case ApplicationExpression e -> { - assertStructurallyEqual(e.applicable(), ((ApplicationExpression) actual).applicable()); - assertStructurallyEqual(e.argument(), ((ApplicationExpression) actual).argument()); - } - } - } + switch (expected) { + case IdentifierExpression e -> + assertEquals(e.name(), ((IdentifierExpression) actual).name(), "Identifier name mismatch"); + case AbstractionExpression e -> { + assertEquals(e.parameter(), ((AbstractionExpression) actual).parameter(), "Parameter mismatch"); + assertStructurallyEqual(e.body(), ((AbstractionExpression) actual).body()); + } + case ApplicationExpression e -> { + assertStructurallyEqual(e.applicable(), ((ApplicationExpression) actual).applicable()); + assertStructurallyEqual(e.argument(), ((ApplicationExpression) actual).argument()); + } + } + } } |
