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