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.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.parser.builder.api.SchemaNodeBuilder;
85 import org.opendaylight.controller.yang.model.parser.builder.impl.ConstraintsBuilder;
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.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);
681 private static List<PatternConstraint> getPatternConstraint(
682 final Type_body_stmtsContext ctx) {
683 List<PatternConstraint> patterns = new ArrayList<PatternConstraint>();
685 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
686 ParseTree stringRestrChild = ctx.getChild(j);
687 if (stringRestrChild instanceof String_restrictionsContext) {
688 for (int k = 0; k < stringRestrChild.getChildCount(); k++) {
689 ParseTree lengthChild = stringRestrChild.getChild(k);
690 if (lengthChild instanceof Pattern_stmtContext) {
691 patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
692 if (k == lengthChild.getChildCount() - 1) {
703 * Internal helper method.
707 * @return PatternConstraint object
709 private static PatternConstraint parsePatternConstraint(
710 final Pattern_stmtContext ctx) {
711 String description = null;
712 String reference = null;
713 for (int i = 0; i < ctx.getChildCount(); i++) {
714 ParseTree child = ctx.getChild(i);
715 if (child instanceof Description_stmtContext) {
716 description = stringFromNode(child);
717 } else if (child instanceof Reference_stmtContext) {
718 reference = stringFromNode(child);
721 String pattern = patternStringFromNode(ctx);
722 return BaseConstraints.patternConstraint(pattern, description,
727 * Parse given context and return pattern value.
731 * @return pattern value as String
733 public static String patternStringFromNode(final Pattern_stmtContext ctx) {
734 StringBuilder result = new StringBuilder();
735 for (int i = 0; i < ctx.getChildCount(); ++i) {
736 ParseTree child = ctx.getChild(i);
737 if (child instanceof StringContext) {
738 for (int j = 0; j < child.getChildCount(); j++) {
740 String patternToken = child.getChild(j).getText();
741 result.append(patternToken.substring(1,
742 patternToken.length() - 1));
747 return result.toString();
751 * Get fraction digits value from context.
754 * type body context to parse
755 * @return 'fraction-digits' value if present in given context, null
758 private static Integer getFractionDigits(Type_body_stmtsContext ctx) {
759 Integer result = null;
760 for (int j = 0; j < ctx.getChildCount(); j++) {
761 ParseTree dec64specChild = ctx.getChild(j);
762 if (dec64specChild instanceof Decimal64_specificationContext) {
763 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild);
769 private static Integer parseFractionDigits(
770 Decimal64_specificationContext ctx) {
771 Integer result = null;
772 for (int k = 0; k < ctx.getChildCount(); k++) {
773 ParseTree fdChild = ctx.getChild(k);
774 if (fdChild instanceof Fraction_digits_stmtContext) {
775 String value = stringFromNode(fdChild);
777 result = Integer.valueOf(value);
778 } catch (NumberFormatException e) {
779 throw new YangParseException(
780 "Unable to parse fraction digits value '" + value
789 * Internal helper method for parsing bit statements from given type body
793 * type body context to parse
795 * current position in YANG model
799 * @return List of Bit objects created from this context
801 private static List<BitsTypeDefinition.Bit> getBits(
802 Type_body_stmtsContext ctx, List<String> actualPath, URI namespace,
803 Date revision, String prefix) {
804 final List<BitsTypeDefinition.Bit> bits = new ArrayList<BitsTypeDefinition.Bit>();
805 for (int j = 0; j < ctx.getChildCount(); j++) {
806 ParseTree bitsSpecChild = ctx.getChild(j);
807 if (bitsSpecChild instanceof Bits_specificationContext) {
808 long highestPosition = -1;
809 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
810 ParseTree bitChild = bitsSpecChild.getChild(k);
811 if (bitChild instanceof Bit_stmtContext) {
812 Bit bit = parseBit((Bit_stmtContext) bitChild,
813 highestPosition, actualPath, namespace,
815 if (bit.getPosition() > highestPosition) {
816 highestPosition = bit.getPosition();
827 * Internal helper method for parsing bit context.
830 * bit statement context to parse
831 * @param highestPosition
832 * current highest position in bits type
834 * current position in YANG model
838 * @return Bit object parsed from this context
840 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx,
841 long highestPosition, List<String> actualPath, final URI namespace,
842 final Date revision, final String prefix) {
843 String name = stringFromNode(ctx);
844 final QName qname = new QName(namespace, revision, prefix, name);
845 Long position = null;
847 String description = null;
848 String reference = null;
849 Status status = Status.CURRENT;
851 Stack<String> bitPath = new Stack<String>();
852 bitPath.addAll(actualPath);
855 SchemaPath schemaPath = createActualSchemaPath(bitPath, namespace,
858 for (int i = 0; i < ctx.getChildCount(); i++) {
859 ParseTree child = ctx.getChild(i);
860 if (child instanceof Position_stmtContext) {
861 String positionStr = stringFromNode(child);
862 position = Long.valueOf(positionStr);
863 } else if (child instanceof Description_stmtContext) {
864 description = stringFromNode(child);
865 } else if (child instanceof Reference_stmtContext) {
866 reference = stringFromNode(child);
867 } else if (child instanceof Status_stmtContext) {
868 status = parseStatus((Status_stmtContext) child);
872 if (position == null) {
873 position = highestPosition + 1;
875 if (position < 0 || position > 4294967295L) {
876 throw new YangParseException(
879 + "': the position value MUST be in the range 0 to 4294967295");
882 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
883 return new BitImpl(position, qname, schemaPath, description, reference,
884 status, unknownNodes);
888 * Parse orderedby statement.
891 * Ordered_by_stmtContext
892 * @return true, if orderedby contains value 'user' or false otherwise
894 public static boolean parseUserOrdered(Ordered_by_stmtContext childNode) {
895 boolean result = false;
896 for (int j = 0; j < childNode.getChildCount(); j++) {
897 ParseTree orderArg = childNode.getChild(j);
898 if (orderArg instanceof Ordered_by_argContext) {
899 String orderStr = stringFromNode(orderArg);
900 if ("system".equals(orderStr)) {
902 } else if ("user".equals(orderStr)) {
905 logger.warn("Invalid 'orderedby' statement.");
913 * Parse given config context and return true if it contains string 'true',
917 * config context to parse.
918 * @return true if given context contains string 'true', false otherwise
920 public static boolean parseConfig(final Config_stmtContext ctx) {
921 boolean result = false;
923 for (int i = 0; i < ctx.getChildCount(); ++i) {
924 final ParseTree configContext = ctx.getChild(i);
925 if (configContext instanceof Config_argContext) {
926 final String value = stringFromNode(configContext);
927 if ("true".equals(value)) {
938 * Parse given type body and creates UnknownType definition.
940 * @param typedefQName
941 * qname of current type
944 * @return UnknownType object with constraints from parsed type body
946 public static TypeDefinition<?> parseUnknownTypeBody(QName typedefQName,
947 Type_body_stmtsContext ctx) {
948 UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
951 List<RangeConstraint> rangeStatements = getRangeConstraints(ctx);
952 List<LengthConstraint> lengthStatements = getLengthConstraints(ctx);
953 List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
954 Integer fractionDigits = getFractionDigits(ctx);
956 unknownType.rangeStatements(rangeStatements);
957 unknownType.lengthStatements(lengthStatements);
958 unknownType.patterns(patternStatements);
959 unknownType.fractionDigits(fractionDigits);
962 return unknownType.build();
966 * Create TypeDefinition object based on given type name and type body.
973 * current path in schema
980 * @return TypeDefinition object based on parsed values.
982 public static TypeDefinition<?> parseTypeBody(final String typeName,
983 final Type_body_stmtsContext typeBody,
984 final List<String> actualPath, final URI namespace,
985 final Date revision, final String prefix) {
986 TypeDefinition<?> type = null;
988 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody);
989 Integer fractionDigits = getFractionDigits(typeBody);
990 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody);
991 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
992 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(
993 typeBody, actualPath, namespace, revision, prefix);
995 if ("decimal64".equals(typeName)) {
996 type = new Decimal64(actualPath, namespace, revision,
998 } else if (typeName.startsWith("int")) {
999 if (typeName.equals("int8")) {
1000 type = new Int8(actualPath, namespace, revision,
1001 rangeStatements, null, null);
1002 } else if (typeName.equals("int16")) {
1003 type = new Int16(actualPath, namespace, revision,
1004 rangeStatements, null, null);
1005 } else if (typeName.equals("int32")) {
1006 type = new Int32(actualPath, namespace, revision,
1007 rangeStatements, null, null);
1008 } else if (typeName.equals("int64")) {
1009 type = new Int64(actualPath, namespace, revision,
1010 rangeStatements, null, null);
1012 } else if (typeName.startsWith("uint")) {
1013 if (typeName.equals("uint8")) {
1014 type = new Uint8(actualPath, namespace, revision,
1015 rangeStatements, null, null);
1016 } else if (typeName.equals("uint16")) {
1017 type = new Uint16(actualPath, namespace, revision,
1018 rangeStatements, null, null);
1019 } else if (typeName.equals("uint32")) {
1020 type = new Uint32(actualPath, namespace, revision,
1021 rangeStatements, null, null);
1022 } else if (typeName.equals("uint64")) {
1023 type = new Uint64(actualPath, namespace, revision,
1024 rangeStatements, null, null);
1026 } else if ("enumeration".equals(typeName)) {
1027 type = new EnumerationType(actualPath, namespace, revision,
1029 } else if ("string".equals(typeName)) {
1030 type = new StringType(actualPath, namespace, revision,
1031 lengthStatements, patternStatements);
1032 } else if ("bits".equals(typeName)) {
1033 type = new BitsType(actualPath, namespace, revision, getBits(
1034 typeBody, actualPath, namespace, revision, prefix));
1035 } else if ("leafref".equals(typeName)) {
1036 final String path = parseLeafrefPath(typeBody);
1037 final boolean absolute = path.startsWith("/");
1038 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path,
1040 type = new Leafref(actualPath, namespace, revision, xpath);
1041 } else if ("binary".equals(typeName)) {
1042 List<Byte> bytes = Collections.emptyList();
1043 type = new BinaryType(actualPath, namespace, revision, bytes,
1044 lengthStatements, null);
1045 } else if ("instance-identifier".equals(typeName)) {
1046 boolean requireInstance = isRequireInstance(typeBody);
1047 type = new InstanceIdentifier(actualPath, namespace, revision,
1048 null, requireInstance);
1053 public static String getIdentityrefBase(Type_body_stmtsContext ctx) {
1054 String result = null;
1055 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1056 ParseTree child = ctx.getChild(i);
1057 if (child instanceof Identityref_specificationContext) {
1058 for (int j = 0; j < child.getChildCount(); j++) {
1059 ParseTree baseArg = child.getChild(j);
1060 if (baseArg instanceof Base_stmtContext) {
1061 result = stringFromNode(baseArg);
1070 private static boolean isRequireInstance(Type_body_stmtsContext ctx) {
1071 for (int i = 0; i < ctx.getChildCount(); i++) {
1072 ParseTree child = ctx.getChild(i);
1073 if (child instanceof Require_instance_stmtContext) {
1074 for (int j = 0; j < child.getChildCount(); j++) {
1075 ParseTree reqArg = child.getChild(j);
1076 if (reqArg instanceof Require_instance_argContext) {
1077 return Boolean.valueOf(stringFromNode(reqArg));
1085 private static String parseLeafrefPath(Type_body_stmtsContext ctx) {
1086 for (int i = 0; i < ctx.getChildCount(); i++) {
1087 ParseTree child = ctx.getChild(i);
1088 if (child instanceof Leafref_specificationContext) {
1089 for (int j = 0; j < child.getChildCount(); j++) {
1090 ParseTree leafRefSpec = child.getChild(j);
1091 if (leafRefSpec instanceof Path_stmtContext) {
1092 return stringFromNode(leafRefSpec);
1101 * Internal helper method for parsing Must_stmtContext.
1105 * @return MustDefinition object based on parsed context
1107 public static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1108 StringBuilder mustText = new StringBuilder();
1109 String description = null;
1110 String reference = null;
1111 String errorAppTag = null;
1112 String errorMessage = null;
1113 for (int i = 0; i < ctx.getChildCount(); ++i) {
1114 ParseTree child = ctx.getChild(i);
1115 if (child instanceof StringContext) {
1116 final StringContext context = (StringContext) child;
1117 if (context.getChildCount() == 1) {
1118 String mustPart = context.getChild(0).getText();
1119 // trim start and end quotation
1120 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1122 for (int j = 0; j < context.getChildCount(); j++) {
1123 String mustPart = context.getChild(j).getText();
1125 mustText.append(mustPart.substring(0,
1126 mustPart.length() - 1));
1130 mustText.append(mustPart.substring(1));
1134 } else if (child instanceof Description_stmtContext) {
1135 description = stringFromNode(child);
1136 } else if (child instanceof Reference_stmtContext) {
1137 reference = stringFromNode(child);
1138 } else if (child instanceof Error_app_tag_stmtContext) {
1139 errorAppTag = stringFromNode(child);
1140 } else if (child instanceof Error_message_stmtContext) {
1141 errorMessage = stringFromNode(child);
1145 MustDefinition must = new MustDefinitionImpl(mustText.toString(),
1146 description, reference, errorAppTag, errorMessage);
1151 * Parse given tree and set constraints to given builder.
1155 * @param constraints
1156 * ConstraintsBuilder to fill
1158 public static void parseConstraints(final ParseTree ctx,
1159 final ConstraintsBuilder constraints) {
1160 for (int i = 0; i < ctx.getChildCount(); ++i) {
1161 final ParseTree childNode = ctx.getChild(i);
1162 if (childNode instanceof Max_elements_stmtContext) {
1163 Integer max = Integer.valueOf(stringFromNode(childNode));
1164 constraints.setMinElements(max);
1165 } else if (childNode instanceof Min_elements_stmtContext) {
1166 Integer min = Integer.valueOf(stringFromNode(childNode));
1167 constraints.setMinElements(min);
1168 } else if (childNode instanceof Must_stmtContext) {
1169 MustDefinition must = parseMust((Must_stmtContext) childNode);
1170 constraints.addMustDefinition(must);
1171 } else if (childNode instanceof Mandatory_stmtContext) {
1172 for (int j = 0; j < childNode.getChildCount(); j++) {
1173 ParseTree mandatoryTree = ctx.getChild(j);
1174 if (mandatoryTree instanceof Mandatory_argContext) {
1175 Boolean mandatory = Boolean
1176 .valueOf(stringFromNode(mandatoryTree));
1177 constraints.setMandatory(mandatory);
1180 } else if (childNode instanceof When_stmtContext) {
1181 constraints.addWhenCondition(stringFromNode(childNode));
1187 * Parse given context and return yin value.
1191 * @return true if value is 'true', false otherwise
1193 public static boolean parseYinValue(Argument_stmtContext ctx) {
1194 boolean yinValue = false;
1195 outer: for (int j = 0; j < ctx.getChildCount(); j++) {
1196 ParseTree yin = ctx.getChild(j);
1197 if (yin instanceof Yin_element_stmtContext) {
1198 for (int k = 0; k < yin.getChildCount(); k++) {
1199 ParseTree yinArg = yin.getChild(k);
1200 if (yinArg instanceof Yin_element_argContext) {
1201 String yinString = stringFromNode(yinArg);
1202 if ("true".equals(yinString)) {
1214 * Check this base type.
1217 * base YANG type name
1219 * name of current module
1222 * @throws YangParseException
1223 * if this is one of YANG type which MUST contain additional
1224 * informations in its body
1226 public static void checkMissingBody(final String typeName,
1227 final String moduleName, final int line) throws YangParseException {
1228 if ("decimal64".equals(typeName)) {
1229 throw new YangParseException(moduleName, line,
1230 "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1231 } else if ("identityref".equals(typeName)) {
1232 throw new YangParseException(moduleName, line,
1233 "The 'base' statement MUST be present if the type is 'identityref'.");
1234 } else if ("leafref".equals(typeName)) {
1235 throw new YangParseException(moduleName, line,
1236 "The 'path' statement MUST be present if the type is 'leafref'.");
1237 } else if("bits".equals(typeName)) {
1238 throw new YangParseException(moduleName, line,
1239 "The 'bit' statement MUST be present if the type is 'bits'.");
1240 } else if("enumeration".equals(typeName)) {
1241 throw new YangParseException(moduleName, line,
1242 "The 'enum' statement MUST be present if the type is 'enumeration'.");
1246 public static RefineHolder parseRefine(Refine_stmtContext child) {
1247 final String refineTarget = stringFromNode(child);
1248 final RefineHolder refine = new RefineHolder(refineTarget, child
1249 .getStart().getLine());
1250 for (int j = 0; j < child.getChildCount(); j++) {
1251 ParseTree refinePom = child.getChild(j);
1252 if (refinePom instanceof Refine_pomContext) {
1253 for (int k = 0; k < refinePom.getChildCount(); k++) {
1254 ParseTree refineStmt = refinePom.getChild(k);
1255 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1257 (Refine_leaf_stmtsContext) refineStmt);
1258 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1260 (Refine_container_stmtsContext) refineStmt);
1261 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1263 (Refine_list_stmtsContext) refineStmt);
1264 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1266 (Refine_leaf_list_stmtsContext) refineStmt);
1267 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1269 (Refine_choice_stmtsContext) refineStmt);
1270 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1272 (Refine_anyxml_stmtsContext) refineStmt);
1280 private static RefineHolder parseRefine(RefineHolder refine,
1281 Refine_leaf_stmtsContext refineStmt) {
1282 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1283 ParseTree refineArg = refineStmt.getChild(i);
1284 if (refineArg instanceof Default_stmtContext) {
1285 String defaultStr = stringFromNode(refineArg);
1286 refine.setDefaultStr(defaultStr);
1287 } else if (refineArg instanceof Mandatory_stmtContext) {
1288 for (int j = 0; j < refineArg.getChildCount(); j++) {
1289 ParseTree mandatoryTree = refineArg.getChild(j);
1290 if (mandatoryTree instanceof Mandatory_argContext) {
1291 Boolean mandatory = Boolean
1292 .valueOf(stringFromNode(mandatoryTree));
1293 refine.setMandatory(mandatory);
1296 } else if (refineArg instanceof Must_stmtContext) {
1297 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1298 refine.setMust(must);
1305 private static RefineHolder parseRefine(RefineHolder refine,
1306 Refine_container_stmtsContext refineStmt) {
1307 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1308 ParseTree refineArg = refineStmt.getChild(m);
1309 if (refineArg instanceof Must_stmtContext) {
1310 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1311 refine.setMust(must);
1312 } else if (refineArg instanceof Presence_stmtContext) {
1313 refine.setPresence(true);
1319 private static RefineHolder parseRefine(RefineHolder refine,
1320 Refine_list_stmtsContext refineStmt) {
1321 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1322 ParseTree refineArg = refineStmt.getChild(m);
1323 if (refineArg instanceof Must_stmtContext) {
1324 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1325 refine.setMust(must);
1326 } else if (refineArg instanceof Max_elements_stmtContext) {
1327 Integer max = Integer.valueOf(stringFromNode(refineArg));
1328 refine.setMinElements(max);
1329 } else if (refineArg instanceof Min_elements_stmtContext) {
1330 Integer min = Integer.valueOf(stringFromNode(refineArg));
1331 refine.setMinElements(min);
1337 private static RefineHolder parseRefine(RefineHolder refine,
1338 Refine_leaf_list_stmtsContext refineStmt) {
1339 for (int m = 0; m < refineStmt.getChildCount(); m++) {
1340 ParseTree refineArg = refineStmt.getChild(m);
1341 if (refineArg instanceof Must_stmtContext) {
1342 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1343 refine.setMust(must);
1344 } else if (refineArg instanceof Max_elements_stmtContext) {
1345 Integer max = Integer.valueOf(stringFromNode(refineArg));
1346 refine.setMinElements(max);
1347 } else if (refineArg instanceof Min_elements_stmtContext) {
1348 Integer min = Integer.valueOf(stringFromNode(refineArg));
1349 refine.setMinElements(min);
1355 private static RefineHolder parseRefine(RefineHolder refine,
1356 Refine_choice_stmtsContext refineStmt) {
1357 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1358 ParseTree refineArg = refineStmt.getChild(i);
1359 if (refineArg instanceof Default_stmtContext) {
1360 String defaultStr = stringFromNode(refineArg);
1361 refine.setDefaultStr(defaultStr);
1362 } else if (refineArg instanceof Mandatory_stmtContext) {
1363 for (int j = 0; j < refineArg.getChildCount(); j++) {
1364 ParseTree mandatoryTree = refineArg.getChild(j);
1365 if (mandatoryTree instanceof Mandatory_argContext) {
1366 Boolean mandatory = Boolean
1367 .valueOf(stringFromNode(mandatoryTree));
1368 refine.setMandatory(mandatory);
1376 private static RefineHolder parseRefine(RefineHolder refine,
1377 Refine_anyxml_stmtsContext refineStmt) {
1378 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1379 ParseTree refineArg = refineStmt.getChild(i);
1380 if (refineArg instanceof Must_stmtContext) {
1381 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1382 refine.setMust(must);
1383 } else if (refineArg instanceof Mandatory_stmtContext) {
1384 for (int j = 0; j < refineArg.getChildCount(); j++) {
1385 ParseTree mandatoryTree = refineArg.getChild(j);
1386 if (mandatoryTree instanceof Mandatory_argContext) {
1387 Boolean mandatory = Boolean
1388 .valueOf(stringFromNode(mandatoryTree));
1389 refine.setMandatory(mandatory);