Scope Handling Ideas

Hello, I'm writing my own file format (for a small personal project). I've looked at many different types of file structures and I've decided that I wanted to structure my file like such:

1
2
3
4
5
6
7
8
9
10
11
12
Outer {
    Middle {
        Inner {
        }
    }
}
OuterB {
    Middle {
        Inner {
        }
    }
}


The scopes can be whatever name that I want them to be, but I used Outer, Middle, and Inner for clarity. The scopes contain information that the program will interpret, and the scope names are statically-coded into the program. I currently use strings to process the scopes. For instance, if the parser was in OuterB.Middle the code would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// ... somewhere early in the parser ... //
while (std::getline(file, line)


// ... do some processing ... //
// ... later in the program ... //

if (scope == "OuterB" && line == "Middle {")
    std::string scope = "OuterB.Middle";

// ... do some processing ... //
// ... later in the program ... //

if (scope =="OuterB.Middle" && line == "}")
    std::string scope = "OuterB";


This doesn't seem efficient to me because I have to write for every situation that the parser might encounter. Whenever a scope terminates, I have to hard code which scope to return to. I do have a control structure and the function isn't 1000s of lines long. (I don't want to give off that opinion from the few pieces of code that I wrote.) It will be easy for me to change anything about this function and I don't want to go too far before I have to change everything.

Thanks for any help,
MaxterTheTurtle


Last edited on
When you encounter new scope, push it on stack, when you exit scope, pop it from stack.
Do you really need to write your own parser for your own file format? Wouldn't something like JSON suit you? http://json.org/
It has many libraries for all kinds of languages.
Example of file and its DOM structure: http://www.jsoneditoronline.org/?id=4c1dba6abbe4a487f7f8e087e9bbbb92
Thanks for the idea about stacks. I can't believe that I forgot about something that fits the purpose so well. At the end of the day, it might be easier to go with JSON. RapidJSON looks promising. I don't want to spend all day re-inventing the wheel.
Last edited on
Topic archived. No new replies allowed.