Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MessageContainer.cs « Linker « linker « src - github.com/mono/linker.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f0a4afd09b18750d45d5743a4483f074cc446f7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text;
using Mono.Cecil;

namespace Mono.Linker
{
	public readonly struct MessageContainer : IComparable<MessageContainer>, IEquatable<MessageContainer>
	{
		public static readonly MessageContainer Empty;

		/// <summary>
		/// Optional data with a filename, line and column that triggered the
		/// linker to output an error (or warning) message.
		/// </summary>
		public MessageOrigin? Origin { get; }

		public MessageCategory Category { get; }

		/// <summary>
		/// Further categorize the message.
		/// </summary>
		public string SubCategory { get; }

		/// <summary>
		/// Code identifier for errors and warnings reported by the IL linker.
		/// </summary>
		public int? Code { get; }

		/// <summary>
		/// User friendly text describing the error or warning.
		/// </summary>
		public string Text { get; }

		/// <summary>
		/// Create an error message.
		/// </summary>
		/// <param name="text">Humanly readable message describing the error</param>
		/// <param name="code">Unique error ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md
		/// for the list of errors and possibly add a new one</param>
		/// <param name="subcategory">Optionally, further categorize this error</param>
		/// <param name="origin">Filename, line, and column where the error was found</param>
		/// <returns>New MessageContainer of 'Error' category</returns>
		internal static MessageContainer CreateErrorMessage (string text, int code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null)
		{
			if (!(code >= 1000 && code <= 2000))
				throw new ArgumentOutOfRangeException (nameof (code), $"The provided code '{code}' does not fall into the error category, which is in the range of 1000 to 2000 (inclusive).");

			return new MessageContainer (MessageCategory.Error, text, code, subcategory, origin);
		}

		/// <summary>
		/// Create a custom error message.
		/// </summary>
		/// <param name="text">Humanly readable message describing the error</param>
		/// <param name="code">A custom error ID. This code should be greater than or equal to 6001
		/// to avoid any collisions with existing and future linker errors</param>
		/// <param name="subcategory">Optionally, further categorize this error</param>
		/// <param name="origin">Filename or member where the error is coming from</param>
		/// <returns>Custom MessageContainer of 'Error' category</returns>
		public static MessageContainer CreateCustomErrorMessage (string text, int code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null)
		{
#if DEBUG
			Debug.Assert (Assembly.GetCallingAssembly () != typeof (MessageContainer).Assembly,
				"'CreateCustomErrorMessage' is intended to be used by external assemblies only. Use 'CreateErrorMessage' instead.");
#endif
			if (code <= 6000)
				throw new ArgumentOutOfRangeException (nameof (code), $"The provided code '{code}' does not fall into the permitted range for external errors. To avoid possible collisions " +
					"with existing and future {Constants.ILLink} errors, external messages should use codes starting from 6001.");

			return new MessageContainer (MessageCategory.Error, text, code, subcategory, origin);
		}

		/// <summary>
		/// Create a warning message.
		/// </summary>
		/// <param name="context">Context with the relevant warning suppression info.</param>
		/// <param name="text">Humanly readable message describing the warning</param>
		/// <param name="code">Unique warning ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md
		/// for the list of warnings and possibly add a new one</param>
		/// /// <param name="origin">Filename or member where the warning is coming from</param>
		/// <param name="subcategory">Optionally, further categorize this warning</param>
		/// <param name="version">Optional warning version number. Versioned warnings can be controlled with the
		/// warning wave option --warn VERSION. Unversioned warnings are unaffected by this option. </param>
		/// <returns>New MessageContainer of 'Warning' category</returns>
		internal static MessageContainer CreateWarningMessage (LinkContext context, string text, int code, MessageOrigin origin, WarnVersion version, string subcategory = MessageSubCategory.None)
		{
			if (!(code > 2000 && code <= 6000))
				throw new ArgumentOutOfRangeException (nameof (code), $"The provided code '{code}' does not fall into the warning category, which is in the range of 2001 to 6000 (inclusive).");

			return CreateWarningMessageContainer (context, text, code, origin, version, subcategory);
		}

		/// <summary>
		/// Create a custom warning message.
		/// </summary>
		/// <param name="context">Context with the relevant warning suppression info.</param>
		/// <param name="text">Humanly readable message describing the warning</param>
		/// <param name="code">A custom warning ID. This code should be greater than or equal to 6001
		/// to avoid any collisions with existing and future linker warnings</param>
		/// <param name="origin">Filename or member where the warning is coming from</param>
		/// <param name="version">Optional warning version number. Versioned warnings can be controlled with the
		/// warning wave option --warn VERSION. Unversioned warnings are unaffected by this option</param>
		/// <param name="subcategory"></param>
		/// <returns>Custom MessageContainer of 'Warning' category</returns>
		public static MessageContainer CreateCustomWarningMessage (LinkContext context, string text, int code, MessageOrigin origin, WarnVersion version, string subcategory = MessageSubCategory.None)
		{
#if DEBUG
			Debug.Assert (Assembly.GetCallingAssembly () != typeof (MessageContainer).Assembly,
				"'CreateCustomWarningMessage' is intended to be used by external assemblies only. Use 'CreateWarningMessage' instead.");
#endif
			if (code <= 6000)
				throw new ArgumentOutOfRangeException (nameof (code), $"The provided code '{code}' does not fall into the permitted range for external warnings. To avoid possible collisions " +
					$"with existing and future {Constants.ILLink} warnings, external messages should use codes starting from 6001.");

			return CreateWarningMessageContainer (context, text, code, origin, version, subcategory);
		}

		private static MessageContainer CreateWarningMessageContainer (LinkContext context, string text, int code, MessageOrigin origin, WarnVersion version, string subcategory = MessageSubCategory.None)
		{
			if (!(version >= WarnVersion.ILLink0 && version <= WarnVersion.Latest))
				throw new ArgumentException ($"The provided warning version '{version}' is invalid.");

			if (context.IsWarningSuppressed (code, origin))
				return Empty;

			if (version > context.WarnVersion)
				return Empty;

			if (TryLogSingleWarning (context, code, origin, subcategory))
				return Empty;

			if (context.IsWarningAsError (code))
				return new MessageContainer (MessageCategory.WarningAsError, text, code, subcategory, origin);

			return new MessageContainer (MessageCategory.Warning, text, code, subcategory, origin);
		}

		public bool IsWarningMessage ([NotNullWhen (true)] out int? code)
		{
			code = null;

			if (Category is MessageCategory.Warning or MessageCategory.WarningAsError) {
				// Warning messages always have a code.
				code = Code!;
				return true;
			}

			return false;
		}

		static bool TryLogSingleWarning (LinkContext context, int code, MessageOrigin origin, string subcategory)
		{
			if (subcategory != MessageSubCategory.TrimAnalysis)
				return false;

			Debug.Assert (origin.Provider != null);
			var assembly = origin.Provider switch {
				AssemblyDefinition asm => asm,
				TypeDefinition type => type.Module.Assembly,
				IMemberDefinition member => member.DeclaringType.Module.Assembly,
				_ => throw new NotSupportedException ()
			};

			Debug.Assert (assembly != null);
			if (assembly == null)
				return false;

			// Any IL2026 warnings left in an assembly with an IsTrimmable attribute are considered intentional
			// and should not be collapsed, so that the user-visible RUC message gets printed.
			if (code == 2026 && context.IsTrimmable (assembly))
				return false;

			var assemblyName = assembly.Name.Name;
			if (!context.IsSingleWarn (assemblyName))
				return false;

			if (context.AssembliesWithGeneratedSingleWarning.Add (assemblyName))
				context.LogWarning ($"Assembly '{assemblyName}' produced trim warnings. For more information see https://aka.ms/dotnet-illink/libraries", 2104, context.GetAssemblyLocation (assembly));

			return true;
		}

		/// <summary>
		/// Create a info message.
		/// </summary>
		/// <param name="text">Humanly readable message</param>
		/// <returns>New MessageContainer of 'Info' category</returns>
		public static MessageContainer CreateInfoMessage (string text)
		{
			return new MessageContainer (MessageCategory.Info, text, null);
		}

		/// <summary>
		/// Create a diagnostics message.
		/// </summary>
		/// <param name="text">Humanly readable message</param>
		/// <returns>New MessageContainer of 'Diagnostic' category</returns>
		public static MessageContainer CreateDiagnosticMessage (string text)
		{
			return new MessageContainer (MessageCategory.Diagnostic, text, null);
		}

		private MessageContainer (MessageCategory category, string text, int? code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null)
		{
			Code = code;
			Category = category;
			Origin = origin;
			SubCategory = subcategory;
			Text = text;
		}

		public override string ToString () => ToMSBuildString ();

		public string ToMSBuildString ()
		{
			const string originApp = Constants.ILLink;
			string origin = Origin?.ToString () ?? originApp;

			StringBuilder sb = new StringBuilder ();
			sb.Append (origin).Append (":");

			if (!string.IsNullOrEmpty (SubCategory))
				sb.Append (" ").Append (SubCategory);

			string cat;
			switch (Category) {
			case MessageCategory.Error:
			case MessageCategory.WarningAsError:
				cat = "error";
				break;
			case MessageCategory.Warning:
				cat = "warning";
				break;
			default:
				cat = "";
				break;
			}

			if (!string.IsNullOrEmpty (cat)) {
				sb.Append (" ")
					.Append (cat)
					.Append (" IL")
					// Warning and error messages always have a code.
					.Append (Code!.Value.ToString ("D4"))
					.Append (": ");
			} else {
				sb.Append (" ");
			}

			if (Origin?.Provider != null) {
				if (Origin?.Provider is MethodDefinition method)
					sb.Append (method.GetDisplayName ());
				else if (Origin?.Provider is IMemberDefinition member)
					sb.Append (member.FullName);
				else if (Origin?.Provider is AssemblyDefinition assembly)
					sb.Append (assembly.Name.Name);
				else
					throw new NotSupportedException ();

				sb.Append (": ");
			}

			// Expected output $"{FileName(SourceLine, SourceColumn)}: {SubCategory}{Category} IL{Code}: ({MemberDisplayName}: ){Text}");
			sb.Append (Text);
			return sb.ToString ();
		}

		public bool Equals (MessageContainer other) =>
			(Category, Text, Code, SubCategory, Origin) == (other.Category, other.Text, other.Code, other.SubCategory, other.Origin);

		public override bool Equals (object obj) => obj is MessageContainer messageContainer && Equals (messageContainer);
		public override int GetHashCode () => (Category, Text, Code, SubCategory, Origin).GetHashCode ();

		public int CompareTo (MessageContainer other)
		{
			if (Origin != null && other.Origin != null) {
				return Origin.Value.CompareTo (other.Origin.Value);
			} else if (Origin == null && other.Origin == null) {
				return (Code < other.Code) ? -1 : 1;
			}

			return (Origin == null) ? 1 : -1;
		}

		public static bool operator == (MessageContainer lhs, MessageContainer rhs) => lhs.Equals (rhs);
		public static bool operator != (MessageContainer lhs, MessageContainer rhs) => !lhs.Equals (rhs);
	}
}