001 /*
002 * Copyright 2010-2015 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.intellij.lang.ASTNode;
020 import com.intellij.psi.ElementManipulators;
021 import com.intellij.psi.LiteralTextEscaper;
022 import com.intellij.psi.PsiLanguageInjectionHost;
023 import com.intellij.psi.tree.TokenSet;
024 import org.jetbrains.annotations.NotNull;
025 import org.jetbrains.kotlin.KtNodeTypes;
026 import org.jetbrains.kotlin.lexer.KtTokens;
027
028 public class KtStringTemplateExpression extends KtExpressionImpl implements PsiLanguageInjectionHost {
029 private static final TokenSet TOKENS_SUITABLE_FOR_INJECTION = TokenSet.create(KtNodeTypes.LITERAL_STRING_TEMPLATE_ENTRY, KtNodeTypes.ESCAPE_STRING_TEMPLATE_ENTRY);
030
031 public KtStringTemplateExpression(@NotNull ASTNode node) {
032 super(node);
033 }
034
035 @Override
036 public <R, D> R accept(@NotNull KtVisitor<R, D> visitor, D data) {
037 return visitor.visitStringTemplateExpression(this, data);
038 }
039
040 @NotNull
041 public KtStringTemplateEntry[] getEntries() {
042 return findChildrenByClass(KtStringTemplateEntry.class);
043 }
044
045 @Override
046 public boolean isValidHost() {
047 ASTNode node = getNode();
048 ASTNode child = node.getFirstChildNode().getTreeNext();
049 while (child != null) {
050 if (child.getElementType() == KtTokens.CLOSING_QUOTE) return true;
051 if (!TOKENS_SUITABLE_FOR_INJECTION.contains(child.getElementType())) return false;
052 child = child.getTreeNext();
053 }
054 return false;
055 }
056
057 @Override
058 public PsiLanguageInjectionHost updateText(@NotNull String text) {
059 KtExpression newExpression = new KtPsiFactory(getProject()).createExpressionIfPossible(text);
060 if (newExpression instanceof KtStringTemplateExpression) return (KtStringTemplateExpression) replace(newExpression);
061 return ElementManipulators.handleContentChange(this, text);
062 }
063
064 @NotNull
065 @Override
066 public LiteralTextEscaper<? extends PsiLanguageInjectionHost> createLiteralTextEscaper() {
067 return new KotlinStringLiteralTextEscaper(this);
068 }
069 }