c4e79e6710388bf1e2401e8c91e89f90c798f0c2
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / util / ParserListenerUtils.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.util;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import java.math.BigDecimal;
13 import java.net.URI;
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;
19
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;
127
128 import com.google.common.base.Optional;
129
130 public final class ParserListenerUtils {
131     private static final Logger LOG = LoggerFactory.getLogger(ParserListenerUtils.class);
132
133     private ParserListenerUtils() {
134     }
135
136     /**
137      * Parse given tree and get first string value.
138      *
139      * @param treeNode
140      *            tree to parse
141      * @return first string value from given tree
142      */
143     public static String stringFromNode(final ParseTree treeNode) {
144         String result = "";
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);
150
151                 }
152             }
153         }
154         return result;
155     }
156
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("\"")){
162                 str.append(result);
163             } else if (!(result.startsWith("\"")) && result.endsWith("\"")) {
164                 LOG.error("Syntax error in module {} at line {}: missing '\"'.", getParentModule(context),
165                         context.getStart().getLine());
166             } else {
167                 str.append(result.replace("\"", ""));
168             }
169         }
170         return str.toString();
171     }
172
173     private static String getParentModule(final ParseTree ctx) {
174         ParseTree current = ctx;
175         while (current != null && !(current instanceof Module_stmtContext)) {
176             current = current.getParent();
177         }
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();
184                 }
185             }
186         }
187         return "";
188     }
189
190     /**
191      * Parse 'description', 'reference' and 'status' statements and fill in
192      * given builder.
193      *
194      * @param ctx
195      *            context to parse
196      * @param builder
197      *            builder to fill in with parsed statements
198      */
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);
211             }
212         }
213     }
214
215     /**
216      * Parse given context and return its value;
217      *
218      * @param ctx
219      *            status context
220      * @return value parsed from context
221      */
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) {
229                 case "current":
230                     result = Status.CURRENT;
231                     break;
232                 case "deprecated":
233                     result = Status.DEPRECATED;
234                     break;
235                 case "obsolete":
236                     result = Status.OBSOLETE;
237                     break;
238                 default:
239                     LOG.warn("Invalid 'status' statement: " + statusArgStr);
240                 }
241             }
242         }
243         return result;
244     }
245
246     /**
247      * Parse given tree and returns units statement as string.
248      *
249      * @param ctx
250      *            context to parse
251      * @return value of units statement as string or null if there is no units
252      *         statement
253      */
254     public static String parseUnits(final ParseTree ctx) {
255         String units = null;
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);
260                 break;
261             }
262         }
263         return units;
264     }
265
266     /**
267      * Parse given tree and returns default statement as string.
268      *
269      * @param ctx
270      *            context to parse
271      * @return value of default statement as string or null if there is no
272      *         default statement
273      */
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);
280                 break;
281             }
282         }
283         return defaultValue;
284     }
285
286     /**
287      * Create SchemaPath from actualPath and new node name.
288      *
289      * @param actualPath
290      *            current position in model
291      * @return SchemaPath object
292      */
293     public static SchemaPath createActualSchemaPath(final Stack<QName> actualPath) {
294         return SchemaPath.create(actualPath, true);
295     }
296
297     /**
298      * Create java.util.List of key node names.
299      *
300      * @param ctx
301      *            Key_stmtContext context
302      * @return YANG list key as java.util.List of key node names
303      */
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);
311             }
312         }
313         return keys;
314     }
315
316     /**
317      * Parse given type body of enumeration statement.
318      *
319      * @param ctx
320      *            type body context to parse
321      * @param path
322      *            actual position in YANG model
323      * @param moduleName
324      *            current module name
325      * @return List of EnumPair object parsed from given context
326      */
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<>();
330
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();
341                         }
342                         enumConstants.add(enumPair);
343                     }
344                 }
345             }
346         }
347         return enumConstants;
348     }
349
350     /**
351      * Parse enum statement context
352      *
353      * @param ctx
354      *            enum statement context
355      * @param highestValue
356      *            current highest value in enumeration
357      * @param actualPath
358      *            actual position in YANG model
359      * @param moduleName
360      *            current module name
361      * @return EnumPair object parsed from given context
362      */
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;
368
369         String description = null;
370         String reference = null;
371         Status status = null;
372
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);
384             }
385         }
386
387         if (value == null) {
388             value = highestValue + 1;
389         }
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);
393         }
394
395         EnumPairImpl result = new EnumPairImpl();
396         result.qname = path.getPath().get(path.getPath().size() - 1);
397         result.path = path;
398         result.description = description;
399         result.reference = reference;
400         result.status = status;
401         result.name = name;
402         result.value = value;
403         return result;
404     }
405
406     /**
407      * Internal implementation of EnumPair.
408      */
409     private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
410         private QName qname;
411         private SchemaPath path;
412         private String description;
413         private String reference;
414         private Status status;
415         private final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
416         private String name;
417         private Integer value;
418
419         @Override
420         public QName getQName() {
421             return qname;
422         }
423
424         @Override
425         public SchemaPath getPath() {
426             return path;
427         }
428
429         @Override
430         public String getDescription() {
431             return description;
432         }
433
434         @Override
435         public String getReference() {
436             return reference;
437         }
438
439         @Override
440         public Status getStatus() {
441             return status;
442         }
443
444         @Override
445         public List<UnknownSchemaNode> getUnknownSchemaNodes() {
446             return unknownNodes;
447         }
448
449         @Override
450         public String getName() {
451             return name;
452         }
453
454         @Override
455         public Integer getValue() {
456             return value;
457         }
458
459         @Override
460         public int hashCode() {
461             final int prime = 31;
462             int result = 1;
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());
468             return result;
469         }
470
471         @Override
472         public boolean equals(final Object obj) {
473             if (this == obj) {
474                 return true;
475             }
476             if (obj == null) {
477                 return false;
478             }
479             if (getClass() != obj.getClass()) {
480                 return false;
481             }
482             EnumPairImpl other = (EnumPairImpl) obj;
483             if (qname == null) {
484                 if (other.qname != null) {
485                     return false;
486                 }
487             } else if (!qname.equals(other.qname)) {
488                 return false;
489             }
490             if (path == null) {
491                 if (other.path != null) {
492                     return false;
493                 }
494             } else if (!path.equals(other.path)) {
495                 return false;
496             }
497             if (unknownNodes == null) {
498                 if (other.unknownNodes != null) {
499                     return false;
500                 }
501             } else if (!unknownNodes.equals(other.unknownNodes)) {
502                 return false;
503             }
504             if (name == null) {
505                 if (other.name != null) {
506                     return false;
507                 }
508             } else if (!name.equals(other.name)) {
509                 return false;
510             }
511             if (value == null) {
512                 if (other.value != null) {
513                     return false;
514                 }
515             } else if (!value.equals(other.value)) {
516                 return false;
517             }
518             return true;
519         }
520
521         @Override
522         public String toString() {
523             return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
524         }
525     }
526
527     /**
528      * Get and parse range from given type body context.
529      *
530      * @param ctx
531      *            type body context to parse
532      * @param moduleName
533      *            name of current module
534      * @return List of RangeConstraint created from this context
535      */
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);
540
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);
546                         break outer;
547                     }
548                 }
549             }
550
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);
559                                 break outer;
560                             }
561                         }
562
563                     }
564                 }
565             }
566         }
567         return rangeConstraints;
568     }
569
570     /**
571      * Parse given range context.
572      *
573      * @param ctx
574      *            range context to parse
575      * @param moduleName
576      *            name of current module
577      * @return List of RangeConstraints parsed from this context
578      */
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;
584
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);
591             }
592         }
593
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("\\.\\.");
599             Number min;
600             Number max;
601             if (splittedRangeDef.length == 1) {
602                 min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
603             } else {
604                 min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
605                 max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
606             }
607             RangeConstraint range = BaseConstraints.rangeConstraint(min, max, description, reference);
608             rangeConstraints.add(range);
609         }
610
611         return rangeConstraints;
612     }
613
614     /**
615      * Get and parse length from given type body context.
616      *
617      * @param ctx
618      *            type body context to parse
619      * @param moduleName
620      *            name of current module
621      * @return List of LengthConstraint created from this context
622      */
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);
632                         break outer;
633                     }
634                 }
635             }
636         }
637         return lengthConstraints;
638     }
639
640     /**
641      * Parse given length context.
642      *
643      * @param ctx
644      *            length context to parse
645      * @param moduleName
646      *            name of current module
647      * @return List of LengthConstraints parsed from this context
648      */
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;
654
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);
661             }
662         }
663
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("\\.\\.");
669             Number min;
670             Number max;
671             if (splittedRangeDef.length == 1) {
672                 min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
673             } else {
674                 min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
675                 max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
676             }
677             LengthConstraint range = BaseConstraints.lengthConstraint(min, max, description, reference);
678             lengthConstraints.add(range);
679         }
680
681         return lengthConstraints;
682     }
683
684     /**
685      * @param value
686      *            value to parse
687      * @param moduleName
688      *            name of current module
689      * @param line
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'
693      */
694     private static Number parseNumberConstraintValue(final String value, final String moduleName, final int line) {
695         Number result;
696         if ("min".equals(value) || "max".equals(value)) {
697             result = new UnknownBoundaryNumber(value);
698         } else {
699             try {
700                 if (value.contains(".")) {
701                     result = new BigDecimal(value);
702                 } else {
703                     result = Long.valueOf(value);
704                 }
705             } catch (NumberFormatException e) {
706                 throw new YangParseException(moduleName, line, "Unable to parse range value '" + value + "'.", e);
707             }
708         }
709         return result;
710     }
711
712     /**
713      * Parse type body and return pattern constraints.
714      *
715      * @param ctx
716      *            type body
717      * @return list of pattern constraints
718      */
719     private static List<PatternConstraint> getPatternConstraint(final Type_body_stmtsContext ctx) {
720         List<PatternConstraint> patterns = new ArrayList<>();
721
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));
729                     }
730                 }
731             }
732         }
733         return patterns;
734     }
735
736     /**
737      * Internal helper method.
738      *
739      * @param ctx
740      *            pattern context
741      * @return PatternConstraint object
742      */
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);
752             }
753         }
754         String pattern = parsePatternString(ctx);
755         return BaseConstraints.patternConstraint(pattern, description, reference);
756     }
757
758     /**
759      * Parse given context and return pattern value.
760      *
761      * @param ctx
762      *            context to parse
763      * @return pattern value as String
764      */
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++) {
771                     if (j % 2 == 0) {
772                         String patternToken = child.getChild(j).getText();
773                         result.append(patternToken.substring(1, patternToken.length() - 1));
774                     }
775                 }
776             }
777         }
778         return result.toString();
779     }
780
781     /**
782      * Get fraction digits value from type body.
783      *
784      * @param ctx
785      *            type body context to parse
786      * @param moduleName
787      *            name of current module
788      * @return 'fraction-digits' value if present in given context, null
789      *         otherwise
790      */
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);
797             }
798         }
799         return result;
800     }
801
802     /**
803      * Parse decimal64 fraction-digits value.
804      *
805      * @param ctx
806      *            decimal64 context
807      * @param moduleName
808      *            name of current module
809      * @return fraction-digits value as Integer
810      */
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);
817                 try {
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);
822                 }
823             }
824         }
825         return result;
826     }
827
828     /**
829      * Internal helper method for parsing bit statements from given type body
830      * context.
831      *
832      * @param ctx
833      *            type body context to parse
834      * @param actualPath
835      *            current position in YANG model
836      * @param moduleName
837      *            current module name
838      * @return List of Bit objects created from this context
839      */
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();
853                         }
854                         bits.add(bit);
855                     }
856                 }
857             }
858         }
859         return bits;
860     }
861
862     /**
863      * Internal helper method for parsing bit context.
864      *
865      * @param ctx
866      *            bit statement context to parse
867      * @param highestPosition
868      *            current highest position in bits type
869      * @param actualPath
870      *            current position in YANG model
871      * @param moduleName
872      *            current module name
873      * @return Bit object parsed from this context
874      */
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;
879
880         String description = null;
881         String reference = null;
882         Status status = Status.CURRENT;
883
884         SchemaPath schemaPath = createBaseTypePath(actualPath, name);
885
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);
897             }
898         }
899
900         if (position == null) {
901             position = highestPosition + 1;
902         }
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");
906         }
907
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);
911     }
912
913     /**
914      * Parse 'ordered-by' statement.
915      *
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".
919      *
920      * @param ctx
921      *            Ordered_by_stmtContext
922      * @return true, if ordered-by contains value 'user', false otherwise
923      */
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);
930                 switch (orderStr) {
931                 case "system":
932                     result = false;
933                     break;
934                 case "user":
935                     result = true;
936                     break;
937                 default:
938                     LOG.warn("Invalid 'ordered-by' statement.");
939                 }
940             }
941         }
942         return result;
943     }
944
945     /**
946      * Get config statement from given context. If there is no config statement,
947      * return config value of parent
948      *
949      * @param ctx
950      *            context to parse
951      * @param node
952      *            current node
953      * @param moduleName
954      *            name of current module
955      * @param line
956      *            line in current module
957      * @return config statement parsed from given context
958      */
959     public static boolean getConfig(final ParseTree ctx, final Builder node, final String moduleName, final int line) {
960         boolean result;
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);
967                 break;
968             }
969         }
970
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;
976         } else {
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'");
982             }
983             result = config;
984         }
985
986         return result;
987     }
988
989     private static boolean getParentConfig(final Builder node) {
990         Builder parent = node.getParent();
991         boolean config = false;
992
993         if (parent instanceof ChoiceCaseBuilder) {
994             parent = parent.getParent();
995         }
996         if (parent instanceof DataSchemaNodeBuilder) {
997             config = ((DataSchemaNodeBuilder) parent).isConfiguration();
998         } else {
999             config = true;
1000         }
1001         return config;
1002     }
1003
1004     /**
1005      * Parse config statement.
1006      *
1007      * @param ctx
1008      *            config context to parse
1009      * @param moduleName
1010      *            current module name
1011      * @return true if given context contains string 'true', false otherwise
1012      */
1013     private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
1014         Boolean result = null;
1015         if (ctx != 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);
1020                     switch (value) {
1021                     case "true":
1022                         result = true;
1023                         break;
1024                     case "false":
1025                         result = false;
1026                         break;
1027                     default:
1028                         throw new YangParseException(moduleName, ctx.getStart().getLine(),
1029                                 "Failed to parse 'config' statement value: '" + value + "'.");
1030                     }
1031                 }
1032             }
1033         }
1034         return result;
1035     }
1036
1037     /**
1038      * Parse type body and create UnknownType definition.
1039      *
1040      * @param typedefQName
1041      *            qname of current type
1042      * @param ctx
1043      *            type body
1044      * @param actualPath
1045      *            actual path in model
1046      * @param namespace
1047      *            module namespace
1048      * @param revision
1049      *            module revision
1050      * @param prefix
1051      *            module prefix
1052      * @param parent
1053      *            current node parent
1054      * @return UnknownType object with constraints from parsed type body
1055      */
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();
1061
1062         UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
1063
1064         if (ctx != null) {
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);
1069
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();
1077             } else {
1078                 TypeDefinition<?> baseType = unknownType.build();
1079                 QName qname = new QName(namespace, revision, prefix, typeName);
1080                 SchemaPath schemaPath = createTypePath(actualPath, typeName);
1081
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);
1087
1088                 return typeBuilder.build();
1089             }
1090         }
1091
1092         return unknownType.build();
1093     }
1094
1095     /**
1096      * Create TypeDefinition object based on given type name and type body.
1097      *
1098      * @param typeName
1099      *            name of type
1100      * @param typeBody
1101      *            type body context
1102      * @param actualPath
1103      *            current path in schema
1104      * @param namespace
1105      *            current namespace
1106      * @param revision
1107      *            current revision
1108      * @param prefix
1109      *            current prefix
1110      * @param parent
1111      *            parent builder
1112      * @return TypeDefinition object based on parsed values.
1113      */
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) {
1117
1118         final String moduleName = parent.getModuleName();
1119         final int line = typeBody.getStart().getLine();
1120         TypeDefinition<?> baseType = null;
1121
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);
1126
1127         TypeConstraints constraints = new TypeConstraints(moduleName, line);
1128         constraints.addFractionDigits(fractionDigits);
1129         constraints.addLengths(lengthStatements);
1130         constraints.addPatterns(patternStatements);
1131         constraints.addRanges(rangeStatements);
1132
1133         SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1134         SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, namespace, revision, prefix, typeName);
1135
1136         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1137             extBaseTypePath = baseTypePath;
1138         }
1139
1140         if ("decimal64".equals(typeName)) {
1141             if (rangeStatements.isEmpty()) {
1142                 try {
1143                     return new Decimal64(baseTypePath, fractionDigits);
1144                 } catch(Exception e) {
1145                     throw new YangParseException(moduleName, line, e.getMessage());
1146                 }
1147             }
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;
1153             switch (typeName) {
1154             case "int8":
1155                 intType = Int8.getInstance();
1156                 break;
1157             case "int16":
1158                 intType = Int16.getInstance();
1159                 break;
1160             case "int32":
1161                 intType = Int32.getInstance();
1162                 break;
1163             case "int64":
1164                 intType = Int64.getInstance();
1165                 break;
1166             }
1167             if (intType == null) {
1168                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1169             }
1170             constraints.addRanges(intType.getRangeConstraints());
1171             baseType = intType;
1172         } else if (typeName.startsWith("uint")) {
1173             UnsignedIntegerTypeDefinition uintType = null;
1174             switch (typeName) {
1175             case "uint8":
1176                 uintType = Uint8.getInstance();
1177                 break;
1178             case "uint16":
1179                 uintType = Uint16.getInstance();
1180                 break;
1181             case "uint32":
1182                 uintType = Uint32.getInstance();
1183                 break;
1184             case "uint64":
1185                 uintType = Uint64.getInstance();
1186                 break;
1187             }
1188             if (uintType == null) {
1189                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1190             }
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);
1214         }
1215
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());
1222             return baseType;
1223         }
1224
1225         List<QName> path = new ArrayList<>(actualPath);
1226         path.add(new QName(namespace, revision, prefix, typeName));
1227         SchemaPath schemaPath = SchemaPath.create(path, true);
1228
1229         QName qname = schemaPath.getPath().get(schemaPath.getPath().size() - 1);
1230         ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
1231
1232         typeBuilder.ranges(constraints.getRange());
1233         typeBuilder.lengths(constraints.getLength());
1234         typeBuilder.patterns(constraints.getPatterns());
1235         typeBuilder.fractionDigits(constraints.getFractionDigits());
1236
1237         return typeBuilder.build();
1238     }
1239
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);
1246     }
1247
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);
1252     }
1253
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);
1262     }
1263
1264     /**
1265      * Parse given context and find identityref base value.
1266      *
1267      * @param ctx
1268      *            type body
1269      * @return identityref base value as String
1270      */
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);
1280                         break outer;
1281                     }
1282                 }
1283             }
1284         }
1285         return result;
1286     }
1287
1288     /**
1289      * Parse type body statement and find require-instance value.
1290      *
1291      * @param ctx
1292      *            type body context
1293      * @return require-instance value
1294      */
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));
1306                             }
1307                         }
1308                     }
1309                 }
1310             }
1311         }
1312         return true;
1313     }
1314
1315     /**
1316      * Parse type body statement and find leafref path.
1317      *
1318      * @param ctx
1319      *            type body context
1320      * @return leafref path as String
1321      */
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);
1330                     }
1331                 }
1332             }
1333         }
1334         return null;
1335     }
1336
1337     /**
1338      * Internal helper method for parsing must statement.
1339      *
1340      * @param ctx
1341      *            Must_stmtContext
1342      * @return MustDefinition object based on parsed context
1343      */
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));
1358                 } else {
1359                     for (int j = 0; j < context.getChildCount(); j++) {
1360                         String mustPart = context.getChild(j).getText();
1361                         if (j == 0) {
1362                             mustText.append(mustPart.substring(0, mustPart.length() - 1));
1363                             continue;
1364                         }
1365                         if (j % 2 == 0) {
1366                             mustText.append(mustPart.substring(1));
1367                         }
1368                     }
1369                 }
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);
1378             }
1379         }
1380
1381         return new MustDefinitionImpl(mustText.toString(), description, reference, errorAppTag, errorMessage);
1382     }
1383
1384     /**
1385      * Parse given context and set constraints to constraints builder.
1386      *
1387      * @param ctx
1388      *            context to parse
1389      * @param constraints
1390      *            ConstraintsBuilder to fill
1391      */
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);
1410                     }
1411                 }
1412             } else if (childNode instanceof When_stmtContext) {
1413                 constraints.addWhenCondition(stringFromNode(childNode));
1414             }
1415         }
1416     }
1417
1418     private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1419         Integer result = null;
1420         try {
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));
1425                 }
1426             }
1427             if (result == null) {
1428                 throw new IllegalArgumentException();
1429             }
1430             return result;
1431         } catch (Exception e) {
1432             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1433         }
1434     }
1435
1436     private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1437         Integer result = null;
1438         try {
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));
1443                 }
1444             }
1445             if (result == null) {
1446                 throw new IllegalArgumentException();
1447             }
1448             return result;
1449         } catch (Exception e) {
1450             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1451         }
1452     }
1453
1454     /**
1455      * Parse given context and return yin value.
1456      *
1457      * @param ctx
1458      *            context to parse
1459      * @return true if value is 'true', false otherwise
1460      */
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)) {
1471                             yinValue = true;
1472                             break outer;
1473                         }
1474                     }
1475                 }
1476             }
1477         }
1478         return yinValue;
1479     }
1480
1481     /**
1482      * Check this base type.
1483      *
1484      * @param typeName
1485      *            base YANG type name
1486      * @param moduleName
1487      *            name of current module
1488      * @param line
1489      *            line in module
1490      * @throws YangParseException
1491      *             if this is one of YANG type which MUST contain additional
1492      *             informations in its body
1493      */
1494     public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1495         switch (typeName) {
1496         case "decimal64":
1497             throw new YangParseException(moduleName, line,
1498                     "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1499         case "identityref":
1500             throw new YangParseException(moduleName, line,
1501                     "The 'base' statement MUST be present if the type is 'identityref'.");
1502         case "leafref":
1503             throw new YangParseException(moduleName, line,
1504                     "The 'path' statement MUST be present if the type is 'leafref'.");
1505         case "bits":
1506             throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1507         case "enumeration":
1508             throw new YangParseException(moduleName, line,
1509                     "The 'enum' statement MUST be present if the type is 'enumeration'.");
1510         }
1511     }
1512
1513     /**
1514      * Parse refine statement.
1515      *
1516      * @param refineCtx
1517      *            refine statement
1518      * @param moduleName
1519      *            name of current module
1520      * @return RefineHolder object representing this refine statement
1521      */
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);
1531
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);
1544                     }
1545                 }
1546             }
1547         }
1548         return refine;
1549     }
1550
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);
1563             }
1564         }
1565     }
1566
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);
1579                     }
1580                 }
1581             } else if (refineArg instanceof Must_stmtContext) {
1582                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1583                 refine.setMust(must);
1584
1585             }
1586         }
1587         return refine;
1588     }
1589
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);
1598             }
1599         }
1600         return refine;
1601     }
1602
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);
1615             }
1616         }
1617         return refine;
1618     }
1619
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);
1632             }
1633         }
1634         return refine;
1635     }
1636
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);
1649                     }
1650                 }
1651             }
1652         }
1653         return refine;
1654     }
1655
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);
1668                     }
1669                 }
1670             }
1671         }
1672         return refine;
1673     }
1674
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));
1679     }
1680
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();
1685         }
1686         return Optional.of(potential.get(0));
1687     }
1688
1689 }