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