diff --git a/src/main/java/dev/superice/gdparser/frontend/lowering/CstToAstMapper.java b/src/main/java/dev/superice/gdparser/frontend/lowering/CstToAstMapper.java index 5f5fcb3..45e9c20 100644 --- a/src/main/java/dev/superice/gdparser/frontend/lowering/CstToAstMapper.java +++ b/src/main/java/dev/superice/gdparser/frontend/lowering/CstToAstMapper.java @@ -71,6 +71,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.regex.Pattern; /// Maps GDScript CST nodes to a stable Java AST and emits lowering diagnostics. /// The lowered AST intentionally models GDScript 4.x only, so legacy 3.x syntax @@ -88,7 +89,7 @@ public final class CstToAstMapper { context.warn("Expected source root node but got: " + root.type(), root); } - var statements = context.mapStatements(root.namedChildren()); + var statements = context.mapStatements(context.significantNamedChildren(root)); var ast = new SourceFile(List.copyOf(statements), AstFactory.range(root.range())); return new AstMappingResult(ast, context.diagnostics()); } @@ -109,6 +110,11 @@ public final class CstToAstMapper { private static final class MappingContext { + /// The grammar models trailing `\` line continuations as named extra nodes, so they can + /// surface between the named children of any construct that spans a continued line. + private static final String LINE_CONTINUATION_TYPE = "line_continuation"; + private static final Pattern LINE_CONTINUATION_PATTERN = Pattern.compile("\\\\\\r?\\n"); + private final byte[] sourceBytes; private final List diagnostics; @@ -161,7 +167,7 @@ private void collectStructuralIssues(CstNodeView root) { } var statements = new ArrayList(); - for (var child : annotationsNode.namedChildren()) { + for (var child : significantNamedChildren(annotationsNode)) { if (child.type().equals("annotation")) { statements.add(mapAnnotationStatement(child)); } @@ -261,7 +267,7 @@ private void collectStructuralIssues(CstNodeView root) { var nameNode = node.childByField("name"); var bodyNode = requireField(node, "body"); var members = new ArrayList(); - for (var child : bodyNode.namedChildren()) { + for (var child : significantNamedChildren(bodyNode)) { if (child.type().equals("enumerator")) { members.add(mapEnumMember(child)); } @@ -344,7 +350,7 @@ private void collectStructuralIssues(CstNodeView root) { var elifClauses = new ArrayList(); Block elseBody = null; - for (var child : node.namedChildren()) { + for (var child : significantNamedChildren(node)) { if (child.type().equals("elif_clause")) { var elifCondition = requireField(child, "condition"); var elifBody = requireField(child, "body"); @@ -398,7 +404,7 @@ private void collectStructuralIssues(CstNodeView root) { var bodyNode = requireField(node, "body"); var sections = new ArrayList(); - for (var child : bodyNode.namedChildren()) { + for (var child : significantNamedChildren(bodyNode)) { if (child.type().equals("pattern_section")) { sections.add(mapMatchSection(child)); } @@ -412,7 +418,7 @@ private void collectStructuralIssues(CstNodeView root) { Expression guard = null; var patterns = new ArrayList(); - for (var child : sectionNode.namedChildren()) { + for (var child : significantNamedChildren(sectionNode)) { if (child == bodyNode) { continue; } @@ -483,7 +489,7 @@ private void collectStructuralIssues(CstNodeView root) { if (bodyNode == null) { return new Block(List.of(), fallbackRange); } - return new Block(mapStatements(bodyNode.namedChildren()), AstFactory.range(bodyNode.range())); + return new Block(mapStatements(significantNamedChildren(bodyNode)), AstFactory.range(bodyNode.range())); } private @NotNull Expression mapExpression(CstNodeView node) { @@ -576,7 +582,7 @@ private void collectStructuralIssues(CstNodeView root) { } private @NotNull AttributeExpression mapAttributeExpression(CstNodeView node) { - var namedChildren = node.namedChildren(); + var namedChildren = significantNamedChildren(node); if (namedChildren.isEmpty()) { error("attribute missing base expression", node); return new AttributeExpression( @@ -693,7 +699,7 @@ private void collectStructuralIssues(CstNodeView root) { private @NotNull ArrayExpression mapArrayExpression(CstNodeView node) { var elements = new ArrayList(); var openEnded = false; - for (var child : node.namedChildren()) { + for (var child : significantNamedChildren(node)) { if (child.type().equals("pattern_open_ending")) { openEnded = true; } else { @@ -707,7 +713,7 @@ private void collectStructuralIssues(CstNodeView root) { var entries = new ArrayList(); var openEnded = false; String lockedStyle = null; - for (var child : node.namedChildren()) { + for (var child : significantNamedChildren(node)) { if (child.type().equals("pair")) { var leftNode = child.childByField("left"); var valueNode = child.childByField("value"); @@ -789,7 +795,7 @@ private void collectStructuralIssues(CstNodeView root) { } var parameters = new ArrayList(); - for (var child : parametersNode.namedChildren()) { + for (var child : significantNamedChildren(parametersNode)) { parameters.add(mapParameter(child)); } return List.copyOf(parameters); @@ -872,7 +878,7 @@ yield new Parameter( return List.of(); } var arguments = new ArrayList(); - for (var child : argumentsNode.namedChildren()) { + for (var child : significantNamedChildren(argumentsNode)) { arguments.add(mapExpression(child)); } return List.copyOf(arguments); @@ -968,7 +974,7 @@ private boolean usesLegacySetgetKeyword(CstNodeView node) { } private @Nullable CstNodeView findNamedChildByType(CstNodeView node, String nodeType) { - for (var child : node.namedChildren()) { + for (var child : significantNamedChildren(node)) { if (child.type().equals(nodeType)) { return child; } @@ -986,12 +992,12 @@ private boolean usesLegacySetgetKeyword(CstNodeView node) { } private @Nullable CstNodeView firstNamedChild(CstNodeView node) { - var children = node.namedChildren(); + var children = significantNamedChildren(node); return children.isEmpty() ? null : children.getFirst(); } private @Nullable CstNodeView firstNamedChildExcluding(CstNodeView node, @Nullable CstNodeView excludedNode) { - for (var child : node.namedChildren()) { + for (var child : significantNamedChildren(node)) { if (child != excludedNode) { return child; } @@ -999,14 +1005,30 @@ private boolean usesLegacySetgetKeyword(CstNodeView node) { return null; } + private boolean isLineContinuation(CstNodeView node) { + return node.type().equals(LINE_CONTINUATION_TYPE); + } + + /// Named children with `line_continuation` extras removed. Continuations carry no + /// semantic meaning for the AST, so every child enumeration during lowering skips them. + private @NotNull List significantNamedChildren(CstNodeView node) { + var children = node.namedChildren(); + var filtered = new ArrayList(children.size()); + for (var child : children) { + if (!isLineContinuation(child)) { + filtered.add(child); + } + } + return filtered.size() == children.size() ? children : List.copyOf(filtered); + } + private @NotNull String operatorBetween(CstNodeView leftNode, CstNodeView rightNode, String fallback) { var start = Math.max(0, leftNode.range().endByte()); var end = Math.min(sourceBytes.length, rightNode.range().startByte()); if (start >= end) { return fallback; } - var operator = new String(sourceBytes, start, end - start, StandardCharsets.UTF_8).trim(); - return operator.isEmpty() ? fallback : operator; + return normalizeOperatorText(new String(sourceBytes, start, end - start, StandardCharsets.UTF_8), fallback); } private @NotNull String prefixOperator(CstNodeView node, CstNodeView operandNode, String fallback) { @@ -1015,7 +1037,13 @@ private boolean usesLegacySetgetKeyword(CstNodeView node) { if (start >= end) { return fallback; } - var operator = new String(sourceBytes, start, end - start, StandardCharsets.UTF_8).trim(); + return normalizeOperatorText(new String(sourceBytes, start, end - start, StandardCharsets.UTF_8), fallback); + } + + /// Recovers the operator from raw source text that may embed `\` line continuations, + /// then collapses whitespace so multi-word operators such as `is not` stay comparable. + private @NotNull String normalizeOperatorText(String rawText, String fallback) { + var operator = LINE_CONTINUATION_PATTERN.matcher(rawText).replaceAll("").replaceAll("\\s+", " ").trim(); return operator.isEmpty() ? fallback : operator; } diff --git a/src/test/java/dev/superice/gdparser/frontend/lowering/CstToAstMapperLineContinuationTest.java b/src/test/java/dev/superice/gdparser/frontend/lowering/CstToAstMapperLineContinuationTest.java new file mode 100644 index 0000000..3235491 --- /dev/null +++ b/src/test/java/dev/superice/gdparser/frontend/lowering/CstToAstMapperLineContinuationTest.java @@ -0,0 +1,183 @@ +package dev.superice.gdparser.frontend.lowering; + +import dev.superice.gdparser.frontend.ast.ArrayExpression; +import dev.superice.gdparser.frontend.ast.AssignmentExpression; +import dev.superice.gdparser.frontend.ast.AstDiagnosticSeverity; +import dev.superice.gdparser.frontend.ast.AstMappingResult; +import dev.superice.gdparser.frontend.ast.BinaryExpression; +import dev.superice.gdparser.frontend.ast.CallExpression; +import dev.superice.gdparser.frontend.ast.CastExpression; +import dev.superice.gdparser.frontend.ast.ExpressionStatement; +import dev.superice.gdparser.frontend.ast.FunctionDeclaration; +import dev.superice.gdparser.frontend.ast.IdentifierExpression; +import dev.superice.gdparser.frontend.ast.IfStatement; +import dev.superice.gdparser.frontend.ast.LiteralExpression; +import dev.superice.gdparser.frontend.ast.TypeTestExpression; +import dev.superice.gdparser.frontend.ast.VariableDeclaration; +import dev.superice.gdparser.infra.treesitter.GdParserFacade; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +/// Regression tests for lowering sources that use `\` line continuations. +/// The grammar emits `line_continuation` as a named extra node, so the mapper must +/// ignore it when enumerating children and when recovering operator source text. +class CstToAstMapperLineContinuationTest { + + private static GdParserFacade parserFacade; + private static CstToAstMapper mapper; + + @BeforeAll + static void setUp() { + parserFacade = GdParserFacade.withDefaultLanguage(); + mapper = new CstToAstMapper(); + } + + @Test + void binaryOperatorsShouldIgnoreLineContinuations() { + var result = map(""" + var sum = 1 + \\ + 2 + """); + + assertNoErrors(result); + var declaration = assertInstanceOf(VariableDeclaration.class, result.ast().statements().getFirst()); + var binary = assertInstanceOf(BinaryExpression.class, declaration.value()); + assertEquals("+", binary.operator()); + assertEquals("1", assertInstanceOf(LiteralExpression.class, binary.left()).sourceText()); + assertEquals("2", assertInstanceOf(LiteralExpression.class, binary.right()).sourceText()); + } + + @Test + void comparisonOperatorsShouldIgnoreLineContinuations() { + var result = map(""" + func check(a, b): + if a > \\ + b: + return a + return b + """); + + assertNoErrors(result); + var function = assertInstanceOf(FunctionDeclaration.class, result.ast().statements().getFirst()); + var ifStatement = assertInstanceOf(IfStatement.class, function.body().statements().getFirst()); + var condition = assertInstanceOf(BinaryExpression.class, ifStatement.condition()); + assertEquals(">", condition.operator()); + assertEquals("a", assertInstanceOf(IdentifierExpression.class, condition.left()).name()); + assertEquals("b", assertInstanceOf(IdentifierExpression.class, condition.right()).name()); + } + + @Test + void assignmentOperatorsShouldIgnoreLineContinuations() { + var result = map(""" + func assign(target): + var value = \\ + target + value = \\ + 42 + value += \\ + 1 + """); + + assertNoErrors(result); + var function = assertInstanceOf(FunctionDeclaration.class, result.ast().statements().getFirst()); + var body = function.body().statements(); + + var inferred = assertInstanceOf(VariableDeclaration.class, body.get(0)); + assertEquals("target", assertInstanceOf(IdentifierExpression.class, inferred.value()).name()); + + var plain = assertInstanceOf(AssignmentExpression.class, + assertInstanceOf(ExpressionStatement.class, body.get(1)).expression()); + assertEquals("=", plain.operator()); + assertEquals("42", assertInstanceOf(LiteralExpression.class, plain.right()).sourceText()); + + var augmented = assertInstanceOf(AssignmentExpression.class, + assertInstanceOf(ExpressionStatement.class, body.get(2)).expression()); + assertEquals("+=", augmented.operator()); + assertEquals("1", assertInstanceOf(LiteralExpression.class, augmented.right()).sourceText()); + } + + @Test + void isAndAsOperatorsShouldIgnoreLineContinuations() { + var result = map(""" + func convert(value): + var tested = value is \\ + int + var negated = value is not \\ + String + var casted = value as \\ + float + """); + + assertNoErrors(result); + var function = assertInstanceOf(FunctionDeclaration.class, result.ast().statements().getFirst()); + var body = function.body().statements(); + + var tested = assertInstanceOf(TypeTestExpression.class, + assertInstanceOf(VariableDeclaration.class, body.get(0)).value()); + assertFalse(tested.negated()); + assertEquals("int", tested.targetType().sourceText()); + + var negated = assertInstanceOf(TypeTestExpression.class, + assertInstanceOf(VariableDeclaration.class, body.get(1)).value()); + assertEquals(true, negated.negated()); + assertEquals("String", negated.targetType().sourceText()); + + var casted = assertInstanceOf(CastExpression.class, + assertInstanceOf(VariableDeclaration.class, body.get(2)).value()); + assertEquals("float", casted.targetType().sourceText()); + } + + @Test + void callArgumentsShouldIgnoreLineContinuations() { + var result = map(""" + func call(): + foo(1, \\ + 2, 3) + """); + + assertNoErrors(result); + var function = assertInstanceOf(FunctionDeclaration.class, result.ast().statements().getFirst()); + var statement = assertInstanceOf(ExpressionStatement.class, function.body().statements().getFirst()); + var call = assertInstanceOf(CallExpression.class, statement.expression()); + assertEquals(3, call.arguments().size()); + assertEquals("1", assertInstanceOf(LiteralExpression.class, call.arguments().get(0)).sourceText()); + assertEquals("2", assertInstanceOf(LiteralExpression.class, call.arguments().get(1)).sourceText()); + assertEquals("3", assertInstanceOf(LiteralExpression.class, call.arguments().get(2)).sourceText()); + } + + @Test + void arrayElementsShouldIgnoreLineContinuations() { + var result = map(""" + var values = [1, \\ + 2, \\ + 3] + """); + + assertNoErrors(result); + var declaration = assertInstanceOf(VariableDeclaration.class, result.ast().statements().getFirst()); + var array = assertInstanceOf(ArrayExpression.class, declaration.value()); + assertEquals(3, array.elements().size()); + assertEquals("1", assertInstanceOf(LiteralExpression.class, array.elements().get(0)).sourceText()); + assertEquals("2", assertInstanceOf(LiteralExpression.class, array.elements().get(1)).sourceText()); + assertEquals("3", assertInstanceOf(LiteralExpression.class, array.elements().get(2)).sourceText()); + } + + private static void assertNoErrors(AstMappingResult result) { + assertFalse(result.diagnostics().stream() + .anyMatch(diagnostic -> diagnostic.severity() == AstDiagnosticSeverity.ERROR), + () -> "Unexpected errors: " + result.diagnostics()); + assertEquals(0, result.diagnostics().stream() + .filter(diagnostic -> diagnostic.severity() == AstDiagnosticSeverity.WARNING) + .count(), + () -> "Unexpected warnings: " + result.diagnostics()); + } + + private static AstMappingResult map(String source) { + var root = parserFacade.parseCstRoot(source); + return mapper.map(source, root); + } +}