d913f5b87fbd25798d1938add82aba073ea00cda
[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         TypeDefinition<?> baseType = null;
1084
1085         Integer fractionDigits = getFractionDigits(typeBody);
1086         List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody);
1087         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1088         List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody);
1089
1090         TypeConstraints constraints = new TypeConstraints(moduleName, typeBody.getStart().getLine());
1091         constraints.addFractionDigits(fractionDigits);
1092         constraints.addLengths(lengthStatements);
1093         constraints.addPatterns(patternStatements);
1094         constraints.addRanges(rangeStatements);
1095
1096         SchemaPath baseTypePathFinal = createTypeSchemaPath(actualPath, namespace, revision, prefix, typeName, true,
1097                 true);
1098         SchemaPath baseTypePath = createTypeSchemaPath(actualPath, namespace, revision, prefix, typeName, true, false);
1099
1100         if ("decimal64".equals(typeName)) {
1101             if (rangeStatements.isEmpty()) {
1102                 return new Decimal64(baseTypePathFinal, fractionDigits);
1103             }
1104             Decimal64 decimalType = new Decimal64(baseTypePath, fractionDigits);
1105             constraints.addRanges(decimalType.getRangeStatements());
1106             baseType = decimalType;
1107         } else if (typeName.startsWith("int")) {
1108             IntegerTypeDefinition intType = null;
1109             if ("int8".equals(typeName)) {
1110                 intType = new Int8(baseTypePath);
1111             } else if ("int16".equals(typeName)) {
1112                 intType = new Int16(baseTypePath);
1113             } else if ("int32".equals(typeName)) {
1114                 intType = new Int32(baseTypePath);
1115             } else if ("int64".equals(typeName)) {
1116                 intType = new Int64(baseTypePath);
1117             }
1118             constraints.addRanges(intType.getRangeStatements());
1119             baseType = intType;
1120         } else if (typeName.startsWith("uint")) {
1121             UnsignedIntegerTypeDefinition uintType = null;
1122             if ("uint8".equals(typeName)) {
1123                 uintType = new Uint8(baseTypePath);
1124             } else if ("uint16".equals(typeName)) {
1125                 uintType = new Uint16(baseTypePath);
1126             } else if ("uint32".equals(typeName)) {
1127                 uintType = new Uint32(baseTypePath);
1128             } else if ("uint64".equals(typeName)) {
1129                 uintType = new Uint64(baseTypePath);
1130             }
1131             constraints.addRanges(uintType.getRangeStatements());
1132             baseType = uintType;
1133         } else if ("enumeration".equals(typeName)) {
1134             List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, namespace,
1135                     revision, prefix);
1136             return new EnumerationType(baseTypePathFinal, enumConstants);
1137         } else if ("string".equals(typeName)) {
1138             StringTypeDefinition stringType = new StringType(baseTypePath);
1139             constraints.addLengths(stringType.getLengthStatements());
1140             baseType = stringType;
1141         } else if ("bits".equals(typeName)) {
1142             return new BitsType(baseTypePathFinal, getBits(typeBody, actualPath, namespace, revision, prefix));
1143         } else if ("leafref".equals(typeName)) {
1144             final String path = parseLeafrefPath(typeBody);
1145             final boolean absolute = path.startsWith("/");
1146             RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1147             return new Leafref(baseTypePathFinal, xpath);
1148         } else if ("binary".equals(typeName)) {
1149             BinaryTypeDefinition binaryType = new BinaryType(baseTypePath);
1150             constraints.addLengths(binaryType.getLengthConstraints());
1151             baseType = binaryType;
1152         } else if ("instance-identifier".equals(typeName)) {
1153             boolean requireInstance = isRequireInstance(typeBody);
1154             baseType = new InstanceIdentifier(baseTypePath, null, requireInstance);
1155         }
1156
1157         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1158             TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1159             typedef.setRanges(constraints.getRange());
1160             typedef.setLengths(constraints.getLength());
1161             typedef.setPatterns(constraints.getPatterns());
1162             typedef.setFractionDigits(constraints.getFractionDigits());
1163             return baseType;
1164         }
1165
1166         TypeDefinition<?> result = null;
1167         QName qname = new QName(namespace, revision, prefix, typeName);
1168         ExtendedType.Builder typeBuilder = null;
1169
1170         SchemaPath schemaPath = createTypeSchemaPath(actualPath, namespace, revision, prefix, typeName, false, false);
1171         typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
1172
1173         typeBuilder.ranges(constraints.getRange());
1174         typeBuilder.lengths(constraints.getLength());
1175         typeBuilder.patterns(constraints.getPatterns());
1176         typeBuilder.fractionDigits(constraints.getFractionDigits());
1177
1178         result = typeBuilder.build();
1179         return result;
1180     }
1181
1182     /**
1183      * Create SchemaPath object from given path list with namespace, revision
1184      * and prefix based on given values.
1185      *
1186      * @param actualPath
1187      *            current position in model
1188      * @param namespace
1189      * @param revision
1190      * @param prefix
1191      * @param typeName
1192      * @param isBaseYangType
1193      *            if this is base yang type
1194      * @param isBaseYangTypeFinal
1195      *            if this is base yang type without restrictions
1196      * @return SchemaPath object.
1197      */
1198     private static SchemaPath createTypeSchemaPath(final List<String> actualPath, final URI namespace,
1199             final Date revision, final String prefix, final String typeName, final boolean isBaseYangType,
1200             final boolean isBaseYangTypeFinal) {
1201         List<String> typePath = new ArrayList<String>(actualPath);
1202         if (isBaseYangType && !isBaseYangTypeFinal) {
1203             typePath.add(typeName);
1204         }
1205
1206         final List<QName> path = new ArrayList<QName>();
1207         QName qname;
1208         // start from index 1 -> module name omited
1209         for (int i = 1; i < typePath.size(); i++) {
1210             qname = new QName(namespace, revision, prefix, typePath.get(i));
1211             path.add(qname);
1212         }
1213         QName typeQName;
1214         if (isBaseYangType) {
1215             typeQName = new QName(BaseTypes.BaseTypesNamespace, typeName);
1216         } else {
1217             typeQName = new QName(namespace, revision, prefix, typeName);
1218         }
1219         path.add(typeQName);
1220         return new SchemaPath(path, true);
1221     }
1222
1223     /**
1224      * Parse given context and find identityref base value.
1225      *
1226      * @param ctx
1227      *            type body
1228      * @return identityref base value as String
1229      */
1230     public static String getIdentityrefBase(Type_body_stmtsContext ctx) {
1231         String result = null;
1232         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1233             ParseTree child = ctx.getChild(i);
1234             if (child instanceof Identityref_specificationContext) {
1235                 for (int j = 0; j < child.getChildCount(); j++) {
1236                     ParseTree baseArg = child.getChild(j);
1237                     if (baseArg instanceof Base_stmtContext) {
1238                         result = stringFromNode(baseArg);
1239                         break outer;
1240                     }
1241                 }
1242             }
1243         }
1244         return result;
1245     }
1246
1247     /**
1248      * Parse type body statement and find require-instance value.
1249      *
1250      * @param ctx
1251      *            type body context
1252      * @return require-instance value
1253      */
1254     private static boolean isRequireInstance(Type_body_stmtsContext ctx) {
1255         for (int i = 0; i < ctx.getChildCount(); i++) {
1256             ParseTree child = ctx.getChild(i);
1257             if (child instanceof Require_instance_stmtContext) {
1258                 for (int j = 0; j < child.getChildCount(); j++) {
1259                     ParseTree reqArg = child.getChild(j);
1260                     if (reqArg instanceof Require_instance_argContext) {
1261                         return Boolean.valueOf(stringFromNode(reqArg));
1262                     }
1263                 }
1264             }
1265         }
1266         return false;
1267     }
1268
1269     /**
1270      * Parse type body statement and find leafref path.
1271      *
1272      * @param ctx
1273      *            type body context
1274      * @return leafref path as String
1275      */
1276     private static String parseLeafrefPath(Type_body_stmtsContext ctx) {
1277         for (int i = 0; i < ctx.getChildCount(); i++) {
1278             ParseTree child = ctx.getChild(i);
1279             if (child instanceof Leafref_specificationContext) {
1280                 for (int j = 0; j < child.getChildCount(); j++) {
1281                     ParseTree leafRefSpec = child.getChild(j);
1282                     if (leafRefSpec instanceof Path_stmtContext) {
1283                         return stringFromNode(leafRefSpec);
1284                     }
1285                 }
1286             }
1287         }
1288         return null;
1289     }
1290
1291     /**
1292      * Internal helper method for parsing must statement.
1293      *
1294      * @param ctx
1295      *            Must_stmtContext
1296      * @return MustDefinition object based on parsed context
1297      */
1298     public static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1299         StringBuilder mustText = new StringBuilder();
1300         String description = null;
1301         String reference = null;
1302         String errorAppTag = null;
1303         String errorMessage = null;
1304         for (int i = 0; i < ctx.getChildCount(); ++i) {
1305             ParseTree child = ctx.getChild(i);
1306             if (child instanceof StringContext) {
1307                 final StringContext context = (StringContext) child;
1308                 if (context.getChildCount() == 1) {
1309                     String mustPart = context.getChild(0).getText();
1310                     // trim start and end quotation
1311                     mustText.append(mustPart.substring(1, mustPart.length() - 1));
1312                 } else {
1313                     for (int j = 0; j < context.getChildCount(); j++) {
1314                         String mustPart = context.getChild(j).getText();
1315                         if (j == 0) {
1316                             mustText.append(mustPart.substring(0, mustPart.length() - 1));
1317                             continue;
1318                         }
1319                         if (j % 2 == 0) {
1320                             mustText.append(mustPart.substring(1));
1321                         }
1322                     }
1323                 }
1324             } else if (child instanceof Description_stmtContext) {
1325                 description = stringFromNode(child);
1326             } else if (child instanceof Reference_stmtContext) {
1327                 reference = stringFromNode(child);
1328             } else if (child instanceof Error_app_tag_stmtContext) {
1329                 errorAppTag = stringFromNode(child);
1330             } else if (child instanceof Error_message_stmtContext) {
1331                 errorMessage = stringFromNode(child);
1332             }
1333         }
1334
1335         MustDefinition must = new MustDefinitionImpl(mustText.toString(), description, reference, errorAppTag,
1336                 errorMessage);
1337         return must;
1338     }
1339
1340     /**
1341      * Parse given context and set constraints to constraints builder.
1342      *
1343      * @param ctx
1344      *            context to parse
1345      * @param constraints
1346      *            ConstraintsBuilder to fill
1347      */
1348     public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1349         for (int i = 0; i < ctx.getChildCount(); ++i) {
1350             final ParseTree childNode = ctx.getChild(i);
1351             if (childNode instanceof Max_elements_stmtContext) {
1352                 Integer max = parseMaxElements((Max_elements_stmtContext) childNode);
1353                 constraints.setMaxElements(max);
1354             } else if (childNode instanceof Min_elements_stmtContext) {
1355                 Integer min = parseMinElements((Min_elements_stmtContext) childNode);
1356                 constraints.setMinElements(min);
1357             } else if (childNode instanceof Must_stmtContext) {
1358                 MustDefinition must = parseMust((Must_stmtContext) childNode);
1359                 constraints.addMustDefinition(must);
1360             } else if (childNode instanceof Mandatory_stmtContext) {
1361                 for (int j = 0; j < childNode.getChildCount(); j++) {
1362                     ParseTree mandatoryTree = ctx.getChild(j);
1363                     if (mandatoryTree instanceof Mandatory_argContext) {
1364                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1365                         constraints.setMandatory(mandatory);
1366                     }
1367                 }
1368             } else if (childNode instanceof When_stmtContext) {
1369                 constraints.addWhenCondition(stringFromNode(childNode));
1370             }
1371         }
1372     }
1373
1374     private static Integer parseMinElements(Min_elements_stmtContext ctx) {
1375         Integer result = null;
1376         try {
1377             for (int j = 0; j < ctx.getChildCount(); j++) {
1378                 ParseTree minArg = ctx.getChild(j);
1379                 if (minArg instanceof Min_value_argContext) {
1380                     result = Integer.valueOf(stringFromNode(minArg));
1381                 }
1382             }
1383             if (result == null) {
1384                 throw new IllegalArgumentException();
1385             }
1386             return result;
1387         } catch (Exception e) {
1388             throw new YangParseException(ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1389         }
1390     }
1391
1392     private static Integer parseMaxElements(Max_elements_stmtContext ctx) {
1393         Integer result = null;
1394         try {
1395             for (int j = 0; j < ctx.getChildCount(); j++) {
1396                 ParseTree maxArg = ctx.getChild(j);
1397                 if (maxArg instanceof Max_value_argContext) {
1398                     result = Integer.valueOf(stringFromNode(maxArg));
1399                 }
1400             }
1401             if (result == null) {
1402                 throw new IllegalArgumentException();
1403             }
1404             return result;
1405         } catch (Exception e) {
1406             throw new YangParseException(ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1407         }
1408     }
1409
1410     /**
1411      * Parse given context and return yin value.
1412      *
1413      * @param ctx
1414      *            context to parse
1415      * @return true if value is 'true', false otherwise
1416      */
1417     public static boolean parseYinValue(Argument_stmtContext ctx) {
1418         boolean yinValue = false;
1419         outer: for (int j = 0; j < ctx.getChildCount(); j++) {
1420             ParseTree yin = ctx.getChild(j);
1421             if (yin instanceof Yin_element_stmtContext) {
1422                 for (int k = 0; k < yin.getChildCount(); k++) {
1423                     ParseTree yinArg = yin.getChild(k);
1424                     if (yinArg instanceof Yin_element_argContext) {
1425                         String yinString = stringFromNode(yinArg);
1426                         if ("true".equals(yinString)) {
1427                             yinValue = true;
1428                             break outer;
1429                         }
1430                     }
1431                 }
1432             }
1433         }
1434         return yinValue;
1435     }
1436
1437     /**
1438      * Check this base type.
1439      *
1440      * @param typeName
1441      *            base YANG type name
1442      * @param moduleName
1443      *            name of current module
1444      * @param line
1445      *            line in module
1446      * @throws YangParseException
1447      *             if this is one of YANG type which MUST contain additional
1448      *             informations in its body
1449      */
1450     public static void checkMissingBody(final String typeName, final String moduleName, final int line)
1451             throws YangParseException {
1452         if ("decimal64".equals(typeName)) {
1453             throw new YangParseException(moduleName, line,
1454                     "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1455         } else if ("identityref".equals(typeName)) {
1456             throw new YangParseException(moduleName, line,
1457                     "The 'base' statement MUST be present if the type is 'identityref'.");
1458         } else if ("leafref".equals(typeName)) {
1459             throw new YangParseException(moduleName, line,
1460                     "The 'path' statement MUST be present if the type is 'leafref'.");
1461         } else if ("bits".equals(typeName)) {
1462             throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1463         } else if ("enumeration".equals(typeName)) {
1464             throw new YangParseException(moduleName, line,
1465                     "The 'enum' statement MUST be present if the type is 'enumeration'.");
1466         }
1467     }
1468
1469     /**
1470      * Parse refine statement.
1471      *
1472      * @param refineCtx
1473      *            refine statement
1474      * @param line
1475      *            current line in yang model
1476      * @return RefineHolder object representing this refine statement
1477      */
1478     public static RefineHolder parseRefine(Refine_stmtContext refineCtx) {
1479         final String refineTarget = stringFromNode(refineCtx);
1480         final RefineHolder refine = new RefineHolder(refineCtx.getStart().getLine(), refineTarget);
1481         for (int j = 0; j < refineCtx.getChildCount(); j++) {
1482             ParseTree refinePom = refineCtx.getChild(j);
1483             if (refinePom instanceof Refine_pomContext) {
1484                 for (int k = 0; k < refinePom.getChildCount(); k++) {
1485                     ParseTree refineStmt = refinePom.getChild(k);
1486                     parseRefineDefault(refine, refineStmt);
1487
1488                     if (refineStmt instanceof Refine_leaf_stmtsContext) {
1489                         parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1490                     } else if (refineStmt instanceof Refine_container_stmtsContext) {
1491                         parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1492                     } else if (refineStmt instanceof Refine_list_stmtsContext) {
1493                         parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1494                     } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1495                         parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1496                     } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1497                         parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1498                     } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1499                         parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1500                     }
1501                 }
1502             }
1503         }
1504         return refine;
1505     }
1506
1507     private static void parseRefineDefault(RefineHolder refine, ParseTree refineStmt) {
1508         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1509             ParseTree refineArg = refineStmt.getChild(i);
1510             if (refineArg instanceof Description_stmtContext) {
1511                 String description = stringFromNode(refineArg);
1512                 refine.setDescription(description);
1513             } else if (refineArg instanceof Reference_stmtContext) {
1514                 String reference = stringFromNode(refineArg);
1515                 refine.setReference(reference);
1516             } else if (refineArg instanceof Config_stmtContext) {
1517                 Boolean config = parseConfig((Config_stmtContext) refineArg);
1518                 refine.setConfiguration(config);
1519             }
1520         }
1521     }
1522
1523     private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_stmtsContext refineStmt) {
1524         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1525             ParseTree refineArg = refineStmt.getChild(i);
1526             if (refineArg instanceof Default_stmtContext) {
1527                 String defaultStr = stringFromNode(refineArg);
1528                 refine.setDefaultStr(defaultStr);
1529             } else if (refineArg instanceof Mandatory_stmtContext) {
1530                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1531                     ParseTree mandatoryTree = refineArg.getChild(j);
1532                     if (mandatoryTree instanceof Mandatory_argContext) {
1533                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1534                         refine.setMandatory(mandatory);
1535                     }
1536                 }
1537             } else if (refineArg instanceof Must_stmtContext) {
1538                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1539                 refine.setMust(must);
1540
1541             }
1542         }
1543         return refine;
1544     }
1545
1546     private static RefineHolder parseRefine(RefineHolder refine, Refine_container_stmtsContext refineStmt) {
1547         for (int m = 0; m < refineStmt.getChildCount(); m++) {
1548             ParseTree refineArg = refineStmt.getChild(m);
1549             if (refineArg instanceof Must_stmtContext) {
1550                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1551                 refine.setMust(must);
1552             } else if (refineArg instanceof Presence_stmtContext) {
1553                 refine.setPresence(true);
1554             }
1555         }
1556         return refine;
1557     }
1558
1559     private static RefineHolder parseRefine(RefineHolder refine, Refine_list_stmtsContext refineStmt) {
1560         for (int m = 0; m < refineStmt.getChildCount(); m++) {
1561             ParseTree refineArg = refineStmt.getChild(m);
1562             if (refineArg instanceof Must_stmtContext) {
1563                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1564                 refine.setMust(must);
1565             } else if (refineArg instanceof Max_elements_stmtContext) {
1566                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg);
1567                 refine.setMaxElements(max);
1568             } else if (refineArg instanceof Min_elements_stmtContext) {
1569                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg);
1570                 refine.setMinElements(min);
1571             }
1572         }
1573         return refine;
1574     }
1575
1576     private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_list_stmtsContext refineStmt) {
1577         for (int m = 0; m < refineStmt.getChildCount(); m++) {
1578             ParseTree refineArg = refineStmt.getChild(m);
1579             if (refineArg instanceof Must_stmtContext) {
1580                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1581                 refine.setMust(must);
1582             } else if (refineArg instanceof Max_elements_stmtContext) {
1583                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg);
1584                 refine.setMaxElements(max);
1585             } else if (refineArg instanceof Min_elements_stmtContext) {
1586                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg);
1587                 refine.setMinElements(min);
1588             }
1589         }
1590         return refine;
1591     }
1592
1593     private static RefineHolder parseRefine(RefineHolder refine, Refine_choice_stmtsContext refineStmt) {
1594         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1595             ParseTree refineArg = refineStmt.getChild(i);
1596             if (refineArg instanceof Default_stmtContext) {
1597                 String defaultStr = stringFromNode(refineArg);
1598                 refine.setDefaultStr(defaultStr);
1599             } else if (refineArg instanceof Mandatory_stmtContext) {
1600                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1601                     ParseTree mandatoryTree = refineArg.getChild(j);
1602                     if (mandatoryTree instanceof Mandatory_argContext) {
1603                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1604                         refine.setMandatory(mandatory);
1605                     }
1606                 }
1607             }
1608         }
1609         return refine;
1610     }
1611
1612     private static RefineHolder parseRefine(RefineHolder refine, Refine_anyxml_stmtsContext refineStmt) {
1613         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1614             ParseTree refineArg = refineStmt.getChild(i);
1615             if (refineArg instanceof Must_stmtContext) {
1616                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1617                 refine.setMust(must);
1618             } else if (refineArg instanceof Mandatory_stmtContext) {
1619                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1620                     ParseTree mandatoryTree = refineArg.getChild(j);
1621                     if (mandatoryTree instanceof Mandatory_argContext) {
1622                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1623                         refine.setMandatory(mandatory);
1624                     }
1625                 }
1626             }
1627         }
1628         return refine;
1629     }
1630
1631 }