我想写一个小代码分析器,它解析嵌套结构并转换为有效的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;
}
输出:
c {
border: 4px; /* comment */
}
b {
border: 3px;
}
a {
border: 2px;
}
#foo {
border: 1px;
}
那么,如何保留从上层继承的标识符呢?
如果您使用c++,为什么不使用OO?
创建一个表示作用域(匹配的{}对)的类,该类有一个指向其子作用域的指针列表和一个指向其父作用域的指示器:即:在您的示例中,foo的列表包含a和b,b的列表包含c。
打印时,递归地进入每个叶作用域,然后通过将其所有"祖先"的名称添加到其自身的开头来打印其"完整"名称。
一个骨架起点:
class Element
{
public:
Element()
: m_pParent( 0 )
{
}
private:
std::string m_Name;
std::string m_Contents;
Element* m_pParent;
std::list<Element*> m_Children;
};