devicetree-language-server 0.8.2 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -102,7 +102,7 @@ Repository: https://github.com/moxystudio/node-cross-spawn
102
102
 
103
103
  ----------------------------------------------------------------------
104
104
 
105
- devicetree-language-server@0.8.2
105
+ devicetree-language-server@0.8.3
106
106
  License: Apache-2.0
107
107
  Repository: https://github.com/kylebonnici/dts-lsp
108
108
 
package/dist/server.js CHANGED
@@ -281,7 +281,7 @@ ${" ".repeat(r-1)}};`}serialize(e,n,r=()=>!0){let i=this.mappedReg(n),s=this.imp
281
281
  `){let o=this.lineNumber,a=this.columnNumber,c=n.length;this.pushToken({tokens:[21],value:n,pos:{col:a-c,line:o,len:c,colEnd:a}}),n=""}else if(this.currentChar==="\\"){let o=this.lineNumber;if(n+=this.currentChar??"",this.move())o===this.lineNumber&&(n+=this.currentChar??"");else break}else n+=this.currentChar??"";if(!this.move())break}n+=e;let r=this.lineNumber,i=this.columnNumber+1,s=n.length;this.pushToken({tokens:[21],value:n,pos:{col:i-s,line:r,len:s,colEnd:i}}),this.move()}lexIt(){for(;!this.endOfFile;){for(;this.isWhiteSpace();)this.move();let e=this.getWord();e&&this.process(e)}}static{this.SINGLE_CHAR_TOKENS=new Map([["{",[2]],["}",[3]],["(",[42]],[")",[43]],["[",[11]],["]",[12]],[";",[1]],[":",[50]],["=",[0]],[">",[4]],["<",[5]],["!",[6]],["|",[8]],["^",[9]],["&",[40,7]],["~",[10]],["/",[13]],["\\",[14]],["+",[15]],["-",[16]],["*",[17]],["%",[18]],["?",[44]],[".",[45]],["_",[48]],["@",[49]],[",",[24]]])}static{this.KEYWORD_TOKENS=new Map([["true",38],["false",39],["#define",25],["#include",26],["#line",27],["#undef",28],["#error",29],["#pragma",30],["#defined",31],["#if",32],["#ifdef",33],["#ifndef",34],["#elif",35],["#else",36],["#endif",37]])}process(e){let n=this.isString(e);if(!n){let i=t.KEYWORD_TOKENS.get(e.toLowerCase());if(i&&(n=!0,this.pushToken({tokens:[i],value:e.toLowerCase(),pos:this.generatePos(e,e.toLowerCase())}),i===39||i===38)){let s=this.tokens.length-1;if(Vt(this.tokens[s-1],this.tokens[s]))n=!1,this.tokens.pop();else return!0}}if(n||(n=this.isDigit(e)||this.isHexDigit(e)||this.isLetters(e)),!n&&e.length===1){let i=t.SINGLE_CHAR_TOKENS.get(e);if(i)return n=!0,this.pushToken({tokens:i,value:e,pos:this.generatePos(e,e)}),!0}if(n||(n=this.isHash(e)||this.unknownToken(e)),!n)throw new Error(`Lexer is not complete!!! Could not find token for "${e}"`);let r=this._tokens[this._tokens.length-1];return n&&!r?.tokens.some(i=>i===21)&&r&&r.pos.len<e.length?this.process(e.slice(r.pos.len)):!0}pushToken(e){let n={tokens:e.tokens,pos:e.pos,value:e.value,fsPath:this.fsPath},r=this._tokens[this._tokens.length-1];n.prevToken=r,r&&(r.nextToken=n),this._tokens.push(n)}isLetters(e){let n=e[0]?.charCodeAt(0);if(t.isLetterCode(n)){let r="";for(let i=0;i<e.length;i++){let s=e.charCodeAt(i);if(t.isLetterCode(s))r+=e[i];else break}return this.pushToken({tokens:[47],value:r,pos:this.generatePos(e,r)}),!0}return!1}isDigit(e){let n=e[0],r=n?.charCodeAt(0);return r>=48&&r<=57?(this.pushToken({tokens:[20,19],value:n,pos:this.generatePos(e,n)}),!0):!1}isHexDigit(e){let n=e[0],r=n?.charCodeAt(0);return r>=65&&r<=70||r>=97&&r<=102?(this.pushToken({tokens:[20,47],value:n,pos:this.generatePos(e,n)}),!0):!1}isHash(e){let n="#";return e.startsWith(n)?(this.pushToken({tokens:[46],pos:this.generatePos(e,n),value:n}),!0):!1}unknownToken(e){return this.pushToken({tokens:[41],pos:this.generatePos(e," "),value:e}),!0}isString(e){if(this.inComment)return!1;let n=e[0];if(n==='"'||n==="'"){let r=e.length-1;if(this.columnNumber+1<r)throw new Error("Error while rewinding");return this.columnNumber-=r,this.getString(n),!0}return!1}generatePos(e,n){let r=this.columnNumber-e.length,i=n.length;return{line:this.lineNumber,col:r,len:i,colEnd:r+i}}};var OT=require("fs"),ba=require("path"),Qc=q(j());var ft=class extends te{constructor(e){super(e),this.semanticTokenType="keyword",this.semanticTokenModifiers="declaration"}};var aD=require("path"),Yf=q(j());var kr=class extends te{constructor(n,r){super();this.keyword=n;this.path=r;this.docSymbolsMeta={name:`Include ${r}`,kind:Yf.SymbolKind.File},this.addChild(n),this.addChild(r)}get resolvedPath(){return this._resolvedPath}set resolvedPath(n){this.docSymbolsMeta={name:`Include ${n}`,kind:Yf.SymbolKind.File},this._resolvedPath=n}},Ta=class extends te{constructor(n,r,i){super(i);this._path=n;this.relative=r;this.docSymbolsMeta={name:(0,aD.basename)(this.path),kind:Yf.SymbolKind.File},this.semanticTokenType="string",this.semanticTokenModifiers="declaration"}get path(){return this.relative?this._path.slice(1,-1):this._path}};var cD=q(j());var pt=class extends ge{constructor(n,r){super(r);this.name=n;this.docSymbolsMeta={name:this.name.toString(),kind:cD.SymbolKind.Variable},this.semanticTokenType="macro",this.semanticTokenModifiers="declaration"}toString(){return this.name}};var Xf=class extends te{constructor(n,r){super(r);this.operator=n;this.semanticTokenType="operator",this.semanticTokenModifiers="declaration"}toString(){return this.operator}};var lD=q(j());var va=class extends ft{toString(){return"..."}},mi=class extends te{constructor(n,r){super();this.functionName=n;this.params=r;this.addChild(n),this.params.forEach(i=>this.addChild(i))}getDocumentSymbols(n){return pe(this.fsPath,n)?[{name:this.functionName.name,kind:lD.SymbolKind.Function,range:ce(this),selectionRange:ce(this),children:this.params.flatMap(r=>r.getDocumentSymbols(n))}]:[]}toString(){return`${this.functionName}(${this.params.map(n=>n.toString()).join(",")})`}};var $i=class t{constructor(){this.positionStack=[];this._issues=[];this.issueLengthPositionStack=[];this.moveEndOfLine=(e,n=!0,r=!1)=>{let i=e.pos.line;if(this.currentToken?.pos.line!==i||!pe(this.currentToken?.fsPath,e.fsPath))return;let s=this.currentToken,o=s;for(;this.currentToken?.pos.line===i&&pe(this.currentToken?.fsPath,e.fsPath);)o=this.moveToNextToken;return n&&this._issues.push(z(22,s,o,null)),r&&o?.value==="\\"&&o.nextToken?this.moveEndOfLine(o.nextToken,n):o};this.parsing=new Promise(e=>{setTimeout(()=>{this.parse().then(e)})})}reset(){this.issueLengthPositionStack=[],this.positionStack=[],this._issues=[]}get issues(){return this._issues}get stable(){return this.parsing}get done(){return this.peekIndex()>=this.tokens.length}get moveToNextToken(){let e=this.currentToken;if(e)return this.moveStackIndex(),e}enqueueToStack(){this.issueLengthPositionStack.push(this._issues.length),this.positionStack.push(this.peekIndex())}popStack(){let e=this.issueLengthPositionStack.pop()??0;e!==this._issues.length&&this._issues.splice(e),this.positionStack.pop()}mergeStack(){let e=this.issueLengthPositionStack.pop(),n=this.positionStack.pop();if(n===void 0||e===void 0)throw new Error("Index out of bounds");this.positionStack[this.positionStack.length-1]=n}peekIndex(e=1){let n=this.positionStack.at(-1*e);if(n===void 0)throw new Error("Index out of bounds");return n}get currentToken(){return this.tokens.at(this.peekIndex())}get prevToken(){let e=this.peekIndex()-1;if(e!==-1)return this.tokens[e]}moveStackIndex(){let e=this.positionStack.length-1;if(this.positionStack[e]===void 0)throw new Error("Index out of bounds");this.positionStack[e]!==this.tokens.length&&this.positionStack[e]++}checkConcurrentTokens(e){this.enqueueToStack();let n=[];return e.every(r=>{let i=this.currentToken,s=r(i),o=!1;return s!=="no"&&i&&(n.push(i),this.moveToNextToken,o=Vt(i,this.currentToken)),s==="yes"&&o}),this.mergeStack(),n}consumeAnyConcurrentTokens(e){this.enqueueToStack();let n=[],r,i=!0;for(;e.some(s=>s(this.currentToken)==="yes"&&i);)n.push(this.currentToken),r=this.moveToNextToken,i=Vt(r,this.currentToken);return this.mergeStack(),n}getDocumentSymbols(e){return this.allAstItems.flatMap(n=>n.getDocumentSymbols(e))}getWorkspaceSymbols(){return this.allAstItems.flatMap(e=>e.getWorkspaceSymbols())}static push(e,n,r,i,s,o){if(!r||!i||!pe(r.fsPath,s)||!pe(i.fsPath,s))return;let a=i.pos.colEnd-r.pos.col;o.push({line:r.pos.line,char:r.pos.col,length:i===r?i.pos.len:a,tokenType:e,tokenModifiers:n})}buildSemanticTokens(e,n,r=[]){this.allAstItems.forEach(i=>{i.buildSemanticTokens((...s)=>t.push(...s,n,r))}),r.sort((i,s)=>i.line===s.line?i.char-s.char:i.line-s.line).forEach(i=>e.push(i.line,i.char,i.length,i.tokenType,i.tokenModifiers))}processCIdentifier(e,n,r=!1){this.enqueueToStack();let i=this.consumeAnyConcurrentTokens([19,47,48].map(Le));if(!i.length){this.popStack();return}if(!i?.[0]?.value.match(/^[_A-Za-z]/)){this.popStack();return}let s=i.map(a=>a.value).join(""),o=new pt(s,de(i[0],i.at(-1)));if(r&&!e.has(o.name)){this.popStack();return}return!n&&o.firstToken!==o.lastToken&&o.name!=="defined"&&(e.get(o.name)||this._issues.push(z(42,o.firstToken,o.lastToken,o))),this.mergeStack(),o}isOperator(){this.enqueueToStack();let e=this.moveToNextToken;if(!e){this.popStack();return}let n=e,r;if(U(e,40)?(r="&",U(this.currentToken,40)&&(r="&&",n=this.moveToNextToken)):U(e,6)?(r="!",U(this.currentToken,0)&&(r="!=",n=this.moveToNextToken)):U(e,10)?r="~":U(e,8)?(r="|",U(this.currentToken,8)&&(r="||",n=this.moveToNextToken)):U(e,9)?r="^":U(e,4)?(r=">",U(this.currentToken,4)?(r=">>",n=this.moveToNextToken):U(this.currentToken,0)&&(r=">=",n=this.moveToNextToken)):U(e,5)?(r="<",U(this.currentToken,5)?(r="<<",n=this.moveToNextToken):U(this.currentToken,0)&&(r="<=",n=this.moveToNextToken)):U(e,15)?r="+":U(e,16)?r="-":U(e,17)?r="*":U(e,13)?r="/":U(e,18)?r="%":U(e,46)?U(this.currentToken,46)&&(r="##",n=this.moveToNextToken):U(e,0)&&U(this.currentToken,0)&&(r="==",n=this.moveToNextToken),r){let i=new Xf(r,de(e,n));return this.mergeStack(),i}this.popStack()}parseScopedBlock(e,n,r){this.enqueueToStack();let i=this.moveToNextToken;if(!i||!e(i)){this.popStack();return}let s=this.peekIndex(),o=()=>{this.positionStack[this.positionStack.length-1]=s},a=m=>m.flatMap(h=>"items"in h?a(h.items):h),c=[i],l=[],u=[];u[0]={rewind:o,tokens:[]};let d=this.currentToken;for(;d&&!n(d);){if(r?.(d)){let m=this.peekIndex()+1,h=()=>{this.positionStack[this.positionStack.length-1]=m};c.push(d),l.push(d),u[u.length]={rewind:h,tokens:[]}}else if(e(d)){let m=this.parseScopedBlock(e,n,r);m&&(c.push(m),u[u.length-1].tokens.push(...a(m.items))),d=this.currentToken;continue}else c.push(d),u[u.length-1].tokens.push(d);this.moveToNextToken,d=this.currentToken}let f=d;f&&n(f)&&(this.moveToNextToken,c.push(f));let p={startToken:i,items:c,splitTokens:u,endToken:f,separatorTokens:l};return this.mergeStack(),p}isFunctionCall(e){this.enqueueToStack();let n=this.processCIdentifier(e,!1);if(!n){this.popStack();return}if(!Vt(n.lastToken,this.currentToken)){this.popStack();return}let r=this.processMacroCallParams();if(!r){this.popStack();return}if(n.name==="defined")r.length>1?this._issues.push(z(44,n.firstToken,n.lastToken,n)):r.length<1&&this._issues.push(z(45,n.firstToken,n.lastToken,n));else{let s=e.get(n.name)?.macro;s&&(s?.identifier instanceof mi?s.identifier.params.at(-1)instanceof va||(r.length>s.identifier.params.length?this._issues.push(z(44,n.firstToken,n.lastToken,n,{linkedTo:[s]})):r.length<s.identifier.params.length&&this._issues.push(z(45,n.firstToken,n.lastToken,n,{linkedTo:[s]}))):this._issues.push(z(43,n.firstToken,n.lastToken,n)))}let i=new Ut(n,r);return i.lastToken=this.prevToken,this.mergeStack(),i}processHex(){this.enqueueToStack();let e=this.checkConcurrentTokens([tt("0"),tt("x",{caseInsensitive:!0})]);if(e.length!==2){this.popStack();return}let n=this.consumeAnyConcurrentTokens([19,20].map(Le));if(!n.length){this.popStack();return}let r=Number.parseInt(n.map(s=>s.value).join(""),16),i=new Zt(r,de(e[0],n.at(-1)),16);return this.mergeStack(),i}processDec(e=!1){this.enqueueToStack();let n;e&&(U(this.currentToken,16)||U(this.currentToken,15))&&Vt(this.currentToken,this.currentToken?.nextToken)&&(n=this.moveToNextToken);let r=this.consumeAnyConcurrentTokens([19].map(Le));if(!r.length){this.popStack();return}let i=Number.parseInt(r.map(o=>o.value).join(""),10);n&&U(n,16)&&(i=4294967295-i);let s=new Zt(i,de(n??r[0],r.at(-1)),10);return this.mergeStack(),s}processEnclosedExpression(e,n){this.enqueueToStack();let r,i;if(U(this.currentToken,42)){let s;r=this.moveToNextToken,i=r;let o=this.processExpression(e,n,!0);return o&&(s=new Qt(o,!0),o=new Qt(s,!1),s.openBracket=r),U(this.currentToken,43)?(i=this.moveToNextToken,s&&(s.closeBracket=i)):r&&this._issues.push(z(26,r,r,n)),this.mergeStack(),o}this.popStack()}processExpression(e,n,r=!1){this.enqueueToStack();let i,s;if(r&&(s=this.isOperator()),i=this.processEnclosedExpression(e,n)||this.isFunctionCall(e)||this.processCIdentifier(e,!1)||this.processHex()||this.processDec(!0),!i){this.popStack();return}if(s&&(i.operator=s),r){let o=this.isOperator();for(;o;){let a=this.processExpression(e,n,!0);a?i instanceof Qt?i.addExpression(o,a):i=new Qt(i,!1,{operator:o,expression:a}):this._issues.push(z(27,o.firstToken,o.lastToken,n)),o=this.isOperator()}}return this.mergeStack(),i}processMacroCallParams(){if(!U(this.currentToken,42))return;let e=this.parseScopedBlock(r=>!!U(r,42),r=>!!U(r,43),r=>!!U(r,24));return e?.items.length===2&&U(e.endToken,43)?[]:e?.splitTokens.map((r,i)=>{if(r.tokens.length===0)return null;let s=new hi(r.tokens.map((o,a)=>{let c=o.value;return o.pos.line===r.tokens.at(a+1)?.pos.line?c=c.padEnd(r.tokens[a+1].pos.col-o.pos.col," "):o.value==="\\"&&(c=c.slice(0,-1)),c}).join(""),de(r.tokens[0],r.tokens.at(-1)),i);return s.splitToken=e.separatorTokens.at(i),s})}};var cr=class extends te{constructor(n){super();this.comments=n;this.disabled=!1;n.forEach(this.addChild.bind(this))}toString(){return this.comments.map(n=>n.toString()).join(`
282
282
  `)}},lr=class extends te{constructor(n){super(n);this.disabled=!1;this.semanticTokenType="comment",this.semanticTokenModifiers="documentation"}toString(){let n,r=this.firstToken,i="";for(;r!==this.lastToken;)i+=r?.value.padStart(r.value.length+(n?r.pos.col-n.pos.colEnd:0)," "),n=r,r=r?.nextToken;r&&(i+=r?.value.padStart(r.value.length+(n?r.pos.col-n.pos.colEnd:0)," "));let s=i.match(/^\s*(?:(?:\/\/|\/\*+)\s*)?(.*?)\s*(?:\*\/)?\s*$/s);return s?s[1]:""}};var Jf=class t extends $i{constructor(n,r=()=>An().requestTokens(this.fsPath,!0)){super();this.fsPath=n;this.getTokens=r;this.comments=[];this.tokens=[]}cleanUpComments(){let n=[];for(let r=0;r<this.tokens.length;r++){let i=t.processBlockComment(this.tokens,r)||t.processLineComment(this.tokens,r);i&&(r=i.index,n.push(...i.tokenUsed),this.comments.push(i.comment))}if(n.length>0){let r=new Set(n),i=[];for(let s=0;s<this.tokens.length;s++)r.has(s)||i.push(this.tokens[s]);this.tokens=i}}get allAstItems(){return this.comments}reset(){super.reset(),this.comments=[]}reparse(){return this.reset(),this.parse()}async parse(){this.tokens=this.getTokens(),this.cleanUpComments()}static processBlockComment(n,r){let i=[],s=()=>(i.push(r++),n[r]),o=()=>n[r],a=()=>n[r-1],c=o(),l=c;if(!c||!U(c,13)||(l=s(),!U(l,17)||c.pos.line!==l.pos.line||c.pos.col+1!==l.pos.col))return;let u=()=>!(!U(a(),17)||!U(o(),13)||!Vt(a(),o())),d=l.pos.line,f=c,p=[];l=s();do{if(o()?.pos.line!==d){let y=new lr(de(f,a()));p.push(y),d=o().pos.line??0,f=o()}l=s()}while(r<n.length&&!u());let m=new lr(de(f,o()));p.push(m);let h=new cr(p);return s(),{comment:h,tokenUsed:i,index:r-1}}static processLineComment(n,r){let i=[];if(!U(n[r],13)||n.length===r+1||!U(n[r+1],13)||!Vt(n[r],n[r+1]))return;for(;n[r].pos.line===n.at(r+1)?.pos.line;)i.push(r++);return i.push(r++),{comment:new lr(de(n[i[0]],n[i.at(-1)])),tokenUsed:i,index:r-1}}};var uD=q(j());var Qf=class extends te{constructor(n,r){super(n);this.content=r}toString(){let n=this.content.filter(r=>!U(r,14));return n.map((r,i)=>{let s=r.value;return r.pos.line===n.at(i+1)?.pos.line?s=s.padEnd(n[i+1].pos.col-r.pos.col," "):n.at(i+1)&&(s=s.padEnd(s.length+1," ")),s}).join("")}},Kc=class extends te{constructor(n,r,i){super();this.keyword=n;this.identifier=r;this.content=i;this.addChild(n),this.addChild(this.identifier),this.content&&this.addChild(this.content)}get name(){return this.identifier instanceof pt?this.identifier.name:this.identifier.functionName.name}toString(){return this.toStringCache??=[this.identifier.toString(),...this.content?[this.content?.toString()]:[]].join(" "),this.toStringCache}toMarkupContent(){return{kind:uD.MarkupKind.Markdown,value:["```cpp",`#define ${this.toString()}`,"```"].join(`
283
283
  `)}}};var co=class extends te{constructor(e){super(e)}},Yc=class extends te{constructor(n,r){super();this.keyword=n;this.content=r;this.active=!1;this.addChild(n)}},Xc=class extends Yc{constructor(n,r,i){super(n,i);this.identifier=r;this.addChild(r),this.addChild(i)}useBlock(n){return this.identifier&&n.has(this.identifier.name)}},Zf=class extends Yc{constructor(n,r,i){super(n,i);this.expression=r;this.addChild(r),this.addChild(i)}useBlock(n){return this.expression?.isTrue(n)}},ep=class extends Xc{useBlock(e){return this.identifier&&!e.has(this.identifier.name)}},Jc=class extends Yc{};var Yr=(t,e)=>{let n=t,r=[];for(;n&&(r.push(n),n!==e);)n=n.nextToken;return r},Xr=class extends te{constructor(n,r,i){super();this.ifDef=n;this.endIf=r;this.elseOption=i;this.addChild(n),i&&this.addChild(i),this.addChild(r)}get inactiveRanges(){if(this.elseOption&&!this.elseOption.active){let n=this.elseOption.firstToken,r=this.elseOption.content?.lastToken??this.endIf?.firstToken??this.lastToken;return[Qe.create(ae(n),ae(r))]}if(!this.ifDef.active){let n=this.ifDef.firstToken,r=this.ifDef.content?this.ifDef.content?.lastToken:this.elseOption?this.elseOption.firstToken:this.endIf?.lastToken;return[Qe.create(ae(n),ae(r??this.ifDef.lastToken))]}return[]}getInValidTokenRange(n){if(!this.ifDef.identifier)return new WeakSet(Yr(this.firstToken,this.lastToken));let r=this.ifDef.useBlock(n);return r?this.ifDef.active=!0:this.elseOption&&(this.elseOption.active=!0),this.getInValidTokenRangeWhenActiveBlock(r?this.ifDef:this.elseOption)}getInValidTokenRangeWhenActiveBlock(n){let r=new WeakSet,i=(this.ifDef.identifier??this.ifDef.keyword).lastToken;Yr(this.ifDef.firstToken,i).forEach(o=>r.add(o));let s=this.ifDef===n;return!s&&this.ifDef.content&&Yr(this.ifDef.content.firstToken,this.ifDef.content.lastToken).forEach(o=>r.add(o)),this.elseOption&&(Yr(this.elseOption.firstToken,this.elseOption.keyword.lastToken).forEach(o=>r.add(o)),s&&this.elseOption.content&&Yr(this.elseOption.content.firstToken,this.elseOption.content.lastToken).forEach(o=>r.add(o))),this.endIf&&Yr(this.endIf.firstToken,this.endIf.lastToken).forEach(o=>r.add(o)),r}},Pr=class extends te{constructor(n,r,i){super();this.ifBlocks=n;this.endIf=r;this.elseOption=i;n.forEach(s=>this.addChild(s)),i&&this.addChild(i),this.addChild(r)}getInValidTokenRange(n){let r=this.ifBlocks.find(i=>i.useBlock(n));return r?r.active=!0:this.elseOption&&(this.elseOption.active=!0),this.getInValidTokenRangeWhenActiveBlock(r||this.elseOption)}get inactiveRanges(){let n=[],r=!!this.elseOption;if(this.ifBlocks.forEach((o,a)=>{if(o.active)return;let c=a===this.ifBlocks.length-1,l=o.firstToken,u=c?r?this.elseOption.firstToken:this.lastToken:o.content?.lastToken??this.ifBlocks[a+1].firstToken??o.lastToken;n.push(Qe.create(ae(l),ae(u)))}),this.elseOption&&n.length){let o=this.elseOption.firstToken,a=this.elseOption.content?.lastToken??this.endIf?.lastToken??this.lastToken;return[Qe.create(ae(o),ae(a))]}let i=this.firstToken,s=this.lastToken;return[Qe.create(ae(i),ae(s))]}getInValidTokenRangeWhenActiveBlock(n){let r=new WeakSet,i=!1;return this.ifBlocks.forEach(s=>{let o=s.expression?.lastToken??s.keyword.lastToken;Yr(s.firstToken,o).forEach(a=>r.add(a)),!i&&s===n?i=!0:s.content&&Yr(s.content.firstToken,s.content.lastToken).forEach(a=>r.add(a))}),this.elseOption&&(Yr(this.elseOption.keyword.firstToken,this.elseOption.keyword.lastToken).forEach(s=>r.add(s)),i&&this.elseOption.content&&Yr(this.elseOption.content.firstToken,this.elseOption.content.lastToken).forEach(s=>r.add(s))),this.endIf&&Yr(this.endIf.firstToken,this.endIf.lastToken).forEach(s=>r.add(s)),r}};var _a=class extends $i{constructor(n,r,i,s,o){super();this.fsPath=n;this.incudes=r;this.getTokens=s;this.optimizeForFormatting=o;this.tokens=[];this.nodes=[];this._comments=[];this.dtsIncludes=[];this.macroSnapShot=new Map;this.macros=new Map;this.rangesToClean=new Set;this.macroStart=!1;i&&(Array.from(i).forEach(([a,c])=>this.macroSnapShot.set(a,c)),Array.from(i).forEach(([a,c])=>this.macros.set(a,c)))}get comments(){return this._comments}removeComments(n){this._comments=this._comments.filter(r=>!n.has(r))}get currentToken(){let n=this.prevToken,r=this.peekIndex(),i=this.tokens.at(r),s=ln(n,i)||!n||U(n,14)&&n.pos.line+1===i?.pos.line;if(!(this.macroStart&&!s))return this.macroStart&&U(i,14)?(this.moveStackIndex(),this.currentToken):i}reset(n){super.reset(),this.macros.clear(),n?(this.macroSnapShot.clear(),Array.from(n).forEach(([r,i])=>this.macroSnapShot.set(r,i)),Array.from(n).forEach(([r,i])=>this.macros.set(r,i))):Array.from(this.macroSnapShot).forEach(([r,i])=>this.macros.set(r,i)),this.nodes=[],this.dtsIncludes=[],this.rangesToClean=new Set}async reparse(n){let r=this.stable;return this.parsing=new Promise(i=>{r.then(()=>{if(n&&n.size===this.macroSnapShot.size){let s=Array.from(n);if(Array.from(this.macroSnapShot).every(([o,a],c)=>{let[l,u]=s[c];return l===o&&u.macro.toString()===a.macro.toString()})){console.log("header file cache hit",this.fsPath),i();return}}this.reset(n),this.parse().then(i)})}),this.parsing}async parse(){let n=new Jf(this.fsPath,this.getTokens);if(await n.stable,this.tokens=n.tokens,this._comments=n.allAstItems,this.positionStack.push(0),this.tokens.length!==0){for(;!this.done;)await this.lineProcessor();if(this.rangesToClean.size&&!this.fsPath.endsWith(".h")&&(this.tokens=this.tokens.filter(r=>!this.rangesToClean.has(r))),this.positionStack.length!==1)throw new Error("Incorrect final stack size")}}async lineProcessor(){if(this.enqueueToStack(),!(!this.prevToken||this.prevToken.pos.line!==this.currentToken?.pos.line||!pe(this.prevToken.fsPath,this.currentToken.fsPath))){this.moveEndOfLine(this.prevToken,!1),this.mergeStack();return}let r=this.currentToken,i=await this.processInclude()||this.processDefinitions()||this.processUndef()||this.processError();this.processIfDefBlocks(),r&&this.moveEndOfLine(r,!!i),this.mergeStack()}addTokensToClean(n){for(let r=n.start;r<n.start+n.count;r++){let i=this.tokens[r];i&&this.rangesToClean.add(i)}}processDefinitions(){this.enqueueToStack();let n=this.peekIndex(),r=this.moveToNextToken;if(!r||!U(r,25))return this.popStack(),!1;this.macroStart=!0;let i=new ft(de(r)),s=this.isFunctionDefinition()||this.processCIdentifier(this.macros,!0);if(!s)return this._issues.push(z(30,i.firstToken,i.lastToken,i)),this.mergeStack(),this.macroStart=!1,!0;let o=this.consumeDefinitionContent(),a;o.length&&(a=new Qf(de(o[0],o.at(-1)),o));let c=new Kc(i,s,a);this.macros.set(c.name,{macro:c,resolver:sE(c.toString())}),this.nodes.push(c);let l=this.peekIndex();return this.addTokensToClean({start:n,count:l-n}),this.mergeStack(),this.macroStart=!1,!0}processUndef(){this.enqueueToStack();let n=this.peekIndex(),r=this.moveToNextToken;if(!r||!U(r,28))return this.popStack(),!1;this.macroStart=!0;let i=new ft(de(r)),s=this.processCIdentifier(this.macros,!0);if(!s)return this._issues.push(z(30,i.firstToken,i.lastToken,i)),this.mergeStack(),this.macroStart=!1,!0;let o=new Kc(i,s);this.macros.delete(s.name),this.nodes.push(o);let a=this.peekIndex();return this.addTokensToClean({start:n,count:a-n}),this.mergeStack(),this.macroStart=!1,!0}processError(){this.enqueueToStack();let n=this.peekIndex(),r=this.moveToNextToken;if(!r||!U(r,29))return this.popStack(),!1;this.moveEndOfLine(r,!1,!0);let i=this.peekIndex();return this.addTokensToClean({start:n,count:i-n}),this.mergeStack(),!0}consumeDefinitionContent(){let n=[];for(;this.currentToken;){let r=this.moveToNextToken;r&&n.push(r)}return n}isFunctionDefinition(){this.enqueueToStack();let n=this.processCIdentifier(this.macros,!0);if(!n){this.popStack();return}let r=this.moveToNextToken;if(!U(r,42)||!Vt(n.lastToken,r)){this.popStack();return}let i=[],s=this.processCIdentifier(this.macros,!0)||this.processVariadic();for(;s;)i.push(s),!U(this.currentToken,24)&&!U(this.currentToken,43)?this._issues.push(z(28,s.firstToken,s.lastToken,s)):U(this.currentToken,43)||(r=this.moveToNextToken),s=this.processCIdentifier(this.macros,!0)||this.processVariadic();let o=new mi(n,i);if(U(this.currentToken,43))r=this.moveToNextToken,o.lastToken=r;else{o.lastToken=this.prevToken;let a=i.at(-1)??o;this._issues.push(z(26,a.firstToken,a.lastToken,a))}return this.mergeStack(),o}processVariadic(){this.enqueueToStack();let n=this.checkConcurrentTokens([Le(45),Le(45),Le(45)]);if(n.length!==3){this.popStack();return}let r=new va(de(n[0],n.at(-1)));return this.mergeStack(),r}processIfDefBlocks(){let n=this.peekIndex(),r=this.parseScopedBlock(a=>!!a&&[33,34,32].some(c=>U(a,c))&&!ln(a.prevToken,a),a=>!!a&&[37].some(c=>U(a,c))&&!ln(a.prevToken,a),a=>!!a&&[36,35].some(c=>U(a,c))&&!ln(a.prevToken,a));if(!r)return;let i;U(r.startToken,32)?i=this.processIfBlock(r,(a,c,l)=>new Zf(a,c??null,l)):i=this.processIfDefBlock(r,(a,c,l)=>U(r.startToken,33)?new Xc(a,c??null,l):new ep(a,c??null,l)),this.nodes.push(i);let s=i.getInValidTokenRange(this.macros);this.tokens=this.tokens.filter(a=>!s.has(a));let o=i.inactiveRanges;this._comments.forEach(a=>{o.some(c=>Mf(c,a.range))&&(a.disabled=!0)}),[...i instanceof Pr?i.ifBlocks:[i.ifDef],...i.elseOption?[i.elseOption]:[]].forEach(a=>{!a.active&&a.content&&this._issues.push(z(47,a.content.firstToken,a.content.lastToken,a.content,{severity:Qc.DiagnosticSeverity.Hint,tags:[Qc.DiagnosticTag.Unnecessary]}))}),this.positionStack[this.positionStack.length-1]=n}processIfDefBlock(n,r){this.enqueueToStack(),this.macroStart=!0;let i=new ft(de(n.startToken));n.splitTokens[0].rewind();let s=this.processCIdentifier(this.macros,!0);s||this._issues.push(z(31,i.firstToken,i.lastToken,i)),this.macroStart=!1;let o,a=n.splitTokens[0].tokens.indexOf(s?.lastToken??i.lastToken)+1,c=n.splitTokens[0].tokens[a];a&&c&&(o=new co(de(c,n.splitTokens[0].tokens.at(-1))));let l=r(i,s??null,o??null),u;if(n.splitTokens.length>1){let p=n.separatorTokens[0],m=new ft(de(p)),h;n.splitTokens[1].tokens.length&&(h=new co(de(n.splitTokens[1].tokens[0],n.splitTokens[1].tokens.at(-1)))),u=new Jc(m,h??null)}let d;n.endToken?d=new ft(de(n.endToken)):this._issues.push(z(46,i.firstToken,i.lastToken,i));let f=new Xr(l,d??null,u);return this.mergeStack(),f}processIfBlock(n,r){this.enqueueToStack();let i=new ft(de(n.startToken)),s=[],o;n.splitTokens.forEach((l,u)=>{l.rewind();let d=this.prevToken,f=new ft(de(d));this.macroStart=!0;let p=this.processExpression(this.macros,f,!0)||this.processCIdentifier(this.macros,!0);if(p instanceof pt&&p.name.toLowerCase()==="defined"&&(p=this.processExpression(this.macros,f,!0)||this.processCIdentifier(this.macros,!0)),this.macroStart=!1,u===n.splitTokens.length-1&&U(d,36)){let h=d,y=new ft(de(h)),_;l.tokens.length&&(_=new co(de(l.tokens[0],l.tokens.at(-1)))),o=new Jc(y,_??null)}else{p||this._issues.push(z(31,i.firstToken,i.lastToken,i));let h,y=n.splitTokens[0].tokens.indexOf(p?.lastToken??i.lastToken)+1,_=n.splitTokens[0].tokens[y];y&&_&&(h=new co(de(_,n.splitTokens[u].tokens.at(-1))));let v=r(f,p??null,h??null);s.push(v)}});let a;n.endToken?a=new ft(de(n.endToken)):this._issues.push(z(46,i.firstToken,i.lastToken,i));let c=new Pr(s,a??null,o);return this.mergeStack(),c}get allAstItems(){return[...this.dtsIncludes,...this.nodes,...this.comments]}resolveInclude(n){if(n.path.path)return n.path.relative?[(0,ba.resolve)((0,ba.dirname)(n.fsPath),n.path.path),...this.incudes.map(r=>(0,ba.resolve)(r,n.path.path))].find(r=>(0,OT.existsSync)(r)):this.incudes.map(r=>(0,ba.resolve)(r,n.path.path)).find(r=>(0,OT.existsSync)(r))}async processInclude(){this.enqueueToStack();let n=this.peekIndex(),r=this.currentToken;if(!r)return this.popStack(),!1;let i=r,s=r;if(U(r,26))this.moveToNextToken;else{let h=this.checkConcurrentTokens([Le(13),tt("include"),Le(13)]);if(h.length!==3)return this.popStack(),!1;i=h[0],s=h.at(-1)}let o=i,a=new ft(de(i,s));r=this.moveToNextToken;let c=r,l=!!U(r,21);if(!c||!l&&!U(r,5))return o&&this.moveEndOfLine(o),this.mergeStack(),!0;let u="";if(l)u=r?.value??"";else for(;this.currentToken?.pos.line===o.pos.line&&!U(this.currentToken,4);)u+=this.currentToken?.value??"",r=this.moveToNextToken;let d=new Ta(u,l,de(c,r)),f=new kr(a,d);this.dtsIncludes.push(f),l||(this.currentToken?.pos.line!==o.pos.line||!U(this.currentToken,4)?this._issues.push(z(12,f.firstToken,f.lastToken,f)):(r=this.moveToNextToken,d.lastToken=r)),this.mergeStack();let p=this.peekIndex(),m=this.resolveInclude(f);if(f.resolvedPath=m,m||this._issues.push(z(36,f.path.firstToken,f.path.lastToken,f.path,{severity:Qc.DiagnosticSeverity.Warning})),m&&!this.optimizeForFormatting){An().requestTokens(m,!0);let h=Zc().getCPreprocessorParser(m,this.incudes,this.macros,this.fsPath);await h.stable,this._issues.push(...h.issues),this.macros.clear(),Array.from(h.macros).forEach(([y,_])=>this.macros.set(y,_)),m.endsWith(".h")?this.addTokensToClean({start:n,count:p-n}):(this.tokens=mE(this.tokens,n,p,h.tokens),this.positionStack[this.positionStack.length-1]=n),this.nodes.push(...h.nodes),this.dtsIncludes.push(...h.dtsIncludes)}else this.addTokensToClean({start:n,count:p-n});return!0}};var MT,tp=class{constructor(){this.headerFiles=new Map;this.includeOwners=new WeakMap}getCPreprocessorParser(e,n,r,i){e=it(e);let s=`${Array.from(r).map(l=>l[1].macro.toString()).join("::")}`,o=this.headerFiles.get(e)?.get(s);if(o)return o.reparse(r),o;console.log("No c-preprocessor cache",e);let a=new _a(e,n,r),c=this.includeOwners.get(a)??new Set;return c.add(i),this.includeOwners.set(a,c),this.headerFiles.has(e)||this.headerFiles.set(e,new Map),this.headerFiles.get(e)?.set(s,a),a}reset(e){e=it(e);let n=this.headerFiles.get(e);n&&Array.from(n).forEach(([r,i])=>{console.log("disposing c-preprocessor cache for",e),Array.from(this.includeOwners.get(i)??[]).forEach(this.reset.bind(this)),this.headerFiles.delete(e)})}};function Zc(){return MT??=new tp,MT}function dD(){MT=new tp}var xT,np=class t{constructor(){this.fileMap=new Map}static clone(e){let n=e.length;if(n===0)return[];let r=new Array(n),i;for(let s=0;s<n;s++){let o=e[s],a={tokens:o.tokens,pos:o.pos,value:o.value,fsPath:o.fsPath,prevToken:i,nextToken:void 0};i&&(i.nextToken=a),r[s]=a,i=a}return r}needsRenew(e,n){return e=it(e),this.fileMap.get(e)?.text!==n}getDocument(e,n){return Vn.create(e,"devicetree",0,n??this.fileMap.get(e)?.text??(0,el.readFileSync)(e).toString())}renewLexer(e,n){if(e=it(e),Zc().reset(e),!n&&!(0,el.existsSync)(e))return[];try{n??=(0,el.readFileSync)(e).toString();let r=new Kr(n,e);return this.fileMap.set(e,r),t.clone(r.tokens)}catch{}return[]}requestTokens(e,n){e=it(e);let r=this.fileMap.get(e)?.tokens;return!r&&n?[...this.renewLexer(e)]:t.clone(r??[])}reset(e){e=it(e),Zc().reset(e),this.fileMap.delete(e)}};function An(){return xT??=new np,xT}function fD(){xT=new np}var gi=class t{constructor(e){this.context=e;this.comments=[];this.includes=[];this.references=[];this.unlinkedDeletes=[];this.unlinkedRefNodes=[];this.globalDeletes=[];this.rootNode=new X(this.context.bindingLoader,"/");this.labelsUsedCache=new Map;this.fileTopMostAstCache=new Map}fileTopMostAsts(e){let n=this.fileTopMostAstCache.get(e);if(n)return n;let r=[...this.rootNode.implementations,...this.references,...this.unlinkedDeletes,...this.unlinkedRefNodes,...this.globalDeletes,...this.context.overlayParsers.flatMap(i=>[...i.cPreprocessorParser.allAstItems,...i.unhandledStatements.children]),...this.context.parser.cPreprocessorParser.allAstItems,...this.context.parser.unhandledStatements.children].flatMap(i=>i.getTopMostAstNodeForFile(e));return this.fileTopMostAstCache.set(e,r),r}getDeepestAstNode(e,n){let r=this.fileTopMostAsts(e),i=r.find(s=>Cn(s,e,n)||rE(An().requestTokens(e,!1),s,n));if(!i){let s=[this.context.parser,...this.context.overlayParsers].flatMap(c=>c.includes),o=(c,l)=>{let u=s.find(d=>pe(d.resolvedPath,c));return u&&this.context.getSortKeyFile(l,c)===void 0?o(u.lastToken.fsPath,ae(u.lastToken)):u},a=o(e,n);a&&(i=r.at(-1)?.parentNode,e=a.fsPath,n=pD.Position.create(a.lastToken.pos.line,a.lastToken.pos.colEnd))}if(i instanceof Et){let o=this.rootNode.getReferenceBy(i)?.getDeepestAstNode(e,n);return o?{...o,runtime:this}:{item:null,runtime:this,ast:zr(i,e,n)}}else if(i instanceof Tt&&i.path){let s=this.rootNode.getDeepestAstNode(e,n);return s?{...s,runtime:this}:void 0}else if(i instanceof He&&i.path){let s=t.getNodeFromPath(i.path.slice(1),this.rootNode)?.getDeepestAstNode(e,n);return s?{...s,runtime:this}:void 0}else if(i)return{runtime:this,item:null,ast:zr(i,e,n)}}static getNodeFromPath(e,n,r=!0){if(e.length===0)return n;let i=e[0].split("@"),s=i[0],a=i.at(1)?.split(",").map(u=>Number.parseInt(u,16)),c=e.slice(1),l=n.getNode(s,a,r);return l?t.getNodeFromPath(c,l,r):void 0}resolvePath(e,n){if(!e.at(0)?.startsWith("&"))return e;let r=this.labelsUsedCache.get(e[0].slice(1));return r||(n??=this.rootNode.allDescendantsLabels,n.find(s=>s.label.value===e.at(0)?.slice(1)&&s.parentNode instanceof Ue)?.lastLinkedTo?.path)}get issues(){return this.issuesCache??=[...this.labelIssues(),...this.rootNode.getIssues(this.context.macros)],this.issuesCache}labelIssues(){let e=[],n=new Map;return this.rootNode.allDescendantsLabelsMapped.forEach(r=>{n.has(r.label.label.value)?n.get(r.label.label.value)?.push(r):n.set(r.label.label.value,[r])}),Array.from(n).forEach(r=>{let i=r[1];if(i.length>1){let s=i.find(a=>a.owner instanceof X);if(!i.every(a=>a&&a.owner===s?.owner)||!s){let a=i[i.length-1].label;e.push(Ht(4,a.firstToken,a.lastToken,a,{linkedTo:i.slice(0,-1).map(c=>c.label),templateStrings:[i.at(0).label.label.value]}))}}}),e}get typesIssues(){let e=n=>[...n.nodeType?.getIssue(this,n)??[],...n.nodes.flatMap(r=>e(r))];return this.typesIssuesCache??=e(this.rootNode),this.typesIssuesCache}getOrderedNodeAst(e){return iE(e.implementations,this.context)}};var tl=q(j());var hD=q(j());var rp=class extends te{constructor(n){super();this.values=n;this.docSymbolsMeta={name:"Values",kind:hD.SymbolKind.String},this.values.forEach(r=>this.addChild(r))}toString(){return this.values.map(n=>n?.toString()).join(",")}toJson(){return this.values.length===1?this.values[0]?.toJson():this.values.map(n=>n?.toJson())}};var mD=q(j());var ip=class extends te{constructor(n){super();this.keyword=n;this.addChild(n),this.docSymbolsMeta={name:"DTS Document version",kind:mD.SymbolKind.Function}}};var yi=class extends te{constructor(n,r){super();this.value=n;this.labels=r;this.labels.forEach(i=>{this.addChild(i)}),this.addChild(this.value)}toString(n){return`${this.labels.map(r=>r.toString()).join(" ")}${this.value?.toString(n)??"NULL"}`}toPrettyString(n){return`${this.labels.map(r=>r.toString()).join(" ")}${this.value?.toPrettyString(n)??"NULL"}`}};var gD=q(j());var sp=class extends te{constructor(n,r,i){super();this.keyword=n;this.startAddress=r;this.endAddress=i;this.addChild(n),this.docSymbolsMeta={name:"Memreserve",kind:gD.SymbolKind.Function},this.addChild(r),this.addChild(i)}toString(){return`/memreserve/ 0x${this.startAddress?.value?.toString(16)} 0x${this.endAddress?.value?.toString(16)}`}};var yD=q(j());var op=class extends te{constructor(n,r){super();this.keyword=n;this.bitsSize=r;this.addChild(n),this.docSymbolsMeta={name:"bits",kind:yD.SymbolKind.Function},this.addChild(r)}toString(){return`/bits/ ${this.bitsSize?.value?.toString()}`}};var Fi=class extends $i{constructor(n,r,i,s,o){super();this.fsPath=n;this.incudes=r;this.tokens=[];this.others=[];this.rootDocument=new Ue;this.unhandledStatements=new Tt;this.injectedMacros=[];this.#e=!1;this.cPreprocessorParser=new _a(this.fsPath,this.incudes,i,s,o)}get issues(){return[...this._issues,...this.cPreprocessorParser.issues]}getFiles(){return[this.fsPath,...this.cPreprocessorParser.dtsIncludes.flatMap(n=>n.resolvedPath).filter(n=>!!n)]}reset(){super.reset(),this.others=[],this.rootDocument=new Ue,this._issues=[],this.unhandledStatements=new Tt,this.#e=!1}async reparse(){let n=performance.now(),r=this.stable;return this.parsing=new Promise(i=>{r.then(async()=>{this.reset(),await this.cPreprocessorParser.reparse(),await this.parse(),console.log("parsing",performance.now()-n),i()})}),this.parsing}async parse(){if(await this.cPreprocessorParser.stable,this.tokens=this.cPreprocessorParser.tokens,it(this.fsPath).endsWith(".h")||(this.positionStack.push(0),this.tokens.length===0))return;let n=async()=>{if(!(this.isDtsDocumentVersion()||this.isMemreserve()||this.isPlugin()||this.isRootNodeDefinition(this.rootDocument)||this.isDeleteNode(this.rootDocument,"Ref")||this.processInjectPreProcessorMacros(this.cPreprocessorParser.macros)||this.isChildNode(this.rootDocument,"Ref")||this.isProperty(this.unhandledStatements)||this.isDeleteProperty(this.unhandledStatements)||this.isChildNode(this.unhandledStatements,"Name"))){let s=this.moveToNextToken;s&&(this._issues.push(z(22,s,s,null)),this.reportExtraEndStatements())}};for(;!this.done;)await n();this.fsPath.endsWith(".dtsi")||(this.unhandledStatements.nodes.forEach(s=>{this._issues.push(z(53,s.firstToken,s.lastToken,s))}),this.unhandledStatements.properties.forEach(s=>{this._issues.push(z(32,s.firstToken,s.lastToken,s))}),this.unhandledStatements.deleteProperties.forEach(s=>{this._issues.push(z(33,s.firstToken,s.lastToken,s))}));let r=this.allAstItems.flatMap(s=>[s,...s.allDescendants]),i=this.cPreprocessorParser.comments;if(i.length&&r.forEach(s=>{(s instanceof Ue||s instanceof je||s instanceof kr)&&fE(s,i)}),this.positionStack.length!==1)throw new Error("Incorrect final stack size")}processInjectPreProcessorMacros(n){let r=this.peekIndex(),i=this.isFunctionCall(n)||this.processCIdentifier(n,!0,!0);return this.injectPreProcessorResults(n,i,r)}injectPreProcessorResults(n,r,i){let s=r?.resolve(n);if(r&&typeof s=="string"){s=hT(s);let o=xf(r.fsPath,ce(r)),a=new Set;if(this.cPreprocessorParser.comments.forEach(l=>{Cn(r,r.fsPath,l.range.start)&&a.add(l)}),this.cPreprocessorParser.removeComments(a),this.injectedMacros.push(r),r instanceof pt&&s.includes(r.name)||r instanceof Ut&&s.includes(r.functionName.name))return!0;let c=new Kr(s,o);return this.tokens.splice(i,this.peekIndex()-i,...c.tokens),this.positionStack[this.positionStack.length-1]=i,!0}}isRootNodeDefinition(n){this.enqueueToStack();let r=this.moveToNextToken,i=r;if(!r||!U(r,13))return this.popStack(),!1;if(i=this.moveToNextToken,!i||!U(i,2))return this.popStack(),!1;let s=new Tt;s.openScope=i,n.addNodeChild(s),this.processNode(s,"Name");let o=this.nodeEnd(s)??i;return s.firstToken=r,s.lastToken=o,this.mergeStack(),!0}nodeEnd(n){let r=this.currentToken;if(U(r,3))this.moveToNextToken;else{let i=this.prevToken;return i&&this._issues.push(z(3,i,i,n)),this.endStatement(n,!1)}return this.prevToken?.value==="}"&&(n.closeScope=this.prevToken),this.endStatement(n)}isNodeEnd(){return U(this.currentToken,3)||U(this.currentToken,1)}endStatement(n,r=!0){let i=this.currentToken;if(!U(i,1)){let s=this.prevToken;if(s&&r)return this._issues.push(z(1,s,s,n)),s}return this.moveToNextToken,this.reportExtraEndStatements(),i}reportExtraEndStatements(){for(;U(this.currentToken,1);){let n=this.moveToNextToken;n&&this._issues.push(z(23,n,n,null))}}processNode(n,r){if(this.done)return!1;let i=!1,s=!1;do{for(;this.processInjectPreProcessorMacros(this.cPreprocessorParser.macros););if(s=this.isChildNode(n,r)||this.isProperty(n)||this.isDeleteNode(n,r)||this.isDeleteProperty(n),!s&&!this.isNodeEnd()&&!this.done){let o=this.moveToNextToken;o&&(this._issues.push(z(22,o,o,null)),this.reportExtraEndStatements())}else if(this.done)break;i=i||s}while(!this.isNodeEnd());return i}processOptionalLabelAssign(n=!1){let r=[],i=this.isLabelAssign(n);for(;i;)r.push(i),i=this.isLabelAssign(n);return r}isChildNode(n,r){this.enqueueToStack();let i;r==="Name"&&(i=this.isOmitIfNoRefNode());let s=this.processOptionalLabelAssign(),o,a,c=r==="Ref"?new Et(s):new He(s,i);if(r==="Ref"?(this.enqueueToStack(),a=this.processNodePathRef(c),!a||!U(this.currentToken,2)?(this.popStack(),a=void 0):this.mergeStack(),a??=this.isLabelRef(c)):r==="Name"&&(o=this.isNodeName()),!a&&!o){if(!U(this.currentToken,2))return this.popStack(),!1;c.firstToken=this.currentToken,this._issues.push(z(r==="Name"?[7]:[10,48,11],c.firstToken,this.currentToken?.nextToken,c))}let l=!1;if(a&&c instanceof Et?(c.reference=a,l=!0):o&&c instanceof He&&(l=o.address!==void 0,c.name=o),U(this.currentToken,2)){c.openScope=this.moveToNextToken;let u=!1;do u=this.processNode(c,"Name");while(u);let d=this.nodeEnd(c);c.lastToken=d}else if(l){let u=a??o;u&&this._issues.push(z(2,u.firstToken,u.lastToken,u))}else return this.popStack(),!1;return n.addNodeChild(c),this.mergeStack(),!0}processNodeAddress(n){let r=this.prevToken;this.enqueueToStack();let i=this.checkConcurrentTokens([tt("0"),tt("x",{caseInsensitive:!0})]);i.length!==2?(i=[],this.popStack()):(this._issues.push(z(50,i[0],i[1],n,{severity:tl.DiagnosticSeverity.Warning})),r=i.at(-1),this.mergeStack());let s=this.consumeAnyConcurrentTokens([19,20,48].map(Le)),o=l=>{l.length%8!==0&&(l=l.padStart(Math.ceil(l.length/8)*8,"0"));let u=[];for(let d=0;d<l.length;d+=8){let f=l.slice(d,d+8);u.push(parseInt(f,16)>>>0)}return u},a=s.length?o(s.filter(l=>l.value!=="_").map(l=>l.value).join("")):[NaN];return r&&(a.some(l=>Number.isNaN(l))?this._issues.push(z(8,r,r,n)):!Number.isNaN(a)&&!Vt(r,s[0])&&!ro(s[0].fsPath)&&this._issues.push(z(29,r,s[0],n,{inclusiveStart:!1,inclusiveEnd:!1}))),this.currentToken?.value.toUpperCase()==="ULL"&&(this._issues.push(z(51,this.currentToken,this.currentToken,n,{severity:tl.DiagnosticSeverity.Warning})),this.moveToNextToken),new Fc(a,de(i.at(0)??s[0]??this.prevToken,this.prevToken))}processNodeAddresses(n){this.enqueueToStack();let r=this.checkConcurrentTokens([Le(49)]);if(r.length){Vt(n.lastToken,r[0])||this._issues.push(z(29,n.lastToken,r[0],n,{inclusiveStart:!1,inclusiveEnd:!1}));let i=[],s=()=>{this.processInjectPreProcessorMacros(this.cPreprocessorParser.macros),i.push(this.processNodeAddress(n)),U(this.currentToken,24)&&(this.prevToken&&!Vt(this.prevToken,this.currentToken)&&this._issues.push(z(29,this.prevToken,this.currentToken,n,{inclusiveStart:!1,inclusiveEnd:!1})),this.moveToNextToken,s())};s();let o=this.currentToken;for(;!U(this.currentToken,2)&&!U(this.currentToken,1)&&!U(this.currentToken,3)&&!U(this.currentToken,13)&&ln(this.currentToken,i.at(-1)?.lastToken);)this.moveToNextToken;if(o&&o!==this.currentToken){this._issues.push(z(52,o,this.currentToken,n));let a=new Fc([],de(o,this.prevToken));i.push(a)}return this.mergeStack(),i}this.popStack()}isNodeName(){this.enqueueToStack();let n=this.consumeAnyConcurrentTokens([19,47,24,45,48,15,16].map(Le));if(!n.length){this.popStack();return}let r=n.map(o=>o.value).join(""),i=new xe(r,de(n[0],n.at(-1))),s=this.processNodeAddresses(i);return i.address=s,qf(r)||this._issues.push(z(49,i.firstToken,i.lastToken,i)),this.mergeStack(),i}isPropertyName(){this.enqueueToStack();let n=this.consumeAnyConcurrentTokens([19,47,24,45,48,15,16,44,46].map(Le));if(!n.length){this.popStack();return}let r=new Ye(n.map(i=>i.value).join(""),de(n[0],n.at(-1)));return this.mergeStack(),r}isLabelName(){this.enqueueToStack();let n=this.consumeAnyConcurrentTokens([19,47,48].map(Le));if(!n.length){this.popStack();return}if(!qf(n?.[0].value)){this.popStack();return}let r=n.map(s=>s.value).join(""),i=new un(r,de(n[0],n[n.length-1]));return this.mergeStack(),i}isLabelAssign(n){this.enqueueToStack();let r=this.consumeAnyConcurrentTokens([19,47,48].map(Le));if(!r.length){this.popStack();return}if(!qf(r?.[0].value)){this.popStack();return}let i=r.map(c=>c.value).join(""),s=this.currentToken,o=s&&U(s,50),a=new ps(new un(i,de(r[0],r.at(-1))),de(r[0],o?s:r.at(-1)));if(o){let c=r.at(-1);c&&(s.pos.line!==a.firstToken.pos.line||s.pos.col!==c.pos.colEnd)&&this._issues.push(z(29,c,s,a,{inclusiveStart:!1,inclusiveEnd:!1})),this.moveToNextToken}else if(n)this._issues.push(z(24,a.firstToken,a.lastToken,a));else{this.popStack();return}return this.mergeStack(),a}isProperty(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(),i=this.isPropertyName();if(!i)return this.popStack(),!1;if(U(this.currentToken,2)||U(this.currentToken,49))return this.popStack(),!1;let s=new je(i,r),o;U(this.currentToken,0)?(s.assignOperatorToken=this.moveToNextToken,o=this.processValue(n),o?.values.filter(c=>!!c).length||this._issues.push(z(0,s.firstToken,s.lastToken,s)),s.values=o??null):s.values=void 0;let a=this.endStatement(s);return s.lastToken=a,n.addNodeChild(s),this.mergeStack(),!0}isDtsDocumentVersion(){this.enqueueToStack();let n=this.checkConcurrentTokens([Le(13),tt("d"),tt("ts"),Le(16),tt("v"),tt("1")]);if(n.length!==6)return this.popStack(),!1;let r=n[0],i=r,s=new ft;s.firstToken=r;let o=new ip(s);if(this.others.push(o),U(this.currentToken,13))i=this.moveToNextToken;else return s.lastToken=n.at(-1),this._issues.push(z(21,o.firstToken,o.lastToken,o)),this.mergeStack(),!0;return s.lastToken=i,o.lastToken=this.endStatement(o),this.mergeStack(),!0}isMemreserve(){this.enqueueToStack();let n=this.checkConcurrentTokens([Le(13),tt("memreserve")]);if(n.length!==2)return this.popStack(),!1;let r=new ft;r.firstToken=n[0];let s=n[0];U(this.currentToken,13)?(s=this.moveToNextToken,r.lastToken=s):(r.lastToken=n.at(-1),this._issues.push(z(21,r.firstToken,r.lastToken,r)));let o=this.processHex()||this.processDec(),a=o&&(this.processHex()||this.processDec()),c=new sp(r,o,a);if(this.others.push(c),o||this._issues.push(z(37,r.firstToken,r.lastToken,r)),!a){let l=o??r;this._issues.push(z(38,l.firstToken,l.lastToken,c))}return c.lastToken=this.endStatement(c),this.mergeStack(),!0}isPlugin(){this.enqueueToStack();let n=this.checkConcurrentTokens([Le(13),tt("plugin"),Le(13)]);if(n.length!==3)return this.popStack(),!1;let r=new ft(de(n[0],n.at(-1)));return r.lastToken=this.endStatement(r),this.mergeStack(),this.others.push(r),!0}processBits(){this.enqueueToStack();let n=this.checkConcurrentTokens([Le(13),tt("b"),tt("its")]);if(n.length!==3){this.popStack();return}let r=new ft;r.firstToken=n[0];let s=n[0];U(this.currentToken,13)?(s=this.moveToNextToken,r.lastToken=s):(r.lastToken=n.at(-1),this._issues.push(z(21,r.firstToken,r.lastToken,r)));let o=this.processDec(),a=new op(r,o);return this.others.push(a),o?o.value!==8&&o.value!==16&&o.value!==32&&o.value!==64&&this._issues.push(z(40,o.firstToken,o.lastToken,o)):this._issues.push(z(39,r.firstToken,r.lastToken,r)),this._issues.push(z(41,a.firstToken,a.lastToken,a,{severity:tl.DiagnosticSeverity.Warning})),this.mergeStack(),a}isOmitIfNoRefNode(){this.enqueueToStack();let n=this.checkConcurrentTokens([Le(13),tt("omit"),Le(16),tt("if"),Le(16),tt("no"),Le(16),tt("ref"),Le(13)]);if(n.length!==9){this.popStack();return}let r=new ft(de(n[0],n.at(-1)));return this.mergeStack(),r}isDeleteNode(n,r){this.enqueueToStack();let i=this.checkConcurrentTokens([Le(13),tt("d"),tt("e"),tt("lete",{allowPartial:!0}),Le(16),tt("node",{allowPartial:!0})]);if(!i.length)return this.popStack(),!1;let s=i[0],o=s,a=new ft;if(a.firstToken=s,i.length===1&&!U(this.currentToken,2)){this._issues.push(z(25,a.firstToken,a.lastToken,a)),a.lastToken=i.at(-1);let d=new Gn(a);return n.addNodeChild(d),this.mergeStack(),!0}let c=i.map(d=>d.value??"").join("");if(!"/delete-node/".startsWith(c)||c.endsWith("-"))return this.popStack(),!1;a.lastToken=i.at(-1),c!=="/delete-node"?this._issues.push(z(c.startsWith("/delete-n")?34:25,a.firstToken,a.lastToken,a)):U(this.currentToken,13)?(o=this.moveToNextToken,a.lastToken=o):this._issues.push(z(21,a.firstToken,a.lastToken,a));let l=new Gn(a);if(ln(a.lastToken,s)){let d=this.processNodePathRef(n);d&&r==="Name"&&this._issues.push(z(7,d.firstToken,d.lastToken,d));let f=d?void 0:this.isLabelRef(n);f&&r==="Name"&&this._issues.push(z(7,f.firstToken,f.lastToken,f));let p=d||f?void 0:this.isNodeName();p&&r==="Ref"&&this._issues.push(z(10,p.firstToken,p.lastToken,p)),!d&&!p&&!f&&this._issues.push(z([7,10],l.firstToken,l.lastToken,l)),l.nodeNameOrRef=d??f??p??null}else r==="Name"?this._issues.push(z(7,a.firstToken,a.lastToken,a)):r==="Ref"&&this._issues.push(z(10,a.firstToken,a.lastToken,a));let u=this.endStatement(l);return l.lastToken=u,n.addNodeChild(l),this.mergeStack(),!0}isDeleteProperty(n){this.enqueueToStack();let r=this.checkConcurrentTokens([Le(13),tt("d"),tt("e"),tt("lete",{allowPartial:!0}),Le(16),tt("property",{allowPartial:!0})]);if(!r.length)return this.popStack(),!1;let i=r[0],s=i,o=new ft;if(o.firstToken=i,r.length===1&&!U(this.currentToken,2)){this._issues.push(z(25,o.firstToken,o.lastToken,o)),o.lastToken=r.at(-1);let u=new yt(o);return n.addNodeChild(u),this.mergeStack(),!0}let a=r.map(u=>u.value??"").join("");if(!"/delete-property/".startsWith(a)||a.endsWith("-"))return this.popStack(),!1;o.lastToken=r.at(-1),a!=="/delete-property"?this._issues.push(z(a.startsWith("/delete-p")?35:25,o.firstToken,o.lastToken,o)):U(this.currentToken,13)?(s=this.moveToNextToken,o.lastToken=s):this._issues.push(z(21,o.firstToken,o.lastToken,o));let c=new yt(o);if(ln(o.lastToken,i)){let u=this.isPropertyName();u||this._issues.push(z(6,c.firstToken,c.lastToken,c)),c.propertyName=u??null}else this._issues.push(z(6,o.firstToken,o.lastToken,o));let l=this.endStatement(c);return c.lastToken=l,n.addNodeChild(c),this.mergeStack(),!0}isNodePathRef(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!0),i=this.processNodePathRef(n);if(!i){this.popStack();return}let s=[];this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&s.push(...this.processOptionalLabelAssign(!0));let o=new Dn(r,i,s);return this.mergeStack(),o}processValue(n){this.enqueueToStack();let i=(()=>{let o=()=>(this.processStringValue()||this.isNodePathRef(n)||this.isLabelRefValue(n)||this.arrayValues(n)||this.processByteStringValue()||this.isExpressionValue(n))??null,a=o();if(!a)return[];let c=[a];for(;!U(this.currentToken,1);){let l=this.prevToken,u=this.currentToken,d,f=U(this.currentToken,24);if(f)d=this.currentToken,this.moveToNextToken;else if(!ln(this.prevToken,this.currentToken))break;let p=o();if(u&&p===null&&f){let h=new te(de(u,this.currentToken));this._issues.push(z(0,h.firstToken,h.lastToken,h))}if(!f&&p===null)break;if(l&&!f&&p){let h=new te(de(l));this._issues.push(z(28,h.firstToken,h.lastToken,h))}let m=c.at(-1);m&&(m.nextValueSeparator??=d),c.push(p)}return c})();if(i.length===0){this.popStack();return}return this.mergeStack(),new rp(i)}processStringValue(){this.enqueueToStack();let n=this.processOptionalLabelAssign(!0),r=this.consumeAnyConcurrentTokens([Le(21)]);if(!r.length){this.popStack();return}if(r.some(u=>u.value===void 0))throw new Error("Token must have value");let i=r.map(u=>u.value).join(`
284
- `),s=i,o=['"',"'"].some(u=>s.endsWith(u));o&&(s=s.slice(1,-1));let a=new re(s,de(r[0],r.at(-1)));o||this._issues.push(z(i.startsWith('"')?16:17,a.firstToken,a.lastToken,a));let c=[];this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&(c=this.processOptionalLabelAssign(!0));let l=new Dn(n,a,c);return this.mergeStack(),l}arrayValues(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!0),i=this.processBits(),s=this.currentToken;if(U(s,5))this.moveToNextToken;else{this.popStack();return}let o=this.processArrayValues(n)??null;o.openBracket=s;let a=this.processOptionalLabelAssign(!0)??[],c=new Dn(r,o,a,i);if(!U(this.currentToken,4))this._issues.push(z(12,c.firstToken,c.lastToken,c));else{let u=this.moveToNextToken;o&&(o.closeBracket=u)}let l=[];return this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&(l=this.processOptionalLabelAssign(!0)),this.mergeStack(),c.endLabels.push(...l),c.firstToken=s,c.lastToken=this.prevToken,c}processByteStringValue(){this.enqueueToStack();let n=this.processOptionalLabelAssign(!0),r=this.moveToNextToken,i=r;if(!U(i,11)){this.popStack();return}let s=this.processLabeledValue(()=>this.processHexString()),o=this.processOptionalLabelAssign(!0)??[];s.forEach(u=>{let d=0;u.value&&u.value.firstToken===u.value.lastToken&&(d=u.value.firstToken.pos.len),d%2!==0&&this._issues.push(z(15,u.firstToken,u.lastToken,u))});let a=new or(s??[]);a.openBracket=i,a.values.length===0&&(a.firstToken=r,this._issues.push(z(14,a.firstToken,a.lastToken,a,{severity:tl.DiagnosticSeverity.Information})));let c=new Dn(n,a,o);U(this.currentToken,12)?a.closeBracket=this.moveToNextToken:this._issues.push(z(5,c.firstToken,c.lastToken,c));let l=[];return this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&(l=this.processOptionalLabelAssign(!0)),this.mergeStack(),c.endLabels.push(...l),c.firstToken=r,a.lastToken=this.prevToken,c}processLabeledValue(n){this.enqueueToStack();let r=n(),i=[];if(!r)return this.popStack(),[];for(;r;)i.push(r),r=n();if(i.length){let s=n();s&&i.push(s)}return this.mergeStack(),i}processArrayValues(n){this.enqueueToStack();let r=this.processLabeledValue(()=>{let s=()=>this.processRefValue(n,!1)||this.processLabeledHex(!1)||this.processLabeledDec(!1)||this.processLabeledExpression(!0,!1,n),o=this.peekIndex(),a=s();return a&&!this.cPreprocessorParser.optimizeForFormatting&&(a.value instanceof Ut&&a.value.params.every(c=>!!c)&&this.cPreprocessorParser.macros.has(a.value.functionName.name)||a.value instanceof pt&&this.cPreprocessorParser.macros.has(a.value.name))&&typeof a.value.evaluate(this.cPreprocessorParser.macros)=="string"?(this.injectPreProcessorResults(this.cPreprocessorParser.macros,a.value,o),s()):a}),i=new gt(r);return r.length===0&&(i.firstToken=this.currentToken),this.mergeStack(),i}processLabeledHex(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(n),i=this.processHex();if(!i){this.popStack();return}let s=new yi(i,r);return this.mergeStack(),s}processHexString(){this.enqueueToStack();let n=this.processOptionalLabelAssign(!1),r=this.checkConcurrentTokens([20,20].map(Le));if(!r.length){this.popStack();return}let i=Number.parseInt(r.map(a=>a.value).join(""),16),s=new Zt(i,de(r[0],r.at(-1)),16),o=new yi(s,n);return this.mergeStack(),o}processLabeledDec(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(n),i=this.processDec();if(!i){this.popStack();return}let s=new yi(i,r);return this.mergeStack(),s}processLabeledExpression(n=!0,r=n,i){this.enqueueToStack();let s=[];n&&(s=this.processOptionalLabelAssign(r));let o=this.processExpression(this.cPreprocessorParser.macros,i);if(!o){this.popStack();return}let a=new yi(o,s);return this.mergeStack(),a}isExpressionValue(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!1),i=this.processExpression(this.cPreprocessorParser.macros,n);if(!i){this.popStack();return}let s=this.processOptionalLabelAssign(!0),o=new Dn(r,i,s);return this.mergeStack(),o}isLabelRef(n){this.enqueueToStack();let r=this.currentToken;if(!r||!U(r,40)){this.popStack();return}else this.moveToNextToken;let i=this.isLabelName();if(!i){let o=new ie(null);return this._issues.push(z(18,r,r,n)),o.firstToken=r,this.mergeStack(),o}r&&(i.firstToken.pos.line!==r.pos.line||i.firstToken.pos.col!==r.pos.colEnd)&&this._issues.push(z(29,r,i.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}));let s=new ie(i);return s.firstToken=r,this.mergeStack(),s}isLabelRefValue(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!0),i=this.isLabelRef(n);if(!i){this.popStack();return}let s=[];this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&(s=this.processOptionalLabelAssign(!0));let o=new Dn(r,i,s);return this.mergeStack(),o}processRefValue(n,r){this.enqueueToStack();let i=this.processOptionalLabelAssign(r),s=this.currentToken;if(!s||!U(s,40)){this.popStack();return}let o=this.processNodePathRef(n);if(o!==void 0){let l=new yi(o,i);return this.mergeStack(),l}let a=this.isLabelRef(n);if(a===void 0){this._issues.push(z([18,9],s,s,n));let l=new yi(null,i);return l.firstToken=i.at(0)?.firstToken??s,this.mergeStack(),l}let c=new yi(a,i);return c.firstToken=i.at(0)?.firstToken??s,this.mergeStack(),c}processNodePath(n=!0,r=new Gr){this.enqueueToStack();let i;if(U(this.currentToken,13))i=this.moveToNextToken;else{if(!n){this.popStack();return}this.prevToken&&this._issues.push(z(19,this.prevToken,this.prevToken,r))}let s=this.isNodeName(),o=i??this.prevToken;if(!s&&o&&!n&&this._issues.push(z(7,o,o,r)),!n||s?r.addPath(s??null,i?new te(de(i)):void 0):n&&!s&&i&&(r.addPath(new xe("/",de(i))),r.firstToken=i),n&&!i&&r.children.length===0){this.mergeStack();return}return this.processNodePath(!1,r),this.mergeStack(),r}processNodePathRef(n){this.enqueueToStack();let r=this.moveToNextToken,i=r;if(!U(i,40)){this.popStack();return}let s=this.moveToNextToken;if(i=s,!U(i,2)){this.popStack();return}r&&!Vt(r,s)&&this._issues.push(z(29,r,s,n,{inclusiveStart:!1,inclusiveEnd:!1}));let o=this.processNodePath(),a=new ot(o??null),c=this.currentToken??this.prevToken,l=c;return o?.children.forEach((u,d)=>{if(d===o?.children.length-1&&u&&l&&!Vt(u.lastToken,l)){this._issues.push(z(29,u.lastToken,l,n,{inclusiveStart:!1,inclusiveEnd:!1}));return}if(d===0&&s&&!Vt(s,u?.firstToken)){this._issues.push(z(29,s,u?.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}));return}let f=o?.children[d+1];u&&f&&!Vt(u.lastToken,f.firstToken)&&this._issues.push(z(29,u.lastToken,f?.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}))}),U(c,3)?this.moveToNextToken:this.prevToken&&this._issues.push(z(3,this.prevToken,this.prevToken,n)),a.firstToken=r,a.lastToken=c??this.prevToken,this.mergeStack(),a}get includes(){return this.allAstItems.filter(n=>n instanceof kr)}get allAstItems(){return[...this.cPreprocessorParser.allAstItems,...this.rootDocument.children,...this.others,...this.unhandledStatements.properties,...this.unhandledStatements.deleteProperties,...this.unhandledStatements.nodes]}#e;get latestSemanticTokensBuilt(){return this.#e}buildSemanticTokens(n,r){let i=[];this.injectedMacros.forEach(s=>{s.buildSemanticTokens((...o)=>$i.push(...o,r,i))}),super.buildSemanticTokens(n,r,i),this.#e=!0}};var ap=class t{constructor(e,n,r){this.settings=e;this.formattingOptions=n;this.bindingLoader=r;this._issues=[];this.overlayParsers=[];this.overlays=[];this.ctxNames_=new Set;this.sortKeys=new WeakMap;this.staleFsPaths=new Set;let i={includePaths:[],overlays:[],zephyrBindings:[],deviceOrgTreeBindings:[],deviceOrgBindingsMetaSchema:[],...e,ctxName:e.ctxName??(0,Sa.basename)(e.dtsFile),lockRenameEdits:[],showFormattingErrorAsDiagnostics:e.showFormattingErrorAsDiagnostics??!0,disableFileWatchers:e.disableFileWatchers??!1};this.isFullContext=this.settings.dtsFile.toLowerCase().endsWith(".dts"),this.overlays=i.overlays,this.overlays.filter(nl.existsSync);let s=this.isFullContext&&r?.type==="Zephyr"?[(0,Sa.join)((0,Sa.dirname)(this.settings.dtsFile),"dts"),...i.includePaths]:i.includePaths;this.parser=new Fi(i.dtsFile,s),this.ctxNames_.add(i.ctxName),this.id=qi(i),this.parser.stable.then(()=>{this.overlayParsers=this.overlays?.map(o=>new Fi(o,s,this.parser.cPreprocessorParser.macros))??[]})}get macros(){return this.allParsers.at(-1).cPreprocessorParser.macros}get ctxNames(){return Array.from(this.ctxNames_)}addCtxName(e){this.ctxNames_.add(e)}removeCtxName(e){this.ctxNames_.delete(e)}async getContextIssues(){return[...(await this.getRuntime()).issues,...this._issues]}async getFileTree(){let e=new Map,n=i=>({fsPath:i,includes:(e.get(i)??[]).map(s=>n(s.resolvedPath??s.path))});return(await this.getRuntime()).includes.forEach(i=>{let s=e.get(i.fsPath);s||(s=[],e.set(i.fsPath,s)),s.push({path:i.path.path,resolvedPath:i.resolvedPath})}),{mainDtsPath:n(this.parser.fsPath),overlays:this.overlays.map(n)}}async stable(){await Promise.all([this.parser.stable,...this.overlayParsers.map(e=>e.stable)])}async getRuntime(){return await this.stable(),this._runtime??=this.evaluate(),this._runtime}getContextFiles(){return[...this.overlayParsers.flatMap(e=>e.getFiles()),...this.parser.getFiles()]}isInContext(e){return this.getContextFiles().some(n=>pe(n,e))}getFsPathParser(e){let n=this.overlayParsers.find(r=>r.getFiles().some(i=>pe(i,e)));return n??=this.parser.getFiles().some(r=>pe(r,e))?this.parser:void 0,n}async getAllStableParsers(){return await this.stable(),this.allParsers}get allParsers(){return[this.parser,...this.overlayParsers]}async getDocumentLinks(e,n){if(!this.isInContext(e))return[];let i=(await this.getRuntime()).rootNode.allBindingsProperties.filter(s=>pe(s.ast.fsPath,e)&&(!n||Cn(s.ast,e,n))).flatMap(s=>s.ast.values?.values.flatMap(o=>{let c=s.parent?.nodeTypes.find(l=>o?.value instanceof re&&l.compatible===o.value.value);return c?{range:ce(o.value),target:ue(c.bindingsPath)}:void 0})).filter(s=>!!s)??[];return[...this.parser.cPreprocessorParser.dtsIncludes.filter(s=>pe(s.fsPath,e)&&(!n||Cn(s,e,n))).map(s=>{let o=this.parser.cPreprocessorParser.resolveInclude(s);if(o)return{range:ce(s.path),target:ue(o)}}).filter(s=>!!s)??[],...i]}linkPropertiesLabelsAndNodePaths(e){let n=s=>[...s.properties,...s.nodes.flatMap(n)],r=n(e.rootNode),i=e.rootNode.allDescendantsLabels;r.forEach(s=>s.ast.allDescendants.forEach(o=>{if(o instanceof ie){let a=e.resolvePath([`&${o.label?.value}`],i);if(a){let c=e.rootNode.getChild(a);o.linksTo=c,c?.linkedRefLabels.push(o)}else o.value&&this._issues.push(Ht(3,o.firstToken,o.lastToken,o,{templateStrings:[o.value]}))}else o instanceof Gr&&this.linkNodePath(o,e.rootNode)}))}linkNodePath(e,n){let r=n,i=e.pathParts;for(let s=0;s<i.length&&i[s];s++){let o=!1,a=i[s];if(a){let c=s===0&&a.name==="/"?n:r?.getNode(a.name,a.fullAddress,!1);a.linksTo=c,!o&&!c&&(o=!0,this._issues.push(Ht(8,a.firstToken,a.lastToken,a,{templateStrings:[a.toString(),`${e.pathParts.filter(l=>l?.linksTo).map(l=>l?.toString()).join("/")}`]}))),c?.linkedNodeNamePaths.push(a),r=c}else break}}setStaleFsPath(e){this.staleFsPaths.add(e)}async reevaluate(e){this.setStaleFsPath(e);let n=new Set;return this.staleFsPaths.forEach(r=>{let i=this.getFsPathParser(r);i&&n.add(i)}),n.size?(this.sortKeys=new WeakMap,await Promise.all(Array.from(n).map(r=>r.reparse())),this._runtime=this.evaluate(),this._runtime):this._runtime}getSortKey(e){if(e)return this.sortKeys.get(e.firstToken)}async evaluate(){let e=performance.now();await this.stable();let n=new gi(this);this.staleFsPaths.clear(),this._issues=[],this.parser.rootDocument.resetIssues(),this.processRoot(this.parser.rootDocument,n);for(let r=0;r<this.overlayParsers.length;r++)this.overlayParsers[r].rootDocument.resetIssues(),this.processRoot(this.overlayParsers[r].rootDocument,n);return await Promise.all(n.rootNode.defaultProperties.map(async r=>{let i=new Kr(r.text,r.fsPath),s=new Fi(r.fsPath,[],void 0,()=>i.tokens);await s.stable,this.processRoot(s.rootDocument,n)})),n.includes=this.parser.includes,n.comments=this.parser.cPreprocessorParser.allAstItems.filter(r=>r instanceof lr),this.allParsers.flatMap(r=>r.tokens).forEach((r,i)=>this.sortKeys.set(r,i)),this.linkPropertiesLabelsAndNodePaths(n),this.reportNodeNameAndPropertyClashes(n),console.log(`(ID: ${this.id}) evaluate`,performance.now()-e),n}getSortKeyFile(e,n){let r=this.findTokenBeforePosition(e,n),i=r,s=i?this.sortKeys.get(i):void 0;for(;i&&!s;)i=i.nextToken,s=i?this.sortKeys.get(i):void 0;if(s!==void 0)return s;for(i=r,s=i?this.sortKeys.get(i):void 0;i&&!s;)i=i.prevToken,s=i?this.sortKeys.get(i):void 0;return s}findTokenBeforePosition(e,n){let r=[this.parser,...this.overlayParsers].flatMap(i=>({parser:i,tokens:i.tokens}));for(let[i,s]of r.entries()){if(s.tokens.length===0&&pe(s.parser.fsPath,n)){let c=r[i-1];return i?c.tokens[c.tokens.length-1]:void 0}let o=s.tokens.find((c,l)=>Bc(c,n,e)&&(l===s.tokens.length-1||!c.nextToken||uT(c.nextToken,n,e)));if(o)return o;let a=s.parser.includes.find(c=>c.resolvedPath===n);if(a)return a.lastToken}}reportNodeNameAndPropertyClashes(e){let n=r=>{r.properties.forEach(i=>{r.nodes.filter(o=>o.address===void 0&&o.name===i.ast.propertyName?.name&&o.definitions.at(-1)?.name).forEach(o=>{let a=o.definitions,c=a[a.length-1].name;this._issues.push(Ht(2,c.firstToken,c.lastToken,c,{linkedTo:[i.ast,...i.allReplaced.map(l=>l.ast)]}))})}),r.nodes.forEach(n)};n(e.rootNode)}processRoot(e,n){for(let r=0;r<e.children.length;r++){let i=e.children[r];this.processChild(i,n.rootNode,n)}}processChild(e,n,r){e instanceof Ue?this.processDtcBaseNode(e,n,r):e instanceof je?this.processDtcProperty(e,n,r):e instanceof Gn?this.processDeleteNode(e,n,r):e instanceof yt&&this.processDeleteProperty(e,n,r)}checkNodeUniqueNames(e,n){let r=(o,a)=>o.filter(c=>c.name===a.name&&(c.address===a.fullAddress&&c.address===void 0||Lt(c.address??[],a.fullAddress??[])===0)).map(c=>c.issueAst),i=n.nodes.map(o=>{let a=o.definitions[0];return{name:o.name,address:o.address,issueAst:a.name??a}}),s=[];e.children.forEach(o=>{if(o instanceof He&&o.name){let a=r(s.map(c=>({name:c.name,address:c.fullAddress,issueAst:c})),o.name);a.length&&this._issues.push(Ht(2,o.name.firstToken,o.name.lastToken,o.name,{linkedTo:a})),s.push(o.name)}else if(o instanceof Gn&&o.nodeNameOrRef instanceof xe){let a=o.nodeNameOrRef;r(i,a)&&(s=s.filter(c=>r(s.map(l=>({name:l.name,address:l.fullAddress,issueAst:l})),c).length))}})}getCompileCommands(){if(!(!this.settings.compileCommands||!(0,nl.existsSync)(this.settings.compileCommands)))return JSON.parse((0,nl.readFileSync)(this.settings.compileCommands).toString())}processDtcBaseNode(e,n,r){e instanceof Tt?this.processDtcRootNode(e,r):e instanceof He?this.processDtcChildNode(e,n,r):e instanceof Et&&this.processDtcRefNode(e,r)}processDtcRootNode(e,n){n.rootNode.implementations.push(e),this.checkNodeUniqueNames(e,n.rootNode),e.children.forEach(r=>this.processChild(r,n.rootNode,n))}processDtcChildNode(e,n,r){if(e.name?.name){let i=e.path?r.resolvePath(e.path):void 0,o=(i?r.rootNode.getChild(i):void 0)??new X(this.bindingLoader,e.name.name,e.name.fullAddress,n);o.implementations.push(e),e.labels.forEach(a=>a.lastLinkedTo=o),n=o,this.checkNodeUniqueNames(e,o)}e.children.forEach(i=>this.processChild(i,n,r))}processDtcRefNodeLabelRef(e,n,r){let i,s=e.resolveNodePath??(e.pathName?r.resolvePath([e.pathName]):void 0);return s?(e.resolveNodePath??=[...s],i=r.rootNode.getChild(s),n.linksTo=i,e.labels.forEach(o=>o.lastLinkedTo=i),i?.linkedRefLabels.push(n),i?.implementations.push(e),e.labels.forEach(o=>{r.labelsUsedCache.set(o.label.value,s)}),i?(r.references.push(e),this.checkNodeUniqueNames(e,i)):r.unlinkedRefNodes.push(e)):(this._issues.push(Ht(3,n.firstToken,n.lastToken,n,{templateStrings:[n.label?.value??""]})),r.unlinkedRefNodes.push(e)),i}processDtcRefNodeNodePathRef(e,n,r){let i;n.path&&this.linkNodePath(n.path,r.rootNode);let o=n.path?.pathParts.at(-1)?.linksTo?.path;return o?(e.resolveNodePath??=o,i=r.rootNode.getChild(o),e.labels.forEach(a=>a.lastLinkedTo=i),i?.implementations.push(e),e.labels.forEach(a=>{r.labelsUsedCache.set(a.label.value,o)}),i?(r.references.push(e),this.checkNodeUniqueNames(e,i)):r.unlinkedRefNodes.push(e)):r.unlinkedRefNodes.push(e),i}processDtcRefNode(e,n){let r;e.reference?e.reference instanceof ie?r=this.processDtcRefNodeLabelRef(e,e.reference,n):r=this.processDtcRefNodeNodePathRef(e,e.reference,n):n.unlinkedRefNodes.push(e),e.children.forEach(i=>this.processChild(i,r??new X(this.bindingLoader,""),n))}processDtcProperty(e,n,r){e.propertyName?.name&&n.addProperty(new Xe(e,n)),e.children.forEach(i=>this.processChild(i,n,r))}processDeleteNode(e,n,r){if(e.nodeNameOrRef instanceof xe&&e.nodeNameOrRef.value){if(e.parentNode?.parentNode)if(!n.hasNode(e.nodeNameOrRef.name,e.nodeNameOrRef.fullAddress))this._issues.push(Ht(5,e.nodeNameOrRef.firstToken,e.nodeNameOrRef.lastToken,e.nodeNameOrRef));else{n.deletes.push(e);let i=n.getNode(e.nodeNameOrRef.name,e.nodeNameOrRef.fullAddress);e.nodeNameOrRef.linksTo=i,n.deleteNode(e.nodeNameOrRef.name,e,e.nodeNameOrRef.fullAddress),i?.labels.forEach(s=>{r.labelsUsedCache.delete(s.label.value)})}}else if(e.nodeNameOrRef instanceof ie&&e.nodeNameOrRef.value){let i=r.resolvePath([`&${e.nodeNameOrRef.value}`]),s;i?(s=r.rootNode.getChild(i),n.deletes.push(e),e.nodeNameOrRef.linksTo=s,s?.labels.forEach(o=>{r.labelsUsedCache.delete(o.label.value)}),s?.linkedRefLabels.push(e.nodeNameOrRef),s?.parent?.deleteNode(s.name,e,s.address),e.parentNode instanceof Ue&&!e.parentNode.pathName&&r.globalDeletes.push(e)):(r.unlinkedDeletes.push(e),this._issues.push(Ht(3,e.nodeNameOrRef.firstToken,e.nodeNameOrRef.lastToken,e.nodeNameOrRef,{templateStrings:[e.nodeNameOrRef.value]})))}else if(e.nodeNameOrRef instanceof ot&&e.nodeNameOrRef.path&&!e.nodeNameOrRef.path.pathParts.some(i=>!i)){let i=r.rootNode,s=e.nodeNameOrRef.path.pathParts;for(let c=0;c<s.length&&s[c];c++){let l=s[c];if(l){let u=i?.getNode(l.name,l.fullAddress,!1);l.linksTo=u,u?.linkedNodeNamePaths.push(l),i=u}}let o=e.nodeNameOrRef.path.pathParts.find(c=>c&&!c.linksTo),a=e.nodeNameOrRef.path.pathParts.at(-1)?.linksTo;a||(r.unlinkedDeletes.push(e),o&&this._issues.push(Ht(8,o.firstToken,o.lastToken,o,{templateStrings:[o.toString(),`${e.nodeNameOrRef.path.pathParts.filter(c=>c?.linksTo).map(c=>c?.toString()).join("/")}`]}))),n.deletes.push(e),a?.labels.forEach(c=>{r.labelsUsedCache.delete(c.label.value)}),a?.parent?.deleteNode(a.name,e,a.address),e.parentNode instanceof Ue&&!e.parentNode.pathName&&r.globalDeletes.push(e)}else r.unlinkedDeletes.push(e);e.children.forEach(i=>this.processChild(i,n,r))}processDeleteProperty(e,n,r){e.propertyName?.name&&!n.hasProperty(e.propertyName.name)?this._issues.push(Ht(1,e.propertyName.firstToken,e.propertyName.lastToken,e.propertyName)):e.propertyName?.name&&(n.deletes.push(e),n.deleteProperty(e.propertyName.name,e)),e.children.forEach(i=>this.processChild(i,n,r))}static#e(e,n,r){let i=r.get(n);i||(i=[],r.set(n,i)),i.push(e)}getIssues(e,n=new Map,r=i=>{if(!(i.raw.severity===lo.DiagnosticSeverity.Hint&&i.raw.virtual))return i.raw.severity===lo.DiagnosticSeverity.Error&&!this.isFullContext&&(i.raw.severity=lo.DiagnosticSeverity.Warning),i}){return e.forEach(i=>{let s=r(i);s&&t.#e(s.diagnostic(),s.raw.fsPath,n)}),n}async getSyntaxIssues(e=new Map,n=r=>{if(r.raw.severity===lo.DiagnosticSeverity.Error&&!this.isFullContext&&!io(r.raw,r.raw.fsPath,!1)&&(r.raw.severity=lo.DiagnosticSeverity.Warning),!(r.raw.severity===lo.DiagnosticSeverity.Hint&&r.raw.virtual))return r}){return(await this.getAllStableParsers()).forEach(r=>this.getIssues(r.issues,e,n)),e}async getDiagnostics(){let e=new Map;try{await this.getSyntaxIssues(e);let n=await this.getContextIssues()??[];this.getIssues(n,e);let r=await this.getRuntime();return this.getIssues(r.typesIssues,e),e}catch(n){throw console.error(n),n}}async toFullString(){return`/dts-v1/;
284
+ `),s=i,o=['"',"'"].some(u=>s.endsWith(u));o&&(s=s.slice(1,-1));let a=new re(s,de(r[0],r.at(-1)));o||this._issues.push(z(i.startsWith('"')?16:17,a.firstToken,a.lastToken,a));let c=[];this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&(c=this.processOptionalLabelAssign(!0));let l=new Dn(n,a,c);return this.mergeStack(),l}arrayValues(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!0),i=this.processBits(),s=this.currentToken;if(U(s,5))this.moveToNextToken;else{this.popStack();return}let o=this.processArrayValues(n)??null;o.openBracket=s;let a=this.processOptionalLabelAssign(!0)??[],c=new Dn(r,o,a,i);if(!U(this.currentToken,4))this._issues.push(z(12,c.firstToken,c.lastToken,c));else{let u=this.moveToNextToken;o&&(o.closeBracket=u)}let l=[];return this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&(l=this.processOptionalLabelAssign(!0)),this.mergeStack(),c.endLabels.push(...l),c.firstToken=s,c.lastToken=this.prevToken,c}processByteStringValue(){this.enqueueToStack();let n=this.processOptionalLabelAssign(!0),r=this.moveToNextToken,i=r;if(!U(i,11)){this.popStack();return}let s=this.processLabeledValue(()=>this.processHexString()),o=this.processOptionalLabelAssign(!0)??[];s.forEach(u=>{let d=0;u.value&&u.value.firstToken===u.value.lastToken&&(d=u.value.firstToken.pos.len),d%2!==0&&this._issues.push(z(15,u.firstToken,u.lastToken,u))});let a=new or(s??[]);a.openBracket=i,a.values.length===0&&(a.firstToken=r,this._issues.push(z(14,a.firstToken,a.lastToken,a,{severity:tl.DiagnosticSeverity.Information})));let c=new Dn(n,a,o);U(this.currentToken,12)?a.closeBracket=this.moveToNextToken:this._issues.push(z(5,c.firstToken,c.lastToken,c));let l=[];return this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&(l=this.processOptionalLabelAssign(!0)),this.mergeStack(),c.endLabels.push(...l),c.firstToken=r,a.lastToken=this.prevToken,c}processLabeledValue(n){this.enqueueToStack();let r=n(),i=[];if(!r)return this.popStack(),[];for(;r;)i.push(r),r=n();if(i.length){let s=n();s&&i.push(s)}return this.mergeStack(),i}processArrayValues(n){this.enqueueToStack();let r=this.processLabeledValue(()=>{let s=()=>this.processRefValue(n,!1)||this.processLabeledHex(!1)||this.processLabeledDec(!1)||this.processLabeledExpression(!0,!1,n),o=this.peekIndex(),a=s();return a&&!this.cPreprocessorParser.optimizeForFormatting&&(a.value instanceof Ut&&a.value.params.every(c=>!!c)&&this.cPreprocessorParser.macros.has(a.value.functionName.name)||a.value instanceof pt&&this.cPreprocessorParser.macros.has(a.value.name))&&typeof a.value.evaluate(this.cPreprocessorParser.macros)=="string"?(this.injectPreProcessorResults(this.cPreprocessorParser.macros,a.value,o),s()):a}),i=new gt(r);return r.length===0&&(i.firstToken=this.currentToken),this.mergeStack(),i}processLabeledHex(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(n),i=this.processHex();if(!i){this.popStack();return}let s=new yi(i,r);return this.mergeStack(),s}processHexString(){this.enqueueToStack();let n=this.processOptionalLabelAssign(!1),r=this.checkConcurrentTokens([20,20].map(Le));if(!r.length){this.popStack();return}let i=Number.parseInt(r.map(a=>a.value).join(""),16),s=new Zt(i,de(r[0],r.at(-1)),16),o=new yi(s,n);return this.mergeStack(),o}processLabeledDec(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(n),i=this.processDec();if(!i){this.popStack();return}let s=new yi(i,r);return this.mergeStack(),s}processLabeledExpression(n=!0,r=n,i){this.enqueueToStack();let s=[];n&&(s=this.processOptionalLabelAssign(r));let o=this.processExpression(this.cPreprocessorParser.macros,i);if(!o){this.popStack();return}let a=new yi(o,s);return this.mergeStack(),a}isExpressionValue(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!1),i=this.processExpression(this.cPreprocessorParser.macros,n);if(!i){this.popStack();return}let s=this.processOptionalLabelAssign(!0),o=new Dn(r,i,s);return this.mergeStack(),o}isLabelRef(n){this.enqueueToStack();let r=this.currentToken;if(!r||!U(r,40)){this.popStack();return}else this.moveToNextToken;let i=this.isLabelName();if(!i){let o=new ie(null);return this._issues.push(z(18,r,r,n)),o.firstToken=r,this.mergeStack(),o}r&&(i.firstToken.pos.line!==r.pos.line||i.firstToken.pos.col!==r.pos.colEnd)&&this._issues.push(z(29,r,i.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}));let s=new ie(i);return s.firstToken=r,this.mergeStack(),s}isLabelRefValue(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!0),i=this.isLabelRef(n);if(!i){this.popStack();return}let s=[];this.currentToken&&this.currentToken.pos.line===this.currentToken.prevToken?.pos.line&&(s=this.processOptionalLabelAssign(!0));let o=new Dn(r,i,s);return this.mergeStack(),o}processRefValue(n,r){this.enqueueToStack();let i=this.processOptionalLabelAssign(r),s=this.currentToken;if(!s||!U(s,40)){this.popStack();return}let o=this.processNodePathRef(n);if(o!==void 0){let l=new yi(o,i);return this.mergeStack(),l}let a=this.isLabelRef(n);if(a===void 0){this._issues.push(z([18,9],s,s,n));let l=new yi(null,i);return l.firstToken=i.at(0)?.firstToken??s,this.mergeStack(),l}let c=new yi(a,i);return c.firstToken=i.at(0)?.firstToken??s,this.mergeStack(),c}processNodePath(n=!0,r=new Gr){this.enqueueToStack();let i;if(U(this.currentToken,13))i=this.moveToNextToken;else{if(!n){this.popStack();return}this.prevToken&&this._issues.push(z(19,this.prevToken,this.prevToken,r))}let s=this.isNodeName(),o=i??this.prevToken;if(!s&&o&&!n&&this._issues.push(z(7,o,o,r)),!n||s?r.addPath(s??null,i?new te(de(i)):void 0):n&&!s&&i&&(r.addPath(new xe("/",de(i))),r.firstToken=i),n&&!i&&r.children.length===0){this.mergeStack();return}return this.processNodePath(!1,r),this.mergeStack(),r}processNodePathRef(n){this.enqueueToStack();let r=this.moveToNextToken,i=r;if(!U(i,40)){this.popStack();return}let s=this.moveToNextToken;if(i=s,!U(i,2)){this.popStack();return}r&&!Vt(r,s)&&this._issues.push(z(29,r,s,n,{inclusiveStart:!1,inclusiveEnd:!1}));let o=this.processNodePath(),a=new ot(o??null),c=this.currentToken??this.prevToken,l=c;return o?.children.forEach((u,d)=>{if(d===o?.children.length-1&&u&&l&&!Vt(u.lastToken,l)){this._issues.push(z(29,u.lastToken,l,n,{inclusiveStart:!1,inclusiveEnd:!1}));return}if(d===0&&s&&!Vt(s,u?.firstToken)){this._issues.push(z(29,s,u?.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}));return}let f=o?.children[d+1];u&&f&&!Vt(u.lastToken,f.firstToken)&&this._issues.push(z(29,u.lastToken,f?.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}))}),U(c,3)?this.moveToNextToken:this.prevToken&&this._issues.push(z(3,this.prevToken,this.prevToken,n)),a.firstToken=r,a.lastToken=c??this.prevToken,this.mergeStack(),a}get includes(){return this.allAstItems.filter(n=>n instanceof kr)}get allAstItems(){return[...this.cPreprocessorParser.allAstItems,...this.rootDocument.children,...this.others,...this.unhandledStatements.properties,...this.unhandledStatements.deleteProperties,...this.unhandledStatements.nodes]}#e;get latestSemanticTokensBuilt(){return this.#e}buildSemanticTokens(n,r){let i=[];this.injectedMacros.forEach(s=>{s.buildSemanticTokens((...o)=>$i.push(...o,r,i))}),super.buildSemanticTokens(n,r,i),this.#e=!0}};var ap=class t{constructor(e,n,r){this.settings=e;this.formattingOptions=n;this.bindingLoader=r;this._issues=[];this.overlayParsers=[];this.overlays=[];this.ctxNames_=new Set;this.sortKeys=new WeakMap;this.staleFsPaths=new Set;let i={includePaths:[],overlays:[],zephyrBindings:[],deviceOrgTreeBindings:[],deviceOrgBindingsMetaSchema:[],...e,ctxName:e.ctxName??(0,Sa.basename)(e.dtsFile),lockRenameEdits:[],showFormattingErrorAsDiagnostics:e.showFormattingErrorAsDiagnostics??!0,disableFileWatchers:e.disableFileWatchers??!1};this.isFullContext=this.settings.dtsFile.toLowerCase().endsWith(".dts"),this.overlays=i.overlays,this.overlays.filter(nl.existsSync);let s=this.isFullContext&&r?.type==="Zephyr"?[(0,Sa.join)((0,Sa.dirname)(this.settings.dtsFile),"dts"),...i.includePaths]:i.includePaths;this.parser=new Fi(i.dtsFile,s),this.ctxNames_.add(i.ctxName),this.id=qi(i),this.parser.stable.then(()=>{this.overlayParsers=this.overlays?.map(o=>new Fi(o,s,this.parser.cPreprocessorParser.macros))??[]})}get macros(){return this.allParsers.at(-1).cPreprocessorParser.macros}get ctxNames(){return Array.from(this.ctxNames_)}addCtxName(e){this.ctxNames_.add(e)}removeCtxName(e){this.ctxNames_.delete(e)}async getContextIssues(){return[...(await this.getRuntime()).issues,...this._issues]}async getFileTree(){let e=new Map,n=i=>({fsPath:i,includes:(e.get(i)??[]).map(s=>n(s.resolvedPath??s.path))});return(await this.getRuntime()).includes.forEach(i=>{let s=e.get(i.fsPath);s||(s=[],e.set(i.fsPath,s)),s.push({path:i.path.path,resolvedPath:i.resolvedPath})}),{mainDtsPath:n(this.parser.fsPath),overlays:this.overlays.map(n)}}async stable(){await Promise.all([this.parser.stable,...this.overlayParsers.map(e=>e.stable)])}async getRuntime(){return await this.stable(),this._runtime??=this.evaluate(),this._runtime}getContextFiles(){return[...this.overlayParsers.flatMap(e=>e.getFiles()),...this.parser.getFiles()]}isInContext(e){return this.getContextFiles().some(n=>pe(n,e))}getFsPathParser(e){let n=this.overlayParsers.find(r=>r.getFiles().some(i=>pe(i,e)));return n??=this.parser.getFiles().some(r=>pe(r,e))?this.parser:void 0,n}async getAllStableParsers(){return await this.stable(),this.allParsers}get allParsers(){return[this.parser,...this.overlayParsers]}async getDocumentLinks(e,n){if(!this.isInContext(e))return[];let i=(await this.getRuntime()).rootNode.allBindingsProperties.filter(s=>pe(s.ast.fsPath,e)&&(!n||Cn(s.ast,e,n))).flatMap(s=>s.ast.values?.values.flatMap(o=>{let c=s.parent?.nodeTypes.find(l=>o?.value instanceof re&&l.compatible===o.value.value);return c?{range:ce(o.value),target:ue(c.bindingsPath)}:void 0})).filter(s=>!!s)??[];return[...this.parser.cPreprocessorParser.dtsIncludes.filter(s=>pe(s.fsPath,e)&&(!n||Cn(s,e,n))).map(s=>{let o=this.parser.cPreprocessorParser.resolveInclude(s);if(o)return{range:ce(s.path),target:ue(o)}}).filter(s=>!!s)??[],...i]}linkPropertiesLabelsAndNodePaths(e){let n=s=>[...s.properties,...s.nodes.flatMap(n)],r=n(e.rootNode),i=e.rootNode.allDescendantsLabels;r.forEach(s=>s.ast.allDescendants.forEach(o=>{if(o instanceof ie){let a=e.resolvePath([`&${o.label?.value}`],i);if(a){let c=e.rootNode.getChild(a);o.linksTo=c,c?.linkedRefLabels.push(o)}else o.value&&this._issues.push(Ht(3,o.firstToken,o.lastToken,o,{templateStrings:[o.value]}))}else o instanceof Gr&&this.linkNodePath(o,e.rootNode)}))}linkNodePath(e,n){let r=n,i=e.pathParts;for(let s=0;s<i.length&&i[s];s++){let o=!1,a=i[s];if(a){let c=s===0&&a.name==="/"?n:r?.getNode(a.name,a.fullAddress,!1);a.linksTo=c,!o&&!c&&(o=!0,this._issues.push(Ht(8,a.firstToken,a.lastToken,a,{templateStrings:[a.toString(),`${e.pathParts.filter(l=>l?.linksTo).map(l=>l?.toString()).join("/")}`]}))),c?.linkedNodeNamePaths.push(a),r=c}else break}}setStaleFsPath(e){this.staleFsPaths.add(e)}async reevaluate(e){this.setStaleFsPath(e);let n=new Set;return this.staleFsPaths.forEach(r=>{let i=this.getFsPathParser(r);i&&n.add(i)}),n.size?(this.sortKeys=new WeakMap,await Promise.all(Array.from(n).map(r=>r.reparse())),this._runtime=this.evaluate(),this._runtime):this._runtime}getSortKey(e){if(e)return this.sortKeys.get(e.firstToken)}async evaluate(){let e=performance.now();await this.stable();let n=new gi(this);this.staleFsPaths.clear(),this._issues=[],this.parser.rootDocument.resetIssues(),this.processRoot(this.parser.rootDocument,n);for(let i=0;i<this.overlayParsers.length;i++)this.overlayParsers[i].rootDocument.resetIssues(),this.processRoot(this.overlayParsers[i].rootDocument,n);let r=await Promise.all(n.rootNode.defaultProperties.map(async i=>{let s=new Kr(i.text,i.fsPath),o=new Fi(i.fsPath,[],void 0,()=>s.tokens);return await o.stable,this.processRoot(o.rootDocument,n),o}));return n.includes=this.parser.includes,n.comments=this.parser.cPreprocessorParser.allAstItems.filter(i=>i instanceof lr),[...this.allParsers,...r].flatMap(i=>i.tokens).forEach((i,s)=>this.sortKeys.set(i,s)),this.linkPropertiesLabelsAndNodePaths(n),this.reportNodeNameAndPropertyClashes(n),console.log(`(ID: ${this.id}) evaluate`,performance.now()-e),n}getSortKeyFile(e,n){let r=this.findTokenBeforePosition(e,n),i=r,s=i?this.sortKeys.get(i):void 0;for(;i&&!s;)i=i.nextToken,s=i?this.sortKeys.get(i):void 0;if(s!==void 0)return s;for(i=r,s=i?this.sortKeys.get(i):void 0;i&&!s;)i=i.prevToken,s=i?this.sortKeys.get(i):void 0;return s}findTokenBeforePosition(e,n){let r=[this.parser,...this.overlayParsers].flatMap(i=>({parser:i,tokens:i.tokens}));for(let[i,s]of r.entries()){if(s.tokens.length===0&&pe(s.parser.fsPath,n)){let c=r[i-1];return i?c.tokens[c.tokens.length-1]:void 0}let o=s.tokens.find((c,l)=>Bc(c,n,e)&&(l===s.tokens.length-1||!c.nextToken||uT(c.nextToken,n,e)));if(o)return o;let a=s.parser.includes.find(c=>c.resolvedPath===n);if(a)return a.lastToken}}reportNodeNameAndPropertyClashes(e){let n=r=>{r.properties.forEach(i=>{r.nodes.filter(o=>o.address===void 0&&o.name===i.ast.propertyName?.name&&o.definitions.at(-1)?.name).forEach(o=>{let a=o.definitions,c=a[a.length-1].name;this._issues.push(Ht(2,c.firstToken,c.lastToken,c,{linkedTo:[i.ast,...i.allReplaced.map(l=>l.ast)]}))})}),r.nodes.forEach(n)};n(e.rootNode)}processRoot(e,n){for(let r=0;r<e.children.length;r++){let i=e.children[r];this.processChild(i,n.rootNode,n)}}processChild(e,n,r){e instanceof Ue?this.processDtcBaseNode(e,n,r):e instanceof je?this.processDtcProperty(e,n,r):e instanceof Gn?this.processDeleteNode(e,n,r):e instanceof yt&&this.processDeleteProperty(e,n,r)}checkNodeUniqueNames(e,n){let r=(o,a)=>o.filter(c=>c.name===a.name&&(c.address===a.fullAddress&&c.address===void 0||Lt(c.address??[],a.fullAddress??[])===0)).map(c=>c.issueAst),i=n.nodes.map(o=>{let a=o.definitions[0];return{name:o.name,address:o.address,issueAst:a.name??a}}),s=[];e.children.forEach(o=>{if(o instanceof He&&o.name){let a=r(s.map(c=>({name:c.name,address:c.fullAddress,issueAst:c})),o.name);a.length&&this._issues.push(Ht(2,o.name.firstToken,o.name.lastToken,o.name,{linkedTo:a})),s.push(o.name)}else if(o instanceof Gn&&o.nodeNameOrRef instanceof xe){let a=o.nodeNameOrRef;r(i,a)&&(s=s.filter(c=>r(s.map(l=>({name:l.name,address:l.fullAddress,issueAst:l})),c).length))}})}getCompileCommands(){if(!(!this.settings.compileCommands||!(0,nl.existsSync)(this.settings.compileCommands)))return JSON.parse((0,nl.readFileSync)(this.settings.compileCommands).toString())}processDtcBaseNode(e,n,r){e instanceof Tt?this.processDtcRootNode(e,r):e instanceof He?this.processDtcChildNode(e,n,r):e instanceof Et&&this.processDtcRefNode(e,r)}processDtcRootNode(e,n){n.rootNode.implementations.push(e),this.checkNodeUniqueNames(e,n.rootNode),e.children.forEach(r=>this.processChild(r,n.rootNode,n))}processDtcChildNode(e,n,r){if(e.name?.name){let i=e.path?r.resolvePath(e.path):void 0,o=(i?r.rootNode.getChild(i):void 0)??new X(this.bindingLoader,e.name.name,e.name.fullAddress,n);o.implementations.push(e),e.labels.forEach(a=>a.lastLinkedTo=o),n=o,this.checkNodeUniqueNames(e,o)}e.children.forEach(i=>this.processChild(i,n,r))}processDtcRefNodeLabelRef(e,n,r){let i,s=e.resolveNodePath??(e.pathName?r.resolvePath([e.pathName]):void 0);return s?(e.resolveNodePath??=[...s],i=r.rootNode.getChild(s),n.linksTo=i,e.labels.forEach(o=>o.lastLinkedTo=i),i?.linkedRefLabels.push(n),i?.implementations.push(e),e.labels.forEach(o=>{r.labelsUsedCache.set(o.label.value,s)}),i?(r.references.push(e),this.checkNodeUniqueNames(e,i)):r.unlinkedRefNodes.push(e)):(this._issues.push(Ht(3,n.firstToken,n.lastToken,n,{templateStrings:[n.label?.value??""]})),r.unlinkedRefNodes.push(e)),i}processDtcRefNodeNodePathRef(e,n,r){let i;n.path&&this.linkNodePath(n.path,r.rootNode);let o=n.path?.pathParts.at(-1)?.linksTo?.path;return o?(e.resolveNodePath??=o,i=r.rootNode.getChild(o),e.labels.forEach(a=>a.lastLinkedTo=i),i?.implementations.push(e),e.labels.forEach(a=>{r.labelsUsedCache.set(a.label.value,o)}),i?(r.references.push(e),this.checkNodeUniqueNames(e,i)):r.unlinkedRefNodes.push(e)):r.unlinkedRefNodes.push(e),i}processDtcRefNode(e,n){let r;e.reference?e.reference instanceof ie?r=this.processDtcRefNodeLabelRef(e,e.reference,n):r=this.processDtcRefNodeNodePathRef(e,e.reference,n):n.unlinkedRefNodes.push(e),e.children.forEach(i=>this.processChild(i,r??new X(this.bindingLoader,""),n))}processDtcProperty(e,n,r){e.propertyName?.name&&n.addProperty(new Xe(e,n)),e.children.forEach(i=>this.processChild(i,n,r))}processDeleteNode(e,n,r){if(e.nodeNameOrRef instanceof xe&&e.nodeNameOrRef.value){if(e.parentNode?.parentNode)if(!n.hasNode(e.nodeNameOrRef.name,e.nodeNameOrRef.fullAddress))this._issues.push(Ht(5,e.nodeNameOrRef.firstToken,e.nodeNameOrRef.lastToken,e.nodeNameOrRef));else{n.deletes.push(e);let i=n.getNode(e.nodeNameOrRef.name,e.nodeNameOrRef.fullAddress);e.nodeNameOrRef.linksTo=i,n.deleteNode(e.nodeNameOrRef.name,e,e.nodeNameOrRef.fullAddress),i?.labels.forEach(s=>{r.labelsUsedCache.delete(s.label.value)})}}else if(e.nodeNameOrRef instanceof ie&&e.nodeNameOrRef.value){let i=r.resolvePath([`&${e.nodeNameOrRef.value}`]),s;i?(s=r.rootNode.getChild(i),n.deletes.push(e),e.nodeNameOrRef.linksTo=s,s?.labels.forEach(o=>{r.labelsUsedCache.delete(o.label.value)}),s?.linkedRefLabels.push(e.nodeNameOrRef),s?.parent?.deleteNode(s.name,e,s.address),e.parentNode instanceof Ue&&!e.parentNode.pathName&&r.globalDeletes.push(e)):(r.unlinkedDeletes.push(e),this._issues.push(Ht(3,e.nodeNameOrRef.firstToken,e.nodeNameOrRef.lastToken,e.nodeNameOrRef,{templateStrings:[e.nodeNameOrRef.value]})))}else if(e.nodeNameOrRef instanceof ot&&e.nodeNameOrRef.path&&!e.nodeNameOrRef.path.pathParts.some(i=>!i)){let i=r.rootNode,s=e.nodeNameOrRef.path.pathParts;for(let c=0;c<s.length&&s[c];c++){let l=s[c];if(l){let u=i?.getNode(l.name,l.fullAddress,!1);l.linksTo=u,u?.linkedNodeNamePaths.push(l),i=u}}let o=e.nodeNameOrRef.path.pathParts.find(c=>c&&!c.linksTo),a=e.nodeNameOrRef.path.pathParts.at(-1)?.linksTo;a||(r.unlinkedDeletes.push(e),o&&this._issues.push(Ht(8,o.firstToken,o.lastToken,o,{templateStrings:[o.toString(),`${e.nodeNameOrRef.path.pathParts.filter(c=>c?.linksTo).map(c=>c?.toString()).join("/")}`]}))),n.deletes.push(e),a?.labels.forEach(c=>{r.labelsUsedCache.delete(c.label.value)}),a?.parent?.deleteNode(a.name,e,a.address),e.parentNode instanceof Ue&&!e.parentNode.pathName&&r.globalDeletes.push(e)}else r.unlinkedDeletes.push(e);e.children.forEach(i=>this.processChild(i,n,r))}processDeleteProperty(e,n,r){e.propertyName?.name&&!n.hasProperty(e.propertyName.name)?this._issues.push(Ht(1,e.propertyName.firstToken,e.propertyName.lastToken,e.propertyName)):e.propertyName?.name&&(n.deletes.push(e),n.deleteProperty(e.propertyName.name,e)),e.children.forEach(i=>this.processChild(i,n,r))}static#e(e,n,r){let i=r.get(n);i||(i=[],r.set(n,i)),i.push(e)}getIssues(e,n=new Map,r=i=>{if(!(i.raw.severity===lo.DiagnosticSeverity.Hint&&i.raw.virtual))return i.raw.severity===lo.DiagnosticSeverity.Error&&!this.isFullContext&&(i.raw.severity=lo.DiagnosticSeverity.Warning),i}){return e.forEach(i=>{let s=r(i);s&&t.#e(s.diagnostic(),s.raw.fsPath,n)}),n}async getSyntaxIssues(e=new Map,n=r=>{if(r.raw.severity===lo.DiagnosticSeverity.Error&&!this.isFullContext&&!io(r.raw,r.raw.fsPath,!1)&&(r.raw.severity=lo.DiagnosticSeverity.Warning),!(r.raw.severity===lo.DiagnosticSeverity.Hint&&r.raw.virtual))return r}){return(await this.getAllStableParsers()).forEach(r=>this.getIssues(r.issues,e,n)),e}async getDiagnostics(){let e=new Map;try{await this.getSyntaxIssues(e);let n=await this.getContextIssues()??[];this.getIssues(n,e);let r=await this.getRuntime();return this.getIssues(r.typesIssues,e),e}catch(n){throw console.error(n),n}}async toFullString(){return`/dts-v1/;
285
285
 
286
286
  ${(await this.getRuntime()).rootNode.toFullString((await this.getAllStableParsers()).at(-1).cPreprocessorParser.macros,this.settings.cwd)}`}async serialize(){let e={};return await this.stable,await this.getDiagnostics(),(await this?.getRuntime())?.rootNode.serialize(e,(await this.getAllStableParsers()).at(-1).cPreprocessorParser.macros),e}};var TD=require("fs"),ka=require("path"),Ct=q(j());function GU(t){if(!t||!(t.ast instanceof Ta))return[];let e=r=>r.flatMap(i=>{try{return(0,TD.readdirSync)(i,{withFileTypes:!0,recursive:!0}).filter(s=>s.name.toLowerCase().endsWith(".dtsi")||s.name.toLowerCase().endsWith(".h")).map(s=>({label:`${(0,ka.join)((0,ka.relative)(i,s.parentPath),s.name)}`,kind:Ct.CompletionItemKind.File}))}catch{return[]}});if(t.ast.relative)return e([(0,ka.dirname)(t.ast.fsPath)]);let n=t.runtime.context.settings.includePaths??[];return e(n)}var cp=(t,e)=>[...t.labels.filter(e),...t.deletedNodes.filter(n=>!e(n.by)).flatMap(n=>cp(n.node,e)),...t.nodes.flatMap(n=>cp(n,e))],LT=(t,e)=>[...t.labels,...t.deletedNodes.filter(n=>!e(n.by)).flatMap(n=>LT(n.node,e)),...t.nodes.flatMap(n=>LT(n,e))];function KU(t,e){if(!t||!(t.item instanceof Xe)||!(t.ast instanceof ie))return[];let n=i=>LT(i,e),r=new Map;return n(t.runtime.rootNode).forEach(i=>r.set(i.label.value,i)),Array.from(r).map(([,i])=>({label:`${i.label.value}`,kind:Ct.CompletionItemKind.Method,documentation:i.lastLinkedTo?.toMarkupContent(t.runtime.context.macros)}))}function YU(t,e){if(!t||t.item!==null||!(t.ast instanceof ie)||!(t.ast.parentNode instanceof Et))return[];let n=r=>cp(r,e).filter(i=>e(i));return[...Array.from(new Set(n(t.runtime.rootNode).map(r=>r.label.value))).map(r=>({label:r,insertText:t.ast.lastToken.nextToken?.value==="{"?r:`${r} {
287
287
  $1
@@ -325,4 +325,4 @@ ${r}`]})]},L6=(t,e)=>hF(t,e.split("/").filter(n=>n)),hF=(t,e)=>{if(e.length===0)
325
325
  `).length-1,o=i.lastIndexOf(`
326
326
  `),a=o===-1?r+1:r-o,c=a+n[0].length;return wn.Range.create(wn.Position.create(s,a),wn.Position.create(s,c))}var hc=require("fs");var V6=(t,e)=>{let n=(0,hc.readFileSync)(t).toString();if(An().needsRenew(t,n))An().renewLexer(t,n),e(t);else return console.log("file changed event has the same text, skipping.",t)},ng=class{constructor(e,n,r){this.file=e;this.cb=n;this.isFileDirty=r}#e=0;watch(){if(this.count++,this.count===1){console.log("create watch for",this.file);let e=this.file,n=this.cb;this.onChange=()=>{if(console.log("onChange - file watcher",e),this.isFileDirty()){console.log("onChange - file is dirty, skipping");return}V6(e,n)},(0,hc.watchFile)(e,this.onChange)}}unwatch(){this.count===1&&(console.log("dispose watch for",this.file),(0,hc.unwatchFile)(this.file,this.onChange),this.onChange=void 0),this.count--}get count(){return this.#e}set count(e){this.#e=e,e<0&&(this.#e=0,console.warn("unwatching an un watched file",this.file))}};var sn=q(require("path")),nk=require("fs");var li=t=>{if(t)return Array.isArray(t)?t:[t]},W6=t=>({...t,deviceOrgBindingsMetaSchema:li(t.deviceOrgBindingsMetaSchema),deviceOrgTreeBindings:li(t.deviceOrgTreeBindings),includePaths:li(t.includePaths),lockRenameEdits:li(t.lockRenameEdits),zephyrBindings:li(t.zephyrBindings),overlays:li(t.overlays)}),LF=t=>({...t,defaultDeviceOrgBindingsMetaSchema:li(t.defaultDeviceOrgBindingsMetaSchema),defaultDeviceOrgTreeBindings:li(t.defaultDeviceOrgTreeBindings),defaultIncludePaths:li(t.defaultIncludePaths),defaultLockRenameEdits:li(t.defaultLockRenameEdits),defaultZephyrBindings:li(t.defaultZephyrBindings),contexts:t.contexts?.map(W6)}),qr=async(t,e=[],n)=>{let r=n?e.map(s=>Se(s.uri)).find(s=>oE(s,n)):void 0;return[...e.at(0)?[{replace:"${workspaceFolder}",fsPath:r??Se(e[0].uri)}]:[],...e.map(s=>({replace:`\${workspaceFolder:${s.name}}`,fsPath:Se(s.uri)}))].forEach(s=>t=t.replaceAll(s.replace,s.fsPath)),t},Us={defaultBindingType:"Zephyr",defaultZephyrBindings:[],defaultIncludePaths:[],defaultDeviceOrgBindingsMetaSchema:[],defaultDeviceOrgTreeBindings:[],contexts:[],defaultLockRenameEdits:[],allowAdhocContexts:!0,autoChangeContext:!0,defaultShowFormattingErrorAsDiagnostics:!0,disableFileWatchers:!1},rk=async(t,e,n)=>{let r=await qr(t.cwd??"${workspaceFolder}",n,t.dtsFile)??e.cwd,i=await Promise.all((t.includePaths??e.defaultIncludePaths).map(p=>qr(p,n,t.dtsFile))),s=await Promise.all((t.zephyrBindings??e.defaultZephyrBindings).map(p=>qr(p,n,t.dtsFile))),o=t.bindingType??e.defaultBindingType,a=await Promise.all((t.deviceOrgTreeBindings??e.defaultDeviceOrgTreeBindings).map(p=>qr(p,n,t.dtsFile))),c=await Promise.all((t.deviceOrgBindingsMetaSchema??e.defaultDeviceOrgBindingsMetaSchema).map(p=>qr(p,n,t.dtsFile))),l=await Promise.all((t.lockRenameEdits??e.defaultLockRenameEdits).map(p=>qr(p,n,t.dtsFile)));r&&o==="Zephyr"&&(!s||s.length===0)&&(s=["./zephyr/dts/bindings"]);let u=t.dtsFile,d=t.overlays??[],f=t.compileCommands;return r&&(s=s.map(p=>(0,sn.resolve)(r,p)).filter(p=>(0,nk.existsSync)(p)),a=a?.map(p=>(0,sn.resolve)(r,p)),c=c.map(p=>(0,sn.resolve)(r,p)),i=i.map(p=>(0,sn.resolve)(r,p)),u=(0,sn.resolve)(r,u),d=d.map(p=>(0,sn.resolve)(r,p)),l=l.map(p=>(0,sn.resolve)(r,p)),f=f?(0,sn.resolve)(r,f):void 0),{ctxName:t.ctxName??(0,sn.basename)(u),cwd:r?it(r):void 0,includePaths:i.map(it),zephyrBindings:s.map(it),bindingType:o,deviceOrgTreeBindings:a.map(it),deviceOrgBindingsMetaSchema:c.map(it),dtsFile:it(u),overlays:d.map(it),lockRenameEdits:l.map(it),compileCommands:f?it(f):void 0,showFormattingErrorAsDiagnostics:t.showFormattingErrorAsDiagnostics??e.defaultShowFormattingErrorAsDiagnostics,disableFileWatchers:t.disableFileWatchers??e.disableFileWatchers}},ju=async(t,e)=>{let n=t.cwd?await qr(t.cwd,e):void 0,r=t.defaultBindingType,i=t.defaultDeviceOrgBindingsMetaSchema=await Promise.all((t.defaultDeviceOrgBindingsMetaSchema??[]).map(d=>qr(d,e))),s=t.defaultDeviceOrgTreeBindings=await Promise.all((t.defaultDeviceOrgTreeBindings??[]).map(d=>qr(d,e))),o=t.defaultIncludePaths=await Promise.all((t.defaultIncludePaths??[]).map(d=>qr(d,e))),a=t.defaultZephyrBindings=await Promise.all((t.defaultZephyrBindings??[]).map(d=>qr(d,e))),c=t.defaultLockRenameEdits=await Promise.all((t.defaultLockRenameEdits??[]).map(d=>qr(d,e)));n&&(o=t.defaultIncludePaths=(t.defaultIncludePaths??[]).map(d=>(0,sn.resolve)(n,d)),r==="Zephyr"&&!t.defaultZephyrBindings&&(a=["./zephyr/dts/bindings"]),a=a.map(d=>(0,sn.resolve)(n,d)),i=i.map(d=>(0,sn.resolve)(n,d)),s=(t.defaultDeviceOrgTreeBindings??[]).map(d=>(0,sn.resolve)(n,d)),c=c.map(d=>(0,sn.resolve)(n,d)));let l={cwd:n,defaultDeviceOrgBindingsMetaSchema:i,defaultDeviceOrgTreeBindings:s,defaultIncludePaths:o,defaultZephyrBindings:a,defaultLockRenameEdits:c,defaultBindingType:r,autoChangeContext:t.autoChangeContext??Us.autoChangeContext,allowAdhocContexts:t.allowAdhocContexts??Us.allowAdhocContexts,defaultShowFormattingErrorAsDiagnostics:t.defaultShowFormattingErrorAsDiagnostics??Us.defaultShowFormattingErrorAsDiagnostics,disableFileWatchers:t.disableFileWatchers??!1},u=(await Promise.all(t.contexts?.map(d=>rk(d,l,e))??[])).filter(d=>[d.dtsFile,...d.overlays].every(f=>(0,nk.existsSync)(f)&&sn.default.isAbsolute(f)));return{...l,contexts:u}};var qF=t=>`DT_PROP(${ik(t.parent)}, ${t.name.replaceAll("-","_")}))`,$F=t=>t.parent.labels.map(e=>`DT_PROP(DT_NODELABEL(${e.label.toString()}), ${t.name.replaceAll("-","_")})`);var ik=t=>`DT_PATH(${t.path.slice(1).map(e=>e.replace("@","_").replaceAll("-","_")).join(",")})`,FF=t=>t.labels.map(e=>`DT_NODELABEL(${e.label.toString()})`),BF=t=>{let e=[];return gi.getNodeFromPath(["aliases"],t.root)?.properties.filter(i=>{if(i.ast.quickValues?.at(0)===t.pathString)return!0;let s=i.ast.values?.values.at(0)?.value;if(s instanceof ie&&s.linksTo===t||s instanceof ot&&s.path?.pathParts.at(-1)?.linksTo===t)return!0})?.forEach(i=>e.push(`DT_ALIAS(${i.name.replaceAll("-","_")})`)),e};function z6(t,e){if(!t||!(t.item instanceof Xe)||!(t.ast instanceof Ye))return[];let n=[];return e.settings.bindingType==="Zephyr"&&(n.push({type:"dt_zephyr_macro_prop_node_path",data:qF(t.item)}),$F(t.item).forEach(r=>{n.push({type:"dt_zephyr_macro_prop_node_label",data:r})})),n}function G6(t,e){if(!t||t.item===null)return[];let n;if(t.item instanceof X?n=t.item:t.ast.parentNode instanceof ie&&t.ast.parentNode.linksTo?n=t.ast.parentNode.linksTo:t.ast instanceof xe&&t.ast.linksTo&&(n=t.ast.linksTo),!n)return[];let r=[{type:"path",data:n.pathString}];return e.settings.bindingType==="Zephyr"&&(FF(n).forEach(i=>{r.push({type:"dt_zephyr_macro_node_label",data:i})}),r.push({type:"dt_zephyr_macro_node_path",data:ik(n)}),BF(n).forEach(i=>{r.push({type:"dt_zephyr_macro_prop_node_alias",data:i})})),r}async function jF(t,e){return e?Nt(t,e,n=>[...G6(n,e),...z6(n,e)]):[]}var UF=q(j());function K6(t){return!t||!(t.item instanceof Xe)?void 0:t.item.parent.nodeType?.getSignatureHelp?.(t.item,t.ast,t.beforeAst,t.afterAst)}async function Y6(t){let e=Hc(t?.ast);if(!e||!e.params.length||!t?.ast||t.ast===e.functionName)return;let r=(await t.runtime.context.getAllStableParsers()).at(-1).cPreprocessorParser.macros.get(e.functionName.name)?.macro.identifier;if(!r||!(r instanceof mi))return;let i=r.params.map(o=>({label:o instanceof pt?o.name:"..."})),s=e.params.find(o=>o&&(t.ast===o||o.isAncestorOf(t.ast)));return s??=t.afterAst?e.params.find(o=>o&&(t.afterAst===o||o.isAncestorOf(t.afterAst))):void 0,s??=t.beforeAst?e.params.find(o=>o&&(t.beforeAst===o||o.isAncestorOf(t.beforeAst))):void 0,{signatures:[UF.SignatureInformation.create(`${e.functionName.name}(${i.map(o=>o.label).join(", ")})`,void 0,...i.flat())],activeSignature:0,activeParameter:s?e.params.indexOf(s):void 0}}async function HF(t,e){if(e)return(await Nt(t,e,async n=>[await Y6(n)||K6(n)])).at(0)}var VF=require("timers"),WF=require("events");var sk=class extends WF.EventEmitter{constructor(e=3e3,n=1e3){super(),this.thresholdBytes=e*1024*1024,this.interval=(0,VF.setInterval)(()=>{let r=process.memoryUsage().heapUsed;r>this.thresholdBytes&&this.emit("thresholdExceeded",{usedMb:(r/1024/1024).toFixed(2),thresholdMb:e})},n)}stop(){clearInterval(this.interval)}},X6=new sk(3e3),zF=()=>{X6.on("thresholdExceeded",({usedMb:t,thresholdMb:e})=>{console.warn(`[HeapMonitor] Heap usage exceeded ${e}MB: ${t}MB used`),fD(),dD()})};var GF=t=>`0x${t.map((e,n)=>e.toString(16).padStart(n?8:0,"0")).join("")}`;function ok(t,e){let n=e.nodePath,r=e.labels.at(0),i=e.nodePath.split("/").pop()??e.nodePath,s=r?`${r} (${i})`:i,o=t.children.filter(c=>{let l=br(e.start,e.size),u=br(c.start,c.size),d=Lt(e.start,c.start)>=0,f=Lt(l,u)<=0,p=Lt(e.start,c.start)===0&&Lt(e.size,c.size)===0;return d&&f&&!p});if(o.length>0){let c=o.find(l=>n.startsWith(`${l.name}/`)||n===l.name);if(c){ok(c,e);return}for(let l of o)ok(l,e);return}let a=t.children.find(c=>c.name===s);a?(a.start=aE(a.start,e.start),a.size=cE(a.size,mT(br(e.start,e.size),a.start))):(a={name:s,start:e.start,size:e.size,children:[]},t.children.push(a))}function J6(t){let e={};for(let n of t){let r={name:n.name,children:[]};for(let i of n.partitions)ok(r,i);e[n.name]=r}return e}function KF(t,e="",n=!0){let r={};for(let d of t.children){let f=`${d.start}-${d.size}`;r[f]||(r[f]=[]),r[f].push(d)}let i="",s=e?n?"\u2514\u2500 ":"\u251C\u2500 ":"",o=[];"start"in t&&t.start&&o.push(`start: ${GF(t.start)}`),"size"in t&&t.size&&o.push(`size: ${GF(t.size)}`);let a=o.length>0?` [${o.join(", ")}]`:"",c=t.name;i+=`${e}${s}${c} ${a}
327
327
  `;let l=e+(n?" ":"\u2502 "),u=Object.keys(r);return u.forEach((d,f)=>{let p=r[d],m=Array.from(new Set(p.map(v=>v.name))).join(", "),h={};p.forEach(v=>{v.children.forEach(b=>{let P=`${b.start}-${b.size}-${b.name}`;h[P]=b})});let y=Object.values(h),_={name:m,start:p[0].start,size:p[0].size,children:y};i+=KF(_,l,f===u.length-1)}),i}function YF(t){return J6(t)}function XF(t){return Object.values(t).map(e=>KF(e)).join(`
328
- `)}var Ee=[],le,Hs,rg=new WeakMap,Uu=new Map;zF();var sg=new Map,QF=t=>{t.settings.disableFileWatchers||t.getContextFiles().forEach(e=>{Uu.has(e)||Uu.set(e,new ng(e,fk,()=>{let n=Ku(e),r=sg.get(e);return!n||r===void 0?!1:r!==n.version})),Uu.get(e)?.watch()})},uk=async t=>{let e=Ee.indexOf(t);if(e===-1)return;Vu(t,void 0,!0),rg.delete(t),console.log(`(ID: ${t.id}) cleaning Context for [${t.ctxNames.join(",")}]`);let n=await Ws(t);if(Q.sendNotification("devicetree/contextDeleted",{ctxNames:t.ctxNames.map(r=>r.toString()),id:t.id,...await t.getFileTree(),settings:t.settings,active:le===t,type:n.type}),Ee.splice(e,1),await mk(),t===le&&(le=void 0,Ee.length)){let r=Hs?vn(Ee,{fsPath:Hs}):void 0;r??=Ee[0],console.log("Active context was deleted. Forcing active to",r.id),await hn({id:r.id},!0)}t.settings.disableFileWatchers||t.getContextFiles().map(r=>{Uu.get(r)?.unwatch()}),setTimeout(async()=>{await Ce();let r=new Set(Ee.flatMap(i=>i.getContextFiles()));t.getContextFiles().map(i=>{r.has(i)||An().reset(i)})},2e3),t.bindingLoader?.dispose()},Q6=t=>{let e=rg.get(t);if(!e?.abort.signal.aborted)return Promise.all([e?.promise,t.getRuntime()])},Ce=async()=>{await Promise.all(Ee.map(Q6))},dk=async(t,e)=>(await ZF(e)).indexOf(t)!==-1,ZF=async t=>{let e=await eB(t);return Ee.filter(n=>!e.some(r=>r===n))},eB=async t=>{let e=await lk(t);return Ee.filter(n=>e.contexts.find(r=>qi(r)===n.id))},Z6=async t=>{let e=await sQ(t);return Ee.filter(n=>e.contexts.find(r=>qi(r)===n.id))},eQ=async(t,e)=>(await Z6(e)).indexOf(t)!==-1,tQ=async(t,e)=>{if(t===e)return!0;let n=(await t.getAllStableParsers()).flatMap(i=>i.cPreprocessorParser.dtsIncludes).filter(i=>i.resolvedPath),r=(await e.getAllStableParsers()).flatMap(i=>i.cPreprocessorParser.dtsIncludes).filter(i=>i.resolvedPath);return r.some(i=>pe(i.resolvedPath,t.parser.fsPath))&&n.length?n.every(i=>r.some(s=>s.resolvedPath===i.resolvedPath&&s.firstToken.pos.col===i.firstToken.pos.col&&s.firstToken.pos.len===i.firstToken.pos.len&&s.firstToken.pos.line===i.firstToken.pos.line&&s.lastToken.pos.col===i.lastToken.pos.col&&s.lastToken.pos.len===i.lastToken.pos.len&&s.lastToken.pos.line===i.lastToken.pos.line)):e.getContextFiles().some(i=>pe(i,t.parser.fsPath))},nQ=async t=>{if(!await dk(t))return;let e=await ZF(),n=await eB(),r=await Lf(e);if(Ee.indexOf(t)===-1)return;let i=await Promise.all(r.flatMap(a=>[...n,...e.filter(c=>c!==a.context)].map(async c=>({context:a.context,same:await tQ(a.context,c)})))),s=t.getContextFiles(),o=r.filter(a=>i.some(c=>c.context===a.context&&c.same)||a.context!==t&&pe(a.context.parser.fsPath,t.parser.fsPath)&&s.some(c=>c&&a.files.indexOf(c)!==-1)).map(a=>a.context);o.length&&await Promise.all(o.map(uk))},Q=(0,Be.createConnection)(Be.ProposedFeatures.all),on=new Be.TextDocuments(Vn),tB=!1,ig=!1,nB=!1,rB=!1,iB=!1,ak;Q.onInitialize(async t=>{ak=t.workspaceFolders??[],Q.console.log(`[Server(${process.pid}) ${ak?.at(0)?.uri} Version 0.8.2 ] Started and initialize received`);let e=t.capabilities;tB=!!(e.workspace&&e.workspace.configuration),ig=!!(e.workspace&&e.workspace.workspaceFolders),nB=!!e.workspace?.diagnostics?.refreshSupport,rB=!!e.workspace?.semanticTokens?.refreshSupport,iB=!!e.workspace?.foldingRange?.refreshSupport;let n={capabilities:{typeDefinitionProvider:!0,workspaceSymbolProvider:!0,textDocumentSync:Be.TextDocumentSyncKind.Incremental,renameProvider:{prepareProvider:!0},completionProvider:{resolveProvider:!0,triggerCharacters:["&","="," ",'"',"(",","]},codeActionProvider:{codeActionKinds:[Be.CodeActionKind.QuickFix,Be.CodeActionKind.SourceFixAll]},documentSymbolProvider:!0,semanticTokensProvider:{legend:{tokenTypes:Df,tokenModifiers:Af},full:!0},documentLinkProvider:{resolveProvider:!1},foldingRangeProvider:!0,definitionProvider:!0,declarationProvider:!0,referencesProvider:!0,documentFormattingProvider:!0,documentRangeFormattingProvider:!0,hoverProvider:!0,signatureHelpProvider:{triggerCharacters:["<","("],retriggerCharacters:[" ",","]}}};return ig&&(n.capabilities.workspace={workspaceFolders:{changeNotifications:!0,supported:!0}}),await cB(t.initializationOptions),n});var ck,rQ={tabSize:8,insertSpaces:!1,trimTrailingWhitespace:!0,insertFinalNewline:!0,wordWrapColumn:100};Q.onInitialized(async()=>{if(tB&&(Q.client.register(Be.DidChangeConfigurationNotification.type,{}),!ck)){let t=await Q.workspace.getConfiguration("editor").catch(()=>{}),e=await Q.workspace.getConfiguration("[devicetree]").catch(()=>{}),n={tabSize:e?.["editor.tabSize"],insertSpaces:e?.["editor.insertSpaces"],trimFinalNewlines:e?.["editor.trimFinalNewlines"],trimTrailingWhitespace:e?.["editor.trimTrailingWhitespace"],insertFinalNewline:e?.["editor.insertFinalNewline"],wordWrapColumn:e?.["editor.wordWrapColumn"]};(t||n)&&(ck={...t,...n})}ig&&Q.workspace.onDidChangeWorkspaceFolders(async t=>{Q.console.log("Workspace folder change event received"),await Gu()})});Q.onRequest("workspace/workspaceFolders",async()=>ak??null);var iQ=async t=>{let e=sB();return e={...Us,...e},ju(e,t??await zu())},lk=async t=>{let e=aQ();return e={...Us,...e},ju(e,t??await zu())},sQ=async t=>{let e=cQ();return e={...Us,...e},ju(e,t??await zu())},Wu=async t=>{let e=oQ();return e={...Us,...e},ju(e,t??await zu())},zu=async()=>ig?await Q.workspace.getWorkspaceFolders()??[]:[],JF=async t=>{let e=vn(Ee,{id:qi(t)});if(e)return e.ctxNames.includes(t.ctxName)||console.log(`(ID: ${e.id}) Adding name ${t.ctxName} for [${e.ctxNames.join(",")}]`),e.addCtxName(t.ctxName),e;let n=qi(t);console.log(`(ID: ${n}) New context [${t.ctxName}]`),console.log(`(ID: ${n}) Settings: ${JSON.stringify(t,void 0," ")}`);let r=(0,gc.join)((0,gc.dirname)(t.dtsFile),"dts","bindings"),i=new ap(t,ck??rQ,t.bindingType?CF({zephyrBindings:t.zephyrBindings?[r,...t.zephyrBindings]:[r],deviceOrgBindingsMetaSchema:t.deviceOrgBindingsMetaSchema??[],deviceOrgTreeBindings:t.deviceOrgTreeBindings??[]},t.bindingType):void 0);Ee.push(i);let s=performance.now();await i.stable(),console.log(`(ID: ${n}) New context took ${performance.now()-s}ms to start [${t.ctxName}]`),QF(i);let o=await Ws(i);return Q.sendNotification("devicetree/contextCreated",{ctxNames:i.ctxNames.map(a=>a.toString()),id:i.id,...await i.getFileTree(),settings:i.settings,active:i===le,type:o.type}),await nQ(i),await mk(),i},Gu=async()=>{let t=await lk(),e=await Wu();e.allowAdhocContexts||(e=await lk());let n=e.contexts.map(qi),r=Ee.filter(i=>!n.includes(i.id));await Promise.all(r.map(uk)),await t.contexts?.reduce((i,s)=>i.then(async()=>{await JF(s)}),Promise.resolve()),e.allowAdhocContexts&&await(await iQ()).contexts?.reduce((s,o)=>s.then(async()=>{vn(Ee,{fsPath:o.dtsFile})||await JF(o)}),Promise.resolve()),setTimeout(async()=>{Hs?await hn({fsPath:Hs}):!le&&Ee.length&&(console.log(`No active context using first context (ID: ${Ee[0].id}) [${Ee[0].ctxNames.join(",")}]`),await hn({id:Ee[0].id}))})},$r,Vs,Hu=new Map,mc=new Map,oQ=()=>!Vs&&!$r?void 0:{...Vs,...$r,contexts:[...$r?.contexts??[],...Array.from(mc.values()),...Array.from(Hu.values())]},sB=()=>!Vs&&!$r?void 0:{...Vs,...$r,contexts:[...Array.from(Hu.values())]},aQ=()=>!Vs&&!$r?void 0:{...Vs,...$r,contexts:[...$r?.contexts??[],...Array.from(mc.values())]},cQ=()=>!Vs&&!$r?void 0:{...$r,contexts:[...$r?.contexts??[]]};function lQ(t){let e={...t};for(let n in e)e[n]===null&&delete e[n];return e}var oB=async()=>{let t=await Wu();console.log("Resolved settings",JSON.stringify(t,void 0," ")),Q.sendNotification("devicetree/settingsChanged",t),await Gu(),Ce().then(()=>{nB&&Q.languages.diagnostics.refresh()})},uQ=async()=>{let t=le?.getContextFiles();await Promise.all(Array.from(on.keys()).filter(zt).map(async e=>{t?.some(n=>pe(n,Se(e)))||await Q.sendDiagnostics({uri:e,version:on.get(e)?.version,diagnostics:[{severity:Be.DiagnosticSeverity.Information,range:Be.Range.create(Be.Position.create(0,0),Be.Position.create(0,0)),message:"File not in active context",source:"devicetree"}]})}))},fk=async t=>{let e=pT(Ee,t);if(e.length)e.sort((n,r)=>n===le?-1:r===le?1:0).forEach(n=>{rg.get(n)?.abort.abort(),le===n&&Q.sendNotification("devicetree/activeContextBusyNotification",n.id),Q.sendNotification("devicetree/contextBusyNotification",n.id);let r=new AbortController,i=new Promise(s=>{setTimeout(async()=>{if(n.setStaleFsPath(t),r.signal.aborted){console.log("Abort parsing due to new request"),s();return}let o=performance.now(),a=le===n,c=a?aB(n):[],l=n.getContextFiles();if(await n.reevaluate(t),QF(n),l.forEach(p=>Uu.get(p)?.unwatch()),a&&gk(n)?.length&&(pk(n).then(p=>{let m=p.items.map(h=>({uri:h.uri,version:h.version??void 0,diagnostics:h.items}));Vu(n,c.filter(h=>m.every(y=>y.uri!==h.uri))),m.forEach(h=>{Q.sendDiagnostics(h)}),Yu.set(n,!0)}),Hs)){let p=n.getFsPathParser(Hs);p&&setTimeout(()=>{p.latestSemanticTokensBuilt||Q.languages.semanticTokens.refresh()},50)}let[u,d]=await Promise.all([Ws(n),n.getFileTree()]),f={ctxNames:n.ctxNames.map(p=>p.toString()),id:n.id,...d,settings:n.settings,active:a,type:u.type};le===n&&Q.sendNotification("devicetree/activeContextStableNotification",f),Q.sendNotification("devicetree/contextStableNotification",f),s(),console.log("reevaluate",performance.now()-o)})});rg.set(n,{abort:r,promise:i})});else{if((await Wu()).allowAdhocContexts===!1)return;await Gu(),await hn({fsPath:t})}},dQ=t=>on.keys().find(e=>pe(Se(e),t)),Ku=t=>{let e=dQ(t);if(e)return on.get(e)},aB=t=>t.getContextFiles().map(e=>({uri:ue(e),version:Ku(e)?.version,diagnostics:[]})),Yu=new WeakMap,Vu=async(t,e=aB(t),n=!1)=>{if(!n&&t!==le)return;let r=performance.now();await Promise.all(e.filter(i=>t===le||!le?.getContextFiles().some(s=>pe(Se(i.uri),s))).map(i=>Q.sendDiagnostics({uri:i.uri,version:on.get(i.uri)?.version,diagnostics:[]}))),Yu.delete(t),console.log(`(ID: ${t.id})`,"clear workspace diagnostics",`[${t.ctxNames.join(",")}]`,performance.now()-r)},pk=async t=>{await t.stable();let e=performance.now(),n=await t.getDiagnostics(),r=await Promise.all(t.getContextFiles().map(async i=>{let s=Ku(i),o=[];return s&&t.settings.showFormattingErrorAsDiagnostics&&o.push(...(await ho({textDocument:s,options:t.formattingOptions},s.getText(),"File Diagnostics").catch(()=>[])).map(a=>a.diagnostic())),{uri:ue(i),kind:Be.DocumentDiagnosticReportKind.Full,items:[...n.get(i)??[],...o],version:s?.version??null}}));return console.log(`(ID: ${t.id})`,"workspace diagnostics",`[${t.ctxNames.join(",")}]`,performance.now()-e),{items:[...r]}},hk=async t=>{let{items:e}=await pk(t);e.map(n=>({uri:n.uri,version:n.version??void 0,diagnostics:n.items})).forEach(async n=>{Q.sendDiagnostics(n)}),Yu.set(t,!0)},mk=async()=>{let t=await Promise.all(Ee.map(e=>Ws(e)));console.log("======== Context List ========"),t.forEach(e=>{console.log(`(ID: ${e.ctx.id}) [${e.ctx.ctxNames.join(",")}]`,`[${e.type}]`,le===e.ctx?" [ACTIVE]":"")}),console.log("==============================")},Ws=async(t,e)=>{let n=await dk(t,e),r=!n&&await eQ(t,e);return{ctx:t,type:n?"Ad Hoc":r?"User":"3rd Party"}},hn=async(t,e=!1)=>{if("fsPath"in t){if(!zt(t.fsPath))return!1;Hs=t.fsPath,console.log("Active File Uri",Hs)}let n=await Wu();if(le&&!e&&!n.autoChangeContext||(await Ce(),!e&&le?.getContextFiles().find(o=>"fsPath"in t&&pe(o,t.fsPath))))return!1;let r=le,i=vn(Ee,t),s=r!==i;return s&&(r&&Vu(r),le=i,i?(Ws(i).then(async o=>{let a=await i.getFileTree();!i||i!==le&&!Ee.includes(i)||Q.sendNotification("devicetree/newActiveContext",{ctxNames:i.ctxNames.map(c=>c.toString()),id:i.id,...a,settings:i.settings,active:le===i,type:o.type})}),gk(i)?.length&&hk(i),await mk()):Q.sendNotification("devicetree/newActiveContext",void 0)),iB&&Q.languages.foldingRange.refresh(),rB&&Q.languages.semanticTokens.refresh(),s},zt=t=>[".dts",".dtsi",".dtso",".overlay"].some(e=>t.endsWith(e));on.listen(Q);var gk=t=>t?.getContextFiles()?.filter(e=>Ku(e));on.onDidSave(t=>{sg.set(Se(t.document.uri),t.document.version)});on.onDidClose(async t=>{let e=Se(t.document.uri);if(!zt(e))return;sg.delete(e);let n=pT(Ee,e);if(n.length===0){Hu.delete(e),Q.sendDiagnostics({uri:t.document.uri,version:on.get(t.document.uri)?.version,diagnostics:[]});return}await Promise.all(n.map(async r=>{!!gk(r)?.filter(s=>s!==e).length?le?.getContextFiles().some(s=>pe(s,e))?le?.getContextFiles().some(s=>pe(s,e))&&(await Vu(le),await hk(le)):Q.sendDiagnostics({uri:t.document.uri,version:on.get(t.document.uri)?.version,diagnostics:[]}):await dk(r)?(await uk(r),Hu.delete(r.settings.dtsFile)):Vu(r)}))});on.onDidOpen(async t=>{let e=Se(t.document.uri);if(!zt(e))return;sg.set(e,t.document.version),await Ce(),uQ();let n=vn(Ee,{fsPath:e});if(console.log("onDidOpen",n?.id,e),n)n!==le?await hn({id:n.id}):n===le&&(!Yu.get(n)||n.getContextFiles().some(r=>!pe(r,e)))&&await hk(n);else{let r={ctxName:(0,gc.basename)(e),dtsFile:e};Hu.set(e,r),await fk(e)}});on.onDidChangeContent(async t=>{let e=Se(t.document.uri);if(!zt(e))return;let n=t.document.getText(),r=An();r.needsRenew(e,n)&&(console.log("Content changed",e),r.renewLexer(e,n),await fk(e))});var cB=async t=>{t?.settings?.devicetree&&($r=LF(lQ(t.settings.devicetree)),console.log("Configuration changed",JSON.stringify(t,void 0," ")),await oB())};Q.onDidChangeConfiguration(async t=>{await cB(t)});Q.listen();Q.languages.diagnostics.onWorkspace(async()=>{await Ce();let t=le;return t?pk(t).finally(()=>{Yu.set(t,!0)}):{items:[]}});Q.onDidChangeWatchedFiles(t=>{Q.console.log("We received a file change event")});Q.onCompletion(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return xA(t,le,on.get(t.textDocument.uri));if(!zt(e))return[];await Ce(),hn({fsPath:e});let n=$n(e);return n?[...await vD(t,n),...await c0(t,n)]:[]});Q.onCompletionResolve(t=>t);var $n=t=>{let e=sB();return vn(Ee,{fsPath:t},le,e?.preferredContext)};Q.onDocumentSymbol(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return[];await Ce();let n=$n(e);return n?n.getFsPathParser(e)?.getDocumentSymbols(e):[]});Q.onWorkspaceSymbol(async()=>{await Ce();let t=le;return t?(await t.getAllStableParsers()).flatMap(e=>e.getWorkspaceSymbols()):[]});Q.languages.semanticTokens.on(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return{data:[]};try{await Ce();let n=$n(e),r=new Be.SemanticTokensBuilder,i=n?.isInContext(e);return!n||!i?{data:[]}:((await n.getAllStableParsers()).forEach(s=>s.buildSemanticTokens(r,e)),r.build())}catch(n){throw console.log(n),n}});Q.onDocumentLinks(async t=>{await Ce();let e=Se(t.textDocument.uri);return zt(e)?$n(e)?.getDocumentLinks(e):e.endsWith(".yaml")&&le?le.bindingLoader?.getDocumentLinks?.(on.get(t.textDocument.uri))??[]:[]});Q.onPrepareRename(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return jA(t,n)});Q.onRenameRequest(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return BA(t,n)});Q.onReferences(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return LA(t,n)});Q.onDefinition(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return VA(t,le,on.get(t.textDocument.uri));if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e),r=(await n?.getDocumentLinks(e,t.position))?.filter(i=>i.target).map(i=>Be.Location.create(i.target,i.range))??[];return r.length?r:HA(t,n)});Q.onDeclaration(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return KA(t,le,on.get(t.textDocument.uri));if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return GA(t,n)});Q.onCodeAction(async t=>{let e=Se(t.textDocument.uri);if(zt(e))return XA(t)});var lB=async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);if(!n)return[];if((await n.getSyntaxIssues(void 0,l=>io(l.raw,e,!1)?l:void 0)).get(e)?.length)return[];let i=on.get(t.textDocument.uri)??An().getDocument(e),s=i.getText(),o=await ho(t,s,"New Text").catch(()=>s);if(o===s)return[];let a=i.lineCount-1,c=i.getText({start:{line:a,character:0},end:{line:a+1,character:0}}).length;return[Be.TextEdit.replace(Be.Range.create(Be.Position.create(0,0),Be.Position.create(i.lineCount,c)),o)]};Q.onDocumentRangeFormatting(lB);Q.onDocumentFormatting(lB);Q.onHover(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return AO(t,le,on.get(t.textDocument.uri));if(!zt(e))return;await Ce();let n=$n(e);return(await l0(t,n)).at(0)});Q.onFoldingRanges(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce();let n=$n(e),r=n?.isInContext(e);if(!n||!r)return[];let i=(await n.getAllStableParsers()).find(s=>s.getFiles().some(o=>o===e));return i?AF(e,i):[]});Q.onTypeDefinition(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return xF(t,n)});Q.onSignatureHelp(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return HF(t,n)});Q.onRequest("devicetree/getContexts",async()=>(await Ce(),Promise.all(Ee.map(async t=>{let e=await Ws(t);return{ctxNames:t.ctxNames.map(n=>n.toString()),id:t.id,...await t.getFileTree(),settings:t.settings,active:le===t,type:e.type}}))));Q.onRequest("devicetree/setActive",async t=>(await Ce(),console.log("devicetree/setActive",t),await hn(t,!0)));Q.onRequest("devicetree/getActiveContext",async()=>{if(await Ce(),console.log("devicetree/getActiveContext"),!le)return;let t=await Ws(le);return le?{ctxNames:le.ctxNames.map(e=>e.toString()),id:le.id,...await le.getFileTree(),settings:le.settings,active:!0,type:t.type}:void 0});Q.onRequest("devicetree/setDefaultSettings",async t=>{await Ce(),Vs=t,console.log("Integration Settings",t),await oB()});Q.onRequest("devicetree/requestContext",async t=>{await Ce();let e=await zu(),n=await Wu(e),r=await rk(t,n,e);console.log("devicetree/requestContext",r);let i=qi(r),s=Array.from(mc).find(([,c])=>c.ctxName===t.ctxName);if(s){let c=s[0].split(":",1)[0];vn(Ee,{name:t.ctxName.toString()})?.removeCtxName(t.ctxName),console.log(`Removing integration context with ID ${c} and name ${t.ctxName}`),mc.delete(s[0])}mc.set(`${i}:${t.ctxName}`,t),await Gu();let o=Ee.find(c=>c.id===i);if(!o)throw new Error("Failed to create context");let a=await Ws(o,e);return{ctxNames:o.ctxNames.map(c=>c.toString()),id:i,...await o.getFileTree(),settings:o.settings,active:!0,type:a.type}});Q.onRequest("devicetree/removeContext",async({id:t,name:e})=>{await Ce(),mc.delete(`${t}:${e}`);let n=vn(Ee,{id:t});if(n){if(n.removeCtxName(e),n.ctxNames.length){console.log("Context will not be deleted as it is still in use by others");return}await Gu()}});Q.onRequest("devicetree/compiledDtsOutput",async t=>{if(await Ce(),!t)return;let e=vn(Ee,{id:t});if(!e)return;let n=await e.toFullString();return ho({textDocument:{uri:ue(e.settings.dtsFile)},options:e.formattingOptions},n,"New Text").catch(()=>n)});Q.onRequest("devicetree/serializedContext",async t=>{if(await Ce(),!t)return;let e=vn(Ee,{id:t}),n=performance.now();return e?.serialize().finally(()=>{console.info("serializedContext",performance.now()-n)})});Q.onRequest("devicetree/activePath",async t=>{if(await Ce(),!le)return;let e=n=>{if(n?.item)return n.item instanceof X?{nodePath:n.item.pathString}:{nodePath:n.item.parent.pathString,propertyName:n.item.name}};return(await Nt(t,le,n=>[e(n)])).at(0)});Q.onRequest("devicetree/customActions",async t=>(await Ce(),jF(t,le)));Q.onRequest("devicetree/activeFsPath",async t=>{await Ce(),hn({fsPath:t})});Q.onRequest("devicetree/formattingText",async t=>{let e=Se(t.textDocument.uri),n=Ku(e)??An().getDocument(e,t.text),r=await ho(t,n.getText(),"Both");return{text:r.text,diagnostics:r.diagnostic.map(i=>i.diagnostic())}});Q.onRequest("devicetree/formatTextEdits",async t=>{await Ce();let e=An().getDocument(Se(t.textDocument.uri),t.text),n=e.positionAt(e.getText().length),r=Be.TextEdit.replace(Be.Range.create(Be.Position.create(0,0),n),""),i=ds(e,t.edits),o=await ho({...t,ranges:void 0},i,"New Text").catch(()=>i);return r.newText=o,r});Q.onRequest("devicetree/diagnosticIssues",async({uri:t,full:e})=>{await Ce();let n=Se(t);hn({fsPath:n});let r=$n(n);if(!r)return[];let i=e?(await r.getDiagnostics()).get(n):(await r.getSyntaxIssues(void 0,s=>io(s.raw,n,!!e)?s:void 0)).get(n);if(i?.length)return i});Q.onRequest("devicetree/evalMacros",async({macros:t,ctxId:e})=>{await Ce();let n=vn(Ee,{id:e});return n?t.map(r=>{let i=$c(r,n.macros),s=De(i);return{macro:r,evaluated:typeof s=="number"?s:i}}):[]});Q.onRequest("devicetree/memoryViews",async({ctxId:t})=>{let e=vn(Ee,{id:t});if(!e)return;await e?.stable();let n=await e.getRuntime(),r=n.rootNode.getMemoryViews(n.context.macros).sort((o,a)=>Lt(o.start,a.start)),i=new Map;r.forEach(o=>{let a=i.get(o.name),c={nodePath:o.nodePath,labels:o.labels,start:o.start,size:o.size};a?a.partitions.push(c):i.set(o.name,{name:o.name,partitions:[c]})});let s=YF(Array.from(i.values()));return{trees:s,treeStr:XF(s)}});Q.onRequest("devicetree/zephyrTypeBindings",async t=>(await Ce(),t?vn(Ee,{id:t})?.bindingLoader?.getZephyrContextBinding():void 0));Q.onRequest("devicetree/contextMacroNames",async t=>{if(await Ce(),!t)return;let e=vn(Ee,{id:t});return Array.from(e?.macros.keys()??[])});Q.onRequest("devicetree/locationScopedInformation",async t=>{await Ce();let e=vn(Ee,{id:t.id}),n=Se(t.textDocument.uri);if(!(!e||!e.isInContext(n)))return new Promise(async r=>{let i=await e.getRuntime(),s=await Nt(t,e,(o,a)=>{let c=i.context.macros,l={};if(!o?.item)return i.rootNode.serialize(l,c,a),[{inNode:!1,inScope:l,parentNode:i.rootNode.pathString}];let u=null;return o.item instanceof X?u=o.item:u=o.item?.parent,u.serialize(l,i.context.macros,a),[{inNode:!0,inScope:l,parentNode:u.pathString}]});r(s[0])})});
328
+ `)}var Ee=[],le,Hs,rg=new WeakMap,Uu=new Map;zF();var sg=new Map,QF=t=>{t.settings.disableFileWatchers||t.getContextFiles().forEach(e=>{Uu.has(e)||Uu.set(e,new ng(e,fk,()=>{let n=Ku(e),r=sg.get(e);return!n||r===void 0?!1:r!==n.version})),Uu.get(e)?.watch()})},uk=async t=>{let e=Ee.indexOf(t);if(e===-1)return;Vu(t,void 0,!0),rg.delete(t),console.log(`(ID: ${t.id}) cleaning Context for [${t.ctxNames.join(",")}]`);let n=await Ws(t);if(Q.sendNotification("devicetree/contextDeleted",{ctxNames:t.ctxNames.map(r=>r.toString()),id:t.id,...await t.getFileTree(),settings:t.settings,active:le===t,type:n.type}),Ee.splice(e,1),await mk(),t===le&&(le=void 0,Ee.length)){let r=Hs?vn(Ee,{fsPath:Hs}):void 0;r??=Ee[0],console.log("Active context was deleted. Forcing active to",r.id),await hn({id:r.id},!0)}t.settings.disableFileWatchers||t.getContextFiles().map(r=>{Uu.get(r)?.unwatch()}),setTimeout(async()=>{await Ce();let r=new Set(Ee.flatMap(i=>i.getContextFiles()));t.getContextFiles().map(i=>{r.has(i)||An().reset(i)})},2e3),t.bindingLoader?.dispose()},Q6=t=>{let e=rg.get(t);if(!e?.abort.signal.aborted)return Promise.all([e?.promise,t.getRuntime()])},Ce=async()=>{await Promise.all(Ee.map(Q6))},dk=async(t,e)=>(await ZF(e)).indexOf(t)!==-1,ZF=async t=>{let e=await eB(t);return Ee.filter(n=>!e.some(r=>r===n))},eB=async t=>{let e=await lk(t);return Ee.filter(n=>e.contexts.find(r=>qi(r)===n.id))},Z6=async t=>{let e=await sQ(t);return Ee.filter(n=>e.contexts.find(r=>qi(r)===n.id))},eQ=async(t,e)=>(await Z6(e)).indexOf(t)!==-1,tQ=async(t,e)=>{if(t===e)return!0;let n=(await t.getAllStableParsers()).flatMap(i=>i.cPreprocessorParser.dtsIncludes).filter(i=>i.resolvedPath),r=(await e.getAllStableParsers()).flatMap(i=>i.cPreprocessorParser.dtsIncludes).filter(i=>i.resolvedPath);return r.some(i=>pe(i.resolvedPath,t.parser.fsPath))&&n.length?n.every(i=>r.some(s=>s.resolvedPath===i.resolvedPath&&s.firstToken.pos.col===i.firstToken.pos.col&&s.firstToken.pos.len===i.firstToken.pos.len&&s.firstToken.pos.line===i.firstToken.pos.line&&s.lastToken.pos.col===i.lastToken.pos.col&&s.lastToken.pos.len===i.lastToken.pos.len&&s.lastToken.pos.line===i.lastToken.pos.line)):e.getContextFiles().some(i=>pe(i,t.parser.fsPath))},nQ=async t=>{if(!await dk(t))return;let e=await ZF(),n=await eB(),r=await Lf(e);if(Ee.indexOf(t)===-1)return;let i=await Promise.all(r.flatMap(a=>[...n,...e.filter(c=>c!==a.context)].map(async c=>({context:a.context,same:await tQ(a.context,c)})))),s=t.getContextFiles(),o=r.filter(a=>i.some(c=>c.context===a.context&&c.same)||a.context!==t&&pe(a.context.parser.fsPath,t.parser.fsPath)&&s.some(c=>c&&a.files.indexOf(c)!==-1)).map(a=>a.context);o.length&&await Promise.all(o.map(uk))},Q=(0,Be.createConnection)(Be.ProposedFeatures.all),on=new Be.TextDocuments(Vn),tB=!1,ig=!1,nB=!1,rB=!1,iB=!1,ak;Q.onInitialize(async t=>{ak=t.workspaceFolders??[],Q.console.log(`[Server(${process.pid}) ${ak?.at(0)?.uri} Version 0.8.3 ] Started and initialize received`);let e=t.capabilities;tB=!!(e.workspace&&e.workspace.configuration),ig=!!(e.workspace&&e.workspace.workspaceFolders),nB=!!e.workspace?.diagnostics?.refreshSupport,rB=!!e.workspace?.semanticTokens?.refreshSupport,iB=!!e.workspace?.foldingRange?.refreshSupport;let n={capabilities:{typeDefinitionProvider:!0,workspaceSymbolProvider:!0,textDocumentSync:Be.TextDocumentSyncKind.Incremental,renameProvider:{prepareProvider:!0},completionProvider:{resolveProvider:!0,triggerCharacters:["&","="," ",'"',"(",","]},codeActionProvider:{codeActionKinds:[Be.CodeActionKind.QuickFix,Be.CodeActionKind.SourceFixAll]},documentSymbolProvider:!0,semanticTokensProvider:{legend:{tokenTypes:Df,tokenModifiers:Af},full:!0},documentLinkProvider:{resolveProvider:!1},foldingRangeProvider:!0,definitionProvider:!0,declarationProvider:!0,referencesProvider:!0,documentFormattingProvider:!0,documentRangeFormattingProvider:!0,hoverProvider:!0,signatureHelpProvider:{triggerCharacters:["<","("],retriggerCharacters:[" ",","]}}};return ig&&(n.capabilities.workspace={workspaceFolders:{changeNotifications:!0,supported:!0}}),await cB(t.initializationOptions),n});var ck,rQ={tabSize:8,insertSpaces:!1,trimTrailingWhitespace:!0,insertFinalNewline:!0,wordWrapColumn:100};Q.onInitialized(async()=>{if(tB&&(Q.client.register(Be.DidChangeConfigurationNotification.type,{}),!ck)){let t=await Q.workspace.getConfiguration("editor").catch(()=>{}),e=await Q.workspace.getConfiguration("[devicetree]").catch(()=>{}),n={tabSize:e?.["editor.tabSize"],insertSpaces:e?.["editor.insertSpaces"],trimFinalNewlines:e?.["editor.trimFinalNewlines"],trimTrailingWhitespace:e?.["editor.trimTrailingWhitespace"],insertFinalNewline:e?.["editor.insertFinalNewline"],wordWrapColumn:e?.["editor.wordWrapColumn"]};(t||n)&&(ck={...t,...n})}ig&&Q.workspace.onDidChangeWorkspaceFolders(async t=>{Q.console.log("Workspace folder change event received"),await Gu()})});Q.onRequest("workspace/workspaceFolders",async()=>ak??null);var iQ=async t=>{let e=sB();return e={...Us,...e},ju(e,t??await zu())},lk=async t=>{let e=aQ();return e={...Us,...e},ju(e,t??await zu())},sQ=async t=>{let e=cQ();return e={...Us,...e},ju(e,t??await zu())},Wu=async t=>{let e=oQ();return e={...Us,...e},ju(e,t??await zu())},zu=async()=>ig?await Q.workspace.getWorkspaceFolders()??[]:[],JF=async t=>{let e=vn(Ee,{id:qi(t)});if(e)return e.ctxNames.includes(t.ctxName)||console.log(`(ID: ${e.id}) Adding name ${t.ctxName} for [${e.ctxNames.join(",")}]`),e.addCtxName(t.ctxName),e;let n=qi(t);console.log(`(ID: ${n}) New context [${t.ctxName}]`),console.log(`(ID: ${n}) Settings: ${JSON.stringify(t,void 0," ")}`);let r=(0,gc.join)((0,gc.dirname)(t.dtsFile),"dts","bindings"),i=new ap(t,ck??rQ,t.bindingType?CF({zephyrBindings:t.zephyrBindings?[r,...t.zephyrBindings]:[r],deviceOrgBindingsMetaSchema:t.deviceOrgBindingsMetaSchema??[],deviceOrgTreeBindings:t.deviceOrgTreeBindings??[]},t.bindingType):void 0);Ee.push(i);let s=performance.now();await i.stable(),console.log(`(ID: ${n}) New context took ${performance.now()-s}ms to start [${t.ctxName}]`),QF(i);let o=await Ws(i);return Q.sendNotification("devicetree/contextCreated",{ctxNames:i.ctxNames.map(a=>a.toString()),id:i.id,...await i.getFileTree(),settings:i.settings,active:i===le,type:o.type}),await nQ(i),await mk(),i},Gu=async()=>{let t=await lk(),e=await Wu();e.allowAdhocContexts||(e=await lk());let n=e.contexts.map(qi),r=Ee.filter(i=>!n.includes(i.id));await Promise.all(r.map(uk)),await t.contexts?.reduce((i,s)=>i.then(async()=>{await JF(s)}),Promise.resolve()),e.allowAdhocContexts&&await(await iQ()).contexts?.reduce((s,o)=>s.then(async()=>{vn(Ee,{fsPath:o.dtsFile})||await JF(o)}),Promise.resolve()),setTimeout(async()=>{Hs?await hn({fsPath:Hs}):!le&&Ee.length&&(console.log(`No active context using first context (ID: ${Ee[0].id}) [${Ee[0].ctxNames.join(",")}]`),await hn({id:Ee[0].id}))})},$r,Vs,Hu=new Map,mc=new Map,oQ=()=>!Vs&&!$r?void 0:{...Vs,...$r,contexts:[...$r?.contexts??[],...Array.from(mc.values()),...Array.from(Hu.values())]},sB=()=>!Vs&&!$r?void 0:{...Vs,...$r,contexts:[...Array.from(Hu.values())]},aQ=()=>!Vs&&!$r?void 0:{...Vs,...$r,contexts:[...$r?.contexts??[],...Array.from(mc.values())]},cQ=()=>!Vs&&!$r?void 0:{...$r,contexts:[...$r?.contexts??[]]};function lQ(t){let e={...t};for(let n in e)e[n]===null&&delete e[n];return e}var oB=async()=>{let t=await Wu();console.log("Resolved settings",JSON.stringify(t,void 0," ")),Q.sendNotification("devicetree/settingsChanged",t),await Gu(),Ce().then(()=>{nB&&Q.languages.diagnostics.refresh()})},uQ=async()=>{let t=le?.getContextFiles();await Promise.all(Array.from(on.keys()).filter(zt).map(async e=>{t?.some(n=>pe(n,Se(e)))||await Q.sendDiagnostics({uri:e,version:on.get(e)?.version,diagnostics:[{severity:Be.DiagnosticSeverity.Information,range:Be.Range.create(Be.Position.create(0,0),Be.Position.create(0,0)),message:"File not in active context",source:"devicetree"}]})}))},fk=async t=>{let e=pT(Ee,t);if(e.length)e.sort((n,r)=>n===le?-1:r===le?1:0).forEach(n=>{rg.get(n)?.abort.abort(),le===n&&Q.sendNotification("devicetree/activeContextBusyNotification",n.id),Q.sendNotification("devicetree/contextBusyNotification",n.id);let r=new AbortController,i=new Promise(s=>{setTimeout(async()=>{if(n.setStaleFsPath(t),r.signal.aborted){console.log("Abort parsing due to new request"),s();return}let o=performance.now(),a=le===n,c=a?aB(n):[],l=n.getContextFiles();if(await n.reevaluate(t),QF(n),l.forEach(p=>Uu.get(p)?.unwatch()),a&&gk(n)?.length&&(pk(n).then(p=>{let m=p.items.map(h=>({uri:h.uri,version:h.version??void 0,diagnostics:h.items}));Vu(n,c.filter(h=>m.every(y=>y.uri!==h.uri))),m.forEach(h=>{Q.sendDiagnostics(h)}),Yu.set(n,!0)}),Hs)){let p=n.getFsPathParser(Hs);p&&setTimeout(()=>{p.latestSemanticTokensBuilt||Q.languages.semanticTokens.refresh()},50)}let[u,d]=await Promise.all([Ws(n),n.getFileTree()]),f={ctxNames:n.ctxNames.map(p=>p.toString()),id:n.id,...d,settings:n.settings,active:a,type:u.type};le===n&&Q.sendNotification("devicetree/activeContextStableNotification",f),Q.sendNotification("devicetree/contextStableNotification",f),s(),console.log("reevaluate",performance.now()-o)})});rg.set(n,{abort:r,promise:i})});else{if((await Wu()).allowAdhocContexts===!1)return;await Gu(),await hn({fsPath:t})}},dQ=t=>on.keys().find(e=>pe(Se(e),t)),Ku=t=>{let e=dQ(t);if(e)return on.get(e)},aB=t=>t.getContextFiles().map(e=>({uri:ue(e),version:Ku(e)?.version,diagnostics:[]})),Yu=new WeakMap,Vu=async(t,e=aB(t),n=!1)=>{if(!n&&t!==le)return;let r=performance.now();await Promise.all(e.filter(i=>t===le||!le?.getContextFiles().some(s=>pe(Se(i.uri),s))).map(i=>Q.sendDiagnostics({uri:i.uri,version:on.get(i.uri)?.version,diagnostics:[]}))),Yu.delete(t),console.log(`(ID: ${t.id})`,"clear workspace diagnostics",`[${t.ctxNames.join(",")}]`,performance.now()-r)},pk=async t=>{await t.stable();let e=performance.now(),n=await t.getDiagnostics(),r=await Promise.all(t.getContextFiles().map(async i=>{let s=Ku(i),o=[];return s&&t.settings.showFormattingErrorAsDiagnostics&&o.push(...(await ho({textDocument:s,options:t.formattingOptions},s.getText(),"File Diagnostics").catch(()=>[])).map(a=>a.diagnostic())),{uri:ue(i),kind:Be.DocumentDiagnosticReportKind.Full,items:[...n.get(i)??[],...o],version:s?.version??null}}));return console.log(`(ID: ${t.id})`,"workspace diagnostics",`[${t.ctxNames.join(",")}]`,performance.now()-e),{items:[...r]}},hk=async t=>{let{items:e}=await pk(t);e.map(n=>({uri:n.uri,version:n.version??void 0,diagnostics:n.items})).forEach(async n=>{Q.sendDiagnostics(n)}),Yu.set(t,!0)},mk=async()=>{let t=await Promise.all(Ee.map(e=>Ws(e)));console.log("======== Context List ========"),t.forEach(e=>{console.log(`(ID: ${e.ctx.id}) [${e.ctx.ctxNames.join(",")}]`,`[${e.type}]`,le===e.ctx?" [ACTIVE]":"")}),console.log("==============================")},Ws=async(t,e)=>{let n=await dk(t,e),r=!n&&await eQ(t,e);return{ctx:t,type:n?"Ad Hoc":r?"User":"3rd Party"}},hn=async(t,e=!1)=>{if("fsPath"in t){if(!zt(t.fsPath))return!1;Hs=t.fsPath,console.log("Active File Uri",Hs)}let n=await Wu();if(le&&!e&&!n.autoChangeContext||(await Ce(),!e&&le?.getContextFiles().find(o=>"fsPath"in t&&pe(o,t.fsPath))))return!1;let r=le,i=vn(Ee,t),s=r!==i;return s&&(r&&Vu(r),le=i,i?(Ws(i).then(async o=>{let a=await i.getFileTree();!i||i!==le&&!Ee.includes(i)||Q.sendNotification("devicetree/newActiveContext",{ctxNames:i.ctxNames.map(c=>c.toString()),id:i.id,...a,settings:i.settings,active:le===i,type:o.type})}),gk(i)?.length&&hk(i),await mk()):Q.sendNotification("devicetree/newActiveContext",void 0)),iB&&Q.languages.foldingRange.refresh(),rB&&Q.languages.semanticTokens.refresh(),s},zt=t=>[".dts",".dtsi",".dtso",".overlay"].some(e=>t.endsWith(e));on.listen(Q);var gk=t=>t?.getContextFiles()?.filter(e=>Ku(e));on.onDidSave(t=>{sg.set(Se(t.document.uri),t.document.version)});on.onDidClose(async t=>{let e=Se(t.document.uri);if(!zt(e))return;sg.delete(e);let n=pT(Ee,e);if(n.length===0){Hu.delete(e),Q.sendDiagnostics({uri:t.document.uri,version:on.get(t.document.uri)?.version,diagnostics:[]});return}await Promise.all(n.map(async r=>{!!gk(r)?.filter(s=>s!==e).length?le?.getContextFiles().some(s=>pe(s,e))?le?.getContextFiles().some(s=>pe(s,e))&&(await Vu(le),await hk(le)):Q.sendDiagnostics({uri:t.document.uri,version:on.get(t.document.uri)?.version,diagnostics:[]}):await dk(r)?(await uk(r),Hu.delete(r.settings.dtsFile)):Vu(r)}))});on.onDidOpen(async t=>{let e=Se(t.document.uri);if(!zt(e))return;sg.set(e,t.document.version),await Ce(),uQ();let n=vn(Ee,{fsPath:e});if(console.log("onDidOpen",n?.id,e),n)n!==le?await hn({id:n.id}):n===le&&(!Yu.get(n)||n.getContextFiles().some(r=>!pe(r,e)))&&await hk(n);else{let r={ctxName:(0,gc.basename)(e),dtsFile:e};Hu.set(e,r),await fk(e)}});on.onDidChangeContent(async t=>{let e=Se(t.document.uri);if(!zt(e))return;let n=t.document.getText(),r=An();r.needsRenew(e,n)&&(console.log("Content changed",e),r.renewLexer(e,n),await fk(e))});var cB=async t=>{t?.settings?.devicetree&&($r=LF(lQ(t.settings.devicetree)),console.log("Configuration changed",JSON.stringify(t,void 0," ")),await oB())};Q.onDidChangeConfiguration(async t=>{await cB(t)});Q.listen();Q.languages.diagnostics.onWorkspace(async()=>{await Ce();let t=le;return t?pk(t).finally(()=>{Yu.set(t,!0)}):{items:[]}});Q.onDidChangeWatchedFiles(t=>{Q.console.log("We received a file change event")});Q.onCompletion(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return xA(t,le,on.get(t.textDocument.uri));if(!zt(e))return[];await Ce(),hn({fsPath:e});let n=$n(e);return n?[...await vD(t,n),...await c0(t,n)]:[]});Q.onCompletionResolve(t=>t);var $n=t=>{let e=sB();return vn(Ee,{fsPath:t},le,e?.preferredContext)};Q.onDocumentSymbol(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return[];await Ce();let n=$n(e);return n?n.getFsPathParser(e)?.getDocumentSymbols(e):[]});Q.onWorkspaceSymbol(async()=>{await Ce();let t=le;return t?(await t.getAllStableParsers()).flatMap(e=>e.getWorkspaceSymbols()):[]});Q.languages.semanticTokens.on(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return{data:[]};try{await Ce();let n=$n(e),r=new Be.SemanticTokensBuilder,i=n?.isInContext(e);return!n||!i?{data:[]}:((await n.getAllStableParsers()).forEach(s=>s.buildSemanticTokens(r,e)),r.build())}catch(n){throw console.log(n),n}});Q.onDocumentLinks(async t=>{await Ce();let e=Se(t.textDocument.uri);return zt(e)?$n(e)?.getDocumentLinks(e):e.endsWith(".yaml")&&le?le.bindingLoader?.getDocumentLinks?.(on.get(t.textDocument.uri))??[]:[]});Q.onPrepareRename(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return jA(t,n)});Q.onRenameRequest(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return BA(t,n)});Q.onReferences(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return LA(t,n)});Q.onDefinition(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return VA(t,le,on.get(t.textDocument.uri));if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e),r=(await n?.getDocumentLinks(e,t.position))?.filter(i=>i.target).map(i=>Be.Location.create(i.target,i.range))??[];return r.length?r:HA(t,n)});Q.onDeclaration(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return KA(t,le,on.get(t.textDocument.uri));if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return GA(t,n)});Q.onCodeAction(async t=>{let e=Se(t.textDocument.uri);if(zt(e))return XA(t)});var lB=async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);if(!n)return[];if((await n.getSyntaxIssues(void 0,l=>io(l.raw,e,!1)?l:void 0)).get(e)?.length)return[];let i=on.get(t.textDocument.uri)??An().getDocument(e),s=i.getText(),o=await ho(t,s,"New Text").catch(()=>s);if(o===s)return[];let a=i.lineCount-1,c=i.getText({start:{line:a,character:0},end:{line:a+1,character:0}}).length;return[Be.TextEdit.replace(Be.Range.create(Be.Position.create(0,0),Be.Position.create(i.lineCount,c)),o)]};Q.onDocumentRangeFormatting(lB);Q.onDocumentFormatting(lB);Q.onHover(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return AO(t,le,on.get(t.textDocument.uri));if(!zt(e))return;await Ce();let n=$n(e);return(await l0(t,n)).at(0)});Q.onFoldingRanges(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce();let n=$n(e),r=n?.isInContext(e);if(!n||!r)return[];let i=(await n.getAllStableParsers()).find(s=>s.getFiles().some(o=>o===e));return i?AF(e,i):[]});Q.onTypeDefinition(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return xF(t,n)});Q.onSignatureHelp(async t=>{let e=Se(t.textDocument.uri);if(!zt(e))return;await Ce(),hn({fsPath:e});let n=$n(e);return HF(t,n)});Q.onRequest("devicetree/getContexts",async()=>(await Ce(),Promise.all(Ee.map(async t=>{let e=await Ws(t);return{ctxNames:t.ctxNames.map(n=>n.toString()),id:t.id,...await t.getFileTree(),settings:t.settings,active:le===t,type:e.type}}))));Q.onRequest("devicetree/setActive",async t=>(await Ce(),console.log("devicetree/setActive",t),await hn(t,!0)));Q.onRequest("devicetree/getActiveContext",async()=>{if(await Ce(),console.log("devicetree/getActiveContext"),!le)return;let t=await Ws(le);return le?{ctxNames:le.ctxNames.map(e=>e.toString()),id:le.id,...await le.getFileTree(),settings:le.settings,active:!0,type:t.type}:void 0});Q.onRequest("devicetree/setDefaultSettings",async t=>{await Ce(),Vs=t,console.log("Integration Settings",t),await oB()});Q.onRequest("devicetree/requestContext",async t=>{await Ce();let e=await zu(),n=await Wu(e),r=await rk(t,n,e);console.log("devicetree/requestContext",r);let i=qi(r),s=Array.from(mc).find(([,c])=>c.ctxName===t.ctxName);if(s){let c=s[0].split(":",1)[0];vn(Ee,{name:t.ctxName.toString()})?.removeCtxName(t.ctxName),console.log(`Removing integration context with ID ${c} and name ${t.ctxName}`),mc.delete(s[0])}mc.set(`${i}:${t.ctxName}`,t),await Gu();let o=Ee.find(c=>c.id===i);if(!o)throw new Error("Failed to create context");let a=await Ws(o,e);return{ctxNames:o.ctxNames.map(c=>c.toString()),id:i,...await o.getFileTree(),settings:o.settings,active:!0,type:a.type}});Q.onRequest("devicetree/removeContext",async({id:t,name:e})=>{await Ce(),mc.delete(`${t}:${e}`);let n=vn(Ee,{id:t});if(n){if(n.removeCtxName(e),n.ctxNames.length){console.log("Context will not be deleted as it is still in use by others");return}await Gu()}});Q.onRequest("devicetree/compiledDtsOutput",async t=>{if(await Ce(),!t)return;let e=vn(Ee,{id:t});if(!e)return;let n=await e.toFullString();return ho({textDocument:{uri:ue(e.settings.dtsFile)},options:e.formattingOptions},n,"New Text").catch(()=>n)});Q.onRequest("devicetree/serializedContext",async t=>{if(await Ce(),!t)return;let e=vn(Ee,{id:t}),n=performance.now();return e?.serialize().finally(()=>{console.info("serializedContext",performance.now()-n)})});Q.onRequest("devicetree/activePath",async t=>{if(await Ce(),!le)return;let e=n=>{if(n?.item)return n.item instanceof X?{nodePath:n.item.pathString}:{nodePath:n.item.parent.pathString,propertyName:n.item.name}};return(await Nt(t,le,n=>[e(n)])).at(0)});Q.onRequest("devicetree/customActions",async t=>(await Ce(),jF(t,le)));Q.onRequest("devicetree/activeFsPath",async t=>{await Ce(),hn({fsPath:t})});Q.onRequest("devicetree/formattingText",async t=>{let e=Se(t.textDocument.uri),n=Ku(e)??An().getDocument(e,t.text),r=await ho(t,n.getText(),"Both");return{text:r.text,diagnostics:r.diagnostic.map(i=>i.diagnostic())}});Q.onRequest("devicetree/formatTextEdits",async t=>{await Ce();let e=An().getDocument(Se(t.textDocument.uri),t.text),n=e.positionAt(e.getText().length),r=Be.TextEdit.replace(Be.Range.create(Be.Position.create(0,0),n),""),i=ds(e,t.edits),o=await ho({...t,ranges:void 0},i,"New Text").catch(()=>i);return r.newText=o,r});Q.onRequest("devicetree/diagnosticIssues",async({uri:t,full:e})=>{await Ce();let n=Se(t);hn({fsPath:n});let r=$n(n);if(!r)return[];let i=e?(await r.getDiagnostics()).get(n):(await r.getSyntaxIssues(void 0,s=>io(s.raw,n,!!e)?s:void 0)).get(n);if(i?.length)return i});Q.onRequest("devicetree/evalMacros",async({macros:t,ctxId:e})=>{await Ce();let n=vn(Ee,{id:e});return n?t.map(r=>{let i=$c(r,n.macros),s=De(i);return{macro:r,evaluated:typeof s=="number"?s:i}}):[]});Q.onRequest("devicetree/memoryViews",async({ctxId:t})=>{let e=vn(Ee,{id:t});if(!e)return;await e?.stable();let n=await e.getRuntime(),r=n.rootNode.getMemoryViews(n.context.macros).sort((o,a)=>Lt(o.start,a.start)),i=new Map;r.forEach(o=>{let a=i.get(o.name),c={nodePath:o.nodePath,labels:o.labels,start:o.start,size:o.size};a?a.partitions.push(c):i.set(o.name,{name:o.name,partitions:[c]})});let s=YF(Array.from(i.values()));return{trees:s,treeStr:XF(s)}});Q.onRequest("devicetree/zephyrTypeBindings",async t=>(await Ce(),t?vn(Ee,{id:t})?.bindingLoader?.getZephyrContextBinding():void 0));Q.onRequest("devicetree/contextMacroNames",async t=>{if(await Ce(),!t)return;let e=vn(Ee,{id:t});return Array.from(e?.macros.keys()??[])});Q.onRequest("devicetree/locationScopedInformation",async t=>{await Ce();let e=vn(Ee,{id:t.id}),n=Se(t.textDocument.uri);if(!(!e||!e.isInContext(n)))return new Promise(async r=>{let i=await e.getRuntime(),s=await Nt(t,e,(o,a)=>{let c=i.context.macros,l={};if(!o?.item)return i.rootNode.serialize(l,c,a),[{inNode:!1,inScope:l,parentNode:i.rootNode.pathString}];let u=null;return o.item instanceof X?u=o.item:u=o.item?.parent,u.serialize(l,i.context.macros,a),[{inNode:!0,inScope:l,parentNode:u.pathString}]});r(s[0])})});
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "author": "Kyle Micallef Bonnici",
5
5
  "package-name": "devicetree-language-server",
6
6
  "main": "dist/server.js",
7
- "version": "0.8.2",
7
+ "version": "0.8.3",
8
8
  "categories": [
9
9
  "Linters",
10
10
  "Formatters",