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.JetNodeTypes;
026    import org.jetbrains.kotlin.lexer.JetTokens;
027    
028    public class JetStringTemplateExpression extends JetExpressionImpl implements PsiLanguageInjectionHost {
029        private static final TokenSet TOKENS_SUITABLE_FOR_INJECTION = TokenSet.create(JetNodeTypes.LITERAL_STRING_TEMPLATE_ENTRY, JetNodeTypes.ESCAPE_STRING_TEMPLATE_ENTRY);
030    
031        public JetStringTemplateExpression(@NotNull ASTNode node) {
032            super(node);
033        }
034    
035        @Override
036        public <R, D> R accept(@NotNull JetVisitor<R, D> visitor, D data) {
037            return visitor.visitStringTemplateExpression(this, data);
038        }
039    
040        @NotNull
041        public JetStringTemplateEntry[] getEntries() {
042            return findChildrenByClass(JetStringTemplateEntry.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() == JetTokens.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            return ElementManipulators.handleContentChange(this, text);
060        }
061    
062        @NotNull
063        @Override
064        public LiteralTextEscaper<? extends PsiLanguageInjectionHost> createLiteralTextEscaper() {
065            return new KotlinStringLiteralTextEscaper(this);
066        }
067    }