Debian Codegraph @

external/api-doc-tools/mdoc/Mono.Documentation/Updater/Formatters/CppFormatters/CppCxFullMemberFormatter.cs

raw
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Text.RegularExpressions;
6 using Mono.Cecil;
7 using Mono.Documentation.Util;
8
9 namespace Mono.Documentation.Updater.Formatters.CppFormatters
10 {
11 public class CppCxFullMemberFormatter : CppFullMemberFormatter
12 {
13 public override string Language => Consts.CppCx;
14 protected override string RefTypeModifier => " & ";
15
16 protected readonly IEnumerable<string> ValueClassPropertyTypeAllowed = new List<string>()
17 {
18 "System.String",
19 "Platform.IBox<T>",
20 //fundamental numeric types
21 "System.SByte",
22 "System.Byte",
23 "System.Int16",
24 "System.UInt16",
25 "System.Int32",
26 "System.UInt32",
27 "System.Int64",
28 "System.UInt64",
29 "System.Single",
30 "System.Double",
31 "System.Decimal"
32 };
33
34 protected readonly IEnumerable<string> CustomAttributesFieldTypesAllowed = new List<string>()
35 {
36 "System.Int32",
37 "System.UInt32",
38 "System.Boolean",
39 "System.String",
40 "Windows.Foundation.HResult",
41 "Platform.Type"
42 };
43
44 protected static readonly IEnumerable<string> AllowedFundamentalTypes = new List<string>()
45 {
46 //fundamental numeric types
47 "System.Byte",
48 "System.Int16",
49 "System.UInt16",
50 "System.Int32",
51 "System.UInt32",
52 "System.Int64",
53 "System.UInt64",
54 "System.Single",
55 "System.Double",
56 "System.SByte",
57 //other fundamental types
58 "System.Object",
59 "System.Boolean",
60 "System.Char",
61 "System.Void",
62 "System.String",
63 "System.ValueType",
64 "System.Enum",
65 };
66
67 protected virtual IList<string> GetAllowedTypes()
68 {
69 return new List<string>(AllowedFundamentalTypes)
70 {
71 "System.Delegate",
72 "System.MulticastDelegate",
73 "System.Type",
74 "System.Attribute"
75 };
76
77 }
78 protected readonly IEnumerable<string> CppCxSpecificNamespases = new List<string>()
79 {
80 "Platform",
81 "Platform.Collections",
82 "Platform.Collections.Details",
83 "Platform.Details",
84 "Platform.Metadata",
85 "Platform.Runtime.CompilerServices",
86 "Platform.Runtime.InteropServices",
87 "Windows.Foundation.Collections"
88 };
89
90 protected override StringBuilder AppendNamespace(StringBuilder buf, TypeReference type)
91 {
92 string ns = DocUtils.GetNamespace(type, NestedTypeSeparator);
93 if (GetCppType(type.FullName) == null && !string.IsNullOrEmpty(ns) && ns != "System")
94 buf.Append(ns).Append(NestedTypeSeparator);
95 return buf;
96 }
97
98 protected override string GetCppType(string t)
99 {
100 // make sure there are no modifiers in the type string (add them back before returning)
101 string typeToCompare = t;
102 string[] splitType = null;
103 if (t.Contains(' '))
104 {
105 splitType = t.Split(' ');
106 typeToCompare = splitType[0];
107 }
108
109 switch (typeToCompare)
110 {
111 case "System.Byte": typeToCompare = "byte"; break;
112 case "System.Int16": typeToCompare = "short"; break;
113 case "System.Int32": typeToCompare = "int"; break;
114 case "System.Int64": typeToCompare = "long long"; break;
115
116 case "System.UInt16": typeToCompare = "unsigned short"; break;
117 case "System.UInt32": typeToCompare = "unsigned int"; break;
118 case "System.UInt64": typeToCompare = "unsigned long long"; break;
119
120 case "System.Single": typeToCompare = "float"; break;
121 case "System.Double": typeToCompare = "double"; break;
122 case "System.Boolean": typeToCompare = "bool"; break;
123 case "System.Char": typeToCompare = "char16"; break;
124 case "System.Void": typeToCompare = "void"; break;
125 case "System.String": typeToCompare = "Platform::String"; break;
126 case "System.Object": typeToCompare = "Platform::Object"; break;
127 case "System.Type": typeToCompare = "Platform::Type"; break;
128 case "System.Attribute": typeToCompare = "Platform::Metadata::Attribute"; break;
129 }
130
131 if (splitType != null)
132 {
133 // re-add modreq/modopt if it was there
134 splitType[0] = typeToCompare;
135 typeToCompare = string.Join(" ", splitType);
136 }
137 return typeToCompare == t ? null : typeToCompare;
138 }
139
140 protected override StringBuilder AppendArrayTypeName(StringBuilder buf, TypeReference type,
141 DynamicParserContext context)
142 {
143 buf.Append("Platform::Array <");
144
145 var item = type is TypeSpecification spec ? spec.ElementType : type.GetElementType();
146 _AppendTypeName(buf, item, context);
147 AppendHat(buf, item);
148
149 if (type is ArrayType arrayType)
150 {
151 int rank = arrayType.Rank;
152 if (rank > 1)
153 {
154 buf.AppendFormat(", {0}", rank);
155 }
156 }
157
158 buf.Append(">");
159
160 return buf;
161 }
162
163 protected override string GetTypeDeclaration(TypeDefinition type)
164 {
165 string visibility = GetTypeVisibility(type.Attributes);
166 if (visibility == null)
167 return null;
168
169 StringBuilder buf = new StringBuilder();
170
171 if (!visibility.Contains(":"))
172 {
173 AppendWebHostHiddenAttribute(buf, type);
174 }
175
176 buf.Append(visibility);
177 buf.Append(" ");
178
179 if (visibility.Contains(":"))
180 {
181 AppendWebHostHiddenAttribute(buf, type);
182 }
183
184 CppFullMemberFormatter full = new CppCxFullMemberFormatter();
185
186 if (DocUtils.IsDelegate(type))
187 {
188 buf.Append("delegate ");
189 MethodDefinition invoke = type.GetMethod("Invoke");
190 buf.Append(full.GetNameWithOptions(invoke.ReturnType)).Append(" ");
191 buf.Append(GetNameWithOptions(type, false, false));
192 AppendParameters(buf, invoke, invoke.Parameters);
193 buf.Append(";");
194
195 return buf.ToString();
196 }
197
198 buf.Append(GetTypeKind(type));
199 buf.Append(" ");
200 buf.Append(GetCppType(type.FullName) == null
201 ? GetNameWithOptions(type, false, false)
202 : type.Name);
203
204 if (type.IsAbstract && !type.IsInterface)
205 buf.Append(" abstract");
206 if (type.IsSealed && !DocUtils.IsDelegate(type) && !type.IsValueType)
207 buf.Append(" sealed");
208
209 if (!type.IsEnum)
210 {
211 TypeReference basetype = type.BaseType;
212 if (basetype != null && basetype.FullName == "System.Object" || type.IsValueType) // FIXME
213 basetype = null;
214
215 List<string> interfaceNames;
216 try
217 {
218 //for c++/cx Resolve() can fail as Cecil understands CX types as .net (eg, "System.Attribute" instead of "Platform::Metadata::Attribute")
219 interfaceNames = DocUtils.GetUserImplementedInterfaces(type)
220 .Select(iface => full.GetNameWithOptions(iface, true, false))
221 .OrderBy(s => s)
222 .ToList();
223 }
224 catch
225 {
226 interfaceNames = null;
227 }
228
229 if (basetype != null || interfaceNames?.Count > 0)
230 buf.Append(" : ");
231
232 if (basetype != null)
233 {
234 var appendValue = GetCppType(basetype.FullName);
235 buf.Append(appendValue ?? full.GetNameWithOptions(basetype, true, false));
236 if (interfaceNames?.Count > 0)
237 buf.Append(", ");
238 }
239
240 for (int i = 0; i < interfaceNames?.Count; i++)
241 {
242 if (i != 0)
243 buf.Append(", ");
244 buf.Append(interfaceNames?[i]);
245 }
246
247 }
248
249 return buf.ToString();
250 }
251
252 public void AppendWebHostHiddenAttribute(StringBuilder buf, TypeDefinition typeDef)
253 {
254 //public unsealed ref class needs to be marked with attribute
255 //to ensure that is not visible to UWP apps that are written in JavaScript
256 if (typeDef.IsClass && !typeDef.IsSealed && (typeDef.IsPublic || typeDef.IsNestedPublic) && typeDef.CustomAttributes.All(x => x.GetDeclaringType() != "Windows.Foundation.Metadata.WebHostHiddenAttribute"))
257 {
258 buf.Append("[Windows::Foundation::Metadata::WebHostHidden]").Append(GetLineEnding());
259 }
260 }
261
262 protected override StringBuilder AppendExplisitImplementationMethod(StringBuilder buf, MethodDefinition method)
263 {
264 if(IsExplicitlyImplemented(method))
265 {
266 buf.Append(" = ");
267
268 var interfaceMethodReference = method.Overrides.FirstOrDefault();
269
270 buf.Append(GetTypeNameWithOptions(interfaceMethodReference?.DeclaringType, !AppendHatOnReturn, true))
271 .Append(NestedTypeSeparator);
272 buf.Append(interfaceMethodReference?.Name);
273 }
274 return buf;
275 }
276
277 protected override string AppendSealedModifiers(string modifiersString, MethodDefinition method)
278 {
279 if (!IsExplicitlyImplemented(method))
280 {
281 if (method.IsFinal) modifiersString += " sealed";
282 if (modifiersString == " virtual sealed") modifiersString = "";
283 }
284
285 return modifiersString;
286 }
287
288 private bool IsExplicitlyImplemented(MethodDefinition method)
289 {
290 if (!method.HasOverrides) return false;
291
292 //apply logic for explicit implementation of interface methods
293 var interfaceMethodReference = method.Overrides.FirstOrDefault();
294
295 if (interfaceMethodReference != null
296 //need to filter UWP specific interfaces, generated by default
297 //eg from decompile, public sealed class Class1 : __IClass1PublicNonVirtuals, __IClass1ProtectedNonVirtuals
298 && !Regex.IsMatch(interfaceMethodReference.DeclaringType.Name,
299 $"^.*{method.DeclaringType.Name}.*Virtual.*$"))
300 {
301 return true;
302 }
303
304 return false;
305 }
306
307 public override bool IsSupported(TypeReference tref)
308 {
309 if (HasNestedClassesDuplicateNames(tref))
310 return false;
311
312 var allowedTypes = GetAllowedTypes();
313
314 //no support of jagged arrays
315 if (tref is ArrayType)
316 {
317 var typeOfArray= tref is TypeSpecification spec ? spec.ElementType : tref.GetElementType();
318 if (typeOfArray is ArrayType)
319 {
320 return false;
321 }
322
323 if (allowedTypes.Contains(typeOfArray.FullName) ||
324 CppCxSpecificNamespases.Contains(typeOfArray.Namespace))
325 {
326 return true;
327 }
328 }
329
330 if (allowedTypes.Contains(tref.FullName.Split(' ')[0]) || CppCxSpecificNamespases.Contains(tref.Namespace))
331 {
332 return true;
333 }
334
335 var ns = DocUtils.GetNamespace(tref);
336
337 var typedef = tref.Resolve();
338 if (typedef != null)
339 {
340 if (DocUtils.IsDelegate(typedef))
341 {
342 if (typedef.HasGenericParameters && typedef.IsPublic)
343 //generic delegates cannot be declared as public
344 return false;
345
346 return
347 //check types of delegate signature
348 IsSupported(typedef.GetMethod("Invoke"))
349 //check type
350 && base.IsSupported(tref) && ! (ns.StartsWith("System.") || ns.StartsWith("System"));
351 }
352
353 if (typedef.IsInterface && typedef.HasGenericParameters &&
354 typedef.GenericParameters.Any(x => x.HasConstraints
355 || x.HasReferenceTypeConstraint
356 || x.HasDefaultConstructorConstraint
357 || x.HasNotNullableValueTypeConstraint)
358 )
359 {
360 //generic interface - Type parameters cannot be constrained
361 return false;
362 }
363
364 if (HasUnsupportedParent(typedef))
365 {
366 return false;
367 }
368
369 var typeVisibility = typedef.Attributes & TypeAttributes.VisibilityMask;
370
371 if (typeVisibility == TypeAttributes.Public
372 //all public types, including those in your own code, must be declared in a namespace
373 && (string.IsNullOrEmpty(ns)
374 //public standard C++ types are not allowed
375 || ns.StartsWith("std") || ns.StartsWith("cli"))
376 )
377 {
378 return false;
379 }
380
381 if (typeVisibility == TypeAttributes.NestedPublic
382 && (typedef.IsEnum || typedef.IsClass)
383 )
384 {
385 //no support of nested public classes/enums
386 return false;
387 }
388
389 if (typedef.IsClass && typeVisibility == TypeAttributes.Public && typedef.HasGenericParameters)
390 {
391 //Public ref classes that have type parameters (generics) are not permitted.
392 return false;
393 }
394
395 if (typedef.IsClass && typeVisibility == TypeAttributes.Public)
396 {
397 //A public ref class that has a public constructor must also be declared as sealed
398 //to prevent further derivation through the application binary interface (ABI).
399 if (typedef.Methods.Any(x => x.IsConstructor && x.IsPublic) && !typedef.IsSealed)
400 {
401 return false;
402 }
403 }
404
405 if (typedef.IsValueType && !typedef.IsEnum && typedef.Fields.Any(x =>
406 !ValueClassPropertyTypeAllowed.Contains(x.FieldType.FullName) && !(x.FieldType.Resolve() != null && x.FieldType.Resolve().IsEnum)))
407 {
408 //A value struct or value class can contain as fields only
409 //fundamental numeric types, enum classes, Platform::String^, or Platform::IBox <T>^
410 return false;
411 }
412
413
414 bool condition;
415 try
416 {
417 //custom attribute can contain only public fields and only with allowed types or enums
418 condition = IsCustomAttribute(typedef)
419 && (typedef.Fields.Any(z =>
420 !CustomAttributesFieldTypesAllowed.Contains(z.FieldType.FullName)
421 && !(z.FieldType.Resolve() != null && z.FieldType.Resolve().IsEnum)
422 )
423 || typedef.Properties.Count != 0
424 || typedef.Methods.Count(x => !x.IsConstructor) != 0
425 || typedef.Events.Count != 0
426 );
427 }
428 catch
429 {
430 condition = false;
431 }
432
433 if (condition)
434 {
435 //custom attribute can contain only public fields and only with allowed types or enums
436 return false;
437 }
438 }
439
440 //cannot support .Net types
441 return !ns.StartsWith("System.") && !ns.Equals("System") && base.IsSupported(tref);
442 }
443
444 protected bool HasUnsupportedParent(TypeDefinition typedef)
445 {
446 var collect = new List<TypeDefinition>();
447 TypeReference baseTypeReference = typedef.BaseType;
448 TypeDefinition basetypeDefenition = null;
449
450 var allowedTypes = GetAllowedTypes();
451
452 try
453 {
454 //iterate through all classes in in inheritance hierarhy to exclude usage of .net types
455 basetypeDefenition = baseTypeReference?.Resolve();
456 while (basetypeDefenition != null)
457 {
458 if (allowedTypes.Contains(basetypeDefenition.FullName) || basetypeDefenition.BaseType == null)
459 {
460 break;
461 }
462
463 collect.Add(basetypeDefenition);
464
465 //needs to call Resolve to grab all base classes
466 basetypeDefenition = basetypeDefenition.BaseType?.Resolve();
467 }
468 }
469 catch (Exception)
470 {
471 //for c++/cx Resolve() can fail as Cecil understands types as .net (eg, "System.Attribute" instead of "Platform::Metadata::Attribute")
472 //needs to ignore those errors
473 baseTypeReference = basetypeDefenition?.BaseType ?? baseTypeReference;
474 }
475
476 if (collect.Any(x => DocUtils.GetNamespace(x).StartsWith("System.") || DocUtils.GetNamespace(x).Equals("System"))
477 || !allowedTypes.Contains(baseTypeReference?.FullName)
478 && (
479 DocUtils.GetNamespace(baseTypeReference).StartsWith("System.")
480 || DocUtils.GetNamespace(baseTypeReference).Equals("System")
481 )
482 )
483 //can only be Windows Runtime types(no support for .net types)
484 return true;
485
486 try
487 {
488 IEnumerable<TypeReference> interfaceNames = DocUtils.GetUserImplementedInterfaces(typedef).ToList();
489
490 if (interfaceNames.Any(x => DocUtils.GetNamespace(x).StartsWith("System.") || DocUtils.GetNamespace(x).Equals("System")))
491 {
492 //can only be Windows Runtime types(no support for .net types)
493 return true;
494 }
495 }
496 catch
497 {
498 //for c++/cx Resolve() can fail as Cecil understands types as .net (eg, "System.Attribute" instead of "Platform::Metadata::Attribute")
499 //needs to ignore those errors
500 }
501
502 return false;
503 }
504
505 public override bool IsSupportedField(FieldDefinition fdef)
506 {
507 bool isEnumFieldType;
508 try
509 {
510 var typedef = fdef.FieldType.Resolve();
511
512 if (typedef != null)
513 isEnumFieldType = typedef.IsEnum;
514 else
515 isEnumFieldType = false;
516 }
517 catch
518 {
519 //for c++/cx Resolve() can fail as Cecil understands types as .net (eg, "System.Attribute" instead of "Platform::Metadata::Attribute")
520 //needs to ignore those errors
521 isEnumFieldType = false;
522 }
523
524 if (IsCustomAttribute(fdef.DeclaringType))
525 {
526 return !CustomAttributesFieldTypesAllowed.Contains(fdef.FieldType.FullName) ||
527 !isEnumFieldType;
528 }
529
530 if (fdef.IsPublic && fdef.DeclaringType.IsClass && !fdef.DeclaringType.IsValueType && !fdef.DeclaringType.IsEnum)
531 {
532 //Public fields are not allowed in ref class
533 return false;
534 }
535
536 //todo: no const members - which can be??
537 //const member functions + pointers
538
539 return base.IsSupportedField(fdef);
540 }
541
542 public override bool IsSupportedProperty(PropertyDefinition pdef)
543 {
544 var propVisibility = GetPropertyVisibility(pdef, out _, out _);
545 if ((propVisibility.Contains("public:")
546 || propVisibility.Contains("protected:"))
547 && pdef.Parameters.Count > 0)
548 //no support of public indexed property
549 return false;
550
551 return base.IsSupportedProperty(pdef);
552 }
553
554 public override bool IsSupportedMethod(MethodDefinition mdef)
555 {
556 if (mdef.Parameters.Any(IsParamsParameter))
557 {
558 return false;
559 }
560
561 return base.IsSupportedMethod(mdef);
562 }
563
564 private bool IsCustomAttribute(TypeDefinition typedef)
565 {
566 var containingTypeNamespace = DocUtils.GetNamespace(typedef);
567
568 if (typedef.BaseType?.FullName == "System.Attribute" && !containingTypeNamespace.StartsWith("System.") && !containingTypeNamespace.StartsWith("System"))
569 {
570 return true;
571 }
572
573 return false;
574 }
575 }
576 }