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