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