2 // report.cs: report errors and warnings.
4 // Author: Miguel de Icaza (miguel@ximian.com)
6 // (C) 2001 Ximian, Inc. (http://www.ximian.com)
10 // FIXME: currently our class library does not support custom number format strings
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Diagnostics;
18 using System.Reflection;
19 using System.Reflection.Emit;
21 namespace Mono.CSharp {
24 /// This class is used to report errors and warnings t te user.
28 /// Errors encountered so far
30 static public int Errors;
33 /// Warnings encountered so far
35 static public int Warnings;
38 /// Whether errors should be throw an exception
40 static public bool Fatal;
43 /// Whether warnings should be considered errors
45 static public bool WarningsAreErrors;
48 /// Whether to dump a stack trace on errors.
50 static public bool Stacktrace;
52 static public TextWriter Stderr = Console.Error;
55 // If the 'expected' error code is reported then the
56 // compilation succeeds.
58 // Used for the test suite to excercise the error codes
60 static int expected_error = 0;
63 // Keeps track of the warnings that we are ignoring
65 public static Hashtable warning_ignore_table;
67 static Hashtable warning_regions_table;
70 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
72 static StringCollection extra_information = new StringCollection ();
74 public static void Reset ()
76 Errors = Warnings = 0;
77 WarningsAreErrors = false;
78 warning_ignore_table = null;
79 warning_regions_table = null;
82 abstract class AbstractMessage {
84 static void Check (int code)
86 if (code == expected_error) {
91 public abstract bool IsWarning { get; }
93 public abstract string MessageType { get; }
95 public virtual void Print (int code, string location, string text)
100 StringBuilder msg = new StringBuilder ();
101 if (location.Length != 0) {
102 msg.Append (location);
105 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, text);
106 Stderr.WriteLine (msg.ToString ());
108 foreach (string s in extra_information)
109 Stderr.WriteLine (s + MessageType);
111 extra_information.Clear ();
114 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
117 if (!IsWarning || WarningsAreErrors)
118 throw new Exception (text);
124 public virtual void Print (int code, Location location, string text)
126 if (location.Equals (Location.Null)) {
127 Print (code, "", text);
130 Print (code, String.Format ("{0}({1})", location.Name, location.Row), text);
134 sealed class WarningMessage: AbstractMessage {
135 Location loc = Location.Null;
138 public WarningMessage ():
141 public WarningMessage (int level)
146 public override bool IsWarning {
150 bool IsEnabled (int code)
152 if (RootContext.WarningLevel < Level)
155 if (warning_ignore_table != null) {
156 if (warning_ignore_table.Contains (code)) {
161 if (warning_regions_table == null || loc.Equals (Location.Null))
164 WarningRegions regions = (WarningRegions)warning_regions_table [loc.Name];
168 return regions.IsWarningEnabled (code, loc.Row);
171 public override void Print(int code, string location, string text)
173 if (!IsEnabled (code)) {
174 extra_information.Clear ();
178 if (WarningsAreErrors) {
179 new ErrorMessage ().Print (code, location, text);
184 base.Print (code, location, text);
187 public override void Print(int code, Location location, string text)
190 base.Print (code, location, text);
193 public override string MessageType {
200 sealed class ErrorMessage: AbstractMessage {
202 public override void Print(int code, string location, string text)
205 base.Print (code, location, text);
208 public override bool IsWarning {
209 get { return false; }
212 public override string MessageType {
220 public static void FeatureIsNotStandardized (Location loc, string feature)
222 Report.Error (1644, loc, "Feature '{0}' cannot be used because it is not part of the standardized ISO C# language specification", feature);
225 public static string FriendlyStackTrace (Exception e)
227 return FriendlyStackTrace (new StackTrace (e, true));
230 static string FriendlyStackTrace (StackTrace t)
232 StringBuilder sb = new StringBuilder ();
234 bool foundUserCode = false;
236 for (int i = 0; i < t.FrameCount; i++) {
237 StackFrame f = t.GetFrame (i);
238 MethodBase mb = f.GetMethod ();
240 if (!foundUserCode && mb.ReflectedType == typeof (Report))
243 foundUserCode = true;
247 if (f.GetFileLineNumber () > 0)
248 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
250 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
253 foreach (ParameterInfo pi in mb.GetParameters ()) {
258 sb.Append (TypeManager.CSharpName (pi.ParameterType));
263 return sb.ToString ();
266 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
267 // IF YOU ADD A NEW WARNING YOU HAVE TO DUPLICATE ITS ID HERE
269 public static bool IsValidWarning (int code)
271 int[] all_warnings = new int[] {
272 28, 67, 78, 105, 108, 109, 114, 192, 168, 169, 183, 184, 219, 251, 612, 618, 626, 628, 642, 649,
273 659, 660, 661, 672, 1030, 1522, 1616, 1691, 1692, 1901, 2002, 2023, 3012, 3019, 8024, 8028
276 foreach (int i in all_warnings) {
283 static public void LocationOfPreviousError (Location loc)
285 Stderr.WriteLine (String.Format ("{0}({1}) (Location of symbol related to previous error)", loc.Name, loc.Row));
288 static public void RuntimeMissingSupport (Location loc, string feature)
290 Report.Error (-88, loc, "Your .NET Runtime does not support '{0}'. Please use the latest Mono runtime instead.", feature);
294 /// In most error cases is very useful to have information about symbol that caused the error.
295 /// Call this method before you call Report.Error when it makes sense.
297 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
299 SymbolRelatedToPreviousError (String.Format ("{0}({1})", loc.Name, loc.Row), symbol);
302 static public void SymbolRelatedToPreviousError (MemberInfo mi)
304 TypeContainer temp_ds = TypeManager.LookupGenericTypeContainer (mi.DeclaringType);
305 if (temp_ds == null) {
306 SymbolRelatedToPreviousError (mi.DeclaringType.Assembly.Location, TypeManager.GetFullNameSignature (mi));
308 MethodBase mb = mi as MethodBase;
310 while (mb.Mono_IsInflatedMethod)
311 mb = mb.GetGenericMethodDefinition ();
312 IMethodData md = TypeManager.GetMethod (mb);
313 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError (temp_ds));
317 MemberCore mc = temp_ds.GetDefinition (mi.Name);
318 SymbolRelatedToPreviousError (mc);
322 static public void SymbolRelatedToPreviousError (MemberCore mc)
324 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
327 static public void SymbolRelatedToPreviousError (Type type)
329 if (type.IsGenericInstance)
330 type = type.GetGenericTypeDefinition ();
331 if (type is TypeBuilder) {
332 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
333 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
334 } else if (type.HasElementType) {
335 SymbolRelatedToPreviousError (type.GetElementType ());
337 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
341 static void SymbolRelatedToPreviousError (string loc, string symbol)
343 extra_information.Add (String.Format ("{0}: '{1}' (name of symbol related to previous ", loc, symbol));
346 public static void ExtraInformation (Location loc, string msg)
348 extra_information.Add (String.Format ("{0}({1}) {2}", loc.Name, loc.Row, msg));
351 public static WarningRegions RegisterWarningRegion (Location location)
353 if (warning_regions_table == null)
354 warning_regions_table = new Hashtable ();
356 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
357 if (regions == null) {
358 regions = new WarningRegions ();
359 warning_regions_table.Add (location.Name, regions);
364 static public void Warning (int code, int level, Location loc, string format, params object[] args)
366 WarningMessage w = new WarningMessage (level);
367 w.Print (code, loc, String.Format (format, args));
370 static public void Warning (int code, Location loc, string format, params object[] args)
372 WarningMessage w = new WarningMessage ();
373 w.Print (code, loc, String.Format (format, args));
376 static public void Warning (int code, string format, params object[] args)
378 Warning (code, Location.Null, String.Format (format, args));
382 /// Did you test your WarningLevel, that you use this method
384 static public void Warning (int code, string text)
386 Warning (code, Location.Null, text);
389 static public void Error (int code, string format, params object[] args)
391 Error (code, Location.Null, String.Format (format, args));
394 static public void Error (int code, Location loc, string format, params object[] args)
396 ErrorMessage e = new ErrorMessage ();
397 e.Print (code, loc, String.Format (format, args));
400 static public void SetIgnoreWarning (int code)
402 if (warning_ignore_table == null)
403 warning_ignore_table = new Hashtable ();
405 warning_ignore_table [code] = true;
408 static public int ExpectedError {
410 expected_error = value;
413 return expected_error;
417 public static int DebugFlags = 0;
419 [Conditional ("MCS_DEBUG")]
420 static public void Debug (string message, params object[] args)
422 Debug (4, message, args);
425 [Conditional ("MCS_DEBUG")]
426 static public void Debug (int category, string message, params object[] args)
428 if ((category & DebugFlags) == 0)
431 StringBuilder sb = new StringBuilder (message);
433 if ((args != null) && (args.Length > 0)) {
437 foreach (object arg in args) {
444 else if (arg is ICollection)
445 sb.Append (PrintCollection ((ICollection) arg));
451 Console.WriteLine (sb.ToString ());
454 static public string PrintCollection (ICollection collection)
456 StringBuilder sb = new StringBuilder ();
458 sb.Append (collection.GetType ());
462 foreach (object o in collection) {
471 return sb.ToString ();
475 public enum TimerType {
485 public enum CounterType {
494 static DateTime[] timer_start;
495 static TimeSpan[] timers;
496 static long[] timer_counters;
497 static long[] counters;
501 timer_start = new DateTime [(int) TimerType.CountTimers];
502 timers = new TimeSpan [(int) TimerType.CountTimers];
503 timer_counters = new long [(int) TimerType.CountTimers];
504 counters = new long [(int) CounterType.CountCounters];
506 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
507 timer_start [i] = DateTime.Now;
508 timers [i] = TimeSpan.Zero;
512 [Conditional("TIMER")]
513 static public void IncrementCounter (CounterType which)
515 ++counters [(int) which];
518 [Conditional("TIMER")]
519 static public void StartTimer (TimerType which)
521 timer_start [(int) which] = DateTime.Now;
524 [Conditional("TIMER")]
525 static public void StopTimer (TimerType which)
527 timers [(int) which] += DateTime.Now - timer_start [(int) which];
528 ++timer_counters [(int) which];
531 [Conditional("TIMER")]
532 static public void ShowTimers ()
534 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
535 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
536 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
537 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
538 ShowTimer (TimerType.CacheInit, "- Cache init");
539 ShowTimer (TimerType.MiscTimer, "- Misc timer");
541 ShowCounter (CounterType.FindMembers, "- Find members");
542 ShowCounter (CounterType.MemberCache, "- Member cache");
543 ShowCounter (CounterType.MiscCounter, "- Misc counter");
546 static public void ShowCounter (CounterType which, string msg)
548 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
551 static public void ShowTimer (TimerType which, string msg)
554 "[{0:00}:{1:000}] {2} (used {3} times)",
555 (int) timers [(int) which].TotalSeconds,
556 timers [(int) which].Milliseconds, msg,
557 timer_counters [(int) which]);
561 public class InternalErrorException : Exception {
562 public InternalErrorException ()
563 : base ("Internal error")
567 public InternalErrorException (string message)
574 /// Handles #pragma warning
576 public class WarningRegions {
578 abstract class PragmaCmd
582 protected PragmaCmd (int line)
587 public abstract bool IsEnabled (int code, bool previous);
590 class Disable: PragmaCmd
593 public Disable (int line, int code)
599 public override bool IsEnabled (int code, bool previous)
601 return this.code == code ? false : previous;
605 class DisableAll: PragmaCmd
607 public DisableAll (int line)
610 public override bool IsEnabled(int code, bool previous)
616 class Enable: PragmaCmd
619 public Enable (int line, int code)
625 public override bool IsEnabled(int code, bool previous)
627 return this.code == code ? true : previous;
631 class EnableAll: PragmaCmd
633 public EnableAll (int line)
636 public override bool IsEnabled(int code, bool previous)
643 ArrayList regions = new ArrayList ();
645 public void WarningDisable (int line)
647 regions.Add (new DisableAll (line));
650 public void WarningDisable (Location location, int code)
652 if (CheckWarningCode (code, location))
653 regions.Add (new Disable (location.Row, code));
656 public void WarningEnable (int line)
658 regions.Add (new EnableAll (line));
661 public void WarningEnable (Location location, int code)
663 if (CheckWarningCode (code, location))
664 regions.Add (new Enable (location.Row, code));
667 public bool IsWarningEnabled (int code, int src_line)
670 foreach (PragmaCmd pragma in regions) {
671 if (src_line < pragma.Line)
674 result = pragma.IsEnabled (code, result);
679 bool CheckWarningCode (int code, Location loc)
681 if (Report.IsValidWarning (code))
684 Report.Warning (1691, 1, loc, "'{0}' is not a valid warning number", code);