Java Code Examples for org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument

The following are top voted examples for showing how to use org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument. 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: 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 2
Project: intellij-ce-playground   File: GroovyAnnotator.java   Source Code and License 6 votes vote down vote up
@Override
public void visitListOrMap(GrListOrMap listOrMap) {
  final PsiReference constructorReference = listOrMap.getReference();
  if (constructorReference instanceof LiteralConstructorReference &&
      ((LiteralConstructorReference)constructorReference).getConstructedClassType() != null) {
    final PsiElement startToken = listOrMap.getFirstChild();
    if (startToken != null && startToken.getNode().getElementType() == GroovyTokenTypes.mLBRACK) {
      myHolder.createInfoAnnotation(startToken, null).setTextAttributes(GroovySyntaxHighlighter.LITERAL_CONVERSION);
    }
    final PsiElement endToken = listOrMap.getLastChild();
    if (endToken != null && endToken.getNode().getElementType() == GroovyTokenTypes.mRBRACK) {
      myHolder.createInfoAnnotation(endToken, null).setTextAttributes(GroovySyntaxHighlighter.LITERAL_CONVERSION);
    }
  }

  final GrNamedArgument[] namedArguments = listOrMap.getNamedArguments();
  final GrExpression[] expressionArguments = listOrMap.getInitializers();

  if (namedArguments.length != 0 && expressionArguments.length != 0) {
    myHolder.createErrorAnnotation(listOrMap, GroovyBundle.message("collection.literal.contains.named.argument.and.expression.items"));
  }

  checkNamedArgs(namedArguments, false);
}
 
Example 3
Project: intellij-ce-playground   File: GroovyExpectedTypesProvider.java   Source Code and License 6 votes vote down vote up
@Override
public void visitNamedArgument(GrNamedArgument argument) {
  GrArgumentLabel label = argument.getLabel();
  if (label != null) {
    PsiElement pparent = argument.getParent().getParent();
    if (pparent instanceof GrCall && resolvesToDefaultConstructor(((GrCall)pparent))) {
      final GroovyResolveResult resolveResult = label.advancedResolve();
      PsiElement resolved = resolveResult.getElement();
      PsiType type = resolved instanceof PsiField ?
                        ((PsiField)resolved).getType() :
                     resolved instanceof PsiMethod && GroovyPropertyUtils.isSimplePropertySetter((PsiMethod)resolved) ?
                        ((PsiMethod)resolved).getParameterList().getParameters()[0].getType()
                     : null;

      PsiType substituted = resolveResult.getSubstitutor().substitute(type);
      if (substituted != null) {
        myResult = createSimpleSubTypeResult(substituted);
      }
    }
  }
}
 
Example 4
Project: intellij-ce-playground   File: GroovyExpectedTypesProvider.java   Source Code and License 6 votes vote down vote up
@Override
public void visitMethodCallExpression(GrMethodCallExpression methodCall) {
  final GrExpression invokedExpression = methodCall.getInvokedExpression();
  if (myExpression.equals(invokedExpression)) {
    myResult = new TypeConstraint[]{SubtypeConstraint.create(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, methodCall)};
    return;
  }

  final GrClosableBlock[] closureArgs = methodCall.getClosureArguments();
  if (ArrayUtil.contains(myExpression, closureArgs)) {
    final GrArgumentList argumentList = methodCall.getArgumentList();
    final GrNamedArgument[] namedArgs = argumentList.getNamedArguments();
    final GrExpression[] expressionArgs = argumentList.getExpressionArguments();
    final GroovyResolveResult[] callVariants = ResolveUtil.getCallVariants(myExpression);
    processCallVariants(methodCall, callVariants, namedArgs, expressionArgs, closureArgs);
  }
}
 
Example 5
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 6
Project: intellij-ce-playground   File: GrListOrMapImpl.java   Source Code and License 6 votes vote down vote up
@Nullable
private static PsiClassType inferMapInitializerType(GrListOrMapImpl listOrMap) {
  GrNamedArgument[] namedArgs = listOrMap.getNamedArguments();

  if (namedArgs.length == 0) {
    PsiType lType = PsiImplUtil.inferExpectedTypeForDiamond(listOrMap);

    if (lType instanceof PsiClassType && InheritanceUtil.isInheritor(lType, CommonClassNames.JAVA_UTIL_MAP)) {
      GlobalSearchScope scope = listOrMap.getResolveScope();
      JavaPsiFacade facade = JavaPsiFacade.getInstance(listOrMap.getProject());
      PsiClass hashMap = facade.findClass(GroovyCommonClassNames.JAVA_UTIL_LINKED_HASH_MAP, scope);
      if (hashMap == null) hashMap = facade.findClass(CommonClassNames.JAVA_UTIL_MAP, scope);
      if (hashMap != null) {
        PsiSubstitutor mapSubstitutor = PsiSubstitutor.EMPTY.
          put(hashMap.getTypeParameters()[0], com.intellij.psi.util.PsiUtil.substituteTypeParameter(lType,  CommonClassNames.JAVA_UTIL_MAP, 0, false)).
          put(hashMap.getTypeParameters()[1], com.intellij.psi.util.PsiUtil.substituteTypeParameter(lType,  CommonClassNames.JAVA_UTIL_MAP, 1, false));
        return facade.getElementFactory().createType(hashMap, mapSubstitutor);
      }
    }
  }

  return GrMapType.createFromNamedArgs(listOrMap, namedArgs);
}
 
Example 7
Project: intellij-ce-playground   File: GrNewExpressionImpl.java   Source Code and License 6 votes vote down vote up
@Override
public GrNamedArgument addNamedArgument(final GrNamedArgument namedArgument) throws IncorrectOperationException {
  final GrArgumentList list = getArgumentList();
  if (list == null) { //so it is not anonymous class declaration
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject());
    final GrArgumentList newList = factory.createExpressionArgumentList();
    PsiElement last = getLastChild();
    assert last != null;
    while (last.getPrevSibling() instanceof PsiWhiteSpace || last.getPrevSibling() instanceof PsiErrorElement) {
      last = last.getPrevSibling();
      assert last != null;
    }
    ASTNode astNode = last.getNode();
    assert astNode != null;
    getNode().addChild(newList.getNode(), astNode);
  }
  return super.addNamedArgument(namedArgument);
}
 
Example 8
Project: intellij-ce-playground   File: CodeBlockGenerator.java   Source Code and License 6 votes vote down vote up
private static String genIteratorVar(GrVariableDeclaration variableDeclaration,
                                     StringBuilder builder,
                                     ExpressionContext expressionContext,
                                     @NotNull GrExpression tupleInitializer,
                                     PsiType iteratorType,
                                     GroovyResolveResult iteratorMethodResult) {

  final String iteratorName = GenerationUtil.suggestVarName(iteratorType, variableDeclaration, expressionContext);
  builder.append("final ");
  TypeWriter.writeType(builder, iteratorType, variableDeclaration);
  builder.append(' ').append(iteratorName).append(" = ");

  GenerationUtil
    .invokeMethodByResolveResult(tupleInitializer, iteratorMethodResult, "iterator", GrExpression.EMPTY_ARRAY, GrNamedArgument.EMPTY_ARRAY,
                              GrClosableBlock.EMPTY_ARRAY, new ExpressionGenerator(builder, expressionContext), variableDeclaration);
  builder.append(";\n");
  return iteratorName;
}
 
Example 9
Project: intellij-ce-playground   File: SetterWriter.java   Source Code and License 6 votes vote down vote up
private void writeBody(boolean aStatic,
                       @NotNull PsiParameter[] parameters,
                       @NotNull PsiParameter parameter, final GroovyPsiElement place) {
  //method body
  myBuffer.append("{\n");

  //arg initialization
  myContext.myUsedVarNames.add("propOwner");
  final GrExpression[] args = generateArguments(parameters, place);

  new ExpressionGenerator(myBuffer, myContext).invokeMethodOn(
    mySetter,
    aStatic ? null : GroovyPsiElementFactory.getInstance(myContext.project).createExpressionFromText("propOwner", place),
    args,
    GrNamedArgument.EMPTY_ARRAY,
    GrClosableBlock.EMPTY_ARRAY,
    PsiSubstitutor.EMPTY,
    place
  );
  myBuffer.append(";\n");
  myBuffer.append("return ").append(parameter.getName()).append(";\n");
  myBuffer.append("}\n");
}
 
Example 10
Project: intellij-ce-playground   File: ExpressionGenerator.java   Source Code and License 6 votes vote down vote up
private void initializeField(String varName,
                             PsiType type,
                             PsiClass resolved,
                             PsiSubstitutor substitutor,
                             String fieldName,
                             GrExpression expression) {
  StringBuilder builder = new StringBuilder();
  final PsiMethod setter = GroovyPropertyUtils.findPropertySetter(resolved, fieldName, false, true);
  if (setter != null) {
    final GrVariableDeclaration var = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", type, varName);
    final GrReferenceExpression caller = factory.createReferenceExpressionFromText(varName, var);
    invokeMethodOn(setter, caller, new GrExpression[]{expression}, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, substitutor,
                   expression);
  }
  else {
    builder.append(varName).append('.').append(fieldName).append(" = ");
    expression.accept(new ExpressionGenerator(builder, context));
  }
  context.myStatements.add(builder.toString());
}
 
Example 11
Project: intellij-ce-playground   File: GrArgumentListImpl.java   Source Code and License 6 votes vote down vote up
@Override
public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
  if (element instanceof GrNamedArgument || element instanceof GrExpression) {
    if (anchor == null) anchor = getLastChild();
    if (anchor == null) {
      return super.addBefore(element, anchor);
    }
    else {
      anchor = anchor.getPrevSibling();
    }
    while (anchor != null && !(anchor instanceof GrExpression) && !(anchor instanceof GrNamedArgument)) {
      anchor = anchor.getPrevSibling();
    }
    return addAfter(element, anchor);
  }
  return super.addBefore(element, anchor);
}
 
Example 12
Project: intellij-ce-playground   File: GrArgumentListImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void deleteChildInternal(@NotNull ASTNode child) {
  PsiElement element = child.getPsi();
  if (element instanceof GrExpression || element instanceof GrNamedArgument) {
    ASTNode prev = TreeUtil.skipElementsBack(child.getTreePrev(), TokenSets.WHITE_SPACES_OR_COMMENTS);
    if (prev != null && prev.getElementType() == GroovyTokenTypes.mCOMMA) {
      final ASTNode pprev = prev.getTreePrev();
      if (pprev != null && PsiImplUtil.isWhiteSpaceOrNls(pprev)) {
        super.deleteChildInternal(pprev);
      }
      super.deleteChildInternal(prev);
    }
    else {
      ASTNode next = TreeUtil.skipElements(child.getTreeNext(), TokenSets.WHITE_SPACES_OR_COMMENTS);
      if (next != null && next.getElementType() == GroovyTokenTypes.mCOMMA) {
        final ASTNode nnext = next.getTreeNext();
        if (nnext != null && PsiImplUtil.isWhiteSpaceOrNls(nnext)) {
          super.deleteChildInternal(nnext);
        }
        super.deleteChildInternal(next);
      }
    }
  }
  super.deleteChildInternal(child);
}
 
Example 13
Project: intellij-ce-playground   File: GenerationUtil.java   Source Code and License 6 votes vote down vote up
public static void invokeMethodByResolveResult(@Nullable GrExpression caller,
                                               @NotNull GroovyResolveResult resolveResult,
                                               @NotNull String methodName,
                                               @NotNull GrExpression[] exprs,
                                               @NotNull GrNamedArgument[] namedArgs,
                                               @NotNull GrClosableBlock[] closureArgs,
                                               @NotNull ExpressionGenerator expressionGenerator,
                                               @NotNull GroovyPsiElement psiContext) {
  final PsiElement resolved = resolveResult.getElement();
  if (resolved instanceof PsiMethod) {
    final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
    expressionGenerator.invokeMethodOn(((PsiMethod)resolved), caller, exprs, namedArgs, closureArgs, substitutor, psiContext);
    return;
  }
  //other case
  final StringBuilder builder = expressionGenerator.getBuilder();
  final ExpressionContext expressionContext = expressionGenerator.getContext();

  if (caller != null) {
    caller.accept(expressionGenerator);
    builder.append('.');
  }
  builder.append(methodName);
  final ArgumentListGenerator argumentListGenerator = new ArgumentListGenerator(builder, expressionContext);
  argumentListGenerator.generate(null, exprs, namedArgs, closureArgs, psiContext);
}
 
Example 14
Project: intellij-ce-playground   File: CustomMethodInvocator.java   Source Code and License 6 votes vote down vote up
public static boolean invokeMethodOn(@NotNull ExpressionGenerator generator,
                                     @NotNull GrGdkMethod method,
                                     @Nullable GrExpression caller,
                                     @NotNull GrExpression[] exprs,
                                     @NotNull GrNamedArgument[] namedArgs,
                                     @NotNull GrClosableBlock[] closures,
                                     @NotNull PsiSubstitutor substitutor,
                                     @NotNull GroovyPsiElement context) {
  final PsiMethod staticMethod = method.getStaticMethod();
  for (CustomMethodInvocator invocator : EP_NAME.getExtensions()) {
    if (invocator.invoke(generator, staticMethod, caller, exprs, namedArgs, closures, substitutor, context)) {
      return true;
    }
  }

  return false;
}
 
Example 15
Project: intellij-ce-playground   File: GroovyParameterInfoHandler.java   Source Code and License 6 votes vote down vote up
private static int getCurrentParameterIndex(GroovyPsiElement place, int offset) {
  if (place instanceof GrArgumentList) {
    GrArgumentList list = (GrArgumentList)place;

    int idx = (list.getNamedArguments().length > 0) ? 1 : 0;
    for (PsiElement child = list.getFirstChild(); child != null; child = child.getNextSibling()) {
      if (child.getTextRange().contains(offset)) {
        if (child instanceof GrNamedArgument) return 0;
        return idx;
      }

      if (child.getNode().getElementType() == GroovyTokenTypes.mCOMMA) idx++;
      if (isNamedArgWithPriorComma(child)) idx--;
    }
  }
  return -1;
}
 
Example 16
Project: intellij-ce-playground   File: GenerationUtil.java   Source Code and License 6 votes vote down vote up
@NotNull
public static GroovyResolveResult resolveMethod(@Nullable GrExpression caller,
                                                 @NotNull String methodName,
                                                 @NotNull GrExpression[] exprs,
                                                 @NotNull GrNamedArgument[] namedArgs,
                                                 @NotNull GrClosableBlock[] closureArgs,
                                                 @NotNull GroovyPsiElement psiContext) {
  GroovyResolveResult call = GroovyResolveResult.EMPTY_RESULT;

  final PsiType type;
  if (caller == null) {
    type = GroovyPsiElementFactory.getInstance(psiContext.getProject()).createExpressionFromText("this", psiContext).getType();
  }
  else {
    type = caller.getType();
  }
  if (type != null) {
    final PsiType[] argumentTypes = PsiUtil.getArgumentTypes(namedArgs, exprs, closureArgs, false, null, false);
    final GroovyResolveResult[] candidates = ResolveUtil.getMethodCandidates(type, methodName, psiContext, argumentTypes);
    call = PsiImplUtil.extractUniqueResult(candidates);
  }
  return call;
}
 
Example 17
Project: intellij-ce-playground   File: GantScriptType.java   Source Code and License 6 votes vote down vote up
@Nullable
private static String getTargetName(Location location) {
  PsiElement parent = location.getPsiElement();
  while (!(parent.getParent() instanceof PsiFile) && parent.getParent() != null) {
    parent = parent.getParent();
  }
  if (parent instanceof GrMethodCallExpression && PsiUtil.isMethodCall((GrMethodCallExpression)parent, "target")) {
    final GrNamedArgument[] args = ((GrMethodCallExpression)parent).getNamedArguments();
    if (args.length == 1) {
      final GrArgumentLabel label = args[0].getLabel();
      if (label != null) {
        return label.getName();
      }
    }
    return null;
  }
  return null;
}
 
Example 18
Project: intellij-ce-playground   File: GantUtils.java   Source Code and License 6 votes vote down vote up
public static GrArgumentLabel[] getScriptTargets(GroovyFile file) {
  ArrayList<GrArgumentLabel> labels = new ArrayList<GrArgumentLabel>();
  for (PsiElement child : file.getChildren()) {
    if (child instanceof GrMethodCallExpression) {
      GrMethodCallExpression call = (GrMethodCallExpression)child;
      GrNamedArgument[] arguments = call.getNamedArguments();
      if (arguments.length == 1) {
        GrArgumentLabel label = arguments[0].getLabel();
        if (label != null && isPlainIdentifier(label)) {
          labels.add(label);
        }
      }
    }
  }
  return labels.toArray(new GrArgumentLabel[labels.size()]);
}
 
Example 19
Project: intellij-ce-playground   File: SwitchStatementGenerator.java   Source Code and License 6 votes vote down vote up
private static void writeCondition(StringBuilder builder,
                                   ExpressionContext context,
                                   GrCaseSection section,
                                   GrCaseLabel[] labels,
                                   GrExpression[] args) {
  builder.append("if (");
  for (GrCaseLabel label : labels) {
    if (label.isDefault()) {
      builder.append("true");
    }
    else {
      GenerationUtil.invokeMethodByName(
        label.getValue(),
        "isCase",
        args,
        GrNamedArgument.EMPTY_ARRAY,
        GrClosableBlock.EMPTY_ARRAY,
        new ExpressionGenerator(builder, context),
        section
      );
    }
    builder.append("||");
  }
  builder.delete(builder.length() - 2, builder.length());
  builder.append(") ");
}
 
Example 20
Project: intellij-ce-playground   File: GrSortMapKeysIntention.java   Source Code and License 6 votes vote down vote up
@NotNull
private static GrListOrMap constructNewMap(@NotNull GrNamedArgument[] args, Project project) {
  StringBuilder builder = new StringBuilder();

  builder.append("[");

  Arrays.sort(args, new Comparator<GrNamedArgument>() {
    @Override
    public int compare(GrNamedArgument o1, GrNamedArgument o2) {
      final String l1 = o1.getLabelName();
      final String l2 = o2.getLabelName();
      assert l1 != null && l2 != null;

      return l1.compareTo(l2);
    }
  });

  for (GrNamedArgument arg : args) {
    builder.append(arg.getText()).append(",\n");
  }


  builder.replace(builder.length() - 2, builder.length(), "]");

  return (GrListOrMap)GroovyPsiElementFactory.getInstance(project).createExpressionFromText(builder);
}
 
Example 21
Project: intellij-ce-playground   File: ConvertMapToClassIntention.java   Source Code and License 6 votes vote down vote up
public static GrTypeDefinition createClass(Project project, GrNamedArgument[] namedArguments, String packageName, String className) {
  StringBuilder classText = new StringBuilder();
  if (!packageName.isEmpty()) {
    classText.append("package ").append(packageName).append('\n');
  }
  classText.append("class ").append(className).append(" {\n");
  for (GrNamedArgument argument : namedArguments) {
    final String fieldName = argument.getLabelName();
    final GrExpression expression = argument.getExpression();
    LOG.assertTrue(expression != null);

    final PsiType type = TypesUtil.unboxPrimitiveTypeWrapper(expression.getType());
    if (type != null) {
      classText.append(type.getCanonicalText());
    }
    else {
      classText.append(GrModifier.DEF);
    }
    classText.append(' ').append(fieldName).append('\n');
  }
  classText.append('}');
  return GroovyPsiElementFactory.getInstance(project).createTypeDefinition(classText.toString());
}
 
Example 22
Project: intellij-ce-playground   File: ConvertMapToClassIntention.java   Source Code and License 6 votes vote down vote up
@Override
public boolean satisfiedBy(PsiElement element) {
  if (!(element instanceof GrListOrMap)) return false;
  final GrListOrMap map = (GrListOrMap)element;
  final GrNamedArgument[] namedArguments = map.getNamedArguments();
  final GrExpression[] initializers = map.getInitializers();
  if (initializers.length != 0) return false;

  for (GrNamedArgument argument : namedArguments) {
    final GrArgumentLabel label = argument.getLabel();
    final GrExpression expression = argument.getExpression();
    if (label == null || expression == null) return false;
    if (label.getName() == null) return false;
  }
  return true;
}
 
Example 23
Project: intellij-ce-playground   File: AbstractGradleCompletionContributor.java   Source Code and License 5 votes vote down vote up
@Nullable
protected String findNamedArgumentValue(@Nullable GrNamedArgumentsOwner namedArgumentsOwner, @NotNull String label) {
  if (namedArgumentsOwner == null) return null;
  GrNamedArgument namedArgument = namedArgumentsOwner.findNamedArgument(label);
  if (namedArgument == null) return null;

  GrExpression expression = namedArgument.getExpression();
  if (!(expression instanceof GrLiteralImpl)) return null;
  Object value = GrLiteralImpl.class.cast(expression).getValue();
  return value == null ? null : String.valueOf(value);
}
 
Example 24
Project: intellij-ce-playground   File: GradleDocumentationProvider.java   Source Code and License 5 votes vote down vote up
@Nullable
private static String findDoc(@Nullable PsiElement element, Object argValue) {
  String result = null;
  if (element instanceof GrLiteral) {
    GrLiteral grLiteral = (GrLiteral)element;
    PsiElement stmt = PsiTreeUtil.findFirstParent(grLiteral, new Condition<PsiElement>() {
      @Override
      public boolean value(PsiElement psiElement) {
        return psiElement instanceof GrCall;
      }
    });
    if (stmt instanceof GrCall) {
      GrCall grCall = (GrCall)stmt;
      PsiMethod psiMethod = grCall.resolveMethod();
      if (psiMethod != null && psiMethod.getContainingClass() != null) {
        //noinspection ConstantConditions
        String qualifiedName = psiMethod.getContainingClass().getQualifiedName();
        if (grLiteral.getParent() instanceof GrNamedArgument) {
          GrNamedArgument namedArgument = (GrNamedArgument)grLiteral.getParent();
          String key = StringUtil.join(new String[]{
            "gradle.documentation",
            qualifiedName,
            psiMethod.getName(),
            namedArgument.getLabelName(),
            String.valueOf(argValue),
          }, "."
          );

          result = GradleDocumentationBundle.messageOrDefault(key, "");
        }
      }
    }
  }
  return result;
}
 
Example 25
Project: intellij-ce-playground   File: EquivalenceChecker.java   Source Code and License 5 votes vote down vote up
private static boolean applicationStatementsAreEquivalent(GrApplicationStatement statement1,
                                                          GrApplicationStatement statement2) {
  final GrExpression funExpression1 = statement1.getInvokedExpression();
  final GrExpression funExpression2 = statement2.getInvokedExpression();
  if (!expressionsAreEquivalent(funExpression1, funExpression2)) {
    return false;
  }

  final GrArgumentList argumentList1 = statement1.getArgumentList();
  if (argumentList1 == null) {
    return false;
  }
  final GrArgumentList argumentList2 = statement2.getArgumentList();
  if (argumentList2 == null) {
    return false;
  }
  final GrExpression[] args1 = argumentList1.getExpressionArguments();
  final GrExpression[] args2 = argumentList2.getExpressionArguments();
  if (!expressionListsAreEquivalent(args1, args2)) {
    return false;
  }
  final GrNamedArgument[] namedArgs1 = argumentList1.getNamedArguments();
  final GrNamedArgument[] namedArgs2 = argumentList2.getNamedArguments();
  if (!namedArgumentListsAreEquivalent(namedArgs1, namedArgs2)) {
    return false;
  }
  return true;
}
 
Example 26
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 27
Project: intellij-ce-playground   File: EquivalenceChecker.java   Source Code and License 5 votes vote down vote up
private static boolean namedArgumentListsAreEquivalent(GrNamedArgument[] namedArgs1, GrNamedArgument[] namedArgs2) {
  if (namedArgs1.length != namedArgs2.length) {
    return false;
  }
  for (GrNamedArgument arg1 : namedArgs1) {
    final GrArgumentLabel label1 = arg1.getLabel();
    if (label1 == null) {
      return false;
    }
    final String name1 = label1.getName();
    boolean found = false;
    final GrExpression expression1 = arg1.getExpression();
    for (GrNamedArgument arg2 : namedArgs2) {
      final GrArgumentLabel label2 = arg2.getLabel();
      if (label2 == null) {
        return false;
      }
      final String name2 = label2.getName();
      final GrExpression expression2 = arg2.getExpression();
      if (name1 == null) {
        if (name2 == null &&
            expressionsAreEquivalent(((GrExpression)label1.getNameElement()), (GrExpression)label2.getNameElement()) &&
            expressionsAreEquivalent(expression1, expression2)) {
          found = true;
          break;
        }
      }
      else if (name1.equals(name2) && expressionsAreEquivalent(expression1, expression2)) {
        found = true;
        break;
      }
    }
    if (!found) {
      return false;
    }
  }
  return true;
}
 
Example 28
Project: intellij-ce-playground   File: GroovyTypeCheckVisitorHelper.java   Source Code and License 5 votes vote down vote up
@Nullable
public static List<GrExpression> getExpressionArgumentsOfCall(@NotNull GrArgumentList argumentList) {
  final ArrayList<GrExpression> args = ContainerUtil.newArrayList();

  for (GroovyPsiElement arg : argumentList.getAllArguments()) {
    if (arg instanceof GrSpreadArgument) {
      GrExpression spreaded = ((GrSpreadArgument)arg).getArgument();
      if (spreaded instanceof GrListOrMap && !((GrListOrMap)spreaded).isMap()) {
        Collections.addAll(args, ((GrListOrMap)spreaded).getInitializers());
      }
      else {
        return null;
      }
    }
    else if (arg instanceof GrExpression) {
      args.add((GrExpression)arg);
    }
    else if (arg instanceof GrNamedArgument) {
      args.add(((GrNamedArgument)arg).getExpression());
    }
  }

  final PsiElement parent = argumentList.getParent();
  if (parent instanceof GrIndexProperty && PsiUtil.isLValue((GroovyPsiElement)parent)) {
    args.add(TypeInferenceHelper.getInitializerFor((GrExpression)parent));
  }
  else if (parent instanceof GrMethodCallExpression) {
    ContainerUtil.addAll(args, ((GrMethodCallExpression)parent).getClosureArguments());
  }
  return args;
}
 
Example 29
Project: intellij-ce-playground   File: GroovyAnnotator.java   Source Code and License 5 votes vote down vote up
@Override
public void visitNamedArgument(GrNamedArgument argument) {
  PsiElement parent = argument.getParent();
  if (parent instanceof GrArgumentList) {
    final PsiElement pparent = parent.getParent();
    if (pparent instanceof GrIndexProperty) {
      myHolder.createErrorAnnotation(argument, GroovyBundle.message("named.arguments.are.not.allowed.inside.index.operations"));
    }
  }
}
 
Example 30
Project: intellij-ce-playground   File: GroovyAnnotator.java   Source Code and License 5 votes vote down vote up
private void highlightNamedArgs(GrNamedArgument[] namedArguments) {
  for (GrNamedArgument namedArgument : namedArguments) {
    final GrArgumentLabel label = namedArgument.getLabel();
    if (label != null && label.getExpression() == null && label.getNameElement().getNode().getElementType() != GroovyTokenTypes.mSTAR) {
      myHolder.createInfoAnnotation(label, null).setTextAttributes(GroovySyntaxHighlighter.MAP_KEY);
    }
  }
}
 
Example 31
Project: intellij-ce-playground   File: ExpressionGenerator.java   Source Code and License 5 votes vote down vote up
private GrExpression[] generateArgsForInvokeMethod(String name,
                                                   GrExpression[] exprs,
                                                   GrNamedArgument[] namedArgs,
                                                   GrClosableBlock[] clArgs,
                                                   GroovyPsiElement psiContext) {
  GrExpression[] result = new GrExpression[2];
  result[0] = factory.createExpressionFromText("\"" + name + "\"");
  StringBuilder builder = new StringBuilder();
  builder.append('[');
  if (namedArgs.length > 0) {
    builder.append('[');
    for (GrNamedArgument namedArg : namedArgs) {
      builder.append(namedArg.getText()).append(',');
    }
    builder.delete(builder.length() - 1, builder.length());
    //builder.removeFromTheEnd(1);
    builder.append("],");
  }
  for (GrExpression expr : exprs) {
    builder.append(expr.getText()).append(',');
  }

  for (GrClosableBlock clArg : clArgs) {
    builder.append(clArg.getText()).append(',');
  }
  if (namedArgs.length + exprs.length + clArgs.length > 0) builder.delete(builder.length() - 1, builder.length());
  //if (namedArgs.length + exprs.length + clArgs.length > 0) builder.removeFromTheEnd(1);
  builder.append("] as Object[]");

  result[1] = factory.createExpressionFromText(builder.toString(), psiContext);
  return result;
}
 
Example 32
Project: intellij-ce-playground   File: ResolveUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
private static PsiClass getLiteralSuperClass(GrClosableBlock closure) {
  PsiClassType type;
  if (closure.getParent() instanceof GrNamedArgument && closure.getParent().getParent() instanceof GrListOrMap) {
    type = LiteralConstructorReference.getTargetConversionType((GrListOrMap)closure.getParent().getParent());
  }
  else {
    type = LiteralConstructorReference.getTargetConversionType(closure);
  }
  return type != null ? type.resolve() : null;
}
 
Example 33
Project: intellij-ce-playground   File: GroovyMethodArgumentReferenceContributor.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
  GrExpression argument = (GrExpression)element;
  PsiElement parent = element.getParent();

  if (parent instanceof GrConditionalExpression) {
    // support case: foo(a > b ? "aaa" : "bbb")

    if (((GrConditionalExpression)parent).getCondition() == parent) return PsiReference.EMPTY_ARRAY;
    argument = (GrConditionalExpression)parent;
    parent = parent.getParent();
  }

  if (parent instanceof GrListOrMap) {
    // support case: foo(["aaa", "bbb"])
    if (!((GrListOrMap)parent).isMap()) {
      argument = (GrListOrMap)parent;
      parent = parent.getParent();
    }
  }

  if (parent instanceof GrNamedArgument) {
    return createReferencesForNamedArgument(element, (GrNamedArgument)parent, context);
  }

  if (parent instanceof GrArgumentList) {
    GrArgumentList argumentList = (GrArgumentList)parent;
    int index = argumentList.getExpressionArgumentIndex(argument);

    PsiElement call = argumentList.getParent();
    if (!(call instanceof GrMethodCall)) return PsiReference.EMPTY_ARRAY;

    return PsiReference.EMPTY_ARRAY;
  }

  return PsiReference.EMPTY_ARRAY;
}
 
Example 34
Project: intellij-ce-playground   File: GroovyNamedArgumentPattern.java   Source Code and License 5 votes vote down vote up
public GroovyNamedArgumentPattern withLabel(@NotNull final String label) {
  return with(new PatternCondition<GrNamedArgument>("left") {
    @Override
    public boolean accepts(@NotNull GrNamedArgument namedArgument, final ProcessingContext context) {
      return label.equals(namedArgument.getLabelName());
    }
  });
}
 
Example 35
Project: intellij-ce-playground   File: GroovyNamedArgumentPattern.java   Source Code and License 5 votes vote down vote up
public GroovyNamedArgumentPattern withLabel(@NotNull final StringPattern labelPattern) {
  return with(new PatternCondition<GrNamedArgument>("left") {
    @Override
    public boolean accepts(@NotNull GrNamedArgument namedArgument, final ProcessingContext context) {
      return labelPattern.accepts(namedArgument.getLabelName(), context);
    }
  });
}
 
Example 36
Project: intellij-ce-playground   File: GroovyNamedArgumentPattern.java   Source Code and License 5 votes vote down vote up
public GroovyNamedArgumentPattern isParameterOfMethodCall(@Nullable final ElementPattern<? extends GrCall> methodCall) {
  return with(new PatternCondition<GrNamedArgument>("left") {
    @Override
    public boolean accepts(@NotNull GrNamedArgument namedArgument, final ProcessingContext context) {
      GrCall call = PsiUtil.getCallByNamedParameter(namedArgument);

      return call != null && (methodCall == null || methodCall.accepts(call, context));
    }
  });
}
 
Example 37
Project: intellij-ce-playground   File: GroovyExpectedTypesProvider.java   Source Code and License 5 votes vote down vote up
private void processCallVariants(@NotNull PsiElement place,
                                 @NotNull GroovyResolveResult[] variants,
                                 @NotNull GrNamedArgument[] namedArguments,
                                 @NotNull GrExpression[] expressionArguments,
                                 @NotNull GrClosableBlock[] closureArguments) {

  List<Pair<PsiParameter, PsiType>> expectedParams =
    ResolveUtil.collectExpectedParamsByArg(place, variants, namedArguments, expressionArguments, closureArguments, myExpression);

  collectExpectedTypeFromPossibleParams(expectedParams);
}
 
Example 38
Project: intellij-ce-playground   File: GroovyExpectedTypesProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void visitBinaryExpression(GrBinaryExpression expression) {
  final IElementType type = expression.getOperationTokenType();
  final GrExpression left = expression.getLeftOperand();
  final GrExpression right = expression.getRightOperand();

  final GrExpression other = myExpression == left ? right : left;
  final PsiType otherType = other != null ? other.getType() : null;

  if (otherType == null) return;

  final GroovyResolveResult[] callVariants = expression.multiResolve(true);
  if (myExpression == left || callVariants.length == 0) {
    if (type == GroovyTokenTypes.mPLUS && otherType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
      final PsiClassType obj = TypesUtil.getJavaLangObject(expression);
      myResult = createSimpleSubTypeResult(obj);
    }
    else if (type == GroovyTokenTypes.mREGEX_FIND || type == GroovyTokenTypes.mREGEX_MATCH) {
      final PsiClassType string = TypesUtil.createType(CommonClassNames.JAVA_LANG_STRING, expression);
      myResult = createSimpleSubTypeResult(string);
    }
    else {
      myResult = createSimpleSubTypeResult(otherType);
    }
  }
  else { //myExpression == right
    processCallVariants(expression, callVariants, GrNamedArgument.EMPTY_ARRAY, new GrExpression[]{myExpression},
                        GrClosableBlock.EMPTY_ARRAY);
  }
}
 
Example 39
Project: intellij-ce-playground   File: PsiUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
public static PsiElement getNamedArgumentValue(GrNamedArgument otherNamedArgument, String argumentName) {
  PsiElement parent = otherNamedArgument.getParent();

  if (!(parent instanceof GrNamedArgumentsOwner)) return null;

  GrNamedArgument namedArgument = ((GrNamedArgumentsOwner)parent).findNamedArgument(argumentName);
  if (namedArgument == null) return null;

  return namedArgument.getExpression();
}
 
Example 40
Project: intellij-ce-playground   File: PsiUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Returns all arguments passed to method. First argument is null if Named Arguments is present.
 */
public static GrExpression[] getAllArguments(@NotNull GrCall call) {
  GrArgumentList argumentList = call.getArgumentList();
  if (argumentList == null) return GrExpression.EMPTY_ARRAY;

  GrClosableBlock[] closureArguments = call.getClosureArguments();
  GrExpression[] expressionArguments = argumentList.getExpressionArguments();
  GrNamedArgument[] namedArguments = argumentList.getNamedArguments();

  int length = expressionArguments.length + closureArguments.length;
  int k = 0;
  if (namedArguments.length > 0) {
    length++;
    k = 1;
  }

  GrExpression[] res = new GrExpression[length];
  for (GrExpression expressionArgument : expressionArguments) {
    res[k++] = expressionArgument;
  }

  for (GrClosableBlock closureArgument : closureArguments) {
    res[k++] = closureArgument;
  }

  return res;
}
 
Example 41
Project: intellij-ce-playground   File: PsiUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
public static GrMethodCall getMethodCallByNamedParameter(GrNamedArgument namedArgument) {
  GrCall res = getCallByNamedParameter(namedArgument);
  if (res instanceof GrMethodCall) return (GrMethodCall)res;

  return null;
}
 
Example 42
Project: intellij-ce-playground   File: PsiUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
public static GrCall getCallByNamedParameter(GrNamedArgument namedArgument) {
  PsiElement parent = namedArgument.getParent();

  PsiElement eMethodCall;

  if (parent instanceof GrArgumentList) {
    eMethodCall = parent.getParent();
  }
  else {
    if (!(parent instanceof GrListOrMap)) return null;

    PsiElement eArgumentList = parent.getParent();
    if (!(eArgumentList instanceof GrArgumentList)) return null;

    GrArgumentList argumentList = (GrArgumentList)eArgumentList;

    if (argumentList.getNamedArguments().length > 0) return null;
    if (argumentList.getExpressionArgumentIndex((GrListOrMap)parent) != 0) return null;

    eMethodCall = eArgumentList.getParent();
  }

  if (!(eMethodCall instanceof GrCall)) return null;

  return (GrCall)eMethodCall;
}
 
Example 43
Project: intellij-ce-playground   File: GrListOrMapImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void deleteChildInternal(@NotNull ASTNode child) {
  final PsiElement psi = child.getPsi();
  if (psi instanceof GrExpression || psi instanceof GrNamedArgument) {
    PsiElement prev = PsiUtil.getPrevNonSpace(psi);
    PsiElement next = PsiUtil.getNextNonSpace(psi);
    if (prev != null && prev.getNode() != null && prev.getNode().getElementType() == GroovyTokenTypes.mCOMMA) {
      super.deleteChildInternal(prev.getNode());
    }
    else if (next instanceof LeafPsiElement && next.getNode() != null && next.getNode().getElementType() == GroovyTokenTypes.mCOMMA) {
      super.deleteChildInternal(next.getNode());
    }
  }
  super.deleteChildInternal(child);
}
 
Example 44
Project: intellij-ce-playground   File: GrListOrMapImpl.java   Source Code and License 5 votes vote down vote up
@Override
@NotNull
public GrNamedArgument[] getNamedArguments() {
  GrNamedArgument[] namedArguments = myNamedArguments;
  if (namedArguments == null) {
    namedArguments = PsiTreeUtil.getChildrenOfType(this, GrNamedArgument.class);
    namedArguments = namedArguments == null ? GrNamedArgument.EMPTY_ARRAY : namedArguments;
    myNamedArguments = namedArguments;
  }
  return namedArguments;
}
 
Example 45
Project: intellij-ce-playground   File: GrCallImpl.java   Source Code and License 5 votes vote down vote up
@Override
public GrNamedArgument addNamedArgument(final GrNamedArgument namedArgument) throws IncorrectOperationException {
  GrArgumentList list = getArgumentList();
  assert list != null;
  if (list.getText().trim().isEmpty()) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject());
    final GrArgumentList newList = factory.createExpressionArgumentList();
    list = (GrArgumentList)list.replace(newList);
  }
  return list.addNamedArgument(namedArgument);
}
 
Example 46
Project: intellij-ce-playground   File: GrEnumConstantImpl.java   Source Code and License 5 votes vote down vote up
@Override
public GrNamedArgument addNamedArgument(final GrNamedArgument namedArgument) throws IncorrectOperationException {
  GrArgumentList list = getArgumentList();
  assert list != null;
  if (list.getText().trim().isEmpty()) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject());
    final GrArgumentList newList = factory.createArgumentList();
    list = (GrArgumentList)list.replace(newList);
  }
  return list.addNamedArgument(namedArgument);
}
 
Example 47
Project: intellij-ce-playground   File: GrArgumentListImpl.java   Source Code and License 5 votes vote down vote up
@Override
@NotNull
public GrNamedArgument[] getNamedArguments() {
  List<GrNamedArgument> result = new ArrayList<GrNamedArgument>();
  for (PsiElement cur = this.getFirstChild(); cur != null; cur = cur.getNextSibling()) {
    if (cur instanceof GrNamedArgument) result.add((GrNamedArgument)cur);
  }
  return result.toArray(new GrNamedArgument[result.size()]);
}
 
Example 48
Project: intellij-ce-playground   File: GrArgumentListImpl.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public GroovyPsiElement[] getAllArguments() {
  List<GroovyPsiElement> args = new ArrayList<GroovyPsiElement>();
  for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) {
    if (child instanceof GrNamedArgument || child instanceof GrExpression) args.add((GroovyPsiElement)child);
  }
  return ContainerUtil.toArray(args, new GroovyPsiElement[args.size()]);
}
 
Example 49
Project: intellij-ce-playground   File: CustomMethodInvocator.java   Source Code and License 5 votes vote down vote up
protected abstract boolean invoke(@NotNull ExpressionGenerator generator,
@NotNull PsiMethod method,
@Nullable GrExpression caller,
@NotNull GrExpression[] exprs,
@NotNull GrNamedArgument[] namedArgs,
@NotNull GrClosableBlock[] closures,
@NotNull PsiSubstitutor substitutor,
@NotNull GroovyPsiElement context);
 
Example 50
Project: intellij-ce-playground   File: PsiImplUtil.java   Source Code and License 5 votes vote down vote up
public static boolean hasNamedArguments(@Nullable GrNamedArgumentsOwner list) {
  if (list == null) return false;
  for (PsiElement child = list.getFirstChild(); child != null; child = child.getNextSibling()) {
    if (child instanceof GrNamedArgument) return true;
  }
  return false;
}
 
Example 51
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 52
Project: intellij-ce-playground   File: GppReferenceContributor.java   Source Code and License 5 votes vote down vote up
@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
  registrar.registerReferenceProvider(PlatformPatterns.psiElement(GrArgumentLabel.class), new PsiReferenceProvider() {
    @NotNull
    @Override
    public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
      final PsiElement parent = element.getParent();
      if (parent instanceof GrNamedArgument && parent.getParent() instanceof GrListOrMap) {
        return new PsiReference[]{new GppMapMemberReference(element)};
      }
      return PsiReference.EMPTY_ARRAY;
    }
  });
}
 
Example 53
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 54
Project: intellij-ce-playground   File: GppExpectedTypesContributor.java   Source Code and License 5 votes vote down vote up
private static List<TypeConstraint> addExpectedConstructorParameters(GrListOrMap list,
                                                                     GrExpression[] args,
                                                                     GrExpression arg) {
  PsiType[] argTypes = ContainerUtil.map2Array(args, PsiType.class, new NullableFunction<GrExpression, PsiType>() {
    @Override
    public PsiType fun(GrExpression grExpression) {
      return grExpression.getType();
    }
  });

  final ArrayList<TypeConstraint> result = new ArrayList<TypeConstraint>();
  for (PsiType type : GroovyExpectedTypesProvider.getDefaultExpectedTypes(list)) {
    if (type instanceof PsiClassType) {
      for (GroovyResolveResult resolveResult : PsiUtil.getConstructorCandidates((PsiClassType)type, argTypes, list)) {
        final PsiElement method = resolveResult.getElement();
        if (method instanceof PsiMethod && ((PsiMethod)method).isConstructor()) {
          final Map<GrExpression,Pair<PsiParameter,PsiType>> map = GrClosureSignatureUtil
            .mapArgumentsToParameters(resolveResult, list, false, true, GrNamedArgument.EMPTY_ARRAY, args, GrClosableBlock.EMPTY_ARRAY);
          if (map != null) {
            final Pair<PsiParameter, PsiType> pair = map.get(arg);
            if (pair != null) {
              result.add(SubtypeConstraint.create(pair.second));
            }
          }
        }
      }
    }
  }
  return result;
}
 
Example 55
Project: intellij-ce-playground   File: GrSortMapKeysIntention.java   Source Code and License 5 votes vote down vote up
private static boolean isLiteralKeys(GrNamedArgument[] args) {
  return DefaultGroovyMethods.find(args, new Closure<Boolean>(null, null) {
    public Boolean doCall(GrNamedArgument it) {
      return it.getLabel().getNameElement() == null;
    }

    public Boolean doCall() {
      return doCall(null);
    }
  }) == null;
}
 
Example 56
Project: intellij-ce-playground   File: ConvertMapToClassIntention.java   Source Code and License 5 votes vote down vote up
@Override
protected void processIntention(@NotNull PsiElement element, final Project project, Editor editor) throws IncorrectOperationException {
  final GrListOrMap map = (GrListOrMap)element;
  final GrNamedArgument[] namedArguments = map.getNamedArguments();
  LOG.assertTrue(map.getInitializers().length == 0);
  final PsiFile file = map.getContainingFile();
  final String packageName = file instanceof GroovyFileBase ? ((GroovyFileBase)file).getPackageName() : "";

  final CreateClassDialog dialog =
    new CreateClassDialog(project, GroovyBundle.message("create.class.family.name"), "", packageName, GrCreateClassKind.CLASS, true,
                          ModuleUtilCore.findModuleForPsiElement(element));
  dialog.show();
  if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;

  boolean replaceReturnType = checkForReturnFromMethod(map);
  boolean variableDeclaration = checkForVariableDeclaration(map);
  final GrParameter methodParameter = checkForMethodParameter(map);

  final String qualifiedClassName = dialog.getClassName();
  final String selectedPackageName = StringUtil.getPackageName(qualifiedClassName);
  final String shortName = StringUtil.getShortName(qualifiedClassName);

  final GrTypeDefinition typeDefinition = createClass(project, namedArguments, selectedPackageName, shortName);
  final PsiClass generatedClass = CreateClassActionBase.createClassByType(
    dialog.getTargetDirectory(), typeDefinition.getName(), PsiManager.getInstance(project), map, GroovyTemplates.GROOVY_CLASS, true);
  final PsiClass replaced = (PsiClass)generatedClass.replace(typeDefinition);
  replaceMapWithClass(project, map, replaced, replaceReturnType, variableDeclaration, methodParameter);
}
 
Example 57
Project: intellij-ce-playground   File: ExpressionGenerator.java   Source Code and License 4 votes vote down vote up
@Override
public void visitBinaryExpression(GrBinaryExpression expression) {
  final GrExpression left = expression.getLeftOperand();
  GrExpression right = expression.getRightOperand();
  final PsiType ltype = left.getType();
  final PsiElement token = expression.getOperationToken();
  final IElementType op = expression.getOperationTokenType();

  if (op == GroovyTokenTypes.mREGEX_FIND) {
    builder.append(GroovyCommonClassNames.JAVA_UTIL_REGEX_PATTERN).append(".compile(");
    if (right != null) {
      right.accept(this);
    }
    builder.append(").matcher(");
    left.accept(this);
    builder.append(')');
    return;
  }
  if (op == GroovyTokenTypes.mREGEX_MATCH) {
    builder.append(GroovyCommonClassNames.JAVA_UTIL_REGEX_PATTERN).append(".matches(");
    if (right != null) {
      right.accept(this);
    }
    builder.append(", ");
    left.accept(this);
    builder.append(')');
    return;
  }
  if ((op == GroovyTokenTypes.mEQUAL || op == GroovyTokenTypes.mNOT_EQUAL) && (GrInspectionUtil.isNull(left) || right != null && GrInspectionUtil.isNull(right))) {
    writeSimpleBinaryExpression(token, left, right);
    return;
  }

  if (op == GroovyTokenTypes.kIN && right instanceof GrReferenceExpression && InheritanceUtil.isInheritor(right.getType(), CommonClassNames.JAVA_LANG_CLASS)) {
    final PsiType type = com.intellij.psi.util.PsiUtil.substituteTypeParameter(right.getType(), CommonClassNames.JAVA_LANG_CLASS, 0, true);
    writeInstanceof(left, type, expression);
    return;
  }

  if (shouldNotReplaceOperatorWithMethod(ltype, right, op)) {
    writeSimpleBinaryExpression(token, left, right);
    return;
  }

  final GroovyResolveResult resolveResult = PsiImplUtil.extractUniqueResult(expression.multiResolve(false));
  final PsiElement resolved = resolveResult.getElement();
  if (resolved instanceof PsiMethod) {
    if (right == null) {
      right = factory.createExpressionFromText("null");
    }

    if (op == GroovyTokenTypes.mNOT_EQUAL && "equals".equals(((PsiMethod)resolved).getName())) {
      builder.append('!');
    }
    invokeMethodOn(
      ((PsiMethod)resolved),
      left,
      new GrExpression[]{right},
      GrNamedArgument.EMPTY_ARRAY,
      GrClosableBlock.EMPTY_ARRAY,
      resolveResult.getSubstitutor(),
      expression
    );
    if (op == GroovyTokenTypes.mGE) {
      builder.append(" >= 0");
    }
    else if (op == GroovyTokenTypes.mGT) {
      builder.append(" > 0");
    }
    else if (op == GroovyTokenTypes.mLT) {
      builder.append(" < 0");
    }
    else if (op == GroovyTokenTypes.mLE) builder.append(" <= 0");
  }
  else {
    writeSimpleBinaryExpression(token, left, right);
  }
}
 
Example 58
Project: intellij-ce-playground   File: ExpressionGenerator.java   Source Code and License 4 votes vote down vote up
@Override
public void visitUnaryExpression(GrUnaryExpression expression) {
  final boolean postfix = expression.isPostfix();

  final GroovyResolveResult resolveResult = PsiImplUtil.extractUniqueResult(expression.multiResolve(false));
  final PsiElement resolved = resolveResult.getElement();
  final GrExpression operand = expression.getOperand();

  IElementType opType = expression.getOperationTokenType();

  if (resolved instanceof PsiMethod) {

    if (opType == GroovyTokenTypes.mINC || opType == GroovyTokenTypes.mDEC) {
      if (!postfix || expression.getParent() instanceof GrStatementOwner || expression.getParent() instanceof GrControlStatement) {
        if (generatePrefixIncDec((PsiMethod)resolved, operand, expression)) return;
      }
    }

    if (operand != null && shouldNotReplaceOperatorWithMethod(operand.getType(), null, expression.getOperationTokenType())) {
      writeSimpleUnary(operand, expression, this);
    }
    else {
      if (opType == GroovyTokenTypes.mLNOT) {
        builder.append('!');
      }
      invokeMethodOn(
        ((PsiMethod)resolved),
        operand,
        GrExpression.EMPTY_ARRAY,
        GrNamedArgument.EMPTY_ARRAY,
        GrClosableBlock.EMPTY_ARRAY,
        resolveResult.getSubstitutor(),
        expression
      );
    }
  }
  else if (operand != null) {
    if (postfix) {
      operand.accept(this);
      builder.append(expression.getOperationToken().getText());
    }
    else {
      builder.append(expression.getOperationToken().getText());
      operand.accept(this);
    }
  }
}
 
Example 59
Project: intellij-ce-playground   File: CallInfo.java   Source Code and License 4 votes vote down vote up
@NotNull
GrNamedArgument[] getNamedArguments();
 
Example 60
Project: intellij-ce-playground   File: DelegatingCallInfo.java   Source Code and License 4 votes vote down vote up
@NotNull
@Override
public GrNamedArgument[] getNamedArguments() {
  return myDelegate.getNamedArguments();
}