W3C CSS 语法、语法怪异
我正在查看 CSS 语法 此处 和 这里,我很惊讶地看到令牌产生式和语法都充满了空格声明。通常,空格在词法分析器中定义一次并被跳过,再也不会出现。同上评论。
我认为面向用户代理而不是真正的编译器是这里动机的一部分,也是面对错误时继续进行的要求,但它仍然看起来很奇怪。
现实生活中解析 CSS 的 UA 真的是按照这个(这些)语法实现的吗?
编辑:问题的原因实际上是各种 LESS 实现。 less.js
不理解连续注释,而 lessc.exe
不理解选择器内的注释。在这方面,他们甚至无法正确解析 CSS,无论它是如何定义的。所以我去看看 CSS 的实际语法是什么......
I was having a look at the CSS syntax here and here and I was amazed to see both the token productions and the grammar littered with whitespace declarations. Normally whitespace is defined once in the lexer and skipped, never to be seen again. Ditto comments.
I imagine the orientation towards user-agents rather than true compilers is part of the motivation here, and also the requirement to proceed in the face of errors, but it still seems pretty odd.
Are real-life UAs that parse CSS really implemented according to this (these) grammars?
EDIT: reason for the question is actually the various LESS implementations. less.js
doesn't understand consecutive comments, and lessc.exe
doesn't understand comments inside selectors. In this respect they are not even able to parse CSS correctly, however that is defined. So I went to see what the actual grammar of CSS was and ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CSS 虽然与许多编程语言类似,但确实有一些罕见的情况,其中空格可能很重要。
假设我们有以下基本标记:
这里没有什么特别的,除了 div 里面有一个 div,上面有一些样式,以便您可以看到它们之间的区别。
现在让我们向外部 div 添加另一个类和一个 ID:
如果我想通过以下方式为外部 div 提供背景:
...那么空白就变得很重要。上面的规则确实设置了外部 div 的样式,因为它的解析方式与以下内容不同:
...它不会设置外部 div 的样式。
要了解如何以不同的方式解析它们,您可以查看选择器是如何标记的:
示例 1:
示例 2:
如果我们盲目地忽略空格(就像编译器通常所做的那样),我们就会错过这种差异。
话虽这么说,我并不是说这个语法很好。我在编写语法方面也有相当多的经验,当我看到这个语法时我感到畏缩。最简单的解决方案是将
#
和.
符号添加到 IDENT 令牌中,然后其他一切都会变得更加容易。然而,他们并没有选择这样做,并且对空白的需求是该决定的产物。
CSS, while similar to many programming languages, does have some rare instances where whitespace can be important.
Say we have the following base markup:
There's nothing special here, except a div inside of a div, with some styles on it so that you can see the difference between them.
Now lets add another class and an ID to the outer div:
If I want to give a background to the outer div in the following manner:
...then the whitespace becomes important. The rule above does style the outer div, as it is parsed differently than the following:
...which does NOT style the outer div.
To see how these are parsed differently, you can look at how the selectors are tokenized:
Example1:
Example2:
If we were to blindly ignore whitespace (as compilers usually do), we would miss this difference.
With that being said, I am not implying that this grammer is good. I also have a fair amount of experience in writing grammars, and I cringe when looking at this grammar. The easiest solution would have been to add the
#
and.
symbols into the IDENT token and then everything else becomes much easier.However they did not chose to do this, and the need for whitespace is an artifact of that decision.