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.controller.yang.model.parser.util;
11 import java.util.ArrayList;
12 import java.util.Collections;
13 import java.util.Date;
14 import java.util.List;
15 import java.util.Stack;
17 import org.antlr.v4.runtime.tree.ParseTree;
18 import org.opendaylight.controller.antlrv4.code.gen.YangParser;
19 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Argument_stmtContext;
20 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Base_stmtContext;
21 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Bit_stmtContext;
22 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Bits_specificationContext;
23 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Config_argContext;
24 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Config_stmtContext;
25 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Decimal64_specificationContext;
26 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Default_stmtContext;
27 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Description_stmtContext;
28 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Enum_specificationContext;
29 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Enum_stmtContext;
30 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Error_app_tag_stmtContext;
31 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Error_message_stmtContext;
32 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Fraction_digits_stmtContext;
33 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Identityref_specificationContext;
34 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Leafref_specificationContext;
35 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Length_stmtContext;
36 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Mandatory_argContext;
37 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Mandatory_stmtContext;
38 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Max_elements_stmtContext;
39 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Min_elements_stmtContext;
40 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Must_stmtContext;
41 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Numerical_restrictionsContext;
42 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Ordered_by_argContext;
43 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
44 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Path_stmtContext;
45 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Pattern_stmtContext;
46 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Position_stmtContext;
47 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Presence_stmtContext;
48 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Range_stmtContext;
49 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Reference_stmtContext;
50 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_anyxml_stmtsContext;
51 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_choice_stmtsContext;
52 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_container_stmtsContext;
53 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_leaf_list_stmtsContext;
54 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_leaf_stmtsContext;
55 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_list_stmtsContext;
56 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_pomContext;
57 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_stmtContext;
58 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Require_instance_argContext;
59 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Require_instance_stmtContext;
60 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Status_argContext;
61 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Status_stmtContext;
62 import org.opendaylight.controller.antlrv4.code.gen.YangParser.StringContext;
63 import org.opendaylight.controller.antlrv4.code.gen.YangParser.String_restrictionsContext;
64 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
65 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Units_stmtContext;
66 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Uses_stmtContext;
67 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Value_stmtContext;
68 import org.opendaylight.controller.antlrv4.code.gen.YangParser.When_stmtContext;
69 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Yin_element_argContext;
70 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
71 import org.opendaylight.controller.yang.common.QName;
72 import org.opendaylight.controller.yang.model.api.MustDefinition;
73 import org.opendaylight.controller.yang.model.api.RevisionAwareXPath;
74 import org.opendaylight.controller.yang.model.api.SchemaPath;
75 import org.opendaylight.controller.yang.model.api.Status;
76 import org.opendaylight.controller.yang.model.api.TypeDefinition;
77 import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
78 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition;
79 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
80 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
81 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
82 import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
83 import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
84 import org.opendaylight.controller.yang.model.api.type.RangeConstraint;
85 import org.opendaylight.controller.yang.model.parser.builder.api.SchemaNodeBuilder;
86 import org.opendaylight.controller.yang.model.parser.builder.impl.ConstraintsBuilder;
87 import org.opendaylight.controller.yang.model.parser.util.RefineHolder.Refine;
88 import org.opendaylight.controller.yang.model.util.BaseConstraints;
89 import org.opendaylight.controller.yang.model.util.BinaryType;
90 import org.opendaylight.controller.yang.model.util.BitsType;
91 import org.opendaylight.controller.yang.model.util.Decimal64;
92 import org.opendaylight.controller.yang.model.util.EnumerationType;
93 import org.opendaylight.controller.yang.model.util.InstanceIdentifier;
94 import org.opendaylight.controller.yang.model.util.Int16;
95 import org.opendaylight.controller.yang.model.util.Int32;
96 import org.opendaylight.controller.yang.model.util.Int64;
97 import org.opendaylight.controller.yang.model.util.Int8;
98 import org.opendaylight.controller.yang.model.util.Leafref;
99 import org.opendaylight.controller.yang.model.util.RevisionAwareXPathImpl;
100 import org.opendaylight.controller.yang.model.util.StringType;
101 import org.opendaylight.controller.yang.model.util.Uint16;
102 import org.opendaylight.controller.yang.model.util.Uint32;
103 import org.opendaylight.controller.yang.model.util.Uint64;
104 import org.opendaylight.controller.yang.model.util.Uint8;
105 import org.opendaylight.controller.yang.model.util.UnknownType;
106 import org.slf4j.Logger;
107 import org.slf4j.LoggerFactory;
109 public final class YangModelBuilderUtil {
111 private static final Logger logger = LoggerFactory
112 .getLogger(YangModelBuilderUtil.class);
114 private YangModelBuilderUtil() {
118 * Parse given tree and get first string value.
122 * @return first string value from given tree
124 public static String stringFromNode(final ParseTree treeNode) {
125 final String result = "";
126 for (int i = 0; i < treeNode.getChildCount(); ++i) {
127 if (treeNode.getChild(i) instanceof StringContext) {
128 final StringContext context = (StringContext) treeNode
130 if (context != null) {
131 return context.getChild(0).getText().replace("\"", "");
139 * Parse 'description', 'reference' and 'status' statements and fill in
145 * builder to fill in with parsed statements
147 public static void parseSchemaNodeArgs(final ParseTree ctx,
148 final SchemaNodeBuilder builder) {
149 for (int i = 0; i < ctx.getChildCount(); i++) {
150 final ParseTree child = ctx.getChild(i);
151 if (child instanceof Description_stmtContext) {
152 final String desc = stringFromNode(child);
153 builder.setDescription(desc);
154 } else if (child instanceof Reference_stmtContext) {
155 final String ref = stringFromNode(child);
156 builder.setReference(ref);
157 } else if (child instanceof Status_stmtContext) {
158 final Status status = parseStatus((Status_stmtContext) child);
159 builder.setStatus(status);
165 * Parse given context and return its value;
169 * @return value parsed from context
171 public static Status parseStatus(final Status_stmtContext ctx) {
172 Status result = null;
173 for (int i = 0; i < ctx.getChildCount(); i++) {
174 ParseTree statusArg = ctx.getChild(i);
175 if (statusArg instanceof Status_argContext) {
176 String statusArgStr = stringFromNode(statusArg);
177 if ("current".equals(statusArgStr)) {
178 result = Status.CURRENT;
179 } else if ("deprecated".equals(statusArgStr)) {
180 result = Status.DEPRECATED;
181 } else if ("obsolete".equals(statusArgStr)) {
182 result = Status.OBSOLETE;
184 logger.warn("Invalid 'status' statement: " + statusArgStr);
192 * Parse given tree and returns units statement as string.
196 * @return value of units statement as string or null if there is no units
199 public static String parseUnits(final ParseTree ctx) {
201 for (int i = 0; i < ctx.getChildCount(); i++) {
202 ParseTree child = ctx.getChild(i);
203 if (child instanceof Units_stmtContext) {
204 units = stringFromNode(child);
212 * Create SchemaPath object from given path list with namespace, revision
213 * and prefix based on given values.
216 * current position in model
220 * @return SchemaPath object.
222 public static SchemaPath createActualSchemaPath(
223 final List<String> actualPath, final URI namespace,
224 final Date revision, final String prefix) {
225 final List<QName> path = new ArrayList<QName>();
227 // start from index 1 - module name omited
228 for (int i = 1; i < actualPath.size(); i++) {
229 qname = new QName(namespace, revision, prefix, actualPath.get(i));
232 return new SchemaPath(path, true);
236 * Create SchemaPath from given string.
239 * string representation of path
240 * @return SchemaPath object
242 public static SchemaPath parseAugmentPath(final String augmentPath) {
243 final boolean absolute = augmentPath.startsWith("/");
244 final String[] splittedPath = augmentPath.split("/");
245 List<QName> path = new ArrayList<QName>();
247 for (String pathElement : splittedPath) {
248 if (pathElement.length() > 0) {
249 String[] splittedElement = pathElement.split(":");
250 if (splittedElement.length == 1) {
251 name = new QName(null, null, null, splittedElement[0]);
253 name = new QName(null, null, splittedElement[0],
259 return new SchemaPath(path, absolute);
263 * Create java.util.List of QName objects from given key definition as
266 * @param keyDefinition
267 * key definition as string
274 * @return YANG list key as java.util.List of QName objects
276 public static List<QName> createListKey(final String keyDefinition,
277 final URI namespace, final Date revision, final String prefix) {
278 List<QName> key = new ArrayList<QName>();
279 String[] splittedKey = keyDefinition.split(" ");
282 for (String keyElement : splittedKey) {
283 if (keyElement.length() != 0) {
284 qname = new QName(namespace, revision, prefix, keyElement);
292 * Parse given type body of enumeration statement.
295 * type body context to parse
297 * actual position in YANG model
301 * @return List of EnumPair object parsed from given context
303 private static List<EnumTypeDefinition.EnumPair> getEnumConstants(
304 final Type_body_stmtsContext ctx, final List<String> path,
305 final URI namespace, final Date revision, final String prefix) {
306 List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<EnumTypeDefinition.EnumPair>();
308 for (int j = 0; j < ctx.getChildCount(); j++) {
309 ParseTree enumSpecChild = ctx.getChild(j);
310 if (enumSpecChild instanceof Enum_specificationContext) {
311 int highestValue = -1;
312 for (int k = 0; k < enumSpecChild.getChildCount(); k++) {
313 ParseTree enumChild = enumSpecChild.getChild(k);
314 if (enumChild instanceof Enum_stmtContext) {
315 EnumPair enumPair = createEnumPair(
316 (Enum_stmtContext) enumChild, highestValue,
317 path, namespace, revision, prefix);
318 if (enumPair.getValue() > highestValue) {
319 highestValue = enumPair.getValue();
321 enumConstants.add(enumPair);
326 return enumConstants;
330 * Parse enum statement context
333 * enum statement context
334 * @param highestValue
335 * current highest value in enumeration
337 * actual position in YANG model
341 * @return EnumPair object parsed from given context
343 private static EnumTypeDefinition.EnumPair createEnumPair(
344 final Enum_stmtContext ctx, final int highestValue,
345 final List<String> path, final URI namespace, final Date revision,
346 final String prefix) {
347 final String name = stringFromNode(ctx);
348 final QName qname = new QName(namespace, revision, prefix, name);
349 Integer value = null;
351 String description = null;
352 String reference = null;
353 Status status = null;
355 List<String> enumPairPath = new ArrayList<String>(path);
356 enumPairPath.add(name);
358 for (int i = 0; i < ctx.getChildCount(); i++) {
359 ParseTree child = ctx.getChild(i);
360 if (child instanceof Value_stmtContext) {
361 String valueStr = stringFromNode(child);
362 value = Integer.valueOf(valueStr);
363 } else if (child instanceof Description_stmtContext) {
364 description = stringFromNode(child);
365 } else if (child instanceof Reference_stmtContext) {
366 reference = stringFromNode(child);
367 } else if (child instanceof Status_stmtContext) {
368 status = parseStatus((Status_stmtContext) child);
373 value = highestValue + 1;
375 if (value < -2147483648 || value > 2147483647) {
376 throw new YangParseException(
379 + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: "
383 EnumPairImpl result = new EnumPairImpl();
384 result.qname = qname;
385 result.path = createActualSchemaPath(enumPairPath, namespace, revision,
387 result.description = description;
388 result.reference = reference;
389 result.status = status;
391 result.value = value;
396 * Internal implementation of EnumPair.
398 private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
400 private SchemaPath path;
401 private String description;
402 private String reference;
403 private Status status;
404 private List<UnknownSchemaNode> extensionSchemaNodes = Collections
407 private Integer value;
410 public QName getQName() {
415 public SchemaPath getPath() {
420 public String getDescription() {
425 public String getReference() {
430 public Status getStatus() {
435 public List<UnknownSchemaNode> getUnknownSchemaNodes() {
436 return extensionSchemaNodes;
440 public String getName() {
445 public Integer getValue() {
450 public int hashCode() {
451 final int prime = 31;
453 result = prime * result + ((qname == null) ? 0 : qname.hashCode());
454 result = prime * result + ((path == null) ? 0 : path.hashCode());
457 + ((extensionSchemaNodes == null) ? 0
458 : extensionSchemaNodes.hashCode());
459 result = prime * result + ((name == null) ? 0 : name.hashCode());
460 result = prime * result + ((value == null) ? 0 : value.hashCode());
465 public boolean equals(Object obj) {
472 if (getClass() != obj.getClass()) {
475 EnumPairImpl other = (EnumPairImpl) obj;
477 if (other.qname != null) {
480 } else if (!qname.equals(other.qname)) {
484 if (other.path != null) {
487 } else if (!path.equals(other.path)) {
490 if (extensionSchemaNodes == null) {
491 if (other.extensionSchemaNodes != null) {
494 } else if (!extensionSchemaNodes.equals(other.extensionSchemaNodes)) {
498 if (other.name != null) {
501 } else if (!name.equals(other.name)) {
505 if (other.value != null) {
508 } else if (!value.equals(other.value)) {
515 public String toString() {
516 return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name="
517 + name + ", value=" + value + "]";
522 * Get and parse range from given type body context.
525 * type body context to parse
526 * @return List of RangeConstraint created from this context
528 private static List<RangeConstraint> getRangeConstraints(
529 final Type_body_stmtsContext ctx) {
530 List<RangeConstraint> rangeConstraints = Collections.emptyList();
531 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
532 ParseTree numRestrChild = ctx.getChild(j);
533 if (numRestrChild instanceof Numerical_restrictionsContext) {
534 for (int k = 0; k < numRestrChild.getChildCount(); k++) {
535 ParseTree rangeChild = numRestrChild.getChild(k);
536 if (rangeChild instanceof Range_stmtContext) {
537 rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild);
543 return rangeConstraints;
547 * Parse given range context.
550 * range context to parse
551 * @return List of RangeConstraints parsed from this context
553 private static List<RangeConstraint> parseRangeConstraints(
554 final Range_stmtContext ctx) {
555 List<RangeConstraint> rangeConstraints = new ArrayList<RangeConstraint>();
556 String description = null;
557 String reference = null;
559 for (int i = 0; i < ctx.getChildCount(); i++) {
560 ParseTree child = ctx.getChild(i);
561 if (child instanceof Description_stmtContext) {
562 description = stringFromNode(child);
563 } else if (child instanceof Reference_stmtContext) {
564 reference = stringFromNode(child);
568 String rangeStr = stringFromNode(ctx);
569 String trimmed = rangeStr.replace(" ", "");
570 String[] splittedRange = trimmed.split("\\|");
571 for (String rangeDef : splittedRange) {
572 String[] splittedRangeDef = rangeDef.split("\\.\\.");
575 if (splittedRangeDef.length == 1) {
576 min = max = parseNumberConstraintValue(splittedRangeDef[0]);
578 min = parseNumberConstraintValue(splittedRangeDef[0]);
579 max = parseNumberConstraintValue(splittedRangeDef[1]);
581 RangeConstraint range = BaseConstraints.rangeConstraint(min, max,
582 description, reference);
583 rangeConstraints.add(range);
586 return rangeConstraints;
590 * Get and parse length from given type body context.
593 * type body context to parse
594 * @return List of LengthConstraint created from this context
596 private static List<LengthConstraint> getLengthConstraints(
597 final Type_body_stmtsContext ctx) {
598 List<LengthConstraint> lengthConstraints = Collections.emptyList();
599 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
600 ParseTree stringRestrChild = ctx.getChild(j);
601 if (stringRestrChild instanceof String_restrictionsContext) {
602 for (int k = 0; k < stringRestrChild.getChildCount(); k++) {
603 ParseTree lengthChild = stringRestrChild.getChild(k);
604 if (lengthChild instanceof Length_stmtContext) {
605 lengthConstraints = parseLengthConstraints((Length_stmtContext) lengthChild);
611 return lengthConstraints;
615 * Parse given length context.
618 * length context to parse
619 * @return List of LengthConstraints parsed from this context
621 private static List<LengthConstraint> parseLengthConstraints(
622 final Length_stmtContext ctx) {
623 List<LengthConstraint> lengthConstraints = new ArrayList<LengthConstraint>();
624 String description = null;
625 String reference = null;
627 for (int i = 0; i < ctx.getChildCount(); i++) {
628 ParseTree child = ctx.getChild(i);
629 if (child instanceof Description_stmtContext) {
630 description = stringFromNode(child);
631 } else if (child instanceof Reference_stmtContext) {
632 reference = stringFromNode(child);
636 String lengthStr = stringFromNode(ctx);
637 String trimmed = lengthStr.replace(" ", "");
638 String[] splittedRange = trimmed.split("\\|");
639 for (String rangeDef : splittedRange) {
640 String[] splittedRangeDef = rangeDef.split("\\.\\.");
643 if (splittedRangeDef.length == 1) {
644 min = max = parseNumberConstraintValue(splittedRangeDef[0]);
646 min = parseNumberConstraintValue(splittedRangeDef[0]);
647 max = parseNumberConstraintValue(splittedRangeDef[1]);
649 LengthConstraint range = BaseConstraints.lengthConstraint(min, max,
650 description, reference);
651 lengthConstraints.add(range);
654 return lengthConstraints;
660 * @return wrapper object of primitive java type or UnknownBoundaryNumber if
661 * type is one of special YANG values 'min' or 'max'
663 private static Number parseNumberConstraintValue(final String value) {
664 Number result = null;
665 if ("min".equals(value) || "max".equals(value)) {
666 result = new UnknownBoundaryNumber(value);
669 result = Long.valueOf(value);
670 } catch (NumberFormatException e) {
671 throw new YangParseException("Unable to parse range value '"
678 private static List<PatternConstraint> getPatternConstraint(
679 final Type_body_stmtsContext ctx) {
680 List<PatternConstraint> patterns = new ArrayList<PatternConstraint>();
682 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
683 ParseTree stringRestrChild = ctx.getChild(j);
684 if (stringRestrChild instanceof String_restrictionsContext) {
685 for (int k = 0; k < stringRestrChild.getChildCount(); k++) {
686 ParseTree lengthChild = stringRestrChild.getChild(k);
687 if (lengthChild instanceof Pattern_stmtContext) {
688 patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
689 if (k == lengthChild.getChildCount() - 1) {
700 * Internal helper method.
704 * @return PatternConstraint object
706 private static PatternConstraint parsePatternConstraint(
707 final Pattern_stmtContext ctx) {
708 String description = null;
709 String reference = null;
710 for (int i = 0; i < ctx.getChildCount(); i++) {
711 ParseTree child = ctx.getChild(i);
712 if (child instanceof Description_stmtContext) {
713 description = stringFromNode(child);
714 } else if (child instanceof Reference_stmtContext) {
715 reference = stringFromNode(child);
718 String pattern = patternStringFromNode(ctx);
719 return BaseConstraints.patternConstraint(pattern, description,
724 * Parse given context and return pattern value.
728 * @return pattern value as String
730 public static String patternStringFromNode(final Pattern_stmtContext ctx) {
731 StringBuilder result = new StringBuilder();
732 for (int i = 0; i < ctx.getChildCount(); ++i) {
733 ParseTree child = ctx.getChild(i);
734 if (child instanceof StringContext) {
735 for (int j = 0; j < child.getChildCount(); j++) {
737 String patternToken = child.getChild(j).getText();
738 result.append(patternToken.substring(1,
739 patternToken.length() - 1));
744 return result.toString();
748 * Get fraction digits value from context.
751 * type body context to parse
752 * @return 'fraction-digits' value if present in given context, null
755 private static Integer getFractionDigits(Type_body_stmtsContext ctx) {
756 Integer result = null;
757 for (int j = 0; j < ctx.getChildCount(); j++) {
758 ParseTree dec64specChild = ctx.getChild(j);
759 if (dec64specChild instanceof Decimal64_specificationContext) {
760 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild);
766 private static Integer parseFractionDigits(
767 Decimal64_specificationContext ctx) {
768 Integer result = null;
769 for (int k = 0; k < ctx.getChildCount(); k++) {
770 ParseTree fdChild = ctx.getChild(k);
771 if (fdChild instanceof Fraction_digits_stmtContext) {
772 String value = stringFromNode(fdChild);
774 result = Integer.valueOf(value);
775 } catch (NumberFormatException e) {
776 throw new YangParseException(
777 "Unable to parse fraction digits value '" + value
786 * Internal helper method for parsing bit statements from given type body
790 * type body context to parse
792 * current position in YANG model
796 * @return List of Bit objects created from this context
798 private static List<BitsTypeDefinition.Bit> getBits(
799 Type_body_stmtsContext ctx, List<String> actualPath, URI namespace,
800 Date revision, String prefix) {
801 final List<BitsTypeDefinition.Bit> bits = new ArrayList<BitsTypeDefinition.Bit>();
802 for (int j = 0; j < ctx.getChildCount(); j++) {
803 ParseTree bitsSpecChild = ctx.getChild(j);
804 if (bitsSpecChild instanceof Bits_specificationContext) {
805 long highestPosition = -1;
806 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
807 ParseTree bitChild = bitsSpecChild.getChild(k);
808 if (bitChild instanceof Bit_stmtContext) {
809 Bit bit = parseBit((Bit_stmtContext) bitChild,
810 highestPosition, actualPath, namespace,
812 if (bit.getPosition() > highestPosition) {
813 highestPosition = bit.getPosition();
824 * Internal helper method for parsing bit context.
827 * bit statement context to parse
828 * @param highestPosition
829 * current highest position in bits type
831 * current position in YANG model
835 * @return Bit object parsed from this context
837 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx,
838 long highestPosition, List<String> actualPath, final URI namespace,
839 final Date revision, final String prefix) {
840 String name = stringFromNode(ctx);
841 final QName qname = new QName(namespace, revision, prefix, name);
842 Long position = null;
844 String description = null;
845 String reference = null;
846 Status status = Status.CURRENT;
848 Stack<String> bitPath = new Stack<String>();
849 bitPath.addAll(actualPath);
852 SchemaPath schemaPath = createActualSchemaPath(bitPath, namespace,
855 for (int i = 0; i < ctx.getChildCount(); i++) {
856 ParseTree child = ctx.getChild(i);
857 if (child instanceof Position_stmtContext) {
858 String positionStr = stringFromNode(child);
859 position = Long.valueOf(positionStr);
860 } else if (child instanceof Description_stmtContext) {
861 description = stringFromNode(child);
862 } else if (child instanceof Reference_stmtContext) {
863 reference = stringFromNode(child);
864 } else if (child instanceof Status_stmtContext) {
865 status = parseStatus((Status_stmtContext) child);
869 if (position == null) {
870 position = highestPosition + 1;
872 if (position < 0 || position > 4294967295L) {
873 throw new YangParseException(
876 + "': the position value MUST be in the range 0 to 4294967295");
879 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
880 return new BitImpl(position, qname, schemaPath, description, reference,
881 status, unknownNodes);
885 * Parse orderedby statement.
888 * Ordered_by_stmtContext
889 * @return true, if orderedby contains value 'user' or false otherwise
891 public static boolean parseUserOrdered(Ordered_by_stmtContext childNode) {
892 boolean result = false;
893 for (int j = 0; j < childNode.getChildCount(); j++) {
894 ParseTree orderArg = childNode.getChild(j);
895 if (orderArg instanceof Ordered_by_argContext) {
896 String orderStr = stringFromNode(orderArg);
897 if ("system".equals(orderStr)) {
899 } else if ("user".equals(orderStr)) {
902 logger.warn("Invalid 'orderedby' statement.");
910 * Parse given config context and return true if it contains string 'true',
914 * config context to parse.
915 * @return true if given context contains string 'true', false otherwise
917 public static boolean parseConfig(final Config_stmtContext ctx) {
918 boolean result = false;
920 for (int i = 0; i < ctx.getChildCount(); ++i) {
921 final ParseTree configContext = ctx.getChild(i);
922 if (configContext instanceof Config_argContext) {
923 final String value = stringFromNode(configContext);
924 if ("true".equals(value)) {
935 * Parse given type body and creates UnknownType definition.
937 * @param typedefQName
938 * qname of current type
941 * @return UnknownType object with constraints from parsed type body
943 public static TypeDefinition<?> parseUnknownTypeBody(QName typedefQName,
944 Type_body_stmtsContext ctx) {
945 UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
948 List<RangeConstraint> rangeStatements = getRangeConstraints(ctx);
949 List<LengthConstraint> lengthStatements = getLengthConstraints(ctx);
950 List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
951 Integer fractionDigits = getFractionDigits(ctx);
953 unknownType.rangeStatements(rangeStatements);
954 unknownType.lengthStatements(lengthStatements);
955 unknownType.patterns(patternStatements);
956 unknownType.fractionDigits(fractionDigits);
959 return unknownType.build();
963 * Create TypeDefinition object based on given type name and type body.
970 * current path in schema
977 * @return TypeDefinition object based on parsed values.
979 public static TypeDefinition<?> parseTypeBody(final String typeName,
980 final Type_body_stmtsContext typeBody,
981 final List<String> actualPath, final URI namespace,
982 final Date revision, final String prefix) {
983 TypeDefinition<?> type = null;
985 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody);
986 Integer fractionDigits = getFractionDigits(typeBody);
987 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody);
988 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
989 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(
990 typeBody, actualPath, namespace, revision, prefix);
992 if ("decimal64".equals(typeName)) {
993 type = new Decimal64(actualPath, namespace, revision, fractionDigits);
994 } else if (typeName.startsWith("int")) {
995 if (typeName.equals("int8")) {
996 type = new Int8(actualPath, namespace, revision, rangeStatements, null, null);
997 } else if (typeName.equals("int16")) {
998 type = new Int16(actualPath, namespace, revision, rangeStatements, null, null);
999 } else if (typeName.equals("int32")) {
1000 type = new Int32(actualPath, namespace, revision, rangeStatements, null, null);
1001 } else if (typeName.equals("int64")) {
1002 type = new Int64(actualPath, namespace, revision, rangeStatements, null, null);
1004 } else if (typeName.startsWith("uint")) {
1005 if (typeName.equals("uint8")) {
1006 type = new Uint8(actualPath, namespace, revision, rangeStatements, null, null);
1007 } else if (typeName.equals("uint16")) {
1008 type = new Uint16(actualPath, namespace, revision, rangeStatements, null, null);
1009 } else if (typeName.equals("uint32")) {
1010 type = new Uint32(actualPath, namespace, revision, rangeStatements, null, null);
1011 } else if (typeName.equals("uint64")) {
1012 type = new Uint64(actualPath, namespace, revision, rangeStatements, null, null);
1014 } else if ("enumeration".equals(typeName)) {
1015 type = new EnumerationType(actualPath, namespace, revision,
1017 } else if ("string".equals(typeName)) {
1018 type = new StringType(actualPath, namespace, revision, lengthStatements, patternStatements);
1019 } else if ("bits".equals(typeName)) {
1020 type = new BitsType(getBits(typeBody, actualPath, namespace,
1022 } else if ("leafref".equals(typeName)) {
1023 final String path = parseLeafrefPath(typeBody);
1024 final boolean absolute = path.startsWith("/");
1025 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path,
1027 type = new Leafref(actualPath, namespace, revision, xpath);
1028 } else if ("binary".equals(typeName)) {
1029 List<Byte> bytes = Collections.emptyList();
1030 type = new BinaryType(bytes, lengthStatements, null);
1031 } else if ("instance-identifier".equals(typeName)) {
1032 boolean requireInstance = isRequireInstance(typeBody);
1033 type = new InstanceIdentifier(null, requireInstance);
1038 public static String getIdentityrefBase(Type_body_stmtsContext ctx) {
1039 String result = null;
1041 for (int i = 0; i < ctx.getChildCount(); i++) {
1042 ParseTree child = ctx.getChild(i);
1043 if (child instanceof Identityref_specificationContext) {
1044 for (int j = 0; j < child.getChildCount(); j++) {
1045 ParseTree baseArg = child.getChild(j);
1046 if (baseArg instanceof Base_stmtContext) {
1047 result = stringFromNode(baseArg);
1056 private static boolean isRequireInstance(Type_body_stmtsContext ctx) {
1057 for (int i = 0; i < ctx.getChildCount(); i++) {
1058 ParseTree child = ctx.getChild(i);
1059 if (child instanceof Require_instance_stmtContext) {
1060 for (int j = 0; j < child.getChildCount(); j++) {
1061 ParseTree reqArg = child.getChild(j);
1062 if (reqArg instanceof Require_instance_argContext) {
1063 return Boolean.valueOf(stringFromNode(reqArg));
1071 private static String parseLeafrefPath(Type_body_stmtsContext ctx) {
1072 for (int i = 0; i < ctx.getChildCount(); i++) {
1073 ParseTree child = ctx.getChild(i);
1074 if (child instanceof Leafref_specificationContext) {
1075 for (int j = 0; j < child.getChildCount(); j++) {
1076 ParseTree leafRefSpec = child.getChild(j);
1077 if (leafRefSpec instanceof Path_stmtContext) {
1078 return stringFromNode(leafRefSpec);
1087 * Internal helper method for parsing Must_stmtContext.
1091 * @return MustDefinition object based on parsed context
1093 public static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1094 StringBuilder mustText = new StringBuilder();
1095 String description = null;
1096 String reference = null;
1097 String errorAppTag = null;
1098 String errorMessage = null;
1099 for (int i = 0; i < ctx.getChildCount(); ++i) {
1100 ParseTree child = ctx.getChild(i);
1101 if (child instanceof StringContext) {
1102 final StringContext context = (StringContext) child;
1103 if (context.getChildCount() == 1) {
1104 String mustPart = context.getChild(0).getText();
1105 // trim start and end quotation
1106 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1108 for (int j = 0; j < context.getChildCount(); j++) {
1109 String mustPart = context.getChild(j).getText();
1111 mustText.append(mustPart.substring(0,
1112 mustPart.length() - 1));
1116 mustText.append(mustPart.substring(1));
1120 } else if (child instanceof Description_stmtContext) {
1121 description = stringFromNode(child);
1122 } else if (child instanceof Reference_stmtContext) {
1123 reference = stringFromNode(child);
1124 } else if (child instanceof Error_app_tag_stmtContext) {
1125 errorAppTag = stringFromNode(child);
1126 } else if (child instanceof Error_message_stmtContext) {
1127 errorMessage = stringFromNode(child);
1131 MustDefinition must = new MustDefinitionImpl(mustText.toString(),
1132 description, reference, errorAppTag, errorMessage);
1137 * Parse given tree and set constraints to given builder.
1141 * @param constraints
1142 * ConstraintsBuilder to fill
1144 public static void parseConstraints(final ParseTree ctx,
1145 final ConstraintsBuilder constraints) {
1146 for (int i = 0; i < ctx.getChildCount(); ++i) {
1147 final ParseTree childNode = ctx.getChild(i);
1148 if (childNode instanceof Max_elements_stmtContext) {
1149 Integer max = Integer.valueOf(stringFromNode(childNode));
1150 constraints.setMinElements(max);
1151 } else if (childNode instanceof Min_elements_stmtContext) {
1152 Integer min = Integer.valueOf(stringFromNode(childNode));
1153 constraints.setMinElements(min);
1154 } else if (childNode instanceof Must_stmtContext) {
1155 MustDefinition must = parseMust((Must_stmtContext) childNode);
1156 constraints.addMustDefinition(must);
1157 } else if (childNode instanceof Mandatory_stmtContext) {
1158 for (int j = 0; j < childNode.getChildCount(); j++) {
1159 ParseTree mandatoryTree = ctx.getChild(j);
1160 if (mandatoryTree instanceof Mandatory_argContext) {
1161 Boolean mandatory = Boolean
1162 .valueOf(stringFromNode(mandatoryTree));
1163 constraints.setMandatory(mandatory);
1166 } else if (childNode instanceof When_stmtContext) {
1167 constraints.addWhenCondition(stringFromNode(childNode));
1173 * Parse given context and return yin value.
1177 * @return true if value is 'true', false otherwise
1179 public static boolean parseYinValue(Argument_stmtContext ctx) {
1180 boolean yinValue = false;
1181 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
1182 ParseTree yin = ctx.getChild(j);
1183 if (yin instanceof Yin_element_stmtContext) {
1184 for (int k = 0; k < yin.getChildCount(); k++) {
1185 ParseTree yinArg = yin.getChild(k);
1186 if (yinArg instanceof Yin_element_argContext) {
1187 String yinString = stringFromNode(yinArg);
1188 if ("true".equals(yinString)) {
1199 public static List<RefineHolder> parseRefines(Uses_stmtContext ctx) {
1200 List<RefineHolder> refines = new ArrayList<RefineHolder>();
1202 for (int i = 0; i < ctx.getChildCount(); i++) {
1203 ParseTree child = ctx.getChild(i);
1204 if (child instanceof Refine_stmtContext) {
1205 final String refineTarget = stringFromNode(child);
1206 final RefineHolder refine = new RefineHolder(refineTarget);
1207 for (int j = 0; j < child.getChildCount(); j++) {
1208 ParseTree refinePom = child.getChild(j);
1209 if (refinePom instanceof Refine_pomContext) {
1210 for (int k = 0; k < refinePom.getChildCount(); k++) {
1211 ParseTree refineStmt = refinePom.getChild(k);
1212 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1214 (Refine_leaf_stmtsContext) refineStmt);
1215 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1218 (Refine_container_stmtsContext) refineStmt);
1219 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1221 (Refine_list_stmtsContext) refineStmt);
1222 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1225 (Refine_leaf_list_stmtsContext) refineStmt);
1226 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1228 (Refine_choice_stmtsContext) refineStmt);
1229 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1231 (Refine_anyxml_stmtsContext) refineStmt);
1236 refines.add(refine);
1242 private static RefineHolder parseRefine(RefineHolder refine,
1243 Refine_leaf_stmtsContext refineStmt) {
1244 refine.setType(Refine.LEAF);
1245 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1246 ParseTree refineArg = refineStmt.getChild(i);
1247 if (refineArg instanceof Default_stmtContext) {
1248 String defaultStr = stringFromNode(refineArg);
1249 refine.setDefaultStr(defaultStr);
1250 } else if (refineArg instanceof Mandatory_stmtContext) {
1251 for (int j = 0; j < refineArg.getChildCount(); j++) {
1252 ParseTree mandatoryTree = refineArg.getChild(j);
1253 if (mandatoryTree instanceof Mandatory_argContext) {
1254 Boolean mandatory = Boolean
1255 .valueOf(stringFromNode(mandatoryTree));
1256 refine.setMandatory(mandatory);
1259 } else if (refineArg instanceof Must_stmtContext) {
1260 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1261 refine.setMust(must);
1268 private static RefineHolder parseRefine(RefineHolder refine,
1269 Refine_container_stmtsContext refineStmt) {
1270 refine.setType(Refine.CONTAINER);
1271 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1272 ParseTree refineArg = refineStmt.getChild(m);
1273 if (refineArg instanceof Must_stmtContext) {
1274 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1275 refine.setMust(must);
1276 } else if (refineArg instanceof Presence_stmtContext) {
1277 refine.setPresence(true);
1283 private static RefineHolder parseRefine(RefineHolder refine,
1284 Refine_list_stmtsContext refineStmt) {
1285 refine.setType(Refine.LIST);
1286 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1287 ParseTree refineArg = refineStmt.getChild(m);
1288 if (refineArg instanceof Must_stmtContext) {
1289 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1290 refine.setMust(must);
1291 } else if (refineArg instanceof Max_elements_stmtContext) {
1292 Integer max = Integer.valueOf(stringFromNode(refineArg));
1293 refine.setMinElements(max);
1294 } else if (refineArg instanceof Min_elements_stmtContext) {
1295 Integer min = Integer.valueOf(stringFromNode(refineArg));
1296 refine.setMinElements(min);
1302 private static RefineHolder parseRefine(RefineHolder refine,
1303 Refine_leaf_list_stmtsContext refineStmt) {
1304 refine.setType(Refine.LEAF_LIST);
1305 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1306 ParseTree refineArg = refineStmt.getChild(m);
1307 if (refineArg instanceof Must_stmtContext) {
1308 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1309 refine.setMust(must);
1310 } else if (refineArg instanceof Max_elements_stmtContext) {
1311 Integer max = Integer.valueOf(stringFromNode(refineArg));
1312 refine.setMinElements(max);
1313 } else if (refineArg instanceof Min_elements_stmtContext) {
1314 Integer min = Integer.valueOf(stringFromNode(refineArg));
1315 refine.setMinElements(min);
1321 private static RefineHolder parseRefine(RefineHolder refine,
1322 Refine_choice_stmtsContext refineStmt) {
1323 refine.setType(Refine.CHOICE);
1324 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1325 ParseTree refineArg = refineStmt.getChild(i);
1326 if (refineArg instanceof Default_stmtContext) {
1327 String defaultStr = stringFromNode(refineArg);
1328 refine.setDefaultStr(defaultStr);
1329 } else if (refineArg instanceof Mandatory_stmtContext) {
1330 for (int j = 0; j < refineArg.getChildCount(); j++) {
1331 ParseTree mandatoryTree = refineArg.getChild(j);
1332 if (mandatoryTree instanceof Mandatory_argContext) {
1333 Boolean mandatory = Boolean
1334 .valueOf(stringFromNode(mandatoryTree));
1335 refine.setMandatory(mandatory);
1343 private static RefineHolder parseRefine(RefineHolder refine,
1344 Refine_anyxml_stmtsContext refineStmt) {
1345 refine.setType(Refine.ANYXML);
1346 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1347 ParseTree refineArg = refineStmt.getChild(i);
1348 if (refineArg instanceof Must_stmtContext) {
1349 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1350 refine.setMust(must);
1351 } else if (refineArg instanceof Mandatory_stmtContext) {
1352 for (int j = 0; j < refineArg.getChildCount(); j++) {
1353 ParseTree mandatoryTree = refineArg.getChild(j);
1354 if (mandatoryTree instanceof Mandatory_argContext) {
1355 Boolean mandatory = Boolean
1356 .valueOf(stringFromNode(mandatoryTree));
1357 refine.setMandatory(mandatory);