1 /*******************************************************************************
2 * Copyright (c) 2000, 2011 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package org.eclipse.jdt.internal.corext.dom;
13 import org.eclipse.core.runtime.Assert;
15 import org.eclipse.jdt.core.dom.ASTNode;
16 import org.eclipse.jdt.core.dom.ASTVisitor;
17 import org.eclipse.jdt.core.dom.BodyDeclaration;
18 import org.eclipse.jdt.core.dom.FieldDeclaration;
19 import org.eclipse.jdt.core.dom.IVariableBinding;
20 import org.eclipse.jdt.core.dom.Initializer;
21 import org.eclipse.jdt.core.dom.MethodDeclaration;
22 import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
23 import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
26 public class LocalVariableIndex extends ASTVisitor {
28 private int fTopIndex;
31 * Computes the maximum number of local variable declarations in the
32 * given body declaration.
34 * @param declaration the body declaration. Must either be a method
35 * declaration, or an initializer, or a field declaration.
36 * @return the maximum number of local variables
38 public static int perform(BodyDeclaration declaration) {
39 Assert.isTrue(declaration != null);
40 switch (declaration.getNodeType()) {
41 case ASTNode.METHOD_DECLARATION:
42 case ASTNode.FIELD_DECLARATION:
43 case ASTNode.INITIALIZER:
44 return internalPerform(declaration);
46 throw new IllegalArgumentException(declaration.toString());
50 private static int internalPerform(BodyDeclaration methodOrInitializer) {
51 // we have to find the outermost method/initializer/field declaration since a local or anonymous
52 // type can reference final variables from the outer scope.
53 BodyDeclaration target= methodOrInitializer;
54 ASTNode parent= target.getParent();
55 while (parent != null) {
56 if (parent instanceof MethodDeclaration || parent instanceof Initializer || parent instanceof FieldDeclaration) {
57 target= (BodyDeclaration)parent;
59 parent= parent.getParent();
62 return doPerform(target);
65 private static int doPerform(BodyDeclaration node) {
66 LocalVariableIndex counter= new LocalVariableIndex();
68 return counter.fTopIndex;
72 public boolean visit(SingleVariableDeclaration node) {
73 handleVariableBinding(node.resolveBinding());
78 public boolean visit(VariableDeclarationFragment node) {
79 handleVariableBinding(node.resolveBinding());
83 private void handleVariableBinding(IVariableBinding binding) {
86 fTopIndex= Math.max(fTopIndex, binding.getVariableId());