@tslite/parser 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +5 -0
- package/dist/index.d.cts +50 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +5 -0
- package/package.json +64 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
'use strict';var core=require('@tslite/core');var $=class extends core.TSLiteError{constructor(p,i,r){super("lex-error",`${p} (${i.line}:${i.column})`,{position:i,index:r});this.position=i;this.index=r;this.name="LexError";}},G=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"]),ve=["...","===","!==","=>","|>","?.","??","==","!=","<=",">=","&&","||","|","++","--","+=","-=","*=","/=","%=","+","-","*","/","%","<",">","!","?",":",".",",",";","=","(",")","[","]","{","}"],_=f=>f>="a"&&f<="z"||f>="A"&&f<="Z"||f==="_"||f==="$",be=f=>_(f)||f>="0"&&f<="9",F=f=>f>="0"&&f<="9",H=f=>F(f)||f>="a"&&f<="f"||f>="A"&&f<="F";function z(f){let x=[],p=0,i=1,r=0,b=()=>({line:i,column:r}),u=(l=0)=>f[p+l]??"",a=l=>{throw new $(l,b(),p)},s=()=>{let l=f[p++];return l==="\r"?(f[p]===`
|
|
2
|
+
`&&p++,i++,r=0):l===`
|
|
3
|
+
`||l==="\u2028"||l==="\u2029"?(i++,r=0):r++,l},w=l=>l===`
|
|
4
|
+
`||l==="\r"||l==="\u2028"||l==="\u2029",y=()=>{for(;;){let l=u();if(l===" "||l===" "||l==="\f"||l==="\v"||w(l))s();else if(l==="/"&&u(1)==="/")for(;p<f.length&&!w(u());)s();else if(l==="/"&&u(1)==="*")for(s(),s();;){if(p>=f.length&&a("Unterminated block comment"),u()==="*"&&u(1)==="/"){s(),s();break}s();}else break}},h=(l,m,N,k)=>{x.push({type:l,value:m,start:N,end:p,loc:{start:k,end:b()}});},c=l=>{for(s();p<f.length;){let m=u();if(m===l)return s(),f.slice(S,p);if(w(m)&&a("Unterminated string literal"),m==="\\"){s(),p>=f.length&&a("Unterminated string literal"),s();continue}s();}return a("Unterminated string literal")},L=()=>{if(u()==="0"&&(u(1)==="x"||u(1)==="X")){for(s(),s(),H(u())||a("Invalid hexadecimal literal");H(u());)s();return}if(u()==="0"&&(u(1)==="b"||u(1)==="B")){for(s(),s(),u()!=="0"&&u()!=="1"&&a("Invalid binary literal");u()==="0"||u()==="1";)s();return}if(u()==="0"&&(u(1)==="o"||u(1)==="O")){for(s(),s(),u()>="0"&&u()<="7"||a("Invalid octal literal");u()>="0"&&u()<="7";)s();return}for(;F(u());)s();if(u()===".")for(s();F(u());)s();if(u()==="e"||u()==="E")for(s(),(u()==="+"||u()==="-")&&s(),F(u())||a("Invalid exponent");F(u());)s();},g=()=>{let l=p;for(;p<f.length;){let m=u();if(m==="`"){let N=f.slice(l,p);return s(),{raw:N,interp:false}}if(m==="$"&&u(1)==="{"){let N=f.slice(l,p);return s(),s(),{raw:N,interp:true}}if(m==="\\"){if(s(),p>=f.length)break;s();continue}s();}return a("Unterminated template literal")},S=0,v=0,d=[];for(;;){y(),S=p;let l=b();if(p>=f.length){h("EOF","",S,l);break}let m=u();if(_(m)){for(;be(u());)s();let k=f.slice(S,p);h(G.has(k)?"Keyword":"Identifier",k,S,l);continue}if(F(m)||m==="."&&F(u(1))){L(),h("Number",f.slice(S,p),S,l);continue}if(m==='"'||m==="'"){let k=c(m);h("String",k,S,l);continue}if(m==="`"){s();let{raw:k,interp:O}=g();O?(h("TemplateHead",k,S,l),d.push(v)):h("Template",k,S,l);continue}if(m==="{"){s(),h("Punctuator","{",S,l),v++;continue}if(m==="}"){if(d.length>0&&v===d[d.length-1]){d.pop(),s();let{raw:k,interp:O}=g();h(O?"TemplateMiddle":"TemplateTail",k,S,l),O&&d.push(v);continue}s(),h("Punctuator","}",S,l),v--;continue}if(m==="?"&&u(1)==="."&&F(u(2))){s(),h("Punctuator","?",S,l);continue}let N=ve.find(k=>f.startsWith(k,p));if(N){for(let k=0;k<N.length;k++)s();h("Punctuator",N,S,l);continue}a(`Unexpected character '${m}'`);}return x}var Y=f=>{let{peek:x,next:p,isP:i,isK:r,expectP:b,fail:u,unescape:a}=f,s=()=>{let v=0;for(let d=f.pos();d<f.tokens.length;d++){let l=f.tokens[d];if(l.type==="EOF")return false;if(l.type==="Punctuator"){if(["(","[","{","<"].includes(l.value))v++;else if([")","]","}",">"].includes(l.value)&&(v--,v===0)){let m=f.tokens[d+1];return !!m&&m.type==="Punctuator"&&m.value==="=>"}}}return false},w=()=>{b("<");let v=[];for(;!i(">");){let d=x();d.type!=="Identifier"&&u("Expected type parameter name"),p(),v.push(d.value),i(">")||b(",");}return b(">"),v},y=v=>{b("<");let d=[];for(;!i(">");)d.push(h(v)),i(">")||b(",");return b(">"),d},h=v=>{let d=c(v);if(!i("|"))return d;let l=[d];for(;i("|");)p(),l.push(c(v));return {t:"union",of:l}},c=v=>{let d=L(v);for(;i("[")&&x(1).type==="Punctuator"&&x(1).value==="]";)p(),p(),d={t:"array",items:d};return d},L=v=>{if(i("<")){let l=w(),m=new Set(v);return l.forEach(N=>m.add(N)),g(m)}if(i("(")){if(s())return g(v);p();let l=h(v);return b(")"),l}if(i("{"))return S(v);let d=x();if(d.type==="String")return p(),{t:"literal",value:a(d.value.slice(1,-1))};if(d.type==="Number")return p(),{t:"literal",value:Number(d.value)};if(r("true"))return p(),{t:"literal",value:true};if(r("false"))return p(),{t:"literal",value:false};if(r("null"))return p(),{t:"null"};if(d.type==="Identifier"){switch(p(),d.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"}}let l=i("<")?y(v):[];return v.has(d.value)&&l.length===0?{t:"var",name:d.value}:{t:"apply",name:d.value,args:l}}return u(`Expected a type but got '${d.value||d.type}'`)},g=v=>{b("(");let d=[];for(;!i(")");){let m=x();m.type!=="Identifier"&&u("Expected parameter name in function type"),p();let N=i("?");N&&p(),b(":");let k=h(v);d.push({name:m.value,type:k,...N?{optional:true}:{}}),i(")")||b(",");}b(")"),b("=>");let l=h(v);return {t:"fn",params:d,returns:l}},S=v=>{b("{");let d={};for(;!i("}");){let l=x(),m;if(l.type==="Identifier"||l.type==="Keyword")p(),m=l.value;else if(l.type==="String")p(),m=a(l.value.slice(1,-1));else return u("Expected property name in object type");let N=i("?");N&&p(),b(":");let k=h(v);if(d[m]={type:k,...N?{optional:true}:{}},i(";")||i(","))p();else break}return b("}"),{t:"object",props:d}};return {parseType:h,parseTypeParamList:w}};var M=class extends core.TSLiteError{constructor(p,i,r){super("parse-error",`${p} (${i.line}:${i.column})`,{position:i,index:r});this.position=i;this.index=r;this.name="ParseError";}},xe={"??":1,"||":2,"&&":3,"==":4,"===":4,"!=":4,"!==":4,"<":5,"<=":5,">":5,">=":5,"+":6,"-":6,"*":7,"/":7,"%":7},ke=new Set(["??","||","&&"]),Te=new Set(["class","import","export","debugger","with"]),Se=new Set(["=","+=","-=","*=","/=","%="]);function X(f){let x=z(f),p=0,i=(e=0)=>x[Math.min(p+e,x.length-1)],r=()=>x[p++],b=()=>x[p-1],u=()=>i().type==="EOF",a=e=>i().type==="Punctuator"&&i().value===e,s=e=>i().type==="Keyword"&&i().value===e,w=(e,n=i())=>{throw new M(e,n.loc.start,n.start)},y=e=>(a(e)||w(`Expected '${e}' but got '${i().value||i().type}'`),r()),h=(e,n)=>{let t=b()??n;return Object.assign(e,{start:n.start,end:t.end,loc:{start:n.loc.start,end:t.loc.end}})},c=(e,n,t)=>Object.assign(e,{start:n.start,end:t.end,loc:{start:n.loc.start,end:t.loc.end}}),L=e=>{let n="";for(let t=0;t<e.length;t++){if(e[t]!=="\\"){n+=e[t];continue}let o=e[++t];switch(o){case "n":n+=`
|
|
5
|
+
`;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 T=e.indexOf("}",t);n+=String.fromCodePoint(parseInt(e.slice(t+2,T),16)),t=T;}else n+=String.fromCharCode(parseInt(e.slice(t+1,t+5),16)),t+=4;break;default:n+=o;}}return n},g=()=>S(),S=()=>{let e=v(),n=i();if(n.type==="Punctuator"&&Se.has(n.value)){r();let t=S();return c({type:"AssignmentExpression",operator:n.value,left:e,right:t},e,t)}return e},v=()=>{let e=d();for(;a("|>");){r();let n=d();e=c({type:"CallExpression",callee:n,arguments:[e],optional:false},e,n);}return e},d=()=>{let e=l(0);if(!a("?"))return e;r();let n=g();y(":");let t=g();return c({type:"ConditionalExpression",test:e,consequent:n,alternate:t},e,t)},l=e=>{let n=m();for(;;){let t=i();if(t.type!=="Punctuator")break;let o=xe[t.value];if(!o||o<=e)break;r();let T=l(o);n=c({type:ke.has(t.value)?"LogicalExpression":"BinaryExpression",operator:t.value,left:n,right:T},n,T);}return n},m=()=>{let e=i();return e.type==="Punctuator"&&(e.value==="++"||e.value==="--")?(r(),h({type:"UpdateExpression",operator:e.value,prefix:true,argument:m()},e)):s("await")?(r(),h({type:"AwaitExpression",argument:m()},e)):s("typeof")||s("void")||s("delete")?(r(),h({type:"UnaryExpression",operator:e.value,prefix:true,argument:m()},e)):e.type==="Punctuator"&&(e.value==="!"||e.value==="-"||e.value==="+")?(r(),h({type:"UnaryExpression",operator:e.value,prefix:true,argument:m()},e)):N()},N=()=>{let e=k();for(;i().type==="Identifier"&&i().value==="as";){r();let n=D(new Set);e=c({type:"TSAsExpression",expression:e,typeAnnotation:n},e,b());}return e},k=()=>{let e=W(),n=false;for(;;)if(a("?."))if(r(),n=true,a("(")){let{args:t,close:o}=O();e=c({type:"CallExpression",callee:e,arguments:t,optional:true},e,o);}else if(a("[")){r();let t=g(),o=y("]");e=c({type:"MemberExpression",object:e,property:t,computed:true,optional:true},e,o);}else {let t=i();t.type!=="Identifier"&&t.type!=="Keyword"&&w("Expected property name after '?.'"),r();let o=h({type:"Identifier",name:t.value},t);e=c({type:"MemberExpression",object:e,property:o,computed:false,optional:true},e,o);}else if(a(".")){r();let t=i();t.type!=="Identifier"&&t.type!=="Keyword"&&w("Expected property name"),r();let o=h({type:"Identifier",name:t.value},t);e=c({type:"MemberExpression",object:e,property:o,computed:false,optional:false},e,o);}else if(a("[")){r();let t=g(),o=y("]");e=c({type:"MemberExpression",object:e,property:t,computed:true,optional:false},e,o);}else if(a("(")){let{args:t,close:o}=O();e=c({type:"CallExpression",callee:e,arguments:t,optional:false},e,o);}else if(a("++")||a("--")){let t=r();e=c({type:"UpdateExpression",operator:t.value,prefix:false,argument:e},e,t);}else break;return n?c({type:"ChainExpression",expression:e},e,e):e},O=()=>{y("(");let e=[];for(;!a(")");)e.push(V()),a(")")||y(",");return {args:e,close:y(")")}},V=()=>{if(a("...")){let e=r(),n=g();return c({type:"SpreadElement",argument:n},e,n)}return g()},j=()=>{let e=i();return e.type!=="Identifier"&&w("Expected identifier"),r(),h({type:"Identifier",name:e.value},e)},Z=()=>{let e=0;for(let n=p;n<x.length;n++){let t=x[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 o=x[n+1];return !o||o.type!=="Punctuator"?false:o.value==="=>"?true:o.value===":"?J(n+2):false}}}return false},J=e=>{let n=0;for(let t=e;t<x.length;t++){let o=x[t];if(o.type==="EOF")return false;if(o.type==="Punctuator")if(["(","[","{","<"].includes(o.value))n++;else if([")","]","}",">"].includes(o.value)){if(n===0)return false;n--;}else {if(n===0&&o.value==="=>")return true;if(n===0&&(o.value===";"||o.value===","))return false}}return false},Q=(e=new Set)=>{y("(");let n=[];for(;!a(")");){if(a("...")){let t=r(),o=j();a(":")&&(r(),o.typeAnnotation=D(e)),n.push(c({type:"RestElement",argument:o},t,o));}else {let t=j();a(":")&&(r(),t.typeAnnotation=D(e)),n.push(t);}a(")")||y(",");}return y(")"),n},R=(e,n)=>{let t=a("(")?Q():[j()],o;a(":")&&(r(),o=D(new Set)),y("=>");let T=a("{")?K():g();return h({type:"ArrowFunctionExpression",params:t,body:T,async:e,expression:T.type!=="BlockStatement",generator:false,...o?{returnType:o}:{}},n)},ee=()=>{let e=y("["),n=[];for(;!a("]");){if(a(",")){r(),n.push(null);continue}n.push(V()),a("]")||y(",");}return c({type:"ArrayExpression",elements:n},e,y("]"))},te=()=>{let e=y("{"),n=[];for(;!a("}");){if(a("...")){let t=r(),o=g();n.push(c({type:"SpreadElement",argument:o},t,o));}else {let t=i(),o,T=false;if(a("["))T=true,r(),o=g(),y("]");else if(t.type==="String")r(),o=h({type:"Literal",value:L(t.value.slice(1,-1)),raw:t.value},t);else if(t.type==="Number")r(),o=h({type:"Literal",value:Number(t.value),raw:t.value},t);else if(t.type==="Identifier"||t.type==="Keyword")r(),o=h({type:"Identifier",name:t.value},t);else return w("Invalid property key");if(a(":")){r();let P=g();n.push(c({type:"Property",key:o,value:P,kind:"init",method:false,shorthand:false,computed:T},t,P));}else n.push(c({type:"Property",key:o,value:o,kind:"init",method:false,shorthand:true,computed:false},t,o));}a("}")||y(",");}return c({type:"ObjectExpression",properties:n},e,y("}"))},U=(e,n)=>({type:"TemplateElement",value:{raw:e,cooked:L(e)},tail:n}),ne=e=>{r();let n=[U(e.value,false)],t=[];for(;;){t.push(g());let o=i();if(o.type==="TemplateMiddle")r(),n.push(U(o.value,false));else if(o.type==="TemplateTail"){r(),n.push(U(o.value,true));break}else w("Expected `}` to close template interpolation");}return h({type:"TemplateLiteral",quasis:n,expressions:t},e)},W=()=>{let e=i();if(s("async")){let n=i(1);return n.value==="("||n.type==="Identifier"?(r(),R(true,e)):w("Unexpected 'async'")}if(a("(")&&Z()||e.type==="Identifier"&&i(1).type==="Punctuator"&&i(1).value==="=>")return R(false,e);if(e.type==="Number")return r(),h({type:"Literal",value:Number(e.value),raw:e.value},e);if(e.type==="String")return r(),h({type:"Literal",value:L(e.value.slice(1,-1)),raw:e.value},e);if(e.type==="Template")return r(),h({type:"TemplateLiteral",expressions:[],quasis:[U(e.value,true)]},e);if(e.type==="TemplateHead")return ne(e);if(e.type==="Keyword")return e.value==="true"?(r(),h({type:"Literal",value:true,raw:"true"},e)):e.value==="false"?(r(),h({type:"Literal",value:false,raw:"false"},e)):e.value==="null"?(r(),h({type:"Literal",value:null,raw:"null"},e)):e.value==="new"?re(e):e.value==="function"?w("Anonymous functions are not supported \u2014 use an arrow function"):w(`'${e.value}' is not supported in this language`);if(e.type==="Identifier")return r(),h({type:"Identifier",name:e.value},e);if(a("(")){r();let n=g();return y(")"),n}return a("[")?ee():a("{")?te():w(`Unexpected token '${e.value||e.type}'`)},re=e=>{r();let n=W();for(;;)if(a(".")){r();let t=i();t.type!=="Identifier"&&t.type!=="Keyword"&&w("Expected property name"),r();let o=h({type:"Identifier",name:t.value},t);n=c({type:"MemberExpression",object:n,property:o,computed:false,optional:false},n,o);}else if(a("[")){r();let t=g(),o=y("]");n=c({type:"MemberExpression",object:n,property:t,computed:true,optional:false},n,o);}else break;if(a("(")){let{args:t,close:o}=O();return c({type:"NewExpression",callee:n,arguments:t},e,o)}return c({type:"NewExpression",callee:n,arguments:[]},e,n)},{parseType:D,parseTypeParamList:oe}=Y({tokens:x,pos:()=>p,peek:i,next:r,isP:a,isK:s,expectP:y,fail:w,unescape:L}),se=()=>{let e=r(),n=j(),t=new Set,o=[];a("<")&&(o=oe(),o.forEach(E=>t.add(E))),y("=");let T=D(t),P=c({type:"TSTypeAliasDeclaration",id:n,typeParameters:o,typeAnnotation:T},e,b());return a(";")&&r(),P},C=()=>{let e=i();if(e.type==="Identifier"&&e.value==="type"&&i(1).type==="Identifier"&&i(2).type==="Punctuator"&&(i(2).value==="="||i(2).value==="<"))return se();if(s("const")||s("let")||s("var")){let o=ae();return a(";")&&r(),o}if(s("if"))return ce();if(s("for"))return ie();if(s("while"))return pe();if(s("do"))return le();if(s("break")||s("continue"))return ue();if(s("return"))return fe();if(s("throw"))return de();if(s("try"))return ye();if(s("switch"))return me();if(a("{"))return K();if((s("function")||s("async")&&i(1).type==="Keyword"&&i(1).value==="function")&&w("Function declarations are not supported \u2014 use 'const fn = () => \u2026'"),a(";"))return r(),h({type:"EmptyStatement"},e);e.type==="Keyword"&&Te.has(e.value)&&w(`'${e.value}' is not supported in this language`);let n=g(),t=a(";")?r():b();return c({type:"ExpressionStatement",expression:n},n,t)},ae=()=>{let e=r(),n=e.value,t=j();a(":")&&(r(),t.typeAnnotation=D(new Set));let o=null;a("=")?(r(),o=g()):n==="const"&&w("'const' declarations must be initialized");let T=c({type:"VariableDeclarator",id:t,init:o},t,o??t);return c({type:"VariableDeclaration",kind:n,declarations:[T]},e,o??t)},q=()=>i().type==="Identifier"&&i().value==="of",B=()=>s("in"),ie=()=>{let e=r();y("(");let n=null,t=null;if(!a(";"))if(s("const")||s("let")||s("var")){let E=r(),I=j();if(a(":")&&(r(),I.typeAnnotation=D(new Set)),q()||B()){let A=c({type:"VariableDeclarator",id:I,init:null},I,I);t=c({type:"VariableDeclaration",kind:E.value,declarations:[A]},E,I);}else {let A=null;a("=")?(r(),A=g()):E.value==="const"&&w("'const' declarations must be initialized");let he=c({type:"VariableDeclarator",id:I,init:A},I,A??I);n=c({type:"VariableDeclaration",kind:E.value,declarations:[he]},E,A??I);}}else {let E=g();q()||B()?t=E:n=E;}if(t){let E=B();r();let I=g();y(")");let A=C();return c(E?{type:"ForInStatement",left:t,right:I,body:A}:{type:"ForOfStatement",left:t,right:I,body:A,await:false},e,A)}y(";");let o=a(";")?null:g();y(";");let T=a(")")?null:g();y(")");let P=C();return c({type:"ForStatement",init:n,test:o,update:T,body:P},e,P)},le=()=>{let e=r(),n=C();s("while")||w("Expected 'while' after the 'do' body"),r(),y("(");let t=g(),o=y(")");return a(";")&&r(),c({type:"DoWhileStatement",body:n,test:t},e,o)},ue=()=>{let e=r(),n=e.value==="break"?"BreakStatement":"ContinueStatement",t=a(";")?r():b();return c({type:n,label:null},e,t)},pe=()=>{let e=r();y("(");let n=g();y(")");let t=C();return c({type:"WhileStatement",test:n,body:t},e,t)},ce=()=>{let e=r();y("(");let n=g();y(")");let t=C(),o=null;return s("else")&&(r(),o=C()),c({type:"IfStatement",test:n,consequent:t,alternate:o},e,o??t)},fe=()=>{let e=r(),n=null;!a(";")&&!a("}")&&!u()&&(n=g());let t=a(";")?r():b();return c({type:"ReturnStatement",argument:n},e,t)},de=()=>{let e=r(),n=g(),t=a(";")?r():b();return c({type:"ThrowStatement",argument:n},e,t)},ye=()=>{let e=r(),n=K(),t=null,o=null;if(s("catch")){let T=r(),P=null;a("(")&&(r(),P=j(),y(")"));let E=K();t=c({type:"CatchClause",param:P,body:E},T,E);}return s("finally")&&(r(),o=K()),!t&&!o&&w("'try' requires a 'catch' or 'finally' clause"),c({type:"TryStatement",block:n,handler:t,finalizer:o},e,o??t??n)},me=()=>{let e=r();y("(");let n=g();y(")"),y("{");let t=[];for(;!a("}")&&!u();){let T=i(),P=null;s("case")?(r(),P=g()):s("default")?r():w("Expected 'case' or 'default' in switch"),y(":");let E=[];for(;!a("}")&&!s("case")&&!s("default")&&!u();)E.push(C());t.push(c({type:"SwitchCase",test:P,consequent:E},T,b()??T));}let o=y("}");return c({type:"SwitchStatement",discriminant:n,cases:t},e,o)},K=()=>{let e=y("{"),n=[];for(;!a("}")&&!u();)n.push(C());return c({type:"BlockStatement",body:n},e,y("}"))};return {parseExpr:g,parseProgram:()=>{let e=i(),n=[];for(;!u();)n.push(C());return c({type:"Program",sourceType:"module",body:n},e,b()??e)},eof:u,fail:w}}function Ne(f){return X(f).parseProgram()}function Ee(f){let{parseExpr:x,eof:p,fail:i}=X(f),r=x();return p()||i("Unexpected token after expression"),r}exports.KEYWORDS=G;exports.LexError=$;exports.ParseError=M;exports.parse=Ne;exports.parseExpression=Ee;exports.tokenize=z;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { TSLiteError, types } from '@tslite/core';
|
|
2
|
+
|
|
3
|
+
/** Code dos erros lançados pelo parser/tokenizer. */
|
|
4
|
+
type ParserErrorCode = "lex-error" | "parse-error";
|
|
5
|
+
/** Posição num ponto da fonte (linha 1-based, coluna 0-based). */
|
|
6
|
+
interface Position {
|
|
7
|
+
readonly line: number;
|
|
8
|
+
readonly column: number;
|
|
9
|
+
}
|
|
10
|
+
/** Intervalo de posições de um token/nó. */
|
|
11
|
+
interface SourceLocation {
|
|
12
|
+
readonly start: Position;
|
|
13
|
+
readonly end: Position;
|
|
14
|
+
}
|
|
15
|
+
type TokenType = "Identifier" | "Keyword" | "Number" | "String" | "Template" | "TemplateHead" | "TemplateMiddle" | "TemplateTail" | "Punctuator" | "EOF";
|
|
16
|
+
interface Token {
|
|
17
|
+
readonly type: TokenType;
|
|
18
|
+
/** O lexema cru, como aparece na fonte (sem decodificar escapes). */
|
|
19
|
+
readonly value: string;
|
|
20
|
+
/** Offset absoluto de início (inclusivo) e fim (exclusivo). */
|
|
21
|
+
readonly start: number;
|
|
22
|
+
readonly end: number;
|
|
23
|
+
readonly loc: SourceLocation;
|
|
24
|
+
}
|
|
25
|
+
/** Erro de léxico, com a posição onde ocorreu. */
|
|
26
|
+
declare class LexError extends TSLiteError<"lex-error"> {
|
|
27
|
+
readonly position: Position;
|
|
28
|
+
readonly index: number;
|
|
29
|
+
constructor(message: string, position: Position, index: number);
|
|
30
|
+
}
|
|
31
|
+
/** Palavras reservadas. As permitidas e as proibidas — o parser decide. */
|
|
32
|
+
declare const KEYWORDS: Set<string>;
|
|
33
|
+
/** Tokeniza a fonte. Devolve a lista de tokens, terminada por um `EOF`. */
|
|
34
|
+
declare function tokenize(source: string): Token[];
|
|
35
|
+
|
|
36
|
+
/** Erro de sintaxe, com a posição onde ocorreu. */
|
|
37
|
+
declare class ParseError extends TSLiteError<"parse-error"> {
|
|
38
|
+
readonly position: Position;
|
|
39
|
+
readonly index: number;
|
|
40
|
+
constructor(message: string, position: Position, index: number);
|
|
41
|
+
}
|
|
42
|
+
/** Faz o parse de uma fonte completa num `Program` (ESTree, com `loc`). */
|
|
43
|
+
declare function parse(source: string): types.Program;
|
|
44
|
+
/**
|
|
45
|
+
* Conveniência: faz o parse de uma **única expressão** (ex.: célula de regra).
|
|
46
|
+
* Entra direto na gramática de expressão — então `{ … }` é objeto, não bloco.
|
|
47
|
+
*/
|
|
48
|
+
declare function parseExpression(source: string): types.Expression;
|
|
49
|
+
|
|
50
|
+
export { KEYWORDS, LexError, ParseError, type ParserErrorCode, type Position, type SourceLocation, type Token, type TokenType, parse, parseExpression, tokenize };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { TSLiteError, types } from '@tslite/core';
|
|
2
|
+
|
|
3
|
+
/** Code dos erros lançados pelo parser/tokenizer. */
|
|
4
|
+
type ParserErrorCode = "lex-error" | "parse-error";
|
|
5
|
+
/** Posição num ponto da fonte (linha 1-based, coluna 0-based). */
|
|
6
|
+
interface Position {
|
|
7
|
+
readonly line: number;
|
|
8
|
+
readonly column: number;
|
|
9
|
+
}
|
|
10
|
+
/** Intervalo de posições de um token/nó. */
|
|
11
|
+
interface SourceLocation {
|
|
12
|
+
readonly start: Position;
|
|
13
|
+
readonly end: Position;
|
|
14
|
+
}
|
|
15
|
+
type TokenType = "Identifier" | "Keyword" | "Number" | "String" | "Template" | "TemplateHead" | "TemplateMiddle" | "TemplateTail" | "Punctuator" | "EOF";
|
|
16
|
+
interface Token {
|
|
17
|
+
readonly type: TokenType;
|
|
18
|
+
/** O lexema cru, como aparece na fonte (sem decodificar escapes). */
|
|
19
|
+
readonly value: string;
|
|
20
|
+
/** Offset absoluto de início (inclusivo) e fim (exclusivo). */
|
|
21
|
+
readonly start: number;
|
|
22
|
+
readonly end: number;
|
|
23
|
+
readonly loc: SourceLocation;
|
|
24
|
+
}
|
|
25
|
+
/** Erro de léxico, com a posição onde ocorreu. */
|
|
26
|
+
declare class LexError extends TSLiteError<"lex-error"> {
|
|
27
|
+
readonly position: Position;
|
|
28
|
+
readonly index: number;
|
|
29
|
+
constructor(message: string, position: Position, index: number);
|
|
30
|
+
}
|
|
31
|
+
/** Palavras reservadas. As permitidas e as proibidas — o parser decide. */
|
|
32
|
+
declare const KEYWORDS: Set<string>;
|
|
33
|
+
/** Tokeniza a fonte. Devolve a lista de tokens, terminada por um `EOF`. */
|
|
34
|
+
declare function tokenize(source: string): Token[];
|
|
35
|
+
|
|
36
|
+
/** Erro de sintaxe, com a posição onde ocorreu. */
|
|
37
|
+
declare class ParseError extends TSLiteError<"parse-error"> {
|
|
38
|
+
readonly position: Position;
|
|
39
|
+
readonly index: number;
|
|
40
|
+
constructor(message: string, position: Position, index: number);
|
|
41
|
+
}
|
|
42
|
+
/** Faz o parse de uma fonte completa num `Program` (ESTree, com `loc`). */
|
|
43
|
+
declare function parse(source: string): types.Program;
|
|
44
|
+
/**
|
|
45
|
+
* Conveniência: faz o parse de uma **única expressão** (ex.: célula de regra).
|
|
46
|
+
* Entra direto na gramática de expressão — então `{ … }` é objeto, não bloco.
|
|
47
|
+
*/
|
|
48
|
+
declare function parseExpression(source: string): types.Expression;
|
|
49
|
+
|
|
50
|
+
export { KEYWORDS, LexError, ParseError, type ParserErrorCode, type Position, type SourceLocation, type Token, type TokenType, parse, parseExpression, tokenize };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import {TSLiteError}from'@tslite/core';var $=class extends TSLiteError{constructor(p,i,r){super("lex-error",`${p} (${i.line}:${i.column})`,{position:i,index:r});this.position=i;this.index=r;this.name="LexError";}},G=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"]),ve=["...","===","!==","=>","|>","?.","??","==","!=","<=",">=","&&","||","|","++","--","+=","-=","*=","/=","%=","+","-","*","/","%","<",">","!","?",":",".",",",";","=","(",")","[","]","{","}"],_=f=>f>="a"&&f<="z"||f>="A"&&f<="Z"||f==="_"||f==="$",be=f=>_(f)||f>="0"&&f<="9",F=f=>f>="0"&&f<="9",H=f=>F(f)||f>="a"&&f<="f"||f>="A"&&f<="F";function z(f){let x=[],p=0,i=1,r=0,b=()=>({line:i,column:r}),u=(l=0)=>f[p+l]??"",a=l=>{throw new $(l,b(),p)},s=()=>{let l=f[p++];return l==="\r"?(f[p]===`
|
|
2
|
+
`&&p++,i++,r=0):l===`
|
|
3
|
+
`||l==="\u2028"||l==="\u2029"?(i++,r=0):r++,l},w=l=>l===`
|
|
4
|
+
`||l==="\r"||l==="\u2028"||l==="\u2029",y=()=>{for(;;){let l=u();if(l===" "||l===" "||l==="\f"||l==="\v"||w(l))s();else if(l==="/"&&u(1)==="/")for(;p<f.length&&!w(u());)s();else if(l==="/"&&u(1)==="*")for(s(),s();;){if(p>=f.length&&a("Unterminated block comment"),u()==="*"&&u(1)==="/"){s(),s();break}s();}else break}},h=(l,m,N,k)=>{x.push({type:l,value:m,start:N,end:p,loc:{start:k,end:b()}});},c=l=>{for(s();p<f.length;){let m=u();if(m===l)return s(),f.slice(S,p);if(w(m)&&a("Unterminated string literal"),m==="\\"){s(),p>=f.length&&a("Unterminated string literal"),s();continue}s();}return a("Unterminated string literal")},L=()=>{if(u()==="0"&&(u(1)==="x"||u(1)==="X")){for(s(),s(),H(u())||a("Invalid hexadecimal literal");H(u());)s();return}if(u()==="0"&&(u(1)==="b"||u(1)==="B")){for(s(),s(),u()!=="0"&&u()!=="1"&&a("Invalid binary literal");u()==="0"||u()==="1";)s();return}if(u()==="0"&&(u(1)==="o"||u(1)==="O")){for(s(),s(),u()>="0"&&u()<="7"||a("Invalid octal literal");u()>="0"&&u()<="7";)s();return}for(;F(u());)s();if(u()===".")for(s();F(u());)s();if(u()==="e"||u()==="E")for(s(),(u()==="+"||u()==="-")&&s(),F(u())||a("Invalid exponent");F(u());)s();},g=()=>{let l=p;for(;p<f.length;){let m=u();if(m==="`"){let N=f.slice(l,p);return s(),{raw:N,interp:false}}if(m==="$"&&u(1)==="{"){let N=f.slice(l,p);return s(),s(),{raw:N,interp:true}}if(m==="\\"){if(s(),p>=f.length)break;s();continue}s();}return a("Unterminated template literal")},S=0,v=0,d=[];for(;;){y(),S=p;let l=b();if(p>=f.length){h("EOF","",S,l);break}let m=u();if(_(m)){for(;be(u());)s();let k=f.slice(S,p);h(G.has(k)?"Keyword":"Identifier",k,S,l);continue}if(F(m)||m==="."&&F(u(1))){L(),h("Number",f.slice(S,p),S,l);continue}if(m==='"'||m==="'"){let k=c(m);h("String",k,S,l);continue}if(m==="`"){s();let{raw:k,interp:O}=g();O?(h("TemplateHead",k,S,l),d.push(v)):h("Template",k,S,l);continue}if(m==="{"){s(),h("Punctuator","{",S,l),v++;continue}if(m==="}"){if(d.length>0&&v===d[d.length-1]){d.pop(),s();let{raw:k,interp:O}=g();h(O?"TemplateMiddle":"TemplateTail",k,S,l),O&&d.push(v);continue}s(),h("Punctuator","}",S,l),v--;continue}if(m==="?"&&u(1)==="."&&F(u(2))){s(),h("Punctuator","?",S,l);continue}let N=ve.find(k=>f.startsWith(k,p));if(N){for(let k=0;k<N.length;k++)s();h("Punctuator",N,S,l);continue}a(`Unexpected character '${m}'`);}return x}var Y=f=>{let{peek:x,next:p,isP:i,isK:r,expectP:b,fail:u,unescape:a}=f,s=()=>{let v=0;for(let d=f.pos();d<f.tokens.length;d++){let l=f.tokens[d];if(l.type==="EOF")return false;if(l.type==="Punctuator"){if(["(","[","{","<"].includes(l.value))v++;else if([")","]","}",">"].includes(l.value)&&(v--,v===0)){let m=f.tokens[d+1];return !!m&&m.type==="Punctuator"&&m.value==="=>"}}}return false},w=()=>{b("<");let v=[];for(;!i(">");){let d=x();d.type!=="Identifier"&&u("Expected type parameter name"),p(),v.push(d.value),i(">")||b(",");}return b(">"),v},y=v=>{b("<");let d=[];for(;!i(">");)d.push(h(v)),i(">")||b(",");return b(">"),d},h=v=>{let d=c(v);if(!i("|"))return d;let l=[d];for(;i("|");)p(),l.push(c(v));return {t:"union",of:l}},c=v=>{let d=L(v);for(;i("[")&&x(1).type==="Punctuator"&&x(1).value==="]";)p(),p(),d={t:"array",items:d};return d},L=v=>{if(i("<")){let l=w(),m=new Set(v);return l.forEach(N=>m.add(N)),g(m)}if(i("(")){if(s())return g(v);p();let l=h(v);return b(")"),l}if(i("{"))return S(v);let d=x();if(d.type==="String")return p(),{t:"literal",value:a(d.value.slice(1,-1))};if(d.type==="Number")return p(),{t:"literal",value:Number(d.value)};if(r("true"))return p(),{t:"literal",value:true};if(r("false"))return p(),{t:"literal",value:false};if(r("null"))return p(),{t:"null"};if(d.type==="Identifier"){switch(p(),d.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"}}let l=i("<")?y(v):[];return v.has(d.value)&&l.length===0?{t:"var",name:d.value}:{t:"apply",name:d.value,args:l}}return u(`Expected a type but got '${d.value||d.type}'`)},g=v=>{b("(");let d=[];for(;!i(")");){let m=x();m.type!=="Identifier"&&u("Expected parameter name in function type"),p();let N=i("?");N&&p(),b(":");let k=h(v);d.push({name:m.value,type:k,...N?{optional:true}:{}}),i(")")||b(",");}b(")"),b("=>");let l=h(v);return {t:"fn",params:d,returns:l}},S=v=>{b("{");let d={};for(;!i("}");){let l=x(),m;if(l.type==="Identifier"||l.type==="Keyword")p(),m=l.value;else if(l.type==="String")p(),m=a(l.value.slice(1,-1));else return u("Expected property name in object type");let N=i("?");N&&p(),b(":");let k=h(v);if(d[m]={type:k,...N?{optional:true}:{}},i(";")||i(","))p();else break}return b("}"),{t:"object",props:d}};return {parseType:h,parseTypeParamList:w}};var M=class extends TSLiteError{constructor(p,i,r){super("parse-error",`${p} (${i.line}:${i.column})`,{position:i,index:r});this.position=i;this.index=r;this.name="ParseError";}},xe={"??":1,"||":2,"&&":3,"==":4,"===":4,"!=":4,"!==":4,"<":5,"<=":5,">":5,">=":5,"+":6,"-":6,"*":7,"/":7,"%":7},ke=new Set(["??","||","&&"]),Te=new Set(["class","import","export","debugger","with"]),Se=new Set(["=","+=","-=","*=","/=","%="]);function X(f){let x=z(f),p=0,i=(e=0)=>x[Math.min(p+e,x.length-1)],r=()=>x[p++],b=()=>x[p-1],u=()=>i().type==="EOF",a=e=>i().type==="Punctuator"&&i().value===e,s=e=>i().type==="Keyword"&&i().value===e,w=(e,n=i())=>{throw new M(e,n.loc.start,n.start)},y=e=>(a(e)||w(`Expected '${e}' but got '${i().value||i().type}'`),r()),h=(e,n)=>{let t=b()??n;return Object.assign(e,{start:n.start,end:t.end,loc:{start:n.loc.start,end:t.loc.end}})},c=(e,n,t)=>Object.assign(e,{start:n.start,end:t.end,loc:{start:n.loc.start,end:t.loc.end}}),L=e=>{let n="";for(let t=0;t<e.length;t++){if(e[t]!=="\\"){n+=e[t];continue}let o=e[++t];switch(o){case "n":n+=`
|
|
5
|
+
`;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 T=e.indexOf("}",t);n+=String.fromCodePoint(parseInt(e.slice(t+2,T),16)),t=T;}else n+=String.fromCharCode(parseInt(e.slice(t+1,t+5),16)),t+=4;break;default:n+=o;}}return n},g=()=>S(),S=()=>{let e=v(),n=i();if(n.type==="Punctuator"&&Se.has(n.value)){r();let t=S();return c({type:"AssignmentExpression",operator:n.value,left:e,right:t},e,t)}return e},v=()=>{let e=d();for(;a("|>");){r();let n=d();e=c({type:"CallExpression",callee:n,arguments:[e],optional:false},e,n);}return e},d=()=>{let e=l(0);if(!a("?"))return e;r();let n=g();y(":");let t=g();return c({type:"ConditionalExpression",test:e,consequent:n,alternate:t},e,t)},l=e=>{let n=m();for(;;){let t=i();if(t.type!=="Punctuator")break;let o=xe[t.value];if(!o||o<=e)break;r();let T=l(o);n=c({type:ke.has(t.value)?"LogicalExpression":"BinaryExpression",operator:t.value,left:n,right:T},n,T);}return n},m=()=>{let e=i();return e.type==="Punctuator"&&(e.value==="++"||e.value==="--")?(r(),h({type:"UpdateExpression",operator:e.value,prefix:true,argument:m()},e)):s("await")?(r(),h({type:"AwaitExpression",argument:m()},e)):s("typeof")||s("void")||s("delete")?(r(),h({type:"UnaryExpression",operator:e.value,prefix:true,argument:m()},e)):e.type==="Punctuator"&&(e.value==="!"||e.value==="-"||e.value==="+")?(r(),h({type:"UnaryExpression",operator:e.value,prefix:true,argument:m()},e)):N()},N=()=>{let e=k();for(;i().type==="Identifier"&&i().value==="as";){r();let n=D(new Set);e=c({type:"TSAsExpression",expression:e,typeAnnotation:n},e,b());}return e},k=()=>{let e=W(),n=false;for(;;)if(a("?."))if(r(),n=true,a("(")){let{args:t,close:o}=O();e=c({type:"CallExpression",callee:e,arguments:t,optional:true},e,o);}else if(a("[")){r();let t=g(),o=y("]");e=c({type:"MemberExpression",object:e,property:t,computed:true,optional:true},e,o);}else {let t=i();t.type!=="Identifier"&&t.type!=="Keyword"&&w("Expected property name after '?.'"),r();let o=h({type:"Identifier",name:t.value},t);e=c({type:"MemberExpression",object:e,property:o,computed:false,optional:true},e,o);}else if(a(".")){r();let t=i();t.type!=="Identifier"&&t.type!=="Keyword"&&w("Expected property name"),r();let o=h({type:"Identifier",name:t.value},t);e=c({type:"MemberExpression",object:e,property:o,computed:false,optional:false},e,o);}else if(a("[")){r();let t=g(),o=y("]");e=c({type:"MemberExpression",object:e,property:t,computed:true,optional:false},e,o);}else if(a("(")){let{args:t,close:o}=O();e=c({type:"CallExpression",callee:e,arguments:t,optional:false},e,o);}else if(a("++")||a("--")){let t=r();e=c({type:"UpdateExpression",operator:t.value,prefix:false,argument:e},e,t);}else break;return n?c({type:"ChainExpression",expression:e},e,e):e},O=()=>{y("(");let e=[];for(;!a(")");)e.push(V()),a(")")||y(",");return {args:e,close:y(")")}},V=()=>{if(a("...")){let e=r(),n=g();return c({type:"SpreadElement",argument:n},e,n)}return g()},j=()=>{let e=i();return e.type!=="Identifier"&&w("Expected identifier"),r(),h({type:"Identifier",name:e.value},e)},Z=()=>{let e=0;for(let n=p;n<x.length;n++){let t=x[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 o=x[n+1];return !o||o.type!=="Punctuator"?false:o.value==="=>"?true:o.value===":"?J(n+2):false}}}return false},J=e=>{let n=0;for(let t=e;t<x.length;t++){let o=x[t];if(o.type==="EOF")return false;if(o.type==="Punctuator")if(["(","[","{","<"].includes(o.value))n++;else if([")","]","}",">"].includes(o.value)){if(n===0)return false;n--;}else {if(n===0&&o.value==="=>")return true;if(n===0&&(o.value===";"||o.value===","))return false}}return false},Q=(e=new Set)=>{y("(");let n=[];for(;!a(")");){if(a("...")){let t=r(),o=j();a(":")&&(r(),o.typeAnnotation=D(e)),n.push(c({type:"RestElement",argument:o},t,o));}else {let t=j();a(":")&&(r(),t.typeAnnotation=D(e)),n.push(t);}a(")")||y(",");}return y(")"),n},R=(e,n)=>{let t=a("(")?Q():[j()],o;a(":")&&(r(),o=D(new Set)),y("=>");let T=a("{")?K():g();return h({type:"ArrowFunctionExpression",params:t,body:T,async:e,expression:T.type!=="BlockStatement",generator:false,...o?{returnType:o}:{}},n)},ee=()=>{let e=y("["),n=[];for(;!a("]");){if(a(",")){r(),n.push(null);continue}n.push(V()),a("]")||y(",");}return c({type:"ArrayExpression",elements:n},e,y("]"))},te=()=>{let e=y("{"),n=[];for(;!a("}");){if(a("...")){let t=r(),o=g();n.push(c({type:"SpreadElement",argument:o},t,o));}else {let t=i(),o,T=false;if(a("["))T=true,r(),o=g(),y("]");else if(t.type==="String")r(),o=h({type:"Literal",value:L(t.value.slice(1,-1)),raw:t.value},t);else if(t.type==="Number")r(),o=h({type:"Literal",value:Number(t.value),raw:t.value},t);else if(t.type==="Identifier"||t.type==="Keyword")r(),o=h({type:"Identifier",name:t.value},t);else return w("Invalid property key");if(a(":")){r();let P=g();n.push(c({type:"Property",key:o,value:P,kind:"init",method:false,shorthand:false,computed:T},t,P));}else n.push(c({type:"Property",key:o,value:o,kind:"init",method:false,shorthand:true,computed:false},t,o));}a("}")||y(",");}return c({type:"ObjectExpression",properties:n},e,y("}"))},U=(e,n)=>({type:"TemplateElement",value:{raw:e,cooked:L(e)},tail:n}),ne=e=>{r();let n=[U(e.value,false)],t=[];for(;;){t.push(g());let o=i();if(o.type==="TemplateMiddle")r(),n.push(U(o.value,false));else if(o.type==="TemplateTail"){r(),n.push(U(o.value,true));break}else w("Expected `}` to close template interpolation");}return h({type:"TemplateLiteral",quasis:n,expressions:t},e)},W=()=>{let e=i();if(s("async")){let n=i(1);return n.value==="("||n.type==="Identifier"?(r(),R(true,e)):w("Unexpected 'async'")}if(a("(")&&Z()||e.type==="Identifier"&&i(1).type==="Punctuator"&&i(1).value==="=>")return R(false,e);if(e.type==="Number")return r(),h({type:"Literal",value:Number(e.value),raw:e.value},e);if(e.type==="String")return r(),h({type:"Literal",value:L(e.value.slice(1,-1)),raw:e.value},e);if(e.type==="Template")return r(),h({type:"TemplateLiteral",expressions:[],quasis:[U(e.value,true)]},e);if(e.type==="TemplateHead")return ne(e);if(e.type==="Keyword")return e.value==="true"?(r(),h({type:"Literal",value:true,raw:"true"},e)):e.value==="false"?(r(),h({type:"Literal",value:false,raw:"false"},e)):e.value==="null"?(r(),h({type:"Literal",value:null,raw:"null"},e)):e.value==="new"?re(e):e.value==="function"?w("Anonymous functions are not supported \u2014 use an arrow function"):w(`'${e.value}' is not supported in this language`);if(e.type==="Identifier")return r(),h({type:"Identifier",name:e.value},e);if(a("(")){r();let n=g();return y(")"),n}return a("[")?ee():a("{")?te():w(`Unexpected token '${e.value||e.type}'`)},re=e=>{r();let n=W();for(;;)if(a(".")){r();let t=i();t.type!=="Identifier"&&t.type!=="Keyword"&&w("Expected property name"),r();let o=h({type:"Identifier",name:t.value},t);n=c({type:"MemberExpression",object:n,property:o,computed:false,optional:false},n,o);}else if(a("[")){r();let t=g(),o=y("]");n=c({type:"MemberExpression",object:n,property:t,computed:true,optional:false},n,o);}else break;if(a("(")){let{args:t,close:o}=O();return c({type:"NewExpression",callee:n,arguments:t},e,o)}return c({type:"NewExpression",callee:n,arguments:[]},e,n)},{parseType:D,parseTypeParamList:oe}=Y({tokens:x,pos:()=>p,peek:i,next:r,isP:a,isK:s,expectP:y,fail:w,unescape:L}),se=()=>{let e=r(),n=j(),t=new Set,o=[];a("<")&&(o=oe(),o.forEach(E=>t.add(E))),y("=");let T=D(t),P=c({type:"TSTypeAliasDeclaration",id:n,typeParameters:o,typeAnnotation:T},e,b());return a(";")&&r(),P},C=()=>{let e=i();if(e.type==="Identifier"&&e.value==="type"&&i(1).type==="Identifier"&&i(2).type==="Punctuator"&&(i(2).value==="="||i(2).value==="<"))return se();if(s("const")||s("let")||s("var")){let o=ae();return a(";")&&r(),o}if(s("if"))return ce();if(s("for"))return ie();if(s("while"))return pe();if(s("do"))return le();if(s("break")||s("continue"))return ue();if(s("return"))return fe();if(s("throw"))return de();if(s("try"))return ye();if(s("switch"))return me();if(a("{"))return K();if((s("function")||s("async")&&i(1).type==="Keyword"&&i(1).value==="function")&&w("Function declarations are not supported \u2014 use 'const fn = () => \u2026'"),a(";"))return r(),h({type:"EmptyStatement"},e);e.type==="Keyword"&&Te.has(e.value)&&w(`'${e.value}' is not supported in this language`);let n=g(),t=a(";")?r():b();return c({type:"ExpressionStatement",expression:n},n,t)},ae=()=>{let e=r(),n=e.value,t=j();a(":")&&(r(),t.typeAnnotation=D(new Set));let o=null;a("=")?(r(),o=g()):n==="const"&&w("'const' declarations must be initialized");let T=c({type:"VariableDeclarator",id:t,init:o},t,o??t);return c({type:"VariableDeclaration",kind:n,declarations:[T]},e,o??t)},q=()=>i().type==="Identifier"&&i().value==="of",B=()=>s("in"),ie=()=>{let e=r();y("(");let n=null,t=null;if(!a(";"))if(s("const")||s("let")||s("var")){let E=r(),I=j();if(a(":")&&(r(),I.typeAnnotation=D(new Set)),q()||B()){let A=c({type:"VariableDeclarator",id:I,init:null},I,I);t=c({type:"VariableDeclaration",kind:E.value,declarations:[A]},E,I);}else {let A=null;a("=")?(r(),A=g()):E.value==="const"&&w("'const' declarations must be initialized");let he=c({type:"VariableDeclarator",id:I,init:A},I,A??I);n=c({type:"VariableDeclaration",kind:E.value,declarations:[he]},E,A??I);}}else {let E=g();q()||B()?t=E:n=E;}if(t){let E=B();r();let I=g();y(")");let A=C();return c(E?{type:"ForInStatement",left:t,right:I,body:A}:{type:"ForOfStatement",left:t,right:I,body:A,await:false},e,A)}y(";");let o=a(";")?null:g();y(";");let T=a(")")?null:g();y(")");let P=C();return c({type:"ForStatement",init:n,test:o,update:T,body:P},e,P)},le=()=>{let e=r(),n=C();s("while")||w("Expected 'while' after the 'do' body"),r(),y("(");let t=g(),o=y(")");return a(";")&&r(),c({type:"DoWhileStatement",body:n,test:t},e,o)},ue=()=>{let e=r(),n=e.value==="break"?"BreakStatement":"ContinueStatement",t=a(";")?r():b();return c({type:n,label:null},e,t)},pe=()=>{let e=r();y("(");let n=g();y(")");let t=C();return c({type:"WhileStatement",test:n,body:t},e,t)},ce=()=>{let e=r();y("(");let n=g();y(")");let t=C(),o=null;return s("else")&&(r(),o=C()),c({type:"IfStatement",test:n,consequent:t,alternate:o},e,o??t)},fe=()=>{let e=r(),n=null;!a(";")&&!a("}")&&!u()&&(n=g());let t=a(";")?r():b();return c({type:"ReturnStatement",argument:n},e,t)},de=()=>{let e=r(),n=g(),t=a(";")?r():b();return c({type:"ThrowStatement",argument:n},e,t)},ye=()=>{let e=r(),n=K(),t=null,o=null;if(s("catch")){let T=r(),P=null;a("(")&&(r(),P=j(),y(")"));let E=K();t=c({type:"CatchClause",param:P,body:E},T,E);}return s("finally")&&(r(),o=K()),!t&&!o&&w("'try' requires a 'catch' or 'finally' clause"),c({type:"TryStatement",block:n,handler:t,finalizer:o},e,o??t??n)},me=()=>{let e=r();y("(");let n=g();y(")"),y("{");let t=[];for(;!a("}")&&!u();){let T=i(),P=null;s("case")?(r(),P=g()):s("default")?r():w("Expected 'case' or 'default' in switch"),y(":");let E=[];for(;!a("}")&&!s("case")&&!s("default")&&!u();)E.push(C());t.push(c({type:"SwitchCase",test:P,consequent:E},T,b()??T));}let o=y("}");return c({type:"SwitchStatement",discriminant:n,cases:t},e,o)},K=()=>{let e=y("{"),n=[];for(;!a("}")&&!u();)n.push(C());return c({type:"BlockStatement",body:n},e,y("}"))};return {parseExpr:g,parseProgram:()=>{let e=i(),n=[];for(;!u();)n.push(C());return c({type:"Program",sourceType:"module",body:n},e,b()??e)},eof:u,fail:w}}function Ne(f){return X(f).parseProgram()}function Ee(f){let{parseExpr:x,eof:p,fail:i}=X(f),r=x();return p()||i("Unexpected token after expression"),r}export{G as KEYWORDS,$ as LexError,M as ParseError,Ne as parse,Ee as parseExpression,z as tokenize};
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tslite/parser",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TSLite parser — tokenizer + Pratt parser for the TSLite language (JS subset + pipe) into ESTree",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/andersondrosa/tslite.git",
|
|
26
|
+
"directory": "packages/parser"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"ast",
|
|
30
|
+
"estree",
|
|
31
|
+
"tokenizer",
|
|
32
|
+
"lexer",
|
|
33
|
+
"parser",
|
|
34
|
+
"pratt",
|
|
35
|
+
"typescript"
|
|
36
|
+
],
|
|
37
|
+
"author": "Anderson D. Rosa <andersondrosa@outlook.com>",
|
|
38
|
+
"license": "MIT",
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@tslite/core": "0.1.0"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@tslite/checker": "0.1.0",
|
|
47
|
+
"@tslite/capability": "0.1.0",
|
|
48
|
+
"@tslite/printer": "0.1.0",
|
|
49
|
+
"@tslite/interpret": "0.1.0"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsup",
|
|
53
|
+
"dev": "tsup --watch",
|
|
54
|
+
"test": "vitest run",
|
|
55
|
+
"test:watch": "vitest",
|
|
56
|
+
"test:coverage": "vitest run --coverage",
|
|
57
|
+
"typecheck": "tsc --noEmit",
|
|
58
|
+
"lint": "eslint src tests",
|
|
59
|
+
"lint:fix": "eslint src tests --fix",
|
|
60
|
+
"clean": "rm -rf dist",
|
|
61
|
+
"format": "prettier --write \"src/**/*.ts\"",
|
|
62
|
+
"format:check": "prettier --check \"src/**/*.ts\""
|
|
63
|
+
}
|
|
64
|
+
}
|