2005-12-27 Atsushi Enomoto <atsushi@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                                         while (mb.Mono_IsInflatedMethod)
320                                                 mb = mb.GetGenericMethodDefinition ();
321                                         IMethodData md = TypeManager.GetMethod (mb);
322                                         SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
323                                         return;
324                                 }
325
326                                 MemberCore mc = temp_ds.GetDefinition (mi.Name);
327                                 SymbolRelatedToPreviousError (mc);
328                         }
329                 }
330
331                 static public void SymbolRelatedToPreviousError (MemberCore mc)
332                 {
333                         SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
334                 }
335
336                 static public void SymbolRelatedToPreviousError (Type type)
337                 {
338                         type = TypeManager.DropGenericTypeArguments (type);
339
340                         if (type.IsGenericParameter) {
341                                 TypeParameter tp = TypeManager.LookupTypeParameter (type);
342                                 if (tp != null) {
343                                         SymbolRelatedToPreviousError (tp.Location, "");
344                                         return;
345                                 }
346                         }
347
348                         if (type is TypeBuilder) {
349                                 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
350                                 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
351                         } else if (type.HasElementType) {
352                                 SymbolRelatedToPreviousError (type.GetElementType ());
353                         } else {
354                                 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
355                         }
356                 }
357
358                 static void SymbolRelatedToPreviousError (string loc, string symbol)
359                 {
360                         extra_information.Add (String.Format ("{0}: `{1}', name of symbol related to previous ", loc, symbol));
361                 }
362
363                 public static void ExtraInformation (Location loc, string msg)
364                 {
365                         extra_information.Add (String.Format ("{0} {1}", loc, msg));
366                 }
367
368                 public static WarningRegions RegisterWarningRegion (Location location)
369                 {
370                         if (warning_regions_table == null)
371                                 warning_regions_table = new Hashtable ();
372
373                         WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
374                         if (regions == null) {
375                                 regions = new WarningRegions ();
376                                 warning_regions_table.Add (location.Name, regions);
377                         }
378                         return regions;
379                 }
380
381                 static public void Warning (int code, int level, Location loc, string format, params string[] args)
382                 {
383                         WarningMessage w = new WarningMessage (level);
384                         w.Print (code, loc, String.Format (format, args));
385                 }
386
387                 static public void Warning (int code, int level, string format, params string[] args)
388                 {
389                         Warning (code, level, Location.Null, String.Format (format, args));
390                 }
391
392                 static public void Error (int code, string format, params string[] args)
393                 {
394                         Error (code, Location.Null, String.Format (format, args));
395                 }
396
397                 static public void Error (int code, Location loc, string format, params string[] args)
398                 {
399                         Error (code, loc, String.Format (format, args));
400                 }
401
402                 static void Error (int code, Location loc, string error)
403                 {
404                         new ErrorMessage ().Print (code, loc, error);
405                 }
406
407                 static public void SetIgnoreWarning (int code)
408                 {
409                         if (warning_ignore_table == null)
410                                 warning_ignore_table = new Hashtable ();
411
412                         warning_ignore_table [code] = true;
413                 }
414                 
415                 static public int ExpectedError {
416                         set {
417                                 expected_error = value;
418                         }
419                         get {
420                                 return expected_error;
421                         }
422                 }
423
424                 public static int DebugFlags = 0;
425
426                 [Conditional ("MCS_DEBUG")]
427                 static public void Debug (string message, params object[] args)
428                 {
429                         Debug (4, message, args);
430                 }
431                         
432                 [Conditional ("MCS_DEBUG")]
433                 static public void Debug (int category, string message, params object[] args)
434                 {
435                         if ((category & DebugFlags) == 0)
436                                 return;
437
438                         StringBuilder sb = new StringBuilder (message);
439
440                         if ((args != null) && (args.Length > 0)) {
441                                 sb.Append (": ");
442
443                                 bool first = true;
444                                 foreach (object arg in args) {
445                                         if (first)
446                                                 first = false;
447                                         else
448                                                 sb.Append (", ");
449                                         if (arg == null)
450                                                 sb.Append ("null");
451                                         else if (arg is ICollection)
452                                                 sb.Append (PrintCollection ((ICollection) arg));
453                                         else
454                                                 sb.Append (arg);
455                                 }
456                         }
457
458                         Console.WriteLine (sb.ToString ());
459                 }
460
461                 static public string PrintCollection (ICollection collection)
462                 {
463                         StringBuilder sb = new StringBuilder ();
464
465                         sb.Append (collection.GetType ());
466                         sb.Append ("(");
467
468                         bool first = true;
469                         foreach (object o in collection) {
470                                 if (first)
471                                         first = false;
472                                 else
473                                         sb.Append (", ");
474                                 sb.Append (o);
475                         }
476
477                         sb.Append (")");
478                         return sb.ToString ();
479                 }
480         }
481
482         public enum TimerType {
483                 FindMembers     = 0,
484                 TcFindMembers   = 1,
485                 MemberLookup    = 2,
486                 CachedLookup    = 3,
487                 CacheInit       = 4,
488                 MiscTimer       = 5,
489                 CountTimers     = 6
490         }
491
492         public enum CounterType {
493                 FindMembers     = 0,
494                 MemberCache     = 1,
495                 MiscCounter     = 2,
496                 CountCounters   = 3
497         }
498
499         public class Timer
500         {
501                 static DateTime[] timer_start;
502                 static TimeSpan[] timers;
503                 static long[] timer_counters;
504                 static long[] counters;
505
506                 static Timer ()
507                 {
508                         timer_start = new DateTime [(int) TimerType.CountTimers];
509                         timers = new TimeSpan [(int) TimerType.CountTimers];
510                         timer_counters = new long [(int) TimerType.CountTimers];
511                         counters = new long [(int) CounterType.CountCounters];
512
513                         for (int i = 0; i < (int) TimerType.CountTimers; i++) {
514                                 timer_start [i] = DateTime.Now;
515                                 timers [i] = TimeSpan.Zero;
516                         }
517                 }
518
519                 [Conditional("TIMER")]
520                 static public void IncrementCounter (CounterType which)
521                 {
522                         ++counters [(int) which];
523                 }
524
525                 [Conditional("TIMER")]
526                 static public void StartTimer (TimerType which)
527                 {
528                         timer_start [(int) which] = DateTime.Now;
529                 }
530
531                 [Conditional("TIMER")]
532                 static public void StopTimer (TimerType which)
533                 {
534                         timers [(int) which] += DateTime.Now - timer_start [(int) which];
535                         ++timer_counters [(int) which];
536                 }
537
538                 [Conditional("TIMER")]
539                 static public void ShowTimers ()
540                 {
541                         ShowTimer (TimerType.FindMembers, "- FindMembers timer");
542                         ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
543                         ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
544                         ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
545                         ShowTimer (TimerType.CacheInit, "- Cache init");
546                         ShowTimer (TimerType.MiscTimer, "- Misc timer");
547
548                         ShowCounter (CounterType.FindMembers, "- Find members");
549                         ShowCounter (CounterType.MemberCache, "- Member cache");
550                         ShowCounter (CounterType.MiscCounter, "- Misc counter");
551                 }
552
553                 static public void ShowCounter (CounterType which, string msg)
554                 {
555                         Console.WriteLine ("{0} {1}", counters [(int) which], msg);
556                 }
557
558                 static public void ShowTimer (TimerType which, string msg)
559                 {
560                         Console.WriteLine (
561                                 "[{0:00}:{1:000}] {2} (used {3} times)",
562                                 (int) timers [(int) which].TotalSeconds,
563                                 timers [(int) which].Milliseconds, msg,
564                                 timer_counters [(int) which]);
565                 }
566         }
567
568         public class InternalErrorException : Exception {
569                 public InternalErrorException ()
570                         : base ("Internal error")
571                 {
572                 }
573
574                 public InternalErrorException (string message)
575                         : base (message)
576                 {
577                 }
578         }
579
580         /// <summary>
581         /// Handles #pragma warning
582         /// </summary>
583         public class WarningRegions {
584
585                 abstract class PragmaCmd
586                 {
587                         public int Line;
588
589                         protected PragmaCmd (int line)
590                         {
591                                 Line = line;
592                         }
593
594                         public abstract bool IsEnabled (int code, bool previous);
595                 }
596                 
597                 class Disable : PragmaCmd
598                 {
599                         int code;
600                         public Disable (int line, int code)
601                                 : base (line)
602                         {
603                                 this.code = code;
604                         }
605
606                         public override bool IsEnabled (int code, bool previous)
607                         {
608                                 return this.code == code ? false : previous;
609                         }
610                 }
611
612                 class DisableAll : PragmaCmd
613                 {
614                         public DisableAll (int line)
615                                 : base (line) {}
616
617                         public override bool IsEnabled(int code, bool previous)
618                         {
619                                 return false;
620                         }
621                 }
622
623                 class Enable : PragmaCmd
624                 {
625                         int code;
626                         public Enable (int line, int code)
627                                 : base (line)
628                         {
629                                 this.code = code;
630                         }
631
632                         public override bool IsEnabled(int code, bool previous)
633                         {
634                                 return this.code == code ? true : previous;
635                         }
636                 }
637
638                 class EnableAll : PragmaCmd
639                 {
640                         public EnableAll (int line)
641                                 : base (line) {}
642
643                         public override bool IsEnabled(int code, bool previous)
644                         {
645                                 return true;
646                         }
647                 }
648
649
650                 ArrayList regions = new ArrayList ();
651
652                 public void WarningDisable (int line)
653                 {
654                         regions.Add (new DisableAll (line));
655                 }
656
657                 public void WarningDisable (Location location, int code)
658                 {
659                         if (CheckWarningCode (code, location))
660                                 regions.Add (new Disable (location.Row, code));
661                 }
662
663                 public void WarningEnable (int line)
664                 {
665                         regions.Add (new EnableAll (line));
666                 }
667
668                 public void WarningEnable (Location location, int code)
669                 {
670                         if (CheckWarningCode (code, location))
671                                 regions.Add (new Enable (location.Row, code));
672                 }
673
674                 public bool IsWarningEnabled (int code, int src_line)
675                 {
676                         bool result = true;
677                         foreach (PragmaCmd pragma in regions) {
678                                 if (src_line < pragma.Line)
679                                         break;
680
681                                 result = pragma.IsEnabled (code, result);
682                         }
683                         return result;
684                 }
685
686                 bool CheckWarningCode (int code, Location loc)
687                 {
688                         if (Report.IsValidWarning (code))
689                                 return true;
690
691                         Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());
692                         return false;
693                 }
694         }
695 }