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