Is JavaScript a Context Free Language?

后端 未结 3 1274
逝去的感伤
逝去的感伤 2021-02-05 11:15

This article on how browsers work explains how CSS is context free, while HTML is not. But what about JavaScript, is JavaScript context free?

I am learning abou

3条回答
  •  青春惊慌失措
    2021-02-05 11:54

    No, JavaScript is not a context-free language.

    It is very close to one, and the ECMAScript 5 specification does indeed use a context-free grammar1 to describe the language's syntax (you can find all productions in Annex A).

    Of course, it does make some extensions to pure context-free grammatical productions, and describes extra behaviour of the parser. One particular thing is the usage of lookahead which still makes a context-free languages, but would complicate the grammar a lot if it couldn't be used for some rules. Not allowing certain things to appear in strict mode code is similar - it could be done by adjusting the grammar (with far more productions), but the rule is much easier expressed by leaving the BNF.

    However, there are also some2 rules that do make the language not context-free. You'll find an overview in the description of early errors, which can make a program code invalid. That object literals must not contain duplicate property names and that function parameter lists must not contain duplicate identifiers are two rules that cannot be expressed using (finite) context-free grammars.
    My gut tells me that the automatic semicolon insertion falls in the same box, but I think its rules are too complicated to even attempt a proof here.

    1: Actually it uses two grammars, a lexical and a syntactical one, where the first disambiguates between division expressions and regular expressions, and does produce the tokens that are the input to the second grammar.
    2: Rather few actually, compared to other programming languages

提交回复
热议问题