aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/yaml/snakeyaml/composer/Composer.java
blob: d89aa2345e39b2926d638691cb33f2f26ee6dd18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/**
 * Copyright (c) 2008, SnakeYAML
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package org.yaml.snakeyaml.composer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.comments.CommentEventsCollector;
import org.yaml.snakeyaml.comments.CommentLine;
import org.yaml.snakeyaml.comments.CommentType;
import org.yaml.snakeyaml.error.Mark;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.events.AliasEvent;
import org.yaml.snakeyaml.events.Event;
import org.yaml.snakeyaml.events.MappingStartEvent;
import org.yaml.snakeyaml.events.NodeEvent;
import org.yaml.snakeyaml.events.ScalarEvent;
import org.yaml.snakeyaml.events.SequenceStartEvent;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeId;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.parser.Parser;
import org.yaml.snakeyaml.resolver.Resolver;

/**
 * Creates a node graph from parser events.
 * <p>
 * Corresponds to the 'Compose' step as described in chapter 3.1 of the
 * <a href="http://yaml.org/spec/1.1/">YAML Specification</a>.
 * </p>
 */
public class Composer {

  protected final Parser parser;
  private final Resolver resolver;
  private final Map<String, Node> anchors;
  private final Set<Node> recursiveNodes;
  private int nonScalarAliasesCount = 0;
  private final LoaderOptions loadingConfig;
  private final CommentEventsCollector blockCommentsCollector;
  private final CommentEventsCollector inlineCommentsCollector;
  // keep the nesting of collections inside other collections
  private int nestingDepth = 0;
  private final int nestingDepthLimit;

  public Composer(Parser parser, Resolver resolver) {
    this(parser, resolver, new LoaderOptions());
  }

  public Composer(Parser parser, Resolver resolver, LoaderOptions loadingConfig) {
    this.parser = parser;
    this.resolver = resolver;
    this.anchors = new HashMap<String, Node>();
    this.recursiveNodes = new HashSet<Node>();
    this.loadingConfig = loadingConfig;
    this.blockCommentsCollector =
        new CommentEventsCollector(parser, CommentType.BLANK_LINE, CommentType.BLOCK);
    this.inlineCommentsCollector = new CommentEventsCollector(parser, CommentType.IN_LINE);
    nestingDepthLimit = loadingConfig.getNestingDepthLimit();
  }

  /**
   * Checks if further documents are available.
   *
   * @return <code>true</code> if there is at least one more document.
   */
  public boolean checkNode() {
    // Drop the STREAM-START event.
    if (parser.checkEvent(Event.ID.StreamStart)) {
      parser.getEvent();
    }
    // If there are more documents available?
    return !parser.checkEvent(Event.ID.StreamEnd);
  }

  /**
   * Reads and composes the next document.
   *
   * @return The root node of the document or <code>null</code> if no more documents are available.
   */
  public Node getNode() {
    // Collect inter-document start comments
    blockCommentsCollector.collectEvents();
    if (parser.checkEvent(Event.ID.StreamEnd)) {
      List<CommentLine> commentLines = blockCommentsCollector.consume();
      Mark startMark = commentLines.get(0).getStartMark();
      List<NodeTuple> children = Collections.emptyList();
      Node node = new MappingNode(Tag.COMMENT, false, children, startMark, null, FlowStyle.BLOCK);
      node.setBlockComments(commentLines);
      return node;
    }
    // Drop the DOCUMENT-START event.
    parser.getEvent();
    // Compose the root node.
    Node node = composeNode(null);
    // Drop the DOCUMENT-END event.
    blockCommentsCollector.collectEvents();
    if (!blockCommentsCollector.isEmpty()) {
      node.setEndComments(blockCommentsCollector.consume());
    }
    parser.getEvent();
    this.anchors.clear();
    this.recursiveNodes.clear();
    return node;
  }

  /**
   * Reads a document from a source that contains only one document.
   * <p>
   * If the stream contains more than one document an exception is thrown.
   * </p>
   *
   * @return The root node of the document or <code>null</code> if no document is available.
   */
  public Node getSingleNode() {
    // Drop the STREAM-START event.
    parser.getEvent();
    // Compose a document if the stream is not empty.
    Node document = null;
    if (!parser.checkEvent(Event.ID.StreamEnd)) {
      document = getNode();
    }
    // Ensure that the stream contains no more documents.
    if (!parser.checkEvent(Event.ID.StreamEnd)) {
      Event event = parser.getEvent();
      Mark contextMark = document != null ? document.getStartMark() : null;
      throw new ComposerException("expected a single document in the stream", contextMark,
          "but found another document", event.getStartMark());
    }
    // Drop the STREAM-END event.
    parser.getEvent();
    return document;
  }

  private Node composeNode(Node parent) {
    blockCommentsCollector.collectEvents();
    if (parent != null) {
      recursiveNodes.add(parent);
    }
    final Node node;
    if (parser.checkEvent(Event.ID.Alias)) {
      AliasEvent event = (AliasEvent) parser.getEvent();
      String anchor = event.getAnchor();
      if (!anchors.containsKey(anchor)) {
        throw new ComposerException(null, null, "found undefined alias " + anchor,
            event.getStartMark());
      }
      node = anchors.get(anchor);
      if (!(node instanceof ScalarNode)) {
        this.nonScalarAliasesCount++;
        if (this.nonScalarAliasesCount > loadingConfig.getMaxAliasesForCollections()) {
          throw new YAMLException(
              "Number of aliases for non-scalar nodes exceeds the specified max="
                  + loadingConfig.getMaxAliasesForCollections());
        }
      }
      if (recursiveNodes.remove(node)) {
        node.setTwoStepsConstruction(true);
      }
      // drop comments, they can not be supported here
      blockCommentsCollector.consume();
      inlineCommentsCollector.collectEvents().consume();
    } else {
      NodeEvent event = (NodeEvent) parser.peekEvent();
      String anchor = event.getAnchor();
      increaseNestingDepth();
      // the check for duplicate anchors has been removed (issue 174)
      if (parser.checkEvent(Event.ID.Scalar)) {
        node = composeScalarNode(anchor, blockCommentsCollector.consume());
      } else if (parser.checkEvent(Event.ID.SequenceStart)) {
        node = composeSequenceNode(anchor);
      } else {
        node = composeMappingNode(anchor);
      }
      decreaseNestingDepth();
    }
    recursiveNodes.remove(parent);
    return node;
  }

  protected Node composeScalarNode(String anchor, List<CommentLine> blockComments) {
    ScalarEvent ev = (ScalarEvent) parser.getEvent();
    String tag = ev.getTag();
    boolean resolved = false;
    Tag nodeTag;
    if (tag == null || tag.equals("!")) {
      nodeTag = resolver.resolve(NodeId.scalar, ev.getValue(),
          ev.getImplicit().canOmitTagInPlainScalar());
      resolved = true;
    } else {
      nodeTag = new Tag(tag);
    }
    Node node = new ScalarNode(nodeTag, resolved, ev.getValue(), ev.getStartMark(), ev.getEndMark(),
        ev.getScalarStyle());
    if (anchor != null) {
      node.setAnchor(anchor);
      anchors.put(anchor, node);
    }
    node.setBlockComments(blockComments);
    node.setInLineComments(inlineCommentsCollector.collectEvents().consume());
    return node;
  }

  protected Node composeSequenceNode(String anchor) {
    SequenceStartEvent startEvent = (SequenceStartEvent) parser.getEvent();
    String tag = startEvent.getTag();
    Tag nodeTag;

    boolean resolved = false;
    if (tag == null || tag.equals("!")) {
      nodeTag = resolver.resolve(NodeId.sequence, null, startEvent.getImplicit());
      resolved = true;
    } else {
      nodeTag = new Tag(tag);
    }
    final ArrayList<Node> children = new ArrayList<Node>();
    SequenceNode node = new SequenceNode(nodeTag, resolved, children, startEvent.getStartMark(),
        null, startEvent.getFlowStyle());
    if (startEvent.isFlow()) {
      node.setBlockComments(blockCommentsCollector.consume());
    }
    if (anchor != null) {
      node.setAnchor(anchor);
      anchors.put(anchor, node);
    }
    while (!parser.checkEvent(Event.ID.SequenceEnd)) {
      blockCommentsCollector.collectEvents();
      if (parser.checkEvent(Event.ID.SequenceEnd)) {
        break;
      }
      children.add(composeNode(node));
    }
    if (startEvent.isFlow()) {
      node.setInLineComments(inlineCommentsCollector.collectEvents().consume());
    }
    Event endEvent = parser.getEvent();
    node.setEndMark(endEvent.getEndMark());
    inlineCommentsCollector.collectEvents();
    if (!inlineCommentsCollector.isEmpty()) {
      node.setInLineComments(inlineCommentsCollector.consume());
    }
    return node;
  }

  protected Node composeMappingNode(String anchor) {
    MappingStartEvent startEvent = (MappingStartEvent) parser.getEvent();
    String tag = startEvent.getTag();
    Tag nodeTag;
    boolean resolved = false;
    if (tag == null || tag.equals("!")) {
      nodeTag = resolver.resolve(NodeId.mapping, null, startEvent.getImplicit());
      resolved = true;
    } else {
      nodeTag = new Tag(tag);
    }

    final List<NodeTuple> children = new ArrayList<NodeTuple>();
    MappingNode node = new MappingNode(nodeTag, resolved, children, startEvent.getStartMark(), null,
        startEvent.getFlowStyle());
    if (startEvent.isFlow()) {
      node.setBlockComments(blockCommentsCollector.consume());
    }
    if (anchor != null) {
      node.setAnchor(anchor);
      anchors.put(anchor, node);
    }
    while (!parser.checkEvent(Event.ID.MappingEnd)) {
      blockCommentsCollector.collectEvents();
      if (parser.checkEvent(Event.ID.MappingEnd)) {
        break;
      }
      composeMappingChildren(children, node);
    }
    if (startEvent.isFlow()) {
      node.setInLineComments(inlineCommentsCollector.collectEvents().consume());
    }
    Event endEvent = parser.getEvent();
    node.setEndMark(endEvent.getEndMark());
    inlineCommentsCollector.collectEvents();
    if (!inlineCommentsCollector.isEmpty()) {
      node.setInLineComments(inlineCommentsCollector.consume());
    }
    return node;
  }

  protected void composeMappingChildren(List<NodeTuple> children, MappingNode node) {
    Node itemKey = composeKeyNode(node);
    if (itemKey.getTag().equals(Tag.MERGE)) {
      node.setMerged(true);
    }
    Node itemValue = composeValueNode(node);
    children.add(new NodeTuple(itemKey, itemValue));
  }

  protected Node composeKeyNode(MappingNode node) {
    return composeNode(node);
  }

  protected Node composeValueNode(MappingNode node) {
    return composeNode(node);
  }

  /**
   * Increase nesting depth and fail when it exceeds the denied limit
   */
  private void increaseNestingDepth() {
    if (nestingDepth > nestingDepthLimit) {
      throw new YAMLException("Nesting Depth exceeded max " + nestingDepthLimit);
    }
    nestingDepth++;
  }

  /**
   * Indicate that the collection is finished and the nesting is decreased
   */
  private void decreaseNestingDepth() {
    if (nestingDepth > 0) {
      nestingDepth--;
    } else {
      throw new YAMLException("Nesting Depth cannot be negative");
    }
  }
}