2 // CSharpCodeGenerator:
5 // Sean Kasun (seank@users.sf.net)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // Copyright (c) Novell, Inc. (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.CodeDom.Compiler;
35 using System.ComponentModel;
38 using System.Reflection;
39 using System.Diagnostics;
40 using System.Text.RegularExpressions;
41 using System.Threading;
42 using System.Collections.Generic;
43 using System.Globalization;
45 namespace Microsoft.CSharp
47 partial class CSharpCodeGenerator
49 private CompilerResults FromFileBatch (CompilerParameters options, string[] fileNames)
52 throw new ArgumentNullException (nameof(options));
54 if (fileNames == null)
55 throw new ArgumentNullException (nameof(fileNames));
57 CompilerResults results=new CompilerResults(options.TempFiles);
58 Process mcs=new Process();
60 // FIXME: these lines had better be platform independent.
61 if (Path.DirectorySeparatorChar == '\\') {
62 mcs.StartInfo.FileName = MonoToolsLocator.Mono;
63 mcs.StartInfo.Arguments = "\"" + MonoToolsLocator.McsCSharpCompiler + "\" ";
65 mcs.StartInfo.FileName = MonoToolsLocator.McsCSharpCompiler;
68 mcs.StartInfo.Arguments += BuildArgs (options, fileNames, _provOptions);
70 var mcsOutMutex = new Mutex ();
72 string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
74 monoPath = String.Empty;
76 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
77 if (privateBinPath != null && privateBinPath.Length > 0)
78 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
80 if (monoPath.Length > 0) {
81 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
82 if (dict.ContainsKey ("MONO_PATH"))
83 dict ["MONO_PATH"] = monoPath;
85 dict.Add ("MONO_PATH", monoPath);
89 * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
90 * may not handle some of the options causing compilation failure
92 mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;
94 mcs.StartInfo.CreateNoWindow=true;
95 mcs.StartInfo.UseShellExecute=false;
96 mcs.StartInfo.RedirectStandardOutput=true;
97 mcs.StartInfo.RedirectStandardError=true;
98 mcs.ErrorDataReceived += new DataReceivedEventHandler ((sender, args) => {
99 if (args.Data != null) {
100 mcsOutMutex.WaitOne ();
101 results.Output.Add (args.Data);
102 mcsOutMutex.ReleaseMutex ();
106 // Use same text decoder as mcs and not user set values in Console
107 mcs.StartInfo.StandardOutputEncoding =
108 mcs.StartInfo.StandardErrorEncoding = Encoding.UTF8;
112 } catch (Exception e) {
113 Win32Exception exc = e as Win32Exception;
115 throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
116 Win32Exception.GetErrorMessage (exc.NativeErrorCode)));
122 mcs.BeginOutputReadLine ();
123 mcs.BeginErrorReadLine ();
126 results.NativeCompilerReturnValue = mcs.ExitCode;
128 mcs.CancelErrorRead ();
129 mcs.CancelOutputRead ();
134 foreach (string error_line in results.Output) {
135 CompilerError error = CreateErrorFromString (error_line);
137 results.Errors.Add (error);
138 if (!error.IsWarning)
143 if (results.Output.Count > 0) {
144 results.Output.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
148 if (!File.Exists (options.OutputAssembly)) {
149 StringBuilder sb = new StringBuilder ();
150 foreach (string s in results.Output)
151 sb.Append (s + Environment.NewLine);
153 throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
156 if (options.GenerateInMemory) {
157 using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
158 byte[] buffer = new byte[fs.Length];
159 fs.Read(buffer, 0, buffer.Length);
160 results.CompiledAssembly = Assembly.Load(buffer, null);
164 // Avoid setting CompiledAssembly right now since the output might be a netmodule
165 results.PathToAssembly = options.OutputAssembly;
168 results.CompiledAssembly = null;
174 private static string BuildArgs (CompilerParameters options, string[] fileNames, IDictionary<string, string> providerOptions)
176 StringBuilder args=new StringBuilder();
177 if (options.GenerateExecutable)
178 args.Append("/target:exe ");
180 args.Append("/target:library ");
182 string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
183 if (privateBinPath != null && privateBinPath.Length > 0)
184 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
186 if (options.Win32Resource != null)
187 args.AppendFormat("/win32res:\"{0}\" ",
188 options.Win32Resource);
190 if (options.IncludeDebugInformation)
191 args.Append("/debug+ /optimize- ");
193 args.Append("/debug- /optimize+ ");
195 if (options.TreatWarningsAsErrors)
196 args.Append("/warnaserror ");
198 if (options.WarningLevel >= 0)
199 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
201 if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
202 string extension = (options.GenerateExecutable ? "exe" : "dll");
203 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
204 !options.GenerateInMemory);
206 args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
208 foreach (string import in options.ReferencedAssemblies) {
209 if (import == null || import.Length == 0)
212 args.AppendFormat("/r:\"{0}\" ",import);
215 if (options.CompilerOptions != null) {
216 args.Append (options.CompilerOptions);
220 foreach (string embeddedResource in options.EmbeddedResources) {
221 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
224 foreach (string linkedResource in options.LinkedResources) {
225 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
228 if (providerOptions != null && providerOptions.Count > 0) {
231 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
234 if (langver.Length >= 1 && langver [0] == 'v')
235 langver = langver.Substring (1);
239 args.Append ("/langversion:ISO-2 ");
243 // current default, omit the switch
248 args.Append ("/noconfig ");
250 args.Append (" -- ");
251 foreach (string source in fileNames)
252 args.AppendFormat("\"{0}\" ",source);
253 return args.ToString();
256 // Keep in sync with mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
257 const string ErrorRegexPattern = @"
259 (\s*(?<file>[^\(]+) # filename (optional)
260 (\((?<line>\d*)(,(?<column>\d*[\+]*))?\))? # line+column (optional)
262 (?<level>\w+) # error|warning
264 (?<number>[^:]*\d) # CS1234
269 static readonly Regex RelatedSymbolsRegex = new Regex(
271 \(Location\ of\ the\ symbol\ related\ to\ previous\ (warning|error)\)
273 RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
275 private static CompilerError CreateErrorFromString(string error_string)
277 if (error_string.StartsWith ("BETA"))
280 if (error_string == null || error_string == "")
283 CompilerError error=new CompilerError();
284 Regex reg = new Regex (ErrorRegexPattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
285 Match match=reg.Match(error_string);
286 if (!match.Success) {
287 match = RelatedSymbolsRegex.Match (error_string);
288 if (!match.Success) {
289 // We had some sort of runtime crash
290 error.ErrorText = error_string;
291 error.IsWarning = false;
292 error.ErrorNumber = "";
295 // This line is a continuation of previous warning of error
299 if (String.Empty != match.Result("${file}"))
300 error.FileName=match.Result("${file}");
301 if (String.Empty != match.Result("${line}"))
302 error.Line=Int32.Parse(match.Result("${line}"));
303 if (String.Empty != match.Result("${column}"))
304 error.Column=Int32.Parse(match.Result("${column}").Trim('+'));
306 string level = match.Result ("${level}");
307 if (level == "warning")
308 error.IsWarning = true;
309 else if (level != "error")
310 return null; // error CS8028 will confuse the regex.
312 error.ErrorNumber=match.Result("${number}");
313 error.ErrorText=match.Result("${message}");
317 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
319 return temp_files.AddExtension (extension, keepFile);