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.parsing; 018 019 import com.intellij.lang.ASTNode; 020 import com.intellij.lang.PsiBuilder; 021 import com.intellij.lang.PsiParser; 022 import com.intellij.openapi.project.Project; 023 import com.intellij.psi.PsiFile; 024 import com.intellij.psi.tree.IElementType; 025 import org.jetbrains.annotations.NotNull; 026 import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider; 027 028 public class KotlinParser implements PsiParser { 029 030 private final KotlinScriptDefinitionProvider scriptDefinitionProvider; 031 032 public KotlinParser(Project project) { 033 scriptDefinitionProvider = KotlinScriptDefinitionProvider.getInstance(project); 034 } 035 036 @Override 037 @NotNull 038 public ASTNode parse(IElementType iElementType, PsiBuilder psiBuilder) { 039 throw new IllegalStateException("use another parse"); 040 } 041 042 // we need this method because we need psiFile 043 @NotNull 044 public ASTNode parse(IElementType iElementType, PsiBuilder psiBuilder, PsiFile psiFile) { 045 KotlinParsing jetParsing = KotlinParsing.createForTopLevel(new SemanticWhitespaceAwarePsiBuilderImpl(psiBuilder)); 046 if (scriptDefinitionProvider != null && scriptDefinitionProvider.isScript(psiFile) 047 || psiFile.getName().endsWith(KotlinParserDefinition.STD_SCRIPT_EXT)) { 048 jetParsing.parseScript(); 049 } 050 else { 051 jetParsing.parseFile(); 052 } 053 return psiBuilder.getTreeBuilt(); 054 } 055 056 @NotNull 057 public static ASTNode parseTypeCodeFragment(PsiBuilder psiBuilder) { 058 KotlinParsing jetParsing = KotlinParsing.createForTopLevel(new SemanticWhitespaceAwarePsiBuilderImpl(psiBuilder)); 059 jetParsing.parseTypeCodeFragment(); 060 return psiBuilder.getTreeBuilt(); 061 } 062 063 @NotNull 064 public static ASTNode parseExpressionCodeFragment(PsiBuilder psiBuilder) { 065 KotlinParsing jetParsing = KotlinParsing.createForTopLevel(new SemanticWhitespaceAwarePsiBuilderImpl(psiBuilder)); 066 jetParsing.parseExpressionCodeFragment(); 067 return psiBuilder.getTreeBuilt(); 068 } 069 070 @NotNull 071 public static ASTNode parseBlockCodeFragment(PsiBuilder psiBuilder) { 072 KotlinParsing jetParsing = KotlinParsing.createForTopLevel(new SemanticWhitespaceAwarePsiBuilderImpl(psiBuilder)); 073 jetParsing.parseBlockCodeFragment(); 074 return psiBuilder.getTreeBuilt(); 075 } 076 }