001/*
002 * Copyright 2010-2013 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
017package org.jetbrains.jet.lang.parsing;
018
019import com.intellij.openapi.components.ServiceManager;
020import com.intellij.openapi.project.Project;
021import com.intellij.psi.PsiFile;
022import org.jetbrains.annotations.NotNull;
023import org.jetbrains.jet.lang.psi.JetFile;
024import org.jetbrains.jet.lang.resolve.AnalyzerScriptParameter;
025
026import java.util.*;
027
028public class JetScriptDefinitionProvider {
029    private final HashMap<String,JetScriptDefinition> scripts = new HashMap<String, JetScriptDefinition>();
030    private final HashSet<PsiFile> scriptsFiles = new HashSet<PsiFile>();
031
032    private static final JetScriptDefinition standardScript = new JetScriptDefinition(".ktscript", Collections.<AnalyzerScriptParameter>emptyList());
033
034    public JetScriptDefinitionProvider() {
035        // .ktscript will take analyzer parameters explicitly specified on compilation
036        addScriptDefinition(standardScript);
037    }
038
039    public void markFileAsScript(JetFile file) {
040        scriptsFiles.add(file);
041    }
042
043    public static JetScriptDefinitionProvider getInstance(Project project) {
044        return ServiceManager.getService(project, JetScriptDefinitionProvider.class);
045    }
046
047    public JetScriptDefinition findScriptDefinition(PsiFile psiFile) {
048        boolean force = scriptsFiles.contains(psiFile);
049
050        String name = psiFile.getName();
051        for (Map.Entry<String, JetScriptDefinition> e : scripts.entrySet()) {
052            if (name.endsWith(e.getKey())) {
053                return e.getValue();
054            }
055        }
056        if(force)
057            return standardScript;
058
059        return null;
060    }
061
062    public boolean isScript(PsiFile psiFile) {
063        return findScriptDefinition(psiFile) != null;
064    }
065
066    public void addScriptDefinition(@NotNull JetScriptDefinition scriptDefinition) {
067        scripts.put(scriptDefinition.getExtension(), scriptDefinition);
068    }
069
070    public void addScriptDefinitions(List<JetScriptDefinition> definitions) {
071        for (JetScriptDefinition definition : definitions) {
072            addScriptDefinition(definition);
073        }
074    }
075}