From 54b8d52b5962090b42390a21c7dfa0ebddafdb48 Mon Sep 17 00:00:00 2001 From: Knut Wannheden Date: Wed, 29 Nov 2023 10:00:06 +0100 Subject: [PATCH] Add `tryConsume()` helper method To avoid issues with unexpected tokens, it would be better if we would try to avoid using `sourceStartsWithAtCursor()`. As an alternative I added `tryConsume()` and `tryConsumeWithPrefix()`. --- .../internal/TypeScriptParserVisitor.java | 45 +++++++++++-------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java b/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java index 907adb91..c3284718 100644 --- a/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java +++ b/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java @@ -478,10 +478,10 @@ private void visitBinaryUpdateExpression(TSCNode incrementor, List JRightPadded padRight(T tree, @Nullable Space right, Markers mark } private JRightPadded maybeSemicolon(K2 k) { + return tryConsumeWithPrefix( + TSCSyntaxKind.SemicolonToken, + prefix -> new JRightPadded<>(k, prefix, Markers.EMPTY.add(new Semicolon(randomId()))) + ).orElseGet(() -> JRightPadded.build(k)); + } + + private boolean tryConsume(TSCSyntaxKind kind) { int saveCursor = getCursor(); - Space beforeSemi = whitespace(); - Semicolon semicolon = null; - if (sourceStartsWithAtCursor(";")) { - semicolon = new Semicolon(randomId()); - consumeToken(TSCSyntaxKind.SemicolonToken); + if (scan() == kind) { + return true; } else { - beforeSemi = EMPTY; - cursor(saveCursor); + cursorContext.resetScanner(saveCursor); + return false; } + } - JRightPadded padded = JRightPadded.build(k).withAfter(beforeSemi); - if (semicolon != null) { - padded = padded.withMarkers(padded.getMarkers().add(semicolon)); + private Optional tryConsumeWithPrefix(TSCSyntaxKind kind, Function whenMatched) { + int saveCursor = getCursor(); + Space prefix = whitespace(); + if (scan() == kind) { + return Optional.of(whenMatched.apply(prefix)); + } else { + cursorContext.resetScanner(saveCursor); + return Optional.empty(); } - - return padded; } private TSCSyntaxKind scan() { @@ -3282,9 +3290,8 @@ private JContainer mapContainer(TSCSyntaxKind open, List