RegexPatternDetector.cs 13.8 KB
Newer Older
1 2 3 4 5 6
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
7
using System.Reflection;
8
using System.Runtime.CompilerServices;
9 10
using System.Text.RegularExpressions;
using System.Threading;
C
Cyrus Najmabadi 已提交
11
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
12 13 14 15
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

C
Cyrus Najmabadi 已提交
16
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
17
{
18 19 20
    /// <summary>
    /// Helper class to detect regex pattern tokens in a document efficiently.
    /// </summary>
21 22 23 24
    internal class RegexPatternDetector
    {
        private const string _patternName = "pattern";

25 26 27
        private static readonly ConditionalWeakTable<SemanticModel, RegexPatternDetector> _modelToDetector =
            new ConditionalWeakTable<SemanticModel, RegexPatternDetector>();

28 29 30 31 32 33
        private readonly SemanticModel _semanticModel;
        private readonly ISyntaxFactsService _syntaxFacts;
        private readonly ISemanticFactsService _semanticFacts;
        private readonly INamedTypeSymbol _regexType;
        private readonly HashSet<string> _methodNamesOfInterest;

34 35 36 37 38 39 40 41 42 43 44
        /// <summary>
        /// Helps match patterns of the form: language=regex,option1,option2,option3
        /// 
        /// All matching is case insensitive, with spaces allowed between the punctuation.
        /// 'regex' or 'regexp' are both allowed.  Option values will be or'ed together
        /// to produce final options value.  If an unknown option is encountered, processing
        /// will stop with whatever value has accumulated so far.
        /// 
        /// Option names are the values from the <see cref="RegexOptions"/> enum.
        /// </summary>
        private static readonly Regex s_languageCommentDetector = 
45
            new Regex(@"language\s*=\s*regex(p)?((\s*,\s*)(?<option>[a-zA-Z]+))*",
46 47 48 49 50 51 52
                RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Compiled);

        private static readonly Dictionary<string, RegexOptions> s_nameToOption =
            typeof(RegexOptions).GetTypeInfo().DeclaredFields
                .Where(f => f.FieldType == typeof(RegexOptions))
                .ToDictionary(f => f.Name, f => (RegexOptions)f.GetValue(null), StringComparer.OrdinalIgnoreCase);

53 54 55 56 57
        public RegexPatternDetector(
            SemanticModel semanticModel, 
            ISyntaxFactsService syntaxFacts,
            ISemanticFactsService semanticFacts,
            INamedTypeSymbol regexType, 
58
            HashSet<string> methodNamesOfInterest)
59 60 61 62 63 64 65 66
        {
            _semanticModel = semanticModel;
            _syntaxFacts = syntaxFacts;
            _semanticFacts = semanticFacts;
            _regexType = regexType;
            _methodNamesOfInterest = methodNamesOfInterest;
        }

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
        public static RegexPatternDetector TryGetOrCreate(
            SemanticModel semanticModel,
            ISyntaxFactsService syntaxFacts,
            ISemanticFactsService semanticFacts)
        {
            // Do a quick non-allocating check first.
            if (_modelToDetector.TryGetValue(semanticModel, out var detector))
            {
                return detector;
            }

            return _modelToDetector.GetValue(
                semanticModel, _ => TryCreate(semanticModel, syntaxFacts, semanticFacts));
        }

        private static RegexPatternDetector TryCreate(
83 84
            SemanticModel semanticModel, 
            ISyntaxFactsService syntaxFacts, 
85
            ISemanticFactsService semanticFacts)
86 87 88 89 90 91 92 93 94 95
        {
            var regexType = semanticModel.Compilation.GetTypeByMetadataName(typeof(Regex).FullName);
            if (regexType == null)
            {
                return null;
            }

            var methodNamesOfInterest = GetMethodNamesOfInterest(regexType, syntaxFacts);
            return new RegexPatternDetector(
                semanticModel, syntaxFacts, semanticFacts,
96 97 98 99 100 101 102 103
                regexType, methodNamesOfInterest);
        }

        public static bool IsDefinitelyNotPattern(SyntaxToken token, ISyntaxFactsService syntaxFacts)
        {
            // We only support string literals passed in arguments to something.
            // In the future we could support any string literal, as long as it has
            // some marker (like a comment on it) stating it's a regex.
104 105 106 107 108 109 110
            if (!syntaxFacts.IsStringLiteral(token))
            {
                return true;
            }

            if (!IsMethodOrConstructorArgument(token, syntaxFacts) && 
                !HasRegexLanguageComment(token, syntaxFacts, out _))
111 112 113 114 115
            {
                return true;
            }

            return false;
116 117
        }

118 119 120
        private static bool HasRegexLanguageComment(
            SyntaxToken token, ISyntaxFactsService syntaxFacts, out RegexOptions options)
        {
121 122 123 124 125
            if (HasRegexLanguageComment(token.GetPreviousToken().TrailingTrivia, syntaxFacts, out options))
            {
                return true;
            }

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
            for (var node = token.Parent; node != null; node = node.Parent)
            {
                if (HasRegexLanguageComment(node.GetLeadingTrivia(), syntaxFacts, out options))
                {
                    return true;
                }
            }

            options = default;
            return false;
        }

        private static bool HasRegexLanguageComment(
            SyntaxTriviaList list, ISyntaxFactsService syntaxFacts, out RegexOptions options)
        {
            foreach (var trivia in list)
            {
                if (HasRegexLanguageComment(trivia, syntaxFacts, out options))
                {
                    return true;
                }
            }

            options = default;
            return false;
        }

        private static bool HasRegexLanguageComment(
            SyntaxTrivia trivia, ISyntaxFactsService syntaxFacts, out RegexOptions options)
        {
            if (syntaxFacts.IsRegularComment(trivia))
            {
                var text = trivia.ToString();
159 160
                var match = s_languageCommentDetector.Match(text);
                if (match.Success)
161 162
                {
                    options = RegexOptions.None;
163 164 165 166 167 168 169 170 171 172 173 174 175 176

                    var optionGroup = match.Groups["option"];
                    foreach (Capture capture in optionGroup.Captures)
                    {
                        if (s_nameToOption.TryGetValue(capture.Value, out var specificOption))
                        {
                            options |= specificOption;
                        }
                        else
                        {
                            break;
                        }
                    }

177 178 179 180 181 182 183 184 185 186 187 188
                    return true;
                }
            }

            options = default;
            return false;
        }

        private static bool IsMethodOrConstructorArgument(SyntaxToken token, ISyntaxFactsService syntaxFacts)
            => syntaxFacts.IsLiteralExpression(token.Parent) &&
               syntaxFacts.IsArgument(token.Parent.Parent);

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        private static HashSet<string> GetMethodNamesOfInterest(INamedTypeSymbol regexType, ISyntaxFactsService syntaxFacts)
        {
            var result = syntaxFacts.IsCaseSensitive
                ? new HashSet<string>()
                : new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            var methods = from method in regexType.GetMembers().OfType<IMethodSymbol>()
                          where method.DeclaredAccessibility == Accessibility.Public
                          where method.IsStatic
                          where method.Parameters.Any(p => p.Name == _patternName)
                          select method.Name;

            result.AddRange(methods);

            return result;
        }

206
        public bool IsRegexPattern(SyntaxToken token, CancellationToken cancellationToken, out RegexOptions options)
207 208
        {
            options = default;
209
            if (IsDefinitelyNotPattern(token, _syntaxFacts))
210 211 212 213
            {
                return false;
            }

214 215 216 217 218
            if (HasRegexLanguageComment(token, _syntaxFacts, out options))
            {
                return true;
            }

219
            var stringLiteral = token;
220 221
            var literalNode = stringLiteral.Parent;
            var argumentNode = literalNode.Parent;
222
            Debug.Assert(_syntaxFacts.IsArgument(argumentNode));
223 224 225 226 227 228 229 230 231 232 233

            var argumentList = argumentNode.Parent;
            var invocationOrCreation = argumentList.Parent;
            if (_syntaxFacts.IsInvocationExpression(invocationOrCreation))
            {
                var invokedExpression = _syntaxFacts.GetExpressionOfInvocationExpression(invocationOrCreation);
                var name = GetNameOfInvokedExpression(invokedExpression);
                if (_methodNamesOfInterest.Contains(name))
                {
                    // Is a string argument to a method that looks like it could be a Regex method.  
                    // Need to do deeper analysis
234
                    var method = _semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken).GetAnySymbol();
C
Cyrus Najmabadi 已提交
235 236
                    if (method != null &&
                        method.DeclaredAccessibility == Accessibility.Public &&
237
                        method.IsStatic &&
C
Cyrus Najmabadi 已提交
238
                        _regexType.Equals(method.ContainingType))
239
                    {
240 241
                        return AnalyzeStringLiteral(
                            stringLiteral, argumentNode, cancellationToken, out options);
242 243 244 245 246 247 248 249 250 251 252
                    }
                }
            }
            else if (_syntaxFacts.IsObjectCreationExpression(invocationOrCreation))
            {
                var typeNode = _syntaxFacts.GetObjectCreationType(invocationOrCreation);
                var name = GetNameOfType(typeNode, _syntaxFacts);
                if (name != null)
                {
                    if (_syntaxFacts.StringComparer.Compare(nameof(Regex), name) == 0)
                    {
253 254
                        var constructor = _semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken).GetAnySymbol();
                        if (_regexType.Equals(constructor?.ContainingType))
255 256 257 258 259
                        {
                            // Argument to "new Regex".  Need to do deeper analysis
                            return AnalyzeStringLiteral(
                                stringLiteral, argumentNode, cancellationToken, out options);
                        }
260 261 262 263 264 265 266
                    }
                }
            }

            return false;
        }

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        public RegexTree TryParseRegexPattern(SyntaxToken token, IVirtualCharService virtualCharService, CancellationToken cancellationToken)
        {
            if (!this.IsRegexPattern(token, cancellationToken, out var options))
            {
                return null;
            }

            var chars = virtualCharService.TryConvertToVirtualChars(token);
            if (chars.IsDefaultOrEmpty)
            {
                return null;
            }

            return RegexParser.TryParse(chars, options);
        }

283
        private bool AnalyzeStringLiteral(
284 285
            SyntaxToken stringLiteral, SyntaxNode argumentNode, 
            CancellationToken cancellationToken, out RegexOptions options)
286 287 288
        {
            options = default;

289
            var parameter = _semanticFacts.FindParameterForArgument(_semanticModel, argumentNode, cancellationToken);
290 291 292 293 294
            if (parameter?.Name != _patternName)
            {
                return false;
            }

295
            options = GetRegexOptions(argumentNode, cancellationToken);
296 297 298
            return true;
        }

299
        private RegexOptions GetRegexOptions(SyntaxNode argumentNode, CancellationToken cancellationToken)
300 301 302 303 304 305 306 307 308 309
        {
            var argumentList = argumentNode.Parent;
            var arguments = _syntaxFacts.GetArgumentsOfArgumentList(argumentList);
            foreach (var siblingArg in arguments)
            {
                if (siblingArg != argumentNode)
                {
                    var expr = _syntaxFacts.GetExpressionOfArgument(siblingArg);
                    if (expr != null)
                    {
310
                        var exprType = _semanticModel.GetTypeInfo(expr, cancellationToken);
311 312
                        if (exprType.Type?.Name == nameof(RegexOptions))
                        {
313
                            var constVal = _semanticModel.GetConstantValue(expr, cancellationToken);
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
                            if (constVal.HasValue)
                            {
                                return (RegexOptions)(int)constVal.Value;
                            }
                        }
                    }
                }
            }

            return RegexOptions.None;
        }

        private string GetNameOfType(SyntaxNode typeNode, ISyntaxFactsService syntaxFacts)
        {
            if (syntaxFacts.IsQualifiedName(typeNode))
            {
                return GetNameOfType(syntaxFacts.GetRightSideOfDot(typeNode), syntaxFacts);
            }
            else if (syntaxFacts.IsIdentifierName(typeNode))
            {
                return syntaxFacts.GetIdentifierOfSimpleName(typeNode).ValueText;
            }

            return null;
        }

        private string GetNameOfInvokedExpression(SyntaxNode invokedExpression)
        {
            if (_syntaxFacts.IsSimpleMemberAccessExpression(invokedExpression))
            {
                return _syntaxFacts.GetIdentifierOfSimpleName(_syntaxFacts.GetNameOfMemberAccessExpression(invokedExpression)).ValueText;
            }
            else if (_syntaxFacts.IsIdentifierName(invokedExpression))
            {
                return _syntaxFacts.GetIdentifierOfSimpleName(invokedExpression).ValueText;
            }

            return null;
        }
    }
}