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 /// This class is used to report errors and warnings t te user.
26 /// Errors encountered so far
28 static public int Errors;
31 /// Warnings encountered so far
33 static public int Warnings;
36 /// Whether errors should be throw an exception
38 static public bool Fatal;
41 /// Whether warnings should be considered errors
43 static public bool WarningsAreErrors;
44 static ArrayList warnings_as_error;
47 /// Whether to dump a stack trace on errors.
49 static public bool Stacktrace;
51 static public TextWriter Stderr = Console.Error;
54 // If the 'expected' error code is reported then the
55 // compilation succeeds.
57 // Used for the test suite to excercise the error codes
59 static int expected_error = 0;
62 // Keeps track of the warnings that we are ignoring
64 public static Hashtable warning_ignore_table;
66 static Hashtable warning_regions_table;
69 // This is used to save/restore the error state. When the
70 // error stack contains elements, warnings and errors are not
71 // reported to the user. This is used by the Lambda expression
72 // support to compile the code with various parameter values.
73 // A stack because of `Report.Errors == errors;'
75 static Stack error_stack;
76 static Stack warning_stack;
77 static bool reporting_disabled;
79 static int warning_level;
82 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
84 static ArrayList extra_information = new ArrayList ();
87 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
89 public static readonly int[] AllWarnings = new int[] {
91 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
92 219, 251, 252, 253, 278, 282,
93 419, 420, 429, 436, 440, 465, 467, 469, 472,
94 612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675,
97 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
98 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692,
102 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
103 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
104 3021, 3022, 3023, 3026, 3027,
106 414, // Non ISO-1 warnings
108 402, 458, 464, 693, 1058, 1700, 3024
114 // Just to be sure that binary search is working
115 Array.Sort (AllWarnings);
118 public static void Reset ()
120 Errors = Warnings = 0;
121 WarningsAreErrors = false;
122 warning_ignore_table = null;
123 warning_regions_table = null;
124 reporting_disabled = false;
125 error_stack = warning_stack = null;
126 warnings_as_error = null;
129 public static void DisableReporting ()
131 if (error_stack == null)
132 error_stack = new Stack ();
133 error_stack.Push (Errors);
136 if (warning_stack == null)
137 warning_stack = new Stack ();
138 warning_stack.Push (Warnings);
141 reporting_disabled = true;
144 public static void EnableReporting ()
146 if (warning_stack != null && warning_stack.Count > 0)
147 Warnings = (int) warning_stack.Pop ();
151 Errors = (int) error_stack.Pop ();
152 if (error_stack.Count == 0) {
153 reporting_disabled = false;
157 public static IMessageRecorder msg_recorder;
159 public static IMessageRecorder SetMessageRecorder (IMessageRecorder recorder)
161 IMessageRecorder previous = msg_recorder;
162 msg_recorder = recorder;
166 public interface IMessageRecorder
168 bool IsEmpty { get; }
170 void AddMessage (AbstractMessage msg);
171 bool PrintMessages ();
175 // Default message recorder, it uses two types of message groups.
176 // Common messages: messages reported in all sessions.
177 // Merged messages: union of all messages in all sessions.
179 public struct MessageRecorder : IMessageRecorder
181 ArrayList session_messages;
183 // A collection of exactly same messages reported in all sessions
185 ArrayList common_messages;
188 // A collection of unique messages reported in all sessions
190 ArrayList merged_messages;
192 public void EndSession ()
194 if (session_messages == null)
198 // Handles the first session
200 if (common_messages == null) {
201 common_messages = new ArrayList (session_messages);
202 merged_messages = session_messages;
203 session_messages = null;
208 // Store common messages if any
210 for (int i = 0; i < common_messages.Count; ++i) {
211 AbstractMessage cmsg = (AbstractMessage) common_messages [i];
212 bool common_msg_found = false;
213 foreach (AbstractMessage msg in session_messages) {
214 if (cmsg.Equals (msg)) {
215 common_msg_found = true;
220 if (!common_msg_found)
221 common_messages.RemoveAt (i);
225 // Merge session and previous messages
227 for (int i = 0; i < session_messages.Count; ++i) {
228 AbstractMessage msg = (AbstractMessage) session_messages [i];
229 bool msg_found = false;
230 for (int ii = 0; ii < merged_messages.Count; ++ii) {
231 if (msg.Equals (merged_messages [ii])) {
238 merged_messages.Add (msg);
242 public void AddMessage (AbstractMessage msg)
244 if (session_messages == null)
245 session_messages = new ArrayList ();
247 session_messages.Add (msg);
250 public bool IsEmpty {
252 return merged_messages == null && common_messages == null;
257 // Prints collected messages, common messages have a priority
259 public bool PrintMessages ()
261 ArrayList messages_to_print = merged_messages;
262 if (common_messages != null && common_messages.Count > 0) {
263 messages_to_print = common_messages;
266 if (messages_to_print == null)
269 foreach (AbstractMessage msg in messages_to_print)
276 public abstract class AbstractMessage
278 readonly string[] extra_info;
279 protected readonly int code;
280 protected readonly Location location;
281 readonly string message;
283 protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
287 this.code = 8000 - code;
291 if (extraInfo.Count != 0) {
292 this.extra_info = (string[])extraInfo.ToArray (typeof (string));
296 protected AbstractMessage (AbstractMessage aMsg)
298 this.code = aMsg.code;
299 this.location = aMsg.location;
300 this.message = aMsg.message;
301 this.extra_info = aMsg.extra_info;
304 static void Check (int code)
306 if (code == expected_error) {
307 Environment.Exit (0);
311 public override bool Equals (object obj)
313 AbstractMessage msg = obj as AbstractMessage;
317 return code == msg.code && location.Equals (msg.location) && message == msg.message;
320 public override int GetHashCode ()
322 return code.GetHashCode ();
325 public abstract bool IsWarning { get; }
327 public abstract string MessageType { get; }
329 public virtual void Print ()
331 if (msg_recorder != null) {
333 // This line is useful when debugging messages recorder
335 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
336 msg_recorder.AddMessage (this);
340 if (reporting_disabled)
343 StringBuilder msg = new StringBuilder ();
344 if (!location.IsNull) {
345 msg.Append (location.ToString ());
348 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, message);
352 if (Stderr == Console.Error)
353 Stderr.WriteLine (ColorFormat (msg.ToString ()));
355 Stderr.WriteLine (msg.ToString ());
357 if (extra_info != null) {
358 foreach (string s in extra_info)
359 Stderr.WriteLine (s + MessageType + ")");
363 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
366 if (!IsWarning || WarningsAreErrors)
367 throw new Exception (message);
373 protected virtual string ColorFormat (string s)
379 sealed class WarningMessage : AbstractMessage
383 public WarningMessage (int code, int level, Location loc, string message, ArrayList extra_info)
384 : base (code, loc, message, extra_info)
389 public override bool IsWarning {
395 if (WarningLevel < Level)
398 if (warning_ignore_table != null) {
399 if (warning_ignore_table.Contains (code)) {
404 if (warning_regions_table == null || location.IsNull)
407 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
411 return regions.IsWarningEnabled (code, location.Row);
414 bool IsErrorWarning {
416 if (WarningsAreErrors)
419 if (warnings_as_error == null)
422 return warnings_as_error.Contains (code);
426 public override void Print ()
431 if (IsErrorWarning) {
432 new ErrorMessage (this).Print ();
440 public override string MessageType {
447 static int NameToCode (string s)
472 // maps a color name to its xterm color code
474 static string GetForeground (string s)
478 if (s.StartsWith ("bright")){
484 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
487 static string GetBackground (string s)
489 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
492 sealed class ErrorMessage : AbstractMessage
494 static string prefix, postfix;
496 static ErrorMessage ()
498 string term = Environment.GetEnvironmentVariable ("TERM");
499 bool xterm_colors = false;
505 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
517 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
520 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
522 config = "errors=red";
523 //config = "brightwhite,red";
526 if (config == "disable")
529 if (!config.StartsWith ("errors="))
532 config = config.Substring (7);
534 int p = config.IndexOf (",");
536 prefix = GetForeground (config);
538 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
539 postfix = "\x001b[0m";
542 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
543 : base (code, loc, message, extraInfo)
547 public ErrorMessage (AbstractMessage aMsg)
552 protected override string ColorFormat (string s)
555 return prefix + s + postfix;
559 public override void Print()
565 public override bool IsWarning {
566 get { return false; }
569 public override string MessageType {
576 public static void FeatureIsNotAvailable (Location loc, string feature)
579 switch (RootContext.Version) {
580 case LanguageVersion.ISO_1:
583 case LanguageVersion.ISO_2:
586 case LanguageVersion.Default_MCS:
587 Report.Error (1644, loc, "Feature `{0}' is not available in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
591 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
594 Report.Error (1644, loc,
595 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
599 public static string FriendlyStackTrace (Exception e)
601 return FriendlyStackTrace (new StackTrace (e, true));
604 static string FriendlyStackTrace (StackTrace t)
606 StringBuilder sb = new StringBuilder ();
608 bool foundUserCode = false;
610 for (int i = 0; i < t.FrameCount; i++) {
611 StackFrame f = t.GetFrame (i);
612 MethodBase mb = f.GetMethod ();
614 if (!foundUserCode && mb.ReflectedType == typeof (Report))
617 foundUserCode = true;
621 if (f.GetFileLineNumber () > 0)
622 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
624 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
627 foreach (ParameterInfo pi in mb.GetParameters ()) {
632 sb.Append (TypeManager.CSharpName (pi.ParameterType));
637 return sb.ToString ();
640 public static void StackTrace ()
642 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
645 static bool IsValidWarning (int code)
647 return Array.BinarySearch (AllWarnings, code) >= 0;
650 static public void RuntimeMissingSupport (Location loc, string feature)
652 Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
656 /// In most error cases is very useful to have information about symbol that caused the error.
657 /// Call this method before you call Report.Error when it makes sense.
659 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
661 SymbolRelatedToPreviousError (loc.ToString (), symbol);
664 static public void SymbolRelatedToPreviousError (MemberInfo mi)
666 if (reporting_disabled)
669 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
670 if (TypeManager.IsDelegateType (dt)) {
671 SymbolRelatedToPreviousError (dt);
675 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
676 if (temp_ds == null) {
677 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
679 MethodBase mb = mi as MethodBase;
681 mb = TypeManager.DropGenericMethodArguments (mb);
682 IMethodData md = TypeManager.GetMethod (mb);
683 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
687 // FIXME: Completely wrong, it has to use FindMembers
688 MemberCore mc = temp_ds.GetDefinition (mi.Name);
690 SymbolRelatedToPreviousError (mc);
694 static public void SymbolRelatedToPreviousError (MemberCore mc)
696 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
699 static public void SymbolRelatedToPreviousError (Type type)
701 if (reporting_disabled)
704 type = TypeManager.DropGenericTypeArguments (type);
706 if (TypeManager.IsGenericParameter (type)) {
707 TypeParameter tp = TypeManager.LookupTypeParameter (type);
709 SymbolRelatedToPreviousError (tp.Location, "");
714 if (type is TypeBuilder) {
715 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
716 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
717 } else if (TypeManager.HasElementType (type)) {
718 SymbolRelatedToPreviousError (TypeManager.GetElementType (type));
720 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
724 static void SymbolRelatedToPreviousError (string loc, string symbol)
726 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
727 if (extra_information.Contains (msg))
730 extra_information.Add (msg);
733 public static void AddWarningAsError (string warningId)
737 id = int.Parse (warningId);
742 if (!CheckWarningCode (id, warningId, Location.Null))
745 if (warnings_as_error == null)
746 warnings_as_error = new ArrayList ();
748 warnings_as_error.Add (id);
751 public static bool CheckWarningCode (int code, Location loc)
753 return CheckWarningCode (code, code.ToString (), loc);
756 public static bool CheckWarningCode (int code, string scode, Location loc)
758 if (IsValidWarning (code))
761 Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
765 public static void ExtraInformation (Location loc, string msg)
767 extra_information.Add (String.Format ("{0} {1}", loc, msg));
770 public static WarningRegions RegisterWarningRegion (Location location)
772 if (warning_regions_table == null)
773 warning_regions_table = new Hashtable ();
775 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
776 if (regions == null) {
777 regions = new WarningRegions ();
778 warning_regions_table.Add (location.Name, regions);
783 static public void Warning (int code, int level, Location loc, string message)
785 WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
786 extra_information.Clear ();
790 static public void Warning (int code, int level, Location loc, string format, string arg)
792 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
793 extra_information.Clear ();
797 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
799 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
800 extra_information.Clear ();
804 static public void Warning (int code, int level, Location loc, string format, params object[] args)
806 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
807 extra_information.Clear ();
811 static public void Warning (int code, int level, string message)
813 Warning (code, level, Location.Null, message);
816 static public void Warning (int code, int level, string format, string arg)
818 Warning (code, level, Location.Null, format, arg);
821 static public void Warning (int code, int level, string format, string arg1, string arg2)
823 Warning (code, level, Location.Null, format, arg1, arg2);
826 static public void Warning (int code, int level, string format, params string[] args)
828 Warning (code, level, Location.Null, String.Format (format, args));
831 static public void Error (int code, Location loc, string error)
833 new ErrorMessage (code, loc, error, extra_information).Print ();
834 extra_information.Clear ();
837 static public void Error (int code, Location loc, string format, string arg)
839 new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
840 extra_information.Clear ();
843 static public void Error (int code, Location loc, string format, string arg1, string arg2)
845 new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
846 extra_information.Clear ();
849 static public void Error (int code, Location loc, string format, params object[] args)
851 Error (code, loc, String.Format (format, args));
854 static public void Error (int code, string error)
856 Error (code, Location.Null, error);
859 static public void Error (int code, string format, string arg)
861 Error (code, Location.Null, format, arg);
864 static public void Error (int code, string format, string arg1, string arg2)
866 Error (code, Location.Null, format, arg1, arg2);
869 static public void Error (int code, string format, params string[] args)
871 Error (code, Location.Null, String.Format (format, args));
874 static public void SetIgnoreWarning (int code)
876 if (warning_ignore_table == null)
877 warning_ignore_table = new Hashtable ();
879 warning_ignore_table [code] = true;
882 static public int ExpectedError {
884 expected_error = value;
887 return expected_error;
891 public static int WarningLevel {
893 return warning_level;
896 warning_level = value;
900 public static int DebugFlags = 0;
902 [Conditional ("MCS_DEBUG")]
903 static public void Debug (string message, params object[] args)
905 Debug (4, message, args);
908 [Conditional ("MCS_DEBUG")]
909 static public void Debug (int category, string message, params object[] args)
911 if ((category & DebugFlags) == 0)
914 StringBuilder sb = new StringBuilder (message);
916 if ((args != null) && (args.Length > 0)) {
920 foreach (object arg in args) {
927 else if (arg is ICollection)
928 sb.Append (PrintCollection ((ICollection) arg));
934 Console.WriteLine (sb.ToString ());
937 static public string PrintCollection (ICollection collection)
939 StringBuilder sb = new StringBuilder ();
941 sb.Append (collection.GetType ());
945 foreach (object o in collection) {
954 return sb.ToString ();
958 public enum TimerType {
968 public enum CounterType {
977 static DateTime[] timer_start;
978 static TimeSpan[] timers;
979 static long[] timer_counters;
980 static long[] counters;
984 timer_start = new DateTime [(int) TimerType.CountTimers];
985 timers = new TimeSpan [(int) TimerType.CountTimers];
986 timer_counters = new long [(int) TimerType.CountTimers];
987 counters = new long [(int) CounterType.CountCounters];
989 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
990 timer_start [i] = DateTime.Now;
991 timers [i] = TimeSpan.Zero;
995 [Conditional("TIMER")]
996 static public void IncrementCounter (CounterType which)
998 ++counters [(int) which];
1001 [Conditional("TIMER")]
1002 static public void StartTimer (TimerType which)
1004 timer_start [(int) which] = DateTime.Now;
1007 [Conditional("TIMER")]
1008 static public void StopTimer (TimerType which)
1010 timers [(int) which] += DateTime.Now - timer_start [(int) which];
1011 ++timer_counters [(int) which];
1014 [Conditional("TIMER")]
1015 static public void ShowTimers ()
1017 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
1018 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
1019 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
1020 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
1021 ShowTimer (TimerType.CacheInit, "- Cache init");
1022 ShowTimer (TimerType.MiscTimer, "- Misc timer");
1024 ShowCounter (CounterType.FindMembers, "- Find members");
1025 ShowCounter (CounterType.MemberCache, "- Member cache");
1026 ShowCounter (CounterType.MiscCounter, "- Misc counter");
1029 static public void ShowCounter (CounterType which, string msg)
1031 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
1034 static public void ShowTimer (TimerType which, string msg)
1037 "[{0:00}:{1:000}] {2} (used {3} times)",
1038 (int) timers [(int) which].TotalSeconds,
1039 timers [(int) which].Milliseconds, msg,
1040 timer_counters [(int) which]);
1044 public class InternalErrorException : Exception {
1045 public InternalErrorException (MemberCore mc, Exception e)
1046 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1050 public InternalErrorException ()
1051 : base ("Internal error")
1055 public InternalErrorException (string message)
1060 public InternalErrorException (string message, params object[] args)
1061 : base (String.Format (message, args))
1064 public InternalErrorException (Exception e, Location loc)
1065 : base (loc.ToString (), e)
1071 /// Handles #pragma warning
1073 public class WarningRegions {
1075 abstract class PragmaCmd
1079 protected PragmaCmd (int line)
1084 public abstract bool IsEnabled (int code, bool previous);
1087 class Disable : PragmaCmd
1090 public Disable (int line, int code)
1096 public override bool IsEnabled (int code, bool previous)
1098 return this.code == code ? false : previous;
1102 class DisableAll : PragmaCmd
1104 public DisableAll (int line)
1107 public override bool IsEnabled(int code, bool previous)
1113 class Enable : PragmaCmd
1116 public Enable (int line, int code)
1122 public override bool IsEnabled(int code, bool previous)
1124 return this.code == code ? true : previous;
1128 class EnableAll : PragmaCmd
1130 public EnableAll (int line)
1133 public override bool IsEnabled(int code, bool previous)
1140 ArrayList regions = new ArrayList ();
1142 public void WarningDisable (int line)
1144 regions.Add (new DisableAll (line));
1147 public void WarningDisable (Location location, int code)
1149 if (Report.CheckWarningCode (code, location))
1150 regions.Add (new Disable (location.Row, code));
1153 public void WarningEnable (int line)
1155 regions.Add (new EnableAll (line));
1158 public void WarningEnable (Location location, int code)
1160 if (Report.CheckWarningCode (code, location))
1161 regions.Add (new Enable (location.Row, code));
1164 public bool IsWarningEnabled (int code, int src_line)
1167 foreach (PragmaCmd pragma in regions) {
1168 if (src_line < pragma.Line)
1171 result = pragma.IsEnabled (code, result);