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