org.codehaus.groovy.ast.VariableScope Java Examples

The following examples show how to use org.codehaus.groovy.ast.VariableScope. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReturnAdder.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Statement adjustSwitchCaseCode(final Statement statement, final VariableScope scope, final boolean defaultCase) {
    if (statement instanceof BlockStatement) {
        List<Statement> statements = ((BlockStatement) statement).getStatements();
        if (!statements.isEmpty()) {
            int lastIndex = statements.size() - 1;
            Statement last = statements.get(lastIndex);
            if (last instanceof BreakStatement) {
                if (doAdd) {
                    statements.remove(lastIndex);
                    return addReturnsIfNeeded(statement, scope);
                } else {
                    BlockStatement newBlock = new BlockStatement();
                    for (int i = 0; i < lastIndex; i += 1) {
                        newBlock.addStatement(statements.get(i));
                    }
                    return addReturnsIfNeeded(newBlock, scope);
                }
            } else if (defaultCase) {
                return addReturnsIfNeeded(statement, scope);
            }
        }
    }
    return statement;
}
 
Example #2
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_add_to_overriden_variables_a_variable_declared_and_already_in_the_process_scope() throws Exception {
    final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);
    Map<String, ScriptVariable> context = new HashMap<String, ScriptVariable>();
    context.put("declaredVar", null);
    when(groovyCompilationUnit.getContext()).thenReturn(context);
    
    final List<Statement> statements = new ArrayList<Statement>();
    statements.add(new ExpressionStatement(
            new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something"))));
    statements.add(new ReturnStatement(new VariableExpression("declaredVar")));
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("declaredVar"));
    final BlockStatement blockStatement = new BlockStatement(statements, variableScope);

    when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
    final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit);

    unknownElementsIndexer.run(new NullProgressMonitor());

    assertThat(unknownElementsIndexer.getOverridenVariables()).containsExactly(entry("declaredVar", new Position(0)));
}
 
Example #3
Source File: AutoNewLineTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitClosureExpression(final ClosureExpression expression) {
    super.visitClosureExpression(expression);
    if (inBuilderMethod) {
        Statement oldCode = expression.getCode();
        BlockStatement block = oldCode instanceof BlockStatement?
                ((BlockStatement)oldCode):
                new BlockStatement(Collections.singletonList(oldCode), new VariableScope());
        List<Statement> statements = block.getStatements();
        if (!statements.isEmpty()) {
            Statement first = statements.get(0);
            Statement last = statements.get(statements.size()-1);
            if (expression.getLineNumber()<first.getLineNumber()) {
                // there's a new line between { -> ... and the first statement
                statements.add(0,createNewLine(expression));
            }
            if (expression.getLastLineNumber()>last.getLastLineNumber()) {
                // there's a new line between { -> ... and the first statement
                statements.add(createNewLine(expression));
            }
        }
        expression.setCode(block);
    }
}
 
Example #4
Source File: CompletionProvider.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
private void populateItemsFromVariableScope(VariableScope variableScope, String memberNamePrefix,
		Set<String> existingNames, List<CompletionItem> items) {
	List<CompletionItem> variableItems = variableScope.getDeclaredVariables().values().stream().filter(variable -> {

		String variableName = variable.getName();
		//overloads can cause duplicates
		if (variableName.startsWith(memberNamePrefix) && !existingNames.contains(variableName)) {
			existingNames.add(variableName);
			return true;
		}
		return false;
	}).map(variable -> {
		CompletionItem item = new CompletionItem();
		item.setLabel(variable.getName());
		item.setKind(GroovyLanguageServerUtils.astNodeToCompletionItemKind((ASTNode) variable));
		return item;
	}).collect(Collectors.toList());
	items.addAll(variableItems);
}
 
Example #5
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_not_add_to_unknonwn_variables_a_variable_declared_but_not_in_the_process_scope() throws Exception {
    final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);

    final List<Statement> statements = new ArrayList<Statement>();
    statements.add(new ExpressionStatement(
            new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something"))));
    statements.add(new ReturnStatement(new VariableExpression("declaredVar")));
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("declaredVar"));
    final BlockStatement blockStatement = new BlockStatement(statements, variableScope);

    when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
    final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit);

    unknownElementsIndexer.run(new NullProgressMonitor());

    assertThat(unknownElementsIndexer.getUnknownVaraibles()).isEmpty();
}
 
Example #6
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_add_to_unknonwn_variables_a_variable_not_declared_and_not_in_the_process_scope() throws Exception {
    final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);

    final List<Statement> statements = new ArrayList<Statement>();
    statements.add(new ReturnStatement(new VariableExpression("unkownVariable")));
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("unkownVariable"));
    final BlockStatement blockStatement = new BlockStatement(statements, variableScope);

    when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
    final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer( groovyCompilationUnit);

    unknownElementsIndexer.run(new NullProgressMonitor());

    assertThat(unknownElementsIndexer.getUnknownVaraibles()).containsExactly("unkownVariable");
}
 
Example #7
Source File: TestGroovyScriptUtil.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
public static Map<String, Serializable> createVariablesMap(final GroovyCompilationUnit unit, final List<ScriptVariable> nodes) {
    Map<String, Serializable> result = new HashMap<String, Serializable>();
    final VariableScope scope = GroovyDocumentUtil.getVariableScope(unit);
    initializeVariableTypes(unit, scope, result, nodes);// Add process and untyped variable to scope

    final Set<String> keys = result.keySet();
    final List<String> orderedKeys = new ArrayList<String>(keys);

    Collections.sort(orderedKeys);

    final Map<String, Serializable> orderedVariableMap = new LinkedHashMap<String, Serializable>();
    for (final String key : orderedKeys) {
        orderedVariableMap.put(key, result.get(key));
    }

    result = orderedVariableMap;
    return result;
}
 
Example #8
Source File: GroovyDocumentUtil.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public static void addToVariableScope(GroovyCompilationUnit unit, List<FieldNode> nodes) {
    VariableScope scope = getVariableScope(unit);

    while (scope != null) {
        for (FieldNode f : nodes) {
            scope.putDeclaredVariable(f);
        }
        scope = scope.getParent();
    }
}
 
Example #9
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void declare(final Variable variable, final ASTNode context) {
    String scopeType = "scope";
    String variableType = "variable";

    if (context.getClass() == FieldNode.class) {
        scopeType = "class";
        variableType = "field";
    } else if (context.getClass() == PropertyNode.class) {
        scopeType = "class";
        variableType = "property";
    }

    StringBuilder msg = new StringBuilder();
    msg.append("The current ").append(scopeType);
    msg.append(" already contains a ").append(variableType);
    msg.append(" of the name ").append(variable.getName());

    if (currentScope.getDeclaredVariable(variable.getName()) != null) {
        addError(msg.toString(), context);
        return;
    }

    for (VariableScope scope = currentScope.getParent(); scope != null; scope = scope.getParent()) {
        // if we are in a class and no variable is declared until
        // now, then we can break the loop, because we are allowed
        // to declare a variable of the same name as a class member
        if (scope.getClassScope() != null && !isAnonymous(scope.getClassScope())) break;

        if (scope.getDeclaredVariable(variable.getName()) != null) {
            // variable already declared
            addError(msg.toString(), context);
            break;
        }
    }
    // declare the variable even if there was an error to allow more checks
    currentScope.putDeclaredVariable(variable);
}
 
Example #10
Source File: ClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Parameter[] getClosureSharedVariables(final ClosureExpression ce) {
    VariableScope scope = ce.getVariableScope();
    Parameter[] ret = new Parameter[scope.getReferencedLocalVariablesCount()];
    int index = 0;
    for (Iterator<Variable> iter = scope.getReferencedLocalVariablesIterator(); iter.hasNext();) {
        Variable element = iter.next();
        Parameter p = new Parameter(element.getType(), element.getName());
        p.setOriginType(element.getOriginType());
        p.setClosureSharedVariable(element.isClosureSharedVariable());
        ret[index] = p;
        index++;
    }
    return ret;
}
 
Example #11
Source File: CompileStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * initializes this class for a MethodNode. This method will
 * automatically define variables for the method parameters
 * and will create references if needed.  The created variables
 * can be accessed by calling getVariable().
 *
 */
public void init(final VariableScope scope, final Parameter[] parameters) {
    if (!clear) throw new GroovyBugError("CompileStack#init called without calling clear before");
    clear = false;
    pushVariableScope(scope);
    defineMethodVariables(parameters, scope.isInStaticContext());
    this.className = BytecodeHelper.getTypeDescription(controller.getClassNode());
}
 
Example #12
Source File: CompileStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Causes the state-stack to add an element and sets
 * the given scope as new current variable scope. Creates
 * a element for the state stack so pop has to be called later
 */
public void pushVariableScope(final VariableScope scope) {
    pushState();
    this.scope = scope;
    superBlockNamedLabels = new HashMap<>(superBlockNamedLabels);
    superBlockNamedLabels.putAll(currentBlockNamedLabels);
    currentBlockNamedLabels = new HashMap<>();
}
 
Example #13
Source File: CompileStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Should be called when descending into a loop that defines
 * also a scope. Calls pushVariableScope and prepares labels
 * for a loop structure. Creates a element for the state stack
 * so pop has to be called later, TODO: @Deprecate
 */
public void pushLoop(final VariableScope scope, final String labelName) {
    pushVariableScope(scope);
    continueLabel = new Label();
    breakLabel = new Label();
    if (labelName != null) {
        initLoopLabels(labelName);
    }
}
 
Example #14
Source File: CompileStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Should be called when descending into a loop that defines
 * also a scope. Calls pushVariableScope and prepares labels
 * for a loop structure. Creates a element for the state stack
 * so pop has to be called later
 */
public void pushLoop(final VariableScope el, final List<String> labelNames) {
    pushVariableScope(el);
    continueLabel = new Label();
    breakLabel = new Label();
    if (labelNames != null) {
        for (String labelName : labelNames) {
            initLoopLabels(labelName);
        }
    }
}
 
Example #15
Source File: TestGroovyScriptUtil.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private static void initializeVariableTypes(final GroovyCompilationUnit unit, final VariableScope scope, final Map<String, Serializable> variableMap,
        final List<ScriptVariable> nodes) {
    final VariablesVisitor variablesVisitor = new VariablesVisitor(scope);
    unit.getModuleNode().getStatementBlock().visit(variablesVisitor);
    for (final String variable : variablesVisitor.getVariableExpressions()) {
        final ScriptVariable processVariable = getProcessVariable(variable, nodes);
        if (processVariable != null) {
            String typeName = processVariable.getType();
            typeName = typeName.substring(typeName.lastIndexOf('.') + 1, typeName.length());
            if (typeName.equals(ActivityInstance.class.getSimpleName()) || typeName.equals(ProcessInstance.class.getSimpleName())
                    || typeName.equals(ProcessDefinition.class.getSimpleName())) {

            } else if (TYPES.contains(typeName)) {
                variableMap.put(variable, typeName);
            } else {
                final List<String> typeValues = org.bonitasoft.studio.groovy.GroovyUtil.getTypeValues(typeName);
                if (typeValues != null
                        && !typeValues.isEmpty()) {
                    variableMap.put(variable, LIST);
                } else {
                    variableMap.put(variable, OBJECT);
                }
            }
        } else if (!variablesVisitor.getDeclaredExpressions().keySet().contains(variable)) {// Not a process variable (set default type as Object)
            final List<String> declaredMethods = GroovyDocumentUtil.getDeclaredMethodsName(unit);
            if (!declaredMethods.contains(variable)
                    && !variable.equals("DefaultGroovyMethods") && !GroovyDocumentUtil.getDefaultMethodsName().contains(variable)) { //$NON-NLS-1$
                if (!PROVIDED_VARIABLES.contains(variable)) {
                    variableMap.put(variable, OBJECT);
                }
            }
        }
    }
}
 
Example #16
Source File: VariablesVisitorTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_add_a_variable_present_as_a_decalred_variable_in_the_scope() throws Exception {
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("aData"));

    final VariablesVisitor variablesVisitor = new VariablesVisitor(variableScope);
    variablesVisitor.visitVariableExpression(new VariableExpression("aData"));

    assertThat(variablesVisitor.getVariableExpressions()).containsExactly("aData");
}
 
Example #17
Source File: VariablesVisitorTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_add_a_variable_present_as_a_referenced_calss_variable_in_the_scope() throws Exception {
    final VariableScope variableScope = new VariableScope();
    variableScope.putReferencedClassVariable(new VariableExpression("aData"));

    final VariablesVisitor variablesVisitor = new VariablesVisitor(variableScope);
    variablesVisitor.visitVariableExpression(new VariableExpression("aData"));

    assertThat(variablesVisitor.getVariableExpressions()).containsExactly("aData");
}
 
Example #18
Source File: VariablesVisitorTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_not_add_a_variable_not_in_the_scope() throws Exception {
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("aData"));

    final VariablesVisitor variablesVisitor = new VariablesVisitor(variableScope);
    variablesVisitor.visitVariableExpression(new VariableExpression("varaibleNotInScope"));

    assertThat(variablesVisitor.getVariableExpressions()).isEmpty();
}
 
Example #19
Source File: VariablesVisitorTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_add_decalred_expression_with_position() throws Exception {
    final VariablesVisitor variablesVisitor = new VariablesVisitor(new VariableScope());

    final DeclarationExpression declarationExpression = new DeclarationExpression(new VariableExpression("myVar"), Token.NULL,
            new VariableExpression("anotherVar"));
    declarationExpression.setStart(42);
    variablesVisitor.visitDeclarationExpression(declarationExpression);

    assertThat(variablesVisitor.getDeclaredExpressions()).containsExactly(entry("myVar", new Position(42)));
}
 
Example #20
Source File: FieldASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void adjustToClassVar(VariableExpression expr) {
    // we only need to check the variable name because the Groovy compiler
    // already fails if a variable with the same name already exists in the scope.
    // this means that a closure cannot shadow a class variable
    expr.setAccessedVariable(fieldNode);
    final VariableScope variableScope = currentClosure.getVariableScope();
    final Iterator<Variable> iterator = variableScope.getReferencedLocalVariablesIterator();
    while (iterator.hasNext()) {
        Variable next = iterator.next();
        if (next.getName().equals(variableName)) iterator.remove();
    }
    variableScope.putReferencedClassVariable(fieldNode);
}
 
Example #21
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void createCloneSerialization(ClassNode cNode) {
    final BlockStatement body = new BlockStatement();
    // def baos = new ByteArrayOutputStream()
    final Expression baos = localVarX("baos");
    body.addStatement(declS(baos, ctorX(BAOS_TYPE)));

    // baos.withObjectOutputStream{ it.writeObject(this) }
    MethodCallExpression writeObject = callX(castX(OOS_TYPE, varX("it")), "writeObject", varX("this"));
    writeObject.setImplicitThis(false);
    ClosureExpression writeClos = closureX(block(stmt(writeObject)));
    writeClos.setVariableScope(new VariableScope());
    body.addStatement(stmt(callX(baos, "withObjectOutputStream", args(writeClos))));

    // def bais = new ByteArrayInputStream(baos.toByteArray())
    final Expression bais = localVarX("bais");
    body.addStatement(declS(bais, ctorX(BAIS_TYPE, args(callX(baos, "toByteArray")))));

    // return bais.withObjectInputStream(getClass().classLoader){ (<type>) it.readObject() }
    MethodCallExpression readObject = callX(castX(OIS_TYPE, varX("it")), "readObject");
    readObject.setImplicitThis(false);
    ClosureExpression readClos = closureX(block(stmt(castX(GenericsUtils.nonGeneric(cNode), readObject))));
    readClos.setVariableScope(new VariableScope());
    Expression classLoader = callX(callThisX("getClass"), "getClassLoader");
    body.addStatement(returnS(callX(bais, "withObjectInputStream", args(classLoader, readClos))));

    new VariableScopeVisitor(sourceUnit, true).visitClass(cNode);
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, body);
}
 
Example #22
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitBlockStatement(final BlockStatement block) {
    VariableScope oldScope = currentScope;
    currentScope = block.getVariableScope();
    super.visitBlockStatement(block);
    currentScope = oldScope;
}
 
Example #23
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
    VariableScope oldScope = currentScope;
    currentScope = node.getVariableScope();
    Map<GenericsTypeName, GenericsType> oldPNames = genericParameterNames;
    genericParameterNames = node.isStatic() && !Traits.isTrait(node.getDeclaringClass())
            ? new HashMap<>() : new HashMap<>(genericParameterNames);

    resolveGenericsHeader(node.getGenericsTypes());

    Parameter[] paras = node.getParameters();
    for (Parameter p : paras) {
        p.setInitialExpression(transform(p.getInitialExpression()));
        resolveOrFail(p.getType(), p.getType());
        visitAnnotations(p);
    }
    ClassNode[] exceptions = node.getExceptions();
    for (ClassNode t : exceptions) {
        resolveOrFail(t, node);
    }
    resolveOrFail(node.getReturnType(), node);

    MethodNode oldCurrentMethod = currentMethod;
    currentMethod = node;
    super.visitConstructorOrMethod(node, isConstructor);

    currentMethod = oldCurrentMethod;
    genericParameterNames = oldPNames;
    currentScope = oldScope;
}
 
Example #24
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethod(MethodNode methodNode) {
    VariableScope variableScope = methodNode.getVariableScope();

    if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
        addMethodOccurrences(methodNode, (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset));
    } else {
        if (leaf instanceof Variable) {
            String name = ((Variable) leaf).getName();
            // This check is here because we can have method parameter with the same
            // name hidding property/field and we don't want to show occurences of these
            if (variableScope != null && variableScope.getDeclaredVariable(name) != null) {
                return;
            }
        } else if (leaf instanceof MethodNode) {
            if (Methods.isSameMethod(methodNode, (MethodNode) leaf)) {
                occurrences.add(methodNode);
            }
        } else if (leaf instanceof DeclarationExpression) {
            VariableExpression variable = ((DeclarationExpression) leaf).getVariableExpression();
            if (!variable.isDynamicTyped() && !methodNode.isDynamicReturnType()) {
                addMethodOccurrences(methodNode, variable.getType());
            }
        } else if (leaf instanceof ConstantExpression && leafParent instanceof MethodCallExpression) {
            MethodCallExpression methodCallExpression = (MethodCallExpression) leafParent;
            if (Methods.isSameMethod(methodNode, methodCallExpression)) {
                occurrences.add(methodNode);
            }
        }
    }
    super.visitMethod(methodNode);
}
 
Example #25
Source File: VariablesVisitor.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
public VariablesVisitor(final VariableScope variableScope) {
    this.variableScope = variableScope;
}
 
Example #26
Source File: ScopeVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void addCreator(String path, Expression expression) {
    ClosureExpression wrappingClosure = new ClosureExpression(new Parameter[0], new ExpressionStatement(expression));
    wrappingClosure.setVariableScope(new VariableScope());
    addCreator(path, wrappingClosure);
}
 
Example #27
Source File: CompileStack.java    From groovy with Apache License 2.0 4 votes vote down vote up
public VariableScope getScope() {
    return scope;
}
 
Example #28
Source File: ClosureWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected ClassNode createClosureClass(final ClosureExpression expression, final int modifiers) {
    ClassNode classNode = controller.getClassNode();
    ClassNode outerClass = controller.getOutermostClass();
    String name = genClosureClassName();
    boolean staticMethodOrInStaticClass = controller.isStaticMethod() || classNode.isStaticClass();

    Parameter[] parameters = expression.getParameters();
    if (parameters == null) {
        parameters = Parameter.EMPTY_ARRAY;
    } else if (parameters.length == 0) {
        // let's create a default 'it' parameter
        Parameter it = new Parameter(ClassHelper.OBJECT_TYPE, "it", ConstantExpression.NULL);
        parameters = new Parameter[]{it};
        Variable ref = expression.getVariableScope().getDeclaredVariable("it");
        if (ref!=null) it.setClosureSharedVariable(ref.isClosureSharedVariable());
    }

    Parameter[] localVariableParams = getClosureSharedVariables(expression);
    removeInitialValues(localVariableParams);

    InnerClassNode answer = new InnerClassNode(classNode, name, modifiers, ClassHelper.CLOSURE_TYPE.getPlainNodeReference());
    answer.setEnclosingMethod(controller.getMethodNode());
    answer.setSynthetic(true);
    answer.setUsingGenerics(outerClass.isUsingGenerics());
    answer.setSourcePosition(expression);

    if (staticMethodOrInStaticClass) {
        answer.setStaticClass(true);
    }
    if (controller.isInScriptBody()) {
        answer.setScriptBody(true);
    }
    MethodNode method =
            answer.addMethod("doCall", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, expression.getCode());
    method.setSourcePosition(expression);

    VariableScope varScope = expression.getVariableScope();
    if (varScope == null) {
        throw new RuntimeException(
                "Must have a VariableScope by now! for expression: " + expression + " class: " + name);
    } else {
        method.setVariableScope(varScope.copy());
    }
    if (parameters.length > 1
            || (parameters.length == 1
            && parameters[0].getType() != null
            && parameters[0].getType() != ClassHelper.OBJECT_TYPE
            && !ClassHelper.OBJECT_TYPE.equals(parameters[0].getType().getComponentType())))
    {

        // let's add a typesafe call method
        MethodNode call = answer.addMethod(
                "call",
                ACC_PUBLIC,
                ClassHelper.OBJECT_TYPE,
                parameters,
                ClassNode.EMPTY_ARRAY,
                new ReturnStatement(
                        new MethodCallExpression(
                                VariableExpression.THIS_EXPRESSION,
                                "doCall",
                                new ArgumentListExpression(parameters))));
        call.setSourcePosition(expression);
    }

    // let's make the constructor
    BlockStatement block = createBlockStatementForConstructor(expression, outerClass, classNode);

    // let's assign all the parameter fields from the outer context
    addFieldsAndGettersForLocalVariables(answer, localVariableParams);

    addConstructor(expression, localVariableParams, answer, block);

    correctAccessedVariable(answer,expression);

    return answer;
}
 
Example #29
Source File: ClosureExpression.java    From groovy with Apache License 2.0 4 votes vote down vote up
public VariableScope getVariableScope() {
    return variableScope;
}
 
Example #30
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
public VariableScopeVisitor(SourceUnit source, boolean recurseInnerClasses) {
    this.source = source;
    this.currentScope = new VariableScope();
    this.recurseInnerClasses = recurseInnerClasses;
}