use of groovy.lang.Tuple2 in project groovy by apache.
the class AstBuilder method visitSwitchBlockStatementGroup.
@Override
@SuppressWarnings("unchecked")
public List<Statement> visitSwitchBlockStatementGroup(final SwitchBlockStatementGroupContext ctx) {
int labelCnt = ctx.switchLabel().size();
List<Token> firstLabelHolder = new ArrayList<>(1);
return (List<Statement>) ctx.switchLabel().stream().map(e -> (Object) this.visitSwitchLabel(e)).reduce(new ArrayList<Statement>(4), (r, e) -> {
List<Statement> statementList = (List<Statement>) r;
Tuple2<Token, Expression> tuple = (Tuple2<Token, Expression>) e;
boolean isLast = labelCnt - 1 == statementList.size();
switch(tuple.getV1().getType()) {
case CASE:
{
if (!asBoolean(statementList)) {
firstLabelHolder.add(tuple.getV1());
}
statementList.add(configureAST(new CaseStatement(tuple.getV2(), // check whether processing the last label. if yes, block statement should be attached.
isLast ? this.visitBlockStatements(ctx.blockStatements()) : EmptyStatement.INSTANCE), firstLabelHolder.get(0)));
break;
}
case DEFAULT:
{
BlockStatement blockStatement = this.visitBlockStatements(ctx.blockStatements());
blockStatement.putNodeMetaData(IS_SWITCH_DEFAULT, true);
statementList.add(// this.configureAST(blockStatement, tuple.getKey())
blockStatement);
break;
}
}
return statementList;
});
}
use of groovy.lang.Tuple2 in project groovy by apache.
the class GenericsUtils method parameterizeSAM.
/**
* Gets the parameter and return types of the abstract method of SAM.
*
* If the abstract method is not parameterized, we will get generics placeholders, e.g. T, U
* For example, the abstract method of {@link java.util.function.Function} is
* <pre>
* R apply(T t);
* </pre>
*
* We parameterize the above interface as {@code Function<String, Integer>}, then the abstract method will be
* <pre>
* Integer apply(String t);
* </pre>
*
* When we call {@code parameterizeSAM} on the ClassNode {@code Function<String, Integer>},
* we can get parameter types and return type of the above abstract method,
* i.e. ClassNode {@code ClassHelper.STRING_TYPE} and {@code ClassHelper.Integer_TYPE}
*
* @param samType the class node which contains only one abstract method
*
* @since 3.0.0
*/
public static Tuple2<ClassNode[], ClassNode> parameterizeSAM(final ClassNode samType) {
MethodNode abstractMethod = ClassHelper.findSAM(samType);
Map<GenericsType, GenericsType> generics = makeDeclaringAndActualGenericsTypeMapOfExactType(abstractMethod.getDeclaringClass(), samType);
Function<ClassNode, ClassNode> resolver = t -> {
if (t.isGenericsPlaceHolder()) {
return findActualTypeByGenericsPlaceholderName(t.getUnresolvedName(), generics);
}
return t;
};
ClassNode[] parameterTypes = Arrays.stream(abstractMethod.getParameters()).map(Parameter::getType).map(resolver).toArray(ClassNode[]::new);
ClassNode returnType = resolver.apply(abstractMethod.getReturnType());
return tuple(parameterTypes, returnType);
}
use of groovy.lang.Tuple2 in project groovy by apache.
the class Node method breadthFirstRest.
private void breadthFirstRest(boolean preorder, int level, Closure c) {
Stack<Tuple2<Object, Integer>> stack = new Stack<Tuple2<Object, Integer>>();
List nextLevelChildren = preorder ? getDirectChildren() : DefaultGroovyMethods.reverse(getDirectChildren());
while (!nextLevelChildren.isEmpty()) {
List working = new NodeList(nextLevelChildren);
nextLevelChildren = new NodeList();
for (Object child : working) {
if (preorder) {
callClosureForNode(c, child, level);
} else {
stack.push(new Tuple2<Object, Integer>(child, level));
}
if (child instanceof Node) {
Node childNode = (Node) child;
List children = childNode.getDirectChildren();
if (children.size() > 1 || (children.size() == 1 && !(children.get(0) instanceof String)))
nextLevelChildren.addAll(preorder ? children : DefaultGroovyMethods.reverse(children));
}
}
level++;
}
while (!stack.isEmpty()) {
Tuple2<Object, Integer> next = stack.pop();
callClosureForNode(c, next.getV1(), next.getV2());
}
}
use of groovy.lang.Tuple2 in project groovy by apache.
the class ASTTransformationVisitor method visitClass.
/**
* Main loop entry.
* <p>
* First, it delegates to the super visitClass so we can collect the
* relevant annotations in an AST tree walk.
* <p>
* Second, it calls the visit method on the transformation for each relevant
* annotation found.
*
* @param classNode the class to visit
*/
@Override
public void visitClass(ClassNode classNode) {
// only descend if we have annotations to look for
Map<Class<? extends ASTTransformation>, Set<ASTNode>> baseTransforms = classNode.getTransforms(phase);
if (!baseTransforms.isEmpty()) {
final Map<Class<? extends ASTTransformation>, ASTTransformation> transformInstances = new HashMap<Class<? extends ASTTransformation>, ASTTransformation>();
for (Class<? extends ASTTransformation> transformClass : baseTransforms.keySet()) {
try {
transformInstances.put(transformClass, transformClass.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
source.getErrorCollector().addError(new SimpleMessage("Could not instantiate Transformation Processor " + transformClass, // + " declared by " + annotation.getClassNode().getName(),
source));
}
}
// invert the map, is now one to many
transforms = new HashMap<ASTNode, List<ASTTransformation>>();
for (Map.Entry<Class<? extends ASTTransformation>, Set<ASTNode>> entry : baseTransforms.entrySet()) {
for (ASTNode node : entry.getValue()) {
List<ASTTransformation> list = transforms.computeIfAbsent(node, k -> new ArrayList<>());
list.add(transformInstances.get(entry.getKey()));
}
}
targetNodes = new LinkedList<ASTNode[]>();
// first pass, collect nodes
super.visitClass(classNode);
// second pass, call visit on all of the collected nodes
List<Tuple2<ASTTransformation, ASTNode[]>> tuples = new ArrayList<>();
for (ASTNode[] node : targetNodes) {
for (ASTTransformation snt : transforms.get(node[0])) {
tuples.add(new Tuple2<>(snt, node));
}
}
tuples.sort(priorityComparator);
for (Tuple2<ASTTransformation, ASTNode[]> tuple : tuples) {
if (tuple.getV1() instanceof CompilationUnitAware) {
((CompilationUnitAware) tuple.getV1()).setCompilationUnit(context.getCompilationUnit());
}
tuple.getV1().visit(tuple.getV2(), source);
}
}
}
use of groovy.lang.Tuple2 in project groovy by apache.
the class SmartDocumentFilter method findTokensToRender.
private List<Token> findTokensToRender(List<Token> tokenList) {
final Tuple2<Integer, Integer> renderRange = getRenderRange();
if (null != renderRange) {
long startLine = lineNumber(renderRange.getV1());
long stopLine = lineNumber(renderRange.getV2());
// should never happen
if (startLine < 0 || stopLine < 0)
return tokenList;
return tokenList.stream().filter(e -> e.getLine() >= startLine && PositionConfigureUtils.endPosition(e).getV1() <= stopLine).collect(Collectors.toList());
}
List<Token> tmpLatestTokenList = filterNewlines(this.latestTokenList);
int latestTokenListSize = tmpLatestTokenList.size();
if (0 == latestTokenListSize) {
return tokenList;
}
List<Token> tmpTokenList = filterNewlines(tokenList);
int tmpTokenListSize = tmpTokenList.size();
if (0 == tmpTokenListSize) {
return tokenList;
}
int startTokenIndex = 0;
int minSize = Math.min(tmpTokenListSize, latestTokenListSize);
for (int i = 0; i < minSize; i++) {
Token token = tmpTokenList.get(i);
Token latestToken = tmpLatestTokenList.get(i);
if (token.getType() == latestToken.getType() && token.getStartIndex() == latestToken.getStartIndex() && token.getStopIndex() == latestToken.getStopIndex()) {
continue;
}
startTokenIndex = i;
break;
}
List<Token> newTokenList = new ReversedList<>(tmpTokenList);
List<Token> newLatestTokenList = new ReversedList<>(tmpLatestTokenList);
int stopTokenIndex = tmpTokenListSize;
Token lastToken = newTokenList.get(0);
Token lastLatestToken = newLatestTokenList.get(0);
for (int i = 0; i < minSize; i++) {
Token token = newTokenList.get(i);
Token latestToken = newLatestTokenList.get(i);
if ((token.getType() == latestToken.getType()) && (token.getStartIndex() - lastToken.getStartIndex()) == (latestToken.getStartIndex() - lastLatestToken.getStartIndex()) && ((token.getStopIndex() - lastToken.getStopIndex()) == (latestToken.getStopIndex() - lastLatestToken.getStopIndex()))) {
continue;
}
stopTokenIndex = tmpTokenListSize - i;
break;
}
if (startTokenIndex == stopTokenIndex) {
return tmpTokenListSize != latestTokenListSize ? tokenList : Collections.emptyList();
} else if (startTokenIndex < stopTokenIndex) {
return tmpTokenList.subList(startTokenIndex, stopTokenIndex);
}
// should never reach here. If unexpected error occurred, it's better to render all tokens
return tokenList;
}
Aggregations