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

TypeParser.cs « Mono.Cecil - github.com/mono/cecil.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a4ebd6954c16b2bc71af22012fdc798b6a695c1a (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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//
// Author:
//   Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//

using System;
using System.Text;

using Mono.Cecil.Metadata;

namespace Mono.Cecil {

	class TypeParser {

		class Type {
			public const int Ptr = -1;
			public const int ByRef = -2;
			public const int SzArray = -3;

			public string type_fullname;
			public string [] nested_names;
			public int arity;
			public int [] specs;
			public Type [] generic_arguments;
			public string assembly;
		}

		readonly string fullname;
		readonly int length;

		int position;

		TypeParser (string fullname)
		{
			this.fullname = fullname;
			this.length = fullname.Length;
		}

		Type ParseType (bool fq_name)
		{
			var type = new Type ();
			type.type_fullname = ParsePart ();

			type.nested_names = ParseNestedNames ();

			if (TryGetArity (type))
				type.generic_arguments = ParseGenericArguments (type.arity);

			type.specs = ParseSpecs ();

			if (fq_name)
				type.assembly = ParseAssemblyName ();

			return type;
		}

		static bool TryGetArity (Type type)
		{
			int arity = 0;

			TryAddArity (type.type_fullname, ref arity);

			var nested_names = type.nested_names;
			if (!nested_names.IsNullOrEmpty ()) {
				for (int i = 0; i < nested_names.Length; i++)
					TryAddArity (nested_names [i], ref arity);
			}

			type.arity = arity;
			return arity > 0;
		}

		static bool TryGetArity (string name, out int arity)
		{
			arity = 0;
			var index = name.LastIndexOf ('`');
			if (index == -1)
				return false;

			return ParseInt32 (name.Substring (index + 1), out arity);
		}

		static bool ParseInt32 (string value, out int result)
		{
			return int.TryParse (value, out result);
		}

		static void TryAddArity (string name, ref int arity)
		{
			int type_arity;
			if (!TryGetArity (name, out type_arity))
				return;

			arity += type_arity;
		}

		string ParsePart ()
		{
			var part = new StringBuilder ();
			while (position < length && !IsDelimiter (fullname [position])) {
				if (fullname [position] == '\\')
					position++;

				part.Append (fullname [position++]);
			}

			return part.ToString ();
		}

		static bool IsDelimiter (char chr)
		{
			return "+,[]*&".IndexOf (chr) != -1;
		}

		void TryParseWhiteSpace ()
		{
			while (position < length && Char.IsWhiteSpace (fullname [position]))
				position++;
		}

		string [] ParseNestedNames ()
		{
			string [] nested_names = null;
			while (TryParse ('+'))
				Add (ref nested_names, ParsePart ());

			return nested_names;
		}

		bool TryParse (char chr)
		{
			if (position < length && fullname [position] == chr) {
				position++;
				return true;
			}

			return false;
		}

		static void Add<T> (ref T [] array, T item)
		{
			array = array.Add (item);
		}

		int [] ParseSpecs ()
		{
			int [] specs = null;

			while (position < length) {
				switch (fullname [position]) {
				case '*':
					position++;
					Add (ref specs, Type.Ptr);
					break;
				case '&':
					position++;
					Add (ref specs, Type.ByRef);
					break;
				case '[':
					position++;
					switch (fullname [position]) {
					case ']':
						position++;
						Add (ref specs, Type.SzArray);
						break;
					case '*':
						position++;
						Add (ref specs, 1);
						break;
					default:
						var rank = 1;
						while (TryParse (','))
							rank++;

						Add (ref specs, rank);

						TryParse (']');
						break;
					}
					break;
				default:
					return specs;
				}
			}

			return specs;
		}

		Type [] ParseGenericArguments (int arity)
		{
			Type [] generic_arguments = null;

			if (position == length || fullname [position] != '[')
				return generic_arguments;

			TryParse ('[');

			for (int i = 0; i < arity; i++) {
				var fq_argument = TryParse ('[');
				Add (ref generic_arguments, ParseType (fq_argument));
				if (fq_argument)
					TryParse (']');

				TryParse (',');
				TryParseWhiteSpace ();
			}

			TryParse (']');

			return generic_arguments;
		}

		string ParseAssemblyName ()
		{
			if (!TryParse (','))
				return string.Empty;

			TryParseWhiteSpace ();

			var start = position;
			while (position < length) {
				var chr = fullname [position];
				if (chr == '[' || chr == ']')
					break;

				position++;
			}

			return fullname.Substring (start, position - start);
		}

		public static TypeReference ParseType (ModuleDefinition module, string fullname, bool typeDefinitionOnly = false)
		{
			if (string.IsNullOrEmpty (fullname))
				return null;

			var parser = new TypeParser (fullname);
			return GetTypeReference (module, parser.ParseType (true), typeDefinitionOnly);
		}

		static TypeReference GetTypeReference (ModuleDefinition module, Type type_info, bool type_def_only)
		{
			TypeReference type;
			if (!TryGetDefinition (module, type_info, out type)) {
				if (type_def_only)
					return null;

				type = CreateReference (type_info, module, GetMetadataScope (module, type_info));
			}

			return CreateSpecs (type, type_info);
		}

		static TypeReference CreateSpecs (TypeReference type, Type type_info)
		{
			type = TryCreateGenericInstanceType (type, type_info);

			var specs = type_info.specs;
			if (specs.IsNullOrEmpty ())
				return type;

			for (int i = 0; i < specs.Length; i++) {
				switch (specs [i]) {
				case Type.Ptr:
					type = new PointerType (type);
					break;
				case Type.ByRef:
					type = new ByReferenceType (type);
					break;
				case Type.SzArray:
					type = new ArrayType (type);
					break;
				default:
					var array = new ArrayType (type);
					array.Dimensions.Clear ();

					for (int j = 0; j < specs [i]; j++)
						array.Dimensions.Add (new ArrayDimension ());

					type = array;
					break;
				}
			}

			return type;
		}

		static TypeReference TryCreateGenericInstanceType (TypeReference type, Type type_info)
		{
			var generic_arguments = type_info.generic_arguments;
			if (generic_arguments.IsNullOrEmpty ())
				return type;

			var instance = new GenericInstanceType (type, generic_arguments.Length);
			var instance_arguments = instance.GenericArguments;

			for (int i = 0; i < generic_arguments.Length; i++)
				instance_arguments.Add (GetTypeReference (type.Module, generic_arguments [i], false));

			return instance;
		}

		public static void SplitFullName (string fullname, out string @namespace, out string name)
		{
			var last_dot = fullname.LastIndexOf ('.');

			if (last_dot == -1) {
				@namespace = string.Empty;
				name = fullname;
			} else {
				@namespace = fullname.Substring (0, last_dot);
				name = fullname.Substring (last_dot + 1);
			}
		}

		static TypeReference CreateReference (Type type_info, ModuleDefinition module, IMetadataScope scope)
		{
			string @namespace, name;
			SplitFullName (type_info.type_fullname, out @namespace, out name);

			var type = new TypeReference (@namespace, name, module, scope);
			MetadataSystem.TryProcessPrimitiveTypeReference (type);

			AdjustGenericParameters (type);

			var nested_names = type_info.nested_names;
			if (nested_names.IsNullOrEmpty ())
				return type;

			for (int i = 0; i < nested_names.Length; i++) {
				type = new TypeReference (string.Empty, nested_names [i], module, null) {
					DeclaringType = type,
				};

				AdjustGenericParameters (type);
			}

			return type;
		}

		static void AdjustGenericParameters (TypeReference type)
		{
			int arity;
			if (!TryGetArity (type.Name, out arity))
				return;

			for (int i = 0; i < arity; i++)
				type.GenericParameters.Add (new GenericParameter (type));
		}

		static IMetadataScope GetMetadataScope (ModuleDefinition module, Type type_info)
		{
			if (string.IsNullOrEmpty (type_info.assembly))
				return module.TypeSystem.CoreLibrary;

			AssemblyNameReference match;
			var reference = AssemblyNameReference.Parse (type_info.assembly);

			return module.TryGetAssemblyNameReference (reference, out match)
				? match
				: reference;
		}

		static bool TryGetDefinition (ModuleDefinition module, Type type_info, out TypeReference type)
		{
			type = null;
			if (!TryCurrentModule (module, type_info))
				return false;

			var typedef = module.GetType (type_info.type_fullname);
			if (typedef == null)
				return false;

			var nested_names = type_info.nested_names;
			if (!nested_names.IsNullOrEmpty ()) {
				for (int i = 0; i < nested_names.Length; i++) {
					var nested_type = typedef.GetNestedType (nested_names [i]);
					if (nested_type == null)
						return false;

					typedef = nested_type;
				}
			}

			type = typedef;
			return true;
		}

		static bool TryCurrentModule (ModuleDefinition module, Type type_info)
		{
			if (string.IsNullOrEmpty (type_info.assembly))
				return true;

			if (module.assembly != null && module.assembly.Name.FullName == type_info.assembly)
				return true;

			return false;
		}

		public static string ToParseable (TypeReference type, bool top_level = true)
		{
			if (type == null)
				return null;

			var name = new StringBuilder ();
			AppendType (type, name, true, top_level);
			return name.ToString ();
		}

		static void AppendNamePart (string part, StringBuilder name)
		{
			foreach (var c in part) {
				if (IsDelimiter (c))
					name.Append ('\\');

				name.Append (c);
			}
		}

		static void AppendType (TypeReference type, StringBuilder name, bool fq_name, bool top_level)
		{
			var element_type = type.GetElementType ();

			var declaring_type = element_type.DeclaringType;
			if (declaring_type != null) {
				AppendType (declaring_type, name, false, top_level);
				name.Append ('+');
			}

			var @namespace = type.Namespace;
			if (!string.IsNullOrEmpty (@namespace)) {
				AppendNamePart (@namespace, name);
				name.Append ('.');
			}

			AppendNamePart (element_type.Name, name);

			if (!fq_name)
				return;

			if (type.IsTypeSpecification ())
				AppendTypeSpecification ((TypeSpecification) type, name);

			if (RequiresFullyQualifiedName (type, top_level)) {
				name.Append (", ");
				name.Append (GetScopeFullName (type));
			}
		}

		static string GetScopeFullName (TypeReference type)
		{
			var scope = type.Scope;
			switch (scope.MetadataScopeType) {
			case MetadataScopeType.AssemblyNameReference:
				return ((AssemblyNameReference) scope).FullName;
			case MetadataScopeType.ModuleDefinition:
				return ((ModuleDefinition) scope).Assembly.Name.FullName;
			}

			throw new ArgumentException ();
		}

		static void AppendTypeSpecification (TypeSpecification type, StringBuilder name)
		{
			if (type.ElementType.IsTypeSpecification ())
				AppendTypeSpecification ((TypeSpecification) type.ElementType, name);

			switch (type.etype) {
			case ElementType.Ptr:
				name.Append ('*');
				break;
			case ElementType.ByRef:
				name.Append ('&');
				break;
			case ElementType.SzArray:
			case ElementType.Array:
				var array = (ArrayType) type;
				if (array.IsVector) {
					name.Append ("[]");
				} else {
					name.Append ('[');
					for (int i = 1; i < array.Rank; i++)
						name.Append (',');
					name.Append (']');
				}
				break;
			case ElementType.GenericInst:
				var instance = (GenericInstanceType) type;
				var arguments = instance.GenericArguments;

				name.Append ('[');

				for (int i = 0; i < arguments.Count; i++) {
					if (i > 0)
						name.Append (',');

					var argument = arguments [i];
					var requires_fqname = argument.Scope != argument.Module;

					if (requires_fqname)
						name.Append ('[');

					AppendType (argument, name, true, false);

					if (requires_fqname)
						name.Append (']');
				}

				name.Append (']');
				break;
			default:
				return;
			}
		}

		static bool RequiresFullyQualifiedName (TypeReference type, bool top_level)
		{
			if (type.Scope == type.Module)
				return false;

			if (type.Scope.Name == "mscorlib" && top_level)
				return false;

			return true;
		}
	}
}