199 points · by ternaryoperator · 12y ago · 203 comments
Also, read http://this-plt-life.tumblr.com/ and don't take yourself too seriously. Stand on the shoulders of giants and continue reaching for the sky. Languages are super fun.
A programming language is the semantics and without a strong notion of those semantics and the interactions you end up with confusion and difficulty. For an example one need look no further than Ruby's "implementation as specification" crazyness.
I won't go as far as to say that all language creators should adopt operational semantics when building a language, but if you're serious about it then you should at least investigate the process.
d = {}
d[key] = value
easier to read/write than (set! d (make-hash-table))
(hash-table-put! d key value)One reason I think that is because syntax helps develop conventions and make them obvious. If everything is an s-expr and you can do absolutely anything with macros anywhere, then two programmers might not really be able to communicate even if they are technically using the same language.
Parsers are far from harmless pieces of logic you can just throw together. And not just because they take time to write - parsers are physically dangerous. Compiler writers develop incipient carpal tunnel syndrome trying to write parsers.
When you finish writing a parser as a language designer the problem of writing a parser for the language doesn't go away. The programming language users might want to apply transformations to source code written in the language -- which now means they need to write brand new parsers from scratch to do these transformations.
What s-exprs give you instead is the option to write a "parser" in one function call: using the read function. It doesn't get shorter than that.
Now, that's a parser that's easy to write.
edit: rewording
If you understand abstract languages, writing a recursive descent parser is a simple, paper and pencil exercise.
If you don't understand abstract languages, you should not be designing a language till you stop and learn them and you should STFU about what people designing languages should do until then.
Really, they are easy. They are literally insignificant when you factor in all the hours you'll work on a language.
I wrote another one recently for a small side project. It took more time to write the unit tests for it. The parser practically wrote itself.
Even that might be overkill, though: a generic operator parser for unary, binary, ternary, n-ary, and so on will take about 50 lines of code. You can encode a surprisingly large number of control structures with a cleverly crafted precedence parser.
The programming language users might want to apply transformations
to source code written in the language -- which now means they need to
write brand new parsers from scratch to do these transformations.
That would be Doing It Wrong. Tools like clang-format (source formatting) and clang-modernize (source transformation to use new language features) use exactly the same parser library — among other things — as the compiler proper.http://tratt.net/laurie/blog/entries/parsing_the_solved_prob... ltu discussion http://lambda-the-ultimate.org/node/4489
I use Haskell and Clojure happily.
Sounds like petty nonsense to me.
While using s-expressions is obviously the right thing to do if you are writing your compiler in some dialect of Lisp, it may not be the best choice if using another language.
In particular, I have past experience from writing several toy programming language interpreter and compiler prototypes in Haskell. Representing the abstract syntax tree with a tree structure and sum types is easy and convenient and writing the actual parser (using e.g. Parsec) is trivial and doing a pretty printer isn't hard either (using Hughes-PJ pretty printers).
If you have not tried it, I recommend doing a small programming language prototype in Haskell. It's a very good exercise and really fun.
But your argument about this having to do with what compiler one is using doesn't make sense to me. S-expressions are easily parseable in virtually any language. S-expressions are always going to be one short-cut around the problem of deciding what syntax your language should have (my object is this short-cut may not help your language in the end - your S-expression language will be considered less-than-understandable by the same reasonably large group of people who consider LISP less-than-understandable).
For example, Google give this complete lisp interpreter in c:
http://www.umcs.maine.edu/~chaitin/lisp.c
Haskell may have facilities that make parsing any language reasonably easy, sure. But I have news, parsing language is easy once you learn a bit anyway.
Representing tree structures like abstract syntax trees is really easy and convenient in Haskell. The traditional example, curried λ-calculus with integers looks something like this:
data Expr =
Constant Int |
Identifier String |
Application Expr Expr |
Lambda String Expr
Haskell makes it easy to handle such tree structures using pattern matching. Of course it is at least as easy to represent s-expressions with a similar tree structure. However, there are multiple benefits of using a tree structure like that, for example you will get a compiler warning if you forget to handle one or more of the possible cases in a non-exhaustive pattern match.It is also easier to write a parser and pretty printer (using Parsec and Pretty combinators) to convert that tree structure to/from human readable/writable strings (ie. program source code) than it is to convert s-expressions to such a tree structure.
So while using s-expressions is certainly possible, in a nicely typed language like Haskell, it will be nicer to have a proper syntax tree data structure and the advantages of s-expressions are not really there unless you are writing an interpreter for a homoiconic language like Lisp or Prolog.
The way I usually start a programming language project (I do lots of those) is writing "programs" by specifying syntax trees for test cases in Haskell using literals and then running them through the interpreter/compiler/type checker. Only when I have something that actually works (and developing and debugging by writing the tree structures becomes unwieldy), I start thinking about the syntax and write the parser and pretty printer.
So if you're using a host language other than Lisp to implement your compiler/interpreter and your source language isn't homoiconic, using s-expressions as your internal program representation might end up being unwieldy. The syntax of your source language is pretty much irrelevant in this discussion, but writing a proper parser to produce tree structure might make sense rather than reading s-expressions.
Does my explanation make sense to you? If you have any questions, don't hesitate to ask.
Here's a few of my toy language projects for your enjoyment, you'll find examples of the things discussed above there:
https://github.com/rikusalminen/funfun LLVM compiler for a toy functional programming language (with type inference!)
https://github.com/rikusalminen/slolog Prolog-esque logic programming language
When you're dealing with human interfaces, existing convention counts enormously.
Wait, if you say "just don't do it, learn LISP instead and just customize your stuff", well that is good advice, OK.
Still, learning real language construction tools is a cool thing. It's mainly cool in the long, miserable, thankless journey way the article describes yes. But beautiful still. Nice syntax the way human like to read has had a long, successful history. But LISP has had it's moments too...
This also means that there can be multiple concrete syntaxes for a language: e.g. for Python, you can use the standard syntax, but you could also use s-expressions, without changing the semantics one bit.
s-Expressions are not the same as LISP sure but I don't think you can say they are orthogonal either. They are a key aspect.
Sure, you can have a non-LISP s-expression language but the boundary between this and a subdialect of LISP is going to be porous.
The strengths and the weaknesses of LISP, as far I can see, come because it is so easy to just create a mini-language, a sub-dialectic to do this and that.
I'll assume people know the strengths (and I'm the one say them most eloquently), I'd mention simplicity, flexibility, recursion, homoiconity, etc.
I'd say the weaknesses "easy wheel reinventing", which has resulted in many half-formed wheels and few canonical wheels.
So to get back to syntax, what's nice about a "strong clear" syntax like infix math or c-style function declarations is that they make purposes clear and make boundaries clear. The useful of designing a "real language" is doing that. You can do everything with s-Expression but if it just your new language for doing X, you'll putting forward your purpose in a loose, flabby way. If you expression-language isn't going to be just rolled into LISP, it will just have all the weaknesses and of the strengths of LISP.
I've been writing my own toy compile-to-js language after reading the book: https://github.com/cosmith/panda (I might have to change the name though, I recently discovered http://yesco.org/panda.html ...)
The demo doesn't show much more than hello world, because that's all there is at the moment - the focus has been on building the end-to-end toolchain and I am now filling out the features, but good suggestion going forward.
It seems like you have a good head start already, I hope you still find something interesting in there. If not, you can always ask for a refund...
The best of both worlds is a library like Parsec in Haskell, which lets you write in the native language, but feel like you're writing in a DSL. Parsec is a breeze and easily my favorite thing with which to write parsers...
I guess if I'm trying to be more clear I'm glad to see this perspective expressed, since it's a relatively rare one to see expressed authoritatively. There are a few topics in parsing that I don't think get enough discussion.
Like, my pet peeve is people thinking a naive implementation of the packrat parser is guaranteed to perform better than a plain recursive descent parser. In reality you might just be trading explosive memory growth for algorithmic steps. In a lot of cases that's actually slower.
Edit: also your lexical spec is much less likely to change than your grammar is.
perhaps just that it's important to keep in mind that computer systems are things we've worked out for ourselves. these notions of "lex" and "parse" are not things given to us by nature...
...although, they do kind of do fall out the circumstances of (1) needing to emit x86 instructions and (2) the preference for writing programs in text editors. the second point gets a lot of discussion what with ideas about editors understanding parse trees and all, but i wonder what happens to the whole lexer-parser dichotomy if we keep 2 and periscope our notions of hardware. does the need for tokenization appear as a result of something fundamental to von neumann architecture, or is it just a result of currently-vogue instruction sets?
ah well, back to making things happen with the tools at hand.
Like, seriously: what are you trying to achieve by writing your lexer by hand? Your result will be both more difficult to maintain and is pretty much guaranteed to be slower than the output of a tool like flex. At least when people throw away the advantages of parser generators and write recursive descent parsers they gain the ability to have "easy context sensitivity" (which makes implementing many languages much easier), but I don't see why anyone would ever hand write a lexer. "I know how it all works" is also fine, but in that case you write your own lexer generator tool, you don't skip directly to the lexer (unless you are doing your first one as a "homework assignment"). If you don't like the input syntax of your lexer generator, there are many to choose from, or maybe you write one yourself, but that's no reason to switch to something that is not only going to be more verbose and error-prone but will also be slower.
(afterthought: I guess an interesting analogy: you don't lay out a hashtable by hand, like in a C initializer list in your source code that has a large number of NULL entries with only a subset filled in, already in hashed order; you instead write a hash function and let the computer reorder your entries for you. Manually hashing the values feels "hard core", but offers no advantages, and means you have to throw away all of your work and start over when the size of your table changes. Doing it by hand is also strictly grunt work: you don't gain anything by having placed it by hand other than the possibility that you made a mistake somewhere and now your element will never be found. And if later you want to try different hash functions or different search algorithms--maybe you are willing to pay some costs to get range queries, and end up using a tree--you can later do so without changing your input files. You should think of your lexer like a really complex data structure tied to an algorithm that always has the abstract interface "get next token".)
Yes, I write my own hash tables also for the same reason (so they support incremental computations).
I've only done it a couple of times with relatively simple syntaxes so YMMV.
I found his explanation on how the lexer/parser for the templating language used in go http://www.youtube.com/watch?v=HxaD_trXwRE was created much easier to understand than other media/literature available online on the same subject. Hence my appreciation of his work. :)
That said, now that my language's grammar is stable and I have a better understanding of lexing and parsing, I'm thinking about ditching Flex/Bison, mainly to achieve more descriptive error messages.
Programming languages don't win because they are better qua programming languages. They win because they solve one problem really well that others do not. Ruby (+ Rails) -> building structured web apps. Javascript -> Being there. C -> Being portable assembler. Java -> C with garbage collection.
Consider the greatest language ever, Lisp (I hate it, but I recognize it's power.) The reason it's never taken off is that there is no one big problem that it solves that other languages can't solve easily enough.
The bad news for a lot of the better, smaller languages out there is that the newer problems are often solved in libraries and momentum (tooling, deployment support, etc.) in the big languages is huge.
That assertion's got more holes than emmental. Where does Python fit? C#? Javascript and Objective-C don't really "solve one problem really well", they're the only fucking option in their space. Java was not and has never been "C with garbage collection", the syntax is the only thing it got from C.
The language being great at solving a specific use case is definitely a boon and increases its chances (witness PHP or Lua), but it's nowhere near sufficient (Tcl lives in the same niche as Lua — lightweight, extensible, multi-paradigm language for embedding in and scripting of native codebases, predates Lua, and is considered by many of its lovers better than Lua, yet it's dying its slow and protracted death)
> The reason it's never taken off is that there is no one big problem that it solves that other languages can't solve easily enough.
The reasons it never took of is a combination of little advertising/pushing (compare with java), and highly fragmentary communities (the community unit of Lisp, as those of mages, is 1) leading to no corpus of code.
> The bad news for a lot of the better, smaller languages
And yet there's never been more uptake in new languages.
Maybe, but your counterexamples don't seem particularly convincing.
Where does Python fit?
Originally, a readable scripting language.
More recently, a language for back-end web development that doesn't ram OO down your throat.
Also carving out something of a niche as a general purpose scripting language embedded in other applications instead of a custom macro language, like Lua but many more people have prior experience programming in it.
C#
Similar strengths to Java, but with a lot of useful extra features, without most of the limitations that should have gone away a decade ago but didn't, and with a runtime environment that is available by default on Windows.
The reasons [Lisp] never took of is a combination of little advertising/pushing ... and highly fragmentary communities ... leading to no corpus of code.
Also, a highly uniform and generic structure is not always an advantage in a programming language. Sometimes it's better to have things that are different obviously look like they're different.
It also need to be an interesting thing to brag about, but, honestly, just getting the first bit is enough challenge....
No, it just needs to be convincing. Plenty of convincing lies (or unproven claims) are used to sell programming languages.
Of course, that discounts Clojure, which is showing Lisp's power to a new generation, in an environment they can relate to (the JVM).
Since then, I've been looking for a language that really offers all the bits that would make for a truly compelling Obvious experience without having to write it as a "framework" and it's pretty difficult to find something that really hits all the points well.
I haven't ventured into building my own language yet, but it's awfully tempting.
"Being portable assembler" is not solving one problem at all, it is one of the most general things you could cite. That literally is being a better language.
Java took millions of dollars of marketing to make it popular, people didn't just suddenly flock to it because it was C with garbage collection (which was already a solved problem: see C).
Perhaps lisp "never took off" (seems like it took off pretty well to me) because it isn't the greatest language ever? Lisp barely is a language, it is more of a toolkit to build a language with.
Could you please explain what you mean? C is the only language I know in any depth. Beyond a basic description, "garbage collection" is a fairly alien concept to me.
Probably less than 100 people have developed for the language (mostly just tweaking the provided applet code), but the goal never was to unleash a new language onto the world. The aim was to provide a rock solid platform for our product that allowed people to customize the applets if they wished, and it achieved that.
I would recommend people build their own programming language simply for the hell of it - it's challening, fun, and could come in useful in future.
Also it won't take "years" to get a working prototype. You can get something working in less than a month. It will obviously take a lot longer to get it stable and bug-free.
It all depends on the language. Tiny domain specific languages might only take hours, under the right circumstances (for an experienced language implementer).
When someone says "years", I assume they mean an industrial strength general purpose language.
Writing a compiler is a lot simpler than people might think. I used "Practice and Principles of Compiler Building With C", which explains things very well. It seems to be out of print now.
Light syntax is useful for readability. I like it when I don't have to end each line with a semicolon, because that's just noise meant to spoon-feed the compiler. However, I hate it when the grammar of the language leads to awful gotchas. And sometimes visual clues are useful, again for readability.
Since we are on the subject, I hate CoffeeScript.
I was lucky in that Zortech C++ came out just as the market for C++ exploded (and it might even be that ZTC++ was the case of that explosion).
http://www.fastcolabs.com/3019948/more-about-d-language-and-...
That said, you're right. Rust and Go both have momentum, and they've both had big backers behind them.
http://www.acooke.org/lepl/intro.html
A quick example:
https://gist.github.com/rch/8791893
Edit -- I guess not many people agree with me:
fn myfor(&init, &test, &incr, &body)
*init
while *test
*body
*incr
var a
myfor a=0, a!=10, ++a
print a
& creates a zero-argument lambda function out of the argument. * is sugar to call a zero-argument function.Also:
fn set(&x y)
*x = y
set a 7 # Set variable a to 7
It works because when variables are evaluated, the result includes both the value and the address from which it originated.Anyway, creating a language is one thing. Creating a fast compiler for it is quite another. It's impressive how well v8 works for the dynamic language javascript, but the amount of work embedded in it is daunting. On my list of future projects is to try to make a simple SSA-based optimizer.
Is there a good overview comparison of strength/weaknesses of what's available (blog post, academic journal don't really care)? I mostly know stuff exists because I've heard it mentioned somewhere (Flex/Bison, yacc, using Prolog :P) and it's not the easiest thing in the world to make an educated decision.
My current plan is to stick with ANTR and muddle through and build a prototype then spend a day or two researching alternatives and seeing what comes up but if someone could cut down that research time I'd be thankful :)
The easiest start would be "Compiler Construction using Flex and Bison" by Anthony A. Aaby, available as free pdf, and for adding LLVM to the mix the link would be: http://gnuu.org/2009/09/18/writing-your-own-toy-compiler/
There needs much more to be said, e.g. links to such languages which were written in a day and are not necessarily lisp or scheme. That would be too easy.
This article seems like the perfect antidote to the usual "here's the dragon book" article.
Articles that point you to the dragon book, give a few ideas of what parser and lexer are, and then turn you loose are just terrible. They are look articles on "how to build a house" that focus on "here's where to buy a backhoe, here's where you can concrete, etc..."
Essentially, designing your own programming language is a difficult and in many ways, bad, idea. But what you to have a ghost of a chance is "what choice should you make, what will it feel like" narrative (there should also be "what are the milestones" but given programming, that will sadly be too variable to predict).
This matches Walter's experiences, and not only his.
After all, it's just an article, not a comprehensive tome.
Minimizing keywords is important not because of a word shortage, but because of an overlap with words the programmer wants to use. It is obvious that if you make "i" a keyword, someone will likely murder you. But there's tons of grey area where you might be stepping on toes and getting in the way, so minimizing the amount of toe stepping is good. Especially since there is absolutely no reason to have lots of keywords.
Given the context I think it isn't so much that Walter is saying you can't have good error messages without semicolons. He's saying you can't have good error messages without redundancy (in this example a statement terminator).
That is what he said though. I understand it is one example for a larger point, but it is an example that doesn't support that point at all. It is pretty hard to judge the overall point when the example is nonsense.
Your goal is to write a whole programming language.
Calculating where each statement starts and ends in order to serve a good error message is misdirected effort. Just use a terminating character, and use the standard one: a semi-colon.