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