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