update odlux sources
[ccsdk/features.git] / sdnr / wt / odlux / apps / configurationApp / src / yang / yangParser.ts
1 /**
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt odlux
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  */
18 import { Token, Statement, Module, Identity, ModuleState } from "../models/yang";
19 import {
20   ViewSpecification, ViewElement, isViewElementObjectOrList, ViewElementBase,
21   isViewElementReference, ViewElementChoise, ViewElementBinary, ViewElementString, isViewElementString,
22   isViewElementNumber, ViewElementNumber, Expression, YangRange, ViewElementUnion, ViewElementRpc, isViewElementRpc, ResolveFunction, ViewElementDate
23 } from "../models/uiModels";
24 import { yangService } from "../services/yangService";
25
26
27 export const splitVPath = (vPath: string, vPathParser: RegExp): RegExpMatchArray[] => {
28   const pathParts: RegExpMatchArray[] = [];
29   let partMatch: RegExpExecArray | null;
30   if (vPath) do {
31     partMatch = vPathParser.exec(vPath);
32     if (partMatch) {
33       pathParts.push(partMatch);
34     }
35   } while (partMatch)
36   return pathParts;
37 }
38
39 class YangLexer {
40
41   private pos: number = 0;
42   private buf: string = "";
43
44   constructor(input: string) {
45     this.pos = 0;
46     this.buf = input;
47   }
48
49   private _optable: { [key: string]: string } = {
50     ';': 'SEMI',
51     '{': 'L_BRACE',
52     '}': 'R_BRACE',
53   };
54
55   private _isNewline(char: string): boolean {
56     return char === '\r' || char === '\n';
57   }
58
59   private _isWhitespace(char: string): boolean {
60     return char === ' ' || char === '\t' || this._isNewline(char);
61   }
62
63   private _isDigit(char: string): boolean {
64     return char >= '0' && char <= '9';
65   }
66
67   private _isAlpha(char: string): boolean {
68     return (char >= 'a' && char <= 'z') ||
69       (char >= 'A' && char <= 'Z')
70   }
71
72   private _isAlphanum(char: string): boolean {
73     return this._isAlpha(char) || this._isDigit(char) ||
74       char === '_' || char === '-' || char === '.';
75   }
76
77   private _skipNontokens() {
78     while (this.pos < this.buf.length) {
79       const char = this.buf.charAt(this.pos);
80       if (this._isWhitespace(char)) {
81         this.pos++;
82       } else {
83         break;
84       }
85     }
86   }
87
88   private _processString(terminator: string | null): Token {
89     // this.pos points at the opening quote. Find the ending quote.
90     let end_index = this.pos + 1;
91     while (end_index < this.buf.length) {
92       const char = this.buf.charAt(end_index);
93       if (char === "\\") {
94         end_index += 2;
95         continue;
96       };
97       if (terminator === null && (this._isWhitespace(char) || this._optable[char] !== undefined) || char === terminator) {
98         break;
99       }
100       end_index++;
101     }
102
103     if (end_index >= this.buf.length) {
104       throw Error('Unterminated quote at ' + this.pos);
105     } else {
106       const start = this.pos + (terminator ? 1 : 0);
107       const end = end_index;
108       const tok = {
109         name: 'STRING',
110         value: this.buf.substring(start, end),
111         start,
112         end
113       };
114       this.pos = terminator ? end + 1 : end;
115       return tok;
116     }
117   }
118
119   private _processIdentifier(): Token {
120     let endpos = this.pos + 1;
121     while (endpos < this.buf.length && this._isAlphanum(this.buf.charAt(endpos))) {
122       ++endpos;
123     }
124
125     let name = 'IDENTIFIER'
126     if (this.buf.charAt(endpos) === ":") {
127       name = 'IDENTIFIERREF';
128       ++endpos;
129       while (endpos < this.buf.length && this._isAlphanum(this.buf.charAt(endpos))) {
130         ++endpos;
131       }
132     }
133
134     const tok = {
135       name: name,
136       value: this.buf.substring(this.pos, endpos),
137       start: this.pos,
138       end: endpos
139     };
140
141     this.pos = endpos;
142     return tok;
143   }
144
145   private _processNumber(): Token {
146     let endpos = this.pos + 1;
147     while (endpos < this.buf.length &&
148       this._isDigit(this.buf.charAt(endpos))) {
149       endpos++;
150     }
151
152     const tok = {
153       name: 'NUMBER',
154       value: this.buf.substring(this.pos, endpos),
155       start: this.pos,
156       end: endpos
157     };
158     this.pos = endpos;
159     return tok;
160   }
161
162   private _processLineComment() {
163     var endpos = this.pos + 2;
164     // Skip until the end of the line
165     while (endpos < this.buf.length && !this._isNewline(this.buf.charAt(endpos))) {
166       endpos++;
167     }
168     this.pos = endpos + 1;
169   }
170
171   private _processBlockComment() {
172     var endpos = this.pos + 2;
173     // Skip until the end of the line
174     while (endpos < this.buf.length && !((this.buf.charAt(endpos) === "/" && this.buf.charAt(endpos - 1) === "*"))) {
175       endpos++;
176     }
177     this.pos = endpos + 1;
178   }
179
180   public tokenize(): Token[] {
181     const result: Token[] = [];
182     this._skipNontokens();
183     while (this.pos < this.buf.length) {
184
185       const char = this.buf.charAt(this.pos);
186       const op = this._optable[char];
187
188       if (op !== undefined) {
189         result.push({ name: op, value: char, start: this.pos, end: ++this.pos });
190       } else if (this._isAlpha(char)) {
191         result.push(this._processIdentifier());
192         this._skipNontokens();
193         const peekChar = this.buf.charAt(this.pos);
194         if (this._optable[peekChar] === undefined) {
195           result.push((peekChar !== "'" && peekChar !== '"')
196             ? this._processString(null)
197             : this._processString(peekChar));
198         }
199       } else if (char === '/' && this.buf.charAt(this.pos + 1) === "/") {
200         this._processLineComment();
201       } else if (char === '/' && this.buf.charAt(this.pos + 1) === "*") {
202         this._processBlockComment();
203       } else {
204         throw Error('Token error at ' + this.pos + " " + this.buf[this.pos]);
205       }
206       this._skipNontokens();
207     }
208     return result;
209   }
210
211   public tokenize2(): Statement {
212     let stack: Statement[] = [{ key: "ROOT", sub: [] }];
213     let current: Statement | null = null;
214
215     this._skipNontokens();
216     while (this.pos < this.buf.length) {
217
218       const char = this.buf.charAt(this.pos);
219       const op = this._optable[char];
220
221       if (op !== undefined) {
222         if (op === "L_BRACE") {
223           current && stack.unshift(current);
224           current = null;
225         } else if (op === "R_BRACE") {
226           current = stack.shift() || null;
227         }
228         this.pos++;
229       } else if (this._isAlpha(char) || char === "_") {
230         const key = this._processIdentifier().value;
231         this._skipNontokens();
232         let peekChar = this.buf.charAt(this.pos);
233         let arg = undefined;
234         if (this._optable[peekChar] === undefined) {
235           arg = (peekChar === '"' || peekChar === "'")
236             ? this._processString(peekChar).value
237             : this._processString(null).value;
238         }
239         do {
240           this._skipNontokens();
241           peekChar = this.buf.charAt(this.pos);
242           if (peekChar !== "+") break;
243           this.pos++;
244           this._skipNontokens();
245           peekChar = this.buf.charAt(this.pos);
246           arg += (peekChar === '"' || peekChar === "'")
247             ? this._processString(peekChar).value
248             : this._processString(null).value;
249         } while (true);
250         current = { key, arg, sub: [] };
251         stack[0].sub!.push(current);
252       } else if (char === '/' && this.buf.charAt(this.pos + 1) === "/") {
253         this._processLineComment();
254       } else if (char === '/' && this.buf.charAt(this.pos + 1) === "*") {
255         this._processBlockComment();
256       } else {
257         throw Error('Token error at ' + this.pos + " " + this.buf.slice(this.pos - 10, this.pos + 10));
258       }
259       this._skipNontokens();
260     }
261     if (stack[0].key !== "ROOT" || !stack[0].sub![0]) {
262       throw new Error("Internal Perser Error");
263     }
264     return stack[0].sub![0];
265   }
266 }
267
268 export class YangParser {
269   private _groupingsToResolve: ViewSpecification[] = [];
270
271   private _identityToResolve: (() => void)[] = [];
272   private _unionsToResolve: (() => void)[] = [];
273   private _modulesToResolve: (() => void)[] = [];
274
275   private _modules: { [name: string]: Module } = {};
276   private _views: ViewSpecification[] = [{
277     id: "0",
278     name: "root",
279     language: "en-US",
280     canEdit: false,
281     config: true,
282     parentView: "0",
283     title: "root",
284     elements: {},
285   }];
286
287   public static ResolveStack = Symbol("ResolveStack");
288
289   constructor(private _unavailableCapabilities: { failureReason: string; capability: string; }[] = [], private _importOnlyModules: { name: string; revision: string; }[] = [], private nodeId: string) {
290    
291   }
292
293   public get modules() {
294     return this._modules;
295   }
296
297   public get views() {
298     return this._views;
299   }
300
301   public async addCapability(capability: string, version?: string, parentImportOnlyModule?: boolean) {
302     // do not add twice
303     if (this._modules[capability]) {
304       // console.warn(`Skipped capability: ${capability} since already contained.` );
305       return;
306     }
307
308     // // do not add unavailable capabilities
309     // if (this._unavailableCapabilities.some(c => c.capability === capability)) {
310     //   // console.warn(`Skipped capability: ${capability} since it is marked as unavailable.` );
311     //   return;
312     // }
313     const data = await yangService.getCapability(capability, this.nodeId, version);
314     if (!data) {
315       throw new Error(`Could not load yang file for ${capability}.`);
316     }
317
318     const rootStatement = new YangLexer(data).tokenize2();
319
320     if (rootStatement.key !== "module") {
321       throw new Error(`Root element of ${capability} is not a module.`);
322     }
323     if (rootStatement.arg !== capability) {
324       throw new Error(`Root element capability ${rootStatement.arg} does not requested ${capability}.`);
325     }
326
327     const isUnavailable = this._unavailableCapabilities.some(c => c.capability === capability);
328     const isImportOnly = parentImportOnlyModule === true || this._importOnlyModules.some(c => c.name === capability);
329     
330     const module = this._modules[capability] = {
331       name: rootStatement.arg,
332       revisions: {},
333       imports: {},
334       features: {},
335       identities: {},
336       augments: {},
337       groupings: {},
338       typedefs: {},
339       views: {},
340       elements: {},
341       state: isUnavailable
342            ? ModuleState.unavailable 
343            : isImportOnly 
344              ? ModuleState.importOnly
345              : ModuleState.stable,
346     };
347
348     await this.handleModule(module, rootStatement, capability);
349   }
350
351   private async handleModule(module: Module, rootStatement: Statement, capability: string) {
352
353     // extract namespace && prefix
354     module.namespace = this.extractValue(rootStatement, "namespace");
355     module.prefix = this.extractValue(rootStatement, "prefix");
356     if (module.prefix) {
357       module.imports[module.prefix] = capability;
358     }
359
360     // extract revisions
361     const revisions = this.extractNodes(rootStatement, "revision");
362     module.revisions = {
363       ...module.revisions,
364       ...revisions.reduce<{ [version: string]: {} }>((acc, version) => {
365         if (!version.arg) {
366           throw new Error(`Module [${module.name}] has a version w/o version number.`);
367         }
368         const description = this.extractValue(version, "description");
369         const reference = this.extractValue(version, "reference");
370         acc[version.arg] = {
371           description,
372           reference,
373         };
374         return acc;
375       }, {})
376     };
377
378     // extract features
379     const features = this.extractNodes(rootStatement, "feature");
380     module.features = {
381       ...module.features,
382       ...features.reduce<{ [version: string]: {} }>((acc, feature) => {
383         if (!feature.arg) {
384           throw new Error(`Module [${module.name}] has a feature w/o name.`);
385         }
386         const description = this.extractValue(feature, "description");
387         acc[feature.arg] = {
388           description,
389         };
390         return acc;
391       }, {})
392     };
393
394     // extract imports
395     const imports = this.extractNodes(rootStatement, "import");
396     module.imports = {
397       ...module.imports,
398       ...imports.reduce<{ [key: string]: string }>((acc, imp) => {
399         const prefix = imp.sub && imp.sub.filter(s => s.key === "prefix");
400         if (!imp.arg) {
401           throw new Error(`Module [${module.name}] has an import with neither name nor prefix.`);
402         }
403         acc[prefix && prefix.length === 1 && prefix[0].arg || imp.arg] = imp.arg;
404         return acc;
405       }, {})
406     };
407
408     // import all required files and set module state 
409     if (imports) for (let ind = 0; ind < imports.length; ++ind) {
410       const moduleName = imports[ind].arg!; 
411
412       //TODO: Fix imports getting loaded without revision
413       await this.addCapability(moduleName, undefined, module.state === ModuleState.importOnly);
414       const importedModule = this._modules[imports[ind].arg!];
415       if (importedModule && importedModule.state > ModuleState.stable) {
416           module.state = Math.max(module.state, ModuleState.instable);
417       }
418     }
419
420     this.extractTypeDefinitions(rootStatement, module, "");
421
422     this.extractIdentities(rootStatement, 0, module, "");
423
424     const groupings = this.extractGroupings(rootStatement, 0, module, "");
425     this._views.push(...groupings);
426
427     const augments = this.extractAugments(rootStatement, 0, module, "");
428     this._views.push(...augments);
429
430     // the default for config on module level is config = true;
431     const [currentView, subViews] = this.extractSubViews(rootStatement, 0, module, "");
432     this._views.push(currentView, ...subViews);
433
434     // create the root elements for this module
435     module.elements = currentView.elements;
436     this._modulesToResolve.push(() => {
437       Object.keys(module.elements).forEach(key => {
438         const viewElement = module.elements[key];
439         if (!(isViewElementObjectOrList(viewElement) || isViewElementRpc(viewElement))) {
440           console.error(new Error(`Module: [${module}]. Only Object, List or RPC are allowed on root level.`));
441         }
442         if (isViewElementObjectOrList(viewElement)) {
443           const viewIdIndex = Number(viewElement.viewId);
444           module.views[key] = this._views[viewIdIndex];
445         }
446         
447         // add only the UI View if the module is available
448         if (module.state === ModuleState.stable || module.state === ModuleState.instable) this._views[0].elements[key] = module.elements[key];
449       });
450     });
451     return module;
452   }
453
454   public postProcess() {
455
456     // execute all post processes like resolving in proper order
457     this._unionsToResolve.forEach(cb => {
458       try { cb(); } catch (error) {
459         console.warn(error.message);
460       }
461     });
462
463     // process all groupings
464     this._groupingsToResolve.filter(vs => vs.uses && vs.uses[ResolveFunction]).forEach(vs => {
465       try { vs.uses![ResolveFunction] !== undefined && vs.uses![ResolveFunction]!("|"); } catch (error) {
466         console.warn(`Error resolving: [${vs.name}] [${error.message}]`);
467       }
468     });
469
470     // process all augmentations / sort by namespace changes to ensure proper order 
471     Object.keys(this.modules).forEach(modKey => {
472       const module = this.modules[modKey];
473       const augmentKeysWithCounter = Object.keys(module.augments).map((key) => {
474         const pathParts = splitVPath(key, /(?:(?:([^\/\:]+):)?([^\/]+))/g);  // 1 = opt: namespace / 2 = property 
475         let nameSpaceChangeCounter = 0;
476         let currentNS = module.name; // init namespace
477         pathParts.forEach(([ns, _])=> {
478           if (ns === currentNS){
479             currentNS = ns;
480             nameSpaceChangeCounter++;
481           }
482         });
483         return {
484           key,
485           nameSpaceChangeCounter,
486         }
487       });
488       
489       const augmentKeys = augmentKeysWithCounter
490         .sort((a,b) => a.nameSpaceChangeCounter > b.nameSpaceChangeCounter ? 1 : a.nameSpaceChangeCounter === b.nameSpaceChangeCounter ? 0 : -1 )
491         .map((a) => a.key);
492
493       augmentKeys.forEach(augKey => {
494         const augments = module.augments[augKey];
495         const viewSpec = this.resolveView(augKey);
496         if (!viewSpec) console.warn(`Could not find view to augment [${augKey}] in [${module.name}].`);
497         if (augments && viewSpec) {
498           augments.forEach(augment => Object.keys(augment.elements).forEach(key => {
499             const elm = augment.elements[key];
500             viewSpec.elements[key] = {
501               ...augment.elements[key],
502               
503               when: elm.when ? `(${augment.when}) and (${elm.when})` : augment.when,
504               ifFeature: elm.ifFeature ? `(${augment.ifFeature}) and (${elm.ifFeature})` : augment.ifFeature,
505             };
506           }));
507         }
508       });
509     });
510
511     // process Identities
512     const traverseIdentity = (identities: Identity[]) => {
513       const result: Identity[] = [];
514       for (let identity of identities) {
515         if (identity.children && identity.children.length > 0) {
516           result.push(...traverseIdentity(identity.children));
517         } else {
518           result.push(identity);
519         }
520       }
521       return result;
522     }
523
524     const baseIdentities: Identity[] = [];
525     Object.keys(this.modules).forEach(modKey => {
526       const module = this.modules[modKey];
527       Object.keys(module.identities).forEach(idKey => {
528         const identity = module.identities[idKey];
529         if (identity.base != null) {
530           const base = this.resolveIdentity(identity.base, module);
531           base.children?.push(identity);
532         } else {
533           baseIdentities.push(identity);
534         }
535       });
536     });
537     baseIdentities.forEach(identity => {
538       identity.values = identity.children && traverseIdentity(identity.children) || [];
539     });
540
541     this._identityToResolve.forEach(cb => {
542       try { cb(); } catch (error) {
543         console.warn(error.message);
544       }
545     });
546
547     this._modulesToResolve.forEach(cb => {
548       try { cb(); } catch (error) {
549         console.warn(error.message);
550       }
551     });
552
553     // resolve readOnly
554     const resolveReadOnly = (view: ViewSpecification, parentConfig: boolean) => {
555       
556       // update view config
557       view.config = view.config && parentConfig;
558       
559       Object.keys(view.elements).forEach((key) => {
560         const elm = view.elements[key];
561
562         // update element config
563         elm.config = elm.config && view.config;
564         
565         // update all sub-elements of objects
566         if (elm.uiType === "object") {
567           resolveReadOnly(this.views[+elm.viewId], elm.config);
568         }
569
570       })
571     }
572
573     const dump = resolveReadOnly(this.views[0], true); 
574   };
575
576   private _nextId = 1;
577   private get nextId() {
578     return this._nextId++;
579   }
580
581   private extractNodes(statement: Statement, key: string): Statement[] {
582     return statement.sub && statement.sub.filter(s => s.key === key) || [];
583   }
584
585   private extractValue(statement: Statement, key: string): string | undefined;
586   private extractValue(statement: Statement, key: string, parser: RegExp): RegExpExecArray | undefined;
587   private extractValue(statement: Statement, key: string, parser?: RegExp): string | RegExpExecArray | undefined {
588     const typeNodes = this.extractNodes(statement, key);
589     const rawValue = typeNodes.length > 0 && typeNodes[0].arg || undefined;
590     return parser
591       ? rawValue && parser.exec(rawValue) || undefined
592       : rawValue;
593   }
594
595   private extractTypeDefinitions(statement: Statement, module: Module, currentPath: string): void {
596     const typedefs = this.extractNodes(statement, "typedef");
597     typedefs && typedefs.forEach(def => {
598       if (!def.arg) {
599         throw new Error(`Module: [${module.name}]. Found typefed without name.`);
600       }
601       module.typedefs[def.arg] = this.getViewElement(def, module, 0, currentPath, false);
602     });
603   }
604
605   /** Handles groupings like named Container */
606   private extractGroupings(statement: Statement, parentId: number, module: Module, currentPath: string): ViewSpecification[] {
607     const subViews: ViewSpecification[] = [];
608     const groupings = this.extractNodes(statement, "grouping");
609     if (groupings && groupings.length > 0) {
610       subViews.push(...groupings.reduce<ViewSpecification[]>((acc, cur) => {
611         if (!cur.arg) {
612           throw new Error(`Module: [${module.name}][${currentPath}]. Found grouping without name.`);
613         }
614         const grouping = cur.arg;
615
616         // the default for config on module level is config = true;
617         const [currentView, subViews] = this.extractSubViews(cur, /* parentId */ -1, module, currentPath);
618         grouping && (module.groupings[grouping] = currentView);
619         acc.push(currentView, ...subViews);
620         return acc;
621       }, []));
622     }
623
624     return subViews;
625   }
626
627   /** Handles augments also like named container */
628   private extractAugments(statement: Statement, parentId: number, module: Module, currentPath: string): ViewSpecification[] {
629     const subViews: ViewSpecification[] = [];
630     const augments = this.extractNodes(statement, "augment");
631     if (augments && augments.length > 0) {
632       subViews.push(...augments.reduce<ViewSpecification[]>((acc, cur) => {
633         if (!cur.arg) {
634           throw new Error(`Module: [${module.name}][${currentPath}]. Found augment without path.`);
635         }
636         const augment = this.resolveReferencePath(cur.arg, module);
637
638         // the default for config on module level is config = true;
639         const [currentView, subViews] = this.extractSubViews(cur, parentId, module, currentPath);
640         if (augment) {
641           module.augments[augment] = module.augments[augment] || [];
642           module.augments[augment].push(currentView);
643         }
644         acc.push(currentView, ...subViews);
645         return acc;
646       }, []));
647     }
648
649     return subViews;
650   }
651
652   /** Handles identities  */
653   private extractIdentities(statement: Statement, parentId: number, module: Module, currentPath: string) {
654     const identities = this.extractNodes(statement, "identity");
655     module.identities = identities.reduce<{ [name: string]: Identity }>((acc, cur) => {
656       if (!cur.arg) {
657         throw new Error(`Module: [${module.name}][${currentPath}]. Found identiy without name.`);
658       }
659       acc[cur.arg] = {
660         id: `${module.name}:${cur.arg}`,
661         label: cur.arg,
662         base: this.extractValue(cur, "base"),
663         description: this.extractValue(cur, "description"),
664         reference: this.extractValue(cur, "reference"),
665         children: []
666       }
667       return acc;
668     }, {});
669   }
670
671    // Hint: use 0 as parentId for rootElements and -1 for rootGroupings.
672   private extractSubViews(statement: Statement, parentId: number, module: Module, currentPath: string): [ViewSpecification, ViewSpecification[]] {
673     // used for scoped definitions
674     const context: Module = {
675       ...module,
676       typedefs: {
677         ...module.typedefs
678       }
679     };
680
681     const currentId = this.nextId;
682     const subViews: ViewSpecification[] = [];
683     let elements: ViewElement[] = [];
684
685     const configValue = this.extractValue(statement, "config");
686     const config = configValue == null ? true : configValue.toLocaleLowerCase() !== "false";
687
688     // extract conditions
689     const ifFeature = this.extractValue(statement, "if-feature");
690     const whenCondition = this.extractValue(statement, "when");
691     if (whenCondition) console.warn("Found in [" + context.name + "]" + currentPath + " when: " + whenCondition);
692
693     // extract all scoped typedefs
694     this.extractTypeDefinitions(statement, context, currentPath);
695
696     // extract all scoped groupings
697     subViews.push(
698       ...this.extractGroupings(statement, parentId, context, currentPath)
699     );
700
701     // extract all container
702     const container = this.extractNodes(statement, "container");
703     if (container && container.length > 0) {
704       subViews.push(...container.reduce<ViewSpecification[]>((acc, cur) => {
705         if (!cur.arg) {
706           throw new Error(`Module: [${context.name}]${currentPath}. Found container without name.`);
707         }
708         const [currentView, subViews] = this.extractSubViews(cur, currentId, context, `${currentPath}/${context.name}:${cur.arg}`);
709         elements.push({
710           id: parentId === 0 ? `${context.name}:${cur.arg}` : cur.arg,
711           label: cur.arg,
712           path: currentPath,
713           module: context.name || module.name || '',
714           uiType: "object",
715           viewId: currentView.id,
716           config: currentView.config,
717         });
718         acc.push(currentView, ...subViews);
719         return acc;
720       }, []));
721     }
722
723     // process all lists
724     // a list is a list of containers with the leafs contained in the list
725     const lists = this.extractNodes(statement, "list");
726     if (lists && lists.length > 0) {
727       subViews.push(...lists.reduce<ViewSpecification[]>((acc, cur) => {
728         let elmConfig = config;
729         if (!cur.arg) {
730           throw new Error(`Module: [${context.name}]${currentPath}. Found list without name.`);
731         }
732         const key = this.extractValue(cur, "key") || undefined;
733         if (elmConfig && !key) {
734           console.warn(`Module: [${context.name}]${currentPath}. Found configurable list without key. Assume config shell be false.`);
735           elmConfig = false;
736         }
737         const [currentView, subViews] = this.extractSubViews(cur, currentId, context, `${currentPath}/${context.name}:${cur.arg}`);
738         elements.push({
739           id: parentId === 0 ? `${context.name}:${cur.arg}` : cur.arg,
740           label: cur.arg,
741           path: currentPath,
742           module: context.name || module.name || '',
743           isList: true,
744           uiType: "object",
745           viewId: currentView.id,
746           key: key,
747           config: elmConfig && currentView.config,
748         });
749         acc.push(currentView, ...subViews);
750         return acc;
751       }, []));
752     }
753
754     // process all leaf-lists
755     // a leaf-list is a list of some type
756     const leafLists = this.extractNodes(statement, "leaf-list");
757     if (leafLists && leafLists.length > 0) {
758       elements.push(...leafLists.reduce<ViewElement[]>((acc, cur) => {
759         const element = this.getViewElement(cur, context, parentId, currentPath, true);
760         element && acc.push(element);
761         return acc;
762       }, []));
763     }
764
765     // process all leafs
766     // a leaf is mainly a property of an object
767     const leafs = this.extractNodes(statement, "leaf");
768     if (leafs && leafs.length > 0) {
769       elements.push(...leafs.reduce<ViewElement[]>((acc, cur) => {
770         const element = this.getViewElement(cur, context, parentId, currentPath, false);
771         element && acc.push(element);
772         return acc;
773       }, []));
774     }
775
776
777     const choiceStms = this.extractNodes(statement, "choice");
778     if (choiceStms && choiceStms.length > 0) {
779       elements.push(...choiceStms.reduce<ViewElementChoise[]>((accChoise, curChoise) => {
780         if (!curChoise.arg) {
781           throw new Error(`Module: [${context.name}]${currentPath}. Found choise without name.`);
782         }
783         // extract all cases like containers
784         const cases: { id: string, label: string, description?: string, elements: { [name: string]: ViewElement } }[] = [];
785         const caseStms = this.extractNodes(curChoise, "case");
786         if (caseStms && caseStms.length > 0) {
787           cases.push(...caseStms.reduce((accCase, curCase) => {
788             if (!curCase.arg) {
789               throw new Error(`Module: [${context.name}]${currentPath}/${curChoise.arg}. Found case without name.`);
790             }
791             const description = this.extractValue(curCase, "description") || undefined;
792             const [caseView, caseSubViews] = this.extractSubViews(curCase, parentId, context, `${currentPath}/${context.name}:${curChoise.arg}`);
793             subViews.push(caseView, ...caseSubViews);
794
795             const caseDef: { id: string, label: string, description?: string, elements: { [name: string]: ViewElement } } = {
796               id: parentId === 0 ? `${context.name}:${curCase.arg}` : curCase.arg,
797               label: curCase.arg,
798               description: description,
799               elements: caseView.elements
800             };
801             accCase.push(caseDef);
802             return accCase;
803           }, [] as { id: string, label: string, description?: string, elements: { [name: string]: ViewElement } }[]));
804         }
805
806         // extract all simple cases (one case per leaf, container, etc.)
807         const [choiseView, choiseSubViews] = this.extractSubViews(curChoise, parentId, context, `${currentPath}/${context.name}:${curChoise.arg}`);
808         subViews.push(choiseView, ...choiseSubViews);
809         cases.push(...Object.keys(choiseView.elements).reduce((accElm, curElm) => {
810           const elm = choiseView.elements[curElm];
811           const caseDef: { id: string, label: string, description?: string, elements: { [name: string]: ViewElement } } = {
812             id: elm.id,
813             label: elm.label,
814             description: elm.description,
815             elements: { [elm.id]: elm }
816           };
817           accElm.push(caseDef);
818           return accElm;
819         }, [] as { id: string, label: string, description?: string, elements: { [name: string]: ViewElement } }[]));
820
821         const description = this.extractValue(curChoise, "description") || undefined;
822         const configValue = this.extractValue(curChoise, "config");
823         const config = configValue == null ? true : configValue.toLocaleLowerCase() !== "false";
824
825         const mandatory = this.extractValue(curChoise, "mandatory") === "true" || false;
826
827         const element: ViewElementChoise = {
828           uiType: "choise",
829           id: parentId === 0 ? `${context.name}:${curChoise.arg}` : curChoise.arg,
830           label: curChoise.arg,
831           path: currentPath,
832           module: context.name || module.name || '',
833           config: config,
834           mandatory: mandatory,
835           description: description,
836           cases: cases.reduce((acc, cur) => {
837             acc[cur.id] = cur;
838             return acc;
839           }, {} as { [name: string]: { id: string, label: string, description?: string, elements: { [name: string]: ViewElement } } })
840         };
841
842         accChoise.push(element);
843         return accChoise;
844       }, []));
845     }
846
847     const rpcStms = this.extractNodes(statement, "rpc");
848     if (rpcStms && rpcStms.length > 0) {
849       elements.push(...rpcStms.reduce<ViewElementRpc[]>((accRpc, curRpc) => {
850         if (!curRpc.arg) {
851           throw new Error(`Module: [${context.name}]${currentPath}. Found rpc without name.`);
852         }
853
854         const description = this.extractValue(curRpc, "description") || undefined;
855         const configValue = this.extractValue(curRpc, "config");
856         const config = configValue == null ? true : configValue.toLocaleLowerCase() !== "false";
857
858         let inputViewId: string | undefined = undefined;
859         let outputViewId: string | undefined = undefined;
860
861         const input = this.extractNodes(curRpc, "input") || undefined;
862         const output = this.extractNodes(curRpc, "output") || undefined;
863
864         if (input && input.length > 0) {
865           const [inputView, inputSubViews] = this.extractSubViews(input[0], parentId, context, `${currentPath}/${context.name}:${curRpc.arg}`);
866           subViews.push(inputView, ...inputSubViews);
867           inputViewId = inputView.id;
868         }
869
870         if (output && output.length > 0) {
871           const [outputView, outputSubViews] = this.extractSubViews(output[0], parentId, context, `${currentPath}/${context.name}:${curRpc.arg}`);
872           subViews.push(outputView, ...outputSubViews);
873           outputViewId = outputView.id;
874         }
875
876         const element: ViewElementRpc = {
877           uiType: "rpc",
878           id: parentId === 0 ? `${context.name}:${curRpc.arg}` : curRpc.arg,
879           label: curRpc.arg,
880           path: currentPath,
881           module: context.name || module.name || '',
882           config: config,
883           description: description,
884           inputViewId: inputViewId,
885           outputViewId: outputViewId,
886         };
887
888         accRpc.push(element);
889
890         return accRpc;
891       }, []));
892     }
893
894     // if (!statement.arg) {
895     //   throw new Error(`Module: [${context.name}]. Found statement without name.`);
896     // }
897
898     const viewSpec: ViewSpecification = {
899       id: String(currentId),
900       parentView: String(parentId),
901       ns: context.name,
902       name: statement.arg != null ? statement.arg : undefined,
903       title: statement.arg != null ? statement.arg : undefined,
904       language: "en-us",
905       canEdit: false,
906       config: config,
907       ifFeature: ifFeature,
908       when: whenCondition,
909       elements: elements.reduce<{ [name: string]: ViewElement }>((acc, cur) => {
910         acc[cur.id] = cur;
911         return acc;
912       }, {}),
913     };
914
915     // evaluate canEdit depending on all conditions
916     Object.defineProperty(viewSpec, "canEdit", {
917       get: () => {
918         return Object.keys(viewSpec.elements).some(key => {
919           const elm = viewSpec.elements[key];
920           return (!isViewElementObjectOrList(elm) && elm.config);
921         });
922       }
923     });
924
925     // merge in all uses references and resolve groupings
926     const usesRefs = this.extractNodes(statement, "uses");
927     if (usesRefs && usesRefs.length > 0) {
928
929       viewSpec.uses = (viewSpec.uses || []);
930       const resolveFunctions : ((parentElementPath: string)=>void)[] = [];
931
932       for (let i = 0; i < usesRefs.length; ++i) {
933         const groupingName = usesRefs[i].arg;
934         if (!groupingName) {
935           throw new Error(`Module: [${context.name}]. Found an uses statement without a grouping name.`);
936         }
937
938         viewSpec.uses.push(this.resolveReferencePath(groupingName, context));
939         
940         resolveFunctions.push((parentElementPath: string) => {
941           const groupingViewSpec = this.resolveGrouping(groupingName, context);
942           if (groupingViewSpec) {
943
944             // resolve recursive
945             const resolveFunc = groupingViewSpec.uses && groupingViewSpec.uses[ResolveFunction];
946             resolveFunc && resolveFunc(parentElementPath);
947
948             Object.keys(groupingViewSpec.elements).forEach(key => {
949               const elm = groupingViewSpec.elements[key];
950               // a useRef on root level need a namespace
951               viewSpec.elements[parentId === 0 ? `${module.name}:${key}` : key] = {
952                 ...elm,
953                 when: elm.when ? `(${groupingViewSpec.when}) and (${elm.when})` : groupingViewSpec.when,
954                 ifFeature: elm.ifFeature ? `(${groupingViewSpec.ifFeature}) and (${elm.ifFeature})` : groupingViewSpec.ifFeature,
955               };
956             });
957           }
958         });
959       }
960
961       viewSpec.uses[ResolveFunction] = (parentElementPath: string) => {
962         const currentElementPath = `${parentElementPath} -> ${viewSpec.ns}:${viewSpec.name}`;  
963         resolveFunctions.forEach(resolve => {
964             try {
965                 resolve(currentElementPath);
966             } catch (error) {
967                 console.error(error);
968             }
969         });
970         // console.log("Resolved "+currentElementPath, viewSpec);
971         if (viewSpec?.uses) {
972           viewSpec.uses[ResolveFunction] = undefined;
973         }
974       }
975
976       this._groupingsToResolve.push(viewSpec);
977     }
978
979     return [viewSpec, subViews];
980   }
981
982   // https://tools.ietf.org/html/rfc7950#section-9.3.4
983   private static decimalRange = [
984     { min: -9223372036854775808, max: 9223372036854775807 },
985     { min: -922337203685477580.8, max: 922337203685477580.7 },
986     { min: -92233720368547758.08, max: 92233720368547758.07 },
987     { min: -9223372036854775.808, max: 9223372036854775.807 },
988     { min: -922337203685477.5808, max: 922337203685477.5807 },
989     { min: -92233720368547.75808, max: 92233720368547.75807 },
990     { min: -9223372036854.775808, max: 9223372036854.775807 },
991     { min: -922337203685.4775808, max: 922337203685.4775807 },
992     { min: -92233720368.54775808, max: 92233720368.54775807 },
993     { min: -9223372036.854775808, max: 9223372036.854775807 },
994     { min: -922337203.6854775808, max: 922337203.6854775807 },
995     { min: -92233720.36854775808, max: 92233720.36854775807 },
996     { min: -9223372.036854775808, max: 9223372.036854775807 },
997     { min: -922337.2036854775808, max: 922337.2036854775807 },
998     { min: -92233.72036854775808, max: 92233.72036854775807 },
999     { min: -9223.372036854775808, max: 9223.372036854775807 },
1000     { min: -922.3372036854775808, max: 922.3372036854775807 },
1001     { min: -92.23372036854775808, max: 92.23372036854775807 },
1002     { min: -9.223372036854775808, max: 9.223372036854775807 },
1003   ];
1004
1005   /** Extracts the UI View from the type in the cur statement. */
1006   private getViewElement(cur: Statement, module: Module, parentId: number, currentPath: string, isList: boolean): ViewElement {
1007
1008     const type = this.extractValue(cur, "type");
1009     const defaultVal = this.extractValue(cur, "default") || undefined;
1010     const description = this.extractValue(cur, "description") || undefined;
1011
1012     const configValue = this.extractValue(cur, "config");
1013     const config = configValue == null ? true : configValue.toLocaleLowerCase() !== "false";
1014
1015     const extractRange = (min: number, max: number, property: string = "range"): { expression: Expression<YangRange> | undefined, min: number, max: number } => {
1016       const ranges = this.extractValue(this.extractNodes(cur, "type")[0]!, property) || undefined;
1017       const range = ranges ?.replace(/min/i, String(min)).replace(/max/i, String(max)).split("|").map(r => {
1018         let minValue: number;
1019         let maxValue: number;
1020         
1021         if (r.indexOf('..') > -1) {
1022             const [minStr, maxStr] = r.split('..');
1023             minValue = Number(minStr);
1024             maxValue = Number(maxStr);
1025         } else if (!isNaN(maxValue = Number(r && r.trim() )) ) {
1026             minValue = maxValue;
1027         } else {
1028             minValue = min,
1029             maxValue = max;
1030         }
1031
1032         if (minValue > min) min = minValue;
1033         if (maxValue < max) max = maxValue;
1034
1035         return {
1036           min: minValue,
1037           max: maxValue
1038         };
1039       });
1040       return {
1041         min: min,
1042         max: max,
1043         expression: range && range.length === 1
1044           ? range[0]
1045           : range && range.length > 1
1046             ? { operation: "OR", arguments: range }
1047             : undefined
1048       }
1049     };
1050
1051     const extractPattern = (): Expression<RegExp> | undefined => {
1052       const pattern = this.extractNodes(this.extractNodes(cur, "type")[0]!, "pattern").map(p => p.arg!).filter(p => !!p).map(p => `^${p}$`);
1053       return pattern && pattern.length == 1
1054         ? new RegExp(pattern[0])
1055         : pattern && pattern.length > 1
1056           ? { operation: "AND", arguments: pattern.map(p => new RegExp(p)) }
1057           : undefined;
1058     }
1059
1060     const mandatory = this.extractValue(cur, "mandatory") === "true" || false;
1061
1062     if (!cur.arg) {
1063       throw new Error(`Module: [${module.name}]. Found element without name.`);
1064     }
1065
1066     if (!type) {
1067       throw new Error(`Module: [${module.name}].[${cur.arg}]. Found element without type.`);
1068     }
1069
1070     const element: ViewElementBase = {
1071       id: parentId === 0 ? `${module.name}:${cur.arg}` : cur.arg,
1072       label: cur.arg, 
1073       path: currentPath,
1074       module: module.name || "",
1075       config: config,
1076       mandatory: mandatory,
1077       isList: isList,
1078       default: defaultVal,
1079       description: description
1080     };
1081
1082     if (type === "string") {
1083       const length = extractRange(0, +18446744073709551615, "length");
1084       return ({
1085         ...element,
1086         uiType: "string",
1087         length: length.expression,
1088         pattern: extractPattern(),
1089       });
1090     } else if (type === "boolean") {
1091       return ({
1092         ...element,
1093         uiType: "boolean"
1094       });
1095     } else if (type === "uint8") {
1096       const range = extractRange(0, +255);
1097       return ({
1098         ...element,
1099         uiType: "number",
1100         range: range.expression,
1101         min: range.min,
1102         max: range.max,
1103         units: this.extractValue(cur, "units") || undefined,
1104         format: this.extractValue(cur, "format") || undefined,
1105       });
1106     } else if (type === "uint16") {
1107       const range = extractRange(0, +65535);
1108       return ({
1109         ...element,
1110         uiType: "number",
1111         range: range.expression,
1112         min: range.min,
1113         max: range.max,
1114         units: this.extractValue(cur, "units") || undefined,
1115         format: this.extractValue(cur, "format") || undefined,
1116       });
1117     } else if (type === "uint32") {
1118       const range = extractRange(0, +4294967295);
1119       return ({
1120         ...element,
1121         uiType: "number",
1122         range: range.expression,
1123         min: range.min,
1124         max: range.max,
1125         units: this.extractValue(cur, "units") || undefined,
1126         format: this.extractValue(cur, "format") || undefined,
1127       });
1128     } else if (type === "uint64") {
1129       const range = extractRange(0, +18446744073709551615);
1130       return ({
1131         ...element,
1132         uiType: "number",
1133         range: range.expression,
1134         min: range.min,
1135         max: range.max,
1136         units: this.extractValue(cur, "units") || undefined,
1137         format: this.extractValue(cur, "format") || undefined,
1138       });
1139     } else if (type === "int8") {
1140       const range = extractRange(-128, +127);
1141       return ({
1142         ...element,
1143         uiType: "number",
1144         range: range.expression,
1145         min: range.min,
1146         max: range.max,
1147         units: this.extractValue(cur, "units") || undefined,
1148         format: this.extractValue(cur, "format") || undefined,
1149       });
1150     } else if (type === "int16") {
1151       const range = extractRange(-32768, +32767);
1152       return ({
1153         ...element,
1154         uiType: "number",
1155         range: range.expression,
1156         min: range.min,
1157         max: range.max,
1158         units: this.extractValue(cur, "units") || undefined,
1159         format: this.extractValue(cur, "format") || undefined,
1160       });
1161     } else if (type === "int32") {
1162       const range = extractRange(-2147483648, +2147483647);
1163       return ({
1164         ...element,
1165         uiType: "number",
1166         range: range.expression,
1167         min: range.min,
1168         max: range.max,
1169         units: this.extractValue(cur, "units") || undefined,
1170         format: this.extractValue(cur, "format") || undefined,
1171       });
1172     } else if (type === "int64") {
1173       const range = extractRange(-9223372036854775808, +9223372036854775807);
1174       return ({
1175         ...element,
1176         uiType: "number",
1177         range: range.expression,
1178         min: range.min,
1179         max: range.max,
1180         units: this.extractValue(cur, "units") || undefined,
1181         format: this.extractValue(cur, "format") || undefined,
1182       });
1183     } else if (type === "decimal64") {
1184       // decimalRange
1185       const fDigits = Number(this.extractValue(this.extractNodes(cur, "type")[0]!, "fraction-digits")) || -1;
1186       if (fDigits === -1) {
1187         throw new Error(`Module: [${module.name}][${currentPath}][${cur.arg}]. Found decimal64 with invalid fraction-digits.`);
1188       }
1189       const range = extractRange(YangParser.decimalRange[fDigits].min, YangParser.decimalRange[fDigits].max);
1190       return ({
1191         ...element,
1192         uiType: "number",
1193         fDigits: fDigits,
1194         range: range.expression,
1195         min: range.min,
1196         max: range.max,
1197         units: this.extractValue(cur, "units") || undefined,
1198         format: this.extractValue(cur, "format") || undefined,
1199       });
1200     } else if (type === "enumeration") {
1201       const typeNode = this.extractNodes(cur, "type")[0]!;
1202       const enumNodes = this.extractNodes(typeNode, "enum");
1203       return ({
1204         ...element,
1205         uiType: "selection",
1206         options: enumNodes.reduce<{ key: string; value: string; description?: string }[]>((acc, enumNode) => {
1207           if (!enumNode.arg) {
1208             throw new Error(`Module: [${module.name}][${currentPath}][${cur.arg}]. Found option without name.`);
1209           }
1210           const ifClause = this.extractValue(enumNode, "if-feature");
1211           const value = this.extractValue(enumNode, "value");
1212           const enumOption = {
1213             key: enumNode.arg,
1214             value: value != null ? value : enumNode.arg,
1215             description: this.extractValue(enumNode, "description") || undefined
1216           };
1217           // todo: ❗ handle the if clause ⚡
1218           acc.push(enumOption);
1219           return acc;
1220         }, [])
1221       });
1222     } else if (type === "leafref") {
1223       const typeNode = this.extractNodes(cur, "type")[0]!;
1224       const vPath = this.extractValue(typeNode, "path");
1225       if (!vPath) {
1226         throw new Error(`Module: [${module.name}][${currentPath}][${cur.arg}]. Found leafref without path.`);
1227       }
1228       const refPath = this.resolveReferencePath(vPath, module);
1229       const resolve = this.resolveReference.bind(this);
1230       const res: ViewElement = {
1231         ...element,
1232         uiType: "reference",
1233         referencePath: refPath,
1234         ref(this: ViewElement, currentPath: string) {
1235           const elementPath = `${currentPath}/${cur.arg}`;  
1236           
1237           const result = resolve(refPath, elementPath);
1238           if (!result) return undefined;
1239
1240           const [resolvedElement, resolvedPath] = result;
1241           return resolvedElement && [{
1242             ...resolvedElement,
1243             id: this.id,
1244             label: this.label,
1245             config: this.config,
1246             mandatory: this.mandatory,
1247             isList: this.isList,
1248             default: this.default,
1249             description: this.description,
1250           } as ViewElement , resolvedPath] || undefined;
1251         }
1252       };
1253       return res;
1254     } else if (type === "identityref") {
1255       const typeNode = this.extractNodes(cur, "type")[0]!;
1256       const base = this.extractValue(typeNode, "base");
1257       if (!base) {
1258         throw new Error(`Module: [${module.name}][${currentPath}][${cur.arg}]. Found identityref without base.`);
1259       }
1260       const res: ViewElement = {
1261         ...element,
1262         uiType: "selection",
1263         options: []
1264       };
1265       this._identityToResolve.push(() => {
1266         const identity: Identity = this.resolveIdentity(base, module);
1267         if (!identity) {
1268           throw new Error(`Module: [${module.name}][${currentPath}][${cur.arg}]. Could not resolve identity [${base}].`);
1269         }
1270         if (!identity.values || identity.values.length === 0) {
1271           throw new Error(`Identity: [${base}] has no values.`);
1272         }
1273         res.options = identity.values.map(val => ({
1274           key: val.id,
1275           value: val.id,
1276           description: val.description
1277         }));
1278       });
1279       return res;
1280     } else if (type === "empty") {
1281       // todo: ❗ handle empty ⚡
1282       /*  9.11.  The empty Built-In Type
1283           The empty built-in type represents a leaf that does not have any
1284           value, it conveys information by its presence or absence. */
1285       return {
1286         ...element,
1287         uiType: "empty",
1288       };
1289     } else if (type === "union") {
1290       // todo: ❗ handle union ⚡
1291       /* 9.12.  The union Built-In Type */
1292       const typeNode = this.extractNodes(cur, "type")[0]!;
1293       const typeNodes = this.extractNodes(typeNode, "type");
1294
1295       const resultingElement = {
1296         ...element,
1297         uiType: "union",
1298         elements: []
1299       } as ViewElementUnion;
1300
1301       const resolveUnion = () => {
1302         resultingElement.elements.push(...typeNodes.map(node => {
1303           const stm: Statement = {
1304             ...cur,
1305             sub: [
1306               ...(cur.sub ?.filter(s => s.key !== "type") || []),
1307               node
1308             ]
1309           };
1310           return {
1311             ...this.getViewElement(stm, module, parentId, currentPath, isList),
1312             id: node.arg!
1313           };
1314         }));
1315       };
1316
1317       this._unionsToResolve.push(resolveUnion);
1318
1319       return resultingElement;
1320     } else if (type === "bits") {
1321       const typeNode = this.extractNodes(cur, "type")[0]!;
1322       const bitNodes = this.extractNodes(typeNode, "bit");
1323       return {
1324         ...element,
1325         uiType: "bits",
1326         flags: bitNodes.reduce<{ [name: string]: number | undefined; }>((acc, bitNode) => {
1327           if (!bitNode.arg) {
1328             throw new Error(`Module: [${module.name}][${currentPath}][${cur.arg}]. Found bit without name.`);
1329           }
1330           const ifClause = this.extractValue(bitNode, "if-feature");
1331           const pos = Number(this.extractValue(bitNode, "position"));
1332           acc[bitNode.arg] = pos === pos ? pos : undefined;
1333           return acc;
1334         }, {})
1335       };
1336     } else if (type === "binary") {
1337       return {
1338         ...element,
1339         uiType: "binary",
1340         length: extractRange(0, +18446744073709551615, "length"),
1341       };
1342     } else if (type === "instance-identifier") {
1343       // https://tools.ietf.org/html/rfc7950#page-168
1344       return {
1345         ...element,
1346         uiType: "string",
1347         length: extractRange(0, +18446744073709551615, "length"),
1348       };
1349     } else {
1350       // not a build in type, need to resolve type
1351       let typeRef = this.resolveType(type, module);
1352       if (typeRef == null) console.error(new Error(`Could not resolve type ${type} in [${module.name}][${currentPath}].`));
1353
1354
1355       if (isViewElementString(typeRef)) {
1356         typeRef = this.resolveStringType(typeRef, extractPattern(), extractRange(0, +18446744073709551615));
1357       } else if (isViewElementNumber(typeRef)) {
1358         typeRef = this.resolveNumberType(typeRef, extractRange(typeRef.min, typeRef.max));
1359       }
1360
1361       // spoof date type here from special string type
1362       if ((type === 'date-and-time' || type.endsWith(':date-and-time') ) && typeRef.module === "ietf-yang-types") {
1363           return {
1364              ...typeRef,
1365              ...element,
1366              description: description,
1367              uiType: "date", 
1368           };
1369       }
1370
1371       return ({
1372         ...typeRef,
1373         ...element,
1374         description: description,
1375       }) as ViewElement;
1376     }
1377   }
1378
1379   private resolveStringType(parentElement: ViewElementString, pattern: Expression<RegExp> | undefined, length: { expression: Expression<YangRange> | undefined, min: number, max: number }) {
1380     return {
1381       ...parentElement,
1382       pattern: pattern != null && parentElement.pattern
1383         ? { operation: "AND", arguments: [pattern, parentElement.pattern] }
1384         : parentElement.pattern
1385           ? parentElement.pattern
1386           : pattern,
1387       length: length.expression != null && parentElement.length
1388         ? { operation: "AND", arguments: [length.expression, parentElement.length] }
1389         : parentElement.length
1390           ? parentElement.length
1391           : length ?.expression,
1392     } as ViewElementString;
1393   }
1394
1395   private resolveNumberType(parentElement: ViewElementNumber, range: { expression: Expression<YangRange> | undefined, min: number, max: number }) {
1396     return {
1397       ...parentElement,
1398       range: range.expression != null && parentElement.range
1399         ? { operation: "AND", arguments: [range.expression, parentElement.range] }
1400         : parentElement.range
1401           ? parentElement.range
1402           : range,
1403       min: range.min,
1404       max: range.max,
1405     } as ViewElementNumber;
1406   }
1407
1408   private resolveReferencePath(vPath: string, module: Module) {
1409     const vPathParser = /(?:(?:([^\/\:]+):)?([^\/]+))/g // 1 = opt: namespace / 2 = property
1410     return vPath.replace(vPathParser, (_, ns, property) => {
1411       const nameSpace = ns && module.imports[ns] || module.name;
1412       return `${nameSpace}:${property}`;
1413     });
1414   }
1415
1416   private resolveReference(vPath: string, currentPath: string) {
1417     const vPathParser = /(?:(?:([^\/\[\]\:]+):)?([^\/\[\]]+)(\[[^\]]+\])?)/g // 1 = opt: namespace / 2 = property / 3 = opt: indexPath
1418     let element: ViewElement | null = null;
1419     let moduleName = "";
1420
1421     const vPathParts = splitVPath(vPath, vPathParser).map(p => ({ ns: p[1], property: p[2], ind: p[3] }));
1422     const resultPathParts = !vPath.startsWith("/")
1423       ? splitVPath(currentPath, vPathParser).map(p => { moduleName = p[1] || moduleName ; return { ns: moduleName, property: p[2], ind: p[3] } })
1424       : [];
1425
1426     for (let i = 0; i < vPathParts.length; ++i) {
1427       const vPathPart = vPathParts[i];
1428       if (vPathPart.property === "..") {
1429         resultPathParts.pop();
1430       } else if (vPathPart.property !== ".") {
1431         resultPathParts.push(vPathPart);
1432       }
1433     }
1434
1435     // resolve element by path
1436     for (let j = 0; j < resultPathParts.length; ++j) {
1437       const pathPart = resultPathParts[j];
1438       if (j === 0) {
1439         moduleName = pathPart.ns;
1440         const rootModule = this._modules[moduleName];
1441         if (!rootModule) throw new Error("Could not resolve module [" + moduleName + "].\r\n" + vPath);
1442         element = rootModule.elements[`${pathPart.ns}:${pathPart.property}`];
1443       } else if (element && isViewElementObjectOrList(element)) {
1444         const view: ViewSpecification = this._views[+element.viewId];
1445         if (moduleName !== pathPart.ns) {
1446           moduleName = pathPart.ns;
1447         }   
1448         element = view.elements[pathPart.property] || view.elements[`${moduleName}:${pathPart.property}`];
1449       } else {
1450         throw new Error("Could not resolve reference.\r\n" + vPath);
1451       }
1452       if (!element) throw new Error("Could not resolve path [" + pathPart.property + "] in [" + currentPath + "] \r\n" + vPath);
1453     }
1454
1455     moduleName = ""; // create the vPath for the resolved element, do not add the element itself this will be done later in the res(...) function
1456     return [element, resultPathParts.slice(0,-1).map(p => `${moduleName !== p.ns ? `${moduleName=p.ns}:` : ""}${p.property}${p.ind || ''}`).join("/")];
1457   }
1458
1459   private resolveView(vPath: string) {
1460     const vPathParser = /(?:(?:([^\/\[\]\:]+):)?([^\/\[\]]+)(\[[^\]]+\])?)/g // 1 = opt: namespace / 2 = property / 3 = opt: indexPath
1461     let element: ViewElement | null = null;
1462     let partMatch: RegExpExecArray | null;
1463     let view: ViewSpecification | null = null;
1464     let moduleName = "";
1465     if (vPath) do {
1466       partMatch = vPathParser.exec(vPath);
1467       if (partMatch) {
1468         if (element === null) {
1469           moduleName = partMatch[1]!;
1470           const rootModule = this._modules[moduleName];
1471           if (!rootModule) return null;
1472           element = rootModule.elements[`${moduleName}:${partMatch[2]!}`];
1473         } else if (isViewElementObjectOrList(element)) {
1474           view = this._views[+element.viewId];
1475           if (moduleName !== partMatch[1]) {
1476             moduleName = partMatch[1];
1477             element = view.elements[`${moduleName}:${partMatch[2]}`];
1478           } else {
1479             element = view.elements[partMatch[2]];
1480           }
1481         } else {
1482           return null;
1483         }
1484         if (!element) return null;
1485       }
1486     } while (partMatch)
1487     return element && isViewElementObjectOrList(element) && this._views[+element.viewId] || null;
1488   }
1489
1490   private resolveType(type: string, module: Module) {
1491     const collonInd = type.indexOf(":");
1492     const preFix = collonInd > -1 ? type.slice(0, collonInd) : "";
1493     const typeName = collonInd > -1 ? type.slice(collonInd + 1) : type;
1494
1495     const res = preFix
1496       ? this._modules[module.imports[preFix]].typedefs[typeName]
1497       : module.typedefs[typeName];
1498     return res;
1499   }
1500
1501   private resolveGrouping(grouping: string, module: Module) {
1502     const collonInd = grouping.indexOf(":");
1503     const preFix = collonInd > -1 ? grouping.slice(0, collonInd) : "";
1504     const groupingName = collonInd > -1 ? grouping.slice(collonInd + 1) : grouping;
1505
1506     return preFix
1507       ? this._modules[module.imports[preFix]].groupings[groupingName]
1508       : module.groupings[groupingName];
1509
1510   }
1511
1512   private resolveIdentity(identity: string, module: Module) {
1513     const collonInd = identity.indexOf(":");
1514     const preFix = collonInd > -1 ? identity.slice(0, collonInd) : "";
1515     const identityName = collonInd > -1 ? identity.slice(collonInd + 1) : identity;
1516
1517     return preFix
1518       ? this._modules[module.imports[preFix]].identities[identityName]
1519       : module.identities[identityName];
1520
1521   }
1522 }