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
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using SourceBrowser.Generator.Model;
using SourceBrowser.Generator.Extensions;
using Microsoft.CodeAnalysis.FindSymbols;

namespace SourceBrowser.Generator.DocumentWalkers
{
    class DocumentWalker<TWalkerUtils> : IWalker
        where TWalkerUtils : IWalkerUtils
    {
        private SemanticModel _model;
        private ReferencesourceLinkProvider _refsourceLinkProvider;
        public DocumentModel DocumentModel { get; private set; }
        public string FilePath { get; set; }

        private Document _document;

        private IWalkerUtils _walkerUtils;

        public DocumentWalker(IProjectItem parent, Document document, ReferencesourceLinkProvider refSourceLinkProvider,
            Func<DocumentWalker<TWalkerUtils>, TWalkerUtils> walkerUtilsFactoryMethod)
        {
            _model = document.GetSemanticModelAsync().Result;
            _refsourceLinkProvider = refSourceLinkProvider;
            string containingPath = document.GetRelativeFilePath();

            var numberOfLines = document.GetTextAsync().Result.Lines.Count + 1;
            DocumentModel = new DocumentModel(parent, document.Name, numberOfLines);
            FilePath = document.GetRelativeFilePath();
            _refsourceLinkProvider = refSourceLinkProvider;
            _document = document;

            _walkerUtils = walkerUtilsFactoryMethod(this);
        }

        public void Visit(SyntaxNode syntaxRoot)
        {
            _walkerUtils.Visit(syntaxRoot);
        }

        public void VisitToken(SyntaxToken token)
        {
            Token tokenModel = null;

            if (_walkerUtils.IsKeyword(token))
            {
                tokenModel = ProcessKeyword(token);
            }
            else if (_walkerUtils.IsIdentifier(token))
            {
                tokenModel = ProcessIdentifier(token);
            }
            else if (_walkerUtils.IsLiteral(token))
            {
                tokenModel = ProcessStringLiteral(token);
            }
            else
            {
                //This covers all semantically useless tokens such as punctuation
                tokenModel = ProcessOtherToken(token);
            }

            var leadingTrivia = ProcessTrivia(token.LeadingTrivia);
            var trailingTrivia = ProcessTrivia(token.TrailingTrivia);

            //Add trivia to the token
            tokenModel = tokenModel.WithTrivia(leadingTrivia, trailingTrivia);

            DocumentModel.Tokens.Add(tokenModel);
        }

        public DocumentModel GetDocumentModel()
        {
            return DocumentModel;
        }

        private ICollection<Trivia> ProcessTrivia(SyntaxTriviaList triviaList)
        {
            var triviaModelList = triviaList.Select(n => new Trivia(
                value: n.ToFullString(),
                type: n.CSharpKind().ToString()
            )).ToList();

            return triviaModelList;
        }

        /// <summary>
        /// Creates a Token based on a SyntaxToken for non-keywords and non-identifiers.
        /// </summary>
        private Token ProcessOtherToken(SyntaxToken token)
        {
            string fullName = token.CSharpKind().ToString();
            string value = token.ToString();
            string type = _walkerUtils.OtherTokenTypeName;
            int lineNumber = token.GetLocation().GetLineSpan().StartLinePosition.Line + 1;

            var tokenModel = new Token(this.DocumentModel, fullName, value, type, lineNumber);
            return tokenModel;
        }

        /// <summary>
        /// Creates a Token based on a SyntaxToken for a Keyword.
        /// </summary>
        public Token ProcessKeyword(SyntaxToken token)
        {
            string fullName = _walkerUtils.GetFullName(token);
            string value = token.ToString();
            string type = _walkerUtils.KeywordTokenTypeName;
            int lineNumber = token.GetLocation().GetLineSpan().StartLinePosition.Line + 1;
            var tokenModel = new Token(this.DocumentModel, fullName, value, type, lineNumber);
            return tokenModel;
        }

        private Token ProcessStringLiteral(SyntaxToken token)
        {
            string fullName = _walkerUtils.GetFullName(token);
            string value = token.ToString();
            string type = _walkerUtils.StringTokenTypeName;
            int lineNumber = token.GetLocation().GetLineSpan().StartLinePosition.Line + 1;
            var tokenModel = new Token(this.DocumentModel, fullName, value, type, lineNumber);
            return tokenModel;
        }

        public Token ProcessSymbolUsage(SyntaxToken token, ISymbol symbol, bool isDeclaration)
        {
            string fullName = GetSymbolName(symbol);
            string value = token.ToString();
            string type = String.Empty;
            int lineNumber = token.GetLocation().GetLineSpan().StartLinePosition.Line + 1;
            bool isSearchable = isDeclaration;

            if (symbol is INamedTypeSymbol)
            {
                type = _walkerUtils.TypeTokenTypeName;
            }
            else
            {
                type = _walkerUtils.IdentifierTokenTypeName;
            }

            //Do not allow us to search locals
            if (symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter)
            {
                isSearchable = false;
            }

            var tokenModel = new Token(this.DocumentModel, fullName, value, type, lineNumber, isDeclaration, isSearchable);

            //If we can find the declaration, we'll link it ourselves
            if (symbol.DeclaringSyntaxReferences.Any()
                && !(symbol is INamespaceSymbol))
            {
                var link = new SymbolLink(referencedSymbolName: fullName);
                tokenModel = tokenModel.WithLink(link);
            }
            //Otherwise, we try to link to the .Net Reference source
            else if (_refsourceLinkProvider.Assemblies.Contains(symbol.ContainingAssembly?.Identity?.Name)
                && !(symbol is INamespaceSymbol))
            {
                var link = new UrlLink(url: _refsourceLinkProvider.GetLink(symbol));
                tokenModel = tokenModel.WithLink(link);
            }

            return tokenModel;
        }

        private string GetSymbolName(ISymbol symbol)
        {
            //If this symbol was derived from another (eg. type substitution with generics)
            //retrieve the original definition of the symbol as it appeared in source code
            symbol = symbol.OriginalDefinition;
            string fullyQualifiedName;
            if (symbol.Kind == SymbolKind.Parameter)
            {
                var containingName = symbol.ContainingSymbol.ToString();
                fullyQualifiedName = containingName + _walkerUtils.ParameterDelimiter + symbol.Name;
            }
            else if (symbol.Kind == SymbolKind.Local)
            {
                var containingName = symbol.ContainingSymbol.ToString();
                fullyQualifiedName = containingName + _walkerUtils.LocalVariableDelimiter + symbol.Name;
            }
            else if(symbol.Kind == SymbolKind.Method)
            {
                var methodSymbol = (IMethodSymbol)symbol;
                if (methodSymbol.ReducedFrom != null)
                {
                    //If this method was reduced from an extension method, we 
                    //want to work with the fully qualified name as it originally 
                    //appeared in source code
                    fullyQualifiedName = methodSymbol.ReducedFrom.ToString();
                }
                else
                {
                    fullyQualifiedName = methodSymbol.ToString();
                }
            }
            else
            {
                fullyQualifiedName = symbol.ToString();
            }

            return fullyQualifiedName;
        }

        public Token ProcessIdentifier(SyntaxToken token)
        {
            //Check if this token is part of a declaration
            bool isDeclaration = false;
            if (_model.GetDeclaredSymbol(token.Parent) != null)
            {
                isDeclaration = true;
            }
            var startPosition = token.GetLocation().SourceSpan.Start;
            //Note: We're using the SymbolFinder as it correctly resolves 
            var symbol = SymbolFinder.FindSymbolAtPosition(_model, startPosition, _document.Project.Solution.Workspace);
            if (symbol != null)
            {
                return ProcessSymbolUsage(token, symbol, isDeclaration);
            }

            //Otherwise it references something we don't
            //have semantic information on...
            return ProcessOtherToken(token);
        }
    }
}