Пример #1
0
        public string Execute(string templateText, dynamic model, IEnumerable <string> assemblyReferences)
        {
            Log.Info("Executing template...");

            Log.Debug(() => string.Format("Template text: {0}", templateText));

            if (assemblyReferences != null)
            {
                Log.Debug(() => string.Format("Assembly References: {0}", string.Join(", ", assemblyReferences)));
                CompilationParameters.SetReferencedAssemblies(assemblyReferences);
            }

            dynamic instance = GetTemplateInstance(templateText);

            instance.Model = model ?? new DynamicDictionary();

            Log.Info("Executing...");
            instance.Execute();

            string templateOutput = instance.Buffer.ToString();

            Log.Info("Template executed.");
            Log.Debug(() => string.Format("Executed template output: {0}", templateOutput));

            return(templateOutput);
        }
Пример #2
0
        /// <summary>
        /// Sets up <paramref name="parameters"/> according to the supplied <paramref name="options"/>.
        /// </summary>
        /// <param name="parameters">The parameters to set up.</param>
        /// <param name="options">The options passed to CodeDom.</param>
        private void SetupCompilerParameters(CompilationParameters /*!*/ parameters, CompilerParameters /*!*/ options)
        {
            parameters.Target     = (options.GenerateExecutable ? ApplicationCompiler.Targets.Console : ApplicationCompiler.Targets.Dll);
            parameters.Debuggable = options.IncludeDebugInformation;
            parameters.SourceRoot = DetermineSourceRoot(parameters);

            if (!String.IsNullOrEmpty(options.OutputAssembly))
            {
                parameters.OutPath = new FullPath(options.OutputAssembly);
            }

            // referenced assemblies
            foreach (string reference in options.ReferencedAssemblies)
            {
                parameters.References.Add(new CompilationParameters.ReferenceItem()
                {
                    Reference = reference
                });
            }

            // referenced resource files
            foreach (string resource in options.LinkedResources)
            {
                parameters.Resources.Add(new FileReference(resource));
            }

            parameters.Pure = true;

            // parse user-provided compiler options
            if (!String.IsNullOrEmpty(options.CompilerOptions))
            {
                CommandLineParser parser = new CommandLineParser(parameters);
                parser.Parse(CommandLineParser.StringToArgumentList(options.CompilerOptions));
            }
        }
 public virtual IEnumerable <string> GetDefineSymbols()
 {
     if (CompilationParameters != null)
     {
         return(CompilationParameters.GetDefineSymbols());
     }
     return(new string[0]);
 }
Пример #4
0
        /// <summary>
        /// Determines the source root for a compilation based on the source file paths and output path.
        /// </summary>
        /// <param name="parameters">The parameters describing source files and the output file.</param>
        /// <returns>A suitable source root, preferrably a common superdirectory of all sources.</returns>
        private FullPath DetermineSourceRoot(CompilationParameters /*!*/ parameters)
        {
            // try to obtain a common superdirectory of all source files
            if (parameters.SourcePaths.Count > 0 && parameters.SourcePaths[0].DirectoryExists)
            {
                CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
                string      result  = Path.GetDirectoryName(parameters.SourcePaths[0].ToString());

                for (int i = 1; i < parameters.SourcePaths.Count; i++)
                {
                    string path = parameters.SourcePaths[i].ToString();

                    int limit = Math.Min(result.Length, path.Length);
                    int index = -1;

                    for (int j = 0; j < limit; j++)
                    {
                        // remember the last directory separator position
                        if (result[j] == Path.DirectorySeparatorChar)
                        {
                            index = j;
                        }

                        if (Char.ToLower(result[j], culture) != Char.ToLower(path[j], culture))
                        {
                            if (index >= 0)
                            {
                                result = result.Substring(0, index);
                            }
                            else
                            {
                                result = null;
                            }
                        }
                    }

                    if (result == null)
                    {
                        break;
                    }
                }

                if (result != null)
                {
                    return(new FullPath(result));
                }
            }

            // otherwise the output directory
            if (!parameters.OutPath.IsEmpty)
            {
                return(new FullPath(Path.GetDirectoryName(parameters.OutPath.ToString())));
            }

            // otherwise fall back to default
            return(new FullPath(Environment.SystemDirectory));
        }
Пример #5
0
        public async Task <IAssembly> CompileAsync(IProject Project, CompilationParameters Parameters)
        {
            var binder = await Parameters.BinderTask;
            var asm    = new SyntaxAssembly(Project.Name, new Version(), Parameters.Log,
                                            CBuildHelpers.Instance.CreatePrimitiveBinder32(binder), new TypeNamerBase());

            await ParseCompilationUnitsAsync(Project.GetSourceItems(), asm, Parameters);

            return(asm);
        }
Пример #6
0
        public static TokenizerStream Preprocess(ISourceDocument Document, CompilationParameters Parameters)
        {
            var sourceFile   = new SourceFile(Document, Parameters);
            var preprocessor = new PreprocessorState(PreprocessorEnvironment.Static_Singleton.Instance.CreateDefaultEnvironment(Parameters.Log), sourceFile);
            var result       = preprocessor.Expand(Document);

            if (Parameters.Log.Options.GetOption <bool>("output-preprocessed", false) || Parameters.Log.Options.GetOption <bool>("E", false))
            {
                Parameters.Log.LogMessage(new LogEntry(Document.Identifier + " after preprocessing", result.ToString()));
            }
            return(new TokenizerStream(result.ToStream()));
        }
Пример #7
0
            /// <summary>
            /// Compiles in a seperate appdomain utilitizing one of the compilers on the stack.
            /// </summary>
            public static void Compile(ErrorSink /*!*/ errorSink, CompilationParameters /*!*/ ps)
            {
                // obtain a compiler
                StackItem item = new StackItem();

                lock (stack)
                {
                    if (stack.Count > 0)
                    {
                        item = stack.Pop();
                    }
                }
                if (item.Compiler == null)
                {
                    item.Compiler = ApplicationCompiler.CreateRemoteCompiler();
                }

                // compile
                item.Compiler.RemoteCompile(ref errorSink, ps);

                // check whether the separate appdomain is not too weedy
                if (++item.CompileCounter == 1 || item.CompileCounter == compileCounterTreshold)
                {
                    item.CompileCounter = 1;

                    CallBackDisplay display = new CallBackDisplay();

                    // avoid passing the array of assemblies across appdomain boundary
                    item.Compiler.Domain.DoCallBack(display.Handler);

                    if (item.RemoteAssemblyCount == 0)
                    {
                        item.RemoteAssemblyCount = display.AssemblyCount;
                    }
                    else
                    {
                        if (display.AssemblyCount > (2 * item.RemoteAssemblyCount))
                        {
                            AppDomain.Unload(item.Compiler.Domain);
                            return;
                        }
                    }
                }

                // recycle the compiler
                lock (stack) stack.Push(item);
            }
Пример #8
0
        /// <summary>
        /// Compiles an assembly from the source code contained within the specified file, using the specified compiler settings.
        /// </summary>
        public CompilerResults /*!*/ CompileAssemblyFromFile(CompilerParameters /*!*/ options, string /*!*/ fileName)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            CompilationParameters parameters = new CompilationParameters();

            parameters.SourcePaths.Add(new FullPath(fileName));

            return(Compile(parameters, options));
        }
Пример #9
0
        /// <summary>
        /// Compiles an assembly from the specified string containing source code, using the specified compiler settings.
        /// </summary>
        public CompilerResults /*!*/ CompileAssemblyFromSource(CompilerParameters /*!*/ options, string /*!*/ source)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            CompilationParameters parameters = new CompilationParameters();

            throw new NotImplementedException();             //parameters.SourceReaders.Add(new StringReader(source));

            //return Compile(parameters, options);
        }
Пример #10
0
        /// <summary>
        /// Compiles an assembly from the <see cref="System.CodeDom"/> tree contained in the specified
        /// <see cref="CodeCompileUnit"/>, using the specified compiler settings.
        /// </summary>
        public CompilerResults /*!*/ CompileAssemblyFromDom(CompilerParameters /*!*/ options, CodeCompileUnit /*!*/ compilationUnit)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (compilationUnit == null)
            {
                throw new ArgumentNullException("compilationUnit");
            }

            CompilationParameters parameters = new CompilationParameters();

            throw new NotImplementedException();             //parameters.SourceReaders.Add(GenerateCompilationUnit(compilationUnit));
            //ResolveReferencedAssemblies(options, compilationUnit);

            //return Compile(parameters, options);
        }
Пример #11
0
 public static ISourceDocument GetSourceSafe(IProjectSourceItem Item, CompilationParameters Parameters)
 {
     try
     {
         return(Item.GetSource(Parameters.CurrentPath.AbsolutePath.Path));
     }
     catch (FileNotFoundException)
     {
         Parameters.Log.LogError(new LogEntry("error getting source code", "file '" + Item.SourceIdentifier + "' was not found."));
         return(null);
     }
     catch (Exception ex)
     {
         Parameters.Log.LogError(new LogEntry("error getting source code", "'" + Item.SourceIdentifier + "' could not be opened."));
         Parameters.Log.LogError(new LogEntry("exception", ex.ToString()));
         return(null);
     }
 }
        public async Task<IAssembly> CompileAsync(IProject Project, CompilationParameters Parameters)
        {
            var name = Parameters.Log.GetAssemblyName(Project.AssemblyName ?? Project.Name ?? "");
            var extBinder = await Parameters.BinderTask;
            var asm = new DescribedAssembly(name, extBinder.Environment);

            var asmBinder = new CachingBinder(new DualBinder(asm.Binder, extBinder));

            var units = await ParseCompilationUnitsAsync(Project.GetSourceItems(), Parameters, asmBinder, asm);
            var rootNs = new RootNamespace(asm, units);

            // Perform a bait-and-switch here such that lazy evaluation will
            // take the types defined in this namespace into account when resolving symbols.
            asm.MainNamespace = rootNs;

            asm.EntryPoint = InferEntryPoint(asm);

            return asm;
        }
Пример #13
0
        /// <summary>
        /// Compiles an assembly from the source code contained within the specified files, using the specified compiler settings.
        /// </summary>
        public CompilerResults /*!*/ CompileAssemblyFromFileBatch(CompilerParameters /*!*/ options, string[] /*!*/ fileNames)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (fileNames == null)
            {
                throw new ArgumentNullException("fileNames");
            }

            CompilationParameters parameters = new CompilationParameters();

            for (int i = 0; i < fileNames.Length; i++)
            {
                parameters.SourcePaths.Add(new FullPath(fileNames[i]));
            }

            return(Compile(parameters, options));
        }
Пример #14
0
        public void RemoteCompile(ref ErrorSink /*!*/ errorSink, CompilationParameters /*!*/ ps)
        {
            lock (buildMutex)             // TODO: do we need thread-safety (if yes, there is a better way)?
            {
                //if (++buildCounter % 10 == 0) // TODO: is it possible to estimate size of memory allocated by the domain?
                //{
                //  // if a referenced assembly gets updated then we should reload the domain as well
                //  AppDomain.Unload(remoteCompiler.Domain);
                //  remoteCompiler = null;
                //}

                if (remoteCompiler != null)
                {
                    AppDomain.Unload(remoteCompiler.Domain);
                }

                remoteCompiler = ApplicationCompiler.CreateRemoteCompiler();

                remoteCompiler.RemoteCompile(ref errorSink, ps);
            }
        }
Пример #15
0
        /// <summary>
        /// Compiles an assembly from the specified array of strings containing source code, using the specified compiler settings.
        /// </summary>
        public CompilerResults /*!*/ CompileAssemblyFromSourceBatch(CompilerParameters /*!*/ options, string[] /*!*/ sources)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (sources == null)
            {
                throw new ArgumentNullException("sources");
            }

            CompilationParameters parameters = new CompilationParameters();

            throw new NotImplementedException();

            //for (int i = 0; i < sources.Length; i++)
            //{
            //     //parameters.SourceReaders.Add(new StringReader(sources[i]));
            //}

            //return Compile(parameters, options);
        }
Пример #16
0
        /// <summary>
        /// Compiles an assembly based on the <see cref="System.CodeDom"/> trees contained in the specified array of
        /// <see cref="CodeCompileUnit"/> objects, using the specified compiler settings.
        /// </summary>
        public CompilerResults /*!*/ CompileAssemblyFromDomBatch(CompilerParameters /*!*/ options, CodeCompileUnit[] /*!*/ compilationUnits)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (compilationUnits == null)
            {
                throw new ArgumentNullException("compilationUnits");
            }

            CompilationParameters parameters = new CompilationParameters();

            throw new NotImplementedException();

            //for (int i = 0; i < compilationUnits.Length; i++)
            //{
            //    parameters.SourceReaders.Add(GenerateCompilationUnit(compilationUnits[i]));
            //    ResolveReferencedAssemblies(options, compilationUnits[i]);
            //}

            //return Compile(parameters, options);
        }
Пример #17
0
        /// <summary>
        /// Performs the compilation.
        /// </summary>
        /// <param name="parameters">Parameters that already contain the source files/streams to compile.</param>
        /// <param name="options">The options specified by CodeCom user.</param>
        /// <returns>The compiler results.</returns>
        private CompilerResults /*!*/ Compile(CompilationParameters /*!*/ parameters, CompilerParameters /*!*/ options)
        {
            // translate options to parameters
            SetupCompilerParameters(parameters, options);

            // set up compiler results
            CompilerResults  results    = new CompilerResults(options.TempFiles); // J: SecurityAction.LinkDemand, "FullTrust"
            CodeDomErrorSink error_sink = new CodeDomErrorSink(results);

            results.Output.Add("Phalanger - the PHP Language Compiler - commencing compilation in a separate appdomain");
            results.Output.Add("Source files to compile:");
            for (int i = 0; i < parameters.SourcePaths.Count; i++)
            {
                results.Output.Add(parameters.SourcePaths[i].ToString());
            }

            // compile the files/streams in a separate appdomain
            AppCompilerStack.Compile(error_sink, parameters);

            // set up the compiler results
            results.PathToAssembly            = parameters.OutPath.ToString();
            results.NativeCompilerReturnValue = (results.Errors.HasErrors ? 1 : 0);

            // J: obsolete, FullTrust demanded earlier
            //new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Assert();
            //try
            //{
            //    results.Evidence = options.Evidence;   // J: SecurityAction.LinkDemand, "FullTrust" // same as CompilerResults above
            //}
            //finally
            //{
            //    CodeAccessPermission.RevertAssert();
            //}

            return(results);
        }
Пример #18
0
		/// <summary>
		/// Sets up <paramref name="parameters"/> according to the supplied <paramref name="options"/>.
		/// </summary>
		/// <param name="parameters">The parameters to set up.</param>
		/// <param name="options">The options passed to CodeDom.</param>
		private void SetupCompilerParameters(CompilationParameters/*!*/ parameters, CompilerParameters/*!*/ options)
		{
			parameters.Target = (options.GenerateExecutable ? ApplicationCompiler.Targets.Console : ApplicationCompiler.Targets.Dll);
			parameters.Debuggable = options.IncludeDebugInformation;
			parameters.SourceRoot = DetermineSourceRoot(parameters);

			if (!String.IsNullOrEmpty(options.OutputAssembly))
			{
				parameters.OutPath = new FullPath(options.OutputAssembly);
			}

			// referenced assemblies
			foreach (string reference in options.ReferencedAssemblies)
			{
                parameters.References.Add(new CompilationParameters.ReferenceItem() { Reference = reference });
			}

			// referenced resource files
			foreach (string resource in options.LinkedResources)
			{
				parameters.Resources.Add(new FileReference(resource));
			}

			parameters.Pure = true;

			// parse user-provided compiler options
			if (!String.IsNullOrEmpty(options.CompilerOptions))
			{
				CommandLineParser parser = new CommandLineParser(parameters);
				parser.Parse(CommandLineParser.StringToArgumentList(options.CompilerOptions));
			}
		}
Пример #19
0
		/// <summary>
		/// Determines the source root for a compilation based on the source file paths and output path.
		/// </summary>
		/// <param name="parameters">The parameters describing source files and the output file.</param>
		/// <returns>A suitable source root, preferrably a common superdirectory of all sources.</returns>
		private FullPath DetermineSourceRoot(CompilationParameters/*!*/ parameters)
		{
			// try to obtain a common superdirectory of all source files
			if (parameters.SourcePaths.Count > 0 && parameters.SourcePaths[0].DirectoryExists)
			{
				CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
				string result = Path.GetDirectoryName(parameters.SourcePaths[0].ToString());

				for (int i = 1; i < parameters.SourcePaths.Count; i++)
				{
					string path = parameters.SourcePaths[i].ToString();

					int limit = Math.Min(result.Length, path.Length);
					int index = -1;

					for (int j = 0; j < limit; j++)
					{
						// remember the last directory separator position
						if (result[j] == Path.DirectorySeparatorChar) index = j;

						if (Char.ToLower(result[j], culture) != Char.ToLower(path[j], culture))
						{
							if (index >= 0) result = result.Substring(0, index);
							else result = null;
						}
					}

					if (result == null) break;
				}

				if (result != null) return new FullPath(result);
			}

			// otherwise the output directory
			if (!parameters.OutPath.IsEmpty)
			{
				return new FullPath(Path.GetDirectoryName(parameters.OutPath.ToString()));
			}

			// otherwise fall back to default
			return new FullPath(Environment.SystemDirectory);
		}
Пример #20
0
		/// <summary>
		/// Compiles an assembly from the specified array of strings containing source code, using the specified compiler settings.
		/// </summary>
		public CompilerResults/*!*/ CompileAssemblyFromSourceBatch(CompilerParameters/*!*/ options, string[]/*!*/ sources)
		{
			if (options == null) throw new ArgumentNullException("options");
			if (sources == null) throw new ArgumentNullException("sources");

			CompilationParameters parameters = new CompilationParameters();

            throw new NotImplementedException();

            //for (int i = 0; i < sources.Length; i++)
            //{
            //     //parameters.SourceReaders.Add(new StringReader(sources[i]));
            //}

            //return Compile(parameters, options);
		}
Пример #21
0
		/// <summary>
		/// Performs the compilation.
		/// </summary>
		/// <param name="parameters">Parameters that already contain the source files/streams to compile.</param>
		/// <param name="options">The options specified by CodeCom user.</param>
		/// <returns>The compiler results.</returns>
		private CompilerResults/*!*/ Compile(CompilationParameters/*!*/ parameters, CompilerParameters/*!*/ options)
		{
			// translate options to parameters
			SetupCompilerParameters(parameters, options);

			// set up compiler results
            CompilerResults results = new CompilerResults(options.TempFiles);   // J: SecurityAction.LinkDemand, "FullTrust"
			CodeDomErrorSink error_sink = new CodeDomErrorSink(results);

			results.Output.Add("Phalanger - the PHP Language Compiler - commencing compilation in a separate appdomain");
			results.Output.Add("Source files to compile:");
			for (int i = 0; i < parameters.SourcePaths.Count; i++)
			{
				results.Output.Add(parameters.SourcePaths[i].ToString());
			}

			// compile the files/streams in a separate appdomain
			AppCompilerStack.Compile(error_sink, parameters);

			// set up the compiler results
			results.PathToAssembly = parameters.OutPath.ToString();
			results.NativeCompilerReturnValue = (results.Errors.HasErrors ? 1 : 0);

            // J: obsolete, FullTrust demanded earlier
            //new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Assert();
            //try
            //{
            //    results.Evidence = options.Evidence;   // J: SecurityAction.LinkDemand, "FullTrust" // same as CompilerResults above
            //}
            //finally
            //{
            //    CodeAccessPermission.RevertAssert();
            //}

			return results;
		}
Пример #22
0
		/// <summary>
		/// Compiles an assembly from the source code contained within the specified files, using the specified compiler settings.
		/// </summary>
		public CompilerResults/*!*/ CompileAssemblyFromFileBatch(CompilerParameters/*!*/ options, string[]/*!*/ fileNames)
		{
			if (options == null) throw new ArgumentNullException("options");
			if (fileNames == null) throw new ArgumentNullException("fileNames");

			CompilationParameters parameters = new CompilationParameters();
			for (int i = 0; i < fileNames.Length; i++)
			{
				parameters.SourcePaths.Add(new FullPath(fileNames[i]));
			}

			return Compile(parameters, options);
		}
Пример #23
0
		/// <summary>
		/// Compiles an assembly from the specified string containing source code, using the specified compiler settings.
		/// </summary>
		public CompilerResults/*!*/ CompileAssemblyFromSource(CompilerParameters/*!*/ options, string/*!*/ source)
		{
			if (options == null) throw new ArgumentNullException("options");
			if (source == null) throw new ArgumentNullException("source");

			CompilationParameters parameters = new CompilationParameters();
			throw new NotImplementedException(); //parameters.SourceReaders.Add(new StringReader(source));

			//return Compile(parameters, options);
		}
Пример #24
0
		/// <summary>
		/// Compiles an assembly based on the <see cref="System.CodeDom"/> trees contained in the specified array of
		/// <see cref="CodeCompileUnit"/> objects, using the specified compiler settings.
		/// </summary>
		public CompilerResults/*!*/ CompileAssemblyFromDomBatch(CompilerParameters/*!*/ options, CodeCompileUnit[]/*!*/ compilationUnits)
		{
			if (options == null) throw new ArgumentNullException("options");
			if (compilationUnits == null) throw new ArgumentNullException("compilationUnits");

			CompilationParameters parameters = new CompilationParameters();

            throw new NotImplementedException();

            //for (int i = 0; i < compilationUnits.Length; i++)
            //{
            //    parameters.SourceReaders.Add(GenerateCompilationUnit(compilationUnits[i]));
            //    ResolveReferencedAssemblies(options, compilationUnits[i]);
            //}

            //return Compile(parameters, options);
		}
Пример #25
0
		/// <summary>
		/// Compiles an assembly from the source code contained within the specified file, using the specified compiler settings.
		/// </summary>
		public CompilerResults/*!*/ CompileAssemblyFromFile(CompilerParameters/*!*/ options, string/*!*/ fileName)
		{
			if (options == null) throw new ArgumentNullException("options");
			if (fileName == null) throw new ArgumentNullException("fileName");

			CompilationParameters parameters = new CompilationParameters();
			parameters.SourcePaths.Add(new FullPath(fileName));

			return Compile(parameters, options);
		}
Пример #26
0
 public void AddAssemblyReference(Type type)
 {
     CompilationParameters.AddAssemblyReference(type.Assembly.Location);
 }
Пример #27
0
		/// <summary>
		/// Compiles an assembly from the <see cref="System.CodeDom"/> tree contained in the specified
		/// <see cref="CodeCompileUnit"/>, using the specified compiler settings. 
		/// </summary>
		public CompilerResults/*!*/ CompileAssemblyFromDom(CompilerParameters/*!*/ options, CodeCompileUnit/*!*/ compilationUnit)
		{
			if (options == null) throw new ArgumentNullException("options");
			if (compilationUnit == null) throw new ArgumentNullException("compilationUnit");

			CompilationParameters parameters = new CompilationParameters();
			throw new NotImplementedException(); //parameters.SourceReaders.Add(GenerateCompilationUnit(compilationUnit));
            //ResolveReferencedAssemblies(options, compilationUnit);

            //return Compile(parameters, options);
		}
Пример #28
0
 public void UpdateWithoutDefinesRemovesExistingOnes()
 {
     CompilationParameters.AddDefineSymbol("UNITY_EDITOR");
     DoUpdate();
     Assert.IsFalse(CompilationParameters.HasDefineSymbol("UNITY_EDITOR"));
 }
Пример #29
0
 public void AddAssemblyReference(Assembly assembly)
 {
     CompilationParameters.AddAssemblyReference(assembly.Location);
 }
Пример #30
0
 public void AddAssemblyReference(string location)
 {
     CompilationParameters.AddAssemblyReference(location);
 }
 public static Task<IFunctionalNamespace[]> ParseCompilationUnitsAsync(List<IProjectSourceItem> SourceItems, CompilationParameters Parameters, IBinder Binder, IAssembly DeclaringAssembly, MacroProcessor Processor, IMessageSink Sink)
 {
     var units = new Task<IFunctionalNamespace>[SourceItems.Count];
     for (int i = 0; i < units.Length; i++)
     {
         var item = SourceItems[i];
         units[i] = ParseCompilationUnitAsync(item, Parameters, Binder, DeclaringAssembly, Processor, Sink);
     }
     return Task.WhenAll(units);
 }
Пример #32
0
 public SourceFile(ISourceDocument Document, CompilationParameters Parameters)
 {
     this.Document   = Document;
     this.Parameters = Parameters;
 }
Пример #33
0
 public static Task <CompilationUnit> ParseCompilationUnitAsync(IProjectSourceItem SourceItem, SyntaxAssembly Assembly, CompilationParameters Parameters)
 {
     Parameters.Log.LogEvent(new LogEntry("Status", "parsing " + SourceItem.SourceIdentifier));
     return(Task.Run(() =>
     {
         var code = GetSourceSafe(SourceItem, Parameters);
         if (code == null)
         {
             return null;
         }
         var parser = Preprocess(code, Parameters);
         var unit = ParseCompilationUnit(parser, Assembly);
         Parameters.Log.LogEvent(new LogEntry("Status", "parsed " + SourceItem.SourceIdentifier));
         return unit;
     }));
 }
        public static Task<IFunctionalNamespace[]> ParseCompilationUnitsAsync(List<IProjectSourceItem> SourceItems, CompilationParameters Parameters, IBinder Binder, IAssembly DeclaringAssembly)
        {
            var sink = new CompilerLogMessageSink(Parameters.Log);
            var processor = new MacroProcessor(typeof(LeMP.Prelude.BuiltinMacros), sink);

            processor.AddMacros(typeof(global::LeMP.StandardMacros).Assembly, false);

            return ParseCompilationUnitsAsync(SourceItems, Parameters, Binder, DeclaringAssembly, processor, sink);
        }
Пример #35
0
 public static Task ParseCompilationUnitsAsync(List <IProjectSourceItem> SourceItems, SyntaxAssembly Assembly, CompilationParameters Parameters)
 {
     Task[] units = new Task[SourceItems.Count];
     for (int i = 0; i < units.Length; i++)
     {
         var item = SourceItems[i];
         units[i] = ParseCompilationUnitAsync(item, Assembly, Parameters);
     }
     return(Task.WhenAll(units));
 }
Пример #36
0
 public IncludeConfiguration(string DirectoryPath, CompilationParameters Parameters)
 {
     this.DirectoryPath = DirectoryPath;
     this.Parameters    = Parameters;
 }
Пример #37
0
 public void UpdateWithNewDefinesGetsAdopted()
 {
     _update.Defines.Add("UNITY_EDITOR");
     DoUpdate();
     Assert.IsTrue(CompilationParameters.HasDefineSymbol("UNITY_EDITOR"));
 }
Пример #38
0
			/// <summary>
			/// Compiles in a seperate appdomain utilitizing one of the compilers on the stack.
			/// </summary>
			public static void Compile(ErrorSink/*!*/ errorSink, CompilationParameters/*!*/ ps)
			{
				// obtain a compiler
				StackItem item = new StackItem();
				lock (stack)
				{
					if (stack.Count > 0) item = stack.Pop();
				}
				if (item.Compiler == null) item.Compiler = ApplicationCompiler.CreateRemoteCompiler();

				// compile
				item.Compiler.RemoteCompile(ref errorSink, ps);

				// check whether the separate appdomain is not too weedy
				if (++item.CompileCounter == 1 || item.CompileCounter == compileCounterTreshold)
				{
					item.CompileCounter = 1;

					CallBackDisplay display = new CallBackDisplay();

					// avoid passing the array of assemblies across appdomain boundary
					item.Compiler.Domain.DoCallBack(display.Handler);

					if (item.RemoteAssemblyCount == 0) item.RemoteAssemblyCount = display.AssemblyCount;
					else
					{
						if (display.AssemblyCount > (2 * item.RemoteAssemblyCount))
						{
							AppDomain.Unload(item.Compiler.Domain);
							return;
						}
					}
				}

				// recycle the compiler
				lock (stack) stack.Push(item);
			}
Пример #39
0
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.Normal, "Phalanger Compilation Task");

            CompilationParameters ps = new CompilationParameters();

            // source root (project directory by default):
            ps.SourceRoot = new FullPath(sourceRoot);

            // target type:
            string assembly_extension;

            switch (outputType.ToLowerInvariant())
            {
            case "dll":
            case "library":
                ps.Target          = ApplicationCompiler.Targets.Dll;
                assembly_extension = ".dll";
                break;

            case "exe":
            case "console":
                ps.Target          = ApplicationCompiler.Targets.Console;
                assembly_extension = ".exe";
                break;

            case "winexe":
            case "winapp":
                ps.Target          = ApplicationCompiler.Targets.WinApp;
                assembly_extension = ".exe";
                break;

            case "webapp":
                ps.Target          = ApplicationCompiler.Targets.Web;
                assembly_extension = ".dll";
                // TODO: precompile option
                return(true);

            default:
                Log.LogError("Invalid output type: '{0}'.", outputType);
                return(false);
            }

            if (Path.GetExtension(outputAssembly) != assembly_extension)
            {
                Log.LogError("Output assembly extension doesn't match project type.");
                return(false);
            }

            if (contentFiles != null)
            {
                foreach (string file in contentFiles)
                {
                    if (String.Compare(Path.GetExtension(file), ".config", true) == 0)
                    {
                        ps.ConfigPaths.Add(new FullPath(file, ps.SourceRoot));
                    }
                }
            }

            // debug symbols:
            ps.Debuggable = this.Debug;

            // compilation of executables in debug mode from VisualStudio/MSBuild will produce 32bit assembly to EE working properly
            ps.Force32Bit = this.Debug && assembly_extension.EqualsOrdinalIgnoreCase(".exe");

            // language features:
            ps.Pure = ApplicationCompiler.IsPureUnit(compilationMode);

            if (!String.IsNullOrEmpty(languageFeatures))
            {
                try
                {
                    ps.LanguageFeatures = (Core.LanguageFeatures)Enum.Parse(typeof(Core.LanguageFeatures),
                                                                            languageFeatures, true);
                }
                catch (Exception)
                {
                    Log.LogError("Invalid language features.");
                    return(false);
                }
            }
            else
            {
                ps.LanguageFeatures = (ps.Pure) ? Core.LanguageFeatures.PureModeDefault : Core.LanguageFeatures.Default;
            }

            // source paths:
            GetSourcePaths(ps.SourceRoot, ps.SourcePaths);

            // directories (TODO)
            // ps.SourceDirs
            // extensions (TODO)
            // ps.FileExtensions = null;

            if (ps.SourcePaths.Count == 0 && ps.SourceDirs.Count == 0)
            {
                Log.LogError("No source files to compile.");
                return(false);
            }

            // out path:
            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(outputAssembly));
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
                return(false);
            }

            ps.OutPath = new FullPath(outputAssembly);

            // doc path (TODO):
            ps.DocPath = FullPath.Empty;

            // startup file/class:
            ps.StartupFile = FullPath.Empty;
            // TODO: string startup_class = null;

            if (ps.Target == ApplicationCompiler.Targets.Console || ps.Target == ApplicationCompiler.Targets.WinApp)
            {
                if (ps.Pure)
                {
                    if (!String.IsNullOrEmpty(startupObject))
                    {
                        // TODO: startup_class = startupObject;

                        Log.LogWarning("Startup class is ignored -- the feature is not supported yet.");
                        return(false);
                    }
                    else
                    {
                        // TODO: startup_class = null;
                    }
                }
                else
                {
                    if (String.IsNullOrEmpty(startupObject))
                    {
                        if (ps.SourcePaths.Count > 1)
                        {
                            Log.LogError("The startup file must be specified in the project property pages.");
                            return(false);
                        }
                        else
                        {
                            ps.StartupFile = new FullPath(ps.SourcePaths[0], ps.SourceRoot);
                        }
                    }
                    else
                    {
                        try
                        {
                            ps.StartupFile = new FullPath(startupObject, ps.SourceRoot);
                        }
                        catch (Exception e)
                        {
                            Log.LogErrorFromException(e);
                            return(false);
                        }

                        // startup file is not in the list of compiled files:
                        if (ps.SourcePaths.IndexOf(ps.StartupFile) == -1)
                        {
                            Log.LogError("The startup file specified in the property pages must be included in the project.");
                            return(false);
                        }
                    }
                }
            }

            // icon:
            ps.Icon = null;
            try
            {
                if (applicationIcon != null)
                {
                    ps.Icon = new Win32IconResource(new FullPath(applicationIcon, ps.SourceRoot));
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
                return(false);
            }

            // strong name, version (TODO):
            try
            {
                ps.Version = new Version(1, 0, 0, 0);
                ps.Key     = null;
                if (!string.IsNullOrEmpty(keyFile))
                {
                    using (FileStream file = new FileStream(new FullPath(keyFile, ps.SourceRoot), FileMode.Open, FileAccess.Read))
                        ps.Key = new StrongNameKeyPair(file);
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
                return(false);
            }

            //Resources
            foreach (ITaskItem resource in this.ResourceFiles)
            {
                bool   publicVisibility = true;
                string access           = resource.GetMetadata("Access");
                if (String.CompareOrdinal("Private", access) == 0)
                {
                    publicVisibility = false;
                }
                string filename    = resource.ItemSpec;
                string logicalName = resource.GetMetadata("LogicalName");
                if (String.IsNullOrEmpty(logicalName))
                {
                    logicalName = Path.GetFileName(resource.ItemSpec);
                }
                ps.Resources.Add(new ResourceFileReference(filename, logicalName, publicVisibility));
            }

            // referenced assemblies:

            //if (referencedAssemblies != null)
            if (references != null)
            {
                foreach (ITaskItem assemblyReference in references /*referencedAssemblies*/)
                {
                    // script library root:
                    var scriptLibraryRoot = assemblyReference.GetMetadata("MSARoot");

                    if (scriptLibraryRoot != null)
                    {
                        scriptLibraryRoot = scriptLibraryRoot.Trim();
                    }

                    if (string.IsNullOrEmpty(scriptLibraryRoot))
                    {
                        scriptLibraryRoot = null;
                    }

                    // add the reference to CompilationParameters:
                    ps.References.Add(new CompilationParameters.ReferenceItem()
                    {
                        Reference   = assemblyReference.ItemSpec,
                        LibraryRoot = scriptLibraryRoot
                    });
                }
            }

            // errors, warnings:
            ErrorSink sink = new CompilerErrorSink(this.Log);

            if (!String.IsNullOrEmpty(disabledWarnings))
            {
                try
                {
                    ps.DisableWarningNumbers = ConfigUtils.ParseIntegerList(disabledWarnings, ',', 1, 10000, null);
                }
                catch (Exception)
                {
                    Log.LogError("Invalid list of disabled warnings.");
                    return(false);
                }
            }
            else
            {
                ps.DisableWarningNumbers = ArrayUtils.EmptyIntegers;
            }

            ps.EnableWarnings |= WarningGroups.DeferredToRuntime;   // enable deferred to runtime warnings

            ps.TreatWarningsAsErrors = this.TreatWarningsAsErrors;

            // compile

            try
            {
                //ApplicationCompiler.CompileInSeparateDomain(sink, ps);
                RemoteCompile(ref sink, ps);
            }
            catch (InvalidSourceException e)
            {
                e.Report(sink);
                return(false);
            }
            catch (Exception e)
            {
                sink.AddInternalError(e);
                return(false);
            }

            return(!sink.AnyError);
        }
        public static Task<IFunctionalNamespace> ParseCompilationUnitAsync(IProjectSourceItem SourceItem, CompilationParameters Parameters, IBinder Binder, IAssembly DeclaringAssembly, MacroProcessor Processor, IMessageSink Sink)
        {
            Parameters.Log.LogEvent(new LogEntry("Status", "Parsing " + SourceItem.SourceIdentifier));
            return Task.Run(() =>
            {
                var code = ProjectHandlerHelpers.GetSourceSafe(SourceItem, Parameters);
                if (code == null)
                {
                    return null;
                }
                var namer = ECSharpTypeNamer.Instance;
                var convRules = DefaultConversionRules.Create(namer.Convert);
                var globalScope = new GlobalScope(new FunctionalBinder(Binder), convRules, Parameters.Log, namer, new Flame.Syntax.MemberProvider(Binder).GetMembers, GetParameters);
                bool isLes = Enumerable.Last(SourceItem.SourceIdentifier.Split('.')).Equals("les", StringComparison.OrdinalIgnoreCase);
                var service = isLes ? (IParsingService)LesLanguageService.Value : EcsLanguageService.Value;
                var nodes = ParseNodes(code.Source, SourceItem.SourceIdentifier, service, Processor, Sink);

                if (Parameters.Log.Options.GetOption<bool>("E", false))
                {
                    var outputService = GetParsingService(Parameters.Log.Options, "syntax-format", service);
                    string newFile = outputService.Print(nodes, Sink, indentString: new string(' ', 4));
                    Parameters.Log.LogMessage(new LogEntry("'" + SourceItem.SourceIdentifier + "' after macro expansion", Environment.NewLine + newFile));
                }

                var unit = ParseCompilationUnit(nodes, globalScope, DeclaringAssembly);
                Parameters.Log.LogEvent(new LogEntry("Status", "Parsed " + SourceItem.SourceIdentifier));
                return unit;
            });
        }