2 // report.cs: report errors and warnings.
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 // Marek Safar (marek.safar@gmail.com)
7 // Copyright 2001 Ximian, Inc. (http://www.ximian.com)
8 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
14 using System.Collections.Generic;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
20 // Errors and warnings manager
24 public const int RuntimeErrorId = 10000;
26 Dictionary<int, WarningRegions> warning_regions_table;
28 ReportPrinter printer;
30 int reporting_disabled;
32 readonly CompilerSettings settings;
35 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
37 List<string> extra_information = new List<string> ();
40 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
42 public static readonly int[] AllWarnings = new int[] {
44 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
45 219, 251, 252, 253, 278, 282,
46 402, 414, 419, 420, 429, 436, 437, 440, 458, 464, 465, 467, 469, 472, 473,
47 612, 618, 626, 628, 642, 649, 652, 657, 658, 659, 660, 661, 665, 672, 675, 693,
50 1030, 1058, 1060, 1066,
51 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
52 1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1699,
53 1700, 1701, 1702, 1709, 1711, 1717, 1718, 1720, 1735,
54 1901, 1956, 1981, 1998,
56 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
57 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
58 3021, 3022, 3023, 3024, 3026, 3027
61 static HashSet<int> AllWarningsHashSet;
63 public Report (CompilerContext context, ReportPrinter printer)
66 throw new ArgumentNullException ("settings");
68 throw new ArgumentNullException ("printer");
70 this.settings = context.Settings;
71 this.printer = printer;
74 public void DisableReporting ()
79 public void EnableReporting ()
84 public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
87 switch (compiler.Settings.Version) {
88 case LanguageVersion.ISO_1:
91 case LanguageVersion.ISO_2:
94 case LanguageVersion.V_3:
97 case LanguageVersion.V_4:
100 case LanguageVersion.V_5:
104 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
108 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
112 public void FeatureIsNotSupported (Location loc, string feature)
115 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
119 public void RuntimeMissingSupport (Location loc, string feature)
121 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
125 /// In most error cases is very useful to have information about symbol that caused the error.
126 /// Call this method before you call Report.Error when it makes sense.
128 public void SymbolRelatedToPreviousError (Location loc, string symbol)
130 SymbolRelatedToPreviousError (loc.ToString ());
133 public void SymbolRelatedToPreviousError (MemberSpec ms)
135 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
138 var mc = ms.MemberDefinition as MemberCore;
139 while (ms is ElementTypeSpec) {
140 ms = ((ElementTypeSpec) ms).Element;
141 mc = ms.MemberDefinition as MemberCore;
145 SymbolRelatedToPreviousError (mc);
147 if (ms.DeclaringType != null)
148 ms = ms.DeclaringType;
150 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
151 if (imported_type != null) {
152 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
153 SymbolRelatedToPreviousError (iad.Location);
158 public void SymbolRelatedToPreviousError (MemberCore mc)
160 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
163 public void SymbolRelatedToPreviousError (string loc)
165 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
166 if (extra_information.Contains (msg))
169 extra_information.Add (msg);
172 public bool CheckWarningCode (string code, Location loc)
174 Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
178 public bool CheckWarningCode (int code, Location loc)
180 if (AllWarningsHashSet == null)
181 AllWarningsHashSet = new HashSet<int> (AllWarnings);
183 if (AllWarningsHashSet.Contains (code))
186 return CheckWarningCode (code.ToString (), loc);
189 public void ExtraInformation (Location loc, string msg)
191 extra_information.Add (String.Format ("{0} {1}", loc, msg));
194 public WarningRegions RegisterWarningRegion (Location location)
196 WarningRegions regions;
197 if (warning_regions_table == null) {
199 warning_regions_table = new Dictionary<int, WarningRegions> ();
201 warning_regions_table.TryGetValue (location.File, out regions);
204 if (regions == null) {
205 regions = new WarningRegions ();
206 warning_regions_table.Add (location.File, regions);
212 public void Warning (int code, int level, Location loc, string message)
214 if (reporting_disabled > 0)
217 if (!settings.IsWarningEnabled (code, level))
220 if (warning_regions_table != null && !loc.IsNull) {
221 WarningRegions regions;
222 if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
227 if (settings.IsWarningAsError (code)) {
228 message = "Warning as Error: " + message;
229 msg = new ErrorMessage (code, loc, message, extra_information);
231 msg = new WarningMessage (code, loc, message, extra_information);
234 extra_information.Clear ();
235 printer.Print (msg, settings.ShowFullPaths);
238 public void Warning (int code, int level, Location loc, string format, string arg)
240 Warning (code, level, loc, String.Format (format, arg));
243 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
245 Warning (code, level, loc, String.Format (format, arg1, arg2));
248 public void Warning (int code, int level, Location loc, string format, params object[] args)
250 Warning (code, level, loc, String.Format (format, args));
253 public void Warning (int code, int level, string message)
255 Warning (code, level, Location.Null, message);
258 public void Warning (int code, int level, string format, string arg)
260 Warning (code, level, Location.Null, format, arg);
263 public void Warning (int code, int level, string format, string arg1, string arg2)
265 Warning (code, level, Location.Null, format, arg1, arg2);
268 public void Warning (int code, int level, string format, params string[] args)
270 Warning (code, level, Location.Null, String.Format (format, args));
274 // Warnings encountered so far
276 public int Warnings {
277 get { return printer.WarningsCount; }
280 public void Error (int code, Location loc, string error)
282 if (reporting_disabled > 0)
285 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
286 extra_information.Clear ();
288 printer.Print (msg, settings.ShowFullPaths);
290 if (settings.Stacktrace)
291 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
293 if (printer.ErrorsCount == settings.FatalCounter)
294 throw new FatalException (msg.Text);
297 public void Error (int code, Location loc, string format, string arg)
299 Error (code, loc, String.Format (format, arg));
302 public void Error (int code, Location loc, string format, string arg1, string arg2)
304 Error (code, loc, String.Format (format, arg1, arg2));
307 public void Error (int code, Location loc, string format, params string[] args)
309 Error (code, loc, String.Format (format, args));
312 public void Error (int code, string error)
314 Error (code, Location.Null, error);
317 public void Error (int code, string format, string arg)
319 Error (code, Location.Null, format, arg);
322 public void Error (int code, string format, string arg1, string arg2)
324 Error (code, Location.Null, format, arg1, arg2);
327 public void Error (int code, string format, params string[] args)
329 Error (code, Location.Null, String.Format (format, args));
333 // Errors encountered so far
336 get { return printer.ErrorsCount; }
339 public bool IsDisabled {
341 return reporting_disabled > 0;
345 public ReportPrinter Printer {
346 get { return printer; }
349 public ReportPrinter SetPrinter (ReportPrinter printer)
351 ReportPrinter old = this.printer;
352 this.printer = printer;
356 [Conditional ("MCS_DEBUG")]
357 static public void Debug (string message, params object[] args)
359 Debug (4, message, args);
362 [Conditional ("MCS_DEBUG")]
363 static public void Debug (int category, string message, params object[] args)
365 // if ((category & DebugFlags) == 0)
368 StringBuilder sb = new StringBuilder (message);
370 if ((args != null) && (args.Length > 0)) {
374 foreach (object arg in args) {
381 // else if (arg is ICollection)
382 // sb.Append (PrintCollection ((ICollection) arg));
388 Console.WriteLine (sb.ToString ());
391 static public string PrintCollection (ICollection collection)
393 StringBuilder sb = new StringBuilder ();
395 sb.Append (collection.GetType ());
399 foreach (object o in collection) {
408 return sb.ToString ();
411 static string FriendlyStackTrace (StackTrace t)
413 StringBuilder sb = new StringBuilder ();
415 bool foundUserCode = false;
417 for (int i = 0; i < t.FrameCount; i++) {
418 StackFrame f = t.GetFrame (i);
419 var mb = f.GetMethod ();
421 if (!foundUserCode && mb.ReflectedType == typeof (Report))
424 foundUserCode = true;
428 if (f.GetFileLineNumber () > 0)
429 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
431 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
434 foreach (var pi in mb.GetParameters ()) {
439 sb.Append (pi.ParameterType.FullName);
444 return sb.ToString ();
448 public abstract class AbstractMessage
450 readonly string[] extra_info;
451 protected readonly int code;
452 protected readonly Location location;
453 readonly string message;
455 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
459 this.code = 8000 - code;
463 if (extraInfo.Count != 0) {
464 this.extra_info = extraInfo.ToArray ();
468 protected AbstractMessage (AbstractMessage aMsg)
470 this.code = aMsg.code;
471 this.location = aMsg.location;
472 this.message = aMsg.message;
473 this.extra_info = aMsg.extra_info;
480 public override bool Equals (object obj)
482 AbstractMessage msg = obj as AbstractMessage;
486 return code == msg.code && location.Equals (msg.location) && message == msg.message;
489 public override int GetHashCode ()
491 return code.GetHashCode ();
494 public abstract bool IsWarning { get; }
496 public Location Location {
497 get { return location; }
500 public abstract string MessageType { get; }
502 public string[] RelatedSymbols {
503 get { return extra_info; }
507 get { return message; }
511 sealed class WarningMessage : AbstractMessage
513 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
514 : base (code, loc, message, extra_info)
518 public override bool IsWarning {
522 public override string MessageType {
529 sealed class ErrorMessage : AbstractMessage
531 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
532 : base (code, loc, message, extraInfo)
536 public ErrorMessage (AbstractMessage aMsg)
541 public override bool IsWarning {
542 get { return false; }
545 public override string MessageType {
553 // Generic base for any message writer
555 public abstract class ReportPrinter
559 public int ErrorsCount { get; protected set; }
561 public int WarningsCount { get; private set; }
564 // When (symbols related to previous ...) can be used
566 public virtual bool HasRelatedSymbolSupport {
573 protected virtual string FormatText (string txt)
578 public virtual void Print (AbstractMessage msg, bool showFullPath)
587 protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
589 StringBuilder txt = new StringBuilder ();
590 if (!msg.Location.IsNull) {
592 txt.Append (msg.Location.ToStringFullName ());
594 txt.Append (msg.Location.ToString ());
599 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
602 output.WriteLine (FormatText (txt.ToString ()));
604 output.WriteLine (txt.ToString ());
606 if (msg.RelatedSymbols != null) {
607 foreach (string s in msg.RelatedSymbols)
608 output.WriteLine (s + msg.MessageType + ")");
614 // HACK: Temporary hack for broken repl flow
615 ErrorsCount = WarningsCount = 0;
619 sealed class NullReportPrinter : ReportPrinter
624 // Default message recorder, it uses two types of message groups.
625 // Common messages: messages reported in all sessions.
626 // Merged messages: union of all messages in all sessions.
628 // Used by the Lambda expressions to compile the code with various
629 // parameter values, or by attribute resolver
631 class SessionReportPrinter : ReportPrinter
633 List<AbstractMessage> session_messages;
635 // A collection of exactly same messages reported in all sessions
637 List<AbstractMessage> common_messages;
640 // A collection of unique messages reported in all sessions
642 List<AbstractMessage> merged_messages;
646 public override void Print (AbstractMessage msg, bool showFullPath)
649 // This line is useful when debugging recorded messages
651 // Console.WriteLine ("RECORDING: {0}", msg.ToString ());
653 if (session_messages == null)
654 session_messages = new List<AbstractMessage> ();
656 session_messages.Add (msg);
658 this.showFullPaths = showFullPath;
659 base.Print (msg, showFullPath);
662 public void EndSession ()
664 if (session_messages == null)
668 // Handles the first session
670 if (common_messages == null) {
671 common_messages = new List<AbstractMessage> (session_messages);
672 merged_messages = session_messages;
673 session_messages = null;
678 // Store common messages if any
680 for (int i = 0; i < common_messages.Count; ++i) {
681 AbstractMessage cmsg = common_messages[i];
682 bool common_msg_found = false;
683 foreach (AbstractMessage msg in session_messages) {
684 if (cmsg.Equals (msg)) {
685 common_msg_found = true;
690 if (!common_msg_found)
691 common_messages.RemoveAt (i);
695 // Merge session and previous messages
697 for (int i = 0; i < session_messages.Count; ++i) {
698 AbstractMessage msg = session_messages[i];
699 bool msg_found = false;
700 for (int ii = 0; ii < merged_messages.Count; ++ii) {
701 if (msg.Equals (merged_messages[ii])) {
708 merged_messages.Add (msg);
712 public bool IsEmpty {
714 return merged_messages == null && common_messages == null;
719 // Prints collected messages, common messages have a priority
721 public bool Merge (ReportPrinter dest)
723 var messages_to_print = merged_messages;
724 if (common_messages != null && common_messages.Count > 0) {
725 messages_to_print = common_messages;
728 if (messages_to_print == null)
731 bool error_msg = false;
732 foreach (AbstractMessage msg in messages_to_print) {
733 dest.Print (msg, showFullPaths);
734 error_msg |= !msg.IsWarning;
741 public class StreamReportPrinter : ReportPrinter
743 readonly TextWriter writer;
745 public StreamReportPrinter (TextWriter writer)
747 this.writer = writer;
750 public override void Print (AbstractMessage msg, bool showFullPath)
752 Print (msg, writer, showFullPath);
753 base.Print (msg, showFullPath);
757 public class ConsoleReportPrinter : StreamReportPrinter
759 static readonly string prefix, postfix;
761 static ConsoleReportPrinter ()
763 string term = Environment.GetEnvironmentVariable ("TERM");
764 bool xterm_colors = false;
770 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
776 case "xterm-256color":
783 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
786 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
788 config = "errors=red";
789 //config = "brightwhite,red";
792 if (config == "disable")
795 if (!config.StartsWith ("errors="))
798 config = config.Substring (7);
800 int p = config.IndexOf (",");
802 prefix = GetForeground (config);
804 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
805 postfix = "\x001b[0m";
808 public ConsoleReportPrinter ()
809 : base (Console.Error)
813 public ConsoleReportPrinter (TextWriter writer)
818 static int NameToCode (string s)
843 // maps a color name to its xterm color code
845 static string GetForeground (string s)
849 if (s.StartsWith ("bright")) {
855 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
858 static string GetBackground (string s)
860 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
863 protected override string FormatText (string txt)
866 return prefix + txt + postfix;
874 public enum TimerType
877 AssemblyBuilderSetup,
882 ModuleDefinitionTotal,
890 readonly Stopwatch[] timers;
893 public TimeReporter (bool enabled)
898 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
901 public void Start (TimerType type)
903 if (timers != null) {
904 var sw = new Stopwatch ();
905 timers[(int) type] = sw;
910 public void StartTotal ()
912 total = new Stopwatch ();
916 public void Stop (TimerType type)
918 if (timers != null) {
919 timers[(int) type].Stop ();
923 public void StopTotal ()
928 public void ShowStats ()
933 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> () {
934 { TimerType.ParseTotal, "Parsing source files" },
935 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
936 { TimerType.CreateTypeTotal, "Compiled types created" },
937 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
938 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
939 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
940 { TimerType.ModuleDefinitionTotal, "Module definition" },
941 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
942 { TimerType.CloseTypes, "Module types closed" },
943 { TimerType.Resouces, "Embedding resources" },
944 { TimerType.OutputSave, "Writing output file" },
945 { TimerType.DebugSave, "Writing debug symbols file" },
949 double percentage = (double) total.ElapsedMilliseconds / 100;
950 long subtotal = total.ElapsedMilliseconds;
951 foreach (var timer in timers) {
952 string msg = timer_names[(TimerType) counter++];
953 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
954 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
958 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
959 Console.WriteLine ();
960 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
964 public class InternalErrorException : Exception {
965 public InternalErrorException (MemberCore mc, Exception e)
966 : base (mc.Location + " " + mc.GetSignatureForError (), e)
970 public InternalErrorException ()
971 : base ("Internal error")
975 public InternalErrorException (string message)
980 public InternalErrorException (string message, params object[] args)
981 : base (String.Format (message, args))
985 public InternalErrorException (Exception exception, string message, params object[] args)
986 : base (String.Format (message, args), exception)
990 public InternalErrorException (Exception e, Location loc)
991 : base (loc.ToString (), e)
996 class FatalException : Exception
998 public FatalException (string message)
1005 /// Handles #pragma warning
1007 public class WarningRegions {
1009 abstract class PragmaCmd
1013 protected PragmaCmd (int line)
1018 public abstract bool IsEnabled (int code, bool previous);
1021 class Disable : PragmaCmd
1024 public Disable (int line, int code)
1030 public override bool IsEnabled (int code, bool previous)
1032 return this.code == code ? false : previous;
1036 class DisableAll : PragmaCmd
1038 public DisableAll (int line)
1041 public override bool IsEnabled(int code, bool previous)
1047 class Enable : PragmaCmd
1050 public Enable (int line, int code)
1056 public override bool IsEnabled(int code, bool previous)
1058 return this.code == code ? true : previous;
1062 class EnableAll : PragmaCmd
1064 public EnableAll (int line)
1067 public override bool IsEnabled(int code, bool previous)
1074 List<PragmaCmd> regions = new List<PragmaCmd> ();
1076 public void WarningDisable (int line)
1078 regions.Add (new DisableAll (line));
1081 public void WarningDisable (Location location, int code, Report Report)
1083 if (Report.CheckWarningCode (code, location))
1084 regions.Add (new Disable (location.Row, code));
1087 public void WarningEnable (int line)
1089 regions.Add (new EnableAll (line));
1092 public void WarningEnable (Location location, int code, CompilerContext context)
1094 if (!context.Report.CheckWarningCode (code, location))
1097 if (context.Settings.IsWarningDisabledGlobally (code))
1098 context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1100 regions.Add (new Enable (location.Row, code));
1103 public bool IsWarningEnabled (int code, int src_line)
1106 foreach (PragmaCmd pragma in regions) {
1107 if (src_line < pragma.Line)
1110 result = pragma.IsEnabled (code, result);