Ethan Nicholas | ca82a92 | 2017-09-07 09:39:50 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2017 Google Inc. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license that can be |
| 5 | * found in the LICENSE file. |
| 6 | */ |
| 7 | |
| 8 | #include "NFA.h" |
| 9 | |
| 10 | int NFA::match(std::string s) const { |
| 11 | std::vector<int> states = fStartStates; |
| 12 | for (size_t i = 0; i < s.size(); ++i) { |
| 13 | std::vector<int> next; |
| 14 | for (int id : states) { |
| 15 | if (fStates[id].accept(s[i])) { |
| 16 | for (int nextId : fStates[id].fNext) { |
| 17 | if (fStates[nextId].fKind != NFAState::kRemapped_Kind) { |
| 18 | next.push_back(nextId); |
| 19 | } else { |
| 20 | next.insert(next.end(), fStates[nextId].fData.begin(), |
| 21 | fStates[nextId].fData.end()); |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | if (!next.size()) { |
Ethan Nicholas | 906126e | 2017-09-19 14:38:40 -0400 | [diff] [blame] | 27 | return INVALID; |
Ethan Nicholas | ca82a92 | 2017-09-07 09:39:50 -0400 | [diff] [blame] | 28 | } |
| 29 | states = next; |
| 30 | } |
Ethan Nicholas | 906126e | 2017-09-19 14:38:40 -0400 | [diff] [blame] | 31 | int accept = INVALID; |
Ethan Nicholas | ca82a92 | 2017-09-07 09:39:50 -0400 | [diff] [blame] | 32 | for (int id : states) { |
| 33 | if (fStates[id].fKind == NFAState::kAccept_Kind) { |
| 34 | int result = fStates[id].fData[0]; |
Ethan Nicholas | 906126e | 2017-09-19 14:38:40 -0400 | [diff] [blame] | 35 | if (accept == INVALID || result < accept) { |
Ethan Nicholas | ca82a92 | 2017-09-07 09:39:50 -0400 | [diff] [blame] | 36 | accept = result; |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | return accept; |
| 41 | } |