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