Skip to content
Marek Fišera edited this page Mar 23, 2015 · 4 revisions

Compilers are abstractions for simple configuration and execution of compiler inside application. They are used by components for generating and compiling source code into .dll and also by SharpKit C# to JavaScript compiler.

CompilerFactory

Entry point for compilers is class CompilerFactory. Creating instance of this class, you can configure references, temp directory and etc and create instances of I***Compiler for compiling code. Configuration from factory is copied to each instance of compiler created from it. So way, you can create base configuration, then create required compilers and for each of them complete its configuration.

Configuration is based on IKeyValueCollection and using extension methods there are provided constants for setting and reading values from it. Each configuration has default value and is completely optional.

// Create compiler and configure factory.
CompilerFactory factory = new CompilerFactory();
factory.References().AddDirectory("References");

// Create desired compiler from factory.
IDynamicCompiler compiler = factory.CreateDynamic();

// Prepare source code.
string sourceCode = "public class Test { public void Run() { System.Console.WriteLine(\"Hello, World!\"); } }";

// Execute compilation.
Assembly assembly;
ICompilerResult result = compiler.FromSourceCode(sourceCode, out assembly);

// Process result.
if (result.IsSuccess)
{
    //TODO: Load type, create instance, execute method.
} 
else 
{
    //TODO: Print errors.
}

IStaticCompiler & IDynamicCompiler

Two compilers shipped with the library are IStaticCompiler and IDynamicCompiler. Both supports compilation from file, from CodeCompileUnit and from source code in variable. The difference is that IStaticCompiler creates assembly on the harddrive, whereas IDynamicCompiler creates in-memory asssembly that is returned.

These two compilers supports these configurations:

  • References of type CompilerReferenceCollection for linking references.
  • IsDebugMode of type string for generating .pdb file and in case of IStaticCompiler for saving/exporting source code file (when compiled from string or CodeCompileUnit - this file is stored in the same directory with same file name as outputed assembly, but with .cs extension).

ISharpKitCompiler (from assembly Neptuo.Compilers.SharpKit)

This compiler enables generating JavaScript from C# code. It requires installation of SharpKit compiler in the .Net framework directory and supports two more configurations:

  • Plugins of type SharpKitPluginCollection to add plugins executed during JavaScript compiler execution.
  • TempDirectory of type string to store temp files.

Result of executing this compiler is translated C# code into JavaScript.

Clone this wiki locally