New test.
[mono.git] / mcs / class / Cscompmgd / Microsoft.CSharp / Compiler.cs
1 // Microsoft.CSharp.Compiler
2 //
3 // Author(s):
4 //  Jackson Harper (Jackson@LatitudeGeo.com)
5 //
6 // (C) 2002 Jackson Harper, All rights reserved.
7 //
8
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.IO;
32 using System.Text;
33 using System.Collections;
34 using System.Diagnostics;
35 using System.Text.RegularExpressions;
36
37 namespace Microsoft.CSharp {
38
39 #if NET_2_0
40         [System.Obsolete]
41 #endif
42         public class Compiler {
43                 
44                 private Compiler()
45                 {
46                 }
47
48                 [MonoTODO("Have not implemented bugreports")]
49                 public static CompilerError[] Compile(string[] sourceTexts,
50                         string[] sourceTextNames, string target, string[] imports,
51                         IDictionary options)
52                 {
53                         VerifyArgs (sourceTexts, sourceTextNames, target);
54                         
55                         string[] temp_cs_files;
56                         CompilerError[] errors;
57                         string bugreport_path = null;   
58                         StreamWriter bug_report = null;
59                         
60                         temp_cs_files = CreateCsFiles (sourceTexts, sourceTextNames);
61                         
62                         if (options != null)
63                                 bugreport_path = (string)options["bugreport"];  
64                         
65                         if (bugreport_path != null) {
66                                 bug_report = CreateBugReport (sourceTexts, sourceTextNames, bugreport_path);
67                         }                       
68
69                         try {
70                                 errors = CompileFiles (temp_cs_files, target, imports, options, bug_report);
71                         } catch {
72                                 throw;
73                         } finally {
74                                 foreach (string temp_file in temp_cs_files) {
75                                         FileInfo file = new FileInfo (temp_file);
76                                         file.Delete ();
77                                 }
78                                 if (bug_report != null)
79                                         bug_report.Close ();
80                         }
81                         
82                         return errors;
83                 }
84                 
85                 //
86                 // Private Methods
87                 //
88
89                 private static CompilerError[] CompileFiles (string[] cs_files,
90                         string target, string[] imports, IDictionary options, StreamWriter bug_report) 
91                 {
92                         ArrayList error_list = new ArrayList ();
93                         Process mcs = new Process ();
94                         string mcs_output;
95                         string[] mcs_output_lines;
96
97                         mcs.StartInfo.FileName = "mcs";
98                         mcs.StartInfo.Arguments = BuildArgs (cs_files, 
99                                 target, imports, options);
100                         mcs.StartInfo.CreateNoWindow = true;
101                         mcs.StartInfo.UseShellExecute = false;
102                         mcs.StartInfo.RedirectStandardOutput = true;
103                         mcs.StartInfo.RedirectStandardError = true;
104
105                         try {
106                                 mcs.Start ();
107                                 mcs_output = mcs.StandardError.ReadToEnd ();
108                                 mcs.StandardOutput.ReadToEnd ();
109                                 mcs.WaitForExit ();
110                         } finally {
111                                 mcs.Close ();
112                         }
113                         
114                         mcs_output_lines = mcs_output.Split (
115                                 System.Environment.NewLine.ToCharArray ());
116                         foreach (string error_line in mcs_output_lines) {
117                                 CompilerError error = CreateErrorFromString (error_line);
118                                 if (null != error)
119                                         error_list.Add (error); 
120                         }
121                         
122                         if (bug_report != null) {
123                                 bug_report.WriteLine ("### Compiler Output");
124                                 bug_report.Write (mcs_output);
125                         }
126
127                         return (CompilerError[])error_list.ToArray (typeof(CompilerError));
128                 }
129
130                 /// <summary>
131                 ///   Converts an error string into a CompilerError object
132                 ///   Return null if the line was not an error string
133                 /// </summary>
134                 private static CompilerError CreateErrorFromString(string error_string) 
135                 {
136                         CompilerError error = new CompilerError();
137                         Regex reg = new Regex (@"^((?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)\s){0,}(?<level>\w+)\sCS(?<number>\d*):\s(?<message>.*)", 
138                         RegexOptions.Compiled | RegexOptions.ExplicitCapture);
139
140                         Match match = reg.Match (error_string);
141                         
142                         if (!match.Success)
143                                 return null;
144                         
145                         if (String.Empty != match.Result ("${file}"))
146                                 error.SourceFile = match.Result ("${file}");
147                         if (String.Empty != match.Result ("${line}"))
148                                 error.SourceLine = Int32.Parse (match.Result ("${line}"));
149                         if (String.Empty != match.Result ("${column}"))
150                                 error.SourceColumn = Int32.Parse (match.Result ("${column}"));
151                         error.ErrorLevel = (ErrorLevel)Enum.Parse (typeof(ErrorLevel),
152                                 match.Result ("${level}"), true);
153                         error.ErrorNumber = Int32.Parse (match.Result ("${number}"));
154                         error.ErrorMessage = match.Result ("${message}");
155                         
156                         return error;
157                 }
158
159                 private static string[] CreateCsFiles (string[] source_text, string[] source_name) 
160                 {
161                         ArrayList temp_file_list = new ArrayList ();
162
163                         for (int i=0; i<source_text.Length; i++) {
164                                 string temp_path = Path.GetTempFileName ();
165                                 StreamWriter writer = null;
166                                 try {
167                                         writer = new StreamWriter (temp_path);
168                                         writer.WriteLine (String.Format ("#line 1 \"{0}\"", 
169                                                 source_name[i]));
170                                         writer.Write (source_text[i]);
171                                 } catch {
172                                 } finally {
173                                         if (writer != null)
174                                                 writer.Close ();
175                                 }
176                                 temp_file_list.Add (temp_path);
177                         }
178                 
179                         return (string[])temp_file_list.ToArray (typeof(string));       
180                 }
181
182                 private static string BuildArgs(string[] source_files,
183                         string target, string[] imports, IDictionary options)
184                 {
185                         StringBuilder args = new StringBuilder ();
186
187                         args.AppendFormat ("/out:{0} ", target);
188                         
189                         if (null != imports) {
190                                 foreach (string import in imports)
191                                         args.AppendFormat ("/r:{0} ", import);
192                         }
193                         
194                         if (null != options) {
195                                 foreach (object option in options.Keys) {
196                                         object value = options[option];
197                                         if (!ValidOption ((string)option))
198                                                 continue;
199                                         args.AppendFormat ("{0} ", OptionString (option,value));
200                                 }
201                         }
202                         
203                         foreach (string source in source_files)
204                                 args.AppendFormat ("{0} ", source);
205
206                         return args.ToString ();
207                 }
208
209                 private static string OptionString(object option, object value)
210                 {
211                         if (null != value)
212                                 return String.Format ("/{0}:{1}", option, value);
213                         
214                         return String.Format("/{0}", option);
215                 }
216
217                 private static void VerifyArgs (string[] sourceTexts,
218                         string[] sourceTextNames, string target)
219                 {
220                         if (null == sourceTexts)
221                                 throw new ArgumentNullException ("sourceTexts");
222                         if (null == sourceTextNames)
223                                 throw new ArgumentNullException ("sourceTextNames");
224                         if (null == target)
225                                 throw new ArgumentNullException ("target");
226
227                         if (sourceTexts.Length <= 0 || sourceTextNames.Length <= 0)
228                                 throw new IndexOutOfRangeException ();
229                 }
230
231                 private static StreamWriter CreateBugReport (string[] source_texts, 
232                         string[] source_names, string path)
233                 {
234                         StreamWriter bug_report = null;
235
236                         try {
237                                 bug_report = new StreamWriter (path);
238                                 bug_report.WriteLine ("### C# Compiler Defect Report," + 
239                                         " created {0}", DateTime.Now);
240                                 // Compiler Version
241                                 // Runtime
242                                 // Operating System
243                                 // Username
244                                 for (int i=0; i<source_texts.Length; i++) {
245                                         bug_report.WriteLine ("### Source file: '{0}'",
246                                                 source_names[i]);
247                                         bug_report.Write (source_texts[i]);
248                                 }
249                         } catch {
250                                 if (bug_report != null)
251                                         bug_report.Close ();
252                                 throw;
253                         }
254                         
255                         return bug_report;
256                 }
257
258
259                 private static bool ValidOption (string option)
260                 {
261                         switch (option) {
262                                 case "addmodule":
263                                 case "baseaddress":
264                                 case "checked":
265                                 case "d":
266                                 case "debug":
267                                 case "doc":
268                                 case "filealign":
269                                 case "incr":
270                                 case "lib":
271                                 case "linkres":
272                                 case "m":
273                                 case "nostdlib":
274                                 case "nowarn":
275                                 case "o":
276                                 case "r":
277                                 case "res":
278                                 case "target":
279                                 case "unsafe":
280                                 case "w":
281                                 case "warnaserror":
282                                 case "win32icon":
283                                 case "win32res":
284                                         return true;
285                         }
286                         return false;
287                 }
288
289         }
290
291 }
292