1 # This module contains abstractions for the input stream. You don't have to
2 # looks further, there are no pretty code.
4 # We define two classes here.
6 # Mark(source, line, column)
7 # It's just a record and its only use is producing nice error messages.
8 # Parser does not use it for any other purposes.
10 # Reader(source, data)
11 # Reader determines the encoding of `data` and converts it to unicode.
12 # Reader provides the following methods and attributes:
13 # reader.peek(length=1) - return the next `length` characters
14 # reader.forward(length=1) - move the current position to `length` characters.
15 # reader.index - the number of the current character.
16 # reader.line, stream.column - the line and the column of the current character.
18 __all__
= ['Reader', 'ReaderError']
20 from error
import YAMLError
, Mark
24 # Unfortunately, codec functions in Python 2.3 does not support the `finish`
25 # arguments, so we have to write our own wrappers.
28 codecs
.utf_8_decode('', 'strict', False)
29 from codecs
import utf_8_decode
, utf_16_le_decode
, utf_16_be_decode
33 def utf_16_le_decode(data
, errors
, finish
=False):
34 if not finish
and len(data
) % 2 == 1:
36 return codecs
.utf_16_le_decode(data
, errors
)
38 def utf_16_be_decode(data
, errors
, finish
=False):
39 if not finish
and len(data
) % 2 == 1:
41 return codecs
.utf_16_be_decode(data
, errors
)
43 def utf_8_decode(data
, errors
, finish
=False):
45 # We are trying to remove a possible incomplete multibyte character
46 # from the suffix of the data.
47 # The first byte of a multi-byte sequence is in the range 0xc0 to 0xfd.
48 # All further bytes are in the range 0x80 to 0xbf.
49 # UTF-8 encoded UCS characters may be up to six bytes long.
51 while count
< 5 and count
< len(data
) \
52 and '\x80' <= data
[-count
-1] <= '\xBF':
54 if count
< 5 and count
< len(data
) \
55 and '\xC0' <= data
[-count
-1] <= '\xFD':
56 data
= data
[:-count
-1]
57 return codecs
.utf_8_decode(data
, errors
)
59 class ReaderError(YAMLError
):
61 def __init__(self
, name
, position
, character
, encoding
, reason
):
63 self
.character
= character
64 self
.position
= position
65 self
.encoding
= encoding
69 if isinstance(self
.character
, str):
70 return "'%s' codec can't decode byte #x%02x: %s\n" \
71 " in \"%s\", position %d" \
72 % (self
.encoding
, ord(self
.character
), self
.reason
,
73 self
.name
, self
.position
)
75 return "unacceptable character #x%04x: %s\n" \
76 " in \"%s\", position %d" \
77 % (ord(self
.character
), self
.reason
,
78 self
.name
, self
.position
)
82 # - determines the data encoding and converts it to unicode,
83 # - checks if characters are in allowed range,
84 # - adds '\0' to the end.
88 # - a `unicode` object,
89 # - a file-like object with its `read` method returning `str`,
90 # - a file-like object with its `read` method returning `unicode`.
92 # Yeah, it's ugly and slow.
94 def __init__(self
, data
):
97 self
.stream_pointer
= 0
101 self
.raw_buffer
= None
102 self
.raw_decode
= None
107 if isinstance(data
, unicode):
108 self
.name
= "<unicode string>"
109 self
.check_printable(data
)
110 self
.buffer = data
+u
'\0'
111 elif isinstance(data
, str):
112 self
.name
= "<string>"
113 self
.raw_buffer
= data
114 self
.determine_encoding()
117 self
.name
= getattr(data
, 'name', "<file>")
120 self
.determine_encoding()
122 def peek(self
, index
=0):
123 if self
.pointer
+index
+1 >= len(self
.buffer):
125 return self
.buffer[self
.pointer
+index
]
127 def prefix(self
, length
=1):
128 if self
.pointer
+length
>= len(self
.buffer):
130 return self
.buffer[self
.pointer
:self
.pointer
+length
]
132 def forward(self
, length
=1):
133 if self
.pointer
+length
+1 >= len(self
.buffer):
134 self
.update(length
+1)
135 for k
in range(length
):
136 ch
= self
.buffer[self
.pointer
]
139 if ch
in u
'\n\x85\u2028\u2029' \
140 or (ch
== u
'\r' and self
.buffer[self
.pointer
+1] != u
'\n'):
143 elif ch
!= u
'\uFEFF':
147 if self
.stream
is None:
148 return Mark(self
.name
, self
.index
, self
.line
, self
.column
,
149 self
.buffer, self
.pointer
)
151 return Mark(self
.name
, self
.index
, self
.line
, self
.column
,
154 def determine_encoding(self
):
155 while not self
.eof
and len(self
.raw_buffer
) < 2:
157 if not isinstance(self
.raw_buffer
, unicode):
158 if self
.raw_buffer
.startswith(codecs
.BOM_UTF16_LE
):
159 self
.raw_decode
= utf_16_le_decode
160 self
.encoding
= 'utf-16-le'
161 elif self
.raw_buffer
.startswith(codecs
.BOM_UTF16_BE
):
162 self
.raw_decode
= utf_16_be_decode
163 self
.encoding
= 'utf-16-be'
165 self
.raw_decode
= utf_8_decode
166 self
.encoding
= 'utf-8'
169 NON_PRINTABLE
= re
.compile(u
'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]')
170 def check_printable(self
, data
):
171 match
= self
.NON_PRINTABLE
.search(data
)
173 character
= match
.group()
174 position
= self
.index
+(len(self
.buffer)-self
.pointer
)+match
.start()
175 raise ReaderError(self
.name
, position
, character
,
176 'unicode', "special characters are not allowed")
178 def update(self
, length
):
179 if self
.raw_buffer
is None:
181 self
.buffer = self
.buffer[self
.pointer
:]
183 while len(self
.buffer) < length
:
186 if self
.raw_decode
is not None:
188 data
, converted
= self
.raw_decode(self
.raw_buffer
,
190 except UnicodeDecodeError, exc
:
191 character
= exc
.object[exc
.start
]
192 if self
.stream
is not None:
193 position
= self
.stream_pointer
-len(self
.raw_buffer
)+exc
.start
196 raise ReaderError(self
.name
, position
, character
,
197 exc
.encoding
, exc
.reason
)
199 data
= self
.raw_buffer
200 converted
= len(data
)
201 self
.check_printable(data
)
203 self
.raw_buffer
= self
.raw_buffer
[converted
:]
206 self
.raw_buffer
= None
209 def update_raw(self
, size
=1024):
210 data
= self
.stream
.read(size
)
212 self
.raw_buffer
+= data
213 self
.stream_pointer
+= len(data
)