Run() public method

public Run ( ) : CompilerContext
return CompilerContext
        public void Run(string text)
        {
            BooCompiler compiler = new BooCompiler();
            compiler.Parameters.Ducky = true;
            compiler.Parameters.Pipeline = new CompileToMemory();
            compiler.Parameters.Input.Add(new StringInput("Script", text));

            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                compiler.Parameters.References.Add(assembly);
            }

            CompilerContext context = compiler.Run();

            if (context.GeneratedAssembly == null)
            {
                if (context.Errors.Count > 0)
                {
                    errors = context.Errors.ToString(true);
                }
                return;
            }

            try
            {
                Type[] types = context.GeneratedAssembly.GetTypes();
                Type scriptModule = types[types.Length - 1];
                MethodInfo mainEntry = scriptModule.Assembly.EntryPoint;
                mainEntry.Invoke(null, new object[mainEntry.GetParameters().Length]);
            }
            catch (Exception ex)
            {
                errors = ex.Message;
            }
        }
 protected override Type CompileMigration(MigrationReference migrationReference)
 {
   BooCompiler compiler = new BooCompiler();
   compiler.Parameters.Input.Add(new FileInput(migrationReference.Path));
   compiler.Parameters.References.Add(typeof(IDatabaseMigration).Assembly);
   foreach (string reference in _configuration.References)
   {
     _log.Debug("Referencing: " + reference);
     compiler.Parameters.References.Add(Assembly.LoadFrom(reference));
   }
   compiler.Parameters.OutputType = CompilerOutputType.Library;
   compiler.Parameters.GenerateInMemory = true;
   compiler.Parameters.OutputAssembly = Path.Combine(_workingDirectoryManager.WorkingDirectory, Path.GetFileNameWithoutExtension(migrationReference.Path) + ".dll");
   compiler.Parameters.Ducky = true;
   compiler.Parameters.Pipeline = new CompileToFile();
   CompilerContext cc = compiler.Run();
   if (cc.Errors.Count > 0)
   {
     foreach (CompilerError error in cc.Errors)
     {
       _log.ErrorFormat("{0}", error);
     }
     throw new InvalidOperationException();
   }
   if (cc.GeneratedAssembly == null)
   {
     throw new InvalidOperationException();
   }
   return MigrationHelpers.LookupMigration(cc.GeneratedAssembly, migrationReference);
 }
Esempio n. 3
0
		public override Assembly Compile(string path, string outPath, bool cache)
		{
			Assembly asm = null;
			try
			{
				if (this.ExistsAndUpToDate(path, outPath) && cache)
					return Assembly.LoadFrom(outPath);

				// Precompile script to a temp file
				var precompiled = this.PreCompile(File.ReadAllText(path));
				var tmp = Path.GetTempFileName();
				File.WriteAllText(tmp, precompiled);

				// Compile
				var compiler = new Boo.Lang.Compiler.BooCompiler();
				compiler.Parameters.AddAssembly(typeof(Log).Assembly);
				compiler.Parameters.AddAssembly(Assembly.GetEntryAssembly());
				compiler.Parameters.Input.Add(new FileInput(tmp));
				compiler.Parameters.OutputAssembly = outPath;
				compiler.Parameters.Pipeline = new CompileToFile();

#if DEBUG
				compiler.Parameters.Debug = true;
#else
				compiler.Parameters.Debug = false;
#endif

				var context = compiler.Run();
				if (context.GeneratedAssembly == null)
				{
					var errors = context.Errors;
					var newExs = new CompilerErrorsException();

					foreach (var err in errors)
					{
						var newEx = new CompilerError(path, err.LexicalInfo.Line, err.LexicalInfo.Column, err.Message, false);
						newExs.Errors.Add(newEx);
					}

					throw newExs;
				}

				asm = context.GeneratedAssembly;
			}
			catch (CompilerErrorsException)
			{
				throw;
			}
			catch (UnauthorizedAccessException)
			{
				// Thrown if file can't be copied. Happens if script was
				// initially loaded from cache.
			}
			catch (Exception ex)
			{
				Log.Exception(ex);
			}

			return asm;
		}
 public CompilerContext Compile(string name, string code, CompilerPipeline pipeline = null, Action<CompilerParameters> prepare = null) {
     if(null==pipeline) pipeline = new Parse();
     var compiler = new BooCompiler();
     compiler.Parameters.Pipeline = pipeline;
     compiler.Parameters.Input.Add(new ReaderInput(name, new StringReader(code)));
     if(prepare!=null) {
         prepare(compiler.Parameters);
     }
     return compiler.Run();
 }
Esempio n. 5
0
		private void RunCompilerStepAfterExpressionResolutionOn(CompileUnit compileUnit, ICompilerStep step)
		{
			var pipeline = new Boo.Lang.Compiler.Pipelines.ResolveExpressions { step };

			var compiler = new Boo.Lang.Compiler.BooCompiler(new CompilerParameters { Pipeline = pipeline });
			var result = compiler.Run(compileUnit);

			if (result.Errors.Count > 0)
				Assert.Fail(result.Errors.ToString(true));
		}
Esempio n. 6
0
        public override Assembly Compile(string path, string outPath)
        {
            Assembly asm = null;

            try
            {
                if (this.ExistsAndUpToDate(path, outPath))
                {
                    return(Assembly.LoadFrom(outPath));
                }

                var compiler = new Boo.Lang.Compiler.BooCompiler();
                compiler.Parameters.AddAssembly(typeof(Log).Assembly);
                compiler.Parameters.AddAssembly(typeof(ScriptManager).Assembly);
                compiler.Parameters.Input.Add(new FileInput(path));
                compiler.Parameters.OutputAssembly = outPath;
                compiler.Parameters.Pipeline       = new CompileToFile();

                var context = compiler.Run();
                if (context.GeneratedAssembly == null)
                {
                    var errors = context.Errors;
                    var newExs = new CompilerErrorsException();

                    foreach (var err in errors)
                    {
                        var newEx = new CompilerError(path, err.LexicalInfo.Line, err.LexicalInfo.Column, err.Message, false);
                        newExs.Errors.Add(newEx);
                    }

                    throw newExs;
                }

                asm = context.GeneratedAssembly;

                //this.SaveAssembly(asm, outPath);
            }
            catch (CompilerErrorsException)
            {
                throw;
            }
            catch (UnauthorizedAccessException)
            {
                // Thrown if file can't be copied. Happens if script was
                // initially loaded from cache.
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }

            return(asm);
        }
Esempio n. 7
0
        public override Assembly Compile(string path, string outPath)
        {
            Assembly asm = null;
            try
            {
                if (this.ExistsAndUpToDate(path, outPath))
                    return Assembly.LoadFrom(outPath);

                var compiler = new Boo.Lang.Compiler.BooCompiler();
                compiler.Parameters.AddAssembly(typeof(Log).Assembly);
                compiler.Parameters.AddAssembly(typeof(ScriptManager).Assembly);
                compiler.Parameters.Input.Add(new FileInput(path));
                compiler.Parameters.OutputAssembly = outPath;
                compiler.Parameters.Pipeline = new CompileToFile();

                var context = compiler.Run();
                if (context.GeneratedAssembly == null)
                {
                    var errors = context.Errors;
                    var newExs = new CompilerErrorsException();

                    foreach (var err in errors)
                    {
                        var newEx = new CompilerError(path, err.LexicalInfo.Line, err.LexicalInfo.Column, err.Message, false);
                        newExs.Errors.Add(newEx);
                    }

                    throw newExs;
                }

                asm = context.GeneratedAssembly;

                //this.SaveAssembly(asm, outPath);
            }
            catch (CompilerErrorsException)
            {
                throw;
            }
            catch (UnauthorizedAccessException)
            {
                // Thrown if file can't be copied. Happens if script was
                // initially loaded from cache.
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }

            return asm;
        }
        protected Assembly Compile(string filename, CompilerOutputType compilerOutputType)
        {
            BooCompiler compiler = new BooCompiler();
            compiler.Parameters.OutputType = compilerOutputType;
            compiler.Parameters.GenerateInMemory = true;
            compiler.Parameters.Pipeline = new CompileToMemory();
            AddCompilerSteps(compiler, filename, compiler.Parameters.Pipeline);
            compiler.Parameters.Input.Add(new FileInput(filename));

            CompilerContext run = compiler.Run();
            if (run.Errors.Count > 0)
                throw new CompilerError(run.Errors.ToString(true));
            return run.GeneratedAssembly;
        }
Esempio n. 9
0
		public void MacroMacroCompilation()
		{
			CompilerParameters parameters = new CompilerParameters(false);
			parameters.References.Add(typeof(IEnumerable<>).Assembly);
			
			parameters.Input.Add(BooLangExtensionsSource("Macros/MacroMacro.boo"));
			parameters.Input.Add(BooLangExtensionsSource("Macros/AssertMacro.boo"));

			parameters.Pipeline = new Boo.Lang.Compiler.Pipelines.ResolveExpressions();

			Boo.Lang.Compiler.BooCompiler compiler = new Boo.Lang.Compiler.BooCompiler(parameters);
			CompilerContext results = compiler.Run();
			Assert.AreEqual(0, results.Errors.Count, results.Errors.ToString());
		}
Esempio n. 10
0
        public int Run(string[] args)
        {
            int resultCode = 127;

            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;

            CheckBooCompiler();

            var parameters = new CompilerParameters(false);
            try
            {
                var setupTime = Stopwatch.StartNew();

                CommandLineParser.ParseInto(parameters, args);

                if (0 == parameters.Input.Count)
                    throw new ApplicationException(ResourceManager.GetString("BooC.NoInputSpecified"));

                var compiler = new BooCompiler(parameters);
                setupTime.Stop();

                var processingTime = Stopwatch.StartNew();
                var context = compiler.Run();
                processingTime.Stop();

                if (context.Warnings.Count > 0)
                {
                    Console.Error.WriteLine(context.Warnings);
                    Console.Error.WriteLine(Boo.Lang.ResourceManager.Format("BooC.Warnings", context.Warnings.Count));
                }

                if (context.Errors.Count == 0)
                    resultCode = 0;
                else
                {
                    foreach (CompilerError error in context.Errors)
                        Console.Error.WriteLine(error.ToString(parameters.TraceInfo));
                    Console.Error.WriteLine(ResourceManager.Format("BooC.Errors", context.Errors.Count));
                }

                if (parameters.TraceWarning)
                    Console.Error.WriteLine(ResourceManager.Format("BooC.ProcessingTime", parameters.Input.Count, processingTime.ElapsedMilliseconds, setupTime.ElapsedMilliseconds));
            }
            catch (Exception x)
            {
                var message = (parameters.TraceWarning) ? (object)x : (object)x.Message;
                Console.Error.WriteLine(ResourceManager.Format("BooC.FatalError", message));
            }
            return resultCode;
        }
Esempio n. 11
0
		public static Assembly CompileString(string code)
		{
			var compiler = new BooCompiler(new CompilerParameters(false));
			
			compiler.Parameters.GenerateInMemory = true;
			compiler.Parameters.Pipeline = new NihPipeline();
			compiler.Parameters.Input.Add(new StringInput("string.nih", code));

			var result = compiler.Run();
			if (result.Errors.Count > 0)
				throw new CompilationErrorsException(result.Errors);
			
			return result.GeneratedAssembly;
		}
Esempio n. 12
0
        public void EnvironmentBindingsCanBeCustomizedThroughCompilerParametersEnvironment()
        {
            EntityFormatter actualFormatter   = null;
            var             expectedFormatter = new EntityFormatter();

            var compiler = new Boo.Lang.Compiler.BooCompiler();

            compiler.Parameters.Pipeline = new CompilerPipeline {
                new ActionStep(() => actualFormatter = My <EntityFormatter> .Instance)
            };
            compiler.Parameters.Environment = new ClosedEnvironment(expectedFormatter);
            compiler.Run();

            Assert.AreSame(expectedFormatter, actualFormatter);
        }
        public void TransformerIsAppliedToCompileUnit()
        {
            StubTransformer transformer = new StubTransformer();

            TransformerCompilerStep transformerStep = new TransformerCompilerStep(transformer);

            CompileUnit unit = new CompileUnit();

            BooCompiler compiler = new BooCompiler();
            compiler.Parameters.Pipeline = new CompilerPipeline();
            compiler.Parameters.Pipeline.Insert(0, transformerStep);
            compiler.Run(unit);

            Assert.IsTrue(transformer.CompileUnitVisited);
        }
Esempio n. 14
0
        public void MacroMacroCompilation()
        {
            CompilerParameters parameters = new CompilerParameters(false);

            parameters.References.Add(typeof(IEnumerable <>).Assembly);

            parameters.Input.Add(BooLangExtensionsSource("Macros/MacroMacro.boo"));
            parameters.Input.Add(BooLangExtensionsSource("Macros/AssertMacro.boo"));

            parameters.Pipeline = new Boo.Lang.Compiler.Pipelines.ResolveExpressions();

            Boo.Lang.Compiler.BooCompiler compiler = new Boo.Lang.Compiler.BooCompiler(parameters);
            CompilerContext results = compiler.Run();

            Assert.AreEqual(0, results.Errors.Count, results.Errors.ToString());
        }
        public BooExpression(string expression)
        {
            var script = string.Format(Scripts.Boo, expression);

            var booC = new BooCompiler();
            booC.Parameters.Input.Add(new StringInput("test", script));
            booC.Parameters.Pipeline = new CompileToMemory();
            var compiler = booC.Run();
            if (compiler.Errors.Count > 0)
                throw compiler.Errors[0];

            var invoker = MethodCache.Do.GetInvoker(
                compiler.GeneratedAssembly.GetType("TestModule").GetMethod("evaluate"));

            evaluator = x => (bool)(invoker(null, new ValueBagFu(x)) ?? false);
        }
Esempio n. 16
0
        private void RunCompilerStepAfterExpressionResolutionOn(CompileUnit compileUnit, ICompilerStep step)
        {
            var pipeline = new Boo.Lang.Compiler.Pipelines.ResolveExpressions {
                step
            };

            var compiler = new Boo.Lang.Compiler.BooCompiler(new CompilerParameters {
                Pipeline = pipeline
            });
            var result = compiler.Run(compileUnit);

            if (result.Errors.Count > 0)
            {
                Assert.Fail(result.Errors.ToString(true));
            }
        }
Esempio n. 17
0
        // practically the same as ForceCompile, but without saving to disk
        CompilerContext IIncludeCompiler.CompileInclude(string url)
        {
            if (!InIncludeMode)
                throw new InvalidOperationException("Cannot CompileInclude when not in include mode.");

            var compiler = new BooCompiler {
                                           	Parameters = {OutputType = CompilerOutputType, GenerateInMemory = true, Pipeline = new Parse()}
                                           };
            CustomizeCompiler(compiler, compiler.Parameters.Pipeline, new[] {url});
            AddInput(compiler, url);
            var compilerContext = compiler.Run();
            if (compilerContext.Errors.Count != 0) {
                throw CreateCompilerException(compilerContext);
            }
            HandleWarnings(compilerContext.Warnings);
            return compilerContext;
        }
Esempio n. 18
0
		/// <summary>
		/// Loads this instance.
		/// </summary>
		public override void LoadOrExecute()
		{
			var compiler = new BooCompiler();

			foreach (Assembly assembly in References) {
				compiler.Parameters.AddAssembly(assembly);
			}

			string outputDir = CompilerOutput;

			if (!string.IsNullOrEmpty(outputDir))
				outputDir = System.IO.Path.GetFullPath(outputDir);
			else
				outputDir = System.IO.Path.GetDirectoryName(Filename);

			string outputAssembly = System.IO.Path.Combine(
				outputDir,
				AssemblyPrefix + System.IO.Path.GetFileNameWithoutExtension(Filename) + ".dll");

			if (File.Exists(outputAssembly) &&
			    File.GetLastWriteTime(outputAssembly) > File.GetLastWriteTime(Filename)) {
				GeneratedAssembly = Assembly.LoadFrom(outputAssembly);
				InvokeEntryPoint();
				return;
			}

			compiler.Parameters.Input.Add(new FileInput(Filename));
			//compiler.Parameters.Pipeline = new CompileToMemory();
			compiler.Parameters.Pipeline = new CompileToFile();
#if DEBUG
			compiler.Parameters.Debug = true;
#else
			compiler.Parameters.Debug = false;
#endif
			compiler.Parameters.OutputAssembly = outputAssembly;
			compiler.Parameters.OutputType = CompilerOutputType.ConsoleApplication;
			compiler.Parameters.Ducky = false;

			_context = compiler.Run();
			GeneratedAssembly = _context.GeneratedAssembly;

			if (GeneratedAssembly == null)
				ThrowError(Filename, _context);

			InvokeEntryPoint();
		}
 public Assembly Compile(ExtensionsFileSystemProvider provider) {
     var compiler = new BooCompiler();
     var pipeline = Pipeline ??( Pipeline = new CompileToFile());
     ExtensionsPreprocessorCompilerStep.Extend(pipeline);
     compiler.Parameters.Pipeline = pipeline;
     var files = provider.GetFileNames();
     if(files.Length==0) {
         WriteLog("no input files provided");
     }
     foreach (var fileName in files) {
         WriteLog("input added: " + fileName);
         compiler.Parameters.Input.Add(new FileInput(fileName));
     }
     compiler.Parameters.References.Add(typeof (IRegistryLoader).Assembly); //need to use Comdiv.Core
     compiler.Parameters.References.Add(typeof (IDictionary<string, object>).Assembly); //need to use System
     WriteLog("compiler created");
     //loading other dlls:
     foreach (var referencedAssembly in provider.GetReferencedAssemblies()) {
         WriteLog("add assembly " + referencedAssembly.GetName().Name);
         compiler.Parameters.References.Add(referencedAssembly);
     }
     compiler.Parameters.OutputAssembly = provider.GetLibraryPath();
     WriteLog("output is setted : " + provider.GetLibraryPath());
     WriteLog("start compiler");
     var result = compiler.Run();
     LastCompiledContext = result;
     if (result.Errors.Count != 0) {
         WriteLog("error occured!");
         WriteLog(result.Errors.ToString());
         ConsoleLogHost.Current.logerror(result.Errors.ToString());
         throw new CompilerErrorException(result);
     }
     //if (result.Warnings.Count != 0)
     //{
     //    WriteLog("warrnings!");
     //    WriteLog(result.Warnings.ToString());
     //}
     WriteLog("compilation successfull");
     if(Pipeline is CompileToMemory) {
         return result.GeneratedAssembly;
     }else {
         return provider.LoadAssembly();
     }
 }
Esempio n. 20
0
        public CompilerErrorCollection Run(params string[] args){
            var referencedAssemblies = ExtractAssemblies();
            var pipeline = ExtractPipeline() ?? new CompileToFile();

            var parameters = new CompilerParameters(true);

            //parameters.Ducky = true;

            parameters.LibPaths.Add(Environment.CurrentDirectory);
            parameters.LibPaths.Add(Path.Combine(Environment.CurrentDirectory, "bin"));
            parameters.OutputAssembly = "script.dll";

            foreach (var assembly in referencedAssemblies){
                parameters.AddAssembly(assembly);
                parameters.References.Add(assembly);
            }
            parameters.Pipeline = pipeline;
            var compiler = new BooCompiler(parameters);
            parameters.Input.Add(new ReaderInput("script", new StringReader(BooScript)));
            var result = compiler.Run();

            if (result.Errors.yes()) return result.Errors;

            var resultAssembly = result.GeneratedAssembly;


            var global__ = resultAssembly.getTypesWithAttribute<GlobalsHandlingClassAttribute>();
            var global = global__.no() ? null : global__.FirstOrDefault();


            if (global.yes() && Globals.Count != 0){
                foreach (var pair in Globals){
                    var pi = global.GetProperty(pair.Key, BindingFlags.Static | BindingFlags.Public | BindingFlags.SetProperty);
                    if (null == pi) throw new Exception("Нет статического свойства с именем " + pair.Key);
                    pi.SetValue(null, pair.Key, null);
                }
            }

            resultAssembly.EntryPoint.Invoke(null, new[]{args});

            return null;
        }
Esempio n. 21
0
		public void TestWithDocPath()
		{
			var parameters = new CompilerParameters();
			CommandLineParser.ParseInto(parameters,
				new string[] { "/doc:TestDoc.xml", "/target:library", "/o:TestDoc.dll", "TestDoc.boo" });
			var compiler = new BooCompiler(parameters);
			var context=compiler.Run();
			if (context.Errors.Count > 0)
			{
				Console.WriteLine(context.Errors);
				throw new AssertionException(context.Errors[0].ToString());
			}
			
			var reference = new XmlDocument();
			reference.Load("TestDocReference.xml");
			var result = new XmlDocument();
			result.Load("TestDoc.xml");
			
			Assert.AreEqual(reference.ToString(), result.ToString());
		}
Esempio n. 22
0
        public static void Compile(int tabSize, IEnumerable<Assembly> assemblies, IEnumerable<CompileResults> codeFiles)
        {
            var pipeline = CompilerPipeline.GetPipeline("compile");
            pipeline.BreakOnErrors = false;
            var compiler = new BooCompiler(new CompilerParameters(false) { Pipeline = pipeline });

            compiler.Parameters.Environment =
                 new ClosedEnvironment(
                     new ParserSettings
                         {
                             TabSize= tabSize
                         });

            compiler.Parameters.Input.Clear();
            compiler.Parameters.References.Clear();

            foreach (var assembly in assemblies)
                compiler.Parameters.References.Add(assembly);

            var results = new Dictionary<string, CompileResults>();

            foreach (var codeFile in codeFiles)
            {
                results.Add(codeFile.Url, codeFile);
                codeFile.SetupForCompilation(compiler.Parameters);
            }

            compiler.Parameters.Pipeline.AfterStep +=
                (sender, args) =>
                {
                    if (args.Step == pipeline[0])
                        MapParsedNodes(results, args.Context);
                    if (args.Step == pipeline[pipeline.Count - 1])
                        MapCompleted(results, args.Context);
                };

            // as a part of compilation process compiler might request assembly load which triggers an assembly
            // resolve event to be processed by type resolver. Such processing has to happen on the same thread the
            // resolver has been created on
            compiler.Run();
        }
Esempio n. 23
0
        void AssertCultureDependentMessage(string message, CultureInfo culture)
        {
            CultureInfo savedCulture = Thread.CurrentThread.CurrentUICulture;
            Thread.CurrentThread.CurrentUICulture = culture;

            try
            {
                Boo.Lang.Compiler.BooCompiler compiler = new Boo.Lang.Compiler.BooCompiler();
                CompilerParameters options = compiler.Parameters;
                options.Input.Add(new Boo.Lang.Compiler.IO.StringInput("testcase", TestCase));
                options.Pipeline = new Boo.Lang.Compiler.Pipelines.Parse();

                CompilerErrorCollection errors = compiler.Run().Errors;

                Assert.AreEqual(1, errors.Count);
                Assert.AreEqual(message, errors[0].Message);
            }
            finally
            {
                Thread.CurrentThread.CurrentUICulture = savedCulture;
            }
        }
Esempio n. 24
0
        void AssertCultureDependentMessage(string message, CultureInfo culture)
        {
            CultureInfo savedCulture = Thread.CurrentThread.CurrentUICulture;

            Thread.CurrentThread.CurrentUICulture = culture;

            try
            {
                Boo.Lang.Compiler.BooCompiler compiler = new Boo.Lang.Compiler.BooCompiler();
                CompilerParameters            options  = compiler.Parameters;
                options.Input.Add(new Boo.Lang.Compiler.IO.StringInput("testcase", TestCase));
                options.Pipeline = new Boo.Lang.Compiler.Pipelines.Parse();

                CompilerErrorCollection errors = compiler.Run().Errors;

                Assert.AreEqual(1, errors.Count);
                Assert.AreEqual(message, errors[0].Message);
            }
            finally
            {
                Thread.CurrentThread.CurrentUICulture = savedCulture;
            }
        }
Esempio n. 25
0
 public IEnumerable<Node> Substitute(MacroStatement callPointMacro){
     var compiler = new BooCompiler();
     compiler.Parameters.Pipeline = new CompilerPipeline();
     compiler.Parameters.Pipeline.Add(new BooParsingStep());
     compiler.Parameters.Input.Add(new StringInput("_code_", Code));
     var compileresult = compiler.Run();
     
     Node target = callPointMacro.ParentNode;
     while(!(target==null||(target is TypeDefinition))){
         target = target.ParentNode;
     }
     if (null != target){
         foreach (var member in compileresult.CompileUnit.Modules[0].Members){
             
             ((TypeDefinition)target).Members.Add(member);
             
         }
     }
     var result = new Block(callPointMacro.LexicalInfo);
     foreach (var statement in compileresult.CompileUnit.Modules[0].Globals.Statements)
     {
         yield return statement;
     }
 }
 private CompilerContext Compile(string url)
 {
     TextReader input = urlResolver(url, baseDirectory ?? Path.GetDirectoryName(url));
     CompilerParameters parameters = SafeCloneParameters(Parameters);
     parameters.Input.Add(new ReaderInput(url, input));
     BooCompiler compiler = new BooCompiler(parameters);
     return compiler.Run();
 }
Esempio n. 27
0
		private ICompilationUnit Parse(IProjectContent projectContent, string fileName, int[] lineLength, BooCompiler compiler)
		{
			compiler.Parameters.OutputWriter = new StringWriter();
			compiler.Parameters.TraceLevel = System.Diagnostics.TraceLevel.Off;
			
			// Compile pipeline as of Boo 0.9.2:
			// Boo.Lang.Compiler.Pipelines.Parse:
			//   Boo.Lang.Parser.BooParsingStep
			// Boo.Lang.Compiler.Pipelines.ExpandMacros:
			//   Boo.Lang.Compiler.Steps.InitializeTypeSystemServices
			//   Boo.Lang.Compiler.Steps.PreErrorChecking
			//   Boo.Lang.Compiler.Steps.MergePartialClasses
			//   Boo.Lang.Compiler.Steps.InitializeNameResolutionService
			//   Boo.Lang.Compiler.Steps.IntroduceGlobalNamespaces
			//   Boo.Lang.Compiler.Steps.TransformCallableDefinitions
			//   Boo.Lang.Compiler.Steps.BindTypeDefinitions
			//   Boo.Lang.Compiler.Steps.BindGenericParameters
			//   Boo.Lang.Compiler.Steps.BindNamespaces
			//   Boo.Lang.Compiler.Steps.BindBaseTypes
			//   Boo.Lang.Compiler.Steps.MacroAndAttributeExpansion
			// Boo.Lang.Compiler.Pipelines.ResolveExpressions:
			//   Boo.Lang.Compiler.Steps.ExpandAstLiterals
			//   Boo.Lang.Compiler.Steps.IntroduceModuleClasses
			//   Boo.Lang.Compiler.Steps.NormalizeStatementModifiers
			//   Boo.Lang.Compiler.Steps.NormalizeTypeAndMemberDefinitions
			//   Boo.Lang.Compiler.Steps.NormalizeOmittedExpressions
			//   Boo.Lang.Compiler.Steps.BindTypeDefinitions
			//   Boo.Lang.Compiler.Steps.BindGenericParameters
			//   Boo.Lang.Compiler.Steps.BindEnumMembers
			//   Boo.Lang.Compiler.Steps.BindBaseTypes
			//   Boo.Lang.Compiler.Steps.CheckMemberTypes
			//   Boo.Lang.Compiler.Steps.BindMethods
			//   Boo.Lang.Compiler.Steps.ResolveTypeReferences
			//   Boo.Lang.Compiler.Steps.BindTypeMembers
			//   Boo.Lang.Compiler.Steps.CheckGenericConstraints
			//   Boo.Lang.Compiler.Steps.ProcessInheritedAbstractMembers
			//   Boo.Lang.Compiler.Steps.CheckMemberNames
			//   Boo.Lang.Compiler.Steps.ProcessMethodBodiesWithDuckTyping
			//   Boo.Lang.Compiler.Steps.PreProcessExtensionMethods
			// Boo.Lang.Compiler.Pipelines.Compile:
			//   Boo.Lang.Compiler.Steps.ConstantFolding
			//   Boo.Lang.Compiler.Steps.NormalizeLiterals
			//   Boo.Lang.Compiler.Steps.OptimizeIterationStatements
			//   Boo.Lang.Compiler.Steps.BranchChecking
			//   Boo.Lang.Compiler.Steps.CheckIdentifiers
			//   Boo.Lang.Compiler.Steps.StricterErrorChecking
			//   Boo.Lang.Compiler.Steps.CheckAttributesUsage
			//   Boo.Lang.Compiler.Steps.ExpandDuckTypedExpressions
			//   Boo.Lang.Compiler.Steps.ProcessAssignmentsToValueTypeMembers
			//   Boo.Lang.Compiler.Steps.ExpandProperties
			//   Boo.Lang.Compiler.Steps.RemoveDeadCode
			//   Boo.Lang.Compiler.Steps.CheckMembersProtectionLevel
			//   Boo.Lang.Compiler.Steps.NormalizeIterationStatements
			//   Boo.Lang.Compiler.Steps.ProcessSharedLocals
			//   Boo.Lang.Compiler.Steps.ProcessClosures
			//   Boo.Lang.Compiler.Steps.ProcessGenerators
			//   Boo.Lang.Compiler.Steps.ExpandVarArgsMethodInvocations
			//   Boo.Lang.Compiler.Steps.InjectCallableConversions
			//   Boo.Lang.Compiler.Steps.ImplementICallableOnCallableDefinitions
			//   Boo.Lang.Compiler.Steps.CheckNeverUsedMembers
			// Boo.Lang.Compiler.Pipelines.CompileToMemory:
			//   Boo.Lang.Compiler.Steps.EmitAssembly
			// Boo.Lang.Compiler.Pipelines.CompileToFile:
			//   Boo.Lang.Compiler.Steps.SaveAssembly
			
			
			CompilerPipeline compilePipe = new Parse();
			compilePipe.Add(new InitializeTypeSystemServices());
			compilePipe.Add(new PreErrorChecking());
			compilePipe.Add(new MergePartialClasses());
			compilePipe.Add(new InitializeNameResolutionService());
			compilePipe.Add(new IntroduceGlobalNamespaces());
			// TransformCallableDefinitions: not used for CC
			compilePipe.Add(new BindTypeDefinitions());
			compilePipe.Add(new BindGenericParameters());
			compilePipe.Add(new BindNamespacesWithoutRemovingErrors());
			compilePipe.Add(new BindBaseTypes());
			compilePipe.Add(new MacroAndAttributeExpansion());
			compilePipe.Add(new IntroduceModuleClasses());
			
			BooParsingStep parsingStep = (BooParsingStep)compilePipe[0];
			parsingStep.TabSize = 1;
			
			ConvertVisitor visitor = new ConvertVisitor(lineLength, projectContent);
			visitor.Cu.FileName = fileName;
			compilePipe.Add(visitor);
			
			compilePipe.BreakOnErrors = false;
			compiler.Parameters.Pipeline = compilePipe;
			compiler.Parameters.References.Add(typeof(Boo.Lang.Useful.Attributes.SingletonAttribute).Assembly);
			
			int errorCount = 0;
			compilePipe.AfterStep += delegate(object sender, CompilerStepEventArgs args) {
				if (args.Step == parsingStep)
					errorCount = args.Context.Errors.Count;
			};
			try {
				compiler.Run();
				visitor.Cu.ErrorsDuringCompile = errorCount > 0;
			} catch (Exception ex) {
				MessageService.ShowError(ex);
			}
			return visitor.Cu;
		}
Esempio n. 28
0
        public int Run(string[] args)
        {
            int resultCode = -1;

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);

            CheckBooCompiler();

            try
            {
                DateTime start = DateTime.Now;

                _options = new CompilerParameters(false); //false means no stdlib loading yet
                _options.GenerateInMemory = false;

                ArrayList tempLibPaths = _options.LibPaths.Clone() as ArrayList;
                _options.LibPaths.Clear();

                BooCompiler compiler = new BooCompiler(_options);

                ParseOptions(args);

                if (0 == _options.Input.Count)
                {
                    throw new ApplicationException(Boo.Lang.ResourceManager.GetString("BooC.NoInputSpecified"));
                }

                //move standard libpaths below any new ones:
                foreach(object o in tempLibPaths)
                    _options.LibPaths.Add(o);

                if (_options.StdLib)
                {
                    _options.LoadDefaultReferences();
                }
                else if (!_noConfig)
                {
                    _references.Insert(0, "mscorlib");
                }

                LoadReferences();
                ConfigurePipeline();

                if (_options.TraceSwitch.TraceInfo)
                {
                    compiler.Parameters.Pipeline.BeforeStep += new CompilerStepEventHandler(OnBeforeStep);
                    compiler.Parameters.Pipeline.AfterStep += new CompilerStepEventHandler(OnAfterStep);
                }

                TimeSpan setupTime = DateTime.Now - start;

                start = DateTime.Now;
                CompilerContext context = compiler.Run();
                TimeSpan processingTime = DateTime.Now - start;

                if (context.Warnings.Count > 0)
                {
                    Console.Error.WriteLine(context.Warnings);
                    Console.Error.WriteLine(Boo.Lang.ResourceManager.Format("BooC.Warnings", context.Warnings.Count));
                }

                if (context.Errors.Count > 0)
                {
                    foreach (CompilerError error in context.Errors)
                    {
                        Console.Error.WriteLine(error.ToString(_options.TraceSwitch.TraceInfo));
                    }
                    Console.Error.WriteLine(Boo.Lang.ResourceManager.Format("BooC.Errors", context.Errors.Count));
                }
                else
                {
                    resultCode = 0;
                }

                if (_options.TraceSwitch.TraceWarning)
                {
                    Console.Error.WriteLine(Boo.Lang.ResourceManager.Format("BooC.ProcessingTime", _options.Input.Count, processingTime.TotalMilliseconds, setupTime.TotalMilliseconds));
                }
            }
            catch (Exception x)
            {
                object message = _options.TraceSwitch.TraceWarning ? (object)x : (object)x.Message;
                Console.Error.WriteLine(Boo.Lang.ResourceManager.Format("BooC.FatalError", message));
            }
            return resultCode;
        }
Esempio n. 29
0
        /// <summary>
        /// Force a compile with no caching
        /// </summary>
        /// <param name="urls">The urls.</param>
        /// <param name="cacheFileName">Name of the cache file.</param>
        /// <returns></returns>
        public virtual CompilerContext ForceCompile(string[] urls, string cacheFileName)
        {
            BooCompiler compiler = new BooCompiler();
            compiler.Parameters.OutputType = CompilerOutputType;
            compiler.Parameters.GenerateInMemory = true;
            compiler.Parameters.Pipeline = new CompileToFile();
            compiler.Parameters.OutputAssembly = cacheFileName;
            CustomizeCompiler(compiler, compiler.Parameters.Pipeline, urls);
            AddInputs(compiler, urls);
            CompilerContext compilerContext = compiler.Run();
            if (compilerContext.Errors.Count != 0)
                throw CreateCompilerException(compilerContext);
            HandleWarnings(compilerContext.Warnings);

            return compilerContext;
        }
Esempio n. 30
0
        public override bool Execute()
        {
            BooCompiler compiler = new BooCompiler();
            if (OutputAssembly == null)
            {
                compiler.Parameters.Pipeline = new CompileToMemory();
            }
            else
            {
                compiler.Parameters.Pipeline = new CompileToFile();
                compiler.Parameters.OutputAssembly = OutputAssembly.ItemSpec;
            }
            compiler.Parameters.OutputType = CompilerOutputType.ConsoleApplication;

            if (files == null || files.Length == 0)
            {
                Log.LogError("Must specify at least one file for the book task");
                return false;
            }

            foreach (ITaskItem taskItem in files)
            {
                FileInput input = new FileInput(taskItem.ItemSpec);
                compiler.Parameters.Input.Add(input);
            }

            foreach (ITaskItem reference in references)
            {
                Assembly assembly = Assembly.LoadFrom(reference.ItemSpec);
                compiler.Parameters.References.Add(assembly);
            }

            CompilerContext run = compiler.Run();

            if (run.Errors.Count > 0)
            {
                string s = run.Errors.ToString(true);
                Log.LogError("Failed to compile code: " + s);
                return false;
            }

            MethodInfo methodInfo = run.GeneratedAssembly.EntryPoint;
            if (methodInfo == null)
            {
                Log.LogError("Could not find entry point for the files");
                return false;
            }
            try
            {
                methodInfo.Invoke(null, new object[] { new string[0] });
            }
            catch (TargetInvocationException e)
            {
                Log.LogError("Scripts failed to run!");
                Log.LogError(e.InnerException.ToString());
            }

            return true;
        }
Esempio n. 31
0
        private static BoostOutputter Compile(string booSource)
        {
            var booc = new BooCompiler();

            booc.Parameters.Input.Add(new StringInput("Input", booSource));
            booc.Parameters.Ducky = true;

            booc.Parameters.References.Add(Assembly.GetAssembly(typeof(BoostOutputter)));

            booc.Parameters.Pipeline = new CompileToMemory();
            booc.Parameters.Pipeline[0] = new WSABooParsingStep();

            var output = new StringBuilder();

            var compilerContext = booc.Run();

            if (null == compilerContext.GeneratedAssembly)
            {
                foreach (CompilerError error in compilerContext.Errors)
                {
                    output.AppendLine(error.Message);
                }

                output.Append(booSource);
                throw new Exception(output.ToString());
            }

            var booClassType = compilerContext.GeneratedAssembly.GetType("GeneratedOutputter", true, true);

            return Activator.CreateInstance(booClassType) as BoostOutputter;
        }
        void BuildAdapter(Assembly assembly, string adapterNamespace, string adapterPath, string importsPath)
        {
            // There are several solutions to this:
            // 1. Directly generate IL, optionally using some intermediate library
            // 2. Generate Boo AST and compile it
            // 3. Generate Boo code and compile it
            // I am going with option 3, just because it is the easiest to debug and understand later

            var referencedTypes = new HashSet<Type>();
            var code = GenerateAdapterCode(assembly, adapterNamespace, referencedTypes);

            var compiler = new BooCompiler {
                                           	Parameters = {
                                           	             	OutputType = CompilerOutputType.Library,
                                           	             	Pipeline = new CompileToFile(),
                                           	             	OutputAssembly = adapterPath,
                                           	             	Input = {new StringInput("integration.boo", code)}
                                           	             }
                                           };
            compiler.Parameters.Pipeline.InsertBefore(typeof (ExpandAstLiterals), new UnescapeNamesStep());
            compiler.Parameters.Pipeline.InsertBefore(typeof (ProcessMethodBodiesWithDuckTyping), new AutoRunAllRunnablesStep());

            compiler.Parameters.References.Add(assembly);
            compiler.Parameters.References.Add(GetType().Assembly);
            foreach (var referencedAssembly in referencedTypes.Select(t => t.Assembly).Distinct()) {
                compiler.Parameters.References.Add(referencedAssembly);
            }

            var result = compiler.Run();
            if (result.Errors.Count > 0) {
                File.WriteAllText(Path.ChangeExtension(adapterPath, ".boo"), code);
                throw new CompilerError(result.Errors.ToString(true));
            }

            using (var writer = new StreamWriter(importsPath, false)) {
                var imports = referencedTypes.Select(type => new {type.Namespace, type.Assembly}).Distinct();
                foreach (var import in imports) {
                    writer.WriteLine(import.Namespace + "," + import.Assembly.Location);
                }
            }
        }
Esempio n. 33
0
        private void RunBooScript(string file)
        {
            uint timer_id = Log.DebugTimerStart ();

            BooCompiler compiler = new BooCompiler ();
            compiler.Parameters.Ducky = true;
            compiler.Parameters.Pipeline = new CompileToMemory ();
            compiler.Parameters.Input.Add (new FileInput (file));

            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies ()) {
                compiler.Parameters.References.Add (assembly);
            }

            CompilerContext context = compiler.Run ();

            if (context.GeneratedAssembly == null) {
                foreach (CompilerError error in context.Errors) {
                    Log.Warning (String.Format ("BooScript: compiler error: {0} ({1})",
                        error.ToString (), file), false);
                }

                return;
            }

            try {
                Type script_module = context.GeneratedAssembly.GetTypes ()[0];

                if (script_module == null) {
                    Log.Warning (String.Format ("BooScript: could not find module in script ({0})", file), false);
                    return;
                }

                MethodInfo main_entry = script_module.Assembly.EntryPoint;
                main_entry.Invoke (null, new object[main_entry.GetParameters ().Length]);

                Log.DebugTimerPrint (timer_id, "BooScript: compiled and invoked: {0}");
            } catch (Exception e) {
                Log.Exception ("BooScript: scripted failed", e);
            }
        }
Esempio n. 34
0
        public CompilerResults CompileAssemblyFromSourceBatch(
            CompilerParameters options, string [] sources)
        {
            if (null == options)
            {
                throw new ArgumentNullException("options");
            }
            if (null == sources)
            {
                throw new ArgumentNullException("fileNames");
            }

            CompilerResults results = new CompilerResults(options.TempFiles);

            BooC.BooCompiler        compiler   = new BooC.BooCompiler();
            BooC.CompilerParameters parameters = compiler.Parameters;

            if (options.OutputAssembly == null)
            {
                options.OutputAssembly = GetTempFileNameWithExtension(options.TempFiles, "dll");
            }
            parameters.OutputAssembly = options.OutputAssembly;

            // set compile options
            if (options.GenerateInMemory)
            {
                parameters.Pipeline = new CompileToMemory();
            }
            else
            {
                parameters.Pipeline = new CompileToFile();
            }

            if (options.GenerateExecutable)
            {
                parameters.OutputType = BooC.CompilerOutputType.ConsoleApplication;                 // winexe ??
            }
            else
            {
                parameters.OutputType = BooC.CompilerOutputType.Library;
            }
            parameters.Debug = options.IncludeDebugInformation;

            if (null != options.ReferencedAssemblies)
            {
                foreach (string import in options.ReferencedAssemblies)
                {
                    parameters.References.Add(Assembly.LoadFrom(import));
                }
            }

            foreach (string source in sources)
            {
                parameters.Input.Add(new StringInput("source", source));
            }
            // run the compiler
            BooC.CompilerContext context = compiler.Run();

            bool loadIt = processCompileResult(context, results);

            if (loadIt)
            {
                results.CompiledAssembly = context.GeneratedAssembly;
                //results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
            }
            else
            {
                results.CompiledAssembly = null;
            }

            return(results);
        }
Esempio n. 35
0
        public override Assembly Compile(string path, string outPath, bool cache)
        {
            Assembly asm = null;

            try
            {
                if (this.ExistsAndUpToDate(path, outPath) && cache)
                {
                    return(Assembly.LoadFrom(outPath));
                }

                // Precompile script to a temp file
                var precompiled = this.PreCompile(File.ReadAllText(path));
                var tmp         = Path.GetTempFileName();
                File.WriteAllText(tmp, precompiled);

                // Compile
                var compiler = new Boo.Lang.Compiler.BooCompiler();
                compiler.Parameters.AddAssembly(typeof(Log).Assembly);
                compiler.Parameters.AddAssembly(Assembly.GetEntryAssembly());
                compiler.Parameters.Input.Add(new FileInput(tmp));
                compiler.Parameters.OutputAssembly = outPath;
                compiler.Parameters.Pipeline       = new CompileToFile();

#if DEBUG
                compiler.Parameters.Debug = true;
#else
                compiler.Parameters.Debug = false;
#endif

                var context = compiler.Run();
                if (context.GeneratedAssembly == null)
                {
                    var errors = context.Errors;
                    var newExs = new CompilerErrorsException();

                    foreach (var err in errors)
                    {
                        var newEx = new CompilerError(path, err.LexicalInfo.Line, err.LexicalInfo.Column, err.Message, false);
                        newExs.Errors.Add(newEx);
                    }

                    throw newExs;
                }

                asm = context.GeneratedAssembly;
            }
            catch (CompilerErrorsException)
            {
                throw;
            }
            catch (UnauthorizedAccessException)
            {
                // Thrown if file can't be copied. Happens if script was
                // initially loaded from cache.
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }

            return(asm);
        }
Esempio n. 36
0
        private static AbstractConfigurationRunner GetConfigurationInstance(
			string name, string environment, ICompilerInput input,
			GenerationOptions generationOptions, ICompilerStep autoReferenceStep,
			params string[] namespaces)
        {
            BooCompiler compiler = new BooCompiler();
            compiler.Parameters.Ducky = true;
            if (generationOptions == GenerationOptions.Memory)
                compiler.Parameters.Pipeline = new CompileToMemory();
            else
                compiler.Parameters.Pipeline = new CompileToFile();

            compiler.Parameters.Pipeline.Insert(1, autoReferenceStep);
            compiler.Parameters.Pipeline.Insert(2, new BinsorCompilerStep(environment, namespaces));
            compiler.Parameters.Pipeline.Replace(
                typeof (ProcessMethodBodiesWithDuckTyping),
                new TransformUnknownReferences());
            compiler.Parameters.Pipeline.InsertAfter(typeof (TransformUnknownReferences),
                                                     new RegisterComponentAndFacilitiesAfterCreation());

            compiler.Parameters.OutputType = CompilerOutputType.Library;
            compiler.Parameters.Input.Add(input);
            compiler.Parameters.References.Add(typeof (BooReader).Assembly);
            compiler.Parameters.References.Add(typeof (MacroMacro).Assembly);

            TryAddAssembliesReferences(compiler.Parameters, "Rhino.Commons.NHibernate", "Rhino.Commons.ActiveRecord");

            CompilerContext run = compiler.Run();
            if (run.Errors.Count != 0)
            {
                throw new CompilerError(string.Format("Could not compile configuration! {0}", run.Errors.ToString(true)));
            }
            Type type = run.GeneratedAssembly.GetType(name.Replace('.', '_'));
            return Activator.CreateInstance(type) as AbstractConfigurationRunner;
        }
Esempio n. 37
-21
		public void EnvironmentBindingsCanBeCustomizedThroughCompilerParametersEnvironment()
		{
			EntityFormatter actualFormatter = null;
			var expectedFormatter = new EntityFormatter();
			
			var compiler = new Boo.Lang.Compiler.BooCompiler();
			compiler.Parameters.Pipeline = new CompilerPipeline { new ActionStep(() => actualFormatter = My<EntityFormatter>.Instance) };
			compiler.Parameters.Environment = new ClosedEnvironment(expectedFormatter);
			compiler.Run();

			Assert.AreSame(expectedFormatter, actualFormatter);
		}