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