2007-06-06 Amit Biswas <amit@amitbiswas.com>
[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@seznam.cz)         
6 //
7 // (C) 2001 Ximian, Inc. (http://www.ximian.com)
8 //
9
10 using System;
11 using System.IO;
12 using System.Text;
13 using System.Collections;
14 using System.Collections.Specialized;
15 using System.Diagnostics;
16 using System.Reflection;
17 using System.Reflection.Emit;
18
19 namespace Mono.CSharp {
20
21         /// <summary>
22         ///   This class is used to report errors and warnings t te user.
23         /// </summary>
24         public class Report {
25                 /// <summary>  
26                 ///   Errors encountered so far
27                 /// </summary>
28                 static public int Errors;
29
30                 /// <summary>  
31                 ///   Warnings encountered so far
32                 /// </summary>
33                 static public int Warnings;
34
35                 /// <summary>  
36                 ///   Whether errors should be throw an exception
37                 /// </summary>
38                 static public bool Fatal;
39                 
40                 /// <summary>  
41                 ///   Whether warnings should be considered errors
42                 /// </summary>
43                 static public bool WarningsAreErrors;
44
45                 /// <summary>  
46                 ///   Whether to dump a stack trace on errors. 
47                 /// </summary>
48                 static public bool Stacktrace;
49
50                 static public TextWriter Stderr = Console.Error;
51                 
52                 //
53                 // If the 'expected' error code is reported then the
54                 // compilation succeeds.
55                 //
56                 // Used for the test suite to excercise the error codes
57                 //
58                 static int expected_error = 0;
59
60                 //
61                 // Keeps track of the warnings that we are ignoring
62                 //
63                 public static Hashtable warning_ignore_table;
64
65                 static Hashtable warning_regions_table;
66
67                 //
68                 // This is used to save/restore the error state.  When the
69                 // error stack contains elements, warnings and errors are not
70                 // reported to the user.  This is used by the Lambda expression
71                 // support to compile the code with various parameter values.
72                 //
73                 static Stack error_stack;
74                 
75                 /// <summary>
76                 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
77                 /// </summary>
78                 static StringCollection extra_information = new StringCollection ();
79
80                 // 
81                 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
82                 //
83                 public static readonly int[] AllWarnings = new int[] {
84                         28, 67, 78,
85                         105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
86                         219, 251, 252, 253, 278, 282,
87                         419, 420, 429, 436, 440, 465, 467, 469,
88                         612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675,
89                         809,
90                         1030,
91                         1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
92                         1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692,
93                         1717, 1718, 1720,
94                         1901,
95                         2002, 2023, 2029,
96                         3005, 3012, 3018, 3019, 3021, 3022, 3023, 3026, 3027,
97 #if GMCS_SOURCE
98                         402, 414, 693, 1058, 1700, 3024
99 #endif
100                 };
101
102                 static Report ()
103                 {
104                         // Just to be sure that binary search is working
105                         Array.Sort (AllWarnings);
106                 }
107
108                 public static void Reset ()
109                 {
110                         Errors = Warnings = 0;
111                         WarningsAreErrors = false;
112                         warning_ignore_table = null;
113                         warning_regions_table = null;
114                 }
115
116                 public static void DisableErrors ()
117                 {
118                         if (error_stack == null)
119                                 error_stack = new Stack ();
120                         error_stack.Push (Errors);
121                 }
122
123                 public static void EnableErrors ()
124                 {
125                         Errors = (int) error_stack.Pop ();
126                 }
127                 
128                 abstract class AbstractMessage {
129
130                         static void Check (int code)
131                         {
132                                 if (code == expected_error) {
133                                         Environment.Exit (0);
134                                 }
135                         }
136
137                         public abstract bool IsWarning { get; }
138
139                         public abstract string MessageType { get; }
140
141                         public virtual void Print (int code, string location, string text)
142                         {
143                                 if (error_stack != null && error_stack.Count != 0){
144                                         //
145                                         // This line is useful when debugging the inner working of
146                                         // Lambdas when various compilation attempts are done.
147                                         //
148                                         //Console.WriteLine ("DISABLED: {0} {1} {2}", code, location, text);
149                                         return;
150                                 }
151                                 
152                                 if (code < 0)
153                                         code = 8000-code;
154
155                                 StringBuilder msg = new StringBuilder ();
156                                 if (location.Length != 0) {
157                                         msg.Append (location);
158                                         msg.Append (' ');
159                                 }
160                                 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, text);
161                                 Stderr.WriteLine (msg.ToString ());
162
163                                 foreach (string s in extra_information) 
164                                         Stderr.WriteLine (s + MessageType + ")");
165
166                                 extra_information.Clear ();
167
168                                 if (Stacktrace)
169                                         Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
170
171                                 if (Fatal) {
172                                         if (!IsWarning || WarningsAreErrors)
173                                                 throw new Exception (text);
174                                 }
175
176                                 Check (code);
177                         }
178
179                         public virtual void Print (int code, Location location, string text)
180                         {
181                                 Print (code, location.IsNull ? "" : location.ToString (), text);
182                         }
183                 }
184
185                 sealed class WarningMessage : AbstractMessage {
186                         Location loc = Location.Null;
187                         readonly int Level;
188
189                         public WarningMessage (int level)
190                         {
191                                 Level = level;
192                         }
193
194                         public override bool IsWarning {
195                                 get { return true; }
196                         }
197
198                         bool IsEnabled (int code)
199                         {
200                                 if (RootContext.WarningLevel < Level)
201                                         return false;
202
203                                 if (warning_ignore_table != null) {
204                                         if (warning_ignore_table.Contains (code)) {
205                                                 return false;
206                                         }
207                                 }
208
209                                 if (warning_regions_table == null || loc.Equals (Location.Null))
210                                         return true;
211
212                                 WarningRegions regions = (WarningRegions)warning_regions_table [loc.Name];
213                                 if (regions == null)
214                                         return true;
215
216                                 return regions.IsWarningEnabled (code, loc.Row);
217                         }
218
219                         public override void Print(int code, string location, string text)
220                         {
221                                 if (!IsEnabled (code)) {
222                                         extra_information.Clear ();
223                                         return;
224                                 }
225
226                                 if (WarningsAreErrors) {
227                                         new ErrorMessage ().Print (code, location, text);
228                                         return;
229                                 }
230
231                                 Warnings++;
232                                 base.Print (code, location, text);
233                         }
234
235                         public override void Print(int code, Location location, string text)
236                         {
237                                 loc = location;
238                                 base.Print (code, location, text);
239                         }
240
241                         public override string MessageType {
242                                 get {
243                                         return "warning";
244                                 }
245                         }
246                 }
247
248                 sealed class ErrorMessage : AbstractMessage {
249
250                         public override void Print(int code, string location, string text)
251                         {
252                                 Errors++;
253                                 base.Print (code, location, text);
254                         }
255
256                         public override bool IsWarning {
257                                 get { return false; }
258                         }
259
260                         public override string MessageType {
261                                 get {
262                                         return "error";
263                                 }
264                         }
265
266                 }
267
268                 public static void FeatureIsNotISO1 (Location loc, string feature)
269                 {
270                         Report.Error (1644, loc,
271                                 "Feature `{0}' cannot be used because it is not part of the C# 1.0 language specification",
272                                       feature);
273                 }
274
275                 public static void FeatureRequiresLINQ (Location loc, string feature)
276                 {
277                         Report.Error (1644, loc,
278                                       "Feature `{0}' can only be used if the language level is LINQ", feature);
279                 }
280                 
281                 public static string FriendlyStackTrace (Exception e)
282                 {
283                         return FriendlyStackTrace (new StackTrace (e, true));
284                 }
285                 
286                 static string FriendlyStackTrace (StackTrace t)
287                 {               
288                         StringBuilder sb = new StringBuilder ();
289                         
290                         bool foundUserCode = false;
291                         
292                         for (int i = 0; i < t.FrameCount; i++) {
293                                 StackFrame f = t.GetFrame (i);
294                                 MethodBase mb = f.GetMethod ();
295                                 
296                                 if (!foundUserCode && mb.ReflectedType == typeof (Report))
297                                         continue;
298                                 
299                                 foundUserCode = true;
300                                 
301                                 sb.Append ("\tin ");
302                                 
303                                 if (f.GetFileLineNumber () > 0)
304                                         sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
305                                 
306                                 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
307                                 
308                                 bool first = true;
309                                 foreach (ParameterInfo pi in mb.GetParameters ()) {
310                                         if (!first)
311                                                 sb.Append (", ");
312                                         first = false;
313                                         
314                                         sb.Append (TypeManager.CSharpName (pi.ParameterType));
315                                 }
316                                 sb.Append (")\n");
317                         }
318         
319                         return sb.ToString ();
320                 }
321
322                 public static void StackTrace ()
323                 {
324                         Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
325                 }
326
327                 public static bool IsValidWarning (int code)
328                 {       
329                         return Array.BinarySearch (AllWarnings, code) >= 0;
330                 }
331                         
332                 static public void RuntimeMissingSupport (Location loc, string feature) 
333                 {
334                         Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
335                 }
336
337                 /// <summary>
338                 /// In most error cases is very useful to have information about symbol that caused the error.
339                 /// Call this method before you call Report.Error when it makes sense.
340                 /// </summary>
341                 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
342                 {
343                         SymbolRelatedToPreviousError (loc.ToString (), symbol);
344                 }
345
346                 static public void SymbolRelatedToPreviousError (MemberInfo mi)
347                 {
348                         Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
349                         DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
350                         if (temp_ds == null) {
351                                 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
352                         } else {
353                                 MethodBase mb = mi as MethodBase;
354                                 if (mb != null) {
355                                         mb = TypeManager.DropGenericMethodArguments (mb);
356                                         IMethodData md = TypeManager.GetMethod (mb);
357                                         SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
358                                         return;
359                                 }
360
361                                 MemberCore mc = temp_ds.GetDefinition (mi.Name);
362                                 SymbolRelatedToPreviousError (mc);
363                         }
364                 }
365
366                 static public void SymbolRelatedToPreviousError (MemberCore mc)
367                 {
368                         SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
369                 }
370
371                 static public void SymbolRelatedToPreviousError (Type type)
372                 {
373                         type = TypeManager.DropGenericTypeArguments (type);
374
375                         if (TypeManager.IsGenericParameter (type)) {
376                                 TypeParameter tp = TypeManager.LookupTypeParameter (type);
377                                 if (tp != null) {
378                                         SymbolRelatedToPreviousError (tp.Location, "");
379                                         return;
380                                 }
381                         }
382
383                         if (type is TypeBuilder) {
384                                 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
385                                 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
386                         } else if (type.HasElementType) {
387                                 SymbolRelatedToPreviousError (type.GetElementType ());
388                         } else {
389                                 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
390                         }
391                 }
392
393                 static void SymbolRelatedToPreviousError (string loc, string symbol)
394                 {
395                         extra_information.Add (String.Format ("{0} (Location of the symbol related to previous ", loc));
396                 }
397
398                 public static void ExtraInformation (Location loc, string msg)
399                 {
400                         extra_information.Add (String.Format ("{0} {1}", loc, msg));
401                 }
402
403                 public static WarningRegions RegisterWarningRegion (Location location)
404                 {
405                         if (warning_regions_table == null)
406                                 warning_regions_table = new Hashtable ();
407
408                         WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
409                         if (regions == null) {
410                                 regions = new WarningRegions ();
411                                 warning_regions_table.Add (location.Name, regions);
412                         }
413                         return regions;
414                 }
415
416                 static public void Warning (int code, int level, Location loc, string message)
417                 {
418                         WarningMessage w = new WarningMessage (level);
419                         w.Print (code, loc, message);
420                 }
421
422                 static public void Warning (int code, int level, Location loc, string format, string arg)
423                 {
424                         WarningMessage w = new WarningMessage (level);
425                         w.Print (code, loc, String.Format (format, arg));
426                 }
427
428                 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
429                 {
430                         WarningMessage w = new WarningMessage (level);
431                         w.Print (code, loc, String.Format (format, arg1, arg2));
432                 }
433
434                 static public void Warning (int code, int level, Location loc, string format, params string[] args)
435                 {
436                         WarningMessage w = new WarningMessage (level);
437                         w.Print (code, loc, String.Format (format, args));
438                 }
439
440                 static public void Warning (int code, int level, string message)
441                 {
442                         Warning (code, level, Location.Null, message);
443                 }
444
445                 static public void Warning (int code, int level, string format, string arg)
446                 {
447                         Warning (code, level, Location.Null, format, arg);
448                 }
449
450                 static public void Warning (int code, int level, string format, string arg1, string arg2)
451                 {
452                         Warning (code, level, Location.Null, format, arg1, arg2);
453                 }
454
455                 static public void Warning (int code, int level, string format, params string[] args)
456                 {
457                         Warning (code, level, Location.Null, String.Format (format, args));
458                 }
459
460                 static public void Error (int code, Location loc, string error)
461                 {
462                         new ErrorMessage ().Print (code, loc, error);
463                 }
464
465                 static public void Error (int code, Location loc, string format, string arg)
466                 {
467                         new ErrorMessage ().Print (code, loc, String.Format (format, arg));
468                 }
469
470                 static public void Error (int code, Location loc, string format, string arg1, string arg2)
471                 {
472                         new ErrorMessage ().Print (code, loc, String.Format (format, arg1, arg2));
473                 }
474
475                 static public void Error (int code, Location loc, string format, params string[] args)
476                 {
477                         Error (code, loc, String.Format (format, args));
478                 }
479
480                 static public void Error (int code, string error)
481                 {
482                         Error (code, Location.Null, error);
483                 }
484
485                 static public void Error (int code, string format, string arg)
486                 {
487                         Error (code, Location.Null, format, arg);
488                 }
489
490                 static public void Error (int code, string format, string arg1, string arg2)
491                 {
492                         Error (code, Location.Null, format, arg1, arg2);
493                 }
494
495                 static public void Error (int code, string format, params string[] args)
496                 {
497                         Error (code, Location.Null, String.Format (format, args));
498                 }
499
500                 static public void SetIgnoreWarning (int code)
501                 {
502                         if (warning_ignore_table == null)
503                                 warning_ignore_table = new Hashtable ();
504
505                         warning_ignore_table [code] = true;
506                 }
507                 
508                 static public int ExpectedError {
509                         set {
510                                 expected_error = value;
511                         }
512                         get {
513                                 return expected_error;
514                         }
515                 }
516
517                 public static int DebugFlags = 0;
518
519                 [Conditional ("MCS_DEBUG")]
520                 static public void Debug (string message, params object[] args)
521                 {
522                         Debug (4, message, args);
523                 }
524                         
525                 [Conditional ("MCS_DEBUG")]
526                 static public void Debug (int category, string message, params object[] args)
527                 {
528                         if ((category & DebugFlags) == 0)
529                                 return;
530
531                         StringBuilder sb = new StringBuilder (message);
532
533                         if ((args != null) && (args.Length > 0)) {
534                                 sb.Append (": ");
535
536                                 bool first = true;
537                                 foreach (object arg in args) {
538                                         if (first)
539                                                 first = false;
540                                         else
541                                                 sb.Append (", ");
542                                         if (arg == null)
543                                                 sb.Append ("null");
544                                         else if (arg is ICollection)
545                                                 sb.Append (PrintCollection ((ICollection) arg));
546                                         else
547                                                 sb.Append (arg);
548                                 }
549                         }
550
551                         Console.WriteLine (sb.ToString ());
552                 }
553
554                 static public string PrintCollection (ICollection collection)
555                 {
556                         StringBuilder sb = new StringBuilder ();
557
558                         sb.Append (collection.GetType ());
559                         sb.Append ("(");
560
561                         bool first = true;
562                         foreach (object o in collection) {
563                                 if (first)
564                                         first = false;
565                                 else
566                                         sb.Append (", ");
567                                 sb.Append (o);
568                         }
569
570                         sb.Append (")");
571                         return sb.ToString ();
572                 }
573         }
574
575         public enum TimerType {
576                 FindMembers     = 0,
577                 TcFindMembers   = 1,
578                 MemberLookup    = 2,
579                 CachedLookup    = 3,
580                 CacheInit       = 4,
581                 MiscTimer       = 5,
582                 CountTimers     = 6
583         }
584
585         public enum CounterType {
586                 FindMembers     = 0,
587                 MemberCache     = 1,
588                 MiscCounter     = 2,
589                 CountCounters   = 3
590         }
591
592         public class Timer
593         {
594                 static DateTime[] timer_start;
595                 static TimeSpan[] timers;
596                 static long[] timer_counters;
597                 static long[] counters;
598
599                 static Timer ()
600                 {
601                         timer_start = new DateTime [(int) TimerType.CountTimers];
602                         timers = new TimeSpan [(int) TimerType.CountTimers];
603                         timer_counters = new long [(int) TimerType.CountTimers];
604                         counters = new long [(int) CounterType.CountCounters];
605
606                         for (int i = 0; i < (int) TimerType.CountTimers; i++) {
607                                 timer_start [i] = DateTime.Now;
608                                 timers [i] = TimeSpan.Zero;
609                         }
610                 }
611
612                 [Conditional("TIMER")]
613                 static public void IncrementCounter (CounterType which)
614                 {
615                         ++counters [(int) which];
616                 }
617
618                 [Conditional("TIMER")]
619                 static public void StartTimer (TimerType which)
620                 {
621                         timer_start [(int) which] = DateTime.Now;
622                 }
623
624                 [Conditional("TIMER")]
625                 static public void StopTimer (TimerType which)
626                 {
627                         timers [(int) which] += DateTime.Now - timer_start [(int) which];
628                         ++timer_counters [(int) which];
629                 }
630
631                 [Conditional("TIMER")]
632                 static public void ShowTimers ()
633                 {
634                         ShowTimer (TimerType.FindMembers, "- FindMembers timer");
635                         ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
636                         ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
637                         ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
638                         ShowTimer (TimerType.CacheInit, "- Cache init");
639                         ShowTimer (TimerType.MiscTimer, "- Misc timer");
640
641                         ShowCounter (CounterType.FindMembers, "- Find members");
642                         ShowCounter (CounterType.MemberCache, "- Member cache");
643                         ShowCounter (CounterType.MiscCounter, "- Misc counter");
644                 }
645
646                 static public void ShowCounter (CounterType which, string msg)
647                 {
648                         Console.WriteLine ("{0} {1}", counters [(int) which], msg);
649                 }
650
651                 static public void ShowTimer (TimerType which, string msg)
652                 {
653                         Console.WriteLine (
654                                 "[{0:00}:{1:000}] {2} (used {3} times)",
655                                 (int) timers [(int) which].TotalSeconds,
656                                 timers [(int) which].Milliseconds, msg,
657                                 timer_counters [(int) which]);
658                 }
659         }
660
661         public class InternalErrorException : Exception {
662                 public InternalErrorException (MemberCore mc, Exception e)
663                         : base (mc.Location + " " + mc.GetSignatureForError (), e)
664                 {
665                 }
666
667                 public InternalErrorException ()
668                         : base ("Internal error")
669                 {
670                 }
671
672                 public InternalErrorException (string message)
673                         : base (message)
674                 {
675                 }
676
677                 public InternalErrorException (string message, params object[] args)
678                         : base (String.Format (message, args))
679                 { }
680         }
681
682         /// <summary>
683         /// Handles #pragma warning
684         /// </summary>
685         public class WarningRegions {
686
687                 abstract class PragmaCmd
688                 {
689                         public int Line;
690
691                         protected PragmaCmd (int line)
692                         {
693                                 Line = line;
694                         }
695
696                         public abstract bool IsEnabled (int code, bool previous);
697                 }
698                 
699                 class Disable : PragmaCmd
700                 {
701                         int code;
702                         public Disable (int line, int code)
703                                 : base (line)
704                         {
705                                 this.code = code;
706                         }
707
708                         public override bool IsEnabled (int code, bool previous)
709                         {
710                                 return this.code == code ? false : previous;
711                         }
712                 }
713
714                 class DisableAll : PragmaCmd
715                 {
716                         public DisableAll (int line)
717                                 : base (line) {}
718
719                         public override bool IsEnabled(int code, bool previous)
720                         {
721                                 return false;
722                         }
723                 }
724
725                 class Enable : PragmaCmd
726                 {
727                         int code;
728                         public Enable (int line, int code)
729                                 : base (line)
730                         {
731                                 this.code = code;
732                         }
733
734                         public override bool IsEnabled(int code, bool previous)
735                         {
736                                 return this.code == code ? true : previous;
737                         }
738                 }
739
740                 class EnableAll : PragmaCmd
741                 {
742                         public EnableAll (int line)
743                                 : base (line) {}
744
745                         public override bool IsEnabled(int code, bool previous)
746                         {
747                                 return true;
748                         }
749                 }
750
751
752                 ArrayList regions = new ArrayList ();
753
754                 public void WarningDisable (int line)
755                 {
756                         regions.Add (new DisableAll (line));
757                 }
758
759                 public void WarningDisable (Location location, int code)
760                 {
761                         if (CheckWarningCode (code, location))
762                                 regions.Add (new Disable (location.Row, code));
763                 }
764
765                 public void WarningEnable (int line)
766                 {
767                         regions.Add (new EnableAll (line));
768                 }
769
770                 public void WarningEnable (Location location, int code)
771                 {
772                         if (CheckWarningCode (code, location))
773                                 regions.Add (new Enable (location.Row, code));
774                 }
775
776                 public bool IsWarningEnabled (int code, int src_line)
777                 {
778                         bool result = true;
779                         foreach (PragmaCmd pragma in regions) {
780                                 if (src_line < pragma.Line)
781                                         break;
782
783                                 result = pragma.IsEnabled (code, result);
784                         }
785                         return result;
786                 }
787
788                 static bool CheckWarningCode (int code, Location loc)
789                 {
790                         if (Report.IsValidWarning (code))
791                                 return true;
792
793                         Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());
794                         return false;
795                 }
796         }
797 }