summaryrefslogtreecommitdiff
path: root/src/srcut.cpp
blob: 6df435b39d34d4049b779e81e89f1f9b3d0afb53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

istream&
operator>>(istream& in, map<string, vector<string>>& container)
{
	static constexpr auto begin_marker = "--8<--";
	static constexpr auto end_marker   = "-->8--";

	auto is_comment = [](string_view s) -> bool {
		return s == "//" || s == "/*" || s == "#" || s == "##" || s == "--";
	};

	// --8<-- match_begin
	auto match_begin = [&is_comment](const string& line, string& name) -> bool {
		stringstream ss{ line };

		string comment, cut_mark;

		if ( !(ss >> comment >> cut_mark >> name) ) {
			return false;
		}

		if ( !is_comment(comment) ) {
			return false;
		}

		if ( cut_mark != begin_marker ) {
			return false;
		}

		return true;
	};
	// -->8--

	// --8<-- match_end
	auto match_end = [&is_comment](const string& line) -> bool {
		stringstream ss{ line };

		string comment, cut_mark;

		if ( !(ss >> comment >> cut_mark) ) {
			return false;
		}

		if ( !is_comment(comment) ) {
			return false;
		}

		if ( cut_mark != end_marker ) {
			return false;
		}

		return true;
	};
	// -->8--

	vector<string> chunks;
	for ( string line; getline(in, line); ) {
		string marker;
		if ( match_begin(line, marker) ) {
			chunks.emplace_back(marker);
		}
		else if ( match_end(line) ) {
			if ( !chunks.empty() ) {
				chunks.pop_back();
			}
		}
		else {
			for ( const auto& chunk: chunks ) {
				container[chunk].emplace_back(line);
			}
		}
	}

	return in;
}

ostream&
operator<<(ostream& os, const map<string, vector<string>>& container)
{
	for ( const auto& chunk: container ) {
		os << "CHUNK: " << chunk.first << '\n';
		auto line = begin(chunk.second);
		while ( line != end(chunk.second) ) {
			os << *line << '\n';

			++line;
		}
		os << "-------\n\n";
	}
	return os;
}

int
main(void)
{
	map<string, vector<string>> container;

	cin >> container;
	cout << container;
}