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.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.Max_value_argContext;
40 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Min_elements_stmtContext;
41 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Min_value_argContext;
42 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Must_stmtContext;
43 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Numerical_restrictionsContext;
44 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Ordered_by_argContext;
45 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
46 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Path_stmtContext;
47 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Pattern_stmtContext;
48 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Position_stmtContext;
49 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Presence_stmtContext;
50 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Range_stmtContext;
51 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Reference_stmtContext;
52 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_anyxml_stmtsContext;
53 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_choice_stmtsContext;
54 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_container_stmtsContext;
55 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_leaf_list_stmtsContext;
56 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_leaf_stmtsContext;
57 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_list_stmtsContext;
58 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_pomContext;
59 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Refine_stmtContext;
60 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Require_instance_argContext;
61 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Require_instance_stmtContext;
62 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Status_argContext;
63 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Status_stmtContext;
64 import org.opendaylight.controller.antlrv4.code.gen.YangParser.StringContext;
65 import org.opendaylight.controller.antlrv4.code.gen.YangParser.String_restrictionsContext;
66 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
67 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Units_stmtContext;
68 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Value_stmtContext;
69 import org.opendaylight.controller.antlrv4.code.gen.YangParser.When_stmtContext;
70 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Yin_element_argContext;
71 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
72 import org.opendaylight.controller.yang.common.QName;
73 import org.opendaylight.controller.yang.model.api.MustDefinition;
74 import org.opendaylight.controller.yang.model.api.RevisionAwareXPath;
75 import org.opendaylight.controller.yang.model.api.SchemaPath;
76 import org.opendaylight.controller.yang.model.api.Status;
77 import org.opendaylight.controller.yang.model.api.TypeDefinition;
78 import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
79 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition;
80 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
81 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
82 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
83 import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
84 import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
85 import org.opendaylight.controller.yang.model.api.type.RangeConstraint;
86 import org.opendaylight.controller.yang.model.util.BaseConstraints;
87 import org.opendaylight.controller.yang.model.util.BinaryType;
88 import org.opendaylight.controller.yang.model.util.BitsType;
89 import org.opendaylight.controller.yang.model.util.Decimal64;
90 import org.opendaylight.controller.yang.model.util.EnumerationType;
91 import org.opendaylight.controller.yang.model.util.InstanceIdentifier;
92 import org.opendaylight.controller.yang.model.util.Int16;
93 import org.opendaylight.controller.yang.model.util.Int32;
94 import org.opendaylight.controller.yang.model.util.Int64;
95 import org.opendaylight.controller.yang.model.util.Int8;
96 import org.opendaylight.controller.yang.model.util.Leafref;
97 import org.opendaylight.controller.yang.model.util.RevisionAwareXPathImpl;
98 import org.opendaylight.controller.yang.model.util.StringType;
99 import org.opendaylight.controller.yang.model.util.Uint16;
100 import org.opendaylight.controller.yang.model.util.Uint32;
101 import org.opendaylight.controller.yang.model.util.Uint64;
102 import org.opendaylight.controller.yang.model.util.Uint8;
103 import org.opendaylight.controller.yang.model.util.UnknownType;
104 import org.opendaylight.controller.yang.parser.builder.api.SchemaNodeBuilder;
105 import org.opendaylight.controller.yang.parser.builder.impl.ConstraintsBuilder;
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(
377 ctx.getStart().getLine(),
380 + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: "
384 EnumPairImpl result = new EnumPairImpl();
385 result.qname = qname;
386 result.path = createActualSchemaPath(enumPairPath, namespace, revision,
388 result.description = description;
389 result.reference = reference;
390 result.status = status;
392 result.value = value;
397 * Internal implementation of EnumPair.
399 private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
401 private SchemaPath path;
402 private String description;
403 private String reference;
404 private Status status;
405 private List<UnknownSchemaNode> extensionSchemaNodes = Collections
408 private Integer value;
411 public QName getQName() {
416 public SchemaPath getPath() {
421 public String getDescription() {
426 public String getReference() {
431 public Status getStatus() {
436 public List<UnknownSchemaNode> getUnknownSchemaNodes() {
437 return extensionSchemaNodes;
441 public String getName() {
446 public Integer getValue() {
451 public int hashCode() {
452 final int prime = 31;
454 result = prime * result + ((qname == null) ? 0 : qname.hashCode());
455 result = prime * result + ((path == null) ? 0 : path.hashCode());
458 + ((extensionSchemaNodes == null) ? 0
459 : extensionSchemaNodes.hashCode());
460 result = prime * result + ((name == null) ? 0 : name.hashCode());
461 result = prime * result + ((value == null) ? 0 : value.hashCode());
466 public boolean equals(Object obj) {
473 if (getClass() != obj.getClass()) {
476 EnumPairImpl other = (EnumPairImpl) obj;
478 if (other.qname != null) {
481 } else if (!qname.equals(other.qname)) {
485 if (other.path != null) {
488 } else if (!path.equals(other.path)) {
491 if (extensionSchemaNodes == null) {
492 if (other.extensionSchemaNodes != null) {
495 } else if (!extensionSchemaNodes.equals(other.extensionSchemaNodes)) {
499 if (other.name != null) {
502 } else if (!name.equals(other.name)) {
506 if (other.value != null) {
509 } else if (!value.equals(other.value)) {
516 public String toString() {
517 return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name="
518 + name + ", value=" + value + "]";
523 * Get and parse range from given type body context.
526 * type body context to parse
527 * @return List of RangeConstraint created from this context
529 private static List<RangeConstraint> getRangeConstraints(
530 final Type_body_stmtsContext ctx) {
531 List<RangeConstraint> rangeConstraints = Collections.emptyList();
532 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
533 ParseTree numRestrChild = ctx.getChild(j);
534 if (numRestrChild instanceof Numerical_restrictionsContext) {
535 for (int k = 0; k < numRestrChild.getChildCount(); k++) {
536 ParseTree rangeChild = numRestrChild.getChild(k);
537 if (rangeChild instanceof Range_stmtContext) {
538 rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild);
544 return rangeConstraints;
548 * Parse given range context.
551 * range context to parse
552 * @return List of RangeConstraints parsed from this context
554 private static List<RangeConstraint> parseRangeConstraints(
555 final Range_stmtContext ctx) {
556 final int line = ctx.getStart().getLine();
557 List<RangeConstraint> rangeConstraints = new ArrayList<RangeConstraint>();
558 String description = null;
559 String reference = null;
561 for (int i = 0; i < ctx.getChildCount(); i++) {
562 ParseTree child = ctx.getChild(i);
563 if (child instanceof Description_stmtContext) {
564 description = stringFromNode(child);
565 } else if (child instanceof Reference_stmtContext) {
566 reference = stringFromNode(child);
570 String rangeStr = stringFromNode(ctx);
571 String trimmed = rangeStr.replace(" ", "");
572 String[] splittedRange = trimmed.split("\\|");
573 for (String rangeDef : splittedRange) {
574 String[] splittedRangeDef = rangeDef.split("\\.\\.");
577 if (splittedRangeDef.length == 1) {
578 min = max = parseNumberConstraintValue(splittedRangeDef[0],
581 min = parseNumberConstraintValue(splittedRangeDef[0], line);
582 max = parseNumberConstraintValue(splittedRangeDef[1], line);
584 RangeConstraint range = BaseConstraints.rangeConstraint(min, max,
585 description, reference);
586 rangeConstraints.add(range);
589 return rangeConstraints;
593 * Get and parse length from given type body context.
596 * type body context to parse
597 * @return List of LengthConstraint created from this context
599 private static List<LengthConstraint> getLengthConstraints(
600 final Type_body_stmtsContext ctx) {
601 List<LengthConstraint> lengthConstraints = Collections.emptyList();
602 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
603 ParseTree stringRestrChild = ctx.getChild(j);
604 if (stringRestrChild instanceof String_restrictionsContext) {
605 for (int k = 0; k < stringRestrChild.getChildCount(); k++) {
606 ParseTree lengthChild = stringRestrChild.getChild(k);
607 if (lengthChild instanceof Length_stmtContext) {
608 lengthConstraints = parseLengthConstraints((Length_stmtContext) lengthChild);
614 return lengthConstraints;
618 * Parse given length context.
621 * length context to parse
622 * @return List of LengthConstraints parsed from this context
624 private static List<LengthConstraint> parseLengthConstraints(
625 final Length_stmtContext ctx) {
626 final int line = ctx.getStart().getLine();
627 List<LengthConstraint> lengthConstraints = new ArrayList<LengthConstraint>();
628 String description = null;
629 String reference = null;
631 for (int i = 0; i < ctx.getChildCount(); i++) {
632 ParseTree child = ctx.getChild(i);
633 if (child instanceof Description_stmtContext) {
634 description = stringFromNode(child);
635 } else if (child instanceof Reference_stmtContext) {
636 reference = stringFromNode(child);
640 String lengthStr = stringFromNode(ctx);
641 String trimmed = lengthStr.replace(" ", "");
642 String[] splittedRange = trimmed.split("\\|");
643 for (String rangeDef : splittedRange) {
644 String[] splittedRangeDef = rangeDef.split("\\.\\.");
647 if (splittedRangeDef.length == 1) {
648 min = max = parseNumberConstraintValue(splittedRangeDef[0],
651 min = parseNumberConstraintValue(splittedRangeDef[0], line);
652 max = parseNumberConstraintValue(splittedRangeDef[1], line);
654 LengthConstraint range = BaseConstraints.lengthConstraint(min, max,
655 description, reference);
656 lengthConstraints.add(range);
659 return lengthConstraints;
665 * @return wrapper object of primitive java type or UnknownBoundaryNumber if
666 * type is one of special YANG values 'min' or 'max'
668 private static Number parseNumberConstraintValue(final String value,
670 Number result = null;
671 if ("min".equals(value) || "max".equals(value)) {
672 result = new UnknownBoundaryNumber(value);
675 result = Long.valueOf(value);
676 } catch (NumberFormatException e) {
677 throw new YangParseException(line,
678 "Unable to parse range value '" + value + "'.", e);
685 * Parse type body and return pattern constraints.
689 * @return list of pattern constraints
691 private static List<PatternConstraint> getPatternConstraint(
692 final Type_body_stmtsContext ctx) {
693 List<PatternConstraint> patterns = new ArrayList<PatternConstraint>();
695 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
696 ParseTree stringRestrChild = ctx.getChild(j);
697 if (stringRestrChild instanceof String_restrictionsContext) {
698 for (int k = 0; k < stringRestrChild.getChildCount(); k++) {
699 ParseTree lengthChild = stringRestrChild.getChild(k);
700 if (lengthChild instanceof Pattern_stmtContext) {
701 patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
702 if (k == lengthChild.getChildCount() - 1) {
713 * Internal helper method.
717 * @return PatternConstraint object
719 private static PatternConstraint parsePatternConstraint(
720 final Pattern_stmtContext ctx) {
721 String description = null;
722 String reference = null;
723 for (int i = 0; i < ctx.getChildCount(); i++) {
724 ParseTree child = ctx.getChild(i);
725 if (child instanceof Description_stmtContext) {
726 description = stringFromNode(child);
727 } else if (child instanceof Reference_stmtContext) {
728 reference = stringFromNode(child);
731 String pattern = patternStringFromNode(ctx);
732 return BaseConstraints.patternConstraint(pattern, description,
737 * Parse given context and return pattern value.
741 * @return pattern value as String
743 public static String patternStringFromNode(final Pattern_stmtContext ctx) {
744 StringBuilder result = new StringBuilder();
745 for (int i = 0; i < ctx.getChildCount(); ++i) {
746 ParseTree child = ctx.getChild(i);
747 if (child instanceof StringContext) {
748 for (int j = 0; j < child.getChildCount(); j++) {
750 String patternToken = child.getChild(j).getText();
751 result.append(patternToken.substring(1,
752 patternToken.length() - 1));
757 return result.toString();
761 * Get fraction digits value from type body.
764 * type body context to parse
765 * @return 'fraction-digits' value if present in given context, null
768 private static Integer getFractionDigits(Type_body_stmtsContext ctx) {
769 Integer result = null;
770 for (int j = 0; j < ctx.getChildCount(); j++) {
771 ParseTree dec64specChild = ctx.getChild(j);
772 if (dec64specChild instanceof Decimal64_specificationContext) {
773 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild);
780 * Parse decimal64 fraction-digits value.
784 * @return fraction-digits value as Integer
786 private static Integer parseFractionDigits(
787 Decimal64_specificationContext ctx) {
788 Integer result = null;
789 for (int k = 0; k < ctx.getChildCount(); k++) {
790 ParseTree fdChild = ctx.getChild(k);
791 if (fdChild instanceof Fraction_digits_stmtContext) {
792 String value = stringFromNode(fdChild);
794 result = Integer.valueOf(value);
795 } catch (NumberFormatException e) {
796 throw new YangParseException(ctx.getStart().getLine(),
797 "Unable to parse fraction digits value '" + value
806 * Internal helper method for parsing bit statements from given type body
810 * type body context to parse
812 * current position in YANG model
816 * @return List of Bit objects created from this context
818 private static List<BitsTypeDefinition.Bit> getBits(
819 Type_body_stmtsContext ctx, List<String> actualPath, URI namespace,
820 Date revision, String prefix) {
821 final List<BitsTypeDefinition.Bit> bits = new ArrayList<BitsTypeDefinition.Bit>();
822 for (int j = 0; j < ctx.getChildCount(); j++) {
823 ParseTree bitsSpecChild = ctx.getChild(j);
824 if (bitsSpecChild instanceof Bits_specificationContext) {
825 long highestPosition = -1;
826 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
827 ParseTree bitChild = bitsSpecChild.getChild(k);
828 if (bitChild instanceof Bit_stmtContext) {
829 Bit bit = parseBit((Bit_stmtContext) bitChild,
830 highestPosition, actualPath, namespace,
832 if (bit.getPosition() > highestPosition) {
833 highestPosition = bit.getPosition();
844 * Internal helper method for parsing bit context.
847 * bit statement context to parse
848 * @param highestPosition
849 * current highest position in bits type
851 * current position in YANG model
855 * @return Bit object parsed from this context
857 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx,
858 long highestPosition, List<String> actualPath, final URI namespace,
859 final Date revision, final String prefix) {
860 String name = stringFromNode(ctx);
861 final QName qname = new QName(namespace, revision, prefix, name);
862 Long position = null;
864 String description = null;
865 String reference = null;
866 Status status = Status.CURRENT;
868 Stack<String> bitPath = new Stack<String>();
869 bitPath.addAll(actualPath);
872 SchemaPath schemaPath = createActualSchemaPath(bitPath, namespace,
875 for (int i = 0; i < ctx.getChildCount(); i++) {
876 ParseTree child = ctx.getChild(i);
877 if (child instanceof Position_stmtContext) {
878 String positionStr = stringFromNode(child);
879 position = Long.valueOf(positionStr);
880 } else if (child instanceof Description_stmtContext) {
881 description = stringFromNode(child);
882 } else if (child instanceof Reference_stmtContext) {
883 reference = stringFromNode(child);
884 } else if (child instanceof Status_stmtContext) {
885 status = parseStatus((Status_stmtContext) child);
889 if (position == null) {
890 position = highestPosition + 1;
892 if (position < 0 || position > 4294967295L) {
893 throw new YangParseException(
894 ctx.getStart().getLine(),
897 + "': the position value MUST be in the range 0 to 4294967295");
900 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
901 return new BitImpl(position, qname, schemaPath, description, reference,
902 status, unknownNodes);
906 * Parse orderedby statement.
909 * Ordered_by_stmtContext
910 * @return true, if orderedby contains value 'user' or false otherwise
912 public static boolean parseUserOrdered(Ordered_by_stmtContext childNode) {
913 boolean result = false;
914 for (int j = 0; j < childNode.getChildCount(); j++) {
915 ParseTree orderArg = childNode.getChild(j);
916 if (orderArg instanceof Ordered_by_argContext) {
917 String orderStr = stringFromNode(orderArg);
918 if ("system".equals(orderStr)) {
920 } else if ("user".equals(orderStr)) {
923 logger.warn("Invalid 'orderedby' statement.");
931 * Parse given config context and return true if it contains string 'true',
935 * config context to parse.
936 * @return true if given context contains string 'true', false otherwise
938 public static boolean parseConfig(final Config_stmtContext ctx) {
939 boolean result = false;
941 for (int i = 0; i < ctx.getChildCount(); ++i) {
942 final ParseTree configContext = ctx.getChild(i);
943 if (configContext instanceof Config_argContext) {
944 final String value = stringFromNode(configContext);
945 if ("true".equals(value)) {
956 * Parse given type body and creates UnknownType definition.
958 * @param typedefQName
959 * qname of current type
962 * @return UnknownType object with constraints from parsed type body
964 public static TypeDefinition<?> parseUnknownTypeBody(QName typedefQName,
965 Type_body_stmtsContext ctx) {
966 UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
968 List<RangeConstraint> rangeStatements = getRangeConstraints(ctx);
969 List<LengthConstraint> lengthStatements = getLengthConstraints(ctx);
970 List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
971 Integer fractionDigits = getFractionDigits(ctx);
973 unknownType.rangeStatements(rangeStatements);
974 unknownType.lengthStatements(lengthStatements);
975 unknownType.patterns(patternStatements);
976 unknownType.fractionDigits(fractionDigits);
978 return unknownType.build();
982 * Create TypeDefinition object based on given type name and type body.
989 * current path in schema
996 * @return TypeDefinition object based on parsed values.
998 public static TypeDefinition<?> parseTypeBody(final String typeName,
999 final Type_body_stmtsContext typeBody,
1000 final List<String> actualPath, final URI namespace,
1001 final Date revision, final String prefix) {
1002 TypeDefinition<?> type = null;
1004 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody);
1005 Integer fractionDigits = getFractionDigits(typeBody);
1006 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody);
1007 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1008 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(
1009 typeBody, actualPath, namespace, revision, prefix);
1011 if ("decimal64".equals(typeName)) {
1012 type = new Decimal64(actualPath, namespace, revision,
1014 } else if (typeName.startsWith("int")) {
1015 if ("int8".equals(typeName)) {
1016 type = new Int8(actualPath, namespace, revision,
1017 rangeStatements, null, null);
1018 } else if ("int16".equals(typeName)) {
1019 type = new Int16(actualPath, namespace, revision,
1020 rangeStatements, null, null);
1021 } else if ("int32".equals(typeName)) {
1022 type = new Int32(actualPath, namespace, revision,
1023 rangeStatements, null, null);
1024 } else if ("int64".equals(typeName)) {
1025 type = new Int64(actualPath, namespace, revision,
1026 rangeStatements, null, null);
1028 } else if (typeName.startsWith("uint")) {
1029 if ("uint8".equals(typeName)) {
1030 type = new Uint8(actualPath, namespace, revision,
1031 rangeStatements, null, null);
1032 } else if ("uint16".equals(typeName)) {
1033 type = new Uint16(actualPath, namespace, revision,
1034 rangeStatements, null, null);
1035 } else if ("uint32".equals(typeName)) {
1036 type = new Uint32(actualPath, namespace, revision,
1037 rangeStatements, null, null);
1038 } else if ("uint64".equals(typeName)) {
1039 type = new Uint64(actualPath, namespace, revision,
1040 rangeStatements, null, null);
1042 } else if ("enumeration".equals(typeName)) {
1043 type = new EnumerationType(actualPath, namespace, revision,
1045 } else if ("string".equals(typeName)) {
1046 type = new StringType(actualPath, namespace, revision,
1047 lengthStatements, patternStatements);
1048 } else if ("bits".equals(typeName)) {
1049 type = new BitsType(actualPath, namespace, revision, getBits(
1050 typeBody, actualPath, namespace, revision, prefix));
1051 } else if ("leafref".equals(typeName)) {
1052 final String path = parseLeafrefPath(typeBody);
1053 final boolean absolute = path.startsWith("/");
1054 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path,
1056 type = new Leafref(actualPath, namespace, revision, xpath);
1057 } else if ("binary".equals(typeName)) {
1058 List<Byte> bytes = Collections.emptyList();
1059 type = new BinaryType(actualPath, namespace, revision, bytes,
1060 lengthStatements, null);
1061 } else if ("instance-identifier".equals(typeName)) {
1062 boolean requireInstance = isRequireInstance(typeBody);
1063 type = new InstanceIdentifier(actualPath, namespace, revision,
1064 null, requireInstance);
1070 * Parse given context and find identityref base value.
1074 * @return identityref base value as String
1076 public static String getIdentityrefBase(Type_body_stmtsContext ctx) {
1077 String result = null;
1078 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1079 ParseTree child = ctx.getChild(i);
1080 if (child instanceof Identityref_specificationContext) {
1081 for (int j = 0; j < child.getChildCount(); j++) {
1082 ParseTree baseArg = child.getChild(j);
1083 if (baseArg instanceof Base_stmtContext) {
1084 result = stringFromNode(baseArg);
1094 * Parse given context and find require-instance value.
1098 * @return require-instance value
1100 private static boolean isRequireInstance(Type_body_stmtsContext ctx) {
1101 for (int i = 0; i < ctx.getChildCount(); i++) {
1102 ParseTree child = ctx.getChild(i);
1103 if (child instanceof Require_instance_stmtContext) {
1104 for (int j = 0; j < child.getChildCount(); j++) {
1105 ParseTree reqArg = child.getChild(j);
1106 if (reqArg instanceof Require_instance_argContext) {
1107 return Boolean.valueOf(stringFromNode(reqArg));
1116 * Parse given context and find leafref path.
1120 * @return leafref path as String
1122 private static String parseLeafrefPath(Type_body_stmtsContext ctx) {
1123 for (int i = 0; i < ctx.getChildCount(); i++) {
1124 ParseTree child = ctx.getChild(i);
1125 if (child instanceof Leafref_specificationContext) {
1126 for (int j = 0; j < child.getChildCount(); j++) {
1127 ParseTree leafRefSpec = child.getChild(j);
1128 if (leafRefSpec instanceof Path_stmtContext) {
1129 return stringFromNode(leafRefSpec);
1138 * Internal helper method for parsing Must_stmtContext.
1142 * @return MustDefinition object based on parsed context
1144 public static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1145 StringBuilder mustText = new StringBuilder();
1146 String description = null;
1147 String reference = null;
1148 String errorAppTag = null;
1149 String errorMessage = null;
1150 for (int i = 0; i < ctx.getChildCount(); ++i) {
1151 ParseTree child = ctx.getChild(i);
1152 if (child instanceof StringContext) {
1153 final StringContext context = (StringContext) child;
1154 if (context.getChildCount() == 1) {
1155 String mustPart = context.getChild(0).getText();
1156 // trim start and end quotation
1157 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1159 for (int j = 0; j < context.getChildCount(); j++) {
1160 String mustPart = context.getChild(j).getText();
1162 mustText.append(mustPart.substring(0,
1163 mustPart.length() - 1));
1167 mustText.append(mustPart.substring(1));
1171 } else if (child instanceof Description_stmtContext) {
1172 description = stringFromNode(child);
1173 } else if (child instanceof Reference_stmtContext) {
1174 reference = stringFromNode(child);
1175 } else if (child instanceof Error_app_tag_stmtContext) {
1176 errorAppTag = stringFromNode(child);
1177 } else if (child instanceof Error_message_stmtContext) {
1178 errorMessage = stringFromNode(child);
1182 MustDefinition must = new MustDefinitionImpl(mustText.toString(),
1183 description, reference, errorAppTag, errorMessage);
1188 * Parse given tree and set constraints to given builder.
1192 * @param constraints
1193 * ConstraintsBuilder to fill
1195 public static void parseConstraints(final ParseTree ctx,
1196 final ConstraintsBuilder constraints) {
1197 for (int i = 0; i < ctx.getChildCount(); ++i) {
1198 final ParseTree childNode = ctx.getChild(i);
1199 if (childNode instanceof Max_elements_stmtContext) {
1200 Integer max = parseMaxElements((Max_elements_stmtContext) childNode);
1201 constraints.setMaxElements(max);
1202 } else if (childNode instanceof Min_elements_stmtContext) {
1203 Integer min = parseMinElements((Min_elements_stmtContext) childNode);
1204 constraints.setMinElements(min);
1205 } else if (childNode instanceof Must_stmtContext) {
1206 MustDefinition must = parseMust((Must_stmtContext) childNode);
1207 constraints.addMustDefinition(must);
1208 } else if (childNode instanceof Mandatory_stmtContext) {
1209 for (int j = 0; j < childNode.getChildCount(); j++) {
1210 ParseTree mandatoryTree = ctx.getChild(j);
1211 if (mandatoryTree instanceof Mandatory_argContext) {
1212 Boolean mandatory = Boolean
1213 .valueOf(stringFromNode(mandatoryTree));
1214 constraints.setMandatory(mandatory);
1217 } else if (childNode instanceof When_stmtContext) {
1218 constraints.addWhenCondition(stringFromNode(childNode));
1223 private static Integer parseMinElements(Min_elements_stmtContext ctx) {
1224 Integer result = null;
1226 for (int j = 0; j < ctx.getChildCount(); j++) {
1227 ParseTree minArg = ctx.getChild(j);
1228 if (minArg instanceof Min_value_argContext) {
1229 result = Integer.valueOf(stringFromNode(minArg));
1232 if (result == null) {
1233 throw new IllegalArgumentException();
1236 } catch (Exception e) {
1237 throw new YangParseException(ctx.getStart().getLine(),
1238 "Failed to parse min-elements.", e);
1242 private static Integer parseMaxElements(Max_elements_stmtContext ctx) {
1243 Integer result = null;
1245 for (int j = 0; j < ctx.getChildCount(); j++) {
1246 ParseTree maxArg = ctx.getChild(j);
1247 if (maxArg instanceof Max_value_argContext) {
1248 result = Integer.valueOf(stringFromNode(maxArg));
1251 if (result == null) {
1252 throw new IllegalArgumentException();
1255 } catch (Exception e) {
1256 throw new YangParseException(ctx.getStart().getLine(),
1257 "Failed to parse max-elements.", e);
1262 * Parse given context and return yin value.
1266 * @return true if value is 'true', false otherwise
1268 public static boolean parseYinValue(Argument_stmtContext ctx) {
1269 boolean yinValue = false;
1270 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
1271 ParseTree yin = ctx.getChild(j);
1272 if (yin instanceof Yin_element_stmtContext) {
1273 for (int k = 0; k < yin.getChildCount(); k++) {
1274 ParseTree yinArg = yin.getChild(k);
1275 if (yinArg instanceof Yin_element_argContext) {
1276 String yinString = stringFromNode(yinArg);
1277 if ("true".equals(yinString)) {
1289 * Check this base type.
1292 * base YANG type name
1294 * name of current module
1297 * @throws YangParseException
1298 * if this is one of YANG type which MUST contain additional
1299 * informations in its body
1301 public static void checkMissingBody(final String typeName,
1302 final String moduleName, final int line) throws YangParseException {
1303 if ("decimal64".equals(typeName)) {
1304 throw new YangParseException(moduleName, line,
1305 "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1306 } else if ("identityref".equals(typeName)) {
1307 throw new YangParseException(moduleName, line,
1308 "The 'base' statement MUST be present if the type is 'identityref'.");
1309 } else if ("leafref".equals(typeName)) {
1310 throw new YangParseException(moduleName, line,
1311 "The 'path' statement MUST be present if the type is 'leafref'.");
1312 } else if ("bits".equals(typeName)) {
1313 throw new YangParseException(moduleName, line,
1314 "The 'bit' statement MUST be present if the type is 'bits'.");
1315 } else if ("enumeration".equals(typeName)) {
1316 throw new YangParseException(moduleName, line,
1317 "The 'enum' statement MUST be present if the type is 'enumeration'.");
1322 * Parse refine statement.
1327 * current line in yang model
1328 * @return RefineHolder object representing this refine statement
1330 public static RefineHolder parseRefine(Refine_stmtContext refineCtx) {
1331 final String refineTarget = stringFromNode(refineCtx);
1332 final RefineHolder refine = new RefineHolder(refineTarget, refineCtx
1333 .getStart().getLine());
1334 for (int j = 0; j < refineCtx.getChildCount(); j++) {
1335 ParseTree refinePom = refineCtx.getChild(j);
1336 if (refinePom instanceof Refine_pomContext) {
1337 for (int k = 0; k < refinePom.getChildCount(); k++) {
1338 ParseTree refineStmt = refinePom.getChild(k);
1339 parseRefineDefault(refine, refineStmt);
1341 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1343 (Refine_leaf_stmtsContext) refineStmt);
1344 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1346 (Refine_container_stmtsContext) refineStmt);
1347 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1349 (Refine_list_stmtsContext) refineStmt);
1350 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1352 (Refine_leaf_list_stmtsContext) refineStmt);
1353 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1355 (Refine_choice_stmtsContext) refineStmt);
1356 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1358 (Refine_anyxml_stmtsContext) refineStmt);
1366 private static void parseRefineDefault(RefineHolder refine,
1367 ParseTree refineStmt) {
1368 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1369 ParseTree refineArg = refineStmt.getChild(i);
1370 if (refineArg instanceof Description_stmtContext) {
1371 String description = stringFromNode(refineArg);
1372 refine.setDescription(description);
1373 } else if (refineArg instanceof Reference_stmtContext) {
1374 String reference = stringFromNode(refineArg);
1375 refine.setReference(reference);
1376 } else if (refineArg instanceof Config_stmtContext) {
1377 boolean config = parseConfig((Config_stmtContext) refineArg);
1378 refine.setConfig(config);
1383 private static RefineHolder parseRefine(RefineHolder refine,
1384 Refine_leaf_stmtsContext refineStmt) {
1385 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1386 ParseTree refineArg = refineStmt.getChild(i);
1387 if (refineArg instanceof Default_stmtContext) {
1388 String defaultStr = stringFromNode(refineArg);
1389 refine.setDefaultStr(defaultStr);
1390 } else if (refineArg instanceof Mandatory_stmtContext) {
1391 for (int j = 0; j < refineArg.getChildCount(); j++) {
1392 ParseTree mandatoryTree = refineArg.getChild(j);
1393 if (mandatoryTree instanceof Mandatory_argContext) {
1394 Boolean mandatory = Boolean
1395 .valueOf(stringFromNode(mandatoryTree));
1396 refine.setMandatory(mandatory);
1399 } else if (refineArg instanceof Must_stmtContext) {
1400 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1401 refine.setMust(must);
1408 private static RefineHolder parseRefine(RefineHolder refine,
1409 Refine_container_stmtsContext refineStmt) {
1410 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1411 ParseTree refineArg = refineStmt.getChild(m);
1412 if (refineArg instanceof Must_stmtContext) {
1413 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1414 refine.setMust(must);
1415 } else if (refineArg instanceof Presence_stmtContext) {
1416 refine.setPresence(true);
1422 private static RefineHolder parseRefine(RefineHolder refine,
1423 Refine_list_stmtsContext refineStmt) {
1424 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1425 ParseTree refineArg = refineStmt.getChild(m);
1426 if (refineArg instanceof Must_stmtContext) {
1427 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1428 refine.setMust(must);
1429 } else if (refineArg instanceof Max_elements_stmtContext) {
1430 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg);
1431 refine.setMaxElements(max);
1432 } else if (refineArg instanceof Min_elements_stmtContext) {
1433 Integer min = parseMinElements((Min_elements_stmtContext) refineArg);
1434 refine.setMinElements(min);
1440 private static RefineHolder parseRefine(RefineHolder refine,
1441 Refine_leaf_list_stmtsContext refineStmt) {
1442 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1443 ParseTree refineArg = refineStmt.getChild(m);
1444 if (refineArg instanceof Must_stmtContext) {
1445 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1446 refine.setMust(must);
1447 } else if (refineArg instanceof Max_elements_stmtContext) {
1448 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg);
1449 refine.setMaxElements(max);
1450 } else if (refineArg instanceof Min_elements_stmtContext) {
1451 Integer min = parseMinElements((Min_elements_stmtContext) refineArg);
1452 refine.setMinElements(min);
1458 private static RefineHolder parseRefine(RefineHolder refine,
1459 Refine_choice_stmtsContext refineStmt) {
1460 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1461 ParseTree refineArg = refineStmt.getChild(i);
1462 if (refineArg instanceof Default_stmtContext) {
1463 String defaultStr = stringFromNode(refineArg);
1464 refine.setDefaultStr(defaultStr);
1465 } else if (refineArg instanceof Mandatory_stmtContext) {
1466 for (int j = 0; j < refineArg.getChildCount(); j++) {
1467 ParseTree mandatoryTree = refineArg.getChild(j);
1468 if (mandatoryTree instanceof Mandatory_argContext) {
1469 Boolean mandatory = Boolean
1470 .valueOf(stringFromNode(mandatoryTree));
1471 refine.setMandatory(mandatory);
1479 private static RefineHolder parseRefine(RefineHolder refine,
1480 Refine_anyxml_stmtsContext refineStmt) {
1481 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1482 ParseTree refineArg = refineStmt.getChild(i);
1483 if (refineArg instanceof Must_stmtContext) {
1484 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1485 refine.setMust(must);
1486 } else if (refineArg instanceof Mandatory_stmtContext) {
1487 for (int j = 0; j < refineArg.getChildCount(); j++) {
1488 ParseTree mandatoryTree = refineArg.getChild(j);
1489 if (mandatoryTree instanceof Mandatory_argContext) {
1490 Boolean mandatory = Boolean
1491 .valueOf(stringFromNode(mandatoryTree));
1492 refine.setMandatory(mandatory);