/*
    Method to start visiting
     */
    private void doInit() {
      if (myChild1 == null || myChild2 == null) return;
      PsiElement psi1 = myChild1.getPsi();
      PsiElement psi2 = myChild2.getPsi();
      if (psi1 == null || psi2 == null) return;
      if (psi1.getLanguage() != MoonFileType.MOON_LANGUAGE
          || psi2.getLanguage() != MoonFileType.MOON_LANGUAGE) {
        return;
      }

      if (myChild2 != null
          && mySettings.KEEP_FIRST_COLUMN_COMMENT
          && SpacingUtil.COMMENT_BIT_SET.contains(myChild2.getElementType())) {

        myResult = Spacing.createKeepingFirstColumnSpacing(0, Integer.MAX_VALUE, true, 1);

        return;
      }

      if (myChild1 != null && myChild2 != null && myChild1.getElementType() == NEWLINE) {
        final ASTNode prev = SpacingUtil.getPrevElementType(myChild1);
        if (prev != null && prev.getElementType() == SHORTCOMMENT) {
          myResult =
              Spacing.createSpacing(
                  0, 0, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
          return;
        }
      }

      if (myParent instanceof MoonPsiElement) {
        ((MoonPsiElement) myParent).accept(this);
      }
    }
  public static PsiStatement[] getChildStatements(CompositeElement psiCodeBlock) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    // no lock is needed because all chameleons are expanded already
    int count = 0;
    for (ASTNode child1 = psiCodeBlock.getFirstChildNode();
        child1 != null;
        child1 = child1.getTreeNext()) {
      if (child1.getPsi() instanceof PsiStatement) {
        count++;
      }
    }

    PsiStatement[] result = PsiStatement.ARRAY_FACTORY.create(count);
    if (count == 0) return result;
    int idx = 0;
    for (ASTNode child = psiCodeBlock.getFirstChildNode();
        child != null && idx < count;
        child = child.getTreeNext()) {
      PsiElement element = child.getPsi();
      if (element instanceof PsiStatement) {
        result[idx++] = (PsiStatement) element;
      }
    }
    return result;
  }
  public static PsiStatement[] getChildStatements(CompositeElement psiCodeBlock) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    // no lock is needed because all chameleons are expanded already
    int count = 0;
    for (ASTNode child1 = psiCodeBlock.getFirstChildNode();
        child1 != null;
        child1 = child1.getTreeNext()) {
      if (child1.getPsi() instanceof PsiStatement) {
        count++;
      }
    }

    PsiStatement[] result = Constants.PSI_STATEMENT_ARRAY_CONSTRUCTOR.newPsiElementArray(count);
    if (count == 0) {
      return result;
    }
    int idx = 0;
    for (ASTNode child = psiCodeBlock.getFirstChildNode();
        child != null && idx < count;
        child = child.getTreeNext()) {
      if (child.getPsi() instanceof PsiStatement) {
        PsiStatement element = (PsiStatement) child.getPsi();
        LOG.assertTrue(element != null, child);
        result[idx++] = element;
      }
    }
    return result;
  }
 private void checkAccessors(
     @NotNull JetProperty property, @NotNull PropertyDescriptor propertyDescriptor) {
   for (JetPropertyAccessor accessor : property.getAccessors()) {
     PropertyAccessorDescriptor propertyAccessorDescriptor =
         accessor.isGetter() ? propertyDescriptor.getGetter() : propertyDescriptor.getSetter();
     assert propertyAccessorDescriptor != null
         : "No property accessor descriptor for " + property.getText();
     modifiersChecker.checkModifiersForDeclaration(accessor, propertyAccessorDescriptor);
     modifiersChecker.reportIllegalModalityModifiers(accessor);
   }
   JetPropertyAccessor getter = property.getGetter();
   PropertyGetterDescriptor getterDescriptor = propertyDescriptor.getGetter();
   JetModifierList getterModifierList = getter != null ? getter.getModifierList() : null;
   if (getterModifierList != null && getterDescriptor != null) {
     Map<JetModifierKeywordToken, ASTNode> nodes =
         ModifiersChecker.getNodesCorrespondingToModifiers(
             getterModifierList,
             Sets.newHashSet(
                 JetTokens.PUBLIC_KEYWORD,
                 JetTokens.PROTECTED_KEYWORD,
                 JetTokens.PRIVATE_KEYWORD,
                 JetTokens.INTERNAL_KEYWORD));
     if (getterDescriptor.getVisibility() != propertyDescriptor.getVisibility()) {
       for (ASTNode node : nodes.values()) {
         trace.report(Errors.GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY.on(node.getPsi()));
       }
     } else {
       for (ASTNode node : nodes.values()) {
         trace.report(Errors.REDUNDANT_MODIFIER_IN_GETTER.on(node.getPsi()));
       }
     }
   }
 }
Exemple #5
0
 @Nullable
 public static PsiElement searchNonSpaceNonCommentBack(PsiElement element) {
   if (element == null || element.getNode() == null) return null;
   ASTNode leftNeibour = TreeUtil.prevLeaf(element.getNode());
   while (leftNeibour != null
       && (leftNeibour.getElementType() == TokenType.WHITE_SPACE
           || leftNeibour.getPsi() instanceof PsiComment)) {
     leftNeibour = TreeUtil.prevLeaf(leftNeibour);
   }
   return leftNeibour != null ? leftNeibour.getPsi() : null;
 }
 @Override
 public void deleteChildInternal(@NotNull ASTNode child) {
   PyExpression left = getLeftExpression();
   PyExpression right = getRightExpression();
   if (left == child.getPsi() && right != null) {
     replace(right);
   } else if (right == child.getPsi() && left != null) {
     replace(left);
   } else {
     throw new IncorrectOperationException(
         "Element " + child.getPsi() + " is neither left expression or right expression");
   }
 }
 /**
  * Adds all children of specified element to given list
  *
  * @param elem
  * @param list
  * @param indent
  * @param alignment
  */
 private void addBinaryChildrenRecursively(
     PsiElement elem, List<Block> list, Indent indent, Alignment alignment) {
   if (elem == null) return;
   // For binary expressions
   if ((elem instanceof GrBinaryExpression)) {
     GrBinaryExpression myExpr = ((GrBinaryExpression) elem);
     if (myExpr.getLeftOperand() instanceof GrBinaryExpression) {
       addBinaryChildrenRecursively(
           myExpr.getLeftOperand(), list, Indent.getContinuationWithoutFirstIndent(), alignment);
     }
     PsiElement op = ((GrBinaryExpression) elem).getOperationToken();
     for (ASTNode childNode : visibleChildren(elem.getNode())) {
       PsiElement psi = childNode.getPsi();
       if (!(psi instanceof GrBinaryExpression)) {
         Alignment alignmentToUse = op == psi ? myInnerAlignments.get(op) : alignment;
         list.add(
             new GroovyBlock(
                 childNode,
                 alignmentToUse,
                 indent,
                 myWrap,
                 mySettings,
                 myGroovySettings,
                 myInnerAlignments));
       }
     }
     if (myExpr.getRightOperand() instanceof GrBinaryExpression) {
       addBinaryChildrenRecursively(
           myExpr.getRightOperand(), list, Indent.getContinuationWithoutFirstIndent(), alignment);
     }
   }
 }
 @Nullable
 public PsiElement getPsiOperator() {
   ASTNode node = getNode();
   final ASTNode child = node.findChildByType(PyElementTypes.BINARY_OPS);
   if (child != null) return child.getPsi();
   return null;
 }
  @Override
  public ASTNode addInternal(ASTNode first, ASTNode last, ASTNode anchor, Boolean before) {
    appendParenthesesIfNeeded();

    if (first == last && first.getPsi() instanceof GrTypeParameter) {
      boolean hasParams = getTypeParameters().length > 0;

      final ASTNode _anchor;

      if (anchor == null) {
        if (before.booleanValue()) {
          _anchor = getLastChild().getNode();
        } else {
          _anchor = getFirstChild().getNode();
        }
      } else {
        _anchor = anchor;
      }

      final ASTNode node = super.addInternal(first, last, _anchor, before);
      if (hasParams) {
        getNode().addLeaf(GroovyTokenTypes.mCOMMA, ",", anchor != null ? anchor : node);
      }
      return node;
    } else {
      return super.addInternal(first, last, anchor, before);
    }
  }
 public static boolean isComment(@Nullable final ASTNode node) {
   if (node == null) {
     return false;
   }
   final PsiElement psi = node.getPsi();
   return psi != null && isComment(psi);
 }
  void addNestedChildrenSuffix(
      List<Block> list,
      @Nullable AlignmentProvider.Aligner aligner,
      boolean topLevel,
      List<ASTNode> children,
      int limit) {
    for (int i = 1; i < limit; i++) {
      ASTNode childNode = children.get(i);
      if (canBeCorrectBlock(childNode)) {
        IElementType type = childNode.getElementType();
        Indent indent =
            topLevel || NESTED.contains(type) || type == mIDENT || TokenSets.DOTS.contains(type)
                ? Indent.getContinuationWithoutFirstIndent()
                : Indent.getNoneIndent();

        if (aligner != null && TokenSets.DOTS.contains(type)) {
          aligner.append(childNode.getPsi());
        }

        list.add(
            new GroovyBlock(
                childNode, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider));
      }
    }
  }
  private void checkClass(
      BodiesResolveContext c,
      JetClass aClass,
      ClassDescriptorWithResolutionScopes classDescriptor) {
    checkOpenMembers(classDescriptor);
    checkTypeParameters(aClass);

    if (aClass.isInterface()) {
      ASTNode traitKeyword = aClass.getNode().findChildByType(JetTokens.TRAIT_KEYWORD);
      if (traitKeyword != null) {
        trace.report(Errors.DEPRECATED_TRAIT_KEYWORD.on(traitKeyword.getPsi()));
      }

      checkTraitModifiers(aClass);
      checkConstructorInTrait(aClass);
    } else if (aClass.isAnnotation()) {
      checkAnnotationClassWithBody(aClass);
      checkValOnAnnotationParameter(aClass);
    } else if (aClass.isEnum()) {
      checkEnumModifiers(aClass);
      if (aClass.isLocal()) {
        trace.report(LOCAL_ENUM_NOT_ALLOWED.on(aClass, classDescriptor));
      }
    } else if (aClass.hasModifier(JetTokens.SEALED_KEYWORD)) {
      checkSealedModifiers(aClass);
    } else if (aClass instanceof JetEnumEntry) {
      checkEnumEntry((JetEnumEntry) aClass, classDescriptor);
    }
  }
Exemple #13
0
  private static boolean isAnnotated(ASTNode element) {
    PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement) element.getPsi();

    PsiElement qualifier = ref.getQualifier();
    if (qualifier instanceof PsiJavaCodeReferenceElement) {
      if (((PsiJavaCodeReferenceElement) qualifier).resolve() instanceof PsiPackage) {
        return false;
      }
      if (PsiTreeUtil.getChildOfType(qualifier, PsiAnnotation.class) != null) {
        return true;
      }
    }

    PsiModifierList modifierList = PsiImplUtil.findNeighbourModifierList(ref);
    if (modifierList != null) {
      for (PsiAnnotation annotation : modifierList.getAnnotations()) {
        if (PsiImplUtil.findApplicableTarget(annotation, PsiAnnotation.TargetType.TYPE_USE)
            != null) {
          return true;
        }
      }
    }

    return false;
  }
 @Override
 public boolean shouldCreateStub(ASTNode node) {
   PsiElement element = node.getPsi();
   return element instanceof PerlMooseAugmentStatement
       && element.isValid()
       && StringUtil.isNotEmpty(((PerlMooseAugmentStatement) element).getSubName());
 }
 private void calculateAlignments(List<ASTNode> children, boolean classLevel) {
   List<GrStatement> currentGroup = null;
   boolean spock = true;
   for (ASTNode child : children) {
     PsiElement psi = child.getPsi();
     if (psi instanceof GrLabeledStatement) {
       alignGroup(currentGroup, spock, classLevel);
       currentGroup = ContainerUtil.newArrayList((GrStatement) psi);
       spock = true;
     } else if (currentGroup != null && spock && isTablePart(psi)) {
       currentGroup.add((GrStatement) psi);
     } else if (psi instanceof GrVariableDeclaration) {
       GrVariable[] variables = ((GrVariableDeclaration) psi).getVariables();
       if (variables.length > 0) {
         if (!classLevel || currentGroup == null || fieldGroupEnded(psi) || spock) {
           alignGroup(currentGroup, spock, classLevel);
           currentGroup = ContainerUtil.newArrayList();
           spock = false;
         }
         currentGroup.add((GrStatement) psi);
       }
     } else {
       if (psi instanceof PsiComment) {
         PsiElement prev = psi.getPrevSibling();
         if (prev != null && prev.getNode().getElementType() != mNLS
             || classLevel && !fieldGroupEnded(psi)) {
           continue;
         }
       }
       alignGroup(currentGroup, spock, classLevel);
       currentGroup = null;
     }
   }
 }
 /**
  * Adds all children of specified element to given list
  *
  * @param elem
  * @param list
  * @param indent
  * @param aligner
  */
 private void addBinaryChildrenRecursively(
     PsiElement elem,
     List<Block> list,
     Indent indent,
     @Nullable AlignmentProvider.Aligner aligner) {
   if (elem == null) return;
   // For binary expressions
   if ((elem instanceof GrBinaryExpression)) {
     GrBinaryExpression myExpr = ((GrBinaryExpression) elem);
     if (myExpr.getLeftOperand() instanceof GrBinaryExpression) {
       addBinaryChildrenRecursively(
           myExpr.getLeftOperand(), list, Indent.getContinuationWithoutFirstIndent(), aligner);
     }
     PsiElement op = ((GrBinaryExpression) elem).getOperationToken();
     for (ASTNode childNode : visibleChildren(elem.getNode())) {
       PsiElement psi = childNode.getPsi();
       if (!(psi instanceof GrBinaryExpression)) {
         if (op != psi && aligner != null) {
           aligner.append(psi);
         }
         list.add(
             new GroovyBlock(
                 childNode, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider));
       }
     }
     if (myExpr.getRightOperand() instanceof GrBinaryExpression) {
       addBinaryChildrenRecursively(
           myExpr.getRightOperand(), list, Indent.getContinuationWithoutFirstIndent(), aligner);
     }
   }
 }
  private void changeParameter(
      int parameterIndex, JetParameter parameter, JetParameterInfo parameterInfo) {
    ASTNode valOrVarAstNode = parameter.getValOrVarNode();
    PsiElement valOrVarNode = valOrVarAstNode != null ? valOrVarAstNode.getPsi() : null;
    JetValVar valOrVar = parameterInfo.getValOrVar();

    JetPsiFactory psiFactory = JetPsiFactory(getProject());
    if (valOrVarNode != null) {
      if (valOrVar == JetValVar.None) {
        valOrVarNode.delete();
      } else {
        valOrVarNode.replace(psiFactory.createValOrVarNode(valOrVar.toString()).getPsi());
      }
    } else if (valOrVar != JetValVar.None) {
      PsiElement firstChild = parameter.getFirstChild();
      parameter.addBefore(psiFactory.createValOrVarNode(valOrVar.toString()).getPsi(), firstChild);
      parameter.addBefore(psiFactory.createWhiteSpace(), firstChild);
    }

    if (parameterInfo.getIsTypeChanged() && parameter.getTypeReference() != null) {
      String renderedType = parameterInfo.renderType(parameterIndex, this);
      parameter.setTypeReference(psiFactory.createType(renderedType));
    }

    PsiElement identifier = parameter.getNameIdentifier();

    if (identifier != null) {
      //noinspection unchecked
      String newName =
          parameterInfo.getInheritedName((JetFunctionDefinitionUsage<PsiElement>) this);
      identifier.replace(psiFactory.createIdentifier(newName));
    }
  }
 @Override
 protected PsiElement getInternalNavigationElement() {
   List<INode> _findNodesForFeature = NodeModelUtils.findNodesForFeature(this.owner, this.feature);
   final Function1<INode, Iterable<ILeafNode>> _function =
       new Function1<INode, Iterable<ILeafNode>>() {
         @Override
         public Iterable<ILeafNode> apply(final INode it) {
           return it.getLeafNodes();
         }
       };
   List<Iterable<ILeafNode>> _map =
       ListExtensions.<INode, Iterable<ILeafNode>>map(_findNodesForFeature, _function);
   Iterable<ILeafNode> _flatten = Iterables.<ILeafNode>concat(_map);
   final Function1<ILeafNode, Boolean> _function_1 =
       new Function1<ILeafNode, Boolean>() {
         @Override
         public Boolean apply(final ILeafNode it) {
           boolean _isHidden = it.isHidden();
           return Boolean.valueOf((!_isHidden));
         }
       };
   Iterable<ILeafNode> _filter = IterableExtensions.<ILeafNode>filter(_flatten, _function_1);
   ILeafNode _head = IterableExtensions.<ILeafNode>head(_filter);
   ASTNode _aSTNode = this.xtextFile.getASTNode(_head);
   return _aSTNode.getPsi();
 }
 private boolean isMultiline(ASTNode node) {
   final PsiElement psi = node.getPsi();
   if (psi == null) {
     return false;
   }
   final String text = psi.getText();
   return text.contains("\n") || text.contains("\r") || text.contains("\r\n");
 }
 @Nullable
 public JetExpression getInitializer() {
   ASTNode eqNode = getNode().findChildByType(EQ);
   if (eqNode == null) {
     return null;
   }
   return PsiTreeUtil.getNextSiblingOfType(eqNode.getPsi(), JetExpression.class);
 }
  /**
   * Returns indent for simple expressions
   *
   * @param psiParent
   * @param child
   * @return
   */
  private static Indent getExpressionIndent(PsiElement psiParent, ASTNode child) {
    // Assignment expression
    if (psiParent instanceof GrAssignmentExpression
        && child.getPsi().equals(((GrAssignmentExpression) psiParent).getRValue())) {
      return Indent.getNormalIndent();
    }
    // Conditional expression
    if (psiParent instanceof GrConditionalExpression
        && (child.getPsi().equals(((GrConditionalExpression) psiParent).getThenBranch())
                && !(psiParent instanceof GrElvisExpression)
            || child.getPsi().equals(((GrConditionalExpression) psiParent).getElseBranch()))) {
      return Indent.getNormalIndent();
    }
    // Property selection

    return Indent.getNoneIndent();
  }
 public static PsiElement getNameIdentifier(X816SymbolAffectation element) {
   ASTNode keyNode = element.getNode().findChildByType(X816Types.SYMBOL);
   if (keyNode != null) {
     return keyNode.getPsi();
   } else {
     return null;
   }
 }
 @Override
 public void deleteChildInternal(@NotNull ASTNode child) {
   final PsiElement psi = child.getPsi();
   if (psi == getTupleInitializer()) {
     deleteChildInternal(findNotNullChildByType(GroovyTokenTypes.mASSIGN).getNode());
   }
   super.deleteChildInternal(child);
 }
 @Override
 public void deleteChildInternal(@NotNull ASTNode child) {
   final PsiElement element = child.getPsi();
   if (element instanceof GrStatement) {
     PsiImplUtil.deleteStatementTail(this, element);
   }
   super.deleteChildInternal(child);
 }
 @Override
 public boolean shouldCreateStub(ASTNode node) {
   if (!super.shouldCreateStub(node)) {
     return false;
   }
   PsiElement psi = node.getPsi();
   return psi instanceof JetParameter && !((JetParameter) psi).isLoopParameter();
 }
 public static PsiElement getNameIdentifier(X816LabelDef element) {
   ASTNode keyNode = element.getNode().findChildByType(X816Types.LABEL);
   if (keyNode != null) {
     return keyNode.getPsi();
   } else {
     return null;
   }
 }
 @Nullable
 @Override
 public String getPlaceholderText(@NotNull ASTNode node) {
   PsiElement psi = node.getPsi();
   if (psi instanceof BnfAttrs) return "{..}";
   if (psi instanceof BnfRule) return ((BnfRule) psi).getName() + " ::= ...";
   if (node.getElementType() == BnfParserDefinition.BNF_BLOCK_COMMENT) return "/*..*/";
   return null;
 }
Exemple #28
0
  private static void addReferencesInRange(
      List<ASTNode> array, ASTNode parent, int startOffset, int endOffset) {
    if (parent.getElementType() == JavaElementType.JAVA_CODE_REFERENCE
        || parent.getElementType() == JavaElementType.REFERENCE_EXPRESSION) {
      array.add(parent);
      return;
    }

    if (parent.getPsi() instanceof PsiFile) {
      JspFile jspFile = JspPsiUtil.getJspFile(parent.getPsi());
      if (jspFile != null) {
        JspClass jspClass = (JspClass) jspFile.getJavaClass();
        addReferencesInRange(array, jspClass.getNode(), startOffset, endOffset);
        return;
      }
    }

    addReferencesInRangeForComposite(array, parent, startOffset, endOffset);
  }
  @Override
  protected String replaceWithPsiInLeaf(
      final TextRange textRange, String whiteSpace, ASTNode leafElement) {
    if (!myCanModifyAllWhiteSpaces) {
      if (leafElement.getElementType() == TokenType.WHITE_SPACE) return null;
      LOG.assertTrue(leafElement.getPsi().isValid());
      ASTNode prevNode = TreeUtil.prevLeaf(leafElement);

      if (prevNode != null) {
        IElementType type = prevNode.getElementType();
        if (type == TokenType.WHITE_SPACE) {
          final String text = prevNode.getText();

          final @NonNls String cdataStartMarker = "<![CDATA[";
          final int cdataPos = text.indexOf(cdataStartMarker);
          if (cdataPos != -1 && whiteSpace.indexOf(cdataStartMarker) == -1) {
            whiteSpace = mergeWsWithCdataMarker(whiteSpace, text, cdataPos);
            if (whiteSpace == null) return null;
          }

          prevNode = TreeUtil.prevLeaf(prevNode);
          type = prevNode != null ? prevNode.getElementType() : null;
        }

        final @NonNls String cdataEndMarker = "]]>";
        if (type == XmlTokenType.XML_CDATA_END && whiteSpace.indexOf(cdataEndMarker) == -1) {
          final ASTNode at = findElementAt(prevNode.getStartOffset());

          if (at != null && at.getPsi() instanceof PsiWhiteSpace) {
            final String s = at.getText();
            final int cdataEndPos = s.indexOf(cdataEndMarker);
            whiteSpace = mergeWsWithCdataMarker(whiteSpace, s, cdataEndPos);
            leafElement = at;
          } else {
            whiteSpace = null;
          }
          if (whiteSpace == null) return null;
        }
      }
    }
    FormatterUtil.replaceWhiteSpace(whiteSpace, leafElement, TokenType.WHITE_SPACE, textRange);
    return whiteSpace;
  }
  @Nullable
  public PsiElement getReferenceNameElement() {
    final ASTNode lastChild = getNode().getLastChildNode();
    if (lastChild == null) return null;
    if (TokenSets.REFERENCE_NAMES.contains(lastChild.getElementType())) {
      return lastChild.getPsi();
    }

    return null;
  }