Debian Codegraph @

src/main.cpp

raw symbols SCIP
1 /*
2 setop -- apply set operations to several input files and print resulting set to standard output
3 Copyright (C) 2015 Frank Stähr, GPL v2 or later
4
5 This program is free software:
6 you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
7
8 This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the GNU General Public License for more details.
11
12 You can find a copy of the GNU General Public License at <http://www.gnu.org/licenses/>.
13 */
14
15
16 #include <iostream>
17 #include <string>
18 #include <set>
19 #include <map>
20 #include <vector>
21 #include <stack>
22 #include <regex>
23 #include <fstream>
24 #include <functional>
25 #include <memory>
26 #include <cstdlib>
27
28 #include <boost/program_options.hpp>
29 #include <boost/algorithm/string/trim.hpp>
30 #include <boost/algorithm/string/case_conv.hpp>
31 #include <boost/algorithm/string/predicate.hpp>
32 #include <boost/regex.hpp>
33
34
35 /**
36 \file
37 \brief Program for parsing input files and streams for string elements and applying several set operations and special queries
38 \details For details how to use the program start it with `--help` and see help text.
39 \author Frank Stähr
40 \date Oct., 1st, 2015
41 */
42
43 #define PROGRAM_NAME "setop" ///< official name of program
44 #define PROGRAM_VERSION "0.2" ///< version of setop
45 /** \brief used when query has negative result (e. g. element not part of input), but program flow has no (other) error */
46 #define EXIT_QUERY_NEGATIVE 3
47 static_assert((EXIT_QUERY_NEGATIVE != EXIT_SUCCESS) && (EXIT_QUERY_NEGATIVE != EXIT_FAILURE),
48 "Macro EXIT_QUERY_NEGATIVE must not be equal to EXIT_SUCCESS or to EXIT_FAILURE.");
49
50 /** \brief all possible commutative set operations */
51 enum class SetConcat : unsigned char { UNION, INTERSECTION, SYM_DIFFERENCE, FORMULA };
52 /** \brief types of different return possibilities for program */
53 enum class SetQuery : unsigned char { RETURN_SET, CARDINALITY, ISEMPTY, SUBSET, SUPERSET, CONTAINS_ELEMENT, SET_EQUALITY };
54
55 using element_t = std::string; ///< basic type of element in sets, must base on character type char
56 using el_comp_t = std::function<bool(element_t const&, element_t const&)>; ///< type of function for comparing elements
57 /**
58 \brief basic type for sets
59 \details A hash set would be faster, but:
60 - even with 1,000,000 elements only about with factor 1.7 or 1.8 (depending on several other influences)
61 - no advantage in memory saving
62 - output is not sorted (at least one more option necessary for letting user to decide if this is acceptable)
63 - much more source code (sorted/unsorted output; overhead for case-insensitive hash function etc.)
64 */
65 using set_t = std::set<element_t, el_comp_t>;
66
67 /** \brief Encapsulates all options for reading and parsing input streams. */
68 class InputOptions
69 {
70 public:
71 el_comp_t element_comp; ///< comparator for set elements (e. g. case-insensitive comparison)
72 bool include_empty_elements; ///< empty input elements are included instead of ignored
73 boost::regex input_element_regex; ///< regular expression describing an input element (use `boost` instead of `std` because `match_partial` is needed)
74 boost::regex input_separator_regex; ///< regular expression describing an input separator
75 std::string output_separator; ///< string elements shall be separated with in output
76 std::string trim_characters; ///< list of characters that shall be ignored in element at begin and end
77 } input_opts;
78
79 std::vector<std::string> input_filenames;
80
81
82 /**
83 \brief Parses escape sequences like `\n` and `\t` to “real” characters (e. g. ``.\'\\\"`` gets to ``.'\"``).
84 \details Escape sequences ``\'``, `\"`, `\?`, `\\`, `\f`, `\n`, `\r`, `\t`, `\v` are supported.
85 \param escape_seq sequence to unescape
86 \note There should be an `std` or `boost` library for a simple task like unescaping, but it seems that there isn’t (yet).
87 Replace this function in the future if possible.
88 \throws std::invalid_argument
89 */
90 std::string unescape_sequence(std::string const& escape_seq)
91 {
92 std::map<char, char> const escape_characters =
93 {
94 { '\'', '\'' },
95 { '\"', '\"' },
96 { '?', '?' },
97 { '\\', '\\' },
98 { 'f', '\f' },
99 { 'n', '\n' },
100 { 'r', '\r' },
101 { 't', '\t' },
102 { 'v', '\v' }
103 };
104
105 std::string result;
106 for (auto curr_char = escape_seq.begin(); curr_char != escape_seq.end(); ++curr_char)
107 {
108 if (*curr_char == '\\')
109 {
110 if (++curr_char == escape_seq.end())
111 throw std::invalid_argument("Parsing failed: Backslash at end of \"" + escape_seq + "\" is invalid.");
112 auto second_char = escape_characters.find(*curr_char);
113 if (second_char != escape_characters.end())
114 result.push_back(second_char->second);
115 else
116 throw std::invalid_argument(std::string("Parsing failed: ") +
117 "Escape sequence \"\\" + *curr_char + "\" in argument \"" + escape_seq + "\" is not supported.");
118 }
119 else
120 {
121 result.push_back(*curr_char);
122 }
123 }
124
125 return result;
126 }
127
128
129 std::map<std::string, set_t> inputstream_cache; // in case an input is needed more than once, do not parse input file again but cache it
130 std::map<std::string, int> inputstream_to_usagecount; // should in general be 1 for all entries
131
132 /**
133 \brief Returns all elements from file as a set.
134 \param filename name of input file with elements to parse
135 */
136 set_t file_to_set(std::string const& filename)
137 {
138 set_t result(input_opts.element_comp);
139
140 // handle caching of input streams in case they are needed multiple times
141 std::map<std::string, int>::iterator usage_count = inputstream_to_usagecount.find(filename);
142 --usage_count->second;
143 std::map<std::string, set_t>::iterator cached_input_it = inputstream_cache.find(filename);
144 if (cached_input_it != inputstream_cache.end())
145 {
146 if (usage_count->second == 0)
147 {
148 result = std::move(cached_input_it->second); // not needed anymore
149 }
150 else
151 result = cached_input_it->second; // copy
152 return result;
153 }
154
155 // set input stream (can be std::cin)
156 std::ifstream inputfile;
157 if (filename != "-")
158 {
159 inputfile.open(filename);
160 if (!inputfile)
161 throw std::runtime_error("input file '" + filename + "' could not be opened.");
162 }
163 std::istream& inputstream = (filename == "-" ? std::cin : inputfile);
164
165 // lambda for running adjust_element and inserting it right after (according to options)
166 auto adjust_and_insert_element = [&result](element_t el_str, bool check_element_regex)
167 {
168 if (!check_element_regex || input_opts.input_element_regex.empty() ||
169 boost::regex_match(el_str, input_opts.input_element_regex))
170 {
171 boost::trim_if(el_str, boost::is_any_of(input_opts.trim_characters));
172 if (!el_str.empty() || input_opts.include_empty_elements)
173 result.insert(std::move(el_str));
174 }
175 };
176
177 // general idea: parse input according to regular expression describing an element or a separator
178
179 bool use_separator_regex = input_opts.input_element_regex.empty();
180 boost::regex const& regex = (use_separator_regex ? input_opts.input_separator_regex : input_opts.input_element_regex);
181
182 // effect of value of initial buffer size is practically unmeasurable, so just take a nice value of form 2^n,
183 // at least it should be much bigger than expected size of elements
184 std::size_t buffersize = 4096;
185 std::size_t used_buffer = 0;
186 // use unique pointer instead of "plain" pointer so that there is no memory leak in case of exception
187 std::unique_ptr<char[]> buffer(new char[buffersize]);
188 do
189 {
190 inputstream.read(buffer.get() + used_buffer, buffersize - used_buffer);
191 char const* const buffer_end = buffer.get() + used_buffer + inputstream.gcount();
192 char const* buffer_handled_until = buffer.get();
193
194 // the whole following thing could be much easier by using a bidirectional input iterator here, but:
195 // do not do this because input "file" could be a named pipe, stream or similar (no backwards iterating would be possible!)
196 // so you have to manage the buffer (and release parts of it) yourself
197 // for a more efficient solution (hopefully in the near future) see <https://svn.boost.org/trac/boost/ticket/11776>
198 boost::cregex_iterator curr_match(buffer.get(), buffer_end, regex, boost::match_default | boost::match_partial);
199 // add element to set when ...
200 while (curr_match != boost::cregex_iterator() &&
201 curr_match->begin()->matched && // ... match is a full match and ...
202 (!inputstream || // ... when file is at end or ...
203 // (see next line) when match does not touch end of buffer (otherwise element could be longer, e. g. partial match)
204 !boost::regex_match(curr_match->begin()->first, buffer_end, regex, boost::match_default | boost::match_partial)))
205 {
206 if (use_separator_regex)
207 {
208 adjust_and_insert_element(element_t(buffer_handled_until, curr_match->begin()->first), true);
209 buffer_handled_until = curr_match->begin()->second;
210 }
211 else
212 {
213 adjust_and_insert_element(curr_match->str(), false);
214 }
215 ++curr_match;
216 }
217 if (!use_separator_regex)
218 // the last match is always a partial match except full match touches buffer end (or buffer is empty)
219 // so mark begin of last match as new begin of buffer when filling it up in next round of do-while-loop
220 buffer_handled_until = (curr_match != boost::cregex_iterator() ? curr_match->begin()->first :
221 buffer_end);
222
223 used_buffer = buffer_end - buffer_handled_until;
224 if (buffer_handled_until == buffer.get())
225 {
226 // if current element fills the whole buffer, buffer is too small and thus doubled
227 buffersize *= 2;
228 std::unique_ptr<char[]> new_buffer(new char[buffersize]);
229 std::memmove(new_buffer.get(), buffer_handled_until, used_buffer);
230 buffer = std::move(new_buffer);
231 }
232 else
233 {
234 // move the rest of new element (buffer_handled_until) to beginning of buffer and mark it as used
235 std::memmove(buffer.get(), buffer_handled_until, used_buffer);
236 }
237 } while (inputstream);
238
239 if (use_separator_regex && used_buffer > 0)
240 adjust_and_insert_element(element_t(buffer.get(), used_buffer), true);
241
242 if (usage_count->second > 0)
243 inputstream_cache[filename] = result; // cache result because it is needed later
244
245 return result;
246 }
247
248 /**
249 \brief Prints complete warning message to console `std::cerr` including hint, that this is a warning.
250 \param warning_message warning message without new line at end
251 */
252 inline void print_warning(std::string const& warning_message)
253 {
254 std::cerr << "Warning: " << warning_message << "\n";
255 }
256
257 /**
258 \brief Prints complete error message to console `std::cerr` including hint, that this is an error.
259 \param error_message error message without new line at end
260 \return exit code `EXIT_FAILURE` (normally 1)
261 */
262 inline int print_error(std::string const& error_message)
263 {
264 std::cerr << "Error: " << error_message << "\n";
265 return EXIT_FAILURE;
266 }
267
268 /**
269 \brief Prints complete error message to console `std::cerr` that an option used a faulty parameter.
270 \param option option with faulty parameter, i. e. `combination` or `output` (without minus signs)
271 \param parameter faulty parameter (e. g. `intersect` instead of `intersection`)
272 \return exit code `EXIT_FAILURE` (normally 1)
273 */
274 inline int print_unsupported_parameter_error(std::string const& option, std::string const& parameter)
275 {
276 return print_error("option '--" + option + "' does not support a parameter '" + parameter + "'.");
277 }
278
279 class invalid_formula_exception : public std::invalid_argument
280 {
281 public:
282 invalid_formula_exception(std::string const& error_message)
283 : invalid_argument(error_message) {}
284 };
285
286 enum class SetCombineOperation
287 {
288 Intersection,
289 SymmetricDiff,
290 Union,
291 SetDifference
292 };
293
294 /// Combine `output_set` with `next_input` via `operation` and store result in `output_set`.
295 void combine_with_next_set(set_t& output_set, SetCombineOperation operation, set_t&& next_input)
296 {
297 switch (operation)
298 {
299 case SetCombineOperation::Intersection:
300 {
301 set_t intersect(input_opts.element_comp);
302 for (element_t const& el : output_set)
303 if (next_input.contains(el))
304 intersect.insert(el);
305
306 output_set = std::move(intersect);
307 break;
308 }
309 case SetCombineOperation::SymmetricDiff:
310 for (element_t const& el : next_input)
311 {
312 set_t::const_iterator it = output_set.find(el);
313 if (it != output_set.end())
314 output_set.erase(it);
315 else
316 output_set.insert(el);
317 }
318 break;
319 case SetCombineOperation::Union:
320 output_set.merge(std::move(next_input));
321 break;
322 case SetCombineOperation::SetDifference:
323 for (element_t const& el : next_input)
324 output_set.erase(el);
325 break;
326 default: // can never happen
327 assert(false && "Internal error, a set comination type is not covered.");
328 }
329 }
330
331 /**
332 \brief Move `formula_it` forward so it shows to non-whitespace (= tab, space, new line).
333 \return `true` if next character is valid, `false` if string is at end (= null character)
334 */
335 bool goto_next_nonwhitespace(std::string::const_iterator& formula_it)
336 {
337 while (*formula_it && std::isspace(*formula_it))
338 ++formula_it;
339 return *formula_it;
340 }
341
342 set_t evaluate_formula(std::string::const_iterator& formula_it, bool within_brackets = false); // needed forward declaration
343
344 /**
345 \brief Calculate next complete term represented by input stream index or by term in brackets.
346 \details E. g. "3 & 4" results in set of input stream 3 and `formula_it` is moved to character after '&',
347 whereas "(3 & 4)" would include calculation of intersection and set `formula_it` to end of string.
348 A term is always expected, i. e. formula must start with number or opening bracket and an empty string triggers an exception.
349 \param formula_it iterator of formula where evaluation shall start, is moved forward to next unread character
350 \return set of evaluated term
351 */
352 set_t evaluate_next_term(std::string::const_iterator& formula_it)
353 {
354 set_t result;
355 if (!goto_next_nonwhitespace(formula_it))
356 throw invalid_formula_exception("a term is missing");
357 if (*formula_it == '(')
358 {
359 ++formula_it;
360 result = evaluate_formula(formula_it, true);
361 }
362 else
363 {
364 std::string::size_type number_read_chars;
365 unsigned long inputstream_index;
366 try
367 {
368 inputstream_index = std::stoul(&*formula_it, &number_read_chars); // throws std::invalid_argument or std::out_of_range
369 }
370 catch (std::logic_error const&)
371 {
372 throw invalid_formula_exception("a positive integer or opening bracket is expected");
373 }
374 if (inputstream_index < 1 || inputstream_index > input_filenames.size())
375 throw invalid_formula_exception("input stream indices should be in the range from 1 to " + std::to_string(input_filenames.size()));
376 result = file_to_set(input_filenames[inputstream_index - 1]);
377 formula_it += number_read_chars;
378 }
379 return result;
380 }
381
382 /**
383 \brief Calculate resulting set from formula.
384 \param formula_it iterator of formula where evaluation shall start, is moved forward to next unread character
385 \param within_brackets for recursively evaluating "subformulas" within brackets; when true, stops directly after closing bracket and returns
386 \return set of evaluated formula
387 */
388 set_t evaluate_formula(std::string::const_iterator& formula_it, bool within_brackets)
389 {
390 // STEP A: a formula contains at least one term, so read it
391 set_t result = evaluate_next_term(formula_it);
392
393 class OperationSetPair
394 {
395 public:
396 SetCombineOperation operation;
397 set_t set;
398 };
399 std::stack<OperationSetPair> op_set_pairs;
400 auto shorten_stack = [&]() // remove top element of stack while letting total value of all operations unchanged
401 {
402 OperationSetPair top_term = std::move(op_set_pairs.top());
403 op_set_pairs.pop();
404 set_t& base_term = (op_set_pairs.empty() ? result : op_set_pairs.top().set);
405 combine_with_next_set(base_term, top_term.operation, std::move(top_term.set));
406 };
407
408 while (goto_next_nonwhitespace(formula_it))
409 {
410 // either STEP B: return from recursive call when end of subformula within brackets is reached
411 if (*formula_it == ')')
412 {
413 if (!within_brackets)
414 throw invalid_formula_exception("found closing bracket without opening bracket");
415 ++formula_it;
416 within_brackets = false;
417 break;
418 }
419
420 // or STEP C
421 // STEP C-1: parse operation
422 std::map<char, SetCombineOperation> const combineoperation_by_operator = {
423 {'&', SetCombineOperation::Intersection},
424 {'^', SetCombineOperation::SymmetricDiff},
425 {'|', SetCombineOperation::Union},
426 {'-', SetCombineOperation::SetDifference}
427 };
428 std::map<char, SetCombineOperation>::const_iterator next_operation = combineoperation_by_operator.find(*formula_it);
429 if (next_operation == combineoperation_by_operator.end())
430 throw invalid_formula_exception("an operator like &, |, ^, or - is missing");
431 ++formula_it;
432
433 // STEP C-2: parse value
434 set_t next_set = evaluate_next_term(formula_it);
435
436 // STEP C-3: handle new value-operation-pair
437 if (next_operation->second == SetCombineOperation::Intersection) // has highest priority, calculate immediately for better performance
438 {
439 set_t& base_term = (op_set_pairs.empty() ? result : op_set_pairs.top().set);
440 combine_with_next_set(base_term, next_operation->second, std::move(next_set));
441 }
442 else // try to merge elements from stack when their operation is as least as important as current operation
443 {
444 while (!op_set_pairs.empty() && next_operation->second >= op_set_pairs.top().operation)
445 shorten_stack();
446 op_set_pairs.push(OperationSetPair{.operation = next_operation->second, .set = std::move(next_set)});
447 }
448 }
449
450 if (within_brackets)
451 throw invalid_formula_exception("a closing bracket is missing");
452
453 // STEP D: handle remaining stack of operations and sets
454 while (!op_set_pairs.empty())
455 shorten_stack();
456
457 return result;
458 }
459
460 /**
461 \brief Main function of program: take command line options and arguments and execute output.
462 \throws std::runtime_error
463 */
464 int execute_setop(int argc, char* argv[])
465 {
466 // needed variables, mainly options and arguments from command line
467 bool quiet, verbose, ignore_case;
468 std::string formula, inputstream_for_set_comparison, separator_format, element_format;
469 element_t element_for_contains_check;
470 std::vector<std::string> combine_parameters, setdifference_filenames, output_parameters;
471
472
473 // PARSE COMMAND LINE
474
475 namespace po = boost::program_options;
476 po::options_description visible_options("Options");
477 visible_options.add_options()
478 ("help", "produce this help message and exit")
479 ("version", "output name and version")
480
481 ("ignore-case,C", po::bool_switch(&ignore_case)->default_value(false), "handle input elements case-insensitive")
482 ("include-empty", po::bool_switch(&input_opts.include_empty_elements)->default_value(false), "don’t ignore empty elements (these can come from empty lines, trimming, etc.)")
483 ("input-separator,n", po::value(&separator_format), "describe the form of an input separator as regular expression in ECMAScript syntax; "
484 "defaults to new line only if --input-element is not present; i. e. don’t forget to include the new line character \\n when you set the input element manually, when desired!")
485 ("input-element,l", po::value(&element_format), "describe the form of input elements as regular expression in ECMAScript syntax")
486 ("output-separator,o", po::value(&input_opts.output_separator)->default_value("\\n"), "string for separating output elements; escape sequences are allowed")
487 ("trim,t", po::value(&input_opts.trim_characters), "trim all given characters at beginning and end of elements (escape sequences allowed)")
488
489 ("combine", po::value(&combine_parameters)->multitoken()/*->default_value("union")*/, "define combination operation applied to given input streams; "
490 "possible parameters are 'union' (default), 'intersection', 'symmetric-difference', and 'formula <value>'")
491 ("subtract", po::value(&setdifference_filenames)->multitoken(), "subtract all elements of all given streams from output set")
492
493 ("output", po::value(&output_parameters)->multitoken()/*->default_value("set")*/, "whether to output determined set or a certain information of this set instead; "
494 "possible parameters are:\n"
495 "set (default): stream all output elements\n"
496 "count: just output number of (different) elements, don’t list them\n"
497 "is-empty: check if resulting set is empty\n"
498 "contains <element-string>: check if given element is contained in set\n"
499 "equals <input-stream>: check set equality, i. e. check if output corresponds with content of <input-stream>\n"
500 "has-subset <input-stream>: check if content of <input-stream> is subset of output set\n"
501 "has-superset <input-stream>: check if content of <input-stream> is superset of output set")
502 ("quiet", po::bool_switch(&quiet)->default_value(false),
503 "suppress all output messages in case of special queries (e. g. when check if element is contained in set)");
504
505 po::options_description invisible_options("Invisible options");
506 invisible_options.add_options()("inputfile", po::value(&input_filenames)->composing(), "");
507 po::options_description deprecated_options("Deprecated options");
508 deprecated_options.add_options()
509 ("union,u", "")
510 ("intersection,i", "")
511 ("symmetric-difference,s", "")
512 ("difference,d", po::value(&setdifference_filenames)->composing(), "")
513 ("verbose", "")
514 ("count,#", "")
515 ("is-empty", "")
516 ("contains,c", po::value(&element_for_contains_check), "")
517 ("equal,e", po::value(&inputstream_for_set_comparison), "")
518 ("subset,b", po::value(&inputstream_for_set_comparison), "")
519 ("superset,p", po::value(&inputstream_for_set_comparison), "");
520 po::options_description all_options("All options");
521 all_options.add(invisible_options).add(deprecated_options).add(visible_options);
522
523 po::variables_map opt_map;
524 po::positional_options_description arguments;
525 arguments.add("inputfile", -1);
526 try
527 {
528 po::parsed_options parsed = po::command_line_parser(argc, argv).options(all_options).positional(arguments).run();
529 po::store(parsed, opt_map);
530 po::notify(opt_map);
531 }
532 catch (po::error const& poexc)
533 {
534 return print_error(std::string("failed to process command line parameters: ") + poexc.what() +
535 "\nTry calling the program with option '--help'.");
536 }
537
538 if (opt_map.contains("help"))
539 {
540 std::cout <<
541 "Apply set operations like union, intersection, or set difference to input files "
542 "and print resulting set (sorted and with unique string elements) to standard output or give answer to special queries like number of elements.\n\n"
543
544 "Usage:\n"
545 PROGRAM_NAME " [input-stream]* [-C] [--include-empty] [--input-separator <value>] [--input-element <value>] [--trim <value>] "
546 "[--combine (union|intersection|symmetric-difference|formula <value>)] [--subtract [input-stream]*] "
547 "[--output (set|count|is-empty|contains <value>|equals <input-stream>|has-subset <input-stream>|has-superset <input-stream>)] "
548 "[--output-separator <value>] [--quiet]\n\n"
549
550 << visible_options
551
552 << "No input filename or '-' is equal to reading from standard input. When an input stream occurs multiple times in the calling command, "
553 "it is read only once and cached.\n\n"
554
555 << "The sequence of events of " PROGRAM_NAME " is as follows:\n"
556 "At first, all input files are parsed and combined according to the --combine option. "
557 "After that, all inputs from option --subtract are parsed and removed from result of first step. "
558 "Finally, the desired output given from option --output is printed to screen: "
559 "the set itself, or its number of elements, or a comparison to another set etc.\n\n"
560
561 "The combination type 'formula' needs an additional string mainly consisting of positive integers and combining operators. "
562 "The integers 1, 2, etc. represent the first, second, etc. input stream; possible operators are '&' for intersection, "
563 "'^' for symmetric difference, '|' for union, and '-' for set difference. At the moment, they are prioritized in that order (i. e. &, ^, |, -), "
564 "but this may change in the future. Use brackets for being explicit about the order of evaluation. Example: "
565 "--combine formula '(1 | 2) & 3' unites first and second input stream and intersects the result with third input stream.\n\n"
566
567 "By default each line of an input stream is considered to be an element, you can change this by defining regular expressions "
568 "within the options --input-separator or --input-element. When using both, the input stream is first split according to the separator "
569 "and after that filtered by the desired input element form. "
570 "After finding the elements they are finally trimmed according to the argument given with --trim.\n"
571 "The option --ignore-case lets you treat Word and WORD equal, only the first occurrence of all input streams is considered. "
572 "Note that --ignore-case does not affect the regular expressions used in --input-separator and --input-element.\n\n"
573 "When describing strings and characters for the output separator or for the option --trim you can use escape sequences like " R"(\t, \n, \" and \'. )"
574 "But be aware that some of these sequences " R"((especially \\ and \"))" " might be interpreted by your shell before passing the string to "
575 PROGRAM_NAME ". In that case you have to use " R"(\\\\ respectively \\\" just for describing a \ or a ". )"
576 "You can check your shell’s behavior with\n"
577 R"(echo "\\ and \"")" "\n\n"
578 "Special boolean queries (e. g. check if element is contained in set) return exit code EXIT_SUCCESS (= " << std::to_string(EXIT_SUCCESS)
579 << ") when the answer is 'yes' and otherwise (e. g. element not contained in set) an exit code that is guaranteed to be unequal "
580 << "to EXIT_SUCCESS and to EXIT_FAILURE (= " << std::to_string(EXIT_FAILURE) << "). This way, " PROGRAM_NAME " can be used in the shell. "
581 << "With option --quiet a verbose result message is omitted for boolean queries.\n\n"
582
583 "Examples:\n"
584 PROGRAM_NAME R"( A.txt --subtract B.txt --output contains ":fooBAR-:" --trim ":-\t" --ignore-case)"
585 "\n\t" "case-insensitive check if element 'foobar' is contained in A minus B\n"
586 PROGRAM_NAME R"( A.txt - B.txt --combine intersection --input-element "\d+")"
587 "\n\t" "output intersection of console, A, and B, where elements are recognized as strings of digits with at least one character; "
588 "i. e. elements are non-negative integers\n"
589 PROGRAM_NAME " A.txt B.txt --combine symmetric-difference --input-separator [[:space:]-]"
590 "\n\t" "find all elements contained in either A or B, not both, where a whitespace" R"( (i. e. \v \t \n \r \f or space) )"
591 "or a minus is interpreted as a separator between elements\n\n"
592
593 "For bug reports, use the issue tracker at\n"
594 "https://github.com/phisigma/setop.\n";
595
596 return EXIT_SUCCESS;
597 }
598
599 for (boost::shared_ptr<po::option_description> const& deprecated_optdesc : deprecated_options.options())
600 {
601 if (opt_map.contains(deprecated_optdesc->long_name()))
602 print_warning("option '--" + deprecated_optdesc->long_name() + "' is deprecated and will be removed in later versions of "
603 PROGRAM_NAME + ".");
604 }
605
606 if (opt_map.contains("version"))
607 {
608 std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION << std::endl;
609 return EXIT_SUCCESS;
610 }
611
612
613 // CHECK PLAUSIBILITY OF INPUT OPTIONS AND ARGUMENTS AND HANDLE THESE OPTIONS
614
615 verbose = opt_map.contains("verbose");
616 if (quiet & verbose)
617 {
618 print_warning("the options '--quiet' and '--verbose' must not be combined. Both ignored.");
619 quiet = verbose = false;
620 }
621
622 // report and delete redundant entries for set differences
623 std::map<std::string, int> setdifference_streams_usagecount;
624 for (std::string const& inputstream : setdifference_filenames)
625 ++setdifference_streams_usagecount[inputstream];
626 for (auto const& [setdifference_stream, usage_count] : setdifference_streams_usagecount)
627 {
628 if (usage_count > 1)
629 {
630 print_warning("option '--" + std::string(opt_map.contains("subtract") ? "subtract" : "difference") + "' contains input stream '"
631 + setdifference_stream + "' multiple times. Redundant entries ignored.");
632 for (int curr_redundant_entry_index = 1; curr_redundant_entry_index < usage_count; ++curr_redundant_entry_index)
633 {
634 std::vector<std::string>::const_iterator found_redundant_entry =
635 std::ranges::find_last(setdifference_filenames, setdifference_stream).begin(); // remove from back so order stays preserved
636 assert(found_redundant_entry != setdifference_filenames.cend() && "Internal error, handling of multiple set difference streams is faulty.");
637 setdifference_filenames.erase(found_redundant_entry);
638 }
639 }
640 }
641
642 if (opt_map.count("combine") + opt_map.count("union") + opt_map.count("intersection") + opt_map.count("symmetric-difference") > 1)
643 return print_error("the options '--combine', '--union', '--intersection', and '--symmetric difference' must not be combined.");
644 SetConcat setconcat_type;
645 if (opt_map.contains("combine"))
646 {
647 int number_parameters = combine_parameters.size();
648 if (number_parameters < 1)
649 return print_error("option '--combine' needs at least one parameter.");
650
651 std::map<std::string, SetConcat> concattype_by_parameter =
652 {{"union", SetConcat::UNION}, {"intersection", SetConcat::INTERSECTION},
653 {"symmetric-difference", SetConcat::SYM_DIFFERENCE}, {"formula", SetConcat::FORMULA}};
654 std::string const& combine_type_str = combine_parameters.front();
655 std::map<std::string, SetConcat>::const_iterator found_concattype_it = concattype_by_parameter.find(combine_type_str);
656 if (found_concattype_it == concattype_by_parameter.end())
657 return print_unsupported_parameter_error("combine", combine_type_str);
658 else
659 setconcat_type = found_concattype_it->second;
660
661 int needed_number_parameters = setconcat_type == SetConcat::FORMULA ? 2 : 1;
662 if (number_parameters != needed_number_parameters)
663 {
664 return print_error(number_parameters < needed_number_parameters ?
665 "option '--combine' with parameter '" + combine_type_str + "' needs an additional parameter." :
666 "option '--combine' with parameter '" + combine_type_str + "' does not need additional parameters. Found unneeded value '" + combine_parameters[2] + "'.");
667 }
668 if (number_parameters == 2)
669 {
670 formula = combine_parameters[1];
671
672 // analyze formula for missing input stream numbers and setup input stream usage counts
673 std::regex integer_regex("[[:digit:]]+");
674 std::map<unsigned long, int> inputstream_number_to_usagecount;
675 std::sregex_iterator curr_found_integer(formula.begin(), formula.end(), integer_regex);
676 for (; curr_found_integer != std::sregex_iterator() /*== end*/; ++curr_found_integer)
677 {
678 ++inputstream_number_to_usagecount[std::stoul(curr_found_integer->str())];
679 }
680
681 if (inputstream_number_to_usagecount.begin()->first > 0 && inputstream_number_to_usagecount.rbegin()->first <= input_filenames.size())
682 // out-of-range error is handled later (to show exact position in formula), just exclude this case here to avoid error on array access
683 {
684 for (std::size_t expected_inputstream_index = 0; expected_inputstream_index < input_filenames.size(); ++expected_inputstream_index)
685 if (!inputstream_number_to_usagecount.contains(expected_inputstream_index + 1))
686 print_warning("the number " + std::to_string(expected_inputstream_index + 1) + " is not used in the formula "
687 "and thus the input stream '" + input_filenames[expected_inputstream_index] + "' is ignored.");
688
689 for (auto const& [inputstream_number, usagecount] : inputstream_number_to_usagecount)
690 inputstream_to_usagecount[input_filenames[inputstream_number - 1]] += usagecount;
691 }
692 for (std::string const& setdifference_filename : setdifference_filenames)
693 ++inputstream_to_usagecount[setdifference_filename];
694 if (!inputstream_for_set_comparison.empty())
695 ++inputstream_to_usagecount[inputstream_for_set_comparison];
696 }
697 }
698 else
699 {
700 setconcat_type =
701 opt_map.contains("intersection") ? SetConcat::INTERSECTION :
702 opt_map.contains("symmetric-difference") ? SetConcat::SYM_DIFFERENCE :
703 SetConcat::UNION;
704 }
705
706 if (opt_map.count("difference") + opt_map.count("subtract") > 1)
707 return print_error("the options '--difference' and '--subtract' must not be combined.");
708
709 if (opt_map.count("output") + opt_map.count("count") + opt_map.count("is-empty") + opt_map.count("subset")
710 + opt_map.count("superset") + opt_map.count("contains") + opt_map.count("equal") > 1)
711 return print_error("the options '--output', '--count', '--is-empty', '--subset', '--superset', '--contains', and '--equal' must not be combined.");
712 SetQuery output_type;
713 bool modern_outputoption_used = opt_map.contains("output");
714 if (modern_outputoption_used)
715 {
716 int number_parameters = output_parameters.size();
717 if (number_parameters < 1)
718 return print_error("option '--output' needs at least one parameter.");
719
720 std::map<std::string, SetQuery> outputtype_by_parameter =
721 {{"set", SetQuery::RETURN_SET}, {"count", SetQuery::CARDINALITY}, {"is-empty", SetQuery::ISEMPTY}, {"contains", SetQuery::CONTAINS_ELEMENT},
722 {"equals", SetQuery::SET_EQUALITY}, {"has-subset", SetQuery::SUBSET}, {"has-superset", SetQuery::SUPERSET}};
723 std::string const& output_type_str = output_parameters.front();
724 std::map<std::string, SetQuery>::const_iterator found_outputtype_it = outputtype_by_parameter.find(output_type_str);
725 if (found_outputtype_it == outputtype_by_parameter.end())
726 return print_unsupported_parameter_error("output", output_type_str);
727 else
728 output_type = found_outputtype_it->second;
729
730 int needed_number_parameters = std::set({SetQuery::RETURN_SET, SetQuery::CARDINALITY, SetQuery::ISEMPTY}).contains(output_type) ? 1 : 2;
731 if (number_parameters != needed_number_parameters)
732 {
733 return print_error(number_parameters < needed_number_parameters ?
734 "option '--output' with parameter '" + output_type_str + "' needs an additional parameter." :
735 "option '--output' with parameter '" + output_type_str + "' does not need additional parameters. Found unneeded value '" + output_parameters[2] + "'.");
736 }
737 if (number_parameters == 2)
738 (output_type == SetQuery::CONTAINS_ELEMENT ? element_for_contains_check : inputstream_for_set_comparison) = output_parameters[1];
739 }
740 else
741 {
742 output_type =
743 opt_map.contains("count") ? SetQuery::CARDINALITY :
744 opt_map.contains("is-empty") ? SetQuery::ISEMPTY :
745 opt_map.contains("subset") ? SetQuery::SUBSET :
746 opt_map.contains("superset") ? SetQuery::SUPERSET :
747 opt_map.contains("contains") ? SetQuery::CONTAINS_ELEMENT :
748 opt_map.contains("equal") ? SetQuery::SET_EQUALITY :
749 SetQuery::RETURN_SET;
750 }
751
752 // parse escape sequences of trim characters and output separator to "real" characters (e. g. ".\'\\" gets ".'\")
753 try
754 {
755 input_opts.trim_characters = unescape_sequence(input_opts.trim_characters);
756 input_opts.output_separator = unescape_sequence(input_opts.output_separator);
757 }
758 catch (std::invalid_argument const& e)
759 {
760 return print_error(e.what());
761 }
762
763 // check if regexes are ok
764 // separator "\n" is default when nothing else is given
765 if (element_format.empty() && separator_format.empty())
766 separator_format = "\\n";
767 for (auto [string_to_parse, resulting_regex_ref] : std::vector<std::pair<std::string const&, boost::regex&>>{
768 {element_format, input_opts.input_element_regex},
769 {separator_format, input_opts.input_separator_regex}})
770 {
771 boost::regex::flag_type regex_flags = boost::regex_constants::ECMAScript | boost::regex_constants::optimize;
772 if (!string_to_parse.empty())
773 {
774 try
775 {
776 resulting_regex_ref = boost::regex(string_to_parse, regex_flags);
777 }
778 catch (boost::regex_error const&)
779 {
780 return print_error("\"" + string_to_parse + "\" is not a valid regular expression.");
781 }
782 }
783 }
784
785 // handle case-insensitive
786 if (ignore_case)
787 input_opts.element_comp = std::bind(
788 boost::algorithm::ilexicographical_compare<element_t, element_t>, std::placeholders::_1, std::placeholders::_2, std::locale()
789 );
790 else
791 input_opts.element_comp = boost::algorithm::lexicographical_compare<element_t, element_t>;
792
793 // use console as input when no file given
794 if (input_filenames.empty())
795 input_filenames.push_back("-");
796
797 // console must not be used multiple times (= inputstream "-")
798 std::vector<std::string> list_of_inputstreams(input_filenames);
799 list_of_inputstreams.insert(list_of_inputstreams.cend(), setdifference_filenames.cbegin(), setdifference_filenames.cend());
800 if (!inputstream_for_set_comparison.empty())
801 list_of_inputstreams.push_back(inputstream_for_set_comparison);
802 bool found_console_as_input = false;
803 for (std::string const& inputstream : list_of_inputstreams)
804 if (inputstream == "-")
805 {
806 if (found_console_as_input)
807 return print_error("reading from standard input via '-' is only allowed once within the calling " PROGRAM_NAME " command.");
808 else
809 found_console_as_input = true;
810 }
811
812
813 // PROCESS CALCULATIONS IN THREE STEPS
814
815 // STEP 1/3: execute all commutative set combinations (union, intersection, symmetric difference) or formula
816
817 set_t output_set(input_opts.element_comp);
818 if (setconcat_type == SetConcat::FORMULA)
819 {
820 std::string::const_iterator formula_it = formula.cbegin();
821 try
822 {
823 output_set = evaluate_formula(formula_it);
824 }
825 catch (invalid_formula_exception const& formula_exception)
826 {
827 return print_error(std::string("invalid formula, ") + formula_exception.what() + "\n" + formula + "\n"
828 + std::string(formula_it - formula.cbegin(), ' ') + "^");
829 }
830 }
831 else
832 {
833 for (auto curr_fn_it = input_filenames.cbegin(); curr_fn_it != input_filenames.cend(); ++curr_fn_it)
834 {
835 if (curr_fn_it == input_filenames.cbegin()) // if it is the first input stream
836 {
837 output_set = file_to_set(*curr_fn_it);
838 }
839 else
840 {
841 SetCombineOperation operation = setconcat_type == SetConcat::UNION ? SetCombineOperation::Union :
842 setconcat_type == SetConcat::INTERSECTION ? SetCombineOperation::Intersection :
843 SetCombineOperation::SymmetricDiff;
844 combine_with_next_set(output_set, operation, file_to_set(*curr_fn_it));
845 }
846 }
847 }
848
849
850 // STEP 2/3: execute all set differences, that is erase all desired elements from current output set
851
852 for (std::string const& filename : setdifference_filenames)
853 {
854 combine_with_next_set(output_set, SetCombineOperation::SetDifference, file_to_set(filename));
855 }
856
857
858 // STEP 3/3: calculate output depending on set query
859
860 // print success and failure messages from query and return exit code of program
861 auto answer_query = [quiet, verbose, modern_outputoption_used](bool success, std::string const& success_msg, std::string const& unsuccess_msg) -> int
862 {
863 if (modern_outputoption_used)
864 {
865 if (!quiet)
866 std::cout << (success ? success_msg : unsuccess_msg);
867 return success ? EXIT_SUCCESS : EXIT_QUERY_NEGATIVE;
868 }
869 else
870 {
871 if (success)
872 {
873 if (verbose)
874 std::cout << success_msg;
875 return EXIT_SUCCESS;
876 }
877 else
878 {
879 if (!quiet)
880 std::cout << unsuccess_msg;
881 return EXIT_QUERY_NEGATIVE;
882 }
883 }
884 };
885
886 switch (output_type)
887 {
888 case SetQuery::RETURN_SET:
889 for (element_t const& el : output_set)
890 std::cout << el << input_opts.output_separator;
891 return EXIT_SUCCESS;
892 case SetQuery::CARDINALITY:
893 std::cout << output_set.size() << "\n";
894 return EXIT_SUCCESS;
895 case SetQuery::ISEMPTY:
896 return answer_query(
897 output_set.empty(),
898 "Resulting set is empty.\n",
899 "Resulting set is not empty.\n");
900 case SetQuery::CONTAINS_ELEMENT:
901 boost::trim_if(element_for_contains_check, boost::is_any_of(input_opts.trim_characters));
902 return answer_query(
903 output_set.contains(element_for_contains_check),
904 "\"" + element_for_contains_check + "\" is contained in set.\n",
905 "Input does not contain element \"" + element_for_contains_check + "\".\n");
906 case SetQuery::SET_EQUALITY:
907 return answer_query(
908 file_to_set(inputstream_for_set_comparison) == output_set,
909 "Resulting set is equal to input \"" + inputstream_for_set_comparison + "\".\n",
910 "Resulting set is not equal to input \"" + inputstream_for_set_comparison + "\".\n");
911 case SetQuery::SUBSET:
912 return answer_query(
913 std::ranges::includes(output_set, file_to_set(inputstream_for_set_comparison)),
914 "\"" + inputstream_for_set_comparison + "\" is a subset.\n",
915 "\"" + inputstream_for_set_comparison + "\" is not a subset.\n");
916 case SetQuery::SUPERSET:
917 return answer_query(
918 std::ranges::includes(file_to_set(inputstream_for_set_comparison), output_set),
919 "\"" + inputstream_for_set_comparison + "\" is a superset.\n",
920 "\"" + inputstream_for_set_comparison + "\" is not a superset.\n");
921 default:
922 // never happens because all cases are handled above
923 return EXIT_FAILURE;
924 }
925 }
926
927
928 /**
929 \brief Executes execute_setop, but handles all possible general exceptions.
930 */
931 int main(int argc, char* argv[])
932 {
933 int exit_code;
934 try
935 {
936 exit_code = execute_setop(argc, argv);
937 }
938 // too much complexity or stack overflow in ++regex_iterator
939 // input file could not be read
940 catch (std::runtime_error const& rt_exc)
941 {
942 return print_error(rt_exc.what());
943 }
944 // no more memory for more elements, or one element is too large because of faulty regular expression
945 catch (std::bad_alloc const&)
946 {
947 return print_error("not enough memory available. Input data could be too large, or input element or separator regex could be erroneous.");
948 }
949 #ifndef _DEBUG
950 catch (std::exception const& exc)
951 {
952 return print_error(exc.what());
953 }
954 catch (...)
955 {
956 return print_error("unknown error occurred.");
957 }
958 #endif
959
960 return exit_code;
961 }