Bug 4540: Yang parser exceptions should follow consistent path
[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.SourceException;
15 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
16 import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter;
17
18 class StatementContextWriter implements StatementWriter {
19
20     private final SourceSpecificContext ctx;
21     private StatementContextBase<?, ?, ?> parent;
22     private ContextBuilder<?, ?, ?> current;
23     private ModelProcessingPhase phase;
24
25     public StatementContextWriter(SourceSpecificContext ctx, ModelProcessingPhase phase) {
26         this.ctx = Preconditions.checkNotNull(ctx);
27         this.phase = Preconditions.checkNotNull(phase);
28     }
29
30     @Override
31     public void startStatement(QName name, StatementSourceReference ref) throws SourceException {
32         defferedCreate();
33         current = ctx.createDeclaredChild(parent, name, ref);
34
35     }
36
37     @Override
38     public void argumentValue(String value, StatementSourceReference ref) {
39         Preconditions.checkState(current != null, "Could not set two arguments for one statement: %s", ref);
40         current.setArgument(value, ref);
41     }
42
43     void defferedCreate() throws SourceException {
44         if(current != null) {
45             parent = current.build();
46             current = null;
47         }
48     }
49
50     @Override
51     public void endStatement(StatementSourceReference ref) throws SourceException {
52         defferedCreate();
53         Preconditions.checkState(parent != null);
54         parent.endDeclared(ref,phase);
55         parent = parent.getParentContext();
56     }
57
58     @Nonnull
59     @Override
60     public ModelProcessingPhase getPhase() {
61         return phase;
62     }
63
64 }