use of org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable in project intellij-community by JetBrains.
the class GroovyCodeFragmentFactory method externalParameters.
public static Pair<Map<String, String>, GroovyFile> externalParameters(String text, @NotNull final PsiElement context) {
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.getProject());
final GroovyFile toEval = factory.createGroovyFile(text, false, context);
final GrClosableBlock closure = PsiTreeUtil.getParentOfType(context, GrClosableBlock.class);
final Map<String, String> parameters = new THashMap<>();
final Map<GrExpression, String> replacements = new HashMap<>();
toEval.accept(new GroovyRecursiveElementVisitor() {
@Override
public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
super.visitReferenceExpression(referenceExpression);
if (PsiUtil.isThisReference(referenceExpression) || PsiUtil.isSuperReference(referenceExpression)) {
replaceWithReference(referenceExpression, "delegate");
return;
}
PsiElement resolved = referenceExpression.resolve();
if (resolved instanceof PsiMember && (resolved instanceof PsiClass || ((PsiMember) resolved).hasModifierProperty(PsiModifier.STATIC))) {
String qName = com.intellij.psi.util.PsiUtil.getMemberQualifiedName((PsiMember) resolved);
if (qName != null && qName.contains(".") && !referenceExpression.isQualified()) {
replaceWithReference(referenceExpression, qName);
return;
}
}
if (shouldDelegate(referenceExpression, resolved)) {
replaceWithReference(referenceExpression, "delegate." + referenceExpression.getReferenceName());
return;
}
if (resolved instanceof GrVariable && !(resolved instanceof GrField) && !PsiTreeUtil.isAncestor(toEval, resolved, false)) {
final String name = ((GrVariable) resolved).getName();
if (resolved instanceof ClosureSyntheticParameter && PsiTreeUtil.isAncestor(toEval, ((ClosureSyntheticParameter) resolved).getClosure(), false)) {
return;
}
if (resolved instanceof GrBindingVariable && !PsiTreeUtil.isAncestor(resolved.getContainingFile(), toEval, false)) {
return;
}
String value;
if (closure != null && PsiTreeUtil.findCommonParent(resolved, closure) != closure && !(resolved instanceof ClosureSyntheticParameter)) {
// Evaluating inside closure for outer variable definitions
// All non-local variables are accessed by references
value = "this." + name;
} else {
value = name;
}
parameters.put(name, value);
return;
}
if (resolved instanceof PsiLocalVariable || resolved instanceof PsiParameter && !(resolved instanceof GrParameter)) {
String name = referenceExpression.getReferenceName();
parameters.put(name, name);
}
}
private boolean shouldDelegate(GrReferenceExpression referenceExpression, @Nullable PsiElement resolved) {
if (referenceExpression.isQualified()) {
return false;
}
if (resolved instanceof GrField) {
return true;
}
if (resolved instanceof PsiMethod) {
String methodName = ((PsiMethod) resolved).getName();
if (closure != null && "getDelegate".equals(methodName) || "call".equals(methodName)) {
return true;
}
}
return closure != null && resolved instanceof GrLightVariable && "owner".equals(((GrLightVariable) resolved).getName());
}
private void replaceWithReference(GrExpression expr, final String exprText) {
replacements.put(expr, exprText);
}
@Override
public void visitCodeReferenceElement(@NotNull GrCodeReferenceElement refElement) {
super.visitCodeReferenceElement(refElement);
if (refElement.getQualifier() == null) {
PsiElement resolved = refElement.resolve();
if (resolved instanceof PsiClass) {
String qName = ((PsiClass) resolved).getQualifiedName();
if (qName != null) {
int dotIndex = qName.lastIndexOf(".");
if (dotIndex < 0)
return;
String packageName = qName.substring(0, dotIndex);
refElement.setQualifier(factory.createReferenceElementFromText(packageName));
}
}
}
}
});
for (GrExpression expression : replacements.keySet()) {
expression.replaceWithExpression(factory.createExpressionFromText(replacements.get(expression)), false);
}
return Pair.create(parameters, toEval);
}
use of org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable in project intellij-community by JetBrains.
the class ExpressionGenerator method visitReferenceExpression.
@Override
public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
final GrExpression qualifier = referenceExpression.getQualifier();
final GroovyResolveResult resolveResult = referenceExpression.advancedResolve();
final PsiElement resolved = resolveResult.getElement();
final String referenceName = referenceExpression.getReferenceName();
if (PsiUtil.isThisOrSuperRef(referenceExpression)) {
writeThisOrSuperRef(referenceExpression, qualifier, referenceName);
return;
}
if (ResolveUtil.isClassReference(referenceExpression)) {
// just delegate to qualifier
LOG.assertTrue(qualifier != null);
qualifier.accept(this);
return;
}
if (resolved instanceof PsiClass) {
builder.append(((PsiClass) resolved).getQualifiedName());
if (PsiUtil.isExpressionUsed(referenceExpression)) {
builder.append(".class");
}
return;
}
//don't try to resolve local vars that are provided my this generator (they are listed in myUsedVarNames)
if (resolved == null && qualifier == null && context.myUsedVarNames.contains(referenceName)) {
builder.append(referenceName);
return;
}
//all refs in script that are not resolved are saved in 'binding' of the script
if (qualifier == null && (resolved == null || resolved instanceof GrBindingVariable || resolved instanceof LightElement && !(resolved instanceof ClosureSyntheticParameter)) && (referenceExpression.getParent() instanceof GrIndexProperty || !(referenceExpression.getParent() instanceof GrCall)) && PsiUtil.getContextClass(referenceExpression) instanceof GroovyScriptClass) {
final GrExpression thisExpr = factory.createExpressionFromText("this", referenceExpression);
thisExpr.accept(this);
builder.append(".getBinding().getProperty(\"").append(referenceExpression.getReferenceName()).append("\")");
return;
}
final IElementType type = referenceExpression.getDotTokenType();
GrExpression qualifierToUse = qualifier;
if (type == GroovyTokenTypes.mMEMBER_POINTER) {
LOG.assertTrue(qualifier != null);
builder.append("new ").append(GroovyCommonClassNames.ORG_CODEHAUS_GROOVY_RUNTIME_METHOD_CLOSURE).append('(');
qualifier.accept(this);
builder.append(", \"").append(referenceName).append("\")");
return;
}
if (type == GroovyTokenTypes.mOPTIONAL_DOT) {
LOG.assertTrue(qualifier != null);
String qualifierName = createVarByInitializer(qualifier);
builder.append('(').append(qualifierName).append(" == null ? null : ");
qualifierToUse = factory.createReferenceExpressionFromText(qualifierName, referenceExpression);
}
if (resolveResult.isInvokedOnProperty()) {
//property-style access to accessor (e.g. qual.prop should be translated to qual.getProp())
LOG.assertTrue(resolved instanceof PsiMethod);
LOG.assertTrue(GroovyPropertyUtils.isSimplePropertyGetter((PsiMethod) resolved));
invokeMethodOn(((PsiMethod) resolved), qualifierToUse, GrExpression.EMPTY_ARRAY, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, resolveResult.getSubstitutor(), referenceExpression);
} else {
if (qualifierToUse != null) {
qualifierToUse.accept(this);
builder.append('.');
}
if (resolved instanceof PsiNamedElement && !(resolved instanceof GrBindingVariable)) {
final String refName = ((PsiNamedElement) resolved).getName();
if (resolved instanceof GrVariable && context.analyzedVars.toWrap((GrVariable) resolved)) {
//this var should be wrapped by groovy.lang.Reference. so we add .get() tail.
builder.append(context.analyzedVars.toVarName((GrVariable) resolved));
if (!PsiUtil.isAccessedForWriting(referenceExpression)) {
builder.append(".get()");
}
} else {
builder.append(refName);
}
} else {
//unresolved reference
if (referenceName != null) {
if (PsiUtil.isAccessedForWriting(referenceExpression)) {
builder.append(referenceName);
} else {
PsiType stringType = PsiType.getJavaLangString(referenceExpression.getManager(), referenceExpression.getResolveScope());
PsiType qualifierType = PsiImplUtil.getQualifierType(referenceExpression);
GroovyResolveResult[] candidates = qualifierType != null ? ResolveUtil.getMethodCandidates(qualifierType, "getProperty", referenceExpression, stringType) : GroovyResolveResult.EMPTY_ARRAY;
final PsiElement method = PsiImplUtil.extractUniqueElement(candidates);
if (method != null) {
builder.append("getProperty(\"").append(referenceName).append("\")");
} else {
builder.append(referenceName);
}
}
} else {
final PsiElement nameElement = referenceExpression.getReferenceNameElement();
if (nameElement instanceof GrExpression) {
((GrExpression) nameElement).accept(this);
} else if (nameElement != null) {
builder.append(nameElement.toString());
}
}
}
}
if (type == GroovyTokenTypes.mOPTIONAL_DOT) {
builder.append(')');
}
}
use of org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable in project intellij-community by JetBrains.
the class ExpressionGenerator method visitAssignmentExpression.
/**
* x= expr ->
* x = expr
* x.set(expr)[: x.get()]
* x+= expr ->
* x+=expr
* x= plus(x, expr)
* x.set(plus(x, expr))[expr]
* x[a] = 4 ->
* x[a] = 4
* x.putAt(a, 4) [4]
*/
@Override
public void visitAssignmentExpression(@NotNull final GrAssignmentExpression expression) {
final GrExpression lValue = expression.getLValue();
final GrExpression rValue = expression.getRValue();
final IElementType token = expression.getOperationTokenType();
PsiElement realLValue = PsiUtil.skipParentheses(lValue, false);
if (realLValue instanceof GrReferenceExpression && rValue != null) {
GroovyResolveResult resolveResult = ((GrReferenceExpression) realLValue).advancedResolve();
PsiElement resolved = resolveResult.getElement();
if (resolved instanceof GrVariable && context.analyzedVars.toWrap((GrVariable) resolved)) {
//write assignment to wrapped local var
writeAssignmentWithRefSetter((GrExpression) realLValue, expression);
return;
} else if (resolved instanceof PsiMethod && resolveResult.isInvokedOnProperty()) {
//write assignment via setter
writeAssignmentWithSetter(((GrReferenceExpression) realLValue).getQualifier(), (PsiMethod) resolved, expression);
return;
} else if (resolved == null || resolved instanceof GrBindingVariable) {
//write unresolved reference assignment via setter GroovyObject.setProperty(String name, Object value)
final GrExpression qualifier = ((GrReferenceExpression) realLValue).getQualifier();
final PsiType type = PsiImplUtil.getQualifierType((GrReferenceExpression) realLValue);
final GrExpression[] args = { factory.createExpressionFromText("\"" + ((GrReferenceExpression) realLValue).getReferenceName() + "\""), getRValue(expression) };
GroovyResolveResult[] candidates = type != null ? ResolveUtil.getMethodCandidates(type, "setProperty", expression, args[0].getType(), args[1].getType()) : GroovyResolveResult.EMPTY_ARRAY;
final PsiMethod method = PsiImplUtil.extractUniqueElement(candidates);
if (method != null) {
writeAssignmentWithSetter(qualifier, method, args, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, PsiSubstitutor.EMPTY, expression);
return;
}
}
} else if (realLValue instanceof GrIndexProperty) {
//qualifier[args] = rValue
//write assignment via qualifier.putAt(Args, Value) method
final GroovyResolveResult result = PsiImplUtil.extractUniqueResult(((GrIndexProperty) realLValue).multiResolve(false));
final PsiElement resolved = result.getElement();
if (resolved instanceof PsiMethod) {
final GrExpression[] args = ((GrIndexProperty) realLValue).getArgumentList().getExpressionArguments();
writeAssignmentWithSetter(((GrIndexProperty) realLValue).getInvokedExpression(), (PsiMethod) resolved, ArrayUtil.append(args, getRValue(expression)), GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, result.getSubstitutor(), expression);
return;
}
}
final PsiType lType = GenerationUtil.getDeclaredType(lValue, context);
if (token == GroovyTokenTypes.mASSIGN) {
//write simple assignment
lValue.accept(this);
builder.append(" = ");
if (rValue != null) {
final PsiType rType = GenerationUtil.getDeclaredType(rValue, context);
GenerationUtil.wrapInCastIfNeeded(builder, GenerationUtil.getNotNullType(expression, lType), rType, expression, context, new StatementWriter() {
@Override
public void writeStatement(StringBuilder builder, ExpressionContext context) {
rValue.accept(ExpressionGenerator.this);
}
});
}
} else {
//write assignment such as +=, -=, etc
final GroovyResolveResult resolveResult = PsiImplUtil.extractUniqueResult(expression.multiResolve(false));
final PsiElement resolved = resolveResult.getElement();
if (resolved instanceof PsiMethod && !shouldNotReplaceOperatorWithMethod(lValue.getType(), rValue, expression.getOperationTokenType())) {
lValue.accept(this);
builder.append(" = ");
final PsiType rType = GenerationUtil.getDeclaredType((PsiMethod) resolved, resolveResult.getSubstitutor(), context);
GenerationUtil.wrapInCastIfNeeded(builder, GenerationUtil.getNotNullType(expression, lType), rType, expression, context, new StatementWriter() {
@Override
public void writeStatement(StringBuilder builder, ExpressionContext context) {
invokeMethodOn(((PsiMethod) resolved), (GrExpression) lValue.copy(), rValue == null ? GrExpression.EMPTY_ARRAY : new GrExpression[] { rValue }, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, resolveResult.getSubstitutor(), expression);
}
});
} else {
writeSimpleBinaryExpression(expression.getOperationToken(), lValue, rValue);
}
}
}
use of org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable in project intellij-community by JetBrains.
the class CompleteReferenceExpression method getBindings.
private void getBindings() {
final PsiClass containingClass = PsiTreeUtil.getParentOfType(myRefExpr, PsiClass.class);
if (containingClass != null)
return;
final PsiFile file = FileContextUtil.getContextFile(myRefExpr);
if (file instanceof GroovyFile) {
((GroovyFile) file).accept(new GroovyRecursiveElementVisitor() {
@Override
public void visitAssignmentExpression(@NotNull GrAssignmentExpression expression) {
super.visitAssignmentExpression(expression);
final GrExpression value = expression.getLValue();
if (value instanceof GrReferenceExpression && !((GrReferenceExpression) value).isQualified()) {
final PsiElement resolved = ((GrReferenceExpression) value).resolve();
if (resolved instanceof GrBindingVariable) {
myProcessor.execute(resolved, ResolveState.initial());
} else if (resolved == null) {
myProcessor.execute(new GrBindingVariable((GroovyFile) file, ((GrReferenceExpression) value).getReferenceName(), true), ResolveState.initial());
}
}
}
@Override
public void visitTypeDefinition(@NotNull GrTypeDefinition typeDefinition) {
//don't go into classes
}
});
}
}
use of org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable in project intellij-community by JetBrains.
the class GrReferenceAdjuster method checkCopyWithoutQualifier.
private static <Qualifier extends PsiElement> boolean checkCopyWithoutQualifier(@NotNull GrQualifiedReference<Qualifier> ref, boolean addImports, @NotNull PsiElement resolved) {
final GrQualifiedReference<Qualifier> copy = getCopy(ref);
if (copy == null)
return false;
copy.setQualifier(null);
final PsiElement resolvedCopy = copy.resolve();
if (ref.getManager().areElementsEquivalent(resolved, resolvedCopy)) {
return true;
} else if (resolvedCopy != null && !(resolvedCopy instanceof GrBindingVariable) && !isFromDefaultPackage(resolvedCopy)) {
return false;
}
if (resolved instanceof PsiClass) {
final PsiClass clazz = (PsiClass) resolved;
final String qName = clazz.getQualifiedName();
if (qName != null && addImports && checkIsInnerClass(clazz, ref) && mayInsertImport(ref)) {
final GroovyFileBase file = (GroovyFileBase) ref.getContainingFile();
final GrImportStatement added = file.addImportForClass(clazz);
if (added != null) {
if (copy.isReferenceTo(resolved))
return true;
file.removeImport(added);
}
}
}
return false;
}
Aggregations