/* All material copyright ESRI, All Rights Reserved, unless otherwise specified. See https://js.arcgis.com/4.25/esri/copyright.txt for details. */ import{isBlockStatement as t,isVariableDeclarator as n,isBlockComment as e,isProgram as s}from"./types.js";function i(t,n){return!!n&&(n.loc.end.line===t.loc.start.line&&n.loc.end.column<=t.loc.start.column)}function m(t,n){return t.range[0]>=n.range[0]&&t.range[1]<=n.range[1]}class o{constructor(){this.comments=[],this._nodeStack=[],this._newComments=[]}insertInnerComments(n){if(!t(n)||0!==n.body.length)return;const e=[];for(let t=this._newComments.length-1;t>=0;--t){const s=this._newComments[t];n.range[1]>=s.range[0]&&(e.unshift(s),this._newComments.splice(t,1))}e.length&&(n.innerComments=e)}attachTrailingComments(n){if(!n)return;const e=this._nodeStack[this._nodeStack.length-1];if(t(n)&&m(e,n))for(let t=this._newComments.length-1;t>=0;--t){const s=this._newComments[t];m(s,n)&&(e.trailingComments=[...e.trailingComments??[],s],this._newComments.splice(t,1))}let s=[];if(this._newComments.length>0)for(let t=this._newComments.length-1;t>=0;--t){const m=this._newComments[t];i(m,e)?(e.trailingComments=[...e.trailingComments??[],m],this._newComments.splice(t,1)):i(m,n)&&(s.unshift(m),this._newComments.splice(t,1))}if(e?.trailingComments){i(e.trailingComments[0],n)&&(s=[...s,...e.trailingComments],delete e.trailingComments)}s.length>0&&(n.trailingComments=s)}attachLeadingComments(t){if(!t)return;let s;for(;this._nodeStack.length>0;){const n=this._nodeStack[this._nodeStack.length-1];if(!(t.range[0]<=n.range[0]))break;s=n,this._nodeStack.pop()}const i=[],m=[];if(s){for(let o=(s.leadingComments?.length??0)-1;o>=0;--o){const l=s.leadingComments[o];t.range[0]>=l.range[1]?(i.unshift(l),s.leadingComments.splice(o,1)):n(t)&&!e(l)&&(m.unshift(l),s.leadingComments.splice(o,1))}return 0===s.leadingComments?.length&&delete s.leadingComments,i.length&&(t.leadingComments=i),void(m.length&&(t.trailingComments=[...m,...t.trailingComments??[]]))}for(let n=this._newComments.length-1;n>=0;--n){const e=this._newComments[n];t.range[0]>=e.range[0]&&(i.unshift(e),this._newComments.splice(n,1))}i.length&&(t.leadingComments=i)}attachComments(t){if(s(t)&&t.body.length>0){const n=this._nodeStack[this._nodeStack.length-1];return n?(n.trailingComments=[...n.trailingComments??[],...this._newComments],this._newComments.length=0,void this._nodeStack.pop()):(t.trailingComments=[...this._newComments],void(this._newComments.length=0))}this.attachTrailingComments(t),this.attachLeadingComments(t),this.insertInnerComments(t),this._nodeStack.push(t)}collectComment(t){this.comments.push(t),this._newComments.push(t)}}export{o as CommentHandler};