devicetree-language-server 0.12.0 → 0.12.1
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.
- package/dist/THIRD_PARTY_LICENSES.txt +1 -1
- package/dist/server.js +2 -2
- package/package.json +1 -1
|
@@ -108,7 +108,7 @@ Repository: https://github.com/moxystudio/node-cross-spawn
|
|
|
108
108
|
|
|
109
109
|
----------------------------------------------------------------------
|
|
110
110
|
|
|
111
|
-
devicetree-language-server@0.12.
|
|
111
|
+
devicetree-language-server@0.12.1
|
|
112
112
|
License: Apache-2.0
|
|
113
113
|
Repository: https://github.com/kylebonnici/dts-lsp
|
|
114
114
|
|
package/dist/server.js
CHANGED
|
@@ -297,7 +297,7 @@ ${" ".repeat(r-1)}};`}serialize(e,n,r=()=>!0){let i=this.mappedReg(n),s=this.imp
|
|
|
297
297
|
`){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(Kt(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){return e.startsWith("#")?(this.pushToken({tokens:[46],pos:this.generatePos(e,"#"),value:"#"}),!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 GT=require("fs"),_a=require("path"),rl=L(U());var At=class extends te{constructor(e){super(e),this.semanticTokenType="keyword",this.semanticTokenModifiers="declaration"}};var OD=require("path"),tp=L(U());var ei=class extends te{constructor(n,r){super();this.keyword=n;this.path=r;this.docSymbolsMeta={name:`Include ${r}`,kind:tp.SymbolKind.File},this.addChild(n),this.addChild(r)}get resolvedPath(){return this._resolvedPath}set resolvedPath(n){this.docSymbolsMeta={name:`Include ${n}`,kind:tp.SymbolKind.File},this._resolvedPath=n}},va=class extends te{constructor(n,r,i){super(i);this._path=n;this.relative=r;this.docSymbolsMeta={name:(0,OD.basename)(this.path),kind:tp.SymbolKind.File},this.semanticTokenType="string",this.semanticTokenModifiers="declaration"}get path(){return this.relative?this._path.slice(1,-1):this._path}};var MD=L(U());var Tt=class extends me{constructor(n,r){super(r);this.name=n;this.docSymbolsMeta={name:this.name.toString(),kind:MD.SymbolKind.Variable},this.semanticTokenType="macro",this.semanticTokenModifiers="declaration"}toString(){return this.name}};var np=class extends te{constructor(n,r){super(r);this.operator=n;this.semanticTokenType="operator",this.semanticTokenModifiers="declaration"}toString(){return this.operator}};var xD=L(U());var ba=class extends At{toString(){return"..."}},ti=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 fe(this.fsPath,n)?[{name:this.functionName.name,kind:xD.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 Gi=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||!fe(this.currentToken?.fsPath,e.fsPath))return;let s=this.currentToken,o=s;for(;this.currentToken?.pos.line===i&&fe(this.currentToken?.fsPath,e.fsPath);)o=this.moveToNextToken;return n&&this._issues.push(Y(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=Kt(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=Kt(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||!fe(r.fsPath,s)||!fe(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(Fe));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 Tt(s,he(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(Y(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(H(e,40)?(r="&",H(this.currentToken,40)&&(r="&&",n=this.moveToNextToken)):H(e,6)?(r="!",H(this.currentToken,0)&&(r="!=",n=this.moveToNextToken)):H(e,10)?r="~":H(e,8)?(r="|",H(this.currentToken,8)&&(r="||",n=this.moveToNextToken)):H(e,9)?r="^":H(e,4)?(r=">",H(this.currentToken,4)?(r=">>",n=this.moveToNextToken):H(this.currentToken,0)&&(r=">=",n=this.moveToNextToken)):H(e,5)?(r="<",H(this.currentToken,5)?(r="<<",n=this.moveToNextToken):H(this.currentToken,0)&&(r="<=",n=this.moveToNextToken)):H(e,15)?r="+":H(e,16)?r="-":H(e,17)?r="*":H(e,13)?r="/":H(e,18)?r="%":H(e,46)?H(this.currentToken,46)&&(r="##",n=this.moveToNextToken):H(e,0)&&H(this.currentToken,0)&&(r="==",n=this.moveToNextToken),r){let i=new np(r,he(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(!(e.get(n.name)?.macro.identifier instanceof ti)&&!Kt(n.lastToken,this.currentToken)){this.popStack();return}let i=this.processMacroCallParams();if(!i){this.popStack();return}if(n.name==="defined")i.length>1?this._issues.push(Y(44,n.firstToken,n.lastToken,n)):i.length<1&&this._issues.push(Y(45,n.firstToken,n.lastToken,n));else{let o=e.get(n.name)?.macro;o&&(o?.identifier instanceof ti?o.identifier.params.at(-1)instanceof ba||(i.length>o.identifier.params.length?this._issues.push(Y(44,n.firstToken,n.lastToken,n,{linkedTo:[o]})):i.length<o.identifier.params.length&&this._issues.push(Y(45,n.firstToken,n.lastToken,n,{linkedTo:[o]}))):this._issues.push(Y(43,n.firstToken,n.lastToken,n)))}let s=new Gt(n,i);return s.lastToken=this.prevToken,this.mergeStack(),s}processHex(){this.enqueueToStack();let e=this.checkConcurrentTokens([ot("0"),ot("x",{caseInsensitive:!0})]);if(e.length!==2){this.popStack();return}let n=this.consumeAnyConcurrentTokens([19,20].map(Fe));if(!n.length){this.popStack();return}let r=Number.parseInt(n.map(s=>s.value).join(""),16),i=new sn(r,he(e[0],n.at(-1)),16);return this.mergeStack(),i}processDec(e=!1){this.enqueueToStack();let n;e&&(H(this.currentToken,16)||H(this.currentToken,15))&&Kt(this.currentToken,this.currentToken?.nextToken)&&(n=this.moveToNextToken);let r=this.consumeAnyConcurrentTokens([19].map(Fe));if(!r.length){this.popStack();return}let i=Number.parseInt(r.map(o=>o.value).join(""),10);n&&H(n,16)&&(i=4294967295-i);let s=new sn(i,he(n??r[0],r.at(-1)),10);return this.mergeStack(),s}processEnclosedExpression(e,n){this.enqueueToStack();let r,i;if(H(this.currentToken,42)){let s;r=this.moveToNextToken,i=r;let o=this.processExpression(e,n,!0);return o&&(s=new rn(o,!0),o=new rn(s,!1),s.openBracket=r),H(this.currentToken,43)?(i=this.moveToNextToken,s&&(s.closeBracket=i)):r&&this._issues.push(Y(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 rn?i.addExpression(o,a):i=new rn(i,!1,{operator:o,expression:a}):this._issues.push(Y(27,o.firstToken,o.lastToken,n)),o=this.isOperator()}}return this.mergeStack(),i}processMacroCallParams(){if(!H(this.currentToken,42))return;let e=this.parseScopedBlock(r=>!!H(r,42),r=>!!H(r,43),r=>!!H(r,24));return e?.items.length===2&&H(e.endToken,43)?[]:e?.splitTokens.map((r,i)=>{if(r.tokens.length===0)return null;let s=new bi(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(""),he(r.tokens[0],r.tokens.at(-1)),i);return s.splitToken=e.separatorTokens.at(i),s})}};var mr=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(`
|
|
298
298
|
`)}},gr=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 rp=class t extends Gi{constructor(n,r=()=>qn().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||!H(c,13)||(l=s(),!H(l,17)||c.pos.line!==l.pos.line||c.pos.col+1!==l.pos.col))return;let u=()=>!(!H(a(),17)||!H(o(),13)||!Kt(a(),o())),d=l.pos.line,f=c,p=[];l=s();do{if(o()?.pos.line!==d){let y=new gr(he(f,a()));p.push(y),d=o().pos.line??0,f=o()}l=s()}while(r<n.length&&!u());let m=new gr(he(f,o()));p.push(m);let h=new mr(p);return s(),{comment:h,tokenUsed:i,index:r-1}}static processLineComment(n,r){let i=[];if(!H(n[r],13)||n.length===r+1||!H(n[r+1],13)||!Kt(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 gr(he(n[i[0]],n[i.at(-1)])),tokenUsed:i,index:r-1}}};var LD=L(U());var ip=class extends te{constructor(n,r){super(n);this.content=r}toString(){let n=this.content.filter(r=>!H(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("")}},Qc=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 Tt?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:LD.MarkupKind.Markdown,value:["```cpp",`#define ${this.toString()}`,"```"].join(`
|
|
299
299
|
`)}}};var el=class extends te{constructor(e){super(e)}},tl=class extends te{constructor(n,r){super();this.keyword=n;this.content=r;this.active=!1;this.addChild(n)}},nl=class extends tl{constructor(n,r,i){super(n,i);this.expression=r;this.addChild(r),this.addChild(i)}useBlock(n){return this.expression&&n.has(this.expression.name)}},sp=class extends tl{constructor(n,r,i){super(n,i);this.expression=r;this.addChild(r),this.addChild(i)}useBlock(n){return this.expression?.isTrue(n)}},op=class extends nl{useBlock(e){return this.expression&&!e.has(this.expression.name)}},ap=class extends tl{};var Zc=(t,e)=>{let n=t,r=[];for(;n&&(r.push(n),n!==e);)n=n.nextToken;return r},Dr=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;this.ifBlocks.forEach((s,o)=>{if(s.active)return;let a=o===this.ifBlocks.length-1,c=s.firstToken,l=a?r?this.elseOption.firstToken:this.lastToken:s.content?.lastToken??this.ifBlocks[o+1].firstToken??s.lastToken;n.push(et.create(se(c),se(l)))});let i=n.length!==this.ifBlocks.length;if(this.elseOption&&i){let s=this.elseOption.firstToken,o=this.elseOption.content?.lastToken??this.endIf?.lastToken??this.lastToken;return n.push(et.create(se(s),se(o))),n}if(!i){let s=this.firstToken,o=this.lastToken;return[et.create(se(s),se(o))]}return n}getInValidTokenRangeWhenActiveBlock(n){let r=new WeakSet,i=!1;return this.ifBlocks.forEach(s=>{let o=s.expression?.lastToken??s.keyword.lastToken;Zc(s.firstToken,o).forEach(a=>r.add(a)),!i&&s===n?i=!0:s.content&&Zc(s.content.firstToken,s.content.lastToken).forEach(a=>r.add(a))}),this.elseOption&&(Zc(this.elseOption.keyword.firstToken,this.elseOption.keyword.lastToken).forEach(s=>r.add(s)),i&&this.elseOption.content&&Zc(this.elseOption.content.firstToken,this.elseOption.content.lastToken).forEach(s=>r.add(s))),this.endIf&&Zc(this.endIf.firstToken,this.endIf.lastToken).forEach(s=>r.add(s)),r}};var Sa=class extends Gi{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=mn(n,i)||!n||H(n,14)&&n.pos.line+1===i?.pos.line;if(!(this.macroStart&&!s))return this.macroStart&&H(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 rp(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||!fe(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||!H(r,25))return this.popStack(),!1;this.macroStart=!0;let i=new At(he(r)),s=this.isFunctionDefinition()||this.processCIdentifier(this.macros,!0);if(!s)return this._issues.push(Y(30,i.firstToken,i.lastToken,i)),this.mergeStack(),this.macroStart=!1,!0;let o=this.consumeDefinitionContent(),a;o.length&&(a=new ip(he(o[0],o.at(-1)),o));let c=new Qc(i,s,a);this.macros.set(c.name,{macro:c,resolver:Nw(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||!H(r,28))return this.popStack(),!1;this.macroStart=!0;let i=new At(he(r)),s=this.processCIdentifier(this.macros,!0);if(!s)return this._issues.push(Y(30,i.firstToken,i.lastToken,i)),this.mergeStack(),this.macroStart=!1,!0;let o=new Qc(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||!H(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(!H(r,42)||!Kt(n.lastToken,r)){this.popStack();return}let i=[],s=this.processCIdentifier(this.macros,!0)||this.processVariadic();for(;s;)i.push(s),!H(this.currentToken,24)&&!H(this.currentToken,43)?this._issues.push(Y(28,s.firstToken,s.lastToken,s)):H(this.currentToken,43)||(r=this.moveToNextToken),s=this.processCIdentifier(this.macros,!0)||this.processVariadic();let o=new ti(n,i);if(H(this.currentToken,43))r=this.moveToNextToken,o.lastToken=r;else{o.lastToken=this.prevToken;let a=i.at(-1)??o;this._issues.push(Y(26,a.firstToken,a.lastToken,a))}return this.mergeStack(),o}processVariadic(){this.enqueueToStack();let n=this.checkConcurrentTokens([Fe(45),Fe(45),Fe(45)]);if(n.length!==3){this.popStack();return}let r=new ba(he(n[0],n.at(-1)));return this.mergeStack(),r}processIfDefBlocks(){let n=this.peekIndex(),r=this.parseScopedBlock(a=>!!a&&[33,34,32].some(c=>H(a,c))&&!mn(a.prevToken,a),a=>!!a&&[37].some(c=>H(a,c))&&!mn(a.prevToken,a),a=>!!a&&[36,35].some(c=>H(a,c))&&!mn(a.prevToken,a));if(!r)return;let i=this.processIfBlock(r);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=>lo(c,a.range))&&(a.disabled=!0)}),[...i.ifBlocks,...i.elseOption?[i.elseOption]:[]].forEach(a=>{!a.active&&a.content&&this._issues.push(Y(47,a.content.firstToken,a.content.lastToken,a.content,{severity:rl.DiagnosticSeverity.Hint,tags:[rl.DiagnosticTag.Unnecessary]}))}),this.positionStack[this.positionStack.length-1]=n}processIfBlock(n){this.enqueueToStack();let r=new At(he(n.startToken)),i=[],s;n.splitTokens.forEach((c,l)=>{c.rewind();let u=this.prevToken,d=l===n.splitTokens.length-1&&H(u,36),f=new At(he(u));this.macroStart=!0;let p,m;if(H(f.firstToken,33)||H(f.firstToken,34)?(m=this.processCIdentifier(this.macros,!0),p=m):(p=this.processExpression(this.macros,f,!0)||this.processCIdentifier(this.macros,!0),p instanceof Tt&&p.name.toLowerCase()==="defined"&&(p=this.processExpression(this.macros,f,!0)||this.processCIdentifier(this.macros,!0))),this.macroStart=!1,d){let h=u,y=new At(he(h)),_;c.tokens.length&&(_=new el(he(c.tokens[0],c.tokens.at(-1)))),s=new ap(y,_??null)}else{p||this._issues.push(Y(31,f.firstToken,f.lastToken,f));let h,y=c.tokens.indexOf(p?.lastToken??r.lastToken)+1,_=c.tokens[y];y!==-1&&_&&(h=new el(he(_,c.tokens.at(-1)))),H(f.firstToken,33)?i.push(new nl(f,m??null,h??null)):H(f.firstToken,34)?i.push(new op(f,m??null,h??null)):i.push(new sp(f,p??null,h??null))}});let o;n.endToken?o=new At(he(n.endToken)):this._issues.push(Y(46,r.firstToken,r.lastToken,r));let a=new Dr(i,o??null,s);return this.mergeStack(),a}get allAstItems(){return[...this.dtsIncludes,...this.nodes,...this.comments]}resolveInclude(n){if(n.path.path)return n.path.relative?[(0,_a.resolve)((0,_a.dirname)(n.fsPath),n.path.path),...this.incudes.map(r=>(0,_a.resolve)(r,n.path.path))].find(r=>(0,GT.existsSync)(r)):this.incudes.map(r=>(0,_a.resolve)(r,n.path.path)).find(r=>(0,GT.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(H(r,26))this.moveToNextToken;else{let h=this.checkConcurrentTokens([Fe(13),ot("include"),Fe(13)]);if(h.length!==3)return this.popStack(),!1;i=h[0],s=h.at(-1)}let o=i,a=new At(he(i,s));r=this.moveToNextToken;let c=r,l=!!H(r,21);if(!c||!l&&!H(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&&!H(this.currentToken,4);)u+=this.currentToken?.value??"",r=this.moveToNextToken;let d=new va(u,l,he(c,r)),f=new ei(a,d);this.dtsIncludes.push(f),l||(this.currentToken?.pos.line!==o.pos.line||!H(this.currentToken,4)?this._issues.push(Y(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(Y(36,f.path.firstToken,f.path.lastToken,f.path,{severity:rl.DiagnosticSeverity.Warning})),m&&!this.optimizeForFormatting){qn().requestTokens(m,!0);let h=il().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=Ow(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 YT,cp=class{constructor(){this.headerFiles=new Map;this.includeOwners=new WeakMap}getCPreprocessorParser(e,n,r,i){e=dt(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 Sa(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=dt(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 il(){return YT??=new cp,YT}function qD(){YT=new cp}var KT,lp=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=dt(e),this.fileMap.get(e)?.text!==n}getDocument(e,n){return Lt.create(e,"devicetree",0,n??this.fileMap.get(e)?.text??(0,sl.readFileSync)(e).toString())}renewLexer(e,n){if(e=dt(e),il().reset(e),!n&&!(0,sl.existsSync)(e))return[];try{n??=(0,sl.readFileSync)(e).toString();let r=new tr(n,e);return this.fileMap.set(e,r),t.clone(r.tokens)}catch{}return[]}requestTokens(e,n){e=dt(e);let r=this.fileMap.get(e)?.tokens;return!r&&n?[...this.renewLexer(e)]:t.clone(r??[])}reset(e){e=dt(e),il().reset(e),this.fileMap.delete(e)}};function qn(){return KT??=new lp,KT}function $D(){KT=new lp}var ki=class t{constructor(e){this.context=e;this.comments=[];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=qn().requestTokens(e,!1),s=r.find(o=>Qt(o,e,n)||Pw(i,o,n));if(!s){let o=this.context.allParsers.flatMap(l=>l.includes),a=(l,u)=>{let d=o.find(f=>fe(f.resolvedPath,l));return d&&this.context.getSortKeyFile(u,l)===void 0?a(d.lastToken.fsPath,se(d.lastToken)):d},c=a(e,n);c&&(s=r.at(-1)?.parentNode,e=c.fsPath,n=up.Position.create(c.lastToken.pos.line,c.lastToken.pos.colEnd))}if(s instanceof st){let a=this.rootNode.getReferenceBy(s)?.getDeepestAstNode(e,n);return a?{...a,runtime:this}:{item:null,runtime:this,ast:Qr(s,e,n)}}else if(s instanceof nt&&s.path){let o=this.rootNode.getDeepestAstNode(e,n);return o?{...o,runtime:this}:void 0}else if(s instanceof we&&s.path){let o=t.getNodeFromPath(s.path.slice(1),this.rootNode)?.getDeepestAstNode(e,n);return o?{...o,runtime:this}:void 0}else if(s)return{runtime:this,item:null,ast:Qr(s,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 Ee)?.lastLinkedTo?.path)}get issues(){return this.issuesCache??=[...this.labelIssues(),...this.includeIssues(),...this.rootNode.getIssues(this.context.macros)],this.issuesCache}includeIssues(){let e=new Map;for(let a of this.context.allParsers.flatMap(c=>c.includes)){if(!a.resolvedPath||!Et(a.resolvedPath))continue;let c=e.get(a.resolvedPath)??[];c.push(a),e.set(a.resolvedPath,c)}let n=new Set([...e.entries()].filter(([,a])=>a.length>1).map(([a])=>a)),r=new Map,i=a=>{for(let c of a.includes){let l=r.get(c.fsPath)??[];l.push(a.fsPath),r.set(c.fsPath,l),i(c)}},s=this.context.getFileTree();i(s.mainDtsPath);for(let a of s.overlays)i(a);function o(a,c=new Set){if(c.has(a))return!1;c.add(a);let l=r.get(a);if(!l)return!1;for(let u of l)if(n.has(u)||o(u,c))return!0;return!1}return[...e.values()].filter(a=>a.length>1).filter(a=>!o(a[0].resolvedPath)).map(([a,...c])=>Bt(11,a.firstToken,a.lastToken,a,{linkedTo:c,templateStrings:[`#include <${a.path.path}>`,c.map(l=>FD.default.basename(l.fsPath)).join(", ")],severity:up.DiagnosticSeverity.Warning}))}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(Bt(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 kw(e.implementations,this.context)}};var ol=L(U());var BD=L(U());var dp=class extends te{constructor(n){super();this.values=n;this.docSymbolsMeta={name:"Values",kind:BD.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 jD=L(U());var fp=class extends te{constructor(n){super();this.keyword=n;this.addChild(n),this.docSymbolsMeta={name:"DTS Document version",kind:jD.SymbolKind.Function}}};var Ni=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 UD=L(U());var pp=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:UD.SymbolKind.Function},this.addChild(r),this.addChild(i)}toString(){return`/memreserve/ 0x${this.startAddress?.value?.toString(16)} 0x${this.endAddress?.value?.toString(16)}`}};var HD=L(U());var hp=class extends te{constructor(n,r){super();this.keyword=n;this.bitsSize=r;this.addChild(n),this.docSymbolsMeta={name:"bits",kind:HD.SymbolKind.Function},this.addChild(r)}toString(){return`/bits/ ${this.bitsSize?.value?.toString()}`}};var Ar=class extends Gi{constructor(n,r,i,s,o){super();this.fsPath=n;this.incudes=r;this.tokens=[];this.others=[];this.rootDocument=new Ee;this.unhandledStatements=new nt;this.injectedMacros=[];this.plugin=!1;this.#e=!1;this.cPreprocessorParser=new Sa(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 Ee,this._issues=[],this.unhandledStatements=new nt,this.#e=!1,this.plugin=!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,dt(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(Y(22,s,s,null)),this.reportExtraEndStatements())}};for(;!this.done;)await n();this.fsPath.endsWith(".dtsi")||(this.unhandledStatements.nodes.forEach(s=>{this._issues.push(Y(53,s.firstToken,s.lastToken,s))}),this.unhandledStatements.properties.forEach(s=>{this._issues.push(Y(32,s.firstToken,s.lastToken,s))}),this.unhandledStatements.deleteProperties.forEach(s=>{this._issues.push(Y(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 Ee||s instanceof Ne||s instanceof ei)&&Dw(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=RT(s);let o=Bf(r.fsPath,ce(r)),a=new Set;if(this.cPreprocessorParser.comments.forEach(l=>{Qt(r,r.fsPath,l.range.start)&&a.add(l)}),this.cPreprocessorParser.removeComments(a),this.injectedMacros.push(r),r instanceof Tt&&s.includes(r.name)||r instanceof Gt&&s.includes(r.functionName.name))return!0;let c=new tr(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||!H(r,13))return this.popStack(),!1;if(i=this.moveToNextToken,!i||!H(i,2))return this.popStack(),!1;let s=new nt;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(H(r,3))this.moveToNextToken;else{let i=this.prevToken;return i&&this._issues.push(Y(3,i,i,n)),this.endStatement(n,!1)}return this.prevToken?.value==="}"&&(n.closeScope=this.prevToken),this.endStatement(n)}isNodeEnd(){return H(this.currentToken,3)||H(this.currentToken,1)}endStatement(n,r=!0){let i=this.currentToken;if(!H(i,1)){let s=this.prevToken;if(s&&r)return this._issues.push(Y(1,s,s,n)),s}return this.moveToNextToken,this.reportExtraEndStatements(),i}reportExtraEndStatements(){for(;H(this.currentToken,1);){let n=this.moveToNextToken;n&&this._issues.push(Y(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(Y(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 st(s):new we(s,i);if(r==="Ref"?(this.enqueueToStack(),a=this.processNodePathRef(c),!a||!H(this.currentToken,2)?(this.popStack(),a=void 0):this.mergeStack(),a??=this.isLabelRef(c)):r==="Name"&&(o=this.isNodeName()),!a&&!o){if(!H(this.currentToken,2))return this.popStack(),!1;c.firstToken=this.currentToken,this._issues.push(Y(r==="Name"?[7]:[10,48,11],c.firstToken,this.currentToken?.nextToken,c))}let l=!1;if(a&&c instanceof st?(c.reference=a,l=!0):o&&c instanceof we&&(l=o.address!==void 0,c.name=o),H(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(Y(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([ot("0"),ot("x",{caseInsensitive:!0})]);i.length!==2?(i=[],this.popStack()):(this._issues.push(Y(50,i[0],i[1],n,{severity:ol.DiagnosticSeverity.Warning})),r=i.at(-1),this.mergeStack());let s=this.consumeAnyConcurrentTokens([19,20,48].map(Fe)),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(Y(8,r,r,n)):!Number.isNaN(a)&&!Kt(r,s[0])&&!_i(s[0].fsPath)&&this._issues.push(Y(29,r,s[0],n,{inclusiveStart:!1,inclusiveEnd:!1}))),this.currentToken?.value.toUpperCase()==="ULL"&&(this._issues.push(Y(51,this.currentToken,this.currentToken,n,{severity:ol.DiagnosticSeverity.Warning})),this.moveToNextToken),new Hc(a,he(i.at(0)??s[0]??this.prevToken,this.prevToken))}processNodeAddresses(n){this.enqueueToStack();let r=this.checkConcurrentTokens([Fe(49)]);if(r.length){Kt(n.lastToken,r[0])||this._issues.push(Y(29,n.lastToken,r[0],n,{inclusiveStart:!1,inclusiveEnd:!1}));let i=[],s=()=>{this.processInjectPreProcessorMacros(this.cPreprocessorParser.macros),i.push(this.processNodeAddress(n)),H(this.currentToken,24)&&(this.prevToken&&!Kt(this.prevToken,this.currentToken)&&this._issues.push(Y(29,this.prevToken,this.currentToken,n,{inclusiveStart:!1,inclusiveEnd:!1})),this.moveToNextToken,s())};s();let o=this.currentToken;for(;!H(this.currentToken,2)&&!H(this.currentToken,1)&&!H(this.currentToken,3)&&!H(this.currentToken,13)&&mn(this.currentToken,i.at(-1)?.lastToken);)this.moveToNextToken;if(o&&o!==this.currentToken){this._issues.push(Y(52,o,this.currentToken,n));let a=new Hc([],he(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(Fe));if(!n.length){this.popStack();return}let r=n.map(a=>a.value).join(""),i=new $e(r,he(n[0],n.at(-1))),s=this.processNodeAddresses(i);i.address=s;let o=["__overlay__","__fixups__","__local_fixups__","__symbols__","__overrides__","__dormant__"];return!Uf(r)&&(!this.plugin||!o.includes(r)&&this.plugin)&&this._issues.push(Y(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(Fe));if(!n.length){this.popStack();return}let r=new Xe(n.map(i=>i.value).join(""),he(n[0],n.at(-1)));return this.mergeStack(),r}isLabelName(){this.enqueueToStack();let n=this.consumeAnyConcurrentTokens([19,47,48].map(Fe));if(!n.length){this.popStack();return}if(!Uf(n?.[0].value)){this.popStack();return}let r=n.map(s=>s.value).join(""),i=new gn(r,he(n[0],n[n.length-1]));return this.mergeStack(),i}isLabelAssign(n){this.enqueueToStack();let r=this.consumeAnyConcurrentTokens([19,47,48].map(Fe));if(!r.length){this.popStack();return}if(!Uf(r?.[0].value)){this.popStack();return}let i=r.map(c=>c.value).join(""),s=this.currentToken,o=s&&H(s,50),a=new bs(new gn(i,he(r[0],r.at(-1))),he(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(Y(29,c,s,a,{inclusiveStart:!1,inclusiveEnd:!1})),this.moveToNextToken}else if(n)this._issues.push(Y(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(H(this.currentToken,2)||H(this.currentToken,49))return this.popStack(),!1;let s=new Ne(i,r),o;H(this.currentToken,0)?(s.assignOperatorToken=this.moveToNextToken,o=this.processValue(n),o?.values.filter(c=>!!c).length||this._issues.push(Y(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([Fe(13),ot("d"),ot("ts"),Fe(16),ot("v"),ot("1")]);if(n.length!==6)return this.popStack(),!1;let r=n[0],i=r,s=new At;s.firstToken=r;let o=new fp(s);if(this.others.push(o),H(this.currentToken,13))i=this.moveToNextToken;else return s.lastToken=n.at(-1),this._issues.push(Y(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([Fe(13),ot("memreserve")]);if(n.length!==2)return this.popStack(),!1;let r=new At;r.firstToken=n[0];let s=n[0];H(this.currentToken,13)?(s=this.moveToNextToken,r.lastToken=s):(r.lastToken=n.at(-1),this._issues.push(Y(21,r.firstToken,r.lastToken,r)));let o=this.processHex()||this.processDec(),a=o&&(this.processHex()||this.processDec()),c=new pp(r,o,a);if(this.others.push(c),o||this._issues.push(Y(37,r.firstToken,r.lastToken,r)),!a){let l=o??r;this._issues.push(Y(38,l.firstToken,l.lastToken,c))}return c.lastToken=this.endStatement(c),this.mergeStack(),!0}isPlugin(){this.enqueueToStack();let n=this.checkConcurrentTokens([Fe(13),ot("plugin"),Fe(13)]);if(n.length!==3)return this.popStack(),!1;let r=new At(he(n[0],n.at(-1)));return r.lastToken=this.endStatement(r),this.mergeStack(),this.others.push(r),this.plugin=!0,!0}processBits(){this.enqueueToStack();let n=this.checkConcurrentTokens([Fe(13),ot("b"),ot("its")]);if(n.length!==3){this.popStack();return}let r=new At;r.firstToken=n[0];let s=n[0];H(this.currentToken,13)?(s=this.moveToNextToken,r.lastToken=s):(r.lastToken=n.at(-1),this._issues.push(Y(21,r.firstToken,r.lastToken,r)));let o=this.processDec(),a=new hp(r,o);return this.others.push(a),o?o.value!==8&&o.value!==16&&o.value!==32&&o.value!==64&&this._issues.push(Y(40,o.firstToken,o.lastToken,o)):this._issues.push(Y(39,r.firstToken,r.lastToken,r)),this._issues.push(Y(41,a.firstToken,a.lastToken,a,{severity:ol.DiagnosticSeverity.Warning})),this.mergeStack(),a}isOmitIfNoRefNode(){this.enqueueToStack();let n=this.checkConcurrentTokens([Fe(13),ot("omit"),Fe(16),ot("if"),Fe(16),ot("no"),Fe(16),ot("ref"),Fe(13)]);if(n.length!==9){this.popStack();return}let r=new At(he(n[0],n.at(-1)));return this.mergeStack(),r}isDeleteNode(n,r){this.enqueueToStack();let i=this.checkConcurrentTokens([Fe(13),ot("d"),ot("e"),ot("lete",{allowPartial:!0}),Fe(16),ot("node",{allowPartial:!0})]);if(!i.length)return this.popStack(),!1;let s=i[0],o=s,a=new At;if(a.firstToken=s,i.length===1&&!H(this.currentToken,2)){this._issues.push(Y(25,a.firstToken,a.lastToken,a)),a.lastToken=i.at(-1);let d=new Jn(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(Y(c.startsWith("/delete-n")?34:25,a.firstToken,a.lastToken,a)):H(this.currentToken,13)?(o=this.moveToNextToken,a.lastToken=o):this._issues.push(Y(21,a.firstToken,a.lastToken,a));let l=new Jn(a);if(mn(a.lastToken,s)){let d=this.processNodePathRef(n);d&&r==="Name"&&this._issues.push(Y(7,d.firstToken,d.lastToken,d));let f=d?void 0:this.isLabelRef(n);f&&r==="Name"&&this._issues.push(Y(7,f.firstToken,f.lastToken,f));let p=d||f?void 0:this.isNodeName();p&&r==="Ref"&&this._issues.push(Y(10,p.firstToken,p.lastToken,p)),!d&&!p&&!f&&this._issues.push(Y([7,10],l.firstToken,l.lastToken,l)),l.nodeNameOrRef=d??f??p??null}else r==="Name"?this._issues.push(Y(7,a.firstToken,a.lastToken,a)):r==="Ref"&&this._issues.push(Y(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([Fe(13),ot("d"),ot("e"),ot("lete",{allowPartial:!0}),Fe(16),ot("property",{allowPartial:!0})]);if(!r.length)return this.popStack(),!1;let i=r[0],s=i,o=new At;if(o.firstToken=i,r.length===1&&!H(this.currentToken,2)){this._issues.push(Y(25,o.firstToken,o.lastToken,o)),o.lastToken=r.at(-1);let u=new ut(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(Y(a.startsWith("/delete-p")?35:25,o.firstToken,o.lastToken,o)):H(this.currentToken,13)?(s=this.moveToNextToken,o.lastToken=s):this._issues.push(Y(21,o.firstToken,o.lastToken,o));let c=new ut(o);if(mn(o.lastToken,i)){let u=this.isPropertyName();u||this._issues.push(Y(6,c.firstToken,c.lastToken,c)),c.propertyName=u??null}else this._issues.push(Y(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 Ln(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(;!H(this.currentToken,1);){let l=this.prevToken,u=this.currentToken,d,f=H(this.currentToken,24);if(f)d=this.currentToken,this.moveToNextToken;else if(!mn(this.prevToken,this.currentToken))break;let p=o();if(u&&p===null&&f){let h=new te(he(u,this.currentToken));this._issues.push(Y(0,h.firstToken,h.lastToken,h))}if(!f&&p===null)break;if(l&&!f&&p){let h=new te(he(l));this._issues.push(Y(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 dp(i)}processStringValue(){this.enqueueToStack();let n=this.processOptionalLabelAssign(!0),r=this.consumeAnyConcurrentTokens([Fe(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(`
|
|
300
|
-
`),s=i,o=['"',"'"].some(u=>s.endsWith(u));o&&(s=s.slice(1,-1));let a=new re(s,he(r[0],r.at(-1)));o||this._issues.push(Y(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 Ln(n,a,c);return this.mergeStack(),l}arrayValues(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!0),i=this.processBits(),s=this.currentToken;if(H(s,5))this.moveToNextToken;else{this.popStack();return}let o=this.processArrayValues(n)??null;o.openBracket=s;let a=this.processOptionalLabelAssign(!0)??[],c=new Ln(r,o,a,i);if(!H(this.currentToken,4))this._issues.push(Y(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(!H(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(Y(15,u.firstToken,u.lastToken,u))});let a=new xn(s??[]);a.openBracket=i,a.values.length===0&&(a.firstToken=r,this._issues.push(Y(14,a.firstToken,a.lastToken,a,{severity:ol.DiagnosticSeverity.Information})));let c=new Ln(n,a,o);H(this.currentToken,12)?a.closeBracket=this.moveToNextToken:this._issues.push(Y(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 Gt&&a.value.params.every(c=>!!c)&&this.cPreprocessorParser.macros.has(a.value.functionName.name)||a.value instanceof Tt&&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 lt(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 Ni(i,r);return this.mergeStack(),s}processHexString(){this.enqueueToStack();let n=this.processOptionalLabelAssign(!1),r=this.checkConcurrentTokens([20,20].map(Fe));if(!r.length){this.popStack();return}let i=Number.parseInt(r.map(a=>a.value).join(""),16),s=new sn(i,he(r[0],r.at(-1)),16),o=new Ni(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 Ni(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 Ni(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 Ln(r,i,s);return this.mergeStack(),o}isLabelRef(n){this.enqueueToStack();let r=this.currentToken;if(!r||!H(r,40)){this.popStack();return}else this.moveToNextToken;let i=this.isLabelName();if(!i){let o=new ie(null);return this._issues.push(Y(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(Y(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 Ln(r,i,s);return this.mergeStack(),o}processRefValue(n,r){this.enqueueToStack();let i=this.processOptionalLabelAssign(r),s=this.currentToken;if(!s||!H(s,40)){this.popStack();return}let o=this.processNodePathRef(n);if(o!==void 0){let l=new Ni(o,i);return this.mergeStack(),l}let a=this.isLabelRef(n);if(a===void 0){this._issues.push(Y([18,9],s,s,n));let l=new Ni(null,i);return l.firstToken=i.at(0)?.firstToken??s,this.mergeStack(),l}let c=new Ni(a,i);return c.firstToken=i.at(0)?.firstToken??s,this.mergeStack(),c}processNodePath(n=!0,r=new Zr){this.enqueueToStack();let i;if(H(this.currentToken,13))i=this.moveToNextToken;else{if(!n){this.popStack();return}this.prevToken&&this._issues.push(Y(19,this.prevToken,this.prevToken,r))}let s=this.isNodeName(),o=i??this.prevToken;if(!s&&o&&!n&&this._issues.push(Y(7,o,o,r)),!n||s?r.addPath(s??null,i?new te(he(i)):void 0):n&&!s&&i&&(r.addPath(new $e("/",he(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(!H(i,40)){this.popStack();return}let s=this.moveToNextToken;if(i=s,!H(i,2)){this.popStack();return}r&&!Kt(r,s)&&this._issues.push(Y(29,r,s,n,{inclusiveStart:!1,inclusiveEnd:!1}));let o=this.processNodePath(),a=new rt(o??null),c=this.currentToken??this.prevToken,l=c;return o?.children.forEach((u,d)=>{if(d===o?.children.length-1&&u&&l&&!Kt(u.lastToken,l)){this._issues.push(Y(29,u.lastToken,l,n,{inclusiveStart:!1,inclusiveEnd:!1}));return}if(d===0&&s&&!Kt(s,u?.firstToken)){this._issues.push(Y(29,s,u?.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}));return}let f=o?.children[d+1];u&&f&&!Kt(u.lastToken,f.firstToken)&&this._issues.push(Y(29,u.lastToken,f?.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}))}),H(c,3)?this.moveToNextToken:this.prevToken&&this._issues.push(Y(3,this.prevToken,this.prevToken,n)),a.firstToken=r,a.lastToken=c??this.prevToken,this.mergeStack(),a}get includes(){return this.cPreprocessorParser.dtsIncludes}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)=>Gi.push(...o,r,i))}),super.buildSemanticTokens(n,r,i),this.#e=!0}};var mp=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={...e,ctxName:e.ctxName??(0,Pa.basename)(e.dtsFile)};this.isFullContext=this.settings.dtsFile.toLowerCase().endsWith(".dts"),this.overlays=i.overlays,this.overlays.filter(al.existsSync);let s=this.isFullContext&&r?.type==="Zephyr"?[(0,Pa.join)((0,Pa.dirname)(this.settings.dtsFile),"dts"),...i.includePaths]:i.includePaths;this.parser=new Ar(i.dtsFile,s),this.ctxNames_.add(i.ctxName),this.id=zi(i),this.parser.stable.then(()=>{this.overlayParsers=this.overlays?.map(o=>new Ar(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]}getFileTree(){let e=new Map,n=r=>({fsPath:r,includes:(e.get(r)??[]).map(i=>n(i.resolvedPath??i.path))});return[...this.parser.includes,...this.overlayParsers.flatMap(r=>r.includes)].forEach(r=>{let i=e.get(r.fsPath);i||(i=[],e.set(r.fsPath,i)),i.push({path:r.path.path,resolvedPath:r.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=>fe(n,e))}getFsPathParser(e){return this.allParsers.find(r=>r.getFiles().some(i=>fe(i,e)))}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=>fe(s.ast.fsPath,e)&&s.ast.values&&(!n||Qt(s.ast.values,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&&c.bindingsPath?{range:ce(o.value),target:ue(c.bindingsPath)}:void 0})).filter(s=>!!s)??[];return[...[...this.parser.cPreprocessorParser.dtsIncludes,...this.overlayParsers.flatMap(s=>s.cPreprocessorParser.dtsIncludes)].filter(s=>fe(s.fsPath,e)&&(!n||Qt(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(Bt(3,o.firstToken,o.lastToken,o,{templateStrings:[o.value],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error}))}else o instanceof Zr&&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(Bt(8,a.firstToken,a.lastToken,a,{templateStrings:[a.toString(),`${e.pathParts.filter(l=>l?.linksTo).map(l=>l?.toString()).join("/")}`],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error}))),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,n=!1){if(e)return this.sortKeys.get(n?e.lastToken:e.firstToken)}async evaluate(){let e=performance.now();await this.stable();let n=new ki(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 tr(i.text,i.fsPath),o=new Ar(i.fsPath,[],void 0,()=>s.tokens);return await o.stable,this.processRoot(o.rootDocument,n),o}));return n.comments=this.parser.cPreprocessorParser.allAstItems.filter(i=>i instanceof gr),[...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.allParsers.flatMap(i=>({parser:i,tokens:i.tokens}));for(let[i,s]of r.entries()){if(s.tokens.length===0&&fe(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)=>Ts(c,n,e)&&(l===s.tokens.length-1||!c.nextToken||ST(c.nextToken,n,e)));if(o)return o;let a=s.parser.includes.find(c=>c.resolvedPath===n);if(a)return a.lastToken;if(s.parser.getFiles().some(c=>fe(c,n)))return s.tokens[s.tokens.length-1]}}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(Bt(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 Ee?this.processDtcBaseNode(e,n,r):e instanceof Ne?this.processDtcProperty(e,n,r):e instanceof Jn?this.processDeleteNode(e,n,r):e instanceof ut&&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||qt(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 we&&o.name){let a=r(s.map(c=>({name:c.name,address:c.fullAddress,issueAst:c})),o.name);a.length&&this._issues.push(Bt(2,o.name.firstToken,o.name.lastToken,o.name,{linkedTo:a})),s.push(o.name)}else if(o instanceof Jn&&o.nodeNameOrRef instanceof $e){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,al.existsSync)(this.settings.compileCommands)))return JSON.parse((0,al.readFileSync)(this.settings.compileCommands).toString())}processDtcBaseNode(e,n,r){e instanceof nt?this.processDtcRootNode(e,r):e instanceof we?this.processDtcChildNode(e,n,r):e instanceof st&&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(Bt(3,n.firstToken,n.lastToken,n,{templateStrings:[n.label?.value??""],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error})),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 Je(e,n)),e.children.forEach(i=>this.processChild(i,n,r))}processDeleteNode(e,n,r){if(e.nodeNameOrRef instanceof $e&&e.nodeNameOrRef.value){if(e.parentNode?.parentNode)if(!n.hasNode(e.nodeNameOrRef.name,e.nodeNameOrRef.fullAddress))this._issues.push(Bt(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 Ee&&!e.parentNode.pathName&&r.globalDeletes.push(e)):(r.unlinkedDeletes.push(e),this._issues.push(Bt(3,e.nodeNameOrRef.firstToken,e.nodeNameOrRef.lastToken,e.nodeNameOrRef,{templateStrings:[e.nodeNameOrRef.value],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error})))}else if(e.nodeNameOrRef instanceof rt&&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(Bt(8,o.firstToken,o.lastToken,o,{templateStrings:[o.toString(),`${e.nodeNameOrRef.path.pathParts.filter(c=>c?.linksTo).map(c=>c?.toString()).join("/")}`],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error}))),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 Ee&&!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(Bt(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===yn.DiagnosticSeverity.Hint&&i.raw.virtual))return i.raw.severity===yn.DiagnosticSeverity.Error&&!this.isFullContext&&(i.raw.severity=yn.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===yn.DiagnosticSeverity.Error&&!this.isFullContext&&!uo(r.raw,r.raw.fsPath,!1)&&(r.raw.severity=yn.DiagnosticSeverity.Warning),!(r.raw.severity===yn.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/;
|
|
300
|
+
`),s=i,o=['"',"'"].some(u=>s.endsWith(u));o&&(s=s.slice(1,-1));let a=new re(s,he(r[0],r.at(-1)));o||this._issues.push(Y(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 Ln(n,a,c);return this.mergeStack(),l}arrayValues(n){this.enqueueToStack();let r=this.processOptionalLabelAssign(!0),i=this.processBits(),s=this.currentToken;if(H(s,5))this.moveToNextToken;else{this.popStack();return}let o=this.processArrayValues(n)??null;o.openBracket=s;let a=this.processOptionalLabelAssign(!0)??[],c=new Ln(r,o,a,i);if(!H(this.currentToken,4))this._issues.push(Y(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(!H(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(Y(15,u.firstToken,u.lastToken,u))});let a=new xn(s??[]);a.openBracket=i,a.values.length===0&&(a.firstToken=r,this._issues.push(Y(14,a.firstToken,a.lastToken,a,{severity:ol.DiagnosticSeverity.Information})));let c=new Ln(n,a,o);H(this.currentToken,12)?a.closeBracket=this.moveToNextToken:this._issues.push(Y(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 Gt&&a.value.params.every(c=>!!c)&&this.cPreprocessorParser.macros.has(a.value.functionName.name)||a.value instanceof Tt&&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 lt(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 Ni(i,r);return this.mergeStack(),s}processHexString(){this.enqueueToStack();let n=this.processOptionalLabelAssign(!1),r=this.checkConcurrentTokens([20,20].map(Fe));if(!r.length){this.popStack();return}let i=Number.parseInt(r.map(a=>a.value).join(""),16),s=new sn(i,he(r[0],r.at(-1)),16),o=new Ni(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 Ni(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 Ni(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 Ln(r,i,s);return this.mergeStack(),o}isLabelRef(n){this.enqueueToStack();let r=this.currentToken;if(!r||!H(r,40)){this.popStack();return}else this.moveToNextToken;let i=this.isLabelName();if(!i){let o=new ie(null);return this._issues.push(Y(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(Y(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 Ln(r,i,s);return this.mergeStack(),o}processRefValue(n,r){this.enqueueToStack();let i=this.processOptionalLabelAssign(r),s=this.currentToken;if(!s||!H(s,40)){this.popStack();return}let o=this.processNodePathRef(n);if(o!==void 0){let l=new Ni(o,i);return this.mergeStack(),l}let a=this.isLabelRef(n);if(a===void 0){this._issues.push(Y([18,9],s,s,n));let l=new Ni(null,i);return l.firstToken=i.at(0)?.firstToken??s,this.mergeStack(),l}let c=new Ni(a,i);return c.firstToken=i.at(0)?.firstToken??s,this.mergeStack(),c}processNodePath(n=!0,r=new Zr){this.enqueueToStack();let i;if(H(this.currentToken,13))i=this.moveToNextToken;else{if(!n){this.popStack();return}this.prevToken&&this._issues.push(Y(19,this.prevToken,this.prevToken,r))}let s=this.isNodeName(),o=i??this.prevToken;if(!s&&o&&!n&&this._issues.push(Y(7,o,o,r)),!n||s?r.addPath(s??null,i?new te(he(i)):void 0):n&&!s&&i&&(r.addPath(new $e("/",he(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(!H(i,40)){this.popStack();return}let s=this.moveToNextToken;if(i=s,!H(i,2)){this.popStack();return}r&&!Kt(r,s)&&this._issues.push(Y(29,r,s,n,{inclusiveStart:!1,inclusiveEnd:!1}));let o=this.processNodePath(),a=new rt(o??null),c=this.currentToken??this.prevToken,l=c;return o?.children.forEach((u,d)=>{if(d===o?.children.length-1&&u&&l&&!Kt(u.lastToken,l)){this._issues.push(Y(29,u.lastToken,l,n,{inclusiveStart:!1,inclusiveEnd:!1}));return}if(d===0&&s&&!Kt(s,u?.firstToken)){this._issues.push(Y(29,s,u?.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}));return}let f=o?.children[d+1];u&&f&&!Kt(u.lastToken,f.firstToken)&&this._issues.push(Y(29,u.lastToken,f?.firstToken,n,{inclusiveStart:!1,inclusiveEnd:!1}))}),H(c,3)?this.moveToNextToken:this.prevToken&&this._issues.push(Y(3,this.prevToken,this.prevToken,n)),a.firstToken=r,a.lastToken=c??this.prevToken,this.mergeStack(),a}get includes(){return this.cPreprocessorParser.dtsIncludes}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)=>Gi.push(...o,r,i))}),super.buildSemanticTokens(n,r,i),this.#e=!0}};var mp=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={...e,ctxName:e.ctxName??(0,Pa.basename)(e.dtsFile)};this.isFullContext=this.settings.dtsFile.toLowerCase().endsWith(".dts"),this.overlays=i.overlays,this.overlays.filter(al.existsSync);let s=this.isFullContext&&r?.type==="Zephyr"?[(0,Pa.join)((0,Pa.dirname)(this.settings.dtsFile),"dts"),...i.includePaths]:i.includePaths;this.parser=new Ar(i.dtsFile,s),this.ctxNames_.add(i.ctxName),this.id=zi(i),this.parser.stable.then(()=>{this.overlayParsers=this.overlays?.map(o=>new Ar(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]}getFileTree(){let e=new Map,n=r=>({fsPath:r,includes:(e.get(r)??[]).map(i=>n(i.resolvedPath??i.path))});return[...this.parser.includes,...this.overlayParsers.flatMap(r=>r.includes)].forEach(r=>{let i=e.get(r.fsPath);i||(i=[],e.set(r.fsPath,i)),i.push({path:r.path.path,resolvedPath:r.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=>fe(n,e))}getFsPathParser(e){return this.allParsers.find(r=>r.getFiles().some(i=>fe(i,e)))}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=>fe(s.ast.fsPath,e)&&s.ast.values&&(!n||Qt(s.ast.values,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&&c.bindingsPath?{range:ce(o.value),target:ue(c.bindingsPath)}:void 0})).filter(s=>!!s)??[];return[...[...this.parser.cPreprocessorParser.dtsIncludes,...this.overlayParsers.flatMap(s=>s.cPreprocessorParser.dtsIncludes)].filter(s=>fe(s.fsPath,e)&&(!n||Qt(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(Bt(3,o.firstToken,o.lastToken,o,{templateStrings:[o.value],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error}))}else o instanceof Zr&&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(Bt(8,a.firstToken,a.lastToken,a,{templateStrings:[a.toString(),`${e.pathParts.filter(l=>l?.linksTo).map(l=>l?.toString()).join("/")}`],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error}))),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,n=!1){if(e)return this.sortKeys.get(n?e.lastToken:e.firstToken)}async evaluate(){let e=performance.now();await this.stable();let n=new ki(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 tr(i.text,i.fsPath),o=new Ar(i.fsPath,[],void 0,()=>s.tokens);return await o.stable,this.processRoot(o.rootDocument,n),o}));return n.comments=this.parser.cPreprocessorParser.allAstItems.filter(i=>i instanceof gr),[...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.allParsers.flatMap(i=>({parser:i,tokens:i.tokens}));for(let[i,s]of r.entries()){if(s.tokens.length===0&&fe(s.parser.fsPath,n)){let c=r.slice(0,i).reverse().find(l=>l.tokens.length);return i?c?.tokens[c.tokens.length-1]:void 0}let o=s.tokens.find((c,l)=>Ts(c,n,e)&&(l===s.tokens.length-1||!c.nextToken||ST(c.nextToken,n,e)));if(o)return o;let a=s.parser.includes.find(c=>c.resolvedPath===n);if(a)return a.lastToken;if(s.parser.getFiles().some(c=>fe(c,n)))return s.tokens[s.tokens.length-1]}}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(Bt(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 Ee?this.processDtcBaseNode(e,n,r):e instanceof Ne?this.processDtcProperty(e,n,r):e instanceof Jn?this.processDeleteNode(e,n,r):e instanceof ut&&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||qt(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 we&&o.name){let a=r(s.map(c=>({name:c.name,address:c.fullAddress,issueAst:c})),o.name);a.length&&this._issues.push(Bt(2,o.name.firstToken,o.name.lastToken,o.name,{linkedTo:a})),s.push(o.name)}else if(o instanceof Jn&&o.nodeNameOrRef instanceof $e){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,al.existsSync)(this.settings.compileCommands)))return JSON.parse((0,al.readFileSync)(this.settings.compileCommands).toString())}processDtcBaseNode(e,n,r){e instanceof nt?this.processDtcRootNode(e,r):e instanceof we?this.processDtcChildNode(e,n,r):e instanceof st&&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(Bt(3,n.firstToken,n.lastToken,n,{templateStrings:[n.label?.value??""],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error})),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 Je(e,n)),e.children.forEach(i=>this.processChild(i,n,r))}processDeleteNode(e,n,r){if(e.nodeNameOrRef instanceof $e&&e.nodeNameOrRef.value){if(e.parentNode?.parentNode)if(!n.hasNode(e.nodeNameOrRef.name,e.nodeNameOrRef.fullAddress))this._issues.push(Bt(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 Ee&&!e.parentNode.pathName&&r.globalDeletes.push(e)):(r.unlinkedDeletes.push(e),this._issues.push(Bt(3,e.nodeNameOrRef.firstToken,e.nodeNameOrRef.lastToken,e.nodeNameOrRef,{templateStrings:[e.nodeNameOrRef.value],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error})))}else if(e.nodeNameOrRef instanceof rt&&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(Bt(8,o.firstToken,o.lastToken,o,{templateStrings:[o.toString(),`${e.nodeNameOrRef.path.pathParts.filter(c=>c?.linksTo).map(c=>c?.toString()).join("/")}`],severity:this.parser.plugin?yn.DiagnosticSeverity.Information:yn.DiagnosticSeverity.Error}))),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 Ee&&!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(Bt(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===yn.DiagnosticSeverity.Hint&&i.raw.virtual))return i.raw.severity===yn.DiagnosticSeverity.Error&&!this.isFullContext&&(i.raw.severity=yn.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===yn.DiagnosticSeverity.Error&&!this.isFullContext&&!uo(r.raw,r.raw.fsPath,!1)&&(r.raw.severity=yn.DiagnosticSeverity.Warning),!(r.raw.severity===yn.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/;
|
|
301
301
|
|
|
302
302
|
${(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 VD=require("fs"),ka=require("path"),It=L(U());function SH(t){if(!t||!(t.ast instanceof va))return[];let e=r=>r.flatMap(i=>{try{return(0,VD.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:It.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 gp=(t,e)=>[...t.labels.filter(e),...t.deletedNodes.filter(n=>!e(n.by)).flatMap(n=>gp(n.node,e)),...t.nodes.flatMap(n=>gp(n,e))],XT=(t,e)=>[...t.labels,...t.deletedNodes.filter(n=>!e(n.by)).flatMap(n=>XT(n.node,e)),...t.nodes.flatMap(n=>XT(n,e))];function PH(t,e){if(!t||!(t.item instanceof Je)||!(t.ast instanceof ie))return[];let n=i=>XT(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:It.CompletionItemKind.Method,documentation:i.lastLinkedTo?.toMarkupContent(t.runtime.context.macros)}))}function kH(t,e){if(!t||t.item!==null||!(t.ast instanceof ie)||!(t.ast.parentNode instanceof st))return[];let n=r=>gp(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} {
|
|
303
303
|
$1
|
|
@@ -347,4 +347,4 @@ ${r}`]})]},IQ=(t,e)=>HF(t,e.split("/").filter(n=>n)),HF=(t,e)=>{if(e.length===0)
|
|
|
347
347
|
`).length-1,o=i.lastIndexOf(`
|
|
348
348
|
`),a=o===-1?r+1:r-o,c=a+n[0].length;return Mn.Range.create(Mn.Position.create(s,a),Mn.Position.create(s,c))}var Tc=require("fs");var jQ=(t,e)=>{let n=(0,Tc.readFileSync)(t).toString();if(qn().needsRenew(t,n))qn().renewLexer(t,n),e(t);else return console.log("file changed event has the same text, skipping.",t)},hg=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}jQ(e,n)},(0,Tc.watchFile)(e,this.onChange)}}unwatch(){this.count===1&&(console.log("dispose watch for",this.file),(0,Tc.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 Vt=L(require("path")),SP=require("fs");var mi=t=>{if(t)return Array.isArray(t)?t:[t]},UQ=t=>({...t,deviceOrgBindingsMetaSchema:mi(t.deviceOrgBindingsMetaSchema),deviceOrgTreeBindings:mi(t.deviceOrgTreeBindings),includePaths:mi(t.includePaths),lockRenameEdits:mi(t.lockRenameEdits),zephyrBindings:mi(t.zephyrBindings),overlays:mi(t.overlays)}),lB=t=>({...t,defaultDeviceOrgBindingsMetaSchema:mi(t.defaultDeviceOrgBindingsMetaSchema),defaultDeviceOrgTreeBindings:mi(t.defaultDeviceOrgTreeBindings),defaultIncludePaths:mi(t.defaultIncludePaths),defaultLockRenameEdits:mi(t.defaultLockRenameEdits),defaultZephyrBindings:mi(t.defaultZephyrBindings),contexts:t.contexts?.map(UQ)}),Hr=async(t,e=[],n)=>{let r=n?e.map(s=>Se(s.uri)).sort((s,o)=>s.split(Vt.sep).length-o.split(Vt.sep).length).find(s=>Rw(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},Ks={defaultBindingType:"Zephyr",defaultZephyrBindings:[],defaultIncludePaths:[],defaultDeviceOrgBindingsMetaSchema:[],defaultDeviceOrgTreeBindings:[],contexts:[],defaultLockRenameEdits:[],allowAdhocContexts:!0,autoChangeContext:!0,defaultShowFormattingErrorAsDiagnostics:!0,disableFileWatchers:!1,autoAddMissingPropertiesOnCompletion:!0},PP=async(t,e,n)=>{let r=await Hr(t.cwd??"${workspaceFolder}",n,t.dtsFile)??e.cwd,i=await Promise.all((t.includePaths??e.defaultIncludePaths).map(p=>Hr(p,n,t.dtsFile))),s=await Promise.all((t.zephyrBindings??e.defaultZephyrBindings).map(p=>Hr(p,n,t.dtsFile))),o=t.bindingType??e.defaultBindingType,a=await Promise.all((t.deviceOrgTreeBindings??e.defaultDeviceOrgTreeBindings).map(p=>Hr(p,n,t.dtsFile))),c=await Promise.all((t.deviceOrgBindingsMetaSchema??e.defaultDeviceOrgBindingsMetaSchema).map(p=>Hr(p,n,t.dtsFile))),l=await Promise.all((t.lockRenameEdits??e.defaultLockRenameEdits).map(p=>Hr(p,n,t.dtsFile)));if(r&&o==="Zephyr"&&(!s||s.length===0)&&(s=["./zephyr/dts/bindings"]),!t.dtsFile){console.log("Context is missing dtsFile, skipping...");return}let u=t.dtsFile,d=t.overlays??[],f=t.compileCommands;return r&&(s=s.map(p=>(0,Vt.resolve)(r,p)).filter(p=>(0,SP.existsSync)(p)),a=a?.map(p=>(0,Vt.resolve)(r,p)),c=c.map(p=>(0,Vt.resolve)(r,p)),i=i.map(p=>(0,Vt.resolve)(r,p)),u=(0,Vt.resolve)(r,u),d=d.map(p=>(0,Vt.resolve)(r,p)),l=l.map(p=>(0,Vt.resolve)(r,p)),f=f?(0,Vt.resolve)(r,f):void 0),{ctxName:t.ctxName??(0,Vt.basename)(u),cwd:r?dt(r):void 0,includePaths:i.map(dt),zephyrBindings:s.map(dt),bindingType:o,deviceOrgTreeBindings:a.map(dt),deviceOrgBindingsMetaSchema:c.map(dt),dtsFile:dt(u),overlays:d.map(dt),lockRenameEdits:l.map(dt),compileCommands:f?dt(f):void 0,showFormattingErrorAsDiagnostics:t.showFormattingErrorAsDiagnostics??e.defaultShowFormattingErrorAsDiagnostics,disableFileWatchers:t.disableFileWatchers??e.disableFileWatchers,autoAddMissingPropertiesOnCompletion:t.autoAddMissingPropertiesOnCompletion??e.autoAddMissingPropertiesOnCompletion}},Gu=async(t,e)=>{let n=t.cwd?await Hr(t.cwd,e):void 0,r=t.defaultBindingType,i=t.defaultDeviceOrgBindingsMetaSchema=await Promise.all((t.defaultDeviceOrgBindingsMetaSchema??[]).map(d=>Hr(d,e))),s=t.defaultDeviceOrgTreeBindings=await Promise.all((t.defaultDeviceOrgTreeBindings??[]).map(d=>Hr(d,e))),o=t.defaultIncludePaths=await Promise.all((t.defaultIncludePaths??[]).map(d=>Hr(d,e))),a=t.defaultZephyrBindings=await Promise.all((t.defaultZephyrBindings??[]).map(d=>Hr(d,e))),c=t.defaultLockRenameEdits=await Promise.all((t.defaultLockRenameEdits??[]).map(d=>Hr(d,e)));n&&(o=t.defaultIncludePaths=(t.defaultIncludePaths??[]).map(d=>(0,Vt.resolve)(n,d)),r==="Zephyr"&&!t.defaultZephyrBindings&&(a=["./zephyr/dts/bindings"]),a=a.map(d=>(0,Vt.resolve)(n,d)),i=i.map(d=>(0,Vt.resolve)(n,d)),s=(t.defaultDeviceOrgTreeBindings??[]).map(d=>(0,Vt.resolve)(n,d)),c=c.map(d=>(0,Vt.resolve)(n,d)));let l={cwd:n,defaultDeviceOrgBindingsMetaSchema:i,defaultDeviceOrgTreeBindings:s,defaultIncludePaths:o,defaultZephyrBindings:a,defaultLockRenameEdits:c,defaultBindingType:r,autoChangeContext:t.autoChangeContext??Ks.autoChangeContext,allowAdhocContexts:t.allowAdhocContexts??Ks.allowAdhocContexts,defaultShowFormattingErrorAsDiagnostics:t.defaultShowFormattingErrorAsDiagnostics??Ks.defaultShowFormattingErrorAsDiagnostics,disableFileWatchers:t.disableFileWatchers??!1,autoAddMissingPropertiesOnCompletion:t.autoAddMissingPropertiesOnCompletion??!0},u=(await Promise.all(t.contexts?.map(d=>PP(d,l,e))??[])).filter(d=>!!d).filter(d=>[d.dtsFile,...d.overlays].every(f=>(0,SP.existsSync)(f)&&Vt.default.isAbsolute(f)));return{...l,contexts:u}};var uB=t=>`DT_PROP(${kP(t.parent)}, ${t.name.replaceAll("-","_")}))`,dB=t=>t.parent.labels.map(e=>`DT_PROP(DT_NODELABEL(${e.label.toString()}), ${t.name.replaceAll("-","_")})`);var kP=t=>`DT_PATH(${t.path.slice(1).map(e=>e.replace("@","_").replaceAll("-","_")).join(",")})`,fB=t=>t.labels.map(e=>`DT_NODELABEL(${e.label.toString()})`),pB=t=>{let e=[];return ki.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 rt&&s.path?.pathParts.at(-1)?.linksTo===t)return!0})?.forEach(i=>e.push(`DT_ALIAS(${i.name.replaceAll("-","_")})`)),e};function HQ(t,e){if(!t||!(t.item instanceof Je)||!(t.ast instanceof Xe))return[];let n=[];return e.settings.bindingType==="Zephyr"&&(n.push({type:"dt_zephyr_macro_prop_node_path",data:uB(t.item)}),dB(t.item).forEach(r=>{n.push({type:"dt_zephyr_macro_prop_node_label",data:r})})),n}function VQ(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 $e&&t.ast.linksTo&&(n=t.ast.linksTo),!n)return[];let r=[{type:"path",data:n.pathString}];return e.settings.bindingType==="Zephyr"&&(fB(n).forEach(i=>{r.push({type:"dt_zephyr_macro_node_label",data:i})}),r.push({type:"dt_zephyr_macro_node_path",data:kP(n)}),pB(n).forEach(i=>{r.push({type:"dt_zephyr_macro_prop_node_alias",data:i})})),r}async function hB(t,e){return e?Rt(t,e,n=>[...VQ(n,e),...HQ(n,e)]):[]}var mB=L(U());function WQ(t){return!t||!(t.item instanceof Je)?void 0:t.item.parent.nodeType?.getSignatureHelp?.(t.item,t.ast,t.beforeAst,t.afterAst)}async function zQ(t){let e=zc(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 ti))return;let i=r.params.map(o=>({label:o instanceof Tt?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:[mB.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 gB(t,e){if(e)return(await Rt(t,e,async n=>[await zQ(n)||WQ(n)])).at(0)}var yB=require("timers"),TB=require("events");var NP=class extends TB.EventEmitter{constructor(e=3e3,n=1e3){super(),this.thresholdBytes=e*1024*1024,this.interval=(0,yB.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)}},GQ=new NP(3e3),vB=()=>{GQ.on("thresholdExceeded",({usedMb:t,thresholdMb:e})=>{console.warn(`[HeapMonitor] Heap usage exceeded ${e}MB: ${t}MB used`),$D(),qD()})};var bB=t=>`0x${t.map((e,n)=>e.toString(16).padStart(n?8:0,"0")).join("")}`;function _B(t,e){let n=e.nodePath,r=e.labels.at(0);e.disabled&&(r+=" <DISABLED>");let i=e.nodePath.split("/").pop()??e.nodePath,s=r?`${r} (${i})`:i,o=t.children.filter(a=>{let c=Jr(e.start,e.size),l=Jr(a.start,a.size),u=qt(e.start,a.start)>=0,d=qt(c,l)<=0,f=qt(e.start,a.start)===0&&qt(e.size,a.size)===0;return u&&d&&!f});if(o.length>0){for(let a of o)_B(a,e);return}t.children.push({name:s,start:e.start,size:e.size,children:[],path:n,disabled:e.disabled})}function YQ(t){let e={};for(let n of t){let r={name:n.name,children:[],path:n.path};for(let i of n.partitions)_B(r,i);e[n.name]=r}return e}function SB(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.length&&o.push(`start: ${bB(t.start)}`),"size"in t&&t.size.length&&o.push(`size: ${bB(t.size)}`);let a=o.length>0?`[${o.join(", ")}]`:"",c=t.name;i+=`${e}${s}${c} ${a}
|
|
349
349
|
`;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(b=>b.name))).join(", "),h={};p.forEach(b=>{b.children.forEach(v=>{let k=`${v.start}-${v.size}-${v.name}`;h[k]=v})});let y=Object.values(h),_={name:m,start:p[0].start,size:p[0].size,children:y,path:t.path};i+=SB(_,l,f===u.length-1)}),i}function PB(t){return YQ(t)}function kB(t){return Object.values(t).map(e=>SB(e)).join(`
|
|
350
|
-
`)}var Ie=[],le,Xs,gg=new WeakMap,Yu=new Map;vB();var Tg=new Map,RB=t=>{t.settings.disableFileWatchers||t.getContextFiles().forEach(e=>{Yu.has(e)||Yu.set(e,new hg(e,IP,()=>{let n=ed(e),r=Tg.get(e);return!n||r===void 0?!1:r!==n.version})),Yu.get(e)?.watch()})},CP=async t=>{let e=Ie.indexOf(t);if(e===-1)return;Xu(t,void 0,!0),gg.delete(t),console.log(`(ID: ${t.id}) cleaning Context for [${t.ctxNames.join(",")}]`);let n=await Js(t);if(J.sendNotification("devicetree/contextDeleted",{ctxNames:t.ctxNames.map(r=>r.toString()),id:t.id,...t.getFileTree(),settings:t.settings,active:le===t,type:n.type}),Ie.splice(e,1),await xP(),t===le&&(le=void 0,Ie.length)){let r=Xs?En(Ie,{fsPath:Xs}):void 0;r??=Ie[0],console.log("Active context was deleted. Forcing active to",r.id),await _n({id:r.id},!0)}t.settings.disableFileWatchers||t.getContextFiles().map(r=>{Yu.get(r)?.unwatch()}),setTimeout(async()=>{await Oe();let r=new Set(Ie.flatMap(i=>i.getContextFiles()));t.getContextFiles().map(i=>{r.has(i)||qn().reset(i)})},2e3),t.bindingLoader?.dispose()},KQ=t=>{let e=gg.get(t);if(!e?.abort.signal.aborted)return Promise.all([e?.promise,t.getRuntime()])},Oe=async()=>{await Promise.all(Ie.map(KQ))},DP=async(t,e)=>(await EB(e)).indexOf(t)!==-1,EB=async t=>{let e=await wB(t);return Ie.filter(n=>!e.some(r=>r===n))},wB=async t=>{let e=await wP(t);return Ie.filter(n=>e.contexts.find(r=>zi(r)===n.id))},XQ=async t=>{let e=await n8(t);return Ie.filter(n=>e.contexts.find(r=>zi(r)===n.id))},JQ=async(t,e)=>(await XQ(e)).indexOf(t)!==-1,QQ=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=>fe(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=>fe(i,t.parser.fsPath))},ZQ=async t=>{if(!await DP(t))return;let e=await EB(),n=await wB(),r=await jf(e);if(Ie.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 QQ(a.context,c)})))),s=t.getContextFiles(),o=r.filter(a=>i.some(c=>c.context===a.context&&c.same)||a.context!==t&&fe(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(CP))},J=(0,He.createConnection)(He.ProposedFeatures.all),un=new He.TextDocuments(Lt),AP=!1,yg=!1,CB=!1,DB=!1,AB=!1,RP;J.onInitialize(async t=>{RP=t.workspaceFolders??[],J.console.log(`[Server(${process.pid}) ${RP?.at(0)?.uri} Version 0.12.0 ] Started and initialize received`);let e=t.capabilities;AP=!!(e.workspace&&e.workspace.configuration),yg=!!(e.workspace&&e.workspace.workspaceFolders),CB=!!e.workspace?.diagnostics?.refreshSupport,DB=!!e.workspace?.semanticTokens?.refreshSupport,AB=!!e.workspace?.foldingRange?.refreshSupport;let n={capabilities:{typeDefinitionProvider:!0,workspaceSymbolProvider:!0,textDocumentSync:He.TextDocumentSyncKind.Incremental,renameProvider:{prepareProvider:!0},completionProvider:{resolveProvider:!0,triggerCharacters:["&","="," ",'"',"(",","]},codeActionProvider:{codeActionKinds:[He.CodeActionKind.QuickFix,He.CodeActionKind.SourceFixAll]},documentSymbolProvider:!0,semanticTokensProvider:{legend:{tokenTypes:Lf,tokenModifiers:qf},full:!0},documentLinkProvider:{resolveProvider:!1},foldingRangeProvider:!0,definitionProvider:!0,declarationProvider:!0,referencesProvider:!0,documentFormattingProvider:!0,documentRangeFormattingProvider:!0,hoverProvider:!0,signatureHelpProvider:{triggerCharacters:["<","("],retriggerCharacters:[" ",","]}}};return yg&&(n.capabilities.workspace={workspaceFolders:{changeNotifications:!0,supported:!0}}),await LB(t.initializationOptions),n});var EP,e8={tabSize:8,insertSpaces:!1,trimTrailingWhitespace:!0,insertFinalNewline:!0,wordWrapColumn:100},IB=t=>({tabSize:t?.["editor.tabSize"],insertSpaces:t?.["editor.insertSpaces"],trimFinalNewlines:t?.["files.trimFinalNewlines"],trimTrailingWhitespace:t?.["files.trimTrailingWhitespace"],insertFinalNewline:t?.["editor.insertFinalNewline"],wordWrapColumn:t?.["editor.wordWrapColumn"],removeMacroMultiline:t?.["editor.removeMacroMultiline"],wrapLongLines:t?.["editor.wrapLongLines"],indentExpressions:t?.["editor.indentExpressions"],removeEmptyReferences:t?.["editor.removeEmptyReferences"],removeEmptyNodes:t?.["editor.removeEmptyNodes"],removeEmptyRoots:t?.["editor.removeEmptyRoots"],sortNodesAndProperties:t?.["editor.sortNodesAndProperties"]});J.onInitialized(async()=>{if(AP&&(J.client.register(He.DidChangeConfigurationNotification.type,{}),!EP)){let t=await J.workspace.getConfiguration("editor").catch(()=>{}),e=await J.workspace.getConfiguration("files").catch(()=>{}),n=await J.workspace.getConfiguration("[devicetree]").catch(()=>{}),r=IB(n);(t||e||r)&&(EP={...t,...e,...r})}yg&&J.workspace.onDidChangeWorkspaceFolders(async t=>{J.console.log("Workspace folder change event received"),await Zu()})});J.onRequest("workspace/workspaceFolders",async()=>RP??null);var t8=async t=>{let e=OB();return e={...Ks,...e},Gu(e,t??await Qu())},wP=async t=>{let e=i8();return e={...Ks,...e},Gu(e,t??await Qu())},n8=async t=>{let e=s8();return e={...Ks,...e},Gu(e,t??await Qu())},Ju=async t=>{let e=r8();return e={...Ks,...e},Gu(e,t??await Qu())},Qu=async()=>yg?await J.workspace.getWorkspaceFolders()??[]:[],NB=async t=>{let e=En(Ie,{id:zi(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=zi(t);console.log(`(ID: ${n}) New context [${t.ctxName}]`),console.log(`(ID: ${n}) Settings: ${JSON.stringify(t,void 0," ")}`);let r=(0,bc.join)((0,bc.dirname)(t.dtsFile),"dts","bindings"),i=new mp(t,EP??e8,t.bindingType?rB({zephyrBindings:t.zephyrBindings?[r,...t.zephyrBindings]:[r],deviceOrgBindingsMetaSchema:t.deviceOrgBindingsMetaSchema??[],deviceOrgTreeBindings:t.deviceOrgTreeBindings??[]},t.bindingType):void 0);Ie.push(i);let s=performance.now();await i.stable(),console.log(`(ID: ${n}) New context took ${performance.now()-s}ms to start [${t.ctxName}]`),RB(i);let o=await Js(i);return J.sendNotification("devicetree/contextCreated",{ctxNames:i.ctxNames.map(a=>a.toString()),id:i.id,...i.getFileTree(),settings:i.settings,active:i===le,type:o.type}),await ZQ(i),await xP(),i},Zu=async()=>{let t=await wP(),e=await Ju();e.allowAdhocContexts||(e=await wP());let n=e.contexts.map(zi),r=Ie.filter(i=>!n.includes(i.id));await Promise.all(r.map(CP)),await t.contexts?.reduce((i,s)=>i.then(async()=>{await NB(s)}),Promise.resolve()),e.allowAdhocContexts&&await(await t8()).contexts?.reduce((s,o)=>s.then(async()=>{En(Ie,{fsPath:o.dtsFile})||await NB(o)}),Promise.resolve()),setTimeout(async()=>{Xs?await _n({fsPath:Xs}):!le&&Ie.length&&(console.log(`No active context using first context (ID: ${Ie[0].id}) [${Ie[0].ctxNames.join(",")}]`),await _n({id:Ie[0].id}))})},dr,is,Ku=new Map,vc=new Map,r8=()=>!is&&!dr?void 0:{...Object.fromEntries(Object.entries(is??{}).filter(([,n])=>n!==void 0)),...dr,contexts:[...dr?.contexts??[],...Array.from(vc.values()),...Array.from(Ku.values())]},OB=()=>!is&&!dr?void 0:{...is,...dr,contexts:[...Array.from(Ku.values())]},i8=()=>!is&&!dr?void 0:{...is,...dr,contexts:[...dr?.contexts??[],...Array.from(vc.values())]},s8=()=>!is&&!dr?void 0:{...dr,contexts:[...dr?.contexts??[]]};function o8(t){let e={...t};for(let n in e)e[n]===null&&delete e[n];return e}var MB=async()=>{let t=await Ju();console.log("Resolved settings",JSON.stringify(t,void 0," ")),J.sendNotification("devicetree/settingsChanged",t),await Zu(),Oe().then(()=>{CB&&J.languages.diagnostics.refresh()})},a8=async()=>{let t=le?.getContextFiles();await Promise.all(Array.from(un.keys()).filter(Et).map(async e=>{t?.some(n=>fe(n,Se(e)))||await J.sendDiagnostics({uri:e,version:un.get(e)?.version,diagnostics:[{severity:He.DiagnosticSeverity.Information,range:He.Range.create(He.Position.create(0,0),He.Position.create(0,0)),message:"File not in active context",source:"devicetree"}]})}))},IP=async t=>{let e=NT(Ie,t);if(e.length)e.sort((n,r)=>n===le?-1:r===le?1:0).forEach(n=>{gg.get(n)?.abort.abort(),le===n&&J.sendNotification("devicetree/activeContextBusyNotification",n.id),J.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?xB(n):[],l=n.getContextFiles();if(await n.reevaluate(t),RB(n),l.forEach(p=>Yu.get(p)?.unwatch()),a&&LP(n)?.length&&(OP(n).then(p=>{let m=p.items.map(h=>({uri:h.uri,version:h.version??void 0,diagnostics:h.items}));Xu(n,c.filter(h=>m.every(y=>y.uri!==h.uri))),m.forEach(h=>{J.sendDiagnostics(h)}),td.set(n,!0)}),Xs)){let p=n.getFsPathParser(Xs);p&&setTimeout(()=>{p.latestSemanticTokensBuilt||J.languages.semanticTokens.refresh()},50)}let u=await Js(n),d=n.getFileTree(),f={ctxNames:n.ctxNames.map(p=>p.toString()),id:n.id,...d,settings:n.settings,active:a,type:u.type};le===n&&J.sendNotification("devicetree/activeContextStableNotification",f),J.sendNotification("devicetree/contextStableNotification",f),s(),console.log("reevaluate",performance.now()-o)})});gg.set(n,{abort:r,promise:i})});else{if((await Ju()).allowAdhocContexts===!1)return;await Zu(),await _n({fsPath:t})}},c8=t=>un.keys().find(e=>fe(Se(e),t)),ed=t=>{let e=c8(t);if(e)return un.get(e)},xB=t=>t.getContextFiles().map(e=>({uri:ue(e),version:ed(e)?.version,diagnostics:[]})),td=new WeakMap,Xu=async(t,e=xB(t),n=!1)=>{if(!n&&t!==le)return;let r=performance.now();await Promise.all(e.filter(i=>t===le||!le?.getContextFiles().some(s=>fe(Se(i.uri),s))).map(i=>J.sendDiagnostics({uri:i.uri,version:un.get(i.uri)?.version,diagnostics:[]}))),td.delete(t),console.log(`(ID: ${t.id})`,"clear workspace diagnostics",`[${t.ctxNames.join(",")}]`,performance.now()-r)},mg=new Map,l8=async t=>{let e=mg.get(t);if(e||!AP)return e;mg.delete(t);let n=await J.workspace.getConfiguration({scopeUri:ue(t),section:"[devicetree]"}).catch(()=>{});if(n){let r=IB(n);return mg.set(t,r),r}},OP=async t=>{await t.stable();let e=performance.now(),n=await t.getDiagnostics(),r=await Promise.all(t.getContextFiles().map(async i=>{let s=ed(i),o=[];if(s&&t.settings.showFormattingErrorAsDiagnostics){let a=await l8(i);o.push(...(await wi({textDocument:s,options:{...t.formattingOptions,...a}},s.getText(),"File Diagnostics").catch(()=>[])).map(c=>c.diagnostic()))}return{uri:ue(i),kind:He.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]}},MP=async t=>{let{items:e}=await OP(t);e.map(n=>({uri:n.uri,version:n.version??void 0,diagnostics:n.items})).forEach(async n=>{J.sendDiagnostics(n)}),td.set(t,!0)},xP=async()=>{let t=await Promise.all(Ie.map(e=>Js(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("==============================")},Js=async(t,e)=>{let n=await DP(t,e),r=!n&&await JQ(t,e);return{ctx:t,type:n?"Ad Hoc":r?"User":"3rd Party"}},_n=async(t,e=!1)=>{if("fsPath"in t){if(!Et(t.fsPath))return!1;Xs=t.fsPath,console.log("Active File Uri",Xs)}let n=await Ju();if(le&&!e&&!n.autoChangeContext||(await Oe(),!e&&le?.getContextFiles().find(o=>"fsPath"in t&&fe(o,t.fsPath))))return!1;let r=le,i=En(Ie,t),s=r!==i;return s&&(r&&Xu(r),le=i,i?(Js(i).then(async o=>{let a=i.getFileTree();!i||i!==le&&!Ie.includes(i)||J.sendNotification("devicetree/newActiveContext",{ctxNames:i.ctxNames.map(c=>c.toString()),id:i.id,...a,settings:i.settings,active:le===i,type:o.type})}),LP(i)?.length&&MP(i),await xP()):J.sendNotification("devicetree/newActiveContext",void 0)),AB&&J.languages.foldingRange.refresh(),DB&&J.languages.semanticTokens.refresh(),s};un.listen(J);var LP=t=>t?.getContextFiles()?.filter(e=>ed(e));un.onDidSave(t=>{Tg.set(Se(t.document.uri),t.document.version)});un.onDidClose(async t=>{let e=Se(t.document.uri);if(!Et(e))return;Tg.delete(e);let n=NT(Ie,e);if(n.length===0){Ku.delete(e),J.sendDiagnostics({uri:t.document.uri,version:un.get(t.document.uri)?.version,diagnostics:[]});return}await Promise.all(n.map(async r=>{!!LP(r)?.filter(s=>s!==e).length?le?.getContextFiles().some(s=>fe(s,e))?le?.getContextFiles().some(s=>fe(s,e))&&(await Xu(le),await MP(le)):J.sendDiagnostics({uri:t.document.uri,version:un.get(t.document.uri)?.version,diagnostics:[]}):await DP(r)?(await CP(r),Ku.delete(r.settings.dtsFile)):Xu(r)}))});un.onDidOpen(async t=>{let e=Se(t.document.uri);if(!Et(e))return;Tg.set(e,t.document.version),await Oe(),a8();let n=En(Ie,{fsPath:e});if(console.log("onDidOpen",n?.id,e),n)n!==le?await _n({id:n.id}):n===le&&(!td.get(n)||n.getContextFiles().some(r=>!fe(r,e)))&&await MP(n);else{let r={ctxName:(0,bc.basename)(e),dtsFile:e};Ku.set(e,r),await IP(e)}});un.onDidChangeContent(async t=>{let e=Se(t.document.uri);if(!Et(e))return;let n=t.document.getText(),r=qn();r.needsRenew(e,n)&&(console.log("Content changed",e),r.renewLexer(e,n),await IP(e))});var LB=async t=>{t?.settings?.devicetree&&(dr=lB(o8(t.settings.devicetree)),dr=Object.fromEntries(Object.entries(dr??{}).filter(([,e])=>e!==void 0)),console.log("Configuration changed",JSON.stringify(t,void 0," ")),await MB())};J.onDidChangeConfiguration(async t=>{await LB(t)});J.listen();J.languages.diagnostics.onWorkspace(async()=>{await Oe();let t=le;return t?OP(t).finally(()=>{td.set(t,!0)}):{items:[]}});J.onDidChangeWatchedFiles(t=>{J.console.log("We received a file change event")});J.onCompletion(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return a0(t,le,un.get(t.textDocument.uri));if(!Et(e))return[];await Oe(),_n({fsPath:e});let n=Vn(e);return n?[...await WD(t,n),...await F0(t,n)]:[]});J.onCompletionResolve(t=>t);var Vn=t=>{let e=OB();return En(Ie,{fsPath:t},le,e?.preferredContext)};J.onDocumentSymbol(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return[];await Oe();let n=Vn(e);return n?n.getFsPathParser(e)?.getDocumentSymbols(e):[]});J.onWorkspaceSymbol(async()=>{await Oe();let t=le;return t?(await t.getAllStableParsers()).flatMap(e=>e.getWorkspaceSymbols()):[]});J.languages.semanticTokens.on(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return{data:[]};try{await Oe();let n=Vn(e),r=new He.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}});J.onDocumentLinks(async t=>{await Oe();let e=Se(t.textDocument.uri);return Et(e)?Vn(e)?.getDocumentLinks(e):e.endsWith(".yaml")&&le?le.bindingLoader?.getDocumentLinks?.(un.get(t.textDocument.uri))??[]:[]});J.onPrepareRename(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return p0(t,n)});J.onRenameRequest(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return f0(t,n)});J.onReferences(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return c0(t,n)});J.onDefinition(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return g0(t,le,un.get(t.textDocument.uri));if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e),r=(await n?.getDocumentLinks(e,t.position))?.filter(i=>i.target).map(i=>He.Location.create(i.target,i.range))??[];return r.length?r:m0(t,n)});J.onDeclaration(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return b0(t,le,un.get(t.textDocument.uri));if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return v0(t,n)});J.onCodeAction(async t=>{let e=Se(t.textDocument.uri);if(Et(e))return S0(t)});var qB=async t=>{if(!Et(t.textDocument.uri))return;let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);if(!n)return[];if((await n.getSyntaxIssues(void 0,l=>uo(l.raw,e,!1)?l:void 0)).get(e)?.length)return[];let i=un.get(t.textDocument.uri)??qn().getDocument(e),s=i.getText();mg.set(e,t.options);let o=await wi({...t,options:{...n.formattingOptions,...t.options}},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[He.TextEdit.replace(He.Range.create(He.Position.create(0,0),He.Position.create(i.lineCount,c)),o)]};J.onDocumentRangeFormatting(qB);J.onDocumentFormatting(qB);J.onHover(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return cM(t,le,un.get(t.textDocument.uri));if(!Et(e))return;await Oe();let n=Vn(e);return(await B0(t,n)).at(0)});J.onFoldingRanges(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe();let n=Vn(e),r=n?.isInContext(e);if(!n||!r)return[];let i=(await n.getAllStableParsers()).find(s=>s.getFiles().some(o=>o===e));return i?iB(e,i):[]});J.onTypeDefinition(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return cB(t,n)});J.onSignatureHelp(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return gB(t,n)});J.onRequest("devicetree/getContexts",async()=>(await Oe(),Promise.all(Ie.map(async t=>{let e=await Js(t);return{ctxNames:t.ctxNames.map(n=>n.toString()),id:t.id,...t.getFileTree(),settings:t.settings,active:le===t,type:e.type}}))));J.onRequest("devicetree/setActive",async t=>(await Oe(),console.log("devicetree/setActive",t),await _n(t,!0)));J.onRequest("devicetree/getActiveContext",async()=>{if(await Oe(),console.log("devicetree/getActiveContext"),!le)return;let t=await Js(le);return le?{ctxNames:le.ctxNames.map(e=>e.toString()),id:le.id,...le.getFileTree(),settings:le.settings,active:!0,type:t.type}:void 0});J.onRequest("devicetree/setDefaultSettings",async t=>{await Oe(),is=Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!==void 0)),console.log("Integration Settings",is),await MB()});J.onRequest("devicetree/requestContext",async t=>{await Oe();let e=await Qu(),n=await Ju(e),r=await PP(t,n,e);if(!r)throw console.log("Failed to resolve context",t),new Error("Failed to resolve context");console.log("devicetree/requestContext",r);let i=zi(r),s=Array.from(vc).find(([,c])=>c.ctxName===t.ctxName);if(s){let c=s[0].split(":",1)[0];En(Ie,{name:r.ctxName.toString()})?.removeCtxName(r.ctxName),console.log(`Removing integration context with ID ${c} and name ${t.ctxName}`),vc.delete(s[0])}vc.set(`${i}:${t.ctxName}`,t),await Zu();let o=Ie.find(c=>c.id===i);if(!o)throw new Error("Failed to create context");let a=await Js(o,e);return{ctxNames:o.ctxNames.map(c=>c.toString()),id:i,...o.getFileTree(),settings:o.settings,active:!0,type:a.type}});J.onRequest("devicetree/removeContext",async({id:t,name:e})=>{await Oe(),vc.delete(`${t}:${e}`);let n=En(Ie,{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 Zu()}});J.onRequest("devicetree/compiledDtsOutput",async t=>{if(await Oe(),!t)return;let e=En(Ie,{id:t});if(!e||!e.settings.dtsFile){console.log("Context or DTS file not found for ID",t);return}let n=await e.toFullString();return wi({textDocument:{uri:ue(e.settings.dtsFile)},options:e.formattingOptions},n,"New Text").catch(()=>n)});J.onRequest("devicetree/serializedContext",async t=>{if(await Oe(),!t)return;let e=En(Ie,{id:t}),n=performance.now();return e?.serialize().finally(()=>{console.info("serializedContext",performance.now()-n)})});J.onRequest("devicetree/activePath",async t=>{if(await Oe(),!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 Rt(t,le,n=>[e(n)])).at(0)});J.onRequest("devicetree/customActions",async t=>(await Oe(),hB(t,le)));J.onRequest("devicetree/activeFsPath",async t=>{await Oe(),_n({fsPath:t})});J.onRequest("devicetree/formattingText",async t=>{let e=Se(t.textDocument.uri),n=ed(e)??qn().getDocument(e,t.text),r=await wi(t,n.getText(),"New Text");return{text:r,diagnostics:(await wi(t,n.getText(),"File Diagnostics")).map(i=>i.diagnostic()),nonActionableDiagnostics:(await wi(t,r,"File Diagnostics")).map(i=>i.diagnostic())}});J.onRequest("devicetree/formatTextEdits",async t=>{await Oe();let e=qn().getDocument(Se(t.textDocument.uri),t.text),n=e.positionAt(e.getText().length),r=He.TextEdit.replace(He.Range.create(He.Position.create(0,0),n),""),i=ET(e,t.edits),s=await wi({...t},i,"New Text").catch(()=>i);return r.newText=s,r});J.onRequest("devicetree/diagnosticIssues",async({uri:t,full:e})=>{await Oe();let n=Se(t);_n({fsPath:n});let r=Vn(n);if(!r)return[];let i=e?(await r.getDiagnostics()).get(n):(await r.getSyntaxIssues(void 0,s=>uo(s.raw,n,!!e)?s:void 0)).get(n);if(i?.length)return i});J.onRequest("devicetree/evalMacros",async({macros:t,ctxId:e})=>{await Oe();let n=En(Ie,{id:e});return n?t.map(r=>{let i=Uc(r,n.macros),s=Me(i);return{macro:r,evaluated:typeof s=="number"?s:i}}):[]});J.onRequest("devicetree/memoryViews",async({ctxId:t})=>{let e=En(Ie,{id:t});if(!e)return;await e?.stable();let n=await e.getRuntime(),r=n.rootNode.getMemoryViews(n.context.macros).sort((o,a)=>{let c=qt(o.start,a.start);return c===0?qt(a.size,o.size):c}),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,disabled:o.disabled};a?a.partitions.push(c):i.set(o.name,{name:o.name,partitions:[c],path:o.nodePath})});let s=PB(Array.from(i.values()));return{trees:s,treeStr:kB(s)}});J.onRequest("devicetree/zephyrTypeBindings",async t=>{if(await Oe(),!t)return;let e=En(Ie,{id:t});return e?.bindingLoader?.getZephyrContextBinding()?.map(n=>({...n,vendor:n.compatible&&e?.bindingLoader?.getBindingVendorString(n.compatible)}))});J.onRequest("devicetree/contextMacroNames",async t=>{if(await Oe(),!t)return;let e=En(Ie,{id:t});return Array.from(e?.macros.keys()??[])});J.onRequest("devicetree/locationScopedInformation",async t=>{await Oe();let e=En(Ie,{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 Rt(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])})});
|
|
350
|
+
`)}var Ie=[],le,Xs,gg=new WeakMap,Yu=new Map;vB();var Tg=new Map,RB=t=>{t.settings.disableFileWatchers||t.getContextFiles().forEach(e=>{Yu.has(e)||Yu.set(e,new hg(e,IP,()=>{let n=ed(e),r=Tg.get(e);return!n||r===void 0?!1:r!==n.version})),Yu.get(e)?.watch()})},CP=async t=>{let e=Ie.indexOf(t);if(e===-1)return;Xu(t,void 0,!0),gg.delete(t),console.log(`(ID: ${t.id}) cleaning Context for [${t.ctxNames.join(",")}]`);let n=await Js(t);if(J.sendNotification("devicetree/contextDeleted",{ctxNames:t.ctxNames.map(r=>r.toString()),id:t.id,...t.getFileTree(),settings:t.settings,active:le===t,type:n.type}),Ie.splice(e,1),await xP(),t===le&&(le=void 0,Ie.length)){let r=Xs?En(Ie,{fsPath:Xs}):void 0;r??=Ie[0],console.log("Active context was deleted. Forcing active to",r.id),await _n({id:r.id},!0)}t.settings.disableFileWatchers||t.getContextFiles().map(r=>{Yu.get(r)?.unwatch()}),setTimeout(async()=>{await Oe();let r=new Set(Ie.flatMap(i=>i.getContextFiles()));t.getContextFiles().map(i=>{r.has(i)||qn().reset(i)})},2e3),t.bindingLoader?.dispose()},KQ=t=>{let e=gg.get(t);if(!e?.abort.signal.aborted)return Promise.all([e?.promise,t.getRuntime()])},Oe=async()=>{await Promise.all(Ie.map(KQ))},DP=async(t,e)=>(await EB(e)).indexOf(t)!==-1,EB=async t=>{let e=await wB(t);return Ie.filter(n=>!e.some(r=>r===n))},wB=async t=>{let e=await wP(t);return Ie.filter(n=>e.contexts.find(r=>zi(r)===n.id))},XQ=async t=>{let e=await n8(t);return Ie.filter(n=>e.contexts.find(r=>zi(r)===n.id))},JQ=async(t,e)=>(await XQ(e)).indexOf(t)!==-1,QQ=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=>fe(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=>fe(i,t.parser.fsPath))},ZQ=async t=>{if(!await DP(t))return;let e=await EB(),n=await wB(),r=await jf(e);if(Ie.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 QQ(a.context,c)})))),s=t.getContextFiles(),o=r.filter(a=>i.some(c=>c.context===a.context&&c.same)||a.context!==t&&fe(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(CP))},J=(0,He.createConnection)(He.ProposedFeatures.all),un=new He.TextDocuments(Lt),AP=!1,yg=!1,CB=!1,DB=!1,AB=!1,RP;J.onInitialize(async t=>{RP=t.workspaceFolders??[],J.console.log(`[Server(${process.pid}) ${RP?.at(0)?.uri} Version 0.12.1 ] Started and initialize received`);let e=t.capabilities;AP=!!(e.workspace&&e.workspace.configuration),yg=!!(e.workspace&&e.workspace.workspaceFolders),CB=!!e.workspace?.diagnostics?.refreshSupport,DB=!!e.workspace?.semanticTokens?.refreshSupport,AB=!!e.workspace?.foldingRange?.refreshSupport;let n={capabilities:{typeDefinitionProvider:!0,workspaceSymbolProvider:!0,textDocumentSync:He.TextDocumentSyncKind.Incremental,renameProvider:{prepareProvider:!0},completionProvider:{resolveProvider:!0,triggerCharacters:["&","="," ",'"',"(",","]},codeActionProvider:{codeActionKinds:[He.CodeActionKind.QuickFix,He.CodeActionKind.SourceFixAll]},documentSymbolProvider:!0,semanticTokensProvider:{legend:{tokenTypes:Lf,tokenModifiers:qf},full:!0},documentLinkProvider:{resolveProvider:!1},foldingRangeProvider:!0,definitionProvider:!0,declarationProvider:!0,referencesProvider:!0,documentFormattingProvider:!0,documentRangeFormattingProvider:!0,hoverProvider:!0,signatureHelpProvider:{triggerCharacters:["<","("],retriggerCharacters:[" ",","]}}};return yg&&(n.capabilities.workspace={workspaceFolders:{changeNotifications:!0,supported:!0}}),await LB(t.initializationOptions),n});var EP,e8={tabSize:8,insertSpaces:!1,trimTrailingWhitespace:!0,insertFinalNewline:!0,wordWrapColumn:100},IB=t=>({tabSize:t?.["editor.tabSize"],insertSpaces:t?.["editor.insertSpaces"],trimFinalNewlines:t?.["files.trimFinalNewlines"],trimTrailingWhitespace:t?.["files.trimTrailingWhitespace"],insertFinalNewline:t?.["editor.insertFinalNewline"],wordWrapColumn:t?.["editor.wordWrapColumn"],removeMacroMultiline:t?.["editor.removeMacroMultiline"],wrapLongLines:t?.["editor.wrapLongLines"],indentExpressions:t?.["editor.indentExpressions"],removeEmptyReferences:t?.["editor.removeEmptyReferences"],removeEmptyNodes:t?.["editor.removeEmptyNodes"],removeEmptyRoots:t?.["editor.removeEmptyRoots"],sortNodesAndProperties:t?.["editor.sortNodesAndProperties"]});J.onInitialized(async()=>{if(AP&&(J.client.register(He.DidChangeConfigurationNotification.type,{}),!EP)){let t=await J.workspace.getConfiguration("editor").catch(()=>{}),e=await J.workspace.getConfiguration("files").catch(()=>{}),n=await J.workspace.getConfiguration("[devicetree]").catch(()=>{}),r=IB(n);(t||e||r)&&(EP={...t,...e,...r})}yg&&J.workspace.onDidChangeWorkspaceFolders(async t=>{J.console.log("Workspace folder change event received"),await Zu()})});J.onRequest("workspace/workspaceFolders",async()=>RP??null);var t8=async t=>{let e=OB();return e={...Ks,...e},Gu(e,t??await Qu())},wP=async t=>{let e=i8();return e={...Ks,...e},Gu(e,t??await Qu())},n8=async t=>{let e=s8();return e={...Ks,...e},Gu(e,t??await Qu())},Ju=async t=>{let e=r8();return e={...Ks,...e},Gu(e,t??await Qu())},Qu=async()=>yg?await J.workspace.getWorkspaceFolders()??[]:[],NB=async t=>{let e=En(Ie,{id:zi(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=zi(t);console.log(`(ID: ${n}) New context [${t.ctxName}]`),console.log(`(ID: ${n}) Settings: ${JSON.stringify(t,void 0," ")}`);let r=(0,bc.join)((0,bc.dirname)(t.dtsFile),"dts","bindings"),i=new mp(t,EP??e8,t.bindingType?rB({zephyrBindings:t.zephyrBindings?[r,...t.zephyrBindings]:[r],deviceOrgBindingsMetaSchema:t.deviceOrgBindingsMetaSchema??[],deviceOrgTreeBindings:t.deviceOrgTreeBindings??[]},t.bindingType):void 0);Ie.push(i);let s=performance.now();await i.stable(),console.log(`(ID: ${n}) New context took ${performance.now()-s}ms to start [${t.ctxName}]`),RB(i);let o=await Js(i);return J.sendNotification("devicetree/contextCreated",{ctxNames:i.ctxNames.map(a=>a.toString()),id:i.id,...i.getFileTree(),settings:i.settings,active:i===le,type:o.type}),await ZQ(i),await xP(),i},Zu=async()=>{let t=await wP(),e=await Ju();e.allowAdhocContexts||(e=await wP());let n=e.contexts.map(zi),r=Ie.filter(i=>!n.includes(i.id));await Promise.all(r.map(CP)),await t.contexts?.reduce((i,s)=>i.then(async()=>{await NB(s)}),Promise.resolve()),e.allowAdhocContexts&&await(await t8()).contexts?.reduce((s,o)=>s.then(async()=>{En(Ie,{fsPath:o.dtsFile})||await NB(o)}),Promise.resolve()),setTimeout(async()=>{Xs?await _n({fsPath:Xs}):!le&&Ie.length&&(console.log(`No active context using first context (ID: ${Ie[0].id}) [${Ie[0].ctxNames.join(",")}]`),await _n({id:Ie[0].id}))})},dr,is,Ku=new Map,vc=new Map,r8=()=>!is&&!dr?void 0:{...Object.fromEntries(Object.entries(is??{}).filter(([,n])=>n!==void 0)),...dr,contexts:[...dr?.contexts??[],...Array.from(vc.values()),...Array.from(Ku.values())]},OB=()=>!is&&!dr?void 0:{...is,...dr,contexts:[...Array.from(Ku.values())]},i8=()=>!is&&!dr?void 0:{...is,...dr,contexts:[...dr?.contexts??[],...Array.from(vc.values())]},s8=()=>!is&&!dr?void 0:{...dr,contexts:[...dr?.contexts??[]]};function o8(t){let e={...t};for(let n in e)e[n]===null&&delete e[n];return e}var MB=async()=>{let t=await Ju();console.log("Resolved settings",JSON.stringify(t,void 0," ")),J.sendNotification("devicetree/settingsChanged",t),await Zu(),Oe().then(()=>{CB&&J.languages.diagnostics.refresh()})},a8=async()=>{let t=le?.getContextFiles();await Promise.all(Array.from(un.keys()).filter(Et).map(async e=>{t?.some(n=>fe(n,Se(e)))||await J.sendDiagnostics({uri:e,version:un.get(e)?.version,diagnostics:[{severity:He.DiagnosticSeverity.Information,range:He.Range.create(He.Position.create(0,0),He.Position.create(0,0)),message:"File not in active context",source:"devicetree"}]})}))},IP=async t=>{let e=NT(Ie,t);if(e.length)e.sort((n,r)=>n===le?-1:r===le?1:0).forEach(n=>{gg.get(n)?.abort.abort(),le===n&&J.sendNotification("devicetree/activeContextBusyNotification",n.id),J.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?xB(n):[],l=n.getContextFiles();if(await n.reevaluate(t),RB(n),l.forEach(p=>Yu.get(p)?.unwatch()),a&&LP(n)?.length&&(OP(n).then(p=>{let m=p.items.map(h=>({uri:h.uri,version:h.version??void 0,diagnostics:h.items}));Xu(n,c.filter(h=>m.every(y=>y.uri!==h.uri))),m.forEach(h=>{J.sendDiagnostics(h)}),td.set(n,!0)}),Xs)){let p=n.getFsPathParser(Xs);p&&setTimeout(()=>{p.latestSemanticTokensBuilt||J.languages.semanticTokens.refresh()},50)}let u=await Js(n),d=n.getFileTree(),f={ctxNames:n.ctxNames.map(p=>p.toString()),id:n.id,...d,settings:n.settings,active:a,type:u.type};le===n&&J.sendNotification("devicetree/activeContextStableNotification",f),J.sendNotification("devicetree/contextStableNotification",f),s(),console.log("reevaluate",performance.now()-o)})});gg.set(n,{abort:r,promise:i})});else{if((await Ju()).allowAdhocContexts===!1)return;await Zu(),await _n({fsPath:t})}},c8=t=>un.keys().find(e=>fe(Se(e),t)),ed=t=>{let e=c8(t);if(e)return un.get(e)},xB=t=>t.getContextFiles().map(e=>({uri:ue(e),version:ed(e)?.version,diagnostics:[]})),td=new WeakMap,Xu=async(t,e=xB(t),n=!1)=>{if(!n&&t!==le)return;let r=performance.now();await Promise.all(e.filter(i=>t===le||!le?.getContextFiles().some(s=>fe(Se(i.uri),s))).map(i=>J.sendDiagnostics({uri:i.uri,version:un.get(i.uri)?.version,diagnostics:[]}))),td.delete(t),console.log(`(ID: ${t.id})`,"clear workspace diagnostics",`[${t.ctxNames.join(",")}]`,performance.now()-r)},mg=new Map,l8=async t=>{let e=mg.get(t);if(e||!AP)return e;mg.delete(t);let n=await J.workspace.getConfiguration({scopeUri:ue(t),section:"[devicetree]"}).catch(()=>{});if(n){let r=IB(n);return mg.set(t,r),r}},OP=async t=>{await t.stable();let e=performance.now(),n=await t.getDiagnostics(),r=await Promise.all(t.getContextFiles().map(async i=>{let s=ed(i),o=[];if(s&&t.settings.showFormattingErrorAsDiagnostics){let a=await l8(i);o.push(...(await wi({textDocument:s,options:{...t.formattingOptions,...a}},s.getText(),"File Diagnostics").catch(()=>[])).map(c=>c.diagnostic()))}return{uri:ue(i),kind:He.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]}},MP=async t=>{let{items:e}=await OP(t);e.map(n=>({uri:n.uri,version:n.version??void 0,diagnostics:n.items})).forEach(async n=>{J.sendDiagnostics(n)}),td.set(t,!0)},xP=async()=>{let t=await Promise.all(Ie.map(e=>Js(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("==============================")},Js=async(t,e)=>{let n=await DP(t,e),r=!n&&await JQ(t,e);return{ctx:t,type:n?"Ad Hoc":r?"User":"3rd Party"}},_n=async(t,e=!1)=>{if("fsPath"in t){if(!Et(t.fsPath))return!1;Xs=t.fsPath,console.log("Active File Uri",Xs)}let n=await Ju();if(le&&!e&&!n.autoChangeContext||(await Oe(),!e&&le?.getContextFiles().find(o=>"fsPath"in t&&fe(o,t.fsPath))))return!1;let r=le,i=En(Ie,t),s=r!==i;return s&&(r&&Xu(r),le=i,i?(Js(i).then(async o=>{let a=i.getFileTree();!i||i!==le&&!Ie.includes(i)||J.sendNotification("devicetree/newActiveContext",{ctxNames:i.ctxNames.map(c=>c.toString()),id:i.id,...a,settings:i.settings,active:le===i,type:o.type})}),LP(i)?.length&&MP(i),await xP()):J.sendNotification("devicetree/newActiveContext",void 0)),AB&&J.languages.foldingRange.refresh(),DB&&J.languages.semanticTokens.refresh(),s};un.listen(J);var LP=t=>t?.getContextFiles()?.filter(e=>ed(e));un.onDidSave(t=>{Tg.set(Se(t.document.uri),t.document.version)});un.onDidClose(async t=>{let e=Se(t.document.uri);if(!Et(e))return;Tg.delete(e);let n=NT(Ie,e);if(n.length===0){Ku.delete(e),J.sendDiagnostics({uri:t.document.uri,version:un.get(t.document.uri)?.version,diagnostics:[]});return}await Promise.all(n.map(async r=>{!!LP(r)?.filter(s=>s!==e).length?le?.getContextFiles().some(s=>fe(s,e))?le?.getContextFiles().some(s=>fe(s,e))&&(await Xu(le),await MP(le)):J.sendDiagnostics({uri:t.document.uri,version:un.get(t.document.uri)?.version,diagnostics:[]}):await DP(r)?(await CP(r),Ku.delete(r.settings.dtsFile)):Xu(r)}))});un.onDidOpen(async t=>{let e=Se(t.document.uri);if(!Et(e))return;Tg.set(e,t.document.version),await Oe(),a8();let n=En(Ie,{fsPath:e});if(console.log("onDidOpen",n?.id,e),n)n!==le?await _n({id:n.id}):n===le&&(!td.get(n)||n.getContextFiles().some(r=>!fe(r,e)))&&await MP(n);else{let r={ctxName:(0,bc.basename)(e),dtsFile:e};Ku.set(e,r),await IP(e)}});un.onDidChangeContent(async t=>{let e=Se(t.document.uri);if(!Et(e))return;let n=t.document.getText(),r=qn();r.needsRenew(e,n)&&(console.log("Content changed",e),r.renewLexer(e,n),await IP(e))});var LB=async t=>{t?.settings?.devicetree&&(dr=lB(o8(t.settings.devicetree)),dr=Object.fromEntries(Object.entries(dr??{}).filter(([,e])=>e!==void 0)),console.log("Configuration changed",JSON.stringify(t,void 0," ")),await MB())};J.onDidChangeConfiguration(async t=>{await LB(t)});J.listen();J.languages.diagnostics.onWorkspace(async()=>{await Oe();let t=le;return t?OP(t).finally(()=>{td.set(t,!0)}):{items:[]}});J.onDidChangeWatchedFiles(t=>{J.console.log("We received a file change event")});J.onCompletion(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return a0(t,le,un.get(t.textDocument.uri));if(!Et(e))return[];await Oe(),_n({fsPath:e});let n=Vn(e);return n?[...await WD(t,n),...await F0(t,n)]:[]});J.onCompletionResolve(t=>t);var Vn=t=>{let e=OB();return En(Ie,{fsPath:t},le,e?.preferredContext)};J.onDocumentSymbol(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return[];await Oe();let n=Vn(e);return n?n.getFsPathParser(e)?.getDocumentSymbols(e):[]});J.onWorkspaceSymbol(async()=>{await Oe();let t=le;return t?(await t.getAllStableParsers()).flatMap(e=>e.getWorkspaceSymbols()):[]});J.languages.semanticTokens.on(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return{data:[]};try{await Oe();let n=Vn(e),r=new He.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}});J.onDocumentLinks(async t=>{await Oe();let e=Se(t.textDocument.uri);return Et(e)?Vn(e)?.getDocumentLinks(e):e.endsWith(".yaml")&&le?le.bindingLoader?.getDocumentLinks?.(un.get(t.textDocument.uri))??[]:[]});J.onPrepareRename(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return p0(t,n)});J.onRenameRequest(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return f0(t,n)});J.onReferences(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return c0(t,n)});J.onDefinition(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return g0(t,le,un.get(t.textDocument.uri));if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e),r=(await n?.getDocumentLinks(e,t.position))?.filter(i=>i.target).map(i=>He.Location.create(i.target,i.range))??[];return r.length?r:m0(t,n)});J.onDeclaration(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return b0(t,le,un.get(t.textDocument.uri));if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return v0(t,n)});J.onCodeAction(async t=>{let e=Se(t.textDocument.uri);if(Et(e))return S0(t)});var qB=async t=>{if(!Et(t.textDocument.uri))return;let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);if(!n)return[];if((await n.getSyntaxIssues(void 0,l=>uo(l.raw,e,!1)?l:void 0)).get(e)?.length)return[];let i=un.get(t.textDocument.uri)??qn().getDocument(e),s=i.getText();mg.set(e,t.options);let o=await wi({...t,options:{...n.formattingOptions,...t.options}},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[He.TextEdit.replace(He.Range.create(He.Position.create(0,0),He.Position.create(i.lineCount,c)),o)]};J.onDocumentRangeFormatting(qB);J.onDocumentFormatting(qB);J.onHover(async t=>{let e=Se(t.textDocument.uri);if((e.endsWith(".c")||e.endsWith(".cpp"))&&le&&le.bindingLoader?.type==="Zephyr")return cM(t,le,un.get(t.textDocument.uri));if(!Et(e))return;await Oe();let n=Vn(e);return(await B0(t,n)).at(0)});J.onFoldingRanges(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe();let n=Vn(e),r=n?.isInContext(e);if(!n||!r)return[];let i=(await n.getAllStableParsers()).find(s=>s.getFiles().some(o=>o===e));return i?iB(e,i):[]});J.onTypeDefinition(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return cB(t,n)});J.onSignatureHelp(async t=>{let e=Se(t.textDocument.uri);if(!Et(e))return;await Oe(),_n({fsPath:e});let n=Vn(e);return gB(t,n)});J.onRequest("devicetree/getContexts",async()=>(await Oe(),Promise.all(Ie.map(async t=>{let e=await Js(t);return{ctxNames:t.ctxNames.map(n=>n.toString()),id:t.id,...t.getFileTree(),settings:t.settings,active:le===t,type:e.type}}))));J.onRequest("devicetree/setActive",async t=>(await Oe(),console.log("devicetree/setActive",t),await _n(t,!0)));J.onRequest("devicetree/getActiveContext",async()=>{if(await Oe(),console.log("devicetree/getActiveContext"),!le)return;let t=await Js(le);return le?{ctxNames:le.ctxNames.map(e=>e.toString()),id:le.id,...le.getFileTree(),settings:le.settings,active:!0,type:t.type}:void 0});J.onRequest("devicetree/setDefaultSettings",async t=>{await Oe(),is=Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!==void 0)),console.log("Integration Settings",is),await MB()});J.onRequest("devicetree/requestContext",async t=>{await Oe();let e=await Qu(),n=await Ju(e),r=await PP(t,n,e);if(!r)throw console.log("Failed to resolve context",t),new Error("Failed to resolve context");console.log("devicetree/requestContext",r);let i=zi(r),s=Array.from(vc).find(([,c])=>c.ctxName===t.ctxName);if(s){let c=s[0].split(":",1)[0];En(Ie,{name:r.ctxName.toString()})?.removeCtxName(r.ctxName),console.log(`Removing integration context with ID ${c} and name ${t.ctxName}`),vc.delete(s[0])}vc.set(`${i}:${t.ctxName}`,t),await Zu();let o=Ie.find(c=>c.id===i);if(!o)throw new Error("Failed to create context");let a=await Js(o,e);return{ctxNames:o.ctxNames.map(c=>c.toString()),id:i,...o.getFileTree(),settings:o.settings,active:!0,type:a.type}});J.onRequest("devicetree/removeContext",async({id:t,name:e})=>{await Oe(),vc.delete(`${t}:${e}`);let n=En(Ie,{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 Zu()}});J.onRequest("devicetree/compiledDtsOutput",async t=>{if(await Oe(),!t)return;let e=En(Ie,{id:t});if(!e||!e.settings.dtsFile){console.log("Context or DTS file not found for ID",t);return}let n=await e.toFullString();return wi({textDocument:{uri:ue(e.settings.dtsFile)},options:e.formattingOptions},n,"New Text").catch(()=>n)});J.onRequest("devicetree/serializedContext",async t=>{if(await Oe(),!t)return;let e=En(Ie,{id:t}),n=performance.now();return e?.serialize().finally(()=>{console.info("serializedContext",performance.now()-n)})});J.onRequest("devicetree/activePath",async t=>{if(await Oe(),!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 Rt(t,le,n=>[e(n)])).at(0)});J.onRequest("devicetree/customActions",async t=>(await Oe(),hB(t,le)));J.onRequest("devicetree/activeFsPath",async t=>{await Oe(),_n({fsPath:t})});J.onRequest("devicetree/formattingText",async t=>{let e=Se(t.textDocument.uri),n=ed(e)??qn().getDocument(e,t.text),r=await wi(t,n.getText(),"New Text");return{text:r,diagnostics:(await wi(t,n.getText(),"File Diagnostics")).map(i=>i.diagnostic()),nonActionableDiagnostics:(await wi(t,r,"File Diagnostics")).map(i=>i.diagnostic())}});J.onRequest("devicetree/formatTextEdits",async t=>{await Oe();let e=qn().getDocument(Se(t.textDocument.uri),t.text),n=e.positionAt(e.getText().length),r=He.TextEdit.replace(He.Range.create(He.Position.create(0,0),n),""),i=ET(e,t.edits),s=await wi({...t},i,"New Text").catch(()=>i);return r.newText=s,r});J.onRequest("devicetree/diagnosticIssues",async({uri:t,full:e})=>{await Oe();let n=Se(t);_n({fsPath:n});let r=Vn(n);if(!r)return[];let i=e?(await r.getDiagnostics()).get(n):(await r.getSyntaxIssues(void 0,s=>uo(s.raw,n,!!e)?s:void 0)).get(n);if(i?.length)return i});J.onRequest("devicetree/evalMacros",async({macros:t,ctxId:e})=>{await Oe();let n=En(Ie,{id:e});return n?t.map(r=>{let i=Uc(r,n.macros),s=Me(i);return{macro:r,evaluated:typeof s=="number"?s:i}}):[]});J.onRequest("devicetree/memoryViews",async({ctxId:t})=>{let e=En(Ie,{id:t});if(!e)return;await e?.stable();let n=await e.getRuntime(),r=n.rootNode.getMemoryViews(n.context.macros).sort((o,a)=>{let c=qt(o.start,a.start);return c===0?qt(a.size,o.size):c}),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,disabled:o.disabled};a?a.partitions.push(c):i.set(o.name,{name:o.name,partitions:[c],path:o.nodePath})});let s=PB(Array.from(i.values()));return{trees:s,treeStr:kB(s)}});J.onRequest("devicetree/zephyrTypeBindings",async t=>{if(await Oe(),!t)return;let e=En(Ie,{id:t});return e?.bindingLoader?.getZephyrContextBinding()?.map(n=>({...n,vendor:n.compatible&&e?.bindingLoader?.getBindingVendorString(n.compatible)}))});J.onRequest("devicetree/contextMacroNames",async t=>{if(await Oe(),!t)return;let e=En(Ie,{id:t});return Array.from(e?.macros.keys()??[])});J.onRequest("devicetree/locationScopedInformation",async t=>{await Oe();let e=En(Ie,{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 Rt(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])})});
|