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.util;
10 import static com.google.common.base.Preconditions.checkState;
12 import java.math.BigDecimal;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.Date;
17 import java.util.List;
18 import java.util.Stack;
20 import org.antlr.v4.runtime.ParserRuleContext;
21 import org.antlr.v4.runtime.tree.ParseTree;
22 import org.antlr.v4.runtime.tree.TerminalNode;
23 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
24 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
25 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
26 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bit_stmtContext;
27 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bits_specificationContext;
28 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_argContext;
29 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_stmtContext;
30 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Decimal64_specificationContext;
31 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Default_stmtContext;
32 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Description_stmtContext;
33 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_specificationContext;
34 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_stmtContext;
35 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_app_tag_stmtContext;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_message_stmtContext;
37 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Fraction_digits_stmtContext;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Identityref_specificationContext;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Instance_identifier_specificationContext;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Key_stmtContext;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Leafref_specificationContext;
42 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Length_stmtContext;
43 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_argContext;
44 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_stmtContext;
45 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_elements_stmtContext;
46 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_value_argContext;
47 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_elements_stmtContext;
48 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_value_argContext;
49 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
50 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Must_stmtContext;
51 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Numerical_restrictionsContext;
52 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_argContext;
53 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
54 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Path_stmtContext;
55 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Pattern_stmtContext;
56 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Position_stmtContext;
57 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Presence_stmtContext;
58 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Range_stmtContext;
59 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Reference_stmtContext;
60 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_anyxml_stmtsContext;
61 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_choice_stmtsContext;
62 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_container_stmtsContext;
63 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_list_stmtsContext;
64 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_stmtsContext;
65 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_list_stmtsContext;
66 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_pomContext;
67 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_stmtContext;
68 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_argContext;
69 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_stmtContext;
70 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_argContext;
71 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_stmtContext;
72 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.StringContext;
73 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.String_restrictionsContext;
74 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
75 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
76 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Value_stmtContext;
77 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
78 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_argContext;
79 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
80 import org.opendaylight.yangtools.yang.common.QName;
81 import org.opendaylight.yangtools.yang.model.api.MustDefinition;
82 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
83 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
84 import org.opendaylight.yangtools.yang.model.api.Status;
85 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
86 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
88 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
89 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
90 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
91 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
92 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
93 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
94 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
95 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
96 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
98 import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
99 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
100 import org.opendaylight.yangtools.yang.model.util.BinaryType;
101 import org.opendaylight.yangtools.yang.model.util.BitsType;
102 import org.opendaylight.yangtools.yang.model.util.Decimal64;
103 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
104 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
105 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifier;
106 import org.opendaylight.yangtools.yang.model.util.Int16;
107 import org.opendaylight.yangtools.yang.model.util.Int32;
108 import org.opendaylight.yangtools.yang.model.util.Int64;
109 import org.opendaylight.yangtools.yang.model.util.Int8;
110 import org.opendaylight.yangtools.yang.model.util.Leafref;
111 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
112 import org.opendaylight.yangtools.yang.model.util.StringType;
113 import org.opendaylight.yangtools.yang.model.util.Uint16;
114 import org.opendaylight.yangtools.yang.model.util.Uint32;
115 import org.opendaylight.yangtools.yang.model.util.Uint64;
116 import org.opendaylight.yangtools.yang.model.util.Uint8;
117 import org.opendaylight.yangtools.yang.model.util.UnknownType;
118 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
119 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
120 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
121 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
122 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
123 import org.opendaylight.yangtools.yang.parser.builder.impl.ConstraintsBuilder;
124 import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
125 import org.slf4j.Logger;
126 import org.slf4j.LoggerFactory;
128 import com.google.common.base.Optional;
130 public final class ParserListenerUtils {
131 private static final Logger LOG = LoggerFactory.getLogger(ParserListenerUtils.class);
133 private ParserListenerUtils() {
137 * Parse given tree and get first string value.
141 * @return first string value from given tree
143 public static String stringFromNode(final ParseTree treeNode) {
145 for (int i = 0; i < treeNode.getChildCount(); ++i) {
146 if (treeNode.getChild(i) instanceof StringContext) {
147 final StringContext context = (StringContext) treeNode.getChild(i);
148 if (context != null) {
149 return stringFromStringContext(context);
157 public static String stringFromStringContext(final StringContext context) {
158 StringBuilder str = new StringBuilder();
159 for (TerminalNode stringNode : context.STRING()) {
160 String result = stringNode.getText();
161 if(!result.contains("\"")){
163 } else if (!(result.startsWith("\"")) && result.endsWith("\"")) {
164 LOG.error("Syntax error in module {} at line {}: missing '\"'.", getParentModule(context),
165 context.getStart().getLine());
167 str.append(result.replace("\"", ""));
170 return str.toString();
173 private static String getParentModule(final ParseTree ctx) {
174 ParseTree current = ctx;
175 while (current != null && !(current instanceof Module_stmtContext)) {
176 current = current.getParent();
178 if (current instanceof Module_stmtContext) {
179 Module_stmtContext module = (Module_stmtContext) current;
180 for (int i = 0; i < module.getChildCount(); i++) {
181 if (module.getChild(i) instanceof StringContext) {
182 final StringContext str = (StringContext) module.getChild(i);
183 return str.getChild(0).getText();
191 * Parse 'description', 'reference' and 'status' statements and fill in
197 * builder to fill in with parsed statements
199 public static void parseSchemaNodeArgs(final ParseTree ctx, final SchemaNodeBuilder builder) {
200 for (int i = 0; i < ctx.getChildCount(); i++) {
201 final ParseTree child = ctx.getChild(i);
202 if (child instanceof Description_stmtContext) {
203 final String desc = stringFromNode(child);
204 builder.setDescription(desc);
205 } else if (child instanceof Reference_stmtContext) {
206 final String ref = stringFromNode(child);
207 builder.setReference(ref);
208 } else if (child instanceof Status_stmtContext) {
209 final Status status = parseStatus((Status_stmtContext) child);
210 builder.setStatus(status);
216 * Parse given context and return its value;
220 * @return value parsed from context
222 public static Status parseStatus(final Status_stmtContext ctx) {
223 Status result = null;
224 for (int i = 0; i < ctx.getChildCount(); i++) {
225 ParseTree statusArg = ctx.getChild(i);
226 if (statusArg instanceof Status_argContext) {
227 String statusArgStr = stringFromNode(statusArg);
228 switch (statusArgStr) {
230 result = Status.CURRENT;
233 result = Status.DEPRECATED;
236 result = Status.OBSOLETE;
239 LOG.warn("Invalid 'status' statement: " + statusArgStr);
247 * Parse given tree and returns units statement as string.
251 * @return value of units statement as string or null if there is no units
254 public static String parseUnits(final ParseTree ctx) {
256 for (int i = 0; i < ctx.getChildCount(); i++) {
257 ParseTree child = ctx.getChild(i);
258 if (child instanceof Units_stmtContext) {
259 units = stringFromNode(child);
267 * Parse given tree and returns default statement as string.
271 * @return value of default statement as string or null if there is no
274 public static String parseDefault(final ParseTree ctx) {
275 String defaultValue = null;
276 for (int i = 0; i < ctx.getChildCount(); i++) {
277 ParseTree child = ctx.getChild(i);
278 if (child instanceof Default_stmtContext) {
279 defaultValue = stringFromNode(child);
287 * Create SchemaPath from actualPath and new node name.
290 * current position in model
291 * @return SchemaPath object
293 public static SchemaPath createActualSchemaPath(final Stack<QName> actualPath) {
294 return SchemaPath.create(actualPath, true);
298 * Create java.util.List of key node names.
301 * Key_stmtContext context
302 * @return YANG list key as java.util.List of key node names
304 public static List<String> createListKey(final Key_stmtContext ctx) {
305 String keyDefinition = stringFromNode(ctx);
306 List<String> keys = new ArrayList<>();
307 String[] splittedKey = keyDefinition.split(" ");
308 for (String keyElement : splittedKey) {
309 if (!keyElement.isEmpty()) {
310 keys.add(keyElement);
317 * Parse given type body of enumeration statement.
320 * type body context to parse
322 * actual position in YANG model
324 * current module name
325 * @return List of EnumPair object parsed from given context
327 private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
328 final Stack<QName> path, final String moduleName) {
329 List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<>();
331 for (int i = 0; i < ctx.getChildCount(); i++) {
332 ParseTree enumSpecChild = ctx.getChild(i);
333 if (enumSpecChild instanceof Enum_specificationContext) {
334 int highestValue = -1;
335 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
336 ParseTree enumChild = enumSpecChild.getChild(j);
337 if (enumChild instanceof Enum_stmtContext) {
338 EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName);
339 if (enumPair.getValue() > highestValue) {
340 highestValue = enumPair.getValue();
342 enumConstants.add(enumPair);
347 return enumConstants;
351 * Parse enum statement context
354 * enum statement context
355 * @param highestValue
356 * current highest value in enumeration
358 * actual position in YANG model
360 * current module name
361 * @return EnumPair object parsed from given context
363 private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
364 final Stack<QName> actualPath, final String moduleName) {
365 final String name = stringFromNode(ctx);
366 SchemaPath path = createTypePath(actualPath, name);
367 Integer value = null;
369 String description = null;
370 String reference = null;
371 Status status = null;
373 for (int i = 0; i < ctx.getChildCount(); i++) {
374 ParseTree child = ctx.getChild(i);
375 if (child instanceof Value_stmtContext) {
376 String valueStr = stringFromNode(child);
377 value = Integer.valueOf(valueStr);
378 } else if (child instanceof Description_stmtContext) {
379 description = stringFromNode(child);
380 } else if (child instanceof Reference_stmtContext) {
381 reference = stringFromNode(child);
382 } else if (child instanceof Status_stmtContext) {
383 status = parseStatus((Status_stmtContext) child);
388 value = highestValue + 1;
390 if (value < -2147483648 || value > 2147483647) {
391 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on enum '" + name
392 + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: " + value);
395 EnumPairImpl result = new EnumPairImpl();
396 result.qname = path.getPath().get(path.getPath().size() - 1);
398 result.description = description;
399 result.reference = reference;
400 result.status = status;
402 result.value = value;
407 * Internal implementation of EnumPair.
409 private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
411 private SchemaPath path;
412 private String description;
413 private String reference;
414 private Status status;
415 private final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
417 private Integer value;
420 public QName getQName() {
425 public SchemaPath getPath() {
430 public String getDescription() {
435 public String getReference() {
440 public Status getStatus() {
445 public List<UnknownSchemaNode> getUnknownSchemaNodes() {
450 public String getName() {
455 public Integer getValue() {
460 public int hashCode() {
461 final int prime = 31;
463 result = prime * result + ((qname == null) ? 0 : qname.hashCode());
464 result = prime * result + ((path == null) ? 0 : path.hashCode());
465 result = prime * result + ((unknownNodes == null) ? 0 : unknownNodes.hashCode());
466 result = prime * result + ((name == null) ? 0 : name.hashCode());
467 result = prime * result + ((value == null) ? 0 : value.hashCode());
472 public boolean equals(final Object obj) {
479 if (getClass() != obj.getClass()) {
482 EnumPairImpl other = (EnumPairImpl) obj;
484 if (other.qname != null) {
487 } else if (!qname.equals(other.qname)) {
491 if (other.path != null) {
494 } else if (!path.equals(other.path)) {
497 if (unknownNodes == null) {
498 if (other.unknownNodes != null) {
501 } else if (!unknownNodes.equals(other.unknownNodes)) {
505 if (other.name != null) {
508 } else if (!name.equals(other.name)) {
512 if (other.value != null) {
515 } else if (!value.equals(other.value)) {
522 public String toString() {
523 return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
528 * Get and parse range from given type body context.
531 * type body context to parse
533 * name of current module
534 * @return List of RangeConstraint created from this context
536 private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
537 List<RangeConstraint> rangeConstraints = Collections.emptyList();
538 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
539 ParseTree numRestrChild = ctx.getChild(i);
541 if (numRestrChild instanceof Numerical_restrictionsContext) {
542 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
543 ParseTree rangeChild = numRestrChild.getChild(j);
544 if (rangeChild instanceof Range_stmtContext) {
545 rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
551 if (numRestrChild instanceof Decimal64_specificationContext) {
552 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
553 ParseTree decRestr = numRestrChild.getChild(j);
554 if (decRestr instanceof Numerical_restrictionsContext) {
555 for (int k = 0; k < decRestr.getChildCount(); k++) {
556 ParseTree rangeChild = decRestr.getChild(k);
557 if (rangeChild instanceof Range_stmtContext) {
558 rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
567 return rangeConstraints;
571 * Parse given range context.
574 * range context to parse
576 * name of current module
577 * @return List of RangeConstraints parsed from this context
579 private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx, final String moduleName) {
580 final int line = ctx.getStart().getLine();
581 List<RangeConstraint> rangeConstraints = new ArrayList<>();
582 String description = null;
583 String reference = null;
585 for (int i = 0; i < ctx.getChildCount(); i++) {
586 ParseTree child = ctx.getChild(i);
587 if (child instanceof Description_stmtContext) {
588 description = stringFromNode(child);
589 } else if (child instanceof Reference_stmtContext) {
590 reference = stringFromNode(child);
594 String rangeStr = stringFromNode(ctx);
595 String trimmed = rangeStr.replace(" ", "");
596 String[] splittedRange = trimmed.split("\\|");
597 for (String rangeDef : splittedRange) {
598 String[] splittedRangeDef = rangeDef.split("\\.\\.");
601 if (splittedRangeDef.length == 1) {
602 min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
604 min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
605 max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
607 RangeConstraint range = BaseConstraints.rangeConstraint(min, max, description, reference);
608 rangeConstraints.add(range);
611 return rangeConstraints;
615 * Get and parse length from given type body context.
618 * type body context to parse
620 * name of current module
621 * @return List of LengthConstraint created from this context
623 private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
624 List<LengthConstraint> lengthConstraints = Collections.emptyList();
625 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
626 ParseTree stringRestrChild = ctx.getChild(i);
627 if (stringRestrChild instanceof String_restrictionsContext) {
628 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
629 ParseTree lengthChild = stringRestrChild.getChild(j);
630 if (lengthChild instanceof Length_stmtContext) {
631 lengthConstraints = parseLengthConstraints((Length_stmtContext) lengthChild, moduleName);
637 return lengthConstraints;
641 * Parse given length context.
644 * length context to parse
646 * name of current module
647 * @return List of LengthConstraints parsed from this context
649 private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx, final String moduleName) {
650 final int line = ctx.getStart().getLine();
651 List<LengthConstraint> lengthConstraints = new ArrayList<>();
652 String description = null;
653 String reference = null;
655 for (int i = 0; i < ctx.getChildCount(); i++) {
656 ParseTree child = ctx.getChild(i);
657 if (child instanceof Description_stmtContext) {
658 description = stringFromNode(child);
659 } else if (child instanceof Reference_stmtContext) {
660 reference = stringFromNode(child);
664 String lengthStr = stringFromNode(ctx);
665 String trimmed = lengthStr.replace(" ", "");
666 String[] splittedRange = trimmed.split("\\|");
667 for (String rangeDef : splittedRange) {
668 String[] splittedRangeDef = rangeDef.split("\\.\\.");
671 if (splittedRangeDef.length == 1) {
672 min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
674 min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
675 max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
677 LengthConstraint range = BaseConstraints.lengthConstraint(min, max, description, reference);
678 lengthConstraints.add(range);
681 return lengthConstraints;
688 * name of current module
690 * current line in module
691 * @return wrapper object of primitive java type or UnknownBoundaryNumber if
692 * type is one of special YANG values 'min' or 'max'
694 private static Number parseNumberConstraintValue(final String value, final String moduleName, final int line) {
696 if ("min".equals(value) || "max".equals(value)) {
697 result = new UnknownBoundaryNumber(value);
700 if (value.contains(".")) {
701 result = new BigDecimal(value);
703 result = Long.valueOf(value);
705 } catch (NumberFormatException e) {
706 throw new YangParseException(moduleName, line, "Unable to parse range value '" + value + "'.", e);
713 * Parse type body and return pattern constraints.
717 * @return list of pattern constraints
719 private static List<PatternConstraint> getPatternConstraint(final Type_body_stmtsContext ctx) {
720 List<PatternConstraint> patterns = new ArrayList<>();
722 for (int i = 0; i < ctx.getChildCount(); i++) {
723 ParseTree stringRestrChild = ctx.getChild(i);
724 if (stringRestrChild instanceof String_restrictionsContext) {
725 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
726 ParseTree lengthChild = stringRestrChild.getChild(j);
727 if (lengthChild instanceof Pattern_stmtContext) {
728 patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
737 * Internal helper method.
741 * @return PatternConstraint object
743 private static PatternConstraint parsePatternConstraint(final Pattern_stmtContext ctx) {
744 String description = null;
745 String reference = null;
746 for (int i = 0; i < ctx.getChildCount(); i++) {
747 ParseTree child = ctx.getChild(i);
748 if (child instanceof Description_stmtContext) {
749 description = stringFromNode(child);
750 } else if (child instanceof Reference_stmtContext) {
751 reference = stringFromNode(child);
754 String pattern = parsePatternString(ctx);
755 return BaseConstraints.patternConstraint(pattern, description, reference);
759 * Parse given context and return pattern value.
763 * @return pattern value as String
765 private static String parsePatternString(final Pattern_stmtContext ctx) {
766 StringBuilder result = new StringBuilder();
767 for (int i = 0; i < ctx.getChildCount(); ++i) {
768 ParseTree child = ctx.getChild(i);
769 if (child instanceof StringContext) {
770 for (int j = 0; j < child.getChildCount(); j++) {
772 String patternToken = child.getChild(j).getText();
773 result.append(patternToken.substring(1, patternToken.length() - 1));
778 return result.toString();
782 * Get fraction digits value from type body.
785 * type body context to parse
787 * name of current module
788 * @return 'fraction-digits' value if present in given context, null
791 private static Integer getFractionDigits(final Type_body_stmtsContext ctx, final String moduleName) {
792 Integer result = null;
793 for (int i = 0; i < ctx.getChildCount(); i++) {
794 ParseTree dec64specChild = ctx.getChild(i);
795 if (dec64specChild instanceof Decimal64_specificationContext) {
796 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild, moduleName);
803 * Parse decimal64 fraction-digits value.
808 * name of current module
809 * @return fraction-digits value as Integer
811 private static Integer parseFractionDigits(final Decimal64_specificationContext ctx, final String moduleName) {
812 Integer result = null;
813 for (int i = 0; i < ctx.getChildCount(); i++) {
814 ParseTree fdChild = ctx.getChild(i);
815 if (fdChild instanceof Fraction_digits_stmtContext) {
816 String value = stringFromNode(fdChild);
818 result = Integer.valueOf(value);
819 } catch (NumberFormatException e) {
820 throw new YangParseException(moduleName, ctx.getStart().getLine(),
821 "Unable to parse fraction digits value '" + value + "'.", e);
829 * Internal helper method for parsing bit statements from given type body
833 * type body context to parse
835 * current position in YANG model
837 * current module name
838 * @return List of Bit objects created from this context
840 private static List<BitsTypeDefinition.Bit> getBits(final Type_body_stmtsContext ctx, final Stack<QName> actualPath,
841 final String moduleName) {
842 final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
843 for (int j = 0; j < ctx.getChildCount(); j++) {
844 ParseTree bitsSpecChild = ctx.getChild(j);
845 if (bitsSpecChild instanceof Bits_specificationContext) {
846 long highestPosition = -1;
847 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
848 ParseTree bitChild = bitsSpecChild.getChild(k);
849 if (bitChild instanceof Bit_stmtContext) {
850 Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, moduleName);
851 if (bit.getPosition() > highestPosition) {
852 highestPosition = bit.getPosition();
863 * Internal helper method for parsing bit context.
866 * bit statement context to parse
867 * @param highestPosition
868 * current highest position in bits type
870 * current position in YANG model
872 * current module name
873 * @return Bit object parsed from this context
875 private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, final long highestPosition,
876 final Stack<QName> actualPath, final String moduleName) {
877 String name = stringFromNode(ctx);
878 Long position = null;
880 String description = null;
881 String reference = null;
882 Status status = Status.CURRENT;
884 SchemaPath schemaPath = createBaseTypePath(actualPath, name);
886 for (int i = 0; i < ctx.getChildCount(); i++) {
887 ParseTree child = ctx.getChild(i);
888 if (child instanceof Position_stmtContext) {
889 String positionStr = stringFromNode(child);
890 position = Long.valueOf(positionStr);
891 } else if (child instanceof Description_stmtContext) {
892 description = stringFromNode(child);
893 } else if (child instanceof Reference_stmtContext) {
894 reference = stringFromNode(child);
895 } else if (child instanceof Status_stmtContext) {
896 status = parseStatus((Status_stmtContext) child);
900 if (position == null) {
901 position = highestPosition + 1;
903 if (position < 0 || position > 4294967295L) {
904 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on bit '" + name
905 + "': the position value MUST be in the range 0 to 4294967295");
908 final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
909 return new BitImpl(position, schemaPath.getPath().get(schemaPath.getPath().size() - 1), schemaPath,
910 description, reference, status, unknownNodes);
914 * Parse 'ordered-by' statement.
916 * The 'ordered-by' statement defines whether the order of entries within a
917 * list are determined by the user or the system. The argument is one of the
918 * strings "system" or "user". If not present, order defaults to "system".
921 * Ordered_by_stmtContext
922 * @return true, if ordered-by contains value 'user', false otherwise
924 public static boolean parseUserOrdered(final Ordered_by_stmtContext ctx) {
925 boolean result = false;
926 for (int j = 0; j < ctx.getChildCount(); j++) {
927 ParseTree orderArg = ctx.getChild(j);
928 if (orderArg instanceof Ordered_by_argContext) {
929 String orderStr = stringFromNode(orderArg);
938 LOG.warn("Invalid 'ordered-by' statement.");
946 * Get config statement from given context. If there is no config statement,
947 * return config value of parent
954 * name of current module
956 * line in current module
957 * @return config statement parsed from given context
959 public static boolean getConfig(final ParseTree ctx, final Builder node, final String moduleName, final int line) {
961 // parse configuration statement
962 Boolean config = null;
963 for (int i = 0; i < ctx.getChildCount(); i++) {
964 ParseTree child = ctx.getChild(i);
965 if (child instanceof Config_stmtContext) {
966 config = parseConfig((Config_stmtContext) child, moduleName);
971 // If 'config' is not specified, the default is the same as the parent
972 // schema node's 'config' value
973 boolean parentConfig = getParentConfig(node);
974 if (config == null) {
975 result = parentConfig;
977 // Check: if a node has 'config' set to 'false', no node underneath
978 // it can have 'config' set to 'true'
979 if (!parentConfig && config) {
980 throw new YangParseException(moduleName, line,
981 "Can not set 'config' to 'true' if parent node has 'config' set to 'false'");
989 private static boolean getParentConfig(final Builder node) {
990 Builder parent = node.getParent();
991 boolean config = false;
993 if (parent instanceof ChoiceCaseBuilder) {
994 parent = parent.getParent();
996 if (parent instanceof DataSchemaNodeBuilder) {
997 config = ((DataSchemaNodeBuilder) parent).isConfiguration();
1005 * Parse config statement.
1008 * config context to parse
1010 * current module name
1011 * @return true if given context contains string 'true', false otherwise
1013 private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
1014 Boolean result = null;
1016 for (int i = 0; i < ctx.getChildCount(); ++i) {
1017 final ParseTree configContext = ctx.getChild(i);
1018 if (configContext instanceof Config_argContext) {
1019 final String value = stringFromNode(configContext);
1028 throw new YangParseException(moduleName, ctx.getStart().getLine(),
1029 "Failed to parse 'config' statement value: '" + value + "'.");
1038 * Parse type body and create UnknownType definition.
1040 * @param typedefQName
1041 * qname of current type
1045 * actual path in model
1053 * current node parent
1054 * @return UnknownType object with constraints from parsed type body
1056 public static TypeDefinition<?> parseUnknownTypeWithBody(final QName typedefQName,
1057 final Type_body_stmtsContext ctx, final Stack<QName> actualPath, final URI namespace, final Date revision,
1058 final String prefix, final Builder parent) {
1059 String moduleName = parent.getModuleName();
1060 String typeName = typedefQName.getLocalName();
1062 UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
1065 List<RangeConstraint> rangeStatements = getRangeConstraints(ctx, moduleName);
1066 List<LengthConstraint> lengthStatements = getLengthConstraints(ctx, moduleName);
1067 List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
1068 Integer fractionDigits = getFractionDigits(ctx, moduleName);
1070 if (parent instanceof TypeDefinitionBuilder) {
1071 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1072 typedef.setRanges(rangeStatements);
1073 typedef.setLengths(lengthStatements);
1074 typedef.setPatterns(patternStatements);
1075 typedef.setFractionDigits(fractionDigits);
1076 return unknownType.build();
1078 TypeDefinition<?> baseType = unknownType.build();
1079 QName qname = new QName(namespace, revision, prefix, typeName);
1080 SchemaPath schemaPath = createTypePath(actualPath, typeName);
1082 ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, null, null, schemaPath);
1083 typeBuilder.ranges(rangeStatements);
1084 typeBuilder.lengths(lengthStatements);
1085 typeBuilder.patterns(patternStatements);
1086 typeBuilder.fractionDigits(fractionDigits);
1088 return typeBuilder.build();
1092 return unknownType.build();
1096 * Create TypeDefinition object based on given type name and type body.
1103 * current path in schema
1112 * @return TypeDefinition object based on parsed values.
1114 public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1115 final Stack<QName> actualPath, final URI namespace, final Date revision, final String prefix,
1116 final Builder parent) {
1118 final String moduleName = parent.getModuleName();
1119 final int line = typeBody.getStart().getLine();
1120 TypeDefinition<?> baseType = null;
1122 Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1123 List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1124 List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1125 List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1127 TypeConstraints constraints = new TypeConstraints(moduleName, line);
1128 constraints.addFractionDigits(fractionDigits);
1129 constraints.addLengths(lengthStatements);
1130 constraints.addPatterns(patternStatements);
1131 constraints.addRanges(rangeStatements);
1133 SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1134 SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, namespace, revision, prefix, typeName);
1136 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1137 extBaseTypePath = baseTypePath;
1140 if ("decimal64".equals(typeName)) {
1141 if (rangeStatements.isEmpty()) {
1143 return new Decimal64(baseTypePath, fractionDigits);
1144 } catch(Exception e) {
1145 throw new YangParseException(moduleName, line, e.getMessage());
1148 Decimal64 decimalType = new Decimal64(extBaseTypePath, fractionDigits);
1149 constraints.addRanges(decimalType.getRangeConstraints());
1150 baseType = decimalType;
1151 } else if (typeName.startsWith("int")) {
1152 IntegerTypeDefinition intType = null;
1155 intType = Int8.getInstance();
1158 intType = Int16.getInstance();
1161 intType = Int32.getInstance();
1164 intType = Int64.getInstance();
1167 if (intType == null) {
1168 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1170 constraints.addRanges(intType.getRangeConstraints());
1172 } else if (typeName.startsWith("uint")) {
1173 UnsignedIntegerTypeDefinition uintType = null;
1176 uintType = Uint8.getInstance();
1179 uintType = Uint16.getInstance();
1182 uintType = Uint32.getInstance();
1185 uintType = Uint64.getInstance();
1188 if (uintType == null) {
1189 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1191 constraints.addRanges(uintType.getRangeConstraints());
1192 baseType = uintType;
1193 } else if ("enumeration".equals(typeName)) {
1194 List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1195 return new EnumerationType(baseTypePath, enumConstants);
1196 } else if ("string".equals(typeName)) {
1197 StringTypeDefinition stringType = StringType.getInstance();
1198 constraints.addLengths(stringType.getLengthConstraints());
1199 baseType = stringType;
1200 } else if ("bits".equals(typeName)) {
1201 return new BitsType(baseTypePath, getBits(typeBody, actualPath, moduleName));
1202 } else if ("leafref".equals(typeName)) {
1203 final String path = parseLeafrefPath(typeBody);
1204 final boolean absolute = path.startsWith("/");
1205 RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1206 return new Leafref(xpath);
1207 } else if ("binary".equals(typeName)) {
1208 BinaryTypeDefinition binaryType = BinaryType.getInstance();
1209 constraints.addLengths(binaryType.getLengthConstraints());
1210 baseType = binaryType;
1211 } else if ("instance-identifier".equals(typeName)) {
1212 boolean requireInstance = isRequireInstance(typeBody);
1213 return new InstanceIdentifier(null, requireInstance);
1216 if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1217 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1218 typedef.setRanges(constraints.getRange());
1219 typedef.setLengths(constraints.getLength());
1220 typedef.setPatterns(constraints.getPatterns());
1221 typedef.setFractionDigits(constraints.getFractionDigits());
1225 List<QName> path = new ArrayList<>(actualPath);
1226 path.add(new QName(namespace, revision, prefix, typeName));
1227 SchemaPath schemaPath = SchemaPath.create(path, true);
1229 QName qname = schemaPath.getPath().get(schemaPath.getPath().size() - 1);
1230 ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
1232 typeBuilder.ranges(constraints.getRange());
1233 typeBuilder.lengths(constraints.getLength());
1234 typeBuilder.patterns(constraints.getPatterns());
1235 typeBuilder.fractionDigits(constraints.getFractionDigits());
1237 return typeBuilder.build();
1240 private static SchemaPath createTypePath(final Stack<QName> actual, final String typeName) {
1241 QName last = actual.peek();
1242 QName typeQName = new QName(last.getNamespace(), last.getRevision(), last.getPrefix(), typeName);
1243 List<QName> path = new ArrayList<>(actual);
1244 path.add(typeQName);
1245 return SchemaPath.create(path, true);
1248 private static SchemaPath createBaseTypePath(final Stack<QName> actual, final String typeName) {
1249 List<QName> path = new ArrayList<>(actual);
1250 path.add(BaseTypes.constructQName(typeName));
1251 return SchemaPath.create(path, true);
1254 private static SchemaPath createExtendedBaseTypePath(final Stack<QName> actual, final URI namespace, final Date revision,
1255 final String prefix, final String typeName) {
1256 QName extTypeName = new QName(namespace, revision, prefix, typeName);
1257 QName baseTypeName = BaseTypes.constructQName(typeName);
1258 List<QName> path = new ArrayList<>(actual);
1259 path.add(extTypeName);
1260 path.add(baseTypeName);
1261 return SchemaPath.create(path, true);
1265 * Parse given context and find identityref base value.
1269 * @return identityref base value as String
1271 public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
1272 String result = null;
1273 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1274 ParseTree child = ctx.getChild(i);
1275 if (child instanceof Identityref_specificationContext) {
1276 for (int j = 0; j < child.getChildCount(); j++) {
1277 ParseTree baseArg = child.getChild(j);
1278 if (baseArg instanceof Base_stmtContext) {
1279 result = stringFromNode(baseArg);
1289 * Parse type body statement and find require-instance value.
1293 * @return require-instance value
1295 private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
1296 for (int i = 0; i < ctx.getChildCount(); i++) {
1297 ParseTree child = ctx.getChild(i);
1298 if (child instanceof Instance_identifier_specificationContext) {
1299 for (int j = 0; j < child.getChildCount(); j++) {
1300 ParseTree reqStmt = child.getChild(j);
1301 if (reqStmt instanceof Require_instance_stmtContext) {
1302 for (int k = 0; k < reqStmt.getChildCount(); k++) {
1303 ParseTree reqArg = reqStmt.getChild(k);
1304 if (reqArg instanceof Require_instance_argContext) {
1305 return Boolean.valueOf(stringFromNode(reqArg));
1316 * Parse type body statement and find leafref path.
1320 * @return leafref path as String
1322 private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
1323 for (int i = 0; i < ctx.getChildCount(); i++) {
1324 ParseTree child = ctx.getChild(i);
1325 if (child instanceof Leafref_specificationContext) {
1326 for (int j = 0; j < child.getChildCount(); j++) {
1327 ParseTree leafRefSpec = child.getChild(j);
1328 if (leafRefSpec instanceof Path_stmtContext) {
1329 return stringFromNode(leafRefSpec);
1338 * Internal helper method for parsing must statement.
1342 * @return MustDefinition object based on parsed context
1344 public static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1345 StringBuilder mustText = new StringBuilder();
1346 String description = null;
1347 String reference = null;
1348 String errorAppTag = null;
1349 String errorMessage = null;
1350 for (int i = 0; i < ctx.getChildCount(); ++i) {
1351 ParseTree child = ctx.getChild(i);
1352 if (child instanceof StringContext) {
1353 final StringContext context = (StringContext) child;
1354 if (context.getChildCount() == 1) {
1355 String mustPart = context.getChild(0).getText();
1356 // trim start and end quotation
1357 mustText.append(mustPart.substring(1, mustPart.length() - 1));
1359 for (int j = 0; j < context.getChildCount(); j++) {
1360 String mustPart = context.getChild(j).getText();
1362 mustText.append(mustPart.substring(0, mustPart.length() - 1));
1366 mustText.append(mustPart.substring(1));
1370 } else if (child instanceof Description_stmtContext) {
1371 description = stringFromNode(child);
1372 } else if (child instanceof Reference_stmtContext) {
1373 reference = stringFromNode(child);
1374 } else if (child instanceof Error_app_tag_stmtContext) {
1375 errorAppTag = stringFromNode(child);
1376 } else if (child instanceof Error_message_stmtContext) {
1377 errorMessage = stringFromNode(child);
1381 return new MustDefinitionImpl(mustText.toString(), description, reference, errorAppTag, errorMessage);
1385 * Parse given context and set constraints to constraints builder.
1389 * @param constraints
1390 * ConstraintsBuilder to fill
1392 public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1393 for (int i = 0; i < ctx.getChildCount(); ++i) {
1394 final ParseTree childNode = ctx.getChild(i);
1395 if (childNode instanceof Max_elements_stmtContext) {
1396 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1397 constraints.setMaxElements(max);
1398 } else if (childNode instanceof Min_elements_stmtContext) {
1399 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1400 constraints.setMinElements(min);
1401 } else if (childNode instanceof Must_stmtContext) {
1402 MustDefinition must = parseMust((Must_stmtContext) childNode);
1403 constraints.addMustDefinition(must);
1404 } else if (childNode instanceof Mandatory_stmtContext) {
1405 for (int j = 0; j < childNode.getChildCount(); j++) {
1406 ParseTree mandatoryTree = childNode.getChild(j);
1407 if (mandatoryTree instanceof Mandatory_argContext) {
1408 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1409 constraints.setMandatory(mandatory);
1412 } else if (childNode instanceof When_stmtContext) {
1413 constraints.addWhenCondition(stringFromNode(childNode));
1418 private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1419 Integer result = null;
1421 for (int i = 0; i < ctx.getChildCount(); i++) {
1422 ParseTree minArg = ctx.getChild(i);
1423 if (minArg instanceof Min_value_argContext) {
1424 result = Integer.valueOf(stringFromNode(minArg));
1427 if (result == null) {
1428 throw new IllegalArgumentException();
1431 } catch (Exception e) {
1432 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1436 private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1437 Integer result = null;
1439 for (int i = 0; i < ctx.getChildCount(); i++) {
1440 ParseTree maxArg = ctx.getChild(i);
1441 if (maxArg instanceof Max_value_argContext) {
1442 result = Integer.valueOf(stringFromNode(maxArg));
1445 if (result == null) {
1446 throw new IllegalArgumentException();
1449 } catch (Exception e) {
1450 throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1455 * Parse given context and return yin value.
1459 * @return true if value is 'true', false otherwise
1461 public static boolean parseYinValue(final Argument_stmtContext ctx) {
1462 boolean yinValue = false;
1463 outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1464 ParseTree yin = ctx.getChild(i);
1465 if (yin instanceof Yin_element_stmtContext) {
1466 for (int j = 0; j < yin.getChildCount(); j++) {
1467 ParseTree yinArg = yin.getChild(j);
1468 if (yinArg instanceof Yin_element_argContext) {
1469 String yinString = stringFromNode(yinArg);
1470 if ("true".equals(yinString)) {
1482 * Check this base type.
1485 * base YANG type name
1487 * name of current module
1490 * @throws YangParseException
1491 * if this is one of YANG type which MUST contain additional
1492 * informations in its body
1494 public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1497 throw new YangParseException(moduleName, line,
1498 "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1500 throw new YangParseException(moduleName, line,
1501 "The 'base' statement MUST be present if the type is 'identityref'.");
1503 throw new YangParseException(moduleName, line,
1504 "The 'path' statement MUST be present if the type is 'leafref'.");
1506 throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1508 throw new YangParseException(moduleName, line,
1509 "The 'enum' statement MUST be present if the type is 'enumeration'.");
1514 * Parse refine statement.
1519 * name of current module
1520 * @return RefineHolder object representing this refine statement
1522 public static RefineHolder parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
1523 final String refineTarget = stringFromNode(refineCtx);
1524 final RefineHolder refine = new RefineHolder(moduleName, refineCtx.getStart().getLine(), refineTarget);
1525 for (int i = 0; i < refineCtx.getChildCount(); i++) {
1526 ParseTree refinePom = refineCtx.getChild(i);
1527 if (refinePom instanceof Refine_pomContext) {
1528 for (int j = 0; j < refinePom.getChildCount(); j++) {
1529 ParseTree refineStmt = refinePom.getChild(j);
1530 parseRefineDefault(refine, refineStmt);
1532 if (refineStmt instanceof Refine_leaf_stmtsContext) {
1533 parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1534 } else if (refineStmt instanceof Refine_container_stmtsContext) {
1535 parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1536 } else if (refineStmt instanceof Refine_list_stmtsContext) {
1537 parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1538 } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1539 parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1540 } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1541 parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1542 } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1543 parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1551 private static void parseRefineDefault(final RefineHolder refine, final ParseTree refineStmt) {
1552 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1553 ParseTree refineArg = refineStmt.getChild(i);
1554 if (refineArg instanceof Description_stmtContext) {
1555 String description = stringFromNode(refineArg);
1556 refine.setDescription(description);
1557 } else if (refineArg instanceof Reference_stmtContext) {
1558 String reference = stringFromNode(refineArg);
1559 refine.setReference(reference);
1560 } else if (refineArg instanceof Config_stmtContext) {
1561 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1562 refine.setConfiguration(config);
1567 private static RefineHolder parseRefine(final RefineHolder refine, final Refine_leaf_stmtsContext refineStmt) {
1568 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1569 ParseTree refineArg = refineStmt.getChild(i);
1570 if (refineArg instanceof Default_stmtContext) {
1571 String defaultStr = stringFromNode(refineArg);
1572 refine.setDefaultStr(defaultStr);
1573 } else if (refineArg instanceof Mandatory_stmtContext) {
1574 for (int j = 0; j < refineArg.getChildCount(); j++) {
1575 ParseTree mandatoryTree = refineArg.getChild(j);
1576 if (mandatoryTree instanceof Mandatory_argContext) {
1577 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1578 refine.setMandatory(mandatory);
1581 } else if (refineArg instanceof Must_stmtContext) {
1582 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1583 refine.setMust(must);
1590 private static RefineHolder parseRefine(final RefineHolder refine, final Refine_container_stmtsContext refineStmt) {
1591 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1592 ParseTree refineArg = refineStmt.getChild(i);
1593 if (refineArg instanceof Must_stmtContext) {
1594 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1595 refine.setMust(must);
1596 } else if (refineArg instanceof Presence_stmtContext) {
1597 refine.setPresence(true);
1603 private static RefineHolder parseRefine(final RefineHolder refine, final Refine_list_stmtsContext refineStmt) {
1604 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1605 ParseTree refineArg = refineStmt.getChild(i);
1606 if (refineArg instanceof Must_stmtContext) {
1607 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1608 refine.setMust(must);
1609 } else if (refineArg instanceof Max_elements_stmtContext) {
1610 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1611 refine.setMaxElements(max);
1612 } else if (refineArg instanceof Min_elements_stmtContext) {
1613 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1614 refine.setMinElements(min);
1620 private static RefineHolder parseRefine(final RefineHolder refine, final Refine_leaf_list_stmtsContext refineStmt) {
1621 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1622 ParseTree refineArg = refineStmt.getChild(i);
1623 if (refineArg instanceof Must_stmtContext) {
1624 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1625 refine.setMust(must);
1626 } else if (refineArg instanceof Max_elements_stmtContext) {
1627 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1628 refine.setMaxElements(max);
1629 } else if (refineArg instanceof Min_elements_stmtContext) {
1630 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1631 refine.setMinElements(min);
1637 private static RefineHolder parseRefine(final RefineHolder refine, final Refine_choice_stmtsContext refineStmt) {
1638 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1639 ParseTree refineArg = refineStmt.getChild(i);
1640 if (refineArg instanceof Default_stmtContext) {
1641 String defaultStr = stringFromNode(refineArg);
1642 refine.setDefaultStr(defaultStr);
1643 } else if (refineArg instanceof Mandatory_stmtContext) {
1644 for (int j = 0; j < refineArg.getChildCount(); j++) {
1645 ParseTree mandatoryTree = refineArg.getChild(j);
1646 if (mandatoryTree instanceof Mandatory_argContext) {
1647 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1648 refine.setMandatory(mandatory);
1656 private static RefineHolder parseRefine(final RefineHolder refine, final Refine_anyxml_stmtsContext refineStmt) {
1657 for (int i = 0; i < refineStmt.getChildCount(); i++) {
1658 ParseTree refineArg = refineStmt.getChild(i);
1659 if (refineArg instanceof Must_stmtContext) {
1660 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1661 refine.setMust(must);
1662 } else if (refineArg instanceof Mandatory_stmtContext) {
1663 for (int j = 0; j < refineArg.getChildCount(); j++) {
1664 ParseTree mandatoryTree = refineArg.getChild(j);
1665 if (mandatoryTree instanceof Mandatory_argContext) {
1666 Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1667 refine.setMandatory(mandatory);
1675 public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
1676 List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1677 checkState(!potentialValues.isEmpty());
1678 return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1681 public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
1682 List<T> potential = context.getRuleContexts(contextType);
1683 if(potential.isEmpty()) {
1684 return Optional.absent();
1686 return Optional.of(potential.get(0));