aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.RegExpr/parser/ParseTree.cs
blob: ba5b35f693dbcfc39894ddf72f03de6ca4fa4e77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/***************************************************************************************************
 Copyright (C) 2024 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
***************************************************************************************************/

using System.Collections.Generic;
using System.Linq;

namespace QtVsTools.SyntaxAnalysis
{
    public abstract partial class RegExpr
    {
        ////////////////////////////////////////////////////////////////////////////////////////////
        ///
        /// RegExpr.ParseTree
        ///
        ////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Result of processing input text with a pattern rendered from a RegExpr.
        /// </summary>
        /// <remarks>
        /// Nodes in a ParseTree correspond to captured tokens. The parent-child relationship
        /// between nodes reflects token embedding.
        /// </remarks>
        public class ParseTree
        {
            public Node Root { get; set; }
            public const string KeyRoot = "0";

            public class Node : IOperatorCapture, IOperandCapture
            {
                public string CaptureId { get; set; }
                public string Value { get; set; }
                public int Begin { get; set; }
                public int End { get; set; }
                public int GroupIdx { get; set; }
                public int CaptureIdx { get; set; }

                class NodeComparer : IComparer<Node>
                {
                    public int Compare(Node x, Node y)
                    {
                        return Comparer<int>.Default.Compare(x.Begin, y.Begin);
                    }
                }

                static readonly NodeComparer _Comparer = new();
                public static IComparer<Node> Comparer => _Comparer;

                public Token Token { get; set; }
                public string TokenId => Token.Id;

                public object Production { get; set; }

                public Node Parent { get; set; }

                public SortedList<int, Node> ChildNodes { get; } = new();

                public ProductionObjects ChildProductions { get; } = new();

                public Queue<Node> TokenStream { get; set; }
                public Stack<Node> OperatorStack { get; set; }
                public Stack<Node> OperandStack { get; set; }

                IProductionRule _Rule;
                public IProductionRule Rule
                {
                    get { return _Rule ??= Token.SelectRule(this); }
                }

                public string Key
                {
                    get => CaptureId == KeyRoot ? KeyRoot : $"{CaptureId}:{Begin}:{End}";
                }

                public override string ToString()
                {
                    return $"{TokenId}[{Value}]";
                }

                public static implicit operator ParseTree(Node node)
                {
                    return new ParseTree { Root = node };
                }

                int SiblingIdx
                {
                    get => Parent?.ChildNodes.IndexOfKey(Begin) ?? 0;
                }

                int SiblingCount
                {
                    get => Parent?.ChildNodes.Count ?? 1;
                }

                public bool IsFirst => SiblingIdx == 0;

                public bool IsLast => SiblingIdx == SiblingCount - 1;

                public IEnumerable<ITokenCapture> LookAhead(params TokenGroup[] ids)
                {
                    if (Parent == null)
                        return Empty<ITokenCapture>();
                    var lookAhead = Parent.ChildNodes.Values
                        .Skip(SiblingIdx + 1);
                    if (ids.Any())
                        lookAhead = lookAhead.Where(x => ids.Any(g => g.Contains(x.TokenId)));
                    return lookAhead.Cast<ITokenCapture>().Concat(Items(EndOfList));
                }

                public IEnumerable<ITokenCapture> LookBehind(params TokenGroup[] ids)
                {
                    if (Parent == null)
                        return Empty<ITokenCapture>();
                    var lookBehind = Parent.ChildNodes.Values
                        .Take(SiblingIdx)
                        .Reverse();
                    if (ids.Any())
                        lookBehind = lookBehind.Where(x => ids.Any(g => g.Contains(x.TokenId)));
                    return lookBehind.Cast<ITokenCapture>().Concat(Items(EndOfList));
                }

                public bool Is(params TokenGroup[] tokenIds)
                {
                    return tokenIds.Any(g => g.Contains(TokenId));
                }

                public bool IsNot(params TokenGroup[] tokenIds)
                {
                    return !tokenIds.Any(g => g.Contains(TokenId));
                }

                public IOperandCapture Operand
                {
                    get
                    {
                        if (Parent is not { OperandStack: {} })
                            return EndOfList;
                        if (!Parent.OperandStack.Any())
                            return EndOfList;
                        return Parent.OperandStack.Peek();
                    }
                }

                public IOperandCapture LeftOperand
                {
                    get
                    {
                        if (Parent is not { OperandStack: {} })
                            return EndOfList;
                        if (Parent.OperandStack.Count() < 2)
                            return EndOfList;
                        return Parent.OperandStack.Skip(1).First();
                    }
                }

                public IOperandCapture RightOperand
                {
                    get
                    {
                        if (Parent is not { OperandStack: {} })
                            return EndOfList;
                        if (Parent.OperandStack.Count() < 2)
                            return EndOfList;
                        return Parent.OperandStack.Peek();
                    }
                }

                public bool HasOperand => Operand != EndOfList;

                public bool HasLeftOperand => LeftOperand != EndOfList;

                public bool HasRightOperand => RightOperand != EndOfList;
            }
        }
    }
}