Skip to content

Topppy/js-interpreter

Repository files navigation

js 解释器 demo

背景: 业务上陆续搞了几个在线编程游戏,涉及 python、C++、blockly,核心都是的 web 在线将其他语言转 AST 再 js 解释,运行 game,所以自己练练手 js 解释器

使用

demo

demo用例:

<script src="./dist/ji.js"></script>
<script>
  var re = ji.run("var re = 3+4;console.log(re); module.exports=re");
</script>

函数签名:

/**
 * 
 * @param code string 代码
 * @param context 预置运行环境
 * @returns 
 */
function run(code:string, context?: Context){}


interface Context {
  [key: string]: function
}

例如:

const code = "var result = a(4); module.exports = result;"
const injectContext = {
  a: (res) => {
    return res + 10;
  },
}
ji.run(code, injectContext)

开发流程

// 首次
yarn install

// test/index.test.js 撰写本次开发feature测试用例,
// 写代码,并执行本次开发特性的测试用例
yarn test:dev

// 开发完特性之后,归档test/index.test.js测试用例到对应的xxfeature.test.js

测试

yarn test

todo

  • Program
  • VariableDeclaration
  • ExpressionStatement
  • BinaryExpression
  • Literal
  • MemberExpression
  • CallExpression
  • Identifier
  • AssignmentExpressionOperatortraverseMap
  • AssignmentExpression
  • FunctionDeclaration
  • FunctionExpression
  • BlockStatement
  • CatchClause
  • ArrowFunctionExpression
  • EmptyStatement
  • DebuggerStatement
  • WithStatement
  • LabeledStatement
  • ReturnStatement
  • BreakStatement
  • ContinueStatement
  • IfStatement
  • SwitchCase
  • SwitchStatement
  • ThrowStatement
  • TryStatement
  • WhileStatement
  • DoWhileStatement
  • ForStatement
  • ForInStatement
  • ForOfStatement
  • Declaration
  • ClassDeclaration
  • ThisExpression
  • ArrayExpression
  • ObjectExpression
  • YieldExpression
  • UnaryExpression
  • UpdateExpression
  • LogicalExpression
  • ConditionalExpression
  • NewExpression
  • SequenceExpression
  • TemplateLiteral
  • TaggedTemplateExpression
  • ClassExpression
  • MetaProperty
  • AwaitExpression
  • ImportExpression
  • ChainExpression
  • PrivateIdentifier
  • Property
  • PropertyDefinition
  • AssignmentProperty
  • Super
  • TemplateElement
  • SpreadElement
  • ObjectPattern
  • ArrayPattern
  • RestElement
  • AssignmentPattern
  • ClassBody
  • Class
  • MethodDefinition
  • ImportDeclaration
  • ExportNamedDeclaration
  • ExportDefaultDeclaration
  • ExportAllDeclaration
  • ImportSpecifier
  • ImportDefaultSpecifier
  • ImportNamespaceSpecifier
  • ExportSpecifier

参考:

About

js 解释器练手

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published