c9e565a2106224d8f57a6542ffd5235a761df04c
[mono.git] / mcs / gmcs / report.cs
1 //
2 // report.cs: report errors and warnings.
3 //
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 //
6 // (C) 2001 Ximian, Inc. (http://www.ximian.com)
7 //
8
9 //
10 // FIXME: currently our class library does not support custom number format strings
11 //
12 using System;
13 using System.Text;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.Diagnostics;
17 using System.Reflection;
18
19 namespace Mono.CSharp {
20
21         /// <summary>
22         ///   This class is used to report errors and warnings t te user.
23         /// </summary>
24         public class Report {
25                 /// <summary>  
26                 ///   Errors encountered so far
27                 /// </summary>
28                 static public int Errors;
29
30                 /// <summary>  
31                 ///   Warnings encountered so far
32                 /// </summary>
33                 static public int Warnings;
34
35                 /// <summary>  
36                 ///   Whether errors should be throw an exception
37                 /// </summary>
38                 static public bool Fatal;
39                 
40                 /// <summary>  
41                 ///   Whether warnings should be considered errors
42                 /// </summary>
43                 static public bool WarningsAreErrors;
44
45                 /// <summary>  
46                 ///   Whether to dump a stack trace on errors. 
47                 /// </summary>
48                 static public bool Stacktrace;
49                 
50                 //
51                 // If the 'expected' error code is reported then the
52                 // compilation succeeds.
53                 //
54                 // Used for the test suite to excercise the error codes
55                 //
56                 static int expected_error = 0;
57
58                 //
59                 // Keeps track of the warnings that we are ignoring
60                 //
61                 static Hashtable warning_ignore_table;
62
63                 /// <summary>
64                 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
65                 /// </summary>
66                 static StringCollection related_symbols = new StringCollection ();
67                 
68                 struct WarningData {
69                         public WarningData (int level, string text) {
70                                 Level = level;
71                                 Message = text;
72                         }
73
74                         public bool IsEnabled ()
75                         {
76                                 return RootContext.WarningLevel >= Level;
77                         }
78
79                         public string Format (params object[] args)
80                         {
81                                 return String.Format (Message, args);
82                         }
83
84                         readonly string Message;
85                         readonly int Level;
86                 }
87
88                 static string GetErrorMsg (int error_no)
89                 {
90                         switch (error_no) {
91                                 case 0122: return "'{0}' is inaccessible due to its protection level";
92                                 case 0160: return "A previous catch clause already catches all exceptions of this or a super type '{0}'";
93                                 case 0619: return "'{0}' is obsolete: '{1}'";
94                                 case 0657: return "'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'";
95                                 case 3001: return "Argument type '{0}' is not CLS-compliant";
96                                 case 3002: return "Return type of '{0}' is not CLS-compliant";
97                                 case 3003: return "Type of '{0}' is not CLS-compliant";
98                                 case 3005: return "Identifier '{0}' differing only in case is not CLS-compliant";
99                                 case 3006: return "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant";
100                                 case 3008: return "Identifier '{0}' is not CLS-compliant";
101                                 case 3009: return "'{0}': base type '{1}' is not CLS-compliant";
102                                 case 3010: return "'{0}': CLS-compliant interfaces must have only CLS-compliant members";
103                                 case 3011: return "'{0}': only CLS-compliant members can be abstract";
104                                 case 3013: return "Added modules must be marked with the CLSCompliant attribute to match the assembly";
105                                 case 3014: return "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute";
106                                 case 3015: return "'{0}' has no accessible constructors which use only CLS-compliant types";
107                                 case 3016: return "Arrays as attribute arguments are not CLS-compliant";
108                         }
109                         throw new InternalErrorException (String.Format ("Missing error '{0}' text", error_no));
110                 }
111
112                 static WarningData GetWarningMsg (int warn_no)
113                 {
114                         switch (warn_no) {
115                                 case -24: return new WarningData (1, "The Microsoft Runtime cannot set this marshal info. Please use the Mono runtime instead.");
116                                 case -28: return new WarningData (1, "The Microsoft .NET Runtime 1.x does not permit setting custom attributes on the return type");
117                                 case 0612: return new WarningData (1, "'{0}' is obsolete");
118                                 case 0618: return new WarningData (2, "'{0}' is obsolete: '{1}'");
119                                 case 0672: return new WarningData (1, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'");
120                                 case 3012: return new WarningData (1, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
121                                 case 3019: return new WarningData (2, "CLS compliance checking will not be performed on '{0}' because it is private or internal");
122                         }
123
124                         throw new InternalErrorException (String.Format ("Wrong warning number '{0}'", warn_no));
125                 }
126                 
127                 static void Check (int code)
128                 {
129                         if (code == expected_error){
130                                 if (Fatal)
131                                         throw new Exception ();
132                                 
133                                 Environment.Exit (0);
134                         }
135                 }
136                 
137                 public static string FriendlyStackTrace (Exception e)
138                 {
139                         return FriendlyStackTrace (new StackTrace (e, true));
140                 }
141                 
142                 static string FriendlyStackTrace (StackTrace t)
143                 {               
144                         StringBuilder sb = new StringBuilder ();
145                         
146                         bool foundUserCode = false;
147                         
148                         for (int i = 0; i < t.FrameCount; i++) {
149                                 StackFrame f = t.GetFrame (i);
150                                 MethodBase mb = f.GetMethod ();
151                                 
152                                 if (!foundUserCode && mb.ReflectedType == typeof (Report))
153                                         continue;
154                                 
155                                 foundUserCode = true;
156                                 
157                                 sb.Append ("\tin ");
158                                 
159                                 if (f.GetFileLineNumber () > 0)
160                                         sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
161                                 
162                                 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
163                                 
164                                 bool first = true;
165                                 foreach (ParameterInfo pi in mb.GetParameters ()) {
166                                         if (!first)
167                                                 sb.Append (", ");
168                                         first = false;
169                                         
170                                         sb.Append (TypeManager.CSharpName (pi.ParameterType));
171                                 }
172                                 sb.Append (")\n");
173                         }
174         
175                         return sb.ToString ();
176                 }
177                 
178                 [Obsolete ("Use SymbolRelatedToPreviousError for better error description")]
179                 static public void LocationOfPreviousError (Location loc)
180                 {
181                         Console.WriteLine (String.Format ("{0}({1}) (Location of symbol related to previous error)", loc.Name, loc.Row));
182                 }                
183
184                 /// <summary>
185                 /// In most error cases is very useful to have information about symbol that caused the error.
186                 /// Call this method before you call Report.Error when it makes sense.
187                 /// </summary>
188                 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
189                 {
190                         SymbolRelatedToPreviousError (String.Format ("{0}({1})", loc.Name, loc.Row), symbol);
191                 }
192
193                 static public void SymbolRelatedToPreviousError (MemberInfo mi)
194                 {
195                         DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
196                         if (temp_ds == null) {
197                                 SymbolRelatedToPreviousError (mi.DeclaringType.Assembly.Location, TypeManager.GetFullNameSignature (mi));
198                         } else {
199                                 string name = String.Concat (temp_ds.Name, ".", mi.Name);
200                                 MemberCore mc = temp_ds.GetDefinition (name) as MemberCore;
201                                 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
202                         }
203                 }
204
205                 static public void SymbolRelatedToPreviousError (Type type)
206                 {
207                         SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
208                 }
209
210                 static void SymbolRelatedToPreviousError (string loc, string symbol)
211                 {
212                         related_symbols.Add (String.Format ("{0}: ('{1}' name of symbol related to previous error)", loc, symbol));
213                 }
214
215                 static public void RealError (string msg)
216                 {
217                         Errors++;
218                         Console.WriteLine (msg);
219
220                         foreach (string s in related_symbols)
221                                 Console.WriteLine (s);
222                         related_symbols.Clear ();
223
224                         if (Stacktrace)
225                                 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
226                         
227                         if (Fatal)
228                                 throw new Exception (msg);
229                 }
230
231
232                 /// <summary>
233                 /// Method reports warning message. Only one reason why exist Warning and Report methods is beter code readability.
234                 /// </summary>
235                 static public void Warning_T (int code, Location loc, params object[] args)
236                 {
237                         WarningData warning = GetWarningMsg (code);
238                         if (warning.IsEnabled ())
239                                 Warning (code, loc, warning.Format (args));
240
241                         related_symbols.Clear ();
242                 }
243
244                 /// <summary>
245                 /// Reports error message.
246                 /// </summary>
247                 static public void Error_T (int code, Location loc, params object[] args)
248                 {
249                         Error_T (code, String.Format ("{0}({1})", loc.Name, loc.Row), args);
250                 }
251
252                 static public void Error_T (int code, string location, params object[] args)
253                 {
254                         string errorText = String.Format (GetErrorMsg (code), args);
255                         PrintError (code, location, errorText);
256                 }
257
258                 static void PrintError (int code, string l, string text)
259                 {
260                         if (code < 0)
261                                 code = 8000-code;
262                         
263                         string msg = String.Format ("{0} error CS{1:0000}: {2}", l, code, text);
264                         RealError (msg);
265                         Check (code);
266                 }
267
268                 static public void Error (int code, Location l, string text)
269                 {
270                         if (code < 0)
271                                 code = 8000-code;
272                         
273                         string msg = String.Format (
274                                 "{0}({1}) error CS{2:0000}: {3}", l.Name, l.Row, code, text);
275 //                              "{0}({1}) error CS{2}: {3}", l.Name, l.Row, code, text);
276                         
277                         RealError (msg);
278                         Check (code);
279                 }
280
281                 static public void Warning (int code, Location l, string text)
282                 {
283                         if (code < 0)
284                                 code = 8000-code;
285                         
286                         if (warning_ignore_table != null){
287                                 if (warning_ignore_table.Contains (code)) {
288                                         related_symbols.Clear ();
289                                         return;
290                                 }
291                         }
292                         
293                         if (WarningsAreErrors)
294                                 Error (code, l, text);
295                         else {
296                                 string row;
297                                 
298                                 if (Location.IsNull (l))
299                                         row = "";
300                                 else
301                                         row = l.Row.ToString ();
302                                 
303                                 Console.WriteLine (String.Format (
304                                         "{0}({1}) warning CS{2:0000}: {3}",
305 //                                      "{0}({1}) warning CS{2}: {3}",
306                                         l.Name,  row, code, text));
307                                 Warnings++;
308
309                                 foreach (string s in related_symbols)
310                                         Console.WriteLine (s);
311                                 related_symbols.Clear ();
312
313                                 Check (code);
314
315                                 if (Stacktrace)
316                                         Console.WriteLine (new StackTrace ().ToString ());
317                         }
318                 }
319                 
320                 static public void Warning (int code, string text)
321                 {
322                         Warning (code, Location.Null, text);
323                 }
324
325                 static public void Warning (int code, int level, string text)
326                 {
327                         if (RootContext.WarningLevel >= level)
328                                 Warning (code, Location.Null, text);
329                 }
330
331                 static public void Warning (int code, int level, Location l, string text)
332                 {
333                         if (RootContext.WarningLevel >= level)
334                                 Warning (code, l, text);
335                 }
336
337                 static public void Error (int code, string text)
338                 {
339                         if (code < 0)
340                                 code = 8000-code;
341                         
342                         string msg = String.Format ("error CS{0:0000}: {1}", code, text);
343 //                      string msg = String.Format ("error CS{0}: {1}", code, text);
344                         
345                         RealError (msg);
346                         Check (code);
347                 }
348
349                 static public void Error (int code, Location loc, string format, params object[] args)
350                 {
351                         Error (code, loc, String.Format (format, args));
352                 }
353
354                 static public void Warning (int code, Location loc, string format, params object[] args)
355                 {
356                         Warning (code, loc, String.Format (format, args));
357                 }
358
359                 static public void Warning (int code, string format, params object[] args)
360                 {
361                         Warning (code, String.Format (format, args));
362                 }
363
364                 static public void Message (Message m)
365                 {
366                         if (m is ErrorMessage)
367                                 Error (m.code, m.text);
368                         else
369                                 Warning (m.code, m.text);
370                 }
371
372                 static public void SetIgnoreWarning (int code)
373                 {
374                         if (warning_ignore_table == null)
375                                 warning_ignore_table = new Hashtable ();
376
377                         warning_ignore_table [code] = true;
378                 }
379                 
380                 static public int ExpectedError {
381                         set {
382                                 expected_error = value;
383                         }
384                         get {
385                                 return expected_error;
386                         }
387                 }
388
389                 public static int DebugFlags = 0;
390
391                 [Conditional ("MCS_DEBUG")]
392                 static public void Debug (string message, params object[] args)
393                 {
394                         Debug (4, message, args);
395                 }
396                         
397                 [Conditional ("MCS_DEBUG")]
398                 static public void Debug (int category, string message, params object[] args)
399                 {
400                         if ((category & DebugFlags) == 0)
401                                 return;
402
403                         StringBuilder sb = new StringBuilder (message);
404
405                         if ((args != null) && (args.Length > 0)) {
406                                 sb.Append (": ");
407
408                                 bool first = true;
409                                 foreach (object arg in args) {
410                                         if (first)
411                                                 first = false;
412                                         else
413                                                 sb.Append (", ");
414                                         if (arg == null)
415                                                 sb.Append ("null");
416                                         else if (arg is ICollection)
417                                                 sb.Append (PrintCollection ((ICollection) arg));
418                                         else if (arg is IntPtr)
419                                                 sb.Append (String.Format ("IntPtr(0x{0:x})", ((IntPtr) arg).ToInt32 ()));
420                                         else
421                                                 sb.Append (arg);
422                                 }
423                         }
424
425                         Console.WriteLine (sb.ToString ());
426                 }
427
428                 static public string PrintCollection (ICollection collection)
429                 {
430                         StringBuilder sb = new StringBuilder ();
431
432                         sb.Append (collection.GetType ());
433                         sb.Append ("(");
434
435                         bool first = true;
436                         foreach (object o in collection) {
437                                 if (first)
438                                         first = false;
439                                 else
440                                         sb.Append (", ");
441                                 sb.Append (o);
442                         }
443
444                         sb.Append (")");
445                         return sb.ToString ();
446                 }
447         }
448
449         public class Message {
450                 public int code;
451                 public string text;
452                 
453                 public Message (int code, string text)
454                 {
455                         this.code = code;
456                         this.text = text;
457                 }
458         }
459
460         public class WarningMessage : Message {
461                 public WarningMessage (int code, string text) : base (code, text)
462                 {
463                 }
464         }
465
466         public class ErrorMessage : Message {
467                 public ErrorMessage (int code, string text) : base (code, text)
468                 {
469                 }
470
471                 //
472                 // For compatibility reasons with old code.
473                 //
474                 public static void report_error (string error)
475                 {
476                         Console.Write ("ERROR: ");
477                         Console.WriteLine (error);
478                 }
479         }
480
481         public enum TimerType {
482                 FindMembers     = 0,
483                 TcFindMembers   = 1,
484                 MemberLookup    = 2,
485                 CachedLookup    = 3,
486                 CacheInit       = 4,
487                 MiscTimer       = 5,
488                 CountTimers     = 6
489         }
490
491         public enum CounterType {
492                 FindMembers     = 0,
493                 MemberCache     = 1,
494                 MiscCounter     = 2,
495                 CountCounters   = 3
496         }
497
498         public class Timer
499         {
500                 static DateTime[] timer_start;
501                 static TimeSpan[] timers;
502                 static long[] timer_counters;
503                 static long[] counters;
504
505                 static Timer ()
506                 {
507                         timer_start = new DateTime [(int) TimerType.CountTimers];
508                         timers = new TimeSpan [(int) TimerType.CountTimers];
509                         timer_counters = new long [(int) TimerType.CountTimers];
510                         counters = new long [(int) CounterType.CountCounters];
511
512                         for (int i = 0; i < (int) TimerType.CountTimers; i++) {
513                                 timer_start [i] = DateTime.Now;
514                                 timers [i] = TimeSpan.Zero;
515                         }
516                 }
517
518                 [Conditional("TIMER")]
519                 static public void IncrementCounter (CounterType which)
520                 {
521                         ++counters [(int) which];
522                 }
523
524                 [Conditional("TIMER")]
525                 static public void StartTimer (TimerType which)
526                 {
527                         timer_start [(int) which] = DateTime.Now;
528                 }
529
530                 [Conditional("TIMER")]
531                 static public void StopTimer (TimerType which)
532                 {
533                         timers [(int) which] += DateTime.Now - timer_start [(int) which];
534                         ++timer_counters [(int) which];
535                 }
536
537                 [Conditional("TIMER")]
538                 static public void ShowTimers ()
539                 {
540                         ShowTimer (TimerType.FindMembers, "- FindMembers timer");
541                         ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
542                         ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
543                         ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
544                         ShowTimer (TimerType.CacheInit, "- Cache init");
545                         ShowTimer (TimerType.MiscTimer, "- Misc timer");
546
547                         ShowCounter (CounterType.FindMembers, "- Find members");
548                         ShowCounter (CounterType.MemberCache, "- Member cache");
549                         ShowCounter (CounterType.MiscCounter, "- Misc counter");
550                 }
551
552                 static public void ShowCounter (CounterType which, string msg)
553                 {
554                         Console.WriteLine ("{0} {1}", counters [(int) which], msg);
555                 }
556
557                 static public void ShowTimer (TimerType which, string msg)
558                 {
559                         Console.WriteLine (
560                                 "[{0:00}:{1:000}] {2} (used {3} times)",
561                                 (int) timers [(int) which].TotalSeconds,
562                                 timers [(int) which].Milliseconds, msg,
563                                 timer_counters [(int) which]);
564                 }
565         }
566
567         public class InternalErrorException : Exception {
568                 public InternalErrorException ()
569                         : base ("Internal error")
570                 {
571                 }
572
573                 public InternalErrorException (string message)
574                         : base (message)
575                 {
576                 }
577
578                 public InternalErrorException (string format, params object[] args)
579                         : this (String.Format (format, args))
580                 { }
581         }
582 }