Skip to content

Commit

Permalink
Added code for anonymous classes and guards in cases.
Browse files Browse the repository at this point in the history
  • Loading branch information
TwoOfTwelve committed Nov 18, 2023
1 parent 80069f0 commit c8d5786
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package de.jplag.java;

import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.SourcePositions;

/**
* Fixes the source positions, so that the end position is always at least the same as the start position.
*/
public class FixedSourcePositions implements SourcePositions {
private final SourcePositions base;

/**
* New instance
* @param base The source positions to use as the base
*/
public FixedSourcePositions(SourcePositions base) {
this.base = base;
}

@Override
public long getStartPosition(CompilationUnitTree compilationUnitTree, Tree tree) {
return this.base.getStartPosition(compilationUnitTree, tree);
}

@Override
public long getEndPosition(CompilationUnitTree compilationUnitTree, Tree tree) {
return Math.max(this.getStartPosition(compilationUnitTree, tree), this.base.getEndPosition(compilationUnitTree, tree));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void parseFiles(Set<File> files, final Parser parser) throws ParsingExcep
final CompilationTask task = javac.getTask(null, fileManager, listener,
List.of("-proc:none", "--enable-preview", "--release=" + JavaLanguage.JAVA_VERSION), null, javaFiles);
final Trees trees = Trees.instance(task);
final SourcePositions positions = trees.getSourcePositions();
final SourcePositions positions = new FixedSourcePositions(trees.getSourcePositions());
for (final CompilationUnitTree ast : executeCompilationTask(task, parser.logger)) {
File file = new File(ast.getSourceFile().toUri());
final LineMap map = ast.getLineMap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,23 @@ public Void visitSwitchExpression(SwitchExpressionTree node, Void unused) {
public Void visitCase(CaseTree node, Void unused) {
long start = positions.getStartPosition(ast, node);
addToken(JavaTokenType.J_CASE, start, 4, CodeSemantics.createControl());
return super.visitCase(node, null);

this.scan(node.getLabels(), null);
if (node.getGuard() != null) {
addToken(JavaTokenType.J_IF_BEGIN, positions.getStartPosition(ast, node.getGuard()), 0, CodeSemantics.createControl());
}
this.scan(node.getGuard(), null);
if (node.getCaseKind() == CaseTree.CaseKind.RULE) {
this.scan(node.getBody(), null);
} else {
this.scan(node.getStatements(), null);
}

if (node.getGuard() != null) {
addToken(JavaTokenType.J_IF_BEGIN, positions.getEndPosition(ast, node), 0, CodeSemantics.createControl());
}

return null;
}

@Override
Expand Down

0 comments on commit c8d5786

Please sign in to comment.