aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py
blob: ef5d0f693ecf7ee28238157153bd28215ee75891 (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
#############################################################################
##
## Copyright (C) 2021 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of Qt for Python.
##
## $QT_BEGIN_LICENSE:COMM$
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and The Qt Company. For licensing terms
## and conditions see https://www.qt.io/terms-conditions. For further
## information use the contact form at https://www.qt.io/contact-us.
##
## $QT_END_LICENSE$
##
#############################################################################

from __future__ import print_function, absolute_import

"""
tool.py

Some useful stuff, see below.
On the function with_metaclass see the answer from Martijn Pieters on
https://stackoverflow.com/questions/18513821/python-metaclass-understanding-the-with-metaclass
"""

from textwrap import dedent


class SimpleNamespace(object):
    # From types.rst, because the builtin is implemented in Python 3, only.
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

try:
    from types import SimpleNamespace
except ImportError:
    pass


def build_brace_pattern(level, separators=""):
    """
    Build a brace pattern upto a given depth

    The brace pattern parses any pattern with round, square, curly, or angle
    brackets. Inside those brackets, any characters are allowed.

    The structure is quite simple and is recursively repeated as needed.
    When separators are given, the match stops at that separator.

    Reason to use this instead of some Python function:
    The resulting regex is _very_ fast!

    A faster replacement would be written in C, but this solution is
    sufficient when the nesting level is not too large.

    Because of the recursive nature of the pattern, the size grows by a factor
    of 4 at every level, as does the creation time. Up to a level of 6, this
    is below 10 ms.

    There are other regex engines available which allow recursive patterns,
    avoiding this problem completely. It might be considered to switch to
    such an engine if the external module is not a problem.
    """
    def escape(str):
        return "".join("\\" + c for c in str)

    ro, rc = round  = "()"
    so, sc = square = "[]"
    co, cc = curly  = "CD"      # we insert "{}", later...
    ao, ac = angle  = "<>"
    qu, bs = '"', "\\"
    all = round + square + curly + angle
    __ = "  "
    ro, rc, so, sc, co, cc, ao, ac, separators, qu, bs, all = map(
        escape, (ro, rc, so, sc, co, cc, ao, ac, separators, qu, bs, all))

    no_brace_sep_q = r"[^{all}{separators}{qu}{bs}]".format(**locals())
    no_quote = r"(?: [^{qu}{bs}] | {bs}. )*".format(**locals())
    pattern = dedent(r"""
        (
          (?: {__} {no_brace_sep_q}
            | {qu} {no_quote} {qu}
            | {ro} {replacer} {rc}
            | {so} {replacer} {sc}
            | {co} {replacer} {cc}
            | {ao} {replacer} {ac}
          )+
        )
        """)
    no_braces_q = "[^{all}{qu}{bs}]*".format(**locals())
    repeated = dedent(r"""
        {indent}  (?: {__} {no_braces_q}
        {indent}    | {qu} {no_quote} {qu}
        {indent}    | {ro} {replacer} {rc}
        {indent}    | {so} {replacer} {sc}
        {indent}    | {co} {replacer} {cc}
        {indent}    | {ao} {replacer} {ac}
        {indent}  )*
        """)
    for idx in range(level):
        pattern = pattern.format(replacer = repeated if idx < level-1 else no_braces_q,
                                 indent = idx * "    ", **locals())
    return pattern.replace("C", "{").replace("D", "}")


# Copied from the six module:
def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    # This requires a bit of explanation: the basic idea is to make a dummy
    # metaclass for one level of class instantiation that replaces itself with
    # the actual metaclass.
    class metaclass(type):

        def __new__(cls, name, this_bases, d):
            return meta(name, bases, d)

        @classmethod
        def __prepare__(cls, name, this_bases):
            return meta.__prepare__(name, bases)
    return type.__new__(metaclass, 'temporary_class', (), {})

# eof