Generates a random postfix command sequence. Stops and returns true once a single sequence has been generated.
| 140 | // Generates a random postfix command sequence. |
| 141 | // Stops and returns true once a single sequence has been generated. |
| 142 | bool RegexpGenerator::GenerateRandomPostfix(std::vector<std::string>* post, |
| 143 | int nstk, int ops, int atoms) { |
| 144 | std::uniform_int_distribution<int> random_stop(0, maxatoms_ - atoms); |
| 145 | std::uniform_int_distribution<int> random_bit(0, 1); |
| 146 | std::uniform_int_distribution<int> random_ops_index( |
| 147 | 0, static_cast<int>(ops_.size()) - 1); |
| 148 | std::uniform_int_distribution<int> random_atoms_index( |
| 149 | 0, static_cast<int>(atoms_.size()) - 1); |
| 150 | |
| 151 | for (;;) { |
| 152 | // Stop if we get to a single element, but only sometimes. |
| 153 | if (nstk == 1 && random_stop(rng_) == 0) { |
| 154 | RunPostfix(*post); |
| 155 | return true; |
| 156 | } |
| 157 | |
| 158 | // Early out: if used too many operators or can't |
| 159 | // get back down to a single expression on the stack |
| 160 | // using binary operators, give up. |
| 161 | if (ops + nstk - 1 > maxops_) |
| 162 | return false; |
| 163 | |
| 164 | // Add operators if there are enough arguments. |
| 165 | if (ops < maxops_ && random_bit(rng_) == 0) { |
| 166 | const std::string& fmt = ops_[random_ops_index(rng_)]; |
| 167 | int nargs = CountArgs(fmt); |
| 168 | if (nargs <= nstk) { |
| 169 | post->push_back(fmt); |
| 170 | bool ret = GenerateRandomPostfix(post, nstk - nargs + 1, |
| 171 | ops + 1, atoms); |
| 172 | post->pop_back(); |
| 173 | if (ret) |
| 174 | return true; |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | // Add atoms if there is room. |
| 179 | if (atoms < maxatoms_ && random_bit(rng_) == 0) { |
| 180 | post->push_back(atoms_[random_atoms_index(rng_)]); |
| 181 | bool ret = GenerateRandomPostfix(post, nstk + 1, ops, atoms + 1); |
| 182 | post->pop_back(); |
| 183 | if (ret) |
| 184 | return true; |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | // Interprets the postfix command sequence to create a regular expression |
| 190 | // passed to HandleRegexp. The results of operators like %s|%s are wrapped |