@tslite/parser 1.10.0 → 1.13.0
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/LICENSE +55 -0
- package/NOTICE +14 -0
- package/dist/_namespaces/ts.d.ts +18 -0
- package/dist/_namespaces/ts.js +21 -0
- package/dist/_namespaces/ts.performance.d.ts +1 -0
- package/dist/_namespaces/ts.performance.js +2 -0
- package/dist/core.d.ts +450 -0
- package/dist/core.js +1394 -0
- package/dist/corePublic.d.ts +62 -0
- package/dist/corePublic.js +31 -0
- package/dist/debug.d.ts +74 -0
- package/dist/debug.js +326 -0
- package/dist/diagnosticInformationMap.generated.d.ts +1435 -0
- package/dist/diagnosticInformationMap.generated.js +1441 -0
- package/dist/factory.d.ts +78 -0
- package/dist/factory.js +622 -0
- package/dist/factoryPublic.d.ts +314 -0
- package/dist/factoryPublic.js +1796 -0
- package/dist/index.d.ts +1 -249
- package/dist/index.js +4 -6
- package/dist/parser.d.ts +59 -0
- package/dist/parser.js +5075 -0
- package/dist/path.d.ts +312 -0
- package/dist/path.js +475 -0
- package/dist/perfLogger.d.ts +4 -0
- package/dist/perfLogger.js +38 -0
- package/dist/performance.d.ts +20 -0
- package/dist/performance.js +49 -0
- package/dist/performanceTimestamp.d.ts +2 -0
- package/dist/performanceTimestamp.js +2 -0
- package/dist/scanner.d.ts +80 -0
- package/dist/scanner.js +1984 -0
- package/dist/shims/mapShim.d.ts +23 -0
- package/dist/shims/mapShim.js +156 -0
- package/dist/types.d.ts +2626 -0
- package/dist/types.js +1074 -0
- package/dist/utilities.d.ts +473 -0
- package/dist/utilities.js +2632 -0
- package/dist/utilitiesPublic.d.ts +274 -0
- package/dist/utilitiesPublic.js +1049 -0
- package/dist/visitor.d.ts +15 -0
- package/dist/visitor.js +64 -0
- package/dist/visitorPublic.d.ts +82 -0
- package/dist/visitorPublic.js +352 -0
- package/package.json +14 -42
- package/dist/index.cjs +0 -6
- package/dist/index.d.cts +0 -249
package/dist/index.cjs
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
'use strict';var ast=require('@tslite/ast');var ie=class extends ast.TSLiteError{constructor(a,i,y,m,E){super("lex-error",`${a} (${i.line}:${i.column})`,{position:i,index:y,loc:m,end:E});this.position=i;this.index=y;this.loc=m;this.end=E;this.name="LexError";}},We=new Set(["const","if","else","return","async","await","true","false","null","typeof","let","var","function","class","new","for","while","do","this","throw","try","catch","finally","switch","case","break","continue","default","void","delete","instanceof","in","yield","import","export","extends","super","debugger","with","enum","interface"]),Dt=["...","===","!==","=>","?.","??=","&&=","||=","**=","??","==","!=","<=",">=","&&","||","|","&","++","--","+=","-=","*=","/=","%=","**","<<","+","-","*","/","%","<",">","!","?",":",".",",",";","=","^","~","(",")","[","]","{","}"],Se=r=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$",ke=r=>Se(r)||r>="0"&&r<="9",ae=r=>r>="0"&&r<="9",ze=r=>ae(r)||r>="a"&&r<="f"||r>="A"&&r<="F",Jt=r=>ke(r)||r==="-",me=r=>r===`
|
|
2
|
-
`||r==="\r"||r==="\u2028"||r==="\u2029",xe=(r,c)=>{let a=c;for(;;){let i=r[a]??"";if(i===" "||i===" "||i==="\f"||i==="\v"||me(i))a++;else if(i==="/"&&r[a+1]==="/")for(a+=2;a<r.length&&!me(r[a]??"");)a++;else if(i==="/"&&r[a+1]==="*"){for(a+=2;a<r.length&&!(r[a]==="*"&&r[a+1]==="/");)a++;a+=2;}else return a}},Ft=(r,c)=>{if(!Se(r[c]??""))return c;let a=c+1;for(;ke(r[a]??"");)a++;return a},qe=(r,c,a)=>r.startsWith(a,c)&&!ke(r[c+a.length]??""),Kt=(r,c)=>{let a=xe(r,c);qe(r,a,"const")&&(a=xe(r,a+5));let i=Ft(r,a);if(i===a)return false;if(a=xe(r,i),qe(r,a,"extends")){let y=xe(r,a+7),m=r[y]??"";return !(m==="="||m===">"||m==="/")}return r[a]===","?true:r[a]==="="&&r[a+1]!==">"},Xt=new Set(["(","[","{",",",";",":","?","=>","...","=","+","-","*","/","%","<","<=",">",">=","==","===","!=","!==","&&","||","??","!","+=","-=","*=","/=","%=","??=","&&=","||=","**="]),Mt=new Set(["return","typeof","await","delete","void","in","instanceof","else","case","yield","throw"]);function $t(r,c,a){return Ae(r,c,a).scan()}function Ae(r,c,a){let i=[],y=0,m=1,E=0,K=()=>({line:m,column:E}),h=(w=0)=>r[y+w]??"",_=w=>{let S=K(),X={start:S,end:{line:m,column:E+1}};if(a){a({message:w,position:S,index:y,loc:X,end:y+1});return}throw new ie(w,S,y,X,y+1)},P=()=>{let w=r[y++];return w==="\r"?(r[y]===`
|
|
3
|
-
`&&y++,m++,E=0):w===`
|
|
4
|
-
`||w==="\u2028"||w==="\u2029"?(m++,E=0):E++,w},H=()=>{for(;;){let w=h();if(w===" "||w===" "||w==="\f"||w==="\v"||me(w))P();else if(w==="/"&&h(1)==="/"){let S=y,X=K();P(),P();let l=y;for(;y<r.length&&!me(h());)P();c?.({type:"Line",value:r.slice(l,y),start:S,end:y,loc:{start:X,end:K()}});}else if(w==="/"&&h(1)==="*"){let S=y,X=K();P(),P();let l=y,p=y;for(;;){if(y>=r.length){_("Unterminated block comment"),p=y;break}if(h()==="*"&&h(1)==="/"){p=y,P(),P();break}P();}c?.({type:"Block",value:r.slice(l,p),start:S,end:y,loc:{start:X,end:K()}});}else break}},A=(w,S,X,l)=>{i.push({type:w,value:S,start:X,end:y,loc:{start:l,end:K()}}),u=w==="Punctuator"?Xt.has(S):w==="Keyword"?Mt.has(S):w==="TemplateHead"||w==="TemplateMiddle";},q=w=>{for(P();y<r.length;){let S=h();if(S===w)return P(),r.slice(C,y);if(me(S))return _("Unterminated string literal"),r.slice(C,y);if(S==="\\"){if(P(),y>=r.length)return _("Unterminated string literal"),r.slice(C,y);P();continue}P();}return _("Unterminated string literal"),r.slice(C,y)},T=()=>{if(h()==="0"&&(h(1)==="x"||h(1)==="X")){if(P(),P(),!ze(h()))return _("Invalid hexadecimal literal");for(;ze(h());)P();return}if(h()==="0"&&(h(1)==="b"||h(1)==="B")){if(P(),P(),h()!=="0"&&h()!=="1")return _("Invalid binary literal");for(;h()==="0"||h()==="1";)P();return}if(h()==="0"&&(h(1)==="o"||h(1)==="O")){if(P(),P(),!(h()>="0"&&h()<="7"))return _("Invalid octal literal");for(;h()>="0"&&h()<="7";)P();return}for(;ae(h());)P();if(h()===".")for(P();ae(h());)P();if(h()==="e"||h()==="E"){if(P(),(h()==="+"||h()==="-")&&P(),!ae(h()))return _("Invalid exponent");for(;ae(h());)P();}},o=()=>{let w=y;for(;y<r.length;){let S=h();if(S==="`"){let X=r.slice(w,y);return P(),{raw:X,interp:false}}if(S==="$"&&h(1)==="{"){let X=r.slice(w,y);return P(),P(),{raw:X,interp:true}}if(S==="\\"){if(P(),y>=r.length)break;P();continue}P();}return _("Unterminated template literal"),{raw:r.slice(w,y),interp:false}},C=0,G=0,U=[],u=true,v="js",B=[],R=[],Y=new Map,Z=-1,re=()=>({i:y,line:m,col:E,mode:v,braceDepth:G,tmplStack:[...U],jsxParent:[...B],jsxExpr:R.map(w=>({...w}))}),N=w=>{y=w.i,m=w.line,E=w.col,v=w.mode,G=w.braceDepth,U=[...w.tmplStack],B=[...w.jsxParent],R=w.jsxExpr.map(S=>({...S}));},O=()=>(i=[],g(),i),g=()=>{for(;;){if(v==="jsxChildren"){C=y;let l=K();if(y>=r.length){A("EOF","",C,l);break}let p=h();if(p==="<"){h(1)==="/"?(P(),P(),A("Punctuator","</",C,l),v="jsxCloseTag"):(P(),A("Punctuator","<",C,l),B.push("jsxChildren"),v="jsxOpenTag");continue}if(p==="{"){P(),A("Punctuator","{",C,l),R.push({level:G,restore:"jsxChildren"}),v="js";continue}for(;y<r.length&&h()!=="<"&&h()!=="{";)P();A("JSXText",r.slice(C,y),C,l);continue}if(v==="jsxOpenTag"||v==="jsxCloseTag"){H(),C=y;let l=K();if(y>=r.length){A("EOF","",C,l);break}let p=h();if(Se(p)){for(P();Jt(h());)P();A("Identifier",r.slice(C,y),C,l);continue}if(p==="/"&&h(1)===">"){P(),P(),A("Punctuator","/>",C,l),v=B.pop()??"js";continue}if(p===">"){P(),A("Punctuator",">",C,l),v=v==="jsxCloseTag"?B.pop()??"js":"jsxChildren";continue}if(p==="{"){P(),A("Punctuator","{",C,l),R.push({level:G,restore:v}),v="js";continue}if(p==='"'||p==="'"){A("String",q(p),C,l);continue}if(p==="="||p==="."||p===":"){P(),A("Punctuator",p,C,l);continue}if(p==="<"&&v==="jsxOpenTag"){P(),A("Punctuator","<",C,l),B.push("jsxOpenTag");continue}_(`Unexpected character '${p}' in JSX tag`),P(),A("Unknown",p,C,l);continue}H(),C=y;let w=K();if(y>=r.length){A("EOF","",C,w);break}let S=h();if(Se(S)){for(;ke(h());)P();let l=r.slice(C,y);A(We.has(l)?"Keyword":"Identifier",l,C,w);continue}if(ae(S)||S==="."&&ae(h(1))){T(),A("Number",r.slice(C,y),C,w);continue}if(S==='"'||S==="'"){let l=q(S);A("String",l,C,w);continue}if(S==="`"){P();let{raw:l,interp:p}=o();p?(A("TemplateHead",l,C,w),U.push(G)):A("Template",l,C,w);continue}if(S==="<"&&y===Z){Z=-1,P(),A("Punctuator","<",C,w);continue}if(S==="<"&&u&&!Kt(r,y+1)){Y.set(y,re()),P(),A("Punctuator","<",C,w),B.push("js"),v="jsxOpenTag";continue}if(S==="{"){P(),A("Punctuator","{",C,w),G++;continue}if(S==="}"){if(U.length>0&&G===U[U.length-1]){U.pop(),P();let{raw:l,interp:p}=o();A(p?"TemplateMiddle":"TemplateTail",l,C,w),p&&U.push(G);continue}if(R.length>0&&G===R[R.length-1].level){let{restore:l}=R.pop();P(),A("Punctuator","}",C,w),v=l;continue}P(),A("Punctuator","}",C,w),G--;continue}if(S==="?"&&h(1)==="."&&ae(h(2))){P(),A("Punctuator","?",C,w);continue}let X=Dt.find(l=>r.startsWith(l,y));if(X){for(let l=0;l<X.length;l++)P();A("Punctuator",X,C,w);continue}_(`Unexpected character '${S}'`),P(),A("Unknown",S,C,w);}};return {scan:O,opensJsx:w=>Y.has(w),rescanLessThan:w=>{let S=Y.get(w);return S?(N(S),Z=w,O()):null}}}var Ut=new Set(["leadingComments","trailingComments","innerComments","comments"]),He=r=>typeof r=="object"&&r!==null&&typeof r.type=="string"&&r.loc!=null&&typeof r.start=="number",Qe=new WeakMap;function Bt(r){let c=Qe.get(r);if(c)return c;let a=[];for(let i of Object.keys(r)){if(Ut.has(i))continue;let y=r[i];if(He(y))a.push(y);else if(Array.isArray(y))for(let m of y)He(m)&&a.push(m);}return a.sort((i,y)=>i.start-y.start),Qe.set(r,a),a}function _t(r,c){let a=r,i,y;for(;;){let m=Bt(a);i=void 0,y=void 0;let E;for(let K of m){if(K.start<=c.start&&c.end<=K.end){E=K;break}if(K.end<=c.start)i=K;else if(c.end<=K.start){y=K;break}}if(!E)break;a=E;}return {enclosing:a,preceding:i,following:y}}var Oe=(r,c)=>{(r.leadingComments??(r.leadingComments=[])).push(c);},we=(r,c)=>{(r.trailingComments??(r.trailingComments=[])).push(c);},De=(r,c)=>{(r.innerComments??(r.innerComments=[])).push(c);};function Vt(r,c){for(let a=c;a<r.length;a++){let i=r[a];if(i!==" "&&i!==" "&&i!=="\r"&&i!==`
|
|
5
|
-
`&&i!=="\f")return i}return ""}var Gt=new Set([")","]","}",","]);function Je(r,c,a=""){for(let i of c){let{enclosing:y,preceding:m,following:E}=_t(r,i),K=m==null||m.loc.end.line<i.loc.start.line,h=!K&&(E==null||i.loc.end.line<E.loc.start.line);if(K)E?Oe(E,i):m?we(m,i):De(y,i);else if(h)m?we(m,i):E?Oe(E,i):De(y,i);else {let _=Gt.has(Vt(a,i.end));m&&_?we(m,i):E?Oe(E,i):m?we(m,i):De(y,i);}}}var zt=Object.prototype.hasOwnProperty,he=(r,c)=>zt.call(r,c)?r[c]:void 0;function Ye(r,c,a){c==="__proto__"?Object.defineProperty(r,c,{value:a,enumerable:true,writable:true,configurable:true}):r[c]=a;}var qt=(r=[])=>({vars:new Set(r),bounds:new Map,noCond:false,inferSink:null}),ue=(r,c)=>{let a=new Set(r.vars),i=new Map(r.bounds);for(let y of c)a.add(y.name),y.bound?i.set(y.name,{bound:y.bound}):i.delete(y.name);return {vars:a,bounds:i,noCond:r.noCond,inferSink:r.inferSink}},Fe=r=>({t:"var",name:r.name,...r.bound?{bound:r.bound}:{},...r.default?{default:r.default}:{}}),Wt=(r,c)=>{let a=r.bounds.get(c)?.bound;return a?{t:"var",name:c,bound:a}:{t:"var",name:c}},Ze=r=>{let{peek:c,next:a,isP:i,isK:y,expectP:m,fail:E,unescape:K}=r,h=(l,p)=>{let f=r.tokens[r.pos()-1]??p;return Object.assign(l,{start:p.start,end:f.end,loc:{start:p.loc.start,end:f.loc.end}})},_=()=>{let l=r.pos(),p=r.tokens[l],f=r.tokens[l-1];return !!f&&!!p&&p.loc.start.line>f.loc.end.line},P=()=>{let l=x=>r.tokens[r.pos()+x],p=(x,...k)=>x?.type==="Punctuator"&&k.includes(x.value),f=l(1);if(p(f,")","..."))return true;if(f?.type!=="Identifier")return false;let b=l(2);return p(b,":",",","?","=")?true:p(b,")")&&p(l(3),"=>")},H=()=>{let l=r.tokens,p=[],f=0,b=false;for(let x=r.pos();x<l.length;x++){let k=l[x];if(k.type==="EOF")break;if(k.type==="Punctuator"){if(k.value==="<")f++,f===1&&(b=true);else if(k.value===">"){if(f--,f===0)break}else k.value==="("||k.value==="["||k.value==="{"?(f++,b=false):k.value===")"||k.value==="]"||k.value==="}"?(f--,b=false):k.value===","&&f===1?b=true:b=false;continue}if(f===1&&b){if(k.type==="Keyword"&&k.value==="const")continue;if(k.type==="Identifier"){p.push(k.value),b=false;continue}}b=false;}return p},A=l=>{let p=ue(l,H().map(b=>({name:b})));m("<");let f=[];for(;!i(">");){let b=c();y("const")&&E("'const' type parameters are not supported in this language; a constraint keeps the literal: '<T extends string>'");let x=c();x.type!=="Identifier"&&E("Expected type parameter name"),a();let k,D;if(y("extends")){a();let I=o(p);k=I.schema,D=I.node;}let F,M;if(i("=")){a();let I=o(p);F=I.schema,M=I.node;}f.push(h({type:"TSTypeParameter",name:x.value,...k?{bound:k}:{},...D?{boundNode:D}:{},...F?{default:F}:{},...M?{defaultNode:M}:{}},b)),i(">")||m(",");}return m(">"),f},q=l=>{r.splitShiftLeft(),m("<");let p=[];for(;!i(">");)p.push(o(l)),i(">")||m(",");return m(">"),p},T=l=>{let p=c();return p.type==="Identifier"&&p.value===l},o=l=>{let p=c(),f=C(l);if(l.noCond||!y("extends")||_())return f;a();let b=[],x=C({...l,noCond:true,inferSink:b});m("?");let k=ue(l,b.map(M=>({name:M}))),D=o(k);m(":");let F=o(k);return {node:h({type:"TSConditionalType",checkType:f.node,extendsType:x.node,trueType:D.node,falseType:F.node},p),schema:{t:"conditional",check:f.schema,extends:x.schema,then:D.schema,else:F.schema,...b.length?{infer:b.map(M=>Fe({name:M}))}:{}}}},C=l=>{let p=c();i("|")&&a();let f=G(l);if(!i("|"))return f;let b=[f.node],x=[f.schema];for(;i("|");){a();let k=G(l);b.push(k.node),x.push(k.schema);}return {node:h({type:"TSUnionType",types:b},p),schema:{t:"union",of:x}}},G=l=>{let p=c();i("&")&&a();let f=U(l);if(!i("&"))return f;let b=[f.node],x=[f.schema];for(;i("&");){a();let k=U(l);b.push(k.node),x.push(k.schema);}return {node:h({type:"TSIntersectionType",types:b},p),schema:{t:"intersection",of:x}}},U=l=>{let p=c();if(T("keyof")){a();let f=U(l);return {node:h({type:"TSTypeOperator",operator:"keyof",typeAnnotation:f.node},p),schema:{t:"keyof",of:f.schema}}}if(T("readonly")){a();let f=U(l);return f.schema.t!=="array"&&f.schema.t!=="tuple"&&E("'readonly' only applies to array and tuple types"),{node:h({...f.node,readonly:true},p),schema:{...f.schema,readonly:true}}}if(T("infer")){a();let f=c();f.type!=="Identifier"&&E("Expected 'infer' variable name"),a();let b=l.inferSink;return b?(b.push(f.value),{node:h({type:"TSInferType",name:f.value},p),schema:{t:"var",name:f.value}}):E("'infer' is only allowed in the 'extends' clause of a conditional")}return u(l)},u=l=>{let p=c(),f=Y(l);for(;i("[")&&!_();)if(a(),i("]"))a(),f={node:h({type:"TSArrayType",elementType:f.node},p),schema:{t:"array",items:f.schema}};else {let b=o(l);m("]"),f={node:h({type:"TSIndexedAccessType",objectType:f.node,indexType:b.node},p),schema:{t:"index",obj:f.schema,key:b.schema}};}return f},v=(l,p,f)=>({node:h({type:"TSKeywordType",kind:p},l),schema:f}),B=l=>{let p=r.namespace?.()??null;r.typeRefs?.push(p===null?l:{...l,namespace:p});},R=(l,p,f)=>{let b=[{name:l.value,loc:l.loc}];for(;i(".");){a();let I=c();I.type!=="Identifier"&&I.type!=="Keyword"&&E("Expected a name after '.' in a qualified type name"),a(),b.push({name:I.value,loc:I.loc});}let x=b.map(I=>I.name).join("."),k=i("<")||i("<<")?q(f):[],D=k.map(I=>I.schema),F=h({type:"TSTypeReference",typeName:x,...k.length?{typeArguments:k.map(I=>I.node)}:{}},p),M=b[b.length-1];return B({name:x,loc:{start:l.loc.start,end:M.loc.end},args:D,segments:b}),{node:F,schema:{t:"apply",name:x,args:D}}},Y=l=>{let p=c();if(y("typeof")){a();let x=c();x.type!=="Identifier"&&E("Expected a name after 'typeof' in type position"),a();let k=[x.value];for(;i(".");){a();let D=c();D.type!=="Identifier"&&D.type!=="Keyword"&&E("Expected a property name after '.' in 'typeof'"),a(),k.push(D.value);}return {node:h({type:"TSTypeQuery",exprName:k},p),schema:{t:"typeQuery",path:k}}}if(i("<")){r.rescanTypeLessThan();let x=A(l),k=ue(l,x);return N(k,p,x)}if(i("(")){if(P())return N(l,p);a();let x=o(l.noCond?{...l,noCond:false}:l);return m(")"),x}if(i("{"))return g()?w(l):S(l);if(i("["))return O(l);let f=c();if(f.type==="String"){a();let x=K(f.value.slice(1,-1));return {node:h({type:"TSLiteralType",literal:x},p),schema:{t:"literal",value:x}}}if(f.type==="Number"){a();let x=Number(f.value);return {node:h({type:"TSLiteralType",literal:x},p),schema:{t:"literal",value:x}}}if(y("true"))return a(),{node:h({type:"TSLiteralType",literal:true},p),schema:{t:"literal",value:true}};if(y("false"))return a(),{node:h({type:"TSLiteralType",literal:false},p),schema:{t:"literal",value:false}};if(y("null"))return a(),v(p,"null",{t:"null"});if(y("void"))return a(),v(p,"void",{t:"void"});if(f.type==="Identifier"){if(a(),i("."))return R(f,p,l);switch(f.value){case "string":return v(p,"string",{t:"string"});case "number":return v(p,"number",{t:"number"});case "boolean":return v(p,"boolean",{t:"boolean"});case "any":return v(p,"any",{t:"any"});case "unknown":return v(p,"unknown",{t:"unknown"});case "undefined":return v(p,"undefined",{t:"undefined"});case "never":return v(p,"never",{t:"union",of:[]});case "object":return v(p,"object",{t:"nonPrimitive"})}let x=i("<")||i("<<")?q(l):[],k=x.map(M=>M.schema),D=x.length?x.map(M=>M.node):void 0,F=h({type:"TSTypeReference",typeName:f.value,...D?{typeArguments:D}:{}},p);return l.vars.has(f.value)&&k.length===0?{node:F,schema:Wt(l,f.value)}:(B({name:f.value,loc:f.loc,args:k}),{node:F,schema:{t:"apply",name:f.value,args:k}})}r.recordError(`Expected a type but got '${f.value||f.type}'`,f);let b=r.createMissingNode({type:"TSTypeReference",typeName:""},f);return B({name:"",loc:b.loc,args:[]}),{node:b,schema:{t:"unknown"}}},Z=l=>{m("(");let p=[];for(;!i(")");){let f=c(),b=i("...");b&&a();let x=c();x.type!=="Identifier"&&E("Expected parameter name in function type"),a();let k=!b&&i("?");k&&a(),m(":");let D=o(l),F=h({type:"Identifier",name:x.value,typeAnnotationNode:D.node,...k?{optional:true}:{}},x);p.push({node:b?h({type:"RestElement",argument:F},f):F,schema:{name:x.value,type:D.schema,...k?{optional:true}:{},...b?{variadic:true}:{}}}),b&&!i(")")&&E("A rest parameter must be last in a parameter list"),i(")")||m(",");}return m(")"),p},re=(l,p)=>{let f=c(),b=r.tokens[r.pos()+1];if(!(f.type==="Identifier"&&b?.type==="Identifier"&&b.value==="is"))return o(l);let k=p.indexOf(f.value);k<0&&E(`Cannot find parameter '${f.value}' for the type predicate`),a(),a();let D=o(l);return {node:h({type:"TSTypePredicate",parameterName:f.value,typeAnnotation:D.node},f),schema:{t:"boolean"},guard:{param:k,type:D.schema}}},N=(l,p,f)=>{let b=Z(l);m("=>");let x=re(l,b.map(k=>k.schema.name));return {node:h({type:"TSFunctionType",params:b.map(k=>k.node),returnType:x.node,...f?.length?{typeParameters:[...f]}:{}},p),schema:{t:"fn",params:b.map(k=>k.schema),returns:x.schema,...x.guard?{guard:x.guard}:{},...f?.length?{typeParams:f.map(Fe)}:{}}}},O=l=>{let p=c();m("[");let f=[],b=[],x=[],k=[],D=()=>{let I=r.tokens[r.pos()],J=r.tokens[r.pos()+1],V=r.tokens[r.pos()+2];if(I?.type==="Identifier"&&J?.type==="Punctuator"&&(J.value===":"||J.value==="?"&&V?.type==="Punctuator"&&V.value===":"))return a(),I.value};for(;!i("]");){if(x[x.length-1]==="rest"&&E("A rest element must be last in a tuple type"),i("...")){a();let I=D();I!==void 0&&m(":"),k.push(I);let J=o(l);J.schema.t!=="array"&&E("A rest element type must be written as an array type ('...T[]')"),b.push(J.schema.items),f.push(J.node.elementType),x.push("rest");}else {let I=D(),J=false;I!==void 0&&(i("?")&&(a(),J=true),m(":")),k.push(I);let V=o(l);!J&&i("?")&&(a(),J=true),b.push(V.schema),f.push(V.node),x.push(J?"optional":"req");}i("]")||m(",");}m("]");let F=x.some(I=>I!=="req"),M=k.some(I=>I!==void 0);return {node:h({type:"TSTupleType",elementTypes:f,...F?{flags:x}:{},...M?{labels:k}:{}},p),schema:F?{t:"tuple",elements:b,flags:x}:{t:"tuple",elements:b}}},g=()=>{let l=r.tokens,p=r.pos()+1;return l[p]?.type==="Punctuator"&&(l[p]?.value==="+"||l[p]?.value==="-")&&(p++,!(l[p]?.type==="Identifier"&&l[p]?.value==="readonly"))?false:(l[p]?.type==="Identifier"&&l[p]?.value==="readonly"&&p++,l[p]?.type==="Punctuator"&&l[p]?.value==="["&&l[p+1]?.type==="Identifier"&&l[p+2]?.type==="Keyword"&&l[p+2]?.value==="in")},w=l=>{let p=c();m("{");let f=i("+")||i("-")?a().value:null,b;T("readonly")&&(a(),b=f==="+"?"+":f==="-"?"-":true),m("[");let x=c();x.type!=="Identifier"&&E("Expected mapped type key name"),a(),y("in")||E("Expected 'in' in mapped type"),a();let k=o(l);T("as")&&E("Key remapping ('as') in mapped types is not supported"),m("]");let D=i("+")||i("-")?a().value:null,F;D!==null&&!i("?")&&E("'?' expected"),i("?")&&(a(),F=D==="+"?"+":D==="-"?"-":true),m(":");let M=o(ue(l,[{name:x.value}]));return (i(";")||i(","))&&a(),m("}"),{node:h({type:"TSMappedType",key:x.value,constraint:k.node,typeAnnotation:M.node,...b!==void 0?{readonly:b}:{},...F!==void 0?{optional:F}:{}},p),schema:{t:"mapped",key:x.value,over:k.schema,body:M.schema,...F===true||F==="+"?{optional:true}:{},...F==="-"?{excludeOptional:true}:{},...b===true||b==="+"?{readonly:true}:{},...b==="-"?{excludeReadonly:true}:{}}}},S=l=>{let p=c();m("{");let f=[],b={},x,k=[];for(;!i("}");){let F=c(),M=T("readonly")&&r.tokens[r.pos()+1]?.value==="[";if(M&&a(),!M&&(i("(")||i("<"))){i("<")&&r.rescanTypeLessThan();let I=i("<")?A(l):[],J=I.length?ue(l,I):l,V=Z(J);m(":");let Q=re(J,V.map(ee=>ee.schema.name));k.push({t:"fn",params:V.map(ee=>ee.schema),returns:Q.schema,...Q.guard?{guard:Q.guard}:{},...I.length?{typeParams:I.map(Fe)}:{}}),f.push(h({type:"TSCallSignatureDeclaration",params:V.map(ee=>ee.node),returnType:Q.node,...I.length?{typeParameters:I}:{}},F));}else if(i("[")){a(),c().type!=="Identifier"&&E("Expected index signature parameter name"),a(),m(":");let I=c();(I.type!=="Identifier"||I.value!=="string"&&I.value!=="number")&&E("Index signature parameter type must be 'string' or 'number'"),a(),m("]"),m(":");let J=o(l);x={key:I.value,value:J.schema,...M?{readonly:true}:{}},f.push(h({type:"TSIndexSignature",keyType:I.value,typeAnnotation:J.node,...M?{readonly:true}:{}},F));}else {let I=false;if(T("readonly")){let ce=r.tokens[r.pos()+1];ce&&(ce.type==="Identifier"||ce.type==="Keyword"||ce.type==="String"||ce.type==="Number")&&(a(),I=true);}let J=c(),V;if(J.type==="Identifier"||J.type==="Keyword")a(),V=J.value;else if(J.type==="String")a(),V=K(J.value.slice(1,-1));else if(J.type==="Number")a(),V=J.value;else return E("Expected property name in object type");let Q=i("?");Q&&a(),m(":");let ee=o(l);Ye(b,V,{type:ee.schema,...Q?{optional:true}:{},...I?{readonly:true}:{}}),f.push(h({type:"TSPropertySignature",key:V,typeAnnotation:ee.node,...Q?{optional:true}:{},...I?{readonly:true}:{}},F));}if(i(";")||i(","))a();else break}m("}");let D=h({type:"TSTypeLiteral",members:f},p);return k.length>0?Object.keys(b).length>0||x?E("Callable object types (call signatures mixed with members) are not supported"):{node:D,schema:k.length===1?k[0]:{t:"overload",signatures:k}}:{node:D,schema:{t:"object",props:b,...x?{index:x}:{}}}},X=qt();return {parseType:()=>o(X),parseReturnType:l=>re(X,l),parseTypeParamList:()=>A(X),parseTypeInScope:l=>o(ue(X,l)),withTypeParams:(l,p)=>{let f=X;X=ue(f,l);try{return p()}finally{X=f;}}}};var le=class extends ast.TSLiteError{constructor(a,i,y,m,E){super("parse-error",`${a} (${i.line}:${i.column})`,{position:i,index:y,loc:m,end:E});this.position=i;this.index=y;this.loc=m;this.end=E;this.name="ParseError";}},Qt=r=>{let c=r;return c!=null&&typeof c.start=="number"&&c.start===c.end&&c.start>=0},et=(r,c)=>Object.assign(r,{start:c.start,end:c.start,loc:{start:c.loc.start,end:c.loc.start}}),Yt={"??":1,"||":2,"&&":3,"|":4,"^":5,"&":6,"==":7,"===":7,"!=":7,"!==":7,"<":8,"<=":8,">":8,">=":8,in:8,as:8,satisfies:8,"<<":9,">>":9,">>>":9,"+":10,"-":10,"*":11,"/":11,"%":11,"**":12},Zt=new Set(["??","||","&&"]),en=new Set(["class","debugger","with","enum","interface"]),tt={enum:'use a union of literals (`type T = "a" | "b"`) \u2014 it is serializable',interface:"use a type alias (`type X = { \u2026 }`)",module:"write it as `namespace X { \u2026 }` \u2014 the same declaration",abstract:"classes are not part of the language \u2014 model with objects + functions"},tn={module:(r,c)=>r.type==="Identifier"&&c.type==="Punctuator"&&c.value==="{",abstract:r=>r.type==="Keyword"&&r.value==="class"},nn=new Set(["=","+=","-=","*=","/=","%=","**=","??=","&&=","||="]),nt=(r,c)=>{let a=0;for(let i of r)c(i)&&(r[a++]=i);r.length=a;};function Ke(r){let c=[],a=[],i=[],y=Ae(r,e=>i.push(e),e=>c.push({code:"lex-error",...e})),m=y.scan(),E=0,K=[],h=e=>{for(;K.length>e;)K.pop()();},_=(e=E)=>{let t=m[e];if(t?.type!=="Punctuator"||t.value!=="<"||!y.opensJsx(t.start))return;let n=m.slice(e),s=c.slice(),d=i.slice();nt(c,j=>j.code!=="lex-error"||j.index<t.start),nt(i,j=>j.start<t.start);let L=y.rescanLessThan(t.start);m.splice(e,m.length-e,...L),K.push(()=>{m.splice(e,m.length-e,...n),c.splice(0,c.length,...s),i.splice(0,i.length,...d);});},P=()=>{let e=m[E];if(e?.type!=="Punctuator"||e.value!=="<<")return;let t={line:e.loc.start.line,column:e.loc.start.column+1},n=E;m.splice(n,1,{...e,value:"<",end:e.start+1,loc:{start:e.loc.start,end:t}},{...e,value:"<",start:e.start+1,loc:{start:t,end:e.loc.end}}),K.push(()=>m.splice(n,2,e));},H=[],A=[],q=false,T=(e=0)=>m[Math.min(E+e,m.length-1)],o=()=>m[E++],C=()=>m[E-1],G=()=>{let e=m[E],t=m[E-1];return !!e&&!!t&&e.loc.start.line>t.loc.end.line},U=()=>T().type==="EOF",u=e=>T().type==="Punctuator"&&T().value===e,v=e=>T().type==="Keyword"&&T().value===e,B=e=>T().type==="Identifier"&&T().value===e,R=(e,t=T())=>{throw Y(e,t),new le(e,t.loc.start,t.start,t.loc,t.end)},Y=(e,t=T())=>{let n=c[c.length-1];n&&n.index===t.start||c.push({code:"parse-error",message:e,position:t.loc.start,index:t.start,loc:t.loc,end:t.end});},Z=(e,t)=>{a.push({code:"parse-error",message:e,position:t.loc.start,index:t.start,loc:t.loc,end:t.end});},re=()=>{c.length||c.push(...a),a.length=0;},N=e=>(u(e)||R(`Expected '${e}' but got '${T().value||T().type}'`),o()),O=(e,t)=>{let n=C()??t;return Object.assign(e,{start:t.start,end:n.end,loc:{start:t.loc.start,end:n.loc.end}})},g=(e,t,n)=>Object.assign(e,{start:t.start,end:n.end,loc:{start:t.loc.start,end:n.loc.end}}),w=e=>{let t="";for(let n=0;n<e.length;n++){if(e[n]!=="\\"){t+=e[n];continue}let s=e[++n];switch(s){case "n":t+=`
|
|
6
|
-
`;break;case "t":t+=" ";break;case "r":t+="\r";break;case "b":t+="\b";break;case "f":t+="\f";break;case "v":t+="\v";break;case "0":t+="\0";break;case "x":t+=String.fromCharCode(parseInt(e.slice(n+1,n+3),16)),n+=2;break;case "u":if(e[n+1]==="{"){let d=e.indexOf("}",n);t+=String.fromCodePoint(parseInt(e.slice(n+2,d),16)),n=d;}else t+=String.fromCharCode(parseInt(e.slice(n+1,n+5),16)),n+=4;break;default:t+=s;}}return t},S=(e=false)=>X(e),X=(e=false)=>{let t=l(e),n=T();if(n.type==="Punctuator"&&nn.has(n.value)){o();let s=X();return g({type:"AssignmentExpression",operator:n.value,left:t,right:s},t,s)}return t},l=(e=false)=>{let t=f(0,e);if(!u("?"))return t;o();let n=S();N(":");let s=S();return g({type:"ConditionalExpression",test:t,consequent:n,alternate:s},t,s)},p=()=>{let e=T();if(e.type==="Keyword")return e.value==="in"?{op:"in",consume:1}:null;if(e.type==="Identifier")return e.value==="as"?{op:"as",consume:1}:e.value==="satisfies"?{op:"satisfies",consume:1}:null;if(e.type!=="Punctuator")return null;if(e.value===">"){let t=T(1);if(t.type==="Punctuator"&&t.value===">"&&e.end===t.start){let n=T(2);return n.type==="Punctuator"&&n.value===">"&&t.end===n.start?{op:">>>",consume:3}:{op:">>",consume:2}}return {op:">",consume:1}}return {op:e.value,consume:1}},f=(e,t=false)=>{let n=b();for(;;){let s=p();if(!s)break;let{op:d,consume:L}=s;if(d==="in"&&t)break;let j=he(Yt,d);if(!j||j<=e)break;if(d==="satisfies"){if(G())break;R("'satisfies' is not supported in this language \u2014 a type annotation (`const x: T = \u2026`) also checks compatibility, but it declares the type as T, while 'satisfies' keeps the inferred one");}if(d==="as"){if(G())break;o();let $=be();n=g({type:"TSAsExpression",expression:n,typeAnnotation:$.schema,typeAnnotationNode:$.node},n,C());continue}for(let $=0;$<L;$++)o();let z=f(d==="**"?j-1:j,t);n=g({type:Zt.has(d)?"LogicalExpression":"BinaryExpression",operator:d,left:n,right:z},n,z);}return n},b=()=>{let e=T();return e.type==="Punctuator"&&(e.value==="++"||e.value==="--")?(o(),O({type:"UpdateExpression",operator:e.value,prefix:true,argument:b()},e)):v("await")?(o(),O({type:"AwaitExpression",argument:b()},e)):v("typeof")||v("void")||v("delete")||e.type==="Punctuator"&&(e.value==="!"||e.value==="-"||e.value==="+"||e.value==="~")?x(e):D()},x=e=>{o();let t=b();return u("**")&&R(`An unary expression with the '${e.value}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.`),O({type:"UnaryExpression",operator:e.value,prefix:true,argument:t},e)},k=()=>{let e=E,t=K.length,n=c.length,s=H.length,d=()=>(h(t),E=e,c.length=n,H.length=s,void 0);try{if(P(),o(),u(">"))return d();let L=[];for(;L.push(be().schema),!!u(",");)o();return u(">")?(o(),u("(")?L:d()):d()}catch{return d()}},D=()=>{let e=ft(),t=false;for(;;)if((T().type==="Template"||T().type==="TemplateHead")&&R("Tagged templates are not supported in this language"),u("?."))if(o(),t=true,u("(")){let{args:n,close:s}=F();e=g({type:"CallExpression",callee:e,arguments:n,optional:true},e,s);}else if(u("[")){o();let n=S(),s=N("]");e=g({type:"MemberExpression",object:e,property:n,computed:true,optional:true},e,s);}else {let n=T();n.type!=="Identifier"&&n.type!=="Keyword"&&R("Expected property name after '?.'"),o();let s=O({type:"Identifier",name:n.value},n);e=g({type:"MemberExpression",object:e,property:s,computed:false,optional:true},e,s);}else if(u(".")){o();let n=T(),s;n.type==="Identifier"||n.type==="Keyword"?(o(),s=O({type:"Identifier",name:n.value},n)):(Y("Expected property name"),s=et({type:"Identifier",name:""},n)),e=g({type:"MemberExpression",object:e,property:s,computed:false,optional:false},e,s);}else if(u("[")){o();let n=S(),s=N("]");e=g({type:"MemberExpression",object:e,property:n,computed:true,optional:false},e,s);}else if(u("(")){let{args:n,close:s}=F();e=g({type:"CallExpression",callee:e,arguments:n,optional:false},e,s);}else if(u("<")||u("<<")){let n=k();if(!n)break;let{args:s,close:d}=F();e=g({type:"CallExpression",callee:e,arguments:s,optional:false,typeArguments:n},e,d);}else if(u("++")||u("--")){let n=o();e=g({type:"UpdateExpression",operator:n.value,prefix:false,argument:e},e,n);}else break;return t?g({type:"ChainExpression",expression:e},e,e):e},F=()=>{N("(");let e=[];for(;!u(")");)e.push(M()),u(")")||N(",");return {args:e,close:N(")")}},M=()=>{if(u("...")){let e=o(),t=S();return g({type:"SpreadElement",argument:t},e,t)}return S()},I=()=>{let e=T();return e.type!=="Identifier"&&R("Expected identifier"),o(),O({type:"Identifier",name:e.value},e)},J=(e=false)=>{let t=u("{")?V():u("[")?Q():I();if(e&&u("?")&&(t.type!=="Identifier"&&R("A binding pattern parameter cannot be optional"),o(),t.optional=true),u(":")){o();let n=be();t.typeAnnotation=n.schema,t.typeAnnotationNode=n.node;}return t},V=()=>{let e=N("{"),t=[];for(;!u("}");){if(u("...")){let s=o(),d=J();t.push(g({type:"RestElement",argument:d},s,d));}else {let s=I(),d,L=false;if(u(":")?(o(),d=J()):(d={...s},L=true),u("=")){o();let j=S();d=g({type:"AssignmentPattern",left:d,right:j},d,j);}t.push(g({type:"Property",key:s,value:d,kind:"init",shorthand:L,computed:false},s,d));}u("}")||N(",");}let n=N("}");return g({type:"ObjectPattern",properties:t},e,n)},Q=()=>{let e=N("["),t=[];for(;!u("]");){if(u(",")){t.push(null),o();continue}if(u("...")){let s=o(),d=J();t.push(g({type:"RestElement",argument:d},s,d));}else {let s=J();if(u("=")){o();let d=S();s=g({type:"AssignmentPattern",left:s,right:d},s,d);}t.push(s);}u("]")||N(",");}let n=N("]");return g({type:"ArrayPattern",elements:t},e,n)},ee=()=>{let e=K.length,t=ce();return t||h(e),t},ce=()=>{let e=0,t="name";for(let n=E;n<m.length;n++){let s=m[n];if(s.type==="EOF")return false;if(s.type==="Punctuator"){if(s.value==="<"&&t==="type"){_(n);continue}if(e===1&&s.value===":"&&t==="name"?t="type":e===1&&s.value==="="?t="default":e===1&&s.value===","&&(t="name"),s.value==="("||s.value==="["||s.value==="{")e++;else if((s.value===")"||s.value==="]"||s.value==="}")&&(e--,e===0)){let d=m[n+1];return !d||d.type!=="Punctuator"?false:d.value==="=>"?true:d.value===":"?ot(n+2):false}}}return false},ot=e=>{let t=0;for(let n=e;n<m.length;n++){let s=m[n];if(s.type==="EOF")return false;if(s.type==="Punctuator")if(s.value==="<"&&_(n),["(","[","{","<"].includes(s.value))t++;else if([")","]","}",">"].includes(s.value)){if(t===0)return false;t--;}else {if(t===0&&s.value==="=>")return true;if(t===0&&(s.value===";"||s.value===","))return false}}return false},st=()=>{N("(");let e=[];for(;!u(")");){if(u("...")){let t=o(),n=J();e.push(g({type:"RestElement",argument:n},t,n));}else {let t=J(true);if(u("=")){t.optional&&R("Parameter cannot have question mark and initializer"),o();let n=S();t=g({type:"AssignmentPattern",left:t,right:n},t,n);}e.push(t);}u(")")||N(",");}return N(")"),e},at=e=>{if(e.type==="Identifier")return e.name;let t=e.left;return e.type==="AssignmentPattern"&&t?.type==="Identifier"?t.name:null},ge=(e,t,n=[])=>ht(n,()=>it(e,t,n)),it=(e,t,n)=>{let s=u("(")?st():[I()],d,L,j;if(u(":")){o();let $=yt(s.map(at));d=$.schema,L=$.node,j=$.guard;}N("=>");let z=u("{")?ye():S();return O({type:"ArrowFunctionExpression",params:s,body:z,async:e,expression:z.type!=="BlockStatement",generator:false,...d?{returnType:d,returnTypeNode:L}:{},...j?{returnGuard:j}:{},...n.length?{typeParameters:[...n]}:{}},t)},lt=()=>{let e=N("["),t=[];for(;!u("]");){if(u(",")){o(),t.push(null);continue}t.push(M()),u("]")||N(",");}return g({type:"ArrayExpression",elements:t},e,N("]"))},ct=()=>{let e=N("{"),t=[];for(;!u("}");){if(u("...")){let n=o(),s=S();t.push(g({type:"SpreadElement",argument:s},n,s));}else {let n=T(),s,d=false;if(u("["))d=true,o(),s=S(),N("]");else if(n.type==="String")o(),s=O({type:"Literal",value:w(n.value.slice(1,-1)),raw:n.value},n);else if(n.type==="Number")o(),s=O({type:"Literal",value:Number(n.value),raw:n.value},n);else if(n.type==="Identifier"||n.type==="Keyword")o(),s=O({type:"Identifier",name:n.value},n);else return R("Invalid property key");if(u(":")){o();let L=S();t.push(g({type:"Property",key:s,value:L,kind:"init",shorthand:false,computed:d},n,L));}else t.push(g({type:"Property",key:s,value:s,kind:"init",shorthand:true,computed:false},n,s));}u("}")||N(",");}return g({type:"ObjectExpression",properties:t},e,N("}"))},Te=(e,t)=>({type:"TemplateElement",value:{raw:e,cooked:w(e)},tail:t}),pt=e=>{o();let t=[Te(e.value,false)],n=[];for(;;){n.push(S());let s=T();if(s.type==="TemplateMiddle")o(),t.push(Te(s.value,false));else if(s.type==="TemplateTail"){o(),t.push(Te(s.value,true));break}else R("Expected `}` to close template interpolation");}return O({type:"TemplateLiteral",quasis:t,expressions:n},e)},de=()=>{let e=T();return e.type!=="Identifier"&&R(`Expected JSX identifier but got '${e.value||e.type}'`),O({type:"JSXIdentifier",name:o().value},e)},Xe=()=>{let e=de();if(u(":")){o();let t=de();return g({type:"JSXNamespacedName",namespace:e,name:t},e,t)}for(;u(".");){o();let t=de();e=g({type:"JSXMemberExpression",object:e,property:t},e,t);}return e},oe=e=>e.type==="JSXIdentifier"?e.name:e.type==="JSXNamespacedName"?`${oe(e.namespace)}:${oe(e.name)}`:`${oe(e.object)}.${oe(e.property)}`,ut=()=>{let e=T();if(e.type==="String")return o(),O({type:"Literal",value:w(e.value.slice(1,-1)),raw:e.value},e);if(u("{")){let t=o(),n=X(),s=N("}");return g({type:"JSXExpressionContainer",expression:n},t,s)}return u("<")?Pe():R(`Invalid JSX attribute value '${e.value||e.type}'`)},dt=()=>{let e=[];for(;!u(">")&&!u("/>")&&!U();){if(u("{")){let s=o();N("...");let d=X(),L=N("}");e.push(g({type:"JSXSpreadAttribute",argument:d},s,L));continue}let t=de();if(u(":")){o();let s=de();t=g({type:"JSXNamespacedName",namespace:t,name:s},t,s);}let n=null;u("=")&&(o(),n=ut()),e.push(g({type:"JSXAttribute",name:t,value:n},t,n??t));}return e},Me=()=>{let e=[];for(;!(u("</")||U());){let t=T();if(t.type==="JSXText")o(),e.push(O({type:"JSXText",value:t.value,raw:t.value},t));else if(u("{")){let n=o();if(u("}")){let s=o(),d=O({type:"JSXEmptyExpression"},n);e.push(g({type:"JSXExpressionContainer",expression:d},n,s));}else if(u("...")){o();let s=X(),d=N("}");e.push(g({type:"JSXSpreadChild",expression:s},n,d));}else {let s=X(),d=N("}");e.push(g({type:"JSXExpressionContainer",expression:s},n,d));}}else u("<")?e.push(Pe()):R(`Unexpected token in JSX children '${t.value||t.type}'`);}return e},Pe=()=>{let e=N("<");if(u(">")){let ne=o(),pe=g({type:"JSXOpeningFragment"},e,ne),Lt=Me(),jt=N("</"),Ge=N(">"),At=g({type:"JSXClosingFragment"},jt,Ge);return g({type:"JSXFragment",openingFragment:pe,children:Lt,closingFragment:At},e,Ge)}let t=Xe(),n=dt();if(u("/>")){let ne=o(),pe=g({type:"JSXOpeningElement",name:t,attributes:n,selfClosing:true},e,ne);return g({type:"JSXElement",openingElement:pe,children:[],closingElement:null},e,ne)}let s=N(">"),d=g({type:"JSXOpeningElement",name:t,attributes:n,selfClosing:false},e,s),L=Me(),j=N("</"),z=T(),$=Xe();oe($)!==oe(t)&&R(`JSX closing tag </${oe($)}> does not match opening <${oe(t)}>`,z);let W=N(">"),te=g({type:"JSXClosingElement",name:$},j,W);return g({type:"JSXElement",openingElement:d,children:L,closingElement:te},e,W)},ft=()=>{let e=T();if(v("async")){let t=T(1);if(t.value==="("||t.type==="Identifier")return o(),ge(true,e);if(t.value==="<"){o();let n=$e(e,true);if(n)return n}return R("Unexpected 'async'")}if(u("(")&&ee()||e.type==="Identifier"&&T(1).type==="Punctuator"&&T(1).value==="=>")return ge(false,e);if(e.type==="Number")return o(),O({type:"Literal",value:Number(e.value),raw:e.value},e);if(e.type==="String")return o(),O({type:"Literal",value:w(e.value.slice(1,-1)),raw:e.value},e);if(e.type==="Template")return o(),O({type:"TemplateLiteral",expressions:[],quasis:[Te(e.value,true)]},e);if(e.type==="TemplateHead")return pt(e);if(e.type==="Keyword")return e.value==="true"?(o(),O({type:"Literal",value:true,raw:"true"},e)):e.value==="false"?(o(),O({type:"Literal",value:false,raw:"false"},e)):e.value==="null"?(o(),O({type:"Literal",value:null,raw:"null"},e)):e.value==="new"?R("'new' is not supported \u2014 the language has no constructors (FP / portable IR). Use a factory function provided via DI (e.g. `now()` instead of `new Date()`)."):e.value==="function"?R("Anonymous functions are not supported \u2014 use an arrow function"):R(`'${e.value}' is not supported in this language`);if(e.type==="Identifier")return o(),O({type:"Identifier",name:e.value},e);if(u("(")){o();let t=S();return N(")"),t}return u("[")?lt():u("{")?ct():u("<")?$e(e)??Pe():R(`Unexpected token '${e.value||e.type}'`)},$e=(e,t=false)=>{let n=E,s=K.length,d=c.length,L=a.length,j=H.length,z=()=>(h(s),E=n,c.length=d,a.length=L,H.length=j,void 0),$=T(1);$.type==="Keyword"&&$.value==="const"&&Ne();try{let W=Ne();return !W.length||!u("(")?z():ge(t,e,W)}catch{return z()}},{parseType:be,parseReturnType:yt,parseTypeParamList:Ne,parseTypeInScope:mt,withTypeParams:ht}=Ze({rescanTypeLessThan:_,splitShiftLeft:P,tokens:m,pos:()=>E,peek:T,next:o,isP:u,isK:v,expectP:N,fail:R,recordError:Y,createMissingNode:et,unescape:w,typeRefs:H,namespace:()=>A.length?A.join("."):null}),Ee=()=>{let e=o(),t=I(),n=[];u("<")&&(n=Ne()),N("=");let s=mt(n),d=g({type:"TSTypeAliasDeclaration",id:t,...n.length?{typeParameters:[...n]}:{},typeAnnotation:s.schema,typeNode:s.node},e,C());return u(";")&&o(),d},Ie=(e,t)=>t.loc.start.line===e.loc.end.line,ve=(e=0)=>T(e).type==="Identifier"&&T(e).value==="namespace"&&T(e+1).type==="Identifier"&&Ie(T(e),T(e+1)),gt=()=>B("declare")&&Ie(T(),T(1))&&ve(1),fe=e=>{let t=T(e),n=T(e+1),s=Ie(t,n);if(t.type==="Keyword")switch(t.value){case "var":case "let":case "const":case "function":case "class":case "enum":return true;case "interface":return n.type==="Identifier"&&s;case "async":return s&&fe(e+1);case "import":return n.type==="String"||n.type==="Identifier"||n.type==="Keyword"||n.type==="Punctuator"&&(n.value==="*"||n.value==="{");case "export":{let d=n.type==="Identifier"&&n.value==="type"?T(e+2):n;return d.type==="Punctuator"&&["=","*","{"].includes(d.value)||d.type==="Keyword"&&d.value==="default"||d.type==="Identifier"&&d.value==="as"||fe(e+1)}default:return false}if(t.type!=="Identifier")return false;switch(t.value){case "type":return n.type==="Identifier"&&s;case "namespace":case "module":return (n.type==="Identifier"||n.type==="String")&&s;case "abstract":case "declare":case "private":case "protected":case "public":case "readonly":return s&&fe(e+1);case "global":return n.type==="Punctuator"&&n.value==="{"||n.type==="Identifier"||n.type==="Keyword"&&n.value==="export";case "static":return fe(e+1);default:return false}},Ue=()=>B("declare")&&fe(0),Ce=()=>{let e=T(),t=B("declare");return t&&o(),o(),Be(e,t)},Be=(e,t)=>{let n=I();A.push(n.name);let s=q;t&&(q=true);try{let d;if(u("."))o(),d=Be(T(),!1);else {let L=N("{"),j=je(()=>u("}"));d=g({type:"TSModuleBlock",body:j},L,N("}"));}return g({type:"TSModuleDeclaration",id:n,body:d,...t?{declare:!0}:{}},e,d)}finally{q=s,A.pop();}},_e=()=>{if(gt())return Ce();let e=o();if(v("const")||v("let")||v("var")){let t=q;q=true;try{let n=g(Object.assign(Re(),{declare:!0}),e,C());return u(";")&&o(),n}finally{q=t;}}if(B("type")){let t=Ee();return g(Object.assign(t,{declare:true}),e,t)}return Tt()},Tt=()=>{let e=T();if(v("export"))return R("'export' modifier must precede 'declare' modifier.");if(v("import"))return R("A 'declare' modifier cannot be used with an import declaration.");if(e.type==="Identifier"&&["public","private","protected","static"].includes(e.value))return R(`'${e.value}' modifier cannot appear on a module or namespace element.`);if(B("readonly"))return R("'readonly' modifier can only appear on a property declaration or index signature.");if(v("function")||v("async"))return R("Function declarations are not supported \u2014 use 'const fn = () => \u2026'");if(e.type==="Identifier"&&e.value==="module"&&T(1).type==="String"||e.type==="Identifier"&&e.value==="global")return R(`'declare ${e.value}' is not supported in this language \u2014 it declares the types of an external module or of the global scope, and module resolution belongs to the application`);let t=he(tt,e.value);return R(`'${e.value}' is not supported in this language`+(t?` \u2014 ${t}`:""))},se=()=>{let e=T();if(e.type==="Identifier"&&e.value==="type"&&T(1).type==="Identifier"&&T(2).type==="Punctuator"&&(T(2).value==="="||T(2).value==="<"))return Ee();if(ve())return Ce();if(Ue())return _e();if(v("const")||v("let")||v("var")){let d=Re();return u(";")&&o(),d}if(v("if"))return Nt();if(v("for"))return St();if(v("while"))return Pt();if(v("do"))return kt();if(v("break")||v("continue"))return wt();if(v("return"))return Et();if(v("throw"))return It();if(v("try"))return Ct();if(v("switch"))return Rt();if(v("import"))return vt();if(v("export"))return xt();if(u("{"))return ye();if((v("function")||v("async")&&T(1).type==="Keyword"&&T(1).value==="function")&&R("Function declarations are not supported \u2014 use 'const fn = () => \u2026'"),u(";"))return o(),O({type:"EmptyStatement"},e);if(e.type==="Keyword"&&en.has(e.value)||e.type==="Identifier"&&he(tn,e.value)?.(T(1),T(2))===true){let d=he(tt,e.value);R(`'${e.value}' is not supported in this language`+(d?` \u2014 ${d}`:""));}let n=S(),s=u(";")?o():C();return g({type:"ExpressionStatement",expression:n},n,s)},Re=()=>{let e=o(),t=e.value,n=()=>{let d=J(),L=null;return u("=")?(o(),L=S()):!q&&d.type!=="Identifier"?Z("A destructuring declaration must have an initializer.",d):t==="const"&&!q&&Z("'const' declarations must be initialized",d),g({type:"VariableDeclarator",id:d,init:L},d,L??d)},s=[n()];for(;u(",");)o(),s.push(n());return g({type:"VariableDeclaration",kind:t,declarations:s},e,s[s.length-1])},bt=()=>{let e=T();return e.type!=="String"&&R("Expected module specifier string"),o(),O({type:"Literal",value:w(e.value.slice(1,-1)),raw:e.value},e)},vt=()=>{let e=o(),t=[],n;if(B("type")){let d=T(1);(d.type==="Punctuator"&&(d.value==="{"||d.value==="*")||d.type==="Identifier"&&d.value!=="from")&&(o(),n="type");}if(T().type!=="String"){if(T().type==="Identifier"){let d=I();t.push(g({type:"ImportDefaultSpecifier",local:d},d,d)),u(",")&&o();}if(u("*")){let d=o();B("as")||R("Expected 'as' after '*' in import"),o();let L=I();t.push(g({type:"ImportNamespaceSpecifier",local:L},d,L));}else if(u("{")){for(o();!u("}")&&!U();){let d;B("type")&&T(1).type==="Identifier"&&T(1).value!=="as"&&(o(),d="type");let L=I(),j=L;if(B("as")&&(o(),j=I()),t.push(g({type:"ImportSpecifier",imported:L,local:j,...d?{importKind:d}:{}},L,j)),u(","))o();else break}N("}");}B("from")||R("Expected 'from' in import declaration"),o();}let s=bt();return u(";")&&o(),O({type:"ImportDeclaration",specifiers:t,source:s,...n?{importKind:n}:{}},e)},xt=()=>{let e=o();if(B("type")&&T(1).type==="Identifier"){let t=Ee();return O({type:"ExportNamedDeclaration",declaration:t,specifiers:[],source:null},e)}if(ve()||Ue()){let t=ve()?Ce():_e();return O({type:"ExportNamedDeclaration",declaration:t,specifiers:[],source:null},e)}if(v("default")){o();let t=S();return u(";")&&o(),O({type:"ExportDefaultDeclaration",declaration:t},e)}if(v("const")||v("let")||v("var")){let t=Re();return u(";")&&o(),O({type:"ExportNamedDeclaration",declaration:t,specifiers:[],source:null},e)}if(u("{")){o();let t=[];for(;!u("}")&&!U();){let n=I(),s=n;if(B("as")&&(o(),s=I()),t.push(g({type:"ExportSpecifier",local:n,exported:s},n,s)),u(","))o();else break}return N("}"),u(";")&&o(),O({type:"ExportNamedDeclaration",declaration:null,specifiers:t,source:null},e)}return R("Expected 'const', 'type', 'namespace', 'declare', '{', or 'default' after 'export'")},Ve=()=>T().type==="Identifier"&&T().value==="of",Le=()=>v("in"),St=()=>{let e=o();N("(");let t=null,n=null;if(!u(";"))if(v("const")||v("let")||v("var")){let j=o(),z=()=>{let W=I();if(u(":")){o();let te=be();W.typeAnnotation=te.schema,W.typeAnnotationNode=te.node;}return W},$=z();if(Ve()||Le()){let W=g({type:"VariableDeclarator",id:$,init:null},$,$);n=g({type:"VariableDeclaration",kind:j.value,declarations:[W]},j,$);}else {let W=ne=>{let pe=null;return u("=")?(o(),pe=S(true)):j.value==="const"&&Z("'const' declarations must be initialized",ne),g({type:"VariableDeclarator",id:ne,init:pe},ne,pe??ne)},te=[W($)];for(;u(",");)o(),te.push(W(z()));t=g({type:"VariableDeclaration",kind:j.value,declarations:te},j,te[te.length-1]);}}else {let j=S(true);Ve()||Le()?n=j:t=j;}if(n){let j=Le();o();let z=S();N(")");let $=se();return g(j?{type:"ForInStatement",left:n,right:z,body:$}:{type:"ForOfStatement",left:n,right:z,body:$,await:false},e,$)}N(";");let s=u(";")?null:S();N(";");let d=u(")")?null:S();N(")");let L=se();return g({type:"ForStatement",init:t,test:s,update:d,body:L},e,L)},kt=()=>{let e=o(),t=se();v("while")||R("Expected 'while' after the 'do' body"),o(),N("(");let n=S(),s=N(")");return u(";")&&o(),g({type:"DoWhileStatement",body:t,test:n},e,s)},wt=()=>{let e=o(),t=e.value==="break"?"BreakStatement":"ContinueStatement",n=u(";")?o():C();return g({type:t,label:null},e,n)},Pt=()=>{let e=o();N("(");let t=S();N(")");let n=se();return g({type:"WhileStatement",test:t,body:n},e,n)},Nt=()=>{let e=o();N("(");let t=S();N(")");let n=se(),s=null;return v("else")&&(o(),s=se()),g({type:"IfStatement",test:t,consequent:n,alternate:s},e,s??n)},Et=()=>{let e=o(),t=null;!u(";")&&!u("}")&&!U()&&(t=S());let n=u(";")?o():C();return g({type:"ReturnStatement",argument:t},e,n)},It=()=>{let e=o(),t=S(),n=u(";")?o():C();return g({type:"ThrowStatement",argument:t},e,n)},Ct=()=>{let e=o(),t=ye(),n=null,s=null;if(v("catch")){let d=o(),L=null;u("(")&&(o(),L=I(),N(")"));let j=ye();n=g({type:"CatchClause",param:L,body:j},d,j);}return v("finally")&&(o(),s=ye()),!n&&!s&&R("'try' requires a 'catch' or 'finally' clause"),g({type:"TryStatement",block:t,handler:n,finalizer:s},e,s??n??t)},Rt=()=>{let e=o();N("(");let t=S();N(")"),N("{");let n=[];for(;!u("}")&&!U();){let d=T(),L=null;v("case")?(o(),L=S()):v("default")?o():R("Expected 'case' or 'default' in switch"),N(":");let j=[];for(;!u("}")&&!v("case")&&!v("default")&&!U();)j.push(se());n.push(g({type:"SwitchCase",test:L,consequent:j},d,C()??d));}let s=N("}");return g({type:"SwitchStatement",discriminant:t,cases:n},e,s)},ye=()=>{let e=N("{"),t=je(()=>u("}"));return g({type:"BlockStatement",body:t},e,N("}"))},je=e=>{let t=[];for(;!e()&&!U();){if(T().type==="Unknown"){o();continue}try{t.push(se());}catch(n){if(!(n instanceof le))throw n;U()||o();}}return t};return {parseExpr:S,parseProgram:()=>{let e=T(),t=je(()=>false);return re(),g({type:"Program",sourceType:"module",body:t,...H.length?{typeRefs:H}:{},...i.length?{comments:i}:{},...c.length?{parseDiagnostics:c}:{}},e,C()??e)},eof:U,fail:R,recordError:Y,settleGrammar:re,diagnostics:c}}function rt(r){let c=Ke(r),a=c.parseProgram(),i=a.comments;return i?.length&&Je(a,i,r),{ast:a,diagnostics:c.diagnostics}}function rn(r){let{ast:c,diagnostics:a}=rt(r),i=a[0];if(i){let y=i.code==="lex-error"?ie:le;throw new y(i.message,i.position,i.index,i.loc,i.end)}return c}function on(r){let c=Ke(r),a=c.parseExpr();c.eof()||c.fail("Unexpected token after expression"),c.settleGrammar();let i=c.diagnostics[0];if(i){let y=i.code==="lex-error"?ie:le;throw new y(i.message,i.position,i.index,i.loc,i.end)}return a}function sn(r){let c=Ke(r),a;try{a=c.parseExpr(),c.eof()||c.recordError("Unexpected token after expression");}catch(i){if(!(i instanceof le)&&!(i instanceof ie))throw i}return c.settleGrammar(),{ast:a,diagnostics:c.diagnostics}}var an="1.10.0";exports.KEYWORDS=We;exports.LexError=ie;exports.ParseError=le;exports.attachComments=Je;exports.nodeIsMissing=Qt;exports.parse=rn;exports.parseExpression=on;exports.parseExpressionTolerant=sn;exports.parseTolerant=rt;exports.tokenize=$t;exports.version=an;
|
package/dist/index.d.cts
DELETED
|
@@ -1,249 +0,0 @@
|
|
|
1
|
-
import { TSLiteError, types } from '@tslite/ast';
|
|
2
|
-
|
|
3
|
-
/** Code dos erros lançados pelo parser/tokenizer. */
|
|
4
|
-
type ParserErrorCode = "lex-error" | "parse-error";
|
|
5
|
-
/** Posição num ponto da fonte (linha 1-based, coluna 0-based). */
|
|
6
|
-
interface Position {
|
|
7
|
-
readonly line: number;
|
|
8
|
-
readonly column: number;
|
|
9
|
-
}
|
|
10
|
-
/** Intervalo de posições de um token/nó. */
|
|
11
|
-
interface SourceLocation {
|
|
12
|
-
readonly start: Position;
|
|
13
|
-
readonly end: Position;
|
|
14
|
-
}
|
|
15
|
-
type TokenType = "Identifier" | "Keyword" | "Number" | "String" | "Template" | "TemplateHead" | "TemplateMiddle" | "TemplateTail" | "Punctuator" | "JSXText" | "Unknown" | "EOF";
|
|
16
|
-
interface Token {
|
|
17
|
-
readonly type: TokenType;
|
|
18
|
-
/** O lexema cru, como aparece na fonte (sem decodificar escapes). */
|
|
19
|
-
readonly value: string;
|
|
20
|
-
/** Offset absoluto de início (inclusivo) e fim (exclusivo). */
|
|
21
|
-
readonly start: number;
|
|
22
|
-
readonly end: number;
|
|
23
|
-
readonly loc: SourceLocation;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Um comentário coletado. É TRIVIA — o parser não o vê como `Token` (não muda a
|
|
27
|
-
* gramática); vai por um canal LATERAL (`onComment`), no modelo do acorn. O
|
|
28
|
-
* `value` é o texto SEM os delimitadores (ESTree): `// foo` → `" foo"`, e o bloco com
|
|
29
|
-
* ` foo ` entre os delimitadores → `" foo "`. Carrega `start`/`end`/`loc` como os nós do
|
|
30
|
-
* parser.
|
|
31
|
-
*/
|
|
32
|
-
interface CommentToken {
|
|
33
|
-
readonly type: "Line" | "Block";
|
|
34
|
-
readonly value: string;
|
|
35
|
-
readonly start: number;
|
|
36
|
-
readonly end: number;
|
|
37
|
-
readonly loc: SourceLocation;
|
|
38
|
-
}
|
|
39
|
-
/** Coletor de comentários passado ao `tokenize` (canal lateral, opt-in). */
|
|
40
|
-
type OnComment = (comment: CommentToken) => void;
|
|
41
|
-
/**
|
|
42
|
-
* Um erro de léxico como DADO (o `onError` do scanner do tsc, que também não
|
|
43
|
-
* lança). Mesma forma que o `ParseDiagnostic` do parser, para viajarem juntos.
|
|
44
|
-
*/
|
|
45
|
-
interface LexDiagnostic {
|
|
46
|
-
readonly message: string;
|
|
47
|
-
readonly position: Position;
|
|
48
|
-
readonly index: number;
|
|
49
|
-
readonly loc: SourceLocation;
|
|
50
|
-
readonly end: number;
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Coletor de erros de léxico (opt-in). PRESENTE → o tokenizer RECUPERA (emite um
|
|
54
|
-
* token `Unknown`, ou o token parcial, e segue), como o scanner do tsc. AUSENTE →
|
|
55
|
-
* o tokenizer LANÇA `LexError` no primeiro erro (o contrato estrito de sempre).
|
|
56
|
-
*/
|
|
57
|
-
type OnLexError = (diagnostic: LexDiagnostic) => void;
|
|
58
|
-
/** Erro de léxico, com a posição onde ocorreu. */
|
|
59
|
-
declare class LexError extends TSLiteError<"lex-error"> {
|
|
60
|
-
readonly position: Position;
|
|
61
|
-
readonly index: number;
|
|
62
|
-
/**
|
|
63
|
-
* RANGE do caractere culpado (mínimo: 1 char) — para o editor sublinhar em
|
|
64
|
-
* vez de marcar um ponto. `position`/`index` seguem sendo o início (compat).
|
|
65
|
-
*/
|
|
66
|
-
readonly loc?: SourceLocation | undefined;
|
|
67
|
-
/** Offset absoluto do fim (exclusivo). */
|
|
68
|
-
readonly end?: number | undefined;
|
|
69
|
-
constructor(message: string, position: Position, index: number,
|
|
70
|
-
/**
|
|
71
|
-
* RANGE do caractere culpado (mínimo: 1 char) — para o editor sublinhar em
|
|
72
|
-
* vez de marcar um ponto. `position`/`index` seguem sendo o início (compat).
|
|
73
|
-
*/
|
|
74
|
-
loc?: SourceLocation | undefined,
|
|
75
|
-
/** Offset absoluto do fim (exclusivo). */
|
|
76
|
-
end?: number | undefined);
|
|
77
|
-
}
|
|
78
|
-
/** Palavras reservadas. As permitidas e as proibidas — o parser decide. */
|
|
79
|
-
declare const KEYWORDS: Set<string>;
|
|
80
|
-
/**
|
|
81
|
-
* Tokeniza a fonte. Devolve a lista de tokens, terminada por um `EOF`.
|
|
82
|
-
*
|
|
83
|
-
* `onComment` (opcional) recebe cada comentário conforme é pulado — canal
|
|
84
|
-
* lateral, sem entrar no stream de tokens.
|
|
85
|
-
*
|
|
86
|
-
* `onError` (opcional) liga a RECUPERAÇÃO: com ele, um erro de léxico é
|
|
87
|
-
* REGISTRADO (não lançado) e o tokenizer segue — char inesperado vira token
|
|
88
|
-
* `Unknown`, string/template/número mal-formados viram o token parcial. Sem ele,
|
|
89
|
-
* o comportamento é o estrito de sempre: o primeiro erro **lança** `LexError`.
|
|
90
|
-
*/
|
|
91
|
-
declare function tokenize(source: string, onComment?: OnComment, onError?: OnLexError): Token[];
|
|
92
|
-
|
|
93
|
-
/** Erro de sintaxe, com a posição onde ocorreu. */
|
|
94
|
-
declare class ParseError extends TSLiteError<"parse-error"> {
|
|
95
|
-
readonly position: Position;
|
|
96
|
-
readonly index: number;
|
|
97
|
-
/**
|
|
98
|
-
* O RANGE completo do token culpado (`start`+`end`) — o que um editor precisa
|
|
99
|
-
* para SUBLINHAR o trecho, em vez de marcar um ponto. `position`/`index`
|
|
100
|
-
* seguem sendo o início (compat).
|
|
101
|
-
*/
|
|
102
|
-
readonly loc?: SourceLocation | undefined;
|
|
103
|
-
/** Offset absoluto do fim (exclusivo) do token culpado. */
|
|
104
|
-
readonly end?: number | undefined;
|
|
105
|
-
constructor(message: string, position: Position, index: number,
|
|
106
|
-
/**
|
|
107
|
-
* O RANGE completo do token culpado (`start`+`end`) — o que um editor precisa
|
|
108
|
-
* para SUBLINHAR o trecho, em vez de marcar um ponto. `position`/`index`
|
|
109
|
-
* seguem sendo o início (compat).
|
|
110
|
-
*/
|
|
111
|
-
loc?: SourceLocation | undefined,
|
|
112
|
-
/** Offset absoluto do fim (exclusivo) do token culpado. */
|
|
113
|
-
end?: number | undefined);
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Um erro de sintaxe como **DADO** (não exceção) — o modelo do tsc, cujo parser
|
|
117
|
-
* não lança: ele empurra em `parseDiagnostics` e segue (`parser.ts:2149`). Carrega
|
|
118
|
-
* o mesmo que o `ParseError`, para que o parse estrito possa relançá-lo idêntico.
|
|
119
|
-
*/
|
|
120
|
-
interface ParseDiagnostic {
|
|
121
|
-
/** De qual fase veio — o `parse` estrito relança a classe certa, e o editor
|
|
122
|
-
* distingue as duas. */
|
|
123
|
-
readonly code: ParserErrorCode;
|
|
124
|
-
readonly message: string;
|
|
125
|
-
readonly position: Position;
|
|
126
|
-
readonly index: number;
|
|
127
|
-
readonly loc: SourceLocation;
|
|
128
|
-
readonly end: number;
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* O nó é FALTANTE (sintético, criado na recuperação de erro)? Marcado pela própria
|
|
132
|
-
* posição — largura zero —, exatamente como o `nodeIsMissing` do tsc
|
|
133
|
-
* (`utilities.ts:1079`: `node.pos === node.end`). Um buraco no texto vira um nó
|
|
134
|
-
* bem-formado de largura zero, em vez de derrubar a árvore inteira.
|
|
135
|
-
*/
|
|
136
|
-
declare const nodeIsMissing: (node: unknown) => boolean;
|
|
137
|
-
/** O resultado do parse TOLERANTE: a árvore (talvez com buracos) + os erros. */
|
|
138
|
-
interface ParseResult {
|
|
139
|
-
/** A árvore. `undefined` só quando nem o léxico passou (erro de `tokenize`). */
|
|
140
|
-
readonly ast: types.Program | undefined;
|
|
141
|
-
/** Os erros de sintaxe como DADO, em ordem de ocorrência. */
|
|
142
|
-
readonly diagnostics: readonly ParseDiagnostic[];
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* Parse **tolerante**: nunca lança por erro de sintaxe. Devolve a árvore — com
|
|
146
|
-
* nós FALTANTES (largura zero, ver {@link nodeIsMissing}) onde o texto tinha
|
|
147
|
-
* buracos — e os diagnósticos ao lado. É o que um EDITOR consome: completion e
|
|
148
|
-
* hover precisam de árvore justamente enquanto o código está incompleto.
|
|
149
|
-
*
|
|
150
|
-
* É o modo único do tsc (o parser dele nunca lança); aqui ele convive com o
|
|
151
|
-
* {@link parse} estrito, que é o contrato de quem VALIDA.
|
|
152
|
-
*/
|
|
153
|
-
declare function parseTolerant(source: string): ParseResult;
|
|
154
|
-
/**
|
|
155
|
-
* Faz o parse de uma fonte completa num `Program` (ESTree, com `loc`).
|
|
156
|
-
*
|
|
157
|
-
* Contrato **estrito** (o de sempre): o primeiro erro de sintaxe **lança**. Quem
|
|
158
|
-
* valida quer tudo-ou-nada — rodar o checker sobre uma árvore com buracos só
|
|
159
|
-
* produziria cascata. Quem precisa da árvore parcial usa o {@link parseTolerant}.
|
|
160
|
-
*/
|
|
161
|
-
declare function parse(source: string): types.Program;
|
|
162
|
-
/**
|
|
163
|
-
* Conveniência: faz o parse de uma **única expressão** (ex.: célula de regra).
|
|
164
|
-
* Entra direto na gramática de expressão — então `{ … }` é objeto, não bloco.
|
|
165
|
-
*/
|
|
166
|
-
declare function parseExpression(source: string): types.Expression;
|
|
167
|
-
/**
|
|
168
|
-
* Parse **tolerante** de uma única expressão: o par de {@link parseExpression} que
|
|
169
|
-
* o {@link parseTolerant} é de `parse`. Nunca lança por sintaxe — devolve o nó (com
|
|
170
|
-
* buracos de largura zero onde faltava) + os diagnósticos ao lado. Um `!eof` vira
|
|
171
|
-
* diagnóstico (`Unexpected token after expression`), não exceção.
|
|
172
|
-
*
|
|
173
|
-
* Existe porque um consumidor de expressão (o editor, o `@tslite/template`) precisa
|
|
174
|
-
* do mesmo contrato tolerante que o `parseTolerant` dá pra Program — sem ele, só o
|
|
175
|
-
* `parseExpression` estrito, que lança e perde o resto.
|
|
176
|
-
*/
|
|
177
|
-
declare function parseExpressionTolerant(source: string): {
|
|
178
|
-
readonly ast: types.Expression | undefined;
|
|
179
|
-
readonly diagnostics: readonly ParseDiagnostic[];
|
|
180
|
-
};
|
|
181
|
-
|
|
182
|
-
/** O mínimo que o algoritmo precisa de um nó: posição e os baldes de comentário. */
|
|
183
|
-
interface Positioned {
|
|
184
|
-
type: string;
|
|
185
|
-
start: number;
|
|
186
|
-
end: number;
|
|
187
|
-
loc: {
|
|
188
|
-
start: {
|
|
189
|
-
line: number;
|
|
190
|
-
};
|
|
191
|
-
end: {
|
|
192
|
-
line: number;
|
|
193
|
-
};
|
|
194
|
-
};
|
|
195
|
-
leadingComments?: CommentToken[];
|
|
196
|
-
trailingComments?: CommentToken[];
|
|
197
|
-
innerComments?: CommentToken[];
|
|
198
|
-
[key: string]: unknown;
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Ancora os `comments` (a lista lateral do `Program`, em ordem de fonte) aos nós
|
|
202
|
-
* de `root`. Mutação IN-PLACE: adiciona `leadingComments`/`trailingComments`/
|
|
203
|
-
* `innerComments` onde couber. A lista `Program.comments` é preservada (é o
|
|
204
|
-
* índice canônico ESTree); o attach só acrescenta referências nos nós.
|
|
205
|
-
*
|
|
206
|
-
* `source` é consultada só para o caso `remaining` (comentário encravado entre
|
|
207
|
-
* dois nós na mesma linha): o próximo caractere real decide de que lado ele está.
|
|
208
|
-
*/
|
|
209
|
-
declare function attachComments(root: Positioned, comments: readonly CommentToken[], source?: string): void;
|
|
210
|
-
|
|
211
|
-
/** Schema cru (espelha o `Schema` de @tslite/checker; aqui é POJO). */
|
|
212
|
-
type TSchema = {
|
|
213
|
-
t: string;
|
|
214
|
-
[k: string]: unknown;
|
|
215
|
-
};
|
|
216
|
-
/**
|
|
217
|
-
* Uma REFERÊNCIA a tipo nomeado, com posição — a tabela lateral que permite
|
|
218
|
-
* "ir para a definição" e hover sobre um nome de tipo.
|
|
219
|
-
*
|
|
220
|
-
* Por que lateral e não `loc` no `Schema`: o `Schema` é dado imutável e os caches
|
|
221
|
-
* do `@tslite/types` são **por referência** (TC17). Pendurar posição faria dois tipos
|
|
222
|
-
* estruturalmente iguais passarem a diferir, quebrando dedup e cache em silêncio.
|
|
223
|
-
* Mesmo movimento do overlay: informação AO LADO, não dentro.
|
|
224
|
-
*/
|
|
225
|
-
type TypeRef = {
|
|
226
|
-
/** O nome como foi escrito — qualificado, se foi (`state.Config`). */
|
|
227
|
-
readonly name: string;
|
|
228
|
-
readonly loc: SourceLocation;
|
|
229
|
-
/** Os argumentos de tipo escritos (`F<number, string>` → dois `Schema`; `F` → `[]`).
|
|
230
|
-
* É o que deixa o checker cobrar aridade e bound na referência (TS2314/TS2344). */
|
|
231
|
-
readonly args: readonly TSchema[];
|
|
232
|
-
/** O namespace em que a referência foi escrita (`"app.router"`), ausente no topo. Um
|
|
233
|
-
* nome resolve primeiro nele e depois nos de fora — o `resolveName` do tsc subindo os
|
|
234
|
-
* contêineres —, e quem resolve é o checker. */
|
|
235
|
-
readonly namespace?: string;
|
|
236
|
-
/** Cada segmento de um nome qualificado, com a posição dele (`state.Config` → `state`
|
|
237
|
-
* e `Config`), ausente num nome simples. O erro de um nome qualificado pousa no
|
|
238
|
-
* segmento que falhou: o namespace que não existe (TS2503) ou o membro que ele não tem
|
|
239
|
-
* (TS2694). */
|
|
240
|
-
readonly segments?: readonly {
|
|
241
|
-
readonly name: string;
|
|
242
|
-
readonly loc: SourceLocation;
|
|
243
|
-
}[];
|
|
244
|
-
};
|
|
245
|
-
|
|
246
|
-
/** A versão deste package, a do módulo de fato carregado. */
|
|
247
|
-
declare const version = "1.10.0";
|
|
248
|
-
|
|
249
|
-
export { type CommentToken, KEYWORDS, type LexDiagnostic, LexError, type OnComment, type OnLexError, type ParseDiagnostic, ParseError, type ParseResult, type ParserErrorCode, type Position, type SourceLocation, type Token, type TokenType, type TypeRef, attachComments, nodeIsMissing, parse, parseExpression, parseExpressionTolerant, parseTolerant, tokenize, version };
|