aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.RegExpr/utils/Utils.cs
blob: 146334bcbb6d807f078a527e61af714fe42cde8f (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
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

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

namespace QtVsTools.SyntaxAnalysis
{
    public abstract partial class RegExpr
    {
        const string MetaChars = @"[]\/#^$.|?*+(){}-";

        protected static string Escape(string s)
        {
            return new string(s.SelectMany(c =>
                MetaChars.Contains(c) ? Items('\\', c) :
                c == ' ' ? "\\x20" :
                c == '\t' ? "\\t" :
                c == '\r' ? "\\r" :
                c == '\n' ? "\\n" :
                Items(c)).ToArray());
        }

        public static bool NeedsGroup(string literal)
        {
            return literal.Length switch
            {
                1 => false,
                2 when literal.StartsWith(@"\") => false,
                3 when literal.StartsWith(@"\c") => false,
                4 when literal.StartsWith(@"\x") => false,
                6 when literal.StartsWith(@"\u") => false,
                _ => true
            };
        }

        internal T As<T>()
            where T : RegExpr
        {
            if (this is T expr)
                return expr;
            throw new InvalidCastException();
        }

        internal static IEnumerable<T> Empty<T>()
        {
            return new T[] { };
        }

        internal static IEnumerable<T> Items<T>(params T[] items)
        {
            return items;
        }

        public sealed class Void { }
    }

    public static class RegExprExtensions
    {
        public static void ReverseTop<T>(this Stack<T> stack, int count = 2)
        {
            if (count < 2 || stack.Count < count)
                return;
            var items = Enumerable.Repeat(stack, count).Select(s => s.Pop()).ToList();
            items.ForEach(stack.Push);
        }
    }
}