Is D's grammar really context-free?

后端 未结 7 1129
萌比男神i
萌比男神i 2021-01-30 03:18

I\'ve posted this on the D newsgroup some months ago, but for some reason, the answer never really convinced me, so I thought I\'d ask it here.


The grammar of D is

7条回答
  •  礼貌的吻别
    2021-01-30 03:43

    To answer the question of if a programming language is context free you must first decide where to draw the line between syntax and semantics. As an extreme example, it is illegal in C for a program to use the value of some kinds of integers after they have been allowed to overflow. Clearly this can't be checked at compile time, let alone parse time:

    void Fn() {
      int i = INT_MAX;
      FnThatMightNotReturn();  // halting problem?
      i++;
      if(Test(i)) printf("Weeee!\n");
    }
    

    As a less extreme example that others have pointed out, deceleration before use rules can't be enforced in a context free syntax so if you wish to keep your syntax pass context free, then that must be deferred to the next pass.

    As a practical definition, I would start with the question of: Can you correctly and unambiguously determine the parse tree of all correct programs using a context free grammar and, for all incorrect programs (that the language requires be rejected), either reject them as syntactically invalid or produce a parse tree that the later passes can identify as invalid and reject?

    Given that the most correct spec for the D syntax is a parser (IIRC an LL parser) I strongly suspect that it is in fact context free by the definition I suggested.


    Note: the above says nothing about what grammar the language documentation or a given parser uses, only if a context free grammar exists. Also, the only full documentation on the D language is the source code of the compiler DMD.

提交回复
热议问题