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