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 &&
509                parentOperation == KtTokens.ELVIS &&
510                !(innerExpression instanceof KtBinaryExpression) &&
511                currentInner == ((KtBinaryExpression) parentElement).getRight()) {
512                return false;
513            }
514    
515            int innerPriority = getPriority(innerExpression);
516            int parentPriority = getPriority((KtExpression) parentElement);
517    
518            if (innerPriority == parentPriority) {
519                if (parentElement instanceof KtBinaryExpression) {
520                    if (innerOperation == KtTokens.ANDAND || innerOperation == KtTokens.OROR) {
521                        return false;
522                    }
523                    return ((KtBinaryExpression) parentElement).getRight() == currentInner;
524                }
525    
526                //'-(-x)' case
527                if (parentElement instanceof KtPrefixExpression && innerExpression instanceof KtPrefixExpression) {
528                    return innerOperation == parentOperation && (innerOperation == KtTokens.PLUS || innerOperation == KtTokens.MINUS);
529                }
530                return false;
531            }
532    
533            return innerPriority < parentPriority;
534        }
535    
536        public static boolean isAssignment(@NotNull PsiElement element) {
537            return element instanceof KtBinaryExpression &&
538                   KtTokens.ALL_ASSIGNMENTS.contains(((KtBinaryExpression) element).getOperationToken());
539        }
540    
541        public static boolean isOrdinaryAssignment(@NotNull PsiElement element) {
542            return element instanceof KtBinaryExpression &&
543                   ((KtBinaryExpression) element).getOperationToken().equals(KtTokens.EQ);
544        }
545    
546        public static boolean checkVariableDeclarationInBlock(@NotNull KtBlockExpression block, @NotNull String varName) {
547            for (KtExpression element : block.getStatements()) {
548                if (element instanceof KtVariableDeclaration) {
549                    if (((KtVariableDeclaration) element).getNameAsSafeName().asString().equals(varName)) {
550                        return true;
551                    }
552                }
553            }
554    
555            return false;
556        }
557    
558        public static boolean checkWhenExpressionHasSingleElse(@NotNull KtWhenExpression whenExpression) {
559            int elseCount = 0;
560            for (KtWhenEntry entry : whenExpression.getEntries()) {
561                if (entry.isElse()) {
562                    elseCount++;
563                }
564            }
565            return (elseCount == 1);
566        }
567    
568        @Nullable
569        public static PsiElement skipTrailingWhitespacesAndComments(@Nullable PsiElement element)  {
570            return PsiTreeUtil.skipSiblingsForward(element, PsiWhiteSpace.class, PsiComment.class);
571        }
572    
573        @Nullable
574        public static PsiElement prevLeafIgnoringWhitespaceAndComments(@NotNull PsiElement element) {
575            PsiElement prev = PsiTreeUtil.prevLeaf(element, true);
576            while (prev != null && KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET.contains(prev.getNode().getElementType())) {
577                prev = PsiTreeUtil.prevLeaf(prev, true);
578            }
579            return prev;
580        }
581    
582        /**
583         * Example:
584         *      code: async* {}
585         *      element = "{}"
586         *      word = "async"
587         *      suffixTokens = [+, -, *, /, %]
588         *
589         *      result = async
590         */
591        @Nullable
592        public static PsiElement getPreviousWord(@NotNull PsiElement element, @NotNull String word, @NotNull TokenSet suffixTokens) {
593            PsiElement prev = prevLeafIgnoringWhitespaceAndComments(element);
594            if (prev != null && suffixTokens.contains(prev.getNode().getElementType())) {
595                prev = PsiTreeUtil.prevLeaf(prev, false);
596            }
597            if (prev != null && prev.getNode().getElementType() == KtTokens.IDENTIFIER && word.equals(prev.getText())) {
598                return prev;
599            }
600    
601            return null;
602        }
603    
604        public static final Predicate<KtElement> ANY_JET_ELEMENT = new Predicate<KtElement>() {
605            @Override
606            public boolean apply(@Nullable KtElement input) {
607                return true;
608            }
609        };
610    
611        @NotNull
612        public static String getText(@Nullable PsiElement element) {
613            return element != null ? element.getText() : "";
614        }
615    
616        @Nullable
617        public static String getNullableText(@Nullable PsiElement element) {
618            return element != null ? element.getText() : null;
619        }
620    
621        /**
622         * CommentUtilCore.isComment fails if element <strong>inside</strong> comment.
623         *
624         * Also, we can not add KDocTokens to COMMENTS TokenSet, because it is used in KotlinParserDefinition.getCommentTokens(),
625         * and therefor all COMMENTS tokens will be ignored by PsiBuilder.
626         *
627         * @param element
628         * @return
629         */
630        public static boolean isInComment(PsiElement element) {
631            return CommentUtilCore.isComment(element) || element instanceof KDocElement;
632        }
633    
634        @Nullable
635        public static PsiElement getOutermostParent(@NotNull PsiElement element, @NotNull PsiElement upperBound, boolean strict) {
636            PsiElement parent = strict ? element.getParent() : element;
637            while (parent != null && parent.getParent() != upperBound) {
638                parent = parent.getParent();
639            }
640    
641            return parent;
642        }
643    
644        public static <T extends PsiElement> T getLastChildByType(@NotNull PsiElement root, @NotNull Class<? extends T>... elementTypes) {
645            PsiElement[] children = root.getChildren();
646    
647            for (int i = children.length - 1; i >= 0; i--) {
648                if (PsiTreeUtil.instanceOf(children[i], elementTypes)) {
649                    //noinspection unchecked
650                    return (T) children[i];
651                }
652            }
653    
654            return null;
655        }
656    
657        @Nullable
658        public static KtElement getOutermostDescendantElement(
659                @Nullable PsiElement root,
660                boolean first,
661                final @NotNull Predicate<KtElement> predicate
662        ) {
663            if (!(root instanceof KtElement)) return null;
664    
665            final List<KtElement> results = Lists.newArrayList();
666    
667            root.accept(
668                    new KtVisitorVoid() {
669                        @Override
670                        public void visitKtElement(@NotNull KtElement element) {
671                            if (predicate.apply(element)) {
672                                //noinspection unchecked
673                                results.add(element);
674                            }
675                            else {
676                                element.acceptChildren(this);
677                            }
678                        }
679                    }
680            );
681    
682            if (results.isEmpty()) return null;
683    
684            return first ? results.get(0) : results.get(results.size() - 1);
685        }
686    
687        @Nullable
688        public static PsiElement findChildByType(@NotNull PsiElement element, @NotNull IElementType type) {
689            ASTNode node = element.getNode().findChildByType(type);
690            return node == null ? null : node.getPsi();
691        }
692    
693        @Nullable
694        public static PsiElement skipSiblingsBackwardByPredicate(@Nullable PsiElement element, Predicate<PsiElement> elementsToSkip) {
695            if (element == null) return null;
696            for (PsiElement e = element.getPrevSibling(); e != null; e = e.getPrevSibling()) {
697                if (elementsToSkip.apply(e)) continue;
698                return e;
699            }
700            return null;
701        }
702    
703        public static PsiElement ascendIfPropertyAccessor(PsiElement element) {
704            if (element instanceof KtPropertyAccessor) {
705                return element.getParent();
706            }
707            return element;
708        }
709    
710        @Nullable
711        @Contract("_, !null -> !null")
712        public static KtModifierList replaceModifierList(@NotNull KtModifierListOwner owner, @Nullable KtModifierList modifierList) {
713            KtModifierList oldModifierList = owner.getModifierList();
714            if (modifierList == null) {
715                if (oldModifierList != null) oldModifierList.delete();
716                return null;
717            }
718            else {
719                if (oldModifierList == null) {
720                    PsiElement firstChild = owner.getFirstChild();
721                    return (KtModifierList) owner.addBefore(modifierList, firstChild);
722                }
723                else {
724                    return (KtModifierList) oldModifierList.replace(modifierList);
725                }
726            }
727        }
728    
729        @Nullable
730        public static String getPackageName(@NotNull KtElement element) {
731            KtFile file = element.getContainingKtFile();
732            KtPackageDirective header = PsiTreeUtil.findChildOfType(file, KtPackageDirective.class);
733    
734            return header != null ? header.getQualifiedName() : null;
735        }
736    
737        @Nullable
738        public static KtElement getEnclosingElementForLocalDeclaration(@NotNull KtDeclaration declaration) {
739            return getEnclosingElementForLocalDeclaration(declaration, true);
740        }
741    
742        private static boolean isMemberOfObjectExpression(@NotNull KtCallableDeclaration propertyOrFunction) {
743            PsiElement parent = PsiTreeUtil.getStubOrPsiParent(propertyOrFunction);
744            if (!(parent instanceof KtClassBody)) return false;
745            PsiElement grandparent = PsiTreeUtil.getStubOrPsiParent(parent);
746            if (!(grandparent instanceof KtObjectDeclaration)) return false;
747            return PsiTreeUtil.getStubOrPsiParent(grandparent) instanceof KtObjectLiteralExpression;
748        }
749    
750        @Nullable
751        public static KtElement getEnclosingElementForLocalDeclaration(@NotNull KtDeclaration declaration, boolean skipParameters) {
752            if (declaration instanceof KtTypeParameter && skipParameters) {
753                declaration = PsiTreeUtil.getParentOfType(declaration, KtNamedDeclaration.class);
754            }
755            else if (declaration instanceof KtParameter) {
756                KtFunctionType functionType = PsiTreeUtil.getParentOfType(declaration, KtFunctionType.class);
757                if (functionType != null) {
758                    return functionType;
759                }
760    
761                PsiElement parent = declaration.getParent();
762    
763                // val/var parameter of primary constructor should be considered as local according to containing class
764                if (((KtParameter) declaration).hasValOrVar() && parent != null && parent.getParent() instanceof KtPrimaryConstructor) {
765                    return getEnclosingElementForLocalDeclaration(((KtPrimaryConstructor) parent.getParent()).getContainingClassOrObject(), skipParameters);
766                }
767                else if (skipParameters && parent != null && parent.getParent() instanceof KtNamedFunction) {
768                    declaration = (KtNamedFunction) parent.getParent();
769                }
770            }
771    
772            if (declaration instanceof PsiFile) {
773                return declaration;
774            }
775    
776            // No appropriate stub-tolerant method in PsiTreeUtil, nor JetStubbedPsiUtil, writing manually
777            PsiElement current = PsiTreeUtil.getStubOrPsiParent(declaration);
778            while (current != null) {
779                PsiElement parent = PsiTreeUtil.getStubOrPsiParent(current);
780                if (parent instanceof KtScript) return null;
781                if (current instanceof KtAnonymousInitializer) {
782                    return ((KtAnonymousInitializer) current).getBody();
783                }
784                if (current instanceof KtProperty || current instanceof KtFunction) {
785                    if (parent instanceof KtFile) {
786                        return (KtElement) current;
787                    }
788                    else if (parent instanceof KtClassBody && !isMemberOfObjectExpression((KtCallableDeclaration) current)) {
789                        return (KtElement) parent;
790                    }
791                }
792                if (current instanceof KtBlockExpression || current instanceof KtParameter) {
793                    return (KtElement) current;
794                }
795                if (current instanceof KtValueArgument) {
796                    return (KtElement) current;
797                }
798    
799                current = parent;
800            }
801            return null;
802        }
803    
804        public static boolean isLocal(@NotNull KtDeclaration declaration) {
805            return getEnclosingElementForLocalDeclaration(declaration) != null;
806        }
807    
808        @Nullable
809        public static KtToken getOperationToken(@NotNull KtOperationExpression expression) {
810            KtSimpleNameExpression operationExpression = expression.getOperationReference();
811            IElementType elementType = operationExpression.getReferencedNameElementType();
812            assert elementType == null || elementType instanceof KtToken :
813                    "JetOperationExpression should have operation token of type KtToken: " +
814                    expression;
815            return (KtToken) elementType;
816        }
817    
818        public static boolean isLabelIdentifierExpression(PsiElement element) {
819            return element instanceof KtLabelReferenceExpression;
820        }
821    
822        @Nullable
823        public static KtExpression getParentCallIfPresent(@NotNull KtExpression expression) {
824            PsiElement parent = expression.getParent();
825            while (parent != null) {
826                if (parent instanceof KtBinaryExpression ||
827                    parent instanceof KtUnaryExpression ||
828                    parent instanceof KtLabeledExpression ||
829                    parent instanceof KtDotQualifiedExpression ||
830                    parent instanceof KtCallExpression ||
831                    parent instanceof KtArrayAccessExpression ||
832                    parent instanceof KtDestructuringDeclaration) {
833    
834                    if (parent instanceof KtLabeledExpression) {
835                        parent = parent.getParent();
836                        continue;
837                    }
838    
839                    //check that it's in inlineable call would be in resolve call of parent
840                    return (KtExpression) parent;
841                }
842                else if (parent instanceof KtParenthesizedExpression || parent instanceof KtBinaryExpressionWithTypeRHS) {
843                    parent = parent.getParent();
844                }
845                else if (parent instanceof KtValueArgument || parent instanceof KtValueArgumentList) {
846                    parent = parent.getParent();
847                }
848                else if (parent instanceof KtLambdaExpression || parent instanceof KtAnnotatedExpression) {
849                    parent = parent.getParent();
850                }
851                else {
852                    return null;
853                }
854            }
855            return null;
856        }
857    
858        @Nullable
859        public static KtExpression getLastElementDeparenthesized(
860                @Nullable KtExpression expression,
861                @NotNull StatementFilter statementFilter
862        ) {
863            KtExpression deparenthesizedExpression = deparenthesize(expression);
864            if (deparenthesizedExpression instanceof KtBlockExpression) {
865                KtBlockExpression blockExpression = (KtBlockExpression) deparenthesizedExpression;
866                // todo
867                // This case is a temporary hack for 'if' branches.
868                // The right way to implement this logic is to interpret 'if' branches as function literals with explicitly-typed signatures
869                // (no arguments and no receiver) and therefore analyze them straight away (not in the 'complete' phase).
870                KtExpression lastStatementInABlock = StatementFilterKt.getLastStatementInABlock(statementFilter, blockExpression);
871                if (lastStatementInABlock != null) {
872                    return getLastElementDeparenthesized(lastStatementInABlock, statementFilter);
873                }
874            }
875            return deparenthesizedExpression;
876        }
877    }