Merge pull request #1082 from esdrubal/bug19287
[mono.git] / mcs / mcs / report.cs
1 //
2 // report.cs: report errors and warnings.
3 //
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 //         Marek Safar (marek.safar@gmail.com)         
6 //
7 // Copyright 2001 Ximian, Inc. (http://www.ximian.com)
8 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9 //
10
11 using System;
12 using System.IO;
13 using System.Text;
14 using System.Collections.Generic;
15 using System.Diagnostics;
16
17 namespace Mono.CSharp {
18
19         //
20         // Errors and warnings manager
21         //
22         public class Report
23         {
24                 public const int RuntimeErrorId = 10000;
25
26                 Dictionary<int, WarningRegions> warning_regions_table;
27
28                 ReportPrinter printer;
29
30                 int reporting_disabled;
31
32                 readonly CompilerSettings settings;
33                 
34                 /// <summary>
35                 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
36                 /// </summary>
37                 List<string> extra_information = new List<string> ();
38
39                 // 
40                 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
41                 //
42                 public static readonly int[] AllWarnings = new int[] {
43                         28, 67, 78,
44                         105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
45                         219, 251, 252, 253, 278, 282,
46                         402, 414, 419, 420, 429, 436, 437, 440, 458, 464, 465, 467, 469, 472, 473,
47                         612, 618, 626, 628, 642, 649, 652, 657, 658, 659, 660, 661, 665, 672, 675, 693,
48                         728,
49                         809, 824,
50                         1030, 1058, 1060, 1066,
51                         1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
52                         1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1697, 1699,
53                         1700, 1701, 1702, 1709, 1711, 1717, 1718, 1720, 1735,
54                         1901, 1956, 1981, 1998,
55                         2002, 2023, 2029,
56                         3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
57                         3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
58                         3021, 3022, 3023, 3024, 3026, 3027,
59                         4014, 4024, 4025, 4026,
60                         7035, 7080, 7081, 7082, 7095,
61                         8009,
62                 };
63
64                 static HashSet<int> AllWarningsHashSet;
65
66                 public Report (CompilerContext context, ReportPrinter printer)
67                 {
68                         if (context == null)
69                                 throw new ArgumentNullException ("settings");
70                         if (printer == null)
71                                 throw new ArgumentNullException ("printer");
72
73                         this.settings = context.Settings;
74                         this.printer = printer;
75                 }
76
77                 public void DisableReporting ()
78                 {
79                         ++reporting_disabled;
80                 }
81
82                 public void EnableReporting ()
83                 {
84                         --reporting_disabled;
85                 }
86
87                 public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
88                 {
89                         string version;
90                         switch (compiler.Settings.Version) {
91                         case LanguageVersion.ISO_1:
92                                 version = "1.0";
93                                 break;
94                         case LanguageVersion.ISO_2:
95                                 version = "2.0";
96                                 break;
97                         case LanguageVersion.V_3:
98                                 version = "3.0";
99                                 break;
100                         case LanguageVersion.V_4:
101                                 version = "4.0";
102                                 break;
103                         case LanguageVersion.V_5:
104                                 version = "5.0";
105                                 break;
106                         default:
107                                 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
108                         }
109
110                         Error (1644, loc,
111                                 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
112                                       feature, version);
113                 }
114
115                 public void FeatureIsNotSupported (Location loc, string feature)
116                 {
117                         Error (1644, loc,
118                                 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
119                                 feature);
120                 }
121                         
122                 public void RuntimeMissingSupport (Location loc, string feature) 
123                 {
124                         Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
125                 }
126
127                 /// <summary>
128                 /// In most error cases is very useful to have information about symbol that caused the error.
129                 /// Call this method before you call Report.Error when it makes sense.
130                 /// </summary>
131                 public void SymbolRelatedToPreviousError (Location loc, string symbol)
132                 {
133                         SymbolRelatedToPreviousError (loc.ToString ());
134                 }
135
136                 public void SymbolRelatedToPreviousError (MemberSpec ms)
137                 {
138                         if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
139                                 return;
140
141                         var mc = ms.MemberDefinition as MemberCore;
142                         while (ms is ElementTypeSpec) {
143                                 ms = ((ElementTypeSpec) ms).Element;
144                                 mc = ms.MemberDefinition as MemberCore;
145                         }
146
147                         if (mc != null) {
148                                 SymbolRelatedToPreviousError (mc);
149                         } else {
150                                 if (ms.DeclaringType != null)
151                                         ms = ms.DeclaringType;
152
153                                 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
154                                 if (imported_type != null) {
155                                         var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
156                                         SymbolRelatedToPreviousError (iad.Location);
157                                 }
158                         }
159                 }
160
161                 public void SymbolRelatedToPreviousError (MemberCore mc)
162                 {
163                         SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
164                 }
165
166                 public void SymbolRelatedToPreviousError (string loc)
167                 {
168                         string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
169                         if (extra_information.Contains (msg))
170                                 return;
171
172                         extra_information.Add (msg);
173                 }
174
175                 public bool CheckWarningCode (int code, Location loc)
176                 {
177                         if (AllWarningsHashSet == null)
178                                 AllWarningsHashSet = new HashSet<int> (AllWarnings);
179
180                         if (AllWarningsHashSet.Contains (code))
181                                 return true;
182
183                         Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
184                         return false;
185                 }
186
187                 public void ExtraInformation (Location loc, string msg)
188                 {
189                         extra_information.Add (String.Format ("{0} {1}", loc, msg));
190                 }
191
192                 public WarningRegions RegisterWarningRegion (Location location)
193                 {
194                         WarningRegions regions;
195                         if (warning_regions_table == null) {
196                                 regions = null;
197                                 warning_regions_table = new Dictionary<int, WarningRegions> ();
198                         } else {
199                                 warning_regions_table.TryGetValue (location.File, out regions);
200                         }
201
202                         if (regions == null) {
203                                 regions = new WarningRegions ();
204                                 warning_regions_table.Add (location.File, regions);
205                         }
206
207                         return regions;
208                 }
209
210                 public void Warning (int code, int level, Location loc, string message)
211                 {
212                         if (reporting_disabled > 0)
213                                 return;
214
215                         if (!settings.IsWarningEnabled (code, level))
216                                 return;
217
218                         if (warning_regions_table != null && !loc.IsNull) {
219                                 WarningRegions regions;
220                                 if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
221                                         return;
222                         }
223
224                         AbstractMessage msg;
225                         if (settings.IsWarningAsError (code)) {
226                                 message = "Warning as Error: " + message;
227                                 msg = new ErrorMessage (code, loc, message, extra_information);
228                         } else {
229                                 msg = new WarningMessage (code, loc, message, extra_information);
230                         }
231
232                         extra_information.Clear ();
233                         printer.Print (msg, settings.ShowFullPaths);
234                 }
235
236                 public void Warning (int code, int level, Location loc, string format, string arg)
237                 {
238                         Warning (code, level, loc, String.Format (format, arg));
239                 }
240
241                 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
242                 {
243                         Warning (code, level, loc, String.Format (format, arg1, arg2));
244                 }
245
246                 public void Warning (int code, int level, Location loc, string format, params object[] args)
247                 {
248                         Warning (code, level, loc, String.Format (format, args));
249                 }
250
251                 public void Warning (int code, int level, string message)
252                 {
253                         Warning (code, level, Location.Null, message);
254                 }
255
256                 public void Warning (int code, int level, string format, string arg)
257                 {
258                         Warning (code, level, Location.Null, format, arg);
259                 }
260
261                 public void Warning (int code, int level, string format, string arg1, string arg2)
262                 {
263                         Warning (code, level, Location.Null, format, arg1, arg2);
264                 }
265
266                 public void Warning (int code, int level, string format, params string[] args)
267                 {
268                         Warning (code, level, Location.Null, String.Format (format, args));
269                 }
270
271                 //
272                 // Warnings encountered so far
273                 //
274                 public int Warnings {
275                         get { return printer.WarningsCount; }
276                 }
277
278                 public void Error (int code, Location loc, string error)
279                 {
280                         if (reporting_disabled > 0)
281                                 return;
282
283                         ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
284                         extra_information.Clear ();
285
286                         printer.Print (msg, settings.ShowFullPaths);
287
288                         if (settings.Stacktrace)
289                                 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
290
291                         if (printer.ErrorsCount == settings.FatalCounter)
292                                 throw new FatalException (msg.Text);
293                 }
294
295                 public void Error (int code, Location loc, string format, string arg)
296                 {
297                         Error (code, loc, String.Format (format, arg));
298                 }
299
300                 public void Error (int code, Location loc, string format, string arg1, string arg2)
301                 {
302                         Error (code, loc, String.Format (format, arg1, arg2));
303                 }
304
305                 public void Error (int code, Location loc, string format, params string[] args)
306                 {
307                         Error (code, loc, String.Format (format, args));
308                 }
309
310                 public void Error (int code, string error)
311                 {
312                         Error (code, Location.Null, error);
313                 }
314
315                 public void Error (int code, string format, string arg)
316                 {
317                         Error (code, Location.Null, format, arg);
318                 }
319
320                 public void Error (int code, string format, string arg1, string arg2)
321                 {
322                         Error (code, Location.Null, format, arg1, arg2);
323                 }
324
325                 public void Error (int code, string format, params string[] args)
326                 {
327                         Error (code, Location.Null, String.Format (format, args));
328                 }
329
330                 //
331                 // Errors encountered so far
332                 //
333                 public int Errors {
334                         get { return printer.ErrorsCount; }
335                 }
336
337                 public bool IsDisabled {
338                         get {
339                                 return reporting_disabled > 0;
340                         }
341                 }
342
343                 public ReportPrinter Printer {
344                         get { return printer; }
345                 }
346
347                 public ReportPrinter SetPrinter (ReportPrinter printer)
348                 {
349                         ReportPrinter old = this.printer;
350                         this.printer = printer;
351                         return old;
352                 }
353
354                 [Conditional ("MCS_DEBUG")]
355                 static public void Debug (string message, params object[] args)
356                 {
357                         Debug (4, message, args);
358                 }
359                         
360                 [Conditional ("MCS_DEBUG")]
361                 static public void Debug (int category, string message, params object[] args)
362                 {
363 //                      if ((category & DebugFlags) == 0)
364 //                              return;
365
366                         StringBuilder sb = new StringBuilder (message);
367
368                         if ((args != null) && (args.Length > 0)) {
369                                 sb.Append (": ");
370
371                                 bool first = true;
372                                 foreach (object arg in args) {
373                                         if (first)
374                                                 first = false;
375                                         else
376                                                 sb.Append (", ");
377                                         if (arg == null)
378                                                 sb.Append ("null");
379 //                                      else if (arg is ICollection)
380 //                                              sb.Append (PrintCollection ((ICollection) arg));
381                                         else
382                                                 sb.Append (arg);
383                                 }
384                         }
385
386                         Console.WriteLine (sb.ToString ());
387                 }
388 /*
389                 static public string PrintCollection (ICollection collection)
390                 {
391                         StringBuilder sb = new StringBuilder ();
392
393                         sb.Append (collection.GetType ());
394                         sb.Append ("(");
395
396                         bool first = true;
397                         foreach (object o in collection) {
398                                 if (first)
399                                         first = false;
400                                 else
401                                         sb.Append (", ");
402                                 sb.Append (o);
403                         }
404
405                         sb.Append (")");
406                         return sb.ToString ();
407                 }
408 */
409                 static string FriendlyStackTrace (StackTrace t)
410                 {
411                         StringBuilder sb = new StringBuilder ();
412
413                         bool foundUserCode = false;
414
415                         for (int i = 0; i < t.FrameCount; i++) {
416                                 StackFrame f = t.GetFrame (i);
417                                 var mb = f.GetMethod ();
418
419                                 if (!foundUserCode && mb.ReflectedType == typeof (Report))
420                                         continue;
421
422                                 foundUserCode = true;
423
424                                 sb.Append ("\tin ");
425
426                                 if (f.GetFileLineNumber () > 0)
427                                         sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
428
429                                 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
430
431                                 bool first = true;
432                                 foreach (var pi in mb.GetParameters ()) {
433                                         if (!first)
434                                                 sb.Append (", ");
435                                         first = false;
436
437                                         sb.Append (pi.ParameterType.FullName);
438                                 }
439                                 sb.Append (")\n");
440                         }
441
442                         return sb.ToString ();
443                 }
444         }
445
446         public abstract class AbstractMessage
447         {
448                 readonly string[] extra_info;
449                 protected readonly int code;
450                 protected readonly Location location;
451                 readonly string message;
452
453                 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
454                 {
455                         this.code = code;
456                         if (code < 0)
457                                 this.code = 8000 - code;
458
459                         this.location = loc;
460                         this.message = msg;
461                         if (extraInfo.Count != 0) {
462                                 this.extra_info = extraInfo.ToArray ();
463                         }
464                 }
465
466                 protected AbstractMessage (AbstractMessage aMsg)
467                 {
468                         this.code = aMsg.code;
469                         this.location = aMsg.location;
470                         this.message = aMsg.message;
471                         this.extra_info = aMsg.extra_info;
472                 }
473
474                 public int Code {
475                         get { return code; }
476                 }
477
478                 public override bool Equals (object obj)
479                 {
480                         AbstractMessage msg = obj as AbstractMessage;
481                         if (msg == null)
482                                 return false;
483
484                         return code == msg.code && location.Equals (msg.location) && message == msg.message;
485                 }
486
487                 public override int GetHashCode ()
488                 {
489                         return code.GetHashCode ();
490                 }
491
492                 public abstract bool IsWarning { get; }
493
494                 public Location Location {
495                         get { return location; }
496                 }
497
498                 public abstract string MessageType { get; }
499
500                 public string[] RelatedSymbols {
501                         get { return extra_info; }
502                 }
503
504                 public string Text {
505                         get { return message; }
506                 }
507         }
508
509         sealed class WarningMessage : AbstractMessage
510         {
511                 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
512                         : base (code, loc, message, extra_info)
513                 {
514                 }
515
516                 public override bool IsWarning {
517                         get { return true; }
518                 }
519
520                 public override string MessageType {
521                         get {
522                                 return "warning";
523                         }
524                 }
525         }
526
527         sealed class ErrorMessage : AbstractMessage
528         {
529                 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
530                         : base (code, loc, message, extraInfo)
531                 {
532                 }
533
534                 public ErrorMessage (AbstractMessage aMsg)
535                         : base (aMsg)
536                 {
537                 }
538
539                 public override bool IsWarning {
540                         get { return false; }
541                 }
542
543                 public override string MessageType {
544                         get {
545                                 return "error";
546                         }
547                 }
548         }
549
550         //
551         // Generic base for any message writer
552         //
553         public abstract class ReportPrinter
554         {
555                 protected HashSet<ITypeDefinition> reported_missing_definitions;
556
557                 #region Properties
558
559                 public int ErrorsCount { get; protected set; }
560                 
561                 public int WarningsCount { get; private set; }
562         
563                 //
564                 // When (symbols related to previous ...) can be used
565                 //
566                 public virtual bool HasRelatedSymbolSupport {
567                         get { return true; }
568                 }
569
570                 #endregion
571
572
573                 protected virtual string FormatText (string txt)
574                 {
575                         return txt;
576                 }
577
578                 public virtual void Print (AbstractMessage msg, bool showFullPath)
579                 {
580                         if (msg.IsWarning) {
581                                 ++WarningsCount;
582                         } else {
583                                 ++ErrorsCount;
584                         }
585                 }
586
587                 protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
588                 {
589                         StringBuilder txt = new StringBuilder ();
590                         if (!msg.Location.IsNull) {
591                                 if (showFullPath)
592                                         txt.Append (msg.Location.ToStringFullName ());
593                                 else
594                                         txt.Append (msg.Location.ToString ());
595
596                                 txt.Append (" ");
597                         }
598
599                         txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
600
601                         if (!msg.IsWarning)
602                                 output.WriteLine (FormatText (txt.ToString ()));
603                         else
604                                 output.WriteLine (txt.ToString ());
605
606                         if (msg.RelatedSymbols != null) {
607                                 foreach (string s in msg.RelatedSymbols)
608                                         output.WriteLine (s + msg.MessageType + ")");
609                         }
610                 }
611
612                 //
613                 // Tracks reported missing types. It needs to be session specific 
614                 // because we can run in probing mode
615                 //
616                 public bool MissingTypeReported (ITypeDefinition typeDefinition)
617                 {
618                         if (reported_missing_definitions == null)
619                                 reported_missing_definitions = new HashSet<ITypeDefinition> ();
620
621                         if (reported_missing_definitions.Contains (typeDefinition))
622                                 return true;
623
624                         reported_missing_definitions.Add (typeDefinition);
625                         return false;
626                 }
627
628                 public void Reset ()
629                 {
630                         // HACK: Temporary hack for broken repl flow
631                         ErrorsCount = WarningsCount = 0;
632                 }
633         }
634
635         sealed class NullReportPrinter : ReportPrinter
636         {
637         }
638
639         //
640         // Default message recorder, it uses two types of message groups.
641         // Common messages: messages reported in all sessions.
642         // Merged messages: union of all messages in all sessions. 
643         //
644         // Used by the Lambda expressions to compile the code with various
645         // parameter values, or by attribute resolver
646         //
647         class SessionReportPrinter : ReportPrinter
648         {
649                 List<AbstractMessage> session_messages;
650                 //
651                 // A collection of exactly same messages reported in all sessions
652                 //
653                 List<AbstractMessage> common_messages;
654
655                 //
656                 // A collection of unique messages reported in all sessions
657                 //
658                 List<AbstractMessage> merged_messages;
659
660                 bool showFullPaths;
661
662                 public void ClearSession ()
663                 {
664                         session_messages = null;
665                 }
666
667                 public override void Print (AbstractMessage msg, bool showFullPath)
668                 {
669                         //
670                         // This line is useful when debugging recorded messages
671                         //
672                         // Console.WriteLine ("RECORDING: {0}", msg.Text);
673
674                         if (session_messages == null)
675                                 session_messages = new List<AbstractMessage> ();
676
677                         session_messages.Add (msg);
678
679                         this.showFullPaths = showFullPath;
680                         base.Print (msg, showFullPath);
681                 }
682
683                 public void EndSession ()
684                 {
685                         if (session_messages == null)
686                                 return;
687
688                         //
689                         // Handles the first session
690                         //
691                         if (common_messages == null) {
692                                 common_messages = new List<AbstractMessage> (session_messages);
693                                 merged_messages = session_messages;
694                                 session_messages = null;
695                                 return;
696                         }
697
698                         //
699                         // Store common messages if any
700                         //
701                         for (int i = 0; i < common_messages.Count; ++i) {
702                                 AbstractMessage cmsg = common_messages[i];
703                                 bool common_msg_found = false;
704                                 foreach (AbstractMessage msg in session_messages) {
705                                         if (cmsg.Equals (msg)) {
706                                                 common_msg_found = true;
707                                                 break;
708                                         }
709                                 }
710
711                                 if (!common_msg_found)
712                                         common_messages.RemoveAt (i);
713                         }
714
715                         //
716                         // Merge session and previous messages
717                         //
718                         for (int i = 0; i < session_messages.Count; ++i) {
719                                 AbstractMessage msg = session_messages[i];
720                                 bool msg_found = false;
721                                 for (int ii = 0; ii < merged_messages.Count; ++ii) {
722                                         if (msg.Equals (merged_messages[ii])) {
723                                                 msg_found = true;
724                                                 break;
725                                         }
726                                 }
727
728                                 if (!msg_found)
729                                         merged_messages.Add (msg);
730                         }
731                 }
732
733                 public bool IsEmpty {
734                         get {
735                                 return merged_messages == null && common_messages == null;
736                         }
737                 }
738
739                 //
740                 // Prints collected messages, common messages have a priority
741                 //
742                 public bool Merge (ReportPrinter dest)
743                 {
744                         var messages_to_print = merged_messages;
745                         if (common_messages != null && common_messages.Count > 0) {
746                                 messages_to_print = common_messages;
747                         }
748
749                         if (messages_to_print == null)
750                                 return false;
751
752                         bool error_msg = false;
753                         foreach (AbstractMessage msg in messages_to_print) {
754                                 dest.Print (msg, showFullPaths);
755                                 error_msg |= !msg.IsWarning;
756                         }
757
758                         if (reported_missing_definitions != null) {
759                                 foreach (var missing in reported_missing_definitions)
760                                         dest.MissingTypeReported (missing);
761                         }
762
763                         return error_msg;
764                 }
765         }
766
767         public class StreamReportPrinter : ReportPrinter
768         {
769                 readonly TextWriter writer;
770
771                 public StreamReportPrinter (TextWriter writer)
772                 {
773                         this.writer = writer;
774                 }
775
776                 public override void Print (AbstractMessage msg, bool showFullPath)
777                 {
778                         Print (msg, writer, showFullPath);
779                         base.Print (msg, showFullPath);
780                 }
781         }
782
783         public class ConsoleReportPrinter : StreamReportPrinter
784         {
785                 static readonly string prefix, postfix;
786
787                 static ConsoleReportPrinter ()
788                 {
789                         string term = Environment.GetEnvironmentVariable ("TERM");
790                         bool xterm_colors = false;
791                         
792                         switch (term){
793                         case "xterm":
794                         case "rxvt":
795                         case "rxvt-unicode": 
796                                 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
797                                         xterm_colors = true;
798                                 }
799                                 break;
800
801                         case "xterm-color":
802                         case "xterm-256color":
803                                 xterm_colors = true;
804                                 break;
805                         }
806                         if (!xterm_colors)
807                                 return;
808
809                         if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
810                                 return;
811                         
812                         string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
813                         if (config == null){
814                                 config = "errors=red";
815                                 //config = "brightwhite,red";
816                         }
817
818                         if (config == "disable")
819                                 return;
820
821                         if (!config.StartsWith ("errors="))
822                                 return;
823
824                         config = config.Substring (7);
825                         
826                         int p = config.IndexOf (",");
827                         if (p == -1)
828                                 prefix = GetForeground (config);
829                         else
830                                 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
831                         postfix = "\x001b[0m";
832                 }
833
834                 public ConsoleReportPrinter ()
835                         : base (Console.Error)
836                 {
837                 }
838
839                 public ConsoleReportPrinter (TextWriter writer)
840                         : base (writer)
841                 {
842                 }
843
844                 static int NameToCode (string s)
845                 {
846                         switch (s) {
847                         case "black":
848                                 return 0;
849                         case "red":
850                                 return 1;
851                         case "green":
852                                 return 2;
853                         case "yellow":
854                                 return 3;
855                         case "blue":
856                                 return 4;
857                         case "magenta":
858                                 return 5;
859                         case "cyan":
860                                 return 6;
861                         case "grey":
862                         case "white":
863                                 return 7;
864                         }
865                         return 7;
866                 }
867
868                 //
869                 // maps a color name to its xterm color code
870                 //
871                 static string GetForeground (string s)
872                 {
873                         string highcode;
874
875                         if (s.StartsWith ("bright")) {
876                                 highcode = "1;";
877                                 s = s.Substring (6);
878                         } else
879                                 highcode = "";
880
881                         return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
882                 }
883
884                 static string GetBackground (string s)
885                 {
886                         return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
887                 }
888
889                 protected override string FormatText (string txt)
890                 {
891                         if (prefix != null)
892                                 return prefix + txt + postfix;
893
894                         return txt;
895                 }
896         }
897
898         class TimeReporter
899         {
900                 public enum TimerType
901                 {
902                         ParseTotal,
903                         AssemblyBuilderSetup,
904                         CreateTypeTotal,
905                         ReferencesLoading,
906                         ReferencesImporting,
907                         PredefinedTypesInit,
908                         ModuleDefinitionTotal,
909                         EmitTotal,
910                         CloseTypes,
911                         Resouces,
912                         OutputSave,
913                         DebugSave,
914                 }
915
916                 readonly Stopwatch[] timers;
917                 Stopwatch total;
918
919                 public TimeReporter (bool enabled)
920                 {
921                         if (!enabled)
922                                 return;
923
924                         timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
925                 }
926
927                 public void Start (TimerType type)
928                 {
929                         if (timers != null) {
930                                 var sw = new Stopwatch ();
931                                 timers[(int) type] = sw;
932                                 sw.Start ();
933                         }
934                 }
935
936                 public void StartTotal ()
937                 {
938                         total = new Stopwatch ();
939                         total.Start ();
940                 }
941
942                 public void Stop (TimerType type)
943                 {
944                         if (timers != null) {
945                                 timers[(int) type].Stop ();
946                         }
947                 }
948
949                 public void StopTotal ()
950                 {
951                         total.Stop ();
952                 }
953
954                 public void ShowStats ()
955                 {
956                         if (timers == null)
957                                 return;
958
959                         Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> {
960                                 { TimerType.ParseTotal, "Parsing source files" },
961                                 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
962                                 { TimerType.CreateTypeTotal, "Compiled types created" },
963                                 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
964                                 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
965                                 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
966                                 { TimerType.ModuleDefinitionTotal, "Module definition" },
967                                 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
968                                 { TimerType.CloseTypes, "Module types closed" },
969                                 { TimerType.Resouces, "Embedding resources" },
970                                 { TimerType.OutputSave, "Writing output file" },
971                                 { TimerType.DebugSave, "Writing debug symbols file" },
972                         };
973
974                         int counter = 0;
975                         double percentage = (double) total.ElapsedMilliseconds / 100;
976                         long subtotal = total.ElapsedMilliseconds;
977                         foreach (var timer in timers) {
978                                 string msg = timer_names[(TimerType) counter++];
979                                 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
980                                 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
981                                 subtotal -= ms;
982                         }
983
984                         Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
985                         Console.WriteLine ();
986                         Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
987                 }
988         }
989
990         public class InternalErrorException : Exception {
991                 public InternalErrorException (MemberCore mc, Exception e)
992                         : base (mc.Location + " " + mc.GetSignatureForError (), e)
993                 {
994                 }
995
996                 public InternalErrorException ()
997                         : base ("Internal error")
998                 {
999                 }
1000
1001                 public InternalErrorException (string message)
1002                         : base (message)
1003                 {
1004                 }
1005
1006                 public InternalErrorException (string message, params object[] args)
1007                         : base (String.Format (message, args))
1008                 {
1009                 }
1010
1011                 public InternalErrorException (Exception exception, string message, params object[] args)
1012                         : base (String.Format (message, args), exception)
1013                 {
1014                 }
1015                 
1016                 public InternalErrorException (Exception e, Location loc)
1017                         : base (loc.ToString (), e)
1018                 {
1019                 }
1020         }
1021
1022         class FatalException : Exception
1023         {
1024                 public FatalException (string message)
1025                         : base (message)
1026                 {
1027                 }
1028         }
1029
1030         /// <summary>
1031         /// Handles #pragma warning
1032         /// </summary>
1033         public class WarningRegions {
1034
1035                 abstract class PragmaCmd
1036                 {
1037                         public int Line;
1038
1039                         protected PragmaCmd (int line)
1040                         {
1041                                 Line = line;
1042                         }
1043
1044                         public abstract bool IsEnabled (int code, bool previous);
1045                 }
1046                 
1047                 class Disable : PragmaCmd
1048                 {
1049                         int code;
1050                         public Disable (int line, int code)
1051                                 : base (line)
1052                         {
1053                                 this.code = code;
1054                         }
1055
1056                         public override bool IsEnabled (int code, bool previous)
1057                         {
1058                                 return this.code != code && previous;
1059                         }
1060                 }
1061
1062                 class DisableAll : PragmaCmd
1063                 {
1064                         public DisableAll (int line)
1065                                 : base (line) {}
1066
1067                         public override bool IsEnabled(int code, bool previous)
1068                         {
1069                                 return false;
1070                         }
1071                 }
1072
1073                 class Enable : PragmaCmd
1074                 {
1075                         int code;
1076                         public Enable (int line, int code)
1077                                 : base (line)
1078                         {
1079                                 this.code = code;
1080                         }
1081
1082                         public override bool IsEnabled(int code, bool previous)
1083                         {
1084                                 return this.code == code || previous;
1085                         }
1086                 }
1087
1088                 class EnableAll : PragmaCmd
1089                 {
1090                         public EnableAll (int line)
1091                                 : base (line) {}
1092
1093                         public override bool IsEnabled(int code, bool previous)
1094                         {
1095                                 return true;
1096                         }
1097                 }
1098
1099
1100                 List<PragmaCmd> regions = new List<PragmaCmd> ();
1101
1102                 public void WarningDisable (int line)
1103                 {
1104                         regions.Add (new DisableAll (line));
1105                 }
1106
1107                 public void WarningDisable (Location location, int code, Report Report)
1108                 {
1109                         if (Report.CheckWarningCode (code, location))
1110                                 regions.Add (new Disable (location.Row, code));
1111                 }
1112
1113                 public void WarningEnable (int line)
1114                 {
1115                         regions.Add (new EnableAll (line));
1116                 }
1117
1118                 public void WarningEnable (Location location, int code, CompilerContext context)
1119                 {
1120                         if (!context.Report.CheckWarningCode (code, location))
1121                                 return;
1122
1123                         if (context.Settings.IsWarningDisabledGlobally (code))
1124                                 context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1125
1126                         regions.Add (new Enable (location.Row, code));
1127                 }
1128
1129                 public bool IsWarningEnabled (int code, int src_line)
1130                 {
1131                         bool result = true;
1132                         foreach (PragmaCmd pragma in regions) {
1133                                 if (src_line < pragma.Line)
1134                                         break;
1135
1136                                 result = pragma.IsEnabled (code, result);
1137                         }
1138                         return result;
1139                 }
1140         }
1141 }