Lexing and Parsing CSS hierarchy

2020-03-04 06:56发布

问题:

.someDiv { width:100%; height:100%; ... more properties ... }

How would I make up a rule in my parser that will match the string above?

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?

回答1:

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) }

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.

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).



标签: parsing f#