2006-03-09 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / gmcs / 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                 /// <summary>
68                 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
69                 /// </summary>
70                 static StringCollection extra_information = new StringCollection ();
71
72                 // 
73                 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
74                 //
75                 public static readonly int[] AllWarnings = new int[] {
76                                                                                                                                  28, 67, 78,
77                                                                                                                                  105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
78                                                                                                                                  219, 251, 252, 253, 282,
79                                                                                                                                  419, 420, 429, 436, 440, 465,
80                                                                                                                                  612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672,
81                                                                                                                                  1030, 1058,
82                                                                                                                                  1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
83                                                                                                                                  1616, 1633, 1634, 1635, 1691, 1692,
84                                                                                                                                  1717, 1718,
85                                                                                                                                  1901,
86                                                                                                                                  2002, 2023,
87                                                                                                                                  3005, 3012, 3019, 3021, 3022, 3023, 3026, 3027,
88                                                                                                                                 // gmcs warnings start here
89                                                                                                                                  414, 1700
90                                                                                                                          };
91
92                 static Report ()
93                 {
94                         // Just to be sure that binary search is working
95                         Array.Sort (AllWarnings);
96                 }
97
98                 public static void Reset ()
99                 {
100                         Errors = Warnings = 0;
101                         WarningsAreErrors = false;
102                         warning_ignore_table = null;
103                         warning_regions_table = null;
104                 }
105
106                 abstract class AbstractMessage {
107
108                         static void Check (int code)
109                         {
110                                 if (code == expected_error) {
111                                         Environment.Exit (0);
112                                 }
113                         }
114
115                         public abstract bool IsWarning { get; }
116
117                         public abstract string MessageType { get; }
118
119                         public virtual void Print (int code, string location, string text)
120                         {
121                                 if (code < 0)
122                                         code = 8000-code;
123
124                                 StringBuilder msg = new StringBuilder ();
125                                 if (location.Length != 0) {
126                                         msg.Append (location);
127                                         msg.Append (' ');
128                                 }
129                                 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, text);
130                                 Stderr.WriteLine (msg.ToString ());
131
132                                 foreach (string s in extra_information) 
133                                         Stderr.WriteLine (s + MessageType);
134
135                                 extra_information.Clear ();
136
137                                 if (Stacktrace)
138                                         Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
139
140                                 if (Fatal) {
141                                         if (!IsWarning || WarningsAreErrors)
142                                                 throw new Exception (text);
143                                 }
144
145                                 Check (code);
146                         }
147
148                         public virtual void Print (int code, Location location, string text)
149                         {
150                                 if (location.IsNull) {
151                                         Print (code, "", text);
152                                         return;
153                                 }
154                                 Print (code, location.ToString (), text);
155                         }
156                 }
157
158                 sealed class WarningMessage : AbstractMessage {
159                         Location loc = Location.Null;
160                         readonly int Level;
161
162                         public WarningMessage (int level)
163                         {
164                                 Level = level;
165                         }
166
167                         public override bool IsWarning {
168                                 get { return true; }
169                         }
170
171                         bool IsEnabled (int code)
172                         {
173                                 if (RootContext.WarningLevel < Level)
174                                         return false;
175
176                                 if (warning_ignore_table != null) {
177                                         if (warning_ignore_table.Contains (code)) {
178                                                 return false;
179                                         }
180                                 }
181
182                                 if (warning_regions_table == null || loc.Equals (Location.Null))
183                                         return true;
184
185                                 WarningRegions regions = (WarningRegions)warning_regions_table [loc.Name];
186                                 if (regions == null)
187                                         return true;
188
189                                 return regions.IsWarningEnabled (code, loc.Row);
190                         }
191
192                         public override void Print(int code, string location, string text)
193                         {
194                                 if (!IsEnabled (code)) {
195                                         extra_information.Clear ();
196                                         return;
197                                 }
198
199                                 if (WarningsAreErrors) {
200                                         new ErrorMessage ().Print (code, location, text);
201                                         return;
202                                 }
203
204                                 Warnings++;
205                                 base.Print (code, location, text);
206                         }
207
208                         public override void Print(int code, Location location, string text)
209                         {
210                                 loc = location;
211                                 base.Print (code, location, text);
212                         }
213
214                         public override string MessageType {
215                                 get {
216                                         return "warning";
217                                 }
218                         }
219                 }
220
221                 sealed class ErrorMessage : AbstractMessage {
222
223                         public override void Print(int code, string location, string text)
224                         {
225                                 Errors++;
226                                 base.Print (code, location, text);
227                         }
228
229                         public override bool IsWarning {
230                                 get { return false; }
231                         }
232
233                         public override string MessageType {
234                                 get {
235                                         return "error";
236                                 }
237                         }
238
239                 }
240
241                 public static void FeatureIsNotStandardized (Location loc, string feature)
242                 {
243                         Report.Error (1644, loc, "Feature `{0}' cannot be used because it is not part of the standardized ISO C# language specification", feature);
244                 }
245                 
246                 public static string FriendlyStackTrace (Exception e)
247                 {
248                         return FriendlyStackTrace (new StackTrace (e, true));
249                 }
250                 
251                 static string FriendlyStackTrace (StackTrace t)
252                 {               
253                         StringBuilder sb = new StringBuilder ();
254                         
255                         bool foundUserCode = false;
256                         
257                         for (int i = 0; i < t.FrameCount; i++) {
258                                 StackFrame f = t.GetFrame (i);
259                                 MethodBase mb = f.GetMethod ();
260                                 
261                                 if (!foundUserCode && mb.ReflectedType == typeof (Report))
262                                         continue;
263                                 
264                                 foundUserCode = true;
265                                 
266                                 sb.Append ("\tin ");
267                                 
268                                 if (f.GetFileLineNumber () > 0)
269                                         sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
270                                 
271                                 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
272                                 
273                                 bool first = true;
274                                 foreach (ParameterInfo pi in mb.GetParameters ()) {
275                                         if (!first)
276                                                 sb.Append (", ");
277                                         first = false;
278                                         
279                                         sb.Append (TypeManager.CSharpName (pi.ParameterType));
280                                 }
281                                 sb.Append (")\n");
282                         }
283         
284                         return sb.ToString ();
285                 }
286
287                 public static void StackTrace ()
288                 {
289                         Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
290                 }
291
292                 public static bool IsValidWarning (int code)
293                 {       
294                         return Array.BinarySearch (AllWarnings, code) >= 0;
295                 }
296                         
297                 static public void RuntimeMissingSupport (Location loc, string feature) 
298                 {
299                         Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
300                 }
301
302                 /// <summary>
303                 /// In most error cases is very useful to have information about symbol that caused the error.
304                 /// Call this method before you call Report.Error when it makes sense.
305                 /// </summary>
306                 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
307                 {
308                         SymbolRelatedToPreviousError (loc.ToString (), symbol);
309                 }
310
311                 static public void SymbolRelatedToPreviousError (MemberInfo mi)
312                 {
313                         TypeContainer temp_ds = TypeManager.LookupGenericTypeContainer (mi.DeclaringType);
314                         if (temp_ds == null) {
315                                 SymbolRelatedToPreviousError (mi.DeclaringType.Assembly.Location, TypeManager.GetFullNameSignature (mi));
316                         } else {
317                                 MethodBase mb = mi as MethodBase;
318                                 if (mb != null) {
319                                         mb = TypeManager.DropGenericMethodArguments (mb);
320                                         IMethodData md = TypeManager.GetMethod (mb);
321                                         SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
322                                         return;
323                                 }
324
325                                 MemberCore mc = temp_ds.GetDefinition (mi.Name);
326                                 SymbolRelatedToPreviousError (mc);
327                         }
328                 }
329
330                 static public void SymbolRelatedToPreviousError (MemberCore mc)
331                 {
332                         SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
333                 }
334
335                 static public void SymbolRelatedToPreviousError (Type type)
336                 {
337                         type = TypeManager.DropGenericTypeArguments (type);
338
339                         if (type.IsGenericParameter) {
340                                 TypeParameter tp = TypeManager.LookupTypeParameter (type);
341                                 if (tp != null) {
342                                         SymbolRelatedToPreviousError (tp.Location, "");
343                                         return;
344                                 }
345                         }
346
347                         if (type is TypeBuilder) {
348                                 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
349                                 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
350                         } else if (type.HasElementType) {
351                                 SymbolRelatedToPreviousError (type.GetElementType ());
352                         } else {
353                                 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
354                         }
355                 }
356
357                 static void SymbolRelatedToPreviousError (string loc, string symbol)
358                 {
359                         extra_information.Add (String.Format ("{0}: `{1}', name of symbol related to previous ", loc, symbol));
360                 }
361
362                 public static void ExtraInformation (Location loc, string msg)
363                 {
364                         extra_information.Add (String.Format ("{0} {1}", loc, msg));
365                 }
366
367                 public static WarningRegions RegisterWarningRegion (Location location)
368                 {
369                         if (warning_regions_table == null)
370                                 warning_regions_table = new Hashtable ();
371
372                         WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
373                         if (regions == null) {
374                                 regions = new WarningRegions ();
375                                 warning_regions_table.Add (location.Name, regions);
376                         }
377                         return regions;
378                 }
379
380                 static public void Warning (int code, int level, Location loc, string format, params string[] args)
381                 {
382                         WarningMessage w = new WarningMessage (level);
383                         w.Print (code, loc, String.Format (format, args));
384                 }
385
386                 static public void Warning (int code, int level, string format, params string[] args)
387                 {
388                         Warning (code, level, Location.Null, String.Format (format, args));
389                 }
390
391                 static public void Error (int code, string format, params string[] args)
392                 {
393                         Error (code, Location.Null, String.Format (format, args));
394                 }
395
396                 static public void Error (int code, Location loc, string format, params string[] args)
397                 {
398                         Error (code, loc, String.Format (format, args));
399                 }
400
401                 static void Error (int code, Location loc, string error)
402                 {
403                         new ErrorMessage ().Print (code, loc, error);
404                 }
405
406                 static public void SetIgnoreWarning (int code)
407                 {
408                         if (warning_ignore_table == null)
409                                 warning_ignore_table = new Hashtable ();
410
411                         warning_ignore_table [code] = true;
412                 }
413                 
414                 static public int ExpectedError {
415                         set {
416                                 expected_error = value;
417                         }
418                         get {
419                                 return expected_error;
420                         }
421                 }
422
423                 public static int DebugFlags = 0;
424
425                 [Conditional ("MCS_DEBUG")]
426                 static public void Debug (string message, params object[] args)
427                 {
428                         Debug (4, message, args);
429                 }
430                         
431                 [Conditional ("MCS_DEBUG")]
432                 static public void Debug (int category, string message, params object[] args)
433                 {
434                         if ((category & DebugFlags) == 0)
435                                 return;
436
437                         StringBuilder sb = new StringBuilder (message);
438
439                         if ((args != null) && (args.Length > 0)) {
440                                 sb.Append (": ");
441
442                                 bool first = true;
443                                 foreach (object arg in args) {
444                                         if (first)
445                                                 first = false;
446                                         else
447                                                 sb.Append (", ");
448                                         if (arg == null)
449                                                 sb.Append ("null");
450                                         else if (arg is ICollection)
451                                                 sb.Append (PrintCollection ((ICollection) arg));
452                                         else
453                                                 sb.Append (arg);
454                                 }
455                         }
456
457                         Console.WriteLine (sb.ToString ());
458                 }
459
460                 static public string PrintCollection (ICollection collection)
461                 {
462                         StringBuilder sb = new StringBuilder ();
463
464                         sb.Append (collection.GetType ());
465                         sb.Append ("(");
466
467                         bool first = true;
468                         foreach (object o in collection) {
469                                 if (first)
470                                         first = false;
471                                 else
472                                         sb.Append (", ");
473                                 sb.Append (o);
474                         }
475
476                         sb.Append (")");
477                         return sb.ToString ();
478                 }
479         }
480
481         public enum TimerType {
482                 FindMembers     = 0,
483                 TcFindMembers   = 1,
484                 MemberLookup    = 2,
485                 CachedLookup    = 3,
486                 CacheInit       = 4,
487                 MiscTimer       = 5,
488                 CountTimers     = 6
489         }
490
491         public enum CounterType {
492                 FindMembers     = 0,
493                 MemberCache     = 1,
494                 MiscCounter     = 2,
495                 CountCounters   = 3
496         }
497
498         public class Timer
499         {
500                 static DateTime[] timer_start;
501                 static TimeSpan[] timers;
502                 static long[] timer_counters;
503                 static long[] counters;
504
505                 static Timer ()
506                 {
507                         timer_start = new DateTime [(int) TimerType.CountTimers];
508                         timers = new TimeSpan [(int) TimerType.CountTimers];
509                         timer_counters = new long [(int) TimerType.CountTimers];
510                         counters = new long [(int) CounterType.CountCounters];
511
512                         for (int i = 0; i < (int) TimerType.CountTimers; i++) {
513                                 timer_start [i] = DateTime.Now;
514                                 timers [i] = TimeSpan.Zero;
515                         }
516                 }
517
518                 [Conditional("TIMER")]
519                 static public void IncrementCounter (CounterType which)
520                 {
521                         ++counters [(int) which];
522                 }
523
524                 [Conditional("TIMER")]
525                 static public void StartTimer (TimerType which)
526                 {
527                         timer_start [(int) which] = DateTime.Now;
528                 }
529
530                 [Conditional("TIMER")]
531                 static public void StopTimer (TimerType which)
532                 {
533                         timers [(int) which] += DateTime.Now - timer_start [(int) which];
534                         ++timer_counters [(int) which];
535                 }
536
537                 [Conditional("TIMER")]
538                 static public void ShowTimers ()
539                 {
540                         ShowTimer (TimerType.FindMembers, "- FindMembers timer");
541                         ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
542                         ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
543                         ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
544                         ShowTimer (TimerType.CacheInit, "- Cache init");
545                         ShowTimer (TimerType.MiscTimer, "- Misc timer");
546
547                         ShowCounter (CounterType.FindMembers, "- Find members");
548                         ShowCounter (CounterType.MemberCache, "- Member cache");
549                         ShowCounter (CounterType.MiscCounter, "- Misc counter");
550                 }
551
552                 static public void ShowCounter (CounterType which, string msg)
553                 {
554                         Console.WriteLine ("{0} {1}", counters [(int) which], msg);
555                 }
556
557                 static public void ShowTimer (TimerType which, string msg)
558                 {
559                         Console.WriteLine (
560                                 "[{0:00}:{1:000}] {2} (used {3} times)",
561                                 (int) timers [(int) which].TotalSeconds,
562                                 timers [(int) which].Milliseconds, msg,
563                                 timer_counters [(int) which]);
564                 }
565         }
566
567         public class InternalErrorException : Exception {
568                 public InternalErrorException ()
569                         : base ("Internal error")
570                 {
571                 }
572
573                 public InternalErrorException (string message)
574                         : base (message)
575                 {
576                 }
577         }
578
579         /// <summary>
580         /// Handles #pragma warning
581         /// </summary>
582         public class WarningRegions {
583
584                 abstract class PragmaCmd
585                 {
586                         public int Line;
587
588                         protected PragmaCmd (int line)
589                         {
590                                 Line = line;
591                         }
592
593                         public abstract bool IsEnabled (int code, bool previous);
594                 }
595                 
596                 class Disable : PragmaCmd
597                 {
598                         int code;
599                         public Disable (int line, int code)
600                                 : base (line)
601                         {
602                                 this.code = code;
603                         }
604
605                         public override bool IsEnabled (int code, bool previous)
606                         {
607                                 return this.code == code ? false : previous;
608                         }
609                 }
610
611                 class DisableAll : PragmaCmd
612                 {
613                         public DisableAll (int line)
614                                 : base (line) {}
615
616                         public override bool IsEnabled(int code, bool previous)
617                         {
618                                 return false;
619                         }
620                 }
621
622                 class Enable : PragmaCmd
623                 {
624                         int code;
625                         public Enable (int line, int code)
626                                 : base (line)
627                         {
628                                 this.code = code;
629                         }
630
631                         public override bool IsEnabled(int code, bool previous)
632                         {
633                                 return this.code == code ? true : previous;
634                         }
635                 }
636
637                 class EnableAll : PragmaCmd
638                 {
639                         public EnableAll (int line)
640                                 : base (line) {}
641
642                         public override bool IsEnabled(int code, bool previous)
643                         {
644                                 return true;
645                         }
646                 }
647
648
649                 ArrayList regions = new ArrayList ();
650
651                 public void WarningDisable (int line)
652                 {
653                         regions.Add (new DisableAll (line));
654                 }
655
656                 public void WarningDisable (Location location, int code)
657                 {
658                         if (CheckWarningCode (code, location))
659                                 regions.Add (new Disable (location.Row, code));
660                 }
661
662                 public void WarningEnable (int line)
663                 {
664                         regions.Add (new EnableAll (line));
665                 }
666
667                 public void WarningEnable (Location location, int code)
668                 {
669                         if (CheckWarningCode (code, location))
670                                 regions.Add (new Enable (location.Row, code));
671                 }
672
673                 public bool IsWarningEnabled (int code, int src_line)
674                 {
675                         bool result = true;
676                         foreach (PragmaCmd pragma in regions) {
677                                 if (src_line < pragma.Line)
678                                         break;
679
680                                 result = pragma.IsEnabled (code, result);
681                         }
682                         return result;
683                 }
684
685                 bool CheckWarningCode (int code, Location loc)
686                 {
687                         if (Report.IsValidWarning (code))
688                                 return true;
689
690                         Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());
691                         return false;
692                 }
693         }
694 }