File: buffering.py

package info (click to toggle)
python-tatsu 5.17.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,516 kB
  • sloc: python: 13,185; makefile: 127
file content (421 lines) | stat: -rw-r--r-- 11,876 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
412
413
414
415
416
417
418
419
420
421
# Copyright (c) 2017-2026 Juancarlo AƱez (apalala@gmail.com)
# SPDX-License-Identifier: BSD-4-Clause
"""
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 pathlib import Path
from typing import Any

from .infos import ParserConfig, PosLine
from .tokenizing import LineIndexInfo, LineInfo, Tokenizer
from .util.itertools import str_from_match
from .util.misc import cached_re_compile
from .util.undefined import Undefined

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

# for backwards compatibility with existing parsers
LineIndexEntry = LineIndexInfo


class Buffer(Tokenizer):

    def __init__(
        self,
        text: str,
        *,
        config: ParserConfig | None = None,
        **settings: Any,
    ):
        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 or '')

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

        self._preprocess()
        self._postprocess()

    @property
    def text(self) -> str:
        return self._text

    @property
    def filename(self) -> str:
        return str(self.config.filename or '')

    @property
    def ignorecase(self) -> bool:
        return bool(self.config.ignorecase)

    @property
    def whitespace(self) -> str | None:
        return self.config.whitespace

    @staticmethod
    def build_whitespace_re(whitespace: Any) -> re.Pattern | None:
        if whitespace is Undefined:
            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: Any, **kwargs: Any):
        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, len(self.text))
        self._line_cache = cache
        self._linecount = count
        self._len = len(self.text)

    def _preprocess_block(
        self,
        name: str,
        block,
        /,
        **kwargs,
    ) -> tuple[list[str], list[LineIndexInfo]]:
        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: str) -> list[str]:
        return block.splitlines(True)

    def join_block_lines(self, lines: list[str]):
        return ''.join(lines)

    def process_block(
        self,
        name: str,
        lines: list[str],
        index: list[LineIndexInfo],
        /,
        **kwargs,
    ) -> tuple[list[str], list[LineIndexInfo]]:
        return lines, index

    def include(
        self,
        lines: list[str],
        index: list[LineIndexInfo],
        i: int,
        j: int,
        name: str,
        block: str,
        /,
        **kwargs,
    ) -> int:
        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: str,
        name: str,
        lines: list[str],
        index: list[LineIndexInfo],
        i: int,
        j: int,
    ) -> int:
        text, filename = self.get_include(source, name)
        return self.include(lines, index, i, j, filename, text)

    def get_include(self, source: str, filename: str) -> tuple[str, str]:
        source_path = Path(source).resolve()
        base = source_path.parent
        include = base / filename
        try:
            return include.read_text(), str(include)
        except OSError as e:
            raise ValueError(f'include not found: {include}') from e

    def replace_lines(self, i: int, j: int, name: str, block: str) -> tuple[int, str]:
        lines = self.split_block_lines(self.text)
        index = 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) -> int:
        return self._pos

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

    @property
    def line(self) -> int:
        return self.posline()

    @property
    def col(self) -> int:
        return self.poscol()

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

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

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

    def ateol(self) -> bool:
        return self.atend() or self.current in {'\r', '\n', None}

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

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

    def peek(self, n: int = 1) -> str | None:
        return self.at(self._pos + n)

    def next(self) -> str | None:
        if self.atend():
            return None
        c = self.text[self.pos]
        self.move(1)
        return c

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

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

    def _eat_regex(self, regex: str | re.Pattern) -> None:
        if not regex:
            return
        while self._matchre_fast(regex):
            pass

    def _eat_regex_list(self, regex: str | re.Pattern | None) -> list[str]:
        if not regex:
            return []

        r = cached_re_compile(regex)
        if r is None:
            return []

        def takewhile_repeat_regex():
            while x := self.matchre(r):
                yield x

        return list(takewhile_repeat_regex())

    def eat_whitespace(self) -> None:
        if self.whitespace_re:
            self._eat_regex(self.whitespace_re)

    def eat_comments(self) -> list[str]:
        return self._eat_regex_list(self.config.comments)

    def eat_eol_comments(self) -> list[str]:
        return self._eat_regex_list(self.config.eol_comments)

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

    def skip_to(self, c: str) -> int:
        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: str) -> int:
        self.skip_to(c)
        self.next()
        return self.pos

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

    def scan_space(self) -> bool:
        return bool(self.whitespace_re) and bool(self._scanre(self.whitespace_re))

    def is_space(self) -> bool:
        return self.scan_space()

    def is_name_char(self, c: str | None) -> bool:
        return c is not None and (c.isalnum() or c in self._namechar_set)

    def is_name(self, s: str) -> bool:
        if not s:
            return False
        goodstart = s[0].isalpha() or s[0] in self._namechar_set
        return goodstart and all(self.is_name_char(c) for c in s[1:])

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

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

        self.move(len(token))
        partial_match = (
            self.nameguard and self.is_name_char(self.current) and self.is_name(token)
        )
        if partial_match:
            self.goto(p)
            return None

        return token

    def _matchre_fast(self, pattern: str | re.Pattern | None):
        if not (match := self._scanre(pattern)):
            return

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

    def matchre(self, pattern: str | re.Pattern) -> str | None:
        if not (match := self._scanre(pattern)):
            return None

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

    def _scanre(self, pattern: str | re.Pattern | None) -> re.Match[Any] | None:
        cre = cached_re_compile(pattern)
        if cre is None:
            return None
        else:
            return cre.match(self.text, self.pos)

    @property
    def linecount(self) -> int:
        return self._linecount

    def lineinfo(self, pos: int | None = None) -> LineInfo:
        if pos is None:
            pos = self._pos
        if not self._line_cache or not self._line_index:
            return LineInfo(
                filename=self.filename,
                line=0,
                col=0,
                start=0,
                end=len(self.text),
                text=self.text,
            )

        # -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) -> str:
        if self.atend():
            return ''
        info = self.lineinfo()
        return '@%d:%d' % (info.line + 1, info.col + 1)

    def lookahead(self) -> str:
        if self.atend():
            return ''
        info = self.lineinfo()
        text = info.text[info.col : info.col + 1 + 80]
        return self.split_block_lines(text)[0].rstrip()

    def get_line(self, n: int | None = None) -> str:
        if n is None:
            n = self.line
        return self._lines[n]

    def get_lines(self, start: int | None = None, end: int | None = None) -> list[str]:
        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: int = 0, end: int | None = None) -> list[LineIndexInfo]:
        if end is None:
            end = len(self._line_index)
        return self._line_index[start : 1 + end]

    def __repr__(self) -> str:
        return f'{type(self).__name__}()'

    def __json__(self, seen: set[int] | None = None) -> str | None:
        return None