Java Code Examples for org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression

The following are top voted examples for showing how to use org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: intellij-ce-playground   File: ConfigSlurperMapContentProvider.java   Source Code and License 6 votes vote down vote up
@Override
protected Collection<String> getKeyVariants(@NotNull GrExpression qualifier, @Nullable PsiElement resolve) {
  Pair<ConfigSlurperSupport.PropertiesProvider, List<String>> info = getInfo(qualifier, resolve);
  if (info == null) return Collections.emptyList();

  final Set<String> res = new HashSet<String>();

  info.first.collectVariants(info.second, new PairConsumer<String, Boolean>() {
    @Override
    public void consume(String variant, Boolean isFinal) {
      res.add(variant);
    }
  });

  return res;
}
 
Example 2
Project: intellij-ce-playground   File: GrMapTypeFromNamedArgs.java   Source Code and License 6 votes vote down vote up
public GrMapTypeFromNamedArgs(@NotNull JavaPsiFacade facade, @NotNull GlobalSearchScope scope, @NotNull GrNamedArgument[] namedArgs) {
  super(facade, scope);

  myStringEntries = ContainerUtil.newLinkedHashMap();
  myOtherEntries = ContainerUtil.newArrayList();
  for (GrNamedArgument namedArg : namedArgs) {
    final GrArgumentLabel label = namedArg.getLabel();
    final GrExpression expression = namedArg.getExpression();
    if (label == null || expression == null) {
      continue;
    }

    final String name = label.getName();
    if (name != null) {
      myStringEntries.put(name, expression);
    }
    else if (label.getExpression() != null) {
      myOtherEntries.add(Couple.of(label.getExpression(), expression));
    }
  }
}
 
Example 3
Project: intellij-ce-playground   File: GrHighlightExitPointHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void computeUsages(List<PsiElement> targets) {
  PsiElement parent = myTarget.getParent();
  if (!(parent instanceof GrReturnStatement) && !(parent instanceof GrThrowStatement)) return;

  final GrControlFlowOwner flowOwner = ControlFlowUtils.findControlFlowOwner(parent);
  ControlFlowUtils.visitAllExitPoints(flowOwner, new ControlFlowUtils.ExitPointVisitor() {
    @Override
    public boolean visitExitPoint(Instruction instruction, @Nullable GrExpression returnValue) {
      final PsiElement returnElement = instruction.getElement();
      if (returnElement != null && isCorrectReturn(returnElement)) {
        final TextRange range = returnElement.getTextRange();
        myReadUsages.add(range);
      }
      return true;
    }
  });
}
 
Example 4
Project: intellij-ce-playground   File: GrIntroduceFieldProcessor.java   Source Code and License 6 votes vote down vote up
@Nullable
protected GrExpression getInitializer() {
  if (mySettings.removeLocalVar()) {
    return extractVarInitializer();
  }

  GrExpression expression = myContext.getExpression();
  StringPartInfo stringPart = myContext.getStringPart();
  if (expression != null) {
    return expression;
  }
  else if (stringPart != null) {
    return stringPart.createLiteralFromSelected();
  }

  throw new IncorrectOperationException("cannot be here!");
}
 
Example 5
Project: intellij-ce-playground   File: GrParameterInfo.java   Source Code and License 6 votes vote down vote up
public GrParameterInfo(GrParameter parameter, int position) {
  myPosition = position;
  myName = parameter.getName();
  final PsiType type = parameter.getDeclaredType();
  if (type != null) {
    myTypeWrapper = CanonicalTypes.createTypeWrapper(type);
  }
  else if (parameter.hasModifierProperty(GrModifier.DEF)) {
    myTypeWrapper = CanonicalTypes.createTypeWrapper(JavaPsiFacade.getElementFactory(parameter.getProject()).createTypeFromText("def", null));
  }
  else {
    myTypeWrapper = null;
  }
  final GrExpression defaultInitializer = parameter.getInitializerGroovy();
  if (defaultInitializer != null) {
    myDefaultInitializer = defaultInitializer.getText();
  }
  else {
    myDefaultInitializer = "";
  }
  myDefaultValue = "";
  myUseAnySingleVariable = false;
}
 
Example 6
Project: intellij-ce-playground   File: ConditionalUtils.java   Source Code and License 6 votes vote down vote up
public static boolean isReturn(GrStatement statement, String value) {
  if (statement == null) {
    return false;
  }
  if (!(statement instanceof GrReturnStatement)) {
    return false;
  }
  final GrReturnStatement returnStatement =
      (GrReturnStatement) statement;
  final GrExpression returnValue = returnStatement.getReturnValue();
  if (returnValue == null) {
    return false;
  }
  final String returnValueText = returnValue.getText();
  return value.equals(returnValueText);
}
 
Example 7
Project: intellij-ce-playground   File: ImplicitClosureCallPredicate.java   Source Code and License 6 votes vote down vote up
@Override
public boolean satisfiedBy(PsiElement element) {
    if (!(element instanceof GrMethodCallExpression)) {
        return false;
    }
    final GrMethodCallExpression call = (GrMethodCallExpression) element;
    final GrExpression invokedExpression = call.getInvokedExpression();
    if (invokedExpression == null) {
        return false;
    }
    final PsiType type = invokedExpression.getType();
    if(type == null)
    {
        return false;
    }
    if (!type.equalsToText(GroovyCommonClassNames.GROOVY_LANG_CLOSURE)) {
        return false;
    }
    return !ErrorUtil.containsError(element);
}
 
Example 8
Project: intellij-ce-playground   File: ImportStaticIntention.java   Source Code and License 6 votes vote down vote up
@Nullable
private static GrReferenceExpression findRef(PsiElement element) {
  if ((element instanceof GrReferenceExpression)) {
    return (GrReferenceExpression)element;

  }
  else if (element instanceof GrArgumentList) {
    PsiElement parent = element.getParent();
    if (parent instanceof GrMethodCall) {
      GrExpression invoked = ((GrMethodCall)parent).getInvokedExpression();
      if (invoked instanceof GrReferenceExpression) {
        return ((GrReferenceExpression)invoked);
      }
    }
  }
  return null;
}
 
Example 9
Project: intellij-ce-playground   File: GroovyTrivialIfInspection.java   Source Code and License 6 votes vote down vote up
private static void replaceSimplifiableAssignmentNegated(GrIfStatement statement)
    throws IncorrectOperationException {
  final GrCondition condition = statement.getCondition();
  if (!(condition instanceof GrExpression)) {
    return;
  }
  final GrExpression expression = (GrExpression) condition;
  final String conditionText =
      BoolUtils.getNegatedExpressionText(expression);
  final GrStatement thenBranch = statement.getThenBranch();
  final GrAssignmentExpression assignmentExpression =
      (GrAssignmentExpression) ConditionalUtils.stripBraces(thenBranch);
  final IElementType operator =
      assignmentExpression.getOperationTokenType();
  final String operatorText = getTextForOperator(operator);
  final GrExpression lhs = assignmentExpression.getLValue();
  final String lhsText = lhs.getText();
  replaceStatement(statement,
      lhsText + operatorText + conditionText + ';');
}
 
Example 10
Project: intellij-ce-playground   File: GrIntroduceLocalVariableProcessor.java   Source Code and License 6 votes vote down vote up
private PsiElement[] processOccurrences() {

    List<PsiElement> result = ContainerUtil.newArrayList();

    GrReferenceExpression templateRef =
      GroovyPsiElementFactory.getInstance(myContext.getProject()).createReferenceExpressionFromText(mySettings.getName());
    for (PsiElement occurrence : myOccurrences) {
      if (!(occurrence instanceof GrExpression)) {
        throw new IncorrectOperationException("Expression occurrence to be replaced is not instance of GroovyPsiElement");
      }

      final GrExpression replaced = ((GrExpression)occurrence).replaceWithExpression(templateRef, true);
      result.add(replaced);
    }

    return PsiUtilCore.toPsiElementArray(result);
  }
 
Example 11
Project: intellij-ce-playground   File: GroovyConfigSlurperCompletionProvider.java   Source Code and License 6 votes vote down vote up
@Nullable
private static String refToString(GrReferenceExpression ref) {
  StringBuilder sb = new StringBuilder();

  while (ref != null) {
    String name = ref.getReferenceName();
    if (name == null) return null;

    for (int i = name.length(); --i >= 0; ) {
      sb.append(name.charAt(i));
    }

    GrExpression qualifierExpression = ref.getQualifierExpression();
    if (qualifierExpression == null) break;

    if (!(qualifierExpression instanceof GrReferenceExpression)) return null;

    sb.append('.');

    ref = (GrReferenceExpression)qualifierExpression;
  }

  sb.reverse();

  return sb.toString();
}
 
Example 12
Project: intellij-ce-playground   File: GroovyUncheckedAssignmentOfMemberOfRawTypeInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitNamedArgument(GrNamedArgument argument) {
  final GrArgumentLabel label = argument.getLabel();
  if (label != null) {
    PsiType expectedType = label.getExpectedArgumentType();
    if (expectedType != null) {
      expectedType = TypeConversionUtil.erasure(expectedType);
      final GrExpression expr = argument.getExpression();
      if (expr != null) {
        final PsiType argType = expr.getType();
        if (argType != null) {
          final PsiClassType listType = JavaPsiFacade.getInstance(argument.getProject()).getElementFactory()
            .createTypeByFQClassName(CommonClassNames.JAVA_UTIL_LIST, argument.getResolveScope());
          if (listType.isAssignableFrom(argType)) return; //this is constructor arguments list
          checkAssignability(expectedType, expr, argument);
        }
      }
    }
  }

}
 
Example 13
Project: intellij-ce-playground   File: GdkMethodUtil.java   Source Code and License 6 votes vote down vote up
@Nullable
private static PsiClass getTypeToMix(GrMethodCall call) {
  if (!isSingleExpressionArg(call)) return null;

  GrExpression mixinRef = call.getExpressionArguments()[0];
  if (isClassRef(mixinRef)) {
    mixinRef = ((GrReferenceExpression)mixinRef).getQualifier();
  }

  if (mixinRef instanceof GrReferenceExpression) {
    PsiElement resolved = ((GrReferenceExpression)mixinRef).resolve();
    if (resolved instanceof PsiClass) {
      return (PsiClass)resolved;
    }
  }

  return null;
}
 
Example 14
Project: intellij-ce-playground   File: GrIntroduceParameterDialog.java   Source Code and License 6 votes vote down vote up
private GrTypeComboBox createTypeComboBox(GrVariable var, GrExpression expr, StringPartInfo stringPartInfo) {
  GrTypeComboBox box;
  if (var != null) {
    box = GrTypeComboBox.createTypeComboBoxWithDefType(var.getDeclaredType(), var);
  }
  else if (expr != null) {
    box = GrTypeComboBox.createTypeComboBoxFromExpression(expr);
  }
  else if (stringPartInfo != null) {
    box = GrTypeComboBox.createTypeComboBoxFromExpression(stringPartInfo.getLiteral());
  }
  else {
    box = GrTypeComboBox.createEmptyTypeComboBox();
  }

  box.addClosureTypesFrom(inferClosureReturnType(), myInfo.getContext());
  if (expr == null && var == null && stringPartInfo == null) {
    box.setSelectedIndex(box.getItemCount() - 1);
  }
  return box;
}
 
Example 15
Project: intellij-ce-playground   File: FlipConjunctionIntention.java   Source Code and License 6 votes vote down vote up
@Override
public void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
  final GrBinaryExpression exp = (GrBinaryExpression)element;
  final IElementType tokenType = exp.getOperationTokenType();

  final GrExpression lhs = exp.getLeftOperand();
  final String lhsText = lhs.getText();

  final GrExpression rhs = exp.getRightOperand();
  final String rhsText = rhs.getText();

  final String conjunction = getConjunction(tokenType);

  final String newExpression = rhsText + conjunction + lhsText;
  PsiImplUtil.replaceExpression(newExpression, exp);
}
 
Example 16
Project: intellij-ce-playground   File: GroovySynchronizationOnNonFinalFieldInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitSynchronizedStatement(GrSynchronizedStatement synchronizedStatement) {
  super.visitSynchronizedStatement(synchronizedStatement);
  final GrExpression lock = synchronizedStatement.getMonitor();
  if (lock == null || !(lock instanceof GrReferenceExpression)) {
    return;
  }
  final PsiElement referent = ((PsiReference) lock).resolve();
  if (!(referent instanceof PsiField)) {
    return;
  }
  final PsiField field = (PsiField) referent;
  if (field.hasModifierProperty(PsiModifier.FINAL)) {
    return;
  }
  registerError(lock);
}
 
Example 17
Project: intellij-ce-playground   File: ResolveUtil.java   Source Code and License 6 votes vote down vote up
@Nullable
public static PsiType extractReturnTypeFromCandidate(GroovyResolveResult candidate, GrExpression expression, @Nullable PsiType[] args) {
  final PsiElement element = candidate.getElement();
  if (element instanceof PsiMethod && !candidate.isInvokedOnProperty()) {
    return TypesUtil.substituteAndNormalizeType(org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.getSmartReturnType((PsiMethod)element),
                                                candidate.getSubstitutor(), candidate.getSpreadState(), expression);
  }

  final PsiType type;
  if (element instanceof GrField) {
    type = ((GrField)element).getTypeGroovy();
  }
  else if (element instanceof PsiMethod) {
    type = org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.getSmartReturnType((PsiMethod)element);
  }
  else {
    return null;
  }
  if (type instanceof GrClosureType) {
    final GrSignature signature = ((GrClosureType)type).getSignature();
    PsiType returnType = GrClosureSignatureUtil.getReturnType(signature, args, expression);
    return TypesUtil.substituteAndNormalizeType(returnType, candidate.getSubstitutor(), candidate.getSpreadState(), expression);
  }
  return null;
}
 
Example 18
Project: intellij-ce-playground   File: GrVariableBaseImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public GrExpression getInitializerGroovy() {
  final PsiElement parent = getParent();
  if (parent instanceof GrVariableDeclaration && ((GrVariableDeclaration)parent).isTuple()){
    final GrVariableDeclaration tuple = (GrVariableDeclaration)parent;
    final GrExpression initializer = tuple.getTupleInitializer();

    if (initializer instanceof GrListOrMap){
      final GrListOrMap listOrMap = (GrListOrMap)initializer;
      final GrExpression[] initializers = listOrMap.getInitializers();

      final int varNumber = ArrayUtil.indexOf(tuple.getVariables(), this);
      if (initializers.length < varNumber + 1) return null;

      return initializers[varNumber];
    }
  }
  return GroovyPsiElementImpl.findExpressionChild(this);
}
 
Example 19
Project: intellij-ce-playground   File: ExtractUtil.java   Source Code and License 6 votes vote down vote up
private static List<GrStatement> generateVarDeclarations(List<VariableInfo> varInfos,
                                                         Project project,
                                                         @Nullable GrExpression initializer) {
  List<GrStatement> result = new ArrayList<GrStatement>();
  if (varInfos.isEmpty()) return result;

  GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
  boolean distinctDeclaration = haveDifferentTypes(varInfos);

  if (distinctDeclaration) {
    for (VariableInfo info : varInfos) {
      result.add(factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", info.getType(), info.getName()));
    }
  }
  else {
    String[] names = new String[varInfos.size()];
    for (int i = 0, mustAddLength = varInfos.size(); i < mustAddLength; i++) {
      names[i] = varInfos.get(i).getName();
    }
    result.add(factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, initializer, varInfos.get(0).getType(), names));
  }
  return result;
}
 
Example 20
Project: intellij-ce-playground   File: ConvertMapToClassIntention.java   Source Code and License 6 votes vote down vote up
public static boolean checkForVariableDeclaration(GrExpression replacedNewExpression) {
  final PsiElement parent = PsiUtil.skipParentheses(replacedNewExpression.getParent(), true);
  if (parent instanceof GrVariable &&
      !(parent instanceof GrField) &&
      !(parent instanceof GrParameter) &&
      ((GrVariable)parent).getDeclaredType() != null &&
      replacedNewExpression.getType() != null) {
    if (ApplicationManager.getApplication().isUnitTestMode() || Messages.showYesNoDialog(replacedNewExpression.getProject(),
                                                                                          GroovyIntentionsBundle.message(
                                                                                            "do.you.want.to.change.variable.type",
                                                                                            ((GrVariable)parent).getName()),
                                                                                          GroovyIntentionsBundle.message(
                                                                                            "convert.map.to.class.intention.name"),
                                                                                          Messages.getQuestionIcon()) ==
                                                                Messages.YES) {
      return true;
    }
  }
  return false;
}
 
Example 21
Project: intellij-ce-playground   File: ExpandBooleanPredicate.java   Source Code and License 6 votes vote down vote up
public static boolean isBooleanReturn(GrStatement statement) {
  if (!(statement instanceof GrReturnStatement)) {
    return false;
  }
  final GrReturnStatement returnStatement =
      (GrReturnStatement) statement;
  final GrExpression returnValue = returnStatement.getReturnValue();
  if (returnValue == null) {
    return false;
  }
  if (returnValue instanceof GrLiteral) {
    return false;
  }
  final PsiType returnType = returnValue.getType();
  if (returnType == null) {
    return false;
  }
  return returnType.equals(PsiType.BOOLEAN) || returnType.equalsToText("java.lang.Boolean");
}
 
Example 22
Project: intellij-ce-playground   File: ConvertMapToClassIntention.java   Source Code and License 5 votes vote down vote up
@Nullable
public static GrParameter checkForMethodParameter(GrExpression map) {
  final GrParameter parameter = getParameterByArgument(map);
  if (parameter == null) return null;
  final PsiElement parent = parameter.getParent().getParent();
  if (!(parent instanceof PsiMethod)) return null;
  final PsiMethod method = (PsiMethod)parent;
  if (ApplicationManager.getApplication().isUnitTestMode() ||
         Messages.showYesNoDialog(map.getProject(), GroovyIntentionsBundle
           .message("do.you.want.to.change.type.of.parameter.in.method", parameter.getName(), method.getName()),
                                  GroovyIntentionsBundle.message("convert.map.to.class.intention.name"), Messages.getQuestionIcon()) == Messages.YES) {
    return parameter;
  }
  return null;
}
 
Example 23
Project: intellij-ce-playground   File: ConvertConcatenationToGstringIntention.java   Source Code and License 5 votes vote down vote up
private static void invokeImpl(final PsiElement element, Document document) {
  boolean isMultiline = containsMultilineStrings((GrExpression)element);

  StringBuilder builder = new StringBuilder(element.getTextLength());
  if (element instanceof GrBinaryExpression) {
    performIntention((GrBinaryExpression)element, builder, isMultiline);
  }
  else if (element instanceof GrLiteral) {
    getOperandText((GrExpression)element, builder, isMultiline);
  }
  else {
    return;
  }

  String text = builder.toString();
  final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject());
  final GrExpression newExpr = factory.createExpressionFromText(GrStringUtil.addQuotes(text, true));

  CommandProcessor.getInstance().executeCommand(element.getProject(), new Runnable() {
    @Override
    public void run() {
      final AccessToken accessToken = WriteAction.start();
      try {
        final GrExpression expression = ((GrExpression)element).replaceWithExpression(newExpr, true);
        if (expression instanceof GrString) {
          GrStringUtil.removeUnnecessaryBracesInGString((GrString)expression);
        }
      }
      finally {
        accessToken.finish();
      }
    }
  }, null, null, document);
}
 
Example 24
Project: intellij-ce-playground   File: GdslClosureCompleter.java   Source Code and License 5 votes vote down vote up
@Override
protected List<ClosureParameterInfo> getParameterInfos(InsertionContext context,
                                                       PsiMethod method,
                                                       PsiSubstitutor substitutor,
                                                       PsiElement place) {
  final ArrayList<ClosureDescriptor> descriptors = new ArrayList<ClosureDescriptor>();
  GrReferenceExpression ref = (GrReferenceExpression)place;
  PsiType qtype = PsiImplUtil.getQualifierType(ref);
  if (qtype == null) return null;

  GrExpression qualifier = ref.getQualifier();
  if (qualifier != null) {
    PsiType type = qualifier.getType();
    if (type == null) return null;
    processExecutors(qtype, ref, descriptors);
  }
  else {
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(context.getProject());
    for (PsiElement parent = ref.getParent(); parent != null; parent = parent.getParent()) {
      if (parent instanceof GrClosableBlock) {
        processExecutors(TypesUtil.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, ref), ref, descriptors);
      }
      else if (parent instanceof GrTypeDefinition) {
        processExecutors(factory.createType(((GrTypeDefinition)parent), PsiType.EMPTY_ARRAY), ref, descriptors);
      }
    }
  }

  for (ClosureDescriptor descriptor : descriptors) {
    if (descriptor.isMethodApplicable(method, ref)) {
      return descriptor.getParameters();
    }
  }
  return null;
}
 
Example 25
Project: intellij-ce-playground   File: SwitchStatementGenerator.java   Source Code and License 5 votes vote down vote up
public static void generate(@NotNull StringBuilder builder,
                            @NotNull ExpressionContext context,
                            @NotNull GrSwitchStatement switchStatement) {
  final GrExpression condition = switchStatement.getCondition();
  final GrCaseSection[] caseSections = switchStatement.getCaseSections();

  final PsiType type = condition == null ? null : TypesUtil.unboxPrimitiveTypeWrapper(condition.getType());
  if (type == null || isValidTypeForSwitchSelector(type)) {
    generateSwitch(builder, context, condition, caseSections);
  }
  else {
    generateIfs(builder, context, condition, caseSections);
  }
}
 
Example 26
Project: intellij-ce-playground   File: GrExpressionWrapper.java   Source Code and License 5 votes vote down vote up
public GrExpressionWrapper(@NotNull GrExpression expression) {
  assert expression.isValid();

  myExpression = expression;
  myFile = expression.getContainingFile();
  if (myFile.isPhysical()) {
    Document document = PsiDocumentManager.getInstance(expression.getProject()).getDocument(myFile);
    assert document != null;
    myMarker = document.createRangeMarker(myExpression.getTextRange());
  }
  else {
    myMarker = null;
  }
}
 
Example 27
Project: intellij-ce-playground   File: GroovyMapCompletionUtil.java   Source Code and License 5 votes vote down vote up
public static void addKeyVariants(@NotNull GroovyMapContentProvider contentProvider, @NotNull GrExpression qualifier, @Nullable PsiElement resolve, @NotNull CompletionResultSet result) {
  for (String key : contentProvider.getKeyVariants(qualifier, resolve)) {
    LookupElement lookup = LookupElementBuilder.create(key);
    lookup = PrioritizedLookupElement.withPriority(lookup, 1);
    result.addElement(lookup);
  }
}
 
Example 28
Project: intellij-ce-playground   File: ConvertConcatenationToGstringIntention.java   Source Code and License 5 votes vote down vote up
private static void _collect(PsiFile file, int offset, List<GrExpression> expressions) {
  final PsiElement elementAtCaret = file.findElementAt(offset);
  for (GrExpression expression = PsiTreeUtil.getParentOfType(elementAtCaret, GrExpression.class);
       expression != null;
       expression = PsiTreeUtil.getParentOfType(expression, GrExpression.class)) {
    if (MyPredicate.satisfied(expression)) {
      expressions.add(expression);
    }
    else if (!expressions.isEmpty()) break;
  }
}
 
Example 29
Project: intellij-ce-playground   File: GroovyExtractChooser.java   Source Code and License 5 votes vote down vote up
public static InitialInfo invoke(Project project, Editor editor, PsiFile file, int start, int end, boolean forceStatements) throws GrRefactoringError {
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  if (!(file instanceof GroovyFileBase)) {
    throw new GrRefactoringError(GroovyRefactoringBundle.message("only.in.groovy.files"));
  }

  if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file)) {
    throw new GrRefactoringError(RefactoringBundle.message("readonly.occurences.found"));
  }

  PsiDocumentManager.getInstance(project).commitAllDocuments();

  final StringPartInfo stringPart = StringPartInfo.findStringPart(file, start, end);
  if (stringPart != null) {
    return new InitialInfo(new VariableInfo[0], new VariableInfo[0], PsiElement.EMPTY_ARRAY, GrStatement.EMPTY_ARRAY, new ArrayList<GrStatement>(), stringPart, project, null);
  }

  final SelectionModel selectionModel = editor.getSelectionModel();
  if (!forceStatements) {
    GrVariable variable = GrIntroduceHandlerBase.findVariable(file, start, end);
    if (variable != null) {
      GrExpression initializer = variable.getInitializerGroovy();
      if (initializer != null) {
        TextRange range = initializer.getTextRange();
        return buildInfo(project, file, range.getStartOffset(), range.getEndOffset(), forceStatements, selectionModel, variable);
      }
    }
  }

  return buildInfo(project, file, start, end, forceStatements, selectionModel, null);
}
 
Example 30
Project: intellij-ce-playground   File: GrIntroduceFieldDialog.java   Source Code and License 5 votes vote down vote up
@Nullable
private static String getInvokedOnLocalVar(GrExpression expression) {
  if (expression instanceof GrReferenceExpression) {
    final PsiElement resolved = ((GrReferenceExpression)expression).resolve();
    if (PsiUtil.isLocalVariable(resolved)) {
      return ((GrVariable)resolved).getName();
    }
  }
  return null;
}
 
Example 31
Project: intellij-ce-playground   File: GradleResolverUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
public static PsiType getTypeOf(@Nullable final GrExpression expression) {
  if (expression == null) return null;
  return RecursionManager.doPreventingRecursion(expression, true, new Computable<PsiType>() {
    @Override
    public PsiType compute() {
      return expression.getNominalType();
    }
  });
}
 
Example 32
Project: intellij-ce-playground   File: GradleScriptType.java   Source Code and License 5 votes vote down vote up
@Nullable
private static List<String> getTasksTarget(Location location) {
  if (location instanceof GradleTaskLocation) {
    return ((GradleTaskLocation)location).getTasks();
  }

  PsiElement parent = location.getPsiElement();
  while (parent.getParent() != null && !(parent.getParent() instanceof PsiFile)) {
    parent = parent.getParent();
  }

  if (isCreateTaskMethod(parent)) {
    final GrExpression[] arguments = ((GrMethodCallExpression)parent).getExpressionArguments();
    if (arguments.length > 0 && arguments[0] instanceof GrLiteral && ((GrLiteral)arguments[0]).getValue() instanceof String) {
      return Collections.singletonList((String)((GrLiteral)arguments[0]).getValue());
    }
  }
  else if (parent instanceof GrApplicationStatement) {
    PsiElement shiftExpression = parent.getChildren()[1].getChildren()[0];
    if (GradleResolverUtil.isLShiftElement(shiftExpression)) {
      PsiElement shiftiesChild = shiftExpression.getChildren()[0];
      if (shiftiesChild instanceof GrReferenceExpression) {
        return Collections.singletonList(shiftiesChild.getText());
      }
      else if (shiftiesChild instanceof GrMethodCallExpression) {
        return Collections.singletonList(shiftiesChild.getChildren()[0].getText());
      }
    }
    else if (shiftExpression instanceof GrMethodCallExpression) {
      return Collections.singletonList(shiftExpression.getChildren()[0].getText());
    }
  }

  return null;
}
 
Example 33
Project: intellij-ce-playground   File: GroovyConstructorUsagesSearcher.java   Source Code and License 5 votes vote down vote up
private static boolean checkLiteralInstantiation(GrExpression expression,
                                                 final LiteralConstructorSearcher literalProcessor) {

  if (expression instanceof GrListOrMap) {
    return literalProcessor.processLiteral((GrListOrMap)expression);
  }
  return true;
}
 
Example 34
Project: intellij-ce-playground   File: GrIfConditionFixer.java   Source Code and License 5 votes vote down vote up
@Override
public void apply(@NotNull Editor editor, @NotNull GroovySmartEnterProcessor processor, @NotNull PsiElement psiElement) {
  if (psiElement instanceof GrIfStatement) {
    final Document doc = editor.getDocument();
    final GrIfStatement ifStatement = (GrIfStatement) psiElement;
    final PsiElement rParen = ifStatement.getRParenth();
    final PsiElement lParen = ifStatement.getLParenth();
    final GrExpression condition = ifStatement.getCondition();

    if (condition == null) {
      if (lParen == null || rParen == null) {
        int stopOffset = doc.getLineEndOffset(doc.getLineNumber(ifStatement.getTextRange().getStartOffset()));
        final GrStatement then = ifStatement.getThenBranch();
        if (then != null) {
          stopOffset = Math.min(stopOffset, then.getTextRange().getStartOffset());
        }
        stopOffset = Math.min(stopOffset, ifStatement.getTextRange().getEndOffset());

        doc.replaceString(ifStatement.getTextRange().getStartOffset(), stopOffset, "if ()");

        processor.registerUnresolvedError(ifStatement.getTextRange().getStartOffset() + "if (".length());
      } else {
        processor.registerUnresolvedError(lParen.getTextRange().getEndOffset());
      }
    } else if (rParen == null) {
      doc.insertString(condition.getTextRange().getEndOffset(), ")");
    }
  }
}
 
Example 35
Project: intellij-ce-playground   File: GrConditionalExprImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Nullable
public GrExpression getThenBranch() {
  final PsiElement question = findChildByType(GroovyTokenTypes.mQUESTION);
  for (PsiElement nextSibling = question;
       nextSibling != null && nextSibling.getNode().getElementType() != GroovyTokenTypes.mCOLON;
       nextSibling = nextSibling.getNextSibling()) {
    if (nextSibling instanceof GrExpression) return (GrExpression)nextSibling;
  }
  return null;
}
 
Example 36
Project: intellij-ce-playground   File: GroovyTypeCheckVisitorHelper.java   Source Code and License 5 votes vote down vote up
public static boolean isSpockTimesOperator(GrBinaryExpression call) {
  if (call.getOperationTokenType() == GroovyTokenTypes.mSTAR && PsiUtil.isExpressionStatement(call)) {
    GrExpression operand = call.getLeftOperand();
    if (operand instanceof GrLiteral && TypesUtil.isNumericType(operand.getType())) {
      PsiClass aClass = PsiUtil.getContextClass(call);
      if (InheritanceUtil.isInheritor(aClass, false, SpockUtils.SPEC_CLASS_NAME)) {
        return true;
      }
    }
  }

  return false;
}
 
Example 37
Project: intellij-ce-playground   File: GroovyTrivialConditionalInspection.java   Source Code and License 5 votes vote down vote up
private static String calculateReplacementExpression(GrConditionalExpression exp) {
  final GrExpression thenExpression = exp.getThenBranch();
  final GrExpression elseExpression = exp.getElseBranch();
  final GrExpression condition = exp.getCondition();

  if (isFalse(thenExpression) && isTrue(elseExpression)) {
    return BoolUtils.getNegatedExpressionText(condition);
  } else {
    return condition.getText();
  }
}
 
Example 38
Project: intellij-ce-playground   File: GrListOrMapImpl.java   Source Code and License 5 votes vote down vote up
@Override
@NotNull
public GrExpression[] getInitializers() {
  GrExpression[] initializers = myInitializers;
  if (initializers == null) {
    initializers = PsiTreeUtil.getChildrenOfType(this, GrExpression.class);
    initializers = initializers == null ? GrExpression.EMPTY_ARRAY : initializers;
    myInitializers = initializers;
  }
  return initializers;
}
 
Example 39
Project: intellij-ce-playground   File: GppReferenceContributor.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
  final GrArgumentLabel context = getElement();
  final GrNamedArgument namedArgument = (GrNamedArgument) context.getParent();
  final GrExpression map = (GrExpression)namedArgument.getParent();
  final PsiClassType classType = LiteralConstructorReference.getTargetConversionType(map);
  if (classType != null) {
    final PsiClass psiClass = classType.resolve();
    if (psiClass != null) {
      final GrExpression value = namedArgument.getExpression();

      final List<ResolveResult> applicable = addMethodCandidates(classType, value);

      final String memberName = getValue();
      if (value == null || applicable.isEmpty()) {
        final PsiMethod setter = PropertyUtil.findPropertySetter(psiClass, memberName, false, true);
        if (setter != null) {
          applicable.add(new PsiElementResolveResult(setter));
        } else {
          final PsiField field = PropertyUtil.findPropertyField(psiClass, memberName, false);
          if (field != null) {
            applicable.add(new PsiElementResolveResult(field));
          }
        }
      }

      return applicable.toArray(new ResolveResult[applicable.size()]);
    }
  }

  return ResolveResult.EMPTY_ARRAY;
}
 
Example 40
Project: intellij-ce-playground   File: GrMethodCallImpl.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public GroovyResolveResult advancedResolve() {
  final GrExpression methodExpr = getInvokedExpression();
  if (methodExpr instanceof GrReferenceExpression) {
    return ((GrReferenceExpression) methodExpr).advancedResolve();
  }

  return GroovyResolveResult.EMPTY_RESULT;
}
 
Example 41
Project: intellij-ce-playground   File: GrIntroduceConstantHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected void checkExpression(@NotNull GrExpression selectedExpr) {
  GrVariable variable = GrIntroduceHandlerBase.resolveLocalVar(selectedExpr);
  if (variable != null) {
    checkVariable(variable);
  }
  else {
    selectedExpr.accept(new ConstantChecker(selectedExpr, selectedExpr));
  }
}
 
Example 42
Project: intellij-ce-playground   File: GroovyTrivialIfInspection.java   Source Code and License 5 votes vote down vote up
public static boolean isSimplifiableImplicitAssignment(GrIfStatement ifStatement) {
  if (ifStatement.getElseBranch() != null) {
    return false;
  }
  GrStatement thenBranch = ifStatement.getThenBranch();
  thenBranch = ConditionalUtils.stripBraces(thenBranch);
  final PsiElement nextStatement =
      PsiTreeUtil.skipSiblingsBackward(ifStatement,
          PsiWhiteSpace.class);
  if (!(nextStatement instanceof GrStatement)) {
    return false;
  }
  GrStatement elseBranch = (GrStatement) nextStatement;

  elseBranch = ConditionalUtils.stripBraces(elseBranch);
  if (ConditionalUtils.isAssignment(thenBranch, "true") &&
      ConditionalUtils.isAssignment(elseBranch, "false")) {
    final GrAssignmentExpression thenExpression =
        (GrAssignmentExpression) thenBranch;
    final GrAssignmentExpression elseExpression =
        (GrAssignmentExpression) elseBranch;
    final IElementType thenSign = thenExpression.getOperationTokenType();
    final IElementType elseSign = elseExpression.getOperationTokenType();
    if (!thenSign.equals(elseSign)) {
      return false;
    }
    final GrExpression thenLhs = thenExpression.getLValue();
    final GrExpression elseLhs = elseExpression.getLValue();
    return EquivalenceChecker.expressionsAreEquivalent(thenLhs,
        elseLhs);
  } else {
    return false;
  }
}
 
Example 43
Project: intellij-ce-playground   File: GroovySillyAssignmentInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void visitAssignmentExpression(@NotNull GrAssignmentExpression assignment) {
  super.visitAssignmentExpression(assignment);

  final IElementType sign = assignment.getOperationTokenType();
  if (!sign.equals(GroovyTokenTypes.mASSIGN)) {
    return;
  }
  final GrExpression lhs = assignment.getLValue();
  final GrExpression rhs = assignment.getRValue();
  if (rhs == null) {
    return;
  }
  if (!(rhs instanceof GrReferenceExpression) || !(lhs instanceof GrReferenceExpression)) {
    return;
  }
  final GrReferenceExpression rhsReference = (GrReferenceExpression) rhs;
  final GrReferenceExpression lhsReference = (GrReferenceExpression) lhs;
  final GrExpression rhsQualifier = rhsReference.getQualifierExpression();
  final GrExpression lhsQualifier = lhsReference.getQualifierExpression();
  if (rhsQualifier != null || lhsQualifier != null) {
    if (!EquivalenceChecker.expressionsAreEquivalent(rhsQualifier, lhsQualifier)) {
      return;
    }
  }
  final String rhsName = rhsReference.getReferenceName();
  final String lhsName = lhsReference.getReferenceName();
  if (rhsName == null || lhsName == null) {
    return;
  }
  if (!rhsName.equals(lhsName)) {
    return;
  }
  final PsiElement rhsReferent = rhsReference.resolve();
  final PsiElement lhsReferent = lhsReference.resolve();
  if (rhsReferent == null || lhsReferent == null || !rhsReferent.equals(lhsReferent)) {
    return;
  }
  registerError(assignment);
}
 
Example 44
Project: intellij-ce-playground   File: ClosureParameterEnhancer.java   Source Code and License 5 votes vote down vote up
@Nullable
private static String findMethodName(@NotNull GrMethodCall methodCall) {
  GrExpression expression = methodCall.getInvokedExpression();
  if (expression instanceof GrReferenceExpression) {
    return ((GrReferenceExpression)expression).getReferenceName();
  }
  return null;
}
 
Example 45
Project: intellij-ce-playground   File: GroovyNotifyWhileNotSynchronizedInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void visitMethodCallExpression(GrMethodCallExpression grMethodCallExpression) {
  super.visitMethodCallExpression(grMethodCallExpression);
  final GrExpression methodExpression = grMethodCallExpression.getInvokedExpression();
  if (!(methodExpression instanceof GrReferenceExpression)) {
    return;
  }
  final GrReferenceExpression reference = (GrReferenceExpression) methodExpression;
  final String name = reference.getReferenceName();
  if (!"notify".equals(name) && !"notifyAll".equals(name)) {
    return;
  }
  final PsiMethod method = grMethodCallExpression.resolveMethod();
  if (method == null) {
    return;
  }
  final PsiClass containingClass = method.getContainingClass();
  if (containingClass == null || !CommonClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName())) {
    return;
  }
  final GrMethod containingMethod = PsiTreeUtil.getParentOfType(grMethodCallExpression, GrMethod.class);
  if (containingMethod != null && containingMethod.hasModifierProperty(PsiModifier.SYNCHRONIZED)) {
    return;
  }
  final GrStatement parent = PsiTreeUtil.getParentOfType(grMethodCallExpression, GrSynchronizedStatement.class, GrClosableBlock.class);
  if (parent instanceof GrSynchronizedStatement) {
    return;
  }
  registerMethodCallError(grMethodCallExpression);
}
 
Example 46
Project: intellij-ce-playground   File: SimplifyTernaryOperatorIntention.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
protected PsiElementPredicate getElementPredicate() {
  return new PsiElementPredicate() {
    @Override
    public boolean satisfiedBy(PsiElement element) {
      if (!(element instanceof GrConditionalExpression)) {
        return false;
      }

      GrConditionalExpression condExp = (GrConditionalExpression)element;
      PsiType condType = condExp.getType();
      if (condType == null || !PsiType.BOOLEAN.isConvertibleFrom(condType)) {
        return false;
      }

      GrExpression thenBranch = condExp.getThenBranch();
      GrExpression elseBranch = condExp.getElseBranch();

      Object thenVal = GroovyConstantExpressionEvaluator.evaluate(thenBranch);
      if (Boolean.TRUE.equals(thenVal) && elseBranch != null) {
        return true;
      }

      Object elseVal = GroovyConstantExpressionEvaluator.evaluate(elseBranch);
      if (thenBranch != null && Boolean.FALSE.equals(elseVal)) {
        return true;
      }

      return false;
    }
  };
}
 
Example 47
Project: intellij-ce-playground   File: GroovyPointlessBooleanInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void visitUnaryExpression(@NotNull GrUnaryExpression expression) {
  super.visitUnaryExpression(expression);
  final IElementType sign = expression.getOperationTokenType();
  if (sign == null) {
    return;
  }
  final GrExpression operand = expression.getOperand();
  if (sign.equals(GroovyTokenTypes.mLNOT) &&
      notExpressionIsPointless(operand)) {
    registerError(expression);
  }
}
 
Example 48
Project: intellij-ce-playground   File: ControlFlowUtils.java   Source Code and License 5 votes vote down vote up
public static List<GrStatement> collectReturns(@NotNull Instruction[] flow, final boolean allExitPoints) {
  boolean[] visited = new boolean[flow.length];
  final List<GrStatement> res = new ArrayList<GrStatement>();
  visitAllExitPointsInner(flow[flow.length - 1], flow[0], visited, new ExitPointVisitor() {
    @Override
    public boolean visitExitPoint(Instruction instruction, @Nullable GrExpression returnValue) {
      final PsiElement element = instruction.getElement();
      if (element instanceof GrReturnStatement || (allExitPoints && instruction instanceof MaybeReturnInstruction)) {
        res.add((GrStatement)element);
      }
      return true;
    }
  });
  return res;
}
 
Example 49
Project: intellij-ce-playground   File: GroovyTypeCheckVisitorHelper.java   Source Code and License 5 votes vote down vote up
public static boolean isOnlyOneMapParam(GrExpression[] exprs) {
  if (!(exprs.length == 1)) return false;

  final GrExpression e = exprs[0];
  return TypesUtil.isAssignableByMethodCallConversion(
    TypesUtil.createTypeByFQClassName(CommonClassNames.JAVA_UTIL_MAP, e),
    e.getType(),
    e
  );
}
 
Example 50
Project: intellij-ce-playground   File: GroovyUncheckedAssignmentOfMemberOfRawTypeInspection.java   Source Code and License 5 votes vote down vote up
private void checkAssignability(PsiType lType, GrExpression rExpr, GroovyPsiElement element) {
  if (PsiUtil.isRawClassMemberAccess(rExpr)) {
    final PsiType rType = rExpr.getType();
    if (!TypesUtil.isAssignable(lType, rType, element)) {
      registerError(element, lType, rType);
    }
  }
}
 
Example 51
Project: intellij-ce-playground   File: GrWhileStatementImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Nullable
public GrExpression getCondition() {
  PsiElement lParenth = getLParenth();

  if (lParenth == null) return null;
  PsiElement afterLParenth = PsiUtil.skipWhitespacesAndComments(lParenth.getNextSibling(), true);

  if (afterLParenth instanceof GrExpression) return ((GrExpression) afterLParenth);

  return null;
}
 
Example 52
Project: intellij-ce-playground   File: CodeBlockGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public void visitIfStatement(final GrIfStatement ifStatement) {
  writeStatement(ifStatement, new StatementWriter() {
    @Override
    public void writeStatement(StringBuilder builder, ExpressionContext context) {
      final GrExpression condition = ifStatement.getCondition();
      final GrStatement thenBranch = ifStatement.getThenBranch();
      final GrStatement elseBranch = ifStatement.getElseBranch();
      builder.append("if (");
      if (condition != null) {
        final PsiType type = condition.getType();
        if (TypesUtil.unboxPrimitiveTypeWrapper(type) == PsiType.BOOLEAN) {
          writeExpression(condition, builder, context);
        }
        else {
          GenerationUtil.invokeMethodByName(
            condition,
            "asBoolean",
            GrExpression.EMPTY_ARRAY, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY,
            new ExpressionGenerator(builder, context), ifStatement);
        }
      }
      builder.append(')');
      if (thenBranch != null) thenBranch.accept(new CodeBlockGenerator(builder, context.extend(), myExitPoints));
      if (ifStatement.getElseKeyword() != null) builder.append(" else ");
      if (elseBranch != null) elseBranch.accept(new CodeBlockGenerator(builder, context.extend(), myExitPoints));
    }
  });
}
 
Example 53
Project: intellij-ce-playground   File: ResolveUtil.java   Source Code and License 5 votes vote down vote up
public static boolean isClassReference(@NotNull GrReferenceExpression ref) {
  GrExpression qualifier = ref.getQualifier();
  return "class".equals(ref.getReferenceName()) &&
         qualifier instanceof GrReferenceExpression &&
         ((GrReferenceExpression)qualifier).resolve() instanceof PsiClass &&
         !org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isThisReference(qualifier);
}
 
Example 54
Project: intellij-ce-playground   File: MoveGroovyMemberHandler.java   Source Code and License 5 votes vote down vote up
@Override
public MoveMembersProcessor.MoveMembersUsageInfo getUsage(@NotNull PsiMember member,
                                                          @NotNull PsiReference psiReference,
                                                          @NotNull Set<PsiMember> membersToMove,
                                                          @NotNull PsiClass targetClass) {
  PsiElement ref = psiReference.getElement();
  if (ref instanceof GrReferenceExpression) {
    GrReferenceExpression refExpr = (GrReferenceExpression)ref;
    GrExpression qualifier = refExpr.getQualifier();
    if (RefactoringHierarchyUtil.willBeInTargetClass(refExpr, membersToMove, targetClass, true)) {
      // both member and the reference to it will be in target class
      if (!RefactoringUtil.isInMovedElement(refExpr, membersToMove)) {
        if (qualifier != null) {
          return new MoveMembersProcessor.MoveMembersUsageInfo(member, refExpr, null, qualifier, psiReference);  // remove qualifier
        }
      }
      else if (qualifier instanceof GrReferenceExpression && ((GrReferenceExpression)qualifier).isReferenceTo(member.getContainingClass())) {
        return new MoveMembersProcessor.MoveMembersUsageInfo(member, refExpr, null, qualifier, psiReference);  // change qualifier
      }
    }
    else {
      // member in target class, the reference will be outside target class
      if (qualifier == null) {
        return new MoveMembersProcessor.MoveMembersUsageInfo(member, refExpr, targetClass, refExpr, psiReference); // add qualifier
      }
      else {
        return new MoveMembersProcessor.MoveMembersUsageInfo(member, refExpr, targetClass, qualifier, psiReference); // change qualifier
      }
    }
  }
  return null;
}
 
Example 55
Project: intellij-ce-playground   File: ConvertStringToMultilineIntention.java   Source Code and License 5 votes vote down vote up
@Override
protected void processIntention(@NotNull PsiElement element, final Project project, final Editor editor) throws IncorrectOperationException {
  final List<GrExpression> expressions;
  if (editor.getSelectionModel().hasSelection()) {
    expressions = Collections.singletonList(((GrExpression)element));
  }
  else {
    final AccessToken accessToken = ReadAction.start();
    try {
      expressions = collectExpressions(element);
    }
    finally {
      accessToken.finish();
    }
  }

  if (expressions.size() == 1) {
    invokeImpl(expressions.get(0), project, editor);
  }
  else if (ApplicationManager.getApplication().isUnitTestMode()) {
    invokeImpl(expressions.get(expressions.size() - 1), project, editor);
  }
  else {
    final Pass<GrExpression> callback = new Pass<GrExpression>() {
      @Override
      public void pass(@NotNull final GrExpression selectedValue) {
        invokeImpl(selectedValue, project, editor);
      }
    };
    final Function<GrExpression, String> renderer = new Function<GrExpression, String>() {
      @Override
      public String fun(@NotNull GrExpression grExpression) {
        return grExpression.getText();
      }
    };
    IntroduceTargetChooser.showChooser(editor, expressions, callback, renderer);
  }
}
 
Example 56
Project: intellij-ce-playground   File: GrStringUtil.java   Source Code and License 5 votes vote down vote up
public static void wrapInjection(GrStringInjection injection) {
  final GrExpression expression = injection.getExpression();
  LOG.assertTrue(expression != null);
  final GroovyPsiElementFactory instance = GroovyPsiElementFactory.getInstance(injection.getProject());
  final GrClosableBlock closure = instance.createClosureFromText("{foo}");
  closure.getNode().replaceChild(closure.getStatements()[0].getNode(), expression.getNode());
  injection.getNode().addChild(closure.getNode());
  CodeEditUtil.setNodeGeneratedRecursively(expression.getNode(), true);
}
 
Example 57
Project: intellij-ce-playground   File: ArgumentListGenerator.java   Source Code and License 5 votes vote down vote up
private void generateSimple(GrExpression[] exprs,
                            GrNamedArgument[] namedArgs,
                            GrClosableBlock[] closures,
                            GroovyPsiElement context,
                            PsiSubstitutor substitutor) {
  myBuilder.append('(');
  if (namedArgs.length > 0) {
    final GrExpression listOrMap =
      GroovyRefactoringUtil.generateArgFromMultiArg(substitutor, Arrays.asList(namedArgs), null, context.getProject());
    LOG.assertTrue(listOrMap instanceof GrListOrMap);
    listOrMap.accept(myExpressionGenerator);
    myBuilder.append(", ");
  }

  for (GrExpression expr : exprs) {
    expr.accept(myExpressionGenerator);
    myBuilder.append(", ");
  }

  for (GrClosableBlock closure : closures) {
    closure.accept(myExpressionGenerator);
    myBuilder.append(", ");
  }

  if (namedArgs.length + exprs.length + closures.length > 0) {
    myBuilder.delete(myBuilder.length()-2, myBuilder.length());
    //myBuilder.removeFromTheEnd(2);
  }

  myBuilder.append(')');
}
 
Example 58
Project: intellij-ce-playground   File: GrIntroduceParameterProcessor.java   Source Code and License 5 votes vote down vote up
private void processStringPart() {
  final StringPartInfo stringPartInfo = mySettings.getStringPartInfo();
  if (stringPartInfo != null) {
    final GrExpression
      expr = mySettings.getStringPartInfo().replaceLiteralWithConcatenation(mySettings.getName());
    final Editor editor = PsiUtilBase.findEditor(expr);
    if (editor != null) {
      editor.getSelectionModel().removeSelection();
      editor.getCaretModel().moveToOffset(expr.getTextRange().getEndOffset());
    }
  }
}
 
Example 59
Project: intellij-ce-playground   File: GrIntroduceLocalVariableProcessor.java   Source Code and License 5 votes vote down vote up
@NotNull
private GrExpression preprocessOccurrences() {
  GroovyRefactoringUtil.sortOccurrences(myOccurrences);
  if (myOccurrences.length == 0 || !(myOccurrences[0] instanceof GrExpression)) {
    throw new IncorrectOperationException("Wrong expression occurrence");
  }

  return (GrExpression)myOccurrences[0];
}
 
Example 60
Project: intellij-ce-playground   File: GroovyCompletionConfidence.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public ThreeState shouldFocusLookup(@NotNull CompletionParameters parameters) {
  final PsiElement position = parameters.getPosition();

  PsiFile file = position.getContainingFile();
  if (file instanceof GroovyFile && GroovyScriptUtil.getScriptType((GroovyFile)file) != GroovyScriptUtil.DEFAULT_TYPE) {
    return ThreeState.NO;
  }

  if (position.getParent() instanceof GrReferenceElement &&
      PsiJavaPatterns.psiElement().afterLeaf(PsiJavaPatterns.psiElement().withText("(").withParent(GrForStatement.class)).accepts(position)) {
    return ThreeState.NO;
  }

  if (position.getParent() instanceof GrReferenceExpression) {
    final GrReferenceExpression ref = (GrReferenceExpression)position.getParent();
    final GrExpression qualifier = ref.getQualifierExpression();
    if (qualifier == null) {
      if (isPossibleClosureParameter(ref)) return ThreeState.NO;
      if (parameters.getOriginalFile().getUserData(GROOVY_SHELL_FILE) == Boolean.TRUE) {
        return ThreeState.NO;
      }

      GrExpression runtimeQualifier = PsiImplUtil.getRuntimeQualifier(ref);
      if (runtimeQualifier != null && runtimeQualifier.getType() == null) {
        return ThreeState.NO;
      }

      return ThreeState.YES;
    }

    if (qualifier.getType() == null) {
      return ThreeState.NO;
    }
    return ThreeState.YES;
  }
  return ThreeState.UNSURE;
}