use of org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint in project intellij-community by JetBrains.
the class ExpressionGenerator method visitLiteralExpression.
@Override
public //doesn't visit GrString and regexps
void visitLiteralExpression(@NotNull GrLiteral literal) {
final TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints(literal);
boolean isChar = false;
for (TypeConstraint constraint : constraints) {
if (constraint instanceof SubtypeConstraint && PsiType.CHAR.equals(TypesUtil.unboxPrimitiveTypeWrapper(constraint.getDefaultType()))) {
isChar = true;
}
}
final String text = literal.getText();
if (text.startsWith("'''") || text.startsWith("\"\"\"")) {
String string = GrStringUtil.removeQuotes(text).replace("\n", "\\n").replace("\r", "\\r");
builder.append('"').append(string).append('"');
} else if (text.startsWith("'")) {
if (isChar) {
builder.append(text);
} else {
builder.append('"').append(StringUtil.escapeQuotes(StringUtil.trimEnd(text.substring(1, text.length()), "'"))).append('"');
}
} else if (text.startsWith("\"")) {
if (isChar) {
builder.append('\'').append(StringUtil.escapeQuotes(StringUtil.trimEnd(text.substring(1, text.length()), "\""))).append('\'');
} else {
builder.append(text);
}
} else {
builder.append(text);
}
}
use of org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint in project intellij-community by JetBrains.
the class IntentionUtils method createTemplateForMethod.
public static void createTemplateForMethod(PsiType[] argTypes, ChooseTypeExpression[] paramTypesExpressions, PsiMethod method, PsiClass owner, TypeConstraint[] constraints, boolean isConstructor, @NotNull final PsiElement context) {
final Project project = owner.getProject();
PsiTypeElement typeElement = method.getReturnTypeElement();
ChooseTypeExpression expr = new ChooseTypeExpression(constraints, PsiManager.getInstance(project), context.getResolveScope(), method.getLanguage() == GroovyLanguage.INSTANCE);
TemplateBuilderImpl builder = new TemplateBuilderImpl(method);
if (!isConstructor) {
assert typeElement != null;
builder.replaceElement(typeElement, expr);
}
PsiParameter[] parameters = method.getParameterList().getParameters();
assert parameters.length == argTypes.length;
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
PsiTypeElement parameterTypeElement = parameter.getTypeElement();
builder.replaceElement(parameterTypeElement, paramTypesExpressions[i]);
builder.replaceElement(parameter.getNameIdentifier(), new ParameterNameExpression(null));
}
PsiCodeBlock body = method.getBody();
if (body != null) {
PsiElement lbrace = body.getLBrace();
assert lbrace != null;
builder.setEndVariableAfter(lbrace);
} else {
builder.setEndVariableAfter(method.getParameterList());
}
method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method);
Template template = builder.buildTemplate();
final PsiFile targetFile = owner.getContainingFile();
final Editor newEditor = positionCursor(project, targetFile, method);
TextRange range = method.getTextRange();
newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
TemplateManager manager = TemplateManager.getInstance(project);
TemplateEditingListener templateListener = new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
ApplicationManager.getApplication().runWriteAction(() -> {
PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
final int offset = newEditor.getCaretModel().getOffset();
PsiMethod method1 = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false);
if (context instanceof PsiMethod) {
final PsiTypeParameter[] typeParameters = ((PsiMethod) context).getTypeParameters();
if (typeParameters.length > 0) {
for (PsiTypeParameter typeParameter : typeParameters) {
if (CreateMethodFromUsageFix.checkTypeParam(method1, typeParameter)) {
final JVMElementFactory factory = JVMElementFactories.getFactory(method1.getLanguage(), method1.getProject());
PsiTypeParameterList list = method1.getTypeParameterList();
if (list == null) {
PsiTypeParameterList newList = factory.createTypeParameterList();
list = (PsiTypeParameterList) method1.addAfter(newList, method1.getModifierList());
}
list.add(factory.createTypeParameter(typeParameter.getName(), typeParameter.getExtendsList().getReferencedTypes()));
}
}
}
}
if (method1 != null) {
try {
final boolean hasNoReturnType = method1.getReturnTypeElement() == null && method1 instanceof GrMethod;
if (hasNoReturnType) {
((GrMethod) method1).setReturnType(PsiType.VOID);
}
if (method1.getBody() != null) {
FileTemplateManager templateManager = FileTemplateManager.getInstance(project);
FileTemplate fileTemplate = templateManager.getCodeTemplate(GroovyTemplates.GROOVY_FROM_USAGE_METHOD_BODY);
PsiClass containingClass = method1.getContainingClass();
LOG.assertTrue(!containingClass.isInterface() || GrTraitUtil.isTrait(containingClass), "Interface bodies should be already set up");
CreateFromUsageUtils.setupMethodBody(method1, containingClass, fileTemplate);
}
if (hasNoReturnType) {
((GrMethod) method1).setReturnType(null);
}
} catch (IncorrectOperationException e) {
LOG.error(e);
}
CreateFromUsageUtils.setupEditor(method1, newEditor);
}
});
}
};
manager.startTemplate(newEditor, template, templateListener);
}
use of org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint in project intellij-community by JetBrains.
the class ChooseTypeExpression method createItems.
@NotNull
private static List<SmartTypePointer> createItems(@NotNull TypeConstraint[] constraints, @NotNull SmartTypePointerManager typePointerManager) {
List<SmartTypePointer> result = ContainerUtil.newArrayList();
for (TypeConstraint constraint : constraints) {
if (constraint instanceof SubtypeConstraint) {
PsiType type = constraint.getDefaultType();
result.add(typePointerManager.createSmartTypePointer(type));
} else if (constraint instanceof SupertypeConstraint) {
processSuperTypes(constraint.getType(), result, typePointerManager);
}
}
return result;
}
use of org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint 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);
}
});
}
}
});
}
Aggregations