2 // report.cs: report errors and warnings.
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Copyright 2001 Ximian, Inc. (http://www.ximian.com)
13 using System.Collections;
14 using System.Collections.Specialized;
15 using System.Diagnostics;
16 using System.Reflection;
17 using System.Reflection.Emit;
19 namespace Mono.CSharp {
22 // Errors and warnings manager
26 /// Whether errors should be throw an exception
31 /// Whether warnings should be considered errors
33 public bool WarningsAreErrors;
34 ArrayList warnings_as_error;
35 ArrayList warnings_only;
37 public static int DebugFlags = 0;
40 // Keeps track of the warnings that we are ignoring
42 public Hashtable warning_ignore_table;
44 Hashtable warning_regions_table;
48 ReportPrinter printer;
50 int reporting_disabled;
53 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
55 ArrayList extra_information = new ArrayList ();
58 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
60 public static readonly int[] AllWarnings = new int[] {
62 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
63 219, 251, 252, 253, 278, 282,
64 419, 420, 429, 436, 440, 465, 467, 469, 472,
65 612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675,
68 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
69 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692,
73 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
74 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
75 3021, 3022, 3023, 3026, 3027,
77 414, // Non ISO-1 warnings
79 402, 458, 464, 693, 1058, 1700, 3024
85 // Just to be sure that binary search is working
86 Array.Sort (AllWarnings);
89 public Report (ReportPrinter printer)
92 throw new ArgumentNullException ("printer");
94 this.printer = printer;
98 public void DisableReporting ()
100 ++reporting_disabled;
103 public void EnableReporting ()
105 --reporting_disabled;
108 public void FeatureIsNotAvailable (Location loc, string feature)
111 switch (RootContext.Version) {
112 case LanguageVersion.ISO_1:
115 case LanguageVersion.ISO_2:
118 case LanguageVersion.V_3:
122 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
126 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
130 public void FeatureIsNotSupported (Location loc, string feature)
133 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
137 static bool IsValidWarning (int code)
139 return Array.BinarySearch (AllWarnings, code) >= 0;
142 bool IsWarningEnabled (int code, int level, Location loc)
144 if (WarningLevel < level)
147 if (warning_ignore_table != null) {
148 if (warning_ignore_table.Contains (code)) {
153 if (warning_regions_table == null || loc.IsNull)
156 WarningRegions regions = (WarningRegions) warning_regions_table [loc.Name];
160 return regions.IsWarningEnabled (code, loc.Row);
163 bool IsWarningAsError (int code)
165 bool is_error = WarningsAreErrors;
167 // Check specific list
168 if (warnings_as_error != null)
169 is_error |= warnings_as_error.Contains (code);
171 // Ignore excluded warnings
172 if (warnings_only != null && warnings_only.Contains (code))
178 public void RuntimeMissingSupport (Location loc, string feature)
180 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
184 /// In most error cases is very useful to have information about symbol that caused the error.
185 /// Call this method before you call Report.Error when it makes sense.
187 public void SymbolRelatedToPreviousError (Location loc, string symbol)
189 SymbolRelatedToPreviousError (loc.ToString (), symbol);
192 public void SymbolRelatedToPreviousError (MemberInfo mi)
194 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
197 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
198 if (TypeManager.IsDelegateType (dt)) {
199 SymbolRelatedToPreviousError (dt);
203 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
204 if (temp_ds == null) {
205 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
207 MethodBase mb = mi as MethodBase;
209 mb = TypeManager.DropGenericMethodArguments (mb);
210 IMethodData md = TypeManager.GetMethod (mb);
212 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
217 // FIXME: Completely wrong, it has to use FindMembers
218 MemberCore mc = temp_ds.GetDefinition (mi.Name);
220 SymbolRelatedToPreviousError (mc);
224 public void SymbolRelatedToPreviousError (MemberCore mc)
226 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
229 public void SymbolRelatedToPreviousError (Type type)
231 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
234 type = TypeManager.DropGenericTypeArguments (type);
236 if (TypeManager.IsGenericParameter (type)) {
237 TypeParameter tp = TypeManager.LookupTypeParameter (type);
239 SymbolRelatedToPreviousError (tp.Location, "");
244 if (type is TypeBuilder) {
245 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
246 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
247 } else if (TypeManager.HasElementType (type)) {
248 SymbolRelatedToPreviousError (TypeManager.GetElementType (type));
250 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
254 void SymbolRelatedToPreviousError (string loc, string symbol)
256 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
257 if (extra_information.Contains (msg))
260 extra_information.Add (msg);
263 public void AddWarningAsError (string warningId)
267 id = int.Parse (warningId);
272 if (!CheckWarningCode (id, warningId, Location.Null))
275 if (warnings_as_error == null)
276 warnings_as_error = new ArrayList ();
278 warnings_as_error.Add (id);
281 public void RemoveWarningAsError (string warningId)
285 id = int.Parse (warningId);
290 if (!CheckWarningCode (id, warningId, Location.Null))
293 if (warnings_only == null)
294 warnings_only = new ArrayList ();
296 warnings_only.Add (id);
299 public bool CheckWarningCode (int code, Location loc)
301 return CheckWarningCode (code, code.ToString (), loc);
304 public bool CheckWarningCode (int code, string scode, Location loc)
306 if (IsValidWarning (code))
309 Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
313 public void ExtraInformation (Location loc, string msg)
315 extra_information.Add (String.Format ("{0} {1}", loc, msg));
318 public WarningRegions RegisterWarningRegion (Location location)
320 if (warning_regions_table == null)
321 warning_regions_table = new Hashtable ();
323 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
324 if (regions == null) {
325 regions = new WarningRegions ();
326 warning_regions_table.Add (location.Name, regions);
331 public void Warning (int code, int level, Location loc, string message)
333 if (reporting_disabled > 0)
336 if (!IsWarningEnabled (code, level, loc))
340 if (IsWarningAsError (code))
341 msg = new ErrorMessage (code, loc, message, extra_information);
343 msg = new WarningMessage (code, loc, message, extra_information);
345 extra_information.Clear ();
349 public void Warning (int code, int level, Location loc, string format, string arg)
351 Warning (code, level, loc, String.Format (format, arg));
354 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
356 Warning (code, level, loc, String.Format (format, arg1, arg2));
359 public void Warning (int code, int level, Location loc, string format, params object[] args)
361 Warning (code, level, loc, String.Format (format, args));
364 public void Warning (int code, int level, string message)
366 Warning (code, level, Location.Null, message);
369 public void Warning (int code, int level, string format, string arg)
371 Warning (code, level, Location.Null, format, arg);
374 public void Warning (int code, int level, string format, string arg1, string arg2)
376 Warning (code, level, Location.Null, format, arg1, arg2);
379 public void Warning (int code, int level, string format, params string[] args)
381 Warning (code, level, Location.Null, String.Format (format, args));
385 // Warnings encountered so far
387 public int Warnings {
388 get { return printer.WarningsCount; }
391 public void Error (int code, Location loc, string error)
393 if (reporting_disabled > 0)
396 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
397 extra_information.Clear ();
402 throw new Exception (msg.Text);
405 public void Error (int code, Location loc, string format, string arg)
407 Error (code, loc, String.Format (format, arg));
410 public void Error (int code, Location loc, string format, string arg1, string arg2)
412 Error (code, loc, String.Format (format, arg1, arg2));
415 public void Error (int code, Location loc, string format, params object[] args)
417 Error (code, loc, String.Format (format, args));
420 public void Error (int code, string error)
422 Error (code, Location.Null, error);
425 public void Error (int code, string format, string arg)
427 Error (code, Location.Null, format, arg);
430 public void Error (int code, string format, string arg1, string arg2)
432 Error (code, Location.Null, format, arg1, arg2);
435 public void Error (int code, string format, params string[] args)
437 Error (code, Location.Null, String.Format (format, args));
441 // Errors encountered so far
444 get { return printer.ErrorsCount; }
447 public ReportPrinter Printer {
448 get { return printer; }
451 public void SetIgnoreWarning (int code)
453 if (warning_ignore_table == null)
454 warning_ignore_table = new Hashtable ();
456 warning_ignore_table [code] = true;
459 public ReportPrinter SetPrinter (ReportPrinter printer)
461 ReportPrinter old = this.printer;
462 this.printer = printer;
466 public int WarningLevel {
468 return warning_level;
471 warning_level = value;
475 [Conditional ("MCS_DEBUG")]
476 static public void Debug (string message, params object[] args)
478 Debug (4, message, args);
481 [Conditional ("MCS_DEBUG")]
482 static public void Debug (int category, string message, params object[] args)
484 if ((category & DebugFlags) == 0)
487 StringBuilder sb = new StringBuilder (message);
489 if ((args != null) && (args.Length > 0)) {
493 foreach (object arg in args) {
500 else if (arg is ICollection)
501 sb.Append (PrintCollection ((ICollection) arg));
507 Console.WriteLine (sb.ToString ());
510 static public string PrintCollection (ICollection collection)
512 StringBuilder sb = new StringBuilder ();
514 sb.Append (collection.GetType ());
518 foreach (object o in collection) {
527 return sb.ToString ();
531 public abstract class AbstractMessage
533 readonly string[] extra_info;
534 protected readonly int code;
535 protected readonly Location location;
536 readonly string message;
538 protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
542 this.code = 8000 - code;
546 if (extraInfo.Count != 0) {
547 this.extra_info = (string[])extraInfo.ToArray (typeof (string));
551 protected AbstractMessage (AbstractMessage aMsg)
553 this.code = aMsg.code;
554 this.location = aMsg.location;
555 this.message = aMsg.message;
556 this.extra_info = aMsg.extra_info;
563 public override bool Equals (object obj)
565 AbstractMessage msg = obj as AbstractMessage;
569 return code == msg.code && location.Equals (msg.location) && message == msg.message;
572 public override int GetHashCode ()
574 return code.GetHashCode ();
577 public abstract bool IsWarning { get; }
579 public Location Location {
580 get { return location; }
583 public abstract string MessageType { get; }
585 public string[] RelatedSymbols {
586 get { return extra_info; }
590 get { return message; }
594 sealed class WarningMessage : AbstractMessage
596 public WarningMessage (int code, Location loc, string message, ArrayList extra_info)
597 : base (code, loc, message, extra_info)
601 public override bool IsWarning {
605 public override string MessageType {
612 sealed class ErrorMessage : AbstractMessage
614 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
615 : base (code, loc, message, extraInfo)
619 public ErrorMessage (AbstractMessage aMsg)
624 public override bool IsWarning {
625 get { return false; }
628 public override string MessageType {
636 // Generic base for any message writer
638 public abstract class ReportPrinter
641 /// Whether to dump a stack trace on errors.
643 public bool Stacktrace;
645 int warnings, errors;
647 public int WarningsCount {
648 get { return warnings; }
651 public int ErrorsCount {
652 get { return errors; }
655 protected virtual string FormatText (string txt)
661 // When (symbols related to previous ...) can be used
663 public virtual bool HasRelatedSymbolSupport {
667 public virtual void Print (AbstractMessage msg)
675 protected void Print (AbstractMessage msg, TextWriter output)
677 StringBuilder txt = new StringBuilder ();
678 if (!msg.Location.IsNull) {
679 txt.Append (msg.Location.ToString ());
683 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
686 output.WriteLine (FormatText (txt.ToString ()));
688 output.WriteLine (txt.ToString ());
690 if (msg.RelatedSymbols != null) {
691 foreach (string s in msg.RelatedSymbols)
692 output.WriteLine (s + msg.MessageType + ")");
698 // Default message recorder, it uses two types of message groups.
699 // Common messages: messages reported in all sessions.
700 // Merged messages: union of all messages in all sessions.
702 // Used by the Lambda expressions to compile the code with various
703 // parameter values, or by attribute resolver
705 class SessionReportPrinter : ReportPrinter
707 ArrayList session_messages;
709 // A collection of exactly same messages reported in all sessions
711 ArrayList common_messages;
714 // A collection of unique messages reported in all sessions
716 ArrayList merged_messages;
718 public override void Print (AbstractMessage msg)
721 // This line is useful when debugging recorded messages
723 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
725 if (session_messages == null)
726 session_messages = new ArrayList ();
728 session_messages.Add (msg);
733 public void EndSession ()
735 if (session_messages == null)
739 // Handles the first session
741 if (common_messages == null) {
742 common_messages = new ArrayList (session_messages);
743 merged_messages = session_messages;
744 session_messages = null;
749 // Store common messages if any
751 for (int i = 0; i < common_messages.Count; ++i) {
752 AbstractMessage cmsg = (AbstractMessage) common_messages[i];
753 bool common_msg_found = false;
754 foreach (AbstractMessage msg in session_messages) {
755 if (cmsg.Equals (msg)) {
756 common_msg_found = true;
761 if (!common_msg_found)
762 common_messages.RemoveAt (i);
766 // Merge session and previous messages
768 for (int i = 0; i < session_messages.Count; ++i) {
769 AbstractMessage msg = (AbstractMessage) session_messages[i];
770 bool msg_found = false;
771 for (int ii = 0; ii < merged_messages.Count; ++ii) {
772 if (msg.Equals (merged_messages[ii])) {
779 merged_messages.Add (msg);
783 public bool IsEmpty {
785 return merged_messages == null && common_messages == null;
790 // Prints collected messages, common messages have a priority
792 public bool Merge (ReportPrinter dest)
794 ArrayList messages_to_print = merged_messages;
795 if (common_messages != null && common_messages.Count > 0) {
796 messages_to_print = common_messages;
799 if (messages_to_print == null)
802 foreach (AbstractMessage msg in messages_to_print)
809 class StreamReportPrinter : ReportPrinter
813 public StreamReportPrinter (TextWriter writer)
815 this.writer = writer;
818 public override void Print (AbstractMessage msg)
825 class ConsoleReportPrinter : ReportPrinter
827 static readonly string prefix, postfix;
829 static ConsoleReportPrinter ()
831 string term = Environment.GetEnvironmentVariable ("TERM");
832 bool xterm_colors = false;
838 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
850 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
853 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
855 config = "errors=red";
856 //config = "brightwhite,red";
859 if (config == "disable")
862 if (!config.StartsWith ("errors="))
865 config = config.Substring (7);
867 int p = config.IndexOf (",");
869 prefix = GetForeground (config);
871 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
872 postfix = "\x001b[0m";
875 static int NameToCode (string s)
900 // maps a color name to its xterm color code
902 static string GetForeground (string s)
906 if (s.StartsWith ("bright")) {
912 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
915 static string GetBackground (string s)
917 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
920 protected override string FormatText (string txt)
923 return prefix + txt + postfix;
928 static string FriendlyStackTrace (StackTrace t)
930 StringBuilder sb = new StringBuilder ();
932 bool foundUserCode = false;
934 for (int i = 0; i < t.FrameCount; i++) {
935 StackFrame f = t.GetFrame (i);
936 MethodBase mb = f.GetMethod ();
938 if (!foundUserCode && mb.ReflectedType == typeof (Report))
941 foundUserCode = true;
945 if (f.GetFileLineNumber () > 0)
946 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
948 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
951 foreach (ParameterInfo pi in mb.GetParameters ()) {
956 sb.Append (TypeManager.CSharpName (pi.ParameterType));
961 return sb.ToString ();
964 public override void Print (AbstractMessage msg)
966 Print (msg, Console.Error);
970 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
973 public static string FriendlyStackTrace (Exception e)
975 return FriendlyStackTrace (new StackTrace (e, true));
978 public static void StackTrace ()
980 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
984 public enum TimerType {
994 public enum CounterType {
1003 static DateTime[] timer_start;
1004 static TimeSpan[] timers;
1005 static long[] timer_counters;
1006 static long[] counters;
1010 timer_start = new DateTime [(int) TimerType.CountTimers];
1011 timers = new TimeSpan [(int) TimerType.CountTimers];
1012 timer_counters = new long [(int) TimerType.CountTimers];
1013 counters = new long [(int) CounterType.CountCounters];
1015 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
1016 timer_start [i] = DateTime.Now;
1017 timers [i] = TimeSpan.Zero;
1021 [Conditional("TIMER")]
1022 static public void IncrementCounter (CounterType which)
1024 ++counters [(int) which];
1027 [Conditional("TIMER")]
1028 static public void StartTimer (TimerType which)
1030 timer_start [(int) which] = DateTime.Now;
1033 [Conditional("TIMER")]
1034 static public void StopTimer (TimerType which)
1036 timers [(int) which] += DateTime.Now - timer_start [(int) which];
1037 ++timer_counters [(int) which];
1040 [Conditional("TIMER")]
1041 static public void ShowTimers ()
1043 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
1044 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
1045 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
1046 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
1047 ShowTimer (TimerType.CacheInit, "- Cache init");
1048 ShowTimer (TimerType.MiscTimer, "- Misc timer");
1050 ShowCounter (CounterType.FindMembers, "- Find members");
1051 ShowCounter (CounterType.MemberCache, "- Member cache");
1052 ShowCounter (CounterType.MiscCounter, "- Misc counter");
1055 static public void ShowCounter (CounterType which, string msg)
1057 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
1060 static public void ShowTimer (TimerType which, string msg)
1063 "[{0:00}:{1:000}] {2} (used {3} times)",
1064 (int) timers [(int) which].TotalSeconds,
1065 timers [(int) which].Milliseconds, msg,
1066 timer_counters [(int) which]);
1070 public class InternalErrorException : Exception {
1071 public InternalErrorException (MemberCore mc, Exception e)
1072 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1076 public InternalErrorException ()
1077 : base ("Internal error")
1081 public InternalErrorException (string message)
1086 public InternalErrorException (string message, params object[] args)
1087 : base (String.Format (message, args))
1090 public InternalErrorException (Exception e, Location loc)
1091 : base (loc.ToString (), e)
1097 /// Handles #pragma warning
1099 public class WarningRegions {
1101 abstract class PragmaCmd
1105 protected PragmaCmd (int line)
1110 public abstract bool IsEnabled (int code, bool previous);
1113 class Disable : PragmaCmd
1116 public Disable (int line, int code)
1122 public override bool IsEnabled (int code, bool previous)
1124 return this.code == code ? false : previous;
1128 class DisableAll : PragmaCmd
1130 public DisableAll (int line)
1133 public override bool IsEnabled(int code, bool previous)
1139 class Enable : PragmaCmd
1142 public Enable (int line, int code)
1148 public override bool IsEnabled(int code, bool previous)
1150 return this.code == code ? true : previous;
1154 class EnableAll : PragmaCmd
1156 public EnableAll (int line)
1159 public override bool IsEnabled(int code, bool previous)
1166 ArrayList regions = new ArrayList ();
1168 public void WarningDisable (int line)
1170 regions.Add (new DisableAll (line));
1173 public void WarningDisable (Location location, int code, Report Report)
1175 if (Report.CheckWarningCode (code, location))
1176 regions.Add (new Disable (location.Row, code));
1179 public void WarningEnable (int line)
1181 regions.Add (new EnableAll (line));
1184 public void WarningEnable (Location location, int code, Report Report)
1186 if (Report.CheckWarningCode (code, location))
1187 regions.Add (new Enable (location.Row, code));
1190 public bool IsWarningEnabled (int code, int src_line)
1193 foreach (PragmaCmd pragma in regions) {
1194 if (src_line < pragma.Line)
1197 result = pragma.IsEnabled (code, result);