@gyro-lang/core
Version:
Fast, Performant and scalable programming language designed for string manipulation and deep recursion.
1 lines • 8.9 kB
JavaScript
var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{qA:()=>u,bp:()=>c,AV:()=>r,qd:()=>n,Cr:()=>o,ku:()=>a,Qc:()=>s});class r{constructor(e){this.input=e,this.pos=0,this.line=1,this.col=0}next(){var e=this.input.charAt(this.pos++);return"\n"==e?(this.line++,this.col=0):this.col++,e}peek(e=0){return this.input.charAt(this.pos+e)}eof(){return""==this.peek()}reset(){this.pos=0,this.line=0,this.col=0}croak(e){console.error(e+" ("+this.line+":"+this.col+")")}}class n{constructor(e){this.stream=e,this.KEYWORDS=["if","else","while","let","const","func","then","for","import","export","from","in","do"]}isKeyword(e){return this.KEYWORDS.indexOf(e)>=0}isDigit(e){return/[0-9]/i.test(e)}isIdentifierStart(e){return/[a-z_]/i.test(e)}isIdentifier(e){return this.isIdentifierStart(e)||"?!<>0123456789".indexOf(e)>=0}isOperatorChar(e){return["+","-","*","/","%","=","&","|","<",">",":","!","~"].indexOf(e)>=0}isPunctuation(e){return",;(){}[]".indexOf(e)>=0}isWhitespace(e){return" \t\n".indexOf(e)>=0}readWhile(e){for(var t="";!this.stream.eof()&&e(this.stream.peek());)t+=this.stream.next();return t}readNumber(){var e=!1,t=this.readWhile((t=>"."==t?!e&&(e=!0,!0):this.isDigit(t)));return{type:"number",value:parseFloat(t)}}readIdentifier(){var e=this.readWhile(this.isIdentifier.bind(this));return{type:this.isKeyword(e)?"keyword":"identifier",value:e}}readEscaped(e){var t=!1,r="";for(this.stream.next();!this.stream.eof();){var n=this.stream.next();if(t)r+=n,t=!1;else if("\\"==n)t=!0;else{if(n==e)break;r+=n}}return r}readString(){return{type:"string",value:this.readEscaped('"')}}skipComment(){this.readWhile((function(e){return"\n"!=e})),this.stream.next()}readNext(){if(this.readWhile(this.isWhitespace),this.stream.eof())return null;var e=this.stream.peek();return"#"==e?(this.skipComment(),this.readNext()):'"'==e?this.readString():this.isDigit(e)?this.readNumber():this.isIdentifierStart(e)?this.readIdentifier():this.isPunctuation(e)?{type:"punctuation",value:this.stream.next()}:this.isOperatorChar(e)?{type:"operator",value:this.readWhile(this.isOperatorChar)}:void this.stream.croak("Can't handle character: "+e)}peek(){return this.current||(this.current=this.readNext())}next(){var e=this.current;return this.current=null,e||this.readNext()}eof(){return null==this.peek()}croak(e){this.stream.croak(e)}all(){for(var e=[];!this.eof();)e.push(this.next());return e}}var i={type:"bool",value:!1};function s(e){var t={":":1,"=":2,"||":3,"&&":4,"<":7,">":7,"<=":7,">=":7,"==":7,"!=":7,"+=":7,"+":10,"-":10,"*":20,"/":20,"%":20,"**":30};return function(){for(var t=[];!e.eof();)t.push(l()),e.eof()||s(";");return{type:"Program",body:t}}();function r(t){var r=e.peek();return r&&"punctuation"==r.type&&(!t||r.value==t)&&r}function n(t){var r=e.peek();return r&&"keyword"==r.type&&(!t||r.value==t)&&r}function s(t){r(t)?e.next():e.croak('Expecting punctuation: "'+t+'"')}function a(t){n(t)?e.next():e.croak('Expecting keyword: "'+t+'"')}function o(r,n){var i=function(t){var r=e.peek();return r&&"operator"==r.type&&(!t||r.value==t)&&r}();if(i){var s=t[i.value];if(s>n||void 0===s)return e.next(),o({type:{"=":"AssignmentExpression",":":"TypeExpression","~":"ObjectAccessor"}[i.value]||"BinaryExpression",operator:i.value,left:r,right:o(f(),s)},n)}return r}function u(t,n,i,a){var o=[],u=!0;for(s(t);!e.eof()&&!r(n)&&(u?u=!1:s(i),!r(n));)o.push(a());return s(n),o}function c(e){return e=e(),r("(")?{type:"CallExpression",callee:e,args:u("(",")",",",l)}:e}function f(){return c((function(){if(r("(")){e.next();var t=l();return s(")"),t}if(r("{"))return 0==(o=u("{","}",";",l)).length?i:1==o.length?o[0]:{type:"Program",body:o};var o;if(n("if"))return function(){a("if");var t=l();r("{")||a("then");var i={type:"if",cond:t,then:l()};return n("else")&&(e.next(),i.else=l()),i}();if(n("for"))return function(){a("for");var e=l();a("in");var t=l();return r("{")||a("do"),{type:"ForInStatement",left:e,right:t,body:l()}}();if(r("["))return{type:"ArrayExpression",elements:u("[","]",",",f)};if(n("true")||n("false"))return{type:"bool",value:"true"==e.next().value};if(n("func"))return e.next(),{type:"FunctionDeclaration",vars:u("(",")",",",l),body:l()};var c=e.next();if("identifier"==c.type||"number"==c.type||"string"==c.type)return c;e.croak("Unexpected token: "+JSON.stringify(e.peek()))}))}function l(){return c((function(){return o(f(),0)}))}}function a(e,t){switch(e.type){case"number":case"string":case"boolean":case"TypeExpression":return e.value;case"identifier":return t.get(e.value);case"AssignmentExpression":if("identifier"!=e.left.type){if("TypeExpression"==e.left.type)return t.def(e.left.left.value,a(e.right,t));throw new Error("Cannot assign to "+JSON.stringify(e.left)+"with missing type")}return t.def(e.left.value,a(e.right,t));case"BinaryExpression":return function(e,t,r){function n(e){if("number"!=typeof e)throw new Error("Expected number but got "+e);return e}function i(e){if(0==n(e))throw new Error("Divide by zero");return e}switch(e){case"+":return n(t)+n(r);case"-":return n(t)-n(r);case"*":return n(t)*n(r);case"/":return n(t)/i(r);case"%":return n(t)%i(r);case"&&":return!1!==t&&r;case"||":return!1!==t?t:r;case"<":return n(t)<n(r);case">":return n(t)>n(r);case"<=":return n(t)<=n(r);case">=":return n(t)>=n(r);case"==":return t===r;case"!=":return t!==r;case"**":return Math.pow(t,r)}throw new Error("Can't apply operator "+e)}(e.operator,a(e.left,t),a(e.right,t));case"ForInStatement":return function(e,t){let r=e.extend(),n=t.left.value,i=a(t.right,e);if("number"==typeof i)for(let e=0;e<i;e++)r.def(n,e),a(t.body,r);else if(Array.isArray(i))for(const e of i)r.def(n,e),a(t.body,r);else for(const e in i)r.def(n,e),a(t.body,r)}(t,e);case"FunctionDeclaration":return function(e,t){return function(){for(var r=t.vars,n=e.extend(),i=0;i<r.length;++i)"TypeExpression"==r[i].type?n.def(r[i].left.value,i<arguments.length&&arguments[i]):n.def(r[i].value,i<arguments.length&&arguments[i]);return a(t.body,n)}}(t,e);case"if":return!1!==a(e.cond,t)?a(e.then,t):!!e.else&&a(e.else,t);case"Program":var r=!1;return e.body.forEach((function(e){r=a(e,t)})),r;case"CallExpression":return a(e.callee,t).apply(null,e.args.map((function(e){return a(e,t)})));case"ObjectAccessor":return a(e.left,t)[a(e.right,t)];case"ArrayExpression":return e.elements.map((function(e){return a(e,t)}));default:throw new Error("I don't know how to evaluate "+e.type)}}function o(e){return"const print = (...args) => console.log(...args);"+t(e);function t(e){switch(e.type){case"number":case"string":case"boolean":return function(e){return JSON.stringify(e.value)}(e);case"ArrayExpression":return function(e){return"["+e.elements.map(t).join(", ")+"]"}(e);case"identifier":return function(e){return e.value}(e);case"BinaryExpression":return n(e);case"AssignmentExpression":return function(e){return n(e)}(e);case"let":return function(e){return 0==e.vars.length?t(e.body):"("+t({type:"call",func:{type:"lambda",vars:[e.vars[0].name],body:{type:"let",vars:e.vars.slice(1),body:e.body}},args:[e.vars[0].def||!1]})+")"}(e);case"FunctionDeclaration":return function(e){var n="(function ";return e.name&&(n+=e.name),(n+="("+e.vars.map(r).join(", ")+") {")+"return "+t(e.body)+" })"}(e);case"if":return function(e){return"("+t(e.cond)+" !== false ? "+t(e.then)+" : "+t(e.else||!1)+")"}(e);case"Program":return function(e){return"("+e.body.map(t).join(", ")+")"}(e);case"CallExpression":return function(e){return t(e.callee)+"("+e.args.map(t).join(", ")+")"}(e);case"ForInStatement":return function(e){return t(e.right).startsWith("{")?`for (let ${t(e.left)} in ${t(e.right)}) {\n\t\t\t\t${t(e.body)}\n\t\t\t}`:t(e.right).startsWith("[")?`for (let ${t(e.left)} of ${t(e.right)}) {\n\t\t\t\t${t(e.body)}\n\t\t\t}`:`for (let ${t(e.left)} = 0; ${t(e.left)} < ${t(e.right)}; ${t(e.left)}++) {\n\t\t\t\t${t(e.body)}\n\t\t\t}`}(e);default:throw new Error("Transpilation failed for: "+JSON.stringify(e))}}function r(e){return e}function n(e){return"("+t(e.left)+e.operator+t(e.right)+")"}}class u{constructor(e){this.vars=Object.create(e?e.vars:null),this.parent=e}extend(){return new u(this)}lookup(e){for(var t=this;t;){if(Object.prototype.hasOwnProperty.call(t.vars,e))return t;t=t.parent}}get(e){if(e in this.vars)return this.vars[e];throw new Error("Undefined variable "+e)}set(e,t){var r=this.lookup(e);if(!r&&this.parent)throw new Error("Undefined variable "+e);return(r||this).vars[e]=t}def(e,t){return this.vars[e]=t}}const c={evaluate(e,t=new u(null)){const i=new r(e);return a(s(new n(i)),t)},evaluateAST:(e,t=new u(null))=>a(e,t),parse(e){const t=new r(e);return s(new n(t))},tokenize(e){const t=new r(e);return new n(t).all()}};var f=t.qA,l=t.bp,h=t.AV,p=t.qd,d=t.Cr,v=t.ku,y=t.Qc;export{f as Environment,l as Gyro,h as InputStream,p as TokenStream,d as compileJS,v as evaluate,y as parse};