Skip to content

Commit b85606c

Browse files
committed
Performance improvement
1 parent 578eec7 commit b85606c

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

peglib.h

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -459,11 +459,15 @@ inline constexpr unsigned int operator"" _(const char *s, size_t l) {
459459
/*
460460
* Semantic values
461461
*/
462+
class Context;
463+
462464
struct SemanticValues : protected std::vector<std::any> {
465+
SemanticValues() = default;
466+
SemanticValues(Context *c): c_(c) {}
467+
463468
// Input text
464469
const char *path = nullptr;
465470
const char *ss = nullptr;
466-
std::function<const std::vector<size_t> &()> source_line_index;
467471

468472
// Matched string
469473
std::string_view sv() const { return sv_; }
@@ -553,6 +557,9 @@ struct SemanticValues : protected std::vector<std::any> {
553557
friend class Holder;
554558
friend class PrecedenceClimbing;
555559

560+
const std::vector<size_t> &source_line_index() const;
561+
562+
Context *c_ = nullptr;
556563
std::string_view sv_;
557564
size_t choice_count_ = 0;
558565
size_t choice_ = 0;
@@ -773,7 +780,6 @@ struct ErrorInfo {
773780
/*
774781
* Context
775782
*/
776-
class Context;
777783
class Ope;
778784
class Definition;
779785

@@ -882,7 +888,7 @@ class Context {
882888
SemanticValues &push() {
883889
assert(value_stack_size <= value_stack.size());
884890
if (value_stack_size == value_stack.size()) {
885-
value_stack.emplace_back(std::make_shared<SemanticValues>());
891+
value_stack.emplace_back(std::make_shared<SemanticValues>(this));
886892
} else {
887893
auto &vs = *value_stack[value_stack_size];
888894
if (!vs.empty()) {
@@ -898,15 +904,6 @@ class Context {
898904
auto &vs = *value_stack[value_stack_size++];
899905
vs.path = path;
900906
vs.ss = s;
901-
vs.source_line_index = [&]() -> const std::vector<size_t> & {
902-
if (source_line_index.empty()) {
903-
for (size_t pos = 0; pos < l; pos++) {
904-
if (s[pos] == '\n') { source_line_index.push_back(pos); }
905-
}
906-
source_line_index.push_back(l);
907-
}
908-
return source_line_index;
909-
};
910907

911908
return vs;
912909
}
@@ -2469,6 +2466,19 @@ inline size_t parse_literal(const char *s, size_t n, SemanticValues &vs,
24692466
return i;
24702467
}
24712468

2469+
inline const std::vector<size_t> &SemanticValues::source_line_index() const {
2470+
if (!c_) {
2471+
std::vector<size_t>();
2472+
}
2473+
if (c_->source_line_index.empty()) {
2474+
for (size_t pos = 0; pos < c_->l; pos++) {
2475+
if (c_->s[pos] == '\n') { c_->source_line_index.push_back(pos); }
2476+
}
2477+
c_->source_line_index.push_back(c_->l);
2478+
}
2479+
return c_->source_line_index;
2480+
}
2481+
24722482
inline void Context::set_error_pos(const char *a_s, const char *literal) {
24732483
if (log) {
24742484
if (error_info.error_pos <= a_s) {

0 commit comments

Comments
 (0)