How to define a grammar for a programming language

前端 未结 5 633
终归单人心
终归单人心 2021-01-30 09:08

How to define a grammar (context-free) for a new programming language (imperative programming language) that you want to design from scratch.

In other words: How do you

5条回答
  •  迷失自我
    2021-01-30 10:07

    If you mean defining a grammar, you would be best served by starting with an existing language and modifying its grammar to match what it is that you are after. Creating a grammar specification is a fairly mechanical exercise, using a set of patterns in your own head. For instance, what does an if statement look like? Does it look like C

    if <- if(exp) block

    if <- if(exp) block else block2

    or like ML?

    if <- if exp then block else block end

    or maybe you want to use elseifs like Lua:

    if <- if exp then exp end

    if <- if exp then exp (elseif exp)* else exp end

    The grammar and semantics codify these decisions. Note that none of these are quite suitable for implementation in a LALR or LL(*) compiler generator yet, and would have to be massaged for implementation because they are ambiguous.

    Programming Language Pragmatics by Michael Scott is a good introduction to the design of programming languages. It's available on Amazon here

提交回复
热议问题