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