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