use of org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable in project intellij-community by JetBrains.
the class GrSetStrongTypeIntention method processIntention.
@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, final Editor editor) throws IncorrectOperationException {
PsiElement parent = element.getParent();
PsiElement elementToBuildTemplate;
GrVariable[] variables;
if (parent instanceof GrVariable && parent.getParent() instanceof GrVariableDeclaration) {
variables = ((GrVariableDeclaration) parent.getParent()).getVariables();
elementToBuildTemplate = parent.getParent();
} else if (parent instanceof GrVariable && parent.getParent() instanceof GrForInClause) {
variables = new GrVariable[] { (GrVariable) parent };
elementToBuildTemplate = parent.getParent().getParent();
} else if (parent instanceof GrVariableDeclaration) {
variables = ((GrVariableDeclaration) parent).getVariables();
elementToBuildTemplate = parent;
} else if (parent instanceof GrParameter && parent.getParent() instanceof GrParameterList) {
variables = new GrVariable[] { (GrVariable) parent };
elementToBuildTemplate = parent.getParent().getParent();
} else if (parent instanceof GrVariable) {
variables = new GrVariable[] { ((GrVariable) parent) };
elementToBuildTemplate = parent;
} else {
return;
}
ArrayList<TypeConstraint> types = new ArrayList<>();
if (parent.getParent() instanceof GrForInClause) {
types.add(SupertypeConstraint.create(PsiUtil.extractIteratedType((GrForInClause) parent.getParent())));
} else {
for (GrVariable variable : variables) {
GrExpression initializer = variable.getInitializerGroovy();
if (initializer != null) {
PsiType type = initializer.getType();
if (type != null) {
types.add(SupertypeConstraint.create(type));
}
}
if (variable instanceof GrParameter) {
final PsiParameter parameter = (PsiParameter) variable;
final PsiType type = getClosureParameterType(parameter);
if (type != null) {
types.add(SupertypeConstraint.create(type));
}
}
}
}
final String originalText = elementToBuildTemplate.getText();
final TypeInfo typeInfo = getOrCreateTypeElement(parent, elementToBuildTemplate);
final PsiElement replaceElement = typeInfo.elementToReplace;
TypeConstraint[] constraints = types.toArray(new TypeConstraint[types.size()]);
ChooseTypeExpression chooseTypeExpression = new ChooseTypeExpression(constraints, element.getManager(), replaceElement.getResolveScope());
TemplateBuilderImpl builder = new TemplateBuilderImpl(elementToBuildTemplate);
builder.replaceElement(replaceElement, chooseTypeExpression);
final Document document = editor.getDocument();
final RangeMarker rangeMarker = document.createRangeMarker(elementToBuildTemplate.getTextRange());
rangeMarker.setGreedyToRight(true);
rangeMarker.setGreedyToLeft(true);
final PsiElement afterPostprocess = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(elementToBuildTemplate);
final Template template = builder.buildTemplate();
TextRange range = afterPostprocess.getTextRange();
document.deleteString(range.getStartOffset(), range.getEndOffset());
TemplateManager templateManager = TemplateManager.getInstance(project);
templateManager.startTemplate(editor, template, new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
if (brokenOff) {
ApplicationManager.getApplication().runWriteAction(() -> {
if (rangeMarker.isValid()) {
document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), originalText);
editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset() + typeInfo.originalOffset);
}
});
}
}
});
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable in project intellij-community by JetBrains.
the class GrSplitDeclarationIntention method processTuple.
private static void processTuple(Project project, GrVariableDeclaration declaration) {
GrExpression initializer = declaration.getTupleInitializer();
assert initializer != null;
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
GrVariable[] variables = declaration.getVariables();
StringBuilder assignmentBuilder = new StringBuilder();
assignmentBuilder.append('(');
for (GrVariable variable : variables) {
assignmentBuilder.append(variable.getName()).append(',');
}
assignmentBuilder.replace(assignmentBuilder.length() - 1, assignmentBuilder.length(), ")=");
assignmentBuilder.append(initializer.getText());
GrStatement assignment = factory.createStatementFromText(assignmentBuilder.toString());
declaration = GroovyRefactoringUtil.addBlockIntoParent(declaration);
declaration.getParent().addAfter(assignment, declaration);
initializer.delete();
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable in project intellij-community by JetBrains.
the class GrSplitDeclarationIntention method processIntention.
@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
if (!(element instanceof GrVariableDeclaration))
return;
GrVariableDeclaration declaration = (GrVariableDeclaration) element;
GrVariable[] variables = declaration.getVariables();
if (variables.length == 1) {
processSingleVar(project, declaration, variables[0]);
} else if (variables.length > 1) {
if (!declaration.isTuple() || declaration.getTupleInitializer() instanceof GrListOrMap) {
processMultipleVars(project, declaration);
} else {
processTuple(project, declaration);
}
}
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable in project intellij-community by JetBrains.
the class MyPredicate method replaceMapWithClass.
public static void replaceMapWithClass(Project project, final GrListOrMap map, PsiClass generatedClass, boolean replaceReturnType, boolean variableDeclaration, GrParameter parameter) {
JavaCodeStyleManager.getInstance(project).shortenClassReferences(generatedClass);
final String text = map.getText();
int begin = 0;
int end = text.length();
if (text.startsWith("["))
begin++;
if (text.endsWith("]"))
end--;
final GrExpression newExpression = GroovyPsiElementFactory.getInstance(project).createExpressionFromText("new " + generatedClass.getQualifiedName() + "(" + text.substring(begin, end) + ")");
final GrExpression replacedNewExpression = ((GrExpression) map.replace(newExpression));
if (replaceReturnType) {
final PsiType type = replacedNewExpression.getType();
final GrMethod method = PsiTreeUtil.getParentOfType(replacedNewExpression, GrMethod.class, true, GrClosableBlock.class);
LOG.assertTrue(method != null);
GrReferenceAdjuster.shortenAllReferencesIn(method.setReturnType(type));
}
if (variableDeclaration) {
final PsiElement parent = PsiUtil.skipParentheses(replacedNewExpression.getParent(), true);
((GrVariable) parent).setType(replacedNewExpression.getType());
}
if (parameter != null) {
parameter.setType(newExpression.getType());
}
JavaCodeStyleManager.getInstance(project).shortenClassReferences(replacedNewExpression);
IntentionUtils.positionCursor(project, generatedClass.getContainingFile(), generatedClass);
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable in project intellij-community by JetBrains.
the class CompletionTestBase method doTest.
protected void doTest(String directory) {
CamelHumpMatcher.forceStartMatching(myFixture.getTestRootDisposable());
final List<String> stringList = TestUtils.readInput(getTestDataPath() + "/" + getTestName(true) + ".test");
if (directory.length() != 0)
directory += "/";
final String fileName = directory + getTestName(true) + "." + getExtension();
myFixture.addFileToProject(fileName, stringList.get(0));
myFixture.configureByFile(fileName);
boolean old = CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX;
CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX = false;
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false;
String result = "";
try {
myFixture.completeBasic();
final LookupImpl lookup = (LookupImpl) LookupManager.getActiveLookup(myFixture.getEditor());
if (lookup != null) {
List<LookupElement> items = lookup.getItems();
if (!addReferenceVariants()) {
items = ContainerUtil.findAll(items, lookupElement -> {
final Object o = lookupElement.getObject();
return !(o instanceof PsiMember) && !(o instanceof GrVariable) && !(o instanceof GroovyResolveResult) && !(o instanceof PsiPackage);
});
}
Collections.sort(items, (o1, o2) -> o1.getLookupString().compareTo(o2.getLookupString()));
result = "";
for (LookupElement item : items) {
result = result + "\n" + item.getLookupString();
}
result = result.trim();
LookupManager.getInstance(myFixture.getProject()).hideActiveLookup();
}
} finally {
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = true;
CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX = old;
}
assertEquals(StringUtil.trimEnd(stringList.get(1), "\n"), result);
}
Aggregations