Lexing和解析CSS层次结构 [英] Lexing and Parsing CSS hierarchy
问题描述
.someDiv { width:100%; height:100%; ... more properties ... }
我如何在解析器中构成一个与上面的字符串匹配的规则?
How would I make up a rule in my parser that will match the string above?
对我来说似乎不太可能,因为您不能在规则中定义无限数量的属性?有人可以澄清一下,您将如何使用FsLex
和FsYacc
做这样的事情?
Seems rather impossible for me, since you cant define an unlimited amount of properties in the rule? Could someone please clarify, how you would do such a thing with FsLex
and FsYacc
?
推荐答案
如果您使用的是FsLex和FsYacc,则可以将{ ... }
内部的属性解析为属性列表.假设您有一个能够正确识别所有特殊字符的词法分析器,并且具有解析单个属性的规则,则可以编写如下内容:
If you're using FsLex and FsYacc then you can parse the properties inside { ... }
as a list of properties. Assuming you have a lexer that properly recognizes all the special characters and you have a rule that parses individual property, you can write something like:
declaration:
| navigators LCURLY propertyList RCURLY { Declaration($1, $3) }
| navigators LCURLY RCURLY { Declaration($1, []) }
propertyList:
| property SEMICOLON propertyList { $1::$2 }
| property { [$1] }
property:
| IDENTIFIER COLON values { Property($1, $3) }
declaration
规则解析整个声明(您需要为可以在CSS中使用的各种导航器(例如div.foo #id
等)编写解析器.)propertyList
规则解析一个属性,然后递归调用自身解析多个属性.
The declaration
rule parses the entire declaration (you'll need to write parser for various navigators that can be used in CSS such as div.foo #id
etc.) The propertyList
rule parses one property and then calls itself recursively to parse multiple properties.
在右侧构造的值将是代表各个属性的值的列表. property
规则解析单个属性分配,例如width:100%
(但是您需要完成值的解析,因为它可以是列表或更复杂的表达式).
The values constructed on the right-hand-side are going to be a list of values representing individual property. The property
rule parses individual property assignment e.g. width:100%
(but you'll need to finish parsing of values, because that can be a list or a more compelx expression).
这篇关于Lexing和解析CSS层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!