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