@tslite/parser 0.4.0 → 0.5.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/index.cjs +6 -5
- package/dist/index.d.cts +121 -5
- package/dist/index.d.ts +121 -5
- package/dist/index.js +6 -5
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
'use strict';var core=require('@tslite/core');var
|
|
2
|
-
`&&
|
|
3
|
-
`||
|
|
4
|
-
`||v==="\r"||v==="\u2028"||v==="\u2029",x=()=>{for(;;){let v=f();if(v===" "||v===" "||v==="\f"||v==="\v"||s(v))y();else if(v==="/"&&f(1)==="/")for(;l<c.length&&!s(f());)y();else if(v==="/"&&f(1)==="*")for(y(),y();;){if(l>=c.length&&L("Unterminated block comment"),f()==="*"&&f(1)==="/"){y(),y();break}y();}else break}},I=(v,C,R,N)=>{S.push({type:v,value:C,start:R,end:l,loc:{start:N,end:r()}}),$=v==="Punctuator"?Ve.has(C):v==="Keyword"?We.has(C):v==="TemplateHead"||v==="TemplateMiddle";},E=v=>{for(y();l<c.length;){let C=f();if(C===v)return y(),c.slice(a,l);if(s(C)&&L("Unterminated string literal"),C==="\\"){y(),l>=c.length&&L("Unterminated string literal"),y();continue}y();}return L("Unterminated string literal")},m=()=>{if(f()==="0"&&(f(1)==="x"||f(1)==="X")){for(y(),y(),de(f())||L("Invalid hexadecimal literal");de(f());)y();return}if(f()==="0"&&(f(1)==="b"||f(1)==="B")){for(y(),y(),f()!=="0"&&f()!=="1"&&L("Invalid binary literal");f()==="0"||f()==="1";)y();return}if(f()==="0"&&(f(1)==="o"||f(1)==="O")){for(y(),y(),f()>="0"&&f()<="7"||L("Invalid octal literal");f()>="0"&&f()<="7";)y();return}for(;B(f());)y();if(f()===".")for(y();B(f());)y();if(f()==="e"||f()==="E")for(y(),(f()==="+"||f()==="-")&&y(),B(f())||L("Invalid exponent");B(f());)y();},T=()=>{let v=l;for(;l<c.length;){let C=f();if(C==="`"){let R=c.slice(v,l);return y(),{raw:R,interp:false}}if(C==="$"&&f(1)==="{"){let R=c.slice(v,l);return y(),y(),{raw:R,interp:true}}if(C==="\\"){if(y(),l>=c.length)break;y();continue}y();}return L("Unterminated template literal")},a=0,J=0,k=[],$=true,X="js",K=[],F=[];for(;;){if(X==="jsxChildren"){a=l;let N=r();if(l>=c.length){I("EOF","",a,N);break}let i=f();if(i==="<"){f(1)==="/"?(y(),y(),I("Punctuator","</",a,N),X="jsxCloseTag"):(y(),I("Punctuator","<",a,N),K.push("jsxChildren"),X="jsxOpenTag");continue}if(i==="{"){y(),I("Punctuator","{",a,N),F.push({level:J,restore:"jsxChildren"}),X="js";continue}for(;l<c.length&&f()!=="<"&&f()!=="{";)y();I("JSXText",c.slice(a,l),a,N);continue}if(X==="jsxOpenTag"||X==="jsxCloseTag"){x(),a=l;let N=r();if(l>=c.length){I("EOF","",a,N);break}let i=f();if(se(i)){for(y();qe(f());)y();I("Identifier",c.slice(a,l),a,N);continue}if(i==="/"&&f(1)===">"){y(),y(),I("Punctuator","/>",a,N),X=K.pop()??"js";continue}if(i===">"){y(),I("Punctuator",">",a,N),X=X==="jsxCloseTag"?K.pop()??"js":"jsxChildren";continue}if(i==="{"){y(),I("Punctuator","{",a,N),F.push({level:J,restore:X}),X="js";continue}if(i==='"'||i==="'"){I("String",E(i),a,N);continue}if(i==="="||i==="."||i===":"){y(),I("Punctuator",i,a,N);continue}L(`Unexpected character '${i}' in JSX tag`);}x(),a=l;let v=r();if(l>=c.length){I("EOF","",a,v);break}let C=f();if(se(C)){for(;me(f());)y();let N=c.slice(a,l);I(ye.has(N)?"Keyword":"Identifier",N,a,v);continue}if(B(C)||C==="."&&B(f(1))){m(),I("Number",c.slice(a,l),a,v);continue}if(C==='"'||C==="'"){let N=E(C);I("String",N,a,v);continue}if(C==="`"){y();let{raw:N,interp:i}=T();i?(I("TemplateHead",N,a,v),k.push(J)):I("Template",N,a,v);continue}if(C==="<"&&$){y(),I("Punctuator","<",a,v),K.push("js"),X="jsxOpenTag";continue}if(C==="{"){y(),I("Punctuator","{",a,v),J++;continue}if(C==="}"){if(k.length>0&&J===k[k.length-1]){k.pop(),y();let{raw:N,interp:i}=T();I(i?"TemplateMiddle":"TemplateTail",N,a,v),i&&k.push(J);continue}if(F.length>0&&J===F[F.length-1].level){let{restore:N}=F.pop();y(),I("Punctuator","}",a,v),X=N;continue}y(),I("Punctuator","}",a,v),J--;continue}if(C==="?"&&f(1)==="."&&B(f(2))){y(),I("Punctuator","?",a,v);continue}let R=ze.find(N=>c.startsWith(N,l));if(R){for(let N=0;N<R.length;N++)y();I("Punctuator",R,a,v);continue}L(`Unexpected character '${C}'`);}return S}var ie=(c=[])=>({vars:new Set(c),bounds:new Map,noCond:false,inferSink:null}),H=(c,S)=>{let l=new Set(c.vars),h=new Map(c.bounds);for(let d of S)l.add(d.name),d.bound||d.isConst?h.set(d.name,{bound:d.bound,isConst:d.isConst}):h.delete(d.name);return {vars:l,bounds:h,noCond:c.noCond,inferSink:c.inferSink}},He=(c,S)=>{let l=c.bounds.get(S);return l&&(l.bound||l.isConst)?{t:"var",name:S,...l.bound?{bound:l.bound}:{},...l.isConst?{isConst:true}:{}}:{t:"var",name:S}},he=c=>{let{peek:S,next:l,isP:h,isK:d,expectP:r,fail:f,unescape:L}=c,y=()=>{let i=c.pos(),p=c.tokens[i],u=c.tokens[i-1];return !!u&&!!p&&p.loc.start.line>u.loc.end.line},s=()=>{let i=0;for(let p=c.pos();p<c.tokens.length;p++){let u=c.tokens[p];if(u.type==="EOF")return false;if(u.type==="Punctuator"){if(["(","[","{","<"].includes(u.value))i++;else if([")","]","}",">"].includes(u.value)&&(i--,i===0)){let b=c.tokens[p+1];return !!b&&b.type==="Punctuator"&&b.value==="=>"}}}return false},x=()=>{let i=c.tokens,p=[],u=0,b=false;for(let w=c.pos();w<i.length;w++){let j=i[w];if(j.type==="EOF")break;if(j.type==="Punctuator"){if(j.value==="<")u++,u===1&&(b=true);else if(j.value===">"){if(u--,u===0)break}else j.value==="("||j.value==="["||j.value==="{"?(u++,b=false):j.value===")"||j.value==="]"||j.value==="}"?(u--,b=false):j.value===","&&u===1?b=true:b=false;continue}if(u===1&&b){if(j.type==="Keyword"&&j.value==="const")continue;if(j.type==="Identifier"){p.push(j.value),b=false;continue}}b=false;}return p},I=i=>{let p=H(i,x().map(b=>({name:b})));r("<");let u=[];for(;!h(">");){let b=d("const");b&&l();let w=S();w.type!=="Identifier"&&f("Expected type parameter name"),l();let j;d("extends")&&(l(),j=T(p)),h("=")&&(l(),T(p)),u.push({name:w.value,...j?{bound:j}:{},...b?{isConst:true}:{}}),h(">")||r(",");}return r(">"),u},E=i=>{r("<");let p=[];for(;!h(">");)p.push(T(i)),h(">")||r(",");return r(">"),p},m=i=>{let p=S();return p.type==="Identifier"&&p.value===i},T=i=>{let p=a(i);if(i.noCond||!d("extends")||y())return p;l();let u=[],b=a({...i,noCond:true,inferSink:u});r("?");let w=H(i,u.map(z=>({name:z}))),j=T(w);r(":");let _=T(w);return {t:"conditional",check:p,extends:b,then:j,else:_,...u.length?{infer:u}:{}}},a=i=>{h("|")&&l();let p=J(i);if(!h("|"))return p;let u=[p];for(;h("|");)l(),u.push(J(i));return {t:"union",of:u}},J=i=>{h("&")&&l();let p=k(i);if(!h("&"))return p;let u=[p];for(;h("&");)l(),u.push(k(i));return {t:"intersection",of:u}},k=i=>{if(m("keyof"))return l(),{t:"keyof",of:k(i)};if(m("readonly")){l();let p=k(i);return p.t!=="array"&&p.t!=="tuple"&&f("'readonly' only applies to array and tuple types"),{...p,readonly:true}}if(m("infer")){l();let p=S();p.type!=="Identifier"&&f("Expected 'infer' variable name"),l();let u=i.inferSink;return u?(u.push(p.value),{t:"var",name:p.value}):f("'infer' is only allowed in the 'extends' clause of a conditional")}return $(i)},$=i=>{let p=X(i);for(;h("[")&&!y();)if(l(),h("]"))l(),p={t:"array",items:p};else {let u=T(i);r("]"),p={t:"index",obj:p,key:u};}return p},X=i=>{if(d("typeof")){l();let u=S();u.type!=="Identifier"&&f("Expected a name after 'typeof' in type position"),l();let b=[u.value];for(;h(".");){l();let w=S();w.type!=="Identifier"&&w.type!=="Keyword"&&f("Expected a property name after '.' in 'typeof'"),l(),b.push(w.value);}return {t:"typeQuery",path:b}}if(h("<")){let u=I(i),b=H(i,u);return F(b,u.map(w=>w.name))}if(h("(")){if(s())return F(i);l();let u=T(i.noCond?{...i,noCond:false}:i);return r(")"),u}if(h("{"))return C()?R(i):N(i);if(h("["))return v(i);let p=S();if(p.type==="String")return l(),{t:"literal",value:L(p.value.slice(1,-1))};if(p.type==="Number")return l(),{t:"literal",value:Number(p.value)};if(d("true"))return l(),{t:"literal",value:true};if(d("false"))return l(),{t:"literal",value:false};if(d("null"))return l(),{t:"null"};if(d("void"))return l(),{t:"void"};if(p.type==="Identifier"){switch(l(),p.value){case "string":return {t:"string"};case "number":return {t:"number"};case "boolean":return {t:"boolean"};case "any":return {t:"any"};case "unknown":return {t:"unknown"};case "undefined":return {t:"undefined"};case "never":return {t:"union",of:[]}}let u=h("<")?E(i):[];return i.vars.has(p.value)&&u.length===0?He(i,p.value):p.value==="ReturnType"&&u.length===1?{t:"returnType",fn:u[0]}:p.value==="Parameters"&&u.length===1?{t:"parameters",fn:u[0]}:(c.typeRefs?.push({name:p.value,loc:p.loc}),{t:"apply",name:p.value,args:u})}return f(`Expected a type but got '${p.value||p.type}'`)},K=i=>{r("(");let p=[];for(;!h(")");){let u=S();u.type!=="Identifier"&&f("Expected parameter name in function type"),l();let b=h("?");b&&l(),r(":");let w=T(i);p.push({name:u.value,type:w,...b?{optional:true}:{}}),h(")")||r(",");}return r(")"),p},F=(i,p)=>{let u=K(i);r("=>");let b=T(i);return {t:"fn",params:u,returns:b,...p?.length?{typeParams:p}:{}}},v=i=>{r("[");let p=[],u=[];for(;!h("]");){if(h("...")){l();let b=T(i);b.t==="array"?(p.push(b.items),u.push("rest")):(p.push(b),u.push("variadic"));}else {let b=T(i),w=h("?");w&&l(),p.push(b),u.push(w?"optional":"req");}h("]")||r(",");}return r("]"),u.some(b=>b!=="req")?{t:"tuple",elements:p,flags:u}:{t:"tuple",elements:p}},C=()=>{let i=c.tokens,p=c.pos()+1;return i[p]?.type==="Punctuator"&&(i[p]?.value==="+"||i[p]?.value==="-")&&p++,i[p]?.type==="Identifier"&&i[p]?.value==="readonly"&&p++,i[p]?.type==="Punctuator"&&i[p]?.value==="["&&i[p+1]?.type==="Identifier"&&i[p+2]?.type==="Keyword"&&i[p+2]?.value==="in"},R=i=>{r("{"),(h("+")||h("-"))&&l(),m("readonly")&&l(),r("[");let p=S();p.type!=="Identifier"&&f("Expected mapped type key name"),l(),d("in")||f("Expected 'in' in mapped type"),l();let u=T(i);m("as")&&f("Key remapping ('as') in mapped types is not supported"),r("]");let b=false,w=h("+")||h("-")?l().value:null;h("?")&&(l(),b=w!=="-"),r(":");let j=T(H(i,[{name:p.value}]));return (h(";")||h(","))&&l(),r("}"),{t:"mapped",key:p.value,over:u,body:j,optional:b}},N=i=>{r("{");let p={},u,b=[];for(;!h("}");){if(h("(")){let w=K(i);r(":");let j=T(i);b.push({t:"fn",params:w,returns:j});}else if(h("[")){l(),S().type!=="Identifier"&&f("Expected index signature parameter name"),l(),r(":");let w=S();(w.type!=="Identifier"||w.value!=="string"&&w.value!=="number")&&f("Index signature parameter type must be 'string' or 'number'"),l(),r("]"),r(":"),u={key:w.value,value:T(i)};}else {let w=S(),j;if(w.type==="Identifier"||w.type==="Keyword")l(),j=w.value;else if(w.type==="String")l(),j=L(w.value.slice(1,-1));else if(w.type==="Number")l(),j=w.value;else return f("Expected property name in object type");let _=h("?");_&&l(),r(":");let z=T(i);p[j]={type:z,..._?{optional:true}:{}};}if(h(";")||h(","))l();else break}return r("}"),b.length>0?Object.keys(p).length>0||u?f("Callable object types (call signatures mixed with members) are not supported"):b.length===1?b[0]:{t:"overload",signatures:b}:{t:"object",props:p,...u?{index:u}:{}}};return {parseType:i=>T(ie(i)),parseTypeParamList:()=>I(ie()),parseTypeInScope:i=>T(H(ie(),i))}};var ee=class extends core.TSLiteError{constructor(l,h,d,r,f){super("parse-error",`${l} (${h.line}:${h.column})`,{position:h,index:d,loc:r,end:f});this.position=h;this.index=d;this.loc=r;this.end=f;this.name="ParseError";}},Ye={"??":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},Qe=new Set(["??","||","&&"]),Ze=new Set(["class","debugger","with","enum","interface"]),et={enum:'use a union of literals (`type T = "a" | "b"`) \u2014 it is serializable',interface:"use a type alias (`type X = { \u2026 }`)",namespace:"use modules (`import`/`export`)",module:"use modules (`import`/`export`)",declare:"declare the shape via the DI env, or with a `type` alias",abstract:"classes are not part of the language \u2014 model with objects + functions"},tt={namespace:(c,S)=>c.type==="Identifier"&&S.type==="Punctuator"&&S.value==="{",module:(c,S)=>c.type==="Identifier"&&S.type==="Punctuator"&&S.value==="{",declare:c=>c.type==="Keyword"&&["const","let","var","function","class","enum","interface"].includes(c.value)||c.type==="Identifier"&&["type","namespace","module"].includes(c.value),abstract:c=>c.type==="Keyword"&&c.value==="class"},nt=new Set(["=","+=","-=","*=","/=","%="]);function ge(c){let S=ae(c),l=0,h=[],d=(e=0)=>S[Math.min(l+e,S.length-1)],r=()=>S[l++],f=()=>S[l-1],L=()=>{let e=S[l],t=S[l-1];return !!e&&!!t&&e.loc.start.line>t.loc.end.line},y=()=>d().type==="EOF",s=e=>d().type==="Punctuator"&&d().value===e,x=e=>d().type==="Keyword"&&d().value===e,I=e=>d().type==="Identifier"&&d().value===e,E=(e,t=d())=>{throw new ee(e,t.loc.start,t.start,t.loc,t.end)},m=e=>(s(e)||E(`Expected '${e}' but got '${d().value||d().type}'`),r()),T=(e,t)=>{let n=f()??t;return Object.assign(e,{start:t.start,end:n.end,loc:{start:t.loc.start,end:n.loc.end}})},a=(e,t,n)=>Object.assign(e,{start:t.start,end:n.end,loc:{start:t.loc.start,end:n.loc.end}}),J=e=>{let t="";for(let n=0;n<e.length;n++){if(e[n]!=="\\"){t+=e[n];continue}let o=e[++n];switch(o){case "n":t+=`
|
|
5
|
-
`;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 g=e.indexOf("}",n);t+=String.fromCodePoint(parseInt(e.slice(n+2,g),16)),n=g;}else t+=String.fromCharCode(parseInt(e.slice(n+1,n+5),16)),n+=4;break;default:t+=o;}}return t},k=(e=false)=>$(e),$=(e=false)=>{let t=X(e),n=d();if(n.type==="Punctuator"&&nt.has(n.value)){r();let o=$();return a({type:"AssignmentExpression",operator:n.value,left:t,right:o},t,o)}return t},X=(e=false)=>{let t=F(0,e);if(!s("?"))return t;r();let n=k();m(":");let o=k();return a({type:"ConditionalExpression",test:t,consequent:n,alternate:o},t,o)},K=()=>{let e=d();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=d(1);if(t.type==="Punctuator"&&t.value===">"&&e.end===t.start){let n=d(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=v();for(;;){let o=K();if(!o)break;let{op:g,consume:P}=o;if(g==="in"&&t)break;let A=Ye[g];if(!A||A<=e)break;if(g==="satisfies"){if(L())break;E("'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(g==="as"){if(L())break;r();let D=V(new Set);n=a({type:"TSAsExpression",expression:n,typeAnnotation:D},n,f());continue}for(let D=0;D<P;D++)r();let O=F(g==="**"?A-1:A,t);n=a({type:Qe.has(g)?"LogicalExpression":"BinaryExpression",operator:g,left:n,right:O},n,O);}return n},v=()=>{let e=d();return e.type==="Punctuator"&&(e.value==="++"||e.value==="--")?(r(),T({type:"UpdateExpression",operator:e.value,prefix:true,argument:v()},e)):x("await")?(r(),T({type:"AwaitExpression",argument:v()},e)):x("typeof")||x("void")||x("delete")||e.type==="Punctuator"&&(e.value==="!"||e.value==="-"||e.value==="+"||e.value==="~")?C(e):N()},C=e=>{r();let t=v();return s("**")&&E(`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.`),T({type:"UnaryExpression",operator:e.value,prefix:true,argument:t},e)},R=()=>{let e=l,t=()=>(l=e,void 0);try{if(r(),s(">"))return t();let n=[];for(;n.push(V(new Set)),!!s(",");)r();return s(">")?(r(),s("(")?n:t()):t()}catch{return t()}},N=()=>{let e=we(),t=false;for(;;)if(s("?."))if(r(),t=true,s("(")){let{args:n,close:o}=i();e=a({type:"CallExpression",callee:e,arguments:n,optional:true},e,o);}else if(s("[")){r();let n=k(),o=m("]");e=a({type:"MemberExpression",object:e,property:n,computed:true,optional:true},e,o);}else {let n=d();n.type!=="Identifier"&&n.type!=="Keyword"&&E("Expected property name after '?.'"),r();let o=T({type:"Identifier",name:n.value},n);e=a({type:"MemberExpression",object:e,property:o,computed:false,optional:true},e,o);}else if(s(".")){r();let n=d();n.type!=="Identifier"&&n.type!=="Keyword"&&E("Expected property name"),r();let o=T({type:"Identifier",name:n.value},n);e=a({type:"MemberExpression",object:e,property:o,computed:false,optional:false},e,o);}else if(s("[")){r();let n=k(),o=m("]");e=a({type:"MemberExpression",object:e,property:n,computed:true,optional:false},e,o);}else if(s("(")){let{args:n,close:o}=i();e=a({type:"CallExpression",callee:e,arguments:n,optional:false},e,o);}else if(s("<")){let n=R();if(!n)break;let{args:o,close:g}=i();e=a({type:"CallExpression",callee:e,arguments:o,optional:false,typeArguments:n},e,g);}else if(s("++")||s("--")){let n=r();e=a({type:"UpdateExpression",operator:n.value,prefix:false,argument:e},e,n);}else break;return t?a({type:"ChainExpression",expression:e},e,e):e},i=()=>{m("(");let e=[];for(;!s(")");)e.push(p()),s(")")||m(",");return {args:e,close:m(")")}},p=()=>{if(s("...")){let e=r(),t=k();return a({type:"SpreadElement",argument:t},e,t)}return k()},u=()=>{let e=d();return e.type!=="Identifier"&&E("Expected identifier"),r(),T({type:"Identifier",name:e.value},e)},b=e=>{let t=s("{")?w(e):s("[")?j(e):u();return s(":")&&(r(),t.typeAnnotation=V(e)),t},w=e=>{let t=m("{"),n=[];for(;!s("}");){if(s("...")){let g=r(),P=b(e);n.push(a({type:"RestElement",argument:P},g,P));}else {let g=u(),P,A=false;if(s(":")?(r(),P=b(e)):(P={...g},A=true),s("=")){r();let O=k();P=a({type:"AssignmentPattern",left:P,right:O},P,O);}n.push(a({type:"Property",key:g,value:P,kind:"init",shorthand:A,computed:false,method:false},g,P));}s("}")||m(",");}let o=m("}");return a({type:"ObjectPattern",properties:n},t,o)},j=e=>{let t=m("["),n=[];for(;!s("]");){if(s(",")){n.push(null),r();continue}if(s("...")){let g=r(),P=b(e);n.push(a({type:"RestElement",argument:P},g,P));}else {let g=b(e);if(s("=")){r();let P=k();g=a({type:"AssignmentPattern",left:g,right:P},g,P);}n.push(g);}s("]")||m(",");}let o=m("]");return a({type:"ArrayPattern",elements:n},t,o)},_=()=>{let e=0;for(let t=l;t<S.length;t++){let n=S[t];if(n.type==="EOF")return false;if(n.type==="Punctuator"){if(n.value==="("||n.value==="["||n.value==="{")e++;else if((n.value===")"||n.value==="]"||n.value==="}")&&(e--,e===0)){let o=S[t+1];return !o||o.type!=="Punctuator"?false:o.value==="=>"?true:o.value===":"?z(t+2):false}}}return false},z=e=>{let t=0;for(let n=e;n<S.length;n++){let o=S[n];if(o.type==="EOF")return false;if(o.type==="Punctuator")if(["(","[","{","<"].includes(o.value))t++;else if([")","]","}",">"].includes(o.value)){if(t===0)return false;t--;}else {if(t===0&&o.value==="=>")return true;if(t===0&&(o.value===";"||o.value===","))return false}}return false},ve=(e=new Set)=>{m("(");let t=[];for(;!s(")");){if(s("...")){let n=r(),o=b(e);t.push(a({type:"RestElement",argument:o},n,o));}else {let n=b(e);if(s("=")){r();let o=k();n=a({type:"AssignmentPattern",left:n,right:o},n,o);}t.push(n);}s(")")||m(",");}return m(")"),t},te=(e,t)=>{let n=s("(")?ve():[u()],o;s(":")&&(r(),o=V(new Set)),m("=>");let g=s("{")?W():k();return T({type:"ArrowFunctionExpression",params:n,body:g,async:e,expression:g.type!=="BlockStatement",generator:false,...o?{returnType:o}:{}},t)},be=()=>{let e=m("["),t=[];for(;!s("]");){if(s(",")){r(),t.push(null);continue}t.push(p()),s("]")||m(",");}return a({type:"ArrayExpression",elements:t},e,m("]"))},Te=()=>{let e=m("{"),t=[];for(;!s("}");){if(s("...")){let n=r(),o=k();t.push(a({type:"SpreadElement",argument:o},n,o));}else {let n=d(),o,g=false;if(s("["))g=true,r(),o=k(),m("]");else if(n.type==="String")r(),o=T({type:"Literal",value:J(n.value.slice(1,-1)),raw:n.value},n);else if(n.type==="Number")r(),o=T({type:"Literal",value:Number(n.value),raw:n.value},n);else if(n.type==="Identifier"||n.type==="Keyword")r(),o=T({type:"Identifier",name:n.value},n);else return E("Invalid property key");if(s(":")){r();let P=k();t.push(a({type:"Property",key:o,value:P,kind:"init",method:false,shorthand:false,computed:g},n,P));}else t.push(a({type:"Property",key:o,value:o,kind:"init",method:false,shorthand:true,computed:false},n,o));}s("}")||m(",");}return a({type:"ObjectExpression",properties:t},e,m("}"))},G=(e,t)=>({type:"TemplateElement",value:{raw:e,cooked:J(e)},tail:t}),xe=e=>{r();let t=[G(e.value,false)],n=[];for(;;){n.push(k());let o=d();if(o.type==="TemplateMiddle")r(),t.push(G(o.value,false));else if(o.type==="TemplateTail"){r(),t.push(G(o.value,true));break}else E("Expected `}` to close template interpolation");}return T({type:"TemplateLiteral",quasis:t,expressions:n},e)},q=()=>{let e=d();return e.type!=="Identifier"&&E(`Expected JSX identifier but got '${e.value||e.type}'`),T({type:"JSXIdentifier",name:r().value},e)},le=()=>{let e=q();if(s(":")){r();let t=q();return a({type:"JSXNamespacedName",namespace:e,name:t},e,t)}for(;s(".");){r();let t=q();e=a({type:"JSXMemberExpression",object:e,property:t},e,t);}return e},M=e=>e.type==="JSXIdentifier"?e.name:e.type==="JSXNamespacedName"?`${M(e.namespace)}:${M(e.name)}`:`${M(e.object)}.${M(e.property)}`,Se=()=>{let e=d();if(e.type==="String")return r(),T({type:"Literal",value:J(e.value.slice(1,-1)),raw:e.value},e);if(s("{")){let t=r(),n=$(),o=m("}");return a({type:"JSXExpressionContainer",expression:n},t,o)}return s("<")?ne():E(`Invalid JSX attribute value '${e.value||e.type}'`)},ke=()=>{let e=[];for(;!s(">")&&!s("/>")&&!y();){if(s("{")){let o=r();m("...");let g=$(),P=m("}");e.push(a({type:"JSXSpreadAttribute",argument:g},o,P));continue}let t=q();if(s(":")){r();let o=q();t=a({type:"JSXNamespacedName",namespace:t,name:o},t,o);}let n=null;s("=")&&(r(),n=Se()),e.push(a({type:"JSXAttribute",name:t,value:n},t,n??t));}return e},pe=()=>{let e=[];for(;!(s("</")||y());){let t=d();if(t.type==="JSXText")r(),e.push(T({type:"JSXText",value:t.value,raw:t.value},t));else if(s("{")){let n=r();if(s("}")){let o=r(),g=T({type:"JSXEmptyExpression"},n);e.push(a({type:"JSXExpressionContainer",expression:g},n,o));}else {let o=$(),g=m("}");e.push(a({type:"JSXExpressionContainer",expression:o},n,g));}}else s("<")?e.push(ne()):E(`Unexpected token in JSX children '${t.value||t.type}'`);}return e},ne=()=>{let e=m("<");if(s(">")){let Q=r(),oe=a({type:"JSXOpeningFragment"},e,Q),Ue=pe(),Me=m("</"),fe=m(">"),Be=a({type:"JSXClosingFragment"},Me,fe);return a({type:"JSXFragment",openingFragment:oe,children:Ue,closingFragment:Be},e,fe)}let t=le(),n=ke();if(s("/>")){let Q=r(),oe=a({type:"JSXOpeningElement",name:t,attributes:n,selfClosing:true},e,Q);return a({type:"JSXElement",openingElement:oe,children:[],closingElement:null},e,Q)}let o=m(">"),g=a({type:"JSXOpeningElement",name:t,attributes:n,selfClosing:false},e,o),P=pe(),A=m("</"),O=d(),D=le();M(D)!==M(t)&&E(`JSX closing tag </${M(D)}> does not match opening <${M(t)}>`,O);let Y=m(">"),Ke=a({type:"JSXClosingElement",name:D},A,Y);return a({type:"JSXElement",openingElement:g,children:P,closingElement:Ke},e,Y)},we=()=>{let e=d();if(x("async")){let t=d(1);return t.value==="("||t.type==="Identifier"?(r(),te(true,e)):E("Unexpected 'async'")}if(s("(")&&_()||e.type==="Identifier"&&d(1).type==="Punctuator"&&d(1).value==="=>")return te(false,e);if(e.type==="Number")return r(),T({type:"Literal",value:Number(e.value),raw:e.value},e);if(e.type==="String")return r(),T({type:"Literal",value:J(e.value.slice(1,-1)),raw:e.value},e);if(e.type==="Template")return r(),T({type:"TemplateLiteral",expressions:[],quasis:[G(e.value,true)]},e);if(e.type==="TemplateHead")return xe(e);if(e.type==="Keyword")return e.value==="true"?(r(),T({type:"Literal",value:true,raw:"true"},e)):e.value==="false"?(r(),T({type:"Literal",value:false,raw:"false"},e)):e.value==="null"?(r(),T({type:"Literal",value:null,raw:"null"},e)):e.value==="new"?E("'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"?E("Anonymous functions are not supported \u2014 use an arrow function"):E(`'${e.value}' is not supported in this language`);if(e.type==="Identifier")return r(),T({type:"Identifier",name:e.value},e);if(s("(")){r();let t=k();return m(")"),t}return s("[")?be():s("{")?Te():s("<")?ne():E(`Unexpected token '${e.value||e.type}'`)},{parseType:V,parseTypeParamList:Ne,parseTypeInScope:Pe}=he({tokens:S,pos:()=>l,peek:d,next:r,isP:s,isK:x,expectP:m,fail:E,unescape:J,typeRefs:h}),Ee=()=>{let e=r(),t=u(),n=[],o=[];s("<")&&(o=Ne(),n=o.map(A=>A.name)),m("=");let g=Pe(o),P=a({type:"TSTypeAliasDeclaration",id:t,typeParameters:n,typeAnnotation:g},e,f());return s(";")&&r(),P},U=()=>{let e=d();if(e.type==="Identifier"&&e.value==="type"&&d(1).type==="Identifier"&&d(2).type==="Punctuator"&&(d(2).value==="="||d(2).value==="<"))return Ee();if(x("const")||x("let")||x("var")){let g=ce();return s(";")&&r(),g}if(x("if"))return Le();if(x("for"))return Ae();if(x("while"))return Je();if(x("do"))return Oe();if(x("break")||x("continue"))return De();if(x("return"))return Xe();if(x("throw"))return Re();if(x("try"))return Fe();if(x("switch"))return $e();if(x("import"))return Ce();if(x("export"))return je();if(s("{"))return W();if((x("function")||x("async")&&d(1).type==="Keyword"&&d(1).value==="function")&&E("Function declarations are not supported \u2014 use 'const fn = () => \u2026'"),s(";"))return r(),T({type:"EmptyStatement"},e);if(e.type==="Keyword"&&Ze.has(e.value)||e.type==="Identifier"&&tt[e.value]?.(d(1),d(2))===true){let g=et[e.value];E(`'${e.value}' is not supported in this language`+(g?` \u2014 ${g}`:""));}let n=k(),o=s(";")?r():f();return a({type:"ExpressionStatement",expression:n},n,o)},ce=()=>{let e=r(),t=e.value,n=b(new Set),o=null;s("=")?(r(),o=k()):t==="const"&&E("'const' declarations must be initialized");let g=a({type:"VariableDeclarator",id:n,init:o},n,o??n);return a({type:"VariableDeclaration",kind:t,declarations:[g]},e,o??n)},Ie=()=>{let e=d();return e.type!=="String"&&E("Expected module specifier string"),r(),T({type:"Literal",value:J(e.value.slice(1,-1)),raw:e.value},e)},Ce=()=>{let e=r(),t=[];if(d().type!=="String"){if(d().type==="Identifier"){let o=u();t.push(a({type:"ImportDefaultSpecifier",local:o},o,o)),s(",")&&r();}if(s("*")){let o=r();I("as")||E("Expected 'as' after '*' in import"),r();let g=u();t.push(a({type:"ImportNamespaceSpecifier",local:g},o,g));}else if(s("{")){for(r();!s("}")&&!y();){let o=u(),g=o;if(I("as")&&(r(),g=u()),t.push(a({type:"ImportSpecifier",imported:o,local:g},o,g)),s(","))r();else break}m("}");}I("from")||E("Expected 'from' in import declaration"),r();}let n=Ie();return s(";")&&r(),T({type:"ImportDeclaration",specifiers:t,source:n},e)},je=()=>{let e=r();if(x("default")){r();let t=k();return s(";")&&r(),T({type:"ExportDefaultDeclaration",declaration:t},e)}if(x("const")||x("let")||x("var")){let t=ce();return s(";")&&r(),T({type:"ExportNamedDeclaration",declaration:t,specifiers:[],source:null},e)}if(s("{")){r();let t=[];for(;!s("}")&&!y();){let n=u(),o=n;if(I("as")&&(r(),o=u()),t.push(a({type:"ExportSpecifier",local:n,exported:o},n,o)),s(","))r();else break}return m("}"),s(";")&&r(),T({type:"ExportNamedDeclaration",declaration:null,specifiers:t,source:null},e)}return E("Expected 'const', '{', or 'default' after 'export'")},ue=()=>d().type==="Identifier"&&d().value==="of",re=()=>x("in"),Ae=()=>{let e=r();m("(");let t=null,n=null;if(!s(";"))if(x("const")||x("let")||x("var")){let A=r(),O=u();if(s(":")&&(r(),O.typeAnnotation=V(new Set)),ue()||re()){let D=a({type:"VariableDeclarator",id:O,init:null},O,O);n=a({type:"VariableDeclaration",kind:A.value,declarations:[D]},A,O);}else {let D=null;s("=")?(r(),D=k(true)):A.value==="const"&&E("'const' declarations must be initialized");let Y=a({type:"VariableDeclarator",id:O,init:D},O,D??O);t=a({type:"VariableDeclaration",kind:A.value,declarations:[Y]},A,D??O);}}else {let A=k(true);ue()||re()?n=A:t=A;}if(n){let A=re();r();let O=k();m(")");let D=U();return a(A?{type:"ForInStatement",left:n,right:O,body:D}:{type:"ForOfStatement",left:n,right:O,body:D,await:false},e,D)}m(";");let o=s(";")?null:k();m(";");let g=s(")")?null:k();m(")");let P=U();return a({type:"ForStatement",init:t,test:o,update:g,body:P},e,P)},Oe=()=>{let e=r(),t=U();x("while")||E("Expected 'while' after the 'do' body"),r(),m("(");let n=k(),o=m(")");return s(";")&&r(),a({type:"DoWhileStatement",body:t,test:n},e,o)},De=()=>{let e=r(),t=e.value==="break"?"BreakStatement":"ContinueStatement",n=s(";")?r():f();return a({type:t,label:null},e,n)},Je=()=>{let e=r();m("(");let t=k();m(")");let n=U();return a({type:"WhileStatement",test:t,body:n},e,n)},Le=()=>{let e=r();m("(");let t=k();m(")");let n=U(),o=null;return x("else")&&(r(),o=U()),a({type:"IfStatement",test:t,consequent:n,alternate:o},e,o??n)},Xe=()=>{let e=r(),t=null;!s(";")&&!s("}")&&!y()&&(t=k());let n=s(";")?r():f();return a({type:"ReturnStatement",argument:t},e,n)},Re=()=>{let e=r(),t=k(),n=s(";")?r():f();return a({type:"ThrowStatement",argument:t},e,n)},Fe=()=>{let e=r(),t=W(),n=null,o=null;if(x("catch")){let g=r(),P=null;s("(")&&(r(),P=u(),m(")"));let A=W();n=a({type:"CatchClause",param:P,body:A},g,A);}return x("finally")&&(r(),o=W()),!n&&!o&&E("'try' requires a 'catch' or 'finally' clause"),a({type:"TryStatement",block:t,handler:n,finalizer:o},e,o??n??t)},$e=()=>{let e=r();m("(");let t=k();m(")"),m("{");let n=[];for(;!s("}")&&!y();){let g=d(),P=null;x("case")?(r(),P=k()):x("default")?r():E("Expected 'case' or 'default' in switch"),m(":");let A=[];for(;!s("}")&&!x("case")&&!x("default")&&!y();)A.push(U());n.push(a({type:"SwitchCase",test:P,consequent:A},g,f()??g));}let o=m("}");return a({type:"SwitchStatement",discriminant:t,cases:n},e,o)},W=()=>{let e=m("{"),t=[];for(;!s("}")&&!y();)t.push(U());return a({type:"BlockStatement",body:t},e,m("}"))};return {parseExpr:k,parseProgram:()=>{let e=d(),t=[];for(;!y();)t.push(U());return a({type:"Program",sourceType:"module",body:t,...h.length?{typeRefs:h}:{}},e,f()??e)},eof:y,fail:E}}function rt(c){return ge(c).parseProgram()}function ot(c){let{parseExpr:S,eof:l,fail:h}=ge(c),d=S();return l()||h("Unexpected token after expression"),d}exports.KEYWORDS=ye;exports.LexError=Z;exports.ParseError=ee;exports.parse=rt;exports.parseExpression=ot;exports.tokenize=ae;
|
|
1
|
+
'use strict';var core=require('@tslite/core');var te=class extends core.TSLiteError{constructor(u,a,p,k,f){super("lex-error",`${u} (${a.line}:${a.column})`,{position:a,index:p,loc:k,end:f});this.position=a;this.index=p;this.loc=k;this.end=f;this.name="LexError";}},Pe=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"]),nt=["...","===","!==","=>","?.","??","==","!=","<=",">=","&&","||","|","&","++","--","+=","-=","*=","/=","%=","**","<<","+","-","*","/","%","<",">","!","?",":",".",",",";","=","^","~","(",")","[","]","{","}"],de=r=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$",Ne=r=>de(r)||r>="0"&&r<="9",Z=r=>r>="0"&&r<="9",we=r=>Z(r)||r>="a"&&r<="f"||r>="A"&&r<="F",ot=r=>Ne(r)||r==="-",rt=new Set(["(","[","{",",",";",":","?","=>","...","=","+","-","*","/","%","<","<=",">",">=","==","===","!=","!==","&&","||","??","!","+=","-=","*=","/=","%="]),st=new Set(["return","typeof","await","delete","void","in","instanceof","else","case","yield","throw"]);function fe(r,d,u){let a=[],p=0,k=1,f=0,o=()=>({line:k,column:f}),y=(P=0)=>r[p+P]??"",K=P=>{let A=o(),X={start:A,end:{line:k,column:f+1}};if(u){u({message:P,position:A,index:p,loc:X,end:p+1});return}throw new te(P,A,p,X,p+1)},T=()=>{let P=r[p++];return P==="\r"?(r[p]===`
|
|
2
|
+
`&&p++,k++,f=0):P===`
|
|
3
|
+
`||P==="\u2028"||P==="\u2029"?(k++,f=0):f++,P},i=P=>P===`
|
|
4
|
+
`||P==="\r"||P==="\u2028"||P==="\u2029",N=()=>{for(;;){let P=y();if(P===" "||P===" "||P==="\f"||P==="\v"||i(P))T();else if(P==="/"&&y(1)==="/"){let A=p,X=o();T(),T();let I=p;for(;p<r.length&&!i(y());)T();d?.({type:"Line",value:r.slice(I,p),start:A,end:p,loc:{start:X,end:o()}});}else if(P==="/"&&y(1)==="*"){let A=p,X=o();T(),T();let I=p,l=p;for(;;){if(p>=r.length){K("Unterminated block comment"),l=p;break}if(y()==="*"&&y(1)==="/"){l=p,T(),T();break}T();}d?.({type:"Block",value:r.slice(I,l),start:A,end:p,loc:{start:X,end:o()}});}else break}},L=(P,A,X,I)=>{a.push({type:P,value:A,start:X,end:p,loc:{start:I,end:o()}}),E=P==="Punctuator"?rt.has(A):P==="Keyword"?st.has(A):P==="TemplateHead"||P==="TemplateMiddle";},R=P=>{for(T();p<r.length;){let A=y();if(A===P)return T(),r.slice(g,p);if(i(A))return K("Unterminated string literal"),r.slice(g,p);if(A==="\\"){if(T(),p>=r.length)return K("Unterminated string literal"),r.slice(g,p);T();continue}T();}return K("Unterminated string literal"),r.slice(g,p)},D=()=>{if(y()==="0"&&(y(1)==="x"||y(1)==="X")){if(T(),T(),!we(y()))return K("Invalid hexadecimal literal");for(;we(y());)T();return}if(y()==="0"&&(y(1)==="b"||y(1)==="B")){if(T(),T(),y()!=="0"&&y()!=="1")return K("Invalid binary literal");for(;y()==="0"||y()==="1";)T();return}if(y()==="0"&&(y(1)==="o"||y(1)==="O")){if(T(),T(),!(y()>="0"&&y()<="7"))return K("Invalid octal literal");for(;y()>="0"&&y()<="7";)T();return}for(;Z(y());)T();if(y()===".")for(T();Z(y());)T();if(y()==="e"||y()==="E"){if(T(),(y()==="+"||y()==="-")&&T(),!Z(y()))return K("Invalid exponent");for(;Z(y());)T();}},v=()=>{let P=p;for(;p<r.length;){let A=y();if(A==="`"){let X=r.slice(P,p);return T(),{raw:X,interp:false}}if(A==="$"&&y(1)==="{"){let X=r.slice(P,p);return T(),T(),{raw:X,interp:true}}if(A==="\\"){if(T(),p>=r.length)break;T();continue}T();}return K("Unterminated template literal"),{raw:r.slice(P,p),interp:false}},g=0,m=0,M=[],E=true,F="js",H=[],z=[];for(;;){if(F==="jsxChildren"){g=p;let I=o();if(p>=r.length){L("EOF","",g,I);break}let l=y();if(l==="<"){y(1)==="/"?(T(),T(),L("Punctuator","</",g,I),F="jsxCloseTag"):(T(),L("Punctuator","<",g,I),H.push("jsxChildren"),F="jsxOpenTag");continue}if(l==="{"){T(),L("Punctuator","{",g,I),z.push({level:m,restore:"jsxChildren"}),F="js";continue}for(;p<r.length&&y()!=="<"&&y()!=="{";)T();L("JSXText",r.slice(g,p),g,I);continue}if(F==="jsxOpenTag"||F==="jsxCloseTag"){N(),g=p;let I=o();if(p>=r.length){L("EOF","",g,I);break}let l=y();if(de(l)){for(T();ot(y());)T();L("Identifier",r.slice(g,p),g,I);continue}if(l==="/"&&y(1)===">"){T(),T(),L("Punctuator","/>",g,I),F=H.pop()??"js";continue}if(l===">"){T(),L("Punctuator",">",g,I),F=F==="jsxCloseTag"?H.pop()??"js":"jsxChildren";continue}if(l==="{"){T(),L("Punctuator","{",g,I),z.push({level:m,restore:F}),F="js";continue}if(l==='"'||l==="'"){L("String",R(l),g,I);continue}if(l==="="||l==="."||l===":"){T(),L("Punctuator",l,g,I);continue}K(`Unexpected character '${l}' in JSX tag`),T(),L("Unknown",l,g,I);continue}N(),g=p;let P=o();if(p>=r.length){L("EOF","",g,P);break}let A=y();if(de(A)){for(;Ne(y());)T();let I=r.slice(g,p);L(Pe.has(I)?"Keyword":"Identifier",I,g,P);continue}if(Z(A)||A==="."&&Z(y(1))){D(),L("Number",r.slice(g,p),g,P);continue}if(A==='"'||A==="'"){let I=R(A);L("String",I,g,P);continue}if(A==="`"){T();let{raw:I,interp:l}=v();l?(L("TemplateHead",I,g,P),M.push(m)):L("Template",I,g,P);continue}if(A==="<"&&E){T(),L("Punctuator","<",g,P),H.push("js"),F="jsxOpenTag";continue}if(A==="{"){T(),L("Punctuator","{",g,P),m++;continue}if(A==="}"){if(M.length>0&&m===M[M.length-1]){M.pop(),T();let{raw:I,interp:l}=v();L(l?"TemplateMiddle":"TemplateTail",I,g,P),l&&M.push(m);continue}if(z.length>0&&m===z[z.length-1].level){let{restore:I}=z.pop();T(),L("Punctuator","}",g,P),F=I;continue}T(),L("Punctuator","}",g,P),m--;continue}if(A==="?"&&y(1)==="."&&Z(y(2))){T(),L("Punctuator","?",g,P);continue}let X=nt.find(I=>r.startsWith(I,p));if(X){for(let I=0;I<X.length;I++)T();L("Punctuator",X,g,P);continue}K(`Unexpected character '${A}'`),T(),L("Unknown",A,g,P);}return a}var at=new Set(["leadingComments","trailingComments","innerComments","comments"]),Ee=r=>typeof r=="object"&&r!==null&&typeof r.type=="string"&&r.loc!=null&&typeof r.start=="number",Ce=new WeakMap;function it(r){let d=Ce.get(r);if(d)return d;let u=[];for(let a of Object.keys(r)){if(at.has(a))continue;let p=r[a];if(Ee(p))u.push(p);else if(Array.isArray(p))for(let k of p)Ee(k)&&u.push(k);}return u.sort((a,p)=>a.start-p.start),Ce.set(r,u),u}function lt(r,d){let u=r,a,p;for(;;){let k=it(u);a=void 0,p=void 0;let f;for(let o of k){if(o.start<=d.start&&d.end<=o.end){f=o;break}if(o.end<=d.start)a=o;else if(d.end<=o.start){p=o;break}}if(!f)break;u=f;}return {enclosing:u,preceding:a,following:p}}var ye=(r,d)=>{(r.leadingComments??(r.leadingComments=[])).push(d);},ce=(r,d)=>{(r.trailingComments??(r.trailingComments=[])).push(d);},me=(r,d)=>{(r.innerComments??(r.innerComments=[])).push(d);};function ct(r,d){for(let u=d;u<r.length;u++){let a=r[u];if(a!==" "&&a!==" "&&a!=="\r"&&a!==`
|
|
5
|
+
`&&a!=="\f")return a}return ""}var pt=new Set([")","]","}",","]);function he(r,d,u=""){for(let a of d){let{enclosing:p,preceding:k,following:f}=lt(r,a),o=k==null||k.loc.end.line<a.loc.start.line,y=!o&&(f==null||a.loc.end.line<f.loc.start.line);if(o)f?ye(f,a):k?ce(k,a):me(p,a);else if(y)k?ce(k,a):f?ye(f,a):me(p,a);else {let K=pt.has(ct(u,a.end));k&&K?ce(k,a):f?ye(f,a):k?ce(k,a):me(p,a);}}}var Te=(r=[])=>({vars:new Set(r),bounds:new Map,noCond:false,inferSink:null}),ae=(r,d)=>{let u=new Set(r.vars),a=new Map(r.bounds);for(let p of d)u.add(p.name),p.bound||p.isConst?a.set(p.name,{bound:p.bound,isConst:p.isConst}):a.delete(p.name);return {vars:u,bounds:a,noCond:r.noCond,inferSink:r.inferSink}},ut=(r,d)=>{let u=r.bounds.get(d);return u&&(u.bound||u.isConst)?{t:"var",name:d,...u.bound?{bound:u.bound}:{},...u.isConst?{isConst:true}:{}}:{t:"var",name:d}},Ie=r=>{let{peek:d,next:u,isP:a,isK:p,expectP:k,fail:f,unescape:o}=r,y=(l,h)=>{let c=r.tokens[r.pos()-1]??h;return Object.assign(l,{start:h.start,end:c.end,loc:{start:h.loc.start,end:c.loc.end}})},K=()=>{let l=r.pos(),h=r.tokens[l],c=r.tokens[l-1];return !!c&&!!h&&h.loc.start.line>c.loc.end.line},T=()=>{let l=0;for(let h=r.pos();h<r.tokens.length;h++){let c=r.tokens[h];if(c.type==="EOF")return false;if(c.type==="Punctuator"){if(["(","[","{","<"].includes(c.value))l++;else if([")","]","}",">"].includes(c.value)&&(l--,l===0)){let b=r.tokens[h+1];return !!b&&b.type==="Punctuator"&&b.value==="=>"}}}return false},i=()=>{let l=r.tokens,h=[],c=0,b=false;for(let x=r.pos();x<l.length;x++){let w=l[x];if(w.type==="EOF")break;if(w.type==="Punctuator"){if(w.value==="<")c++,c===1&&(b=true);else if(w.value===">"){if(c--,c===0)break}else w.value==="("||w.value==="["||w.value==="{"?(c++,b=false):w.value===")"||w.value==="]"||w.value==="}"?(c--,b=false):w.value===","&&c===1?b=true:b=false;continue}if(c===1&&b){if(w.type==="Keyword"&&w.value==="const")continue;if(w.type==="Identifier"){h.push(w.value),b=false;continue}}b=false;}return h},N=l=>{let h=ae(l,i().map(b=>({name:b})));k("<");let c=[];for(;!a(">");){let b=p("const");b&&u();let x=d();x.type!=="Identifier"&&f("Expected type parameter name"),u();let w;p("extends")&&(u(),w=D(h).schema),a("=")&&(u(),D(h)),c.push({name:x.value,...w?{bound:w}:{},...b?{isConst:true}:{}}),a(">")||k(",");}return k(">"),c},L=l=>{k("<");let h=[];for(;!a(">");)h.push(D(l)),a(">")||k(",");return k(">"),h},R=l=>{let h=d();return h.type==="Identifier"&&h.value===l},D=l=>{let h=d(),c=v(l);if(l.noCond||!p("extends")||K())return c;u();let b=[],x=v({...l,noCond:true,inferSink:b});k("?");let w=ae(l,b.map(J=>({name:J}))),O=D(w);k(":");let $=D(w);return {node:y({type:"TSConditionalType",checkType:c.node,extendsType:x.node,trueType:O.node,falseType:$.node},h),schema:{t:"conditional",check:c.schema,extends:x.schema,then:O.schema,else:$.schema,...b.length?{infer:b}:{}}}},v=l=>{let h=d();a("|")&&u();let c=g(l);if(!a("|"))return c;let b=[c.node],x=[c.schema];for(;a("|");){u();let w=g(l);b.push(w.node),x.push(w.schema);}return {node:y({type:"TSUnionType",types:b},h),schema:{t:"union",of:x}}},g=l=>{let h=d();a("&")&&u();let c=m(l);if(!a("&"))return c;let b=[c.node],x=[c.schema];for(;a("&");){u();let w=m(l);b.push(w.node),x.push(w.schema);}return {node:y({type:"TSIntersectionType",types:b},h),schema:{t:"intersection",of:x}}},m=l=>{let h=d();if(R("keyof")){u();let c=m(l);return {node:y({type:"TSTypeOperator",operator:"keyof",typeAnnotation:c.node},h),schema:{t:"keyof",of:c.schema}}}if(R("readonly")){u();let c=m(l);return c.schema.t!=="array"&&c.schema.t!=="tuple"&&f("'readonly' only applies to array and tuple types"),{node:y({...c.node,readonly:true},h),schema:{...c.schema,readonly:true}}}if(R("infer")){u();let c=d();c.type!=="Identifier"&&f("Expected 'infer' variable name"),u();let b=l.inferSink;return b?(b.push(c.value),{node:y({type:"TSInferType",name:c.value},h),schema:{t:"var",name:c.value}}):f("'infer' is only allowed in the 'extends' clause of a conditional")}return M(l)},M=l=>{let h=d(),c=F(l);for(;a("[")&&!K();)if(u(),a("]"))u(),c={node:y({type:"TSArrayType",elementType:c.node},h),schema:{t:"array",items:c.schema}};else {let b=D(l);k("]"),c={node:y({type:"TSIndexedAccessType",objectType:c.node,indexType:b.node},h),schema:{t:"index",obj:c.schema,key:b.schema}};}return c},E=(l,h,c)=>({node:y({type:"TSKeywordType",kind:h},l),schema:c}),F=l=>{let h=d();if(p("typeof")){u();let x=d();x.type!=="Identifier"&&f("Expected a name after 'typeof' in type position"),u();let w=[x.value];for(;a(".");){u();let O=d();O.type!=="Identifier"&&O.type!=="Keyword"&&f("Expected a property name after '.' in 'typeof'"),u(),w.push(O.value);}return {node:y({type:"TSTypeQuery",exprName:w},h),schema:{t:"typeQuery",path:w}}}if(a("<")){let x=N(l),w=ae(l,x);return z(w,h,x.map(O=>O.name))}if(a("(")){if(T())return z(l,h);u();let x=D(l.noCond?{...l,noCond:false}:l);return k(")"),x}if(a("{"))return A()?X(l):I(l);if(a("["))return P(l);let c=d();if(c.type==="String"){u();let x=o(c.value.slice(1,-1));return {node:y({type:"TSLiteralType",literal:x},h),schema:{t:"literal",value:x}}}if(c.type==="Number"){u();let x=Number(c.value);return {node:y({type:"TSLiteralType",literal:x},h),schema:{t:"literal",value:x}}}if(p("true"))return u(),{node:y({type:"TSLiteralType",literal:true},h),schema:{t:"literal",value:true}};if(p("false"))return u(),{node:y({type:"TSLiteralType",literal:false},h),schema:{t:"literal",value:false}};if(p("null"))return u(),E(h,"null",{t:"null"});if(p("void"))return u(),E(h,"void",{t:"void"});if(c.type==="Identifier"){switch(u(),c.value){case "string":return E(h,"string",{t:"string"});case "number":return E(h,"number",{t:"number"});case "boolean":return E(h,"boolean",{t:"boolean"});case "any":return E(h,"any",{t:"any"});case "unknown":return E(h,"unknown",{t:"unknown"});case "undefined":return E(h,"undefined",{t:"undefined"});case "never":return E(h,"never",{t:"union",of:[]})}let x=a("<")?L(l):[],w=x.map(J=>J.schema),O=x.length?x.map(J=>J.node):void 0,$=y({type:"TSTypeReference",typeName:c.value,...O?{typeArguments:O}:{}},h);return l.vars.has(c.value)&&w.length===0?{node:$,schema:ut(l,c.value)}:c.value==="ReturnType"&&w.length===1?{node:$,schema:{t:"returnType",fn:w[0]}}:c.value==="Parameters"&&w.length===1?{node:$,schema:{t:"parameters",fn:w[0]}}:(r.typeRefs?.push({name:c.value,loc:c.loc}),{node:$,schema:{t:"apply",name:c.value,args:w}})}r.recordError(`Expected a type but got '${c.value||c.type}'`,c);let b=r.createMissingNode({type:"TSTypeReference",typeName:""},c);return r.typeRefs?.push({name:"",loc:b.loc}),{node:b,schema:{t:"unknown"}}},H=l=>{k("(");let h=[];for(;!a(")");){let c=d();c.type!=="Identifier"&&f("Expected parameter name in function type"),u();let b=a("?");b&&u(),k(":");let x=D(l);h.push({node:y({type:"TSTypeParameter",name:c.value,typeAnnotation:x.node,...b?{optional:true}:{}},c),schema:{name:c.value,type:x.schema,...b?{optional:true}:{}}}),a(")")||k(",");}return k(")"),h},z=(l,h,c)=>{let b=H(l);k("=>");let x=D(l);return {node:y({type:"TSFunctionType",params:b.map(w=>w.node),returnType:x.node,...c?.length?{typeParams:[...c]}:{}},h),schema:{t:"fn",params:b.map(w=>w.schema),returns:x.schema,...c?.length?{typeParams:c}:{}}}},P=l=>{let h=d();k("[");let c=[],b=[],x=[];for(;!a("]");){if(a("...")){u();let O=D(l);O.schema.t==="array"?(b.push(O.schema.items),c.push(O.node.elementType),x.push("rest")):(b.push(O.schema),c.push(O.node),x.push("variadic"));}else {let O=D(l),$=a("?");$&&u(),b.push(O.schema),c.push(O.node),x.push($?"optional":"req");}a("]")||k(",");}k("]");let w=x.some(O=>O!=="req");return {node:y({type:"TSTupleType",elementTypes:c,...w?{flags:x}:{}},h),schema:w?{t:"tuple",elements:b,flags:x}:{t:"tuple",elements:b}}},A=()=>{let l=r.tokens,h=r.pos()+1;return l[h]?.type==="Punctuator"&&(l[h]?.value==="+"||l[h]?.value==="-")&&h++,l[h]?.type==="Identifier"&&l[h]?.value==="readonly"&&h++,l[h]?.type==="Punctuator"&&l[h]?.value==="["&&l[h+1]?.type==="Identifier"&&l[h+2]?.type==="Keyword"&&l[h+2]?.value==="in"},X=l=>{let h=d();k("{"),(a("+")||a("-"))&&u(),R("readonly")&&u(),k("[");let c=d();c.type!=="Identifier"&&f("Expected mapped type key name"),u(),p("in")||f("Expected 'in' in mapped type"),u();let b=D(l);R("as")&&f("Key remapping ('as') in mapped types is not supported"),k("]");let x=false,w=a("+")||a("-")?u().value:null;a("?")&&(u(),x=w!=="-"),k(":");let O=D(ae(l,[{name:c.value}]));return (a(";")||a(","))&&u(),k("}"),{node:y({type:"TSMappedType",key:c.value,constraint:b.node,typeAnnotation:O.node,optional:x},h),schema:{t:"mapped",key:c.value,over:b.schema,body:O.schema,optional:x}}},I=l=>{let h=d();k("{");let c=[],b={},x,w=[];for(;!a("}");){let $=d();if(a("(")){let J=H(l);k(":");let B=D(l);w.push({t:"fn",params:J.map(W=>W.schema),returns:B.schema}),c.push(y({type:"TSCallSignatureDeclaration",params:J.map(W=>W.node),returnType:B.node},$));}else if(a("[")){u(),d().type!=="Identifier"&&f("Expected index signature parameter name"),u(),k(":");let J=d();(J.type!=="Identifier"||J.value!=="string"&&J.value!=="number")&&f("Index signature parameter type must be 'string' or 'number'"),u(),k("]"),k(":");let B=D(l);x={key:J.value,value:B.schema},c.push(y({type:"TSIndexSignature",keyType:J.value,typeAnnotation:B.node},$));}else {let J=d(),B;if(J.type==="Identifier"||J.type==="Keyword")u(),B=J.value;else if(J.type==="String")u(),B=o(J.value.slice(1,-1));else if(J.type==="Number")u(),B=J.value;else return f("Expected property name in object type");let W=a("?");W&&u(),k(":");let ie=D(l);b[B]={type:ie.schema,...W?{optional:true}:{}},c.push(y({type:"TSPropertySignature",key:B,typeAnnotation:ie.node,...W?{optional:true}:{}},$));}if(a(";")||a(","))u();else break}k("}");let O=y({type:"TSTypeLiteral",members:c},h);return w.length>0?Object.keys(b).length>0||x?f("Callable object types (call signatures mixed with members) are not supported"):{node:O,schema:w.length===1?w[0]:{t:"overload",signatures:w}}:{node:O,schema:{t:"object",props:b,...x?{index:x}:{}}}};return {parseType:l=>D(Te(l)),parseTypeParamList:()=>N(Te()),parseTypeInScope:l=>D(ae(Te(),l))}};var ne=class extends core.TSLiteError{constructor(u,a,p,k,f){super("parse-error",`${u} (${a.line}:${a.column})`,{position:a,index:p,loc:k,end:f});this.position=a;this.index=p;this.loc=k;this.end=f;this.name="ParseError";}},ft=r=>{let d=r;return d!=null&&typeof d.start=="number"&&d.start===d.end&&d.start>=0},yt=(r,d)=>Object.assign(r,{start:d.start,end:d.start,loc:{start:d.loc.start,end:d.loc.start}}),mt={"??":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},ht=new Set(["??","||","&&"]),Tt=new Set(["class","debugger","with","enum","interface"]),gt={enum:'use a union of literals (`type T = "a" | "b"`) \u2014 it is serializable',interface:"use a type alias (`type X = { \u2026 }`)",namespace:"use modules (`import`/`export`)",module:"use modules (`import`/`export`)",declare:"declare the shape via the DI env, or with a `type` alias",abstract:"classes are not part of the language \u2014 model with objects + functions"},bt={namespace:(r,d)=>r.type==="Identifier"&&d.type==="Punctuator"&&d.value==="{",module:(r,d)=>r.type==="Identifier"&&d.type==="Punctuator"&&d.value==="{",declare:r=>r.type==="Keyword"&&["const","let","var","function","class","enum","interface"].includes(r.value)||r.type==="Identifier"&&["type","namespace","module"].includes(r.value),abstract:r=>r.type==="Keyword"&&r.value==="class"},St=new Set(["=","+=","-=","*=","/=","%="]);function Ae(r){let d=[],u=[],a=fe(r,e=>u.push(e),e=>d.push({code:"lex-error",...e})),p=0,k=[],f=(e=0)=>a[Math.min(p+e,a.length-1)],o=()=>a[p++],y=()=>a[p-1],K=()=>{let e=a[p],n=a[p-1];return !!e&&!!n&&e.loc.start.line>n.loc.end.line},T=()=>f().type==="EOF",i=e=>f().type==="Punctuator"&&f().value===e,N=e=>f().type==="Keyword"&&f().value===e,L=e=>f().type==="Identifier"&&f().value===e,R=(e,n=f())=>{throw D(e,n),new ne(e,n.loc.start,n.start,n.loc,n.end)},D=(e,n=f())=>{let t=d[d.length-1];t&&t.index===n.start||d.push({code:"parse-error",message:e,position:n.loc.start,index:n.start,loc:n.loc,end:n.end});},v=e=>(i(e)||R(`Expected '${e}' but got '${f().value||f().type}'`),o()),g=(e,n)=>{let t=y()??n;return Object.assign(e,{start:n.start,end:t.end,loc:{start:n.loc.start,end:t.loc.end}})},m=(e,n,t)=>Object.assign(e,{start:n.start,end:t.end,loc:{start:n.loc.start,end:t.loc.end}}),M=e=>{let n="";for(let t=0;t<e.length;t++){if(e[t]!=="\\"){n+=e[t];continue}let s=e[++t];switch(s){case "n":n+=`
|
|
6
|
+
`;break;case "t":n+=" ";break;case "r":n+="\r";break;case "b":n+="\b";break;case "f":n+="\f";break;case "v":n+="\v";break;case "0":n+="\0";break;case "x":n+=String.fromCharCode(parseInt(e.slice(t+1,t+3),16)),t+=2;break;case "u":if(e[t+1]==="{"){let S=e.indexOf("}",t);n+=String.fromCodePoint(parseInt(e.slice(t+2,S),16)),t=S;}else n+=String.fromCharCode(parseInt(e.slice(t+1,t+5),16)),t+=4;break;default:n+=s;}}return n},E=(e=false)=>F(e),F=(e=false)=>{let n=H(e),t=f();if(t.type==="Punctuator"&&St.has(t.value)){o();let s=F();return m({type:"AssignmentExpression",operator:t.value,left:n,right:s},n,s)}return n},H=(e=false)=>{let n=P(0,e);if(!i("?"))return n;o();let t=E();v(":");let s=E();return m({type:"ConditionalExpression",test:n,consequent:t,alternate:s},n,s)},z=()=>{let e=f();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 n=f(1);if(n.type==="Punctuator"&&n.value===">"&&e.end===n.start){let t=f(2);return t.type==="Punctuator"&&t.value===">"&&n.end===t.start?{op:">>>",consume:3}:{op:">>",consume:2}}return {op:">",consume:1}}return {op:e.value,consume:1}},P=(e,n=false)=>{let t=A();for(;;){let s=z();if(!s)break;let{op:S,consume:C}=s;if(S==="in"&&n)break;let j=mt[S];if(!j||j<=e)break;if(S==="satisfies"){if(K())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(S==="as"){if(K())break;o();let U=re(new Set);t=m({type:"TSAsExpression",expression:t,typeAnnotation:U.schema,typeAnnotationNode:U.node},t,y());continue}for(let U=0;U<C;U++)o();let _=P(S==="**"?j-1:j,n);t=m({type:ht.has(S)?"LogicalExpression":"BinaryExpression",operator:S,left:t,right:_},t,_);}return t},A=()=>{let e=f();return e.type==="Punctuator"&&(e.value==="++"||e.value==="--")?(o(),g({type:"UpdateExpression",operator:e.value,prefix:true,argument:A()},e)):N("await")?(o(),g({type:"AwaitExpression",argument:A()},e)):N("typeof")||N("void")||N("delete")||e.type==="Punctuator"&&(e.value==="!"||e.value==="-"||e.value==="+"||e.value==="~")?X(e):l()},X=e=>{o();let n=A();return i("**")&&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.`),g({type:"UnaryExpression",operator:e.value,prefix:true,argument:n},e)},I=()=>{let e=p,n=d.length,t=()=>(p=e,d.length=n,void 0);try{if(o(),i(">"))return t();let s=[];for(;s.push(re(new Set).schema),!!i(",");)o();return i(">")?(o(),i("(")?s:t()):t()}catch{return t()}},l=()=>{let e=Je(),n=false;for(;;)if(i("?."))if(o(),n=true,i("(")){let{args:t,close:s}=h();e=m({type:"CallExpression",callee:e,arguments:t,optional:true},e,s);}else if(i("[")){o();let t=E(),s=v("]");e=m({type:"MemberExpression",object:e,property:t,computed:true,optional:true},e,s);}else {let t=f();t.type!=="Identifier"&&t.type!=="Keyword"&&R("Expected property name after '?.'"),o();let s=g({type:"Identifier",name:t.value},t);e=m({type:"MemberExpression",object:e,property:s,computed:false,optional:true},e,s);}else if(i(".")){o();let t=f();t.type!=="Identifier"&&t.type!=="Keyword"&&R("Expected property name"),o();let s=g({type:"Identifier",name:t.value},t);e=m({type:"MemberExpression",object:e,property:s,computed:false,optional:false},e,s);}else if(i("[")){o();let t=E(),s=v("]");e=m({type:"MemberExpression",object:e,property:t,computed:true,optional:false},e,s);}else if(i("(")){let{args:t,close:s}=h();e=m({type:"CallExpression",callee:e,arguments:t,optional:false},e,s);}else if(i("<")){let t=I();if(!t)break;let{args:s,close:S}=h();e=m({type:"CallExpression",callee:e,arguments:s,optional:false,typeArguments:t},e,S);}else if(i("++")||i("--")){let t=o();e=m({type:"UpdateExpression",operator:t.value,prefix:false,argument:e},e,t);}else break;return n?m({type:"ChainExpression",expression:e},e,e):e},h=()=>{v("(");let e=[];for(;!i(")");)e.push(c()),i(")")||v(",");return {args:e,close:v(")")}},c=()=>{if(i("...")){let e=o(),n=E();return m({type:"SpreadElement",argument:n},e,n)}return E()},b=()=>{let e=f();return e.type!=="Identifier"&&R("Expected identifier"),o(),g({type:"Identifier",name:e.value},e)},x=e=>{let n=i("{")?w(e):i("[")?O(e):b();if(i(":")){o();let t=re(e);n.typeAnnotation=t.schema,n.typeAnnotationNode=t.node;}return n},w=e=>{let n=v("{"),t=[];for(;!i("}");){if(i("...")){let S=o(),C=x(e);t.push(m({type:"RestElement",argument:C},S,C));}else {let S=b(),C,j=false;if(i(":")?(o(),C=x(e)):(C={...S},j=true),i("=")){o();let _=E();C=m({type:"AssignmentPattern",left:C,right:_},C,_);}t.push(m({type:"Property",key:S,value:C,kind:"init",shorthand:j,computed:false,method:false},S,C));}i("}")||v(",");}let s=v("}");return m({type:"ObjectPattern",properties:t},n,s)},O=e=>{let n=v("["),t=[];for(;!i("]");){if(i(",")){t.push(null),o();continue}if(i("...")){let S=o(),C=x(e);t.push(m({type:"RestElement",argument:C},S,C));}else {let S=x(e);if(i("=")){o();let C=E();S=m({type:"AssignmentPattern",left:S,right:C},S,C);}t.push(S);}i("]")||v(",");}let s=v("]");return m({type:"ArrayPattern",elements:t},n,s)},$=()=>{let e=0;for(let n=p;n<a.length;n++){let t=a[n];if(t.type==="EOF")return false;if(t.type==="Punctuator"){if(t.value==="("||t.value==="["||t.value==="{")e++;else if((t.value===")"||t.value==="]"||t.value==="}")&&(e--,e===0)){let s=a[n+1];return !s||s.type!=="Punctuator"?false:s.value==="=>"?true:s.value===":"?J(n+2):false}}}return false},J=e=>{let n=0;for(let t=e;t<a.length;t++){let s=a[t];if(s.type==="EOF")return false;if(s.type==="Punctuator")if(["(","[","{","<"].includes(s.value))n++;else if([")","]","}",">"].includes(s.value)){if(n===0)return false;n--;}else {if(n===0&&s.value==="=>")return true;if(n===0&&(s.value===";"||s.value===","))return false}}return false},B=(e=new Set)=>{v("(");let n=[];for(;!i(")");){if(i("...")){let t=o(),s=x(e);n.push(m({type:"RestElement",argument:s},t,s));}else {let t=x(e);if(i("=")){o();let s=E();t=m({type:"AssignmentPattern",left:t,right:s},t,s);}n.push(t);}i(")")||v(",");}return v(")"),n},W=(e,n)=>{let t=i("(")?B():[b()],s,S;if(i(":")){o();let j=re(new Set);s=j.schema,S=j.node;}v("=>");let C=i("{")?se():E();return g({type:"ArrowFunctionExpression",params:t,body:C,async:e,expression:C.type!=="BlockStatement",generator:false,...s?{returnType:s,returnTypeNode:S}:{}},n)},ie=()=>{let e=v("["),n=[];for(;!i("]");){if(i(",")){o(),n.push(null);continue}n.push(c()),i("]")||v(",");}return m({type:"ArrayExpression",elements:n},e,v("]"))},Le=()=>{let e=v("{"),n=[];for(;!i("}");){if(i("...")){let t=o(),s=E();n.push(m({type:"SpreadElement",argument:s},t,s));}else {let t=f(),s,S=false;if(i("["))S=true,o(),s=E(),v("]");else if(t.type==="String")o(),s=g({type:"Literal",value:M(t.value.slice(1,-1)),raw:t.value},t);else if(t.type==="Number")o(),s=g({type:"Literal",value:Number(t.value),raw:t.value},t);else if(t.type==="Identifier"||t.type==="Keyword")o(),s=g({type:"Identifier",name:t.value},t);else return R("Invalid property key");if(i(":")){o();let C=E();n.push(m({type:"Property",key:s,value:C,kind:"init",method:false,shorthand:false,computed:S},t,C));}else n.push(m({type:"Property",key:s,value:s,kind:"init",method:false,shorthand:true,computed:false},t,s));}i("}")||v(",");}return m({type:"ObjectExpression",properties:n},e,v("}"))},le=(e,n)=>({type:"TemplateElement",value:{raw:e,cooked:M(e)},tail:n}),je=e=>{o();let n=[le(e.value,false)],t=[];for(;;){t.push(E());let s=f();if(s.type==="TemplateMiddle")o(),n.push(le(s.value,false));else if(s.type==="TemplateTail"){o(),n.push(le(s.value,true));break}else R("Expected `}` to close template interpolation");}return g({type:"TemplateLiteral",quasis:n,expressions:t},e)},oe=()=>{let e=f();return e.type!=="Identifier"&&R(`Expected JSX identifier but got '${e.value||e.type}'`),g({type:"JSXIdentifier",name:o().value},e)},ge=()=>{let e=oe();if(i(":")){o();let n=oe();return m({type:"JSXNamespacedName",namespace:e,name:n},e,n)}for(;i(".");){o();let n=oe();e=m({type:"JSXMemberExpression",object:e,property:n},e,n);}return e},G=e=>e.type==="JSXIdentifier"?e.name:e.type==="JSXNamespacedName"?`${G(e.namespace)}:${G(e.name)}`:`${G(e.object)}.${G(e.property)}`,Oe=()=>{let e=f();if(e.type==="String")return o(),g({type:"Literal",value:M(e.value.slice(1,-1)),raw:e.value},e);if(i("{")){let n=o(),t=F(),s=v("}");return m({type:"JSXExpressionContainer",expression:t},n,s)}return i("<")?pe():R(`Invalid JSX attribute value '${e.value||e.type}'`)},De=()=>{let e=[];for(;!i(">")&&!i("/>")&&!T();){if(i("{")){let s=o();v("...");let S=F(),C=v("}");e.push(m({type:"JSXSpreadAttribute",argument:S},s,C));continue}let n=oe();if(i(":")){o();let s=oe();n=m({type:"JSXNamespacedName",namespace:n,name:s},n,s);}let t=null;i("=")&&(o(),t=Oe()),e.push(m({type:"JSXAttribute",name:n,value:t},n,t??n));}return e},be=()=>{let e=[];for(;!(i("</")||T());){let n=f();if(n.type==="JSXText")o(),e.push(g({type:"JSXText",value:n.value,raw:n.value},n));else if(i("{")){let t=o();if(i("}")){let s=o(),S=g({type:"JSXEmptyExpression"},t);e.push(m({type:"JSXExpressionContainer",expression:S},t,s));}else {let s=F(),S=v("}");e.push(m({type:"JSXExpressionContainer",expression:s},t,S));}}else i("<")?e.push(pe()):R(`Unexpected token in JSX children '${n.value||n.type}'`);}return e},pe=()=>{let e=v("<");if(i(">")){let Q=o(),ee=m({type:"JSXOpeningFragment"},e,Q),Qe=be(),Ze=v("</"),ke=v(">"),et=m({type:"JSXClosingFragment"},Ze,ke);return m({type:"JSXFragment",openingFragment:ee,children:Qe,closingFragment:et},e,ke)}let n=ge(),t=De();if(i("/>")){let Q=o(),ee=m({type:"JSXOpeningElement",name:n,attributes:t,selfClosing:true},e,Q);return m({type:"JSXElement",openingElement:ee,children:[],closingElement:null},e,Q)}let s=v(">"),S=m({type:"JSXOpeningElement",name:n,attributes:t,selfClosing:false},e,s),C=be(),j=v("</"),_=f(),U=ge();G(U)!==G(n)&&R(`JSX closing tag </${G(U)}> does not match opening <${G(n)}>`,_);let q=v(">"),V=m({type:"JSXClosingElement",name:U},j,q);return m({type:"JSXElement",openingElement:S,children:C,closingElement:V},e,q)},Je=()=>{let e=f();if(N("async")){let n=f(1);return n.value==="("||n.type==="Identifier"?(o(),W(true,e)):R("Unexpected 'async'")}if(i("(")&&$()||e.type==="Identifier"&&f(1).type==="Punctuator"&&f(1).value==="=>")return W(false,e);if(e.type==="Number")return o(),g({type:"Literal",value:Number(e.value),raw:e.value},e);if(e.type==="String")return o(),g({type:"Literal",value:M(e.value.slice(1,-1)),raw:e.value},e);if(e.type==="Template")return o(),g({type:"TemplateLiteral",expressions:[],quasis:[le(e.value,true)]},e);if(e.type==="TemplateHead")return je(e);if(e.type==="Keyword")return e.value==="true"?(o(),g({type:"Literal",value:true,raw:"true"},e)):e.value==="false"?(o(),g({type:"Literal",value:false,raw:"false"},e)):e.value==="null"?(o(),g({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(),g({type:"Identifier",name:e.value},e);if(i("(")){o();let n=E();return v(")"),n}return i("[")?ie():i("{")?Le():i("<")?pe():R(`Unexpected token '${e.value||e.type}'`)},{parseType:re,parseTypeParamList:Fe,parseTypeInScope:Xe}=Ie({tokens:a,pos:()=>p,peek:f,next:o,isP:i,isK:N,expectP:v,fail:R,recordError:D,createMissingNode:yt,unescape:M,typeRefs:k}),Ke=()=>{let e=o(),n=b(),t=[],s=[];i("<")&&(s=Fe(),t=s.map(j=>j.name)),v("=");let S=Xe(s),C=m({type:"TSTypeAliasDeclaration",id:n,typeParameters:t,typeAnnotation:S.schema,typeNode:S.node},e,y());return i(";")&&o(),C},Y=()=>{let e=f();if(e.type==="Identifier"&&e.value==="type"&&f(1).type==="Identifier"&&f(2).type==="Punctuator"&&(f(2).value==="="||f(2).value==="<"))return Ke();if(N("const")||N("let")||N("var")){let S=Se();return i(";")&&o(),S}if(N("if"))return qe();if(N("for"))return Be();if(N("while"))return We();if(N("do"))return _e();if(N("break")||N("continue"))return ze();if(N("return"))return He();if(N("throw"))return Ve();if(N("try"))return Ge();if(N("switch"))return Ye();if(N("import"))return $e();if(N("export"))return Me();if(i("{"))return se();if((N("function")||N("async")&&f(1).type==="Keyword"&&f(1).value==="function")&&R("Function declarations are not supported \u2014 use 'const fn = () => \u2026'"),i(";"))return o(),g({type:"EmptyStatement"},e);if(e.type==="Keyword"&&Tt.has(e.value)||e.type==="Identifier"&&bt[e.value]?.(f(1),f(2))===true){let S=gt[e.value];R(`'${e.value}' is not supported in this language`+(S?` \u2014 ${S}`:""));}let t=E(),s=i(";")?o():y();return m({type:"ExpressionStatement",expression:t},t,s)},Se=()=>{let e=o(),n=e.value,t=()=>{let S=x(new Set),C=null;return i("=")?(o(),C=E()):n==="const"&&D("'const' declarations must be initialized"),m({type:"VariableDeclarator",id:S,init:C},S,C??S)},s=[t()];for(;i(",");)o(),s.push(t());return m({type:"VariableDeclaration",kind:n,declarations:s},e,s[s.length-1])},Ue=()=>{let e=f();return e.type!=="String"&&R("Expected module specifier string"),o(),g({type:"Literal",value:M(e.value.slice(1,-1)),raw:e.value},e)},$e=()=>{let e=o(),n=[];if(f().type!=="String"){if(f().type==="Identifier"){let s=b();n.push(m({type:"ImportDefaultSpecifier",local:s},s,s)),i(",")&&o();}if(i("*")){let s=o();L("as")||R("Expected 'as' after '*' in import"),o();let S=b();n.push(m({type:"ImportNamespaceSpecifier",local:S},s,S));}else if(i("{")){for(o();!i("}")&&!T();){let s=b(),S=s;if(L("as")&&(o(),S=b()),n.push(m({type:"ImportSpecifier",imported:s,local:S},s,S)),i(","))o();else break}v("}");}L("from")||R("Expected 'from' in import declaration"),o();}let t=Ue();return i(";")&&o(),g({type:"ImportDeclaration",specifiers:n,source:t},e)},Me=()=>{let e=o();if(N("default")){o();let n=E();return i(";")&&o(),g({type:"ExportDefaultDeclaration",declaration:n},e)}if(N("const")||N("let")||N("var")){let n=Se();return i(";")&&o(),g({type:"ExportNamedDeclaration",declaration:n,specifiers:[],source:null},e)}if(i("{")){o();let n=[];for(;!i("}")&&!T();){let t=b(),s=t;if(L("as")&&(o(),s=b()),n.push(m({type:"ExportSpecifier",local:t,exported:s},t,s)),i(","))o();else break}return v("}"),i(";")&&o(),g({type:"ExportNamedDeclaration",declaration:null,specifiers:n,source:null},e)}return R("Expected 'const', '{', or 'default' after 'export'")},ve=()=>f().type==="Identifier"&&f().value==="of",ue=()=>N("in"),Be=()=>{let e=o();v("(");let n=null,t=null;if(!i(";"))if(N("const")||N("let")||N("var")){let j=o(),_=()=>{let q=b();if(i(":")){o();let V=re(new Set);q.typeAnnotation=V.schema,q.typeAnnotationNode=V.node;}return q},U=_();if(ve()||ue()){let q=m({type:"VariableDeclarator",id:U,init:null},U,U);t=m({type:"VariableDeclaration",kind:j.value,declarations:[q]},j,U);}else {let q=Q=>{let ee=null;return i("=")?(o(),ee=E(true)):j.value==="const"&&R("'const' declarations must be initialized"),m({type:"VariableDeclarator",id:Q,init:ee},Q,ee??Q)},V=[q(U)];for(;i(",");)o(),V.push(q(_()));n=m({type:"VariableDeclaration",kind:j.value,declarations:V},j,V[V.length-1]);}}else {let j=E(true);ve()||ue()?t=j:n=j;}if(t){let j=ue();o();let _=E();v(")");let U=Y();return m(j?{type:"ForInStatement",left:t,right:_,body:U}:{type:"ForOfStatement",left:t,right:_,body:U,await:false},e,U)}v(";");let s=i(";")?null:E();v(";");let S=i(")")?null:E();v(")");let C=Y();return m({type:"ForStatement",init:n,test:s,update:S,body:C},e,C)},_e=()=>{let e=o(),n=Y();N("while")||R("Expected 'while' after the 'do' body"),o(),v("(");let t=E(),s=v(")");return i(";")&&o(),m({type:"DoWhileStatement",body:n,test:t},e,s)},ze=()=>{let e=o(),n=e.value==="break"?"BreakStatement":"ContinueStatement",t=i(";")?o():y();return m({type:n,label:null},e,t)},We=()=>{let e=o();v("(");let n=E();v(")");let t=Y();return m({type:"WhileStatement",test:n,body:t},e,t)},qe=()=>{let e=o();v("(");let n=E();v(")");let t=Y(),s=null;return N("else")&&(o(),s=Y()),m({type:"IfStatement",test:n,consequent:t,alternate:s},e,s??t)},He=()=>{let e=o(),n=null;!i(";")&&!i("}")&&!T()&&(n=E());let t=i(";")?o():y();return m({type:"ReturnStatement",argument:n},e,t)},Ve=()=>{let e=o(),n=E(),t=i(";")?o():y();return m({type:"ThrowStatement",argument:n},e,t)},Ge=()=>{let e=o(),n=se(),t=null,s=null;if(N("catch")){let S=o(),C=null;i("(")&&(o(),C=b(),v(")"));let j=se();t=m({type:"CatchClause",param:C,body:j},S,j);}return N("finally")&&(o(),s=se()),!t&&!s&&R("'try' requires a 'catch' or 'finally' clause"),m({type:"TryStatement",block:n,handler:t,finalizer:s},e,s??t??n)},Ye=()=>{let e=o();v("(");let n=E();v(")"),v("{");let t=[];for(;!i("}")&&!T();){let S=f(),C=null;N("case")?(o(),C=E()):N("default")?o():R("Expected 'case' or 'default' in switch"),v(":");let j=[];for(;!i("}")&&!N("case")&&!N("default")&&!T();)j.push(Y());t.push(m({type:"SwitchCase",test:C,consequent:j},S,y()??S));}let s=v("}");return m({type:"SwitchStatement",discriminant:n,cases:t},e,s)},se=()=>{let e=v("{"),n=xe(()=>i("}"));return m({type:"BlockStatement",body:n},e,v("}"))},xe=e=>{let n=[];for(;!e()&&!T();){if(f().type==="Unknown"){o();continue}try{n.push(Y());}catch(t){if(!(t instanceof ne))throw t;T()||o();}}return n};return {parseExpr:E,parseProgram:()=>{let e=f(),n=xe(()=>false);return m({type:"Program",sourceType:"module",body:n,...k.length?{typeRefs:k}:{},...u.length?{comments:u}:{},...d.length?{parseDiagnostics:d}:{}},e,y()??e)},eof:T,fail:R,diagnostics:d}}function Re(r){let d=Ae(r),u=d.parseProgram(),a=u.comments;return a?.length&&he(u,a,r),{ast:u,diagnostics:d.diagnostics}}function vt(r){let{ast:d,diagnostics:u}=Re(r),a=u[0];if(a){let p=a.code==="lex-error"?te:ne;throw new p(a.message,a.position,a.index,a.loc,a.end)}return d}function xt(r){let d=Ae(r),u=d.parseExpr();d.eof()||d.fail("Unexpected token after expression");let a=d.diagnostics[0];if(a){let p=a.code==="lex-error"?te:ne;throw new p(a.message,a.position,a.index,a.loc,a.end)}return u}exports.KEYWORDS=Pe;exports.LexError=te;exports.ParseError=ne;exports.attachComments=he;exports.nodeIsMissing=ft;exports.parse=vt;exports.parseExpression=xt;exports.parseTolerant=Re;exports.tokenize=fe;
|
package/dist/index.d.cts
CHANGED
|
@@ -12,7 +12,7 @@ interface SourceLocation {
|
|
|
12
12
|
readonly start: Position;
|
|
13
13
|
readonly end: Position;
|
|
14
14
|
}
|
|
15
|
-
type TokenType = "Identifier" | "Keyword" | "Number" | "String" | "Template" | "TemplateHead" | "TemplateMiddle" | "TemplateTail" | "Punctuator" | "JSXText" | "EOF";
|
|
15
|
+
type TokenType = "Identifier" | "Keyword" | "Number" | "String" | "Template" | "TemplateHead" | "TemplateMiddle" | "TemplateTail" | "Punctuator" | "JSXText" | "Unknown" | "EOF";
|
|
16
16
|
interface Token {
|
|
17
17
|
readonly type: TokenType;
|
|
18
18
|
/** O lexema cru, como aparece na fonte (sem decodificar escapes). */
|
|
@@ -22,6 +22,38 @@ interface Token {
|
|
|
22
22
|
readonly end: number;
|
|
23
23
|
readonly loc: SourceLocation;
|
|
24
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"`;
|
|
29
|
+
* `/* foo */` → `" foo "`. Carrega `start`/`end`/`loc` como os nós do parser.
|
|
30
|
+
*/
|
|
31
|
+
interface CommentToken {
|
|
32
|
+
readonly type: "Line" | "Block";
|
|
33
|
+
readonly value: string;
|
|
34
|
+
readonly start: number;
|
|
35
|
+
readonly end: number;
|
|
36
|
+
readonly loc: SourceLocation;
|
|
37
|
+
}
|
|
38
|
+
/** Coletor de comentários passado ao `tokenize` (canal lateral, opt-in). */
|
|
39
|
+
type OnComment = (comment: CommentToken) => void;
|
|
40
|
+
/**
|
|
41
|
+
* Um erro de léxico como DADO (o `onError` do scanner do tsc, que também não
|
|
42
|
+
* lança). Mesma forma que o `ParseDiagnostic` do parser, para viajarem juntos.
|
|
43
|
+
*/
|
|
44
|
+
interface LexDiagnostic {
|
|
45
|
+
readonly message: string;
|
|
46
|
+
readonly position: Position;
|
|
47
|
+
readonly index: number;
|
|
48
|
+
readonly loc: SourceLocation;
|
|
49
|
+
readonly end: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Coletor de erros de léxico (opt-in). PRESENTE → o tokenizer RECUPERA (emite um
|
|
53
|
+
* token `Unknown`, ou o token parcial, e segue), como o scanner do tsc. AUSENTE →
|
|
54
|
+
* o tokenizer LANÇA `LexError` no primeiro erro (o contrato estrito de sempre).
|
|
55
|
+
*/
|
|
56
|
+
type OnLexError = (diagnostic: LexDiagnostic) => void;
|
|
25
57
|
/** Erro de léxico, com a posição onde ocorreu. */
|
|
26
58
|
declare class LexError extends TSLiteError<"lex-error"> {
|
|
27
59
|
readonly position: Position;
|
|
@@ -44,8 +76,18 @@ declare class LexError extends TSLiteError<"lex-error"> {
|
|
|
44
76
|
}
|
|
45
77
|
/** Palavras reservadas. As permitidas e as proibidas — o parser decide. */
|
|
46
78
|
declare const KEYWORDS: Set<string>;
|
|
47
|
-
/**
|
|
48
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Tokeniza a fonte. Devolve a lista de tokens, terminada por um `EOF`.
|
|
81
|
+
*
|
|
82
|
+
* `onComment` (opcional) recebe cada comentário conforme é pulado — canal
|
|
83
|
+
* lateral, sem entrar no stream de tokens.
|
|
84
|
+
*
|
|
85
|
+
* `onError` (opcional) liga a RECUPERAÇÃO: com ele, um erro de léxico é
|
|
86
|
+
* REGISTRADO (não lançado) e o tokenizer segue — char inesperado vira token
|
|
87
|
+
* `Unknown`, string/template/número mal-formados viram o token parcial. Sem ele,
|
|
88
|
+
* o comportamento é o estrito de sempre: o primeiro erro **lança** `LexError`.
|
|
89
|
+
*/
|
|
90
|
+
declare function tokenize(source: string, onComment?: OnComment, onError?: OnLexError): Token[];
|
|
49
91
|
|
|
50
92
|
/** Erro de sintaxe, com a posição onde ocorreu. */
|
|
51
93
|
declare class ParseError extends TSLiteError<"parse-error"> {
|
|
@@ -69,7 +111,52 @@ declare class ParseError extends TSLiteError<"parse-error"> {
|
|
|
69
111
|
/** Offset absoluto do fim (exclusivo) do token culpado. */
|
|
70
112
|
end?: number | undefined);
|
|
71
113
|
}
|
|
72
|
-
/**
|
|
114
|
+
/**
|
|
115
|
+
* Um erro de sintaxe como **DADO** (não exceção) — o modelo do tsc, cujo parser
|
|
116
|
+
* não lança: ele empurra em `parseDiagnostics` e segue (`parser.ts:2149`). Carrega
|
|
117
|
+
* o mesmo que o `ParseError`, para que o parse estrito possa relançá-lo idêntico.
|
|
118
|
+
*/
|
|
119
|
+
interface ParseDiagnostic {
|
|
120
|
+
/** De qual fase veio — o `parse` estrito relança a classe certa, e o editor
|
|
121
|
+
* distingue as duas. */
|
|
122
|
+
readonly code: ParserErrorCode;
|
|
123
|
+
readonly message: string;
|
|
124
|
+
readonly position: Position;
|
|
125
|
+
readonly index: number;
|
|
126
|
+
readonly loc: SourceLocation;
|
|
127
|
+
readonly end: number;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* O nó é FALTANTE (sintético, criado na recuperação de erro)? Marcado pela própria
|
|
131
|
+
* posição — largura zero —, exatamente como o `nodeIsMissing` do tsc
|
|
132
|
+
* (`utilities.ts:1079`: `node.pos === node.end`). Um buraco no texto vira um nó
|
|
133
|
+
* bem-formado de largura zero, em vez de derrubar a árvore inteira.
|
|
134
|
+
*/
|
|
135
|
+
declare const nodeIsMissing: (node: unknown) => boolean;
|
|
136
|
+
/** O resultado do parse TOLERANTE: a árvore (talvez com buracos) + os erros. */
|
|
137
|
+
interface ParseResult {
|
|
138
|
+
/** A árvore. `undefined` só quando nem o léxico passou (erro de `tokenize`). */
|
|
139
|
+
readonly ast: types.Program | undefined;
|
|
140
|
+
/** Os erros de sintaxe como DADO, em ordem de ocorrência. */
|
|
141
|
+
readonly diagnostics: readonly ParseDiagnostic[];
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Parse **tolerante**: nunca lança por erro de sintaxe. Devolve a árvore — com
|
|
145
|
+
* nós FALTANTES (largura zero, ver {@link nodeIsMissing}) onde o texto tinha
|
|
146
|
+
* buracos — e os diagnósticos ao lado. É o que um EDITOR consome: completion e
|
|
147
|
+
* hover precisam de árvore justamente enquanto o código está incompleto.
|
|
148
|
+
*
|
|
149
|
+
* É o modo único do tsc (o parser dele nunca lança); aqui ele convive com o
|
|
150
|
+
* {@link parse} estrito, que é o contrato de quem VALIDA.
|
|
151
|
+
*/
|
|
152
|
+
declare function parseTolerant(source: string): ParseResult;
|
|
153
|
+
/**
|
|
154
|
+
* Faz o parse de uma fonte completa num `Program` (ESTree, com `loc`).
|
|
155
|
+
*
|
|
156
|
+
* Contrato **estrito** (o de sempre): o primeiro erro de sintaxe **lança**. Quem
|
|
157
|
+
* valida quer tudo-ou-nada — rodar o checker sobre uma árvore com buracos só
|
|
158
|
+
* produziria cascata. Quem precisa da árvore parcial usa o {@link parseTolerant}.
|
|
159
|
+
*/
|
|
73
160
|
declare function parse(source: string): types.Program;
|
|
74
161
|
/**
|
|
75
162
|
* Conveniência: faz o parse de uma **única expressão** (ex.: célula de regra).
|
|
@@ -77,6 +164,35 @@ declare function parse(source: string): types.Program;
|
|
|
77
164
|
*/
|
|
78
165
|
declare function parseExpression(source: string): types.Expression;
|
|
79
166
|
|
|
167
|
+
/** O mínimo que o algoritmo precisa de um nó: posição e os baldes de comentário. */
|
|
168
|
+
interface Positioned {
|
|
169
|
+
type: string;
|
|
170
|
+
start: number;
|
|
171
|
+
end: number;
|
|
172
|
+
loc: {
|
|
173
|
+
start: {
|
|
174
|
+
line: number;
|
|
175
|
+
};
|
|
176
|
+
end: {
|
|
177
|
+
line: number;
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
leadingComments?: CommentToken[];
|
|
181
|
+
trailingComments?: CommentToken[];
|
|
182
|
+
innerComments?: CommentToken[];
|
|
183
|
+
[key: string]: unknown;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Ancora os `comments` (a lista lateral do `Program`, em ordem de fonte) aos nós
|
|
187
|
+
* de `root`. Mutação IN-PLACE: adiciona `leadingComments`/`trailingComments`/
|
|
188
|
+
* `innerComments` onde couber. A lista `Program.comments` é preservada (é o
|
|
189
|
+
* índice canônico ESTree); o attach só acrescenta referências nos nós.
|
|
190
|
+
*
|
|
191
|
+
* `source` é consultada só para o caso `remaining` (comentário encravado entre
|
|
192
|
+
* dois nós na mesma linha): o próximo caractere real decide de que lado ele está.
|
|
193
|
+
*/
|
|
194
|
+
declare function attachComments(root: Positioned, comments: readonly CommentToken[], source?: string): void;
|
|
195
|
+
|
|
80
196
|
/**
|
|
81
197
|
* Uma REFERÊNCIA a tipo nomeado, com posição — a tabela lateral que permite
|
|
82
198
|
* "ir para a definição" e hover sobre um nome de tipo.
|
|
@@ -91,4 +207,4 @@ type TypeRef = {
|
|
|
91
207
|
readonly loc: SourceLocation;
|
|
92
208
|
};
|
|
93
209
|
|
|
94
|
-
export { KEYWORDS, LexError, ParseError, type ParserErrorCode, type Position, type SourceLocation, type Token, type TokenType, type TypeRef, parse, parseExpression, tokenize };
|
|
210
|
+
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, parseTolerant, tokenize };
|
package/dist/index.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ interface SourceLocation {
|
|
|
12
12
|
readonly start: Position;
|
|
13
13
|
readonly end: Position;
|
|
14
14
|
}
|
|
15
|
-
type TokenType = "Identifier" | "Keyword" | "Number" | "String" | "Template" | "TemplateHead" | "TemplateMiddle" | "TemplateTail" | "Punctuator" | "JSXText" | "EOF";
|
|
15
|
+
type TokenType = "Identifier" | "Keyword" | "Number" | "String" | "Template" | "TemplateHead" | "TemplateMiddle" | "TemplateTail" | "Punctuator" | "JSXText" | "Unknown" | "EOF";
|
|
16
16
|
interface Token {
|
|
17
17
|
readonly type: TokenType;
|
|
18
18
|
/** O lexema cru, como aparece na fonte (sem decodificar escapes). */
|
|
@@ -22,6 +22,38 @@ interface Token {
|
|
|
22
22
|
readonly end: number;
|
|
23
23
|
readonly loc: SourceLocation;
|
|
24
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"`;
|
|
29
|
+
* `/* foo */` → `" foo "`. Carrega `start`/`end`/`loc` como os nós do parser.
|
|
30
|
+
*/
|
|
31
|
+
interface CommentToken {
|
|
32
|
+
readonly type: "Line" | "Block";
|
|
33
|
+
readonly value: string;
|
|
34
|
+
readonly start: number;
|
|
35
|
+
readonly end: number;
|
|
36
|
+
readonly loc: SourceLocation;
|
|
37
|
+
}
|
|
38
|
+
/** Coletor de comentários passado ao `tokenize` (canal lateral, opt-in). */
|
|
39
|
+
type OnComment = (comment: CommentToken) => void;
|
|
40
|
+
/**
|
|
41
|
+
* Um erro de léxico como DADO (o `onError` do scanner do tsc, que também não
|
|
42
|
+
* lança). Mesma forma que o `ParseDiagnostic` do parser, para viajarem juntos.
|
|
43
|
+
*/
|
|
44
|
+
interface LexDiagnostic {
|
|
45
|
+
readonly message: string;
|
|
46
|
+
readonly position: Position;
|
|
47
|
+
readonly index: number;
|
|
48
|
+
readonly loc: SourceLocation;
|
|
49
|
+
readonly end: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Coletor de erros de léxico (opt-in). PRESENTE → o tokenizer RECUPERA (emite um
|
|
53
|
+
* token `Unknown`, ou o token parcial, e segue), como o scanner do tsc. AUSENTE →
|
|
54
|
+
* o tokenizer LANÇA `LexError` no primeiro erro (o contrato estrito de sempre).
|
|
55
|
+
*/
|
|
56
|
+
type OnLexError = (diagnostic: LexDiagnostic) => void;
|
|
25
57
|
/** Erro de léxico, com a posição onde ocorreu. */
|
|
26
58
|
declare class LexError extends TSLiteError<"lex-error"> {
|
|
27
59
|
readonly position: Position;
|
|
@@ -44,8 +76,18 @@ declare class LexError extends TSLiteError<"lex-error"> {
|
|
|
44
76
|
}
|
|
45
77
|
/** Palavras reservadas. As permitidas e as proibidas — o parser decide. */
|
|
46
78
|
declare const KEYWORDS: Set<string>;
|
|
47
|
-
/**
|
|
48
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Tokeniza a fonte. Devolve a lista de tokens, terminada por um `EOF`.
|
|
81
|
+
*
|
|
82
|
+
* `onComment` (opcional) recebe cada comentário conforme é pulado — canal
|
|
83
|
+
* lateral, sem entrar no stream de tokens.
|
|
84
|
+
*
|
|
85
|
+
* `onError` (opcional) liga a RECUPERAÇÃO: com ele, um erro de léxico é
|
|
86
|
+
* REGISTRADO (não lançado) e o tokenizer segue — char inesperado vira token
|
|
87
|
+
* `Unknown`, string/template/número mal-formados viram o token parcial. Sem ele,
|
|
88
|
+
* o comportamento é o estrito de sempre: o primeiro erro **lança** `LexError`.
|
|
89
|
+
*/
|
|
90
|
+
declare function tokenize(source: string, onComment?: OnComment, onError?: OnLexError): Token[];
|
|
49
91
|
|
|
50
92
|
/** Erro de sintaxe, com a posição onde ocorreu. */
|
|
51
93
|
declare class ParseError extends TSLiteError<"parse-error"> {
|
|
@@ -69,7 +111,52 @@ declare class ParseError extends TSLiteError<"parse-error"> {
|
|
|
69
111
|
/** Offset absoluto do fim (exclusivo) do token culpado. */
|
|
70
112
|
end?: number | undefined);
|
|
71
113
|
}
|
|
72
|
-
/**
|
|
114
|
+
/**
|
|
115
|
+
* Um erro de sintaxe como **DADO** (não exceção) — o modelo do tsc, cujo parser
|
|
116
|
+
* não lança: ele empurra em `parseDiagnostics` e segue (`parser.ts:2149`). Carrega
|
|
117
|
+
* o mesmo que o `ParseError`, para que o parse estrito possa relançá-lo idêntico.
|
|
118
|
+
*/
|
|
119
|
+
interface ParseDiagnostic {
|
|
120
|
+
/** De qual fase veio — o `parse` estrito relança a classe certa, e o editor
|
|
121
|
+
* distingue as duas. */
|
|
122
|
+
readonly code: ParserErrorCode;
|
|
123
|
+
readonly message: string;
|
|
124
|
+
readonly position: Position;
|
|
125
|
+
readonly index: number;
|
|
126
|
+
readonly loc: SourceLocation;
|
|
127
|
+
readonly end: number;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* O nó é FALTANTE (sintético, criado na recuperação de erro)? Marcado pela própria
|
|
131
|
+
* posição — largura zero —, exatamente como o `nodeIsMissing` do tsc
|
|
132
|
+
* (`utilities.ts:1079`: `node.pos === node.end`). Um buraco no texto vira um nó
|
|
133
|
+
* bem-formado de largura zero, em vez de derrubar a árvore inteira.
|
|
134
|
+
*/
|
|
135
|
+
declare const nodeIsMissing: (node: unknown) => boolean;
|
|
136
|
+
/** O resultado do parse TOLERANTE: a árvore (talvez com buracos) + os erros. */
|
|
137
|
+
interface ParseResult {
|
|
138
|
+
/** A árvore. `undefined` só quando nem o léxico passou (erro de `tokenize`). */
|
|
139
|
+
readonly ast: types.Program | undefined;
|
|
140
|
+
/** Os erros de sintaxe como DADO, em ordem de ocorrência. */
|
|
141
|
+
readonly diagnostics: readonly ParseDiagnostic[];
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Parse **tolerante**: nunca lança por erro de sintaxe. Devolve a árvore — com
|
|
145
|
+
* nós FALTANTES (largura zero, ver {@link nodeIsMissing}) onde o texto tinha
|
|
146
|
+
* buracos — e os diagnósticos ao lado. É o que um EDITOR consome: completion e
|
|
147
|
+
* hover precisam de árvore justamente enquanto o código está incompleto.
|
|
148
|
+
*
|
|
149
|
+
* É o modo único do tsc (o parser dele nunca lança); aqui ele convive com o
|
|
150
|
+
* {@link parse} estrito, que é o contrato de quem VALIDA.
|
|
151
|
+
*/
|
|
152
|
+
declare function parseTolerant(source: string): ParseResult;
|
|
153
|
+
/**
|
|
154
|
+
* Faz o parse de uma fonte completa num `Program` (ESTree, com `loc`).
|
|
155
|
+
*
|
|
156
|
+
* Contrato **estrito** (o de sempre): o primeiro erro de sintaxe **lança**. Quem
|
|
157
|
+
* valida quer tudo-ou-nada — rodar o checker sobre uma árvore com buracos só
|
|
158
|
+
* produziria cascata. Quem precisa da árvore parcial usa o {@link parseTolerant}.
|
|
159
|
+
*/
|
|
73
160
|
declare function parse(source: string): types.Program;
|
|
74
161
|
/**
|
|
75
162
|
* Conveniência: faz o parse de uma **única expressão** (ex.: célula de regra).
|
|
@@ -77,6 +164,35 @@ declare function parse(source: string): types.Program;
|
|
|
77
164
|
*/
|
|
78
165
|
declare function parseExpression(source: string): types.Expression;
|
|
79
166
|
|
|
167
|
+
/** O mínimo que o algoritmo precisa de um nó: posição e os baldes de comentário. */
|
|
168
|
+
interface Positioned {
|
|
169
|
+
type: string;
|
|
170
|
+
start: number;
|
|
171
|
+
end: number;
|
|
172
|
+
loc: {
|
|
173
|
+
start: {
|
|
174
|
+
line: number;
|
|
175
|
+
};
|
|
176
|
+
end: {
|
|
177
|
+
line: number;
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
leadingComments?: CommentToken[];
|
|
181
|
+
trailingComments?: CommentToken[];
|
|
182
|
+
innerComments?: CommentToken[];
|
|
183
|
+
[key: string]: unknown;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Ancora os `comments` (a lista lateral do `Program`, em ordem de fonte) aos nós
|
|
187
|
+
* de `root`. Mutação IN-PLACE: adiciona `leadingComments`/`trailingComments`/
|
|
188
|
+
* `innerComments` onde couber. A lista `Program.comments` é preservada (é o
|
|
189
|
+
* índice canônico ESTree); o attach só acrescenta referências nos nós.
|
|
190
|
+
*
|
|
191
|
+
* `source` é consultada só para o caso `remaining` (comentário encravado entre
|
|
192
|
+
* dois nós na mesma linha): o próximo caractere real decide de que lado ele está.
|
|
193
|
+
*/
|
|
194
|
+
declare function attachComments(root: Positioned, comments: readonly CommentToken[], source?: string): void;
|
|
195
|
+
|
|
80
196
|
/**
|
|
81
197
|
* Uma REFERÊNCIA a tipo nomeado, com posição — a tabela lateral que permite
|
|
82
198
|
* "ir para a definição" e hover sobre um nome de tipo.
|
|
@@ -91,4 +207,4 @@ type TypeRef = {
|
|
|
91
207
|
readonly loc: SourceLocation;
|
|
92
208
|
};
|
|
93
209
|
|
|
94
|
-
export { KEYWORDS, LexError, ParseError, type ParserErrorCode, type Position, type SourceLocation, type Token, type TokenType, type TypeRef, parse, parseExpression, tokenize };
|
|
210
|
+
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, parseTolerant, tokenize };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {TSLiteError}from'@tslite/core';var
|
|
2
|
-
`&&
|
|
3
|
-
`||
|
|
4
|
-
`||v==="\r"||v==="\u2028"||v==="\u2029",x=()=>{for(;;){let v=f();if(v===" "||v===" "||v==="\f"||v==="\v"||s(v))y();else if(v==="/"&&f(1)==="/")for(;l<c.length&&!s(f());)y();else if(v==="/"&&f(1)==="*")for(y(),y();;){if(l>=c.length&&L("Unterminated block comment"),f()==="*"&&f(1)==="/"){y(),y();break}y();}else break}},I=(v,C,R,N)=>{S.push({type:v,value:C,start:R,end:l,loc:{start:N,end:r()}}),$=v==="Punctuator"?Ve.has(C):v==="Keyword"?We.has(C):v==="TemplateHead"||v==="TemplateMiddle";},E=v=>{for(y();l<c.length;){let C=f();if(C===v)return y(),c.slice(a,l);if(s(C)&&L("Unterminated string literal"),C==="\\"){y(),l>=c.length&&L("Unterminated string literal"),y();continue}y();}return L("Unterminated string literal")},m=()=>{if(f()==="0"&&(f(1)==="x"||f(1)==="X")){for(y(),y(),de(f())||L("Invalid hexadecimal literal");de(f());)y();return}if(f()==="0"&&(f(1)==="b"||f(1)==="B")){for(y(),y(),f()!=="0"&&f()!=="1"&&L("Invalid binary literal");f()==="0"||f()==="1";)y();return}if(f()==="0"&&(f(1)==="o"||f(1)==="O")){for(y(),y(),f()>="0"&&f()<="7"||L("Invalid octal literal");f()>="0"&&f()<="7";)y();return}for(;B(f());)y();if(f()===".")for(y();B(f());)y();if(f()==="e"||f()==="E")for(y(),(f()==="+"||f()==="-")&&y(),B(f())||L("Invalid exponent");B(f());)y();},T=()=>{let v=l;for(;l<c.length;){let C=f();if(C==="`"){let R=c.slice(v,l);return y(),{raw:R,interp:false}}if(C==="$"&&f(1)==="{"){let R=c.slice(v,l);return y(),y(),{raw:R,interp:true}}if(C==="\\"){if(y(),l>=c.length)break;y();continue}y();}return L("Unterminated template literal")},a=0,J=0,k=[],$=true,X="js",K=[],F=[];for(;;){if(X==="jsxChildren"){a=l;let N=r();if(l>=c.length){I("EOF","",a,N);break}let i=f();if(i==="<"){f(1)==="/"?(y(),y(),I("Punctuator","</",a,N),X="jsxCloseTag"):(y(),I("Punctuator","<",a,N),K.push("jsxChildren"),X="jsxOpenTag");continue}if(i==="{"){y(),I("Punctuator","{",a,N),F.push({level:J,restore:"jsxChildren"}),X="js";continue}for(;l<c.length&&f()!=="<"&&f()!=="{";)y();I("JSXText",c.slice(a,l),a,N);continue}if(X==="jsxOpenTag"||X==="jsxCloseTag"){x(),a=l;let N=r();if(l>=c.length){I("EOF","",a,N);break}let i=f();if(se(i)){for(y();qe(f());)y();I("Identifier",c.slice(a,l),a,N);continue}if(i==="/"&&f(1)===">"){y(),y(),I("Punctuator","/>",a,N),X=K.pop()??"js";continue}if(i===">"){y(),I("Punctuator",">",a,N),X=X==="jsxCloseTag"?K.pop()??"js":"jsxChildren";continue}if(i==="{"){y(),I("Punctuator","{",a,N),F.push({level:J,restore:X}),X="js";continue}if(i==='"'||i==="'"){I("String",E(i),a,N);continue}if(i==="="||i==="."||i===":"){y(),I("Punctuator",i,a,N);continue}L(`Unexpected character '${i}' in JSX tag`);}x(),a=l;let v=r();if(l>=c.length){I("EOF","",a,v);break}let C=f();if(se(C)){for(;me(f());)y();let N=c.slice(a,l);I(ye.has(N)?"Keyword":"Identifier",N,a,v);continue}if(B(C)||C==="."&&B(f(1))){m(),I("Number",c.slice(a,l),a,v);continue}if(C==='"'||C==="'"){let N=E(C);I("String",N,a,v);continue}if(C==="`"){y();let{raw:N,interp:i}=T();i?(I("TemplateHead",N,a,v),k.push(J)):I("Template",N,a,v);continue}if(C==="<"&&$){y(),I("Punctuator","<",a,v),K.push("js"),X="jsxOpenTag";continue}if(C==="{"){y(),I("Punctuator","{",a,v),J++;continue}if(C==="}"){if(k.length>0&&J===k[k.length-1]){k.pop(),y();let{raw:N,interp:i}=T();I(i?"TemplateMiddle":"TemplateTail",N,a,v),i&&k.push(J);continue}if(F.length>0&&J===F[F.length-1].level){let{restore:N}=F.pop();y(),I("Punctuator","}",a,v),X=N;continue}y(),I("Punctuator","}",a,v),J--;continue}if(C==="?"&&f(1)==="."&&B(f(2))){y(),I("Punctuator","?",a,v);continue}let R=ze.find(N=>c.startsWith(N,l));if(R){for(let N=0;N<R.length;N++)y();I("Punctuator",R,a,v);continue}L(`Unexpected character '${C}'`);}return S}var ie=(c=[])=>({vars:new Set(c),bounds:new Map,noCond:false,inferSink:null}),H=(c,S)=>{let l=new Set(c.vars),h=new Map(c.bounds);for(let d of S)l.add(d.name),d.bound||d.isConst?h.set(d.name,{bound:d.bound,isConst:d.isConst}):h.delete(d.name);return {vars:l,bounds:h,noCond:c.noCond,inferSink:c.inferSink}},He=(c,S)=>{let l=c.bounds.get(S);return l&&(l.bound||l.isConst)?{t:"var",name:S,...l.bound?{bound:l.bound}:{},...l.isConst?{isConst:true}:{}}:{t:"var",name:S}},he=c=>{let{peek:S,next:l,isP:h,isK:d,expectP:r,fail:f,unescape:L}=c,y=()=>{let i=c.pos(),p=c.tokens[i],u=c.tokens[i-1];return !!u&&!!p&&p.loc.start.line>u.loc.end.line},s=()=>{let i=0;for(let p=c.pos();p<c.tokens.length;p++){let u=c.tokens[p];if(u.type==="EOF")return false;if(u.type==="Punctuator"){if(["(","[","{","<"].includes(u.value))i++;else if([")","]","}",">"].includes(u.value)&&(i--,i===0)){let b=c.tokens[p+1];return !!b&&b.type==="Punctuator"&&b.value==="=>"}}}return false},x=()=>{let i=c.tokens,p=[],u=0,b=false;for(let w=c.pos();w<i.length;w++){let j=i[w];if(j.type==="EOF")break;if(j.type==="Punctuator"){if(j.value==="<")u++,u===1&&(b=true);else if(j.value===">"){if(u--,u===0)break}else j.value==="("||j.value==="["||j.value==="{"?(u++,b=false):j.value===")"||j.value==="]"||j.value==="}"?(u--,b=false):j.value===","&&u===1?b=true:b=false;continue}if(u===1&&b){if(j.type==="Keyword"&&j.value==="const")continue;if(j.type==="Identifier"){p.push(j.value),b=false;continue}}b=false;}return p},I=i=>{let p=H(i,x().map(b=>({name:b})));r("<");let u=[];for(;!h(">");){let b=d("const");b&&l();let w=S();w.type!=="Identifier"&&f("Expected type parameter name"),l();let j;d("extends")&&(l(),j=T(p)),h("=")&&(l(),T(p)),u.push({name:w.value,...j?{bound:j}:{},...b?{isConst:true}:{}}),h(">")||r(",");}return r(">"),u},E=i=>{r("<");let p=[];for(;!h(">");)p.push(T(i)),h(">")||r(",");return r(">"),p},m=i=>{let p=S();return p.type==="Identifier"&&p.value===i},T=i=>{let p=a(i);if(i.noCond||!d("extends")||y())return p;l();let u=[],b=a({...i,noCond:true,inferSink:u});r("?");let w=H(i,u.map(z=>({name:z}))),j=T(w);r(":");let _=T(w);return {t:"conditional",check:p,extends:b,then:j,else:_,...u.length?{infer:u}:{}}},a=i=>{h("|")&&l();let p=J(i);if(!h("|"))return p;let u=[p];for(;h("|");)l(),u.push(J(i));return {t:"union",of:u}},J=i=>{h("&")&&l();let p=k(i);if(!h("&"))return p;let u=[p];for(;h("&");)l(),u.push(k(i));return {t:"intersection",of:u}},k=i=>{if(m("keyof"))return l(),{t:"keyof",of:k(i)};if(m("readonly")){l();let p=k(i);return p.t!=="array"&&p.t!=="tuple"&&f("'readonly' only applies to array and tuple types"),{...p,readonly:true}}if(m("infer")){l();let p=S();p.type!=="Identifier"&&f("Expected 'infer' variable name"),l();let u=i.inferSink;return u?(u.push(p.value),{t:"var",name:p.value}):f("'infer' is only allowed in the 'extends' clause of a conditional")}return $(i)},$=i=>{let p=X(i);for(;h("[")&&!y();)if(l(),h("]"))l(),p={t:"array",items:p};else {let u=T(i);r("]"),p={t:"index",obj:p,key:u};}return p},X=i=>{if(d("typeof")){l();let u=S();u.type!=="Identifier"&&f("Expected a name after 'typeof' in type position"),l();let b=[u.value];for(;h(".");){l();let w=S();w.type!=="Identifier"&&w.type!=="Keyword"&&f("Expected a property name after '.' in 'typeof'"),l(),b.push(w.value);}return {t:"typeQuery",path:b}}if(h("<")){let u=I(i),b=H(i,u);return F(b,u.map(w=>w.name))}if(h("(")){if(s())return F(i);l();let u=T(i.noCond?{...i,noCond:false}:i);return r(")"),u}if(h("{"))return C()?R(i):N(i);if(h("["))return v(i);let p=S();if(p.type==="String")return l(),{t:"literal",value:L(p.value.slice(1,-1))};if(p.type==="Number")return l(),{t:"literal",value:Number(p.value)};if(d("true"))return l(),{t:"literal",value:true};if(d("false"))return l(),{t:"literal",value:false};if(d("null"))return l(),{t:"null"};if(d("void"))return l(),{t:"void"};if(p.type==="Identifier"){switch(l(),p.value){case "string":return {t:"string"};case "number":return {t:"number"};case "boolean":return {t:"boolean"};case "any":return {t:"any"};case "unknown":return {t:"unknown"};case "undefined":return {t:"undefined"};case "never":return {t:"union",of:[]}}let u=h("<")?E(i):[];return i.vars.has(p.value)&&u.length===0?He(i,p.value):p.value==="ReturnType"&&u.length===1?{t:"returnType",fn:u[0]}:p.value==="Parameters"&&u.length===1?{t:"parameters",fn:u[0]}:(c.typeRefs?.push({name:p.value,loc:p.loc}),{t:"apply",name:p.value,args:u})}return f(`Expected a type but got '${p.value||p.type}'`)},K=i=>{r("(");let p=[];for(;!h(")");){let u=S();u.type!=="Identifier"&&f("Expected parameter name in function type"),l();let b=h("?");b&&l(),r(":");let w=T(i);p.push({name:u.value,type:w,...b?{optional:true}:{}}),h(")")||r(",");}return r(")"),p},F=(i,p)=>{let u=K(i);r("=>");let b=T(i);return {t:"fn",params:u,returns:b,...p?.length?{typeParams:p}:{}}},v=i=>{r("[");let p=[],u=[];for(;!h("]");){if(h("...")){l();let b=T(i);b.t==="array"?(p.push(b.items),u.push("rest")):(p.push(b),u.push("variadic"));}else {let b=T(i),w=h("?");w&&l(),p.push(b),u.push(w?"optional":"req");}h("]")||r(",");}return r("]"),u.some(b=>b!=="req")?{t:"tuple",elements:p,flags:u}:{t:"tuple",elements:p}},C=()=>{let i=c.tokens,p=c.pos()+1;return i[p]?.type==="Punctuator"&&(i[p]?.value==="+"||i[p]?.value==="-")&&p++,i[p]?.type==="Identifier"&&i[p]?.value==="readonly"&&p++,i[p]?.type==="Punctuator"&&i[p]?.value==="["&&i[p+1]?.type==="Identifier"&&i[p+2]?.type==="Keyword"&&i[p+2]?.value==="in"},R=i=>{r("{"),(h("+")||h("-"))&&l(),m("readonly")&&l(),r("[");let p=S();p.type!=="Identifier"&&f("Expected mapped type key name"),l(),d("in")||f("Expected 'in' in mapped type"),l();let u=T(i);m("as")&&f("Key remapping ('as') in mapped types is not supported"),r("]");let b=false,w=h("+")||h("-")?l().value:null;h("?")&&(l(),b=w!=="-"),r(":");let j=T(H(i,[{name:p.value}]));return (h(";")||h(","))&&l(),r("}"),{t:"mapped",key:p.value,over:u,body:j,optional:b}},N=i=>{r("{");let p={},u,b=[];for(;!h("}");){if(h("(")){let w=K(i);r(":");let j=T(i);b.push({t:"fn",params:w,returns:j});}else if(h("[")){l(),S().type!=="Identifier"&&f("Expected index signature parameter name"),l(),r(":");let w=S();(w.type!=="Identifier"||w.value!=="string"&&w.value!=="number")&&f("Index signature parameter type must be 'string' or 'number'"),l(),r("]"),r(":"),u={key:w.value,value:T(i)};}else {let w=S(),j;if(w.type==="Identifier"||w.type==="Keyword")l(),j=w.value;else if(w.type==="String")l(),j=L(w.value.slice(1,-1));else if(w.type==="Number")l(),j=w.value;else return f("Expected property name in object type");let _=h("?");_&&l(),r(":");let z=T(i);p[j]={type:z,..._?{optional:true}:{}};}if(h(";")||h(","))l();else break}return r("}"),b.length>0?Object.keys(p).length>0||u?f("Callable object types (call signatures mixed with members) are not supported"):b.length===1?b[0]:{t:"overload",signatures:b}:{t:"object",props:p,...u?{index:u}:{}}};return {parseType:i=>T(ie(i)),parseTypeParamList:()=>I(ie()),parseTypeInScope:i=>T(H(ie(),i))}};var ee=class extends TSLiteError{constructor(l,h,d,r,f){super("parse-error",`${l} (${h.line}:${h.column})`,{position:h,index:d,loc:r,end:f});this.position=h;this.index=d;this.loc=r;this.end=f;this.name="ParseError";}},Ye={"??":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},Qe=new Set(["??","||","&&"]),Ze=new Set(["class","debugger","with","enum","interface"]),et={enum:'use a union of literals (`type T = "a" | "b"`) \u2014 it is serializable',interface:"use a type alias (`type X = { \u2026 }`)",namespace:"use modules (`import`/`export`)",module:"use modules (`import`/`export`)",declare:"declare the shape via the DI env, or with a `type` alias",abstract:"classes are not part of the language \u2014 model with objects + functions"},tt={namespace:(c,S)=>c.type==="Identifier"&&S.type==="Punctuator"&&S.value==="{",module:(c,S)=>c.type==="Identifier"&&S.type==="Punctuator"&&S.value==="{",declare:c=>c.type==="Keyword"&&["const","let","var","function","class","enum","interface"].includes(c.value)||c.type==="Identifier"&&["type","namespace","module"].includes(c.value),abstract:c=>c.type==="Keyword"&&c.value==="class"},nt=new Set(["=","+=","-=","*=","/=","%="]);function ge(c){let S=ae(c),l=0,h=[],d=(e=0)=>S[Math.min(l+e,S.length-1)],r=()=>S[l++],f=()=>S[l-1],L=()=>{let e=S[l],t=S[l-1];return !!e&&!!t&&e.loc.start.line>t.loc.end.line},y=()=>d().type==="EOF",s=e=>d().type==="Punctuator"&&d().value===e,x=e=>d().type==="Keyword"&&d().value===e,I=e=>d().type==="Identifier"&&d().value===e,E=(e,t=d())=>{throw new ee(e,t.loc.start,t.start,t.loc,t.end)},m=e=>(s(e)||E(`Expected '${e}' but got '${d().value||d().type}'`),r()),T=(e,t)=>{let n=f()??t;return Object.assign(e,{start:t.start,end:n.end,loc:{start:t.loc.start,end:n.loc.end}})},a=(e,t,n)=>Object.assign(e,{start:t.start,end:n.end,loc:{start:t.loc.start,end:n.loc.end}}),J=e=>{let t="";for(let n=0;n<e.length;n++){if(e[n]!=="\\"){t+=e[n];continue}let o=e[++n];switch(o){case "n":t+=`
|
|
5
|
-
`;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 g=e.indexOf("}",n);t+=String.fromCodePoint(parseInt(e.slice(n+2,g),16)),n=g;}else t+=String.fromCharCode(parseInt(e.slice(n+1,n+5),16)),n+=4;break;default:t+=o;}}return t},k=(e=false)=>$(e),$=(e=false)=>{let t=X(e),n=d();if(n.type==="Punctuator"&&nt.has(n.value)){r();let o=$();return a({type:"AssignmentExpression",operator:n.value,left:t,right:o},t,o)}return t},X=(e=false)=>{let t=F(0,e);if(!s("?"))return t;r();let n=k();m(":");let o=k();return a({type:"ConditionalExpression",test:t,consequent:n,alternate:o},t,o)},K=()=>{let e=d();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=d(1);if(t.type==="Punctuator"&&t.value===">"&&e.end===t.start){let n=d(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=v();for(;;){let o=K();if(!o)break;let{op:g,consume:P}=o;if(g==="in"&&t)break;let A=Ye[g];if(!A||A<=e)break;if(g==="satisfies"){if(L())break;E("'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(g==="as"){if(L())break;r();let D=V(new Set);n=a({type:"TSAsExpression",expression:n,typeAnnotation:D},n,f());continue}for(let D=0;D<P;D++)r();let O=F(g==="**"?A-1:A,t);n=a({type:Qe.has(g)?"LogicalExpression":"BinaryExpression",operator:g,left:n,right:O},n,O);}return n},v=()=>{let e=d();return e.type==="Punctuator"&&(e.value==="++"||e.value==="--")?(r(),T({type:"UpdateExpression",operator:e.value,prefix:true,argument:v()},e)):x("await")?(r(),T({type:"AwaitExpression",argument:v()},e)):x("typeof")||x("void")||x("delete")||e.type==="Punctuator"&&(e.value==="!"||e.value==="-"||e.value==="+"||e.value==="~")?C(e):N()},C=e=>{r();let t=v();return s("**")&&E(`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.`),T({type:"UnaryExpression",operator:e.value,prefix:true,argument:t},e)},R=()=>{let e=l,t=()=>(l=e,void 0);try{if(r(),s(">"))return t();let n=[];for(;n.push(V(new Set)),!!s(",");)r();return s(">")?(r(),s("(")?n:t()):t()}catch{return t()}},N=()=>{let e=we(),t=false;for(;;)if(s("?."))if(r(),t=true,s("(")){let{args:n,close:o}=i();e=a({type:"CallExpression",callee:e,arguments:n,optional:true},e,o);}else if(s("[")){r();let n=k(),o=m("]");e=a({type:"MemberExpression",object:e,property:n,computed:true,optional:true},e,o);}else {let n=d();n.type!=="Identifier"&&n.type!=="Keyword"&&E("Expected property name after '?.'"),r();let o=T({type:"Identifier",name:n.value},n);e=a({type:"MemberExpression",object:e,property:o,computed:false,optional:true},e,o);}else if(s(".")){r();let n=d();n.type!=="Identifier"&&n.type!=="Keyword"&&E("Expected property name"),r();let o=T({type:"Identifier",name:n.value},n);e=a({type:"MemberExpression",object:e,property:o,computed:false,optional:false},e,o);}else if(s("[")){r();let n=k(),o=m("]");e=a({type:"MemberExpression",object:e,property:n,computed:true,optional:false},e,o);}else if(s("(")){let{args:n,close:o}=i();e=a({type:"CallExpression",callee:e,arguments:n,optional:false},e,o);}else if(s("<")){let n=R();if(!n)break;let{args:o,close:g}=i();e=a({type:"CallExpression",callee:e,arguments:o,optional:false,typeArguments:n},e,g);}else if(s("++")||s("--")){let n=r();e=a({type:"UpdateExpression",operator:n.value,prefix:false,argument:e},e,n);}else break;return t?a({type:"ChainExpression",expression:e},e,e):e},i=()=>{m("(");let e=[];for(;!s(")");)e.push(p()),s(")")||m(",");return {args:e,close:m(")")}},p=()=>{if(s("...")){let e=r(),t=k();return a({type:"SpreadElement",argument:t},e,t)}return k()},u=()=>{let e=d();return e.type!=="Identifier"&&E("Expected identifier"),r(),T({type:"Identifier",name:e.value},e)},b=e=>{let t=s("{")?w(e):s("[")?j(e):u();return s(":")&&(r(),t.typeAnnotation=V(e)),t},w=e=>{let t=m("{"),n=[];for(;!s("}");){if(s("...")){let g=r(),P=b(e);n.push(a({type:"RestElement",argument:P},g,P));}else {let g=u(),P,A=false;if(s(":")?(r(),P=b(e)):(P={...g},A=true),s("=")){r();let O=k();P=a({type:"AssignmentPattern",left:P,right:O},P,O);}n.push(a({type:"Property",key:g,value:P,kind:"init",shorthand:A,computed:false,method:false},g,P));}s("}")||m(",");}let o=m("}");return a({type:"ObjectPattern",properties:n},t,o)},j=e=>{let t=m("["),n=[];for(;!s("]");){if(s(",")){n.push(null),r();continue}if(s("...")){let g=r(),P=b(e);n.push(a({type:"RestElement",argument:P},g,P));}else {let g=b(e);if(s("=")){r();let P=k();g=a({type:"AssignmentPattern",left:g,right:P},g,P);}n.push(g);}s("]")||m(",");}let o=m("]");return a({type:"ArrayPattern",elements:n},t,o)},_=()=>{let e=0;for(let t=l;t<S.length;t++){let n=S[t];if(n.type==="EOF")return false;if(n.type==="Punctuator"){if(n.value==="("||n.value==="["||n.value==="{")e++;else if((n.value===")"||n.value==="]"||n.value==="}")&&(e--,e===0)){let o=S[t+1];return !o||o.type!=="Punctuator"?false:o.value==="=>"?true:o.value===":"?z(t+2):false}}}return false},z=e=>{let t=0;for(let n=e;n<S.length;n++){let o=S[n];if(o.type==="EOF")return false;if(o.type==="Punctuator")if(["(","[","{","<"].includes(o.value))t++;else if([")","]","}",">"].includes(o.value)){if(t===0)return false;t--;}else {if(t===0&&o.value==="=>")return true;if(t===0&&(o.value===";"||o.value===","))return false}}return false},ve=(e=new Set)=>{m("(");let t=[];for(;!s(")");){if(s("...")){let n=r(),o=b(e);t.push(a({type:"RestElement",argument:o},n,o));}else {let n=b(e);if(s("=")){r();let o=k();n=a({type:"AssignmentPattern",left:n,right:o},n,o);}t.push(n);}s(")")||m(",");}return m(")"),t},te=(e,t)=>{let n=s("(")?ve():[u()],o;s(":")&&(r(),o=V(new Set)),m("=>");let g=s("{")?W():k();return T({type:"ArrowFunctionExpression",params:n,body:g,async:e,expression:g.type!=="BlockStatement",generator:false,...o?{returnType:o}:{}},t)},be=()=>{let e=m("["),t=[];for(;!s("]");){if(s(",")){r(),t.push(null);continue}t.push(p()),s("]")||m(",");}return a({type:"ArrayExpression",elements:t},e,m("]"))},Te=()=>{let e=m("{"),t=[];for(;!s("}");){if(s("...")){let n=r(),o=k();t.push(a({type:"SpreadElement",argument:o},n,o));}else {let n=d(),o,g=false;if(s("["))g=true,r(),o=k(),m("]");else if(n.type==="String")r(),o=T({type:"Literal",value:J(n.value.slice(1,-1)),raw:n.value},n);else if(n.type==="Number")r(),o=T({type:"Literal",value:Number(n.value),raw:n.value},n);else if(n.type==="Identifier"||n.type==="Keyword")r(),o=T({type:"Identifier",name:n.value},n);else return E("Invalid property key");if(s(":")){r();let P=k();t.push(a({type:"Property",key:o,value:P,kind:"init",method:false,shorthand:false,computed:g},n,P));}else t.push(a({type:"Property",key:o,value:o,kind:"init",method:false,shorthand:true,computed:false},n,o));}s("}")||m(",");}return a({type:"ObjectExpression",properties:t},e,m("}"))},G=(e,t)=>({type:"TemplateElement",value:{raw:e,cooked:J(e)},tail:t}),xe=e=>{r();let t=[G(e.value,false)],n=[];for(;;){n.push(k());let o=d();if(o.type==="TemplateMiddle")r(),t.push(G(o.value,false));else if(o.type==="TemplateTail"){r(),t.push(G(o.value,true));break}else E("Expected `}` to close template interpolation");}return T({type:"TemplateLiteral",quasis:t,expressions:n},e)},q=()=>{let e=d();return e.type!=="Identifier"&&E(`Expected JSX identifier but got '${e.value||e.type}'`),T({type:"JSXIdentifier",name:r().value},e)},le=()=>{let e=q();if(s(":")){r();let t=q();return a({type:"JSXNamespacedName",namespace:e,name:t},e,t)}for(;s(".");){r();let t=q();e=a({type:"JSXMemberExpression",object:e,property:t},e,t);}return e},M=e=>e.type==="JSXIdentifier"?e.name:e.type==="JSXNamespacedName"?`${M(e.namespace)}:${M(e.name)}`:`${M(e.object)}.${M(e.property)}`,Se=()=>{let e=d();if(e.type==="String")return r(),T({type:"Literal",value:J(e.value.slice(1,-1)),raw:e.value},e);if(s("{")){let t=r(),n=$(),o=m("}");return a({type:"JSXExpressionContainer",expression:n},t,o)}return s("<")?ne():E(`Invalid JSX attribute value '${e.value||e.type}'`)},ke=()=>{let e=[];for(;!s(">")&&!s("/>")&&!y();){if(s("{")){let o=r();m("...");let g=$(),P=m("}");e.push(a({type:"JSXSpreadAttribute",argument:g},o,P));continue}let t=q();if(s(":")){r();let o=q();t=a({type:"JSXNamespacedName",namespace:t,name:o},t,o);}let n=null;s("=")&&(r(),n=Se()),e.push(a({type:"JSXAttribute",name:t,value:n},t,n??t));}return e},pe=()=>{let e=[];for(;!(s("</")||y());){let t=d();if(t.type==="JSXText")r(),e.push(T({type:"JSXText",value:t.value,raw:t.value},t));else if(s("{")){let n=r();if(s("}")){let o=r(),g=T({type:"JSXEmptyExpression"},n);e.push(a({type:"JSXExpressionContainer",expression:g},n,o));}else {let o=$(),g=m("}");e.push(a({type:"JSXExpressionContainer",expression:o},n,g));}}else s("<")?e.push(ne()):E(`Unexpected token in JSX children '${t.value||t.type}'`);}return e},ne=()=>{let e=m("<");if(s(">")){let Q=r(),oe=a({type:"JSXOpeningFragment"},e,Q),Ue=pe(),Me=m("</"),fe=m(">"),Be=a({type:"JSXClosingFragment"},Me,fe);return a({type:"JSXFragment",openingFragment:oe,children:Ue,closingFragment:Be},e,fe)}let t=le(),n=ke();if(s("/>")){let Q=r(),oe=a({type:"JSXOpeningElement",name:t,attributes:n,selfClosing:true},e,Q);return a({type:"JSXElement",openingElement:oe,children:[],closingElement:null},e,Q)}let o=m(">"),g=a({type:"JSXOpeningElement",name:t,attributes:n,selfClosing:false},e,o),P=pe(),A=m("</"),O=d(),D=le();M(D)!==M(t)&&E(`JSX closing tag </${M(D)}> does not match opening <${M(t)}>`,O);let Y=m(">"),Ke=a({type:"JSXClosingElement",name:D},A,Y);return a({type:"JSXElement",openingElement:g,children:P,closingElement:Ke},e,Y)},we=()=>{let e=d();if(x("async")){let t=d(1);return t.value==="("||t.type==="Identifier"?(r(),te(true,e)):E("Unexpected 'async'")}if(s("(")&&_()||e.type==="Identifier"&&d(1).type==="Punctuator"&&d(1).value==="=>")return te(false,e);if(e.type==="Number")return r(),T({type:"Literal",value:Number(e.value),raw:e.value},e);if(e.type==="String")return r(),T({type:"Literal",value:J(e.value.slice(1,-1)),raw:e.value},e);if(e.type==="Template")return r(),T({type:"TemplateLiteral",expressions:[],quasis:[G(e.value,true)]},e);if(e.type==="TemplateHead")return xe(e);if(e.type==="Keyword")return e.value==="true"?(r(),T({type:"Literal",value:true,raw:"true"},e)):e.value==="false"?(r(),T({type:"Literal",value:false,raw:"false"},e)):e.value==="null"?(r(),T({type:"Literal",value:null,raw:"null"},e)):e.value==="new"?E("'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"?E("Anonymous functions are not supported \u2014 use an arrow function"):E(`'${e.value}' is not supported in this language`);if(e.type==="Identifier")return r(),T({type:"Identifier",name:e.value},e);if(s("(")){r();let t=k();return m(")"),t}return s("[")?be():s("{")?Te():s("<")?ne():E(`Unexpected token '${e.value||e.type}'`)},{parseType:V,parseTypeParamList:Ne,parseTypeInScope:Pe}=he({tokens:S,pos:()=>l,peek:d,next:r,isP:s,isK:x,expectP:m,fail:E,unescape:J,typeRefs:h}),Ee=()=>{let e=r(),t=u(),n=[],o=[];s("<")&&(o=Ne(),n=o.map(A=>A.name)),m("=");let g=Pe(o),P=a({type:"TSTypeAliasDeclaration",id:t,typeParameters:n,typeAnnotation:g},e,f());return s(";")&&r(),P},U=()=>{let e=d();if(e.type==="Identifier"&&e.value==="type"&&d(1).type==="Identifier"&&d(2).type==="Punctuator"&&(d(2).value==="="||d(2).value==="<"))return Ee();if(x("const")||x("let")||x("var")){let g=ce();return s(";")&&r(),g}if(x("if"))return Le();if(x("for"))return Ae();if(x("while"))return Je();if(x("do"))return Oe();if(x("break")||x("continue"))return De();if(x("return"))return Xe();if(x("throw"))return Re();if(x("try"))return Fe();if(x("switch"))return $e();if(x("import"))return Ce();if(x("export"))return je();if(s("{"))return W();if((x("function")||x("async")&&d(1).type==="Keyword"&&d(1).value==="function")&&E("Function declarations are not supported \u2014 use 'const fn = () => \u2026'"),s(";"))return r(),T({type:"EmptyStatement"},e);if(e.type==="Keyword"&&Ze.has(e.value)||e.type==="Identifier"&&tt[e.value]?.(d(1),d(2))===true){let g=et[e.value];E(`'${e.value}' is not supported in this language`+(g?` \u2014 ${g}`:""));}let n=k(),o=s(";")?r():f();return a({type:"ExpressionStatement",expression:n},n,o)},ce=()=>{let e=r(),t=e.value,n=b(new Set),o=null;s("=")?(r(),o=k()):t==="const"&&E("'const' declarations must be initialized");let g=a({type:"VariableDeclarator",id:n,init:o},n,o??n);return a({type:"VariableDeclaration",kind:t,declarations:[g]},e,o??n)},Ie=()=>{let e=d();return e.type!=="String"&&E("Expected module specifier string"),r(),T({type:"Literal",value:J(e.value.slice(1,-1)),raw:e.value},e)},Ce=()=>{let e=r(),t=[];if(d().type!=="String"){if(d().type==="Identifier"){let o=u();t.push(a({type:"ImportDefaultSpecifier",local:o},o,o)),s(",")&&r();}if(s("*")){let o=r();I("as")||E("Expected 'as' after '*' in import"),r();let g=u();t.push(a({type:"ImportNamespaceSpecifier",local:g},o,g));}else if(s("{")){for(r();!s("}")&&!y();){let o=u(),g=o;if(I("as")&&(r(),g=u()),t.push(a({type:"ImportSpecifier",imported:o,local:g},o,g)),s(","))r();else break}m("}");}I("from")||E("Expected 'from' in import declaration"),r();}let n=Ie();return s(";")&&r(),T({type:"ImportDeclaration",specifiers:t,source:n},e)},je=()=>{let e=r();if(x("default")){r();let t=k();return s(";")&&r(),T({type:"ExportDefaultDeclaration",declaration:t},e)}if(x("const")||x("let")||x("var")){let t=ce();return s(";")&&r(),T({type:"ExportNamedDeclaration",declaration:t,specifiers:[],source:null},e)}if(s("{")){r();let t=[];for(;!s("}")&&!y();){let n=u(),o=n;if(I("as")&&(r(),o=u()),t.push(a({type:"ExportSpecifier",local:n,exported:o},n,o)),s(","))r();else break}return m("}"),s(";")&&r(),T({type:"ExportNamedDeclaration",declaration:null,specifiers:t,source:null},e)}return E("Expected 'const', '{', or 'default' after 'export'")},ue=()=>d().type==="Identifier"&&d().value==="of",re=()=>x("in"),Ae=()=>{let e=r();m("(");let t=null,n=null;if(!s(";"))if(x("const")||x("let")||x("var")){let A=r(),O=u();if(s(":")&&(r(),O.typeAnnotation=V(new Set)),ue()||re()){let D=a({type:"VariableDeclarator",id:O,init:null},O,O);n=a({type:"VariableDeclaration",kind:A.value,declarations:[D]},A,O);}else {let D=null;s("=")?(r(),D=k(true)):A.value==="const"&&E("'const' declarations must be initialized");let Y=a({type:"VariableDeclarator",id:O,init:D},O,D??O);t=a({type:"VariableDeclaration",kind:A.value,declarations:[Y]},A,D??O);}}else {let A=k(true);ue()||re()?n=A:t=A;}if(n){let A=re();r();let O=k();m(")");let D=U();return a(A?{type:"ForInStatement",left:n,right:O,body:D}:{type:"ForOfStatement",left:n,right:O,body:D,await:false},e,D)}m(";");let o=s(";")?null:k();m(";");let g=s(")")?null:k();m(")");let P=U();return a({type:"ForStatement",init:t,test:o,update:g,body:P},e,P)},Oe=()=>{let e=r(),t=U();x("while")||E("Expected 'while' after the 'do' body"),r(),m("(");let n=k(),o=m(")");return s(";")&&r(),a({type:"DoWhileStatement",body:t,test:n},e,o)},De=()=>{let e=r(),t=e.value==="break"?"BreakStatement":"ContinueStatement",n=s(";")?r():f();return a({type:t,label:null},e,n)},Je=()=>{let e=r();m("(");let t=k();m(")");let n=U();return a({type:"WhileStatement",test:t,body:n},e,n)},Le=()=>{let e=r();m("(");let t=k();m(")");let n=U(),o=null;return x("else")&&(r(),o=U()),a({type:"IfStatement",test:t,consequent:n,alternate:o},e,o??n)},Xe=()=>{let e=r(),t=null;!s(";")&&!s("}")&&!y()&&(t=k());let n=s(";")?r():f();return a({type:"ReturnStatement",argument:t},e,n)},Re=()=>{let e=r(),t=k(),n=s(";")?r():f();return a({type:"ThrowStatement",argument:t},e,n)},Fe=()=>{let e=r(),t=W(),n=null,o=null;if(x("catch")){let g=r(),P=null;s("(")&&(r(),P=u(),m(")"));let A=W();n=a({type:"CatchClause",param:P,body:A},g,A);}return x("finally")&&(r(),o=W()),!n&&!o&&E("'try' requires a 'catch' or 'finally' clause"),a({type:"TryStatement",block:t,handler:n,finalizer:o},e,o??n??t)},$e=()=>{let e=r();m("(");let t=k();m(")"),m("{");let n=[];for(;!s("}")&&!y();){let g=d(),P=null;x("case")?(r(),P=k()):x("default")?r():E("Expected 'case' or 'default' in switch"),m(":");let A=[];for(;!s("}")&&!x("case")&&!x("default")&&!y();)A.push(U());n.push(a({type:"SwitchCase",test:P,consequent:A},g,f()??g));}let o=m("}");return a({type:"SwitchStatement",discriminant:t,cases:n},e,o)},W=()=>{let e=m("{"),t=[];for(;!s("}")&&!y();)t.push(U());return a({type:"BlockStatement",body:t},e,m("}"))};return {parseExpr:k,parseProgram:()=>{let e=d(),t=[];for(;!y();)t.push(U());return a({type:"Program",sourceType:"module",body:t,...h.length?{typeRefs:h}:{}},e,f()??e)},eof:y,fail:E}}function rt(c){return ge(c).parseProgram()}function ot(c){let{parseExpr:S,eof:l,fail:h}=ge(c),d=S();return l()||h("Unexpected token after expression"),d}export{ye as KEYWORDS,Z as LexError,ee as ParseError,rt as parse,ot as parseExpression,ae as tokenize};
|
|
1
|
+
import {TSLiteError}from'@tslite/core';var te=class extends TSLiteError{constructor(u,a,p,k,f){super("lex-error",`${u} (${a.line}:${a.column})`,{position:a,index:p,loc:k,end:f});this.position=a;this.index=p;this.loc=k;this.end=f;this.name="LexError";}},Pe=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"]),nt=["...","===","!==","=>","?.","??","==","!=","<=",">=","&&","||","|","&","++","--","+=","-=","*=","/=","%=","**","<<","+","-","*","/","%","<",">","!","?",":",".",",",";","=","^","~","(",")","[","]","{","}"],de=r=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$",Ne=r=>de(r)||r>="0"&&r<="9",Z=r=>r>="0"&&r<="9",we=r=>Z(r)||r>="a"&&r<="f"||r>="A"&&r<="F",ot=r=>Ne(r)||r==="-",rt=new Set(["(","[","{",",",";",":","?","=>","...","=","+","-","*","/","%","<","<=",">",">=","==","===","!=","!==","&&","||","??","!","+=","-=","*=","/=","%="]),st=new Set(["return","typeof","await","delete","void","in","instanceof","else","case","yield","throw"]);function fe(r,d,u){let a=[],p=0,k=1,f=0,o=()=>({line:k,column:f}),y=(P=0)=>r[p+P]??"",K=P=>{let A=o(),X={start:A,end:{line:k,column:f+1}};if(u){u({message:P,position:A,index:p,loc:X,end:p+1});return}throw new te(P,A,p,X,p+1)},T=()=>{let P=r[p++];return P==="\r"?(r[p]===`
|
|
2
|
+
`&&p++,k++,f=0):P===`
|
|
3
|
+
`||P==="\u2028"||P==="\u2029"?(k++,f=0):f++,P},i=P=>P===`
|
|
4
|
+
`||P==="\r"||P==="\u2028"||P==="\u2029",N=()=>{for(;;){let P=y();if(P===" "||P===" "||P==="\f"||P==="\v"||i(P))T();else if(P==="/"&&y(1)==="/"){let A=p,X=o();T(),T();let I=p;for(;p<r.length&&!i(y());)T();d?.({type:"Line",value:r.slice(I,p),start:A,end:p,loc:{start:X,end:o()}});}else if(P==="/"&&y(1)==="*"){let A=p,X=o();T(),T();let I=p,l=p;for(;;){if(p>=r.length){K("Unterminated block comment"),l=p;break}if(y()==="*"&&y(1)==="/"){l=p,T(),T();break}T();}d?.({type:"Block",value:r.slice(I,l),start:A,end:p,loc:{start:X,end:o()}});}else break}},L=(P,A,X,I)=>{a.push({type:P,value:A,start:X,end:p,loc:{start:I,end:o()}}),E=P==="Punctuator"?rt.has(A):P==="Keyword"?st.has(A):P==="TemplateHead"||P==="TemplateMiddle";},R=P=>{for(T();p<r.length;){let A=y();if(A===P)return T(),r.slice(g,p);if(i(A))return K("Unterminated string literal"),r.slice(g,p);if(A==="\\"){if(T(),p>=r.length)return K("Unterminated string literal"),r.slice(g,p);T();continue}T();}return K("Unterminated string literal"),r.slice(g,p)},D=()=>{if(y()==="0"&&(y(1)==="x"||y(1)==="X")){if(T(),T(),!we(y()))return K("Invalid hexadecimal literal");for(;we(y());)T();return}if(y()==="0"&&(y(1)==="b"||y(1)==="B")){if(T(),T(),y()!=="0"&&y()!=="1")return K("Invalid binary literal");for(;y()==="0"||y()==="1";)T();return}if(y()==="0"&&(y(1)==="o"||y(1)==="O")){if(T(),T(),!(y()>="0"&&y()<="7"))return K("Invalid octal literal");for(;y()>="0"&&y()<="7";)T();return}for(;Z(y());)T();if(y()===".")for(T();Z(y());)T();if(y()==="e"||y()==="E"){if(T(),(y()==="+"||y()==="-")&&T(),!Z(y()))return K("Invalid exponent");for(;Z(y());)T();}},v=()=>{let P=p;for(;p<r.length;){let A=y();if(A==="`"){let X=r.slice(P,p);return T(),{raw:X,interp:false}}if(A==="$"&&y(1)==="{"){let X=r.slice(P,p);return T(),T(),{raw:X,interp:true}}if(A==="\\"){if(T(),p>=r.length)break;T();continue}T();}return K("Unterminated template literal"),{raw:r.slice(P,p),interp:false}},g=0,m=0,M=[],E=true,F="js",H=[],z=[];for(;;){if(F==="jsxChildren"){g=p;let I=o();if(p>=r.length){L("EOF","",g,I);break}let l=y();if(l==="<"){y(1)==="/"?(T(),T(),L("Punctuator","</",g,I),F="jsxCloseTag"):(T(),L("Punctuator","<",g,I),H.push("jsxChildren"),F="jsxOpenTag");continue}if(l==="{"){T(),L("Punctuator","{",g,I),z.push({level:m,restore:"jsxChildren"}),F="js";continue}for(;p<r.length&&y()!=="<"&&y()!=="{";)T();L("JSXText",r.slice(g,p),g,I);continue}if(F==="jsxOpenTag"||F==="jsxCloseTag"){N(),g=p;let I=o();if(p>=r.length){L("EOF","",g,I);break}let l=y();if(de(l)){for(T();ot(y());)T();L("Identifier",r.slice(g,p),g,I);continue}if(l==="/"&&y(1)===">"){T(),T(),L("Punctuator","/>",g,I),F=H.pop()??"js";continue}if(l===">"){T(),L("Punctuator",">",g,I),F=F==="jsxCloseTag"?H.pop()??"js":"jsxChildren";continue}if(l==="{"){T(),L("Punctuator","{",g,I),z.push({level:m,restore:F}),F="js";continue}if(l==='"'||l==="'"){L("String",R(l),g,I);continue}if(l==="="||l==="."||l===":"){T(),L("Punctuator",l,g,I);continue}K(`Unexpected character '${l}' in JSX tag`),T(),L("Unknown",l,g,I);continue}N(),g=p;let P=o();if(p>=r.length){L("EOF","",g,P);break}let A=y();if(de(A)){for(;Ne(y());)T();let I=r.slice(g,p);L(Pe.has(I)?"Keyword":"Identifier",I,g,P);continue}if(Z(A)||A==="."&&Z(y(1))){D(),L("Number",r.slice(g,p),g,P);continue}if(A==='"'||A==="'"){let I=R(A);L("String",I,g,P);continue}if(A==="`"){T();let{raw:I,interp:l}=v();l?(L("TemplateHead",I,g,P),M.push(m)):L("Template",I,g,P);continue}if(A==="<"&&E){T(),L("Punctuator","<",g,P),H.push("js"),F="jsxOpenTag";continue}if(A==="{"){T(),L("Punctuator","{",g,P),m++;continue}if(A==="}"){if(M.length>0&&m===M[M.length-1]){M.pop(),T();let{raw:I,interp:l}=v();L(l?"TemplateMiddle":"TemplateTail",I,g,P),l&&M.push(m);continue}if(z.length>0&&m===z[z.length-1].level){let{restore:I}=z.pop();T(),L("Punctuator","}",g,P),F=I;continue}T(),L("Punctuator","}",g,P),m--;continue}if(A==="?"&&y(1)==="."&&Z(y(2))){T(),L("Punctuator","?",g,P);continue}let X=nt.find(I=>r.startsWith(I,p));if(X){for(let I=0;I<X.length;I++)T();L("Punctuator",X,g,P);continue}K(`Unexpected character '${A}'`),T(),L("Unknown",A,g,P);}return a}var at=new Set(["leadingComments","trailingComments","innerComments","comments"]),Ee=r=>typeof r=="object"&&r!==null&&typeof r.type=="string"&&r.loc!=null&&typeof r.start=="number",Ce=new WeakMap;function it(r){let d=Ce.get(r);if(d)return d;let u=[];for(let a of Object.keys(r)){if(at.has(a))continue;let p=r[a];if(Ee(p))u.push(p);else if(Array.isArray(p))for(let k of p)Ee(k)&&u.push(k);}return u.sort((a,p)=>a.start-p.start),Ce.set(r,u),u}function lt(r,d){let u=r,a,p;for(;;){let k=it(u);a=void 0,p=void 0;let f;for(let o of k){if(o.start<=d.start&&d.end<=o.end){f=o;break}if(o.end<=d.start)a=o;else if(d.end<=o.start){p=o;break}}if(!f)break;u=f;}return {enclosing:u,preceding:a,following:p}}var ye=(r,d)=>{(r.leadingComments??(r.leadingComments=[])).push(d);},ce=(r,d)=>{(r.trailingComments??(r.trailingComments=[])).push(d);},me=(r,d)=>{(r.innerComments??(r.innerComments=[])).push(d);};function ct(r,d){for(let u=d;u<r.length;u++){let a=r[u];if(a!==" "&&a!==" "&&a!=="\r"&&a!==`
|
|
5
|
+
`&&a!=="\f")return a}return ""}var pt=new Set([")","]","}",","]);function he(r,d,u=""){for(let a of d){let{enclosing:p,preceding:k,following:f}=lt(r,a),o=k==null||k.loc.end.line<a.loc.start.line,y=!o&&(f==null||a.loc.end.line<f.loc.start.line);if(o)f?ye(f,a):k?ce(k,a):me(p,a);else if(y)k?ce(k,a):f?ye(f,a):me(p,a);else {let K=pt.has(ct(u,a.end));k&&K?ce(k,a):f?ye(f,a):k?ce(k,a):me(p,a);}}}var Te=(r=[])=>({vars:new Set(r),bounds:new Map,noCond:false,inferSink:null}),ae=(r,d)=>{let u=new Set(r.vars),a=new Map(r.bounds);for(let p of d)u.add(p.name),p.bound||p.isConst?a.set(p.name,{bound:p.bound,isConst:p.isConst}):a.delete(p.name);return {vars:u,bounds:a,noCond:r.noCond,inferSink:r.inferSink}},ut=(r,d)=>{let u=r.bounds.get(d);return u&&(u.bound||u.isConst)?{t:"var",name:d,...u.bound?{bound:u.bound}:{},...u.isConst?{isConst:true}:{}}:{t:"var",name:d}},Ie=r=>{let{peek:d,next:u,isP:a,isK:p,expectP:k,fail:f,unescape:o}=r,y=(l,h)=>{let c=r.tokens[r.pos()-1]??h;return Object.assign(l,{start:h.start,end:c.end,loc:{start:h.loc.start,end:c.loc.end}})},K=()=>{let l=r.pos(),h=r.tokens[l],c=r.tokens[l-1];return !!c&&!!h&&h.loc.start.line>c.loc.end.line},T=()=>{let l=0;for(let h=r.pos();h<r.tokens.length;h++){let c=r.tokens[h];if(c.type==="EOF")return false;if(c.type==="Punctuator"){if(["(","[","{","<"].includes(c.value))l++;else if([")","]","}",">"].includes(c.value)&&(l--,l===0)){let b=r.tokens[h+1];return !!b&&b.type==="Punctuator"&&b.value==="=>"}}}return false},i=()=>{let l=r.tokens,h=[],c=0,b=false;for(let x=r.pos();x<l.length;x++){let w=l[x];if(w.type==="EOF")break;if(w.type==="Punctuator"){if(w.value==="<")c++,c===1&&(b=true);else if(w.value===">"){if(c--,c===0)break}else w.value==="("||w.value==="["||w.value==="{"?(c++,b=false):w.value===")"||w.value==="]"||w.value==="}"?(c--,b=false):w.value===","&&c===1?b=true:b=false;continue}if(c===1&&b){if(w.type==="Keyword"&&w.value==="const")continue;if(w.type==="Identifier"){h.push(w.value),b=false;continue}}b=false;}return h},N=l=>{let h=ae(l,i().map(b=>({name:b})));k("<");let c=[];for(;!a(">");){let b=p("const");b&&u();let x=d();x.type!=="Identifier"&&f("Expected type parameter name"),u();let w;p("extends")&&(u(),w=D(h).schema),a("=")&&(u(),D(h)),c.push({name:x.value,...w?{bound:w}:{},...b?{isConst:true}:{}}),a(">")||k(",");}return k(">"),c},L=l=>{k("<");let h=[];for(;!a(">");)h.push(D(l)),a(">")||k(",");return k(">"),h},R=l=>{let h=d();return h.type==="Identifier"&&h.value===l},D=l=>{let h=d(),c=v(l);if(l.noCond||!p("extends")||K())return c;u();let b=[],x=v({...l,noCond:true,inferSink:b});k("?");let w=ae(l,b.map(J=>({name:J}))),O=D(w);k(":");let $=D(w);return {node:y({type:"TSConditionalType",checkType:c.node,extendsType:x.node,trueType:O.node,falseType:$.node},h),schema:{t:"conditional",check:c.schema,extends:x.schema,then:O.schema,else:$.schema,...b.length?{infer:b}:{}}}},v=l=>{let h=d();a("|")&&u();let c=g(l);if(!a("|"))return c;let b=[c.node],x=[c.schema];for(;a("|");){u();let w=g(l);b.push(w.node),x.push(w.schema);}return {node:y({type:"TSUnionType",types:b},h),schema:{t:"union",of:x}}},g=l=>{let h=d();a("&")&&u();let c=m(l);if(!a("&"))return c;let b=[c.node],x=[c.schema];for(;a("&");){u();let w=m(l);b.push(w.node),x.push(w.schema);}return {node:y({type:"TSIntersectionType",types:b},h),schema:{t:"intersection",of:x}}},m=l=>{let h=d();if(R("keyof")){u();let c=m(l);return {node:y({type:"TSTypeOperator",operator:"keyof",typeAnnotation:c.node},h),schema:{t:"keyof",of:c.schema}}}if(R("readonly")){u();let c=m(l);return c.schema.t!=="array"&&c.schema.t!=="tuple"&&f("'readonly' only applies to array and tuple types"),{node:y({...c.node,readonly:true},h),schema:{...c.schema,readonly:true}}}if(R("infer")){u();let c=d();c.type!=="Identifier"&&f("Expected 'infer' variable name"),u();let b=l.inferSink;return b?(b.push(c.value),{node:y({type:"TSInferType",name:c.value},h),schema:{t:"var",name:c.value}}):f("'infer' is only allowed in the 'extends' clause of a conditional")}return M(l)},M=l=>{let h=d(),c=F(l);for(;a("[")&&!K();)if(u(),a("]"))u(),c={node:y({type:"TSArrayType",elementType:c.node},h),schema:{t:"array",items:c.schema}};else {let b=D(l);k("]"),c={node:y({type:"TSIndexedAccessType",objectType:c.node,indexType:b.node},h),schema:{t:"index",obj:c.schema,key:b.schema}};}return c},E=(l,h,c)=>({node:y({type:"TSKeywordType",kind:h},l),schema:c}),F=l=>{let h=d();if(p("typeof")){u();let x=d();x.type!=="Identifier"&&f("Expected a name after 'typeof' in type position"),u();let w=[x.value];for(;a(".");){u();let O=d();O.type!=="Identifier"&&O.type!=="Keyword"&&f("Expected a property name after '.' in 'typeof'"),u(),w.push(O.value);}return {node:y({type:"TSTypeQuery",exprName:w},h),schema:{t:"typeQuery",path:w}}}if(a("<")){let x=N(l),w=ae(l,x);return z(w,h,x.map(O=>O.name))}if(a("(")){if(T())return z(l,h);u();let x=D(l.noCond?{...l,noCond:false}:l);return k(")"),x}if(a("{"))return A()?X(l):I(l);if(a("["))return P(l);let c=d();if(c.type==="String"){u();let x=o(c.value.slice(1,-1));return {node:y({type:"TSLiteralType",literal:x},h),schema:{t:"literal",value:x}}}if(c.type==="Number"){u();let x=Number(c.value);return {node:y({type:"TSLiteralType",literal:x},h),schema:{t:"literal",value:x}}}if(p("true"))return u(),{node:y({type:"TSLiteralType",literal:true},h),schema:{t:"literal",value:true}};if(p("false"))return u(),{node:y({type:"TSLiteralType",literal:false},h),schema:{t:"literal",value:false}};if(p("null"))return u(),E(h,"null",{t:"null"});if(p("void"))return u(),E(h,"void",{t:"void"});if(c.type==="Identifier"){switch(u(),c.value){case "string":return E(h,"string",{t:"string"});case "number":return E(h,"number",{t:"number"});case "boolean":return E(h,"boolean",{t:"boolean"});case "any":return E(h,"any",{t:"any"});case "unknown":return E(h,"unknown",{t:"unknown"});case "undefined":return E(h,"undefined",{t:"undefined"});case "never":return E(h,"never",{t:"union",of:[]})}let x=a("<")?L(l):[],w=x.map(J=>J.schema),O=x.length?x.map(J=>J.node):void 0,$=y({type:"TSTypeReference",typeName:c.value,...O?{typeArguments:O}:{}},h);return l.vars.has(c.value)&&w.length===0?{node:$,schema:ut(l,c.value)}:c.value==="ReturnType"&&w.length===1?{node:$,schema:{t:"returnType",fn:w[0]}}:c.value==="Parameters"&&w.length===1?{node:$,schema:{t:"parameters",fn:w[0]}}:(r.typeRefs?.push({name:c.value,loc:c.loc}),{node:$,schema:{t:"apply",name:c.value,args:w}})}r.recordError(`Expected a type but got '${c.value||c.type}'`,c);let b=r.createMissingNode({type:"TSTypeReference",typeName:""},c);return r.typeRefs?.push({name:"",loc:b.loc}),{node:b,schema:{t:"unknown"}}},H=l=>{k("(");let h=[];for(;!a(")");){let c=d();c.type!=="Identifier"&&f("Expected parameter name in function type"),u();let b=a("?");b&&u(),k(":");let x=D(l);h.push({node:y({type:"TSTypeParameter",name:c.value,typeAnnotation:x.node,...b?{optional:true}:{}},c),schema:{name:c.value,type:x.schema,...b?{optional:true}:{}}}),a(")")||k(",");}return k(")"),h},z=(l,h,c)=>{let b=H(l);k("=>");let x=D(l);return {node:y({type:"TSFunctionType",params:b.map(w=>w.node),returnType:x.node,...c?.length?{typeParams:[...c]}:{}},h),schema:{t:"fn",params:b.map(w=>w.schema),returns:x.schema,...c?.length?{typeParams:c}:{}}}},P=l=>{let h=d();k("[");let c=[],b=[],x=[];for(;!a("]");){if(a("...")){u();let O=D(l);O.schema.t==="array"?(b.push(O.schema.items),c.push(O.node.elementType),x.push("rest")):(b.push(O.schema),c.push(O.node),x.push("variadic"));}else {let O=D(l),$=a("?");$&&u(),b.push(O.schema),c.push(O.node),x.push($?"optional":"req");}a("]")||k(",");}k("]");let w=x.some(O=>O!=="req");return {node:y({type:"TSTupleType",elementTypes:c,...w?{flags:x}:{}},h),schema:w?{t:"tuple",elements:b,flags:x}:{t:"tuple",elements:b}}},A=()=>{let l=r.tokens,h=r.pos()+1;return l[h]?.type==="Punctuator"&&(l[h]?.value==="+"||l[h]?.value==="-")&&h++,l[h]?.type==="Identifier"&&l[h]?.value==="readonly"&&h++,l[h]?.type==="Punctuator"&&l[h]?.value==="["&&l[h+1]?.type==="Identifier"&&l[h+2]?.type==="Keyword"&&l[h+2]?.value==="in"},X=l=>{let h=d();k("{"),(a("+")||a("-"))&&u(),R("readonly")&&u(),k("[");let c=d();c.type!=="Identifier"&&f("Expected mapped type key name"),u(),p("in")||f("Expected 'in' in mapped type"),u();let b=D(l);R("as")&&f("Key remapping ('as') in mapped types is not supported"),k("]");let x=false,w=a("+")||a("-")?u().value:null;a("?")&&(u(),x=w!=="-"),k(":");let O=D(ae(l,[{name:c.value}]));return (a(";")||a(","))&&u(),k("}"),{node:y({type:"TSMappedType",key:c.value,constraint:b.node,typeAnnotation:O.node,optional:x},h),schema:{t:"mapped",key:c.value,over:b.schema,body:O.schema,optional:x}}},I=l=>{let h=d();k("{");let c=[],b={},x,w=[];for(;!a("}");){let $=d();if(a("(")){let J=H(l);k(":");let B=D(l);w.push({t:"fn",params:J.map(W=>W.schema),returns:B.schema}),c.push(y({type:"TSCallSignatureDeclaration",params:J.map(W=>W.node),returnType:B.node},$));}else if(a("[")){u(),d().type!=="Identifier"&&f("Expected index signature parameter name"),u(),k(":");let J=d();(J.type!=="Identifier"||J.value!=="string"&&J.value!=="number")&&f("Index signature parameter type must be 'string' or 'number'"),u(),k("]"),k(":");let B=D(l);x={key:J.value,value:B.schema},c.push(y({type:"TSIndexSignature",keyType:J.value,typeAnnotation:B.node},$));}else {let J=d(),B;if(J.type==="Identifier"||J.type==="Keyword")u(),B=J.value;else if(J.type==="String")u(),B=o(J.value.slice(1,-1));else if(J.type==="Number")u(),B=J.value;else return f("Expected property name in object type");let W=a("?");W&&u(),k(":");let ie=D(l);b[B]={type:ie.schema,...W?{optional:true}:{}},c.push(y({type:"TSPropertySignature",key:B,typeAnnotation:ie.node,...W?{optional:true}:{}},$));}if(a(";")||a(","))u();else break}k("}");let O=y({type:"TSTypeLiteral",members:c},h);return w.length>0?Object.keys(b).length>0||x?f("Callable object types (call signatures mixed with members) are not supported"):{node:O,schema:w.length===1?w[0]:{t:"overload",signatures:w}}:{node:O,schema:{t:"object",props:b,...x?{index:x}:{}}}};return {parseType:l=>D(Te(l)),parseTypeParamList:()=>N(Te()),parseTypeInScope:l=>D(ae(Te(),l))}};var ne=class extends TSLiteError{constructor(u,a,p,k,f){super("parse-error",`${u} (${a.line}:${a.column})`,{position:a,index:p,loc:k,end:f});this.position=a;this.index=p;this.loc=k;this.end=f;this.name="ParseError";}},ft=r=>{let d=r;return d!=null&&typeof d.start=="number"&&d.start===d.end&&d.start>=0},yt=(r,d)=>Object.assign(r,{start:d.start,end:d.start,loc:{start:d.loc.start,end:d.loc.start}}),mt={"??":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},ht=new Set(["??","||","&&"]),Tt=new Set(["class","debugger","with","enum","interface"]),gt={enum:'use a union of literals (`type T = "a" | "b"`) \u2014 it is serializable',interface:"use a type alias (`type X = { \u2026 }`)",namespace:"use modules (`import`/`export`)",module:"use modules (`import`/`export`)",declare:"declare the shape via the DI env, or with a `type` alias",abstract:"classes are not part of the language \u2014 model with objects + functions"},bt={namespace:(r,d)=>r.type==="Identifier"&&d.type==="Punctuator"&&d.value==="{",module:(r,d)=>r.type==="Identifier"&&d.type==="Punctuator"&&d.value==="{",declare:r=>r.type==="Keyword"&&["const","let","var","function","class","enum","interface"].includes(r.value)||r.type==="Identifier"&&["type","namespace","module"].includes(r.value),abstract:r=>r.type==="Keyword"&&r.value==="class"},St=new Set(["=","+=","-=","*=","/=","%="]);function Ae(r){let d=[],u=[],a=fe(r,e=>u.push(e),e=>d.push({code:"lex-error",...e})),p=0,k=[],f=(e=0)=>a[Math.min(p+e,a.length-1)],o=()=>a[p++],y=()=>a[p-1],K=()=>{let e=a[p],n=a[p-1];return !!e&&!!n&&e.loc.start.line>n.loc.end.line},T=()=>f().type==="EOF",i=e=>f().type==="Punctuator"&&f().value===e,N=e=>f().type==="Keyword"&&f().value===e,L=e=>f().type==="Identifier"&&f().value===e,R=(e,n=f())=>{throw D(e,n),new ne(e,n.loc.start,n.start,n.loc,n.end)},D=(e,n=f())=>{let t=d[d.length-1];t&&t.index===n.start||d.push({code:"parse-error",message:e,position:n.loc.start,index:n.start,loc:n.loc,end:n.end});},v=e=>(i(e)||R(`Expected '${e}' but got '${f().value||f().type}'`),o()),g=(e,n)=>{let t=y()??n;return Object.assign(e,{start:n.start,end:t.end,loc:{start:n.loc.start,end:t.loc.end}})},m=(e,n,t)=>Object.assign(e,{start:n.start,end:t.end,loc:{start:n.loc.start,end:t.loc.end}}),M=e=>{let n="";for(let t=0;t<e.length;t++){if(e[t]!=="\\"){n+=e[t];continue}let s=e[++t];switch(s){case "n":n+=`
|
|
6
|
+
`;break;case "t":n+=" ";break;case "r":n+="\r";break;case "b":n+="\b";break;case "f":n+="\f";break;case "v":n+="\v";break;case "0":n+="\0";break;case "x":n+=String.fromCharCode(parseInt(e.slice(t+1,t+3),16)),t+=2;break;case "u":if(e[t+1]==="{"){let S=e.indexOf("}",t);n+=String.fromCodePoint(parseInt(e.slice(t+2,S),16)),t=S;}else n+=String.fromCharCode(parseInt(e.slice(t+1,t+5),16)),t+=4;break;default:n+=s;}}return n},E=(e=false)=>F(e),F=(e=false)=>{let n=H(e),t=f();if(t.type==="Punctuator"&&St.has(t.value)){o();let s=F();return m({type:"AssignmentExpression",operator:t.value,left:n,right:s},n,s)}return n},H=(e=false)=>{let n=P(0,e);if(!i("?"))return n;o();let t=E();v(":");let s=E();return m({type:"ConditionalExpression",test:n,consequent:t,alternate:s},n,s)},z=()=>{let e=f();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 n=f(1);if(n.type==="Punctuator"&&n.value===">"&&e.end===n.start){let t=f(2);return t.type==="Punctuator"&&t.value===">"&&n.end===t.start?{op:">>>",consume:3}:{op:">>",consume:2}}return {op:">",consume:1}}return {op:e.value,consume:1}},P=(e,n=false)=>{let t=A();for(;;){let s=z();if(!s)break;let{op:S,consume:C}=s;if(S==="in"&&n)break;let j=mt[S];if(!j||j<=e)break;if(S==="satisfies"){if(K())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(S==="as"){if(K())break;o();let U=re(new Set);t=m({type:"TSAsExpression",expression:t,typeAnnotation:U.schema,typeAnnotationNode:U.node},t,y());continue}for(let U=0;U<C;U++)o();let _=P(S==="**"?j-1:j,n);t=m({type:ht.has(S)?"LogicalExpression":"BinaryExpression",operator:S,left:t,right:_},t,_);}return t},A=()=>{let e=f();return e.type==="Punctuator"&&(e.value==="++"||e.value==="--")?(o(),g({type:"UpdateExpression",operator:e.value,prefix:true,argument:A()},e)):N("await")?(o(),g({type:"AwaitExpression",argument:A()},e)):N("typeof")||N("void")||N("delete")||e.type==="Punctuator"&&(e.value==="!"||e.value==="-"||e.value==="+"||e.value==="~")?X(e):l()},X=e=>{o();let n=A();return i("**")&&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.`),g({type:"UnaryExpression",operator:e.value,prefix:true,argument:n},e)},I=()=>{let e=p,n=d.length,t=()=>(p=e,d.length=n,void 0);try{if(o(),i(">"))return t();let s=[];for(;s.push(re(new Set).schema),!!i(",");)o();return i(">")?(o(),i("(")?s:t()):t()}catch{return t()}},l=()=>{let e=Je(),n=false;for(;;)if(i("?."))if(o(),n=true,i("(")){let{args:t,close:s}=h();e=m({type:"CallExpression",callee:e,arguments:t,optional:true},e,s);}else if(i("[")){o();let t=E(),s=v("]");e=m({type:"MemberExpression",object:e,property:t,computed:true,optional:true},e,s);}else {let t=f();t.type!=="Identifier"&&t.type!=="Keyword"&&R("Expected property name after '?.'"),o();let s=g({type:"Identifier",name:t.value},t);e=m({type:"MemberExpression",object:e,property:s,computed:false,optional:true},e,s);}else if(i(".")){o();let t=f();t.type!=="Identifier"&&t.type!=="Keyword"&&R("Expected property name"),o();let s=g({type:"Identifier",name:t.value},t);e=m({type:"MemberExpression",object:e,property:s,computed:false,optional:false},e,s);}else if(i("[")){o();let t=E(),s=v("]");e=m({type:"MemberExpression",object:e,property:t,computed:true,optional:false},e,s);}else if(i("(")){let{args:t,close:s}=h();e=m({type:"CallExpression",callee:e,arguments:t,optional:false},e,s);}else if(i("<")){let t=I();if(!t)break;let{args:s,close:S}=h();e=m({type:"CallExpression",callee:e,arguments:s,optional:false,typeArguments:t},e,S);}else if(i("++")||i("--")){let t=o();e=m({type:"UpdateExpression",operator:t.value,prefix:false,argument:e},e,t);}else break;return n?m({type:"ChainExpression",expression:e},e,e):e},h=()=>{v("(");let e=[];for(;!i(")");)e.push(c()),i(")")||v(",");return {args:e,close:v(")")}},c=()=>{if(i("...")){let e=o(),n=E();return m({type:"SpreadElement",argument:n},e,n)}return E()},b=()=>{let e=f();return e.type!=="Identifier"&&R("Expected identifier"),o(),g({type:"Identifier",name:e.value},e)},x=e=>{let n=i("{")?w(e):i("[")?O(e):b();if(i(":")){o();let t=re(e);n.typeAnnotation=t.schema,n.typeAnnotationNode=t.node;}return n},w=e=>{let n=v("{"),t=[];for(;!i("}");){if(i("...")){let S=o(),C=x(e);t.push(m({type:"RestElement",argument:C},S,C));}else {let S=b(),C,j=false;if(i(":")?(o(),C=x(e)):(C={...S},j=true),i("=")){o();let _=E();C=m({type:"AssignmentPattern",left:C,right:_},C,_);}t.push(m({type:"Property",key:S,value:C,kind:"init",shorthand:j,computed:false,method:false},S,C));}i("}")||v(",");}let s=v("}");return m({type:"ObjectPattern",properties:t},n,s)},O=e=>{let n=v("["),t=[];for(;!i("]");){if(i(",")){t.push(null),o();continue}if(i("...")){let S=o(),C=x(e);t.push(m({type:"RestElement",argument:C},S,C));}else {let S=x(e);if(i("=")){o();let C=E();S=m({type:"AssignmentPattern",left:S,right:C},S,C);}t.push(S);}i("]")||v(",");}let s=v("]");return m({type:"ArrayPattern",elements:t},n,s)},$=()=>{let e=0;for(let n=p;n<a.length;n++){let t=a[n];if(t.type==="EOF")return false;if(t.type==="Punctuator"){if(t.value==="("||t.value==="["||t.value==="{")e++;else if((t.value===")"||t.value==="]"||t.value==="}")&&(e--,e===0)){let s=a[n+1];return !s||s.type!=="Punctuator"?false:s.value==="=>"?true:s.value===":"?J(n+2):false}}}return false},J=e=>{let n=0;for(let t=e;t<a.length;t++){let s=a[t];if(s.type==="EOF")return false;if(s.type==="Punctuator")if(["(","[","{","<"].includes(s.value))n++;else if([")","]","}",">"].includes(s.value)){if(n===0)return false;n--;}else {if(n===0&&s.value==="=>")return true;if(n===0&&(s.value===";"||s.value===","))return false}}return false},B=(e=new Set)=>{v("(");let n=[];for(;!i(")");){if(i("...")){let t=o(),s=x(e);n.push(m({type:"RestElement",argument:s},t,s));}else {let t=x(e);if(i("=")){o();let s=E();t=m({type:"AssignmentPattern",left:t,right:s},t,s);}n.push(t);}i(")")||v(",");}return v(")"),n},W=(e,n)=>{let t=i("(")?B():[b()],s,S;if(i(":")){o();let j=re(new Set);s=j.schema,S=j.node;}v("=>");let C=i("{")?se():E();return g({type:"ArrowFunctionExpression",params:t,body:C,async:e,expression:C.type!=="BlockStatement",generator:false,...s?{returnType:s,returnTypeNode:S}:{}},n)},ie=()=>{let e=v("["),n=[];for(;!i("]");){if(i(",")){o(),n.push(null);continue}n.push(c()),i("]")||v(",");}return m({type:"ArrayExpression",elements:n},e,v("]"))},Le=()=>{let e=v("{"),n=[];for(;!i("}");){if(i("...")){let t=o(),s=E();n.push(m({type:"SpreadElement",argument:s},t,s));}else {let t=f(),s,S=false;if(i("["))S=true,o(),s=E(),v("]");else if(t.type==="String")o(),s=g({type:"Literal",value:M(t.value.slice(1,-1)),raw:t.value},t);else if(t.type==="Number")o(),s=g({type:"Literal",value:Number(t.value),raw:t.value},t);else if(t.type==="Identifier"||t.type==="Keyword")o(),s=g({type:"Identifier",name:t.value},t);else return R("Invalid property key");if(i(":")){o();let C=E();n.push(m({type:"Property",key:s,value:C,kind:"init",method:false,shorthand:false,computed:S},t,C));}else n.push(m({type:"Property",key:s,value:s,kind:"init",method:false,shorthand:true,computed:false},t,s));}i("}")||v(",");}return m({type:"ObjectExpression",properties:n},e,v("}"))},le=(e,n)=>({type:"TemplateElement",value:{raw:e,cooked:M(e)},tail:n}),je=e=>{o();let n=[le(e.value,false)],t=[];for(;;){t.push(E());let s=f();if(s.type==="TemplateMiddle")o(),n.push(le(s.value,false));else if(s.type==="TemplateTail"){o(),n.push(le(s.value,true));break}else R("Expected `}` to close template interpolation");}return g({type:"TemplateLiteral",quasis:n,expressions:t},e)},oe=()=>{let e=f();return e.type!=="Identifier"&&R(`Expected JSX identifier but got '${e.value||e.type}'`),g({type:"JSXIdentifier",name:o().value},e)},ge=()=>{let e=oe();if(i(":")){o();let n=oe();return m({type:"JSXNamespacedName",namespace:e,name:n},e,n)}for(;i(".");){o();let n=oe();e=m({type:"JSXMemberExpression",object:e,property:n},e,n);}return e},G=e=>e.type==="JSXIdentifier"?e.name:e.type==="JSXNamespacedName"?`${G(e.namespace)}:${G(e.name)}`:`${G(e.object)}.${G(e.property)}`,Oe=()=>{let e=f();if(e.type==="String")return o(),g({type:"Literal",value:M(e.value.slice(1,-1)),raw:e.value},e);if(i("{")){let n=o(),t=F(),s=v("}");return m({type:"JSXExpressionContainer",expression:t},n,s)}return i("<")?pe():R(`Invalid JSX attribute value '${e.value||e.type}'`)},De=()=>{let e=[];for(;!i(">")&&!i("/>")&&!T();){if(i("{")){let s=o();v("...");let S=F(),C=v("}");e.push(m({type:"JSXSpreadAttribute",argument:S},s,C));continue}let n=oe();if(i(":")){o();let s=oe();n=m({type:"JSXNamespacedName",namespace:n,name:s},n,s);}let t=null;i("=")&&(o(),t=Oe()),e.push(m({type:"JSXAttribute",name:n,value:t},n,t??n));}return e},be=()=>{let e=[];for(;!(i("</")||T());){let n=f();if(n.type==="JSXText")o(),e.push(g({type:"JSXText",value:n.value,raw:n.value},n));else if(i("{")){let t=o();if(i("}")){let s=o(),S=g({type:"JSXEmptyExpression"},t);e.push(m({type:"JSXExpressionContainer",expression:S},t,s));}else {let s=F(),S=v("}");e.push(m({type:"JSXExpressionContainer",expression:s},t,S));}}else i("<")?e.push(pe()):R(`Unexpected token in JSX children '${n.value||n.type}'`);}return e},pe=()=>{let e=v("<");if(i(">")){let Q=o(),ee=m({type:"JSXOpeningFragment"},e,Q),Qe=be(),Ze=v("</"),ke=v(">"),et=m({type:"JSXClosingFragment"},Ze,ke);return m({type:"JSXFragment",openingFragment:ee,children:Qe,closingFragment:et},e,ke)}let n=ge(),t=De();if(i("/>")){let Q=o(),ee=m({type:"JSXOpeningElement",name:n,attributes:t,selfClosing:true},e,Q);return m({type:"JSXElement",openingElement:ee,children:[],closingElement:null},e,Q)}let s=v(">"),S=m({type:"JSXOpeningElement",name:n,attributes:t,selfClosing:false},e,s),C=be(),j=v("</"),_=f(),U=ge();G(U)!==G(n)&&R(`JSX closing tag </${G(U)}> does not match opening <${G(n)}>`,_);let q=v(">"),V=m({type:"JSXClosingElement",name:U},j,q);return m({type:"JSXElement",openingElement:S,children:C,closingElement:V},e,q)},Je=()=>{let e=f();if(N("async")){let n=f(1);return n.value==="("||n.type==="Identifier"?(o(),W(true,e)):R("Unexpected 'async'")}if(i("(")&&$()||e.type==="Identifier"&&f(1).type==="Punctuator"&&f(1).value==="=>")return W(false,e);if(e.type==="Number")return o(),g({type:"Literal",value:Number(e.value),raw:e.value},e);if(e.type==="String")return o(),g({type:"Literal",value:M(e.value.slice(1,-1)),raw:e.value},e);if(e.type==="Template")return o(),g({type:"TemplateLiteral",expressions:[],quasis:[le(e.value,true)]},e);if(e.type==="TemplateHead")return je(e);if(e.type==="Keyword")return e.value==="true"?(o(),g({type:"Literal",value:true,raw:"true"},e)):e.value==="false"?(o(),g({type:"Literal",value:false,raw:"false"},e)):e.value==="null"?(o(),g({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(),g({type:"Identifier",name:e.value},e);if(i("(")){o();let n=E();return v(")"),n}return i("[")?ie():i("{")?Le():i("<")?pe():R(`Unexpected token '${e.value||e.type}'`)},{parseType:re,parseTypeParamList:Fe,parseTypeInScope:Xe}=Ie({tokens:a,pos:()=>p,peek:f,next:o,isP:i,isK:N,expectP:v,fail:R,recordError:D,createMissingNode:yt,unescape:M,typeRefs:k}),Ke=()=>{let e=o(),n=b(),t=[],s=[];i("<")&&(s=Fe(),t=s.map(j=>j.name)),v("=");let S=Xe(s),C=m({type:"TSTypeAliasDeclaration",id:n,typeParameters:t,typeAnnotation:S.schema,typeNode:S.node},e,y());return i(";")&&o(),C},Y=()=>{let e=f();if(e.type==="Identifier"&&e.value==="type"&&f(1).type==="Identifier"&&f(2).type==="Punctuator"&&(f(2).value==="="||f(2).value==="<"))return Ke();if(N("const")||N("let")||N("var")){let S=Se();return i(";")&&o(),S}if(N("if"))return qe();if(N("for"))return Be();if(N("while"))return We();if(N("do"))return _e();if(N("break")||N("continue"))return ze();if(N("return"))return He();if(N("throw"))return Ve();if(N("try"))return Ge();if(N("switch"))return Ye();if(N("import"))return $e();if(N("export"))return Me();if(i("{"))return se();if((N("function")||N("async")&&f(1).type==="Keyword"&&f(1).value==="function")&&R("Function declarations are not supported \u2014 use 'const fn = () => \u2026'"),i(";"))return o(),g({type:"EmptyStatement"},e);if(e.type==="Keyword"&&Tt.has(e.value)||e.type==="Identifier"&&bt[e.value]?.(f(1),f(2))===true){let S=gt[e.value];R(`'${e.value}' is not supported in this language`+(S?` \u2014 ${S}`:""));}let t=E(),s=i(";")?o():y();return m({type:"ExpressionStatement",expression:t},t,s)},Se=()=>{let e=o(),n=e.value,t=()=>{let S=x(new Set),C=null;return i("=")?(o(),C=E()):n==="const"&&D("'const' declarations must be initialized"),m({type:"VariableDeclarator",id:S,init:C},S,C??S)},s=[t()];for(;i(",");)o(),s.push(t());return m({type:"VariableDeclaration",kind:n,declarations:s},e,s[s.length-1])},Ue=()=>{let e=f();return e.type!=="String"&&R("Expected module specifier string"),o(),g({type:"Literal",value:M(e.value.slice(1,-1)),raw:e.value},e)},$e=()=>{let e=o(),n=[];if(f().type!=="String"){if(f().type==="Identifier"){let s=b();n.push(m({type:"ImportDefaultSpecifier",local:s},s,s)),i(",")&&o();}if(i("*")){let s=o();L("as")||R("Expected 'as' after '*' in import"),o();let S=b();n.push(m({type:"ImportNamespaceSpecifier",local:S},s,S));}else if(i("{")){for(o();!i("}")&&!T();){let s=b(),S=s;if(L("as")&&(o(),S=b()),n.push(m({type:"ImportSpecifier",imported:s,local:S},s,S)),i(","))o();else break}v("}");}L("from")||R("Expected 'from' in import declaration"),o();}let t=Ue();return i(";")&&o(),g({type:"ImportDeclaration",specifiers:n,source:t},e)},Me=()=>{let e=o();if(N("default")){o();let n=E();return i(";")&&o(),g({type:"ExportDefaultDeclaration",declaration:n},e)}if(N("const")||N("let")||N("var")){let n=Se();return i(";")&&o(),g({type:"ExportNamedDeclaration",declaration:n,specifiers:[],source:null},e)}if(i("{")){o();let n=[];for(;!i("}")&&!T();){let t=b(),s=t;if(L("as")&&(o(),s=b()),n.push(m({type:"ExportSpecifier",local:t,exported:s},t,s)),i(","))o();else break}return v("}"),i(";")&&o(),g({type:"ExportNamedDeclaration",declaration:null,specifiers:n,source:null},e)}return R("Expected 'const', '{', or 'default' after 'export'")},ve=()=>f().type==="Identifier"&&f().value==="of",ue=()=>N("in"),Be=()=>{let e=o();v("(");let n=null,t=null;if(!i(";"))if(N("const")||N("let")||N("var")){let j=o(),_=()=>{let q=b();if(i(":")){o();let V=re(new Set);q.typeAnnotation=V.schema,q.typeAnnotationNode=V.node;}return q},U=_();if(ve()||ue()){let q=m({type:"VariableDeclarator",id:U,init:null},U,U);t=m({type:"VariableDeclaration",kind:j.value,declarations:[q]},j,U);}else {let q=Q=>{let ee=null;return i("=")?(o(),ee=E(true)):j.value==="const"&&R("'const' declarations must be initialized"),m({type:"VariableDeclarator",id:Q,init:ee},Q,ee??Q)},V=[q(U)];for(;i(",");)o(),V.push(q(_()));n=m({type:"VariableDeclaration",kind:j.value,declarations:V},j,V[V.length-1]);}}else {let j=E(true);ve()||ue()?t=j:n=j;}if(t){let j=ue();o();let _=E();v(")");let U=Y();return m(j?{type:"ForInStatement",left:t,right:_,body:U}:{type:"ForOfStatement",left:t,right:_,body:U,await:false},e,U)}v(";");let s=i(";")?null:E();v(";");let S=i(")")?null:E();v(")");let C=Y();return m({type:"ForStatement",init:n,test:s,update:S,body:C},e,C)},_e=()=>{let e=o(),n=Y();N("while")||R("Expected 'while' after the 'do' body"),o(),v("(");let t=E(),s=v(")");return i(";")&&o(),m({type:"DoWhileStatement",body:n,test:t},e,s)},ze=()=>{let e=o(),n=e.value==="break"?"BreakStatement":"ContinueStatement",t=i(";")?o():y();return m({type:n,label:null},e,t)},We=()=>{let e=o();v("(");let n=E();v(")");let t=Y();return m({type:"WhileStatement",test:n,body:t},e,t)},qe=()=>{let e=o();v("(");let n=E();v(")");let t=Y(),s=null;return N("else")&&(o(),s=Y()),m({type:"IfStatement",test:n,consequent:t,alternate:s},e,s??t)},He=()=>{let e=o(),n=null;!i(";")&&!i("}")&&!T()&&(n=E());let t=i(";")?o():y();return m({type:"ReturnStatement",argument:n},e,t)},Ve=()=>{let e=o(),n=E(),t=i(";")?o():y();return m({type:"ThrowStatement",argument:n},e,t)},Ge=()=>{let e=o(),n=se(),t=null,s=null;if(N("catch")){let S=o(),C=null;i("(")&&(o(),C=b(),v(")"));let j=se();t=m({type:"CatchClause",param:C,body:j},S,j);}return N("finally")&&(o(),s=se()),!t&&!s&&R("'try' requires a 'catch' or 'finally' clause"),m({type:"TryStatement",block:n,handler:t,finalizer:s},e,s??t??n)},Ye=()=>{let e=o();v("(");let n=E();v(")"),v("{");let t=[];for(;!i("}")&&!T();){let S=f(),C=null;N("case")?(o(),C=E()):N("default")?o():R("Expected 'case' or 'default' in switch"),v(":");let j=[];for(;!i("}")&&!N("case")&&!N("default")&&!T();)j.push(Y());t.push(m({type:"SwitchCase",test:C,consequent:j},S,y()??S));}let s=v("}");return m({type:"SwitchStatement",discriminant:n,cases:t},e,s)},se=()=>{let e=v("{"),n=xe(()=>i("}"));return m({type:"BlockStatement",body:n},e,v("}"))},xe=e=>{let n=[];for(;!e()&&!T();){if(f().type==="Unknown"){o();continue}try{n.push(Y());}catch(t){if(!(t instanceof ne))throw t;T()||o();}}return n};return {parseExpr:E,parseProgram:()=>{let e=f(),n=xe(()=>false);return m({type:"Program",sourceType:"module",body:n,...k.length?{typeRefs:k}:{},...u.length?{comments:u}:{},...d.length?{parseDiagnostics:d}:{}},e,y()??e)},eof:T,fail:R,diagnostics:d}}function Re(r){let d=Ae(r),u=d.parseProgram(),a=u.comments;return a?.length&&he(u,a,r),{ast:u,diagnostics:d.diagnostics}}function vt(r){let{ast:d,diagnostics:u}=Re(r),a=u[0];if(a){let p=a.code==="lex-error"?te:ne;throw new p(a.message,a.position,a.index,a.loc,a.end)}return d}function xt(r){let d=Ae(r),u=d.parseExpr();d.eof()||d.fail("Unexpected token after expression");let a=d.diagnostics[0];if(a){let p=a.code==="lex-error"?te:ne;throw new p(a.message,a.position,a.index,a.loc,a.end)}return u}export{Pe as KEYWORDS,te as LexError,ne as ParseError,he as attachComments,ft as nodeIsMissing,vt as parse,xt as parseExpression,Re as parseTolerant,fe as tokenize};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tslite/parser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "TSLite parser — tokenizer + Pratt parser for the TSLite language (JS subset + pipe) into ESTree",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -40,13 +40,13 @@
|
|
|
40
40
|
"access": "public"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@tslite/core": "0.
|
|
43
|
+
"@tslite/core": "0.4.0"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"@tslite/capability": "0.2.0",
|
|
47
|
-
"@tslite/printer": "0.
|
|
48
|
-
"@tslite/interpret": "0.
|
|
49
|
-
"@tslite/checker": "0.
|
|
47
|
+
"@tslite/printer": "0.3.0",
|
|
48
|
+
"@tslite/interpret": "0.3.0",
|
|
49
|
+
"@tslite/checker": "0.5.0"
|
|
50
50
|
},
|
|
51
51
|
"scripts": {
|
|
52
52
|
"build": "tsup",
|