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.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.Value_stmtContext;
67 import org.opendaylight.controller.antlrv4.code.gen.YangParser.When_stmtContext;
68 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Yin_element_argContext;
69 import org.opendaylight.controller.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
70 import org.opendaylight.controller.yang.common.QName;
71 import org.opendaylight.controller.yang.model.api.MustDefinition;
72 import org.opendaylight.controller.yang.model.api.RevisionAwareXPath;
73 import org.opendaylight.controller.yang.model.api.SchemaPath;
74 import org.opendaylight.controller.yang.model.api.Status;
75 import org.opendaylight.controller.yang.model.api.TypeDefinition;
76 import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
77 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition;
78 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
79 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
80 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
81 import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
82 import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
83 import org.opendaylight.controller.yang.model.api.type.RangeConstraint;
84 import org.opendaylight.controller.yang.model.util.BaseConstraints;
85 import org.opendaylight.controller.yang.model.util.BinaryType;
86 import org.opendaylight.controller.yang.model.util.BitsType;
87 import org.opendaylight.controller.yang.model.util.Decimal64;
88 import org.opendaylight.controller.yang.model.util.EnumerationType;
89 import org.opendaylight.controller.yang.model.util.InstanceIdentifier;
90 import org.opendaylight.controller.yang.model.util.Int16;
91 import org.opendaylight.controller.yang.model.util.Int32;
92 import org.opendaylight.controller.yang.model.util.Int64;
93 import org.opendaylight.controller.yang.model.util.Int8;
94 import org.opendaylight.controller.yang.model.util.Leafref;
95 import org.opendaylight.controller.yang.model.util.RevisionAwareXPathImpl;
96 import org.opendaylight.controller.yang.model.util.StringType;
97 import org.opendaylight.controller.yang.model.util.Uint16;
98 import org.opendaylight.controller.yang.model.util.Uint32;
99 import org.opendaylight.controller.yang.model.util.Uint64;
100 import org.opendaylight.controller.yang.model.util.Uint8;
101 import org.opendaylight.controller.yang.model.util.UnknownType;
102 import org.opendaylight.controller.yang.parser.builder.api.SchemaNodeBuilder;
103 import org.opendaylight.controller.yang.parser.builder.impl.ConstraintsBuilder;
104 import org.slf4j.Logger;
105 import org.slf4j.LoggerFactory;
107 public final class YangModelBuilderUtil {
109 private static final Logger logger = LoggerFactory
110 .getLogger(YangModelBuilderUtil.class);
112 private YangModelBuilderUtil() {
116 * Parse given tree and get first string value.
120 * @return first string value from given tree
122 public static String stringFromNode(final ParseTree treeNode) {
123 final String result = "";
124 for (int i = 0; i < treeNode.getChildCount(); ++i) {
125 if (treeNode.getChild(i) instanceof StringContext) {
126 final StringContext context = (StringContext) treeNode
128 if (context != null) {
129 return context.getChild(0).getText().replace("\"", "");
137 * Parse 'description', 'reference' and 'status' statements and fill in
143 * builder to fill in with parsed statements
145 public static void parseSchemaNodeArgs(final ParseTree ctx,
146 final SchemaNodeBuilder builder) {
147 for (int i = 0; i < ctx.getChildCount(); i++) {
148 final ParseTree child = ctx.getChild(i);
149 if (child instanceof Description_stmtContext) {
150 final String desc = stringFromNode(child);
151 builder.setDescription(desc);
152 } else if (child instanceof Reference_stmtContext) {
153 final String ref = stringFromNode(child);
154 builder.setReference(ref);
155 } else if (child instanceof Status_stmtContext) {
156 final Status status = parseStatus((Status_stmtContext) child);
157 builder.setStatus(status);
163 * Parse given context and return its value;
167 * @return value parsed from context
169 public static Status parseStatus(final Status_stmtContext ctx) {
170 Status result = null;
171 for (int i = 0; i < ctx.getChildCount(); i++) {
172 ParseTree statusArg = ctx.getChild(i);
173 if (statusArg instanceof Status_argContext) {
174 String statusArgStr = stringFromNode(statusArg);
175 if ("current".equals(statusArgStr)) {
176 result = Status.CURRENT;
177 } else if ("deprecated".equals(statusArgStr)) {
178 result = Status.DEPRECATED;
179 } else if ("obsolete".equals(statusArgStr)) {
180 result = Status.OBSOLETE;
182 logger.warn("Invalid 'status' statement: " + statusArgStr);
190 * Parse given tree and returns units statement as string.
194 * @return value of units statement as string or null if there is no units
197 public static String parseUnits(final ParseTree ctx) {
199 for (int i = 0; i < ctx.getChildCount(); i++) {
200 ParseTree child = ctx.getChild(i);
201 if (child instanceof Units_stmtContext) {
202 units = stringFromNode(child);
210 * Create SchemaPath object from given path list with namespace, revision
211 * and prefix based on given values.
214 * current position in model
218 * @return SchemaPath object.
220 public static SchemaPath createActualSchemaPath(
221 final List<String> actualPath, final URI namespace,
222 final Date revision, final String prefix) {
223 final List<QName> path = new ArrayList<QName>();
225 // start from index 1 - module name omited
226 for (int i = 1; i < actualPath.size(); i++) {
227 qname = new QName(namespace, revision, prefix, actualPath.get(i));
230 return new SchemaPath(path, true);
234 * Create SchemaPath from given string.
237 * string representation of path
238 * @return SchemaPath object
240 public static SchemaPath parseAugmentPath(final String augmentPath) {
241 final boolean absolute = augmentPath.startsWith("/");
242 final String[] splittedPath = augmentPath.split("/");
243 List<QName> path = new ArrayList<QName>();
245 for (String pathElement : splittedPath) {
246 if (pathElement.length() > 0) {
247 String[] splittedElement = pathElement.split(":");
248 if (splittedElement.length == 1) {
249 name = new QName(null, null, null, splittedElement[0]);
251 name = new QName(null, null, splittedElement[0],
257 return new SchemaPath(path, absolute);
261 * Create java.util.List of QName objects from given key definition as
264 * @param keyDefinition
265 * key definition as string
272 * @return YANG list key as java.util.List of QName objects
274 public static List<QName> createListKey(final String keyDefinition,
275 final URI namespace, final Date revision, final String prefix) {
276 List<QName> key = new ArrayList<QName>();
277 String[] splittedKey = keyDefinition.split(" ");
280 for (String keyElement : splittedKey) {
281 if (keyElement.length() != 0) {
282 qname = new QName(namespace, revision, prefix, keyElement);
290 * Parse given type body of enumeration statement.
293 * type body context to parse
295 * actual position in YANG model
299 * @return List of EnumPair object parsed from given context
301 private static List<EnumTypeDefinition.EnumPair> getEnumConstants(
302 final Type_body_stmtsContext ctx, final List<String> path,
303 final URI namespace, final Date revision, final String prefix) {
304 List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<EnumTypeDefinition.EnumPair>();
306 for (int j = 0; j < ctx.getChildCount(); j++) {
307 ParseTree enumSpecChild = ctx.getChild(j);
308 if (enumSpecChild instanceof Enum_specificationContext) {
309 int highestValue = -1;
310 for (int k = 0; k < enumSpecChild.getChildCount(); k++) {
311 ParseTree enumChild = enumSpecChild.getChild(k);
312 if (enumChild instanceof Enum_stmtContext) {
313 EnumPair enumPair = createEnumPair(
314 (Enum_stmtContext) enumChild, highestValue,
315 path, namespace, revision, prefix);
316 if (enumPair.getValue() > highestValue) {
317 highestValue = enumPair.getValue();
319 enumConstants.add(enumPair);
324 return enumConstants;
328 * Parse enum statement context
331 * enum statement context
332 * @param highestValue
333 * current highest value in enumeration
335 * actual position in YANG model
339 * @return EnumPair object parsed from given context
341 private static EnumTypeDefinition.EnumPair createEnumPair(
342 final Enum_stmtContext ctx, final int highestValue,
343 final List<String> path, final URI namespace, final Date revision,
344 final String prefix) {
345 final String name = stringFromNode(ctx);
346 final QName qname = new QName(namespace, revision, prefix, name);
347 Integer value = null;
349 String description = null;
350 String reference = null;
351 Status status = null;
353 List<String> enumPairPath = new ArrayList<String>(path);
354 enumPairPath.add(name);
356 for (int i = 0; i < ctx.getChildCount(); i++) {
357 ParseTree child = ctx.getChild(i);
358 if (child instanceof Value_stmtContext) {
359 String valueStr = stringFromNode(child);
360 value = Integer.valueOf(valueStr);
361 } else if (child instanceof Description_stmtContext) {
362 description = stringFromNode(child);
363 } else if (child instanceof Reference_stmtContext) {
364 reference = stringFromNode(child);
365 } else if (child instanceof Status_stmtContext) {
366 status = parseStatus((Status_stmtContext) child);
371 value = highestValue + 1;
373 if (value < -2147483648 || value > 2147483647) {
374 throw new YangParseException(
377 + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: "
381 EnumPairImpl result = new EnumPairImpl();
382 result.qname = qname;
383 result.path = createActualSchemaPath(enumPairPath, namespace, revision,
385 result.description = description;
386 result.reference = reference;
387 result.status = status;
389 result.value = value;
394 * Internal implementation of EnumPair.
396 private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
398 private SchemaPath path;
399 private String description;
400 private String reference;
401 private Status status;
402 private List<UnknownSchemaNode> extensionSchemaNodes = Collections
405 private Integer value;
408 public QName getQName() {
413 public SchemaPath getPath() {
418 public String getDescription() {
423 public String getReference() {
428 public Status getStatus() {
433 public List<UnknownSchemaNode> getUnknownSchemaNodes() {
434 return extensionSchemaNodes;
438 public String getName() {
443 public Integer getValue() {
448 public int hashCode() {
449 final int prime = 31;
451 result = prime * result + ((qname == null) ? 0 : qname.hashCode());
452 result = prime * result + ((path == null) ? 0 : path.hashCode());
455 + ((extensionSchemaNodes == null) ? 0
456 : extensionSchemaNodes.hashCode());
457 result = prime * result + ((name == null) ? 0 : name.hashCode());
458 result = prime * result + ((value == null) ? 0 : value.hashCode());
463 public boolean equals(Object obj) {
470 if (getClass() != obj.getClass()) {
473 EnumPairImpl other = (EnumPairImpl) obj;
475 if (other.qname != null) {
478 } else if (!qname.equals(other.qname)) {
482 if (other.path != null) {
485 } else if (!path.equals(other.path)) {
488 if (extensionSchemaNodes == null) {
489 if (other.extensionSchemaNodes != null) {
492 } else if (!extensionSchemaNodes.equals(other.extensionSchemaNodes)) {
496 if (other.name != null) {
499 } else if (!name.equals(other.name)) {
503 if (other.value != null) {
506 } else if (!value.equals(other.value)) {
513 public String toString() {
514 return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name="
515 + name + ", value=" + value + "]";
520 * Get and parse range from given type body context.
523 * type body context to parse
524 * @return List of RangeConstraint created from this context
526 private static List<RangeConstraint> getRangeConstraints(
527 final Type_body_stmtsContext ctx) {
528 List<RangeConstraint> rangeConstraints = Collections.emptyList();
529 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
530 ParseTree numRestrChild = ctx.getChild(j);
531 if (numRestrChild instanceof Numerical_restrictionsContext) {
532 for (int k = 0; k < numRestrChild.getChildCount(); k++) {
533 ParseTree rangeChild = numRestrChild.getChild(k);
534 if (rangeChild instanceof Range_stmtContext) {
535 rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild);
541 return rangeConstraints;
545 * Parse given range context.
548 * range context to parse
549 * @return List of RangeConstraints parsed from this context
551 private static List<RangeConstraint> parseRangeConstraints(
552 final Range_stmtContext ctx) {
553 final int line = ctx.getStart().getLine();
554 List<RangeConstraint> rangeConstraints = new ArrayList<RangeConstraint>();
555 String description = null;
556 String reference = null;
558 for (int i = 0; i < ctx.getChildCount(); i++) {
559 ParseTree child = ctx.getChild(i);
560 if (child instanceof Description_stmtContext) {
561 description = stringFromNode(child);
562 } else if (child instanceof Reference_stmtContext) {
563 reference = stringFromNode(child);
567 String rangeStr = stringFromNode(ctx);
568 String trimmed = rangeStr.replace(" ", "");
569 String[] splittedRange = trimmed.split("\\|");
570 for (String rangeDef : splittedRange) {
571 String[] splittedRangeDef = rangeDef.split("\\.\\.");
574 if (splittedRangeDef.length == 1) {
575 min = max = parseNumberConstraintValue(splittedRangeDef[0],
578 min = parseNumberConstraintValue(splittedRangeDef[0], line);
579 max = parseNumberConstraintValue(splittedRangeDef[1], line);
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 final int line = ctx.getStart().getLine();
624 List<LengthConstraint> lengthConstraints = new ArrayList<LengthConstraint>();
625 String description = null;
626 String reference = null;
628 for (int i = 0; i < ctx.getChildCount(); i++) {
629 ParseTree child = ctx.getChild(i);
630 if (child instanceof Description_stmtContext) {
631 description = stringFromNode(child);
632 } else if (child instanceof Reference_stmtContext) {
633 reference = stringFromNode(child);
637 String lengthStr = stringFromNode(ctx);
638 String trimmed = lengthStr.replace(" ", "");
639 String[] splittedRange = trimmed.split("\\|");
640 for (String rangeDef : splittedRange) {
641 String[] splittedRangeDef = rangeDef.split("\\.\\.");
644 if (splittedRangeDef.length == 1) {
645 min = max = parseNumberConstraintValue(splittedRangeDef[0],
648 min = parseNumberConstraintValue(splittedRangeDef[0], line);
649 max = parseNumberConstraintValue(splittedRangeDef[1], line);
651 LengthConstraint range = BaseConstraints.lengthConstraint(min, max,
652 description, reference);
653 lengthConstraints.add(range);
656 return lengthConstraints;
662 * @return wrapper object of primitive java type or UnknownBoundaryNumber if
663 * type is one of special YANG values 'min' or 'max'
665 private static Number parseNumberConstraintValue(final String value,
667 Number result = null;
668 if ("min".equals(value) || "max".equals(value)) {
669 result = new UnknownBoundaryNumber(value);
672 result = Long.valueOf(value);
673 } catch (NumberFormatException e) {
674 throw new YangParseException("Error on line " + line
675 + ": Unable to parse range value '" + value + "'.", e);
682 * Parse type body and return pattern constraints.
686 * @return list of pattern constraints
688 private static List<PatternConstraint> getPatternConstraint(
689 final Type_body_stmtsContext ctx) {
690 List<PatternConstraint> patterns = new ArrayList<PatternConstraint>();
692 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
693 ParseTree stringRestrChild = ctx.getChild(j);
694 if (stringRestrChild instanceof String_restrictionsContext) {
695 for (int k = 0; k < stringRestrChild.getChildCount(); k++) {
696 ParseTree lengthChild = stringRestrChild.getChild(k);
697 if (lengthChild instanceof Pattern_stmtContext) {
698 patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
699 if (k == lengthChild.getChildCount() - 1) {
710 * Internal helper method.
714 * @return PatternConstraint object
716 private static PatternConstraint parsePatternConstraint(
717 final Pattern_stmtContext ctx) {
718 String description = null;
719 String reference = null;
720 for (int i = 0; i < ctx.getChildCount(); i++) {
721 ParseTree child = ctx.getChild(i);
722 if (child instanceof Description_stmtContext) {
723 description = stringFromNode(child);
724 } else if (child instanceof Reference_stmtContext) {
725 reference = stringFromNode(child);
728 String pattern = patternStringFromNode(ctx);
729 return BaseConstraints.patternConstraint(pattern, description,
734 * Parse given context and return pattern value.
738 * @return pattern value as String
740 public static String patternStringFromNode(final Pattern_stmtContext ctx) {
741 StringBuilder result = new StringBuilder();
742 for (int i = 0; i < ctx.getChildCount(); ++i) {
743 ParseTree child = ctx.getChild(i);
744 if (child instanceof StringContext) {
745 for (int j = 0; j < child.getChildCount(); j++) {
747 String patternToken = child.getChild(j).getText();
748 result.append(patternToken.substring(1,
749 patternToken.length() - 1));
754 return result.toString();
758 * Get fraction digits value from type body.
761 * type body context to parse
762 * @return 'fraction-digits' value if present in given context, null
765 private static Integer getFractionDigits(Type_body_stmtsContext ctx) {
766 Integer result = null;
767 for (int j = 0; j < ctx.getChildCount(); j++) {
768 ParseTree dec64specChild = ctx.getChild(j);
769 if (dec64specChild instanceof Decimal64_specificationContext) {
770 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild);
777 * Parse decimal64 fraction-digits value.
781 * @return fraction-digits value as Integer
783 private static Integer parseFractionDigits(
784 Decimal64_specificationContext ctx) {
785 Integer result = null;
786 for (int k = 0; k < ctx.getChildCount(); k++) {
787 ParseTree fdChild = ctx.getChild(k);
788 if (fdChild instanceof Fraction_digits_stmtContext) {
789 String value = stringFromNode(fdChild);
791 result = Integer.valueOf(value);
792 } catch (NumberFormatException e) {
793 throw new YangParseException(
794 "Unable to parse fraction digits value '" + value
803 * Internal helper method for parsing bit statements from given type body
807 * type body context to parse
809 * current position in YANG model
813 * @return List of Bit objects created from this context
815 private static List<BitsTypeDefinition.Bit> getBits(
816 Type_body_stmtsContext ctx, List<String> actualPath, URI namespace,
817 Date revision, String prefix) {
818 final List<BitsTypeDefinition.Bit> bits = new ArrayList<BitsTypeDefinition.Bit>();
819 for (int j = 0; j < ctx.getChildCount(); j++) {
820 ParseTree bitsSpecChild = ctx.getChild(j);
821 if (bitsSpecChild instanceof Bits_specificationContext) {
822 long highestPosition = -1;
823 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
824 ParseTree bitChild = bitsSpecChild.getChild(k);
825 if (bitChild instanceof Bit_stmtContext) {
826 Bit bit = parseBit((Bit_stmtContext) bitChild,
827 highestPosition, actualPath, namespace,
829 if (bit.getPosition() > highestPosition) {
830 highestPosition = bit.getPosition();
841 * Internal helper method for parsing bit context.
844 * bit statement context to parse
845 * @param highestPosition
846 * current highest position in bits type
848 * current position in YANG model
852 * @return Bit object parsed from this context
854 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx,
855 long highestPosition, List<String> actualPath, final URI namespace,
856 final Date revision, final String prefix) {
857 String name = stringFromNode(ctx);
858 final QName qname = new QName(namespace, revision, prefix, name);
859 Long position = null;
861 String description = null;
862 String reference = null;
863 Status status = Status.CURRENT;
865 Stack<String> bitPath = new Stack<String>();
866 bitPath.addAll(actualPath);
869 SchemaPath schemaPath = createActualSchemaPath(bitPath, namespace,
872 for (int i = 0; i < ctx.getChildCount(); i++) {
873 ParseTree child = ctx.getChild(i);
874 if (child instanceof Position_stmtContext) {
875 String positionStr = stringFromNode(child);
876 position = Long.valueOf(positionStr);
877 } else if (child instanceof Description_stmtContext) {
878 description = stringFromNode(child);
879 } else if (child instanceof Reference_stmtContext) {
880 reference = stringFromNode(child);
881 } else if (child instanceof Status_stmtContext) {
882 status = parseStatus((Status_stmtContext) child);
886 if (position == null) {
887 position = highestPosition + 1;
889 if (position < 0 || position > 4294967295L) {
890 throw new YangParseException(
893 + "': the position value MUST be in the range 0 to 4294967295");
896 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
897 return new BitImpl(position, qname, schemaPath, description, reference,
898 status, unknownNodes);
902 * Parse orderedby statement.
905 * Ordered_by_stmtContext
906 * @return true, if orderedby contains value 'user' or false otherwise
908 public static boolean parseUserOrdered(Ordered_by_stmtContext childNode) {
909 boolean result = false;
910 for (int j = 0; j < childNode.getChildCount(); j++) {
911 ParseTree orderArg = childNode.getChild(j);
912 if (orderArg instanceof Ordered_by_argContext) {
913 String orderStr = stringFromNode(orderArg);
914 if ("system".equals(orderStr)) {
916 } else if ("user".equals(orderStr)) {
919 logger.warn("Invalid 'orderedby' statement.");
927 * Parse given config context and return true if it contains string 'true',
931 * config context to parse.
932 * @return true if given context contains string 'true', false otherwise
934 public static boolean parseConfig(final Config_stmtContext ctx) {
935 boolean result = false;
937 for (int i = 0; i < ctx.getChildCount(); ++i) {
938 final ParseTree configContext = ctx.getChild(i);
939 if (configContext instanceof Config_argContext) {
940 final String value = stringFromNode(configContext);
941 if ("true".equals(value)) {
952 * Parse given type body and creates UnknownType definition.
954 * @param typedefQName
955 * qname of current type
958 * @return UnknownType object with constraints from parsed type body
960 public static TypeDefinition<?> parseUnknownTypeBody(QName typedefQName,
961 Type_body_stmtsContext ctx) {
962 UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
964 List<RangeConstraint> rangeStatements = getRangeConstraints(ctx);
965 List<LengthConstraint> lengthStatements = getLengthConstraints(ctx);
966 List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
967 Integer fractionDigits = getFractionDigits(ctx);
969 unknownType.rangeStatements(rangeStatements);
970 unknownType.lengthStatements(lengthStatements);
971 unknownType.patterns(patternStatements);
972 unknownType.fractionDigits(fractionDigits);
974 return unknownType.build();
978 * Create TypeDefinition object based on given type name and type body.
985 * current path in schema
992 * @return TypeDefinition object based on parsed values.
994 public static TypeDefinition<?> parseTypeBody(final String typeName,
995 final Type_body_stmtsContext typeBody,
996 final List<String> actualPath, final URI namespace,
997 final Date revision, final String prefix) {
998 TypeDefinition<?> type = null;
1000 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody);
1001 Integer fractionDigits = getFractionDigits(typeBody);
1002 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody);
1003 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1004 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(
1005 typeBody, actualPath, namespace, revision, prefix);
1007 if ("decimal64".equals(typeName)) {
1008 type = new Decimal64(actualPath, namespace, revision,
1010 } else if (typeName.startsWith("int")) {
1011 if ("int8".equals(typeName)) {
1012 type = new Int8(actualPath, namespace, revision,
1013 rangeStatements, null, null);
1014 } else if ("int16".equals(typeName)) {
1015 type = new Int16(actualPath, namespace, revision,
1016 rangeStatements, null, null);
1017 } else if ("int32".equals(typeName)) {
1018 type = new Int32(actualPath, namespace, revision,
1019 rangeStatements, null, null);
1020 } else if ("int64".equals(typeName)) {
1021 type = new Int64(actualPath, namespace, revision,
1022 rangeStatements, null, null);
1024 } else if (typeName.startsWith("uint")) {
1025 if ("uint8".equals(typeName)) {
1026 type = new Uint8(actualPath, namespace, revision,
1027 rangeStatements, null, null);
1028 } else if ("uint16".equals(typeName)) {
1029 type = new Uint16(actualPath, namespace, revision,
1030 rangeStatements, null, null);
1031 } else if ("uint32".equals(typeName)) {
1032 type = new Uint32(actualPath, namespace, revision,
1033 rangeStatements, null, null);
1034 } else if ("uint64".equals(typeName)) {
1035 type = new Uint64(actualPath, namespace, revision,
1036 rangeStatements, null, null);
1038 } else if ("enumeration".equals(typeName)) {
1039 type = new EnumerationType(actualPath, namespace, revision,
1041 } else if ("string".equals(typeName)) {
1042 type = new StringType(actualPath, namespace, revision,
1043 lengthStatements, patternStatements);
1044 } else if ("bits".equals(typeName)) {
1045 type = new BitsType(actualPath, namespace, revision, getBits(
1046 typeBody, actualPath, namespace, revision, prefix));
1047 } else if ("leafref".equals(typeName)) {
1048 final String path = parseLeafrefPath(typeBody);
1049 final boolean absolute = path.startsWith("/");
1050 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path,
1052 type = new Leafref(actualPath, namespace, revision, xpath);
1053 } else if ("binary".equals(typeName)) {
1054 List<Byte> bytes = Collections.emptyList();
1055 type = new BinaryType(actualPath, namespace, revision, bytes,
1056 lengthStatements, null);
1057 } else if ("instance-identifier".equals(typeName)) {
1058 boolean requireInstance = isRequireInstance(typeBody);
1059 type = new InstanceIdentifier(actualPath, namespace, revision,
1060 null, requireInstance);
1066 * Parse given context and find identityref base value.
1070 * @return identityref base value as String
1072 public static String getIdentityrefBase(Type_body_stmtsContext ctx) {
1073 String result = null;
1074 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1075 ParseTree child = ctx.getChild(i);
1076 if (child instanceof Identityref_specificationContext) {
1077 for (int j = 0; j < child.getChildCount(); j++) {
1078 ParseTree baseArg = child.getChild(j);
1079 if (baseArg instanceof Base_stmtContext) {
1080 result = stringFromNode(baseArg);
1090 * Parse given context and find require-instance value.
1094 * @return require-instance value
1096 private static boolean isRequireInstance(Type_body_stmtsContext ctx) {
1097 for (int i = 0; i < ctx.getChildCount(); i++) {
1098 ParseTree child = ctx.getChild(i);
1099 if (child instanceof Require_instance_stmtContext) {
1100 for (int j = 0; j < child.getChildCount(); j++) {
1101 ParseTree reqArg = child.getChild(j);
1102 if (reqArg instanceof Require_instance_argContext) {
1103 return Boolean.valueOf(stringFromNode(reqArg));
1112 * Parse given context and find leafref path.
1116 * @return leafref path as String
1118 private static String parseLeafrefPath(Type_body_stmtsContext ctx) {
1119 for (int i = 0; i < ctx.getChildCount(); i++) {
1120 ParseTree child = ctx.getChild(i);
1121 if (child instanceof Leafref_specificationContext) {
1122 for (int j = 0; j < child.getChildCount(); j++) {
1123 ParseTree leafRefSpec = child.getChild(j);
1124 if (leafRefSpec instanceof Path_stmtContext) {
1125 return stringFromNode(leafRefSpec);
1134 * Internal helper method for parsing Must_stmtContext.
1138 * @return MustDefinition object based on parsed context
1140 public static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1141 StringBuilder mustText = new StringBuilder();
1142 String description = null;
1143 String reference = null;
1144 String errorAppTag = null;
1145 String errorMessage = null;
1146 for (int i = 0; i < ctx.getChildCount(); ++i) {
1147 ParseTree child = ctx.getChild(i);
1148 if (child instanceof StringContext) {
1149 final StringContext context = (StringContext) child;
1150 if (context.getChildCount() == 1) {
1151 String mustPart = context.getChild(0).getText();
1152 // trim start and end quotation
1153 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1155 for (int j = 0; j < context.getChildCount(); j++) {
1156 String mustPart = context.getChild(j).getText();
1158 mustText.append(mustPart.substring(0,
1159 mustPart.length() - 1));
1163 mustText.append(mustPart.substring(1));
1167 } else if (child instanceof Description_stmtContext) {
1168 description = stringFromNode(child);
1169 } else if (child instanceof Reference_stmtContext) {
1170 reference = stringFromNode(child);
1171 } else if (child instanceof Error_app_tag_stmtContext) {
1172 errorAppTag = stringFromNode(child);
1173 } else if (child instanceof Error_message_stmtContext) {
1174 errorMessage = stringFromNode(child);
1178 MustDefinition must = new MustDefinitionImpl(mustText.toString(),
1179 description, reference, errorAppTag, errorMessage);
1184 * Parse given tree and set constraints to given builder.
1188 * @param constraints
1189 * ConstraintsBuilder to fill
1191 public static void parseConstraints(final ParseTree ctx,
1192 final ConstraintsBuilder constraints) {
1193 for (int i = 0; i < ctx.getChildCount(); ++i) {
1194 final ParseTree childNode = ctx.getChild(i);
1195 if (childNode instanceof Max_elements_stmtContext) {
1196 Integer max = Integer.valueOf(stringFromNode(childNode));
1197 constraints.setMinElements(max);
1198 } else if (childNode instanceof Min_elements_stmtContext) {
1199 Integer min = Integer.valueOf(stringFromNode(childNode));
1200 constraints.setMinElements(min);
1201 } else if (childNode instanceof Must_stmtContext) {
1202 MustDefinition must = parseMust((Must_stmtContext) childNode);
1203 constraints.addMustDefinition(must);
1204 } else if (childNode instanceof Mandatory_stmtContext) {
1205 for (int j = 0; j < childNode.getChildCount(); j++) {
1206 ParseTree mandatoryTree = ctx.getChild(j);
1207 if (mandatoryTree instanceof Mandatory_argContext) {
1208 Boolean mandatory = Boolean
1209 .valueOf(stringFromNode(mandatoryTree));
1210 constraints.setMandatory(mandatory);
1213 } else if (childNode instanceof When_stmtContext) {
1214 constraints.addWhenCondition(stringFromNode(childNode));
1220 * Parse given context and return yin value.
1224 * @return true if value is 'true', false otherwise
1226 public static boolean parseYinValue(Argument_stmtContext ctx) {
1227 boolean yinValue = false;
1228 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
1229 ParseTree yin = ctx.getChild(j);
1230 if (yin instanceof Yin_element_stmtContext) {
1231 for (int k = 0; k < yin.getChildCount(); k++) {
1232 ParseTree yinArg = yin.getChild(k);
1233 if (yinArg instanceof Yin_element_argContext) {
1234 String yinString = stringFromNode(yinArg);
1235 if ("true".equals(yinString)) {
1247 * Check this base type.
1250 * base YANG type name
1252 * name of current module
1255 * @throws YangParseException
1256 * if this is one of YANG type which MUST contain additional
1257 * informations in its body
1259 public static void checkMissingBody(final String typeName,
1260 final String moduleName, final int line) throws YangParseException {
1261 if ("decimal64".equals(typeName)) {
1262 throw new YangParseException(moduleName, line,
1263 "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1264 } else if ("identityref".equals(typeName)) {
1265 throw new YangParseException(moduleName, line,
1266 "The 'base' statement MUST be present if the type is 'identityref'.");
1267 } else if ("leafref".equals(typeName)) {
1268 throw new YangParseException(moduleName, line,
1269 "The 'path' statement MUST be present if the type is 'leafref'.");
1270 } else if ("bits".equals(typeName)) {
1271 throw new YangParseException(moduleName, line,
1272 "The 'bit' statement MUST be present if the type is 'bits'.");
1273 } else if ("enumeration".equals(typeName)) {
1274 throw new YangParseException(moduleName, line,
1275 "The 'enum' statement MUST be present if the type is 'enumeration'.");
1280 * Parse refine statement.
1281 * @param refineCtx refine statement
1284 public static RefineHolder parseRefine(Refine_stmtContext refineCtx) {
1285 final String refineTarget = stringFromNode(refineCtx);
1286 final RefineHolder refine = new RefineHolder(refineTarget, refineCtx
1287 .getStart().getLine());
1288 for (int j = 0; j < refineCtx.getChildCount(); j++) {
1289 ParseTree refinePom = refineCtx.getChild(j);
1290 if (refinePom instanceof Refine_pomContext) {
1291 for (int k = 0; k < refinePom.getChildCount(); k++) {
1292 ParseTree refineStmt = refinePom.getChild(k);
1293 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1295 (Refine_leaf_stmtsContext) refineStmt);
1296 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1298 (Refine_container_stmtsContext) refineStmt);
1299 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1301 (Refine_list_stmtsContext) refineStmt);
1302 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1304 (Refine_leaf_list_stmtsContext) refineStmt);
1305 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1307 (Refine_choice_stmtsContext) refineStmt);
1308 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1310 (Refine_anyxml_stmtsContext) refineStmt);
1318 private static RefineHolder parseRefine(RefineHolder refine,
1319 Refine_leaf_stmtsContext refineStmt) {
1320 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1321 ParseTree refineArg = refineStmt.getChild(i);
1322 if (refineArg instanceof Default_stmtContext) {
1323 String defaultStr = stringFromNode(refineArg);
1324 refine.setDefaultStr(defaultStr);
1325 } else if (refineArg instanceof Mandatory_stmtContext) {
1326 for (int j = 0; j < refineArg.getChildCount(); j++) {
1327 ParseTree mandatoryTree = refineArg.getChild(j);
1328 if (mandatoryTree instanceof Mandatory_argContext) {
1329 Boolean mandatory = Boolean
1330 .valueOf(stringFromNode(mandatoryTree));
1331 refine.setMandatory(mandatory);
1334 } else if (refineArg instanceof Must_stmtContext) {
1335 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1336 refine.setMust(must);
1343 private static RefineHolder parseRefine(RefineHolder refine,
1344 Refine_container_stmtsContext refineStmt) {
1345 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1346 ParseTree refineArg = refineStmt.getChild(m);
1347 if (refineArg instanceof Must_stmtContext) {
1348 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1349 refine.setMust(must);
1350 } else if (refineArg instanceof Presence_stmtContext) {
1351 refine.setPresence(true);
1357 private static RefineHolder parseRefine(RefineHolder refine,
1358 Refine_list_stmtsContext refineStmt) {
1359 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1360 ParseTree refineArg = refineStmt.getChild(m);
1361 if (refineArg instanceof Must_stmtContext) {
1362 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1363 refine.setMust(must);
1364 } else if (refineArg instanceof Max_elements_stmtContext) {
1365 Integer max = Integer.valueOf(stringFromNode(refineArg));
1366 refine.setMinElements(max);
1367 } else if (refineArg instanceof Min_elements_stmtContext) {
1368 Integer min = Integer.valueOf(stringFromNode(refineArg));
1369 refine.setMinElements(min);
1375 private static RefineHolder parseRefine(RefineHolder refine,
1376 Refine_leaf_list_stmtsContext refineStmt) {
1377 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1378 ParseTree refineArg = refineStmt.getChild(m);
1379 if (refineArg instanceof Must_stmtContext) {
1380 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1381 refine.setMust(must);
1382 } else if (refineArg instanceof Max_elements_stmtContext) {
1383 Integer max = Integer.valueOf(stringFromNode(refineArg));
1384 refine.setMinElements(max);
1385 } else if (refineArg instanceof Min_elements_stmtContext) {
1386 Integer min = Integer.valueOf(stringFromNode(refineArg));
1387 refine.setMinElements(min);
1393 private static RefineHolder parseRefine(RefineHolder refine,
1394 Refine_choice_stmtsContext refineStmt) {
1395 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1396 ParseTree refineArg = refineStmt.getChild(i);
1397 if (refineArg instanceof Default_stmtContext) {
1398 String defaultStr = stringFromNode(refineArg);
1399 refine.setDefaultStr(defaultStr);
1400 } else if (refineArg instanceof Mandatory_stmtContext) {
1401 for (int j = 0; j < refineArg.getChildCount(); j++) {
1402 ParseTree mandatoryTree = refineArg.getChild(j);
1403 if (mandatoryTree instanceof Mandatory_argContext) {
1404 Boolean mandatory = Boolean
1405 .valueOf(stringFromNode(mandatoryTree));
1406 refine.setMandatory(mandatory);
1414 private static RefineHolder parseRefine(RefineHolder refine,
1415 Refine_anyxml_stmtsContext refineStmt) {
1416 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1417 ParseTree refineArg = refineStmt.getChild(i);
1418 if (refineArg instanceof Must_stmtContext) {
1419 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1420 refine.setMust(must);
1421 } else if (refineArg instanceof Mandatory_stmtContext) {
1422 for (int j = 0; j < refineArg.getChildCount(); j++) {
1423 ParseTree mandatoryTree = refineArg.getChild(j);
1424 if (mandatoryTree instanceof Mandatory_argContext) {
1425 Boolean mandatory = Boolean
1426 .valueOf(stringFromNode(mandatoryTree));
1427 refine.setMandatory(mandatory);