001    /*
002     * Copyright 2010-2016 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.kotlin.psi;
018    
019    import com.google.common.base.Predicate;
020    import com.google.common.collect.Lists;
021    import com.intellij.lang.ASTNode;
022    import com.intellij.psi.PsiComment;
023    import com.intellij.psi.PsiElement;
024    import com.intellij.psi.PsiFile;
025    import com.intellij.psi.PsiWhiteSpace;
026    import com.intellij.psi.tree.IElementType;
027    import com.intellij.psi.tree.TokenSet;
028    import com.intellij.psi.util.PsiTreeUtil;
029    import com.intellij.util.codeInsight.CommentUtilCore;
030    import org.jetbrains.annotations.Contract;
031    import org.jetbrains.annotations.NotNull;
032    import org.jetbrains.annotations.Nullable;
033    import org.jetbrains.kotlin.KtNodeTypes;
034    import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
035    import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
036    import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor;
037    import org.jetbrains.kotlin.kdoc.psi.api.KDocElement;
038    import org.jetbrains.kotlin.lexer.KtToken;
039    import org.jetbrains.kotlin.lexer.KtTokens;
040    import org.jetbrains.kotlin.name.Name;
041    import org.jetbrains.kotlin.name.SpecialNames;
042    import org.jetbrains.kotlin.parsing.KotlinExpressionParsing;
043    import org.jetbrains.kotlin.psi.psiUtil.KtPsiUtilKt;
044    import org.jetbrains.kotlin.resolve.StatementFilter;
045    import org.jetbrains.kotlin.resolve.StatementFilterKt;
046    import org.jetbrains.kotlin.types.expressions.OperatorConventions;
047    
048    import java.util.Collection;
049    import java.util.HashSet;
050    import java.util.List;
051    import java.util.Set;
052    
053    public class KtPsiUtil {
054        private KtPsiUtil() {
055        }
056    
057        public interface KtExpressionWrapper {
058            KtExpression getBaseExpression();
059        }
060    
061        public static <D> void visitChildren(@NotNull KtElement element, @NotNull KtVisitor<Void, D> visitor, D data) {
062            PsiElement child = element.getFirstChild();
063            while (child != null) {
064                if (child instanceof KtElement) {
065                    ((KtElement) child).accept(visitor, data);
066                }
067                child = child.getNextSibling();
068            }
069        }
070    
071        @NotNull
072        public static KtExpression safeDeparenthesize(@NotNull KtExpression expression) {
073            KtExpression deparenthesized = deparenthesize(expression);
074            return deparenthesized != null ? deparenthesized : expression;
075        }
076    
077        @Nullable
078        public static KtExpression deparenthesize(@Nullable KtExpression expression ) {
079            while (true) {
080                KtExpression baseExpression = deparenthesizeOnce(expression);
081    
082                if (baseExpression == expression) return baseExpression;
083                expression = baseExpression;
084            }
085        }
086    
087        @Nullable
088        public static KtExpression deparenthesizeOnce(
089                @Nullable KtExpression expression
090        ) {
091            if (expression instanceof KtAnnotatedExpression) {
092                return ((KtAnnotatedExpression) expression).getBaseExpression();
093            }
094            else if (expression instanceof KtLabeledExpression) {
095                return ((KtLabeledExpression) expression).getBaseExpression();
096            }
097            else if (expression instanceof KtExpressionWrapper) {
098                return ((KtExpressionWrapper) expression).getBaseExpression();
099            }
100            else if (expression instanceof KtParenthesizedExpression) {
101                return ((KtParenthesizedExpression) expression).getExpression();
102            }
103            return expression;
104        }
105    
106        @NotNull
107        public static Name safeName(@Nullable String name) {
108            return name == null ? SpecialNames.NO_NAME_PROVIDED : Name.identifier(name);
109        }
110    
111        @NotNull
112        public static Set<KtElement> findRootExpressions(@NotNull Collection<KtElement> unreachableElements) {
113            Set<KtElement> rootElements = new HashSet<KtElement>();
114            final Set<KtElement> shadowedElements = new HashSet<KtElement>();
115            KtVisitorVoid shadowAllChildren = new KtVisitorVoid() {
116                @Override
117                public void visitKtElement(@NotNull KtElement element) {
118                    if (shadowedElements.add(element)) {
119                        element.acceptChildren(this);
120                    }
121                }
122            };
123    
124            for (KtElement element : unreachableElements) {
125                if (shadowedElements.contains(element)) continue;
126                element.acceptChildren(shadowAllChildren);
127    
128                rootElements.removeAll(shadowedElements);
129                rootElements.add(element);
130            }
131            return rootElements;
132        }
133    
134        @NotNull
135        public static String unquoteIdentifier(@NotNull String quoted) {
136            if (quoted.indexOf('`') < 0) {
137                return quoted;
138            }
139    
140            if (quoted.startsWith("`") && quoted.endsWith("`") && quoted.length() >= 2) {
141                return quoted.substring(1, quoted.length() - 1);
142            }
143            else {
144                return quoted;
145            }
146        }
147    
148        @NotNull
149        public static String unquoteIdentifierOrFieldReference(@NotNull String quoted) {
150            if (quoted.indexOf('`') < 0) {
151                return quoted;
152            }
153    
154            if (quoted.startsWith("$")) {
155                return "$" + unquoteIdentifier(quoted.substring(1));
156            }
157            else {
158                return unquoteIdentifier(quoted);
159            }
160        }
161    
162        @Nullable
163        public static Name getShortName(@NotNull KtAnnotationEntry annotation) {
164            KtTypeReference typeReference = annotation.getTypeReference();
165            assert typeReference != null : "Annotation entry hasn't typeReference " + annotation.getText();
166            KtTypeElement typeElement = typeReference.getTypeElement();
167            if (typeElement instanceof KtUserType) {
168                KtUserType userType = (KtUserType) typeElement;
169                String shortName = userType.getReferencedName();
170                if (shortName != null) {
171                    return Name.identifier(shortName);
172                }
173            }
174            return null;
175        }
176    
177        public static boolean isDeprecated(@NotNull KtModifierListOwner owner) {
178            KtModifierList modifierList = owner.getModifierList();
179            if (modifierList != null) {
180                List<KtAnnotationEntry> annotationEntries = modifierList.getAnnotationEntries();
181                for (KtAnnotationEntry annotation : annotationEntries) {
182                    Name shortName = getShortName(annotation);
183                    if (KotlinBuiltIns.FQ_NAMES.deprecated.shortName().equals(shortName)) {
184                        return true;
185                    }
186                }
187            }
188            return false;
189        }
190    
191        @Nullable
192        public static <T extends PsiElement> T getDirectParentOfTypeForBlock(@NotNull KtBlockExpression block, @NotNull Class<T> aClass) {
193            T parent = PsiTreeUtil.getParentOfType(block, aClass);
194            if (parent instanceof KtIfExpression) {
195                KtIfExpression ifExpression = (KtIfExpression) parent;
196                if (ifExpression.getElse() == block || ifExpression.getThen() == block) {
197                    return parent;
198                }
199            }
200            if (parent instanceof KtWhenExpression) {
201                KtWhenExpression whenExpression = (KtWhenExpression) parent;
202                for (KtWhenEntry whenEntry : whenExpression.getEntries()) {
203                    if (whenEntry.getExpression() == block) {
204                        return parent;
205                    }
206                }
207            }
208            if (parent instanceof KtFunctionLiteral) {
209                KtFunctionLiteral functionLiteral = (KtFunctionLiteral) parent;
210                if (functionLiteral.getBodyExpression() == block) {
211                    return parent;
212                }
213            }
214            if (parent instanceof KtTryExpression) {
215                KtTryExpression tryExpression = (KtTryExpression) parent;
216                if (tryExpression.getTryBlock() == block) {
217                    return parent;
218                }
219                for (KtCatchClause clause : tryExpression.getCatchClauses()) {
220                    if (clause.getCatchBody() == block) {
221                        return parent;
222                    }
223                }
224            }
225            return null;
226        }
227    
228        @Nullable
229        public static Name getAliasName(@NotNull KtImportDirective importDirective) {
230            if (importDirective.isAllUnder()) {
231                return null;
232            }
233            String aliasName = importDirective.getAliasName();
234            KtExpression importedReference = importDirective.getImportedReference();
235            if (importedReference == null) {
236                return null;
237            }
238            KtSimpleNameExpression referenceExpression = getLastReference(importedReference);
239            if (aliasName == null) {
240                aliasName = referenceExpression != null ? referenceExpression.getReferencedName() : null;
241            }
242    
243            return aliasName != null && !aliasName.isEmpty() ? Name.identifier(aliasName) : null;
244        }
245    
246        @Nullable
247        public static KtSimpleNameExpression getLastReference(@NotNull KtExpression importedReference) {
248            KtElement selector = KtPsiUtilKt.getQualifiedElementSelector(importedReference);
249            return selector instanceof KtSimpleNameExpression ? (KtSimpleNameExpression) selector : null;
250        }
251    
252        public static boolean isSelectorInQualified(@NotNull KtSimpleNameExpression nameExpression) {
253            KtElement qualifiedElement = KtPsiUtilKt.getQualifiedElement(nameExpression);
254            return qualifiedElement instanceof KtQualifiedExpression
255                   || ((qualifiedElement instanceof KtUserType) && ((KtUserType) qualifiedElement).getQualifier() != null);
256        }
257    
258        public static boolean isLHSOfDot(@NotNull KtExpression expression) {
259            PsiElement parent = expression.getParent();
260            if (!(parent instanceof KtQualifiedExpression)) return false;
261            KtQualifiedExpression qualifiedParent = (KtQualifiedExpression) parent;
262            return qualifiedParent.getReceiverExpression() == expression || isLHSOfDot(qualifiedParent);
263        }
264    
265        public static boolean isScriptDeclaration(@NotNull KtDeclaration namedDeclaration) {
266            return getScript(namedDeclaration) != null;
267        }
268    
269        @Nullable
270        public static KtScript getScript(@NotNull KtDeclaration namedDeclaration) {
271            PsiElement parent = namedDeclaration.getParent();
272            if (parent != null && parent.getParent() instanceof KtScript) {
273                return (KtScript) parent.getParent();
274            }
275            else {
276                return null;
277            }
278        }
279    
280        public static boolean isRemovableVariableDeclaration(@NotNull KtDeclaration declaration) {
281            if (!(declaration instanceof KtVariableDeclaration)) return false;
282            if (declaration instanceof KtProperty) return true;
283            assert declaration instanceof KtDestructuringDeclarationEntry;
284            KtDestructuringDeclaration parentDeclaration = (KtDestructuringDeclaration) declaration.getParent();
285            List<KtDestructuringDeclarationEntry> entries = parentDeclaration.getEntries();
286            return entries.size() > 1 && entries.get(entries.size() - 1) == declaration;
287        }
288    
289        @Nullable
290        @Contract("null, _ -> null")
291        public static PsiElement getTopmostParentOfTypes(
292                @Nullable PsiElement element,
293                @NotNull Class<? extends PsiElement>... parentTypes) {
294            if (element instanceof PsiFile) return null;
295    
296            PsiElement answer = PsiTreeUtil.getParentOfType(element, parentTypes);
297            if (answer instanceof PsiFile) return answer;
298    
299            do {
300                PsiElement next = PsiTreeUtil.getParentOfType(answer, parentTypes);
301                if (next == null) break;
302                answer = next;
303            }
304            while (true);
305    
306            return answer;
307        }
308    
309        public static boolean isNullConstant(@NotNull KtExpression expression) {
310            KtExpression deparenthesized = deparenthesize(expression);
311            return deparenthesized instanceof KtConstantExpression && deparenthesized.getNode().getElementType() == KtNodeTypes.NULL;
312        }
313    
314        public static boolean isTrueConstant(@Nullable KtExpression condition) {
315            return isBooleanConstant(condition) && condition.getNode().findChildByType(KtTokens.TRUE_KEYWORD) != null;
316        }
317    
318        public static boolean isFalseConstant(@Nullable KtExpression condition) {
319            return isBooleanConstant(condition) && condition.getNode().findChildByType(KtTokens.FALSE_KEYWORD) != null;
320        }
321    
322        private static boolean isBooleanConstant(@Nullable KtExpression condition) {
323            return condition != null && condition.getNode().getElementType() == KtNodeTypes.BOOLEAN_CONSTANT;
324        }
325    
326        public static boolean isAbstract(@NotNull KtDeclarationWithBody declaration) {
327            return declaration.getBodyExpression() == null;
328        }
329    
330        public static boolean isBackingFieldReference(@Nullable DeclarationDescriptor descriptor) {
331            return descriptor instanceof SyntheticFieldDescriptor;
332        }
333    
334        @Nullable
335        public static KtExpression getExpressionOrLastStatementInBlock(@Nullable KtExpression expression) {
336            if (expression instanceof KtBlockExpression) {
337                return getLastStatementInABlock((KtBlockExpression) expression);
338            }
339            return expression;
340        }
341    
342        @Nullable
343        public static KtExpression getLastStatementInABlock(@Nullable KtBlockExpression blockExpression) {
344            if (blockExpression == null) return null;
345            List<KtExpression> statements = blockExpression.getStatements();
346            return statements.isEmpty() ? null : statements.get(statements.size() - 1);
347        }
348    
349        public static boolean isTrait(@NotNull KtClassOrObject classOrObject) {
350            return classOrObject instanceof KtClass && ((KtClass) classOrObject).isInterface();
351        }
352    
353        @Nullable
354        public static KtClassOrObject getOutermostClassOrObject(@NotNull KtClassOrObject classOrObject) {
355            KtClassOrObject current = classOrObject;
356            while (true) {
357                PsiElement parent = current.getParent();
358                assert classOrObject.getParent() != null : "Class with no parent: " + classOrObject.getText();
359    
360                if (parent instanceof PsiFile) {
361                    return current;
362                }
363                if (!(parent instanceof KtClassBody)) {
364                    // It is a local class, no legitimate outer
365                    return current;
366                }
367    
368                current = (KtClassOrObject) parent.getParent();
369            }
370        }
371    
372        @Nullable
373        public static KtClassOrObject getClassIfParameterIsProperty(@NotNull KtParameter jetParameter) {
374            if (jetParameter.hasValOrVar()) {
375                PsiElement grandParent = jetParameter.getParent().getParent();
376                if (grandParent instanceof KtPrimaryConstructor) {
377                    return ((KtPrimaryConstructor) grandParent).getContainingClassOrObject();
378                }
379            }
380    
381            return null;
382        }
383    
384        @Nullable
385        private static IElementType getOperation(@NotNull KtExpression expression) {
386            if (expression instanceof KtQualifiedExpression) {
387                return ((KtQualifiedExpression) expression).getOperationSign();
388            }
389            else if (expression instanceof KtOperationExpression) {
390                return ((KtOperationExpression) expression).getOperationReference().getReferencedNameElementType();
391            }
392            return null;
393        }
394    
395    
396        private static int getPriority(@NotNull KtExpression expression) {
397            int maxPriority = KotlinExpressionParsing.Precedence.values().length + 1;
398    
399            // same as postfix operations
400            if (expression instanceof KtPostfixExpression ||
401                expression instanceof KtQualifiedExpression ||
402                expression instanceof KtCallExpression ||
403                expression instanceof KtArrayAccessExpression) {
404                return maxPriority - 1;
405            }
406    
407            if (expression instanceof KtPrefixExpression || expression instanceof KtLabeledExpression) return maxPriority - 2;
408    
409            if (expression instanceof KtIfExpression) {
410                return KotlinExpressionParsing.Precedence.ASSIGNMENT.ordinal();
411            }
412    
413            if (expression instanceof KtSuperExpression) {
414                return maxPriority;
415            }
416    
417            if (expression instanceof KtDeclaration || expression instanceof KtStatementExpression) {
418                return 0;
419            }
420    
421            IElementType operation = getOperation(expression);
422            for (KotlinExpressionParsing.Precedence precedence : KotlinExpressionParsing.Precedence.values()) {
423                if (precedence != KotlinExpressionParsing.Precedence.PREFIX && precedence != KotlinExpressionParsing.Precedence.POSTFIX &&
424                    precedence.getOperations().contains(operation)) {
425                    return maxPriority - precedence.ordinal() - 1;
426                }
427            }
428    
429            return maxPriority;
430        }
431    
432        public static boolean areParenthesesUseless(@NotNull KtParenthesizedExpression expression) {
433            KtExpression innerExpression = expression.getExpression();
434            if (innerExpression == null) return true;
435    
436            PsiElement parent = expression.getParent();
437            if (!(parent instanceof KtExpression)) return true;
438    
439            return !areParenthesesNecessary(innerExpression, expression, (KtExpression) parent);
440        }
441    
442        public static boolean areParenthesesNecessary(
443                @NotNull KtExpression innerExpression,
444                @NotNull KtExpression currentInner,
445                @NotNull KtElement parentElement
446        ) {
447            if (parentElement instanceof KtParenthesizedExpression || innerExpression instanceof KtParenthesizedExpression) {
448                return false;
449            }
450    
451            if (parentElement instanceof KtPackageDirective) return false;
452    
453            if (parentElement instanceof KtWhenExpression || innerExpression instanceof KtWhenExpression) {
454                return false;
455            }
456    
457            if (innerExpression instanceof KtIfExpression) {
458                if (parentElement instanceof KtQualifiedExpression) return true;
459    
460                PsiElement current = parentElement;
461    
462                while (!(current instanceof KtBlockExpression || current instanceof KtDeclaration || current instanceof KtStatementExpression || current instanceof KtFile)) {
463                    if (current.getTextRange().getEndOffset() != currentInner.getTextRange().getEndOffset()) {
464                        return !(current instanceof KtParenthesizedExpression) && !(current instanceof KtValueArgumentList); // if current expression is "guarded" by parenthesis, no extra parenthesis is necessary
465                    }
466    
467                    current = current.getParent();
468                }
469            }
470    
471            if (parentElement instanceof KtCallExpression && currentInner == ((KtCallExpression) parentElement).getCalleeExpression()) {
472                if (innerExpression instanceof KtSimpleNameExpression) return false;
473                if (KtPsiUtilKt.getQualifiedExpressionForSelector(parentElement) != null) return true;
474                return !(innerExpression instanceof KtThisExpression
475                         || innerExpression instanceof KtArrayAccessExpression
476                         || innerExpression instanceof KtConstantExpression
477                         || innerExpression instanceof KtStringTemplateExpression
478                         || innerExpression instanceof KtCallExpression);
479            }
480    
481            if (parentElement instanceof KtValueArgument) {
482                // a(___, d > (e + f)) => a((b < c), d > (e + f)) to prevent parsing < c, d > as type argument list
483                KtValueArgument nextArg = PsiTreeUtil.getNextSiblingOfType(parentElement, KtValueArgument.class);
484                PsiElement nextExpression = nextArg != null ? nextArg.getArgumentExpression() : null;
485                if (innerExpression instanceof KtBinaryExpression &&
486                    ((KtBinaryExpression) innerExpression).getOperationToken() == KtTokens.LT &&
487                    nextExpression instanceof KtBinaryExpression &&
488                    ((KtBinaryExpression) nextExpression).getOperationToken() == KtTokens.GT) return true;
489            }
490    
491            if (!(parentElement instanceof KtExpression)) return false;
492    
493            IElementType innerOperation = getOperation(innerExpression);
494            IElementType parentOperation = getOperation((KtExpression) parentElement);
495    
496            // 'return (@label{...})' case
497            if (parentElement instanceof KtReturnExpression
498                && (innerExpression instanceof KtLabeledExpression || innerExpression instanceof KtAnnotatedExpression)) return true;
499    
500            // '(x: Int) < y' case
501            if (innerExpression instanceof KtBinaryExpressionWithTypeRHS && parentOperation == KtTokens.LT) {
502                return true;
503            }
504    
505            if (parentElement instanceof KtLabeledExpression) return false;
506    
507            // 'x ?: ...' case
508            if (parentElement instanceof KtBinaryExpression && parentOperation == KtTokens.ELVIS && currentInner == ((KtBinaryExpression) parentElement).getRight()) {
509                return false;
510            }
511    
512            int innerPriority = getPriority(innerExpression);
513            int parentPriority = getPriority((KtExpression) parentElement);
514    
515            if (innerPriority == parentPriority) {
516                if (parentElement instanceof KtBinaryExpression) {
517                    if (innerOperation == KtTokens.ANDAND || innerOperation == KtTokens.OROR) {
518                        return false;
519                    }
520                    return ((KtBinaryExpression) parentElement).getRight() == currentInner;
521                }
522    
523                //'-(-x)' case
524                if (parentElement instanceof KtPrefixExpression && innerExpression instanceof KtPrefixExpression) {
525                    return innerOperation == parentOperation && (innerOperation == KtTokens.PLUS || innerOperation == KtTokens.MINUS);
526                }
527                return false;
528            }
529    
530            return innerPriority < parentPriority;
531        }
532    
533        public static boolean isAssignment(@NotNull PsiElement element) {
534            return element instanceof KtBinaryExpression &&
535                   KtTokens.ALL_ASSIGNMENTS.contains(((KtBinaryExpression) element).getOperationToken());
536        }
537    
538        public static boolean isOrdinaryAssignment(@NotNull PsiElement element) {
539            return element instanceof KtBinaryExpression &&
540                   ((KtBinaryExpression) element).getOperationToken().equals(KtTokens.EQ);
541        }
542    
543        public static boolean checkVariableDeclarationInBlock(@NotNull KtBlockExpression block, @NotNull String varName) {
544            for (KtExpression element : block.getStatements()) {
545                if (element instanceof KtVariableDeclaration) {
546                    if (((KtVariableDeclaration) element).getNameAsSafeName().asString().equals(varName)) {
547                        return true;
548                    }
549                }
550            }
551    
552            return false;
553        }
554    
555        public static boolean checkWhenExpressionHasSingleElse(@NotNull KtWhenExpression whenExpression) {
556            int elseCount = 0;
557            for (KtWhenEntry entry : whenExpression.getEntries()) {
558                if (entry.isElse()) {
559                    elseCount++;
560                }
561            }
562            return (elseCount == 1);
563        }
564    
565        @Nullable
566        public static PsiElement skipTrailingWhitespacesAndComments(@Nullable PsiElement element)  {
567            return PsiTreeUtil.skipSiblingsForward(element, PsiWhiteSpace.class, PsiComment.class);
568        }
569    
570        @Nullable
571        public static PsiElement prevLeafIgnoringWhitespaceAndComments(@NotNull PsiElement element) {
572            PsiElement prev = PsiTreeUtil.prevLeaf(element, true);
573            while (prev != null && KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET.contains(prev.getNode().getElementType())) {
574                prev = PsiTreeUtil.prevLeaf(prev, true);
575            }
576            return prev;
577        }
578    
579        /**
580         * Example:
581         *      code: async* {}
582         *      element = "{}"
583         *      word = "async"
584         *      suffixTokens = [+, -, *, /, %]
585         *
586         *      result = async
587         */
588        @Nullable
589        public static PsiElement getPreviousWord(@NotNull PsiElement element, @NotNull String word, @NotNull TokenSet suffixTokens) {
590            PsiElement prev = prevLeafIgnoringWhitespaceAndComments(element);
591            if (prev != null && suffixTokens.contains(prev.getNode().getElementType())) {
592                prev = PsiTreeUtil.prevLeaf(prev, false);
593            }
594            if (prev != null && prev.getNode().getElementType() == KtTokens.IDENTIFIER && word.equals(prev.getText())) {
595                return prev;
596            }
597    
598            return null;
599        }
600    
601        public static final Predicate<KtElement> ANY_JET_ELEMENT = new Predicate<KtElement>() {
602            @Override
603            public boolean apply(@Nullable KtElement input) {
604                return true;
605            }
606        };
607    
608        @NotNull
609        public static String getText(@Nullable PsiElement element) {
610            return element != null ? element.getText() : "";
611        }
612    
613        @Nullable
614        public static String getNullableText(@Nullable PsiElement element) {
615            return element != null ? element.getText() : null;
616        }
617    
618        /**
619         * CommentUtilCore.isComment fails if element <strong>inside</strong> comment.
620         *
621         * Also, we can not add KDocTokens to COMMENTS TokenSet, because it is used in KotlinParserDefinition.getCommentTokens(),
622         * and therefor all COMMENTS tokens will be ignored by PsiBuilder.
623         *
624         * @param element
625         * @return
626         */
627        public static boolean isInComment(PsiElement element) {
628            return CommentUtilCore.isComment(element) || element instanceof KDocElement;
629        }
630    
631        @Nullable
632        public static PsiElement getOutermostParent(@NotNull PsiElement element, @NotNull PsiElement upperBound, boolean strict) {
633            PsiElement parent = strict ? element.getParent() : element;
634            while (parent != null && parent.getParent() != upperBound) {
635                parent = parent.getParent();
636            }
637    
638            return parent;
639        }
640    
641        public static <T extends PsiElement> T getLastChildByType(@NotNull PsiElement root, @NotNull Class<? extends T>... elementTypes) {
642            PsiElement[] children = root.getChildren();
643    
644            for (int i = children.length - 1; i >= 0; i--) {
645                if (PsiTreeUtil.instanceOf(children[i], elementTypes)) {
646                    //noinspection unchecked
647                    return (T) children[i];
648                }
649            }
650    
651            return null;
652        }
653    
654        @Nullable
655        public static KtElement getOutermostDescendantElement(
656                @Nullable PsiElement root,
657                boolean first,
658                final @NotNull Predicate<KtElement> predicate
659        ) {
660            if (!(root instanceof KtElement)) return null;
661    
662            final List<KtElement> results = Lists.newArrayList();
663    
664            root.accept(
665                    new KtVisitorVoid() {
666                        @Override
667                        public void visitKtElement(@NotNull KtElement element) {
668                            if (predicate.apply(element)) {
669                                //noinspection unchecked
670                                results.add(element);
671                            }
672                            else {
673                                element.acceptChildren(this);
674                            }
675                        }
676                    }
677            );
678    
679            if (results.isEmpty()) return null;
680    
681            return first ? results.get(0) : results.get(results.size() - 1);
682        }
683    
684        @Nullable
685        public static PsiElement findChildByType(@NotNull PsiElement element, @NotNull IElementType type) {
686            ASTNode node = element.getNode().findChildByType(type);
687            return node == null ? null : node.getPsi();
688        }
689    
690        @Nullable
691        public static PsiElement skipSiblingsBackwardByPredicate(@Nullable PsiElement element, Predicate<PsiElement> elementsToSkip) {
692            if (element == null) return null;
693            for (PsiElement e = element.getPrevSibling(); e != null; e = e.getPrevSibling()) {
694                if (elementsToSkip.apply(e)) continue;
695                return e;
696            }
697            return null;
698        }
699    
700        public static PsiElement ascendIfPropertyAccessor(PsiElement element) {
701            if (element instanceof KtPropertyAccessor) {
702                return element.getParent();
703            }
704            return element;
705        }
706    
707        @Nullable
708        @Contract("_, !null -> !null")
709        public static KtModifierList replaceModifierList(@NotNull KtModifierListOwner owner, @Nullable KtModifierList modifierList) {
710            KtModifierList oldModifierList = owner.getModifierList();
711            if (modifierList == null) {
712                if (oldModifierList != null) oldModifierList.delete();
713                return null;
714            }
715            else {
716                if (oldModifierList == null) {
717                    PsiElement firstChild = owner.getFirstChild();
718                    return (KtModifierList) owner.addBefore(modifierList, firstChild);
719                }
720                else {
721                    return (KtModifierList) oldModifierList.replace(modifierList);
722                }
723            }
724        }
725    
726        @Nullable
727        public static String getPackageName(@NotNull KtElement element) {
728            KtFile file = element.getContainingKtFile();
729            KtPackageDirective header = PsiTreeUtil.findChildOfType(file, KtPackageDirective.class);
730    
731            return header != null ? header.getQualifiedName() : null;
732        }
733    
734        @Nullable
735        public static KtElement getEnclosingElementForLocalDeclaration(@NotNull KtDeclaration declaration) {
736            return getEnclosingElementForLocalDeclaration(declaration, true);
737        }
738    
739        private static boolean isMemberOfObjectExpression(@NotNull KtCallableDeclaration propertyOrFunction) {
740            PsiElement parent = PsiTreeUtil.getStubOrPsiParent(propertyOrFunction);
741            if (!(parent instanceof KtClassBody)) return false;
742            PsiElement grandparent = PsiTreeUtil.getStubOrPsiParent(parent);
743            if (!(grandparent instanceof KtObjectDeclaration)) return false;
744            return PsiTreeUtil.getStubOrPsiParent(grandparent) instanceof KtObjectLiteralExpression;
745        }
746    
747        @Nullable
748        public static KtElement getEnclosingElementForLocalDeclaration(@NotNull KtDeclaration declaration, boolean skipParameters) {
749            if (declaration instanceof KtTypeParameter && skipParameters) {
750                declaration = PsiTreeUtil.getParentOfType(declaration, KtNamedDeclaration.class);
751            }
752            else if (declaration instanceof KtParameter) {
753                KtFunctionType functionType = PsiTreeUtil.getParentOfType(declaration, KtFunctionType.class);
754                if (functionType != null) {
755                    return functionType;
756                }
757    
758                PsiElement parent = declaration.getParent();
759    
760                // val/var parameter of primary constructor should be considered as local according to containing class
761                if (((KtParameter) declaration).hasValOrVar() && parent != null && parent.getParent() instanceof KtPrimaryConstructor) {
762                    return getEnclosingElementForLocalDeclaration(((KtPrimaryConstructor) parent.getParent()).getContainingClassOrObject(), skipParameters);
763                }
764    
765                else if (skipParameters && parent != null && parent.getParent() instanceof KtNamedFunction) {
766                    declaration = (KtNamedFunction) parent.getParent();
767                }
768            }
769    
770            if (declaration instanceof PsiFile) {
771                return declaration;
772            }
773    
774            // No appropriate stub-tolerant method in PsiTreeUtil, nor JetStubbedPsiUtil, writing manually
775            PsiElement current = PsiTreeUtil.getStubOrPsiParent(declaration);
776            while (current != null) {
777                PsiElement parent = PsiTreeUtil.getStubOrPsiParent(current);
778                if (parent instanceof KtScript) return null;
779                if (current instanceof KtAnonymousInitializer) {
780                    return ((KtAnonymousInitializer) current).getBody();
781                }
782                if (current instanceof KtProperty || current instanceof KtFunction) {
783                    if (parent instanceof KtFile) {
784                        return (KtElement) current;
785                    }
786                    else if (parent instanceof KtClassBody && !isMemberOfObjectExpression((KtCallableDeclaration) current)) {
787                        return (KtElement) parent;
788                    }
789                }
790                if (current instanceof KtBlockExpression || current instanceof KtParameter) {
791                    return (KtElement) current;
792                }
793                if (current instanceof KtValueArgument) {
794                    return (KtElement) current;
795                }
796    
797                current = parent;
798            }
799            return null;
800        }
801    
802        public static boolean isLocal(@NotNull KtDeclaration declaration) {
803            return getEnclosingElementForLocalDeclaration(declaration) != null;
804        }
805    
806        @Nullable
807        public static KtToken getOperationToken(@NotNull KtOperationExpression expression) {
808            KtSimpleNameExpression operationExpression = expression.getOperationReference();
809            IElementType elementType = operationExpression.getReferencedNameElementType();
810            assert elementType == null || elementType instanceof KtToken :
811                    "JetOperationExpression should have operation token of type KtToken: " +
812                    expression;
813            return (KtToken) elementType;
814        }
815    
816        public static boolean isLabelIdentifierExpression(PsiElement element) {
817            return element instanceof KtLabelReferenceExpression;
818        }
819    
820        @Nullable
821        public static KtExpression getParentCallIfPresent(@NotNull KtExpression expression) {
822            PsiElement parent = expression.getParent();
823            while (parent != null) {
824                if (parent instanceof KtBinaryExpression ||
825                    parent instanceof KtUnaryExpression ||
826                    parent instanceof KtLabeledExpression ||
827                    parent instanceof KtDotQualifiedExpression ||
828                    parent instanceof KtCallExpression ||
829                    parent instanceof KtArrayAccessExpression ||
830                    parent instanceof KtDestructuringDeclaration) {
831    
832                    if (parent instanceof KtLabeledExpression) {
833                        parent = parent.getParent();
834                        continue;
835                    }
836    
837                    //check that it's in inlineable call would be in resolve call of parent
838                    return (KtExpression) parent;
839                }
840                else if (parent instanceof KtParenthesizedExpression || parent instanceof KtBinaryExpressionWithTypeRHS) {
841                    parent = parent.getParent();
842                }
843                else if (parent instanceof KtValueArgument || parent instanceof KtValueArgumentList) {
844                    parent = parent.getParent();
845                }
846                else if (parent instanceof KtLambdaExpression || parent instanceof KtAnnotatedExpression) {
847                    parent = parent.getParent();
848                }
849                else {
850                    return null;
851                }
852            }
853            return null;
854        }
855    
856        @Nullable
857        public static KtExpression getLastElementDeparenthesized(
858                @Nullable KtExpression expression,
859                @NotNull StatementFilter statementFilter
860        ) {
861            KtExpression deparenthesizedExpression = deparenthesize(expression);
862            if (deparenthesizedExpression instanceof KtBlockExpression) {
863                KtBlockExpression blockExpression = (KtBlockExpression) deparenthesizedExpression;
864                // todo
865                // This case is a temporary hack for 'if' branches.
866                // The right way to implement this logic is to interpret 'if' branches as function literals with explicitly-typed signatures
867                // (no arguments and no receiver) and therefore analyze them straight away (not in the 'complete' phase).
868                KtExpression lastStatementInABlock = StatementFilterKt.getLastStatementInABlock(statementFilter, blockExpression);
869                if (lastStatementInABlock != null) {
870                    return getLastElementDeparenthesized(lastStatementInABlock, statementFilter);
871                }
872            }
873            return deparenthesizedExpression;
874        }
875    }