how to start writing a very simple programming lan

2020-02-17 05:35发布

Recently, I was going around looking for ideas on what I can build using C this summer and I came across this post: Interesting project to learn C?

Implement a programming language. This doesn't have to be terribly hard - I did the language that must not be named - but it will force you to learn a lot of the important parts of C. If you don't want to write a lexer and/or parser yourself, you can use lex/flex and yacc/bison, but if you plan on that you might want to start with a somewhat smaller project.

I was kinda intrigued about the implementing a programming language answer and I'm wondering how do I go about starting this? I've gone through the whole K&R book and I've done some of the exercises as well. I also have a bit of experience in C++ and Java if that matters. Any tips? Thanks!

14条回答
ゆ 、 Hurt°
2楼-- · 2020-02-17 05:48

To keep things simple, I recommend implementing a simple postfix language. FORTH or the core part of PostScript would be great choices.

查看更多
Ridiculous、
3楼-- · 2020-02-17 05:48

Let someone else do the dirty work for you, namely, the lexer and the parser. Use cup, yacc, or bison to handle the syntax. This will let you focus on the more important language design decisions. There are even example parser definitions for many languages that you can use as a template for yours.

查看更多
混吃等死
4楼-- · 2020-02-17 05:54

Start with a very simple (toy) language; later you can create a more complex syntax.

You could write an interpreter to parse strings like,

integer x
integer y
set x, 2
set y, 5
add x, y // x = x + y
print x

and evaluate each line immediately. If you store the lines in a vector it'd be easy to implement loops with goto command.


An example, Another World (vintage game)
Script editor:

alt text

查看更多
神经病院院长
5楼-- · 2020-02-17 05:54

you can read some well-written papers by Niklaus Wirth:

  • "Compiler Construction" (available here) is a short, concise introduction to the art of building a compiler.
  • "Algorithms + Data Structure = Programs" (unfortunately out of print), presents a simpler language (named PL/0) in his last chapter.

although those papers are mainly written in Pascal, the concepts exposed are easily translated to C.

查看更多
ゆ 、 Hurt°
6楼-- · 2020-02-17 05:55

One old compiler tutorial is this one. Though it is in Pascal it is a very good source of information. If you want something more recent you should have a look at ANTLR.

查看更多
狗以群分
7楼-- · 2020-02-17 05:55

Scheme from Scratch is a nice series of blog posts about implementing Scheme in C. The code is very readable, and each version builds on the previous one in a way that's easy to follow.

Here is the first installment: v0.1 - Integers.

查看更多
登录 后发表回答