Tutorials for writing a parser with Javascript [cl

2019-02-01 10:23发布

I've seen a couple of languages (namely CoffeeScript and LessCSS) that are built on Javascript.

Are there tutorials anywhere for writing languages/parsers with Javascript?

3条回答
欢心
2楼-- · 2019-02-01 11:10

Why would you think the fundamental concepts of implementing languages "on JavaScript" are fundamentally dependent on JavaScript? Mostly its just a programming language and standard compiler-like approaches can be applied; one "merely" compiles to JavaScript instead of machine instructions.

Here's a tutorial on writing compilers using very straightforward metacompiling methods. It happens to target JavaScript as a starting place, but it isn't committed to JavaScript either. This tutorial is based on a paper by Val Schorre on "MetaII", a kind of metacompiler .... dated 1964 (yes, you read that right) . I learned how to build my first compiler from this paper (but not with JavaScript :), and it is still a valuable technique:

Meta II Compiler Tutorial targeting JavaScript

If you want something more immediate, consider writing a recursive descent parser by hand.. After you've written a few of these, you'll really appreciate what bit of genius MetaII is.

查看更多
一夜七次
3楼-- · 2019-02-01 11:16

I would start by looking at more languages that compile to javascript and see what they do. Here's a list: https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS

See the list of parser generators at the bottom of that page that make things a bit easier, such as jison and peg.js.

There are certain limits or hurdles when writing an alternative language that compiles to javascript, since javascript wasn't designed to be a 'bytecode' or a runtime for other languages. There are no static types or class system, for example, like in java and C#. If you're just doing a minor alteration to fix some of javascript's issues like coffeescript and others listed at the top of the page at that link, stuff like that isn't a problem, but then a bigger issue is why not just contribute to coffeescript or similar languages instead.

查看更多
Fickle 薄情
4楼-- · 2019-02-01 11:25

Jison is modeled on the GNU Bison parser generator. It takes a language grammar in Bison-like or JSON format and outputs a Javascript parser for the language. If you're wanting to make an interpreter that's based on on another well-known language, there's probably a Bison grammar around somewhere you can tweak for Jison. I've found it very straightforward to get started on a from-scratch DSL.

查看更多
登录 后发表回答