source: pyyaml/trunk/lib/yaml/parser.py @ 130

Revision 130, 22.3 KB checked in by xi, 9 years ago (diff)

Add style information to events generated by Parser.

RevLine 
[43]1
[51]2# YAML can be parsed by an LL(1) parser!
3#
4# We use the following production rules:
[118]5# stream            ::= STREAM-START implicit_document? explicit_document* STREAM-END
[43]6# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END?
7# implicit_document ::= block_node DOCUMENT-END?
8# block_node    ::= ALIAS | properties? block_content
9# flow_node     ::= ALIAS | properties? flow_content
10# properties    ::= TAG ANCHOR? | ANCHOR TAG?
11# block_content     ::= block_collection | flow_collection | SCALAR
12# flow_content      ::= flow_collection | SCALAR
13# block_collection  ::= block_sequence | block_mapping
[51]14# block_sequence    ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
[43]15# block_mapping     ::= BLOCK-MAPPING_START ((KEY block_node_or_indentless_sequence?)? (VALUE block_node_or_indentless_sequence?)?)* BLOCK-END
16# block_node_or_indentless_sequence ::= ALIAS | properties? (block_content | indentless_block_sequence)
[51]17# indentless_block_sequence         ::= (BLOCK-ENTRY block_node?)+
[43]18# flow_collection   ::= flow_sequence | flow_mapping
[51]19# flow_sequence     ::= FLOW-SEQUENCE-START (flow_sequence_entry FLOW-ENTRY)* flow_sequence_entry? FLOW-SEQUENCE-END
20# flow_mapping      ::= FLOW-MAPPING-START (flow_mapping_entry FLOW-ENTRY)* flow_mapping_entry? FLOW-MAPPING-END
21# flow_sequence_entry   ::= flow_node | KEY flow_node? (VALUE flow_node?)?
22# flow_mapping_entry    ::= flow_node | KEY flow_node? (VALUE flow_node?)?
[52]23
24# TODO: support for BOM within a stream.
25# stream ::= (BOM? implicit_document)? (BOM? explicit_document)* STREAM-END
26
[51]27# Note that there is a slight deviation from the specification. We require a
28# non-empty node content if ANCHOR or TAG is specified. This disallow such
29# documents as
30#
31#   key:    !!str   # empty value
32#
33# This is done to prevent ambiguity in parsing tags and aliases:
34#
35#   {   !!perl/YAML::Parser:    value }
36#
37# What is it? Should it be interpreted as
38#   {   ? !<tag:yaml.org,2002:perl/YAML::Parser> '' : value }
39# or
40#   {   ? !<tag:yaml.org,2002:perl/YAML::Parser:> value : '' }
41# Since we disallow non-empty node content, tags are always followed by spaces
42# or line breaks.
[43]43
[51]44# FIRST sets:
[118]45# stream: { STREAM-START }
[43]46# explicit_document: { DIRECTIVE DOCUMENT-START }
[51]47# implicit_document: FIRST(block_node)
[43]48# block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START }
49# flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START }
50# block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
51# flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
52# block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START }
53# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
54# block_sequence: { BLOCK-SEQUENCE-START }
55# block_mapping: { BLOCK-MAPPING-START }
[51]56# block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY }
[43]57# indentless_sequence: { ENTRY }
58# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
59# flow_sequence: { FLOW-SEQUENCE-START }
60# flow_mapping: { FLOW-MAPPING-START }
61# flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
62# flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
63
[57]64__all__ = ['Parser', 'ParserError']
65
[52]66from error import MarkedYAMLError
[46]67from tokens import *
[51]68from events import *
[44]69
[52]70class ParserError(MarkedYAMLError):
71    pass
[44]72
[51]73class Parser:
74    # Since writing an LL(1) parser is a straightforward task, we do not give
75    # many comments here.
[55]76    # Note that we use Python generators. If you rewrite the parser in another
[51]77    # language, you may replace all 'yield'-s with event handler calls.
[44]78
[51]79    DEFAULT_TAGS = {
80        u'!':   u'!',
81        u'!!':  u'tag:yaml.org,2002:',
82    }
[44]83
[46]84    def __init__(self, scanner):
85        self.scanner = scanner
[51]86        self.current_event = None
87        self.yaml_version = None
88        self.tag_handles = {}
89        self.event_generator = self.parse_stream()
[43]90
[51]91    def check(self, *choices):
92        # Check the type of the next event.
93        if self.current_event is None:
94            try:
95                self.current_event = self.event_generator.next()
96            except StopIteration:
97                pass
98        if self.current_event is not None:
99            for choice in choices:
100                if isinstance(self.current_event, choice):
101                    return True
[44]102        return False
103
[53]104    def peek(self):
105        # Get the next event.
106        if self.current_event is None:
107            try:
108                self.current_event = self.event_generator.next()
109            except StopIteration:
110                pass
111        return self.current_event
112
[51]113    def get(self):
114        # Get the next event.
115        if self.current_event is None:
116            try:
117                self.current_event = self.event_generator.next()
118            except StopIteration:
119                pass
120        value = self.current_event
121        self.current_event = None
122        return value
[44]123
[51]124    def __iter__(self):
125        # Iterator protocol.
126        return self.event_generator
[44]127
[43]128    def parse_stream(self):
[118]129        # STREAM-START implicit_document? explicit_document* STREAM-END
[51]130
[118]131        # Parse start of stream.
132        token = self.scanner.get()
[130]133        yield StreamStartEvent(token.start_mark, token.end_mark,
134                encoding=token.encoding)
[118]135
[51]136        # Parse implicit document.
137        if not self.scanner.check(DirectiveToken, DocumentStartToken,
138                StreamEndToken):
139            self.tag_handles = self.DEFAULT_TAGS
[118]140            token = self.scanner.peek()
141            start_mark = end_mark = token.start_mark
[130]142            yield DocumentStartEvent(start_mark, end_mark,
143                    implicit=True)
[51]144            for event in self.parse_block_node():
145                yield event
[118]146            token = self.scanner.peek()
147            start_mark = end_mark = token.start_mark
[130]148            implicit = True
[118]149            while self.scanner.check(DocumentEndToken):
150                token = self.scanner.get()
151                end_mark = token.end_mark
[130]152                implicit = True
153            yield DocumentEndEvent(start_mark, end_mark,
154                    implicit=implicit)
[51]155
156        # Parse explicit documents.
157        while not self.scanner.check(StreamEndToken):
[118]158            token = self.scanner.peek()
159            start_mark = token.start_mark
[130]160            version, tags = self.process_directives()
[51]161            if not self.scanner.check(DocumentStartToken):
162                raise ParserError(None, None,
163                        "expected '<document start>', but found %r"
164                        % self.scanner.peek().id,
[116]165                        self.scanner.peek().start_mark)
[51]166            token = self.scanner.get()
[118]167            end_mark = token.end_mark
[130]168            yield DocumentStartEvent(start_mark, end_mark,
169                    implicit=False, version=version, tags=tags)
[51]170            if self.scanner.check(DirectiveToken,
[47]171                    DocumentStartToken, DocumentEndToken, StreamEndToken):
[116]172                yield self.process_empty_scalar(token.end_mark)
[43]173            else:
[51]174                for event in self.parse_block_node():
175                    yield event
[118]176            token = self.scanner.peek()
177            start_mark = end_mark = token.start_mark
[130]178            implicit=True
[51]179            while self.scanner.check(DocumentEndToken):
[118]180                token = self.scanner.get()
181                end_mark = token.end_mark
[130]182                implicit=False
183            yield DocumentEndEvent(start_mark, end_mark,
184                    implicit=implicit)
[43]185
[51]186        # Parse end of stream.
187        token = self.scanner.get()
[116]188        yield StreamEndEvent(token.start_mark, token.end_mark)
[51]189
190    def process_directives(self):
191        # DIRECTIVE*
192        self.yaml_version = None
193        self.tag_handles = {}
194        while self.scanner.check(DirectiveToken):
195            token = self.scanner.get()
196            if token.name == u'YAML':
197                if self.yaml_version is not None:
198                    raise ParserError(None, None,
[116]199                            "found duplicate YAML directive", token.start_mark)
[51]200                major, minor = token.value
201                if major != 1:
202                    raise ParserError(None, None,
203                            "found incompatible YAML document (version 1.* is required)",
[116]204                            token.start_mark)
[51]205                self.yaml_version = token.value
206            elif token.name == u'TAG':
207                handle, prefix = token.value
208                if handle in self.tag_handles:
209                    raise ParserError(None, None,
210                            "duplicate tag handle %r" % handle.encode('utf-8'),
[116]211                            token.start_mark)
[51]212                self.tag_handles[handle] = prefix
[130]213        if self.tag_handles:
214            value = self.yaml_version, self.tag_handles.copy()
215        else:
216            value = self.yaml_version, None
[51]217        for key in self.DEFAULT_TAGS:
218            if key not in self.tag_handles:
219                self.tag_handles[key] = self.DEFAULT_TAGS[key]
[130]220        return value
[51]221
[43]222    def parse_block_node(self):
[44]223        return self.parse_node(block=True)
[43]224
225    def parse_flow_node(self):
[44]226        return self.parse_node()
[43]227
228    def parse_block_node_or_indentless_sequence(self):
[44]229        return self.parse_node(block=True, indentless_sequence=True)
[43]230
[44]231    def parse_node(self, block=False, indentless_sequence=False):
[51]232        # block_node    ::= ALIAS | properties? block_content
233        # flow_node     ::= ALIAS | properties? flow_content
234        # properties    ::= TAG ANCHOR? | ANCHOR TAG?
235        # block_content     ::= block_collection | flow_collection | SCALAR
236        # flow_content      ::= flow_collection | SCALAR
237        # block_collection  ::= block_sequence | block_mapping
238        # block_node_or_indentless_sequence ::= ALIAS | properties?
239        #                                       (block_content | indentless_block_sequence)
240        if self.scanner.check(AliasToken):
241            token = self.scanner.get()
[116]242            yield AliasEvent(token.value, token.start_mark, token.end_mark)
[44]243        else:
[51]244            anchor = None
245            tag = None
[116]246            start_mark = end_mark = tag_mark = None
[51]247            if self.scanner.check(AnchorToken):
248                token = self.scanner.get()
[130]249                start_mark = token.start_mark
250                end_mark = token.end_mark
[51]251                anchor = token.value
252                if self.scanner.check(TagToken):
253                    token = self.scanner.get()
[130]254                    tag_mark = token.start_mark
255                    end_mark = token.end_mark
[51]256                    tag = token.value
257            elif self.scanner.check(TagToken):
258                token = self.scanner.get()
[130]259                start_mark = tag_mark = token.start_mark
260                end_mark = token.end_mark
[51]261                tag = token.value
262                if self.scanner.check(AnchorToken):
263                    token = self.scanner.get()
[130]264                    end_mark = token.end_mark
[51]265                    anchor = token.value
266            if tag is not None:
267                handle, suffix = tag
268                if handle is not None:
269                    if handle not in self.tag_handles:
[116]270                        raise ParserError("while parsing a node", start_mark,
[51]271                                "found undefined tag handle %r" % handle.encode('utf-8'),
[116]272                                tag_mark)
[51]273                    tag = self.tag_handles[handle]+suffix
274                else:
275                    tag = suffix
276            if tag is None:
277                if not (self.scanner.check(ScalarToken) and
[130]278                        self.scanner.peek().implicit):
[51]279                    tag = u'!'
[116]280            if start_mark is None:
[130]281                start_mark = end_mark = self.scanner.peek().start_mark
[51]282            event = None
283            collection_events = None
284            if indentless_sequence and self.scanner.check(BlockEntryToken):
[116]285                end_mark = self.scanner.peek().end_mark
[130]286                event = SequenceStartEvent(anchor, tag, start_mark, end_mark)
[51]287                collection_events = self.parse_indentless_sequence()
[44]288            else:
[51]289                if self.scanner.check(ScalarToken):
290                    token = self.scanner.get()
[116]291                    end_mark = token.end_mark
[51]292                    event = ScalarEvent(anchor, tag, token.value,
[130]293                            start_mark, end_mark,
294                            implicit=token.implicit, style=token.style)
[51]295                elif self.scanner.check(FlowSequenceStartToken):
[116]296                    end_mark = self.scanner.peek().end_mark
[130]297                    event = SequenceStartEvent(anchor, tag, start_mark, end_mark,
298                            flow_style=True)
[51]299                    collection_events = self.parse_flow_sequence()
300                elif self.scanner.check(FlowMappingStartToken):
[116]301                    end_mark = self.scanner.peek().end_mark
[130]302                    event = MappingStartEvent(anchor, tag, start_mark, end_mark,
303                            flow_style=True)
[51]304                    collection_events = self.parse_flow_mapping()
305                elif block and self.scanner.check(BlockSequenceStartToken):
[116]306                    end_mark = self.scanner.peek().start_mark
[130]307                    event = SequenceStartEvent(anchor, tag, start_mark, end_mark,
308                            flow_style=False)
[51]309                    collection_events = self.parse_block_sequence()
310                elif block and self.scanner.check(BlockMappingStartToken):
[116]311                    end_mark = self.scanner.peek().start_mark
[130]312                    event = MappingStartEvent(anchor, tag, start_mark, end_mark,
313                            flow_style=False)
[51]314                    collection_events = self.parse_block_mapping()
[130]315                elif anchor is not None or tag is not None:
316                    # Empty scalars are allowed even if a tag or an anchor is
317                    # specified.
318                    event = ScalarEvent(anchor, tag, u'', start_mark, end_mark,
319                            implicit=True)
[51]320                else:
321                    if block:
322                        node = 'block'
323                    else:
324                        node = 'flow'
325                    token = self.scanner.peek()
[116]326                    raise ParserError("while scanning a %s node" % node, start_mark,
[51]327                            "expected the node content, but found %r" % token.id,
[116]328                            token.start_mark)
[51]329            yield event
330            if collection_events is not None:
331                for event in collection_events:
332                    yield event
[44]333
[43]334    def parse_block_sequence(self):
[51]335        # BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
336        token = self.scanner.get()
[116]337        start_mark = token.start_mark
[51]338        while self.scanner.check(BlockEntryToken):
339            token = self.scanner.get()
340            if not self.scanner.check(BlockEntryToken, BlockEndToken):
341                for event in self.parse_block_node():
342                    yield event
[43]343            else:
[116]344                yield self.process_empty_scalar(token.end_mark)
[51]345        if not self.scanner.check(BlockEndToken):
346            token = self.scanner.peek()
[116]347            raise ParserError("while scanning a block collection", start_mark,
348                    "expected <block end>, but found %r" % token.id, token.start_mark)
[51]349        token = self.scanner.get()
[130]350        yield SequenceEndEvent(token.start_mark, token.end_mark)
[43]351
352    def parse_indentless_sequence(self):
[51]353        # (BLOCK-ENTRY block_node?)+
354        while self.scanner.check(BlockEntryToken):
355            token = self.scanner.get()
356            if not self.scanner.check(BlockEntryToken,
357                    KeyToken, ValueToken, BlockEndToken):
358                for event in self.parse_block_node():
359                    yield event
[43]360            else:
[116]361                yield self.process_empty_scalar(token.end_mark)
[51]362        token = self.scanner.peek()
[130]363        yield SequenceEndEvent(token.start_mark, token.start_mark)
[43]364
365    def parse_block_mapping(self):
[51]366        # BLOCK-MAPPING_START
367        #   ((KEY block_node_or_indentless_sequence?)?
368        #   (VALUE block_node_or_indentless_sequence?)?)*
369        # BLOCK-END
370        token = self.scanner.get()
[116]371        start_mark = token.start_mark
[51]372        while self.scanner.check(KeyToken, ValueToken):
373            if self.scanner.check(KeyToken):
374                token = self.scanner.get()
375                if not self.scanner.check(KeyToken, ValueToken, BlockEndToken):
376                    for event in self.parse_block_node_or_indentless_sequence():
377                        yield event
378                else:
[116]379                    yield self.process_empty_scalar(token.end_mark)
[51]380            if self.scanner.check(ValueToken):
381                token = self.scanner.get()
382                if not self.scanner.check(KeyToken, ValueToken, BlockEndToken):
383                    for event in self.parse_block_node_or_indentless_sequence():
384                        yield event
385                else:
[116]386                    yield self.process_empty_scalar(token.end_mark)
[51]387            else:
388                token = self.scanner.peek()
[116]389                yield self.process_empty_scalar(token.start_mark)
[51]390        if not self.scanner.check(BlockEndToken):
391            token = self.scanner.peek()
[116]392            raise ParserError("while scanning a block mapping", start_mark,
393                    "expected <block end>, but found %r" % token.id, token.start_mark)
[51]394        token = self.scanner.get()
[130]395        yield MappingEndEvent(token.start_mark, token.end_mark)
[43]396
397    def parse_flow_sequence(self):
[51]398        # flow_sequence     ::= FLOW-SEQUENCE-START
399        #                       (flow_sequence_entry FLOW-ENTRY)*
400        #                       flow_sequence_entry?
401        #                       FLOW-SEQUENCE-END
402        # flow_sequence_entry   ::= flow_node | KEY flow_node? (VALUE flow_node?)?
403        #
404        # Note that while production rules for both flow_sequence_entry and
405        # flow_mapping_entry are equal, their interpretations are different.
406        # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?`
407        # generate an inline mapping (set syntax).
408        token = self.scanner.get()
[116]409        start_mark = token.start_mark
[51]410        while not self.scanner.check(FlowSequenceEndToken):
411            if self.scanner.check(KeyToken):
412                token = self.scanner.get()
[130]413                yield MappingStartEvent(None, u'!',
414                        token.start_mark, token.end_mark,
415                        flow_style=True)
[51]416                if not self.scanner.check(ValueToken,
417                        FlowEntryToken, FlowSequenceEndToken):
418                    for event in self.parse_flow_node():
419                        yield event
420                else:
[116]421                    yield self.process_empty_scalar(token.end_mark)
[51]422                if self.scanner.check(ValueToken):
423                    token = self.scanner.get()
424                    if not self.scanner.check(FlowEntryToken, FlowSequenceEndToken):
425                        for event in self.parse_flow_node():
426                            yield event
427                    else:
[116]428                        yield self.process_empty_scalar(token.end_mark)
[51]429                else:
430                    token = self.scanner.peek()
[116]431                    yield self.process_empty_scalar(token.start_mark)
[51]432                token = self.scanner.peek()
[130]433                yield MappingEndEvent(token.start_mark, token.start_mark)
[43]434            else:
[51]435                for event in self.parse_flow_node():
436                    yield event
437            if not self.scanner.check(FlowEntryToken, FlowSequenceEndToken):
438                token = self.scanner.peek()
[116]439                raise ParserError("while scanning a flow sequence", start_mark,
440                        "expected ',' or ']', but got %r" % token.id, token.start_mark)
[51]441            if self.scanner.check(FlowEntryToken):
442                self.scanner.get()
443        token = self.scanner.get()
[130]444        yield SequenceEndEvent(token.start_mark, token.end_mark)
[43]445
446    def parse_flow_mapping(self):
[51]447        # flow_mapping      ::= FLOW-MAPPING-START
448        #                       (flow_mapping_entry FLOW-ENTRY)*
449        #                       flow_mapping_entry?
450        #                       FLOW-MAPPING-END
451        # flow_mapping_entry    ::= flow_node | KEY flow_node? (VALUE flow_node?)?
452        token = self.scanner.get()
[116]453        start_mark = token.start_mark
[51]454        while not self.scanner.check(FlowMappingEndToken):
455            if self.scanner.check(KeyToken):
456                token = self.scanner.get()
457                if not self.scanner.check(ValueToken,
458                        FlowEntryToken, FlowMappingEndToken):
459                    for event in self.parse_flow_node():
460                        yield event
461                else:
[116]462                    yield self.process_empty_scalar(token.end_mark)
[51]463                if self.scanner.check(ValueToken):
464                    token = self.scanner.get()
465                    if not self.scanner.check(FlowEntryToken, FlowMappingEndToken):
466                        for event in self.parse_flow_node():
467                            yield event
468                    else:
[116]469                        yield self.process_empty_scalar(token.end_mark)
[51]470                else:
471                    token = self.scanner.peek()
[116]472                    yield self.process_empty_scalar(token.start_mark)
[43]473            else:
[51]474                for event in self.parse_flow_node():
475                    yield event
[116]476                yield self.process_empty_scalar(self.scanner.peek().start_mark)
[51]477            if not self.scanner.check(FlowEntryToken, FlowMappingEndToken):
478                token = self.scanner.peek()
[116]479                raise ParserError("while scanning a flow mapping", start_mark,
480                        "expected ',' or '}', but got %r" % token.id, token.start_mark)
[51]481            if self.scanner.check(FlowEntryToken):
482                self.scanner.get()
483        if not self.scanner.check(FlowMappingEndToken):
484            token = self.scanner.peek()
[116]485            raise ParserError("while scanning a flow mapping", start_mark,
486                    "expected '}', but found %r" % token.id, token.start_mark)
[51]487        token = self.scanner.get()
[130]488        yield MappingEndEvent(token.start_mark, token.end_mark)
[43]489
[116]490    def process_empty_scalar(self, mark):
[130]491        return ScalarEvent(None, None, u'', mark, mark,
492                implicit=True)
[43]493
Note: See TracBrowser for help on using the repository browser.