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