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