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