2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org
.jetbrains
.plugins
.groovy
.intentions
.conversions
;
19 import com
.intellij
.psi
.PsiElement
;
20 import com
.intellij
.util
.IncorrectOperationException
;
21 import org
.jetbrains
.annotations
.NotNull
;
22 import org
.jetbrains
.plugins
.groovy
.intentions
.base
.Intention
;
23 import org
.jetbrains
.plugins
.groovy
.intentions
.base
.PsiElementPredicate
;
24 import org
.jetbrains
.plugins
.groovy
.lang
.psi
.GroovyPsiElementFactory
;
25 import org
.jetbrains
.plugins
.groovy
.lang
.psi
.api
.statements
.GrVariableDeclaration
;
26 import org
.jetbrains
.plugins
.groovy
.lang
.psi
.api
.statements
.blocks
.GrOpenBlock
;
27 import org
.jetbrains
.plugins
.groovy
.lang
.psi
.api
.statements
.typedef
.GrTypeDefinitionBody
;
28 import org
.jetbrains
.plugins
.groovy
.lang
.psi
.api
.statements
.typedef
.members
.GrMethod
;
32 * @author Maxim.Medvedev
34 public class ConvertMethodToClosureIntention
extends Intention
{
37 protected PsiElementPredicate
getElementPredicate() {
38 return new MyPredicate();
42 protected void processIntention(@NotNull PsiElement element
) throws IncorrectOperationException
{
43 element
= element
.getParent();
44 final GrMethod method
= (GrMethod
)element
;
45 StringBuilder builder
= new StringBuilder(method
.getTextLength());
46 String modifiers
= method
.getModifierList().getText();
47 if (modifiers
.trim().length() == 0) {
50 builder
.append(modifiers
).append(' ');
51 builder
.append(method
.getName()).append("={");
52 builder
.append(method
.getParameterList().getText()).append(" ->");
53 final GrOpenBlock block
= method
.getBlock();
54 builder
.append(block
.getText().substring(1));
55 final GrVariableDeclaration variableDeclaration
=
56 GroovyPsiElementFactory
.getInstance(element
.getProject()).createFieldDeclarationFromText(builder
.toString());
57 method
.replace(variableDeclaration
);
60 private static class MyPredicate
implements PsiElementPredicate
{
61 public boolean satisfiedBy(PsiElement element
) {
62 final PsiElement parent
= element
.getParent();
63 return parent
instanceof GrMethod
&&
64 element
== ((GrMethod
)parent
).getNameIdentifierGroovy() &&
65 ((GrMethod
)parent
).getBlock() != null &&
66 parent
.getParent() instanceof GrTypeDefinitionBody
;
67 // return element instanceof GrMethod && ((GrMethod)element).getBlock() != null && element.getParent() instanceof GrTypeDefinitionBody;