~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to contrib/ICSharpCode.NRefactory/Documentation/XmlDocumentationProvider.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
2
 
// 
3
 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
4
 
// software and associated documentation files (the "Software"), to deal in the Software
5
 
// without restriction, including without limitation the rights to use, copy, modify, merge,
6
 
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
7
 
// to whom the Software is furnished to do so, subject to the following conditions:
8
 
// 
9
 
// The above copyright notice and this permission notice shall be included in all copies or
10
 
// substantial portions of the Software.
11
 
// 
12
 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13
 
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14
 
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
15
 
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
 
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
17
 
// DEALINGS IN THE SOFTWARE.
18
 
 
19
 
using System;
20
 
using System.Collections.Generic;
21
 
using System.Diagnostics;
22
 
using System.IO;
23
 
using System.Runtime.Serialization;
24
 
using System.Xml;
25
 
using ICSharpCode.NRefactory.Editor;
26
 
using ICSharpCode.NRefactory.TypeSystem;
27
 
using ICSharpCode.NRefactory.TypeSystem.Implementation;
28
 
 
29
 
namespace ICSharpCode.NRefactory.Documentation
30
 
{
31
 
        /// <summary>
32
 
        /// Provides documentation from an .xml file (as generated by the Microsoft C# compiler).
33
 
        /// </summary>
34
 
        /// <remarks>
35
 
        /// This class first creates an in-memory index of the .xml file, and then uses that to read only the requested members.
36
 
        /// This way, we avoid keeping all the documentation in memory.
37
 
        /// The .xml file is only opened when necessary, the file handle is not kept open all the time.
38
 
        /// If the .xml file is changed, the index will automatically be recreated.
39
 
        /// </remarks>
40
 
        [Serializable]
41
 
        public class XmlDocumentationProvider : IDocumentationProvider, IDeserializationCallback
42
 
        {
43
 
                #region Cache
44
 
                sealed class XmlDocumentationCache
45
 
                {
46
 
                        readonly KeyValuePair<string, string>[] entries;
47
 
                        int pos;
48
 
                        
49
 
                        public XmlDocumentationCache(int size = 50)
50
 
                        {
51
 
                                if (size <= 0)
52
 
                                        throw new ArgumentOutOfRangeException("size", size, "Value must be positive");
53
 
                                this.entries = new KeyValuePair<string, string>[size];
54
 
                        }
55
 
                        
56
 
                        internal string Get(string key)
57
 
                        {
58
 
                                foreach (var pair in entries) {
59
 
                                        if (pair.Key == key)
60
 
                                                return pair.Value;
61
 
                                }
62
 
                                return null;
63
 
                        }
64
 
                        
65
 
                        internal void Add(string key, string value)
66
 
                        {
67
 
                                entries[pos++] = new KeyValuePair<string, string>(key, value);
68
 
                                if (pos == entries.Length)
69
 
                                        pos = 0;
70
 
                        }
71
 
                }
72
 
                #endregion
73
 
                
74
 
                [Serializable]
75
 
                struct IndexEntry : IComparable<IndexEntry>
76
 
                {
77
 
                        /// <summary>
78
 
                        /// Hash code of the documentation tag
79
 
                        /// </summary>
80
 
                        internal readonly int HashCode;
81
 
                        
82
 
                        /// <summary>
83
 
                        /// Position in the .xml file where the documentation starts
84
 
                        /// </summary>
85
 
                        internal readonly int PositionInFile;
86
 
                        
87
 
                        internal IndexEntry(int hashCode, int positionInFile)
88
 
                        {
89
 
                                this.HashCode = hashCode;
90
 
                                this.PositionInFile = positionInFile;
91
 
                        }
92
 
                        
93
 
                        public int CompareTo(IndexEntry other)
94
 
                        {
95
 
                                return this.HashCode.CompareTo(other.HashCode);
96
 
                        }
97
 
                }
98
 
                
99
 
                [NonSerialized]
100
 
                XmlDocumentationCache cache = new XmlDocumentationCache();
101
 
                
102
 
                readonly string fileName;
103
 
                DateTime lastWriteDate;
104
 
                IndexEntry[] index; // SORTED array of index entries
105
 
                
106
 
                #region Constructor / Redirection support
107
 
                /// <summary>
108
 
                /// Creates a new XmlDocumentationProvider.
109
 
                /// </summary>
110
 
                /// <param name="fileName">Name of the .xml file.</param>
111
 
                public XmlDocumentationProvider(string fileName)
112
 
                {
113
 
                        if (fileName == null)
114
 
                                throw new ArgumentNullException("fileName");
115
 
                        
116
 
                        using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
117
 
                                using (XmlTextReader xmlReader = new XmlTextReader(fs)) {
118
 
                                        xmlReader.XmlResolver = null; // no DTD resolving
119
 
                                        xmlReader.MoveToContent();
120
 
                                        if (string.IsNullOrEmpty(xmlReader.GetAttribute("redirect"))) {
121
 
                                                this.fileName = fileName;
122
 
                                                ReadXmlDoc(xmlReader);
123
 
                                        } else {
124
 
                                                string redirectionTarget = GetRedirectionTarget(xmlReader.GetAttribute("redirect"));
125
 
                                                if (redirectionTarget != null) {
126
 
                                                        Debug.WriteLine("XmlDoc " + fileName + " is redirecting to " + redirectionTarget);
127
 
                                                        using (FileStream redirectedFs = new FileStream(redirectionTarget, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
128
 
                                                                using (XmlTextReader redirectedXmlReader = new XmlTextReader(redirectedFs)) {
129
 
                                                                        this.fileName = redirectionTarget;
130
 
                                                                        ReadXmlDoc(redirectedXmlReader);
131
 
                                                                }
132
 
                                                        }
133
 
                                                } else {
134
 
                                                        throw new XmlException("XmlDoc " + fileName + " is redirecting to " + xmlReader.GetAttribute("redirect") + ", but that file was not found.");
135
 
                                                }
136
 
                                        }
137
 
                                }
138
 
                        }
139
 
                }
140
 
 
141
 
                // ProgramFilesX86 is broken on 32-bit WinXP, this is a workaround
142
 
                static string GetProgramFilesX86()
143
 
                {
144
 
                        return Environment.GetFolderPath(IntPtr.Size == 8?
145
 
                                Environment.SpecialFolder.ProgramFilesX86 : Environment.SpecialFolder.ProgramFiles);
146
 
                }
147
 
 
148
 
                static string GetRedirectionTarget(string target)
149
 
                {
150
 
                        string programFilesDir = AppendDirectorySeparator(GetProgramFilesX86());
151
 
                        
152
 
                        string corSysDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
153
 
                        corSysDir = AppendDirectorySeparator(corSysDir);
154
 
                        
155
 
                        return LookupLocalizedXmlDoc(target.Replace("%PROGRAMFILESDIR%", programFilesDir)
156
 
                                                     .Replace("%CORSYSDIR%", corSysDir));
157
 
                }
158
 
                
159
 
                static string AppendDirectorySeparator(string dir)
160
 
                {
161
 
                        if (dir.EndsWith("\\", StringComparison.Ordinal) || dir.EndsWith("/", StringComparison.Ordinal))
162
 
                                return dir;
163
 
                        else
164
 
                                return dir + Path.DirectorySeparatorChar;
165
 
                }
166
 
                
167
 
                /// <summary>
168
 
                /// Given the assembly file name, looks up the XML documentation file name.
169
 
                /// Returns null if no XML documentation file is found.
170
 
                /// </summary>
171
 
                public static string LookupLocalizedXmlDoc(string fileName)
172
 
                {
173
 
                        string xmlFileName = Path.ChangeExtension(fileName, ".xml");
174
 
                        string currentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
175
 
                        string localizedXmlDocFile = GetLocalizedName(xmlFileName, currentCulture);
176
 
                        
177
 
                        Debug.WriteLine("Try find XMLDoc @" + localizedXmlDocFile);
178
 
                        if (File.Exists(localizedXmlDocFile)) {
179
 
                                return localizedXmlDocFile;
180
 
                        }
181
 
                        Debug.WriteLine("Try find XMLDoc @" + xmlFileName);
182
 
                        if (File.Exists(xmlFileName)) {
183
 
                                return xmlFileName;
184
 
                        }
185
 
                        if (currentCulture != "en") {
186
 
                                string englishXmlDocFile = GetLocalizedName(xmlFileName, "en");
187
 
                                Debug.WriteLine("Try find XMLDoc @" + englishXmlDocFile);
188
 
                                if (File.Exists(englishXmlDocFile)) {
189
 
                                        return englishXmlDocFile;
190
 
                                }
191
 
                        }
192
 
                        return null;
193
 
                }
194
 
                
195
 
                static string GetLocalizedName(string fileName, string language)
196
 
                {
197
 
                        string localizedXmlDocFile = Path.GetDirectoryName(fileName);
198
 
                        localizedXmlDocFile = Path.Combine(localizedXmlDocFile, language);
199
 
                        localizedXmlDocFile = Path.Combine(localizedXmlDocFile, Path.GetFileName(fileName));
200
 
                        return localizedXmlDocFile;
201
 
                }
202
 
                #endregion
203
 
                
204
 
                #region Load / Create Index
205
 
                void ReadXmlDoc(XmlTextReader reader)
206
 
                {
207
 
                        lastWriteDate = File.GetLastWriteTimeUtc(fileName);
208
 
                        // Open up a second file stream for the line<->position mapping
209
 
                        using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
210
 
                                LinePositionMapper linePosMapper = new LinePositionMapper(fs);
211
 
                                List<IndexEntry> indexList = new List<IndexEntry>();
212
 
                                while (reader.Read()) {
213
 
                                        if (reader.IsStartElement()) {
214
 
                                                switch (reader.LocalName) {
215
 
                                                        case "members":
216
 
                                                                ReadMembersSection(reader, linePosMapper, indexList);
217
 
                                                                break;
218
 
                                                }
219
 
                                        }
220
 
                                }
221
 
                                indexList.Sort();
222
 
                                this.index = indexList.ToArray();
223
 
                        }
224
 
                }
225
 
                
226
 
                sealed class LinePositionMapper
227
 
                {
228
 
                        readonly FileStream fs;
229
 
                        int currentLine = 1;
230
 
                        
231
 
                        public LinePositionMapper(FileStream fs)
232
 
                        {
233
 
                                this.fs = fs;
234
 
                        }
235
 
                        
236
 
                        public int GetPositionForLine(int line)
237
 
                        {
238
 
                                Debug.Assert(line >= currentLine);
239
 
                                while (line > currentLine) {
240
 
                                        int b = fs.ReadByte();
241
 
                                        if (b < 0)
242
 
                                                throw new EndOfStreamException();
243
 
                                        if (b == '\n') {
244
 
                                                currentLine++;
245
 
                                        }
246
 
                                }
247
 
                                return checked((int)fs.Position);
248
 
                        }
249
 
                }
250
 
                
251
 
                static void ReadMembersSection(XmlTextReader reader, LinePositionMapper linePosMapper, List<IndexEntry> indexList)
252
 
                {
253
 
                        while (reader.Read()) {
254
 
                                switch (reader.NodeType) {
255
 
                                        case XmlNodeType.EndElement:
256
 
                                                if (reader.LocalName == "members") {
257
 
                                                        return;
258
 
                                                }
259
 
                                                break;
260
 
                                        case XmlNodeType.Element:
261
 
                                                if (reader.LocalName == "member") {
262
 
                                                        int pos = linePosMapper.GetPositionForLine(reader.LineNumber) + Math.Max(reader.LinePosition - 2, 0);
263
 
                                                        string memberAttr = reader.GetAttribute("name");
264
 
                                                        if (memberAttr != null)
265
 
                                                                indexList.Add(new IndexEntry(memberAttr.GetHashCode(), pos));
266
 
                                                        reader.Skip();
267
 
                                                }
268
 
                                                break;
269
 
                                }
270
 
                        }
271
 
                }
272
 
                #endregion
273
 
                
274
 
                #region GetDocumentation
275
 
                /// <summary>
276
 
                /// Get the documentation for the member with the specified documentation key.
277
 
                /// </summary>
278
 
                public string GetDocumentation(string key)
279
 
                {
280
 
                        if (key == null)
281
 
                                throw new ArgumentNullException("key");
282
 
                        
283
 
                        int hashcode = key.GetHashCode();
284
 
                        // index is sorted, so we can use binary search
285
 
                        int m = Array.BinarySearch(index, new IndexEntry(hashcode, 0));
286
 
                        if (m < 0)
287
 
                                return null;
288
 
                        // correct hash code found.
289
 
                        // possibly there are multiple items with the same hash, so go to the first.
290
 
                        while (--m >= 0 && index[m].HashCode == hashcode);
291
 
                        // m is now 1 before the first item with the correct hash
292
 
                        
293
 
                        XmlDocumentationCache cache = this.cache;
294
 
                        lock (cache) {
295
 
                                string val = cache.Get(key);
296
 
                                if (val == null) {
297
 
                                        // go through all items that have the correct hash
298
 
                                        while (++m < index.Length && index[m].HashCode == hashcode) {
299
 
                                                val = LoadDocumentation(key, index[m].PositionInFile);
300
 
                                                if (val != null)
301
 
                                                        break;
302
 
                                        }
303
 
                                        // cache the result (even if it is null)
304
 
                                        cache.Add(key, val);
305
 
                                }
306
 
                                return val;
307
 
                        }
308
 
                }
309
 
                #endregion
310
 
                
311
 
                #region GetDocumentation for entity
312
 
                /// <inheritdoc/>
313
 
                public DocumentationComment GetDocumentation(IEntity entity)
314
 
                {
315
 
                        string xmlDoc = GetDocumentation(IdStringProvider.GetIdString(entity));
316
 
                        if (xmlDoc != null) {
317
 
                                return new DocumentationComment(new StringTextSource(xmlDoc), new SimpleTypeResolveContext(entity));
318
 
                        } else {
319
 
                                return null;
320
 
                        }
321
 
                }
322
 
                #endregion
323
 
                
324
 
                #region Load / Read XML
325
 
                string LoadDocumentation(string key, int positionInFile)
326
 
                {
327
 
                        using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
328
 
                                fs.Position = positionInFile;
329
 
                                using (XmlTextReader r = new XmlTextReader(fs, XmlNodeType.Element, null)) {
330
 
                                        r.XmlResolver = null; // no DTD resolving
331
 
                                        while (r.Read()) {
332
 
                                                if (r.NodeType == XmlNodeType.Element) {
333
 
                                                        string memberAttr = r.GetAttribute("name");
334
 
                                                        if (memberAttr == key) {
335
 
                                                                return r.ReadInnerXml();
336
 
                                                        } else {
337
 
                                                                return null;
338
 
                                                        }
339
 
                                                }
340
 
                                        }
341
 
                                        return null;
342
 
                                }
343
 
                        }
344
 
                }
345
 
                #endregion
346
 
                
347
 
                public virtual void OnDeserialization(object sender)
348
 
                {
349
 
                        cache = new XmlDocumentationCache();
350
 
                }
351
 
        }
352
 
}