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,
62
static HashSet<int> AllWarningsHashSet;
64
public Report (CompilerContext context, ReportPrinter printer)
67
throw new ArgumentNullException ("settings");
69
throw new ArgumentNullException ("printer");
71
this.settings = context.Settings;
72
this.printer = printer;
75
public void DisableReporting ()
80
public void EnableReporting ()
85
public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
88
switch (compiler.Settings.Version) {
89
case LanguageVersion.ISO_1:
92
case LanguageVersion.ISO_2:
95
case LanguageVersion.V_3:
98
case LanguageVersion.V_4:
101
case LanguageVersion.V_5:
105
throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
109
"Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
113
public void FeatureIsNotSupported (Location loc, string feature)
116
"Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
120
public void RuntimeMissingSupport (Location loc, string feature)
122
Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
126
/// In most error cases is very useful to have information about symbol that caused the error.
127
/// Call this method before you call Report.Error when it makes sense.
129
public void SymbolRelatedToPreviousError (Location loc, string symbol)
131
SymbolRelatedToPreviousError (loc.ToString ());
134
public void SymbolRelatedToPreviousError (MemberSpec ms)
136
if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
139
var mc = ms.MemberDefinition as MemberCore;
140
while (ms is ElementTypeSpec) {
141
ms = ((ElementTypeSpec) ms).Element;
142
mc = ms.MemberDefinition as MemberCore;
146
SymbolRelatedToPreviousError (mc);
148
if (ms.DeclaringType != null)
149
ms = ms.DeclaringType;
151
var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
152
if (imported_type != null) {
153
var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
154
SymbolRelatedToPreviousError (iad.Location);
159
public void SymbolRelatedToPreviousError (MemberCore mc)
161
SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
164
public void SymbolRelatedToPreviousError (string loc)
166
string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
167
if (extra_information.Contains (msg))
170
extra_information.Add (msg);
173
public bool CheckWarningCode (int code, Location loc)
175
if (AllWarningsHashSet == null)
176
AllWarningsHashSet = new HashSet<int> (AllWarnings);
178
if (AllWarningsHashSet.Contains (code))
181
Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
185
public void ExtraInformation (Location loc, string msg)
187
extra_information.Add (String.Format ("{0} {1}", loc, msg));
190
public WarningRegions RegisterWarningRegion (Location location)
192
WarningRegions regions;
193
if (warning_regions_table == null) {
195
warning_regions_table = new Dictionary<int, WarningRegions> ();
197
warning_regions_table.TryGetValue (location.File, out regions);
200
if (regions == null) {
201
regions = new WarningRegions ();
202
warning_regions_table.Add (location.File, regions);
208
public void Warning (int code, int level, Location loc, string message)
210
if (reporting_disabled > 0)
213
if (!settings.IsWarningEnabled (code, level))
216
if (warning_regions_table != null && !loc.IsNull) {
217
WarningRegions regions;
218
if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
223
if (settings.IsWarningAsError (code)) {
224
message = "Warning as Error: " + message;
225
msg = new ErrorMessage (code, loc, message, extra_information);
227
msg = new WarningMessage (code, loc, message, extra_information);
230
extra_information.Clear ();
231
printer.Print (msg, settings.ShowFullPaths);
234
public void Warning (int code, int level, Location loc, string format, string arg)
236
Warning (code, level, loc, String.Format (format, arg));
239
public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
241
Warning (code, level, loc, String.Format (format, arg1, arg2));
244
public void Warning (int code, int level, Location loc, string format, params object[] args)
246
Warning (code, level, loc, String.Format (format, args));
249
public void Warning (int code, int level, string message)
251
Warning (code, level, Location.Null, message);
254
public void Warning (int code, int level, string format, string arg)
256
Warning (code, level, Location.Null, format, arg);
259
public void Warning (int code, int level, string format, string arg1, string arg2)
261
Warning (code, level, Location.Null, format, arg1, arg2);
264
public void Warning (int code, int level, string format, params string[] args)
266
Warning (code, level, Location.Null, String.Format (format, args));
270
// Warnings encountered so far
272
public int Warnings {
273
get { return printer.WarningsCount; }
276
public void Error (int code, Location loc, string error)
278
if (reporting_disabled > 0)
281
ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
282
extra_information.Clear ();
284
printer.Print (msg, settings.ShowFullPaths);
286
if (settings.Stacktrace)
287
Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
289
if (printer.ErrorsCount == settings.FatalCounter)
290
throw new FatalException (msg.Text);
293
public void Error (int code, Location loc, string format, string arg)
295
Error (code, loc, String.Format (format, arg));
298
public void Error (int code, Location loc, string format, string arg1, string arg2)
300
Error (code, loc, String.Format (format, arg1, arg2));
303
public void Error (int code, Location loc, string format, params string[] args)
305
Error (code, loc, String.Format (format, args));
308
public void Error (int code, string error)
310
Error (code, Location.Null, error);
313
public void Error (int code, string format, string arg)
315
Error (code, Location.Null, format, arg);
318
public void Error (int code, string format, string arg1, string arg2)
320
Error (code, Location.Null, format, arg1, arg2);
323
public void Error (int code, string format, params string[] args)
325
Error (code, Location.Null, String.Format (format, args));
329
// Errors encountered so far
332
get { return printer.ErrorsCount; }
335
public bool IsDisabled {
337
return reporting_disabled > 0;
341
public ReportPrinter Printer {
342
get { return printer; }
345
public ReportPrinter SetPrinter (ReportPrinter printer)
347
ReportPrinter old = this.printer;
348
this.printer = printer;
352
[Conditional ("MCS_DEBUG")]
353
static public void Debug (string message, params object[] args)
355
Debug (4, message, args);
358
[Conditional ("MCS_DEBUG")]
359
static public void Debug (int category, string message, params object[] args)
361
// if ((category & DebugFlags) == 0)
364
StringBuilder sb = new StringBuilder (message);
366
if ((args != null) && (args.Length > 0)) {
370
foreach (object arg in args) {
377
// else if (arg is ICollection)
378
// sb.Append (PrintCollection ((ICollection) arg));
384
Console.WriteLine (sb.ToString ());
387
static public string PrintCollection (ICollection collection)
389
StringBuilder sb = new StringBuilder ();
391
sb.Append (collection.GetType ());
395
foreach (object o in collection) {
404
return sb.ToString ();
407
static string FriendlyStackTrace (StackTrace t)
409
StringBuilder sb = new StringBuilder ();
411
bool foundUserCode = false;
413
for (int i = 0; i < t.FrameCount; i++) {
414
StackFrame f = t.GetFrame (i);
415
var mb = f.GetMethod ();
417
if (!foundUserCode && mb.ReflectedType == typeof (Report))
420
foundUserCode = true;
424
if (f.GetFileLineNumber () > 0)
425
sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
427
sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
430
foreach (var pi in mb.GetParameters ()) {
435
sb.Append (pi.ParameterType.FullName);
440
return sb.ToString ();
444
public abstract class AbstractMessage
446
readonly string[] extra_info;
447
protected readonly int code;
448
protected readonly Location location;
449
readonly string message;
451
protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
455
this.code = 8000 - code;
459
if (extraInfo.Count != 0) {
460
this.extra_info = extraInfo.ToArray ();
464
protected AbstractMessage (AbstractMessage aMsg)
466
this.code = aMsg.code;
467
this.location = aMsg.location;
468
this.message = aMsg.message;
469
this.extra_info = aMsg.extra_info;
476
public override bool Equals (object obj)
478
AbstractMessage msg = obj as AbstractMessage;
482
return code == msg.code && location.Equals (msg.location) && message == msg.message;
485
public override int GetHashCode ()
487
return code.GetHashCode ();
490
public abstract bool IsWarning { get; }
492
public Location Location {
493
get { return location; }
496
public abstract string MessageType { get; }
498
public string[] RelatedSymbols {
499
get { return extra_info; }
503
get { return message; }
507
sealed class WarningMessage : AbstractMessage
509
public WarningMessage (int code, Location loc, string message, List<string> extra_info)
510
: base (code, loc, message, extra_info)
514
public override bool IsWarning {
518
public override string MessageType {
525
sealed class ErrorMessage : AbstractMessage
527
public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
528
: base (code, loc, message, extraInfo)
532
public ErrorMessage (AbstractMessage aMsg)
537
public override bool IsWarning {
538
get { return false; }
541
public override string MessageType {
549
// Generic base for any message writer
551
public abstract class ReportPrinter
555
public int ErrorsCount { get; protected set; }
557
public int WarningsCount { get; private set; }
560
// When (symbols related to previous ...) can be used
562
public virtual bool HasRelatedSymbolSupport {
569
protected virtual string FormatText (string txt)
574
public virtual void Print (AbstractMessage msg, bool showFullPath)
583
protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
585
StringBuilder txt = new StringBuilder ();
586
if (!msg.Location.IsNull) {
588
txt.Append (msg.Location.ToStringFullName ());
590
txt.Append (msg.Location.ToString ());
595
txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
598
output.WriteLine (FormatText (txt.ToString ()));
600
output.WriteLine (txt.ToString ());
602
if (msg.RelatedSymbols != null) {
603
foreach (string s in msg.RelatedSymbols)
604
output.WriteLine (s + msg.MessageType + ")");
610
// HACK: Temporary hack for broken repl flow
611
ErrorsCount = WarningsCount = 0;
615
sealed class NullReportPrinter : ReportPrinter
620
// Default message recorder, it uses two types of message groups.
621
// Common messages: messages reported in all sessions.
622
// Merged messages: union of all messages in all sessions.
624
// Used by the Lambda expressions to compile the code with various
625
// parameter values, or by attribute resolver
627
class SessionReportPrinter : ReportPrinter
629
List<AbstractMessage> session_messages;
631
// A collection of exactly same messages reported in all sessions
633
List<AbstractMessage> common_messages;
636
// A collection of unique messages reported in all sessions
638
List<AbstractMessage> merged_messages;
642
public void ClearSession ()
644
session_messages = null;
647
public override void Print (AbstractMessage msg, bool showFullPath)
650
// This line is useful when debugging recorded messages
652
// Console.WriteLine ("RECORDING: {0}", msg.ToString ());
654
if (session_messages == null)
655
session_messages = new List<AbstractMessage> ();
657
session_messages.Add (msg);
659
this.showFullPaths = showFullPath;
660
base.Print (msg, showFullPath);
663
public void EndSession ()
665
if (session_messages == null)
669
// Handles the first session
671
if (common_messages == null) {
672
common_messages = new List<AbstractMessage> (session_messages);
673
merged_messages = session_messages;
674
session_messages = null;
679
// Store common messages if any
681
for (int i = 0; i < common_messages.Count; ++i) {
682
AbstractMessage cmsg = common_messages[i];
683
bool common_msg_found = false;
684
foreach (AbstractMessage msg in session_messages) {
685
if (cmsg.Equals (msg)) {
686
common_msg_found = true;
691
if (!common_msg_found)
692
common_messages.RemoveAt (i);
696
// Merge session and previous messages
698
for (int i = 0; i < session_messages.Count; ++i) {
699
AbstractMessage msg = session_messages[i];
700
bool msg_found = false;
701
for (int ii = 0; ii < merged_messages.Count; ++ii) {
702
if (msg.Equals (merged_messages[ii])) {
709
merged_messages.Add (msg);
713
public bool IsEmpty {
715
return merged_messages == null && common_messages == null;
720
// Prints collected messages, common messages have a priority
722
public bool Merge (ReportPrinter dest)
724
var messages_to_print = merged_messages;
725
if (common_messages != null && common_messages.Count > 0) {
726
messages_to_print = common_messages;
729
if (messages_to_print == null)
732
bool error_msg = false;
733
foreach (AbstractMessage msg in messages_to_print) {
734
dest.Print (msg, showFullPaths);
735
error_msg |= !msg.IsWarning;
742
public class StreamReportPrinter : ReportPrinter
744
readonly TextWriter writer;
746
public StreamReportPrinter (TextWriter writer)
748
this.writer = writer;
751
public override void Print (AbstractMessage msg, bool showFullPath)
753
Print (msg, writer, showFullPath);
754
base.Print (msg, showFullPath);
758
public class ConsoleReportPrinter : StreamReportPrinter
760
static readonly string prefix, postfix;
762
static ConsoleReportPrinter ()
764
string term = Environment.GetEnvironmentVariable ("TERM");
765
bool xterm_colors = false;
771
if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
777
case "xterm-256color":
784
if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
787
string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
789
config = "errors=red";
790
//config = "brightwhite,red";
793
if (config == "disable")
796
if (!config.StartsWith ("errors="))
799
config = config.Substring (7);
801
int p = config.IndexOf (",");
803
prefix = GetForeground (config);
805
prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
806
postfix = "\x001b[0m";
809
public ConsoleReportPrinter ()
810
: base (Console.Error)
814
public ConsoleReportPrinter (TextWriter writer)
819
static int NameToCode (string s)
844
// maps a color name to its xterm color code
846
static string GetForeground (string s)
850
if (s.StartsWith ("bright")) {
856
return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
859
static string GetBackground (string s)
861
return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
864
protected override string FormatText (string txt)
867
return prefix + txt + postfix;
875
public enum TimerType
878
AssemblyBuilderSetup,
883
ModuleDefinitionTotal,
891
readonly Stopwatch[] timers;
894
public TimeReporter (bool enabled)
899
timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
902
public void Start (TimerType type)
904
if (timers != null) {
905
var sw = new Stopwatch ();
906
timers[(int) type] = sw;
911
public void StartTotal ()
913
total = new Stopwatch ();
917
public void Stop (TimerType type)
919
if (timers != null) {
920
timers[(int) type].Stop ();
924
public void StopTotal ()
929
public void ShowStats ()
934
Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> () {
935
{ TimerType.ParseTotal, "Parsing source files" },
936
{ TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
937
{ TimerType.CreateTypeTotal, "Compiled types created" },
938
{ TimerType.ReferencesLoading, "Referenced assemblies loading" },
939
{ TimerType.ReferencesImporting, "Referenced assemblies importing" },
940
{ TimerType.PredefinedTypesInit, "Predefined types initialization" },
941
{ TimerType.ModuleDefinitionTotal, "Module definition" },
942
{ TimerType.EmitTotal, "Resolving and emitting members blocks" },
943
{ TimerType.CloseTypes, "Module types closed" },
944
{ TimerType.Resouces, "Embedding resources" },
945
{ TimerType.OutputSave, "Writing output file" },
946
{ TimerType.DebugSave, "Writing debug symbols file" },
950
double percentage = (double) total.ElapsedMilliseconds / 100;
951
long subtotal = total.ElapsedMilliseconds;
952
foreach (var timer in timers) {
953
string msg = timer_names[(TimerType) counter++];
954
var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
955
Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
959
Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
960
Console.WriteLine ();
961
Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
965
public class InternalErrorException : Exception {
966
public InternalErrorException (MemberCore mc, Exception e)
967
: base (mc.Location + " " + mc.GetSignatureForError (), e)
971
public InternalErrorException ()
972
: base ("Internal error")
976
public InternalErrorException (string message)
981
public InternalErrorException (string message, params object[] args)
982
: base (String.Format (message, args))
986
public InternalErrorException (Exception exception, string message, params object[] args)
987
: base (String.Format (message, args), exception)
991
public InternalErrorException (Exception e, Location loc)
992
: base (loc.ToString (), e)
997
class FatalException : Exception
999
public FatalException (string message)
1006
/// Handles #pragma warning
1008
public class WarningRegions {
1010
abstract class PragmaCmd
1014
protected PragmaCmd (int line)
1019
public abstract bool IsEnabled (int code, bool previous);
1022
class Disable : PragmaCmd
1025
public Disable (int line, int code)
1031
public override bool IsEnabled (int code, bool previous)
1033
return this.code == code ? false : previous;
1037
class DisableAll : PragmaCmd
1039
public DisableAll (int line)
1042
public override bool IsEnabled(int code, bool previous)
1048
class Enable : PragmaCmd
1051
public Enable (int line, int code)
1057
public override bool IsEnabled(int code, bool previous)
1059
return this.code == code ? true : previous;
1063
class EnableAll : PragmaCmd
1065
public EnableAll (int line)
1068
public override bool IsEnabled(int code, bool previous)
1075
List<PragmaCmd> regions = new List<PragmaCmd> ();
1077
public void WarningDisable (int line)
1079
regions.Add (new DisableAll (line));
1082
public void WarningDisable (Location location, int code, Report Report)
1084
if (Report.CheckWarningCode (code, location))
1085
regions.Add (new Disable (location.Row, code));
1088
public void WarningEnable (int line)
1090
regions.Add (new EnableAll (line));
1093
public void WarningEnable (Location location, int code, CompilerContext context)
1095
if (!context.Report.CheckWarningCode (code, location))
1098
if (context.Settings.IsWarningDisabledGlobally (code))
1099
context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1101
regions.Add (new Enable (location.Row, code));
1104
public bool IsWarningEnabled (int code, int src_line)
1107
foreach (PragmaCmd pragma in regions) {
1108
if (src_line < pragma.Line)
1111
result = pragma.IsEnabled (code, result);