2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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/eplv10.html
8 package org.opendaylight.yangtools.yang.parser.impl;
10 import static com.google.common.base.Preconditions.checkState;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.Lists;
16 import java.math.BigDecimal;
17 import java.math.BigInteger;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Iterator;
21 import java.util.List;
22 import org.antlr.v4.runtime.ParserRuleContext;
23 import org.antlr.v4.runtime.tree.ParseTree;
24 import org.antlr.v4.runtime.tree.TerminalNode;
25 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
26 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
27 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
28 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bit_stmtContext;
29 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bits_specificationContext;
30 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_argContext;
31 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_stmtContext;
32 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Decimal64_specificationContext;
33 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Default_stmtContext;
34 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Description_stmtContext;
35 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_specificationContext;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_stmtContext;
37 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_app_tag_stmtContext;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_message_stmtContext;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Fraction_digits_stmtContext;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Identityref_specificationContext;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Instance_identifier_specificationContext;
42 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Key_stmtContext;
43 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Leafref_specificationContext;
44 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Length_stmtContext;
45 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_argContext;
46 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_stmtContext;
47 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_elements_stmtContext;
48 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_value_argContext;
49 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_elements_stmtContext;
50 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_value_argContext;
51 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
52 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Must_stmtContext;
53 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Numerical_restrictionsContext;
54 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_argContext;
55 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
56 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Path_stmtContext;
57 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Pattern_stmtContext;
58 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Position_stmtContext;
59 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Presence_stmtContext;
60 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Range_stmtContext;
61 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Reference_stmtContext;
62 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_anyxml_stmtsContext;
63 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_choice_stmtsContext;
64 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_container_stmtsContext;
65 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_list_stmtsContext;
66 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_stmtsContext;
67 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_list_stmtsContext;
68 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_pomContext;
69 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_stmtContext;
70 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_argContext;
71 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_stmtContext;
72 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_argContext;
73 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_stmtContext;
74 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.StringContext;
75 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.String_restrictionsContext;
76 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
77 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
78 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Value_stmtContext;
79 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
80 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_argContext;
81 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
82 import org.opendaylight.yangtools.yang.common.QName;
83 import org.opendaylight.yangtools.yang.model.api.MustDefinition;
84 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
85 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
86 import org.opendaylight.yangtools.yang.model.api.Status;
87 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
88 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
90 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
91 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
92 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
93 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
94 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
96 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
97 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
98 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
99 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
100 import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
101 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
102 import org.opendaylight.yangtools.yang.model.util.BinaryType;
103 import org.opendaylight.yangtools.yang.model.util.BitImpl;
104 import org.opendaylight.yangtools.yang.model.util.BitsType;
105 import org.opendaylight.yangtools.yang.model.util.Decimal64;
106 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
107 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
108 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
109 import org.opendaylight.yangtools.yang.model.util.Int16;
110 import org.opendaylight.yangtools.yang.model.util.Int32;
111 import org.opendaylight.yangtools.yang.model.util.Int64;
112 import org.opendaylight.yangtools.yang.model.util.Int8;
113 import org.opendaylight.yangtools.yang.model.util.Leafref;
114 import org.opendaylight.yangtools.yang.model.util.MustDefinitionImpl;
115 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
116 import org.opendaylight.yangtools.yang.model.util.StringType;
117 import org.opendaylight.yangtools.yang.model.util.Uint16;
118 import org.opendaylight.yangtools.yang.model.util.Uint32;
119 import org.opendaylight.yangtools.yang.model.util.Uint64;
120 import org.opendaylight.yangtools.yang.model.util.Uint8;
121 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
122 import org.opendaylight.yangtools.yang.parser.builder.api.ConstraintsBuilder;
123 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
124 import org.opendaylight.yangtools.yang.parser.builder.api.RefineBuilder;
125 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
126 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
127 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
128 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
129 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
130 import org.opendaylight.yangtools.yang.parser.builder.impl.RefineHolderImpl;
131 import org.opendaylight.yangtools.yang.parser.builder.impl.TypeDefinitionBuilderImpl;
132 import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
133 import org.opendaylight.yangtools.yang.parser.util.TypeConstraints;
134 import org.opendaylight.yangtools.yang.parser.util.UnknownBoundaryNumber;
135 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
136 import org.slf4j.Logger;
137 import org.slf4j.LoggerFactory;
139 public final class ParserListenerUtils {
140 private static final Logger LOG = LoggerFactory.getLogger(ParserListenerUtils.class);
141 private static final Splitter KEYDEF_SPLITTER = Splitter.on(' ').omitEmptyStrings();
142 private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults();
143 private static final Splitter DOT_DOT_SPLITTER = Splitter.on("..").trimResults();
144 private static final CharMatcher DOUBLE_QUOTE_MATCHER = CharMatcher.is('"');
145 private static final CharMatcher SINGLE_QUOTE_MATCHER = CharMatcher.is('\'');
147 private ParserListenerUtils() {
151 * Parse given tree and get first string value.
155 * @return first string value from given tree
157 public static String stringFromNode(final ParseTree treeNode) {
159 for (int i = 0; i < treeNode.getChildCount(); ++i) {
160 final ParseTree child = treeNode.getChild(i);
161 if (child instanceof StringContext) {
162 return stringFromStringContext((StringContext)child);
168 private static String stringFromStringContext(final StringContext context) {
169 StringBuilder sb = new StringBuilder();
170 for (TerminalNode stringNode : context.STRING()) {
171 final String str = stringNode.getText();
172 char firstChar = str.charAt(0);
173 final CharMatcher quoteMatcher;
174 if(SINGLE_QUOTE_MATCHER.matches(firstChar)) {
175 quoteMatcher = SINGLE_QUOTE_MATCHER;
176 } else if (DOUBLE_QUOTE_MATCHER.matches(firstChar)) {
177 quoteMatcher = DOUBLE_QUOTE_MATCHER;
184 * It is safe not to check last argument to be same
185 * grammars enforces that.
187 * FIXME: Introduce proper escaping and translation of escaped
191 sb.append(quoteMatcher.removeFrom(str.substring(1, str.length()-1)));
193 return sb.toString();
196 private static String getParentModule(final ParseTree ctx) {
197 ParseTree current = ctx;
198 while (current != null && !(current instanceof Module_stmtContext)) {
199 current = current.getParent();
201 if (current != null) {
202 Module_stmtContext module = (Module_stmtContext) current;
203 for (int i = 0; i < module.getChildCount(); i++) {
204 if (module.getChild(i) instanceof StringContext) {
205 final StringContext str = (StringContext) module.getChild(i);
206 return str.getChild(0).getText();
214 * Parse 'description', 'reference' and 'status' statements and fill in
220 * builder to fill in with parsed statements
222 public static void parseSchemaNodeArgs(final ParseTree ctx, final SchemaNodeBuilder builder) {
223 for (int i = 0; i < ctx.getChildCount(); i++) {
224 final ParseTree child = ctx.getChild(i);
225 if (child instanceof Description_stmtContext) {
226 final String desc = stringFromNode(child);
227 builder.setDescription(desc);
228 } else if (child instanceof Reference_stmtContext) {
229 final String ref = stringFromNode(child);
230 builder.setReference(ref);
231 } else if (child instanceof Status_stmtContext) {
232 final Status status = parseStatus((Status_stmtContext) child);
233 builder.setStatus(status);
239 * Parse given context and return its value;
243 * @return value parsed from context
245 public static Status parseStatus(final Status_stmtContext ctx) {
246 Status result = null;
247 for (int i = 0; i < ctx.getChildCount(); i++) {
248 ParseTree statusArg = ctx.getChild(i);
249 if (statusArg instanceof Status_argContext) {
250 String statusArgStr = stringFromNode(statusArg);
251 switch (statusArgStr) {
253 result = Status.CURRENT;
256 result = Status.DEPRECATED;
259 result = Status.OBSOLETE;
262 LOG.warn("Invalid 'status' statement: " + statusArgStr);
270 * Parse given tree and returns units statement as string.
274 * @return value of units statement as string or null if there is no units
277 public static String parseUnits(final ParseTree ctx) {
278 for (int i = 0; i < ctx.getChildCount(); i++) {
279 ParseTree child = ctx.getChild(i);
280 if (child instanceof Units_stmtContext) {
281 return stringFromNode(child);
288 * Parse given tree and returns default statement as string.
292 * @return value of default statement as string or null if there is no
295 public static String parseDefault(final ParseTree ctx) {
296 for (int i = 0; i < ctx.getChildCount(); i++) {
297 ParseTree child = ctx.getChild(i);
298 if (child instanceof Default_stmtContext) {
299 return stringFromNode(child);
306 * Create java.util.List of key node names.
309 * Key_stmtContext context
310 * @return YANG list key as java.util.List of key node names
312 public static List<String> createListKey(final Key_stmtContext ctx) {
313 String keyDefinition = stringFromNode(ctx);
314 return Lists.newArrayList(KEYDEF_SPLITTER.split(keyDefinition));
318 * Parse given type body of enumeration statement.
321 * type body context to parse
323 * actual position in YANG model
325 * current module name
326 * @return List of EnumPair object parsed from given context
328 private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
329 final SchemaPath path, final String moduleName) {
330 List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<>();
332 for (int i = 0; i < ctx.getChildCount(); i++) {
333 ParseTree enumSpecChild = ctx.getChild(i);
334 if (enumSpecChild instanceof Enum_specificationContext) {
335 int highestValue = -1;
336 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
337 ParseTree enumChild = enumSpecChild.getChild(j);
338 if (enumChild instanceof Enum_stmtContext) {
339 EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName);
340 if (enumPair.getValue() > highestValue) {
341 highestValue = enumPair.getValue();
343 enumConstants.add(enumPair);
348 return enumConstants;
352 * Parse enum statement context
355 * enum statement context
356 * @param highestValue
357 * current highest value in enumeration
359 * actual position in YANG model
361 * current module name
362 * @return EnumPair object parsed from given context
364 private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
365 final SchemaPath actualPath, final String moduleName) {
366 final String name = stringFromNode(ctx);
367 SchemaPath path = createTypePath(actualPath, name);
368 Integer value = null;
370 String description = null;
371 String reference = null;
372 Status status = null;
374 for (int i = 0; i < ctx.getChildCount(); i++) {
375 ParseTree child = ctx.getChild(i);
376 if (child instanceof Value_stmtContext) {
377 String valueStr = stringFromNode(child);
379 // yang enum value has same restrictions as JAVA Integer
380 value = Integer.valueOf(valueStr);
381 } catch (NumberFormatException e) {
383 .format("Error on enum '%s': the enum value MUST be in the range from -2147483648 to 2147483647, but was: %s",
385 throw new YangParseException(moduleName, ctx.getStart().getLine(), err, e);
387 } else if (child instanceof Description_stmtContext) {
388 description = stringFromNode(child);
389 } else if (child instanceof Reference_stmtContext) {
390 reference = stringFromNode(child);
391 } else if (child instanceof Status_stmtContext) {
392 status = parseStatus((Status_stmtContext) child);
397 value = highestValue + 1;
400 EnumPairImpl result = new EnumPairImpl();
401 result.qname = path.getPathTowardsRoot().iterator().next();
403 result.description = description;
404 result.reference = reference;
405 result.status = status;
407 result.value = value;
412 * Internal implementation of EnumPair.
414 private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
416 private SchemaPath path;
417 private String description;
418 private String reference;
419 private Status status;
420 private final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
422 private Integer value;
425 public QName getQName() {
430 public SchemaPath getPath() {
435 public String getDescription() {
440 public String getReference() {
445 public Status getStatus() {
450 public List<UnknownSchemaNode> getUnknownSchemaNodes() {
455 public String getName() {
460 public Integer getValue() {
465 public int hashCode() {
466 final int prime = 31;
468 result = prime * result + ((qname == null) ? 0 : qname.hashCode());
469 result = prime * result + ((path == null) ? 0 : path.hashCode());
470 result = prime * result + ((unknownNodes == null) ? 0 : unknownNodes.hashCode());
471 result = prime * result + ((name == null) ? 0 : name.hashCode());
472 result = prime * result + ((value == null) ? 0 : value.hashCode());
477 public boolean equals(final Object obj) {
484 if (getClass() != obj.getClass()) {
487 EnumPairImpl other = (EnumPairImpl) obj;
489 if (other.qname != null) {
492 } else if (!qname.equals(other.qname)) {
496 if (other.path != null) {
499 } else if (!path.equals(other.path)) {
502 if (unknownNodes == null) {
503 if (other.unknownNodes != null) {
506 } else if (!unknownNodes.equals(other.unknownNodes)) {
510 if (other.name != null) {
513 } else if (!name.equals(other.name)) {
517 if (other.value != null) {
520 } else if (!value.equals(other.value)) {
527 public String toString() {
528 return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
533 * Get and parse range from given type body context.
536 * type body context to parse
538 * name of current module
539 * @return List of RangeConstraint created from this context
541 private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
542 for (int i = 0; i < ctx.getChildCount(); i++) {
543 ParseTree numRestrChild = ctx.getChild(i);
545 if (numRestrChild instanceof Numerical_restrictionsContext) {
546 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
547 ParseTree rangeChild = numRestrChild.getChild(j);
548 if (rangeChild instanceof Range_stmtContext) {
549 return parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
554 if (numRestrChild instanceof Decimal64_specificationContext) {
555 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
556 ParseTree decRestr = numRestrChild.getChild(j);
557 if (decRestr instanceof Numerical_restrictionsContext) {
558 for (int k = 0; k < decRestr.getChildCount(); k++) {
559 ParseTree rangeChild = decRestr.getChild(k);
560 if (rangeChild instanceof Range_stmtContext) {
561 return parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
568 return Collections.emptyList();
572 * Parse given range context.
575 * range context to parse
577 * name of current module
578 * @return List of RangeConstraints parsed from this context
580 private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx, final String moduleName) {
581 final int line = ctx.getStart().getLine();
582 Optional<String> description = Optional.absent();
583 Optional<String> reference = Optional.absent();
585 for (int i = 0; i < ctx.getChildCount(); i++) {
586 ParseTree child = ctx.getChild(i);
587 if (child instanceof Description_stmtContext) {
588 description = Optional.fromNullable(stringFromNode(child));
589 } else if (child instanceof Reference_stmtContext) {
590 reference = Optional.fromNullable(stringFromNode(child));
594 List<RangeConstraint> rangeConstraints = new ArrayList<>();
595 for (String def : PIPE_SPLITTER.split(stringFromNode(ctx))) {
596 final Iterator<String> split = DOT_DOT_SPLITTER.split(def).iterator();
597 final Number min = parseNumberConstraintValue(split.next(), moduleName, line);
600 if (split.hasNext()) {
601 max = parseNumberConstraintValue(split.next(), moduleName, line);
602 if (split.hasNext()) {
603 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Malformed length constraint \"" + def + "\".");
609 RangeConstraint range = BaseConstraints.newRangeConstraint(min, max, description, reference);
610 rangeConstraints.add(range);
613 return rangeConstraints;
617 * Get and parse length from given type body context.
620 * type body context to parse
622 * name of current module
623 * @return List of LengthConstraint created from this context
625 private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
626 for (int i = 0; i < ctx.getChildCount(); i++) {
627 ParseTree stringRestrChild = ctx.getChild(i);
628 if (stringRestrChild instanceof String_restrictionsContext) {
629 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
630 ParseTree lengthChild = stringRestrChild.getChild(j);
631 if (lengthChild instanceof Length_stmtContext) {
632 return parseLengthConstraints((Length_stmtContext) lengthChild, moduleName);
637 return Collections.emptyList();
641 * Parse given length context.
644 * length context to parse
646 * name of current module
647 * @return List of LengthConstraints parsed from this context
649 private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx, final String moduleName) {
650 final int line = ctx.getStart().getLine();
651 Optional<String> description = Optional.absent();
652 Optional<String> reference = Optional.absent();
654 for (int i = 0; i < ctx.getChildCount(); i++) {
655 ParseTree child = ctx.getChild(i);
656 if (child instanceof Description_stmtContext) {
657 description = Optional.fromNullable(stringFromNode(child));
658 } else if (child instanceof Reference_stmtContext) {
659 reference = Optional.fromNullable(stringFromNode(child));
663 List<LengthConstraint> lengthConstraints = new ArrayList<>();
664 for (String def : PIPE_SPLITTER.split(stringFromNode(ctx))) {
665 final Iterator<String> split = DOT_DOT_SPLITTER.split(def).iterator();
666 final Number min = parseNumberConstraintValue(split.next(), moduleName, line);
669 if (split.hasNext()) {
670 max = parseNumberConstraintValue(split.next(), moduleName, line);
671 if (split.hasNext()) {
672 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Malformed length constraint \"" + def + "\".");
678 LengthConstraint range = BaseConstraints.newLengthConstraint(min, max, description, reference);
679 lengthConstraints.add(range);
682 return lengthConstraints;
689 * name of current module
691 * current line in module
692 * @return wrapper object of primitive java type or UnknownBoundaryNumber if
693 * type is one of special YANG values 'min' or 'max'
695 private static Number parseNumberConstraintValue(final String value, final String moduleName, final int line) {
697 if ("min".equals(value) || "max".equals(value)) {
698 result = new UnknownBoundaryNumber(value);
701 if (value.indexOf('.') != -1) {
702 result = new BigDecimal(value);
704 result = new BigInteger(value);
706 } catch (NumberFormatException e) {
707 throw new YangParseException(moduleName, line, "Unable to parse range value '" + value + "'.", e);
714 * Parse type body and return pattern constraints.
718 * @return list of pattern constraints
720 private static List<PatternConstraint> getPatternConstraint(final Type_body_stmtsContext ctx) {
721 List<PatternConstraint> patterns = new ArrayList<>();
723 for (int i = 0; i < ctx.getChildCount(); i++) {
724 ParseTree stringRestrChild = ctx.getChild(i);
725 if (stringRestrChild instanceof String_restrictionsContext) {
726 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
727 ParseTree lengthChild = stringRestrChild.getChild(j);
728 if (lengthChild instanceof Pattern_stmtContext) {
729 patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
738 * Internal helper method.
742 * @return PatternConstraint object
744 private static PatternConstraint parsePatternConstraint(final Pattern_stmtContext ctx) {
745 Optional<String> description = Optional.absent();
746 Optional<String> reference = Optional.absent();
747 for (int i = 0; i < ctx.getChildCount(); i++) {
748 ParseTree child = ctx.getChild(i);
749 if (child instanceof Description_stmtContext) {
750 description = Optional.of(stringFromNode(child));
751 } else if (child instanceof Reference_stmtContext) {
752 reference = Optional.of(stringFromNode(child));
755 String pattern = parsePatternString(ctx);
756 return BaseConstraints.newPatternConstraint(pattern, description, reference);
760 * Parse given context and return pattern value.
764 * @return pattern value as String
766 private static String parsePatternString(final Pattern_stmtContext ctx) {
767 StringBuilder result = new StringBuilder();
768 for (int i = 0; i < ctx.getChildCount(); ++i) {
769 ParseTree child = ctx.getChild(i);
770 if (child instanceof StringContext) {
771 for (int j = 0; j < child.getChildCount(); j++) {
773 String patternToken = child.getChild(j).getText();
774 result.append(patternToken.substring(1, patternToken.length() - 1));
779 return result.toString();
783 * Get fraction digits value from type body.
786 * type body context to parse
788 * name of current module
789 * @return 'fraction-digits' value if present in given context, null
792 private static Integer getFractionDigits(final Type_body_stmtsContext ctx, final String moduleName) {
793 Integer result = null;
794 for (int i = 0; i < ctx.getChildCount(); i++) {
795 ParseTree dec64specChild = ctx.getChild(i);
796 if (dec64specChild instanceof Decimal64_specificationContext) {
797 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild, moduleName);
804 * Parse decimal64 fraction-digits value.
809 * name of current module
810 * @return fraction-digits value as Integer
812 private static Integer parseFractionDigits(final Decimal64_specificationContext ctx, final String moduleName) {
813 Integer result = null;
814 for (int i = 0; i < ctx.getChildCount(); i++) {
815 ParseTree fdChild = ctx.getChild(i);
816 if (fdChild instanceof Fraction_digits_stmtContext) {
817 String value = stringFromNode(fdChild);
819 result = Integer.valueOf(value);
820 } catch (NumberFormatException e) {
821 throw new YangParseException(moduleName, ctx.getStart().getLine(),
822 "Unable to parse fraction digits value '" + value + "'.", e);
830 * Internal helper method for parsing bit statements from given type body
834 * type body context to parse
836 * current position in YANG model
838 * current module name
839 * @return List of Bit objects created from this context
841 private static List<BitsTypeDefinition.Bit> getBits(final Type_body_stmtsContext ctx, final SchemaPath actualPath,
842 final String moduleName) {
843 final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
844 for (int j = 0; j < ctx.getChildCount(); j++) {
845 ParseTree bitsSpecChild = ctx.getChild(j);
846 if (bitsSpecChild instanceof Bits_specificationContext) {
847 long highestPosition = -1;
848 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
849 ParseTree bitChild = bitsSpecChild.getChild(k);
850 if (bitChild instanceof Bit_stmtContext) {
851 Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, moduleName);
852 if (bit.getPosition() > highestPosition) {
853 highestPosition = bit.getPosition();
864 * Internal helper method for parsing bit context.
867 * bit statement context to parse
868 * @param highestPosition
869 * current highest position in bits type
871 * current position in YANG model
873 * current module name
874 * @return Bit object parsed from this context
876 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, final long highestPosition,
877 final SchemaPath actualPath, final String moduleName) {
878 String name = stringFromNode(ctx);
879 Long position = null;
881 String description = null;
882 String reference = null;
883 Status status = Status.CURRENT;
885 SchemaPath schemaPath = createBaseTypePath(actualPath, name);
887 for (int i = 0; i < ctx.getChildCount(); i++) {
888 ParseTree child = ctx.getChild(i);
889 if (child instanceof Position_stmtContext) {
890 String positionStr = stringFromNode(child);
891 position = Long.valueOf(positionStr);
892 } else if (child instanceof Description_stmtContext) {
893 description = stringFromNode(child);
894 } else if (child instanceof Reference_stmtContext) {
895 reference = stringFromNode(child);
896 } else if (child instanceof Status_stmtContext) {
897 status = parseStatus((Status_stmtContext) child);
901 if (position == null) {
902 position = highestPosition + 1;
904 if (position < 0 || position > 4294967295L) {
905 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on bit '" + name
906 + "': the position value MUST be in the range 0 to 4294967295");
909 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
910 return new BitImpl(position, schemaPath.getPathTowardsRoot().iterator().next(), schemaPath,
911 description, reference, status, unknownNodes);
915 * Parse 'ordered-by' statement.
917 * The 'ordered-by' statement defines whether the order of entries within a
918 * list are determined by the user or the system. The argument is one of the
919 * strings "system" or "user". If not present, order defaults to "system".
922 * Ordered_by_stmtContext
923 * @return true, if ordered-by contains value 'user', false otherwise
925 public static boolean parseUserOrdered(final Ordered_by_stmtContext ctx) {
926 boolean result = false;
927 for (int j = 0; j < ctx.getChildCount(); j++) {
928 ParseTree orderArg = ctx.getChild(j);
929 if (orderArg instanceof Ordered_by_argContext) {
930 String orderStr = stringFromNode(orderArg);
939 LOG.warn("Invalid 'ordered-by' statement.");
947 * Get config statement from given context. If there is no config statement,
948 * return config value of parent
955 * name of current module
957 * line in current module
958 * @return config statement parsed from given context
960 public static boolean getConfig(final ParseTree ctx, final Builder node, final String moduleName, final int line) {
962 // parse configuration statement
963 Boolean config = null;
964 for (int i = 0; i < ctx.getChildCount(); i++) {
965 ParseTree child = ctx.getChild(i);
966 if (child instanceof Config_stmtContext) {
967 config = parseConfig((Config_stmtContext) child, moduleName);
972 // If 'config' is not specified, the default is the same as the parent
973 // schema node's 'config' value
974 boolean parentConfig = getParentConfig(node);
975 if (config == null) {
976 result = parentConfig;
978 // Check: if a node has 'config' set to 'false', no node underneath
979 // it can have 'config' set to 'true'
980 if (!parentConfig && config) {
981 throw new YangParseException(moduleName, line,
982 "Can not set 'config' to 'true' if parent node has 'config' set to 'false'");
990 private static boolean getParentConfig(final Builder node) {
991 Builder parent = node.getParent();
994 if (parent instanceof ChoiceCaseBuilder) {
995 parent = parent.getParent();
997 if (parent instanceof DataSchemaNodeBuilder) {
998 config = ((DataSchemaNodeBuilder) parent).isConfiguration();
1006 * Parse config statement.
1009 * config context to parse
1011 * current module name
1012 * @return true if given context contains string 'true', false otherwise
1014 private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
1015 Boolean result = null;
1017 for (int i = 0; i < ctx.getChildCount(); ++i) {
1018 final ParseTree configContext = ctx.getChild(i);
1019 if (configContext instanceof Config_argContext) {
1020 final String value = stringFromNode(configContext);
1029 throw new YangParseException(moduleName, ctx.getStart().getLine(),
1030 "Failed to parse 'config' statement value: '" + value + "'.");
1039 * Parse unknown type with body.
1044 * current node parent
1045 * @param prefixedQName
1046 * type qname with prefix
1047 * @param moduleBuilder
1048 * current module builder
1049 * @param moduleQName
1050 * current module qname
1052 * actual path in model
1054 public static void parseUnknownTypeWithBody(Type_body_stmtsContext typeBody, TypeAwareBuilder parent,
1055 QName prefixedQName, ModuleBuilder moduleBuilder, QName moduleQName, SchemaPath actualPath) {
1056 final int line = typeBody.getStart().getLine();
1058 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleBuilder.getName());
1059 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleBuilder.getName());
1060 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1061 Integer fractionDigits = getFractionDigits(typeBody, moduleBuilder.getName());
1063 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1064 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1065 typedef.setRanges(rangeStatements);
1066 typedef.setLengths(lengthStatements);
1067 typedef.setPatterns(patternStatements);
1068 typedef.setFractionDigits(fractionDigits);
1069 typedef.setTypeQName(prefixedQName);
1070 // add parent node of this type statement to dirty nodes
1071 moduleBuilder.markActualNodeDirty();
1073 QName qname = QName.create(moduleQName, prefixedQName.getLocalName());
1074 SchemaPath schemaPath = createTypePath(actualPath, prefixedQName.getLocalName());
1075 TypeDefinitionBuilder typeBuilder = new TypeDefinitionBuilderImpl(moduleBuilder.getName(), line, qname, schemaPath);
1076 typeBuilder.setRanges(rangeStatements);
1077 typeBuilder.setLengths(lengthStatements);
1078 typeBuilder.setPatterns(patternStatements);
1079 typeBuilder.setFractionDigits(fractionDigits);
1080 typeBuilder.setTypeQName(prefixedQName);
1081 parent.setTypedef(typeBuilder);
1082 moduleBuilder.getDirtyNodes().add(typeBuilder);
1087 * Create TypeDefinition object based on given type name and type body.
1094 * current path in schema
1095 * @param moduleQName
1096 * current module qname
1099 * @return TypeDefinition object based on parsed values.
1101 public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1102 final SchemaPath actualPath, final QName moduleQName, final Builder parent) {
1104 final String moduleName = parent.getModuleName();
1105 final int line = typeBody.getStart().getLine();
1106 TypeDefinition<?> baseType = null;
1108 Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1109 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1110 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1111 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1113 TypeConstraints constraints = new TypeConstraints(moduleName, line);
1114 constraints.addFractionDigits(fractionDigits);
1115 constraints.addLengths(lengthStatements);
1116 constraints.addPatterns(patternStatements);
1117 constraints.addRanges(rangeStatements);
1119 SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1120 SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, moduleQName, typeName);
1122 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1123 extBaseTypePath = baseTypePath;
1126 if ("decimal64".equals(typeName)) {
1127 if (rangeStatements.isEmpty()) {
1129 return Decimal64.create(baseTypePath, fractionDigits);
1130 } catch(Exception e) {
1131 throw new YangParseException(moduleName, line, e.getMessage());
1134 Decimal64 decimalType = Decimal64.create(extBaseTypePath, fractionDigits);
1135 constraints.addRanges(decimalType.getRangeConstraints());
1136 baseType = decimalType;
1137 } else if (typeName.startsWith("int")) {
1138 IntegerTypeDefinition intType = null;
1141 intType = Int8.getInstance();
1144 intType = Int16.getInstance();
1147 intType = Int32.getInstance();
1150 intType = Int64.getInstance();
1153 if (intType == null) {
1154 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1156 constraints.addRanges(intType.getRangeConstraints());
1158 } else if (typeName.startsWith("uint")) {
1159 UnsignedIntegerTypeDefinition uintType = null;
1162 uintType = Uint8.getInstance();
1165 uintType = Uint16.getInstance();
1168 uintType = Uint32.getInstance();
1171 uintType = Uint64.getInstance();
1174 if (uintType == null) {
1175 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1177 constraints.addRanges(uintType.getRangeConstraints());
1178 baseType = uintType;
1179 } else if ("enumeration".equals(typeName)) {
1180 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1181 return EnumerationType.create(baseTypePath, enumConstants, Optional.<EnumPair> absent());
1182 } else if ("string".equals(typeName)) {
1183 StringTypeDefinition stringType = StringType.getInstance();
1184 constraints.addLengths(stringType.getLengthConstraints());
1185 baseType = stringType;
1186 } else if ("bits".equals(typeName)) {
1187 return BitsType.create(baseTypePath, getBits(typeBody, actualPath, moduleName));
1188 } else if ("leafref".equals(typeName)) {
1189 final String path = parseLeafrefPath(typeBody);
1190 final boolean absolute = path.startsWith("/");
1191 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1192 return new Leafref(xpath);
1193 } else if ("binary".equals(typeName)) {
1194 BinaryTypeDefinition binaryType = BinaryType.getInstance();
1195 constraints.addLengths(binaryType.getLengthConstraints());
1196 baseType = binaryType;
1197 } else if ("instance-identifier".equals(typeName)) {
1198 return InstanceIdentifierType.create(isRequireInstance(typeBody));
1201 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1202 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1203 typedef.setRanges(constraints.getRange());
1204 typedef.setLengths(constraints.getLength());
1205 typedef.setPatterns(constraints.getPatterns());
1206 typedef.setFractionDigits(constraints.getFractionDigits());
1210 QName qname = QName.create(moduleQName, typeName);
1211 SchemaPath schemaPath = actualPath.createChild(qname);
1212 final Optional<String> opt = Optional.of("");
1213 ExtendedType.Builder typeBuilder = ExtendedType.builder(qname, baseType, opt, opt, schemaPath);
1215 typeBuilder.ranges(constraints.getRange());
1216 typeBuilder.lengths(constraints.getLength());
1217 typeBuilder.patterns(constraints.getPatterns());
1218 typeBuilder.fractionDigits(constraints.getFractionDigits());
1220 return typeBuilder.build();
1223 private static SchemaPath createTypePath(final SchemaPath actual, final String typeName) {
1224 QName last = actual.getLastComponent();
1225 return actual.createChild(QName.create(last, typeName));
1228 private static SchemaPath createBaseTypePath(final SchemaPath actual, final String typeName) {
1229 return actual.createChild(BaseTypes.constructQName(typeName));
1232 private static SchemaPath createExtendedBaseTypePath(final SchemaPath actual, final QName moduleQName, final String typeName) {
1233 return actual.createChild(
1234 QName.create(moduleQName, typeName),
1235 BaseTypes.constructQName(typeName));
1239 * Parse given context and find identityref base value.
1243 * @return identityref base value as String
1245 public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
1246 String result = null;
1247 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1248 ParseTree child = ctx.getChild(i);
1249 if (child instanceof Identityref_specificationContext) {
1250 for (int j = 0; j < child.getChildCount(); j++) {
1251 ParseTree baseArg = child.getChild(j);
1252 if (baseArg instanceof Base_stmtContext) {
1253 result = stringFromNode(baseArg);
1263 * Parse type body statement and find require-instance value.
1267 * @return require-instance value
1269 private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
1270 for (int i = 0; i < ctx.getChildCount(); i++) {
1271 ParseTree child = ctx.getChild(i);
1272 if (child instanceof Instance_identifier_specificationContext) {
1273 for (int j = 0; j < child.getChildCount(); j++) {
1274 ParseTree reqStmt = child.getChild(j);
1275 if (reqStmt instanceof Require_instance_stmtContext) {
1276 for (int k = 0; k < reqStmt.getChildCount(); k++) {
1277 ParseTree reqArg = reqStmt.getChild(k);
1278 if (reqArg instanceof Require_instance_argContext) {
1279 return Boolean.valueOf(stringFromNode(reqArg));
1290 * Parse type body statement and find leafref path.
1294 * @return leafref path as String
1296 private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
1297 for (int i = 0; i < ctx.getChildCount(); i++) {
1298 ParseTree child = ctx.getChild(i);
1299 if (child instanceof Leafref_specificationContext) {
1300 for (int j = 0; j < child.getChildCount(); j++) {
1301 ParseTree leafRefSpec = child.getChild(j);
1302 if (leafRefSpec instanceof Path_stmtContext) {
1303 return stringFromNode(leafRefSpec);
1312 * Internal helper method for parsing must statement.
1316 * @return MustDefinition object based on parsed context
1318 private static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1319 StringBuilder mustText = new StringBuilder();
1320 Optional<String> description = Optional.absent();
1321 Optional<String> reference = Optional.absent();
1322 Optional<String> errorAppTag = Optional.absent();
1323 Optional<String> errorMessage = Optional.absent();
1324 for (int i = 0; i < ctx.getChildCount(); ++i) {
1325 ParseTree child = ctx.getChild(i);
1326 if (child instanceof StringContext) {
1327 final StringContext context = (StringContext) child;
1328 if (context.getChildCount() == 1) {
1329 String mustPart = context.getChild(0).getText();
1330 // trim start and end quotation
1331 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1333 for (int j = 0; j < context.getChildCount(); j++) {
1334 String mustPart = context.getChild(j).getText();
1336 mustText.append(mustPart.substring(0, mustPart.length() - 1));
1340 mustText.append(mustPart.substring(1));
1344 } else if (child instanceof Description_stmtContext) {
1345 description = Optional.of(stringFromNode(child));
1346 } else if (child instanceof Reference_stmtContext) {
1347 reference = Optional.of(stringFromNode(child));
1348 } else if (child instanceof Error_app_tag_stmtContext) {
1349 errorAppTag = Optional.of(stringFromNode(child));
1350 } else if (child instanceof Error_message_stmtContext) {
1351 errorMessage = Optional.of(stringFromNode(child));
1355 return MustDefinitionImpl.create(mustText.toString(), description, reference, errorAppTag, errorMessage);
1359 * Parse given context and set constraints to constraints builder.
1363 * @param constraints
1364 * ConstraintsBuilder to fill
1366 public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1367 for (int i = 0; i < ctx.getChildCount(); ++i) {
1368 final ParseTree childNode = ctx.getChild(i);
1369 if (childNode instanceof Max_elements_stmtContext) {
1370 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1371 constraints.setMaxElements(max);
1372 } else if (childNode instanceof Min_elements_stmtContext) {
1373 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1374 constraints.setMinElements(min);
1375 } else if (childNode instanceof Must_stmtContext) {
1376 MustDefinition must = parseMust((Must_stmtContext) childNode);
1377 constraints.addMustDefinition(must);
1378 } else if (childNode instanceof Mandatory_stmtContext) {
1379 for (int j = 0; j < childNode.getChildCount(); j++) {
1380 ParseTree mandatoryTree = childNode.getChild(j);
1381 if (mandatoryTree instanceof Mandatory_argContext) {
1382 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1383 constraints.setMandatory(mandatory);
1386 } else if (childNode instanceof When_stmtContext) {
1387 constraints.addWhenCondition(stringFromNode(childNode));
1392 private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1393 Integer result = null;
1395 for (int i = 0; i < ctx.getChildCount(); i++) {
1396 ParseTree minArg = ctx.getChild(i);
1397 if (minArg instanceof Min_value_argContext) {
1398 result = Integer.valueOf(stringFromNode(minArg));
1401 if (result == null) {
1402 throw new IllegalArgumentException();
1405 } catch (Exception e) {
1406 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1410 private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1411 Integer result = null;
1413 for (int i = 0; i < ctx.getChildCount(); i++) {
1414 ParseTree maxArg = ctx.getChild(i);
1415 if (maxArg instanceof Max_value_argContext) {
1416 String maxValue = stringFromNode(maxArg);
1417 if ("unbounded".equals(maxValue)) {
1418 result = Integer.MAX_VALUE;
1420 result = Integer.valueOf(maxValue);
1424 if (result == null) {
1425 throw new IllegalArgumentException();
1428 } catch (Exception e) {
1429 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1434 * Parse given context and return yin value.
1438 * @return true if value is 'true', false otherwise
1440 public static boolean parseYinValue(final Argument_stmtContext ctx) {
1441 boolean yinValue = false;
1442 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1443 ParseTree yin = ctx.getChild(i);
1444 if (yin instanceof Yin_element_stmtContext) {
1445 for (int j = 0; j < yin.getChildCount(); j++) {
1446 ParseTree yinArg = yin.getChild(j);
1447 if (yinArg instanceof Yin_element_argContext) {
1448 String yinString = stringFromNode(yinArg);
1449 if ("true".equals(yinString)) {
1461 * Check this base type.
1464 * base YANG type name
1466 * name of current module
1469 * @throws YangParseException
1470 * if this is one of YANG type which MUST contain additional
1471 * informations in its body
1473 public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1476 throw new YangParseException(moduleName, line,
1477 "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1479 throw new YangParseException(moduleName, line,
1480 "The 'base' statement MUST be present if the type is 'identityref'.");
1482 throw new YangParseException(moduleName, line,
1483 "The 'path' statement MUST be present if the type is 'leafref'.");
1485 throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1487 throw new YangParseException(moduleName, line,
1488 "The 'enum' statement MUST be present if the type is 'enumeration'.");
1493 * Parse refine statement.
1498 * name of current module
1499 * @return RefineHolder object representing this refine statement
1501 public static RefineHolderImpl parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
1502 final String refineTarget = stringFromNode(refineCtx);
1503 final RefineHolderImpl refine = new RefineHolderImpl(moduleName, refineCtx.getStart().getLine(), refineTarget);
1504 for (int i = 0; i < refineCtx.getChildCount(); i++) {
1505 ParseTree refinePom = refineCtx.getChild(i);
1506 if (refinePom instanceof Refine_pomContext) {
1507 for (int j = 0; j < refinePom.getChildCount(); j++) {
1508 ParseTree refineStmt = refinePom.getChild(j);
1509 parseRefineDefault(refine, refineStmt);
1511 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1512 parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1513 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1514 parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1515 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1516 parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1517 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1518 parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1519 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1520 parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1521 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1522 parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1530 private static void parseRefineDefault(final RefineHolderImpl refine, final ParseTree refineStmt) {
1531 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1532 ParseTree refineArg = refineStmt.getChild(i);
1533 if (refineArg instanceof Description_stmtContext) {
1534 String description = stringFromNode(refineArg);
1535 refine.setDescription(description);
1536 } else if (refineArg instanceof Reference_stmtContext) {
1537 String reference = stringFromNode(refineArg);
1538 refine.setReference(reference);
1539 } else if (refineArg instanceof Config_stmtContext) {
1540 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1541 refine.setConfiguration(config);
1546 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_stmtsContext refineStmt) {
1547 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1548 ParseTree refineArg = refineStmt.getChild(i);
1549 if (refineArg instanceof Default_stmtContext) {
1550 String defaultStr = stringFromNode(refineArg);
1551 refine.setDefaultStr(defaultStr);
1552 } else if (refineArg instanceof Mandatory_stmtContext) {
1553 for (int j = 0; j < refineArg.getChildCount(); j++) {
1554 ParseTree mandatoryTree = refineArg.getChild(j);
1555 if (mandatoryTree instanceof Mandatory_argContext) {
1556 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1557 refine.setMandatory(mandatory);
1560 } else if (refineArg instanceof Must_stmtContext) {
1561 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1562 refine.setMust(must);
1569 private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_container_stmtsContext refineStmt) {
1570 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1571 ParseTree refineArg = refineStmt.getChild(i);
1572 if (refineArg instanceof Must_stmtContext) {
1573 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1574 refine.setMust(must);
1575 } else if (refineArg instanceof Presence_stmtContext) {
1576 refine.setPresence(true);
1582 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_list_stmtsContext refineStmt) {
1583 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1584 ParseTree refineArg = refineStmt.getChild(i);
1585 if (refineArg instanceof Must_stmtContext) {
1586 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1587 refine.setMust(must);
1588 } else if (refineArg instanceof Max_elements_stmtContext) {
1589 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1590 refine.setMaxElements(max);
1591 } else if (refineArg instanceof Min_elements_stmtContext) {
1592 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1593 refine.setMinElements(min);
1599 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_list_stmtsContext refineStmt) {
1600 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1601 ParseTree refineArg = refineStmt.getChild(i);
1602 if (refineArg instanceof Must_stmtContext) {
1603 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1604 refine.setMust(must);
1605 } else if (refineArg instanceof Max_elements_stmtContext) {
1606 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1607 refine.setMaxElements(max);
1608 } else if (refineArg instanceof Min_elements_stmtContext) {
1609 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1610 refine.setMinElements(min);
1616 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_choice_stmtsContext refineStmt) {
1617 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1618 ParseTree refineArg = refineStmt.getChild(i);
1619 if (refineArg instanceof Default_stmtContext) {
1620 String defaultStr = stringFromNode(refineArg);
1621 refine.setDefaultStr(defaultStr);
1622 } else if (refineArg instanceof Mandatory_stmtContext) {
1623 for (int j = 0; j < refineArg.getChildCount(); j++) {
1624 ParseTree mandatoryTree = refineArg.getChild(j);
1625 if (mandatoryTree instanceof Mandatory_argContext) {
1626 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1627 refine.setMandatory(mandatory);
1635 private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_anyxml_stmtsContext refineStmt) {
1636 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1637 ParseTree refineArg = refineStmt.getChild(i);
1638 if (refineArg instanceof Must_stmtContext) {
1639 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1640 refine.setMust(must);
1641 } else if (refineArg instanceof Mandatory_stmtContext) {
1642 for (int j = 0; j < refineArg.getChildCount(); j++) {
1643 ParseTree mandatoryTree = refineArg.getChild(j);
1644 if (mandatoryTree instanceof Mandatory_argContext) {
1645 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1646 refine.setMandatory(mandatory);
1654 public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
1655 List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1656 checkState(!potentialValues.isEmpty());
1657 return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1660 public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
1661 List<T> potential = context.getRuleContexts(contextType);
1662 if(potential.isEmpty()) {
1663 return Optional.absent();
1665 return Optional.of(potential.get(0));