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