System.Diagnostics.Debug.Assert(bool)

Here are the examples of the csharp api System.Diagnostics.Debug.Assert(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

12000 Examples 7

19 View Source File : DialogBox.cs
License : GNU General Public License v3.0
Project Creator : audiamus

public void WndProcRet(object sender, WndProcRetEventArgs e)
		{
			if (e.cw.message == WndMessage.WM_INITDIALOG ||
				e.cw.message == WndMessage.WM_UNKNOWINIT)
			{
				USER32.MoveWindow(e.cw.hwnd, rect.Left, rect.Top, rect.Width, rect.Height, 1);
				
				// uninstall this hook
				WindowsHook wndHook = (WindowsHook)sender;
				Debug.replacedert(wndProcRetHook == wndHook);
				wndProcRetHook.Uninstall();
				wndProcRetHook = null;
			}
		}

19 View Source File : ButtonJudge.cs
License : MIT License
Project Creator : audfx

public JudgeResult? UserPressed(time_t position)
        {
            // This check just makes sure that we can process ticks.
            // If there are no state ticks, there should never be score ticks left.
            if (HreplacedtateTicks)
            {
                Debug.replacedert(HreplacedcoreTicks);
            }
            else
            {
                SpawnKeyBeam?.Invoke(Label, JudgeKind.Preplacedive, false);
                return null;
            }

            switch (m_state)
            {
                case JudgeState.Idle:
                {
                    var nextStateTick = NextStateTick;

                    time_t difference = position - (nextStateTick.Position + JudgementOffset);
                    time_t absDifference = Math.Abs((double)difference);

                    if (nextStateTick.State == JudgeState.ChipAwaitPress && absDifference <= m_chipMissRadius)
                    {
                        var scoreTick = NextScoreTick;

                        Debug.replacedert(scoreTick.Kind == TickKind.Chip);
                        Debug.replacedert(scoreTick.Position == nextStateTick.Position);

                        // `difference` applies to both ticks, don't recalculate

                        JudgeResult result;
                        if (absDifference <= m_chipPerfectRadius)
                            result = new JudgeResult(difference, JudgeKind.Perfect);
                        else if (absDifference <= m_chipCriticalRadius)
                            result = new JudgeResult(difference, JudgeKind.Critical);
                        else if (absDifference <= m_chipNearRadius)
                            result = new JudgeResult(difference, JudgeKind.Near);
                        // TODO(local): Is this how we want to handle misses?
                        else result = new JudgeResult(difference, JudgeKind.Bad);

                        OnTickProcessed?.Invoke(scoreTick.Enreplacedy, position, result, difference < 0);
                        OnChipPressed?.Invoke(position, scoreTick.Enreplacedy);
                        SpawnKeyBeam?.Invoke(scoreTick.Enreplacedy.Lane, result.Kind, difference < 0);

                        AdvanceStateTick();
                        AdvanceScoreTick();

                        // state stays idle after a chip press, chips are instantaneous

                        IsBeingPlayed = true;

                        return result;
                    }
                    else if (nextStateTick.State == JudgeState.HoldAwaitPress && absDifference <= m_holdActivateRadius)
                    {
                        OnHoldPressed?.Invoke(position, nextStateTick.Enreplacedy);

                        AdvanceStateTick();
                        // No need to advance a score tick, we haven't judged anything

                        // state is `hold on` because ofc we pressed the hold!
                        m_state = JudgeState.HoldOn;
                        m_currentStateTick = nextStateTick;

                        IsBeingPlayed = true;
                    }

                    // do nothing when pressed otherwise
                    else SpawnKeyBeam?.Invoke(Label, JudgeKind.Preplacedive, false);
                } break;

                case JudgeState.HoldOff:
                {
                    OnHoldPressed?.Invoke(position, m_currentStateTick.Enreplacedy);

                    m_state = JudgeState.HoldOn;

                    IsBeingPlayed = true;
                } break;

                case JudgeState.HoldOn: throw new InvalidOperationException();
            }

            return null;
        }

19 View Source File : ClassSettingPanel.xaml.cs
License : GNU General Public License v3.0
Project Creator : autodotua

private void ApplyMatchConditions(Clreplaced c)
        {
            foreach (var m in c.MatchConditions)
            {
                if (m.Value == null)
                {
                    Debug.replacedert(false);
                    m.Value = "";
                }
            }
            c.MatchConditions.Clear();
            c.MatchConditions.AddRange(MatchConditions);
        }

19 View Source File : SmoothScrollViewerHelper.cs
License : GNU General Public License v3.0
Project Creator : autodotua

public static void HandleMouseWheel(ScrollViewer scr, int delta)
        {
            Debug.replacedert(scr != null);
            Debug.WriteLineIf(DebugSwitch.ScorllInfo, "Scroll Happened");

            //如果当前的滚动视图还没有进行过滚动,那么进行注册
            if (!remainsDeltas.ContainsKey(scr))
            {
                remainsDeltas.Add(scr, 0);
            }

            remainsDeltas[scr] = remainsDeltas[scr] * 1.5 + delta;//乘一个系数,那么滚轮越快页面滑动也将越快
            if (remainsDeltas[scr] != delta)
            {
                //如果滚动正在进行,那么把滚动交给之前的方法即可
                return;
            }
            if (currentScrollViewer != null && remainsDeltas.ContainsKey(currentScrollViewer))
            {
                remainsDeltas[currentScrollViewer] = 0;
            }
            currentScrollViewer = scr;
        }

19 View Source File : FileClassUtility.cs
License : GNU General Public License v3.0
Project Creator : autodotua

public static void UpdateFilesOfClreplacedes(UpdateFilesArgs args)
        {
            Debug.WriteLine("db begin: " + nameof(UpdateFilesOfClreplacedes));

            //dbFiles只在需要刷新物理文件时用到,但是因为有两个作用域,所以写在了外层
            HashSet<File> dbFiles = null;//= new HashSet<File>(Queryable.Where(DbUtility.db.Files, (System.Linq.Expressions.Expression<Func<File, bool>>)(p => (bool)(p.Project == args.Project))));

            List<File> files = null;
            if (args.Research)
            {
                dbFiles = new HashSet<File>(db.Files.Where(p => p.ProjectID == args.Project.ID));
                IReadOnlyList<System.IO.FileSystemInfo> diskFiles = FzLib.IO.FileSystem.EnumerateAccessibleFileSystemInfos(args.Project.RootPath);
                if (args.DeleteNonExistenreplacedems)
                {
                    HashSet<string> paths = new HashSet<string>(diskFiles.Select(p => p.FullName));

                    //删除已不存在的文件
                    foreach (var file in dbFiles)
                    {
                        if (!paths.Contains(file.GetAbsolutePath()))
                        {
                            db.Entry(file).State = EnreplacedyState.Deleted;
                        }
                    }
                    db.SaveChanges();
                }
                files = diskFiles
                .OfType<FI>()
                .Select(p => new File(p, args.Project)).ToList();
            }
            else
            {
                files = db.Files.Where(p => p.ProjectID == args.Project.ID).Include(p => p.Project).ToList();
            }

            //现在数据库中该项目的所有文件应该都存在相对应的物理文件
            int index = 0;
            int count = files.Count;
            DateTime lastCallbackTime = DateTime.MinValue;
            var clreplacedes = db.Clreplacedes.ToList();
            foreach (var file in files)
            {
                File f = null;// new File(file, args.Project);
                if (args.Research)
                {
                    //先判断一下数据库中是否已存在该文件
                    if (!dbFiles.Contains(file))
                    {
                        f = file;
                        db.Files.Add(f);
                    }
                    else
                    {
                        //如果数据库中存在该文件,则从HashSet中提取该文件
                        if (!dbFiles.TryGetValue(file, out File newF))
                        {
                            //理论上不会进来
                            Debug.replacedert(false);
                        }
                        f = newF;
                    }
                    args.GenerateThumbnailsMethod?.Invoke(f);
                    //if (args.IncludeThumbnails)
                    //{
                    //    FileUtility.TryGenerateThumbnail(f);
                    //}
                    //if (args.IncludeExplorerIcons)
                    //{
                    //    FileUtility.TryGenerateExplorerIcon(f);
                    //}
                }
                else
                {
                    f = file;
                }
                if (args.Reclreplacedify)
                {
                    foreach (var c in clreplacedes.Where(p => p.ProjectID == args.Project.ID))
                    {
                        FileClreplaced fc = IncludeAll(db.FileClreplacedes)
                            .FirstOrDefault(p => p.Clreplaced == c && p.File == f);
                        bool isMatched = FileUtility.IsMatched(f.FileInfo, c);
                        if (fc == null && isMatched)
                        {
                            //如果匹配并且不存在,那么新增关系
                            db.Add(new FileClreplaced(c, f, false));
                        }
                        else if (fc != null && !isMatched && fc.Status != FileClreplacedStatus.AddManully)
                        {
                            //如果存在关系但不匹配,那么应该删除已存在的关系
                            //注意,手动删除的关系并不会走到这一步
                            db.Entry(fc).State = EnreplacedyState.Deleted;
                        }
                        //其他情况,既不需要增加,也不需要删除
                    }
                }
                index++;
                if (args.Callback != null && (DateTime.Now - lastCallbackTime).TotalMilliseconds > CallbackUpdateMs)
                {
                    lastCallbackTime = DateTime.Now;
                    if (!args.Callback(index * 1.0 / count, f))
                    {
                        db.SaveChanges();
                        return;
                    }
                }
            }

            db.SaveChanges();
            Debug.WriteLine("db end: " + nameof(UpdateFilesOfClreplacedes));
        }

19 View Source File : DisplayFormatConverter.cs
License : GNU General Public License v3.0
Project Creator : autodotua

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values[0].Equals(DependencyProperty.UnsetValue))
            {
                return "";
            }
            UIFileDisplay display = values[0] as UIFileDisplay;
            Clreplaced c = values[1] as Clreplaced;
            System.Diagnostics.Debug.replacedert(c != null);
            string format = (int)parameter switch
            {
                0 => c.DisplayNameFormat,
                1 => c.DisplayProperty1,
                2 => c.DisplayProperty2,
                3 => c.DisplayProperty3
            };

19 View Source File : TokenBindingExtensions.cs
License : MIT License
Project Creator : autostep

private static string GetFullText(TokenisedArgumentValue binding, ILifetimeScope scope, string rawText, Func<string, string?> getVariableValue)
        {
            // Ok, so we need to go get the raw text from the matched tokens.
            var tokens = binding.MatchedTokens;

            if (tokens.Length == 0)
            {
                return string.Empty;
            }

            var lastStopIdx = 0;

            var foundVariables = new string?[tokens.Length];

            int textSize = 0;

            // Do a first preplaced to determine string length and variable size.
            for (int tokenIdx = 0; tokenIdx < tokens.Length; tokenIdx++)
            {
                var currentToken = tokens[tokenIdx];

                if (binding.StartExclusive && tokenIdx == 0)
                {
                    lastStopIdx = currentToken.StartIndex + currentToken.Length;

                    // Just skip.
                    continue;
                }

                if (tokenIdx > 0)
                {
                    // Add the space between this and the last token.
                    textSize += currentToken.StartIndex - lastStopIdx;
                }

                if (!binding.EndExclusive || tokenIdx != tokens.Length - 1)
                {
                    // Add text size for the token itself.
                    if (currentToken is VariableToken variable)
                    {
                        var variableText = getVariableValue(variable.VariableName) ?? string.Empty;
                        foundVariables[tokenIdx] = variableText;
                        textSize += variableText.Length;
                    }
                    else if (currentToken is InterpolateStartToken)
                    {
                        // We'll come back to this.
                        // This is where we need the service scope.
                        Debug.replacedert(scope is object);

                        textSize += currentToken.Length;
                    }
                    else
                    {
                        textSize += currentToken.Length;
                    }

                    lastStopIdx = currentToken.StartIndex + currentToken.Length;
                }
            }

            var createdString = string.Create(textSize, tokens, (chars, tokens) =>
            {
                var textSpan = rawText.replacedpan();

                // Now we loop over the tokens and do our actual copy.
                for (int tokenIdx = 0; tokenIdx < tokens.Length; tokenIdx++)
                {
                    var currentToken = tokens[tokenIdx];

                    if (binding.StartExclusive && tokenIdx == 0)
                    {
                        lastStopIdx = currentToken.StartIndex + currentToken.Length;

                        // Just skip.
                        continue;
                    }

                    if (tokenIdx > 0)
                    {
                        // Add the space between this and the last token.
                        var whiteSpaceLength = currentToken.StartIndex - lastStopIdx;

                        textSpan.Slice(lastStopIdx, whiteSpaceLength).CopyTo(chars);

                        // Move the chars along.
                        chars = chars.Slice(whiteSpaceLength);
                    }

                    if (!binding.EndExclusive || tokenIdx != tokens.Length - 1)
                    {
                        var knownVariable = foundVariables[tokenIdx];

                        if (knownVariable is null)
                        {
                            // Copy the contents of the token.
                            textSpan.Slice(currentToken.StartIndex, currentToken.Length).CopyTo(chars);
                            chars = chars.Slice(currentToken.Length);
                        }
                        else
                        {
                            knownVariable.replacedpan().CopyTo(chars);
                            chars = chars.Slice(knownVariable.Length);
                        }

                        lastStopIdx = currentToken.StartIndex + currentToken.Length;
                    }
                }
            });

            return createdString;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitFeatureBlock([NotNull] AutoStepParser.FeatureBlockContext context)
        {
            Debug.replacedert(Result is object);

            // Clear the set of feature scenario names.
            featureScenarioNames.Clear();

            if (Result!.Feature != null)
            {
                // We already have a feature, don't go any deeper, add an error.
                MessageSet.Add(context.featureDefinition().featurereplacedle(), CompilerMessageLevel.Error, CompilerMessageCode.OnlyOneFeatureAllowed);
                return Result!;
            }

            Result!.Feature = new FeatureElement
            {
                SourceName = SourceName,
            };

            currentAnnotatable = Result!.Feature;

            PositionIndex?.PushScope(Result.Feature, context);

            VisitChildren(context);

            PositionIndex?.PopScope(context);

            if (!string.IsNullOrEmpty(Result!.Feature.Name) && Result!.Feature.Scenarios.Count == 0)
            {
                // Warning should be replacedociated to the replacedle.
                MessageSet.Add(context.featureDefinition().featurereplacedle(), CompilerMessageLevel.Warning, CompilerMessageCode.NoScenarios, Result!.Feature.Name ?? "unknown");
            }

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitTagAnnotation([NotNull] AutoStepParser.TagAnnotationContext context)
        {
            Debug.replacedert(Result is object);

            if (currentAnnotatable == null)
            {
                MessageSet.Add(context, CompilerMessageLevel.Error, CompilerMessageCode.UnexpectedAnnotation);
                return Result!;
            }

            var tagBody = context.ANNOTATION_TEXT().GetText();

            tagBody = tagBody.TrimEnd();

            var element = new TagElement(tagBody).AddLineInfo(context);

            currentAnnotatable.Annotations.Add(element);

            PositionIndex?.AddLineToken(context, element, LineTokenCategory.Annotation, LineTokenSubCategory.Tag);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitOptionAnnotation([NotNull] AutoStepParser.OptionAnnotationContext context)
        {
            Debug.replacedert(Result is object);

            if (currentAnnotatable == null)
            {
                MessageSet.Add(context, CompilerMessageLevel.Error, CompilerMessageCode.UnexpectedAnnotation);
                return Result!;
            }

            var optBody = context.ANNOTATION_TEXT().GetText();

            // Trim the body to get rid of trailing whitespace.
            optBody = optBody.TrimEnd();

            // Now split on the first ':'.
            var positionOfColon = optBody.IndexOf(':', StringComparison.CurrentCulture);

            string? setting = null;
            var name = optBody;

            if (positionOfColon != -1)
            {
                var nextChar = positionOfColon + 1;
                name = name.Substring(0, positionOfColon);

                if (nextChar < optBody.Length)
                {
                    // Error, colon has been placed with no other content.
                    setting = optBody.Substring(nextChar).Trim();
                }

                if (string.IsNullOrEmpty(setting))
                {
                    MessageSet.Add(context, CompilerMessageLevel.Error, CompilerMessageCode.OptionWithNoSetting, name);
                }
            }

            var optElement = new OptionElement(name)
            {
                Setting = setting,
            }.AddLineInfo(context);

            currentAnnotatable.Annotations.Add(optElement);

            PositionIndex?.AddLineToken(context, optElement, LineTokenCategory.Annotation, LineTokenSubCategory.Option);

            return Result;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitFeatureDefinition([NotNull] AutoStepParser.FeatureDefinitionContext context)
        {
            Debug.replacedert(Result is object);

            var replacedleTree = context.featurereplacedle();

            var featureToken = replacedleTree.FEATURE();
            var featureKeyWordText = featureToken.GetText();

            PositionIndex?.AddLineToken(featureToken, LineTokenCategory.EntryMarker, LineTokenSubCategory.Feature);

            // We want the parser to allow case-insensitive keywords through, so we can replacedert on them
            // here and give more useful errors.
            if (featureKeyWordText != "Feature:")
            {
                MessageSet.Add(featureToken, CompilerMessageLevel.Error, CompilerMessageCode.InvalidFeatureKeyword, featureKeyWordText);
            }

            var textEl = replacedleTree.text();

            if (textEl is object)
            {
                PositionIndex?.AddLineToken(textEl, LineTokenCategory.EnreplacedyName, LineTokenSubCategory.Feature);
            }

            var replacedle = textEl?.GetText() ?? string.Empty;
            var description = ExtractDescription(context.description());

            // Past this point, annotations aren't valid.
            currentAnnotatable = null;

            Result!.Feature!.AddLineInfo(replacedleTree);

            Result!.Feature!.Name = replacedle;
            Result!.Feature!.Description = string.IsNullOrWhiteSpace(description) ? null : description;

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitBackgroundBlock([NotNull] AutoStepParser.BackgroundBlockContext context)
        {
            Debug.replacedert(Result is object);

            var background = new BackgroundElement();

            var backgroundNode = context.BACKGROUND();

            PositionIndex?.PushScope(background, context);

            PositionIndex?.AddLineToken(backgroundNode, LineTokenCategory.EntryMarker, LineTokenSubCategory.Background);

            background.AddLineInfo(backgroundNode);

            Result!.Feature!.Background = background;

            currentStepSet = background.Steps;
            currentStepSetLastConcrete = null;

            VisitChildren(context);

            PositionIndex?.PopScope(context);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitStepDefinitionBlock([NotNull] AutoStepParser.StepDefinitionBlockContext context)
        {
            Debug.replacedert(Result is object);

            var definition = context.stepDefinition();

            var declaration = definition.stepDeclaration();

            StepType? type = declaration switch
            {
                AutoStepParser.DeclareGivenContext _ => StepType.Given,
                AutoStepParser.DeclareWhenContext _ => StepType.When,
                AutoStepParser.DeclareThenContext _ => StepType.Then,
                _ => null
            };

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitScenarioBlock([NotNull] AutoStepParser.ScenarioBlockContext context)
        {
            Debug.replacedert(Result is object);

            ScenarioElement scenario;

            var definition = context.scenarioDefinition();
            var replacedle = definition.scenarioreplacedle();

            string replacedleText;

            if (replacedle is AutoStepParser.NormalScenarioreplacedleContext scenarioreplacedle)
            {
                var scenarioToken = scenarioreplacedle.SCENARIO();
                var scenarioKeyWordText = scenarioToken.GetText();

                // We want the parser to allow case-insensitive keywords through, so we can replacedert on them
                // here and give more useful errors.
                if (scenarioKeyWordText != "Scenario:")
                {
                    MessageSet.Add(scenarioToken, CompilerMessageLevel.Error, CompilerMessageCode.InvalidScenarioKeyword, scenarioKeyWordText);
                }

                var replacedleToken = scenarioreplacedle.text();
                scenario = new ScenarioElement();
                replacedleText = replacedleToken?.GetText() ?? string.Empty;

                PositionIndex?.PushScope(scenario, context);

                PositionIndex?.AddLineToken(scenarioToken, LineTokenCategory.EntryMarker, LineTokenSubCategory.Scenario);

                if (replacedleToken is object)
                {
                    PositionIndex?.AddLineToken(replacedleToken, LineTokenCategory.EnreplacedyName, LineTokenSubCategory.Scenario);
                }
            }
            else if (replacedle is AutoStepParser.ScenarioOutlinereplacedleContext scenarioOutlinereplacedle)
            {
                var scenarioOutlineToken = scenarioOutlinereplacedle.SCENARIO_OUTLINE();
                var scenarioOutlineKeyWordText = scenarioOutlineToken.GetText();

                // We want the parser to allow case-insensitive keywords through, so we can replacedert on them
                // here and give more useful errors.
                if (scenarioOutlineKeyWordText != "Scenario Outline:")
                {
                    MessageSet.Add(scenarioOutlineToken, CompilerMessageLevel.Error, CompilerMessageCode.InvalidScenarioOutlineKeyword, scenarioOutlineKeyWordText);
                }

                var replacedleToken = scenarioOutlinereplacedle.text();

                scenario = new ScenarioOutlineElement();
                replacedleText = replacedleToken?.GetText() ?? string.Empty;

                PositionIndex?.PushScope(scenario, context);

                PositionIndex?.AddLineToken(scenarioOutlineToken, LineTokenCategory.EntryMarker, LineTokenSubCategory.ScenarioOutline);

                if (replacedleToken is object)
                {
                    PositionIndex?.AddLineToken(replacedleToken, LineTokenCategory.EnreplacedyName, LineTokenSubCategory.ScenarioOutline);
                }
            }
            else
            {
                const string replacedertFailure = "Cannot reach here if the parser rules are valid; parser will not enter the " +
                                             "scenario block if neither SCENARIO or SCENARIO_OUTLINE tokens are present.";
                Debug.replacedert(false, replacedertFailure);
                return Result!;
            }

            currentAnnotatable = scenario;

            var annotations = context.annotations();
            if (annotations is object)
            {
                Visit(annotations);
            }

            scenario.AddPositionalLineInfo(replacedle);
            scenario.Name = replacedleText;

            // Try to add our scenario name to the unique set.
            if (!string.IsNullOrEmpty(scenario.Name) && !featureScenarioNames.Add(scenario.Name))
            {
                // This scenario name is already in-use in this feature, add an error.
                MessageSet.Add(replacedle, CompilerMessageLevel.Error, CompilerMessageCode.DuplicateScenarioNames, scenario.Name);
            }

            var description = ExtractDescription(definition.description());

            scenario.Description = string.IsNullOrWhiteSpace(description) ? null : description;

            currentAnnotatable = null;
            currentScenario = scenario;

            // Visit the examples first, it will let us validate any insertion variables
            // when we process the steps.
            Visit(context.examples());

            currentStepSet = scenario.Steps;
            currentStepSetLastConcrete = null;

            Visit(context.scenarioBody());

            currentStepSet = null;
            currentScenario = null;

            Result!.Feature!.Scenarios.Add(scenario);

            PositionIndex?.PopScope(context);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitGiven([NotNull] AutoStepParser.GivenContext context)
        {
            Debug.replacedert(Result is object);

            AddStep(context.GIVEN(), context);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitThen([NotNull] AutoStepParser.ThenContext context)
        {
            Debug.replacedert(Result is object);

            AddStep(context.THEN(), context);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitWhen([NotNull] AutoStepParser.WhenContext context)
        {
            Debug.replacedert(Result is object);

            AddStep(context.WHEN(), context);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitAnd([NotNull] AutoStepParser.AndContext context)
        {
            Debug.replacedert(Result is object);

            AddStep(context.AND(), context);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitStatementWithTable([NotNull] AutoStepParser.StatementWithTableContext context)
        {
            Debug.replacedert(Result is object);

            Visit(context.statement());

            var tableBlock = context.tableBlock();

            var table = tableVisitor.BuildTable(tableBlock);

            if (lastStep is object)
            {
                lastStep.Table = table;
            }

            MergeVisitorAndReset(tableVisitor);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

public override FileElement VisitExampleBlock([NotNull] AutoStepParser.ExampleBlockContext context)
        {
            Debug.replacedert(Result is object);
            Debug.replacedert(currentScenario is object);

            var outline = currentScenario as ScenarioOutlineElement;

            var examplesKeyword = context.EXAMPLES();

            var exampleTokenText = examplesKeyword.GetText();

            if (exampleTokenText != "Examples:")
            {
                MessageSet.Add(examplesKeyword, CompilerMessageLevel.Error, CompilerMessageCode.InvalidExamplesKeyword, exampleTokenText);
            }

            if (outline == null)
            {
                MessageSet.Add(examplesKeyword, CompilerMessageLevel.Error, CompilerMessageCode.NotExpectingExample, currentScenario!.Name!);
            }

            var example = new ExampleElement();

            PositionIndex?.PushScope(example, context);

            currentAnnotatable = example;

            example.AddLineInfo(examplesKeyword);

            PositionIndex?.AddLineToken(examplesKeyword, LineTokenCategory.EntryMarker, LineTokenSubCategory.Examples);

            Visit(context.annotations());

            currentAnnotatable = null;

            var table = tableVisitor.BuildTable(context.tableBlock());

            example.Table = table;

            MergeVisitorAndReset(tableVisitor);

            if (outline is object)
            {
                outline.AddExample(example);
            }

            PositionIndex?.PopScope(context);

            return Result!;
        }

19 View Source File : FileVisitor.cs
License : MIT License
Project Creator : autostep

private void AddStep(ITerminalNode keywordNode, StatementContext context)
        {
            Debug.replacedert(Result is object);

            if (currentStepSet is null && currentStepDefinition is null)
            {
                MessageSet.Add(context, CompilerMessageLevel.Error, CompilerMessageCode.StepNotExpected);
                return;
            }

            var type = keywordNode.Symbol.Type switch
            {
                GIVEN => StepType.Given,
                WHEN => StepType.When,
                THEN => StepType.Then,
                AND => StepType.And,
                _ => throw new LanguageEnginereplacedertException()
            };

19 View Source File : StepDefinitionVisitor.cs
License : MIT License
Project Creator : autostep

public override StepDefinitionElement VisitDeclarationArgument([NotNull] AutoStepParser.DeclarationArgumentContext context)
        {
            Debug.replacedert(Result is object);

            var content = context.stepDeclarationArgument();

            var name = content.stepDeclarationArgumentName().GetText();
            var hint = DetermineTypeHint(name, content.stepDeclarationTypeHint()?.GetText());

            var part = new ArgumentPart(context.GetText(), name, hint).AddPositionalLineInfo(context);

            AddPart(part);

            return Result;
        }

19 View Source File : StepReferenceVisitor.cs
License : MIT License
Project Creator : autostep

public override StepReferenceElement VisitStatementBody([NotNull] AutoStepParser.StatementBodyContext context)
        {
            Debug.replacedert(Result is object);

            textColumnOffset = context.Start.Column;

            VisitChildren(context);

            Result!.RawText = context.GetText();

            return Result;
        }

19 View Source File : TableVisitor.cs
License : MIT License
Project Creator : autostep

public override TableElement VisitTableRow([NotNull] AutoStepParser.TableRowContext context)
        {
            Debug.replacedert(Result is object);

            currentRow = new TableRowElement().AddLineInfo(context);

            PositionIndex?.PushScope(currentRow, context);

            base.VisitTableRow(context);

            // Check if the number of cells in the row doesn't match the headings.
            if (currentRow.Cells.Count != Result!.ColumnCount)
            {
                MessageSet.Add(context, CompilerMessageLevel.Error, CompilerMessageCode.TableColumnsMismatch, currentRow.Cells.Count, Result!.ColumnCount);
            }

            Result!.AddRow(currentRow);

            PositionIndex?.PopScope(context);

            return Result!;
        }

19 View Source File : TableVisitor.cs
License : MIT License
Project Creator : autostep

public override TableElement VisitTableRowCell([NotNull] AutoStepParser.TableRowCellContext context)
        {
            Debug.replacedert(Result is object);
            Debug.replacedert(currentRow is object);

            var cellContent = context.tableRowCellContent();

            var cell = new TableCellElement();

            if (cellContent == null)
            {
                var cellWs = context.WS(0);

                if (cellWs == null)
                {
                    // If there's no whitespace, we'll just have to use the start of the table delimiter.
                    cell.AddPositionalLineInfo(context);
                }
                else
                {
                    cell.AddPositionalLineInfo(cellWs);
                }

                currentRow!.AddCell(cell);
            }
            else
            {
                cell.Text = cellContent.GetText();

                currentCell = cell;

                cell.AddPositionalLineInfo(cellContent);

                try
                {
                    Visit(cellContent);
                }
                finally
                {
                    currentCell = null;
                }

                currentRow!.AddCell(cell);
            }

            return Result!;
        }

19 View Source File : TableVisitor.cs
License : MIT License
Project Creator : autostep

public override TableElement VisitCellVariable([NotNull] AutoStepParser.CellVariableContext context)
        {
            Debug.replacedert(Result is object);
            Debug.replacedert(currentCell is object);

            var variablePart = CreatePart(context, (s, l) => new VariableToken(context.cellVariableName().GetText(), s, l));

            if (insertionNameValidator is object)
            {
                var additionalError = insertionNameValidator(context, variablePart.VariableName);

                if (additionalError is object)
                {
                    MessageSet.Add(additionalError);
                }
            }

            AddPart(variablePart);

            return Result;
        }

19 View Source File : TableVisitor.cs
License : MIT License
Project Creator : autostep

public override TableElement VisitCellInterpolate([NotNull] AutoStepParser.CellInterpolateContext context)
        {
            Debug.replacedert(Result is object);

            // Interpolate part itself is just the colon.
            AddPart(CreatePart(context.CELL_COLON(), (s, l) => new InterpolateStartToken(s)));

            // Now add a part for the first word.
            AddPart(CreatePart(context.CELL_WORD(), (s, l) => new TextToken(s, l)));

            return Result;
        }

19 View Source File : TableVisitor.cs
License : MIT License
Project Creator : autostep

private void AddPart(StepToken part)
        {
            Debug.replacedert(currentCell is object);

            currentCell!.AddToken(part);

            PositionIndex?.AddLineToken(part, LineTokenCategory.Text, LineTokenSubCategory.Cell);
        }

19 View Source File : TableVisitor.cs
License : MIT License
Project Creator : autostep

private void AddPart(VariableToken part)
        {
            Debug.replacedert(currentCell is object);

            currentCell!.AddToken(part);

            PositionIndex?.AddLineToken(part, LineTokenCategory.Variable, LineTokenSubCategory.Cell);
        }

19 View Source File : TableVisitor.cs
License : MIT License
Project Creator : autostep

private TStepPart CreatePart<TStepPart>(ITerminalNode ctxt, Func<int, int, TStepPart> creator)
            where TStepPart : StepToken
        {
            Debug.replacedert(currentCell is object);

            var offset = currentCell!.StartColumn;
            var start = ctxt.Symbol.Column + 1 - offset;
            var startIndex = ctxt.Symbol.StartIndex;

            var part = creator(start, ctxt.Symbol.StopIndex - startIndex + 1);

            part.AddPositionalLineInfo(ctxt);

            return part;
        }

19 View Source File : InteractionDefinitionVisitor.cs
License : MIT License
Project Creator : autostep

protected void ProvideName(string name, ParserRuleContext nameItemContext)
        {
            Debug.replacedert(Result != null);

            if (ExplicitNameProvided)
            {
                // An explicit name has already been set. Can't do it twice.
                MessageSet.Add(nameItemContext, CompilerMessageLevel.Error, CompilerMessageCode.InteractionNameAlreadySet, Result!.Name);
            }
            else
            {
                Result!.Name = name;
                ExplicitNameProvided = true;
            }
        }

19 View Source File : InteractionStepDefinitionVisitor.cs
License : MIT License
Project Creator : autostep

public override InteractionStepDefinitionElement VisitDeclarationArgument([NotNull] DeclarationArgumentContext context)
        {
            Debug.replacedert(Result is object);

            var content = context.stepDeclarationArgument();

            var name = content.stepDeclarationArgumentName().GetText();
            var hint = DetermineTypeHint(name, content.stepDeclarationTypeHint()?.GetText());

            var part = new ArgumentPart(context.GetText(), name, hint).AddPositionalLineInfo(context);

            AddPart(part);

            return Result;
        }

19 View Source File : TableVisitor.cs
License : MIT License
Project Creator : autostep

private TStepPart CreatePart<TStepPart>(ParserRuleContext ctxt, Func<int, int, TStepPart> creator)
            where TStepPart : StepToken
        {
            Debug.replacedert(currentCell is object);

            var offset = currentCell!.StartColumn;
            var start = ctxt.Start.Column + 1 - offset;
            var startIndex = ctxt.Start.StartIndex;

            var part = creator(start, ctxt.Stop.StopIndex - startIndex + 1);

            part.AddPositionalLineInfo(ctxt);

            return part;
        }

19 View Source File : MatchingTreeNode.cs
License : MIT License
Project Creator : autostep

private bool SearchMatches(LinkedList<MatchResult> results, string referenceText, ReadOnlySpan<StepToken> remainingTokenSpan, bool exactOnly, PlaceHolderCopyOnWriteDictionary placeHolderDictionary, out ReadOnlySpan<StepToken> finalSpan)
        {
            Debug.replacedert(matchingPart is object);

            StepReferenceMatchResult match;

            if (remainingTokenSpan.Length > 0)
            {
                // Check for match quality between the part replacedigned to this node and the part we are looking for.
                match = matchingPart!.DoStepReferenceMatch(referenceText, remainingTokenSpan);

                finalSpan = match.RemainingTokens;

                if (match.Length == 0)
                {
                    // No match, nothing at this node or below.
                    return false;
                }
            }
            else
            {
                finalSpan = remainingTokenSpan;

                if (exactOnly)
                {
                    return false;
                }
                else
                {
                    match = new StepReferenceMatchResult(0, false, remainingTokenSpan, ReadOnlySpan<StepToken>.Empty);
                }
            }

            var addAllRemaining = true;
            var ignoreExact = false;
            var addedSomething = false;

            if (matchingPart is PlaceholderMatchPart placeholderPart)
            {
                var placeholderValue = GetContent(referenceText, match.MatchedTokens);

                // A placeholder value needs to be the same for all parts in order to match.
                // We need to take the matched placeholder and remember it for this search path.
                if (placeHolderDictionary.TryGetValue(placeholderPart.PlaceholderValueName, out var existingValue))
                {
                    // If the existing value does not have the same value, then we do not match, and we will jump out
                    // (return false).
                    if (!string.Equals(placeholderValue, existingValue, StringComparison.CurrentCulture))
                    {
                        // Different placeholder value; not okay.
                        // Do not match on this placeholder.
                        return false;
                    }
                }
                else
                {
                    placeHolderDictionary.Set(placeholderPart.PlaceholderValueName, placeholderValue);
                }
            }

            // The current match has consumed the entirety of the rest of the reference.
            if (match.RemainingTokens.IsEmpty)
            {
                // If this is an exact match, do we have an exact step def for it?
                if (match.IsExact && exactMatchNodes is object && exactMatchNodes.Count > 0)
                {
                    ignoreExact = true;

                    foreach (var exact in exactMatchNodes)
                    {
                        results.AddFirst(new MatchResult(true, int.MaxValue, exact.Value));
                    }

                    addedSomething = true;
                }
            }
            else if (children is object)
            {
                // There's no point looking at the children unless this node was an exact match. If it's not an exact match
                // then there's no point going further in the tree.
                if (match.IsExact)
                {
                    var currentChild = children.First;

                    while (currentChild is object)
                    {
                        var childMatched = currentChild.Value.SearchMatches(results, referenceText, match.RemainingTokens, exactOnly, placeHolderDictionary.Copy(), out var searchDepthSpan);

                        if (childMatched)
                        {
                            // A more specific match was found, so don't use any results from higher in the tree.
                            addAllRemaining = false;
                            addedSomething = true;
                            finalSpan = searchDepthSpan;
                        }

                        currentChild = currentChild.Next;
                    }
                }
            }

            if (addAllRemaining)
            {
                if (!exactOnly)
                {
                    // Add whatever items we have between left and right definitions.
                    var currentNode = leftDefinition;

                    // Add every node up until the right-hand side.
                    while (currentNode != null)
                    {
                        if (!ignoreExact || (exactMatchNodes is object && !exactMatchNodes.Contains(currentNode)))
                        {
                            addedSomething = true;
                            results.AddLast(new MatchResult(false, match.Length, currentNode.Value));
                        }

                        if (currentNode == rightDefinition)
                        {
                            currentNode = null;
                        }
                        else
                        {
                            currentNode = currentNode.Next;
                        }
                    }
                }
            }

            if (addedSomething && (results.First.Value.IsExact || !exactOnly))
            {
                if (matchingPart is ArgumentPart arg)
                {
                    var currentResult = results.First;

                    if (match.IsExact)
                    {
                        // If we're in 'exact only' mode, only worry about exact matches (and all the exacts come at the start of the list).
                        while (currentResult is object && (currentResult.Value.IsExact || !exactOnly))
                        {
                            // When at least one exact match has been added, it means that this node's
                            // argument binding resulted in a final match.
                            var exactMatch = currentResult.Value;

                            // Add to the list of 'argument token spans'.
                            exactMatch.PrependArgumentSet(arg, match);

                            currentResult = currentResult.Next;

                            exactMatch.MatchedParts++;
                        }
                    }
                }
                else if (matchingPart is PlaceholderMatchPart placeholder &&
                         placeHolderDictionary.TryGetValue(placeholder.PlaceholderValueName, out var placeholderValue))
                {
                    var currentResult = results.First;

                    if (match.IsExact)
                    {
                        // Only worry about exact matches (and all the exacts come at the start of the list).
                        while (currentResult is object && (currentResult.Value.IsExact || !exactOnly))
                        {
                            // When at least one exact match has been added, it means that this node's
                            // placeholder binding resulted in a final match.
                            var exactMatch = currentResult.Value;

                            // Set the placeholder result in the final item.
                            exactMatch.IncludePlaceholderValue(placeholder.PlaceholderValueName, placeholderValue);

                            currentResult = currentResult.Next;

                            exactMatch.MatchedParts++;
                        }
                    }
                }
                else if (match.IsExact)
                {
                    var currentResult = results.First;

                    // Only worry about exact matches (and all the exacts come at the start of the list).
                    while (currentResult is object && (currentResult.Value.IsExact || !exactOnly))
                    {
                        var exactMatch = currentResult.Value;

                        exactMatch.MatchedParts++;

                        currentResult = currentResult.Next;
                    }
                }
            }

            return addedSomething;
        }

19 View Source File : DocumentChangeOperation.cs
License : MIT License
Project Creator : AvaloniaUI

public void Undo(UndoStack stack)
		{
			Debug.replacedert(stack.State == UndoStack.StatePlayback);
			stack.RegisterAffectedDoreplacedent(_doreplacedent);
			stack.State = UndoStack.StatePlaybackModifyDoreplacedent;
			Undo();
			stack.State = UndoStack.StatePlayback;
		}

19 View Source File : DocumentChangeOperation.cs
License : MIT License
Project Creator : AvaloniaUI

public void Redo(UndoStack stack)
		{
			Debug.replacedert(stack.State == UndoStack.StatePlayback);
			stack.RegisterAffectedDoreplacedent(_doreplacedent);
			stack.State = UndoStack.StatePlaybackModifyDoreplacedent;
			Redo();
			stack.State = UndoStack.StatePlayback;
		}

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : AvaloniaUI

public void RebuildTree(List<DoreplacedentLine> doreplacedentLines)
        {
            var nodes = new DoreplacedentLine[doreplacedentLines.Count];
            for (var i = 0; i < doreplacedentLines.Count; i++)
            {
                var ls = doreplacedentLines[i];
                var node = ls.InitLineNode();
                nodes[i] = node;
            }
            Debug.replacedert(nodes.Length > 0);
            // now build the corresponding balanced tree
            var height = GetTreeHeight(nodes.Length);
            Debug.WriteLine("DoreplacedentLineTree will have height: " + height);
            _root = BuildTree(nodes, 0, nodes.Length, height);
            _root.Color = Black;
#if DEBUG
            CheckProperties();
#endif
        }

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : AvaloniaUI

private DoreplacedentLine BuildTree(DoreplacedentLine[] nodes, int start, int end, int subtreeHeight)
        {
            Debug.replacedert(start <= end);
            if (start == end)
            {
                return null;
            }
            var middle = (start + end) / 2;
            var node = nodes[middle];
            node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
            node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
            if (node.Left != null) node.Left.Parent = node;
            if (node.Right != null) node.Right.Parent = node;
            if (subtreeHeight == 1)
                node.Color = Red;
            UpdateAfterChildrenChange(node);
            return node;
        }

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : AvaloniaUI

private DoreplacedentLine GetNodeByIndex(int index)
        {
            Debug.replacedert(index >= 0);
            Debug.replacedert(index < _root.NodeTotalCount);
            var node = _root;
            while (true)
            {
                if (node.Left != null && index < node.Left.NodeTotalCount)
                {
                    node = node.Left;
                }
                else
                {
                    if (node.Left != null)
                    {
                        index -= node.Left.NodeTotalCount;
                    }
                    if (index == 0)
                        return node;
                    index--;
                    node = node.Right;
                }
            }
        }

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : AvaloniaUI

private DoreplacedentLine GetNodeByOffset(int offset)
        {
            Debug.replacedert(offset >= 0);
            Debug.replacedert(offset <= _root.NodeTotalLength);
            if (offset == _root.NodeTotalLength)
            {
                return _root.RightMost;
            }
            var node = _root;
            while (true)
            {
                if (node.Left != null && offset < node.Left.NodeTotalLength)
                {
                    node = node.Left;
                }
                else
                {
                    if (node.Left != null)
                    {
                        offset -= node.Left.NodeTotalLength;
                    }
                    offset -= node.TotalLength;
                    if (offset < 0)
                        return node;
                    node = node.Right;
                }
            }
        }

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : AvaloniaUI

private void InsertAsLeft(DoreplacedentLine parentNode, DoreplacedentLine newNode)
        {
            Debug.replacedert(parentNode.Left == null);
            parentNode.Left = newNode;
            newNode.Parent = parentNode;
            newNode.Color = Red;
            UpdateAfterChildrenChange(parentNode);
            FixTreeOnInsert(newNode);
        }

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : AvaloniaUI

private void InsertAsRight(DoreplacedentLine parentNode, DoreplacedentLine newNode)
        {
            Debug.replacedert(parentNode.Right == null);
            parentNode.Right = newNode;
            newNode.Parent = parentNode;
            newNode.Color = Red;
            UpdateAfterChildrenChange(parentNode);
            FixTreeOnInsert(newNode);
        }

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : AvaloniaUI

private void RotateRight(DoreplacedentLine p)
        {
            // let q be p's left child
            var q = p.Left;
            Debug.replacedert(q != null);
            Debug.replacedert(q.Parent == p);
            // set q to be the new root
            ReplaceNode(p, q);

            // set p's left child to be q's right child
            p.Left = q.Right;
            if (p.Left != null) p.Left.Parent = p;
            // set q's right child to be p
            q.Right = p;
            p.Parent = q;
            UpdateAfterRotateRight(p);
        }

19 View Source File : TextSegmentCollection.cs
License : MIT License
Project Creator : AvaloniaUI

public T FindFirstSegmentWithStartAfter(int startOffset)
        {
            if (_root == null)
                return null;
            if (startOffset <= 0)
                return (T)_root.LeftMost;
            var s = FindNode(ref startOffset);
            // startOffset means that the previous segment is starting at the offset we were looking for
            while (startOffset == 0)
            {
                var p = (s == null) ? _root.RightMost : s.Predecessor;
                // There must always be a predecessor: if we were looking for the first node, we would have already
                // returned it as root.LeftMost above.
                Debug.replacedert(p != null);
                startOffset += p.NodeLength;
                s = p;
            }
            return (T)s;
        }

19 View Source File : CaretNavigationCommandHandler.cs
License : MIT License
Project Creator : AvaloniaUI

private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
        {
            var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
            if (pos >= 0)
            {
                return visualLine.GetTextViewPosition(pos);
            }
            else
            {
                // move to start of next line
                var nextDoreplacedentLine = visualLine.LastDoreplacedentLine.NextLine;
                if (nextDoreplacedentLine != null)
                {
                    var nextLine = textView.GetOrConstructVisualLine(nextDoreplacedentLine);
                    pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
                    if (pos < 0)
                        throw ThrowUtil.NoValidCaretPosition();
                    return nextLine.GetTextViewPosition(pos);
                }
                else
                {
                    // at end of doreplacedent
                    Debug.replacedert(visualLine.LastDoreplacedentLine.Offset + visualLine.LastDoreplacedentLine.TotalLength == textView.Doreplacedent.TextLength);
                    return new TextViewPosition(textView.Doreplacedent.GetLocation(textView.Doreplacedent.TextLength));
                }
            }
        }

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : AvaloniaUI

private void FixTreeOnDelete(DoreplacedentLine node, DoreplacedentLine parentNode)
        {
            Debug.replacedert(node == null || node.Parent == parentNode);
            if (parentNode == null)
                return;

            // warning: node may be null
            var sibling = Sibling(node, parentNode);
            if (sibling.Color == Red)
            {
                parentNode.Color = Red;
                sibling.Color = Black;
                if (node == parentNode.Left)
                {
                    RotateLeft(parentNode);
                }
                else
                {
                    RotateRight(parentNode);
                }

                sibling = Sibling(node, parentNode); // update value of sibling after rotation
            }

            if (parentNode.Color == Black
                && sibling.Color == Black
                && GetColor(sibling.Left) == Black
                && GetColor(sibling.Right) == Black)
            {
                sibling.Color = Red;
                FixTreeOnDelete(parentNode, parentNode.Parent);
                return;
            }

            if (parentNode.Color == Red
                && sibling.Color == Black
                && GetColor(sibling.Left) == Black
                && GetColor(sibling.Right) == Black)
            {
                sibling.Color = Red;
                parentNode.Color = Black;
                return;
            }

            if (node == parentNode.Left &&
                sibling.Color == Black &&
                GetColor(sibling.Left) == Red &&
                GetColor(sibling.Right) == Black)
            {
                sibling.Color = Red;
                sibling.Left.Color = Black;
                RotateRight(sibling);
            }
            else if (node == parentNode.Right &&
                     sibling.Color == Black &&
                     GetColor(sibling.Right) == Red &&
                     GetColor(sibling.Left) == Black)
            {
                sibling.Color = Red;
                sibling.Right.Color = Black;
                RotateLeft(sibling);
            }
            sibling = Sibling(node, parentNode); // update value of sibling after rotation

            sibling.Color = parentNode.Color;
            parentNode.Color = Black;
            if (node == parentNode.Left)
            {
                if (sibling.Right != null)
                {
                    Debug.replacedert(sibling.Right.Color == Red);
                    sibling.Right.Color = Black;
                }
                RotateLeft(parentNode);
            }
            else
            {
                if (sibling.Left != null)
                {
                    Debug.replacedert(sibling.Left.Color == Red);
                    sibling.Left.Color = Black;
                }
                RotateRight(parentNode);
            }
        }

19 View Source File : LineManager.cs
License : MIT License
Project Creator : AvaloniaUI

public void Insert(int offset, ITextSource text)
        {
            var line = _doreplacedentLineTree.GetByOffset(offset);
            var lineOffset = line.Offset;

            Debug.replacedert(offset <= lineOffset + line.TotalLength);
            if (offset > lineOffset + line.Length)
            {
                Debug.replacedert(line.DelimiterLength == 2);
                // we are inserting in the middle of a delimiter

                // shorten line
                SetLineLength(line, line.TotalLength - 1);
                // add new line
                line = InsertLineAfter(line, 1);
                line = SetLineLength(line, 1);
            }

            var ds = NewLineFinder.NextNewLine(text, 0);
            if (ds == SimpleSegment.Invalid)
            {
                // no newline is being inserted, all text is inserted in a single line
                //line.InsertedLinePart(offset - line.Offset, text.Length);
                SetLineLength(line, line.TotalLength + text.TextLength);
                return;
            }
            //DoreplacedentLine firstLine = line;
            //firstLine.InsertedLinePart(offset - firstLine.Offset, ds.Offset);
            var lastDelimiterEnd = 0;
            while (ds != SimpleSegment.Invalid)
            {
                // split line segment at line delimiter
                var lineBreakOffset = offset + ds.Offset + ds.Length;
                lineOffset = line.Offset;
                var lengthAfterInsertionPos = lineOffset + line.TotalLength - (offset + lastDelimiterEnd);
                line = SetLineLength(line, lineBreakOffset - lineOffset);
                var newLine = InsertLineAfter(line, lengthAfterInsertionPos);
                newLine = SetLineLength(newLine, lengthAfterInsertionPos);

                line = newLine;
                lastDelimiterEnd = ds.Offset + ds.Length;

                ds = NewLineFinder.NextNewLine(text, lastDelimiterEnd);
            }
            //firstLine.SplitTo(line);
            // insert rest after last delimiter
            if (lastDelimiterEnd != text.TextLength)
            {
                //line.InsertedLinePart(0, text.Length - lastDelimiterEnd);
                SetLineLength(line, line.TotalLength + text.TextLength - lastDelimiterEnd);
            }
        }

19 View Source File : TextAnchorTree.cs
License : MIT License
Project Creator : AvaloniaUI

private void InsertText(int offset, int length, bool defaultAnchorMovementIsBeforeInsertion)
        {
            if (length == 0 || _root == null || offset > _root.TotalLength)
                return;

            // find the range of nodes that are placed exactly at offset
            // beginNode is inclusive, endNode is exclusive
            if (offset == _root.TotalLength)
            {
                PerformInsertText(FindActualBeginNode(_root.RightMost), null, length, defaultAnchorMovementIsBeforeInsertion);
            }
            else
            {
                TextAnchorNode endNode = FindNode(ref offset);
                Debug.replacedert(endNode.Length > 0);

                if (offset > 0)
                {
                    // there are no nodes exactly at offset
                    endNode.Length += length;
                    UpdateAugmentedData(endNode);
                }
                else
                {
                    PerformInsertText(FindActualBeginNode(endNode.Predecessor), endNode, length, defaultAnchorMovementIsBeforeInsertion);
                }
            }
            DeleteMarkedNodes();
        }

19 View Source File : TextAnchorTree.cs
License : MIT License
Project Creator : AvaloniaUI

public TextAnchor CreateAnchor(int offset)
        {
            Log("CreateAnchor(" + offset + ")");
            TextAnchor anchor = new TextAnchor(_doreplacedent);
            anchor.Node = new TextAnchorNode(anchor);
            if (_root == null)
            {
                // creating the first text anchor
                _root = anchor.Node;
                _root.TotalLength = _root.Length = offset;
            }
            else if (offset >= _root.TotalLength)
            {
                // append anchor at end of tree
                anchor.Node.TotalLength = anchor.Node.Length = offset - _root.TotalLength;
                InsertAsRight(_root.RightMost, anchor.Node);
            }
            else
            {
                // insert anchor in middle of tree
                TextAnchorNode n = FindNode(ref offset);
                Debug.replacedert(offset < n.Length);
                // split segment 'n' at offset
                anchor.Node.TotalLength = anchor.Node.Length = offset;
                n.Length -= offset;
                InsertBefore(n, anchor.Node);
            }
            DeleteMarkedNodes();
            return anchor;
        }

19 View Source File : TextAnchorTree.cs
License : MIT License
Project Creator : AvaloniaUI

private void InsertAsLeft(TextAnchorNode parentNode, TextAnchorNode newNode)
        {
            Debug.replacedert(parentNode.Left == null);
            parentNode.Left = newNode;
            newNode.Parent = parentNode;
            newNode.Color = Red;
            UpdateAugmentedData(parentNode);
            FixTreeOnInsert(newNode);
        }

See More Examples