Exemplo n.º 1
0
        internal static IEnumerable <TypeMatchSpec> ReadTypesAndMembers(AnalyzerOptions analyzerOptions, Regex fileNamePattern, CancellationToken cancellationToken)
        {
            foreach (string line in ReadAdditionalFiles(analyzerOptions, fileNamePattern, cancellationToken))
            {
                Match?match = null;
                try
                {
                    match = NegatableTypeOrMemberReferenceRegex.Match(line);
                }
                catch (RegexMatchTimeoutException)
                {
                    throw new InvalidOperationException($"Regex.Match timeout when parsing line: {line}");
                }

                if (!match.Success)
                {
                    throw new InvalidOperationException($"Parsing error on line: {line}");
                }

                bool            inverted            = match.Groups["negated"].Success;
                string[]        typeNameElements    = match.Groups["typeName"].Value.Split(QualifiedIdentifierSeparators);
                string          typeName            = typeNameElements[typeNameElements.Length - 1];
                var             containingNamespace = typeNameElements.Take(typeNameElements.Length - 1).ToImmutableArray();
                var             type   = new QualifiedType(containingNamespace, typeName);
                QualifiedMember member = match.Groups["memberName"].Success ? new QualifiedMember(type, match.Groups["memberName"].Value) : default(QualifiedMember);
                yield return(new TypeMatchSpec(type, member, inverted));
            }
        }
Exemplo n.º 2
0
        public static IEnumerable <T> Split <T>([NotNull] this Regex regex, [NotNull] string input, [NotNull] Func <string, bool, T> itemGenerator)
        {
            // ReSharper disable once RedundantEnumerableCastCall (only works in netcoreapp3.0)
            var textParts = regex.Matches(input).Cast <Match>().ToArray();

            Match?previousTextPart = null;

            foreach (var textPart in textParts)
            {
                if (textPart == null)
                {
                    continue;
                }

                var startIndex = previousTextPart?.Index + previousTextPart?.Length ?? 0;

                yield return(itemGenerator(input.Substring(startIndex, textPart.Index - startIndex), false));

                yield return(itemGenerator(textPart.Value, true));

                previousTextPart = textPart;
            }

            yield return(itemGenerator(input.Substring(previousTextPart?.Index + previousTextPart?.Length ?? 0), false));
        }
        /// <summary>
        /// Creates a predicate that checks if the provided regex matches the selected property of any of the channels of the given build.
        /// </summary>
        /// <param name="channelPropertyGetter">Function to select a string from a channel for regex matching.</param>
        /// <param name="regex">Regular expression to be used for evaluating the names of build channels.</param>
        /// <returns>The created predicate.</returns>
        private static Predicate <Build> CreateBuildPredicateBasedOnChannel(Func <Channel, string?> channelPropertyGetter, Regex regex)
        {
            return((build) =>
            {
                if (build.Channels == null || build.Channels.Count == 0)
                {
                    // We couldn't find a channel matching this regular expression
                    return false;
                }

                foreach (Channel?channel in build.Channels)
                {
                    if (channel == null)
                    {
                        // Null channel cannot be considered a match.
                        continue;
                    }

                    string propertyValue = channelPropertyGetter(channel) ?? "";
                    Match?match = regex.Match(propertyValue);

                    if (match == null || !match.Success)
                    {
                        return false;
                    }

                    return match.Length == propertyValue.Length;
                }

                return false;
            });
        }
Exemplo n.º 4
0
        partial void ExtractFailureContent(
            string?content,
            ResponseHeaders responseHeaders,
            ref string?message,
            ref string?errorCode,
            ref IDictionary <string, string>?additionalInfo)
#pragma warning restore CA1801 // Remove unused parameter
#pragma warning restore CA1822 // Member can be static
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return;
            }

            try
            {
                var      errorContentXml = XElement.Parse(content);
                XElement detail          = errorContentXml.Element("Detail");

                message = detail?.Value ?? content;
                Match?match = Regex.Match(
                    detail?.Value,
                    "SubCode=(\\d+)\\.");
                if (match.Success)
                {
                    errorCode = match.Groups[1].Value;
                }
            }
            catch (Exception)
            {
                message = content;
            }
        }
Exemplo n.º 5
0
        // TODO https://github.com/dotnet/runtime/issues/62573: Obsolete this.
        /// <summary>
        /// This method's body is only kept since it is a protected member that could be called by someone outside
        /// the assembly.
        /// </summary>
        protected internal Match?Scan(Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, TimeSpan timeout)
        {
            InitializeTimeout(timeout);

            RegexRunnerMode mode = quick ? RegexRunnerMode.ExistenceRequired : RegexRunnerMode.FullMatchRequired;

            // We set runtext before calling InitializeForScan so that runmatch object is initialized with the text
            runtext = text;

            InitializeForScan(regex, text, textstart, mode);

            // InitializeForScan will default runtextstart and runtextend to 0 and length of string
            // since it is configured to work over a sliced portion of text so we adjust those values.
            runtextstart = textstart;
            runtextend   = textend;

            // Configure the additional value to "bump" the position along each time we loop around
            // to call FindFirstChar again, as well as the stopping position for the loop.  We generally
            // bump by 1 and stop at textend, but if we're examining right-to-left, we instead bump
            // by -1 and stop at textbeg.
            int bump = 1, stoppos = textend;

            if (regex.RightToLeft)
            {
                bump    = -1;
                stoppos = textbeg;
            }

            // If previous match was empty or failed, advance by one before matching.
            if (prevlen == 0)
            {
                if (textstart == stoppos)
                {
                    return(Match.Empty);
                }

                runtextpos += bump;
            }

            Match match = InternalScan(regex, textbeg, textend);

            runtext = null; //drop reference

            if (match.FoundMatch)
            {
                if (quick)
                {
                    return(null);
                }

                runmatch = null;
                match.Tidy(runtextpos, 0, mode);
            }
            else
            {
                runmatch !.Text = null;
            }

            return(match);
        }
Exemplo n.º 6
0
        private async Task GetPagedResponseAsync <T>(string url, Action <T> onGetResults)
        {
            string currentUrl = url;

            while (true)
            {
                HttpResponseMessage response = await SendRequestAsync(
                    () => new HttpRequestMessage(HttpMethod.Get, currentUrl));

                T results = JsonConvert.DeserializeObject <T>(await response.Content.ReadAsStringAsync());

                onGetResults(results);

                if (response.Headers.TryGetValues("Link", out IEnumerable <string>?linkValues))
                {
                    Match?nextLinkMatch = linkValues
                                          .Select(linkValue => s_linkHeaderRegex.Match(linkValue))
                                          .FirstOrDefault(match => match.Success && match.Groups[RelationshipTypeGroup].Value == "next");

                    if (nextLinkMatch == null)
                    {
                        throw new InvalidOperationException(
                                  $"Unable to parse link header '{string.Join(", ", linkValues.ToArray())}'");
                    }

                    currentUrl = $"{_baseUrl}{nextLinkMatch.Groups[LinkUrlGroup].Value}";
                }
                else
                {
                    return;
                }
            }
        }
        protected override ResponseError?ExtractFailureContent(
            string?content,
            ResponseHeaders responseHeaders,
            ref IDictionary <string, string>?additionalInfo)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return(null);
            }

            try
            {
                var      errorContentXml = XElement.Parse(content);
                XElement detail          = errorContentXml.Element("Detail");

                var   message = detail?.Value ?? content;
                Match?match   = Regex.Match(
                    detail?.Value,
                    "SubCode=(\\d+)\\.");

                string?errorCode = null;
                if (match.Success)
                {
                    errorCode = match.Groups[1].Value;
                }

                return(new ResponseError(errorCode, message));
            }
            catch (Exception)
            {
                return(new ResponseError(null, content));
            }
        }
Exemplo n.º 8
0
        internal static QualifiedMember ParseAdditionalFileMethodLine(string line)
        {
            Match?match = null;

            try
            {
                match = MemberReferenceRegex.Match(line);
            }
            catch (RegexMatchTimeoutException)
            {
                throw new InvalidOperationException($"Regex.Match timeout when parsing line: {line}");
            }

            if (!match.Success)
            {
                throw new InvalidOperationException($"Parsing error on line: {line}");
            }

            string methodName = match.Groups["memberName"].Value;

            string[] typeNameElements = match.Groups["typeName"].Value.Split(QualifiedIdentifierSeparators);
            string   typeName         = typeNameElements[typeNameElements.Length - 1];
            var      containingType   = new QualifiedType(typeNameElements.Take(typeNameElements.Length - 1).ToImmutableArray(), typeName);

            return(new QualifiedMember(containingType, methodName));
        }
Exemplo n.º 9
0
 private StatementBuilder Match(
     bool optional,
     Where?optionalWhere,
     params IPatternElement[] elements)
 {
     _match = new Match(optional, new Pattern(elements.ToList()), optionalWhere);
     return(this);
 }
Exemplo n.º 10
0
        public bool Equals(Match?x, Match?y)
        {
            if (x is null || y is null)
            {
                return(false);
            }

            return(x.Value.Equals(y.Value, StringComparison.Ordinal));
        }
Exemplo n.º 11
0
        private void ExecuteInput(SearchContext context, string input)
        {
            int    count         = 0;
            var    maxReason     = MaxReason.None;
            Filter contentFilter = ContentFilter !;
            Match? match         = contentFilter.Match(input);

            if (match != null)
            {
                ContentWriter? contentWriter = null;
                List <Capture>?groups        = null;

                try
                {
                    groups = ListCache <Capture> .GetInstance();

                    maxReason = GetCaptures(match, FileWriterOptions.GroupNumber, context, isPathWritten: false, predicate: contentFilter.Predicate, captures: groups);

                    if (ShouldLog(Verbosity.Normal))
                    {
                        MatchOutputInfo?outputInfo = Options.CreateOutputInfo(input, match, contentFilter);

                        contentWriter = ContentWriter.CreateReplace(Options.ContentDisplayStyle, input, Options.ReplaceOptions, FileWriterOptions, outputInfo: outputInfo);
                    }
                    else
                    {
                        contentWriter = new EmptyContentWriter(FileWriterOptions);
                    }

                    WriteMatches(contentWriter, groups, context);
                    count = contentWriter.MatchCount;
                }
                finally
                {
                    contentWriter?.Dispose();

                    if (groups != null)
                    {
                        ListCache <Capture> .Free(groups);
                    }
                }
            }

            if (ShouldLog(Verbosity.Detailed) ||
                Options.IncludeSummary)
            {
                Verbosity verbosity = (Options.IncludeSummary) ? Verbosity.Minimal : Verbosity.Detailed;

                WriteLine(verbosity);
                WriteCount("Replacements", count, Colors.Message_OK, verbosity);
                WriteIf(maxReason == MaxReason.CountExceedsMax, "+", Colors.Message_OK, verbosity);
                WriteLine(verbosity);
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Returns the ith Match in the collection.
 /// </summary>
 public virtual Match this[int i]
 {
     get
     {
         Match?match = null;
         if (i < 0 || (match = GetMatch(i)) is null)
         {
             ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.i);
         }
         return(match);
     }
 }
Exemplo n.º 13
0
 public bool Equals(Match?other)
 {
     if (other is null)
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(Tile1 == other.Tile1 && Tile1Orientation == other.Tile1Orientation && Tile2 == other.Tile2 && Tile2Orientation == other.Tile2Orientation);
 }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes all the data members that are used by Go()
        /// </summary>
        private void InitializeForGo()
        {
            if (runmatch is null)
            {
                // Use a hashtabled Match object if the capture numbers are sparse
                runmatch = runregex !.caps is null ?
                           new Match(runregex, runregex.capsize, runtext !, runtextbeg, runtextend - runtextbeg, runtextstart) :
                           new MatchSparse(runregex, runregex.caps, runregex.capsize, runtext !, runtextbeg, runtextend - runtextbeg, runtextstart);
            }
            else
            {
                runmatch.Reset(runregex !, runtext !, runtextbeg, runtextend, runtextstart);
            }

            // Note we test runcrawl, because it is the last one to be allocated
            // If there is an alloc failure in the middle of the three allocations,
            // we may still return to reuse this instance, and we want to behave
            // as if the allocations didn't occur.
            if (runcrawl != null)
            {
                runtrackpos = runtrack !.Length;
                runstackpos = runstack !.Length;
                runcrawlpos = runcrawl.Length;
                return;
            }

            // Everything above runs once per match.
            // Everything below runs once per runner.

            InitTrackCount();

            int stacksize;
            int tracksize = stacksize = runtrackcount * 8;

            if (tracksize < 32)
            {
                tracksize = 32;
            }
            if (stacksize < 16)
            {
                stacksize = 16;
            }

            runtrack    = new int[tracksize];
            runtrackpos = tracksize;

            runstack    = new int[stacksize];
            runstackpos = stacksize;

            runcrawl    = new int[32];
            runcrawlpos = 32;
        }
Exemplo n.º 15
0
        /// <summary>
        /// 指定された置換文字列が特殊置換にあてはまるなら、特殊置換のMatchEvaluatorを生成する
        /// </summary>
        /// <param name="replaceText">置換文字列</param>
        /// <returns>特殊置換、なければnull</returns>
        private MatchEvaluator?ConvertToEvaluator(string replaceText)
        {
            Match?matchResult = this.MatchRegex.Match(replaceText);

            if (matchResult?.Success != true || matchResult.Groups.Count <= 2)
            {
                return(null);
            }

            int groupIndex = int.Parse(matchResult.Groups[2].Value);

            return(this.EvaluatorCreator(groupIndex));
        }
Exemplo n.º 16
0
    public static Instruction GetInstruction(string input)
    {
        Match?match = Regex.Match(input, @"(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)");

        if (match.Success)
        {
            return(new(
                       match.Groups[1].Value,
                       new Point(int.Parse(match.Groups[2].Value), int.Parse(match.Groups[3].Value)),
                       new Point(int.Parse(match.Groups[4].Value), int.Parse(match.Groups[5].Value))
                       ));
        }
        return(null !);
    }
Exemplo n.º 17
0
        protected Match?MatchRegExes(string remoteUrl, string[] regExs)
        {
            Match?m = null;

            foreach (var regex in regExs)
            {
                m = Regex.Match(remoteUrl, regex);
                if (m.Success)
                {
                    break;
                }
            }

            return(m);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a predicate that checks if the given property matches the provided regular expression.
        /// </summary>
        /// <param name="propertyGetter">Getter that will return a string property from a <see cref="Build"/></param>
        /// <param name="regex">Regular expression to be used for evaluating the value of the property.</param>
        /// <returns>The created predicate.</returns>
        private static Predicate <Build> CreateBuildPredicateBasedOnStringProperty(Func <Build, string?> propertyGetter, Regex regex)
        {
            return((build) =>
            {
                string value = propertyGetter(build) ?? "";
                Match?match = regex.Match(value);

                if (match == null || !match.Success)
                {
                    return false;
                }

                return match.Length == (value?.Length ?? 0);
            });
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initializes all the data members that are used by Go()
        /// </summary>
        private void InitMatch()
        {
            // Use a hashtabled Match object if the capture numbers are sparse

            if (runmatch == null)
            {
                if (runregex !.caps != null)
                {
                    runmatch = new MatchSparse(runregex, runregex.caps, runregex.capsize, runtext !, runtextbeg, runtextend - runtextbeg, runtextstart);
                }
                else
                {
                    runmatch = new Match(runregex, runregex.capsize, runtext !, runtextbeg, runtextend - runtextbeg, runtextstart);
                }
            }
Exemplo n.º 20
0
        public static List <Token> GetTokens(string?sql)
        {
            if (sql.IsNullOrEmpty())
            {
                return(new List <Token>());
            }

            int startat = 0;
            var tokens  = new List <Token>();

            while (startat < sql.Length)
            {
                Match?match = null;
                foreach (var rex in SqlRegexes)
                { // Complex tokens
                    match = rex.Regex.Match(sql, startat);
                    if (match.Success)
                    {
                        tokens.Add(new Token(rex.TokenType, match.Value, tokens.LastOrDefault()));
                        startat += match.Length;
                        break;
                    }
                }
                if (match?.Success == true)
                {
                    continue;
                }

                match = RegexKeyword.Match(sql, startat);
                if (match.Success)
                { // Simple keywords
                    var token = IsKeyword(match.Value, tokens.LastOrDefault());
                    if (token != null)
                    {
                        tokens.Add(token);
                        startat += match.Length;
                        continue;
                    }
                }

                // Fallback to TokenType.Name
                tokens.Add(new Token(TokenType.Name, match.Value, tokens.LastOrDefault()));
                startat += match.Length == 0 ? 1 : match.Length;
            }

            return(tokens);
        }
        public static IntegerRadixDetector?DetectRadixByFormat(string text)
        {
            #region Проверка аргументов
#if CHECK_ARGS
            _ = text ?? throw new ArgumentNullException(nameof(text));
#endif
            #endregion Проверка аргументов
            foreach (var md in _Detectors)
            {
                Match?m = md.Expression?.Match(text) ?? null;
                if (m?.Success ?? false)
                {
                    return(new IntegerRadixDetector(md, m));
                }
            }
            return(null);
        }
Exemplo n.º 22
0
            public bool MoveNext()
            {
                if (_index == -2)
                {
                    return(false);
                }

                _index++;
                Match?match = _collection.GetMatch(_index);

                if (match == null)
                {
                    _index = -2;
                    return(false);
                }

                return(true);
            }
Exemplo n.º 23
0
        /// <summary>
        /// Returns the ith Match in the collection.
        /// </summary>
        public virtual Match this[int i]
        {
            get
            {
                if (i < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(i));
                }

                Match?match = GetMatch(i);

                if (match == null)
                {
                    throw new ArgumentOutOfRangeException(nameof(i));
                }

                return(match);
            }
        }
Exemplo n.º 24
0
    public BotParser(string message, bool botMentioned, IEnumerable <string>?roles, bool isOwner, string user)
    {
        BotMentioned    = botMentioned;
        OriginalMessage = message;
        Roles           = roles;
        IsOwner         = isOwner;
        User            = user;

        if (message.EndsWith('?'))
        {
            // Parse queries
            Match?matchQuery = _exQuery.Matches(message).FirstOrDefault();
            if (matchQuery is object)
            {
                foreach (Group?group in matchQuery.Groups)
                {
                    if (group?.Name == "query")
                    {
                        Query = string.IsNullOrEmpty(group.Value) ? null : group.Value;
                    }
                }
            }
            return;
        }

        Match?match = _exCommand.Matches(message).FirstOrDefault();

        if (match is object)
        {
            foreach (Group?group in match.Groups)
            {
                if (group?.Name == "command")
                {
                    Command = string.IsNullOrEmpty(group.Value) ? null : group.Value.ToLowerInvariant();
                }
                else if (group?.Name == "argument")
                {
                    CommandArgs = string.IsNullOrEmpty(group.Value) ? null : group.Value;
                }
            }
        }
    }
Exemplo n.º 25
0
        private static List <Match> SearchForMatches(Size targetSize, List <Rectangle> regions, Int32 scaleDivider)
        {
            CalculateHashedImageData(SourceImageContainer, SourceHashedImageData, targetSize, regions);
            CalculateHashedImageData(TargetImageContainer, TargetHashedImageData, targetSize, targetSize);
            ConcurrentBag <Match> matches = new ConcurrentBag <Match>();

            Parallel.ForEach(regions, (Rectangle region) => {
                Parallel.For(region.Left, region.Right - targetSize.Width, (Int32 xSource) => {
                    Parallel.For(region.Top, region.Bottom - targetSize.Height, (Int32 ySource) => {
                        Match?match = Compare(xSource, ySource, targetSize, scaleDivider);
                        if (match != null)
                        {
                            matches.Add(match.Value);
                        }
                    });
                });
            });
            List <Match> result = new List <Match>();

            result.AddRange(matches.ToArray());
            return(result);
        }
Exemplo n.º 26
0
        public ExternalLink Apply(Match?remoteMatch, Match?revisionMatch, GitRevision revision)
        {
            var groups = new List <string>();

            AddGroupsFromMatches(remoteMatch);
            AddGroupsFromMatches(revisionMatch);
            var groupsArray = groups.ToArray <object>();

            string?caption = null;
            string?uri;

            try
            {
                caption = string.Format(Caption, groupsArray);
                Assumes.NotNull(Format);
                uri     = Format.Replace("%COMMIT_HASH%", revision.Guid);
                uri     = string.Format(uri, groupsArray);
                IsValid = true;
            }
            catch (Exception e)
            {
                uri     = e.Message + ": " + Format + " " + groupsArray;
                IsValid = false;
            }

            return(new ExternalLink(caption, uri));

            void AddGroupsFromMatches(Match?match)
            {
                if (match is not null)
                {
                    for (int i = match.Groups.Count > 1 ? 1 : 0; i < match.Groups.Count; i++)
                    {
                        groups.Add(match.Groups[i].Value);
                    }
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>Enumerates all of the matches with the specified regex, invoking the callback for each.</summary>
        /// <remarks>
        /// This optionally repeatedly hands out the same Match instance, updated with new information.
        /// <paramref name="reuseMatchObject"/> should be set to false if the Match object is handed out to user code.
        /// </remarks>
        internal void Scan <TState>(Regex regex, string text, int textstart, ref TState state, MatchCallback <TState> callback, bool reuseMatchObject, TimeSpan timeout)
        {
            // Handle timeout argument
            _timeout = -1; // (int)Regex.InfiniteMatchTimeout.TotalMilliseconds
            bool ignoreTimeout = _ignoreTimeout = Regex.InfiniteMatchTimeout == timeout;

            if (!ignoreTimeout)
            {
                // We are using Environment.TickCount and not Stopwatch for performance reasons.
                // Environment.TickCount is an int that cycles. We intentionally let timeoutOccursAt
                // overflow it will still stay ahead of Environment.TickCount for comparisons made
                // in DoCheckTimeout().
                _timeout             = (int)(timeout.TotalMilliseconds + 0.5); // Round;
                _timeoutOccursAt     = Environment.TickCount + _timeout;
                _timeoutChecksToSkip = TimeoutCheckFrequency;
            }

            // Configure the additional value to "bump" the position along each time we loop around
            // to call FindFirstChar again, as well as the stopping position for the loop.  We generally
            // bump by 1 and stop at text.Length, but if we're examining right-to-left, we instead bump
            // by -1 and stop at 0.
            int bump = 1, stoppos = text.Length;

            if (regex.RightToLeft)
            {
                bump    = -1;
                stoppos = 0;
            }

            // Store remaining arguments into fields now that we're going to start the scan.
            // These are referenced by the derived runner.
            runregex     = regex;
            runtextstart = runtextpos = textstart;
            runtext      = text;
            runtextend   = text.Length;
            runtextbeg   = 0;

            // Main loop: FindFirstChar/Go + bump until the ending position.
            bool initialized = false;

            while (true)
            {
#if DEBUG
                if (regex.IsDebug)
                {
                    Debug.WriteLine("");
                    Debug.WriteLine($"Search range: from {runtextbeg} to {runtextend}");
                    Debug.WriteLine($"Firstchar search starting at {runtextpos} stopping at {stoppos}");
                }
#endif

                // Find the next potential location for a match in the input.
                if (FindFirstChar())
                {
                    if (!ignoreTimeout)
                    {
                        DoCheckTimeout();
                    }

                    // Ensure that the runner is initialized.  This includes initializing all of the state in the runner
                    // that Go might use, such as the backtracking stack, as well as a Match object for it to populate.
                    if (!initialized)
                    {
                        InitializeForGo();
                        initialized = true;
                    }

#if DEBUG
                    if (regex.IsDebug)
                    {
                        Debug.WriteLine($"Executing engine starting at {runtextpos}");
                        Debug.WriteLine("");
                    }
#endif

                    // See if there's a match at this position.
                    Go();

                    // See if we have a match.
                    Match match = runmatch !;
                    if (match._matchcount[0] > 0)
                    {
                        // Hand it out to the callback in canonical form.
                        if (!reuseMatchObject)
                        {
                            // We're not reusing match objects, so null out our field reference to the instance.
                            // It'll be recreated the next time one is needed.
                            runmatch = null;
                        }
                        match.Tidy(runtextpos);
                        initialized = false;
                        if (!callback(ref state, match))
                        {
                            // If the callback returns false, we're done.
                            // Drop reference to text to avoid keeping it alive in a cache.
                            runtext = null !;
                            if (reuseMatchObject)
                            {
                                // We're reusing the single match instance, so clear out its text as well.
                                // We don't do this if we're not reusing instances, as in that case we're
                                // dropping the whole reference to the match, and we no longer own the instance
                                // having handed it out to the callback.
                                match.Text = null !;
                            }
                            return;
                        }

                        // Now that we've matched successfully, update the starting position to reflect
                        // the current position, just as Match.NextMatch() would pass in _textpos as textstart.
                        runtextstart = runtextpos;

                        // Reset state for another iteration.
                        runtrackpos = runtrack !.Length;
                        runstackpos = runstack !.Length;
                        runcrawlpos = runcrawl !.Length;
                        if (match.Length == 0)
                        {
                            if (runtextpos == stoppos)
                            {
                                // Drop reference to text to avoid keeping it alive in a cache.
                                runtext = null !;
                                if (reuseMatchObject)
                                {
                                    // See above comment.
                                    match.Text = null !;
                                }
                                return;
                            }

                            runtextpos += bump;
                        }

                        // Loop around to perform next match from where we left off.
                        continue;
                    }

                    // Ran Go but it didn't find a match. Reset state for another iteration.
                    runtrackpos = runtrack !.Length;
                    runstackpos = runstack !.Length;
                    runcrawlpos = runcrawl !.Length;
                }

                // We failed to match at this position.  If we're at the stopping point, we're done.
                if (runtextpos == stoppos)
                {
                    runtext = null; // drop reference to text to avoid keeping it alive in a cache
                    if (runmatch != null)
                    {
                        runmatch.Text = null !;
                    }
                    return;
                }

                // Bump by one (in whichever direction is appropriate) and loop to go again.
                runtextpos += bump;
            }
        }
Exemplo n.º 28
0
        internal void InitializeForScan(Regex regex, ReadOnlySpan <char> text, int textstart, bool quick)
        {
            // Store remaining arguments into fields now that we're going to start the scan.
            // These are referenced by the derived runner.
            this.quick   = quick;
            runregex     = regex;
            runtextstart = textstart;
            runtextbeg   = 0;
            runtextend   = text.Length;
            runtextpos   = textstart;

            if (runmatch is null)
            {
                // Use a hashtabled Match object if the capture numbers are sparse
                runmatch = runregex !.caps is null ?
                           new Match(runregex, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart) :
                           new MatchSparse(runregex, runregex.caps, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
            }
            else
            {
                runmatch.Reset(runregex !, runtext, runtextbeg, runtextend, runtextstart);
            }

            // Note we test runcrawl, because it is the last one to be allocated
            // If there is an alloc failure in the middle of the three allocations,
            // we may still return to reuse this instance, and we want to behave
            // as if the allocations didn't occur.
            if (runcrawl != null)
            {
                runtrackpos = runtrack !.Length;
                runstackpos = runstack !.Length;
                runcrawlpos = runcrawl.Length;
                return;
            }

            // Everything above runs once per match.
            // Everything below runs once per runner.

            InitTrackCount();

            int stacksize;
            int tracksize = stacksize = runtrackcount * 8;

            if (tracksize < 32)
            {
                tracksize = 32;
            }
            if (stacksize < 16)
            {
                stacksize = 16;
            }

            runtrack    = new int[tracksize];
            runtrackpos = tracksize;

            runstack    = new int[stacksize];
            runstackpos = stacksize;

            runcrawl    = new int[32];
            runcrawlpos = 32;
        }
Exemplo n.º 29
0
        protected internal Match?Scan(Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, TimeSpan timeout)
        {
            // Store arguments into fields for derived runner to examine
            runregex   = regex;
            runtext    = text;
            runtextbeg = textbeg;
            runtextend = textend;
            runtextpos = runtextstart = textstart;

            // Handle timeout argument
            _timeout = -1; // (int)Regex.InfiniteMatchTimeout.TotalMilliseconds
            bool ignoreTimeout = _ignoreTimeout = Regex.InfiniteMatchTimeout == timeout;

            if (!ignoreTimeout)
            {
                // We are using Environment.TickCount and not Stopwatch for performance reasons.
                // Environment.TickCount is an int that cycles. We intentionally let timeoutOccursAt
                // overflow it will still stay ahead of Environment.TickCount for comparisons made
                // in DoCheckTimeout().
                Regex.ValidateMatchTimeout(timeout);                           // validate timeout as this could be called from user code due to being protected
                _timeout             = (int)(timeout.TotalMilliseconds + 0.5); // Round;
                _timeoutOccursAt     = Environment.TickCount + _timeout;
                _timeoutChecksToSkip = TimeoutCheckFrequency;
            }

            // Configure the additional value to "bump" the position along each time we loop around
            // to call FindFirstChar again, as well as the stopping position for the loop.  We generally
            // bump by 1 and stop at runtextend, but if we're examining right-to-left, we instead bump
            // by -1 and stop at runtextbeg.
            int bump = 1, stoppos = runtextend;

            if (runregex.RightToLeft)
            {
                bump    = -1;
                stoppos = runtextbeg;
            }

            // If previous match was empty or failed, advance by one before matching.
            if (prevlen == 0)
            {
                if (runtextpos == stoppos)
                {
                    return(Match.Empty);
                }

                runtextpos += bump;
            }

            // Main loop: FindFirstChar/Go + bump until the ending position.
            bool initialized = false;

            while (true)
            {
#if DEBUG
                if (runregex.IsDebug)
                {
                    Debug.WriteLine("");
                    Debug.WriteLine($"Search range: from {runtextbeg} to {runtextend}");
                    Debug.WriteLine($"Firstchar search starting at {runtextpos} stopping at {stoppos}");
                }
#endif

                // Find the next potential location for a match in the input.
                if (FindFirstChar())
                {
                    if (!ignoreTimeout)
                    {
                        DoCheckTimeout();
                    }

                    // Ensure that the runner is initialized.  This includes initializing all of the state in the runner
                    // that Go might use, such as the backtracking stack, as well as a Match object for it to populate.
                    if (!initialized)
                    {
                        InitializeForGo();
                        initialized = true;
                    }

#if DEBUG
                    if (runregex.IsDebug)
                    {
                        Debug.WriteLine($"Executing engine starting at {runtextpos}");
                        Debug.WriteLine("");
                    }
#endif

                    // See if there's a match at this position.
                    Go();

                    // If we got a match, we're done.
                    Match match = runmatch !;
                    if (match._matchcount[0] > 0)
                    {
                        if (quick)
                        {
                            return(null);
                        }

                        // Return the match in its canonical form.
                        runmatch = null;
                        match.Tidy(runtextpos);
                        return(match);
                    }

                    // Reset state for another iteration.
                    runtrackpos = runtrack !.Length;
                    runstackpos = runstack !.Length;
                    runcrawlpos = runcrawl !.Length;
                }

                // We failed to match at this position.  If we're at the stopping point, we're done.
                if (runtextpos == stoppos)
                {
                    return(Match.Empty);
                }

                // Bump by one (in whichever direction is appropriate) and loop to go again.
                runtextpos += bump;
            }
        }
Exemplo n.º 30
0
        public static Dictionary <string, object> GenerateProperties(FieldType f, Label?l, Caption?c, Search?s, Match?m, Web?w, Highlight?h, Require?r, DateTimeDefault?d)
        {
            var properties = new Dictionary <string, object>
            {
                [PropertyName.SType.GetEnumStringValue()] = (int)f,
                [PropertyName.Label.GetEnumStringValue()] = LabelMapperValue[l ?? Label.Min],
            };

            CaptionMapperValue[c ?? Caption.Missing](properties);
            SearchMapperValue[s ?? Search.Missing](properties);
            MatchMapperValue[m ?? Match.Missing](properties);
            WebMapperValue[w ?? Web.Missing](properties);
            HighlightMapperValue[h ?? Highlight.Missing](properties);
            RequireMapperValue[r ?? Require.Missing](properties);
            DefaultDateMapper[d ?? DateTimeDefault.Missing](properties);
            return(properties);
        }