Extacts the next code block from stream f. Returns true if found.
| 35 | // Extacts the next code block from stream f. |
| 36 | // Returns true if found. |
| 37 | auto ParseCodeBlock(std::istream& fin) { |
| 38 | struct Res { |
| 39 | bool found; |
| 40 | CodeBlock block; |
| 41 | std::string error; |
| 42 | }; |
| 43 | const auto flags = fin.flags(); |
| 44 | fin >> std::noskipws; |
| 45 | CodeBlock block; |
| 46 | enum class S { begin, name, content, exit }; |
| 47 | S s = S::begin; // state |
| 48 | char c = ' '; |
| 49 | int braces = 0; |
| 50 | std::string error; |
| 51 | while (fin && s != S::exit && error.empty()) { |
| 52 | auto next = [&fin, &c]() { fin >> c; }; |
| 53 | switch (s) { |
| 54 | case S::begin: { |
| 55 | if (std::isspace(c)) { |
| 56 | next(); |
| 57 | } else { |
| 58 | s = S::name; |
| 59 | } |
| 60 | break; |
| 61 | } |
| 62 | case S::name: { |
| 63 | if (c == '{') { |
| 64 | s = S::content; |
| 65 | next(); |
| 66 | } else if (c == '}') { |
| 67 | error = "name cannot contain '}', unmatched brace?"; |
| 68 | } else { |
| 69 | block.name += c; |
| 70 | next(); |
| 71 | } |
| 72 | break; |
| 73 | } |
| 74 | case S::content: { |
| 75 | if (c == '}' && braces == 0) { |
| 76 | s = S::exit; |
| 77 | next(); |
| 78 | } else { |
| 79 | block.content += c; |
| 80 | if (c == '{') { |
| 81 | ++braces; |
| 82 | } else if (c == '}') { |
| 83 | --braces; |
| 84 | } |
| 85 | next(); |
| 86 | } |
| 87 | break; |
| 88 | } |
| 89 | case S::exit: { |
| 90 | break; |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | if (error.empty() && s != S::exit && |
no test coverage detected