blob: 4b3e0f8207f65cb74be36a1c915b12bb4613781b [file] [log] [blame]
Ethan Nicholasca82a922017-09-07 09:39:50 -04001/*
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
10int 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 Nicholas906126e2017-09-19 14:38:40 -040027 return INVALID;
Ethan Nicholasca82a922017-09-07 09:39:50 -040028 }
29 states = next;
30 }
Ethan Nicholas906126e2017-09-19 14:38:40 -040031 int accept = INVALID;
Ethan Nicholasca82a922017-09-07 09:39:50 -040032 for (int id : states) {
33 if (fStates[id].fKind == NFAState::kAccept_Kind) {
34 int result = fStates[id].fData[0];
Ethan Nicholas906126e2017-09-19 14:38:40 -040035 if (accept == INVALID || result < accept) {
Ethan Nicholasca82a922017-09-07 09:39:50 -040036 accept = result;
37 }
38 }
39 }
40 return accept;
41}