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 org.antlr.v4.runtime.ParserRuleContext;
23 import org.antlr.v4.runtime.tree.ParseTree;
24 import org.antlr.v4.runtime.tree.TerminalNode;
25 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
26 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
27 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
28 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bit_stmtContext;
29 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bits_specificationContext;
30 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_argContext;
31 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_stmtContext;
32 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Decimal64_specificationContext;
33 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Default_stmtContext;
34 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Description_stmtContext;
35 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_specificationContext;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_stmtContext;
37 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_app_tag_stmtContext;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_message_stmtContext;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Fraction_digits_stmtContext;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Identityref_specificationContext;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Instance_identifier_specificationContext;
42 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Key_stmtContext;
43 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Leafref_specificationContext;
44 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Length_stmtContext;
45 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_argContext;
46 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_stmtContext;
47 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_elements_stmtContext;
48 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_value_argContext;
49 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_elements_stmtContext;
50 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_value_argContext;
51 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
52 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Must_stmtContext;
53 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Numerical_restrictionsContext;
54 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_argContext;
55 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
56 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Path_stmtContext;
57 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Pattern_stmtContext;
58 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Position_stmtContext;
59 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Presence_stmtContext;
60 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Range_stmtContext;
61 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Reference_stmtContext;
62 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_anyxml_stmtsContext;
63 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_choice_stmtsContext;
64 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_container_stmtsContext;
65 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_list_stmtsContext;
66 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_stmtsContext;
67 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_list_stmtsContext;
68 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_pomContext;
69 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_stmtContext;
70 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_argContext;
71 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_stmtContext;
72 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_argContext;
73 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_stmtContext;
74 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.StringContext;
75 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.String_restrictionsContext;
76 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
77 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
78 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Value_stmtContext;
79 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
80 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_argContext;
81 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
82 import org.opendaylight.yangtools.yang.common.QName;
83 import org.opendaylight.yangtools.yang.model.api.MustDefinition;
84 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
85 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
86 import org.opendaylight.yangtools.yang.model.api.Status;
87 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
88 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
90 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
91 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
92 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
93 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
94 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
96 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
97 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
98 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
99 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
100 import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
101 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
102 import org.opendaylight.yangtools.yang.model.util.BinaryType;
103 import org.opendaylight.yangtools.yang.model.util.BitImpl;
104 import org.opendaylight.yangtools.yang.model.util.BitsType;
105 import org.opendaylight.yangtools.yang.model.util.Decimal64;
106 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
107 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
108 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
109 import org.opendaylight.yangtools.yang.model.util.Int16;
110 import org.opendaylight.yangtools.yang.model.util.Int32;
111 import org.opendaylight.yangtools.yang.model.util.Int64;
112 import org.opendaylight.yangtools.yang.model.util.Int8;
113 import org.opendaylight.yangtools.yang.model.util.Leafref;
114 import org.opendaylight.yangtools.yang.model.util.MustDefinitionImpl;
115 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
116 import org.opendaylight.yangtools.yang.model.util.StringType;
117 import org.opendaylight.yangtools.yang.model.util.Uint16;
118 import org.opendaylight.yangtools.yang.model.util.Uint32;
119 import org.opendaylight.yangtools.yang.model.util.Uint64;
120 import org.opendaylight.yangtools.yang.model.util.Uint8;
121 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
122 import org.opendaylight.yangtools.yang.parser.builder.api.ConstraintsBuilder;
123 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
124 import org.opendaylight.yangtools.yang.parser.builder.api.RefineBuilder;
125 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
126 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
127 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
128 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
129 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
130 import org.opendaylight.yangtools.yang.parser.builder.impl.RefineHolderImpl;
131 import org.opendaylight.yangtools.yang.parser.builder.impl.TypeDefinitionBuilderImpl;
132 import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
133 import org.opendaylight.yangtools.yang.parser.util.TypeConstraints;
134 import org.opendaylight.yangtools.yang.parser.util.UnknownBoundaryNumber;
135 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
136 import org.slf4j.Logger;
137 import org.slf4j.LoggerFactory;
139 public final class ParserListenerUtils {
140 private static final Logger LOG = LoggerFactory.getLogger(ParserListenerUtils.class);
141 private static final Splitter KEYDEF_SPLITTER = Splitter.on(' ').omitEmptyStrings();
142 private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults();
143 private static final Splitter DOT_DOT_SPLITTER = Splitter.on("..").trimResults();
144 private static final CharMatcher QUOTE_MATCHER = CharMatcher.is('"');
146 private ParserListenerUtils() {
150 * Parse given tree and get first string value.
154 * @return first string value from given tree
156 public static String stringFromNode(final ParseTree treeNode) {
158 for (int i = 0; i < treeNode.getChildCount(); ++i) {
159 final ParseTree child = treeNode.getChild(i);
160 if (child instanceof StringContext) {
161 return stringFromStringContext((StringContext)child);
167 private static String stringFromStringContext(final StringContext context) {
168 StringBuilder sb = new StringBuilder();
169 for (TerminalNode stringNode : context.STRING()) {
170 final String str = stringNode.getText();
171 final int i = str.indexOf('"');
179 * The string contains quotes, so we have to tread carefully.
181 * FIXME: I think this code is broken, but proving that requires
182 * making sense of the parser/lexer and how they tie into
183 * this method. Especially what format 'str' can have and
184 * how we need to handle it. The original check was:
186 * if (!(result.startsWith("\"")) && result.endsWith("\""))
188 * Looking at the parentheses it is hard to justify the
189 * pair right after negation -- the intent may have been
190 * to negate the entire expression.
192 if (i != 0 && str.endsWith("\"")) {
193 LOG.error("Syntax error in module {} at line {}: missing '\"'.", getParentModule(context),
194 context.getStart().getLine());
196 sb.append(QUOTE_MATCHER.removeFrom(str));
199 return sb.toString();
202 private static String getParentModule(final ParseTree ctx) {
203 ParseTree current = ctx;
204 while (current != null && !(current instanceof Module_stmtContext)) {
205 current = current.getParent();
207 if (current != null) {
208 Module_stmtContext module = (Module_stmtContext) current;
209 for (int i = 0; i < module.getChildCount(); i++) {
210 if (module.getChild(i) instanceof StringContext) {
211 final StringContext str = (StringContext) module.getChild(i);
212 return str.getChild(0).getText();
220 * Parse 'description', 'reference' and 'status' statements and fill in
226 * builder to fill in with parsed statements
228 public static void parseSchemaNodeArgs(final ParseTree ctx, final SchemaNodeBuilder builder) {
229 for (int i = 0; i < ctx.getChildCount(); i++) {
230 final ParseTree child = ctx.getChild(i);
231 if (child instanceof Description_stmtContext) {
232 final String desc = stringFromNode(child);
233 builder.setDescription(desc);
234 } else if (child instanceof Reference_stmtContext) {
235 final String ref = stringFromNode(child);
236 builder.setReference(ref);
237 } else if (child instanceof Status_stmtContext) {
238 final Status status = parseStatus((Status_stmtContext) child);
239 builder.setStatus(status);
245 * Parse given context and return its value;
249 * @return value parsed from context
251 public static Status parseStatus(final Status_stmtContext ctx) {
252 Status result = null;
253 for (int i = 0; i < ctx.getChildCount(); i++) {
254 ParseTree statusArg = ctx.getChild(i);
255 if (statusArg instanceof Status_argContext) {
256 String statusArgStr = stringFromNode(statusArg);
257 switch (statusArgStr) {
259 result = Status.CURRENT;
262 result = Status.DEPRECATED;
265 result = Status.OBSOLETE;
268 LOG.warn("Invalid 'status' statement: " + statusArgStr);
276 * Parse given tree and returns units statement as string.
280 * @return value of units statement as string or null if there is no units
283 public static String parseUnits(final ParseTree ctx) {
284 for (int i = 0; i < ctx.getChildCount(); i++) {
285 ParseTree child = ctx.getChild(i);
286 if (child instanceof Units_stmtContext) {
287 return stringFromNode(child);
294 * Parse given tree and returns default statement as string.
298 * @return value of default statement as string or null if there is no
301 public static String parseDefault(final ParseTree ctx) {
302 for (int i = 0; i < ctx.getChildCount(); i++) {
303 ParseTree child = ctx.getChild(i);
304 if (child instanceof Default_stmtContext) {
305 return stringFromNode(child);
312 * Create java.util.List of key node names.
315 * Key_stmtContext context
316 * @return YANG list key as java.util.List of key node names
318 public static List<String> createListKey(final Key_stmtContext ctx) {
319 String keyDefinition = stringFromNode(ctx);
320 return Lists.newArrayList(KEYDEF_SPLITTER.split(keyDefinition));
324 * Parse given type body of enumeration statement.
327 * type body context to parse
329 * actual position in YANG model
331 * current module name
332 * @return List of EnumPair object parsed from given context
334 private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
335 final SchemaPath path, final String moduleName) {
336 List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<>();
338 for (int i = 0; i < ctx.getChildCount(); i++) {
339 ParseTree enumSpecChild = ctx.getChild(i);
340 if (enumSpecChild instanceof Enum_specificationContext) {
341 int highestValue = -1;
342 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
343 ParseTree enumChild = enumSpecChild.getChild(j);
344 if (enumChild instanceof Enum_stmtContext) {
345 EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName);
346 if (enumPair.getValue() > highestValue) {
347 highestValue = enumPair.getValue();
349 enumConstants.add(enumPair);
354 return enumConstants;
358 * Parse enum statement context
361 * enum statement context
362 * @param highestValue
363 * current highest value in enumeration
365 * actual position in YANG model
367 * current module name
368 * @return EnumPair object parsed from given context
370 private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
371 final SchemaPath actualPath, final String moduleName) {
372 final String name = stringFromNode(ctx);
373 SchemaPath path = createTypePath(actualPath, name);
374 Integer value = null;
376 String description = null;
377 String reference = null;
378 Status status = null;
380 for (int i = 0; i < ctx.getChildCount(); i++) {
381 ParseTree child = ctx.getChild(i);
382 if (child instanceof Value_stmtContext) {
383 String valueStr = stringFromNode(child);
384 value = Integer.valueOf(valueStr);
385 } else if (child instanceof Description_stmtContext) {
386 description = stringFromNode(child);
387 } else if (child instanceof Reference_stmtContext) {
388 reference = stringFromNode(child);
389 } else if (child instanceof Status_stmtContext) {
390 status = parseStatus((Status_stmtContext) child);
395 value = highestValue + 1;
397 if (value < -2147483648 || value > 2147483647) {
398 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on enum '" + name
399 + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: " + value);
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) {
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 patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
740 * Internal helper method.
744 * @return PatternConstraint object
746 private static PatternConstraint parsePatternConstraint(final Pattern_stmtContext ctx) {
747 Optional<String> description = Optional.absent();
748 Optional<String> reference = Optional.absent();
749 for (int i = 0; i < ctx.getChildCount(); i++) {
750 ParseTree child = ctx.getChild(i);
751 if (child instanceof Description_stmtContext) {
752 description = Optional.of(stringFromNode(child));
753 } else if (child instanceof Reference_stmtContext) {
754 reference = Optional.of(stringFromNode(child));
757 String pattern = parsePatternString(ctx);
758 return BaseConstraints.newPatternConstraint(pattern, description, reference);
762 * Parse given context and return pattern value.
766 * @return pattern value as String
768 private static String parsePatternString(final Pattern_stmtContext ctx) {
769 StringBuilder result = new StringBuilder();
770 for (int i = 0; i < ctx.getChildCount(); ++i) {
771 ParseTree child = ctx.getChild(i);
772 if (child instanceof StringContext) {
773 for (int j = 0; j < child.getChildCount(); j++) {
775 String patternToken = child.getChild(j).getText();
776 result.append(patternToken.substring(1, patternToken.length() - 1));
781 return result.toString();
785 * Get fraction digits value from type body.
788 * type body context to parse
790 * name of current module
791 * @return 'fraction-digits' value if present in given context, null
794 private static Integer getFractionDigits(final Type_body_stmtsContext ctx, final String moduleName) {
795 Integer result = null;
796 for (int i = 0; i < ctx.getChildCount(); i++) {
797 ParseTree dec64specChild = ctx.getChild(i);
798 if (dec64specChild instanceof Decimal64_specificationContext) {
799 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild, moduleName);
806 * Parse decimal64 fraction-digits value.
811 * name of current module
812 * @return fraction-digits value as Integer
814 private static Integer parseFractionDigits(final Decimal64_specificationContext ctx, final String moduleName) {
815 Integer result = null;
816 for (int i = 0; i < ctx.getChildCount(); i++) {
817 ParseTree fdChild = ctx.getChild(i);
818 if (fdChild instanceof Fraction_digits_stmtContext) {
819 String value = stringFromNode(fdChild);
821 result = Integer.valueOf(value);
822 } catch (NumberFormatException e) {
823 throw new YangParseException(moduleName, ctx.getStart().getLine(),
824 "Unable to parse fraction digits value '" + value + "'.", e);
832 * Internal helper method for parsing bit statements from given type body
836 * type body context to parse
838 * current position in YANG model
840 * current module name
841 * @return List of Bit objects created from this context
843 private static List<BitsTypeDefinition.Bit> getBits(final Type_body_stmtsContext ctx, final SchemaPath actualPath,
844 final String moduleName) {
845 final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
846 for (int j = 0; j < ctx.getChildCount(); j++) {
847 ParseTree bitsSpecChild = ctx.getChild(j);
848 if (bitsSpecChild instanceof Bits_specificationContext) {
849 long highestPosition = -1;
850 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
851 ParseTree bitChild = bitsSpecChild.getChild(k);
852 if (bitChild instanceof Bit_stmtContext) {
853 Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, moduleName);
854 if (bit.getPosition() > highestPosition) {
855 highestPosition = bit.getPosition();
866 * Internal helper method for parsing bit context.
869 * bit statement context to parse
870 * @param highestPosition
871 * current highest position in bits type
873 * current position in YANG model
875 * current module name
876 * @return Bit object parsed from this context
878 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, final long highestPosition,
879 final SchemaPath actualPath, final String moduleName) {
880 String name = stringFromNode(ctx);
881 Long position = null;
883 String description = null;
884 String reference = null;
885 Status status = Status.CURRENT;
887 SchemaPath schemaPath = createBaseTypePath(actualPath, name);
889 for (int i = 0; i < ctx.getChildCount(); i++) {
890 ParseTree child = ctx.getChild(i);
891 if (child instanceof Position_stmtContext) {
892 String positionStr = stringFromNode(child);
893 position = Long.valueOf(positionStr);
894 } else if (child instanceof Description_stmtContext) {
895 description = stringFromNode(child);
896 } else if (child instanceof Reference_stmtContext) {
897 reference = stringFromNode(child);
898 } else if (child instanceof Status_stmtContext) {
899 status = parseStatus((Status_stmtContext) child);
903 if (position == null) {
904 position = highestPosition + 1;
906 if (position < 0 || position > 4294967295L) {
907 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on bit '" + name
908 + "': the position value MUST be in the range 0 to 4294967295");
911 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
912 return new BitImpl(position, schemaPath.getPathTowardsRoot().iterator().next(), schemaPath,
913 description, reference, status, unknownNodes);
917 * Parse 'ordered-by' statement.
919 * The 'ordered-by' statement defines whether the order of entries within a
920 * list are determined by the user or the system. The argument is one of the
921 * strings "system" or "user". If not present, order defaults to "system".
924 * Ordered_by_stmtContext
925 * @return true, if ordered-by contains value 'user', false otherwise
927 public static boolean parseUserOrdered(final Ordered_by_stmtContext ctx) {
928 boolean result = false;
929 for (int j = 0; j < ctx.getChildCount(); j++) {
930 ParseTree orderArg = ctx.getChild(j);
931 if (orderArg instanceof Ordered_by_argContext) {
932 String orderStr = stringFromNode(orderArg);
941 LOG.warn("Invalid 'ordered-by' statement.");
949 * Get config statement from given context. If there is no config statement,
950 * return config value of parent
957 * name of current module
959 * line in current module
960 * @return config statement parsed from given context
962 public static boolean getConfig(final ParseTree ctx, final Builder node, final String moduleName, final int line) {
964 // parse configuration statement
965 Boolean config = null;
966 for (int i = 0; i < ctx.getChildCount(); i++) {
967 ParseTree child = ctx.getChild(i);
968 if (child instanceof Config_stmtContext) {
969 config = parseConfig((Config_stmtContext) child, moduleName);
974 // If 'config' is not specified, the default is the same as the parent
975 // schema node's 'config' value
976 boolean parentConfig = getParentConfig(node);
977 if (config == null) {
978 result = parentConfig;
980 // Check: if a node has 'config' set to 'false', no node underneath
981 // it can have 'config' set to 'true'
982 if (!parentConfig && config) {
983 throw new YangParseException(moduleName, line,
984 "Can not set 'config' to 'true' if parent node has 'config' set to 'false'");
992 private static boolean getParentConfig(final Builder node) {
993 Builder parent = node.getParent();
996 if (parent instanceof ChoiceCaseBuilder) {
997 parent = parent.getParent();
999 if (parent instanceof DataSchemaNodeBuilder) {
1000 config = ((DataSchemaNodeBuilder) parent).isConfiguration();
1008 * Parse config statement.
1011 * config context to parse
1013 * current module name
1014 * @return true if given context contains string 'true', false otherwise
1016 private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
1017 Boolean result = null;
1019 for (int i = 0; i < ctx.getChildCount(); ++i) {
1020 final ParseTree configContext = ctx.getChild(i);
1021 if (configContext instanceof Config_argContext) {
1022 final String value = stringFromNode(configContext);
1031 throw new YangParseException(moduleName, ctx.getStart().getLine(),
1032 "Failed to parse 'config' statement value: '" + value + "'.");
1041 * Parse unknown type with body.
1046 * current node parent
1047 * @param prefixedQName
1048 * type qname with prefix
1049 * @param moduleBuilder
1050 * current module builder
1051 * @param moduleQName
1052 * current module qname
1054 * actual path in model
1056 public static void parseUnknownTypeWithBody(Type_body_stmtsContext typeBody, TypeAwareBuilder parent,
1057 QName prefixedQName, ModuleBuilder moduleBuilder, QName moduleQName, SchemaPath actualPath) {
1058 final int line = typeBody.getStart().getLine();
1060 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleBuilder.getName());
1061 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleBuilder.getName());
1062 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1063 Integer fractionDigits = getFractionDigits(typeBody, moduleBuilder.getName());
1065 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1066 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1067 typedef.setRanges(rangeStatements);
1068 typedef.setLengths(lengthStatements);
1069 typedef.setPatterns(patternStatements);
1070 typedef.setFractionDigits(fractionDigits);
1071 typedef.setTypeQName(prefixedQName);
1072 // add parent node of this type statement to dirty nodes
1073 moduleBuilder.markActualNodeDirty();
1075 QName qname = QName.create(moduleQName, prefixedQName.getLocalName());
1076 SchemaPath schemaPath = createTypePath(actualPath, prefixedQName.getLocalName());
1077 TypeDefinitionBuilder typeBuilder = new TypeDefinitionBuilderImpl(moduleBuilder.getName(), line, qname, schemaPath);
1078 typeBuilder.setRanges(rangeStatements);
1079 typeBuilder.setLengths(lengthStatements);
1080 typeBuilder.setPatterns(patternStatements);
1081 typeBuilder.setFractionDigits(fractionDigits);
1082 typeBuilder.setTypeQName(prefixedQName);
1083 parent.setTypedef(typeBuilder);
1084 moduleBuilder.getDirtyNodes().add(typeBuilder);
1089 * Create TypeDefinition object based on given type name and type body.
1096 * current path in schema
1105 * @return TypeDefinition object based on parsed values.
1107 public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1108 final SchemaPath actualPath, final QName moduleQName, final Builder parent) {
1110 final String moduleName = parent.getModuleName();
1111 final int line = typeBody.getStart().getLine();
1112 TypeDefinition<?> baseType = null;
1114 Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1115 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1116 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1117 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1119 TypeConstraints constraints = new TypeConstraints(moduleName, line);
1120 constraints.addFractionDigits(fractionDigits);
1121 constraints.addLengths(lengthStatements);
1122 constraints.addPatterns(patternStatements);
1123 constraints.addRanges(rangeStatements);
1125 SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1126 SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, moduleQName, typeName);
1128 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1129 extBaseTypePath = baseTypePath;
1132 if ("decimal64".equals(typeName)) {
1133 if (rangeStatements.isEmpty()) {
1135 return Decimal64.create(baseTypePath, fractionDigits);
1136 } catch(Exception e) {
1137 throw new YangParseException(moduleName, line, e.getMessage());
1140 Decimal64 decimalType = Decimal64.create(extBaseTypePath, fractionDigits);
1141 constraints.addRanges(decimalType.getRangeConstraints());
1142 baseType = decimalType;
1143 } else if (typeName.startsWith("int")) {
1144 IntegerTypeDefinition intType = null;
1147 intType = Int8.getInstance();
1150 intType = Int16.getInstance();
1153 intType = Int32.getInstance();
1156 intType = Int64.getInstance();
1159 if (intType == null) {
1160 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1162 constraints.addRanges(intType.getRangeConstraints());
1164 } else if (typeName.startsWith("uint")) {
1165 UnsignedIntegerTypeDefinition uintType = null;
1168 uintType = Uint8.getInstance();
1171 uintType = Uint16.getInstance();
1174 uintType = Uint32.getInstance();
1177 uintType = Uint64.getInstance();
1180 if (uintType == null) {
1181 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1183 constraints.addRanges(uintType.getRangeConstraints());
1184 baseType = uintType;
1185 } else if ("enumeration".equals(typeName)) {
1186 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1187 return EnumerationType.create(baseTypePath, enumConstants, Optional.<EnumPair> absent());
1188 } else if ("string".equals(typeName)) {
1189 StringTypeDefinition stringType = StringType.getInstance();
1190 constraints.addLengths(stringType.getLengthConstraints());
1191 baseType = stringType;
1192 } else if ("bits".equals(typeName)) {
1193 return BitsType.create(baseTypePath, getBits(typeBody, actualPath, moduleName));
1194 } else if ("leafref".equals(typeName)) {
1195 final String path = parseLeafrefPath(typeBody);
1196 final boolean absolute = path.startsWith("/");
1197 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1198 return new Leafref(xpath);
1199 } else if ("binary".equals(typeName)) {
1200 BinaryTypeDefinition binaryType = BinaryType.getInstance();
1201 constraints.addLengths(binaryType.getLengthConstraints());
1202 baseType = binaryType;
1203 } else if ("instance-identifier".equals(typeName)) {
1204 return InstanceIdentifierType.create(isRequireInstance(typeBody));
1207 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1208 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1209 typedef.setRanges(constraints.getRange());
1210 typedef.setLengths(constraints.getLength());
1211 typedef.setPatterns(constraints.getPatterns());
1212 typedef.setFractionDigits(constraints.getFractionDigits());
1216 QName qname = QName.create(moduleQName, typeName);
1217 SchemaPath schemaPath = actualPath.createChild(qname);
1218 final Optional<String> opt = Optional.of("");
1219 ExtendedType.Builder typeBuilder = ExtendedType.builder(qname, baseType, opt, opt, schemaPath);
1221 typeBuilder.ranges(constraints.getRange());
1222 typeBuilder.lengths(constraints.getLength());
1223 typeBuilder.patterns(constraints.getPatterns());
1224 typeBuilder.fractionDigits(constraints.getFractionDigits());
1226 return typeBuilder.build();
1229 private static SchemaPath createTypePath(final SchemaPath actual, final String typeName) {
1230 QName last = actual.getLastComponent();
1231 return actual.createChild(QName.create(last, typeName));
1234 private static SchemaPath createBaseTypePath(final SchemaPath actual, final String typeName) {
1235 return actual.createChild(BaseTypes.constructQName(typeName));
1238 private static SchemaPath createExtendedBaseTypePath(final SchemaPath actual, final QName moduleQName, final String typeName) {
1239 return actual.createChild(
1240 QName.create(moduleQName, typeName),
1241 BaseTypes.constructQName(typeName));
1245 * Parse given context and find identityref base value.
1249 * @return identityref base value as String
1251 public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
1252 String result = null;
1253 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1254 ParseTree child = ctx.getChild(i);
1255 if (child instanceof Identityref_specificationContext) {
1256 for (int j = 0; j < child.getChildCount(); j++) {
1257 ParseTree baseArg = child.getChild(j);
1258 if (baseArg instanceof Base_stmtContext) {
1259 result = stringFromNode(baseArg);
1269 * Parse type body statement and find require-instance value.
1273 * @return require-instance value
1275 private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
1276 for (int i = 0; i < ctx.getChildCount(); i++) {
1277 ParseTree child = ctx.getChild(i);
1278 if (child instanceof Instance_identifier_specificationContext) {
1279 for (int j = 0; j < child.getChildCount(); j++) {
1280 ParseTree reqStmt = child.getChild(j);
1281 if (reqStmt instanceof Require_instance_stmtContext) {
1282 for (int k = 0; k < reqStmt.getChildCount(); k++) {
1283 ParseTree reqArg = reqStmt.getChild(k);
1284 if (reqArg instanceof Require_instance_argContext) {
1285 return Boolean.valueOf(stringFromNode(reqArg));
1296 * Parse type body statement and find leafref path.
1300 * @return leafref path as String
1302 private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
1303 for (int i = 0; i < ctx.getChildCount(); i++) {
1304 ParseTree child = ctx.getChild(i);
1305 if (child instanceof Leafref_specificationContext) {
1306 for (int j = 0; j < child.getChildCount(); j++) {
1307 ParseTree leafRefSpec = child.getChild(j);
1308 if (leafRefSpec instanceof Path_stmtContext) {
1309 return stringFromNode(leafRefSpec);
1318 * Internal helper method for parsing must statement.
1322 * @return MustDefinition object based on parsed context
1324 private static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1325 StringBuilder mustText = new StringBuilder();
1326 Optional<String> description = Optional.absent();
1327 Optional<String> reference = Optional.absent();
1328 Optional<String> errorAppTag = Optional.absent();
1329 Optional<String> errorMessage = Optional.absent();
1330 for (int i = 0; i < ctx.getChildCount(); ++i) {
1331 ParseTree child = ctx.getChild(i);
1332 if (child instanceof StringContext) {
1333 final StringContext context = (StringContext) child;
1334 if (context.getChildCount() == 1) {
1335 String mustPart = context.getChild(0).getText();
1336 // trim start and end quotation
1337 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1339 for (int j = 0; j < context.getChildCount(); j++) {
1340 String mustPart = context.getChild(j).getText();
1342 mustText.append(mustPart.substring(0, mustPart.length() - 1));
1346 mustText.append(mustPart.substring(1));
1350 } else if (child instanceof Description_stmtContext) {
1351 description = Optional.of(stringFromNode(child));
1352 } else if (child instanceof Reference_stmtContext) {
1353 reference = Optional.of(stringFromNode(child));
1354 } else if (child instanceof Error_app_tag_stmtContext) {
1355 errorAppTag = Optional.of(stringFromNode(child));
1356 } else if (child instanceof Error_message_stmtContext) {
1357 errorMessage = Optional.of(stringFromNode(child));
1361 return MustDefinitionImpl.create(mustText.toString(), description, reference, errorAppTag, errorMessage);
1365 * Parse given context and set constraints to constraints builder.
1369 * @param constraints
1370 * ConstraintsBuilder to fill
1372 public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1373 for (int i = 0; i < ctx.getChildCount(); ++i) {
1374 final ParseTree childNode = ctx.getChild(i);
1375 if (childNode instanceof Max_elements_stmtContext) {
1376 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1377 constraints.setMaxElements(max);
1378 } else if (childNode instanceof Min_elements_stmtContext) {
1379 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1380 constraints.setMinElements(min);
1381 } else if (childNode instanceof Must_stmtContext) {
1382 MustDefinition must = parseMust((Must_stmtContext) childNode);
1383 constraints.addMustDefinition(must);
1384 } else if (childNode instanceof Mandatory_stmtContext) {
1385 for (int j = 0; j < childNode.getChildCount(); j++) {
1386 ParseTree mandatoryTree = childNode.getChild(j);
1387 if (mandatoryTree instanceof Mandatory_argContext) {
1388 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1389 constraints.setMandatory(mandatory);
1392 } else if (childNode instanceof When_stmtContext) {
1393 constraints.addWhenCondition(stringFromNode(childNode));
1398 private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1399 Integer result = null;
1401 for (int i = 0; i < ctx.getChildCount(); i++) {
1402 ParseTree minArg = ctx.getChild(i);
1403 if (minArg instanceof Min_value_argContext) {
1404 result = Integer.valueOf(stringFromNode(minArg));
1407 if (result == null) {
1408 throw new IllegalArgumentException();
1411 } catch (Exception e) {
1412 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1416 private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1417 Integer result = null;
1419 for (int i = 0; i < ctx.getChildCount(); i++) {
1420 ParseTree maxArg = ctx.getChild(i);
1421 if (maxArg instanceof Max_value_argContext) {
1422 String maxValue = stringFromNode(maxArg);
1423 if ("unbounded".equals(maxValue)) {
1424 result = Integer.MAX_VALUE;
1426 result = Integer.valueOf(maxValue);
1430 if (result == null) {
1431 throw new IllegalArgumentException();
1434 } catch (Exception e) {
1435 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1440 * Parse given context and return yin value.
1444 * @return true if value is 'true', false otherwise
1446 public static boolean parseYinValue(final Argument_stmtContext ctx) {
1447 boolean yinValue = false;
1448 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1449 ParseTree yin = ctx.getChild(i);
1450 if (yin instanceof Yin_element_stmtContext) {
1451 for (int j = 0; j < yin.getChildCount(); j++) {
1452 ParseTree yinArg = yin.getChild(j);
1453 if (yinArg instanceof Yin_element_argContext) {
1454 String yinString = stringFromNode(yinArg);
1455 if ("true".equals(yinString)) {
1467 * Check this base type.
1470 * base YANG type name
1472 * name of current module
1475 * @throws YangParseException
1476 * if this is one of YANG type which MUST contain additional
1477 * informations in its body
1479 public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1482 throw new YangParseException(moduleName, line,
1483 "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1485 throw new YangParseException(moduleName, line,
1486 "The 'base' statement MUST be present if the type is 'identityref'.");
1488 throw new YangParseException(moduleName, line,
1489 "The 'path' statement MUST be present if the type is 'leafref'.");
1491 throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1493 throw new YangParseException(moduleName, line,
1494 "The 'enum' statement MUST be present if the type is 'enumeration'.");
1499 * Parse refine statement.
1504 * name of current module
1505 * @return RefineHolder object representing this refine statement
1507 public static RefineHolderImpl parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
1508 final String refineTarget = stringFromNode(refineCtx);
1509 final RefineHolderImpl refine = new RefineHolderImpl(moduleName, refineCtx.getStart().getLine(), refineTarget);
1510 for (int i = 0; i < refineCtx.getChildCount(); i++) {
1511 ParseTree refinePom = refineCtx.getChild(i);
1512 if (refinePom instanceof Refine_pomContext) {
1513 for (int j = 0; j < refinePom.getChildCount(); j++) {
1514 ParseTree refineStmt = refinePom.getChild(j);
1515 parseRefineDefault(refine, refineStmt);
1517 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1518 parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1519 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1520 parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1521 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1522 parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1523 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1524 parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1525 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1526 parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1527 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1528 parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1536 private static void parseRefineDefault(final RefineHolderImpl refine, final ParseTree refineStmt) {
1537 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1538 ParseTree refineArg = refineStmt.getChild(i);
1539 if (refineArg instanceof Description_stmtContext) {
1540 String description = stringFromNode(refineArg);
1541 refine.setDescription(description);
1542 } else if (refineArg instanceof Reference_stmtContext) {
1543 String reference = stringFromNode(refineArg);
1544 refine.setReference(reference);
1545 } else if (refineArg instanceof Config_stmtContext) {
1546 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1547 refine.setConfiguration(config);
1552 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_stmtsContext refineStmt) {
1553 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1554 ParseTree refineArg = refineStmt.getChild(i);
1555 if (refineArg instanceof Default_stmtContext) {
1556 String defaultStr = stringFromNode(refineArg);
1557 refine.setDefaultStr(defaultStr);
1558 } else if (refineArg instanceof Mandatory_stmtContext) {
1559 for (int j = 0; j < refineArg.getChildCount(); j++) {
1560 ParseTree mandatoryTree = refineArg.getChild(j);
1561 if (mandatoryTree instanceof Mandatory_argContext) {
1562 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1563 refine.setMandatory(mandatory);
1566 } else if (refineArg instanceof Must_stmtContext) {
1567 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1568 refine.setMust(must);
1575 private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_container_stmtsContext refineStmt) {
1576 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1577 ParseTree refineArg = refineStmt.getChild(i);
1578 if (refineArg instanceof Must_stmtContext) {
1579 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1580 refine.setMust(must);
1581 } else if (refineArg instanceof Presence_stmtContext) {
1582 refine.setPresence(true);
1588 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_list_stmtsContext refineStmt) {
1589 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1590 ParseTree refineArg = refineStmt.getChild(i);
1591 if (refineArg instanceof Must_stmtContext) {
1592 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1593 refine.setMust(must);
1594 } else if (refineArg instanceof Max_elements_stmtContext) {
1595 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1596 refine.setMaxElements(max);
1597 } else if (refineArg instanceof Min_elements_stmtContext) {
1598 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1599 refine.setMinElements(min);
1605 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_list_stmtsContext refineStmt) {
1606 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1607 ParseTree refineArg = refineStmt.getChild(i);
1608 if (refineArg instanceof Must_stmtContext) {
1609 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1610 refine.setMust(must);
1611 } else if (refineArg instanceof Max_elements_stmtContext) {
1612 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1613 refine.setMaxElements(max);
1614 } else if (refineArg instanceof Min_elements_stmtContext) {
1615 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1616 refine.setMinElements(min);
1622 private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_choice_stmtsContext refineStmt) {
1623 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1624 ParseTree refineArg = refineStmt.getChild(i);
1625 if (refineArg instanceof Default_stmtContext) {
1626 String defaultStr = stringFromNode(refineArg);
1627 refine.setDefaultStr(defaultStr);
1628 } else if (refineArg instanceof Mandatory_stmtContext) {
1629 for (int j = 0; j < refineArg.getChildCount(); j++) {
1630 ParseTree mandatoryTree = refineArg.getChild(j);
1631 if (mandatoryTree instanceof Mandatory_argContext) {
1632 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1633 refine.setMandatory(mandatory);
1641 private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_anyxml_stmtsContext refineStmt) {
1642 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1643 ParseTree refineArg = refineStmt.getChild(i);
1644 if (refineArg instanceof Must_stmtContext) {
1645 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1646 refine.setMust(must);
1647 } else if (refineArg instanceof Mandatory_stmtContext) {
1648 for (int j = 0; j < refineArg.getChildCount(); j++) {
1649 ParseTree mandatoryTree = refineArg.getChild(j);
1650 if (mandatoryTree instanceof Mandatory_argContext) {
1651 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1652 refine.setMandatory(mandatory);
1660 public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
1661 List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1662 checkState(!potentialValues.isEmpty());
1663 return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1666 public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
1667 List<T> potential = context.getRuleContexts(contextType);
1668 if(potential.isEmpty()) {
1669 return Optional.absent();
1671 return Optional.of(potential.get(0));