File: buffering.py

package info (click to toggle)
python-tatsu 5.15.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 904 kB
  • sloc: python: 10,128; makefile: 54
file content (411 lines) | stat: -rw-r--r-- 11,362 bytes parent folder | download
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""
The Buffer class provides the functionality required by a parser-driven lexer.

Line analysis and caching are done so the parser can freely move with goto(p)
to any position in the parsed text, and still recover accurate information
about source lines and content.
"""
from __future__ import annotations

import re
from itertools import repeat, takewhile
from pathlib import Path
from typing import Any

from .exceptions import ParseError
from .infos import (
    CommentInfo,
    LineIndexInfo,
    LineInfo,
    PosLine,
    UndefinedStr,
)
from .parserconfig import ParserConfig
from .tokenizing import Tokenizer
from .util import (
    contains_sublist,
    extend_list,
    identity,
)
from .util.misc import cached_re_compile, match_to_find

DEFAULT_WHITESPACE_RE = re.compile(r'(?m)\s+')

# for backwards compatibility with existing parsers
LineIndexEntry = LineIndexInfo


class Buffer(Tokenizer):

    def __init__(
        self, text, /, config: ParserConfig | None = None, **settings: Any,
    ):
        super().__init__()
        config = ParserConfig.new(config=config, **settings)
        self.config = config

        text = str(text)
        self.text = self.original_text = text

        self.whitespace_re = self.build_whitespace_re(config.whitespace)
        self.nameguard = (
            config.nameguard
            if config.nameguard is not None
            else bool(self.whitespace_re) or bool(config.namechars)
        )
        self._namechar_set = set(config.namechars)

        self._pos = 0
        self._len = 0
        self._linecount = 0
        self._lines: list[str] = []
        self._line_index: list[LineIndexInfo] = []
        self._line_cache: list[PosLine] = []
        self._comment_index: list[CommentInfo] = []

        self._preprocess()
        self._postprocess()

    @property
    def filename(self):
        return self.config.filename

    @property
    def ignorecase(self):
        return self.config.ignorecase

    @property
    def whitespace(self):
        return self.config.whitespace

    @staticmethod
    def build_whitespace_re(whitespace):
        if type(whitespace) is UndefinedStr:
            return DEFAULT_WHITESPACE_RE
        if whitespace in {None, ''}:
            return None
        elif isinstance(whitespace, re.Pattern):
            return whitespace
        elif whitespace:
            return cached_re_compile(whitespace)
        else:
            return None

    def _preprocess(self, *args, **kwargs):
        lines, index = self._preprocess_block(self.filename, self.text)
        self._lines = lines
        self._line_index = index
        self.text = self.join_block_lines(lines)

    def _postprocess(self):
        cache, count = PosLine.build_line_cache(self._lines)
        self._line_cache = cache
        self._linecount = count
        self._len = len(self.text)

    def _preprocess_block(self, name, block, **kwargs):
        lines = self.split_block_lines(block)
        index = LineIndexInfo.block_index(name, len(lines))
        return self.process_block(name, lines, index, **kwargs)

    def split_block_lines(self, block):
        return block.splitlines(True)

    def join_block_lines(self, lines):
        return ''.join(lines)

    def process_block(self, name, lines, index, **kwargs):
        return lines, index

    def include(self, lines, index, i, j, name, block, **kwargs):
        blines, bindex = self._preprocess_block(name, block, **kwargs)
        assert len(blines) == len(bindex)
        lines[i:j] = blines
        index[i:j] = bindex
        assert len(lines) == len(index)
        return j + len(blines) - 1

    def include_file(self, source, name, lines, index, i, j):
        text, filename = self.get_include(source, name)
        return self.include(lines, index, i, j, filename, text)

    def get_include(self, source, filename):
        source = Path(source).resolve()
        base = source.parent
        include = base / filename
        try:
            with include.open() as f:
                return f.read(), include
        except OSError as e:
            raise ParseError(f'include not found: {include}') from e

    def replace_lines(self, i, j, name, block):
        lines = self.split_block_lines(self.text)
        index = list(self._line_index)

        endline = self.include(lines, index, i, j, name, block)

        self.text = self.join_block_lines(lines)
        self._line_index = index
        self._postprocess()

        newtext = self.join_block_lines(lines[j + 1: endline + 2])
        return endline, newtext

    @property
    def pos(self):
        return self._pos

    @pos.setter
    def pos(self, p):
        self.goto(p)

    @property
    def line(self):
        return self.posline()

    @property
    def col(self):
        return self.poscol()

    def posline(self, pos=None):
        if pos is None:
            pos = self._pos
        return self._line_cache[pos].line

    def poscol(self, pos=None):
        if pos is None:
            pos = self._pos
        start = self._line_cache[pos].start
        return pos - start

    def atend(self):
        return self._pos >= self._len

    def ateol(self):
        return self.atend() or self.current in '\r\n'

    @property
    def current(self):
        if self._pos >= self._len:
            return None
        return self.text[self._pos]

    def at(self, p):
        if p >= self._len:
            return None
        return self.text[p]

    def peek(self, n=1):
        return self.at(self._pos + n)

    def next(self):
        if self.atend():
            return None
        c = self.text[self._pos]
        self._pos += 1
        return c

    def goto(self, pos):
        self._pos = max(0, min(len(self.text), pos))

    def move(self, n):
        self.goto(self.pos + n)

    def comments(self, p, clear=False):
        if not self.config.comment_recovery or not self._comment_index:
            return CommentInfo([], [])

        n = self.posline(p)
        if n >= len(self._comment_index):
            return CommentInfo([], [])

        eolcmm = []
        if n < len(self._comment_index):
            eolcmm = self._comment_index[n].eol
            if clear:
                self._comment_index[n].eol = []

        cmm = []
        while n >= 0 and self._comment_index[n].inline:
            cmm.insert(0, self._comment_index[n].inline)
            if clear:
                self._comment_index[n].inline = []
            n -= 1

        return CommentInfo(cmm, eolcmm)

    def _index_comments(self, comments, selector):
        if comments and self.config.comment_recovery:
            n = self.line
            extend_list(
                self._comment_index, n, default=CommentInfo.new_comment,
            )
            previous = selector(self._comment_index[n])
            if not contains_sublist(
                previous, comments,
            ):  # FIXME: will discard repeated comments
                previous.extend(comments)

    def _eat_regex(self, regex):
        if not regex:
            return
        while self._matchre_fast(regex):
            pass

    def _eat_regex_list(self, regex):
        if not regex:
            return []
        regex = cached_re_compile(regex)
        return list(takewhile(identity, map(self.matchre, repeat(regex))))

    def eat_whitespace(self):
        return self._eat_regex(self.whitespace_re)

    def eat_comments(self):
        comments = self._eat_regex_list(self.config.comments)
        self._index_comments(comments, lambda x: x.inline)

    def eat_eol_comments(self):
        comments = self._eat_regex_list(self.config.eol_comments)
        self._index_comments(comments, lambda x: x.eol)

    def next_token(self):
        p = None
        while self._pos != p:
            p = self._pos
            self.eat_eol_comments()
            self.eat_comments()
            self.eat_whitespace()

    def skip_to(self, c):
        p = self._pos
        le = self._len
        while p < le and self.text[p] != c:
            p += 1
        self.goto(p)
        return self.pos

    def skip_past(self, c):
        self.skip_to(c)
        self.next()
        return self.pos

    def skip_to_eol(self):
        return self.skip_to('\n')

    def scan_space(self):
        return (
            self.whitespace_re and self._scanre(self.whitespace_re) is not None
        )

    def is_space(self):
        return self.scan_space()

    def is_name_char(self, c):
        return c is not None and (c.isalnum() or c in self._namechar_set)

    def match(self, token: str) -> str | None:
        if token is None:
            return self.atend()

        p = self.pos
        if self.ignorecase:
            is_match = self.text[p: p + len(token)].lower() == token.lower()
        else:
            is_match = self.text[p: p + len(token)] == token

        if not is_match:
            return None

        self.move(len(token))
        partial_match = (
            self.nameguard
            and token
            and token[0].isalpha()
            and self.is_name_char(self.current)
            and all(self.is_name_char(t) for t in token)
        )
        if partial_match:
            self.goto(p)
            return None

        return token

    def _matchre_fast(self, pattern):
        if not (match := self._scanre(pattern)):
            return

        self.move(len(match.group()))

    def matchre(self, pattern):
        if not (match := self._scanre(pattern)):
            return None

        matched = match.group()
        token = match_to_find(match)
        self.move(len(matched))
        return token

    def _scanre(self, pattern):
        cre = cached_re_compile(pattern)
        return cre.match(self.text, self.pos)

    @property
    def linecount(self):
        return self._linecount

    def line_info(self, pos=None):
        if pos is None:
            pos = self._pos

        # -2 to skip over sentinel
        pos = min(pos, len(self._line_cache) - 2)
        start, line, length = self._line_cache[pos]
        end = start + length
        col = pos - start

        text = self.text[start:end]

        # only required to support includes
        n = min(len(self._line_index) - 1, line)
        filename, line = self._line_index[n]

        return LineInfo(filename, line, col, start, end, text)

    def lookahead_pos(self):
        if self.atend():
            return ''
        info = self.line_info()
        return '~%d:%d' % (info.line + 1, info.col + 1)

    def lookahead(self):
        if self.atend():
            return ''
        info = self.line_info()
        text = info.text[info.col: info.col + 1 + 80]
        text = self.split_block_lines(text)[0].rstrip()
        return f'{text}'

    def get_line(self, n=None):
        if n is None:
            n = self.line
        return self._lines[n]

    def get_lines(self, start=None, end=None):
        if start is None:
            start = 0
        if end is None:
            end = len(self._lines)
        return self._lines[start: end + 1]

    def line_index(self, start=0, end=None):
        if end is None:
            end = len(self._line_index)
        return self._line_index[start: 1 + end]

    def __repr__(self):
        return '%s@%d' % (type(self).__name__, self.pos)

    def __json__(self, seen=None):
        return None