예제 #1
0
  @Override
  @Nullable
  public Collection<PsiImportStatementBase> findRedundantImports(final PsiJavaFile file) {
    final PsiImportList importList = file.getImportList();
    if (importList == null) return null;
    final PsiImportStatementBase[] imports = importList.getAllImportStatements();
    if (imports.length == 0) return null;

    Set<PsiImportStatementBase> allImports =
        new THashSet<PsiImportStatementBase>(Arrays.asList(imports));
    final Collection<PsiImportStatementBase> redundant;
    if (FileTypeUtils.isInServerPageFile(file)) {
      // remove only duplicate imports
      redundant = ContainerUtil.newIdentityTroveSet();
      ContainerUtil.addAll(redundant, imports);
      redundant.removeAll(allImports);
      for (PsiImportStatementBase importStatement : imports) {
        if (importStatement instanceof JspxImportStatement
            && importStatement.isForeignFileImport()) {
          redundant.remove(importStatement);
        }
      }
    } else {
      redundant = allImports;
      final List<PsiFile> roots = file.getViewProvider().getAllFiles();
      for (PsiElement root : roots) {
        root.accept(
            new JavaRecursiveElementWalkingVisitor() {
              @Override
              public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
                if (!reference.isQualified()) {
                  final JavaResolveResult resolveResult = reference.advancedResolve(false);
                  if (!inTheSamePackage(file, resolveResult.getElement())) {
                    final PsiElement resolveScope = resolveResult.getCurrentFileResolveScope();
                    if (resolveScope instanceof PsiImportStatementBase) {
                      final PsiImportStatementBase importStatementBase =
                          (PsiImportStatementBase) resolveScope;
                      redundant.remove(importStatementBase);
                    }
                  }
                }
                super.visitReferenceElement(reference);
              }

              private boolean inTheSamePackage(PsiJavaFile file, PsiElement element) {
                if (element instanceof PsiClass
                    && ((PsiClass) element).getContainingClass() == null) {
                  final PsiFile containingFile = element.getContainingFile();
                  if (containingFile instanceof PsiJavaFile) {
                    return Comparing.strEqual(
                        file.getPackageName(), ((PsiJavaFile) containingFile).getPackageName());
                  }
                }
                return false;
              }
            });
      }
    }
    return redundant;
  }
예제 #2
0
  private void fixReferencesToStatic(PsiElement classMember) throws IncorrectOperationException {
    final StaticReferencesCollector collector = new StaticReferencesCollector();
    classMember.accept(collector);
    ArrayList<PsiJavaCodeReferenceElement> refs = collector.getReferences();
    ArrayList<PsiElement> members = collector.getReferees();
    ArrayList<PsiClass> classes = collector.getRefereeClasses();
    PsiElementFactory factory =
        JavaPsiFacade.getInstance(classMember.getProject()).getElementFactory();

    for (int i = 0; i < refs.size(); i++) {
      PsiJavaCodeReferenceElement ref = refs.get(i);
      PsiElement namedElement = members.get(i);
      PsiClass aClass = classes.get(i);

      if (namedElement instanceof PsiNamedElement) {
        PsiReferenceExpression newRef =
            (PsiReferenceExpression)
                factory.createExpressionFromText(
                    "a." + ((PsiNamedElement) namedElement).getName(), null);
        PsiExpression qualifierExpression = newRef.getQualifierExpression();
        assert qualifierExpression != null;
        qualifierExpression =
            (PsiExpression) qualifierExpression.replace(factory.createReferenceExpression(aClass));
        qualifierExpression.putCopyableUserData(PRESERVE_QUALIFIER, ref.isQualified());
        ref.replace(newRef);
      }
    }
  }
예제 #3
0
 @NotNull
 public Element elementToElement(@Nullable PsiElement e) {
   if (e == null) return Element.EMPTY_ELEMENT;
   ElementVisitor elementVisitor = new ElementVisitor(this);
   e.accept(elementVisitor);
   return elementVisitor.getResult();
 }
  private static void checkMethodCall(RefElement refWhat, final PsiElement element) {
    if (!(refWhat instanceof RefMethod)) return;
    final RefMethod refMethod = (RefMethod) refWhat;
    final PsiElement psiElement = refMethod.getElement();
    if (!(psiElement instanceof PsiMethod)) return;
    final PsiMethod psiMethod = (PsiMethod) psiElement;
    if (!PsiType.BOOLEAN.equals(psiMethod.getReturnType())) return;
    element.accept(
        new JavaRecursiveElementWalkingVisitor() {
          @Override
          public void visitMethodCallExpression(PsiMethodCallExpression call) {
            super.visitMethodCallExpression(call);
            final PsiReferenceExpression methodExpression = call.getMethodExpression();
            if (methodExpression.isReferenceTo(psiMethod)) {
              if (isInvertedMethodCall(methodExpression)) return;
              refMethod.putUserData(ALWAYS_INVERTED, Boolean.FALSE);
            }
          }

          @Override
          public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
            super.visitMethodReferenceExpression(expression);
            if (expression.isReferenceTo(psiElement)) {
              refMethod.putUserData(ALWAYS_INVERTED, Boolean.FALSE);
            }
          }
        });
  }
예제 #5
0
  @Override
  public void annotate(@NotNull final PsiElement element, @NotNull final AnnotationHolder holder) {
    element.accept(
        new ShapeVisitor() {
          @Override
          public void visitViewName(@NotNull ShapeViewName o) {
            super.visitViewName(o);
            setHighlighting(o, holder, XmlHighlighterColors.HTML_TAG_NAME);
          }

          @Override
          public void visitAttrKey(@NotNull ShapeAttrKey o) {
            super.visitAttrKey(o);
            setHighlighting(o, holder, XmlHighlighterColors.HTML_ATTRIBUTE_NAME);
          }

          @Override
          public void visitAttrValue(@NotNull ShapeAttrValue o) {
            super.visitAttrValue(o);
            setHighlighting(o, holder, XmlHighlighterColors.HTML_ATTRIBUTE_VALUE);
          }

          @Override
          public void visitIdDefinition(@NotNull ShapeIdDefinition o) {
            super.visitIdDefinition(o);
            setHighlighting(o, holder, DefaultLanguageHighlighterColors.STATIC_FIELD);
          }
        });
  }
  private static void decodeRefs(
      @NotNull PsiElement element,
      final Map<PsiClass, PsiElement> oldToNewMap,
      final Set<PsiElement> rebindExpressions) {
    element.accept(
        new JavaRecursiveElementVisitor() {
          @Override
          public void visitReferenceExpression(PsiReferenceExpression expression) {
            decodeRef(expression, oldToNewMap, rebindExpressions);
            super.visitReferenceExpression(expression);
          }

          @Override
          public void visitNewExpression(PsiNewExpression expression) {
            final PsiJavaCodeReferenceElement referenceElement = expression.getClassReference();
            if (referenceElement != null) {
              decodeRef(referenceElement, oldToNewMap, rebindExpressions);
            }
            super.visitNewExpression(expression);
          }

          @Override
          public void visitTypeElement(PsiTypeElement type) {
            final PsiJavaCodeReferenceElement referenceElement =
                type.getInnermostComponentReferenceElement();
            if (referenceElement != null) {
              decodeRef(referenceElement, oldToNewMap, rebindExpressions);
            }
            super.visitTypeElement(type);
          }
        });
    rebindExternalReferences(element, oldToNewMap, rebindExpressions);
  }
 /**
  * @return true, if the element contains a reference to a different class than fullyQualifiedName
  *     but which has the same class name
  */
 public static boolean containsReferenceToConflictingClass(
     PsiElement element, String fullyQualifiedName) {
   final ConflictingClassReferenceVisitor visitor =
       new ConflictingClassReferenceVisitor(fullyQualifiedName);
   element.accept(visitor);
   return visitor.isReferenceFound();
 }
 private boolean checkConstantValueVariableUse(
     @Nullable PsiExpression expression,
     @NotNull PsiExpression constantExpression,
     @NotNull PsiElement body) {
   final PsiType constantType = constantExpression.getType();
   if (PsiType.DOUBLE.equals(constantType)) {
     final Object result = ExpressionUtils.computeConstantExpression(constantExpression, false);
     if (Double.valueOf(0.0).equals(result) || Double.valueOf(-0.0).equals(result)) {
       return false;
     }
   }
   if (!(expression instanceof PsiReferenceExpression)) {
     return false;
   }
   final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression;
   final PsiElement target = referenceExpression.resolve();
   if (!(target instanceof PsiVariable)) {
     return false;
   }
   if (target instanceof PsiField) {
     return false;
   }
   final PsiVariable variable = (PsiVariable) target;
   final VariableReadVisitor visitor = new VariableReadVisitor(variable);
   body.accept(visitor);
   if (!visitor.isRead()) {
     return false;
   }
   registerError(visitor.getReference(), constantExpression);
   return true;
 }
예제 #9
0
 public void checkSourceClassConflicts() {
   final PsiElement[] children = myClass.getChildren();
   for (PsiElement child : children) {
     if (child instanceof PsiMember && !myMovedMembers.contains(child)) {
       child.accept(new UsedMovedMembersConflictsCollector(child));
     }
   }
 }
 @Override
 public void acceptChildren(@NotNull PsiElementVisitor visitor) {
   PsiElement child = getFirstChild();
   while (child != null) {
     child.accept(visitor);
     child = child.getNextSibling();
   }
 }
 public static boolean hasError(PsiElement element) {
   try {
     element.accept(INSTANCE);
     return false;
   } catch (HasError e) {
     return true;
   }
 }
예제 #12
0
  public static List<PsiLambdaExpression> collectLambdas(
      @NotNull SourcePosition position, final boolean onlyOnTheLine) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    PsiFile file = position.getFile();
    final int line = position.getLine();
    final Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
    if (document == null || line >= document.getLineCount()) {
      return Collections.emptyList();
    }
    PsiElement element = position.getElementAt();
    final TextRange lineRange = DocumentUtil.getLineTextRange(document, line);
    do {
      PsiElement parent = element.getParent();
      if (parent == null || (parent.getTextOffset() < lineRange.getStartOffset())) {
        break;
      }
      element = parent;
    } while (true);

    final List<PsiLambdaExpression> lambdas = new ArrayList<PsiLambdaExpression>(3);
    final PsiElementVisitor lambdaCollector =
        new JavaRecursiveElementVisitor() {
          @Override
          public void visitLambdaExpression(PsiLambdaExpression expression) {
            super.visitLambdaExpression(expression);
            if (!onlyOnTheLine || getFirstElementOnTheLine(expression, document, line) != null) {
              lambdas.add(expression);
            }
          }
        };
    element.accept(lambdaCollector);
    // add initial lambda if we're inside already
    PsiElement method = getContainingMethod(element);
    if (method instanceof PsiLambdaExpression) {
      lambdas.add((PsiLambdaExpression) method);
    }
    for (PsiElement sibling = getNextElement(element);
        sibling != null;
        sibling = getNextElement(sibling)) {
      if (!intersects(lineRange, sibling)) {
        break;
      }
      sibling.accept(lambdaCollector);
    }
    return lambdas;
  }
  @NotNull
  @Override
  public StackValue gen(
      @NotNull PsiElement block, @NotNull StackValue data, ExpressionCodegen expressionCodegen) {
    OnlyStringCheckVisitor checkVisitor = new OnlyStringCheckVisitor();
    block.accept(checkVisitor);

    String str = checkVisitor.getText();
    if (str != null) return StackValue.constant(block, str, AsmConstants.STRING_TYPE);
    else {
      PartToPartGenVisitor genVisitor =
          new PartToPartGenVisitor(expressionCodegen.instructs, expressionCodegen);
      block.accept(genVisitor);
      genVisitor.genToString();
      return StackValue.onStack(AsmConstants.STRING_TYPE);
    }
  }
 @Override
 public void visitParenthesizedExpression(GrParenthesizedExpression expression) {
   final PsiElement parent = expression.getParent();
   if (parent instanceof GroovyPsiElement) {
     ((GroovyPsiElement) parent).accept(this);
   } else {
     parent.accept(new GroovyPsiElementVisitor(this));
   }
 }
  @Override
  public void annotate(@NotNull PsiElement element, final @NotNull AnnotationHolder holder) {
    // error checks
    element.accept(
        new JqlElementVisitor() {
          @Override
          public void visitEmptyValue(JqlEmptyValue emptyValue) {
            JqlSimpleClause clause = PsiTreeUtil.getParentOfType(emptyValue, JqlSimpleClause.class);
            if (clause != null && !isEmptyClause(clause)) {
              holder.createErrorAnnotation(
                  emptyValue, String.format("Not expecting '%s' here", emptyValue.getText()));
            }
          }

          @Override
          public void visitJqlList(JqlList list) {
            JqlSimpleClause clause = PsiTreeUtil.getParentOfType(list, JqlSimpleClause.class);
            if (clause != null && !isListClause(clause)) {
              holder.createErrorAnnotation(
                  list, String.format("Not expecting list of values here"));
            }
          }

          @Override
          public void visitJqlSimpleClause(JqlSimpleClause clause) {
            JqlOperand operand = clause.getOperand();
            if (operand == null) {
              return;
            }
            boolean operandIsListLiteral = operand instanceof JqlList;
            boolean operandIsListFunction = false;
            if (operand instanceof JqlFunctionCall) {
              JqlFunctionCall functionCall = (JqlFunctionCall) operand;
              JqlStandardFunction standardFunction =
                  JqlStandardFunction.byName(functionCall.getFunctionName().getText());
              operandIsListFunction =
                  standardFunction != null && standardFunction.hasMultipleResults();
            }
            boolean hasListOperand = operandIsListLiteral || operandIsListFunction;
            if (isListClause(clause) && !hasListOperand) {
              holder.createErrorAnnotation(operand, "Expecting list of values here");
            }

            boolean hasEmptyOperand = operand instanceof JqlEmptyValue;
            if (isEmptyClause(clause) && !hasEmptyOperand) {
              holder.createErrorAnnotation(operand, "Expecting 'empty' or 'null' here");
            }
          }

          @Override
          public void visitJqlIdentifier(JqlIdentifier identifier) {
            Annotation annotation = holder.createInfoAnnotation(identifier, null);
            annotation.setEnforcedTextAttributes(CONSTANT.getDefaultAttributes());
          }
        });
  }
 @Override
 public void visitElement(PsiElement element) {
   final RefManagerExtension extension = getExtension(element.getLanguage());
   if (extension != null) {
     extension.visitElement(element);
   }
   for (PsiElement aChildren : element.getChildren()) {
     aChildren.accept(this);
   }
 }
예제 #17
0
 static void collectReferences(
     @NotNull PsiElement context, final PsiVariable variable, final List<PsiElement> references) {
   context.accept(
       new JavaRecursiveElementWalkingVisitor() {
         @Override
         public void visitReferenceExpression(PsiReferenceExpression expression) {
           if (expression.resolve() == variable) references.add(expression);
           super.visitReferenceExpression(expression);
         }
       });
 }
예제 #18
0
    private void initTopLevelElement(PsiElement element) {
      CompiledPattern pattern = myGlobalVisitor.getContext().getPattern();

      PsiElement newElement = SkippingHandler.skipNodeIfNeccessary(element);

      if (element != newElement && newElement != null) {
        // way to support partial matching (ex. if ($condition$) )
        newElement.accept(this);
        pattern.setHandler(element, new LightTopLevelMatchingHandler(pattern.getHandler(element)));
      } else {
        myGlobalVisitor.setCodeBlockLevel(myGlobalVisitor.getCodeBlockLevel() + 1);

        for (PsiElement el = element.getFirstChild(); el != null; el = el.getNextSibling()) {
          if (GlobalCompilingVisitor.getFilter().accepts(el)) {
            if (el instanceof PsiWhiteSpace) {
              myGlobalVisitor.addLexicalNode(el);
            }
          } else {
            el.accept(this);

            MatchingHandler matchingHandler = pattern.getHandler(el);
            pattern.setHandler(
                el,
                element == myTopElement
                    ? new TopLevelMatchingHandler(matchingHandler)
                    : new LightTopLevelMatchingHandler(matchingHandler));

            /*
             do not assign light-top-level handlers through skipping, because it is incorrect;
             src: if (...) { st1; st2; }
             pattern: if (...) {$a$;}

             $a$ will have top-level handler, so matching will be considered as correct, although "st2;" is left!
            */
          }
        }

        myGlobalVisitor.setCodeBlockLevel(myGlobalVisitor.getCodeBlockLevel() - 1);
        pattern.setHandler(element, new TopLevelMatchingHandler(pattern.getHandler(element)));
      }
    }
 private static void shortenWithStaticImports(
     PsiElement affectedElement, int startOffset, int endOffset) {
   final int elementOffset = affectedElement.getTextOffset();
   final int finalStartOffset = startOffset + elementOffset;
   final int finalEndOffset = endOffset + elementOffset;
   final List<PsiReferenceExpression> references = new ArrayList<PsiReferenceExpression>();
   final JavaRecursiveElementVisitor collector =
       new JavaRecursiveElementVisitor() {
         @Override
         public void visitReferenceExpression(PsiReferenceExpression expression) {
           final int offset = expression.getTextOffset();
           if (offset > finalEndOffset) {
             return;
           }
           super.visitReferenceExpression(expression);
           if (offset + expression.getTextLength() < finalStartOffset)
             if (expression.getQualifierExpression() == null) {
               return;
             }
           references.add(expression);
         }
       };
   affectedElement.accept(collector);
   for (PsiReferenceExpression expression : references) {
     final PsiElement target = expression.resolve();
     if (!(target instanceof PsiMember)) {
       continue;
     }
     final PsiMember member = (PsiMember) target;
     final PsiClass containingClass = member.getContainingClass();
     if (containingClass == null) {
       continue;
     }
     final String className = containingClass.getQualifiedName();
     if (className == null) {
       continue;
     }
     final String name = member.getName();
     if (name == null) {
       continue;
     }
     if (ImportUtils.addStaticImport(className, name, expression)) {
       final PsiExpression qualifierExpression = expression.getQualifierExpression();
       if (qualifierExpression != null) {
         qualifierExpression.delete();
       }
     }
   }
 }
 private boolean initializerDependsOnMoved(PsiElement initializer) {
   final boolean[] dependsOnMoved = new boolean[] {false};
   initializer.accept(
       new JavaRecursiveElementWalkingVisitor() {
         public void visitReferenceExpression(final PsiReferenceExpression expression) {
           super.visitReferenceExpression(expression);
           final PsiElement resolved = expression.resolve();
           if (resolved instanceof PsiMember) {
             dependsOnMoved[0] |=
                 !((PsiMember) resolved).hasModifierProperty(PsiModifier.STATIC)
                     && isInMovedElement(resolved);
           }
         }
       });
   return dependsOnMoved[0];
 }
 private static void replaceReferences(
     PsiElement context, final PsiVariable variable, final PsiElement newExpression) {
   context.accept(
       new JavaRecursiveElementVisitor() {
         @Override
         public void visitReferenceExpression(PsiReferenceExpression expression) {
           if (expression.resolve() == variable)
             try {
               expression.replace(newExpression);
             } catch (IncorrectOperationException e) {
               LOG.error(e);
             }
           super.visitReferenceExpression(expression);
         }
       });
 }
  @NotNull
  @Override
  public String suggestUniqueVariableName(
      @NotNull @NonNls String baseName, PsiElement place, boolean lookForward) {
    int index = 0;
    PsiElement scope =
        PsiTreeUtil.getNonStrictParentOfType(
            place, PsiStatement.class, PsiCodeBlock.class, PsiMethod.class);
    NextName:
    while (true) {
      String name = baseName;
      if (index > 0) {
        name += index;
      }
      index++;
      if (PsiUtil.isVariableNameUnique(name, place)) {
        if (lookForward) {
          final String name1 = name;
          PsiElement run = scope;
          while (run != null) {
            class CancelException extends RuntimeException {}
            try {
              run.accept(
                  new JavaRecursiveElementWalkingVisitor() {
                    @Override
                    public void visitAnonymousClass(final PsiAnonymousClass aClass) {}

                    @Override
                    public void visitVariable(PsiVariable variable) {
                      if (name1.equals(variable.getName())) {
                        throw new CancelException();
                      }
                    }
                  });
            } catch (CancelException e) {
              continue NextName;
            }
            run = run.getNextSibling();
            if (scope instanceof PsiMethod) { // do not check next member for param name conflict
              break;
            }
          }
        }
        return name;
      }
    }
  }
예제 #23
0
 public static PsiExpression[] findVariableOccurrences(
     final PsiElement[] scopeElements, final PsiVariable variable) {
   final ArrayList<PsiExpression> result = new ArrayList<PsiExpression>();
   for (final PsiElement element : scopeElements) {
     element.accept(
         new JavaRecursiveElementWalkingVisitor() {
           @Override
           public void visitReferenceExpression(final PsiReferenceExpression expression) {
             super.visitReferenceExpression(expression);
             if (!expression.isQualified() && expression.isReferenceTo(variable)) {
               result.add(expression);
             }
           }
         });
   }
   return result.toArray(new PsiExpression[result.size()]);
 }
 private static TextRange adjustRange(final PsiElement element, final TextRange originalRange) {
   final Ref<TextRange> rangeRef = new Ref<TextRange>(originalRange);
   element.accept(
       new JavaRecursiveElementVisitor() {
         @Override
         public void visitExpressionStatement(final PsiExpressionStatement statement) {
           final TextRange stRange = statement.getTextRange();
           if (originalRange.intersects(stRange)) {
             final TextRange currentRange = rangeRef.get();
             final int start = Math.min(currentRange.getStartOffset(), stRange.getStartOffset());
             final int end = Math.max(currentRange.getEndOffset(), stRange.getEndOffset());
             rangeRef.set(new TextRange(start, end));
           }
         }
       });
   return rangeRef.get();
 }
예제 #25
0
 private static void decodeRefs(
     @NotNull PsiElement element,
     final Map<PsiClass, PsiElement> oldToNewMap,
     final Set<PsiElement> rebindExpressions) {
   final Map<PsiJavaCodeReferenceElement, PsiElement> rebindMap = new LinkedHashMap<>();
   element.accept(
       new JavaRecursiveElementVisitor() {
         @Override
         public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
           super.visitReferenceElement(reference);
           decodeRef(reference, oldToNewMap, rebindMap);
         }
       });
   for (Map.Entry<PsiJavaCodeReferenceElement, PsiElement> entry : rebindMap.entrySet()) {
     rebindExpressions.add(entry.getKey().bindToElement(entry.getValue()));
   }
   rebindExternalReferences(element, oldToNewMap, rebindExpressions);
 }
 @Override
 public String getUnescapedText(@NotNull final PsiElement injectedNode) {
   final StringBuilder text = new StringBuilder(injectedNode.getTextLength());
   // gather text from (patched) leaves
   injectedNode.accept(
       new PsiRecursiveElementWalkingVisitor() {
         @Override
         public void visitElement(PsiElement element) {
           String leafText = InjectedLanguageUtil.getUnescapedLeafText(element, false);
           if (leafText != null) {
             text.append(leafText);
             return;
           }
           super.visitElement(element);
         }
       });
   return text.toString();
 }
예제 #27
0
  @NotNull
  private Collection<JetDeclarationContainer> collectPackageFragmentsAndClassifiers(
      @NotNull TopDownAnalysisContext c,
      @NotNull JetScope outerScope,
      @NotNull PackageLikeBuilder owner,
      @NotNull Iterable<? extends PsiElement> declarations) {
    Collection<JetDeclarationContainer> forDeferredResolve =
        new ArrayList<JetDeclarationContainer>();

    ClassifierCollector collector =
        new ClassifierCollector(c, outerScope, owner, forDeferredResolve);

    for (PsiElement declaration : declarations) {
      declaration.accept(collector);
    }

    return forDeferredResolve;
  }
예제 #28
0
  private static boolean checkErrorElements(PsiElement element) {
    final boolean[] result = {true};
    final int endOffset = element.getTextRange().getEndOffset();

    element.accept(
        new PsiRecursiveElementWalkingVisitor() {
          @Override
          public void visitElement(PsiElement element) {
            super.visitElement(element);

            if (element instanceof PsiErrorElement
                && element.getTextRange().getEndOffset() == endOffset) {
              result[0] = false;
            }
          }
        });

    return result[0];
  }
예제 #29
0
  private static boolean checkOptionalChildren(PsiElement root) {
    final boolean[] result = {true};

    root.accept(
        new PsiRecursiveElementWalkingVisitor() {
          @Override
          public void visitElement(PsiElement element) {
            super.visitElement(element);

            if (element instanceof LeafElement) {
              return;
            }

            final EquivalenceDescriptorProvider provider =
                EquivalenceDescriptorProvider.getInstance(element);
            if (provider == null) {
              return;
            }

            final EquivalenceDescriptor descriptor = provider.buildDescriptor(element);
            if (descriptor == null) {
              return;
            }

            for (SingleChildDescriptor childDescriptor : descriptor.getSingleChildDescriptors()) {
              if (childDescriptor.getType() == SingleChildDescriptor.MyType.OPTIONALLY_IN_PATTERN
                  && childDescriptor.getElement() == null) {
                result[0] = false;
              }
            }

            for (MultiChildDescriptor childDescriptor : descriptor.getMultiChildDescriptors()) {
              if (childDescriptor.getType() == MultiChildDescriptor.MyType.OPTIONALLY_IN_PATTERN) {
                PsiElement[] elements = childDescriptor.getElements();
                if (elements == null || elements.length == 0) {
                  result[0] = false;
                }
              }
            }
          }
        });
    return result[0];
  }
예제 #30
0
  @Override
  public void annotate(@NotNull PsiElement element, @NotNull final AnnotationHolder holder) {
    for (HighlightingVisitor visitor : getBeforeAnalysisVisitors(holder)) {
      element.accept(visitor);
    }

    if (element instanceof JetFile) {
      JetFile file = (JetFile) element;

      try {
        BindingContext bindingContext =
            WholeProjectAnalyzerFacade.analyzeProjectWithCacheOnAFile(file).getBindingContext();

        if (errorReportingEnabled) {
          Collection<Diagnostic> diagnostics =
              Sets.newLinkedHashSet(bindingContext.getDiagnostics());
          Set<PsiElement> redeclarations = Sets.newHashSet();
          for (Diagnostic diagnostic : diagnostics) {
            // This is needed because we have the same context for all files
            if (diagnostic.getPsiFile() != file) continue;

            registerDiagnosticAnnotations(diagnostic, redeclarations, holder);
          }
        }

        for (HighlightingVisitor visitor : getAfterAnalysisVisitor(holder, bindingContext)) {
          file.acceptChildren(visitor);
        }
      } catch (ProcessCanceledException e) {
        throw e;
      } catch (AssertionError e) {
        // For failing tests and to notify about idea internal error in -ea mode
        holder.createErrorAnnotation(
            element, e.getClass().getCanonicalName() + ": " + e.getMessage());
        throw e;
      } catch (Throwable e) {
        // TODO
        holder.createErrorAnnotation(
            element, e.getClass().getCanonicalName() + ": " + e.getMessage());
        e.printStackTrace();
      }
    }
  }