toolkit.py 13 KB
Newer Older
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
"""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.


Module ``toolkit`` contains utility functions and cross-sectional
functionality like logging support that is needed across several 
of the the other DHParser-Modules.

For logging functionality, the global variable LOGGING is defined which
contains the name of a directory where log files shall be placed. By
setting its value to the empty string "" logging can be turned off.

To read the directory name function ``LOGS_DIR()`` should be called
rather than reading the variable LOGGING. ``LOGS_DIR()`` makes sure
the directory exists and raises an error if a file with the same name
already exists.
"""

import collections
Eckhart Arnold's avatar
Eckhart Arnold committed
34
import contextlib
35
36
import hashlib
import os
di68kap's avatar
di68kap committed
37
38
39
40
try:
    import regex as re
except ImportError:
    import re
41
try:
42
    from typing import Any, List, Tuple
43
except ImportError:
44
    from .typing34 import Any, List, Tuple
45
46


Eckhart Arnold's avatar
Eckhart Arnold committed
47
48
49
__all__ = ['logging',
           'is_logging',
           'log_dir',
50
           'logfile_basename',
51
52
           # 'supress_warnings',
           # 'warnings',
53
           'repr_call',
54
           'line_col',
55
           'error_messages',
Eckhart Arnold's avatar
Eckhart Arnold committed
56
           'compact_sexpr',
57
           'escape_re',
Eckhart Arnold's avatar
Eckhart Arnold committed
58
           'is_filename',
59
60
           'load_if_file',
           'is_python_code',
61
62
           'md5',
           'expand_table',
63
           'smart_list',
64
           'sane_parser_name']
65
66


Eckhart Arnold's avatar
Eckhart Arnold committed
67
68
69
def log_dir() -> str:
    """Creates a directory for log files (if it does not exist) and
    returns its path.
70

Eckhart Arnold's avatar
Eckhart Arnold committed
71
72
73
    WARNING: Any files in the log dir will eventually be overwritten.
    Don't use a directory name that could be the name of a directory
    for other purposes than logging.
74
75
76
77

    Returns:
        name of the logging directory
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
78
    # the try-except clauses in the following are precautions for multiprocessing
79
    global LOGGING
Eckhart Arnold's avatar
Eckhart Arnold committed
80
81
82
83
84
85
86
87
88
89
    try:
        dirname = LOGGING    # raises a name error if LOGGING is not defined
        if not dirname:
            raise NameError  # raise a name error if LOGGING evaluates to False
    except NameError:
        raise NameError("No access to log directory before logging has been turned "
                        "on within the same thread/process.")
    if os.path.exists(dirname) and not os.path.isdir(dirname):
        raise IOError('"' + dirname + '" cannot be used as log directory, '
                                      'because it is not a directory!')
90
    else:
Eckhart Arnold's avatar
Eckhart Arnold committed
91
92
93
94
95
        try:
            os.mkdir(dirname)
        except FileExistsError:
            pass
    info_file_name = os.path.join(dirname, 'info.txt')
96
97
98
99
    if not os.path.exists(info_file_name):
        with open(info_file_name, 'w') as f:
            f.write("This directory has been created by DHParser to store log files from\n"
                    "parsing. ANY FILE IN THIS DIRECTORY CAN BE OVERWRITTEN! Therefore,\n"
100
101
                    "do not place any files here and do not bother editing files in this\n"
                    "directory as any changes will get lost.\n")
102
103
104
    return dirname


Eckhart Arnold's avatar
Eckhart Arnold committed
105
@contextlib.contextmanager
106
def logging(dirname: str = "LOGS"):
Eckhart Arnold's avatar
Eckhart Arnold committed
107
108
109
110
111
112
113
114
    """Context manager. Log files within this context will be stored in
    directory ``dirname``. Logging is turned off if name is empty.
    
    Args:
        dirname: the name for the log directory or the empty string to
            turn logging of
    """
    global LOGGING
Eckhart Arnold's avatar
Eckhart Arnold committed
115
    if dirname == True:  dirname = "LOGS"  # be fail tolerant here...
Eckhart Arnold's avatar
Eckhart Arnold committed
116
117
118
119
120
121
122
123
124
    try:
        save = LOGGING
    except NameError:
        save = ""
    LOGGING = dirname
    yield
    LOGGING = save


125
def is_logging() -> bool:
Eckhart Arnold's avatar
Eckhart Arnold committed
126
127
128
129
130
131
132
133
    """-> True, if logging is turned on."""
    global LOGGING
    try:
        return bool(LOGGING)
    except NameError:
        return False


134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# @contextlib.contextmanager
# def supress_warnings(supress: bool = True):
#     global SUPRESS_WARNINGS
#     try:
#         save = SUPRESS_WARNINGS
#     except NameError:
#         save = False  # global default for warning supression is False
#     SUPRESS_WARNINGS = supress
#     yield
#     SUPRESS_WARNINGS = save
#
#
# def warnings() -> bool:
#     global SUPRESS_WARNINGS
#     try:
#         return not SUPRESS_WARNINGS
#     except NameError:
#         return True
152
153


154
155
156
def repr_call(f, parameter_list) -> str:
    """Turns a list of items into a string resembling the parameter
    list of a function call by omitting default values at the end:
157
    >>> def f(a, b=1):    print(a, b)
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
    >>> repr_call(f, (5,1))
    'f(5)'
    >>> repr_call(f, (5,2))
    'f(5, 2)'
    """
    i = 0
    defaults = f.__defaults__ if f.__defaults__ is not None else []
    for parameter, default in zip(reversed(parameter_list), reversed(defaults)):
        if parameter != default:
            break
        i -= 1
    if i < 0:
        parameter_list = parameter_list[:i]
    name = f.__self__.__class__.__name__ if f.__name__ == '__init__' else f.__name__
    return "%s(%s)" % (name, ", ".join(repr(item) for item in parameter_list))



176
def line_col(text: str, pos: int) -> Tuple[int, int]:
177
178
    """Returns the position within a text as (line, column)-tuple.
    """
179
    assert pos <= len(text), str(pos) + " > " + str(len(text))  # can point one character after EOF
180
181
182
183
184
    line = text.count("\n", 0, pos) + 1
    column = pos - text.rfind("\n", 0, pos)
    return line, column


185
def error_messages(source_text, errors) -> List[str]:
186
187
188
189
190
191
192
193
194
195
196
    """Returns the sequence or iterator of error objects as an intertor
    of error messages with line and column numbers at the beginning.
    
    Args:
        source_text (str):  The source text on which the errors occurred.
            (Needed in order to determine the line and column numbers.)
        errors (list):  The list of errors as returned by the method 
            ``collect_errors()`` of a Node object     
    Returns:
        a list that contains all error messages in string form. Each
        string starts with "line: [Line-No], column: [Column-No]
197
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
198
    return ["line: %i, column: %i" % line_col(source_text, err.pos) + ", error: %s" % err.msg
199
            for err in sorted(list(errors))]
200
201


202
def compact_sexpr(s) -> str:
203
204
205
206
    """Returns S-expression ``s`` as a one liner without unnecessary
    whitespace.

    Example:
207
208
    >>> compact_sexpr('(a\\n    (b\\n        c\\n    )\\n)\\n')
    '(a (b c))'
209
210
211
212
    """
    return re.sub('\s(?=\))', '', re.sub('\s+', ' ', s)).strip()


Eckhart Arnold's avatar
Eckhart Arnold committed
213
214
215
216
217
218
219
220
# def quick_report(parsing_result) -> str:
#     """Returns short report (compact s-expression + errors messages)
#     of the parsing results by either a call to a grammar or to a parser
#     directly."""
#     err = ''
#     if isinstance(parsing_result, collections.Collection):
#         result = parsing_result[0]
#         err = ('\nUnmatched sequence: ' + parsing_result[1]) if parsing_result[1] else ''
221
#     sexpr = compact_sexpr(result.as_sxpr())
Eckhart Arnold's avatar
Eckhart Arnold committed
222
223
224
#     return sexpr + err


225
def escape_re(s) -> str:
226
227
228
229
230
231
232
233
234
    """Returns `s` with all regular expression special characters escaped.
    """
    assert isinstance(s, str)
    re_chars = r"\.^$*+?{}[]()#<>=|!"
    for esc_ch in re_chars:
        s = s.replace(esc_ch, '\\' + esc_ch)
    return s


235
def is_filename(s) -> bool:
Eckhart Arnold's avatar
Eckhart Arnold committed
236
237
238
239
240
    """Tries to guess whether string ``s`` is a file name."""
    return s.find('\n') < 0 and s[:1] != " " and s[-1:] != " " \
           and s.find('*') < 0 and s.find('?') < 0


241
def logfile_basename(filename_or_text, function_or_class_or_instance) -> str:
Eckhart Arnold's avatar
Eckhart Arnold committed
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    """Generates a reasonable logfile-name (without extension) based on
    the given information.
    """
    if is_filename(filename_or_text):
        return os.path.basename(os.path.splitext(filename_or_text)[0])
    else:
        try:
            s = function_or_class_or_instance.__qualname.__
        except AttributeError:
            s = function_or_class_or_instance.__class__.__name__
        i = s.find('.')
        return s[:i] + '_out' if i >= 0 else s


256
257
258
259
260
def load_if_file(text_or_file) -> str:
    """Reads and returns content of a text-file if parameter
    `text_or_file` is a file name (i.e. a single line string),
    otherwise (i.e. if `text_or_file` is a multiline string)
    `text_or_file` is returned.
261
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
262
    if is_filename(text_or_file):
263
264
265
266
267
        try:
            with open(text_or_file, encoding="utf-8") as f:
                content = f.read()
            return content
        except FileNotFoundError as error:
268
            if re.fullmatch(r'[\w/:. \\]+', text_or_file):
269
270
                raise FileNotFoundError('Not a valid file: ' + text_or_file + '!\n(Add "\\n" '
                                        'to distinguish source data from a file name.)')
271
272
            else:
                return text_or_file
273
274
275
276
    else:
        return text_or_file


277
def is_python_code(text_or_file) -> bool:
278
279
280
    """Checks whether 'text_or_file' is python code or the name of a file that
    contains python code.
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
281
    if is_filename(text_or_file):
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
        return text_or_file[-3:].lower() == '.py'
    try:
        compile(text_or_file, '<string>', 'exec')
        return True
    except (SyntaxError, ValueError, OverflowError):
        pass
    return False


def md5(*txt):
    """Returns the md5-checksum for `txt`. This can be used to test if
    some piece of text, for example a grammar source file, has changed.
    """
    md5_hash = hashlib.md5()
    for t in txt:
        md5_hash.update(t.encode('utf8'))
    return md5_hash.hexdigest()


301
302
def smart_list(arg) -> list:
    """Returns the argument as list, depending on its type and content.
303
304
305
306
    
    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.
307
308
309
310
311
312
313
    >>> smart_list('1; 2, 3; 4')
    ['1', '2, 3', '4']
    >>> smart_list('2, 3')
    ['2', '3']
    >>> smart_list('a b cd')
    ['a', 'b', 'cd']

314
315
    If the argument is a collection other than a string, it will be
    returned as is, e.g.
316
317
318
319
320
    >>> smart_list((1, 2, 3))
    (1, 2, 3)
    >>> smart_list({1, 2, 3})
    {1, 2, 3}

321
322
    If the argument is another iterable than a collection, it will
    be converted into a list, e.g.
323
324
325
    >>> smart_list(i for i in {1,2,3})
    [1, 2, 3]

326
327
    Finally, if none of the above is true, the argument will be 
    wrapped in a list and returned, e.g.
328
329
    >>> smart_list(125)
    [125]
330
331
332
333
334
    """
    if isinstance(arg, str):
        for delimiter in (';', ','):
            lst = arg.split(delimiter)
            if len(lst) > 1:
335
336
                return [s.strip() for s in lst]
        return [s.strip() for s in arg.strip().split(' ')]
337
338
    elif isinstance(arg, collections.abc.Container):
        return arg
339
    elif isinstance(arg, collections.abc.Iterable):
340
        return list(arg)
341
342
343
344
    else:
        return [arg]


345
346
347
348
349
def expand_table(compact_table):
    """Expands a table by separating keywords that are tuples or strings
    containing comma separated words into single keyword entries with
    the same values. Returns the expanded table.
    Example:
350
351
    >>> expand_table({"a, b": 1, ('d','e','f'):5, "c":3})
    {'a': 1, 'b': 1, 'd': 5, 'e': 5, 'f': 5, 'c': 3}
352
353
354
355
356
    """
    expanded_table = {}
    keys = list(compact_table.keys())
    for key in keys:
        value = compact_table[key]
357
        for k in smart_list(key):
358
359
            if k in expanded_table:
                raise KeyError("Key %s used more than once in compact table!" % key)
360
            expanded_table[k] = value
361
    return expanded_table
362
363


364
def sane_parser_name(name) -> bool:
365
366
367
    """Checks whether given name is an acceptable parser name. Parser names
    must not be preceeded or succeeded by a double underscore '__'!
    """
di68kap's avatar
di68kap committed
368
369
370
    return name and name[:2] != '__' and name[-2:] != '__'


371
372
373
374
def compile_python_object(python_src, catch_obj_regex=""):
    """Compiles the python source code and returns the (first) object 
    the name of which is matched by ``catch_obj_regex``. If catch_obj
    is the empty string, the namespace dictionary will be returned.
di68kap's avatar
di68kap committed
375
376
377
378
379
380
    """
    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?
381
382
383
384
385
386
387
388
389
390
391
    if catch_obj_regex:
        matches = [key for key in namespace.keys() if catch_obj_regex.match(key)]
        if len(matches) == 0:
            raise ValueError("No object matching /%s/ defined in source code." %
                             catch_obj_regex.pattern)
        elif len(matches) > 1:
            raise ValueError("Ambigous matches for %s : %s" %
                             (str(catch_obj_regex), str(matches)))
        return namespace[matches[0]] if matches else None
    else:
        return namespace