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