嵌套CSS结构的解析
我想编写一个小型代码分析器,它可以解析嵌套结构并转换为有效的 CSS
。但是,我没有保留从上层继承的标识符。
嵌套结构:
#foo {
border: 1px;
a {
border: 2px;
}
b {
border: 3px;
c {
border: 4px; /* comment */
}
}
}
我想将结构翻译成:
#foo {
border: 1px;
}
#foo a {
border: 2px;
}
#foo b {
border: 3px;
}
#foo b c {
border: 4px; /* comment */
}
解析代码:
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
string str = "\
#foo {\
border: 1px;\
a {\
border: 2px;\
}\
b {\
border: 3px;\
c {\
border: 4px; /* comment */\
}\
}\
}";
string::const_iterator i = str.end(),
begin = str.begin(), end;
while (i != begin) {
if (*i == ';' || (*i == '/' && *(i-1) == '*')) {
end = i++;
while (*i-- != '{');
while (true) {
if (*i == ';' || *i == '}' || *i == '{' || i == begin)
break;
i--;
}
string item(++i, ++end);
cout << item << "}" << endl;
}
i--;
}
return 0;
}
Out:
c {
border: 4px; /* comment */
}
b {
border: 3px;
}
a {
border: 2px;
}
#foo {
border: 1px;
}
那么,如何保留从上层继承的标识符呢?
I want write a little code analyzer which parses nested structures and translates into valid CSS
. However, I did't get to keep the identifiers that are inherited from upper level.
The nested structure:
#foo {
border: 1px;
a {
border: 2px;
}
b {
border: 3px;
c {
border: 4px; /* comment */
}
}
}
I want to translate the structure into:
#foo {
border: 1px;
}
#foo a {
border: 2px;
}
#foo b {
border: 3px;
}
#foo b c {
border: 4px; /* comment */
}
Parse code:
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
string str = "\
#foo {\
border: 1px;\
a {\
border: 2px;\
}\
b {\
border: 3px;\
c {\
border: 4px; /* comment */\
}\
}\
}";
string::const_iterator i = str.end(),
begin = str.begin(), end;
while (i != begin) {
if (*i == ';' || (*i == '/' && *(i-1) == '*')) {
end = i++;
while (*i-- != '{');
while (true) {
if (*i == ';' || *i == '}' || *i == '{' || i == begin)
break;
i--;
}
string item(++i, ++end);
cout << item << "}" << endl;
}
i--;
}
return 0;
}
Out:
c {
border: 4px; /* comment */
}
b {
border: 3px;
}
a {
border: 2px;
}
#foo {
border: 1px;
}
So, how to keep the identifiers that are inherited from upper level?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 C++,为什么不使用 OO?
创建一个表示作用域的类(匹配的 {} 对),该类具有指向其子作用域的指针列表和指向其父作用域的指针:即:在示例中 foo 的列表包含 a 和 b,b 的列表包含 c。
打印时,递归地进入每个叶范围,然后通过将其所有“祖先”的名称添加到其自身的开头来打印其“完整”名称。
骨架起点:
If you're using c++, why not use OO?
Create a class that represents a scope (a matched {} pair), which has a list of pointers to it's child scopes and a pointer to its parent scope: ie: from your example foo's list contains a and b, b's list contains c.
When printing out, recursively go into each leaf scope, then get it to print its 'full' name by adding the names of all its 'ancestors' onto the beginning of its own.
A skeleton starting point: