Implemented support for generating YangModuleInfo implementation.
[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.*;
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(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         final List<QName> path = new ArrayList<>(actualPath);
295         return new SchemaPath(path, true);
296     }
297
298     /**
299      * Create java.util.List of key node names.
300      *
301      * @param ctx
302      *            Key_stmtContext context
303      * @return YANG list key as java.util.List of key node names
304      */
305     public static List<String> createListKey(final Key_stmtContext ctx) {
306         String keyDefinition = stringFromNode(ctx);
307         List<String> keys = new ArrayList<>();
308         String[] splittedKey = keyDefinition.split(" ");
309         for (String keyElement : splittedKey) {
310             if (!keyElement.isEmpty()) {
311                 keys.add(keyElement);
312             }
313         }
314         return keys;
315     }
316
317     /**
318      * Parse given type body of enumeration statement.
319      *
320      * @param ctx
321      *            type body context to parse
322      * @param path
323      *            actual position in YANG model
324      * @param moduleName
325      *            current module name
326      * @return List of EnumPair object parsed from given context
327      */
328     private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
329             final Stack<QName> path, final String moduleName) {
330         List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<>();
331
332         for (int i = 0; i < ctx.getChildCount(); i++) {
333             ParseTree enumSpecChild = ctx.getChild(i);
334             if (enumSpecChild instanceof Enum_specificationContext) {
335                 int highestValue = -1;
336                 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
337                     ParseTree enumChild = enumSpecChild.getChild(j);
338                     if (enumChild instanceof Enum_stmtContext) {
339                         EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName);
340                         if (enumPair.getValue() > highestValue) {
341                             highestValue = enumPair.getValue();
342                         }
343                         enumConstants.add(enumPair);
344                     }
345                 }
346             }
347         }
348         return enumConstants;
349     }
350
351     /**
352      * Parse enum statement context
353      *
354      * @param ctx
355      *            enum statement context
356      * @param highestValue
357      *            current highest value in enumeration
358      * @param actualPath
359      *            actual position in YANG model
360      * @param moduleName
361      *            current module name
362      * @return EnumPair object parsed from given context
363      */
364     private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
365             final Stack<QName> actualPath, final String moduleName) {
366         final String name = stringFromNode(ctx);
367         SchemaPath path = createTypePath(actualPath, name);
368         Integer value = null;
369
370         String description = null;
371         String reference = null;
372         Status status = null;
373
374         for (int i = 0; i < ctx.getChildCount(); i++) {
375             ParseTree child = ctx.getChild(i);
376             if (child instanceof Value_stmtContext) {
377                 String valueStr = stringFromNode(child);
378                 value = Integer.valueOf(valueStr);
379             } else if (child instanceof Description_stmtContext) {
380                 description = stringFromNode(child);
381             } else if (child instanceof Reference_stmtContext) {
382                 reference = stringFromNode(child);
383             } else if (child instanceof Status_stmtContext) {
384                 status = parseStatus((Status_stmtContext) child);
385             }
386         }
387
388         if (value == null) {
389             value = highestValue + 1;
390         }
391         if (value < -2147483648 || value > 2147483647) {
392             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on enum '" + name
393                     + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: " + value);
394         }
395
396         EnumPairImpl result = new EnumPairImpl();
397         result.qname = path.getPath().get(path.getPath().size() - 1);
398         result.path = path;
399         result.description = description;
400         result.reference = reference;
401         result.status = status;
402         result.name = name;
403         result.value = value;
404         return result;
405     }
406
407     /**
408      * Internal implementation of EnumPair.
409      */
410     private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
411         private QName qname;
412         private SchemaPath path;
413         private String description;
414         private String reference;
415         private Status status;
416         private List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
417         private String name;
418         private Integer value;
419
420         @Override
421         public QName getQName() {
422             return qname;
423         }
424
425         @Override
426         public SchemaPath getPath() {
427             return path;
428         }
429
430         @Override
431         public String getDescription() {
432             return description;
433         }
434
435         @Override
436         public String getReference() {
437             return reference;
438         }
439
440         @Override
441         public Status getStatus() {
442             return status;
443         }
444
445         @Override
446         public List<UnknownSchemaNode> getUnknownSchemaNodes() {
447             return unknownNodes;
448         }
449
450         @Override
451         public String getName() {
452             return name;
453         }
454
455         @Override
456         public Integer getValue() {
457             return value;
458         }
459
460         @Override
461         public int hashCode() {
462             final int prime = 31;
463             int result = 1;
464             result = prime * result + ((qname == null) ? 0 : qname.hashCode());
465             result = prime * result + ((path == null) ? 0 : path.hashCode());
466             result = prime * result + ((unknownNodes == null) ? 0 : unknownNodes.hashCode());
467             result = prime * result + ((name == null) ? 0 : name.hashCode());
468             result = prime * result + ((value == null) ? 0 : value.hashCode());
469             return result;
470         }
471
472         @Override
473         public boolean equals(Object obj) {
474             if (this == obj) {
475                 return true;
476             }
477             if (obj == null) {
478                 return false;
479             }
480             if (getClass() != obj.getClass()) {
481                 return false;
482             }
483             EnumPairImpl other = (EnumPairImpl) obj;
484             if (qname == null) {
485                 if (other.qname != null) {
486                     return false;
487                 }
488             } else if (!qname.equals(other.qname)) {
489                 return false;
490             }
491             if (path == null) {
492                 if (other.path != null) {
493                     return false;
494                 }
495             } else if (!path.equals(other.path)) {
496                 return false;
497             }
498             if (unknownNodes == null) {
499                 if (other.unknownNodes != null) {
500                     return false;
501                 }
502             } else if (!unknownNodes.equals(other.unknownNodes)) {
503                 return false;
504             }
505             if (name == null) {
506                 if (other.name != null) {
507                     return false;
508                 }
509             } else if (!name.equals(other.name)) {
510                 return false;
511             }
512             if (value == null) {
513                 if (other.value != null) {
514                     return false;
515                 }
516             } else if (!value.equals(other.value)) {
517                 return false;
518             }
519             return true;
520         }
521
522         @Override
523         public String toString() {
524             return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
525         }
526     }
527
528     /**
529      * Get and parse range from given type body context.
530      *
531      * @param ctx
532      *            type body context to parse
533      * @param moduleName
534      *            name of current module
535      * @return List of RangeConstraint created from this context
536      */
537     private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
538         List<RangeConstraint> rangeConstraints = Collections.emptyList();
539         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
540             ParseTree numRestrChild = ctx.getChild(i);
541
542             if (numRestrChild instanceof Numerical_restrictionsContext) {
543                 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
544                     ParseTree rangeChild = numRestrChild.getChild(j);
545                     if (rangeChild instanceof Range_stmtContext) {
546                         rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
547                         break outer;
548                     }
549                 }
550             }
551
552             if (numRestrChild instanceof Decimal64_specificationContext) {
553                 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
554                     ParseTree decRestr = numRestrChild.getChild(j);
555                     if (decRestr instanceof Numerical_restrictionsContext) {
556                         for (int k = 0; k < decRestr.getChildCount(); k++) {
557                             ParseTree rangeChild = decRestr.getChild(k);
558                             if (rangeChild instanceof Range_stmtContext) {
559                                 rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
560                                 break outer;
561                             }
562                         }
563
564                     }
565                 }
566             }
567         }
568         return rangeConstraints;
569     }
570
571     /**
572      * Parse given range context.
573      *
574      * @param ctx
575      *            range context to parse
576      * @param moduleName
577      *            name of current module
578      * @return List of RangeConstraints parsed from this context
579      */
580     private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx, final String moduleName) {
581         final int line = ctx.getStart().getLine();
582         List<RangeConstraint> rangeConstraints = new ArrayList<>();
583         String description = null;
584         String reference = null;
585
586         for (int i = 0; i < ctx.getChildCount(); i++) {
587             ParseTree child = ctx.getChild(i);
588             if (child instanceof Description_stmtContext) {
589                 description = stringFromNode(child);
590             } else if (child instanceof Reference_stmtContext) {
591                 reference = stringFromNode(child);
592             }
593         }
594
595         String rangeStr = stringFromNode(ctx);
596         String trimmed = rangeStr.replace(" ", "");
597         String[] splittedRange = trimmed.split("\\|");
598         for (String rangeDef : splittedRange) {
599             String[] splittedRangeDef = rangeDef.split("\\.\\.");
600             Number min;
601             Number max;
602             if (splittedRangeDef.length == 1) {
603                 min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
604             } else {
605                 min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
606                 max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
607             }
608             RangeConstraint range = BaseConstraints.rangeConstraint(min, max, description, reference);
609             rangeConstraints.add(range);
610         }
611
612         return rangeConstraints;
613     }
614
615     /**
616      * Get and parse length from given type body context.
617      *
618      * @param ctx
619      *            type body context to parse
620      * @param moduleName
621      *            name of current module
622      * @return List of LengthConstraint created from this context
623      */
624     private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
625         List<LengthConstraint> lengthConstraints = Collections.emptyList();
626         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
627             ParseTree stringRestrChild = ctx.getChild(i);
628             if (stringRestrChild instanceof String_restrictionsContext) {
629                 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
630                     ParseTree lengthChild = stringRestrChild.getChild(j);
631                     if (lengthChild instanceof Length_stmtContext) {
632                         lengthConstraints = parseLengthConstraints((Length_stmtContext) lengthChild, moduleName);
633                         break outer;
634                     }
635                 }
636             }
637         }
638         return lengthConstraints;
639     }
640
641     /**
642      * Parse given length context.
643      *
644      * @param ctx
645      *            length context to parse
646      * @param moduleName
647      *            name of current module
648      * @return List of LengthConstraints parsed from this context
649      */
650     private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx, final String moduleName) {
651         final int line = ctx.getStart().getLine();
652         List<LengthConstraint> lengthConstraints = new ArrayList<>();
653         String description = null;
654         String reference = null;
655
656         for (int i = 0; i < ctx.getChildCount(); i++) {
657             ParseTree child = ctx.getChild(i);
658             if (child instanceof Description_stmtContext) {
659                 description = stringFromNode(child);
660             } else if (child instanceof Reference_stmtContext) {
661                 reference = stringFromNode(child);
662             }
663         }
664
665         String lengthStr = stringFromNode(ctx);
666         String trimmed = lengthStr.replace(" ", "");
667         String[] splittedRange = trimmed.split("\\|");
668         for (String rangeDef : splittedRange) {
669             String[] splittedRangeDef = rangeDef.split("\\.\\.");
670             Number min;
671             Number max;
672             if (splittedRangeDef.length == 1) {
673                 min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
674             } else {
675                 min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
676                 max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
677             }
678             LengthConstraint range = BaseConstraints.lengthConstraint(min, max, description, reference);
679             lengthConstraints.add(range);
680         }
681
682         return lengthConstraints;
683     }
684
685     /**
686      * @param value
687      *            value to parse
688      * @param moduleName
689      *            name of current module
690      * @param line
691      *            current line in module
692      * @return wrapper object of primitive java type or UnknownBoundaryNumber if
693      *         type is one of special YANG values 'min' or 'max'
694      */
695     private static Number parseNumberConstraintValue(final String value, final String moduleName, final int line) {
696         Number result;
697         if ("min".equals(value) || "max".equals(value)) {
698             result = new UnknownBoundaryNumber(value);
699         } else {
700             try {
701                 if (value.contains(".")) {
702                     result = new BigDecimal(value);
703                 } else {
704                     result = Long.valueOf(value);
705                 }
706             } catch (NumberFormatException e) {
707                 throw new YangParseException(moduleName, line, "Unable to parse range value '" + value + "'.", e);
708             }
709         }
710         return result;
711     }
712
713     /**
714      * Parse type body and return pattern constraints.
715      *
716      * @param ctx
717      *            type body
718      * @return list of pattern constraints
719      */
720     private static List<PatternConstraint> getPatternConstraint(final Type_body_stmtsContext ctx) {
721         List<PatternConstraint> patterns = new ArrayList<>();
722
723         for (int i = 0; i < ctx.getChildCount(); i++) {
724             ParseTree stringRestrChild = ctx.getChild(i);
725             if (stringRestrChild instanceof String_restrictionsContext) {
726                 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
727                     ParseTree lengthChild = stringRestrChild.getChild(j);
728                     if (lengthChild instanceof Pattern_stmtContext) {
729                         patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
730                     }
731                 }
732             }
733         }
734         return patterns;
735     }
736
737     /**
738      * Internal helper method.
739      *
740      * @param ctx
741      *            pattern context
742      * @return PatternConstraint object
743      */
744     private static PatternConstraint parsePatternConstraint(final Pattern_stmtContext ctx) {
745         String description = null;
746         String reference = null;
747         for (int i = 0; i < ctx.getChildCount(); i++) {
748             ParseTree child = ctx.getChild(i);
749             if (child instanceof Description_stmtContext) {
750                 description = stringFromNode(child);
751             } else if (child instanceof Reference_stmtContext) {
752                 reference = stringFromNode(child);
753             }
754         }
755         String pattern = parsePatternString(ctx);
756         return BaseConstraints.patternConstraint(pattern, description, reference);
757     }
758
759     /**
760      * Parse given context and return pattern value.
761      *
762      * @param ctx
763      *            context to parse
764      * @return pattern value as String
765      */
766     private static String parsePatternString(final Pattern_stmtContext ctx) {
767         StringBuilder result = new StringBuilder();
768         for (int i = 0; i < ctx.getChildCount(); ++i) {
769             ParseTree child = ctx.getChild(i);
770             if (child instanceof StringContext) {
771                 for (int j = 0; j < child.getChildCount(); j++) {
772                     if (j % 2 == 0) {
773                         String patternToken = child.getChild(j).getText();
774                         result.append(patternToken.substring(1, patternToken.length() - 1));
775                     }
776                 }
777             }
778         }
779         return result.toString();
780     }
781
782     /**
783      * Get fraction digits value from type body.
784      *
785      * @param ctx
786      *            type body context to parse
787      * @param moduleName
788      *            name of current module
789      * @return 'fraction-digits' value if present in given context, null
790      *         otherwise
791      */
792     private static Integer getFractionDigits(Type_body_stmtsContext ctx, String moduleName) {
793         Integer result = null;
794         for (int i = 0; i < ctx.getChildCount(); i++) {
795             ParseTree dec64specChild = ctx.getChild(i);
796             if (dec64specChild instanceof Decimal64_specificationContext) {
797                 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild, moduleName);
798             }
799         }
800         return result;
801     }
802
803     /**
804      * Parse decimal64 fraction-digits value.
805      *
806      * @param ctx
807      *            decimal64 context
808      * @param moduleName
809      *            name of current module
810      * @return fraction-digits value as Integer
811      */
812     private static Integer parseFractionDigits(Decimal64_specificationContext ctx, String moduleName) {
813         Integer result = null;
814         for (int i = 0; i < ctx.getChildCount(); i++) {
815             ParseTree fdChild = ctx.getChild(i);
816             if (fdChild instanceof Fraction_digits_stmtContext) {
817                 String value = stringFromNode(fdChild);
818                 try {
819                     result = Integer.valueOf(value);
820                 } catch (NumberFormatException e) {
821                     throw new YangParseException(moduleName, ctx.getStart().getLine(),
822                             "Unable to parse fraction digits value '" + value + "'.", e);
823                 }
824             }
825         }
826         return result;
827     }
828
829     /**
830      * Internal helper method for parsing bit statements from given type body
831      * context.
832      *
833      * @param ctx
834      *            type body context to parse
835      * @param actualPath
836      *            current position in YANG model
837      * @param moduleName
838      *            current module name
839      * @return List of Bit objects created from this context
840      */
841     private static List<BitsTypeDefinition.Bit> getBits(Type_body_stmtsContext ctx, Stack<QName> actualPath,
842             String moduleName) {
843         final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
844         for (int j = 0; j < ctx.getChildCount(); j++) {
845             ParseTree bitsSpecChild = ctx.getChild(j);
846             if (bitsSpecChild instanceof Bits_specificationContext) {
847                 long highestPosition = -1;
848                 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
849                     ParseTree bitChild = bitsSpecChild.getChild(k);
850                     if (bitChild instanceof Bit_stmtContext) {
851                         Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, moduleName);
852                         if (bit.getPosition() > highestPosition) {
853                             highestPosition = bit.getPosition();
854                         }
855                         bits.add(bit);
856                     }
857                 }
858             }
859         }
860         return bits;
861     }
862
863     /**
864      * Internal helper method for parsing bit context.
865      *
866      * @param ctx
867      *            bit statement context to parse
868      * @param highestPosition
869      *            current highest position in bits type
870      * @param actualPath
871      *            current position in YANG model
872      * @param moduleName
873      *            current module name
874      * @return Bit object parsed from this context
875      */
876     private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, long highestPosition,
877             Stack<QName> actualPath, final String moduleName) {
878         String name = stringFromNode(ctx);
879         Long position = null;
880
881         String description = null;
882         String reference = null;
883         Status status = Status.CURRENT;
884
885         SchemaPath schemaPath = createBaseTypePath(actualPath, name);
886
887         for (int i = 0; i < ctx.getChildCount(); i++) {
888             ParseTree child = ctx.getChild(i);
889             if (child instanceof Position_stmtContext) {
890                 String positionStr = stringFromNode(child);
891                 position = Long.valueOf(positionStr);
892             } else if (child instanceof Description_stmtContext) {
893                 description = stringFromNode(child);
894             } else if (child instanceof Reference_stmtContext) {
895                 reference = stringFromNode(child);
896             } else if (child instanceof Status_stmtContext) {
897                 status = parseStatus((Status_stmtContext) child);
898             }
899         }
900
901         if (position == null) {
902             position = highestPosition + 1;
903         }
904         if (position < 0 || position > 4294967295L) {
905             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on bit '" + name
906                     + "': the position value MUST be in the range 0 to 4294967295");
907         }
908
909         final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
910         return new BitImpl(position, schemaPath.getPath().get(schemaPath.getPath().size() - 1), schemaPath,
911                 description, reference, status, unknownNodes);
912     }
913
914     /**
915      * Parse 'ordered-by' statement.
916      *
917      * The 'ordered-by' statement defines whether the order of entries within a
918      * list are determined by the user or the system. The argument is one of the
919      * strings "system" or "user". If not present, order defaults to "system".
920      *
921      * @param ctx
922      *            Ordered_by_stmtContext
923      * @return true, if ordered-by contains value 'user', false otherwise
924      */
925     public static boolean parseUserOrdered(Ordered_by_stmtContext ctx) {
926         boolean result = false;
927         for (int j = 0; j < ctx.getChildCount(); j++) {
928             ParseTree orderArg = ctx.getChild(j);
929             if (orderArg instanceof Ordered_by_argContext) {
930                 String orderStr = stringFromNode(orderArg);
931                 switch (orderStr) {
932                 case "system":
933                     result = false;
934                     break;
935                 case "user":
936                     result = true;
937                     break;
938                 default:
939                     LOG.warn("Invalid 'ordered-by' statement.");
940                 }
941             }
942         }
943         return result;
944     }
945
946     /**
947      * Get config statement from given context. If there is no config statement,
948      * return config value of parent
949      *
950      * @param ctx
951      *            context to parse
952      * @param parent
953      *            parent node
954      * @param moduleName
955      *            name of current module
956      * @param line
957      *            line in current module
958      * @return config statement parsed from given context
959      */
960     public static Boolean getConfig(final ParseTree ctx, final Builder parent, final String moduleName, final int line) {
961         Boolean result;
962         // parse configuration statement
963         Boolean config = null;
964         for (int i = 0; i < ctx.getChildCount(); i++) {
965             ParseTree child = ctx.getChild(i);
966             if (child instanceof Config_stmtContext) {
967                 config = parseConfig((Config_stmtContext) child, moduleName);
968                 break;
969             }
970         }
971
972         // If 'config' is not specified, the default is the same as the parent
973         // schema node's 'config' value
974         if (config == null) {
975             if (parent instanceof DataSchemaNodeBuilder) {
976                 Boolean parentConfig = ((DataSchemaNodeBuilder) parent).isConfiguration();
977                 // If the parent node is a rpc input or output, it can has
978                 // config set to null
979                 result = parentConfig == null ? true : parentConfig;
980             } else {
981                 result = true;
982             }
983         } else {
984             // Check first: if a node has 'config' set to 'false', no node
985             // underneath it can have 'config' set to 'true'
986             if (parent instanceof DataSchemaNodeBuilder && !(parent instanceof ChoiceCaseBuilder)) {
987                 Boolean parentConfig = ((DataSchemaNodeBuilder) parent).isConfiguration();
988                 if (!parentConfig && config) {
989                     throw new YangParseException(moduleName, line,
990                             "Can not set 'config' to 'true' if parent node has 'config' set to 'false'");
991                 }
992             }
993             result = config;
994         }
995
996         return result;
997     }
998
999     /**
1000      * Parse config statement.
1001      *
1002      * @param ctx
1003      *            config context to parse
1004      * @param moduleName
1005      *            current module name
1006      * @return true if given context contains string 'true', false otherwise
1007      */
1008     private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
1009         Boolean result = null;
1010         if (ctx != null) {
1011             for (int i = 0; i < ctx.getChildCount(); ++i) {
1012                 final ParseTree configContext = ctx.getChild(i);
1013                 if (configContext instanceof Config_argContext) {
1014                     final String value = stringFromNode(configContext);
1015                     switch (value) {
1016                     case "true":
1017                         result = true;
1018                         break;
1019                     case "false":
1020                         result = false;
1021                         break;
1022                     default:
1023                         throw new YangParseException(moduleName, ctx.getStart().getLine(),
1024                                 "Failed to parse 'config' statement value: '" + value + "'.");
1025                     }
1026                 }
1027             }
1028         }
1029         return result;
1030     }
1031
1032     /**
1033      * Parse type body and create UnknownType definition.
1034      *
1035      * @param typedefQName
1036      *            qname of current type
1037      * @param ctx
1038      *            type body
1039      * @param actualPath
1040      *            actual path in model
1041      * @param namespace
1042      *            module namespace
1043      * @param revision
1044      *            module revision
1045      * @param prefix
1046      *            module prefix
1047      * @param parent
1048      *            current node parent
1049      * @return UnknownType object with constraints from parsed type body
1050      */
1051     public static TypeDefinition<?> parseUnknownTypeWithBody(final QName typedefQName,
1052             final Type_body_stmtsContext ctx, final Stack<QName> actualPath, final URI namespace, final Date revision,
1053             final String prefix, final Builder parent) {
1054         String moduleName = parent.getModuleName();
1055         String typeName = typedefQName.getLocalName();
1056
1057         UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
1058
1059         if (ctx != null) {
1060             List<RangeConstraint> rangeStatements = getRangeConstraints(ctx, moduleName);
1061             List<LengthConstraint> lengthStatements = getLengthConstraints(ctx, moduleName);
1062             List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
1063             Integer fractionDigits = getFractionDigits(ctx, moduleName);
1064
1065             if (parent instanceof TypeDefinitionBuilder) {
1066                 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1067                 typedef.setRanges(rangeStatements);
1068                 typedef.setLengths(lengthStatements);
1069                 typedef.setPatterns(patternStatements);
1070                 typedef.setFractionDigits(fractionDigits);
1071                 return unknownType.build();
1072             } else {
1073                 TypeDefinition<?> baseType = unknownType.build();
1074                 QName qname = new QName(namespace, revision, prefix, typeName);
1075                 SchemaPath schemaPath = createTypePath(actualPath, typeName);
1076
1077                 ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, null, null, schemaPath);
1078                 typeBuilder.ranges(rangeStatements);
1079                 typeBuilder.lengths(lengthStatements);
1080                 typeBuilder.patterns(patternStatements);
1081                 typeBuilder.fractionDigits(fractionDigits);
1082
1083                 return typeBuilder.build();
1084             }
1085         }
1086
1087         return unknownType.build();
1088     }
1089
1090     /**
1091      * Create TypeDefinition object based on given type name and type body.
1092      *
1093      * @param typeName
1094      *            name of type
1095      * @param typeBody
1096      *            type body context
1097      * @param actualPath
1098      *            current path in schema
1099      * @param namespace
1100      *            current namespace
1101      * @param revision
1102      *            current revision
1103      * @param prefix
1104      *            current prefix
1105      * @param parent
1106      *            parent builder
1107      * @return TypeDefinition object based on parsed values.
1108      */
1109     public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1110             final Stack<QName> actualPath, final URI namespace, final Date revision, final String prefix,
1111             final Builder parent) {
1112
1113         final String moduleName = parent.getModuleName();
1114         final int line = typeBody.getStart().getLine();
1115         TypeDefinition<?> baseType = null;
1116
1117         Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1118         List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1119         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1120         List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1121
1122         TypeConstraints constraints = new TypeConstraints(moduleName, line);
1123         constraints.addFractionDigits(fractionDigits);
1124         constraints.addLengths(lengthStatements);
1125         constraints.addPatterns(patternStatements);
1126         constraints.addRanges(rangeStatements);
1127
1128         SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1129         SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, namespace, revision, prefix, typeName);
1130
1131         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1132             extBaseTypePath = baseTypePath;
1133         }
1134
1135         if ("decimal64".equals(typeName)) {
1136             if (rangeStatements.isEmpty()) {
1137                 try {
1138                     return new Decimal64(baseTypePath, fractionDigits);
1139                 } catch(Exception e) {
1140                     throw new YangParseException(moduleName, line, e.getMessage());
1141                 }
1142             }
1143             Decimal64 decimalType = new Decimal64(extBaseTypePath, fractionDigits);
1144             constraints.addRanges(decimalType.getRangeConstraints());
1145             baseType = decimalType;
1146         } else if (typeName.startsWith("int")) {
1147             IntegerTypeDefinition intType = null;
1148             switch (typeName) {
1149             case "int8":
1150                 intType = Int8.getInstance();
1151                 break;
1152             case "int16":
1153                 intType = Int16.getInstance();
1154                 break;
1155             case "int32":
1156                 intType = Int32.getInstance();
1157                 break;
1158             case "int64":
1159                 intType = Int64.getInstance();
1160                 break;
1161             }
1162             if (intType == null) {
1163                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1164             }
1165             constraints.addRanges(intType.getRangeConstraints());
1166             baseType = intType;
1167         } else if (typeName.startsWith("uint")) {
1168             UnsignedIntegerTypeDefinition uintType = null;
1169             switch (typeName) {
1170             case "uint8":
1171                 uintType = Uint8.getInstance();
1172                 break;
1173             case "uint16":
1174                 uintType = Uint16.getInstance();
1175                 break;
1176             case "uint32":
1177                 uintType = Uint32.getInstance();
1178                 break;
1179             case "uint64":
1180                 uintType = Uint64.getInstance();
1181                 break;
1182             }
1183             if (uintType == null) {
1184                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1185             }
1186             constraints.addRanges(uintType.getRangeConstraints());
1187             baseType = uintType;
1188         } else if ("enumeration".equals(typeName)) {
1189             List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1190             return new EnumerationType(baseTypePath, enumConstants);
1191         } else if ("string".equals(typeName)) {
1192             StringTypeDefinition stringType = StringType.getInstance();
1193             constraints.addLengths(stringType.getLengthConstraints());
1194             baseType = stringType;
1195         } else if ("bits".equals(typeName)) {
1196             return new BitsType(baseTypePath, getBits(typeBody, actualPath, moduleName));
1197         } else if ("leafref".equals(typeName)) {
1198             final String path = parseLeafrefPath(typeBody);
1199             final boolean absolute = path.startsWith("/");
1200             RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1201             return new Leafref(xpath);
1202         } else if ("binary".equals(typeName)) {
1203             BinaryTypeDefinition binaryType = BinaryType.getInstance();
1204             constraints.addLengths(binaryType.getLengthConstraints());
1205             baseType = binaryType;
1206         } else if ("instance-identifier".equals(typeName)) {
1207             boolean requireInstance = isRequireInstance(typeBody);
1208             return new InstanceIdentifier(null, requireInstance);
1209         }
1210
1211         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1212             TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1213             typedef.setRanges(constraints.getRange());
1214             typedef.setLengths(constraints.getLength());
1215             typedef.setPatterns(constraints.getPatterns());
1216             typedef.setFractionDigits(constraints.getFractionDigits());
1217             return baseType;
1218         }
1219
1220         List<QName> path = new ArrayList<>(actualPath);
1221         path.add(new QName(namespace, revision, prefix, typeName));
1222         SchemaPath schemaPath = new SchemaPath(path, true);
1223
1224         QName qname = schemaPath.getPath().get(schemaPath.getPath().size() - 1);
1225         ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
1226
1227         typeBuilder.ranges(constraints.getRange());
1228         typeBuilder.lengths(constraints.getLength());
1229         typeBuilder.patterns(constraints.getPatterns());
1230         typeBuilder.fractionDigits(constraints.getFractionDigits());
1231
1232         return typeBuilder.build();
1233     }
1234
1235     private static SchemaPath createTypePath(Stack<QName> actual, String typeName) {
1236         QName last = actual.peek();
1237         QName typeQName = new QName(last.getNamespace(), last.getRevision(), last.getPrefix(), typeName);
1238         List<QName> path = new ArrayList<>(actual);
1239         path.add(typeQName);
1240         return new SchemaPath(path, true);
1241     }
1242
1243     private static SchemaPath createBaseTypePath(Stack<QName> actual, String typeName) {
1244         List<QName> path = new ArrayList<>(actual);
1245         path.add(BaseTypes.constructQName(typeName));
1246         return new SchemaPath(path, true);
1247     }
1248
1249     private static SchemaPath createExtendedBaseTypePath(Stack<QName> actual, URI namespace, Date revision,
1250             String prefix, String typeName) {
1251         QName extTypeName = new QName(namespace, revision, prefix, typeName);
1252         QName baseTypeName = BaseTypes.constructQName(typeName);
1253         List<QName> path = new ArrayList<>(actual);
1254         path.add(extTypeName);
1255         path.add(baseTypeName);
1256         return new SchemaPath(path, true);
1257     }
1258
1259     /**
1260      * Parse given context and find identityref base value.
1261      *
1262      * @param ctx
1263      *            type body
1264      * @return identityref base value as String
1265      */
1266     public static String getIdentityrefBase(Type_body_stmtsContext ctx) {
1267         String result = null;
1268         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1269             ParseTree child = ctx.getChild(i);
1270             if (child instanceof Identityref_specificationContext) {
1271                 for (int j = 0; j < child.getChildCount(); j++) {
1272                     ParseTree baseArg = child.getChild(j);
1273                     if (baseArg instanceof Base_stmtContext) {
1274                         result = stringFromNode(baseArg);
1275                         break outer;
1276                     }
1277                 }
1278             }
1279         }
1280         return result;
1281     }
1282
1283     /**
1284      * Parse type body statement and find require-instance value.
1285      *
1286      * @param ctx
1287      *            type body context
1288      * @return require-instance value
1289      */
1290     private static boolean isRequireInstance(Type_body_stmtsContext ctx) {
1291         for (int i = 0; i < ctx.getChildCount(); i++) {
1292             ParseTree child = ctx.getChild(i);
1293             if (child instanceof Instance_identifier_specificationContext) {
1294                 for (int j = 0; j < child.getChildCount(); j++) {
1295                     ParseTree reqStmt = child.getChild(j);
1296                     if (reqStmt instanceof Require_instance_stmtContext) {
1297                         for (int k = 0; k < reqStmt.getChildCount(); k++) {
1298                             ParseTree reqArg = reqStmt.getChild(k);
1299                             if (reqArg instanceof Require_instance_argContext) {
1300                                 return Boolean.valueOf(stringFromNode(reqArg));
1301                             }
1302                         }
1303                     }
1304                 }
1305             }
1306         }
1307         return true;
1308     }
1309
1310     /**
1311      * Parse type body statement and find leafref path.
1312      *
1313      * @param ctx
1314      *            type body context
1315      * @return leafref path as String
1316      */
1317     private static String parseLeafrefPath(Type_body_stmtsContext ctx) {
1318         for (int i = 0; i < ctx.getChildCount(); i++) {
1319             ParseTree child = ctx.getChild(i);
1320             if (child instanceof Leafref_specificationContext) {
1321                 for (int j = 0; j < child.getChildCount(); j++) {
1322                     ParseTree leafRefSpec = child.getChild(j);
1323                     if (leafRefSpec instanceof Path_stmtContext) {
1324                         return stringFromNode(leafRefSpec);
1325                     }
1326                 }
1327             }
1328         }
1329         return null;
1330     }
1331
1332     /**
1333      * Internal helper method for parsing must statement.
1334      *
1335      * @param ctx
1336      *            Must_stmtContext
1337      * @return MustDefinition object based on parsed context
1338      */
1339     public static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1340         StringBuilder mustText = new StringBuilder();
1341         String description = null;
1342         String reference = null;
1343         String errorAppTag = null;
1344         String errorMessage = null;
1345         for (int i = 0; i < ctx.getChildCount(); ++i) {
1346             ParseTree child = ctx.getChild(i);
1347             if (child instanceof StringContext) {
1348                 final StringContext context = (StringContext) child;
1349                 if (context.getChildCount() == 1) {
1350                     String mustPart = context.getChild(0).getText();
1351                     // trim start and end quotation
1352                     mustText.append(mustPart.substring(1, mustPart.length() - 1));
1353                 } else {
1354                     for (int j = 0; j < context.getChildCount(); j++) {
1355                         String mustPart = context.getChild(j).getText();
1356                         if (j == 0) {
1357                             mustText.append(mustPart.substring(0, mustPart.length() - 1));
1358                             continue;
1359                         }
1360                         if (j % 2 == 0) {
1361                             mustText.append(mustPart.substring(1));
1362                         }
1363                     }
1364                 }
1365             } else if (child instanceof Description_stmtContext) {
1366                 description = stringFromNode(child);
1367             } else if (child instanceof Reference_stmtContext) {
1368                 reference = stringFromNode(child);
1369             } else if (child instanceof Error_app_tag_stmtContext) {
1370                 errorAppTag = stringFromNode(child);
1371             } else if (child instanceof Error_message_stmtContext) {
1372                 errorMessage = stringFromNode(child);
1373             }
1374         }
1375
1376         return new MustDefinitionImpl(mustText.toString(), description, reference, errorAppTag, errorMessage);
1377     }
1378
1379     /**
1380      * Parse given context and set constraints to constraints builder.
1381      *
1382      * @param ctx
1383      *            context to parse
1384      * @param constraints
1385      *            ConstraintsBuilder to fill
1386      */
1387     public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1388         for (int i = 0; i < ctx.getChildCount(); ++i) {
1389             final ParseTree childNode = ctx.getChild(i);
1390             if (childNode instanceof Max_elements_stmtContext) {
1391                 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1392                 constraints.setMaxElements(max);
1393             } else if (childNode instanceof Min_elements_stmtContext) {
1394                 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1395                 constraints.setMinElements(min);
1396             } else if (childNode instanceof Must_stmtContext) {
1397                 MustDefinition must = parseMust((Must_stmtContext) childNode);
1398                 constraints.addMustDefinition(must);
1399             } else if (childNode instanceof Mandatory_stmtContext) {
1400                 for (int j = 0; j < childNode.getChildCount(); j++) {
1401                     ParseTree mandatoryTree = childNode.getChild(j);
1402                     if (mandatoryTree instanceof Mandatory_argContext) {
1403                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1404                         constraints.setMandatory(mandatory);
1405                     }
1406                 }
1407             } else if (childNode instanceof When_stmtContext) {
1408                 constraints.addWhenCondition(stringFromNode(childNode));
1409             }
1410         }
1411     }
1412
1413     private static Integer parseMinElements(Min_elements_stmtContext ctx, String moduleName) {
1414         Integer result = null;
1415         try {
1416             for (int i = 0; i < ctx.getChildCount(); i++) {
1417                 ParseTree minArg = ctx.getChild(i);
1418                 if (minArg instanceof Min_value_argContext) {
1419                     result = Integer.valueOf(stringFromNode(minArg));
1420                 }
1421             }
1422             if (result == null) {
1423                 throw new IllegalArgumentException();
1424             }
1425             return result;
1426         } catch (Exception e) {
1427             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1428         }
1429     }
1430
1431     private static Integer parseMaxElements(Max_elements_stmtContext ctx, String moduleName) {
1432         Integer result = null;
1433         try {
1434             for (int i = 0; i < ctx.getChildCount(); i++) {
1435                 ParseTree maxArg = ctx.getChild(i);
1436                 if (maxArg instanceof Max_value_argContext) {
1437                     result = Integer.valueOf(stringFromNode(maxArg));
1438                 }
1439             }
1440             if (result == null) {
1441                 throw new IllegalArgumentException();
1442             }
1443             return result;
1444         } catch (Exception e) {
1445             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1446         }
1447     }
1448
1449     /**
1450      * Parse given context and return yin value.
1451      *
1452      * @param ctx
1453      *            context to parse
1454      * @return true if value is 'true', false otherwise
1455      */
1456     public static boolean parseYinValue(Argument_stmtContext ctx) {
1457         boolean yinValue = false;
1458         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1459             ParseTree yin = ctx.getChild(i);
1460             if (yin instanceof Yin_element_stmtContext) {
1461                 for (int j = 0; j < yin.getChildCount(); j++) {
1462                     ParseTree yinArg = yin.getChild(j);
1463                     if (yinArg instanceof Yin_element_argContext) {
1464                         String yinString = stringFromNode(yinArg);
1465                         if ("true".equals(yinString)) {
1466                             yinValue = true;
1467                             break outer;
1468                         }
1469                     }
1470                 }
1471             }
1472         }
1473         return yinValue;
1474     }
1475
1476     /**
1477      * Check this base type.
1478      *
1479      * @param typeName
1480      *            base YANG type name
1481      * @param moduleName
1482      *            name of current module
1483      * @param line
1484      *            line in module
1485      * @throws YangParseException
1486      *             if this is one of YANG type which MUST contain additional
1487      *             informations in its body
1488      */
1489     public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1490         switch (typeName) {
1491         case "decimal64":
1492             throw new YangParseException(moduleName, line,
1493                     "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1494         case "identityref":
1495             throw new YangParseException(moduleName, line,
1496                     "The 'base' statement MUST be present if the type is 'identityref'.");
1497         case "leafref":
1498             throw new YangParseException(moduleName, line,
1499                     "The 'path' statement MUST be present if the type is 'leafref'.");
1500         case "bits":
1501             throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1502         case "enumeration":
1503             throw new YangParseException(moduleName, line,
1504                     "The 'enum' statement MUST be present if the type is 'enumeration'.");
1505         }
1506     }
1507
1508     /**
1509      * Parse refine statement.
1510      *
1511      * @param refineCtx
1512      *            refine statement
1513      * @param moduleName
1514      *            name of current module
1515      * @return RefineHolder object representing this refine statement
1516      */
1517     public static RefineHolder parseRefine(Refine_stmtContext refineCtx, String moduleName) {
1518         final String refineTarget = stringFromNode(refineCtx);
1519         final RefineHolder refine = new RefineHolder(moduleName, refineCtx.getStart().getLine(), refineTarget);
1520         for (int i = 0; i < refineCtx.getChildCount(); i++) {
1521             ParseTree refinePom = refineCtx.getChild(i);
1522             if (refinePom instanceof Refine_pomContext) {
1523                 for (int j = 0; j < refinePom.getChildCount(); j++) {
1524                     ParseTree refineStmt = refinePom.getChild(j);
1525                     parseRefineDefault(refine, refineStmt);
1526
1527                     if (refineStmt instanceof Refine_leaf_stmtsContext) {
1528                         parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1529                     } else if (refineStmt instanceof Refine_container_stmtsContext) {
1530                         parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1531                     } else if (refineStmt instanceof Refine_list_stmtsContext) {
1532                         parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1533                     } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1534                         parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1535                     } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1536                         parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1537                     } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1538                         parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1539                     }
1540                 }
1541             }
1542         }
1543         return refine;
1544     }
1545
1546     private static void parseRefineDefault(RefineHolder refine, ParseTree refineStmt) {
1547         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1548             ParseTree refineArg = refineStmt.getChild(i);
1549             if (refineArg instanceof Description_stmtContext) {
1550                 String description = stringFromNode(refineArg);
1551                 refine.setDescription(description);
1552             } else if (refineArg instanceof Reference_stmtContext) {
1553                 String reference = stringFromNode(refineArg);
1554                 refine.setReference(reference);
1555             } else if (refineArg instanceof Config_stmtContext) {
1556                 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1557                 refine.setConfiguration(config);
1558             }
1559         }
1560     }
1561
1562     private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_stmtsContext refineStmt) {
1563         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1564             ParseTree refineArg = refineStmt.getChild(i);
1565             if (refineArg instanceof Default_stmtContext) {
1566                 String defaultStr = stringFromNode(refineArg);
1567                 refine.setDefaultStr(defaultStr);
1568             } else if (refineArg instanceof Mandatory_stmtContext) {
1569                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1570                     ParseTree mandatoryTree = refineArg.getChild(j);
1571                     if (mandatoryTree instanceof Mandatory_argContext) {
1572                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1573                         refine.setMandatory(mandatory);
1574                     }
1575                 }
1576             } else if (refineArg instanceof Must_stmtContext) {
1577                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1578                 refine.setMust(must);
1579
1580             }
1581         }
1582         return refine;
1583     }
1584
1585     private static RefineHolder parseRefine(RefineHolder refine, Refine_container_stmtsContext refineStmt) {
1586         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1587             ParseTree refineArg = refineStmt.getChild(i);
1588             if (refineArg instanceof Must_stmtContext) {
1589                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1590                 refine.setMust(must);
1591             } else if (refineArg instanceof Presence_stmtContext) {
1592                 refine.setPresence(true);
1593             }
1594         }
1595         return refine;
1596     }
1597
1598     private static RefineHolder parseRefine(RefineHolder refine, Refine_list_stmtsContext refineStmt) {
1599         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1600             ParseTree refineArg = refineStmt.getChild(i);
1601             if (refineArg instanceof Must_stmtContext) {
1602                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1603                 refine.setMust(must);
1604             } else if (refineArg instanceof Max_elements_stmtContext) {
1605                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1606                 refine.setMaxElements(max);
1607             } else if (refineArg instanceof Min_elements_stmtContext) {
1608                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1609                 refine.setMinElements(min);
1610             }
1611         }
1612         return refine;
1613     }
1614
1615     private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_list_stmtsContext refineStmt) {
1616         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1617             ParseTree refineArg = refineStmt.getChild(i);
1618             if (refineArg instanceof Must_stmtContext) {
1619                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1620                 refine.setMust(must);
1621             } else if (refineArg instanceof Max_elements_stmtContext) {
1622                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1623                 refine.setMaxElements(max);
1624             } else if (refineArg instanceof Min_elements_stmtContext) {
1625                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1626                 refine.setMinElements(min);
1627             }
1628         }
1629         return refine;
1630     }
1631
1632     private static RefineHolder parseRefine(RefineHolder refine, Refine_choice_stmtsContext refineStmt) {
1633         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1634             ParseTree refineArg = refineStmt.getChild(i);
1635             if (refineArg instanceof Default_stmtContext) {
1636                 String defaultStr = stringFromNode(refineArg);
1637                 refine.setDefaultStr(defaultStr);
1638             } else if (refineArg instanceof Mandatory_stmtContext) {
1639                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1640                     ParseTree mandatoryTree = refineArg.getChild(j);
1641                     if (mandatoryTree instanceof Mandatory_argContext) {
1642                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1643                         refine.setMandatory(mandatory);
1644                     }
1645                 }
1646             }
1647         }
1648         return refine;
1649     }
1650
1651     private static RefineHolder parseRefine(RefineHolder refine, Refine_anyxml_stmtsContext refineStmt) {
1652         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1653             ParseTree refineArg = refineStmt.getChild(i);
1654             if (refineArg instanceof Must_stmtContext) {
1655                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1656                 refine.setMust(must);
1657             } else if (refineArg instanceof Mandatory_stmtContext) {
1658                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1659                     ParseTree mandatoryTree = refineArg.getChild(j);
1660                     if (mandatoryTree instanceof Mandatory_argContext) {
1661                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1662                         refine.setMandatory(mandatory);
1663                     }
1664                 }
1665             }
1666         }
1667         return refine;
1668     }
1669
1670     public static String getArgumentString(org.antlr.v4.runtime.ParserRuleContext ctx) {
1671         List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1672         checkState(!potentialValues.isEmpty());
1673         return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1674     }
1675
1676     public static <T extends ParserRuleContext> Optional<T> getFirstContext(ParserRuleContext context,Class<T> contextType) {
1677         List<T> potential = context.getRuleContexts(contextType);
1678         if(potential.isEmpty()) {
1679             return Optional.absent();
1680         }
1681         return Optional.of(potential.get(0));
1682     }
1683
1684 }