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?
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: