boo compilation context.
        public DslFactoryFixture()
        {
            factory = new DslFactory();
            mocks = new MockRepository();
            mockedDslEngine = mocks.DynamicMock<DslEngine>();
            mockCache = mocks.DynamicMock<IDslEngineCache>();
        	
			mockCache.WriteLock(null);
        	LastCall.Repeat.Any()
        		.IgnoreArguments()
        		.Do((Action<CacheAction>) ExecuteCachedAction);
			
			mockCache.ReadLock(null);
			LastCall.Repeat.Any()
				.IgnoreArguments()
				.Do((Action<CacheAction>)ExecuteCachedAction);
            
			IDslEngineStorage mockStorage = mocks.DynamicMock<IDslEngineStorage>();
            Assembly assembly = Assembly.GetCallingAssembly();
            context = new CompilerContext();
            context.GeneratedAssembly = assembly;
            mockedDslEngine.Storage = mockStorage;
            mockedDslEngine.Cache = mockCache;

            SetupResult.For(mockStorage.GetMatchingUrlsIn("", ref testUrl)).Return(new string[] { testUrl });
            SetupResult.For(mockStorage.IsUrlIncludeIn(null, null, null))
                .IgnoreArguments()
                .Return(true);
        }
        public GeneratorExpressionProcessor(CompilerContext context,
								ForeignReferenceCollector collector,
								GeneratorExpression node)
        {
            _collector = collector;
            _generator = node;
            Initialize(context);
        }
 public static ClassDefinition GetScriptClass(CompilerContext context)
 {
     object obj1 = context.get_Item("ScriptClass");
     if (!(obj1 is ClassDefinition))
     {
     }
     return (ClassDefinition) RuntimeServices.Coerce(obj1, typeof(ClassDefinition));
 }
		private static string RunThroughPreProcessor(string code)
		{
			var ppc = new BrailPreProcessor(new BooViewEngine());
			var context = new CompilerContext();
			context.Parameters.Input.Add(new StringInput("test", code));
			ppc.Initialize(context);
			ppc.Run();
			return context.Parameters.Input[0].Open().ReadToEnd();
		}
 public override void Initialize(CompilerContext context)
 {
     base.Initialize(context);
     Type type = typeof(UnityRuntimeServices.MemberValueTypeChange);
     this._valueTypeChangeConstructor = this.get_TypeSystemServices().Map(type.GetConstructors()[0]);
     this._valueTypeChangeType = this.get_TypeSystemServices().Map(typeof(UnityRuntimeServices.ValueTypeChange));
     Type type2 = typeof(UnityRuntimeServices.SliceValueTypeChange);
     this._sliceValueTypeChangeConstructor = this.get_TypeSystemServices().Map(type2.GetConstructors()[0]);
     this._propagateChanges = this.get_TypeSystemServices().Map(new __ProcessAssignmentToDuckMembers_Initialize$callable0$25_95__(UnityRuntimeServices.PropagateValueTypeChanges).Method);
 }
        public static void MapParsedNodes(Dictionary<string, CompileResults> results, CompilerContext compilerContext)
        {
            foreach (var module in compilerContext.CompileUnit.Modules)
                results[module.LexicalInfo.FileName].MapParsedNodes(module);

            foreach (var error in compilerContext.Errors)
                results[error.LexicalInfo.FileName].MapParsingMessage(error);

            foreach (var warning in compilerContext.Warnings)
                results[warning.LexicalInfo.FileName].MapParsingMessage(warning);
        }
 public GeneratorMethodProcessor(CompilerContext context, InternalMethod method)
 {
     _labels = new List();
     _mapping = new Hashtable();
     _generator = method;
     _generatorItemType = (IType)_generator.Method["GeneratorItemType"];
     _enumerable = (BooClassBuilder)_generator.Method["GeneratorClassBuilder"];
     Debug.Assert(null != _generatorItemType);
     Debug.Assert(null != _enumerable);
     Initialize(context);
 }
Exemple #8
0
		public CompilerContext Run(CompileUnit compileUnit)
		{
			if (null == compileUnit)
				throw new ArgumentNullException("compileUnit");
			if (null == _parameters.Pipeline)
				throw new InvalidOperationException(Boo.Lang.Resources.StringResources.BooC_CantRunWithoutPipeline);
			
			var context = new CompilerContext(_parameters, compileUnit);
			_parameters.Pipeline.Run(context);
			return context;
		}
		/// <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();
		}
Exemple #10
0
		/// <summary>
		/// Throws the error.
		/// </summary>
		/// <param name="filename">The filename.</param>
		/// <param name="context">The context.</param>
		internal static void ThrowError(string filename, CompilerContext context)
		{
			var errors = new List<string>();

			using (StreamWriter errorFile = File.CreateText(filename + ".errors")) {
				foreach (CompilerError error in context.Errors) {
					errorFile.WriteLine("= ERROR ========================================================================");
					errorFile.WriteLine(error);
					errorFile.WriteLine("================================================================================");
					errorFile.WriteLine();

					errors.Add(error.ToString());
				}

				errorFile.Flush();
			}

			throw new ScriptErrorException(filename, errors.ToArray());
		}
        public virtual void setup() {
            string code = @"import System.Data
class X :
    def Z() as string :
        return  ''
def B() as bool :
    return false
registry['x'] = X
if B() :
    pass";
            this.cu = Compile("test",code, getPipeline() , prepareCompiler);
            Console.WriteLine(cu.Errors);
            Assert.True(cu.Errors.Count==0);
            this.srcmodule = cu.CompileUnit.Modules[0].Clone() as Module;
            Console.WriteLine(srcmodule.ToCodeString());
            this.pr = postProcess();
            if(pr.ToCodeString()!=srcmodule.ToCodeString()) {
                Console.WriteLine(pr.ToCodeString());
            }
        }
		/// <summary>
		/// Loads this instance.
		/// </summary>
		public override void LoadOrExecute()
		{
			_interpreter.Reset();
			_interpreter.References.Clear();
			_interpreter.RememberLastValue = true;

			foreach (Assembly assembly in References) {
				_interpreter.References.Add(assembly);
			}

			var booFile = new StringBuilder();
			booFile.Append(File.ReadAllText(Filename));

			_context = _interpreter.Eval(booFile.ToString());

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

			GeneratedAssembly = _context.GeneratedAssembly;
			GetFileLastChange();
		}
Exemple #13
0
 protected bool processCompileResult(BooC.CompilerContext context, CompilerResults results)
 {
     foreach (BooC.CompilerError booError in context.Errors)
     {
         CompilerError error = new CompilerError();
         error.ErrorNumber = booError.Code;
         error.Line        = booError.LexicalInfo.Line;
         error.Column      = booError.LexicalInfo.Column;
         error.FileName    = booError.LexicalInfo.FileName;
         error.ErrorText   = booError.Message;
         error.IsWarning   = false;
         results.Errors.Add(error);
     }
     if (context.Errors.Count > 0)
     {
         return(false);
     }
     else
     {
         return(true);
     }
 }
        private IEnumerable<Tuple<Assembly,string >> getmacronamespaces(CompilerContext context) {
            if (context["macronamespaces"] == null)
            {

                var macronamespaces = new List<Tuple<Assembly, string>>();
                context["macronamespaces"] = macronamespaces;
                foreach (ICompileUnit reference in context.References) {
                    try {
                        var a = reference.getPropertySafe<Assembly>("Assembly");
                        // импортирует автоматически макросы только из библиотек Comdiv - иначе жестокие тормоза и смысла главное никакого
                        if (a != null) {
                            var n = a.GetName().Name;
                            //HACK: due to performance issues uses only comdiv based libriries
                            if (!n.StartsWith("Comdiv.")) continue;
                            if (n.EndsWith(".Test")||n.EndsWith(".Tests")) continue;

         
                            var attrs = a.GetCustomAttributes(typeof(AssemblyBooMacroNamespaceAttribute), false);
                            if (attrs.Length != 0)
                            {
                                foreach (
                                    string ns in
                                        attrs.Cast<AssemblyBooMacroNamespaceAttribute>().Select(x => x.Namespace))
                                {
                                    macronamespaces.Add(Tuple.Create(a, ns));

                                }
                            }
                            
                        }
                    }
                    catch (Exception ex) {
                        context.TraceInfo("ошибка импорта пространства имен " + ex.Message);
                    }
                }
            }
            return (IEnumerable<Tuple<Assembly, string>>) context["macronamespaces"];
        }
		}

		protected string Run(string stdin, out CompilerContext context)
		{
			var oldStdOut = Console.Out;
			var oldStdIn = Console.In;

			try
			{
				Console.SetOut(_output);
				if (stdin != null)
					Console.SetIn(new StringReader(stdin));

				context = _compiler.Run();

				if (HasErrors(context) && !IgnoreErrors)
				{
					Assert.Fail(GetFirstInputName(context)
								+ ": "
								+ context.Errors.ToString(true)
								+ context.Warnings);				
				}
				return _output.ToString().Replace("\r\n", "\n");
			}
			finally
			{
				_output.GetStringBuilder().Length = 0;

				Console.SetOut(oldStdOut);
				Console.SetIn(oldStdIn);
 public virtual void Initialize(CompilerContext context)
 {
     if (null == context)
     {
         throw new ArgumentNullException("context");
     }
     _context = context;
 }
		}
		
		private bool HasErrors(CompilerContext context)
		{
		private CompilerContext LoadCompilerContext(string file)
		{
			if (!File.Exists(file)) 
				return null;

			Assembly assembly = null;
			ReadLock(delegate
			{
				if (assemblyCache.TryGetValue(file, out assembly) == false)
				{
					WriteLock(delegate
					{
						byte[] bytes = File.ReadAllBytes(file);
						assembly = Assembly.Load(bytes);
						assemblyCache[file] = assembly;
						AssemblyLoaded(file, assembly, true);
					});
				}
			});
			
			CompilerContext context = new CompilerContext();
			context.GeneratedAssembly = assembly;
			return context;
		}
 public virtual void Dispose()
 {
     _context = null;
 }
Exemple #20
0
			public CompilationResult(CompilerContext context, BrailPreProcessor processor)
			{
				this.context = context;
				this.processor = processor;
			}
        private void AddNamespaceImports(Import node)
        {
            RemoveCurrentNode();

            string url = GetFilePath(node);
            using(TextReader reader = urlResolver(url, baseDirectory))
            {
                BooParsingStep parser = new BooParsingStep();
                CompilerContext context = new CompilerContext();
                StringInput input = new StringInput(node.AssemblyReference.Name, reader.ReadToEnd());
                context.Parameters.Input.Add(input);
                parser.Initialize(context);
                parser.Run();
                Module current = (Module) node.GetAncestor(NodeType.Module);
                foreach (Module module in context.CompileUnit.Modules)
                {
                    foreach (Import import in module.Imports)
                    {
                        current.Imports.Add(import);
                    }
                }
            }
        }
 private Type DoCompile()
 {
     UnityScriptCompiler compiler = new UnityScriptCompiler();
     compiler.Parameters.set_Pipeline(AdjustPipeline(this._context, UnityScriptCompiler.Pipelines.CompileToMemory()));
     compiler.Parameters.ScriptBaseType = typeof(EvaluationScript);
     compiler.Parameters.GlobalVariablesBecomeFields = false;
     compiler.Parameters.ScriptMainMethod = "Run";
     compiler.Parameters.get_Input().Add(new StringInput("script", this._code + ";"));
     compiler.Parameters.set_Debug(false);
     compiler.Parameters.set_GenerateInMemory(true);
     this.AddEvaluationContextReferencesTo(compiler);
     this._compilationResult = compiler.Run();
     if (this._compilationResult.get_Errors().Count != 0)
     {
         throw new CompilationErrorsException(this._compilationResult.get_Errors());
     }
     return this._compilationResult.get_GeneratedAssembly().GetType("script");
 }
		protected AbstractAstGeneratorMacro(CompilerContext context) : base (context)
		{
		}
Exemple #24
0
 public CompilerStepEventArgs(CompilerContext context, ICompilerStep step)
 {
     this.Context = context;
     this.Step    = step;
 }
Exemple #25
0
 virtual protected void Prepare(CompilerContext context)
 {
 }
 public CompilerStepEventArgs(CompilerContext context, ICompilerStep step) : base(context)
 {
     this.Step = step;
 }
 public static void SetScriptClass(CompilerContext context, ClassDefinition klass)
 {
     context.set_Item("ScriptClass", klass);
 }
 protected LexicalInfoPreservingGeneratorMacro(CompilerContext context)
     : base(context)
 {
 }
		}

		string GetFirstInputName(CompilerContext context)
		{
Exemple #30
0
 public CompilerStepEventArgs(CompilerContext context, ICompilerStep step)
 {
     this.Context = context;
     this.Step = step;
 }
		override public void Initialize(CompilerContext context)
		{
			base.Initialize(context);
			NameResolutionService.Reset();
		}
Exemple #32
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);
        }
 protected override void OnAfter(CompilerContext context)
 {
     RunStep(context, new Boo.Lang.Compiler.Steps.PrintErrors());
 }
 public override void Run(CompilerContext context)
 {
     base.Run(context);
     RunStep(context, new Boo.Lang.Compiler.Steps.PrintErrors());
 }
 public override void Initialize(CompilerContext context)
 {
     base.Initialize(context);
     _booModuleAttributeType = TypeSystemServices.Map(typeof(System.Runtime.CompilerServices.CompilerGlobalScopeAttribute));
 }
 public CompilerPipelineEventArgs(CompilerContext context)
 {
     this.Context = context;
 }