duplicate anchors result in exception (should be allowed per spec)

Issue #66 new
Ted Timmons
created an issue

Rudimentary test script:

import yaml
print("yaml lib version: {}".format(yaml.__version__))
y = '''
  - &anchor 1
  - &anchor 1
'''
yaml.load(y)

And output:

$ python3 test.py
yaml lib version: 3.12
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    yaml.load(y)
  File "/usr/local/lib/python3.6/site-packages/yaml/__init__.py", line 72, in load
    return loader.get_single_data()
  File "/usr/local/lib/python3.6/site-packages/yaml/constructor.py", line 35, in get_single_data
    node = self.get_single_node()
  File "/usr/local/lib/python3.6/site-packages/yaml/composer.py", line 36, in get_single_node
    document = self.compose_document()
  File "/usr/local/lib/python3.6/site-packages/yaml/composer.py", line 55, in compose_document
    node = self.compose_node(None, None)
  File "/usr/local/lib/python3.6/site-packages/yaml/composer.py", line 82, in compose_node
    node = self.compose_sequence_node(anchor)
  File "/usr/local/lib/python3.6/site-packages/yaml/composer.py", line 111, in compose_sequence_node
    node.value.append(self.compose_node(node, index))
  File "/usr/local/lib/python3.6/site-packages/yaml/composer.py", line 77, in compose_node
    "second occurence", event.start_mark)
yaml.composer.ComposerError: found duplicate anchor 'anchor'; first occurence
  in "<unicode string>", line 2, column 5:
      - &anchor 1
        ^
second occurence
  in "<unicode string>", line 3, column 5:
      - &anchor 1
        ^

The YAML spec in all versions (1.0, 1.1, 1.2) specifically allow for these duplicate anchors:

When composing a representation graph from serialized events, an alias node refers to the most recent node in the serialization having the specified anchor. Therefore, anchors need not be unique within a serialization. In addition, an anchor need not have an alias node referring to it.

This was originally raised as an error in 2009. Here's the duplicate-checking code in composer.py.

(also, 'occurrence' is spelled wrong)

Comments (0)

  1. Log in to comment