toolkit.py 13.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# toolkit.py - utility functions for DHParser
#
# Copyright 2016  by Eckhart Arnold (arnold@badw.de)
#                 Bavarian Academy of Sciences an Humanities (badw.de)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.  See the License for the specific language governing
# permissions and limitations under the License.
17
18


19
20
"""
Module ``toolkit`` contains utility functions that are needed across
eckhart's avatar
eckhart committed
21
22
23
24
several of the the other DHParser-Modules Helper funcions that are not
needed in more than one module are best placed within that module and
not in the toolkit-module. An acceptable exception from this rule are
functions that are very generic.
25
26
"""

27
import hashlib
di68kap's avatar
di68kap committed
28
import io
29
import multiprocessing
30
import parser
31
import threading
32

di68kap's avatar
di68kap committed
33
34
35
36
try:
    import regex as re
except ImportError:
    import re
37
import sys
38
39
import typing
from typing import Any, Iterable, Sequence, Set, Union, Dict, Hashable
40

eckhart's avatar
eckhart committed
41
42
43
try:
    import cython
    cython_optimized = cython.compiled  # type: bool
eckhart's avatar
eckhart committed
44
45
    if cython_optimized:
        import DHParser.shadow_cython as cython
eckhart's avatar
eckhart committed
46
except ImportError:
47
    cython_optimized = False
eckhart's avatar
eckhart committed
48
49
    import DHParser.shadow_cython as cython

50
51
from DHParser.configuration import CONFIG_PRESET

52

eckhart's avatar
eckhart committed
53
54
55
56
__all__ = ('typing',
           'cython',
           'cython_optimized',
           'escape_re',
57
           'escape_control_characters',
Eckhart Arnold's avatar
Eckhart Arnold committed
58
           'is_filename',
59
           'concurrent_ident',
60
           'unrepr',
61
           'lstrip_docstring',
62
63
           'issubtype',
           'isgenerictype',
64
65
           'load_if_file',
           'is_python_code',
66
67
           'md5',
           'expand_table',
68
           'compile_python_object',
69
           'smart_list',
70
           'sane_parser_name',
71
72
73
           'GLOBALS',
           'get_config_value',
           'set_config_value')
74
75
76
77


#######################################################################
#
78
# Thread local globals and configuration
79
80
#
#######################################################################
81

82
GLOBALS = threading.local()
83

eckhart's avatar
eckhart committed
84
def get_config_value(key: Hashable) -> Any:
85
86
87
88
89
90
91
92
    """
    Retrieves a configuration value thread-safely.
    :param key:  the key (an immutable, usually a string)
    :return:     the value
    """
    try:
        cfg = GLOBALS.config
    except AttributeError:
eckhart's avatar
eckhart committed
93
        GLOBALS.config = dict()
94
95
96
97
98
99
100
101
102
        cfg = GLOBALS.config
    try:
        return cfg[key]
    except KeyError:
        value = CONFIG_PRESET[key]
        GLOBALS.config[key] = value
        return value


eckhart's avatar
eckhart committed
103
def set_config_value(key: Hashable, value: Any):
104
105
106
107
108
109
110
111
112
113
114
    """
    Changes a configuration value thread-safely. The configuration
    value will be set only for the current thread. In order to
    set configuration values for any new thread, add the key and value
    to CONFIG_PRESET, before the thread is started.
    :param key:    the key (an immutable, usually a string)
    :param value:  the value
    """
    try:
        _ = GLOBALS.config
    except AttributeError:
eckhart's avatar
eckhart committed
115
        GLOBALS.config = dict()
116
117
118
119
120
121
122
123
    GLOBALS.config[key] = value


#######################################################################
#
# miscellaneous (generic)
#
#######################################################################
124
125


126
def escape_re(strg: str) -> str:
127
128
    """
    Returns the string with all regular expression special characters escaped.
129
    """
130

131
    # assert isinstance(strg, str)
132
133
    re_chars = r"\.^$*+?{}[]()#<>=|!"
    for esc_ch in re_chars:
134
135
        strg = strg.replace(esc_ch, '\\' + esc_ch)
    return strg
136
137


138
def escape_control_characters(strg: str) -> str:
139
140
141
    """
    Replace all control characters (e.g. \n \t) in a string by their backslashed representation.
    """
142

143
144
145
146
147
148
149
    return repr(strg).replace('\\\\', '\\')[1:-1]


def lstrip_docstring(docstring: str) -> str:
    """
    Strips leading whitespace from a docstring.
    """
150

151
152
153
154
155
156
157
158
159
160
161
    lines = docstring.replace('\t', '    ').split('\n')
    indent = 255  # highest integer value
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:  # ignore empty lines
            indent = min(indent, len(line) - len(stripped))
    if indent >= 255:
        indent = 0
    return '\n'.join([lines[0]] + [line[indent:] for line in lines[1:]])


162
def is_filename(strg: str) -> bool:
163
164
165
166
    """
    Tries to guess whether string ``strg`` is a file name.
    """

167
    return strg.find('\n') < 0 and strg[:1] != " " and strg[-1:] != " " \
168
        and all(strg.find(ch) < 0 for ch in '*?"<>|')
169
    #   and strg.select('*') < 0 and strg.select('?') < 0
Eckhart Arnold's avatar
Eckhart Arnold committed
170
171


172
173
174
175
176
177
178
def concurrent_ident() -> str:
    """
    Returns an identificator for the current process and thread
    """
    return multiprocessing.current_process().name + '_' + str(threading.get_ident())


179
180
181
182
183
184
185
186
187
188
189
190
191
class unrepr:
    """
    unrepr encapsulates a string representing a python function in such
    a way that the representation of the string yields the function call
    itself rather then a string representing the function call and delimited
    by quotation marks.

    Example:
        >>> "re.compile(r'abc+')"
        "re.compile(r'abc+')"
        >>> unrepr("re.compile(r'abc+')")
        re.compile(r'abc+')
    """
192
193
194
    def __init__(self, s: str):
        self.s = s  # type: str

eckhart's avatar
eckhart committed
195
    def __eq__(self, other: object) -> bool:
196
197
198
199
200
201
202
        if isinstance(other, unrepr):
            return self.s == other.s
        elif isinstance(other, str):
            return self.s == other
        else:
            raise TypeError('unrepr objects can only be compared with '
                            'other unrepr objects or strings!')
203

eckhart's avatar
eckhart committed
204
    def __str__(self) -> str:
205
206
        return self.s

eckhart's avatar
eckhart committed
207
    def __repr__(self) -> str:
208
209
210
        return self.s


211
212
213
214
215
216
217
218
#######################################################################
#
# type system support
#
#######################################################################


def issubtype(sub_type, base_type):
219
220
221
222
    def origin(t):
        try:
            ot = t.__origin__
        except AttributeError:
223
224
            if t == 'unicode':  # work-around for cython bug
                return str
225
226
227
            return t
        return ot if ot is not None else t
    return issubclass(origin(sub_type), origin(base_type))
228
229
230
231
232
233


def isgenerictype(t):
    return str(t).endswith(']')


234
235
236
237
238
239
240
#######################################################################
#
# loading and compiling
#
#######################################################################


241
def load_if_file(text_or_file) -> str:
242
243
    """
    Reads and returns content of a text-file if parameter
244
    `text_or_file` is a file name (i.e. a single line string),
245
    otherwise (i.e. if `text_or_file` is a multi-line string)
246
    `text_or_file` is returned.
247
    """
248

Eckhart Arnold's avatar
Eckhart Arnold committed
249
    if is_filename(text_or_file):
250
251
252
253
        try:
            with open(text_or_file, encoding="utf-8") as f:
                content = f.read()
            return content
254
        except FileNotFoundError:
255
            if re.fullmatch(r'[\w/:. \\]+', text_or_file):
256
257
                raise FileNotFoundError('Not a valid file: ' + text_or_file + '!\n(Add "\\n" '
                                        'to distinguish source data from a file name.)')
258
259
            else:
                return text_or_file
260
261
262
263
    else:
        return text_or_file


264
def is_python_code(text_or_file: str) -> bool:
265
266
    """
    Checks whether 'text_or_file' is python code or the name of a file that
267
268
    contains python code.
    """
269

Eckhart Arnold's avatar
Eckhart Arnold committed
270
    if is_filename(text_or_file):
271
272
        return text_or_file[-3:].lower() == '.py'
    try:
273
274
        parser.suite(text_or_file)
        # compile(text_or_file, '<string>', 'exec')
275
276
277
278
279
280
        return True
    except (SyntaxError, ValueError, OverflowError):
        pass
    return False


281
def has_fenced_code(text_or_file: str, info_strings=('ebnf', 'test')) -> bool:
282
283
    """
    Checks whether `text_or_file` contains fenced code blocks, which are
284
285
286
287
    marked by one of the given info strings.
    See http://spec.commonmark.org/0.28/#fenced-code-blocks for more
    information on fenced code blocks in common mark documents.
    """
288

289
290
291
292
293
294
295
296
297
    if is_filename(text_or_file):
        with open(text_or_file, 'r', encoding='utf-8') as f:
            markdown = f.read()
    else:
        markdown = text_or_file

    if markdown.find('\n~~~') < 0 and markdown.find('\n```') < 0:
        return False

298
299
    if isinstance(info_strings, str):
        info_strings = (info_strings,)
eckhart's avatar
eckhart committed
300
301
    fence_tmpl = r'\n(?:(?:``[`]*[ ]*(?:%s)(?=[ .\-:\n])[^`\n]*\n)' + \
                 r'|(?:~~[~]*[ ]*(?:%s)(?=[ .\-:\n])[\n]*\n))'
302
303
    label_re = '|'.join('(?:%s)' % matched_string for matched_string in info_strings)
    rx_fence = re.compile(fence_tmpl % (label_re, label_re), flags=re.IGNORECASE)
304

305
    for match in rx_fence.finditer(markdown):
eckhart's avatar
eckhart committed
306
        matched_string = re.match(r'(?:\n`+)|(?:\n~+)', match.group(0)).group(0)
307
        if markdown.find(matched_string, match.end()) >= 0:
308
309
            return True
        else:
310
311
            break
    return False
312
313


314
def md5(*txt):
315
316
    """
    Returns the md5-checksum for `txt`. This can be used to test if
317
318
    some piece of text, for example a grammar source file, has changed.
    """
319

320
321
322
323
324
325
    md5_hash = hashlib.md5()
    for t in txt:
        md5_hash.update(t.encode('utf8'))
    return md5_hash.hexdigest()


326
def compile_python_object(python_src, catch_obj_regex=""):
327
328
    """
    Compiles the python source code and returns the (first) object
329
330
331
    the name of which is matched by ``catch_obj_regex``. If catch_obj
    is the empty string, the namespace dictionary will be returned.
    """
332

333
334
335
336
337
338
    if isinstance(catch_obj_regex, str):
        catch_obj_regex = re.compile(catch_obj_regex)
    code = compile(python_src, '<string>', 'exec')
    namespace = {}
    exec(code, namespace)  # safety risk?
    if catch_obj_regex:
339
340
        matches = [key for key in namespace if catch_obj_regex.match(key)]
        if len(matches) < 1:
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
            raise ValueError("No object matching /%s/ defined in source code." %
                             catch_obj_regex.pattern)
        elif len(matches) > 1:
            raise ValueError("Ambiguous matches for %s : %s" %
                             (str(catch_obj_regex), str(matches)))
        return namespace[matches[0]] if matches else None
    else:
        return namespace


#######################################################################
#
# smart lists and multi-keyword tables
#
#######################################################################


Eckhart Arnold's avatar
Eckhart Arnold committed
358
# def smart_list(arg: Union[str, Iterable[T]]) -> Union[Sequence[str], Sequence[T]]:
359
def smart_list(arg: Union[str, Iterable, Any]) -> Union[Sequence, Set]:
360
361
    """
    Returns the argument as list, depending on its type and content.
362

363
364
365
    If the argument is a string, it will be interpreted as a list of
    comma separated values, trying ';', ',', ' ' as possible delimiters
    in this order, e.g.
366
367
368
369
370
371
372
    >>> smart_list('1; 2, 3; 4')
    ['1', '2, 3', '4']
    >>> smart_list('2, 3')
    ['2', '3']
    >>> smart_list('a b cd')
    ['a', 'b', 'cd']

373
374
    If the argument is a collection other than a string, it will be
    returned as is, e.g.
375
376
377
378
379
    >>> smart_list((1, 2, 3))
    (1, 2, 3)
    >>> smart_list({1, 2, 3})
    {1, 2, 3}

380
381
    If the argument is another iterable than a collection, it will
    be converted into a list, e.g.
382
383
384
    >>> smart_list(i for i in {1,2,3})
    [1, 2, 3]

385
    Finally, if none of the above is true, the argument will be
386
    wrapped in a list and returned, e.g.
387
388
    >>> smart_list(125)
    [125]
389
    """
390

391
392
393
394
    if isinstance(arg, str):
        for delimiter in (';', ','):
            lst = arg.split(delimiter)
            if len(lst) > 1:
395
396
                return [s.strip() for s in lst]
        return [s.strip() for s in arg.strip().split(' ')]
397
    elif isinstance(arg, Sequence) or isinstance(arg, Set):
398
        return arg
Eckhart Arnold's avatar
Eckhart Arnold committed
399
    elif isinstance(arg, Iterable):
400
        return list(arg)
401
402
403
404
    else:
        return [arg]


405
def expand_table(compact_table: Dict) -> Dict:
406
407
    """
    Expands a table by separating keywords that are tuples or strings
408
409
410
    containing comma separated words into single keyword entries with
    the same values. Returns the expanded table.
    Example:
411
412
    >>> expand_table({"a, b": 1, ('d','e','f'):5, "c":3})
    {'a': 1, 'b': 1, 'd': 5, 'e': 5, 'f': 5, 'c': 3}
413
    """
414

415
    expanded_table = {}  # type: Dict
416
417
418
    keys = list(compact_table.keys())
    for key in keys:
        value = compact_table[key]
419
        for k in smart_list(key):
420
            if k in expanded_table:
421
                raise KeyError('Key "%s" used more than once in compact table!' % key)
422
            expanded_table[k] = value
423
    return expanded_table
424
425


426
427
#######################################################################
#
428
# miscellaneous (DHParser-specific)
429
430
431
432
#
#######################################################################


433
def sane_parser_name(name) -> bool:
434
435
    """
    Checks whether given name is an acceptable parser name. Parser names
436
    must not be preceded or succeeded by a double underscore '__'!
437
    """
438

di68kap's avatar
di68kap committed
439
440
441
    return name and name[:2] != '__' and name[-2:] != '__'


442
443
444
445
446
447
448
#######################################################################
#
# initialization
#
#######################################################################


di68kap's avatar
di68kap committed
449
450
451
452
453
454
455
456
457
458
try:
    if sys.stdout.encoding.upper() != "UTF-8":  # and  platform.system() == "Windows":
        # make sure that `print()` does not raise an error on
        # non-ASCII characters:
        # sys.stdout = cast(io.TextIOWrapper, codecs.getwriter("utf-8")(cast(
        #     io.BytesIO, cast(io.TextIOWrapper, sys.stdout).detach())))
        sys.stdout = io.TextIOWrapper(sys.stdout.detach(), sys.stdout.encoding, 'replace')
except AttributeError:
    # somebody has already taken care of this !?
    pass
eckhart's avatar
eckhart committed
459
460