source: pyyaml/trunk/lib/yaml/scanner.py @ 136

Revision 136, 50.9 KB checked in by xi, 8 years ago (diff)

Major refactoring.

Line 
1
2# Scanner produces tokens of the following types:
3# STREAM-START
4# STREAM-END
5# DIRECTIVE(name, value)
6# DOCUMENT-START
7# DOCUMENT-END
8# BLOCK-SEQUENCE-START
9# BLOCK-MAPPING-START
10# BLOCK-END
11# FLOW-SEQUENCE-START
12# FLOW-MAPPING-START
13# FLOW-SEQUENCE-END
14# FLOW-MAPPING-END
15# BLOCK-ENTRY
16# FLOW-ENTRY
17# KEY
18# VALUE
19# ALIAS(value)
20# ANCHOR(value)
21# TAG(value)
22# SCALAR(value, plain)
23#
24# Read comments in the Scanner code for more details.
25#
26
27__all__ = ['Scanner', 'ScannerError']
28
29from error import MarkedYAMLError
30from tokens import *
31
32class ScannerError(MarkedYAMLError):
33    pass
34
35class SimpleKey:
36    # See below simple keys treatment.
37
38    def __init__(self, token_number, required, index, line, column, mark):
39        self.token_number = token_number
40        self.required = required
41        self.index = index
42        self.line = line
43        self.column = column
44        self.mark = mark
45
46class Scanner:
47
48    def __init__(self):
49        """Initialize the scanner."""
50        # It is assumed that Scanner and Reader will have a common descendant.
51        # Reader do the dirty work of checking for BOM and converting the
52        # input data to Unicode. It also adds NUL to the end.
53        #
54        # Reader supports the following methods
55        #   self.peek(i=0)       # peek the next i-th character
56        #   self.prefix(l=1)     # peek the next l characters
57        #   self.forward(l=1)    # read the next l characters and move the pointer.
58
59        # Had we reached the end of the stream?
60        self.done = False
61
62        # The number of unclosed '{' and '['. `flow_level == 0` means block
63        # context.
64        self.flow_level = 0
65
66        # List of processed tokens that are not yet emitted.
67        self.tokens = []
68
69        # Add the STREAM-START token.
70        self.fetch_stream_start()
71
72        # Number of tokens that were emitted through the `get_token` method.
73        self.tokens_taken = 0
74
75        # The current indentation level.
76        self.indent = -1
77
78        # Past indentation levels.
79        self.indents = []
80
81        # Variables related to simple keys treatment.
82
83        # A simple key is a key that is not denoted by the '?' indicator.
84        # Example of simple keys:
85        #   ---
86        #   block simple key: value
87        #   ? not a simple key:
88        #   : { flow simple key: value }
89        # We emit the KEY token before all keys, so when we find a potential
90        # simple key, we try to locate the corresponding ':' indicator.
91        # Simple keys should be limited to a single line and 1024 characters.
92
93        # Can a simple key start at the current position? A simple key may
94        # start:
95        # - at the beginning of the line, not counting indentation spaces
96        #       (in block context),
97        # - after '{', '[', ',' (in the flow context),
98        # - after '?', ':', '-' (in the block context).
99        # In the block context, this flag also signifies if a block collection
100        # may start at the current position.
101        self.allow_simple_key = True
102
103        # Keep track of possible simple keys. This is a dictionary. The key
104        # is `flow_level`; there can be no more that one possible simple key
105        # for each level. The value is a SimpleKey record:
106        #   (token_number, required, index, line, column, mark)
107        # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow),
108        # '[', or '{' tokens.
109        self.possible_simple_keys = {}
110
111    # Public methods.
112
113    def check_token(self, *choices):
114        # Check if the next token is one of the given types.
115        while self.need_more_tokens():
116            self.fetch_more_tokens()
117        if self.tokens:
118            if not choices:
119                return True
120            for choice in choices:
121                if isinstance(self.tokens[0], choice):
122                    return True
123        return False
124
125    def peek_token(self):
126        # Return the next token, but do not delete if from the queue.
127        while self.need_more_tokens():
128            self.fetch_more_tokens()
129        if self.tokens:
130            return self.tokens[0]
131
132    def get_token(self):
133        # Return the next token.
134        while self.need_more_tokens():
135            self.fetch_more_tokens()
136        if self.tokens:
137            self.tokens_taken += 1
138            return self.tokens.pop(0)
139
140    def __iter__(self):
141        # Iterator protocol.
142        while self.need_more_tokens():
143            self.fetch_more_tokens()
144        while self.tokens:
145            self.tokens_taken += 1
146            yield self.tokens.pop(0)
147            while self.need_more_tokens():
148                self.fetch_more_tokens()
149
150    # Private methods.
151
152    def need_more_tokens(self):
153        if self.done:
154            return False
155        if not self.tokens:
156            return True
157        # The current token may be a potential simple key, so we
158        # need to look further.
159        self.stale_possible_simple_keys()
160        if self.next_possible_simple_key() == self.tokens_taken:
161            return True
162
163    def fetch_more_tokens(self):
164
165        # Eat whitespaces and comments until we reach the next token.
166        self.scan_to_next_token()
167
168        # Remove obsolete possible simple keys.
169        self.stale_possible_simple_keys()
170
171        # Compare the current indentation and column. It may add some tokens
172        # and decrease the current indentation level.
173        self.unwind_indent(self.column)
174
175        # Peek the next character.
176        ch = self.peek()
177
178        # Is it the end of stream?
179        if ch == u'\0':
180            return self.fetch_stream_end()
181
182        # Is it a directive?
183        if ch == u'%' and self.check_directive():
184            return self.fetch_directive()
185
186        # Is it the document start?
187        if ch == u'-' and self.check_document_start():
188            return self.fetch_document_start()
189
190        # Is it the document end?
191        if ch == u'.' and self.check_document_end():
192            return self.fetch_document_end()
193
194        # TODO: support for BOM within a stream.
195        #if ch == u'\uFEFF':
196        #    return self.fetch_bom()    <-- issue BOMToken
197
198        # Note: the order of the following checks is NOT significant.
199
200        # Is it the flow sequence start indicator?
201        if ch == u'[':
202            return self.fetch_flow_sequence_start()
203
204        # Is it the flow mapping start indicator?
205        if ch == u'{':
206            return self.fetch_flow_mapping_start()
207
208        # Is it the flow sequence end indicator?
209        if ch == u']':
210            return self.fetch_flow_sequence_end()
211
212        # Is it the flow mapping end indicator?
213        if ch == u'}':
214            return self.fetch_flow_mapping_end()
215
216        # Is it the flow entry indicator?
217        if ch in u',':
218            return self.fetch_flow_entry()
219
220        # Is it the block entry indicator?
221        if ch in u'-' and self.check_block_entry():
222            return self.fetch_block_entry()
223
224        # Is it the key indicator?
225        if ch == u'?' and self.check_key():
226            return self.fetch_key()
227
228        # Is it the value indicator?
229        if ch == u':' and self.check_value():
230            return self.fetch_value()
231
232        # Is it an alias?
233        if ch == u'*':
234            return self.fetch_alias()
235
236        # Is it an anchor?
237        if ch == u'&':
238            return self.fetch_anchor()
239
240        # Is it a tag?
241        if ch == u'!':
242            return self.fetch_tag()
243
244        # Is it a literal scalar?
245        if ch == u'|' and not self.flow_level:
246            return self.fetch_literal()
247
248        # Is it a folded scalar?
249        if ch == u'>' and not self.flow_level:
250            return self.fetch_folded()
251
252        # Is it a single quoted scalar?
253        if ch == u'\'':
254            return self.fetch_single()
255
256        # Is it a double quoted scalar?
257        if ch == u'\"':
258            return self.fetch_double()
259
260        # It must be a plain scalar then.
261        if self.check_plain():
262            return self.fetch_plain()
263
264        # No? It's an error. Let's produce a nice error message.
265        raise ScannerError("while scanning for the next token", None,
266                "found character %r that cannot start any token"
267                % ch.encode('utf-8'), self.get_mark())
268
269    # Simple keys treatment.
270
271    def next_possible_simple_key(self):
272        # Return the number of the nearest possible simple key. Actually we
273        # don't need to loop through the whole dictionary. We may replace it
274        # with the following code:
275        #   if not self.possible_simple_keys:
276        #       return None
277        #   return self.possible_simple_keys[
278        #           min(self.possible_simple_keys.keys())].token_number
279        min_token_number = None
280        for level in self.possible_simple_keys:
281            key = self.possible_simple_keys[level]
282            if min_token_number is None or key.token_number < min_token_number:
283                min_token_number = key.token_number
284        return min_token_number
285
286    def stale_possible_simple_keys(self):
287        # Remove entries that are no longer possible simple keys. According to
288        # the YAML specification, simple keys
289        # - should be limited to a single line,
290        # - should be no longer than 1024 characters.
291        # Disabling this procedure will allow simple keys of any length and
292        # height (may cause problems if indentation is broken though).
293        for level in self.possible_simple_keys.keys():
294            key = self.possible_simple_keys[level]
295            if key.line != self.line  \
296                    or self.index-key.index > 1024:
297                if key.required:
298                    raise ScannerError("while scanning a simple key", key.mark,
299                            "could not found expected ':'", self.get_mark())
300                del self.possible_simple_keys[level]
301
302    def save_possible_simple_key(self):
303        # The next token may start a simple key. We check if it's possible
304        # and save its position. This function is called for
305        #   ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'.
306
307        # Check if a simple key is required at the current position.
308        required = not self.flow_level and self.indent == self.column
309
310        # A simple key is required only if it is the first token in the current
311        # line. Therefore it is always allowed.
312        assert self.allow_simple_key or not required
313
314        # The next token might be a simple key. Let's save it's number and
315        # position.
316        if self.allow_simple_key:
317            self.remove_possible_simple_key()
318            token_number = self.tokens_taken+len(self.tokens)
319            key = SimpleKey(token_number, required,
320                    self.index, self.line, self.column, self.get_mark())
321            self.possible_simple_keys[self.flow_level] = key
322
323    def remove_possible_simple_key(self):
324        # Remove the saved possible key position at the current flow level.
325        if self.flow_level in self.possible_simple_keys:
326            key = self.possible_simple_keys[self.flow_level]
327           
328            # I don't think it's possible, but I could be wrong.
329            assert not key.required
330            #if key.required:
331            #    raise ScannerError("while scanning a simple key", key.mark,
332            #            "could not found expected ':'", self.get_mark())
333
334    # Indentation functions.
335
336    def unwind_indent(self, column):
337
338        ## In flow context, tokens should respect indentation.
339        ## Actually the condition should be `self.indent >= column` according to
340        ## the spec. But this condition will prohibit intuitively correct
341        ## constructions such as
342        ## key : {
343        ## }
344        #if self.flow_level and self.indent > column:
345        #    raise ScannerError(None, None,
346        #            "invalid intendation or unclosed '[' or '{'",
347        #            self.get_mark())
348
349        # In the flow context, indentation is ignored. We make the scanner less
350        # restrictive then specification requires.
351        if self.flow_level:
352            return
353
354        # In block context, we may need to issue the BLOCK-END tokens.
355        while self.indent > column:
356            mark = self.get_mark()
357            self.indent = self.indents.pop()
358            self.tokens.append(BlockEndToken(mark, mark))
359
360    def add_indent(self, column):
361        # Check if we need to increase indentation.
362        if self.indent < column:
363            self.indents.append(self.indent)
364            self.indent = column
365            return True
366        return False
367
368    # Fetchers.
369
370    def fetch_stream_start(self):
371        # We always add STREAM-START as the first token and STREAM-END as the
372        # last token.
373
374        # Read the token.
375        mark = self.get_mark()
376       
377        # Add STREAM-START.
378        self.tokens.append(StreamStartToken(mark, mark,
379            encoding=self.encoding))
380       
381
382    def fetch_stream_end(self):
383
384        # Set the current intendation to -1.
385        self.unwind_indent(-1)
386
387        # Reset everything (not really needed).
388        self.allow_simple_key = False
389        self.possible_simple_keys = {}
390
391        # Read the token.
392        mark = self.get_mark()
393       
394        # Add STREAM-END.
395        self.tokens.append(StreamEndToken(mark, mark))
396
397        # The steam is finished.
398        self.done = True
399
400    def fetch_directive(self):
401       
402        # Set the current intendation to -1.
403        self.unwind_indent(-1)
404
405        # Reset simple keys.
406        self.remove_possible_simple_key()
407        self.allow_simple_key = False
408
409        # Scan and add DIRECTIVE.
410        self.tokens.append(self.scan_directive())
411
412    def fetch_document_start(self):
413        self.fetch_document_indicator(DocumentStartToken)
414
415    def fetch_document_end(self):
416        self.fetch_document_indicator(DocumentEndToken)
417
418    def fetch_document_indicator(self, TokenClass):
419
420        # Set the current intendation to -1.
421        self.unwind_indent(-1)
422
423        # Reset simple keys. Note that there could not be a block collection
424        # after '---'.
425        self.remove_possible_simple_key()
426        self.allow_simple_key = False
427
428        # Add DOCUMENT-START or DOCUMENT-END.
429        start_mark = self.get_mark()
430        self.forward(3)
431        end_mark = self.get_mark()
432        self.tokens.append(TokenClass(start_mark, end_mark))
433
434    def fetch_flow_sequence_start(self):
435        self.fetch_flow_collection_start(FlowSequenceStartToken)
436
437    def fetch_flow_mapping_start(self):
438        self.fetch_flow_collection_start(FlowMappingStartToken)
439
440    def fetch_flow_collection_start(self, TokenClass):
441
442        # '[' and '{' may start a simple key.
443        self.save_possible_simple_key()
444
445        # Increase the flow level.
446        self.flow_level += 1
447
448        # Simple keys are allowed after '[' and '{'.
449        self.allow_simple_key = True
450
451        # Add FLOW-SEQUENCE-START or FLOW-MAPPING-START.
452        start_mark = self.get_mark()
453        self.forward()
454        end_mark = self.get_mark()
455        self.tokens.append(TokenClass(start_mark, end_mark))
456
457    def fetch_flow_sequence_end(self):
458        self.fetch_flow_collection_end(FlowSequenceEndToken)
459
460    def fetch_flow_mapping_end(self):
461        self.fetch_flow_collection_end(FlowMappingEndToken)
462
463    def fetch_flow_collection_end(self, TokenClass):
464
465        # Reset possible simple key on the current level.
466        self.remove_possible_simple_key()
467
468        # Decrease the flow level.
469        self.flow_level -= 1
470
471        # No simple keys after ']' or '}'.
472        self.allow_simple_key = False
473
474        # Add FLOW-SEQUENCE-END or FLOW-MAPPING-END.
475        start_mark = self.get_mark()
476        self.forward()
477        end_mark = self.get_mark()
478        self.tokens.append(TokenClass(start_mark, end_mark))
479
480    def fetch_flow_entry(self):
481
482        # Simple keys are allowed after ','.
483        self.allow_simple_key = True
484
485        # Reset possible simple key on the current level.
486        self.remove_possible_simple_key()
487
488        # Add FLOW-ENTRY.
489        start_mark = self.get_mark()
490        self.forward()
491        end_mark = self.get_mark()
492        self.tokens.append(FlowEntryToken(start_mark, end_mark))
493
494    def fetch_block_entry(self):
495
496        # Block context needs additional checks.
497        if not self.flow_level:
498
499            # Are we allowed to start a new entry?
500            if not self.allow_simple_key:
501                raise ScannerError(None, None,
502                        "sequence entries are not allowed here",
503                        self.get_mark())
504
505            # We may need to add BLOCK-SEQUENCE-START.
506            if self.add_indent(self.column):
507                mark = self.get_mark()
508                self.tokens.append(BlockSequenceStartToken(mark, mark))
509
510        # It's an error for the block entry to occur in the flow context,
511        # but we let the parser detect this.
512        else:
513            pass
514
515        # Simple keys are allowed after '-'.
516        self.allow_simple_key = True
517
518        # Reset possible simple key on the current level.
519        self.remove_possible_simple_key()
520
521        # Add BLOCK-ENTRY.
522        start_mark = self.get_mark()
523        self.forward()
524        end_mark = self.get_mark()
525        self.tokens.append(BlockEntryToken(start_mark, end_mark))
526
527    def fetch_key(self):
528       
529        # Block context needs additional checks.
530        if not self.flow_level:
531
532            # Are we allowed to start a key (not nessesary a simple)?
533            if not self.allow_simple_key:
534                raise ScannerError(None, None,
535                        "mapping keys are not allowed here",
536                        self.get_mark())
537
538            # We may need to add BLOCK-MAPPING-START.
539            if self.add_indent(self.column):
540                mark = self.get_mark()
541                self.tokens.append(BlockMappingStartToken(mark, mark))
542
543        # Simple keys are allowed after '?' in the block context.
544        self.allow_simple_key = not self.flow_level
545
546        # Reset possible simple key on the current level.
547        self.remove_possible_simple_key()
548
549        # Add KEY.
550        start_mark = self.get_mark()
551        self.forward()
552        end_mark = self.get_mark()
553        self.tokens.append(KeyToken(start_mark, end_mark))
554
555    def fetch_value(self):
556
557        # Do we determine a simple key?
558        if self.flow_level in self.possible_simple_keys:
559
560            # Add KEY.
561            key = self.possible_simple_keys[self.flow_level]
562            del self.possible_simple_keys[self.flow_level]
563            self.tokens.insert(key.token_number-self.tokens_taken,
564                    KeyToken(key.mark, key.mark))
565
566            # If this key starts a new block mapping, we need to add
567            # BLOCK-MAPPING-START.
568            if not self.flow_level:
569                if self.add_indent(key.column):
570                    self.tokens.insert(key.token_number-self.tokens_taken,
571                            BlockMappingStartToken(key.mark, key.mark))
572
573            # There cannot be two simple keys one after another.
574            self.allow_simple_key = False
575
576        # It must be a part of a complex key.
577        else:
578           
579            # Block context needs additional checks.
580            # (Do we really need them? They will be catched by the parser
581            # anyway.)
582            if not self.flow_level:
583
584                # We are allowed to start a complex value if and only if
585                # we can start a simple key.
586                if not self.allow_simple_key:
587                    raise ScannerError(None, None,
588                            "mapping values are not allowed here",
589                            self.get_mark())
590
591            # Simple keys are allowed after ':' in the block context.
592            self.allow_simple_key = not self.flow_level
593
594            # Reset possible simple key on the current level.
595            self.remove_possible_simple_key()
596
597        # Add VALUE.
598        start_mark = self.get_mark()
599        self.forward()
600        end_mark = self.get_mark()
601        self.tokens.append(ValueToken(start_mark, end_mark))
602
603    def fetch_alias(self):
604
605        # ALIAS could be a simple key.
606        self.save_possible_simple_key()
607
608        # No simple keys after ALIAS.
609        self.allow_simple_key = False
610
611        # Scan and add ALIAS.
612        self.tokens.append(self.scan_anchor(AliasToken))
613
614    def fetch_anchor(self):
615
616        # ANCHOR could start a simple key.
617        self.save_possible_simple_key()
618
619        # No simple keys after ANCHOR.
620        self.allow_simple_key = False
621
622        # Scan and add ANCHOR.
623        self.tokens.append(self.scan_anchor(AnchorToken))
624
625    def fetch_tag(self):
626
627        # TAG could start a simple key.
628        self.save_possible_simple_key()
629
630        # No simple keys after TAG.
631        self.allow_simple_key = False
632
633        # Scan and add TAG.
634        self.tokens.append(self.scan_tag())
635
636    def fetch_literal(self):
637        self.fetch_block_scalar(style='|')
638
639    def fetch_folded(self):
640        self.fetch_block_scalar(style='>')
641
642    def fetch_block_scalar(self, style):
643
644        # A simple key may follow a block scalar.
645        self.allow_simple_key = True
646
647        # Reset possible simple key on the current level.
648        self.remove_possible_simple_key()
649
650        # Scan and add SCALAR.
651        self.tokens.append(self.scan_block_scalar(style))
652
653    def fetch_single(self):
654        self.fetch_flow_scalar(style='\'')
655
656    def fetch_double(self):
657        self.fetch_flow_scalar(style='"')
658
659    def fetch_flow_scalar(self, style):
660
661        # A flow scalar could be a simple key.
662        self.save_possible_simple_key()
663
664        # No simple keys after flow scalars.
665        self.allow_simple_key = False
666
667        # Scan and add SCALAR.
668        self.tokens.append(self.scan_flow_scalar(style))
669
670    def fetch_plain(self):
671
672        # A plain scalar could be a simple key.
673        self.save_possible_simple_key()
674
675        # No simple keys after plain scalars. But note that `scan_plain` will
676        # change this flag if the scan is finished at the beginning of the
677        # line.
678        self.allow_simple_key = False
679
680        # Scan and add SCALAR. May change `allow_simple_key`.
681        self.tokens.append(self.scan_plain())
682
683    # Checkers.
684
685    def check_directive(self):
686
687        # DIRECTIVE:        ^ '%' ...
688        # The '%' indicator is already checked.
689        if self.column == 0:
690            return True
691
692    def check_document_start(self):
693
694        # DOCUMENT-START:   ^ '---' (' '|'\n')
695        if self.column == 0:
696            if self.prefix(3) == u'---'  \
697                    and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
698                return True
699
700    def check_document_end(self):
701
702        # DOCUMENT-END:     ^ '...' (' '|'\n')
703        if self.column == 0:
704            prefix = self.peek(4)
705            if self.prefix(3) == u'...'  \
706                    and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
707                return True
708
709    def check_block_entry(self):
710
711        # BLOCK-ENTRY:      '-' (' '|'\n')
712        return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
713
714    def check_key(self):
715
716        # KEY(flow context):    '?'
717        if self.flow_level:
718            return True
719
720        # KEY(block context):   '?' (' '|'\n')
721        else:
722            return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
723
724    def check_value(self):
725
726        # VALUE(flow context):  ':'
727        if self.flow_level:
728            return True
729
730        # VALUE(block context): ':' (' '|'\n')
731        else:
732            return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
733
734    def check_plain(self):
735
736        # A plain scalar may start with any non-space character except:
737        #   '-', '?', ':', ',', '[', ']', '{', '}',
738        #   '#', '&', '*', '!', '|', '>', '\'', '\"',
739        #   '%', '@', '`'.
740        #
741        # It may also start with
742        #   '-', '?', ':'
743        # if it is followed by a non-space character.
744        #
745        # Note that we limit the last rule to the block context (except the
746        # '-' character) because we want the flow context to be space
747        # independent.
748        ch = self.peek()
749        return ch not in u'\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`'  \
750                or (self.peek(1) not in u'\0 \t\r\n\x85\u2028\u2029'
751                        and (ch == u'-' or (not self.flow_level and ch in u'?:')))
752
753    # Scanners.
754
755    def scan_to_next_token(self):
756        # We ignore spaces, line breaks and comments.
757        # If we find a line break in the block context, we set the flag
758        # `allow_simple_key` on.
759        # The byte order mark is stripped if it's the first character in the
760        # stream. We do not yet support BOM inside the stream as the
761        # specification requires. Any such mark will be considered as a part
762        # of the document.
763        #
764        # TODO: We need to make tab handling rules more sane. A good rule is
765        #   Tabs cannot precede tokens
766        #   BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END,
767        #   KEY(block), VALUE(block), BLOCK-ENTRY
768        # So the checking code is
769        #   if <TAB>:
770        #       self.allow_simple_keys = False
771        # We also need to add the check for `allow_simple_keys == True` to
772        # `unwind_indent` before issuing BLOCK-END.
773        # Scanners for block, flow, and plain scalars need to be modified.
774
775        if self.index == 0 and self.peek() == u'\uFEFF':
776            self.forward()
777        found = False
778        while not found:
779            while self.peek() == u' ':
780                self.forward()
781            if self.peek() == u'#':
782                while self.peek() not in u'\0\r\n\x85\u2028\u2029':
783                    self.forward()
784            if self.scan_line_break():
785                if not self.flow_level:
786                    self.allow_simple_key = True
787            else:
788                found = True
789
790    def scan_directive(self):
791        # See the specification for details.
792        start_mark = self.get_mark()
793        self.forward()
794        name = self.scan_directive_name(start_mark)
795        value = None
796        if name == u'YAML':
797            value = self.scan_yaml_directive_value(start_mark)
798            end_mark = self.get_mark()
799        elif name == u'TAG':
800            value = self.scan_tag_directive_value(start_mark)
801            end_mark = self.get_mark()
802        else:
803            end_mark = self.get_mark()
804            while self.peek() not in u'\0\r\n\x85\u2028\u2029':
805                self.forward()
806        self.scan_directive_ignored_line(start_mark)
807        return DirectiveToken(name, value, start_mark, end_mark)
808
809    def scan_directive_name(self, start_mark):
810        # See the specification for details.
811        length = 0
812        ch = self.peek(length)
813        while u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'  \
814                or ch in u'-_':
815            length += 1
816            ch = self.peek(length)
817        if not length:
818            raise ScannerError("while scanning a directive", start_mark,
819                    "expected alphabetic or numeric character, but found %r"
820                    % ch.encode('utf-8'), self.get_mark())
821        value = self.prefix(length)
822        self.forward(length)
823        ch = self.peek()
824        if ch not in u'\0 \r\n\x85\u2028\u2029':
825            raise ScannerError("while scanning a directive", start_mark,
826                    "expected alphabetic or numeric character, but found %r"
827                    % ch.encode('utf-8'), self.get_mark())
828        return value
829
830    def scan_yaml_directive_value(self, start_mark):
831        # See the specification for details.
832        while self.peek() == u' ':
833            self.forward()
834        major = self.scan_yaml_directive_number(start_mark)
835        if self.peek() != '.':
836            raise ScannerError("while scanning a directive", start_mark,
837                    "expected a digit or '.', but found %r"
838                    % self.peek().encode('utf-8'),
839                    self.get_mark())
840        self.forward()
841        minor = self.scan_yaml_directive_number(start_mark)
842        if self.peek() not in u'\0 \r\n\x85\u2028\u2029':
843            raise ScannerError("while scanning a directive", start_mark,
844                    "expected a digit or ' ', but found %r"
845                    % self.peek().encode('utf-8'),
846                    self.get_mark())
847        return (major, minor)
848
849    def scan_yaml_directive_number(self, start_mark):
850        # See the specification for details.
851        ch = self.peek()
852        if not (u'0' <= ch <= '9'):
853            raise ScannerError("while scanning a directive", start_mark,
854                    "expected a digit, but found %r" % ch.encode('utf-8'),
855                    self.get_mark())
856        length = 0
857        while u'0' <= self.peek(length) <= u'9':
858            length += 1
859        value = int(self.prefix(length))
860        self.forward(length)
861        return value
862
863    def scan_tag_directive_value(self, start_mark):
864        # See the specification for details.
865        while self.peek() == u' ':
866            self.forward()
867        handle = self.scan_tag_directive_handle(start_mark)
868        while self.peek() == u' ':
869            self.forward()
870        prefix = self.scan_tag_directive_prefix(start_mark)
871        return (handle, prefix)
872
873    def scan_tag_directive_handle(self, start_mark):
874        # See the specification for details.
875        value = self.scan_tag_handle('directive', start_mark)
876        ch = self.peek()
877        if ch != u' ':
878            raise ScannerError("while scanning a directive", start_mark,
879                    "expected ' ', but found %r" % ch.encode('utf-8'),
880                    self.get_mark())
881        return value
882
883    def scan_tag_directive_prefix(self, start_mark):
884        # See the specification for details.
885        value = self.scan_tag_uri('directive', start_mark)
886        ch = self.peek()
887        if ch not in u'\0 \r\n\x85\u2028\u2029':
888            raise ScannerError("while scanning a directive", start_mark,
889                    "expected ' ', but found %r" % ch.encode('utf-8'),
890                    self.get_mark())
891        return value
892
893    def scan_directive_ignored_line(self, start_mark):
894        # See the specification for details.
895        while self.peek() == u' ':
896            self.forward()
897        if self.peek() == u'#':
898            while self.peek() not in u'\0\r\n\x85\u2028\u2029':
899                self.forward()
900        ch = self.peek()
901        if ch not in u'\0\r\n\x85\u2028\u2029':
902            raise ScannerError("while scanning a directive", start_mark,
903                    "expected a comment or a line break, but found %r"
904                        % ch.encode('utf-8'), self.get_mark())
905        self.scan_line_break()
906
907    def scan_anchor(self, TokenClass):
908        # The specification does not restrict characters for anchors and
909        # aliases. This may lead to problems, for instance, the document:
910        #   [ *alias, value ]
911        # can be interpteted in two ways, as
912        #   [ "value" ]
913        # and
914        #   [ *alias , "value" ]
915        # Therefore we restrict aliases to numbers and ASCII letters.
916        start_mark = self.get_mark()
917        indicator = self.peek()
918        if indicator == '*':
919            name = 'alias'
920        else:
921            name = 'anchor'
922        self.forward()
923        length = 0
924        ch = self.peek(length)
925        while u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'  \
926                or ch in u'-_':
927            length += 1
928            ch = self.peek(length)
929        if not length:
930            raise ScannerError("while scanning an %s" % name, start_mark,
931                    "expected alphabetic or numeric character, but found %r"
932                    % ch.encode('utf-8'), self.get_mark())
933        value = self.prefix(length)
934        self.forward(length)
935        ch = self.peek()
936        if ch not in u'\0 \t\r\n\x85\u2028\u2029?:,]}%@`':
937            raise ScannerError("while scanning an %s" % name, start_mark,
938                    "expected alphabetic or numeric character, but found %r"
939                    % ch.encode('utf-8'), self.get_mark())
940        end_mark = self.get_mark()
941        return TokenClass(value, start_mark, end_mark)
942
943    def scan_tag(self):
944        # See the specification for details.
945        start_mark = self.get_mark()
946        ch = self.peek(1)
947        if ch == u'<':
948            handle = None
949            self.forward(2)
950            suffix = self.scan_tag_uri('tag', start_mark)
951            if self.peek() != u'>':
952                raise ScannerError("while parsing a tag", start_mark,
953                        "expected '>', but found %r" % self.peek().encode('utf-8'),
954                        self.get_mark())
955            self.forward()
956        elif ch in u'\0 \t\r\n\x85\u2028\u2029':
957            handle = None
958            suffix = u'!'
959            self.forward()
960        else:
961            length = 1
962            use_handle = False
963            while ch not in u'\0 \r\n\x85\u2028\u2029':
964                if ch == u'!':
965                    use_handle = True
966                    break
967                length += 1
968                ch = self.peek(length)
969            handle = u'!'
970            if use_handle:
971                handle = self.scan_tag_handle('tag', start_mark)
972            else:
973                handle = u'!'
974                self.forward()
975            suffix = self.scan_tag_uri('tag', start_mark)
976        ch = self.peek()
977        if ch not in u'\0 \r\n\x85\u2028\u2029':
978            raise ScannerError("while scanning a tag", start_mark,
979                    "expected ' ', but found %r" % ch.encode('utf-8'),
980                    self.get_mark())
981        value = (handle, suffix)
982        end_mark = self.get_mark()
983        return TagToken(value, start_mark, end_mark)
984
985    def scan_block_scalar(self, style):
986        # See the specification for details.
987
988        if style == '>':
989            folded = True
990        else:
991            folded = False
992
993        chunks = []
994        start_mark = self.get_mark()
995
996        # Scan the header.
997        self.forward()
998        chomping, increment = self.scan_block_scalar_indicators(start_mark)
999        self.scan_block_scalar_ignored_line(start_mark)
1000
1001        # Determine the indentation level and go to the first non-empty line.
1002        min_indent = self.indent+1
1003        if min_indent < 1:
1004            min_indent = 1
1005        if increment is None:
1006            breaks, max_indent, end_mark = self.scan_block_scalar_indentation()
1007            indent = max(min_indent, max_indent)
1008        else:
1009            indent = min_indent+increment-1
1010            breaks, end_mark = self.scan_block_scalar_breaks(indent)
1011        line_break = u''
1012
1013        # Scan the inner part of the block scalar.
1014        while self.column == indent and self.peek() != u'\0':
1015            chunks.extend(breaks)
1016            leading_non_space = self.peek() not in u' \t'
1017            length = 0
1018            while self.peek(length) not in u'\0\r\n\x85\u2028\u2029':
1019                length += 1
1020            chunks.append(self.prefix(length))
1021            self.forward(length)
1022            line_break = self.scan_line_break()
1023            breaks, end_mark = self.scan_block_scalar_breaks(indent)
1024            if self.column == indent and self.peek() != u'\0':
1025
1026                # Unfortunately, folding rules are ambiguous.
1027                #
1028                # This is the folding according to the specification:
1029               
1030                if folded and line_break == u'\n'   \
1031                        and leading_non_space and self.peek() not in u' \t':
1032                    if not breaks:
1033                        chunks.append(u' ')
1034                else:
1035                    chunks.append(line_break)
1036               
1037                # This is Clark Evans's interpretation (also in the spec
1038                # examples):
1039                #
1040                #if folded and line_break == u'\n':
1041                #    if not breaks:
1042                #        if self.peek() not in ' \t':
1043                #            chunks.append(u' ')
1044                #        else:
1045                #            chunks.append(line_break)
1046                #else:
1047                #    chunks.append(line_break)
1048            else:
1049                break
1050
1051        # Chomp the tail.
1052        if chomping is not False:
1053            chunks.append(line_break)
1054        if chomping is True:
1055            chunks.extend(breaks)
1056
1057        # We are done.
1058        return ScalarToken(u''.join(chunks), False, start_mark, end_mark,
1059                style)
1060
1061    def scan_block_scalar_indicators(self, start_mark):
1062        # See the specification for details.
1063        chomping = None
1064        increment = None
1065        ch = self.peek()
1066        if ch in u'+-':
1067            if ch == '+':
1068                chomping = True
1069            else:
1070                chomping = False
1071            self.forward()
1072            ch = self.peek()
1073            if ch in u'0123456789':
1074                increment = int(ch)
1075                if increment == 0:
1076                    raise ScannerError("while scanning a block scalar", start_mark,
1077                            "expected indentation indicator in the range 1-9, but found 0",
1078                            self.get_mark())
1079                self.forward()
1080        elif ch in u'0123456789':
1081            increment = int(ch)
1082            if increment == 0:
1083                raise ScannerError("while scanning a block scalar", start_mark,
1084                        "expected indentation indicator in the range 1-9, but found 0",
1085                        self.get_mark())
1086            self.forward()
1087            ch = self.peek()
1088            if ch in u'+-':
1089                if ch == '+':
1090                    chomping = True
1091                else:
1092                    chomping = False
1093                self.forward()
1094        ch = self.peek()
1095        if ch not in u'\0 \r\n\x85\u2028\u2029':
1096            raise ScannerError("while scanning a block scalar", start_mark,
1097                    "expected chomping or indentation indicators, but found %r"
1098                        % ch.encode('utf-8'), self.get_mark())
1099        return chomping, increment
1100
1101    def scan_block_scalar_ignored_line(self, start_mark):
1102        # See the specification for details.
1103        while self.peek() == u' ':
1104            self.forward()
1105        if self.peek() == u'#':
1106            while self.peek() not in u'\0\r\n\x85\u2028\u2029':
1107                self.forward()
1108        ch = self.peek()
1109        if ch not in u'\0\r\n\x85\u2028\u2029':
1110            raise ScannerError("while scanning a block scalar", start_mark,
1111                    "expected a comment or a line break, but found %r"
1112                        % ch.encode('utf-8'), self.get_mark())
1113        self.scan_line_break()
1114
1115    def scan_block_scalar_indentation(self):
1116        # See the specification for details.
1117        chunks = []
1118        max_indent = 0
1119        end_mark = self.get_mark()
1120        while self.peek() in u' \r\n\x85\u2028\u2029':
1121            if self.peek() != u' ':
1122                chunks.append(self.scan_line_break())
1123                end_mark = self.get_mark()
1124            else:
1125                self.forward()
1126                if self.column > max_indent:
1127                    max_indent = self.column
1128        return chunks, max_indent, end_mark
1129
1130    def scan_block_scalar_breaks(self, indent):
1131        # See the specification for details.
1132        chunks = []
1133        end_mark = self.get_mark()
1134        while self.column < indent and self.peek() == u' ':
1135            self.forward()
1136        while self.peek() in u'\r\n\x85\u2028\u2029':
1137            chunks.append(self.scan_line_break())
1138            end_mark = self.get_mark()
1139            while self.column < indent and self.peek() == u' ':
1140                self.forward()
1141        return chunks, end_mark
1142
1143    def scan_flow_scalar(self, style):
1144        # See the specification for details.
1145        # Note that we loose indentation rules for quoted scalars. Quoted
1146        # scalars don't need to adhere indentation because " and ' clearly
1147        # mark the beginning and the end of them. Therefore we are less
1148        # restrictive then the specification requires. We only need to check
1149        # that document separators are not included in scalars.
1150        if style == '"':
1151            double = True
1152        else:
1153            double = False
1154        chunks = []
1155        start_mark = self.get_mark()
1156        quote = self.peek()
1157        self.forward()
1158        chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
1159        while self.peek() != quote:
1160            chunks.extend(self.scan_flow_scalar_spaces(double, start_mark))
1161            chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
1162        self.forward()
1163        end_mark = self.get_mark()
1164        return ScalarToken(u''.join(chunks), False, start_mark, end_mark,
1165                style)
1166
1167    ESCAPE_REPLACEMENTS = {
1168        u'0':   u'\0',
1169        u'a':   u'\x07',
1170        u'b':   u'\x08',
1171        u't':   u'\x09',
1172        u'\t':  u'\x09',
1173        u'n':   u'\x0A',
1174        u'v':   u'\x0B',
1175        u'f':   u'\x0C',
1176        u'r':   u'\x0D',
1177        u'e':   u'\x1B',
1178        u' ':   u'\x20',
1179        u'\"':  u'\"',
1180        u'\\':  u'\\',
1181        u'N':   u'\x85',
1182        u'_':   u'\xA0',
1183        u'L':   u'\u2028',
1184        u'P':   u'\u2029',
1185    }
1186
1187    ESCAPE_CODES = {
1188        u'x':   2,
1189        u'u':   4,
1190        u'U':   8,
1191    }
1192
1193    def scan_flow_scalar_non_spaces(self, double, start_mark):
1194        # See the specification for details.
1195        chunks = []
1196        while True:
1197            length = 0
1198            while self.peek(length) not in u'\'\"\\\0 \t\r\n\x85\u2028\u2029':
1199                length += 1
1200            if length:
1201                chunks.append(self.prefix(length))
1202                self.forward(length)
1203            ch = self.peek()
1204            if not double and ch == u'\'' and self.peek(1) == u'\'':
1205                chunks.append(u'\'')
1206                self.forward(2)
1207            elif (double and ch == u'\'') or (not double and ch in u'\"\\'):
1208                chunks.append(ch)
1209                self.forward()
1210            elif double and ch == u'\\':
1211                self.forward()
1212                ch = self.peek()
1213                if ch in self.ESCAPE_REPLACEMENTS:
1214                    chunks.append(self.ESCAPE_REPLACEMENTS[ch])
1215                    self.forward()
1216                elif ch in self.ESCAPE_CODES:
1217                    length = self.ESCAPE_CODES[ch]
1218                    self.forward()
1219                    for k in range(length):
1220                        if self.peek(k) not in u'0123456789ABCDEFabcdef':
1221                            raise ScannerError("while scanning a double-quoted scalar", start_mark,
1222                                    "expected escape sequence of %d hexdecimal numbers, but found %r" %
1223                                        (length, self.peek(k).encode('utf-8')), self.get_mark())
1224                    code = int(self.prefix(length), 16)
1225                    chunks.append(unichr(code))
1226                    self.forward(length)
1227                elif ch in u'\r\n\x85\u2028\u2029':
1228                    self.scan_line_break()
1229                    chunks.extend(self.scan_flow_scalar_breaks(double, start_mark))
1230                else:
1231                    raise ScannerError("while scanning a double-quoted scalar", start_mark,
1232                            "found unknown escape character %r" % ch.encode('utf-8'), self.get_mark())
1233            else:
1234                return chunks
1235
1236    def scan_flow_scalar_spaces(self, double, start_mark):
1237        # See the specification for details.
1238        chunks = []
1239        length = 0
1240        while self.peek(length) in u' \t':
1241            length += 1
1242        whitespaces = self.prefix(length)
1243        self.forward(length)
1244        ch = self.peek()
1245        if ch == u'\0':
1246            raise ScannerError("while scanning a quoted scalar", start_mark,
1247                    "found unexpected end of stream", self.get_mark())
1248        elif ch in u'\r\n\x85\u2028\u2029':
1249            line_break = self.scan_line_break()
1250            breaks = self.scan_flow_scalar_breaks(double, start_mark)
1251            if line_break != u'\n':
1252                chunks.append(line_break)
1253            elif not breaks:
1254                chunks.append(u' ')
1255            chunks.extend(breaks)
1256        else:
1257            chunks.append(whitespaces)
1258        return chunks
1259
1260    def scan_flow_scalar_breaks(self, double, start_mark):
1261        # See the specification for details.
1262        chunks = []
1263        while True:
1264            # Instead of checking indentation, we check for document
1265            # separators.
1266            prefix = self.prefix(3)
1267            if (prefix == u'---' or prefix == u'...')   \
1268                    and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
1269                raise ScannerError("while scanning a quoted scalar", start_mark,
1270                        "found unexpected document separator", self.get_mark())
1271            while self.peek() in u' \t':
1272                self.forward()
1273            if self.peek() in u'\r\n\x85\u2028\u2029':
1274                chunks.append(self.scan_line_break())
1275            else:
1276                return chunks
1277
1278    def scan_plain(self):
1279        # See the specification for details.
1280        # We add an additional restriction for the flow context:
1281        #   plain scalars in the flow context cannot contain ',', ':' and '?'.
1282        # We also keep track of the `allow_simple_key` flag here.
1283        # Indentation rules are loosed for the flow context.
1284        chunks = []
1285        start_mark = self.get_mark()
1286        end_mark = start_mark
1287        indent = self.indent+1
1288        # We allow zero indentation for scalars, but then we need to check for
1289        # document separators at the beginning of the line.
1290        #if indent == 0:
1291        #    indent = 1
1292        spaces = []
1293        while True:
1294            length = 0
1295            if self.peek() == u'#':
1296                break
1297            while True:
1298                ch = self.peek(length)
1299                if ch in u'\0 \t\r\n\x85\u2028\u2029'   \
1300                        or (not self.flow_level and ch == u':' and
1301                                self.peek(length+1) in u'\0 \t\r\n\x28\u2028\u2029') \
1302                        or (self.flow_level and ch in u',:?[]{}'):
1303                    break
1304                length += 1
1305            if length == 0:
1306                break
1307            self.allow_simple_key = False
1308            chunks.extend(spaces)
1309            chunks.append(self.prefix(length))
1310            self.forward(length)
1311            end_mark = self.get_mark()
1312            spaces = self.scan_plain_spaces(indent, start_mark)
1313            if not spaces or self.peek() == u'#' \
1314                    or (not self.flow_level and self.column < indent):
1315                break
1316        return ScalarToken(u''.join(chunks), True, start_mark, end_mark)
1317
1318    def scan_plain_spaces(self, indent, start_mark):
1319        # See the specification for details.
1320        # The specification is really confusing about tabs in plain scalars.
1321        # We just forbid them completely. Do not use tabs in YAML!
1322        chunks = []
1323        length = 0
1324        while self.peek(length) in u' ':
1325            length += 1
1326        whitespaces = self.prefix(length)
1327        self.forward(length)
1328        ch = self.peek()
1329        if ch in u'\r\n\x85\u2028\u2029':
1330            line_break = self.scan_line_break()
1331            self.allow_simple_key = True
1332            prefix = self.prefix(3)
1333            if (prefix == u'---' or prefix == u'...')   \
1334                    and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
1335                return
1336            breaks = []
1337            while self.peek() in u' \r\n\x85\u2028\u2029':
1338                if self.peek() == ' ':
1339                    self.forward()
1340                else:
1341                    breaks.append(self.scan_line_break())
1342                    prefix = self.prefix(3)
1343                    if (prefix == u'---' or prefix == u'...')   \
1344                            and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
1345                        return
1346            if line_break != u'\n':
1347                chunks.append(line_break)
1348            elif not breaks:
1349                chunks.append(u' ')
1350            chunks.extend(breaks)
1351        elif whitespaces:
1352            chunks.append(whitespaces)
1353        return chunks
1354
1355    def scan_tag_handle(self, name, start_mark):
1356        # See the specification for details.
1357        # For some strange reasons, the specification does not allow '_' in
1358        # tag handles. I have allowed it anyway.
1359        ch = self.peek()
1360        if ch != u'!':
1361            raise ScannerError("while scanning a %s" % name, start_mark,
1362                    "expected '!', but found %r" % ch.encode('utf-8'),
1363                    self.get_mark())
1364        length = 1
1365        ch = self.peek(length)
1366        if ch != u' ':
1367            while u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'  \
1368                    or ch in u'-_':
1369                length += 1
1370                ch = self.peek(length)
1371            if ch != u'!':
1372                self.forward(length)
1373                raise ScannerError("while scanning a %s" % name, start_mark,
1374                        "expected '!', but found %r" % ch.encode('utf-8'),
1375                        self.get_mark())
1376            length += 1
1377        value = self.prefix(length)
1378        self.forward(length)
1379        return value
1380
1381    def scan_tag_uri(self, name, start_mark):
1382        # See the specification for details.
1383        # Note: we do not check if URI is well-formed.
1384        chunks = []
1385        length = 0
1386        ch = self.peek(length)
1387        while u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'  \
1388                or ch in u'-;/?:@&=+$,_.!~*\'()[]%':
1389            if ch == u'%':
1390                chunks.append(self.prefix(length))
1391                self.forward(length)
1392                length = 0
1393                chunks.append(self.scan_uri_escapes(name, start_mark))
1394            else:
1395                length += 1
1396            ch = self.peek(length)
1397        if length:
1398            chunks.append(self.prefix(length))
1399            self.forward(length)
1400            length = 0
1401        if not chunks:
1402            raise ScannerError("while parsing a %s" % name, start_mark,
1403                    "expected URI, but found %r" % ch.encode('utf-8'),
1404                    self.get_mark())
1405        return u''.join(chunks)
1406
1407    def scan_uri_escapes(self, name, start_mark):
1408        # See the specification for details.
1409        bytes = []
1410        mark = self.get_mark()
1411        while self.peek() == u'%':
1412            self.forward()
1413            for k in range(2):
1414                if self.peek(k) not in u'0123456789ABCDEFabcdef':
1415                    raise ScannerError("while scanning a %s" % name, start_mark,
1416                            "expected URI escape sequence of 2 hexdecimal numbers, but found %r" %
1417                                (self.peek(k).encode('utf-8')), self.get_mark())
1418            bytes.append(chr(int(self.prefix(2), 16)))
1419            self.forward(2)
1420        try:
1421            value = unicode(''.join(bytes), 'utf-8')
1422        except UnicodeDecodeError, exc:
1423            raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark)
1424        return value
1425
1426    def scan_line_break(self):
1427        # Transforms:
1428        #   '\r\n'      :   '\n'
1429        #   '\r'        :   '\n'
1430        #   '\n'        :   '\n'
1431        #   '\x85'      :   '\n'
1432        #   '\u2028'    :   '\u2028'
1433        #   '\u2029     :   '\u2029'
1434        #   default     :   ''
1435        ch = self.peek()
1436        if ch in u'\r\n\x85':
1437            if self.prefix(2) == u'\r\n':
1438                self.forward(2)
1439            else:
1440                self.forward()
1441            return u'\n'
1442        elif ch in u'\u2028\u2029':
1443            self.forward()
1444            return ch
1445        return u''
1446
1447#try:
1448#    import psyco
1449#    psyco.bind(Scanner)
1450#except ImportError:
1451#    pass
1452
Note: See TracBrowser for help on using the repository browser.