2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/eplv10.html
8 package org.opendaylight.yangtools.yang.parser.impl;
10 import static com.google.common.base.Preconditions.checkState;
12 import com.google.common.base.Optional;
13 import java.math.BigDecimal;
15 import java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.Date;
18 import java.util.List;
19 import java.util.Stack;
20 import org.antlr.v4.runtime.ParserRuleContext;
21 import org.antlr.v4.runtime.tree.ParseTree;
22 import org.antlr.v4.runtime.tree.TerminalNode;
23 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
24 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
25 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
26 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bit_stmtContext;
27 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bits_specificationContext;
28 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_argContext;
29 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_stmtContext;
30 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Decimal64_specificationContext;
31 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Default_stmtContext;
32 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Description_stmtContext;
33 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_specificationContext;
34 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_stmtContext;
35 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_app_tag_stmtContext;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_message_stmtContext;
37 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Fraction_digits_stmtContext;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Identityref_specificationContext;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Instance_identifier_specificationContext;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Key_stmtContext;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Leafref_specificationContext;
42 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Length_stmtContext;
43 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_argContext;
44 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_stmtContext;
45 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_elements_stmtContext;
46 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_value_argContext;
47 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_elements_stmtContext;
48 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_value_argContext;
49 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
50 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Must_stmtContext;
51 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Numerical_restrictionsContext;
52 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_argContext;
53 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
54 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Path_stmtContext;
55 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Pattern_stmtContext;
56 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Position_stmtContext;
57 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Presence_stmtContext;
58 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Range_stmtContext;
59 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Reference_stmtContext;
60 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_anyxml_stmtsContext;
61 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_choice_stmtsContext;
62 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_container_stmtsContext;
63 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_list_stmtsContext;
64 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_stmtsContext;
65 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_list_stmtsContext;
66 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_pomContext;
67 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_stmtContext;
68 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_argContext;
69 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_stmtContext;
70 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_argContext;
71 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_stmtContext;
72 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.StringContext;
73 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.String_restrictionsContext;
74 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
75 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
76 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Value_stmtContext;
77 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
78 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_argContext;
79 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
80 import org.opendaylight.yangtools.yang.common.QName;
81 import org.opendaylight.yangtools.yang.model.api.MustDefinition;
82 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
83 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
84 import org.opendaylight.yangtools.yang.model.api.Status;
85 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
86 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
88 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
89 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
90 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
91 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
92 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
93 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
94 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
95 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
96 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
98 import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
99 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
100 import org.opendaylight.yangtools.yang.model.util.BinaryType;
101 import org.opendaylight.yangtools.yang.model.util.BitImpl;
102 import org.opendaylight.yangtools.yang.model.util.BitsType;
103 import org.opendaylight.yangtools.yang.model.util.Decimal64;
104 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
105 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
106 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifier;
107 import org.opendaylight.yangtools.yang.model.util.Int16;
108 import org.opendaylight.yangtools.yang.model.util.Int32;
109 import org.opendaylight.yangtools.yang.model.util.Int64;
110 import org.opendaylight.yangtools.yang.model.util.Int8;
111 import org.opendaylight.yangtools.yang.model.util.Leafref;
112 import org.opendaylight.yangtools.yang.model.util.MustDefinitionImpl;
113 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
114 import org.opendaylight.yangtools.yang.model.util.StringType;
115 import org.opendaylight.yangtools.yang.model.util.Uint16;
116 import org.opendaylight.yangtools.yang.model.util.Uint32;
117 import org.opendaylight.yangtools.yang.model.util.Uint64;
118 import org.opendaylight.yangtools.yang.model.util.Uint8;
119 import org.opendaylight.yangtools.yang.model.util.UnknownType;
120 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
121 import org.opendaylight.yangtools.yang.parser.builder.api.ConstraintsBuilder;
122 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
123 import org.opendaylight.yangtools.yang.parser.builder.api.RefineBuilder;
124 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
125 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
126 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
127 import org.opendaylight.yangtools.yang.parser.builder.impl.RefineHolderImpl;
128 import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
129 import org.opendaylight.yangtools.yang.parser.util.TypeConstraints;
130 import org.opendaylight.yangtools.yang.parser.util.UnknownBoundaryNumber;
131 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
132 import org.slf4j.Logger;
133 import org.slf4j.LoggerFactory;
135 public final class ParserListenerUtils {
136 private static final Logger LOG = LoggerFactory.getLogger(ParserListenerUtils.class);
138 private ParserListenerUtils() {
142 * Parse given tree and get first string value.
146 * @return first string value from given tree
148 public static String stringFromNode(final ParseTree treeNode) {
150 for (int i = 0; i < treeNode.getChildCount(); ++i) {
151 if (treeNode.getChild(i) instanceof StringContext) {
152 final StringContext context = (StringContext) treeNode.getChild(i);
153 if (context != null) {
154 return stringFromStringContext(context);
162 private static String stringFromStringContext(final StringContext context) {
163 StringBuilder str = new StringBuilder();
164 for (TerminalNode stringNode : context.STRING()) {
165 String result = stringNode.getText();
166 if(!result.contains("\"")){
168 } else if (!(result.startsWith("\"")) && result.endsWith("\"")) {
169 LOG.error("Syntax error in module {} at line {}: missing '\"'.", getParentModule(context),
170 context.getStart().getLine());
172 str.append(result.replace("\"", ""));
175 return str.toString();
178 private static String getParentModule(final ParseTree ctx) {
179 ParseTree current = ctx;
180 while (current != null && !(current instanceof Module_stmtContext)) {
181 current = current.getParent();
183 if (current != null) {
184 Module_stmtContext module = (Module_stmtContext) current;
185 for (int i = 0; i < module.getChildCount(); i++) {
186 if (module.getChild(i) instanceof StringContext) {
187 final StringContext str = (StringContext) module.getChild(i);
188 return str.getChild(0).getText();
196 * Parse 'description', 'reference' and 'status' statements and fill in
202 * builder to fill in with parsed statements
204 public static void parseSchemaNodeArgs(final ParseTree ctx, final SchemaNodeBuilder builder) {
205 for (int i = 0; i < ctx.getChildCount(); i++) {
206 final ParseTree child = ctx.getChild(i);
207 if (child instanceof Description_stmtContext) {
208 final String desc = stringFromNode(child);
209 builder.setDescription(desc);
210 } else if (child instanceof Reference_stmtContext) {
211 final String ref = stringFromNode(child);
212 builder.setReference(ref);
213 } else if (child instanceof Status_stmtContext) {
214 final Status status = parseStatus((Status_stmtContext) child);
215 builder.setStatus(status);
221 * Parse given context and return its value;
225 * @return value parsed from context
227 public static Status parseStatus(final Status_stmtContext ctx) {
228 Status result = null;
229 for (int i = 0; i < ctx.getChildCount(); i++) {
230 ParseTree statusArg = ctx.getChild(i);
231 if (statusArg instanceof Status_argContext) {
232 String statusArgStr = stringFromNode(statusArg);
233 switch (statusArgStr) {
235 result = Status.CURRENT;
238 result = Status.DEPRECATED;
241 result = Status.OBSOLETE;
244 LOG.warn("Invalid 'status' statement: " + statusArgStr);
252 * Parse given tree and returns units statement as string.
256 * @return value of units statement as string or null if there is no units
259 public static String parseUnits(final ParseTree ctx) {
261 for (int i = 0; i < ctx.getChildCount(); i++) {
262 ParseTree child = ctx.getChild(i);
263 if (child instanceof Units_stmtContext) {
264 units = stringFromNode(child);
272 * Parse given tree and returns default statement as string.
276 * @return value of default statement as string or null if there is no
279 public static String parseDefault(final ParseTree ctx) {
280 String defaultValue = null;
281 for (int i = 0; i < ctx.getChildCount(); i++) {
282 ParseTree child = ctx.getChild(i);
283 if (child instanceof Default_stmtContext) {
284 defaultValue = stringFromNode(child);
292 * Create SchemaPath from actualPath and new node name.
295 * current position in model
296 * @return SchemaPath object
298 public static SchemaPath createActualSchemaPath(final Stack<QName> actualPath) {
299 return SchemaPath.create(actualPath, true);
303 * Create java.util.List of key node names.
306 * Key_stmtContext context
307 * @return YANG list key as java.util.List of key node names
309 public static List<String> createListKey(final Key_stmtContext ctx) {
310 String keyDefinition = stringFromNode(ctx);
311 List<String> keys = new ArrayList<>();
312 String[] splittedKey = keyDefinition.split(" ");
313 for (String keyElement : splittedKey) {
314 if (!keyElement.isEmpty()) {
315 keys.add(keyElement);
322 * Parse given type body of enumeration statement.
325 * type body context to parse
327 * actual position in YANG model
329 * current module name
330 * @return List of EnumPair object parsed from given context
332 private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
333 final Stack<QName> path, final String moduleName) {
334 List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<>();
336 for (int i = 0; i < ctx.getChildCount(); i++) {
337 ParseTree enumSpecChild = ctx.getChild(i);
338 if (enumSpecChild instanceof Enum_specificationContext) {
339 int highestValue = -1;
340 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
341 ParseTree enumChild = enumSpecChild.getChild(j);
342 if (enumChild instanceof Enum_stmtContext) {
343 EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName);
344 if (enumPair.getValue() > highestValue) {
345 highestValue = enumPair.getValue();
347 enumConstants.add(enumPair);
352 return enumConstants;
356 * Parse enum statement context
359 * enum statement context
360 * @param highestValue
361 * current highest value in enumeration
363 * actual position in YANG model
365 * current module name
366 * @return EnumPair object parsed from given context
368 private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
369 final Stack<QName> actualPath, final String moduleName) {
370 final String name = stringFromNode(ctx);
371 SchemaPath path = createTypePath(actualPath, name);
372 Integer value = null;
374 String description = null;
375 String reference = null;
376 Status status = null;
378 for (int i = 0; i < ctx.getChildCount(); i++) {
379 ParseTree child = ctx.getChild(i);
380 if (child instanceof Value_stmtContext) {
381 String valueStr = stringFromNode(child);
382 value = Integer.valueOf(valueStr);
383 } else if (child instanceof Description_stmtContext) {
384 description = stringFromNode(child);
385 } else if (child instanceof Reference_stmtContext) {
386 reference = stringFromNode(child);
387 } else if (child instanceof Status_stmtContext) {
388 status = parseStatus((Status_stmtContext) child);
393 value = highestValue + 1;
395 if (value < -2147483648 || value > 2147483647) {
396 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on enum '" + name
397 + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: " + value);
400 EnumPairImpl result = new EnumPairImpl();
401 result.qname = path.getPathTowardsRoot().iterator().next();
403 result.description = description;
404 result.reference = reference;
405 result.status = status;
407 result.value = value;
412 * Internal implementation of EnumPair.
414 private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
416 private SchemaPath path;
417 private String description;
418 private String reference;
419 private Status status;
420 private final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
422 private Integer value;
425 public QName getQName() {
430 public SchemaPath getPath() {
435 public String getDescription() {
440 public String getReference() {
445 public Status getStatus() {
450 public List<UnknownSchemaNode> getUnknownSchemaNodes() {
455 public String getName() {
460 public Integer getValue() {
465 public int hashCode() {
466 final int prime = 31;
468 result = prime * result + ((qname == null) ? 0 : qname.hashCode());
469 result = prime * result + ((path == null) ? 0 : path.hashCode());
470 result = prime * result + ((unknownNodes == null) ? 0 : unknownNodes.hashCode());
471 result = prime * result + ((name == null) ? 0 : name.hashCode());
472 result = prime * result + ((value == null) ? 0 : value.hashCode());
477 public boolean equals(final Object obj) {
484 if (getClass() != obj.getClass()) {
487 EnumPairImpl other = (EnumPairImpl) obj;
489 if (other.qname != null) {
492 } else if (!qname.equals(other.qname)) {
496 if (other.path != null) {
499 } else if (!path.equals(other.path)) {
502 if (unknownNodes == null) {
503 if (other.unknownNodes != null) {
506 } else if (!unknownNodes.equals(other.unknownNodes)) {
510 if (other.name != null) {
513 } else if (!name.equals(other.name)) {
517 if (other.value != null) {
520 } else if (!value.equals(other.value)) {
527 public String toString() {
528 return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
533 * Get and parse range from given type body context.
536 * type body context to parse
538 * name of current module
539 * @return List of RangeConstraint created from this context
541 private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
542 List<RangeConstraint> rangeConstraints = Collections.emptyList();
543 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
544 ParseTree numRestrChild = ctx.getChild(i);
546 if (numRestrChild instanceof Numerical_restrictionsContext) {
547 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
548 ParseTree rangeChild = numRestrChild.getChild(j);
549 if (rangeChild instanceof Range_stmtContext) {
550 rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
556 if (numRestrChild instanceof Decimal64_specificationContext) {
557 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
558 ParseTree decRestr = numRestrChild.getChild(j);
559 if (decRestr instanceof Numerical_restrictionsContext) {
560 for (int k = 0; k < decRestr.getChildCount(); k++) {
561 ParseTree rangeChild = decRestr.getChild(k);
562 if (rangeChild instanceof Range_stmtContext) {
563 rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
572 return rangeConstraints;
576 * Parse given range context.
579 * range context to parse
581 * name of current module
582 * @return List of RangeConstraints parsed from this context
584 private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx, final String moduleName) {
585 final int line = ctx.getStart().getLine();
586 List<RangeConstraint> rangeConstraints = new ArrayList<>();
587 String description = null;
588 String reference = null;
590 for (int i = 0; i < ctx.getChildCount(); i++) {
591 ParseTree child = ctx.getChild(i);
592 if (child instanceof Description_stmtContext) {
593 description = stringFromNode(child);
594 } else if (child instanceof Reference_stmtContext) {
595 reference = stringFromNode(child);
599 String rangeStr = stringFromNode(ctx);
600 String trimmed = rangeStr.replace(" ", "");
601 String[] splittedRange = trimmed.split("\\|");
602 for (String rangeDef : splittedRange) {
603 String[] splittedRangeDef = rangeDef.split("\\.\\.");
606 if (splittedRangeDef.length == 1) {
607 min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
609 min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
610 max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
612 RangeConstraint range = BaseConstraints.rangeConstraint(min, max, description, reference);
613 rangeConstraints.add(range);
616 return rangeConstraints;
620 * Get and parse length from given type body context.
623 * type body context to parse
625 * name of current module
626 * @return List of LengthConstraint created from this context
628 private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
629 List<LengthConstraint> lengthConstraints = Collections.emptyList();
630 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
631 ParseTree stringRestrChild = ctx.getChild(i);
632 if (stringRestrChild instanceof String_restrictionsContext) {
633 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
634 ParseTree lengthChild = stringRestrChild.getChild(j);
635 if (lengthChild instanceof Length_stmtContext) {
636 lengthConstraints = parseLengthConstraints((Length_stmtContext) lengthChild, moduleName);
642 return lengthConstraints;
646 * Parse given length context.
649 * length context to parse
651 * name of current module
652 * @return List of LengthConstraints parsed from this context
654 private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx, final String moduleName) {
655 final int line = ctx.getStart().getLine();
656 List<LengthConstraint> lengthConstraints = new ArrayList<>();
657 String description = null;
658 String reference = null;
660 for (int i = 0; i < ctx.getChildCount(); i++) {
661 ParseTree child = ctx.getChild(i);
662 if (child instanceof Description_stmtContext) {
663 description = stringFromNode(child);
664 } else if (child instanceof Reference_stmtContext) {
665 reference = stringFromNode(child);
669 String lengthStr = stringFromNode(ctx);
670 String trimmed = lengthStr.replace(" ", "");
671 String[] splittedRange = trimmed.split("\\|");
672 for (String rangeDef : splittedRange) {
673 String[] splittedRangeDef = rangeDef.split("\\.\\.");
676 if (splittedRangeDef.length == 1) {
677 min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
679 min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
680 max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
682 LengthConstraint range = BaseConstraints.lengthConstraint(min, max, description, reference);
683 lengthConstraints.add(range);
686 return lengthConstraints;
693 * name of current module
695 * current line in module
696 * @return wrapper object of primitive java type or UnknownBoundaryNumber if
697 * type is one of special YANG values 'min' or 'max'
699 private static Number parseNumberConstraintValue(final String value, final String moduleName, final int line) {
701 if ("min".equals(value) || "max".equals(value)) {
702 result = new UnknownBoundaryNumber(value);
705 if (value.contains(".")) {
706 result = new BigDecimal(value);
708 result = Long.valueOf(value);
710 } catch (NumberFormatException e) {
711 throw new YangParseException(moduleName, line, "Unable to parse range value '" + value + "'.", e);
718 * Parse type body and return pattern constraints.
722 * @return list of pattern constraints
724 private static List<PatternConstraint> getPatternConstraint(final Type_body_stmtsContext ctx) {
725 List<PatternConstraint> patterns = new ArrayList<>();
727 for (int i = 0; i < ctx.getChildCount(); i++) {
728 ParseTree stringRestrChild = ctx.getChild(i);
729 if (stringRestrChild instanceof String_restrictionsContext) {
730 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
731 ParseTree lengthChild = stringRestrChild.getChild(j);
732 if (lengthChild instanceof Pattern_stmtContext) {
733 patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
742 * Internal helper method.
746 * @return PatternConstraint object
748 private static PatternConstraint parsePatternConstraint(final Pattern_stmtContext ctx) {
749 String description = null;
750 String reference = null;
751 for (int i = 0; i < ctx.getChildCount(); i++) {
752 ParseTree child = ctx.getChild(i);
753 if (child instanceof Description_stmtContext) {
754 description = stringFromNode(child);
755 } else if (child instanceof Reference_stmtContext) {
756 reference = stringFromNode(child);
759 String pattern = parsePatternString(ctx);
760 return BaseConstraints.patternConstraint(pattern, description, reference);
764 * Parse given context and return pattern value.
768 * @return pattern value as String
770 private static String parsePatternString(final Pattern_stmtContext ctx) {
771 StringBuilder result = new StringBuilder();
772 for (int i = 0; i < ctx.getChildCount(); ++i) {
773 ParseTree child = ctx.getChild(i);
774 if (child instanceof StringContext) {
775 for (int j = 0; j < child.getChildCount(); j++) {
777 String patternToken = child.getChild(j).getText();
778 result.append(patternToken.substring(1, patternToken.length() - 1));
783 return result.toString();
787 * Get fraction digits value from type body.
790 * type body context to parse
792 * name of current module
793 * @return 'fraction-digits' value if present in given context, null
796 private static Integer getFractionDigits(final Type_body_stmtsContext ctx, final String moduleName) {
797 Integer result = null;
798 for (int i = 0; i < ctx.getChildCount(); i++) {
799 ParseTree dec64specChild = ctx.getChild(i);
800 if (dec64specChild instanceof Decimal64_specificationContext) {
801 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild, moduleName);
808 * Parse decimal64 fraction-digits value.
813 * name of current module
814 * @return fraction-digits value as Integer
816 private static Integer parseFractionDigits(final Decimal64_specificationContext ctx, final String moduleName) {
817 Integer result = null;
818 for (int i = 0; i < ctx.getChildCount(); i++) {
819 ParseTree fdChild = ctx.getChild(i);
820 if (fdChild instanceof Fraction_digits_stmtContext) {
821 String value = stringFromNode(fdChild);
823 result = Integer.valueOf(value);
824 } catch (NumberFormatException e) {
825 throw new YangParseException(moduleName, ctx.getStart().getLine(),
826 "Unable to parse fraction digits value '" + value + "'.", e);
834 * Internal helper method for parsing bit statements from given type body
838 * type body context to parse
840 * current position in YANG model
842 * current module name
843 * @return List of Bit objects created from this context
845 private static List<BitsTypeDefinition.Bit> getBits(final Type_body_stmtsContext ctx, final Stack<QName> actualPath,
846 final String moduleName) {
847 final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
848 for (int j = 0; j < ctx.getChildCount(); j++) {
849 ParseTree bitsSpecChild = ctx.getChild(j);
850 if (bitsSpecChild instanceof Bits_specificationContext) {
851 long highestPosition = -1;
852 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
853 ParseTree bitChild = bitsSpecChild.getChild(k);
854 if (bitChild instanceof Bit_stmtContext) {
855 Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, moduleName);
856 if (bit.getPosition() > highestPosition) {
857 highestPosition = bit.getPosition();
868 * Internal helper method for parsing bit context.
871 * bit statement context to parse
872 * @param highestPosition
873 * current highest position in bits type
875 * current position in YANG model
877 * current module name
878 * @return Bit object parsed from this context
880 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, final long highestPosition,
881 final Stack<QName> actualPath, final String moduleName) {
882 String name = stringFromNode(ctx);
883 Long position = null;
885 String description = null;
886 String reference = null;
887 Status status = Status.CURRENT;
889 SchemaPath schemaPath = createBaseTypePath(actualPath, name);
891 for (int i = 0; i < ctx.getChildCount(); i++) {
892 ParseTree child = ctx.getChild(i);
893 if (child instanceof Position_stmtContext) {
894 String positionStr = stringFromNode(child);
895 position = Long.valueOf(positionStr);
896 } else if (child instanceof Description_stmtContext) {
897 description = stringFromNode(child);
898 } else if (child instanceof Reference_stmtContext) {
899 reference = stringFromNode(child);
900 } else if (child instanceof Status_stmtContext) {
901 status = parseStatus((Status_stmtContext) child);
905 if (position == null) {
906 position = highestPosition + 1;
908 if (position < 0 || position > 4294967295L) {
909 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on bit '" + name
910 + "': the position value MUST be in the range 0 to 4294967295");
913 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
914 return new BitImpl(position, schemaPath.getPathTowardsRoot().iterator().next(), schemaPath,
915 description, reference, status, unknownNodes);
919 * Parse 'ordered-by' statement.
921 * The 'ordered-by' statement defines whether the order of entries within a
922 * list are determined by the user or the system. The argument is one of the
923 * strings "system" or "user". If not present, order defaults to "system".
926 * Ordered_by_stmtContext
927 * @return true, if ordered-by contains value 'user', false otherwise
929 public static boolean parseUserOrdered(final Ordered_by_stmtContext ctx) {
930 boolean result = false;
931 for (int j = 0; j < ctx.getChildCount(); j++) {
932 ParseTree orderArg = ctx.getChild(j);
933 if (orderArg instanceof Ordered_by_argContext) {
934 String orderStr = stringFromNode(orderArg);
943 LOG.warn("Invalid 'ordered-by' statement.");
951 * Get config statement from given context. If there is no config statement,
952 * return config value of parent
959 * name of current module
961 * line in current module
962 * @return config statement parsed from given context
964 public static boolean getConfig(final ParseTree ctx, final Builder node, final String moduleName, final int line) {
966 // parse configuration statement
967 Boolean config = null;
968 for (int i = 0; i < ctx.getChildCount(); i++) {
969 ParseTree child = ctx.getChild(i);
970 if (child instanceof Config_stmtContext) {
971 config = parseConfig((Config_stmtContext) child, moduleName);
976 // If 'config' is not specified, the default is the same as the parent
977 // schema node's 'config' value
978 boolean parentConfig = getParentConfig(node);
979 if (config == null) {
980 result = parentConfig;
982 // Check: if a node has 'config' set to 'false', no node underneath
983 // it can have 'config' set to 'true'
984 if (!parentConfig && config) {
985 throw new YangParseException(moduleName, line,
986 "Can not set 'config' to 'true' if parent node has 'config' set to 'false'");
994 private static boolean getParentConfig(final Builder node) {
995 Builder parent = node.getParent();
998 if (parent instanceof ChoiceCaseBuilder) {
999 parent = parent.getParent();
1001 if (parent instanceof DataSchemaNodeBuilder) {
1002 config = ((DataSchemaNodeBuilder) parent).isConfiguration();
1010 * Parse config statement.
1013 * config context to parse
1015 * current module name
1016 * @return true if given context contains string 'true', false otherwise
1018 private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
1019 Boolean result = null;
1021 for (int i = 0; i < ctx.getChildCount(); ++i) {
1022 final ParseTree configContext = ctx.getChild(i);
1023 if (configContext instanceof Config_argContext) {
1024 final String value = stringFromNode(configContext);
1033 throw new YangParseException(moduleName, ctx.getStart().getLine(),
1034 "Failed to parse 'config' statement value: '" + value + "'.");
1043 * Parse type body and create UnknownType definition.
1045 * @param typedefQName
1046 * qname of current type
1050 * actual path in model
1058 * current node parent
1059 * @return UnknownType object with constraints from parsed type body
1061 public static TypeDefinition<?> parseUnknownTypeWithBody(final QName typedefQName,
1062 final Type_body_stmtsContext ctx, final Stack<QName> actualPath, final URI namespace, final Date revision,
1063 final String prefix, final Builder parent) {
1064 String moduleName = parent.getModuleName();
1065 String typeName = typedefQName.getLocalName();
1067 UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
1070 List<RangeConstraint> rangeStatements = getRangeConstraints(ctx, moduleName);
1071 List<LengthConstraint> lengthStatements = getLengthConstraints(ctx, moduleName);
1072 List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
1073 Integer fractionDigits = getFractionDigits(ctx, moduleName);
1075 if (parent instanceof TypeDefinitionBuilder) {
1076 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1077 typedef.setRanges(rangeStatements);
1078 typedef.setLengths(lengthStatements);
1079 typedef.setPatterns(patternStatements);
1080 typedef.setFractionDigits(fractionDigits);
1081 return unknownType.build();
1083 TypeDefinition<?> baseType = unknownType.build();
1084 QName qname = new QName(namespace, revision, prefix, typeName);
1085 SchemaPath schemaPath = createTypePath(actualPath, typeName);
1087 ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, null, null, schemaPath);
1088 typeBuilder.ranges(rangeStatements);
1089 typeBuilder.lengths(lengthStatements);
1090 typeBuilder.patterns(patternStatements);
1091 typeBuilder.fractionDigits(fractionDigits);
1093 return typeBuilder.build();
1097 return unknownType.build();
1101 * Create TypeDefinition object based on given type name and type body.
1108 * current path in schema
1117 * @return TypeDefinition object based on parsed values.
1119 public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1120 final Stack<QName> actualPath, final URI namespace, final Date revision, final String prefix,
1121 final Builder parent) {
1123 final String moduleName = parent.getModuleName();
1124 final int line = typeBody.getStart().getLine();
1125 TypeDefinition<?> baseType = null;
1127 Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1128 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1129 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1130 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1132 TypeConstraints constraints = new TypeConstraints(moduleName, line);
1133 constraints.addFractionDigits(fractionDigits);
1134 constraints.addLengths(lengthStatements);
1135 constraints.addPatterns(patternStatements);
1136 constraints.addRanges(rangeStatements);
1138 SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1139 SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, namespace, revision, prefix, typeName);
1141 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1142 extBaseTypePath = baseTypePath;
1145 if ("decimal64".equals(typeName)) {
1146 if (rangeStatements.isEmpty()) {
1148 return new Decimal64(baseTypePath, fractionDigits);
1149 } catch(Exception e) {
1150 throw new YangParseException(moduleName, line, e.getMessage());
1153 Decimal64 decimalType = new Decimal64(extBaseTypePath, fractionDigits);
1154 constraints.addRanges(decimalType.getRangeConstraints());
1155 baseType = decimalType;
1156 } else if (typeName.startsWith("int")) {
1157 IntegerTypeDefinition intType = null;
1160 intType = Int8.getInstance();
1163 intType = Int16.getInstance();
1166 intType = Int32.getInstance();
1169 intType = Int64.getInstance();
1172 if (intType == null) {
1173 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1175 constraints.addRanges(intType.getRangeConstraints());
1177 } else if (typeName.startsWith("uint")) {
1178 UnsignedIntegerTypeDefinition uintType = null;
1181 uintType = Uint8.getInstance();
1184 uintType = Uint16.getInstance();
1187 uintType = Uint32.getInstance();
1190 uintType = Uint64.getInstance();
1193 if (uintType == null) {
1194 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1196 constraints.addRanges(uintType.getRangeConstraints());
1197 baseType = uintType;
1198 } else if ("enumeration".equals(typeName)) {
1199 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1200 return new EnumerationType(baseTypePath, enumConstants);
1201 } else if ("string".equals(typeName)) {
1202 StringTypeDefinition stringType = StringType.getInstance();
1203 constraints.addLengths(stringType.getLengthConstraints());
1204 baseType = stringType;
1205 } else if ("bits".equals(typeName)) {
1206 return new BitsType(baseTypePath, getBits(typeBody, actualPath, moduleName));
1207 } else if ("leafref".equals(typeName)) {
1208 final String path = parseLeafrefPath(typeBody);
1209 final boolean absolute = path.startsWith("/");
1210 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1211 return new Leafref(xpath);
1212 } else if ("binary".equals(typeName)) {
1213 BinaryTypeDefinition binaryType = BinaryType.getInstance();
1214 constraints.addLengths(binaryType.getLengthConstraints());
1215 baseType = binaryType;
1216 } else if ("instance-identifier".equals(typeName)) {
1217 boolean requireInstance = isRequireInstance(typeBody);
1218 return new InstanceIdentifier(null, requireInstance);
1221 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1222 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1223 typedef.setRanges(constraints.getRange());
1224 typedef.setLengths(constraints.getLength());
1225 typedef.setPatterns(constraints.getPatterns());
1226 typedef.setFractionDigits(constraints.getFractionDigits());
1230 List<QName> path = new ArrayList<>(actualPath);
1231 path.add(new QName(namespace, revision, prefix, typeName));
1232 SchemaPath schemaPath = SchemaPath.create(path, true);
1234 QName qname = schemaPath.getPath().get(schemaPath.getPath().size() - 1);
1235 ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
1237 typeBuilder.ranges(constraints.getRange());
1238 typeBuilder.lengths(constraints.getLength());
1239 typeBuilder.patterns(constraints.getPatterns());
1240 typeBuilder.fractionDigits(constraints.getFractionDigits());
1242 return typeBuilder.build();
1245 private static SchemaPath createTypePath(final Stack<QName> actual, final String typeName) {
1246 QName last = actual.peek();
1247 QName typeQName = new QName(last.getNamespace(), last.getRevision(), last.getPrefix(), typeName);
1248 List<QName> path = new ArrayList<>(actual);
1249 path.add(typeQName);
1250 return SchemaPath.create(path, true);
1253 private static SchemaPath createBaseTypePath(final Stack<QName> actual, final String typeName) {
1254 List<QName> path = new ArrayList<>(actual);
1255 path.add(BaseTypes.constructQName(typeName));
1256 return SchemaPath.create(path, true);
1259 private static SchemaPath createExtendedBaseTypePath(final Stack<QName> actual, final URI namespace, final Date revision,
1260 final String prefix, final String typeName) {
1261 QName extTypeName = new QName(namespace, revision, prefix, typeName);
1262 QName baseTypeName = BaseTypes.constructQName(typeName);
1263 List<QName> path = new ArrayList<>(actual);
1264 path.add(extTypeName);
1265 path.add(baseTypeName);
1266 return SchemaPath.create(path, true);
1270 * Parse given context and find identityref base value.
1274 * @return identityref base value as String
1276 public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
1277 String result = null;
1278 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1279 ParseTree child = ctx.getChild(i);
1280 if (child instanceof Identityref_specificationContext) {
1281 for (int j = 0; j < child.getChildCount(); j++) {
1282 ParseTree baseArg = child.getChild(j);
1283 if (baseArg instanceof Base_stmtContext) {
1284 result = stringFromNode(baseArg);
1294 * Parse type body statement and find require-instance value.
1298 * @return require-instance value
1300 private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
1301 for (int i = 0; i < ctx.getChildCount(); i++) {
1302 ParseTree child = ctx.getChild(i);
1303 if (child instanceof Instance_identifier_specificationContext) {
1304 for (int j = 0; j < child.getChildCount(); j++) {
1305 ParseTree reqStmt = child.getChild(j);
1306 if (reqStmt instanceof Require_instance_stmtContext) {
1307 for (int k = 0; k < reqStmt.getChildCount(); k++) {
1308 ParseTree reqArg = reqStmt.getChild(k);
1309 if (reqArg instanceof Require_instance_argContext) {
1310 return Boolean.valueOf(stringFromNode(reqArg));
1321 * Parse type body statement and find leafref path.
1325 * @return leafref path as String
1327 private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
1328 for (int i = 0; i < ctx.getChildCount(); i++) {
1329 ParseTree child = ctx.getChild(i);
1330 if (child instanceof Leafref_specificationContext) {
1331 for (int j = 0; j < child.getChildCount(); j++) {
1332 ParseTree leafRefSpec = child.getChild(j);
1333 if (leafRefSpec instanceof Path_stmtContext) {
1334 return stringFromNode(leafRefSpec);
1343 * Internal helper method for parsing must statement.
1347 * @return MustDefinition object based on parsed context
1349 private static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1350 StringBuilder mustText = new StringBuilder();
1351 String description = null;
1352 String reference = null;
1353 String errorAppTag = null;
1354 String errorMessage = null;
1355 for (int i = 0; i < ctx.getChildCount(); ++i) {
1356 ParseTree child = ctx.getChild(i);
1357 if (child instanceof StringContext) {
1358 final StringContext context = (StringContext) child;
1359 if (context.getChildCount() == 1) {
1360 String mustPart = context.getChild(0).getText();
1361 // trim start and end quotation
1362 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1364 for (int j = 0; j < context.getChildCount(); j++) {
1365 String mustPart = context.getChild(j).getText();
1367 mustText.append(mustPart.substring(0, mustPart.length() - 1));
1371 mustText.append(mustPart.substring(1));
1375 } else if (child instanceof Description_stmtContext) {
1376 description = stringFromNode(child);
1377 } else if (child instanceof Reference_stmtContext) {
1378 reference = stringFromNode(child);
1379 } else if (child instanceof Error_app_tag_stmtContext) {
1380 errorAppTag = stringFromNode(child);
1381 } else if (child instanceof Error_message_stmtContext) {
1382 errorMessage = stringFromNode(child);
1386 return new MustDefinitionImpl(mustText.toString(), description, reference, errorAppTag, errorMessage);
1390 * Parse given context and set constraints to constraints builder.
1394 * @param constraints
1395 * ConstraintsBuilder to fill
1397 public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1398 for (int i = 0; i < ctx.getChildCount(); ++i) {
1399 final ParseTree childNode = ctx.getChild(i);
1400 if (childNode instanceof Max_elements_stmtContext) {
1401 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1402 constraints.setMaxElements(max);
1403 } else if (childNode instanceof Min_elements_stmtContext) {
1404 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1405 constraints.setMinElements(min);
1406 } else if (childNode instanceof Must_stmtContext) {
1407 MustDefinition must = parseMust((Must_stmtContext) childNode);
1408 constraints.addMustDefinition(must);
1409 } else if (childNode instanceof Mandatory_stmtContext) {
1410 for (int j = 0; j < childNode.getChildCount(); j++) {
1411 ParseTree mandatoryTree = childNode.getChild(j);
1412 if (mandatoryTree instanceof Mandatory_argContext) {
1413 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1414 constraints.setMandatory(mandatory);
1417 } else if (childNode instanceof When_stmtContext) {
1418 constraints.addWhenCondition(stringFromNode(childNode));
1423 private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1424 Integer result = null;
1426 for (int i = 0; i < ctx.getChildCount(); i++) {
1427 ParseTree minArg = ctx.getChild(i);
1428 if (minArg instanceof Min_value_argContext) {
1429 result = Integer.valueOf(stringFromNode(minArg));
1432 if (result == null) {
1433 throw new IllegalArgumentException();
1436 } catch (Exception e) {
1437 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1441 private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1442 Integer result = null;
1444 for (int i = 0; i < ctx.getChildCount(); i++) {
1445 ParseTree maxArg = ctx.getChild(i);
1446 if (maxArg instanceof Max_value_argContext) {
1447 result = Integer.valueOf(stringFromNode(maxArg));
1450 if (result == null) {
1451 throw new IllegalArgumentException();
1454 } catch (Exception e) {
1455 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1460 * Parse given context and return yin value.
1464 * @return true if value is 'true', false otherwise
1466 public static boolean parseYinValue(final Argument_stmtContext ctx) {
1467 boolean yinValue = false;
1468 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1469 ParseTree yin = ctx.getChild(i);
1470 if (yin instanceof Yin_element_stmtContext) {
1471 for (int j = 0; j < yin.getChildCount(); j++) {
1472 ParseTree yinArg = yin.getChild(j);
1473 if (yinArg instanceof Yin_element_argContext) {
1474 String yinString = stringFromNode(yinArg);
1475 if ("true".equals(yinString)) {
1487 * Check this base type.
1490 * base YANG type name
1492 * name of current module
1495 * @throws YangParseException
1496 * if this is one of YANG type which MUST contain additional
1497 * informations in its body
1499 public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1502 throw new YangParseException(moduleName, line,
1503 "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1505 throw new YangParseException(moduleName, line,
1506 "The 'base' statement MUST be present if the type is 'identityref'.");
1508 throw new YangParseException(moduleName, line,
1509 "The 'path' statement MUST be present if the type is 'leafref'.");
1511 throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1513 throw new YangParseException(moduleName, line,
1514 "The 'enum' statement MUST be present if the type is 'enumeration'.");
1519 * Parse refine statement.
1524 * name of current module
1525 * @return RefineHolder object representing this refine statement
1527 public static RefineHolderImpl parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
1528 final String refineTarget = stringFromNode(refineCtx);
1529 final RefineHolderImpl refine = new RefineHolderImpl(moduleName, refineCtx.getStart().getLine(), refineTarget);
1530 for (int i = 0; i < refineCtx.getChildCount(); i++) {
1531 ParseTree refinePom = refineCtx.getChild(i);
1532 if (refinePom instanceof Refine_pomContext) {
1533 for (int j = 0; j < refinePom.getChildCount(); j++) {
1534 ParseTree refineStmt = refinePom.getChild(j);
1535 parseRefineDefault(refine, refineStmt);
1537 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1538 parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1539 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1540 parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1541 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1542 parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1543 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1544 parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1545 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1546 parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1547 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1548 parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1556 private static void parseRefineDefault(final RefineHolderImpl refine, final ParseTree refineStmt) {
1557 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1558 ParseTree refineArg = refineStmt.getChild(i);
1559 if (refineArg instanceof Description_stmtContext) {
1560 String description = stringFromNode(refineArg);
1561 refine.setDescription(description);
1562 } else if (refineArg instanceof Reference_stmtContext) {
1563 String reference = stringFromNode(refineArg);
1564 refine.setReference(reference);
1565 } else if (refineArg instanceof Config_stmtContext) {
1566 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1567 refine.setConfiguration(config);
1572 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_stmtsContext refineStmt) {
1573 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1574 ParseTree refineArg = refineStmt.getChild(i);
1575 if (refineArg instanceof Default_stmtContext) {
1576 String defaultStr = stringFromNode(refineArg);
1577 refine.setDefaultStr(defaultStr);
1578 } else if (refineArg instanceof Mandatory_stmtContext) {
1579 for (int j = 0; j < refineArg.getChildCount(); j++) {
1580 ParseTree mandatoryTree = refineArg.getChild(j);
1581 if (mandatoryTree instanceof Mandatory_argContext) {
1582 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1583 refine.setMandatory(mandatory);
1586 } else if (refineArg instanceof Must_stmtContext) {
1587 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1588 refine.setMust(must);
1595 private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_container_stmtsContext refineStmt) {
1596 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1597 ParseTree refineArg = refineStmt.getChild(i);
1598 if (refineArg instanceof Must_stmtContext) {
1599 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1600 refine.setMust(must);
1601 } else if (refineArg instanceof Presence_stmtContext) {
1602 refine.setPresence(true);
1608 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_list_stmtsContext refineStmt) {
1609 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1610 ParseTree refineArg = refineStmt.getChild(i);
1611 if (refineArg instanceof Must_stmtContext) {
1612 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1613 refine.setMust(must);
1614 } else if (refineArg instanceof Max_elements_stmtContext) {
1615 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1616 refine.setMaxElements(max);
1617 } else if (refineArg instanceof Min_elements_stmtContext) {
1618 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1619 refine.setMinElements(min);
1625 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_list_stmtsContext refineStmt) {
1626 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1627 ParseTree refineArg = refineStmt.getChild(i);
1628 if (refineArg instanceof Must_stmtContext) {
1629 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1630 refine.setMust(must);
1631 } else if (refineArg instanceof Max_elements_stmtContext) {
1632 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1633 refine.setMaxElements(max);
1634 } else if (refineArg instanceof Min_elements_stmtContext) {
1635 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1636 refine.setMinElements(min);
1642 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_choice_stmtsContext refineStmt) {
1643 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1644 ParseTree refineArg = refineStmt.getChild(i);
1645 if (refineArg instanceof Default_stmtContext) {
1646 String defaultStr = stringFromNode(refineArg);
1647 refine.setDefaultStr(defaultStr);
1648 } else if (refineArg instanceof Mandatory_stmtContext) {
1649 for (int j = 0; j < refineArg.getChildCount(); j++) {
1650 ParseTree mandatoryTree = refineArg.getChild(j);
1651 if (mandatoryTree instanceof Mandatory_argContext) {
1652 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1653 refine.setMandatory(mandatory);
1661 private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_anyxml_stmtsContext refineStmt) {
1662 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1663 ParseTree refineArg = refineStmt.getChild(i);
1664 if (refineArg instanceof Must_stmtContext) {
1665 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1666 refine.setMust(must);
1667 } else if (refineArg instanceof Mandatory_stmtContext) {
1668 for (int j = 0; j < refineArg.getChildCount(); j++) {
1669 ParseTree mandatoryTree = refineArg.getChild(j);
1670 if (mandatoryTree instanceof Mandatory_argContext) {
1671 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1672 refine.setMandatory(mandatory);
1680 public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
1681 List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1682 checkState(!potentialValues.isEmpty());
1683 return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1686 public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
1687 List<T> potential = context.getRuleContexts(contextType);
1688 if(potential.isEmpty()) {
1689 return Optional.absent();
1691 return Optional.of(potential.get(0));