summaryrefslogtreecommitdiffstats
path: root/org.eclipse.jgit.junit
diff options
context:
space:
mode:
authorDave Borowitz <dborowitz@google.com>2017-07-17 11:03:38 -0400
committerDave Borowitz <dborowitz@google.com>2017-07-25 13:14:50 -0400
commit65b64768b347d0074513d9a8c770e34d258528ad (patch)
treec1f87bc937768c45f3c57f3c71a831c56786c47d /org.eclipse.jgit.junit
parent26962861d4fd50ac32edd642eafca1c10f29a4ba (diff)
downloadjgit-65b64768b347d0074513d9a8c770e34d258528ad.tar.gz
jgit-65b64768b347d0074513d9a8c770e34d258528ad.zip
Move BatchRefUpdate tests to a new file
Run with @Parameterized, so we don't have to duplicate test setup for each atomic/non-atomic test. We still have to have two different sets of asserts for the cases where the behavior is different. In fact, this is a readability win: it emphasizes that performing the exact same setup except for the atomic setting will have different behavior. Change-Id: I78a8214075e204732a423341f14c09de273a7854
Diffstat (limited to 'org.eclipse.jgit.junit')
-rw-r--r--org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/StrictWorkMonitor.java78
1 files changed, 78 insertions, 0 deletions
diff --git a/org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/StrictWorkMonitor.java b/org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/StrictWorkMonitor.java
new file mode 100644
index 0000000000..22b69a3ee5
--- /dev/null
+++ b/org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/StrictWorkMonitor.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2017 Google Inc.
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ * names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.junit;
+
+import static org.junit.Assert.assertEquals;
+
+import org.eclipse.jgit.lib.ProgressMonitor;
+
+public final class StrictWorkMonitor implements ProgressMonitor {
+ private int lastWork, totalWork;
+
+ @Override
+ public void start(int totalTasks) {
+ // empty
+ }
+
+ @Override
+ public void beginTask(String title, int total) {
+ this.totalWork = total;
+ lastWork = 0;
+ }
+
+ @Override
+ public void update(int completed) {
+ lastWork += completed;
+ }
+
+ @Override
+ public void endTask() {
+ assertEquals("Units of work recorded", totalWork, lastWork);
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return false;
+ }
+}
4' href='#n264'>264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
/*-
 * Copyright 2021 Vsevolod Stakhov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "css_parser.hxx"
#include "css_tokeniser.hxx"
#include "css_selector.hxx"
#include "css_rule.hxx"
#include "css_util.hxx"
#include "css.hxx"
#include "fmt/core.h"

#include <vector>
#include <unicode/utf8.h>

#define DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL
#include "doctest/doctest.h"

namespace rspamd::css {

const css_consumed_block css_parser_eof_block{};

auto css_consumed_block::attach_block(consumed_block_ptr &&block) -> bool {
	if (std::holds_alternative<std::monostate>(content)) {
		/* Switch from monostate */
		content = std::vector<consumed_block_ptr>();
	}
	else if (!std::holds_alternative<std::vector<consumed_block_ptr>>(content)) {
		/* A single component, cannot attach a block ! */
		return false;
	}

	auto &value_vec = std::get<std::vector<consumed_block_ptr>>(content);
	value_vec.push_back(std::move(block));

	return true;
}

auto css_consumed_block::add_function_argument(consumed_block_ptr &&block)  -> bool {
	if (!std::holds_alternative<css_function_block>(content)) {
		return false;
	}

	auto &&func_bloc = std::get<css_function_block>(content);
	func_bloc.args.push_back(std::move(block));

	return true;
}

auto css_consumed_block::token_type_str(void) const -> const char *
{
	const auto *ret = "";

	switch(tag) {
	case parser_tag_type::css_top_block:
		ret = "top";
		break;
	case parser_tag_type::css_qualified_rule:
		ret = "qualified rule";
		break;
	case parser_tag_type::css_at_rule:
		ret = "at rule";
		break;
	case parser_tag_type::css_simple_block:
		ret = "simple block";
		break;
	case parser_tag_type::css_function:
		ret = "function";
		break;
	case parser_tag_type::css_function_arg:
		ret = "function arg";
		break;
	case parser_tag_type::css_component:
		ret = "component";
		break;
	case parser_tag_type::css_eof_block:
		ret = "eof";
		break;
	}

	return ret;
}

auto css_consumed_block::debug_str(void) -> std::string {
	std::string ret = fmt::format(R"("type": "{}", "value": )", token_type_str());

	std::visit([&](auto& arg) {
				using T = std::decay_t<decltype(arg)>;

				if constexpr (std::is_same_v<T, std::vector<consumed_block_ptr>>) {
					/* Array of blocks */
					ret += "[";
					for (const auto &block : arg) {
						ret += "{";
						ret += block->debug_str();
						ret += "}, ";
					}

					if (*(--ret.end()) == ' ') {
						ret.pop_back();
						ret.pop_back(); /* Last ',' */
					}
					ret += "]";
				}
				else if constexpr (std::is_same_v<T, std::monostate>) {
					/* Empty block */
					ret += R"("empty")";
				}
				else if constexpr (std::is_same_v<T, css_function_block>) {
					ret += R"({ "content": {"token": )";
					ret += "\"" + arg.function.debug_token_str() + "\", ";
					ret += R"("arguments":  [)";

					for (const auto &block : arg.args) {
						ret += "{";
						ret += block->debug_str();
						ret += "}, ";
					}
					if (*(--ret.end()) == ' ') {
						ret.pop_back();
						ret.pop_back(); /* Last ',' */
					}
					ret += "]}}";
				}
				else {
					/* Single element block */
					ret += "\"" + arg.debug_token_str() + "\"";
				}
			},
			content);

	return ret;
}

class css_parser {
public:
	css_parser(void) = delete; /* Require mempool to be set for logging */
	explicit css_parser(rspamd_mempool_t *pool) : pool (pool) {
		/* Int this case we need to remove style in case of parser error */
		owned_style = true;
	}

	/*
	 * This constructor captures existing via unique_ptr, but it does not
	 * destruct it on errors (we assume that it is owned somewhere else)
	 */
	explicit css_parser(css_style_sheet *existing, rspamd_mempool_t *pool) :
			style_object(existing), pool(pool) {}

	/*
	 * Process input css blocks
	 */
	std::unique_ptr<css_consumed_block> consume_css_blocks(const std::string_view &sv);
	/*
	 * Process a single css rule
	 */
	std::unique_ptr<css_consumed_block> consume_css_rule(const std::string_view &sv);
	bool consume_input(const std::string_view &sv);

	auto get_object_maybe(void) -> tl::expected<std::unique_ptr<css_style_sheet>, css_parse_error> {
		if (style_object) {
			return std::move(style_object);
		}

		return tl::make_unexpected(error);
	}

	/* Helper parser methods */
	bool need_unescape(const std::string_view &sv);

	~css_parser() {
		if (!owned_style && style_object) {
			/* Avoid double free */
			(void)style_object.release();
		}
	}

private:
	std::unique_ptr<css_style_sheet> style_object;
	std::unique_ptr<css_tokeniser> tokeniser;

	css_parse_error error;
	rspamd_mempool_t *pool;

	int rec_level = 0;
	const int max_rec = 20;
	bool eof = false;
	bool owned_style = false;

	/* Consumers */
	auto component_value_consumer(std::unique_ptr<css_consumed_block> &top) -> bool;
	auto function_consumer(std::unique_ptr<css_consumed_block> &top) -> bool;
	auto simple_block_consumer(std::unique_ptr<css_consumed_block> &top,
							   css_parser_token::token_type expected_end,
							   bool consume_current) -> bool;
	auto qualified_rule_consumer(std::unique_ptr<css_consumed_block> &top) -> bool;
	auto at_rule_consumer(std::unique_ptr<css_consumed_block> &top) -> bool;
};

/*
 * Find if we need to unescape css
 */
bool
css_parser::need_unescape(const std::string_view &sv)
{
	bool in_quote = false;
	char quote_char, prev_c = 0;

	for (const auto c : sv) {
		if (!in_quote) {
			if (c == '"' || c == '\'') {
				in_quote = true;
				quote_char = c;
			}
			else if (c == '\\') {
				return true;
			}
		}
		else {
			if (c == quote_char) {
				if (prev_c != '\\') {
					in_quote = false;
				}
			}
			prev_c = c;
		}
	}

	return false;
}

auto css_parser::function_consumer(std::unique_ptr<css_consumed_block> &top) -> bool
{
	auto ret = true, want_more = true;

	msg_debug_css("consume function block; top block: %s, recursion level %d",
			top->token_type_str(), rec_level);

	if (++rec_level > max_rec) {
		msg_err_css("max nesting reached, ignore style");
		error = css_parse_error(css_parse_error_type::PARSE_ERROR_BAD_NESTING);
		return false;
	}

	while (ret && want_more && !eof) {
		auto next_token = tokeniser->next_token();

		switch (next_token.type) {
		case css_parser_token::token_type::eof_token:
			eof = true;
			break;
		case css_parser_token::token_type::whitespace_token:
			/* Ignore whitespaces */
			break;
		case css_parser_token::token_type::ebrace_token:
			ret = true;
			want_more = false;
			break;
		case css_parser_token::token_type::comma_token:
		case css_parser_token::token_type::delim_token:
		case css_parser_token::token_type::obrace_token:
			break;
		default:
			/* Attach everything to the function block */
			top->add_function_argument(std::make_unique<css_consumed_block>(
					css::css_consumed_block::parser_tag_type::css_function_arg,
					std::move(next_token)));
			break;
		}
	}

	--rec_level;

	return ret;
}

auto css_parser::simple_block_consumer(std::unique_ptr<css_consumed_block> &top,
									   css_parser_token::token_type expected_end,
									   bool consume_current) -> bool
{
	auto ret = true;
	std::unique_ptr<css_consumed_block> block;

	msg_debug_css("consume simple block; top block: %s, recursion level %d",
			top->token_type_str(), rec_level);

	if (!consume_current && ++rec_level > max_rec) {
		msg_err_css("max nesting reached, ignore style");
		error = css_parse_error(css_parse_error_type::PARSE_ERROR_BAD_NESTING);
		return false;
	}

	if (!consume_current) {
		block = std::make_unique<css_consumed_block>(
				css_consumed_block::parser_tag_type::css_simple_block);
	}


	while (ret && !eof) {
		auto next_token = tokeniser->next_token();

		if (next_token.type == expected_end) {
			break;
		}

		switch (next_token.type) {
		case css_parser_token::token_type::eof_token:
			eof = true;
			break;
		case css_parser_token::token_type::whitespace_token:
			/* Ignore whitespaces */
			break;
		default:
			tokeniser->pushback_token(std::move(next_token));
			ret = component_value_consumer(consume_current ? top : block);
			break;
		}
	}

	if (!consume_current && ret) {
		msg_debug_css("attached node 'simple block' rule %s; length=%d",
				block->token_type_str(), (int)block->size());
		top->attach_block(std::move(block));
	}

	if (!consume_current) {
		--rec_level;
	}

	return ret;
}

auto css_parser::qualified_rule_consumer(std::unique_ptr<css_consumed_block> &top) -> bool
{
	msg_debug_css("consume qualified block; top block: %s, recursion level %d",
			top->token_type_str(), rec_level);

	if (++rec_level > max_rec) {
		msg_err_css("max nesting reached, ignore style");
		error = css_parse_error(css_parse_error_type::PARSE_ERROR_BAD_NESTING);
		return false;
	}

	auto ret = true, want_more = true;
	auto block = std::make_unique<css_consumed_block>(
			css_consumed_block::parser_tag_type::css_qualified_rule);

	while (ret && want_more && !eof) {
		auto next_token = tokeniser->next_token();
		switch (next_token.type) {
		case css_parser_token::token_type::eof_token:
			eof = true;
			break;
		case css_parser_token::token_type::cdo_token:
		case css_parser_token::token_type::cdc_token:
			if (top->tag == css_consumed_block::parser_tag_type::css_top_block) {
				/* Ignore */
				ret = true;
			}
			else {

			}
			break;
		case css_parser_token::token_type::ocurlbrace_token:
			ret = simple_block_consumer(block,
					css_parser_token::token_type::ecurlbrace_token, false);
			want_more = false;
			break;
		case css_parser_token::token_type::whitespace_token:
			/* Ignore whitespaces */
			break;
		default:
			tokeniser->pushback_token(std::move(next_token));
			ret = component_value_consumer(block);
			break;
		};
	}

	if (ret) {
		if (top->tag == css_consumed_block::parser_tag_type::css_top_block) {
			msg_debug_css("attached node qualified rule %s; length=%d",
					block->token_type_str(), (int)block->size());
			top->attach_block(std::move(block));
		}
	}

	--rec_level;

	return ret;
}

auto css_parser::at_rule_consumer(std::unique_ptr<css_consumed_block> &top) -> bool
{
	msg_debug_css("consume at-rule block; top block: %s, recursion level %d",
			top->token_type_str(), rec_level);

	if (++rec_level > max_rec) {
		msg_err_css("max nesting reached, ignore style");
		error = css_parse_error(css_parse_error_type::PARSE_ERROR_BAD_NESTING);
		return false;
	}

	auto ret = true, want_more = true;
	auto block = std::make_unique<css_consumed_block>(
			css_consumed_block::parser_tag_type::css_at_rule);

	while (ret && want_more && !eof) {
		auto next_token = tokeniser->next_token();
		switch (next_token.type) {
		case css_parser_token::token_type::eof_token:
			eof = true;
			break;
		case css_parser_token::token_type::cdo_token:
		case css_parser_token::token_type::cdc_token:
			if (top->tag == css_consumed_block::parser_tag_type::css_top_block) {
				/* Ignore */
				ret = true;
			}
			else {

			}
			break;
		case css_parser_token::token_type::ocurlbrace_token:
			ret = simple_block_consumer(block,
					css_parser_token::token_type::ecurlbrace_token, false);
			want_more = false;
			break;
		case css_parser_token::token_type::whitespace_token:
			/* Ignore whitespaces */
			break;
		case css_parser_token::token_type::semicolon_token:
			want_more = false;
			break;
		default:
			tokeniser->pushback_token(std::move(next_token));
			ret = component_value_consumer(block);
			break;
		};
	}

	if (ret) {
		if (top->tag == css_consumed_block::parser_tag_type::css_top_block) {
			msg_debug_css("attached node qualified rule %s; length=%d",
					block->token_type_str(), (int)block->size());
			top->attach_block(std::move(block));
		}
	}

	--rec_level;

	return ret;
}

auto css_parser::component_value_consumer(std::unique_ptr<css_consumed_block> &top) -> bool
{
	auto ret = true, need_more = true;
	std::unique_ptr<css_consumed_block> block;

	msg_debug_css("consume component block; top block: %s, recursion level %d",
			top->token_type_str(), rec_level);

	if (++rec_level > max_rec) {
		error = css_parse_error(css_parse_error_type::PARSE_ERROR_BAD_NESTING);
		return false;
	}

	while (ret && need_more && !eof) {
		auto next_token = tokeniser->next_token();

		switch (next_token.type) {
		case css_parser_token::token_type::eof_token:
			eof = true;
			break;
		case css_parser_token::token_type::ocurlbrace_token:
			block = std::make_unique<css_consumed_block>(
					css_consumed_block::parser_tag_type::css_simple_block);
			ret = simple_block_consumer(block,
					css_parser_token::token_type::ecurlbrace_token,
					true);
			need_more = false;
			break;
		case css_parser_token::token_type::obrace_token:
			block = std::make_unique<css_consumed_block>(
					css_consumed_block::parser_tag_type::css_simple_block);
			ret = simple_block_consumer(block,
					css_parser_token::token_type::ebrace_token,
					true);
			need_more = false;
			break;
		case css_parser_token::token_type::osqbrace_token:
			block = std::make_unique<css_consumed_block>(
					css_consumed_block::parser_tag_type::css_simple_block);
			ret = simple_block_consumer(block,
					css_parser_token::token_type::esqbrace_token,
					true);
			need_more = false;
			break;
		case css_parser_token::token_type::whitespace_token:
			/* Ignore whitespaces */
			break;
		case css_parser_token::token_type::function_token: {
			need_more = false;
			block = std::make_unique<css_consumed_block>(
					css_consumed_block::parser_tag_type::css_function,
					std::move(next_token));

			/* Consume the rest */
			ret = function_consumer(block);
			break;
		}
		default:
			block = std::make_unique<css_consumed_block>(
					css_consumed_block::parser_tag_type::css_component,
					std::move(next_token));
			need_more = false;
			break;
		}
	}

	if (ret && block) {
		msg_debug_css("attached node component rule %s; length=%d",
				block->token_type_str(), (int)block->size());
		top->attach_block(std::move(block));
	}

	--rec_level;

	return ret;
}

auto
css_parser::consume_css_blocks(const std::string_view &sv) -> std::unique_ptr<css_consumed_block>
{
	tokeniser = std::make_unique<css_tokeniser>(pool, sv);
	auto ret = true;

	auto consumed_blocks =
			std::make_unique<css_consumed_block>(css_consumed_block::parser_tag_type::css_top_block);

	while (!eof && ret) {
		auto next_token = tokeniser->next_token();

		switch (next_token.type) {
		case css_parser_token::token_type::whitespace_token:
			/* Ignore whitespaces */
			break;
		case css_parser_token::token_type::eof_token:
			eof = true;
			break;
		case css_parser_token::token_type::at_keyword_token:
			tokeniser->pushback_token(std::move(next_token));
			ret = at_rule_consumer(consumed_blocks);
			break;
		default:
			tokeniser->pushback_token(std::move(next_token));
			ret = qualified_rule_consumer(consumed_blocks);
			break;
		}

	}

	tokeniser.reset(nullptr); /* No longer needed */

	return consumed_blocks;
}

auto
css_parser::consume_css_rule(const std::string_view &sv) -> std::unique_ptr<css_consumed_block>
{
	tokeniser = std::make_unique<css_tokeniser>(pool, sv);
	auto ret = true;

	auto rule_block =
			std::make_unique<css_consumed_block>(css_consumed_block::parser_tag_type::css_simple_block);

	while (!eof && ret) {
		auto next_token = tokeniser->next_token();

		switch (next_token.type) {
		case css_parser_token::token_type::eof_token:
			eof = true;
			break;
		case css_parser_token::token_type::whitespace_token:
			/* Ignore whitespaces */
			break;
		default:
			tokeniser->pushback_token(std::move(next_token));
			ret = component_value_consumer(rule_block);
			break;
		}

	}

	tokeniser.reset(nullptr); /* No longer needed */

	return rule_block;
}

bool css_parser::consume_input(const std::string_view &sv)
{
	auto &&consumed_blocks = consume_css_blocks(sv);
	const auto &rules = consumed_blocks->get_blocks_or_empty();

	if (rules.empty()) {
		return false;
	}

	if (!style_object) {
		style_object = std::make_unique<css_style_sheet>(pool);
	}

	for (auto &&rule : rules) {
		/*
		 * For now, we do not need any of the at rules, so we can safely ignore them
		 */
		auto &&children = rule->get_blocks_or_empty();

		if (children.size() > 1 &&
			children[0]->tag == css_consumed_block::parser_tag_type::css_component) {
			auto simple_block = std::find_if(children.begin(), children.end(),
					[](auto &bl) {
						return bl->tag == css_consumed_block::parser_tag_type::css_simple_block;
					});

			if (simple_block != children.end()) {
				/*
				 * We have a component and a simple block,
				 * so we can parse a selector and then extract
				 * declarations from a simple block
				 */

				/* First, tag all components as preamble */
				auto selector_it = children.cbegin();

				auto selector_token_functor = [&selector_it,&simple_block](void)
						-> const css_consumed_block & {
					for (;;) {
						if (selector_it == simple_block) {
							return css_parser_eof_block;
						}

						const auto &ret = (*selector_it);

						++selector_it;

						return *ret;
					}
				};

				auto selectors_vec = process_selector_tokens(pool, selector_token_functor);

				if (selectors_vec.size() > 0) {
					msg_debug_css("processed %d selectors", (int)selectors_vec.size());
					auto decls_it = (*simple_block)->get_blocks_or_empty().cbegin();
					auto decls_end = (*simple_block)->get_blocks_or_empty().cend();
					auto declaration_token_functor = [&decls_it, &decls_end](void)
							-> const css_consumed_block & {
						for (;;) {
							if (decls_it == decls_end) {
								return css_parser_eof_block;
							}

							const auto &ret = (*decls_it);

							++decls_it;

							return *ret;
						}
					};

					auto declarations_vec = process_declaration_tokens(pool,
							declaration_token_functor);

					if (declarations_vec && !declarations_vec->get_rules().empty()) {
						msg_debug_css("processed %d rules",
								(int)declarations_vec->get_rules().size());

						for (auto &&selector : selectors_vec) {
							style_object->add_selector_rule(std::move(selector),
									   declarations_vec);
						}
					}
				}
			}
		}
	}

	auto debug_str = consumed_blocks->debug_str();
	msg_debug_css("consumed css: {%*s}", (int)debug_str.size(), debug_str.data());

	return true;
}

auto
get_selectors_parser_functor(rspamd_mempool_t *pool,
							 const std::string_view &st) -> blocks_gen_functor
{
	css_parser parser(pool);

	auto &&consumed_blocks = parser.consume_css_blocks(st);
	const auto &rules = consumed_blocks->get_blocks_or_empty();

	auto rules_it = rules.begin();
	auto &&children = (*rules_it)->get_blocks_or_empty();
	auto cur = children.begin();
	auto last = children.end();

	/*
	 * We use move only wrapper to state the fact that the cosumed blocks
	 * are moved into the closure, not copied.
	 * It prevents us from thinking about copies of the blocks and
	 * functors.
	 * Mutable lambda is required to copy iterators inside of the closure,
	 * as, again, it is C++ where lifetime of the objects must be explicitly
	 * transferred. On the other hand, we could move all stuff inside and remove
	 * mutable.
	 */
	return [cur, consumed_blocks = std::move(consumed_blocks), last](void) mutable
		-> const css_consumed_block & {
		if (cur != last) {
			const auto &ret = (*cur);

			++cur;

			return *ret;
		}

		return css_parser_eof_block;
	};
}

auto
get_rules_parser_functor(rspamd_mempool_t *pool,
							 const std::string_view &st) -> blocks_gen_functor
{
	css_parser parser(pool);

	auto &&consumed_blocks = parser.consume_css_rule(st);
	const auto &rules = consumed_blocks->get_blocks_or_empty();

	auto cur = rules.begin();
	auto last = rules.end();

	return [cur, consumed_blocks = std::move(consumed_blocks), last](void) mutable
			-> const css_consumed_block & {
		if (cur != last) {
			const auto &ret = (*cur);

			++cur;

			return *ret;
		}

		return css_parser_eof_block;
	};
}


/*
 * Wrapper for the parser
 */
auto parse_css(rspamd_mempool_t *pool, const std::string_view &st,
						  css_style_sheet *other)
	-> tl::expected<std::unique_ptr<css_style_sheet>, css_parse_error>
{
	css_parser parser(other, pool);
	std::string_view processed_input;

	if (parser.need_unescape(st)) {
		processed_input = rspamd::css::unescape_css(pool, st);
	}
	else {
		/* Lowercase inplace */
		auto *nspace = reinterpret_cast<char *>(rspamd_mempool_alloc(pool, st.length()));
		auto *p = nspace;

		for (const auto c : st) {
			*p++ = g_ascii_tolower(c);
		}

		processed_input = std::string_view{nspace, (std::size_t)(p - nspace)};
	}

	if (parser.consume_input(processed_input)) {
		return parser.get_object_maybe();
	}

	return tl::make_unexpected(css_parse_error{css_parse_error_type::PARSE_ERROR_INVALID_SYNTAX,
											   "cannot parse input"});
}

TEST_SUITE("css parser") {
	TEST_CASE("parse colors") {
		const std::vector<const char *> cases{
			"p { color: rgb(100%, 50%, 0%); opacity: -1; width: 1em; display: none; } /* very transparent solid orange */",
			"p { color: rgb(100%, 50%, 0%); opacity: 2; display: inline; } /* very transparent solid orange */",
			"p { color: rgb(100%, 50%, 0%); opacity: 0.5; } /* very transparent solid orange */\n",
			"p { color: rgb(100%, 50%, 0%); opacity: 1; width: 99%; } /* very transparent solid orange */\n",
			"p { color: rgb(100%, 50%, 0%); opacity: 10%; width: 99%; } /* very transparent solid orange */\n",
			"p { color: rgb(100%, 50%, 0%); opacity: 10%; width: 100px; } /* very transparent solid orange */\n",
			"p { color: rgb(100%, 50%, 0%); opacity: 10% } /* very transparent solid orange */\n",
			"* { color: hsl(0, 100%, 50%) !important }   /* red */\n",
			"* { color: hsl(120, 100%, 50%) important } /* lime */\n",
			"* { color: hsl(120, 100%, 25%) } /* dark green */\n",
			"* { color: hsl(120, 100%, 75%) } /* light green */\n",
			"* { color: hsl(120, 75%, 75%) }  /* pastel green, and so on */\n",
			"em { color: #f00 }              /* #rgb */\n",
			"em { color: #ff0000 }           /* #rrggbb */\n",
			"em { color: rgb(255,0,0) }\n",
			"em { color: rgb(100%, 0%, 0%) }\n",
			"body {color: black; background: white }\n",
			"h1 { color: maroon }\n",
			"h2 { color: olive }\n",
			"em { color: rgb(255,0,0) }       /* integer range 0 - 255 */\n",
			"em { color: rgb(300,0,0) }       /* clipped to rgb(255,0,0) */\n",
			"em { color: rgb(255,-10,0) }     /* clipped to rgb(255,0,0) */\n",
			"em { color: rgb(110%, 0%, 0%) }  /* clipped to rgb(100%,0%,0%) */\n",
			"em { color: rgb(255,0,0) }      /* integer range 0 - 255 */\n",
			"em { color: rgba(255,0,0,1)     /* the same, with explicit opacity of 1 */\n",
			"em { color: rgb(100%,0%,0%) }   /* float range 0.0% - 100.0% */\n",
			"em { color: rgba(100%,0%,0%,1) } /* the same, with explicit opacity of 1 */\n",
			"p { color: rgba(0,0,255,0.5) }        /* semi-transparent solid blue */\n",
			"p { color: rgba(100%, 50%, 0%, 0.1) } /* very transparent solid orange */",
			".chat-icon[_ng-cnj-c0]::before{content:url(group-2.63e87cd21fbf8c966dd.svg);width:60px;height:60px;display:block}",
			"tt{color:#1e3482}",
			"tt{unicode-range: u+0049-u+004a,u+0020;}",
		};

		rspamd_mempool_t *pool = rspamd_mempool_new(rspamd_mempool_suggest_size(),
				"css", 0);
		for (const auto &c : cases) {
			CHECK(parse_css(pool, c, nullptr).value().get() != nullptr);
		}

		/* We now merge all styles together */
		css_style_sheet *merged = nullptr;
		for (const auto &c : cases) {
			auto ret = parse_css(pool, c, merged);
			/* Avoid destruction as we are using this to interoperate with C */
			merged = ret->release();
		}

		CHECK(merged != nullptr);

		rspamd_mempool_delete(pool);
	}
}
}