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