In ilasm/tests:
[mcs.git] / mcs / doc.cs
blobdf44df59a726775cf0376433544df8aa80751d76
1 //
2 // doc.cs: Support for XML documentation comment.
3 //
4 // Author:
5 // Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2004 Novell, Inc.
12 #if ! BOOTSTRAP_WITH_OLDLIB
13 using System;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.IO;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.CompilerServices;
20 using System.Runtime.InteropServices;
21 using System.Security;
22 using System.Security.Permissions;
23 using System.Text;
24 using System.Xml;
26 using Mono.CompilerServices.SymbolWriter;
28 namespace Mono.CSharp {
31 // Support class for XML documentation.
33 #if NET_2_0
34 static
35 #else
36 abstract
37 #endif
38 public class DocUtil
40 #if !NET_2_0
41 private DocUtil () {}
42 #endif
43 // TypeContainer
46 // Generates xml doc comments (if any), and if required,
47 // handle warning report.
49 internal static void GenerateTypeDocComment (TypeContainer t,
50 DeclSpace ds)
52 GenerateDocComment (t, ds);
54 if (t.DefaultStaticConstructor != null)
55 t.DefaultStaticConstructor.GenerateDocComment (t);
57 if (t.InstanceConstructors != null)
58 foreach (Constructor c in t.InstanceConstructors)
59 c.GenerateDocComment (t);
61 if (t.Types != null)
62 foreach (TypeContainer tc in t.Types)
63 tc.GenerateDocComment (t);
65 if (t.Enums != null)
66 foreach (Enum en in t.Enums)
67 en.GenerateDocComment (t);
69 if (t.Constants != null)
70 foreach (Const c in t.Constants)
71 c.GenerateDocComment (t);
73 if (t.Fields != null)
74 foreach (FieldBase f in t.Fields)
75 f.GenerateDocComment (t);
77 if (t.Events != null)
78 foreach (Event e in t.Events)
79 e.GenerateDocComment (t);
81 if (t.Indexers != null)
82 foreach (Indexer ix in t.Indexers)
83 ix.GenerateDocComment (t);
85 if (t.Properties != null)
86 foreach (Property p in t.Properties)
87 p.GenerateDocComment (t);
89 if (t.Methods != null)
90 foreach (Method m in t.Methods)
91 m.GenerateDocComment (t);
93 if (t.Operators != null)
94 foreach (Operator o in t.Operators)
95 o.GenerateDocComment (t);
98 // MemberCore
99 private static readonly string lineHead =
100 Environment.NewLine + " ";
102 private static XmlNode GetDocCommentNode (MemberCore mc,
103 string name)
105 // FIXME: It could be even optimizable as not
106 // to use XmlDocument. But anyways the nodes
107 // are not kept in memory.
108 XmlDocument doc = RootContext.Documentation.XmlDocumentation;
109 try {
110 XmlElement el = doc.CreateElement ("member");
111 el.SetAttribute ("name", name);
112 string normalized = mc.DocComment;
113 el.InnerXml = normalized;
114 // csc keeps lines as written in the sources
115 // and inserts formatting indentation (which
116 // is different from XmlTextWriter.Formatting
117 // one), but when a start tag contains an
118 // endline, it joins the next line. We don't
119 // have to follow such a hacky behavior.
120 string [] split =
121 normalized.Split ('\n');
122 int j = 0;
123 for (int i = 0; i < split.Length; i++) {
124 string s = split [i].TrimEnd ();
125 if (s.Length > 0)
126 split [j++] = s;
128 el.InnerXml = lineHead + String.Join (
129 lineHead, split, 0, j);
130 return el;
131 } catch (XmlException ex) {
132 Report.Warning (1570, 1, mc.Location, "XML comment on `{0}' has non-well-formed XML ({1})", name, ex.Message);
133 XmlComment com = doc.CreateComment (String.Format ("FIXME: Invalid documentation markup was found for member {0}", name));
134 return com;
139 // Generates xml doc comments (if any), and if required,
140 // handle warning report.
142 internal static void GenerateDocComment (MemberCore mc,
143 DeclSpace ds)
145 if (mc.DocComment != null) {
146 string name = mc.GetDocCommentName (ds);
148 XmlNode n = GetDocCommentNode (mc, name);
150 XmlElement el = n as XmlElement;
151 if (el != null) {
152 mc.OnGenerateDocComment (el);
154 // FIXME: it could be done with XmlReader
155 XmlNodeList nl = n.SelectNodes (".//include");
156 if (nl.Count > 0) {
157 // It could result in current node removal, so prepare another list to iterate.
158 ArrayList al = new ArrayList (nl.Count);
159 foreach (XmlNode inc in nl)
160 al.Add (inc);
161 foreach (XmlElement inc in al)
162 if (!HandleInclude (mc, inc))
163 inc.ParentNode.RemoveChild (inc);
166 // FIXME: it could be done with XmlReader
167 DeclSpace dsTarget = mc as DeclSpace;
168 if (dsTarget == null)
169 dsTarget = ds;
171 foreach (XmlElement see in n.SelectNodes (".//see"))
172 HandleSee (mc, dsTarget, see);
173 foreach (XmlElement seealso in n.SelectNodes (".//seealso"))
174 HandleSeeAlso (mc, dsTarget, seealso);
175 foreach (XmlElement see in n.SelectNodes (".//exception"))
176 HandleException (mc, dsTarget, see);
179 n.WriteTo (RootContext.Documentation.XmlCommentOutput);
181 else if (mc.IsExposedFromAssembly ()) {
182 Constructor c = mc as Constructor;
183 if (c == null || !c.IsDefault ())
184 Report.Warning (1591, 4, mc.Location,
185 "Missing XML comment for publicly visible type or member `{0}'", mc.GetSignatureForError ());
190 // Processes "include" element. Check included file and
191 // embed the document content inside this documentation node.
193 private static bool HandleInclude (MemberCore mc, XmlElement el)
195 bool keepIncludeNode = false;
196 string file = el.GetAttribute ("file");
197 string path = el.GetAttribute ("path");
198 if (file == "") {
199 Report.Warning (1590, 1, mc.Location, "Invalid XML `include' element. Missing `file' attribute");
200 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
201 keepIncludeNode = true;
203 else if (path.Length == 0) {
204 Report.Warning (1590, 1, mc.Location, "Invalid XML `include' element. Missing `path' attribute");
205 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
206 keepIncludeNode = true;
208 else {
209 XmlDocument doc = RootContext.Documentation.StoredDocuments [file] as XmlDocument;
210 if (doc == null) {
211 try {
212 doc = new XmlDocument ();
213 doc.Load (file);
214 RootContext.Documentation.StoredDocuments.Add (file, doc);
215 } catch (Exception) {
216 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (String.Format (" Badly formed XML in at comment file `{0}': cannot be included ", file)), el);
217 Report.Warning (1592, 1, mc.Location, "Badly formed XML in included comments file -- `{0}'", file);
220 if (doc != null) {
221 try {
222 XmlNodeList nl = doc.SelectNodes (path);
223 if (nl.Count == 0) {
224 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" No matching elements were found for the include tag embedded here. "), el);
226 keepIncludeNode = true;
228 foreach (XmlNode n in nl)
229 el.ParentNode.InsertBefore (el.OwnerDocument.ImportNode (n, true), el);
230 } catch (Exception ex) {
231 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Failed to insert some or all of included XML "), el);
232 Report.Warning (1589, 1, mc.Location, "Unable to include XML fragment `{0}' of file `{1}' ({2})", path, file, ex.Message);
236 return keepIncludeNode;
240 // Handles <see> elements.
242 private static void HandleSee (MemberCore mc,
243 DeclSpace ds, XmlElement see)
245 HandleXrefCommon (mc, ds, see);
249 // Handles <seealso> elements.
251 private static void HandleSeeAlso (MemberCore mc,
252 DeclSpace ds, XmlElement seealso)
254 HandleXrefCommon (mc, ds, seealso);
258 // Handles <exception> elements.
260 private static void HandleException (MemberCore mc,
261 DeclSpace ds, XmlElement seealso)
263 HandleXrefCommon (mc, ds, seealso);
266 static readonly char [] wsChars =
267 new char [] {' ', '\t', '\n', '\r'};
270 // returns a full runtime type name from a name which might
271 // be C# specific type name.
273 private static Type FindDocumentedType (MemberCore mc, string name, DeclSpace ds, string cref)
275 bool isArray = false;
276 string identifier = name;
277 if (name [name.Length - 1] == ']') {
278 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
279 if (tmp [tmp.Length - 1] == '[') {
280 identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
281 isArray = true;
284 Type t = FindDocumentedTypeNonArray (mc, identifier, ds, cref);
285 if (t != null && isArray)
286 t = Array.CreateInstance (t, 0).GetType ();
287 return t;
290 private static Type FindDocumentedTypeNonArray (MemberCore mc,
291 string identifier, DeclSpace ds, string cref)
293 switch (identifier) {
294 case "int":
295 return typeof (int);
296 case "uint":
297 return typeof (uint);
298 case "short":
299 return typeof (short);
300 case "ushort":
301 return typeof (ushort);
302 case "long":
303 return typeof (long);
304 case "ulong":
305 return typeof (ulong);
306 case "float":
307 return typeof (float);
308 case "double":
309 return typeof (double);
310 case "char":
311 return typeof (char);
312 case "decimal":
313 return typeof (decimal);
314 case "byte":
315 return typeof (byte);
316 case "sbyte":
317 return typeof (sbyte);
318 case "object":
319 return typeof (object);
320 case "bool":
321 return typeof (bool);
322 case "string":
323 return typeof (string);
324 case "void":
325 return typeof (void);
327 FullNamedExpression e = ds.LookupType (identifier, mc.Location, false);
328 if (e != null) {
329 if (!(e is TypeExpr))
330 return null;
331 return e.Type;
333 int index = identifier.LastIndexOf ('.');
334 if (index < 0)
335 return null;
336 int warn;
337 Type parent = FindDocumentedType (mc, identifier.Substring (0, index), ds, cref);
338 if (parent == null)
339 return null;
340 // no need to detect warning 419 here
341 return FindDocumentedMember (mc, parent,
342 identifier.Substring (index + 1),
343 null, ds, out warn, cref, false, null).Member as Type;
346 private static MemberInfo [] empty_member_infos =
347 new MemberInfo [0];
349 private static MemberInfo [] FindMethodBase (Type type,
350 BindingFlags bindingFlags, MethodSignature signature)
352 MemberList ml = TypeManager.FindMembers (
353 type,
354 MemberTypes.Constructor | MemberTypes.Method | MemberTypes.Property | MemberTypes.Custom,
355 bindingFlags,
356 MethodSignature.method_signature_filter,
357 signature);
358 if (ml == null)
359 return empty_member_infos;
361 return FilterOverridenMembersOut ((MemberInfo []) ml);
364 static bool IsOverride (PropertyInfo deriv_prop, PropertyInfo base_prop)
366 if (!Invocation.IsAncestralType (base_prop.DeclaringType, deriv_prop.DeclaringType))
367 return false;
369 Type [] deriv_pd = TypeManager.GetArgumentTypes (deriv_prop);
370 Type [] base_pd = TypeManager.GetArgumentTypes (base_prop);
372 if (deriv_pd.Length != base_pd.Length)
373 return false;
375 for (int j = 0; j < deriv_pd.Length; ++j) {
376 if (deriv_pd [j] != base_pd [j])
377 return false;
378 Type ct = TypeManager.TypeToCoreType (deriv_pd [j]);
379 Type bt = TypeManager.TypeToCoreType (base_pd [j]);
381 if (ct != bt)
382 return false;
385 return true;
388 private static MemberInfo [] FilterOverridenMembersOut (
389 MemberInfo [] ml)
391 if (ml == null)
392 return empty_member_infos;
394 ArrayList al = new ArrayList (ml.Length);
395 for (int i = 0; i < ml.Length; i++) {
396 MethodBase mx = ml [i] as MethodBase;
397 PropertyInfo px = ml [i] as PropertyInfo;
398 if (mx != null || px != null) {
399 bool overriden = false;
400 for (int j = 0; j < ml.Length; j++) {
401 if (j == i)
402 continue;
403 MethodBase my = ml [j] as MethodBase;
404 if (mx != null && my != null &&
405 Invocation.IsOverride (my, mx)) {
406 overriden = true;
407 break;
409 else if (mx != null)
410 continue;
411 PropertyInfo py = ml [j] as PropertyInfo;
412 if (px != null && py != null &&
413 IsOverride (py, px)) {
414 overriden = true;
415 break;
418 if (overriden)
419 continue;
421 al.Add (ml [i]);
423 return al.ToArray (typeof (MemberInfo)) as MemberInfo [];
426 struct FoundMember
428 public static FoundMember Empty = new FoundMember (true);
430 public bool IsEmpty;
431 public readonly MemberInfo Member;
432 public readonly Type Type;
434 public FoundMember (bool regardlessOfThisValueItsEmpty)
436 IsEmpty = true;
437 Member = null;
438 Type = null;
441 public FoundMember (Type foundType, MemberInfo member)
443 IsEmpty = false;
444 Type = foundType;
445 Member = member;
450 // Returns a MemberInfo that is referenced in XML documentation
451 // (by "see" or "seealso" elements).
453 private static FoundMember FindDocumentedMember (MemberCore mc,
454 Type type, string memberName, Type [] paramList,
455 DeclSpace ds, out int warningType, string cref,
456 bool warn419, string nameForError)
458 for (; type != null; type = type.DeclaringType) {
459 MemberInfo mi = FindDocumentedMemberNoNest (
460 mc, type, memberName, paramList, ds,
461 out warningType, cref, warn419,
462 nameForError);
463 if (mi != null)
464 return new FoundMember (type, mi);
466 warningType = 0;
467 return FoundMember.Empty;
470 private static MemberInfo FindDocumentedMemberNoNest (
471 MemberCore mc, Type type, string memberName,
472 Type [] paramList, DeclSpace ds, out int warningType,
473 string cref, bool warn419, string nameForError)
475 warningType = 0;
476 MemberInfo [] mis;
478 if (paramList == null) {
479 // search for fields/events etc.
480 mis = TypeManager.MemberLookup (type, null,
481 type, MemberTypes.All,
482 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
483 memberName, null);
484 mis = FilterOverridenMembersOut (mis);
485 if (mis == null || mis.Length == 0)
486 return null;
487 if (warn419 && IsAmbiguous (mis))
488 Report419 (mc, nameForError, mis);
489 return mis [0];
492 MethodSignature msig = new MethodSignature (memberName, null, paramList);
493 mis = FindMethodBase (type,
494 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
495 msig);
497 if (warn419 && mis.Length > 0) {
498 if (IsAmbiguous (mis))
499 Report419 (mc, nameForError, mis);
500 return mis [0];
503 // search for operators (whose parameters exactly
504 // matches with the list) and possibly report CS1581.
505 string oper = null;
506 string returnTypeName = null;
507 if (memberName.StartsWith ("implicit operator ")) {
508 oper = "op_Implicit";
509 returnTypeName = memberName.Substring (18).Trim (wsChars);
511 else if (memberName.StartsWith ("explicit operator ")) {
512 oper = "op_Explicit";
513 returnTypeName = memberName.Substring (18).Trim (wsChars);
515 else if (memberName.StartsWith ("operator ")) {
516 oper = memberName.Substring (9).Trim (wsChars);
517 switch (oper) {
518 // either unary or binary
519 case "+":
520 oper = paramList.Length == 2 ?
521 Binary.oper_names [(int) Binary.Operator.Addition] :
522 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
523 break;
524 case "-":
525 oper = paramList.Length == 2 ?
526 Binary.oper_names [(int) Binary.Operator.Subtraction] :
527 Unary.oper_names [(int) Unary.Operator.UnaryNegation];
528 break;
529 // unary
530 case "!":
531 oper = Unary.oper_names [(int) Unary.Operator.LogicalNot]; break;
532 case "~":
533 oper = Unary.oper_names [(int) Unary.Operator.OnesComplement]; break;
535 case "++":
536 oper = "op_Increment"; break;
537 case "--":
538 oper = "op_Decrement"; break;
539 case "true":
540 oper = "op_True"; break;
541 case "false":
542 oper = "op_False"; break;
543 // binary
544 case "*":
545 oper = Binary.oper_names [(int) Binary.Operator.Multiply]; break;
546 case "/":
547 oper = Binary.oper_names [(int) Binary.Operator.Division]; break;
548 case "%":
549 oper = Binary.oper_names [(int) Binary.Operator.Modulus]; break;
550 case "&":
551 oper = Binary.oper_names [(int) Binary.Operator.BitwiseAnd]; break;
552 case "|":
553 oper = Binary.oper_names [(int) Binary.Operator.BitwiseOr]; break;
554 case "^":
555 oper = Binary.oper_names [(int) Binary.Operator.ExclusiveOr]; break;
556 case "<<":
557 oper = Binary.oper_names [(int) Binary.Operator.LeftShift]; break;
558 case ">>":
559 oper = Binary.oper_names [(int) Binary.Operator.RightShift]; break;
560 case "==":
561 oper = Binary.oper_names [(int) Binary.Operator.Equality]; break;
562 case "!=":
563 oper = Binary.oper_names [(int) Binary.Operator.Inequality]; break;
564 case "<":
565 oper = Binary.oper_names [(int) Binary.Operator.LessThan]; break;
566 case ">":
567 oper = Binary.oper_names [(int) Binary.Operator.GreaterThan]; break;
568 case "<=":
569 oper = Binary.oper_names [(int) Binary.Operator.LessThanOrEqual]; break;
570 case ">=":
571 oper = Binary.oper_names [(int) Binary.Operator.GreaterThanOrEqual]; break;
572 default:
573 warningType = 1584;
574 Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", paramList.Length == 2 ? "binary" : "unary");
575 Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
576 mc.GetSignatureForError (), cref);
577 return null;
580 // here we still don't consider return type (to
581 // detect CS1581 or CS1002+CS1584).
582 msig = new MethodSignature (oper, null, paramList);
584 mis = FindMethodBase (type,
585 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
586 msig);
587 if (mis.Length == 0)
588 return null; // CS1574
589 MemberInfo mi = mis [0];
590 Type expected = mi is MethodInfo ?
591 ((MethodInfo) mi).ReturnType :
592 mi is PropertyInfo ?
593 ((PropertyInfo) mi).PropertyType :
594 null;
595 if (returnTypeName != null) {
596 Type returnType = FindDocumentedType (mc, returnTypeName, ds, cref);
597 if (returnType == null || returnType != expected) {
598 warningType = 1581;
599 Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
600 return null;
603 return mis [0];
606 private static bool IsAmbiguous (MemberInfo [] members)
608 if (members.Length < 2)
609 return false;
610 if (members.Length > 2)
611 return true;
612 if (members [0] is EventInfo && members [1] is FieldInfo)
613 return false;
614 if (members [1] is EventInfo && members [0] is FieldInfo)
615 return false;
616 return true;
620 // Processes "see" or "seealso" elements.
621 // Checks cref attribute.
623 private static void HandleXrefCommon (MemberCore mc,
624 DeclSpace ds, XmlElement xref)
626 string cref = xref.GetAttribute ("cref").Trim (wsChars);
627 // when, XmlReader, "if (cref == null)"
628 if (!xref.HasAttribute ("cref"))
629 return;
630 if (cref.Length == 0)
631 Report.Warning (1001, 1, mc.Location, "Identifier expected");
632 // ... and continue until CS1584.
634 string signature; // "x:" are stripped
635 string name; // method invokation "(...)" are removed
636 string parameters; // method parameter list
638 // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
639 // Here, MS ignores its member kind. No idea why.
640 if (cref.Length > 2 && cref [1] == ':')
641 signature = cref.Substring (2).Trim (wsChars);
642 else
643 signature = cref;
645 int parensPos = signature.IndexOf ('(');
646 int bracePos = parensPos >= 0 ? -1 :
647 signature.IndexOf ('[');
648 if (parensPos > 0 && signature [signature.Length - 1] == ')') {
649 name = signature.Substring (0, parensPos).Trim (wsChars);
650 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2).Trim (wsChars);
652 else if (bracePos > 0 && signature [signature.Length - 1] == ']') {
653 name = signature.Substring (0, bracePos).Trim (wsChars);
654 parameters = signature.Substring (bracePos + 1, signature.Length - bracePos - 2).Trim (wsChars);
656 else {
657 name = signature;
658 parameters = null;
660 Normalize (mc, ref name);
662 string identifier = GetBodyIdentifierFromName (name);
664 // Check if identifier is valid.
665 // This check is not necessary to mark as error, but
666 // csc specially reports CS1584 for wrong identifiers.
667 string [] nameElems = identifier.Split ('.');
668 for (int i = 0; i < nameElems.Length; i++) {
669 string nameElem = GetBodyIdentifierFromName (nameElems [i]);
670 if (i > 0)
671 Normalize (mc, ref nameElem);
672 if (!Tokenizer.IsValidIdentifier (nameElem)
673 && nameElem.IndexOf ("operator") < 0) {
674 Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
675 mc.GetSignatureForError (), cref);
676 xref.SetAttribute ("cref", "!:" + signature);
677 return;
681 // check if parameters are valid
682 Type [] parameterTypes;
683 if (parameters == null)
684 parameterTypes = null;
685 else if (parameters.Length == 0)
686 parameterTypes = Type.EmptyTypes;
687 else {
688 string [] paramList = parameters.Split (',');
689 ArrayList plist = new ArrayList ();
690 for (int i = 0; i < paramList.Length; i++) {
691 string paramTypeName = paramList [i].Trim (wsChars);
692 Normalize (mc, ref paramTypeName);
693 Type paramType = FindDocumentedType (mc, paramTypeName, ds, cref);
694 if (paramType == null) {
695 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
696 (i + 1).ToString (), cref);
697 return;
699 plist.Add (paramType);
701 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
704 Type type = FindDocumentedType (mc, name, ds, cref);
705 if (type != null
706 // delegate must not be referenced with args
707 && (!type.IsSubclassOf (typeof (System.Delegate))
708 || parameterTypes == null)) {
709 string result = GetSignatureForDoc (type)
710 + (bracePos < 0 ? String.Empty : signature.Substring (bracePos));
711 xref.SetAttribute ("cref", "T:" + result);
712 return; // a type
715 int period = name.LastIndexOf ('.');
716 if (period > 0) {
717 string typeName = name.Substring (0, period);
718 string memberName = name.Substring (period + 1);
719 Normalize (mc, ref memberName);
720 type = FindDocumentedType (mc, typeName, ds, cref);
721 int warnResult;
722 if (type != null) {
723 FoundMember fm = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref, true, name);
724 if (warnResult > 0)
725 return;
726 if (!fm.IsEmpty) {
727 MemberInfo mi = fm.Member;
728 // we cannot use 'type' directly
729 // to get its name, since mi
730 // could be from DeclaringType
731 // for nested types.
732 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + memberName + GetParametersFormatted (mi));
733 return; // a member of a type
737 else {
738 int warnResult;
739 FoundMember fm = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref, true, name);
740 if (warnResult > 0)
741 return;
742 if (!fm.IsEmpty) {
743 MemberInfo mi = fm.Member;
744 // we cannot use 'type' directly
745 // to get its name, since mi
746 // could be from DeclaringType
747 // for nested types.
748 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + name + GetParametersFormatted (mi));
749 return; // local member name
753 // It still might be part of namespace name.
754 Namespace ns = ds.NamespaceEntry.NS.GetNamespace (name, false);
755 if (ns != null) {
756 xref.SetAttribute ("cref", "N:" + ns.FullName);
757 return; // a namespace
759 if (RootNamespace.Global.IsNamespace (name)) {
760 xref.SetAttribute ("cref", "N:" + name);
761 return; // a namespace
764 Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved",
765 mc.GetSignatureForError (), cref);
767 xref.SetAttribute ("cref", "!:" + name);
770 static string GetParametersFormatted (MemberInfo mi)
772 MethodBase mb = mi as MethodBase;
773 bool isSetter = false;
774 PropertyInfo pi = mi as PropertyInfo;
775 if (pi != null) {
776 mb = pi.GetGetMethod ();
777 if (mb == null) {
778 isSetter = true;
779 mb = pi.GetSetMethod ();
782 if (mb == null)
783 return String.Empty;
785 ParameterData parameters = TypeManager.GetParameterData (mb);
786 if (parameters == null || parameters.Count == 0)
787 return String.Empty;
789 StringBuilder sb = new StringBuilder ();
790 sb.Append ('(');
791 for (int i = 0; i < parameters.Count; i++) {
792 if (isSetter && i + 1 == parameters.Count)
793 break; // skip "value".
794 if (i > 0)
795 sb.Append (',');
796 Type t = parameters.ParameterType (i);
797 sb.Append (GetSignatureForDoc (t));
799 sb.Append (')');
800 return sb.ToString ();
803 static string GetBodyIdentifierFromName (string name)
805 string identifier = name;
807 if (name.Length > 0 && name [name.Length - 1] == ']') {
808 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
809 int last = tmp.LastIndexOf ('[');
810 if (last > 0)
811 identifier = tmp.Substring (0, last).Trim (wsChars);
814 return identifier;
817 static void Report419 (MemberCore mc, string memberName, MemberInfo [] mis)
819 Report.Warning (419, 3, mc.Location,
820 "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
821 memberName,
822 TypeManager.GetFullNameSignature (mis [0]),
823 TypeManager.GetFullNameSignature (mis [1]));
827 // Get a prefix from member type for XML documentation (used
828 // to formalize cref target name).
830 static string GetMemberDocHead (MemberTypes type)
832 switch (type) {
833 case MemberTypes.Constructor:
834 case MemberTypes.Method:
835 return "M:";
836 case MemberTypes.Event:
837 return "E:";
838 case MemberTypes.Field:
839 return "F:";
840 case MemberTypes.NestedType:
841 case MemberTypes.TypeInfo:
842 return "T:";
843 case MemberTypes.Property:
844 return "P:";
846 return "!:";
849 // MethodCore
852 // Returns a string that represents the signature for this
853 // member which should be used in XML documentation.
855 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
857 Parameter [] plist = mc.Parameters.FixedParameters;
858 string paramSpec = String.Empty;
859 if (plist != null) {
860 StringBuilder psb = new StringBuilder ();
861 foreach (Parameter p in plist) {
862 psb.Append (psb.Length != 0 ? "," : "(");
863 psb.Append (GetSignatureForDoc (p.ExternalType ()));
865 paramSpec = psb.ToString ();
868 if (paramSpec.Length > 0)
869 paramSpec += ")";
871 string name = mc is Constructor ? "#ctor" : mc.Name;
872 string suffix = String.Empty;
873 Operator op = mc as Operator;
874 if (op != null) {
875 switch (op.OperatorType) {
876 case Operator.OpType.Implicit:
877 case Operator.OpType.Explicit:
878 suffix = "~" + GetSignatureForDoc (op.MethodBuilder.ReturnType);
879 break;
882 return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
885 static string GetSignatureForDoc (Type type)
887 return TypeManager.IsGenericParameter (type) ?
888 "`" + TypeManager.GenericParameterPosition (type) :
889 type.FullName.Replace ("+", ".").Replace ('&', '@');
893 // Raised (and passed an XmlElement that contains the comment)
894 // when GenerateDocComment is writing documentation expectedly.
896 // FIXME: with a few effort, it could be done with XmlReader,
897 // that means removal of DOM use.
899 internal static void OnMethodGenerateDocComment (
900 MethodCore mc, XmlElement el)
902 Hashtable paramTags = new Hashtable ();
903 foreach (XmlElement pelem in el.SelectNodes ("param")) {
904 int i;
905 string xname = pelem.GetAttribute ("name");
906 if (xname.Length == 0)
907 continue; // really? but MS looks doing so
908 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
909 Report.Warning (1572, 2, mc.Location, "XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name",
910 mc.GetSignatureForError (), xname);
911 else if (paramTags [xname] != null)
912 Report.Warning (1571, 2, mc.Location, "XML comment on `{0}' has a duplicate param tag for `{1}'",
913 mc.GetSignatureForError (), xname);
914 paramTags [xname] = xname;
916 Parameter [] plist = mc.Parameters.FixedParameters;
917 foreach (Parameter p in plist) {
918 if (paramTags.Count > 0 && paramTags [p.Name] == null)
919 Report.Warning (1573, 4, mc.Location, "Parameter `{0}' has no matching param tag in the XML comment for `{1}'",
920 p.Name, mc.GetSignatureForError ());
924 private static void Normalize (MemberCore mc, ref string name)
926 if (name.Length > 0 && name [0] == '@')
927 name = name.Substring (1);
928 else if (name == "this")
929 name = "Item";
930 else if (Tokenizer.IsKeyword (name) && !IsTypeName (name))
931 Report.Warning (1041, 1, mc.Location, "Identifier expected. `{0}' is a keyword", name);
934 private static bool IsTypeName (string name)
936 switch (name) {
937 case "bool":
938 case "byte":
939 case "char":
940 case "decimal":
941 case "double":
942 case "float":
943 case "int":
944 case "long":
945 case "object":
946 case "sbyte":
947 case "short":
948 case "string":
949 case "uint":
950 case "ulong":
951 case "ushort":
952 case "void":
953 return true;
955 return false;
960 // Implements XML documentation generation.
962 public class Documentation
964 public Documentation (string xml_output_filename)
966 docfilename = xml_output_filename;
967 XmlDocumentation = new XmlDocument ();
968 XmlDocumentation.PreserveWhitespace = false;
971 private string docfilename;
974 // Used to create element which helps well-formedness checking.
976 public XmlDocument XmlDocumentation;
979 // The output for XML documentation.
981 public XmlWriter XmlCommentOutput;
984 // Stores XmlDocuments that are included in XML documentation.
985 // Keys are included filenames, values are XmlDocuments.
987 public Hashtable StoredDocuments = new Hashtable ();
990 // Outputs XML documentation comment from tokenized comments.
992 public bool OutputDocComment (string asmfilename)
994 XmlTextWriter w = null;
995 try {
996 w = new XmlTextWriter (docfilename, null);
997 w.Indentation = 4;
998 w.Formatting = Formatting.Indented;
999 w.WriteStartDocument ();
1000 w.WriteStartElement ("doc");
1001 w.WriteStartElement ("assembly");
1002 w.WriteStartElement ("name");
1003 w.WriteString (Path.ChangeExtension (asmfilename, null));
1004 w.WriteEndElement (); // name
1005 w.WriteEndElement (); // assembly
1006 w.WriteStartElement ("members");
1007 XmlCommentOutput = w;
1008 GenerateDocComment ();
1009 w.WriteFullEndElement (); // members
1010 w.WriteEndElement ();
1011 w.WriteWhitespace (Environment.NewLine);
1012 w.WriteEndDocument ();
1013 return true;
1014 } catch (Exception ex) {
1015 Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", docfilename, ex.Message);
1016 return false;
1017 } finally {
1018 if (w != null)
1019 w.Close ();
1024 // Fixes full type name of each documented types/members up.
1026 public void GenerateDocComment ()
1028 TypeContainer root = RootContext.Tree.Types;
1029 if (root.Interfaces != null)
1030 foreach (Interface i in root.Interfaces)
1031 DocUtil.GenerateTypeDocComment (i, null);
1033 if (root.Types != null)
1034 foreach (TypeContainer tc in root.Types)
1035 DocUtil.GenerateTypeDocComment (tc, null);
1037 if (root.Delegates != null)
1038 foreach (Delegate d in root.Delegates)
1039 DocUtil.GenerateDocComment (d, null);
1041 if (root.Enums != null)
1042 foreach (Enum e in root.Enums)
1043 e.GenerateDocComment (null);
1048 #endif