| 1 |
# coding: utf-8 |
| 2 |
|
| 3 |
from __future__ import absolute_import |
| 4 |
|
| 5 |
# This module contains abstractions for the input stream. You don't have to |
| 6 |
# looks further, there are no pretty code. |
| 7 |
# |
| 8 |
# We define two classes here. |
| 9 |
# |
| 10 |
# Mark(source, line, column) |
| 11 |
# It's just a record and its only use is producing nice error messages. |
| 12 |
# Parser does not use it for any other purposes. |
| 13 |
# |
| 14 |
# Reader(source, data) |
| 15 |
# Reader determines the encoding of `data` and converts it to unicode. |
| 16 |
# Reader provides the following methods and attributes: |
| 17 |
# reader.peek(length=1) - return the next `length` characters |
| 18 |
# reader.forward(length=1) - move the current position to `length` |
| 19 |
# characters. |
| 20 |
# reader.index - the number of the current character. |
| 21 |
# reader.line, stream.column - the line and the column of the current |
| 22 |
# character. |
| 23 |
|
| 24 |
import codecs |
| 25 |
|
| 26 |
from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError |
| 27 |
from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE |
| 28 |
from strictyaml.ruamel.util import RegExp |
| 29 |
|
| 30 |
if False: # MYPY |
| 31 |
from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA |
| 32 |
# from strictyaml.ruamel.compat import StreamTextType # NOQA |
| 33 |
|
| 34 |
__all__ = ["Reader", "ReaderError"] |
| 35 |
|
| 36 |
|
| 37 |
class ReaderError(YAMLError): |
| 38 |
def __init__(self, name, position, character, encoding, reason): |
| 39 |
# type: (Any, Any, Any, Any, Any) -> None |
| 40 |
self.name = name |
| 41 |
self.character = character |
| 42 |
self.position = position |
| 43 |
self.encoding = encoding |
| 44 |
self.reason = reason |
| 45 |
|
| 46 |
def __str__(self): |
| 47 |
# type: () -> str |
| 48 |
if isinstance(self.character, binary_type): |
| 49 |
return ( |
| 50 |
"'%s' codec can't decode byte #x%02x: %s\n" |
| 51 |
' in "%s", position %d' |
| 52 |
% ( |
| 53 |
self.encoding, |
| 54 |
ord(self.character), |
| 55 |
self.reason, |
| 56 |
self.name, |
| 57 |
self.position, |
| 58 |
) |
| 59 |
) |
| 60 |
else: |
| 61 |
return "unacceptable character #x%04x: %s\n" ' in "%s", position %d' % ( |
| 62 |
self.character, |
| 63 |
self.reason, |
| 64 |
self.name, |
| 65 |
self.position, |
| 66 |
) |
| 67 |
|
| 68 |
|
| 69 |
class Reader(object): |
| 70 |
# Reader: |
| 71 |
# - determines the data encoding and converts it to a unicode string, |
| 72 |
# - checks if characters are in allowed range, |
| 73 |
# - adds '\0' to the end. |
| 74 |
|
| 75 |
# Reader accepts |
| 76 |
# - a `str` object (PY2) / a `bytes` object (PY3), |
| 77 |
# - a `unicode` object (PY2) / a `str` object (PY3), |
| 78 |
# - a file-like object with its `read` method returning `str`, |
| 79 |
# - a file-like object with its `read` method returning `unicode`. |
| 80 |
|
| 81 |
# Yeah, it's ugly and slow. |
| 82 |
|
| 83 |
def __init__(self, stream, loader=None): |
| 84 |
# type: (Any, Any) -> None |
| 85 |
self.loader = loader |
| 86 |
if self.loader is not None and getattr(self.loader, "_reader", None) is None: |
| 87 |
self.loader._reader = self |
| 88 |
self.reset_reader() |
| 89 |
self.stream = stream # type: Any # as .read is called |
| 90 |
|
| 91 |
def reset_reader(self): |
| 92 |
# type: () -> None |
| 93 |
self.name = None # type: Any |
| 94 |
self.stream_pointer = 0 |
| 95 |
self.eof = True |
| 96 |
self.buffer = "" |
| 97 |
self.pointer = 0 |
| 98 |
self.raw_buffer = None # type: Any |
| 99 |
self.raw_decode = None |
| 100 |
self.encoding = None # type: Optional[Text] |
| 101 |
self.index = 0 |
| 102 |
self.line = 0 |
| 103 |
self.column = 0 |
| 104 |
|
| 105 |
@property |
| 106 |
def stream(self): |
| 107 |
# type: () -> Any |
| 108 |
try: |
| 109 |
return self._stream |
| 110 |
except AttributeError: |
| 111 |
raise YAMLStreamError("input stream needs to specified") |
| 112 |
|
| 113 |
@stream.setter |
| 114 |
def stream(self, val): |
| 115 |
# type: (Any) -> None |
| 116 |
if val is None: |
| 117 |
return |
| 118 |
self._stream = None |
| 119 |
if isinstance(val, text_type): |
| 120 |
self.name = "<unicode string>" |
| 121 |
self.check_printable(val) |
| 122 |
self.buffer = val + u"\0" # type: ignore |
| 123 |
elif isinstance(val, binary_type): |
| 124 |
self.name = "<byte string>" |
| 125 |
self.raw_buffer = val |
| 126 |
self.determine_encoding() |
| 127 |
else: |
| 128 |
if not hasattr(val, "read"): |
| 129 |
raise YAMLStreamError("stream argument needs to have a read() method") |
| 130 |
self._stream = val |
| 131 |
self.name = getattr(self.stream, "name", "<file>") |
| 132 |
self.eof = False |
| 133 |
self.raw_buffer = None |
| 134 |
self.determine_encoding() |
| 135 |
|
| 136 |
def peek(self, index=0): |
| 137 |
# type: (int) -> Text |
| 138 |
try: |
| 139 |
return self.buffer[self.pointer + index] |
| 140 |
except IndexError: |
| 141 |
self.update(index + 1) |
| 142 |
return self.buffer[self.pointer + index] |
| 143 |
|
| 144 |
def prefix(self, length=1): |
| 145 |
# type: (int) -> Any |
| 146 |
if self.pointer + length >= len(self.buffer): |
| 147 |
self.update(length) |
| 148 |
return self.buffer[self.pointer : self.pointer + length] |
| 149 |
|
| 150 |
def forward_1_1(self, length=1): |
| 151 |
# type: (int) -> None |
| 152 |
if self.pointer + length + 1 >= len(self.buffer): |
| 153 |
self.update(length + 1) |
| 154 |
while length != 0: |
| 155 |
ch = self.buffer[self.pointer] |
| 156 |
self.pointer += 1 |
| 157 |
self.index += 1 |
| 158 |
if ch in u"\n\x85\u2028\u2029" or ( |
| 159 |
ch == u"\r" and self.buffer[self.pointer] != u"\n" |
| 160 |
): |
| 161 |
self.line += 1 |
| 162 |
self.column = 0 |
| 163 |
elif ch != u"\uFEFF": |
| 164 |
self.column += 1 |
| 165 |
length -= 1 |
| 166 |
|
| 167 |
def forward(self, length=1): |
| 168 |
# type: (int) -> None |
| 169 |
if self.pointer + length + 1 >= len(self.buffer): |
| 170 |
self.update(length + 1) |
| 171 |
while length != 0: |
| 172 |
ch = self.buffer[self.pointer] |
| 173 |
self.pointer += 1 |
| 174 |
self.index += 1 |
| 175 |
if ch == u"\n" or (ch == u"\r" and self.buffer[self.pointer] != u"\n"): |
| 176 |
self.line += 1 |
| 177 |
self.column = 0 |
| 178 |
elif ch != u"\uFEFF": |
| 179 |
self.column += 1 |
| 180 |
length -= 1 |
| 181 |
|
| 182 |
def get_mark(self): |
| 183 |
# type: () -> Any |
| 184 |
if self.stream is None: |
| 185 |
return StringMark( |
| 186 |
self.name, self.index, self.line, self.column, self.buffer, self.pointer |
| 187 |
) |
| 188 |
else: |
| 189 |
return FileMark(self.name, self.index, self.line, self.column) |
| 190 |
|
| 191 |
def determine_encoding(self): |
| 192 |
# type: () -> None |
| 193 |
while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2): |
| 194 |
self.update_raw() |
| 195 |
if isinstance(self.raw_buffer, binary_type): |
| 196 |
if self.raw_buffer.startswith(codecs.BOM_UTF16_LE): |
| 197 |
self.raw_decode = codecs.utf_16_le_decode # type: ignore |
| 198 |
self.encoding = "utf-16-le" |
| 199 |
elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE): |
| 200 |
self.raw_decode = codecs.utf_16_be_decode # type: ignore |
| 201 |
self.encoding = "utf-16-be" |
| 202 |
else: |
| 203 |
self.raw_decode = codecs.utf_8_decode # type: ignore |
| 204 |
self.encoding = "utf-8" |
| 205 |
self.update(1) |
| 206 |
|
| 207 |
if UNICODE_SIZE == 2: |
| 208 |
NON_PRINTABLE = RegExp( |
| 209 |
u"[^\x09\x0A\x0D\x20-\x7E\x85" u"\xA0-\uD7FF" u"\uE000-\uFFFD" u"]" |
| 210 |
) |
| 211 |
else: |
| 212 |
NON_PRINTABLE = RegExp( |
| 213 |
u"[^\x09\x0A\x0D\x20-\x7E\x85" |
| 214 |
u"\xA0-\uD7FF" |
| 215 |
u"\uE000-\uFFFD" |
| 216 |
u"\U00010000-\U0010FFFF" |
| 217 |
u"]" |
| 218 |
) |
| 219 |
|
| 220 |
_printable_ascii = ("\x09\x0A\x0D" + "".join(map(chr, range(0x20, 0x7F)))).encode( |
| 221 |
"ascii" |
| 222 |
) |
| 223 |
|
| 224 |
@classmethod |
| 225 |
def _get_non_printable_ascii(cls, data): # type: ignore |
| 226 |
# type: (Text, bytes) -> Optional[Tuple[int, Text]] |
| 227 |
ascii_bytes = data.encode("ascii") |
| 228 |
non_printables = ascii_bytes.translate(None, cls._printable_ascii) # type: ignore |
| 229 |
if not non_printables: |
| 230 |
return None |
| 231 |
non_printable = non_printables[:1] |
| 232 |
return ascii_bytes.index(non_printable), non_printable.decode("ascii") |
| 233 |
|
| 234 |
@classmethod |
| 235 |
def _get_non_printable_regex(cls, data): |
| 236 |
# type: (Text) -> Optional[Tuple[int, Text]] |
| 237 |
match = cls.NON_PRINTABLE.search(data) |
| 238 |
if not bool(match): |
| 239 |
return None |
| 240 |
return match.start(), match.group() |
| 241 |
|
| 242 |
@classmethod |
| 243 |
def _get_non_printable(cls, data): |
| 244 |
# type: (Text) -> Optional[Tuple[int, Text]] |
| 245 |
try: |
| 246 |
return cls._get_non_printable_ascii(data) # type: ignore |
| 247 |
except UnicodeEncodeError: |
| 248 |
return cls._get_non_printable_regex(data) |
| 249 |
|
| 250 |
def check_printable(self, data): |
| 251 |
# type: (Any) -> None |
| 252 |
non_printable_match = self._get_non_printable(data) |
| 253 |
if non_printable_match is not None: |
| 254 |
start, character = non_printable_match |
| 255 |
position = self.index + (len(self.buffer) - self.pointer) + start |
| 256 |
raise ReaderError( |
| 257 |
self.name, |
| 258 |
position, |
| 259 |
ord(character), |
| 260 |
"unicode", |
| 261 |
"special characters are not allowed", |
| 262 |
) |
| 263 |
|
| 264 |
def update(self, length): |
| 265 |
# type: (int) -> None |
| 266 |
if self.raw_buffer is None: |
| 267 |
return |
| 268 |
self.buffer = self.buffer[self.pointer :] |
| 269 |
self.pointer = 0 |
| 270 |
while len(self.buffer) < length: |
| 271 |
if not self.eof: |
| 272 |
self.update_raw() |
| 273 |
if self.raw_decode is not None: |
| 274 |
try: |
| 275 |
data, converted = self.raw_decode( |
| 276 |
self.raw_buffer, "strict", self.eof |
| 277 |
) |
| 278 |
except UnicodeDecodeError as exc: |
| 279 |
if PY3: |
| 280 |
character = self.raw_buffer[exc.start] |
| 281 |
else: |
| 282 |
character = exc.object[exc.start] |
| 283 |
if self.stream is not None: |
| 284 |
position = ( |
| 285 |
self.stream_pointer - len(self.raw_buffer) + exc.start |
| 286 |
) |
| 287 |
elif self.stream is not None: |
| 288 |
position = ( |
| 289 |
self.stream_pointer - len(self.raw_buffer) + exc.start |
| 290 |
) |
| 291 |
else: |
| 292 |
position = exc.start |
| 293 |
raise ReaderError( |
| 294 |
self.name, position, character, exc.encoding, exc.reason |
| 295 |
) |
| 296 |
else: |
| 297 |
data = self.raw_buffer |
| 298 |
converted = len(data) |
| 299 |
self.check_printable(data) |
| 300 |
self.buffer += data |
| 301 |
self.raw_buffer = self.raw_buffer[converted:] |
| 302 |
if self.eof: |
| 303 |
self.buffer += "\0" |
| 304 |
self.raw_buffer = None |
| 305 |
break |
| 306 |
|
| 307 |
def update_raw(self, size=None): |
| 308 |
# type: (Optional[int]) -> None |
| 309 |
if size is None: |
| 310 |
size = 4096 if PY3 else 1024 |
| 311 |
data = self.stream.read(size) |
| 312 |
if self.raw_buffer is None: |
| 313 |
self.raw_buffer = data |
| 314 |
else: |
| 315 |
self.raw_buffer += data |
| 316 |
self.stream_pointer += len(data) |
| 317 |
if not data: |
| 318 |
self.eof = True |
| 319 |
|
| 320 |
|
| 321 |
# try: |
| 322 |
# import psyco |
| 323 |
# psyco.bind(Reader) |
| 324 |
# except ImportError: |
| 325 |
# pass |