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.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.Lists;
16 import java.math.BigDecimal;
17 import java.math.BigInteger;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.regex.Pattern;
23 import java.util.regex.PatternSyntaxException;
24 import org.antlr.v4.runtime.ParserRuleContext;
25 import org.antlr.v4.runtime.tree.ParseTree;
26 import org.antlr.v4.runtime.tree.TerminalNode;
27 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
28 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
29 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
30 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bit_stmtContext;
31 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bits_specificationContext;
32 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_argContext;
33 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_stmtContext;
34 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Decimal64_specificationContext;
35 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Default_stmtContext;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Description_stmtContext;
37 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_specificationContext;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_stmtContext;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_app_tag_stmtContext;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_message_stmtContext;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Fraction_digits_stmtContext;
42 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Identityref_specificationContext;
43 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Instance_identifier_specificationContext;
44 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Key_stmtContext;
45 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Leafref_specificationContext;
46 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Length_stmtContext;
47 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_argContext;
48 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_stmtContext;
49 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_elements_stmtContext;
50 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_value_argContext;
51 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_elements_stmtContext;
52 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_value_argContext;
53 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
54 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Must_stmtContext;
55 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Numerical_restrictionsContext;
56 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_argContext;
57 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
58 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Path_stmtContext;
59 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Pattern_stmtContext;
60 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Position_stmtContext;
61 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Presence_stmtContext;
62 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Range_stmtContext;
63 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Reference_stmtContext;
64 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_anyxml_stmtsContext;
65 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_choice_stmtsContext;
66 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_container_stmtsContext;
67 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_list_stmtsContext;
68 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_stmtsContext;
69 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_list_stmtsContext;
70 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_pomContext;
71 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_stmtContext;
72 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_argContext;
73 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_stmtContext;
74 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_argContext;
75 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_stmtContext;
76 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.StringContext;
77 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.String_restrictionsContext;
78 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
79 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
80 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Value_stmtContext;
81 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
82 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_argContext;
83 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
84 import org.opendaylight.yangtools.yang.common.QName;
85 import org.opendaylight.yangtools.yang.model.api.MustDefinition;
86 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
87 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
88 import org.opendaylight.yangtools.yang.model.api.Status;
89 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
90 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
92 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
93 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
94 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
96 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
98 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
99 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
100 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
103 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
104 import org.opendaylight.yangtools.yang.model.util.BinaryType;
105 import org.opendaylight.yangtools.yang.model.util.BitImpl;
106 import org.opendaylight.yangtools.yang.model.util.BitsType;
107 import org.opendaylight.yangtools.yang.model.util.Decimal64;
108 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
109 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
110 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
111 import org.opendaylight.yangtools.yang.model.util.Int16;
112 import org.opendaylight.yangtools.yang.model.util.Int32;
113 import org.opendaylight.yangtools.yang.model.util.Int64;
114 import org.opendaylight.yangtools.yang.model.util.Int8;
115 import org.opendaylight.yangtools.yang.model.util.Leafref;
116 import org.opendaylight.yangtools.yang.model.util.MustDefinitionImpl;
117 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
118 import org.opendaylight.yangtools.yang.model.util.StringType;
119 import org.opendaylight.yangtools.yang.model.util.Uint16;
120 import org.opendaylight.yangtools.yang.model.util.Uint32;
121 import org.opendaylight.yangtools.yang.model.util.Uint64;
122 import org.opendaylight.yangtools.yang.model.util.Uint8;
123 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
124 import org.opendaylight.yangtools.yang.parser.builder.api.ConstraintsBuilder;
125 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
126 import org.opendaylight.yangtools.yang.parser.builder.api.RefineBuilder;
127 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
128 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
129 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
130 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
131 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
132 import org.opendaylight.yangtools.yang.parser.builder.impl.RefineHolderImpl;
133 import org.opendaylight.yangtools.yang.parser.builder.impl.TypeDefinitionBuilderImpl;
134 import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
135 import org.opendaylight.yangtools.yang.parser.util.TypeConstraints;
136 import org.opendaylight.yangtools.yang.parser.util.UnknownBoundaryNumber;
137 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
138 import org.slf4j.Logger;
139 import org.slf4j.LoggerFactory;
141 public final class ParserListenerUtils {
142 private static final Logger LOG = LoggerFactory.getLogger(ParserListenerUtils.class);
143 private static final Splitter KEYDEF_SPLITTER = Splitter.on(' ').omitEmptyStrings();
144 private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults();
145 private static final Splitter DOT_DOT_SPLITTER = Splitter.on("..").trimResults();
146 private static final CharMatcher DOUBLE_QUOTE_MATCHER = CharMatcher.is('"');
147 private static final CharMatcher SINGLE_QUOTE_MATCHER = CharMatcher.is('\'');
149 private ParserListenerUtils() {
153 * Parse given tree and get first string value.
157 * @return first string value from given tree
159 public static String stringFromNode(final ParseTree treeNode) {
161 for (int i = 0; i < treeNode.getChildCount(); ++i) {
162 final ParseTree child = treeNode.getChild(i);
163 if (child instanceof StringContext) {
164 return stringFromStringContext((StringContext)child);
170 private static String stringFromStringContext(final StringContext context) {
171 StringBuilder sb = new StringBuilder();
172 for (TerminalNode stringNode : context.STRING()) {
173 final String str = stringNode.getText();
174 char firstChar = str.charAt(0);
175 final CharMatcher quoteMatcher;
176 if(SINGLE_QUOTE_MATCHER.matches(firstChar)) {
177 quoteMatcher = SINGLE_QUOTE_MATCHER;
178 } else if (DOUBLE_QUOTE_MATCHER.matches(firstChar)) {
179 quoteMatcher = DOUBLE_QUOTE_MATCHER;
186 * It is safe not to check last argument to be same
187 * grammars enforces that.
189 * FIXME: Introduce proper escaping and translation of escaped
193 sb.append(quoteMatcher.removeFrom(str.substring(1, str.length()-1)));
195 return sb.toString();
198 private static String getParentModule(final ParseTree ctx) {
199 ParseTree current = ctx;
200 while (current != null && !(current instanceof Module_stmtContext)) {
201 current = current.getParent();
203 if (current != null) {
204 Module_stmtContext module = (Module_stmtContext) current;
205 for (int i = 0; i < module.getChildCount(); i++) {
206 if (module.getChild(i) instanceof StringContext) {
207 final StringContext str = (StringContext) module.getChild(i);
208 return str.getChild(0).getText();
216 * Parse 'description', 'reference' and 'status' statements and fill in
222 * builder to fill in with parsed statements
224 public static void parseSchemaNodeArgs(final ParseTree ctx, final SchemaNodeBuilder builder) {
225 for (int i = 0; i < ctx.getChildCount(); i++) {
226 final ParseTree child = ctx.getChild(i);
227 if (child instanceof Description_stmtContext) {
228 final String desc = stringFromNode(child);
229 builder.setDescription(desc);
230 } else if (child instanceof Reference_stmtContext) {
231 final String ref = stringFromNode(child);
232 builder.setReference(ref);
233 } else if (child instanceof Status_stmtContext) {
234 final Status status = parseStatus((Status_stmtContext) child);
235 builder.setStatus(status);
241 * Parse given context and return its value;
245 * @return value parsed from context
247 public static Status parseStatus(final Status_stmtContext ctx) {
248 Status result = null;
249 for (int i = 0; i < ctx.getChildCount(); i++) {
250 ParseTree statusArg = ctx.getChild(i);
251 if (statusArg instanceof Status_argContext) {
252 String statusArgStr = stringFromNode(statusArg);
253 switch (statusArgStr) {
255 result = Status.CURRENT;
258 result = Status.DEPRECATED;
261 result = Status.OBSOLETE;
264 LOG.warn("Invalid 'status' statement: " + statusArgStr);
272 * Parse given tree and returns units statement as string.
276 * @return value of units statement as string or null if there is no units
279 public static String parseUnits(final ParseTree ctx) {
280 for (int i = 0; i < ctx.getChildCount(); i++) {
281 ParseTree child = ctx.getChild(i);
282 if (child instanceof Units_stmtContext) {
283 return stringFromNode(child);
290 * Parse given tree and returns default statement as string.
294 * @return value of default statement as string or null if there is no
297 public static String parseDefault(final ParseTree ctx) {
298 for (int i = 0; i < ctx.getChildCount(); i++) {
299 ParseTree child = ctx.getChild(i);
300 if (child instanceof Default_stmtContext) {
301 return stringFromNode(child);
308 * Create java.util.List of key node names.
311 * Key_stmtContext context
312 * @return YANG list key as java.util.List of key node names
314 public static List<String> createListKey(final Key_stmtContext ctx) {
315 String keyDefinition = stringFromNode(ctx);
316 return Lists.newArrayList(KEYDEF_SPLITTER.split(keyDefinition));
320 * Parse given type body of enumeration statement.
323 * type body context to parse
325 * actual position in YANG model
327 * current module name
328 * @return List of EnumPair object parsed from given context
330 private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
331 final SchemaPath path, final String moduleName) {
332 List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<>();
334 for (int i = 0; i < ctx.getChildCount(); i++) {
335 ParseTree enumSpecChild = ctx.getChild(i);
336 if (enumSpecChild instanceof Enum_specificationContext) {
337 int highestValue = -1;
338 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
339 ParseTree enumChild = enumSpecChild.getChild(j);
340 if (enumChild instanceof Enum_stmtContext) {
341 EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName);
342 if (enumPair.getValue() > highestValue) {
343 highestValue = enumPair.getValue();
345 enumConstants.add(enumPair);
350 return enumConstants;
354 * Parse enum statement context
357 * enum statement context
358 * @param highestValue
359 * current highest value in enumeration
361 * actual position in YANG model
363 * current module name
364 * @return EnumPair object parsed from given context
366 private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
367 final SchemaPath actualPath, final String moduleName) {
368 final String name = stringFromNode(ctx);
369 SchemaPath path = createTypePath(actualPath, name);
370 Integer value = null;
372 String description = null;
373 String reference = null;
374 Status status = null;
376 for (int i = 0; i < ctx.getChildCount(); i++) {
377 ParseTree child = ctx.getChild(i);
378 if (child instanceof Value_stmtContext) {
379 String valueStr = stringFromNode(child);
381 // yang enum value has same restrictions as JAVA Integer
382 value = Integer.valueOf(valueStr);
383 } catch (NumberFormatException e) {
385 .format("Error on enum '%s': the enum value MUST be in the range from -2147483648 to 2147483647, but was: %s",
387 throw new YangParseException(moduleName, ctx.getStart().getLine(), err, e);
389 } else if (child instanceof Description_stmtContext) {
390 description = stringFromNode(child);
391 } else if (child instanceof Reference_stmtContext) {
392 reference = stringFromNode(child);
393 } else if (child instanceof Status_stmtContext) {
394 status = parseStatus((Status_stmtContext) child);
399 value = highestValue + 1;
402 EnumPairImpl result = new EnumPairImpl();
403 result.qname = path.getPathTowardsRoot().iterator().next();
405 result.description = description;
406 result.reference = reference;
407 result.status = status;
409 result.value = value;
414 * Internal implementation of EnumPair.
416 private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
418 private SchemaPath path;
419 private String description;
420 private String reference;
421 private Status status;
422 private final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
424 private Integer value;
427 public QName getQName() {
432 public SchemaPath getPath() {
437 public String getDescription() {
442 public String getReference() {
447 public Status getStatus() {
452 public List<UnknownSchemaNode> getUnknownSchemaNodes() {
457 public String getName() {
462 public Integer getValue() {
467 public int hashCode() {
468 final int prime = 31;
470 result = prime * result + ((qname == null) ? 0 : qname.hashCode());
471 result = prime * result + ((path == null) ? 0 : path.hashCode());
472 result = prime * result + ((unknownNodes == null) ? 0 : unknownNodes.hashCode());
473 result = prime * result + ((name == null) ? 0 : name.hashCode());
474 result = prime * result + ((value == null) ? 0 : value.hashCode());
479 public boolean equals(final Object obj) {
486 if (getClass() != obj.getClass()) {
489 EnumPairImpl other = (EnumPairImpl) obj;
491 if (other.qname != null) {
494 } else if (!qname.equals(other.qname)) {
498 if (other.path != null) {
501 } else if (!path.equals(other.path)) {
504 if (unknownNodes == null) {
505 if (other.unknownNodes != null) {
508 } else if (!unknownNodes.equals(other.unknownNodes)) {
512 if (other.name != null) {
515 } else if (!name.equals(other.name)) {
519 if (other.value != null) {
522 } else if (!value.equals(other.value)) {
529 public String toString() {
530 return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
535 * Get and parse range from given type body context.
538 * type body context to parse
540 * name of current module
541 * @return List of RangeConstraint created from this context
543 private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
544 for (int i = 0; i < ctx.getChildCount(); i++) {
545 ParseTree numRestrChild = ctx.getChild(i);
547 if (numRestrChild instanceof Numerical_restrictionsContext) {
548 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
549 ParseTree rangeChild = numRestrChild.getChild(j);
550 if (rangeChild instanceof Range_stmtContext) {
551 return 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 return parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
570 return Collections.emptyList();
574 * Parse given range context.
577 * range context to parse
579 * name of current module
580 * @return List of RangeConstraints parsed from this context
582 private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx, final String moduleName) {
583 final int line = ctx.getStart().getLine();
584 Optional<String> description = Optional.absent();
585 Optional<String> reference = Optional.absent();
587 for (int i = 0; i < ctx.getChildCount(); i++) {
588 ParseTree child = ctx.getChild(i);
589 if (child instanceof Description_stmtContext) {
590 description = Optional.fromNullable(stringFromNode(child));
591 } else if (child instanceof Reference_stmtContext) {
592 reference = Optional.fromNullable(stringFromNode(child));
596 List<RangeConstraint> rangeConstraints = new ArrayList<>();
597 for (String def : PIPE_SPLITTER.split(stringFromNode(ctx))) {
598 final Iterator<String> split = DOT_DOT_SPLITTER.split(def).iterator();
599 final Number min = parseNumberConstraintValue(split.next(), moduleName, line);
602 if (split.hasNext()) {
603 max = parseNumberConstraintValue(split.next(), moduleName, line);
604 if (split.hasNext()) {
605 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Malformed length constraint \"" + def + "\".");
611 RangeConstraint range = BaseConstraints.newRangeConstraint(min, max, description, reference);
612 rangeConstraints.add(range);
615 return rangeConstraints;
619 * Get and parse length from given type body context.
622 * type body context to parse
624 * name of current module
625 * @return List of LengthConstraint created from this context
627 private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
628 for (int i = 0; i < ctx.getChildCount(); i++) {
629 ParseTree stringRestrChild = ctx.getChild(i);
630 if (stringRestrChild instanceof String_restrictionsContext) {
631 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
632 ParseTree lengthChild = stringRestrChild.getChild(j);
633 if (lengthChild instanceof Length_stmtContext) {
634 return parseLengthConstraints((Length_stmtContext) lengthChild, moduleName);
639 return Collections.emptyList();
643 * Parse given length context.
646 * length context to parse
648 * name of current module
649 * @return List of LengthConstraints parsed from this context
651 private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx, final String moduleName) {
652 final int line = ctx.getStart().getLine();
653 Optional<String> description = Optional.absent();
654 Optional<String> reference = Optional.absent();
656 for (int i = 0; i < ctx.getChildCount(); i++) {
657 ParseTree child = ctx.getChild(i);
658 if (child instanceof Description_stmtContext) {
659 description = Optional.fromNullable(stringFromNode(child));
660 } else if (child instanceof Reference_stmtContext) {
661 reference = Optional.fromNullable(stringFromNode(child));
665 List<LengthConstraint> lengthConstraints = new ArrayList<>();
666 for (String def : PIPE_SPLITTER.split(stringFromNode(ctx))) {
667 final Iterator<String> split = DOT_DOT_SPLITTER.split(def).iterator();
668 final Number min = parseNumberConstraintValue(split.next(), moduleName, line);
671 if (split.hasNext()) {
672 max = parseNumberConstraintValue(split.next(), moduleName, line);
673 if (split.hasNext()) {
674 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Malformed length constraint \"" + def + "\".");
680 LengthConstraint range = BaseConstraints.newLengthConstraint(min, max, description, reference);
681 lengthConstraints.add(range);
684 return lengthConstraints;
691 * name of current module
693 * current line in module
694 * @return wrapper object of primitive java type or UnknownBoundaryNumber if
695 * type is one of special YANG values 'min' or 'max'
697 private static Number parseNumberConstraintValue(final String value, final String moduleName, final int line) {
699 if ("min".equals(value) || "max".equals(value)) {
700 result = new UnknownBoundaryNumber(value);
703 if (value.indexOf('.') != -1) {
704 result = new BigDecimal(value);
706 result = new BigInteger(value);
708 } catch (NumberFormatException e) {
709 throw new YangParseException(moduleName, line, "Unable to parse range value '" + value + "'.", e);
716 * Parse type body and return pattern constraints.
720 * @return list of pattern constraints
722 private static List<PatternConstraint> getPatternConstraint(final Type_body_stmtsContext ctx, final String moduleName) {
723 List<PatternConstraint> patterns = new ArrayList<>();
725 for (int i = 0; i < ctx.getChildCount(); i++) {
726 ParseTree stringRestrChild = ctx.getChild(i);
727 if (stringRestrChild instanceof String_restrictionsContext) {
728 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
729 ParseTree lengthChild = stringRestrChild.getChild(j);
730 if (lengthChild instanceof Pattern_stmtContext) {
731 final PatternConstraint constraint = parsePatternConstraint((Pattern_stmtContext) lengthChild,
733 if (constraint != null) {
734 patterns.add(constraint);
744 * Internal helper method.
748 * @return PatternConstraint object
750 private static PatternConstraint parsePatternConstraint(final Pattern_stmtContext ctx, final String moduleName) {
751 Optional<String> description = Optional.absent();
752 Optional<String> reference = Optional.absent();
753 for (int i = 0; i < ctx.getChildCount(); i++) {
754 ParseTree child = ctx.getChild(i);
755 if (child instanceof Description_stmtContext) {
756 description = Optional.of(stringFromNode(child));
757 } else if (child instanceof Reference_stmtContext) {
758 reference = Optional.of(stringFromNode(child));
761 final String rawPattern = parsePatternString(ctx);
762 final String pattern = wrapPattern(rawPattern);
763 if (isValidPattern(pattern, ctx, moduleName)) {
764 return BaseConstraints.newPatternConstraint(pattern, description, reference);
769 private static String wrapPattern(String rawPattern) {
770 final StringBuilder wrapPatternBuilder = new StringBuilder(rawPattern.length() + 2);
771 wrapPatternBuilder.append('^');
772 wrapPatternBuilder.append(rawPattern);
773 wrapPatternBuilder.append('$');
774 return wrapPatternBuilder.toString();
777 private static boolean isValidPattern(final String pattern, final Pattern_stmtContext ctx, final String moduleName) {
779 Pattern.compile(pattern);
781 } catch (PatternSyntaxException ex) {
782 LOG.warn("Unable to compile pattern defined in module {} at line {}. Error message: {}",
783 moduleName, ctx.getStart().getLine(), ex.getMessage());
789 * Parse given context and return pattern value.
793 * @return pattern value as String
795 private static String parsePatternString(final Pattern_stmtContext ctx) {
796 StringBuilder result = new StringBuilder();
797 for (int i = 0; i < ctx.getChildCount(); ++i) {
798 ParseTree child = ctx.getChild(i);
799 if (child instanceof StringContext) {
800 for (int j = 0; j < child.getChildCount(); j++) {
802 String patternToken = child.getChild(j).getText();
803 result.append(patternToken.substring(1, patternToken.length() - 1));
808 return result.toString();
812 * Get fraction digits value from type body.
815 * type body context to parse
817 * name of current module
818 * @return 'fraction-digits' value if present in given context, null
821 private static Integer getFractionDigits(final Type_body_stmtsContext ctx, final String moduleName) {
822 Integer result = null;
823 for (int i = 0; i < ctx.getChildCount(); i++) {
824 ParseTree dec64specChild = ctx.getChild(i);
825 if (dec64specChild instanceof Decimal64_specificationContext) {
826 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild, moduleName);
833 * Parse decimal64 fraction-digits value.
838 * name of current module
839 * @return fraction-digits value as Integer
841 private static Integer parseFractionDigits(final Decimal64_specificationContext ctx, final String moduleName) {
842 Integer result = null;
843 for (int i = 0; i < ctx.getChildCount(); i++) {
844 ParseTree fdChild = ctx.getChild(i);
845 if (fdChild instanceof Fraction_digits_stmtContext) {
846 String value = stringFromNode(fdChild);
848 result = Integer.valueOf(value);
849 } catch (NumberFormatException e) {
850 throw new YangParseException(moduleName, ctx.getStart().getLine(),
851 "Unable to parse fraction digits value '" + value + "'.", e);
859 * Internal helper method for parsing bit statements from given type body
863 * type body context to parse
865 * current position in YANG model
867 * current module name
868 * @return List of Bit objects created from this context
870 private static List<BitsTypeDefinition.Bit> getBits(final Type_body_stmtsContext ctx, final SchemaPath actualPath,
871 final String moduleName) {
872 final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
873 for (int j = 0; j < ctx.getChildCount(); j++) {
874 ParseTree bitsSpecChild = ctx.getChild(j);
875 if (bitsSpecChild instanceof Bits_specificationContext) {
876 long highestPosition = -1;
877 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
878 ParseTree bitChild = bitsSpecChild.getChild(k);
879 if (bitChild instanceof Bit_stmtContext) {
880 Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, moduleName);
881 if (bit.getPosition() > highestPosition) {
882 highestPosition = bit.getPosition();
893 * Internal helper method for parsing bit context.
896 * bit statement context to parse
897 * @param highestPosition
898 * current highest position in bits type
900 * current position in YANG model
902 * current module name
903 * @return Bit object parsed from this context
905 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, final long highestPosition,
906 final SchemaPath actualPath, final String moduleName) {
907 String name = stringFromNode(ctx);
908 Long position = null;
910 String description = null;
911 String reference = null;
912 Status status = Status.CURRENT;
914 SchemaPath schemaPath = createBaseTypePath(actualPath, name);
916 for (int i = 0; i < ctx.getChildCount(); i++) {
917 ParseTree child = ctx.getChild(i);
918 if (child instanceof Position_stmtContext) {
919 String positionStr = stringFromNode(child);
920 position = Long.valueOf(positionStr);
921 } else if (child instanceof Description_stmtContext) {
922 description = stringFromNode(child);
923 } else if (child instanceof Reference_stmtContext) {
924 reference = stringFromNode(child);
925 } else if (child instanceof Status_stmtContext) {
926 status = parseStatus((Status_stmtContext) child);
930 if (position == null) {
931 position = highestPosition + 1;
933 if (position < 0 || position > 4294967295L) {
934 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on bit '" + name
935 + "': the position value MUST be in the range 0 to 4294967295");
938 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
939 return new BitImpl(position, schemaPath.getPathTowardsRoot().iterator().next(), schemaPath,
940 description, reference, status, unknownNodes);
944 * Parse 'ordered-by' statement.
946 * The 'ordered-by' statement defines whether the order of entries within a
947 * list are determined by the user or the system. The argument is one of the
948 * strings "system" or "user". If not present, order defaults to "system".
951 * Ordered_by_stmtContext
952 * @return true, if ordered-by contains value 'user', false otherwise
954 public static boolean parseUserOrdered(final Ordered_by_stmtContext ctx) {
955 boolean result = false;
956 for (int j = 0; j < ctx.getChildCount(); j++) {
957 ParseTree orderArg = ctx.getChild(j);
958 if (orderArg instanceof Ordered_by_argContext) {
959 String orderStr = stringFromNode(orderArg);
968 LOG.warn("Invalid 'ordered-by' statement.");
976 * Get config statement from given context. If there is no config statement,
977 * return config value of parent
984 * name of current module
986 * line in current module
987 * @return config statement parsed from given context
989 public static boolean getConfig(final ParseTree ctx, final Builder node, final String moduleName, final int line) {
991 // parse configuration statement
992 Boolean config = null;
993 for (int i = 0; i < ctx.getChildCount(); i++) {
994 ParseTree child = ctx.getChild(i);
995 if (child instanceof Config_stmtContext) {
996 config = parseConfig((Config_stmtContext) child, moduleName);
1001 // If 'config' is not specified, the default is the same as the parent
1002 // schema node's 'config' value
1003 boolean parentConfig = getParentConfig(node);
1004 if (config == null) {
1005 result = parentConfig;
1007 // Check: if a node has 'config' set to 'false', no node underneath
1008 // it can have 'config' set to 'true'
1009 if (!parentConfig && config) {
1010 throw new YangParseException(moduleName, line,
1011 "Can not set 'config' to 'true' if parent node has 'config' set to 'false'");
1019 private static boolean getParentConfig(final Builder node) {
1020 Builder parent = node.getParent();
1023 if (parent instanceof ChoiceCaseBuilder) {
1024 parent = parent.getParent();
1026 if (parent instanceof DataSchemaNodeBuilder) {
1027 config = ((DataSchemaNodeBuilder) parent).isConfiguration();
1035 * Parse config statement.
1038 * config context to parse
1040 * current module name
1041 * @return true if given context contains string 'true', false otherwise
1043 private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
1044 Boolean result = null;
1046 for (int i = 0; i < ctx.getChildCount(); ++i) {
1047 final ParseTree configContext = ctx.getChild(i);
1048 if (configContext instanceof Config_argContext) {
1049 final String value = stringFromNode(configContext);
1058 throw new YangParseException(moduleName, ctx.getStart().getLine(),
1059 "Failed to parse 'config' statement value: '" + value + "'.");
1068 * Parse unknown type with body.
1073 * current node parent
1074 * @param prefixedQName
1075 * type qname with prefix
1076 * @param moduleBuilder
1077 * current module builder
1078 * @param moduleQName
1079 * current module qname
1081 * actual path in model
1083 public static void parseUnknownTypeWithBody(Type_body_stmtsContext typeBody, TypeAwareBuilder parent,
1084 QName prefixedQName, ModuleBuilder moduleBuilder, QName moduleQName, SchemaPath actualPath) {
1085 final int line = typeBody.getStart().getLine();
1087 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleBuilder.getName());
1088 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleBuilder.getName());
1089 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody, moduleBuilder.getName());
1090 Integer fractionDigits = getFractionDigits(typeBody, moduleBuilder.getName());
1092 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1093 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1094 typedef.setRanges(rangeStatements);
1095 typedef.setLengths(lengthStatements);
1096 typedef.setPatterns(patternStatements);
1097 typedef.setFractionDigits(fractionDigits);
1098 typedef.setTypeQName(prefixedQName);
1099 // add parent node of this type statement to dirty nodes
1100 moduleBuilder.markActualNodeDirty();
1102 QName qname = QName.create(moduleQName, prefixedQName.getLocalName());
1103 SchemaPath schemaPath = createTypePath(actualPath, prefixedQName.getLocalName());
1104 TypeDefinitionBuilder typeBuilder = new TypeDefinitionBuilderImpl(moduleBuilder.getName(), line, qname, schemaPath);
1105 typeBuilder.setRanges(rangeStatements);
1106 typeBuilder.setLengths(lengthStatements);
1107 typeBuilder.setPatterns(patternStatements);
1108 typeBuilder.setFractionDigits(fractionDigits);
1109 typeBuilder.setTypeQName(prefixedQName);
1110 parent.setTypedef(typeBuilder);
1111 moduleBuilder.getDirtyNodes().add(typeBuilder);
1116 * Create TypeDefinition object based on given type name and type body.
1123 * current path in schema
1124 * @param moduleQName
1125 * current module qname
1128 * @return TypeDefinition object based on parsed values.
1130 public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1131 final SchemaPath actualPath, final QName moduleQName, final Builder parent) {
1133 final String moduleName = parent.getModuleName();
1134 final int line = typeBody.getStart().getLine();
1135 TypeDefinition<?> baseType = null;
1137 Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1138 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1139 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody, moduleName);
1140 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1142 TypeConstraints constraints = new TypeConstraints(moduleName, line);
1143 constraints.addFractionDigits(fractionDigits);
1144 constraints.addLengths(lengthStatements);
1145 constraints.addPatterns(patternStatements);
1146 constraints.addRanges(rangeStatements);
1148 SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1149 SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, moduleQName, typeName);
1151 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1152 extBaseTypePath = baseTypePath;
1155 if ("decimal64".equals(typeName)) {
1156 if (rangeStatements.isEmpty()) {
1158 return Decimal64.create(baseTypePath, fractionDigits);
1159 } catch(Exception e) {
1160 throw new YangParseException(moduleName, line, e.getMessage());
1163 Decimal64 decimalType = Decimal64.create(extBaseTypePath, fractionDigits);
1164 constraints.addRanges(decimalType.getRangeConstraints());
1165 baseType = decimalType;
1166 } else if (typeName.startsWith("int")) {
1167 IntegerTypeDefinition intType = null;
1170 intType = Int8.getInstance();
1173 intType = Int16.getInstance();
1176 intType = Int32.getInstance();
1179 intType = Int64.getInstance();
1182 if (intType == null) {
1183 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1185 constraints.addRanges(intType.getRangeConstraints());
1187 } else if (typeName.startsWith("uint")) {
1188 UnsignedIntegerTypeDefinition uintType = null;
1191 uintType = Uint8.getInstance();
1194 uintType = Uint16.getInstance();
1197 uintType = Uint32.getInstance();
1200 uintType = Uint64.getInstance();
1203 if (uintType == null) {
1204 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1206 constraints.addRanges(uintType.getRangeConstraints());
1207 baseType = uintType;
1208 } else if ("enumeration".equals(typeName)) {
1209 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1210 return EnumerationType.create(baseTypePath, enumConstants, Optional.<EnumPair> absent());
1211 } else if ("string".equals(typeName)) {
1212 StringTypeDefinition stringType = StringType.getInstance();
1213 constraints.addLengths(stringType.getLengthConstraints());
1214 baseType = stringType;
1215 } else if ("bits".equals(typeName)) {
1216 return BitsType.create(baseTypePath, getBits(typeBody, actualPath, moduleName));
1217 } else if ("leafref".equals(typeName)) {
1218 final String path = parseLeafrefPath(typeBody);
1219 final boolean absolute = path.startsWith("/");
1220 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1221 return new Leafref(xpath);
1222 } else if ("binary".equals(typeName)) {
1223 BinaryTypeDefinition binaryType = BinaryType.getInstance();
1224 constraints.addLengths(binaryType.getLengthConstraints());
1225 baseType = binaryType;
1226 } else if ("instance-identifier".equals(typeName)) {
1227 return InstanceIdentifierType.create(isRequireInstance(typeBody));
1230 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1231 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1232 typedef.setRanges(constraints.getRange());
1233 typedef.setLengths(constraints.getLength());
1234 typedef.setPatterns(constraints.getPatterns());
1235 typedef.setFractionDigits(constraints.getFractionDigits());
1239 QName qname = QName.create(moduleQName, typeName);
1240 SchemaPath schemaPath = actualPath.createChild(qname);
1241 final Optional<String> opt = Optional.of("");
1242 ExtendedType.Builder typeBuilder = ExtendedType.builder(qname, baseType, opt, opt, schemaPath);
1244 typeBuilder.ranges(constraints.getRange());
1245 typeBuilder.lengths(constraints.getLength());
1246 typeBuilder.patterns(constraints.getPatterns());
1247 typeBuilder.fractionDigits(constraints.getFractionDigits());
1249 return typeBuilder.build();
1252 private static SchemaPath createTypePath(final SchemaPath actual, final String typeName) {
1253 QName last = actual.getLastComponent();
1254 return actual.createChild(QName.create(last, typeName));
1257 private static SchemaPath createBaseTypePath(final SchemaPath actual, final String typeName) {
1258 return actual.createChild(BaseTypes.constructQName(typeName));
1261 private static SchemaPath createExtendedBaseTypePath(final SchemaPath actual, final QName moduleQName, final String typeName) {
1262 return actual.createChild(
1263 QName.create(moduleQName, typeName),
1264 BaseTypes.constructQName(typeName));
1268 * Parse given context and find identityref base value.
1272 * @return identityref base value as String
1274 public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
1275 String result = null;
1276 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1277 ParseTree child = ctx.getChild(i);
1278 if (child instanceof Identityref_specificationContext) {
1279 for (int j = 0; j < child.getChildCount(); j++) {
1280 ParseTree baseArg = child.getChild(j);
1281 if (baseArg instanceof Base_stmtContext) {
1282 result = stringFromNode(baseArg);
1292 * Parse type body statement and find require-instance value.
1296 * @return require-instance value
1298 private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
1299 for (int i = 0; i < ctx.getChildCount(); i++) {
1300 ParseTree child = ctx.getChild(i);
1301 if (child instanceof Instance_identifier_specificationContext) {
1302 for (int j = 0; j < child.getChildCount(); j++) {
1303 ParseTree reqStmt = child.getChild(j);
1304 if (reqStmt instanceof Require_instance_stmtContext) {
1305 for (int k = 0; k < reqStmt.getChildCount(); k++) {
1306 ParseTree reqArg = reqStmt.getChild(k);
1307 if (reqArg instanceof Require_instance_argContext) {
1308 return Boolean.valueOf(stringFromNode(reqArg));
1319 * Parse type body statement and find leafref path.
1323 * @return leafref path as String
1325 private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
1326 for (int i = 0; i < ctx.getChildCount(); i++) {
1327 ParseTree child = ctx.getChild(i);
1328 if (child instanceof Leafref_specificationContext) {
1329 for (int j = 0; j < child.getChildCount(); j++) {
1330 ParseTree leafRefSpec = child.getChild(j);
1331 if (leafRefSpec instanceof Path_stmtContext) {
1332 return stringFromNode(leafRefSpec);
1341 * Internal helper method for parsing must statement.
1345 * @return MustDefinition object based on parsed context
1347 private static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1348 StringBuilder mustText = new StringBuilder();
1349 Optional<String> description = Optional.absent();
1350 Optional<String> reference = Optional.absent();
1351 Optional<String> errorAppTag = Optional.absent();
1352 Optional<String> errorMessage = Optional.absent();
1353 for (int i = 0; i < ctx.getChildCount(); ++i) {
1354 ParseTree child = ctx.getChild(i);
1355 if (child instanceof StringContext) {
1356 final StringContext context = (StringContext) child;
1357 if (context.getChildCount() == 1) {
1358 String mustPart = context.getChild(0).getText();
1359 // trim start and end quotation
1360 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1362 for (int j = 0; j < context.getChildCount(); j++) {
1363 String mustPart = context.getChild(j).getText();
1365 mustText.append(mustPart.substring(0, mustPart.length() - 1));
1369 mustText.append(mustPart.substring(1));
1373 } else if (child instanceof Description_stmtContext) {
1374 description = Optional.of(stringFromNode(child));
1375 } else if (child instanceof Reference_stmtContext) {
1376 reference = Optional.of(stringFromNode(child));
1377 } else if (child instanceof Error_app_tag_stmtContext) {
1378 errorAppTag = Optional.of(stringFromNode(child));
1379 } else if (child instanceof Error_message_stmtContext) {
1380 errorMessage = Optional.of(stringFromNode(child));
1384 return MustDefinitionImpl.create(mustText.toString(), description, reference, errorAppTag, errorMessage);
1388 * Parse given context and set constraints to constraints builder.
1392 * @param constraints
1393 * ConstraintsBuilder to fill
1395 public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1396 for (int i = 0; i < ctx.getChildCount(); ++i) {
1397 final ParseTree childNode = ctx.getChild(i);
1398 if (childNode instanceof Max_elements_stmtContext) {
1399 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1400 constraints.setMaxElements(max);
1401 } else if (childNode instanceof Min_elements_stmtContext) {
1402 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1403 constraints.setMinElements(min);
1404 } else if (childNode instanceof Must_stmtContext) {
1405 MustDefinition must = parseMust((Must_stmtContext) childNode);
1406 constraints.addMustDefinition(must);
1407 } else if (childNode instanceof Mandatory_stmtContext) {
1408 for (int j = 0; j < childNode.getChildCount(); j++) {
1409 ParseTree mandatoryTree = childNode.getChild(j);
1410 if (mandatoryTree instanceof Mandatory_argContext) {
1411 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1412 constraints.setMandatory(mandatory);
1415 } else if (childNode instanceof When_stmtContext) {
1416 constraints.addWhenCondition(stringFromNode(childNode));
1421 private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1422 Integer result = null;
1424 for (int i = 0; i < ctx.getChildCount(); i++) {
1425 ParseTree minArg = ctx.getChild(i);
1426 if (minArg instanceof Min_value_argContext) {
1427 result = Integer.valueOf(stringFromNode(minArg));
1430 if (result == null) {
1431 throw new IllegalArgumentException();
1434 } catch (Exception e) {
1435 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1439 private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1440 Integer result = null;
1442 for (int i = 0; i < ctx.getChildCount(); i++) {
1443 ParseTree maxArg = ctx.getChild(i);
1444 if (maxArg instanceof Max_value_argContext) {
1445 String maxValue = stringFromNode(maxArg);
1446 if ("unbounded".equals(maxValue)) {
1447 result = Integer.MAX_VALUE;
1449 result = Integer.valueOf(maxValue);
1453 if (result == null) {
1454 throw new IllegalArgumentException();
1457 } catch (Exception e) {
1458 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1463 * Parse given context and return yin value.
1467 * @return true if value is 'true', false otherwise
1469 public static boolean parseYinValue(final Argument_stmtContext ctx) {
1470 boolean yinValue = false;
1471 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1472 ParseTree yin = ctx.getChild(i);
1473 if (yin instanceof Yin_element_stmtContext) {
1474 for (int j = 0; j < yin.getChildCount(); j++) {
1475 ParseTree yinArg = yin.getChild(j);
1476 if (yinArg instanceof Yin_element_argContext) {
1477 String yinString = stringFromNode(yinArg);
1478 if ("true".equals(yinString)) {
1490 * Check this base type.
1493 * base YANG type name
1495 * name of current module
1498 * @throws YangParseException
1499 * if this is one of YANG type which MUST contain additional
1500 * informations in its body
1502 public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1505 throw new YangParseException(moduleName, line,
1506 "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1508 throw new YangParseException(moduleName, line,
1509 "The 'base' statement MUST be present if the type is 'identityref'.");
1511 throw new YangParseException(moduleName, line,
1512 "The 'path' statement MUST be present if the type is 'leafref'.");
1514 throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1516 throw new YangParseException(moduleName, line,
1517 "The 'enum' statement MUST be present if the type is 'enumeration'.");
1522 * Parse refine statement.
1527 * name of current module
1528 * @return RefineHolder object representing this refine statement
1530 public static RefineHolderImpl parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
1531 final String refineTarget = stringFromNode(refineCtx);
1532 final RefineHolderImpl refine = new RefineHolderImpl(moduleName, refineCtx.getStart().getLine(), refineTarget);
1533 for (int i = 0; i < refineCtx.getChildCount(); i++) {
1534 ParseTree refinePom = refineCtx.getChild(i);
1535 if (refinePom instanceof Refine_pomContext) {
1536 for (int j = 0; j < refinePom.getChildCount(); j++) {
1537 ParseTree refineStmt = refinePom.getChild(j);
1538 parseRefineDefault(refine, refineStmt);
1540 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1541 parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1542 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1543 parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1544 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1545 parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1546 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1547 parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1548 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1549 parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1550 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1551 parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1559 private static void parseRefineDefault(final RefineHolderImpl refine, final ParseTree refineStmt) {
1560 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1561 ParseTree refineArg = refineStmt.getChild(i);
1562 if (refineArg instanceof Description_stmtContext) {
1563 String description = stringFromNode(refineArg);
1564 refine.setDescription(description);
1565 } else if (refineArg instanceof Reference_stmtContext) {
1566 String reference = stringFromNode(refineArg);
1567 refine.setReference(reference);
1568 } else if (refineArg instanceof Config_stmtContext) {
1569 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1570 refine.setConfiguration(config);
1575 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_stmtsContext refineStmt) {
1576 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1577 ParseTree refineArg = refineStmt.getChild(i);
1578 if (refineArg instanceof Default_stmtContext) {
1579 String defaultStr = stringFromNode(refineArg);
1580 refine.setDefaultStr(defaultStr);
1581 } else if (refineArg instanceof Mandatory_stmtContext) {
1582 for (int j = 0; j < refineArg.getChildCount(); j++) {
1583 ParseTree mandatoryTree = refineArg.getChild(j);
1584 if (mandatoryTree instanceof Mandatory_argContext) {
1585 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1586 refine.setMandatory(mandatory);
1589 } else if (refineArg instanceof Must_stmtContext) {
1590 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1591 refine.setMust(must);
1598 private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_container_stmtsContext refineStmt) {
1599 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1600 ParseTree refineArg = refineStmt.getChild(i);
1601 if (refineArg instanceof Must_stmtContext) {
1602 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1603 refine.setMust(must);
1604 } else if (refineArg instanceof Presence_stmtContext) {
1605 refine.setPresence(true);
1611 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_list_stmtsContext refineStmt) {
1612 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1613 ParseTree refineArg = refineStmt.getChild(i);
1614 if (refineArg instanceof Must_stmtContext) {
1615 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1616 refine.setMust(must);
1617 } else if (refineArg instanceof Max_elements_stmtContext) {
1618 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1619 refine.setMaxElements(max);
1620 } else if (refineArg instanceof Min_elements_stmtContext) {
1621 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1622 refine.setMinElements(min);
1628 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_list_stmtsContext refineStmt) {
1629 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1630 ParseTree refineArg = refineStmt.getChild(i);
1631 if (refineArg instanceof Must_stmtContext) {
1632 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1633 refine.setMust(must);
1634 } else if (refineArg instanceof Max_elements_stmtContext) {
1635 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1636 refine.setMaxElements(max);
1637 } else if (refineArg instanceof Min_elements_stmtContext) {
1638 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1639 refine.setMinElements(min);
1645 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_choice_stmtsContext refineStmt) {
1646 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1647 ParseTree refineArg = refineStmt.getChild(i);
1648 if (refineArg instanceof Default_stmtContext) {
1649 String defaultStr = stringFromNode(refineArg);
1650 refine.setDefaultStr(defaultStr);
1651 } else if (refineArg instanceof Mandatory_stmtContext) {
1652 for (int j = 0; j < refineArg.getChildCount(); j++) {
1653 ParseTree mandatoryTree = refineArg.getChild(j);
1654 if (mandatoryTree instanceof Mandatory_argContext) {
1655 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1656 refine.setMandatory(mandatory);
1664 private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_anyxml_stmtsContext refineStmt) {
1665 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1666 ParseTree refineArg = refineStmt.getChild(i);
1667 if (refineArg instanceof Must_stmtContext) {
1668 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1669 refine.setMust(must);
1670 } else if (refineArg instanceof Mandatory_stmtContext) {
1671 for (int j = 0; j < refineArg.getChildCount(); j++) {
1672 ParseTree mandatoryTree = refineArg.getChild(j);
1673 if (mandatoryTree instanceof Mandatory_argContext) {
1674 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1675 refine.setMandatory(mandatory);
1683 public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
1684 List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1685 checkState(!potentialValues.isEmpty());
1686 return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1689 public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
1690 List<T> potential = context.getRuleContexts(contextType);
1691 if(potential.isEmpty()) {
1692 return Optional.absent();
1694 return Optional.of(potential.get(0));