BUG-5717: add unique child identifier
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / StatementContextWriter.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
9
10 import com.google.common.base.Preconditions;
11 import javax.annotation.Nonnull;
12 import org.opendaylight.yangtools.yang.common.QName;
13 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
14 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
15 import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter;
16
17 final class StatementContextWriter implements StatementWriter {
18     private final ModelProcessingPhase phase;
19     private final SourceSpecificContext ctx;
20
21     private StatementContextBase<?, ?, ?> parent;
22     private ContextBuilder<?, ?, ?> current;
23
24     public StatementContextWriter(final SourceSpecificContext ctx, final ModelProcessingPhase phase) {
25         this.ctx = Preconditions.checkNotNull(ctx);
26         this.phase = Preconditions.checkNotNull(phase);
27     }
28
29     @Override
30     public void startStatement(final int childId, final QName name, final String argument,
31             final StatementSourceReference ref) {
32         deferredCreate();
33         current = ctx.createDeclaredChild(parent, childId, name, argument, ref);
34     }
35
36     @Override
37     public void endStatement(final StatementSourceReference ref) {
38         deferredCreate();
39         Preconditions.checkState(parent != null);
40         parent.endDeclared(ref,phase);
41         parent = parent.getParentContext();
42     }
43
44     @Nonnull
45     @Override
46     public ModelProcessingPhase getPhase() {
47         return phase;
48     }
49
50     private void deferredCreate() {
51         if (current != null) {
52             parent = current.build();
53             current = null;
54         }
55     }
56 }