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