Extract reusable functionality from K2JVMCompiler, K2JVMCompilerArguments, CompilerEnvironmentConfiguration.

This commit is contained in:
pTalanov
2012-04-26 13:43:04 +04:00
parent 98bd8bc90a
commit cdfa0678cf
13 changed files with 323 additions and 151 deletions
@@ -0,0 +1,49 @@
/*
* Copyright 2010-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.cli.common;
import com.sampullara.cli.Args;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments;
import java.io.PrintStream;
/**
* @author Pavel Talanov
*/
public final class ArgsUtil {
private ArgsUtil() {
}
public static void printUsage(@NotNull PrintStream target, @NotNull CompilerArguments exampleInstance) {
// We should say something like
// Args.usage(target, K2JVMCompilerArguments.class);
// but currently cli-parser we are using does not support that
// a corresponding patch has been sent to the authors
// For now, we are using this:
PrintStream oldErr = System.err;
System.setErr(target);
try {
// TODO: use proper argv0
Args.usage(exampleInstance);
}
finally {
System.setErr(oldErr);
}
}
}
@@ -0,0 +1,81 @@
/*
* Copyright 2010-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.cli.common;
import com.sampullara.cli.Args;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.cli.common.messages.MessageRenderer;
import java.io.PrintStream;
import java.util.List;
import static org.jetbrains.jet.cli.common.ExitCode.INTERNAL_ERROR;
/**
* @author Pavel Talanov
*/
public abstract class CLICompiler<CLArgs extends CompilerArguments, CEConf extends CompileEnvironmentConfig> {
@NotNull
public ExitCode exec(@NotNull PrintStream errStream, @NotNull String... args) {
CLArgs arguments = createArguments();
if (!parseArguments(errStream, arguments, args)) {
return INTERNAL_ERROR;
}
return exec(errStream, arguments);
}
/**
* Returns true if the arguments can be parsed correctly
*/
protected boolean parseArguments(@NotNull PrintStream errStream, @NotNull CLArgs arguments, @NotNull String[] args) {
try {
Args.parse(arguments, args);
return true;
}
catch (IllegalArgumentException e) {
usage(errStream);
}
catch (Throwable t) {
// Always use tags
errStream.println(MessageRenderer.TAGS.renderException(t));
}
return false;
}
/**
* Allow derived classes to add additional command line arguments
*/
protected void usage(@NotNull PrintStream target) {
ArgsUtil.printUsage(target, createArguments());
}
/**
* Strategy method to configure the environment, allowing compiler
* based tools to customise their own plugins
*/
protected void configureEnvironment(@NotNull CEConf configuration, @NotNull CLArgs arguments) {
List<CompilerPlugin> plugins = arguments.getCompilerPlugins();
configuration.getCompilerPlugins().addAll(plugins);
}
@NotNull
protected abstract CLArgs createArguments();
@NotNull
public abstract ExitCode exec(final PrintStream errStream, CLArgs arguments);
}
@@ -0,0 +1,54 @@
/*
* Copyright 2010-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.cli.common;
import com.google.common.collect.Lists;
import com.intellij.openapi.util.Disposer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.cli.common.messages.MessageCollector;
import java.util.List;
/**
* @author Pavel Talanov
*/
public abstract class CompileEnvironmentConfig {
@NotNull
private final MessageCollector messageCollector;
@NotNull
private List<CompilerPlugin> compilerPlugins = Lists.newArrayList();
/**
* NOTE: It's very important to call dispose for every object of this class or there will be memory leaks.
*
* @see Disposer
*/
public CompileEnvironmentConfig(@NotNull MessageCollector messageCollector) {
this.messageCollector = messageCollector;
}
@NotNull
public MessageCollector getMessageCollector() {
return messageCollector;
}
@NotNull
public List<CompilerPlugin> getCompilerPlugins() {
return compilerPlugins;
}
}
@@ -0,0 +1,43 @@
/*
* Copyright 2010-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.cli.common;
import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* @author Pavel Talanov
*/
public abstract class CompilerArguments {
@NotNull
private List<CompilerPlugin> compilerPlugins = Lists.newArrayList();
@NotNull
public List<CompilerPlugin> getCompilerPlugins() {
return compilerPlugins;
}
/**
* Sets the compiler plugins to be used when working with the {@link org.jetbrains.jet.cli.CLICompiler}
*/
public void setCompilerPlugins(@NotNull List<CompilerPlugin> compilerPlugins) {
this.compilerPlugins = compilerPlugins;
}
}
@@ -16,10 +16,12 @@
package org.jetbrains.jet.cli.common;
import org.jetbrains.annotations.NotNull;
/**
* A simple interface for compiler plugins to run after the compiler has finished such as for things like
* generating documentation or code generation etc
*/
public interface CompilerPlugin {
void processFiles(CompilerPluginContext context);
void processFiles(@NotNull CompilerPluginContext context);
}
@@ -17,6 +17,7 @@
package org.jetbrains.jet.cli.common;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.resolve.BindingContext;
@@ -27,8 +28,12 @@ import java.util.List;
* the {@link Project}, the {@link BindingContext} and the underlying {@link JetFile} files.
*/
public class CompilerPluginContext {
@NotNull
private final Project project;
//TODO: should we in fact store AnalyzeExhaust here?
@NotNull
private final BindingContext context;
@NotNull
private final List<JetFile> files;
public CompilerPluginContext(Project project, BindingContext context, List<JetFile> files) {
@@ -37,14 +42,17 @@ public class CompilerPluginContext {
this.files = files;
}
@NotNull
public BindingContext getContext() {
return context;
}
@NotNull
public List<JetFile> getFiles() {
return files;
}
@NotNull
public Project getProject() {
return project;
}
@@ -20,15 +20,13 @@ import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.sampullara.cli.Args;
import jet.modules.Module;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.cli.common.CompilerPlugin;
import org.jetbrains.jet.cli.common.CLICompiler;
import org.jetbrains.jet.cli.common.ExitCode;
import org.jetbrains.jet.cli.common.messages.PrintingMessageCollector;
import org.jetbrains.jet.codegen.CompilationException;
import org.jetbrains.jet.cli.jvm.compiler.*;
import org.jetbrains.jet.cli.common.messages.*;
import org.jetbrains.jet.cli.jvm.compiler.*;
import org.jetbrains.jet.codegen.CompilationException;
import org.jetbrains.jet.lang.resolve.java.CompilerDependencies;
import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode;
import org.jetbrains.jet.utils.PathUtil;
@@ -44,7 +42,7 @@ import static org.jetbrains.jet.cli.common.ExitCode.*;
* @author alex.tkachman
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class K2JVMCompiler {
public class K2JVMCompiler extends CLICompiler<K2JVMCompilerArguments, CompileEnvironmentConfiguration> {
public static void main(String... args) {
doMain(new K2JVMCompiler(), args);
@@ -67,17 +65,12 @@ public class K2JVMCompiler {
}
}
public ExitCode exec(PrintStream errStream, String... args) {
K2JVMCompilerArguments arguments = createArguments();
if (!parseArguments(errStream, arguments, args)) {
return INTERNAL_ERROR;
}
return exec(errStream, arguments);
}
/**
* Executes the compiler on the parsed arguments
*/
@NotNull
@Override
public ExitCode exec(final PrintStream errStream, K2JVMCompilerArguments arguments) {
if (arguments.help) {
usage(errStream);
@@ -91,7 +84,9 @@ public class K2JVMCompiler {
try {
if (arguments.version) {
errStream.println(messageRenderer.render(CompilerMessageSeverity.INFO, "Kotlin Compiler version " + K2JVMCompilerVersion.VERSION, CompilerMessageLocation.NO_LOCATION));
errStream.println(messageRenderer
.render(CompilerMessageSeverity.INFO, "Kotlin Compiler version " + K2JVMCompilerVersion.VERSION,
CompilerMessageLocation.NO_LOCATION));
}
CompilerSpecialMode mode = parseCompilerSpecialMode(arguments);
@@ -127,7 +122,8 @@ public class K2JVMCompiler {
Disposable rootDisposable = CompileEnvironmentUtil.createMockDisposable();
JetCoreEnvironment environment = new JetCoreEnvironment(rootDisposable, dependencies);
CompileEnvironmentConfiguration configuration = new CompileEnvironmentConfiguration(environment, dependencies, messageCollector);
CompileEnvironmentConfiguration configuration =
new CompileEnvironmentConfiguration(environment, dependencies, messageCollector);
messageCollector.report(CompilerMessageSeverity.LOGGING, "Configuring the compilation environment",
CompilerMessageLocation.NO_LOCATION);
@@ -136,7 +132,8 @@ public class K2JVMCompiler {
boolean noErrors;
if (arguments.module != null) {
List<Module> modules = CompileEnvironmentUtil.loadModuleScript(arguments.module, new PrintingMessageCollector(errStream, messageRenderer, false));
List<Module> modules = CompileEnvironmentUtil
.loadModuleScript(arguments.module, new PrintingMessageCollector(errStream, messageRenderer, false));
File directory = new File(arguments.module).getParentFile();
noErrors = KotlinToJVMBytecodeCompiler.compileModules(configuration, modules,
directory, arguments.jar, arguments.outputDir,
@@ -146,11 +143,14 @@ public class K2JVMCompiler {
// TODO ideally we'd unify to just having a single field that supports multiple files/dirs
if (arguments.getSourceDirs() != null) {
noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSourceDirectories(configuration,
arguments.getSourceDirs(), arguments.jar, arguments.outputDir, arguments.includeRuntime);
arguments.getSourceDirs(), arguments.jar,
arguments.outputDir,
arguments.includeRuntime);
}
else {
noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSources(configuration,
arguments.src, arguments.jar, arguments.outputDir, arguments.includeRuntime);
arguments.src, arguments.jar, arguments.outputDir,
arguments.includeRuntime);
}
}
return noErrors ? OK : COMPILATION_ERROR;
@@ -161,7 +161,8 @@ public class K2JVMCompiler {
return INTERNAL_ERROR;
}
catch (Throwable t) {
messageCollector.report(CompilerMessageSeverity.EXCEPTION, MessageRenderer.PLAIN.renderException(t), CompilerMessageLocation.NO_LOCATION);
messageCollector.report(CompilerMessageSeverity.EXCEPTION, MessageRenderer.PLAIN.renderException(t),
CompilerMessageLocation.NO_LOCATION);
return INTERNAL_ERROR;
}
finally {
@@ -170,12 +171,12 @@ public class K2JVMCompiler {
}
}
finally {
errStream.print(messageRenderer.renderConclusion());
errStream.print(messageRenderer.renderConclusion());
}
}
@NotNull
private CompilerSpecialMode parseCompilerSpecialMode(@NotNull K2JVMCompilerArguments arguments) {
private static CompilerSpecialMode parseCompilerSpecialMode(@NotNull K2JVMCompilerArguments arguments) {
if (arguments.mode == null) {
return CompilerSpecialMode.REGULAR;
}
@@ -190,58 +191,21 @@ public class K2JVMCompiler {
throw new IllegalArgumentException("unknown compiler mode: " + arguments.mode);
}
/**
* Returns true if the arguments can be parsed correctly
*/
protected boolean parseArguments(PrintStream errStream, K2JVMCompilerArguments arguments, String[] args) {
try {
Args.parse(arguments, args);
return true;
}
catch (IllegalArgumentException e) {
usage(errStream);
}
catch (Throwable t) {
// Always use tags
errStream.println(MessageRenderer.TAGS.renderException(t));
}
return false;
}
protected void usage(PrintStream target) {
// We should say something like
// Args.usage(target, K2JVMCompilerArguments.class);
// but currently cli-parser we are using does not support that
// a corresponding patch has been sent to the authors
// For now, we are using this:
PrintStream oldErr = System.err;
System.setErr(target);
try {
// TODO: use proper argv0
Args.usage(new K2JVMCompilerArguments());
} finally {
System.setErr(oldErr);
}
}
/**
* Allow derived classes to add additional command line arguments
*/
@NotNull
@Override
protected K2JVMCompilerArguments createArguments() {
return new K2JVMCompilerArguments();
}
/**
* Strategy method to configure the environment, allowing compiler
* based tools to customise their own plugins
*/
protected void configureEnvironment(CompileEnvironmentConfiguration configuration, K2JVMCompilerArguments arguments) {
// install any compiler plugins
List<CompilerPlugin> plugins = arguments.getCompilerPlugins();
if (plugins != null) {
configuration.getCompilerPlugins().addAll(plugins);
}
@Override
protected void configureEnvironment(@NotNull CompileEnvironmentConfiguration configuration,
@NotNull K2JVMCompilerArguments arguments) {
super.configureEnvironment(configuration, arguments);
if (configuration.getCompilerDependencies().getRuntimeJar() != null) {
CompileEnvironmentUtil.addToClasspath(configuration.getEnvironment(), configuration.getCompilerDependencies().getRuntimeJar());
@@ -18,16 +18,15 @@
package org.jetbrains.jet.cli.jvm;
import com.sampullara.cli.Argument;
import org.jetbrains.jet.cli.common.CompilerPlugin;
import org.jetbrains.jet.cli.common.CompilerArguments;
import java.util.ArrayList;
import java.util.List;
/**
* Command line arguments for the {@link K2JVMCompiler}
*/
public class K2JVMCompilerArguments {
private List<CompilerPlugin> compilerPlugins = new ArrayList<CompilerPlugin>();
public class K2JVMCompilerArguments extends CompilerArguments {
// TODO ideally we'd unify this with 'src' to just having a single field that supports multiple files/dirs
private List<String> sourceDirs;
@@ -151,15 +150,4 @@ public class K2JVMCompilerArguments {
public void setTags(boolean tags) {
this.tags = tags;
}
public List<CompilerPlugin> getCompilerPlugins() {
return compilerPlugins;
}
/**
* Sets the compiler plugins to be used when working with the {@link K2JVMCompiler}
*/
public void setCompilerPlugins(List<CompilerPlugin> compilerPlugins) {
this.compilerPlugins = compilerPlugins;
}
}
@@ -16,32 +16,28 @@
package org.jetbrains.jet.cli.jvm.compiler;
import com.google.common.collect.Lists;
import com.intellij.openapi.util.Disposer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.cli.common.CompilerPlugin;
import org.jetbrains.jet.cli.common.CompileEnvironmentConfig;
import org.jetbrains.jet.cli.common.messages.MessageCollector;
import org.jetbrains.jet.lang.resolve.java.CompilerDependencies;
import java.util.List;
/**
* @author abreslav
*/
public class CompileEnvironmentConfiguration {
public class CompileEnvironmentConfiguration extends CompileEnvironmentConfig {
private final JetCoreEnvironment environment;
private final CompilerDependencies compilerDependencies;
private final MessageCollector messageCollector;
private List<CompilerPlugin> compilerPlugins = Lists.newArrayList();
/**
* NOTE: It's very important to call dispose for every object of this class or there will be memory leaks.
*
* @see Disposer
*/
public CompileEnvironmentConfiguration(@NotNull JetCoreEnvironment environment,
@NotNull CompilerDependencies compilerDependencies, @NotNull MessageCollector messageCollector) {
this.messageCollector = messageCollector;
@NotNull CompilerDependencies compilerDependencies,
@NotNull MessageCollector messageCollector) {
super(messageCollector);
this.compilerDependencies = compilerDependencies;
this.environment = environment;
}
@@ -54,13 +50,4 @@ public class CompileEnvironmentConfiguration {
public CompilerDependencies getCompilerDependencies() {
return compilerDependencies;
}
@NotNull
public MessageCollector getMessageCollector() {
return messageCollector;
}
public List<CompilerPlugin> getCompilerPlugins() {
return compilerPlugins;
}
}
@@ -20,7 +20,7 @@ fun main(args: Array<String?>): Unit {
*/
class KDocCompiler() : K2JVMCompiler() {
protected override fun configureEnvironment(configuration : CompileEnvironmentConfiguration?, arguments : K2JVMCompilerArguments?) {
protected override fun configureEnvironment(configuration : CompileEnvironmentConfiguration, arguments : K2JVMCompilerArguments) {
super.configureEnvironment(configuration, arguments)
val coreEnvironment = configuration?.getEnvironment()
if (coreEnvironment != null) {
@@ -38,11 +38,11 @@ class KDocCompiler() : K2JVMCompiler() {
}
}
protected override fun createArguments() : K2JVMCompilerArguments? {
protected override fun createArguments() : K2JVMCompilerArguments {
return KDocArguments()
}
protected override fun usage(target : PrintStream?) {
protected override fun usage(target : PrintStream) {
target?.println("Usage: KDocCompiler -docOutput <docOutputDir> [-output <outputDir>|-jar <jarFileName>] [-stdlib <path to runtime.jar>] [-src <filename or dirname>|-module <module file>] [-includeRuntime]");
}
}
@@ -7,20 +7,18 @@ import org.jetbrains.jet.cli.common.CompilerPluginContext
*/
class HtmlCompilerPlugin: CompilerPlugin {
public override fun processFiles(context: CompilerPluginContext?) {
if (context != null) {
val bindingContext = context.getContext()
val files = context.getFiles()
if (bindingContext != null && files != null) {
if (files != null && bindingContext != null) {
for (file in files) {
if (file != null) {
val visitor = HtmlKotlinVisitor()
file.accept(visitor)
}
}
}
}
}
public override fun processFiles(context: CompilerPluginContext) {
val bindingContext = context.getContext()
val files = context.getFiles()
if (bindingContext != null && files != null) {
if (files != null && bindingContext != null) {
for (file in files) {
if (file != null) {
val visitor = HtmlKotlinVisitor()
file.accept(visitor)
}
}
}
}
}
}
@@ -10,16 +10,14 @@ abstract class KModelCompilerPlugin: CompilerPlugin {
public open var config: KDocConfig = KDocConfig()
public override fun processFiles(context: CompilerPluginContext?) {
if (context != null) {
val bindingContext = context.getContext()
val sources = context.getFiles()
if (bindingContext != null && sources != null) {
val model = KModel(bindingContext, config)
model.load(sources)
public override fun processFiles(context: CompilerPluginContext) {
val bindingContext = context.getContext()
val sources = context.getFiles()
if (bindingContext != null && sources != null) {
val model = KModel(bindingContext, config)
model.load(sources)
processModel(model)
}
processModel(model)
}
}
@@ -28,6 +28,7 @@ import org.jetbrains.k2js.facade.K2JSTranslator;
import java.io.File;
import java.io.IOException;
import java.lang.Override;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@@ -38,32 +39,31 @@ import java.util.List;
public class K2JSCompilerPlugin implements CompilerPlugin {
private String outFile = "target/js/program.js";
public void processFiles(CompilerPluginContext context) {
if (context != null) {
Project project = context.getProject();
BindingContext bindingContext = context.getContext();
List<JetFile> sources = context.getFiles();
@Override
public void processFiles(@NotNull CompilerPluginContext context) {
Project project = context.getProject();
BindingContext bindingContext = context.getContext();
List<JetFile> sources = context.getFiles();
if (bindingContext != null && sources != null && project != null) {
Config config = new Config(project) {
@NotNull
@Override
protected List<JetFile> generateLibFiles() {
return new ArrayList<JetFile>();
}
};
K2JSTranslator translator = new K2JSTranslator(config);
final String code = translator.generateProgramCode(sources);
File file = new File(outFile);
try {
Files.createParentDirs(file);
Files.write(code, file, Charset.forName("UTF-8"));
} catch (IOException e) {
throw new RuntimeException(e);
if (bindingContext != null && sources != null && project != null) {
Config config = new Config(project) {
@NotNull
@Override
protected List<JetFile> generateLibFiles() {
return new ArrayList<JetFile>();
}
};
K2JSTranslator translator = new K2JSTranslator(config);
final String code = translator.generateProgramCode(sources);
File file = new File(outFile);
try {
Files.createParentDirs(file);
Files.write(code, file, Charset.forName("UTF-8"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}