|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +#include <pytorch/tokenizers/re2_regex.h> |
| 10 | +#include <pytorch/tokenizers/regex.h> |
| 11 | +#include <pytorch/tokenizers/std_regex.h> |
| 12 | + |
| 13 | +#include <re2/re2.h> |
| 14 | +#include <iostream> |
| 15 | +#include <memory> |
| 16 | + |
| 17 | +namespace tokenizers { |
| 18 | + |
| 19 | +/** |
| 20 | + * @brief Factory function that creates a regex object using RE2 if possible. |
| 21 | + * Falls back to std::regex if RE2 rejects the pattern with |
| 22 | + * ErrorBadPerlOp. |
| 23 | + */ |
| 24 | +Result<std::unique_ptr<IRegex>> create_regex(const std::string& pattern) { |
| 25 | + // Try RE2 first |
| 26 | + auto re2 = std::make_unique<Re2Regex>("(" + pattern + ")"); |
| 27 | + |
| 28 | + if (re2->regex_->ok()) { |
| 29 | + return static_cast<std::unique_ptr<IRegex>>(std::move(re2)); |
| 30 | + } |
| 31 | + |
| 32 | + if (re2->regex_->error_code() == re2::RE2::ErrorBadPerlOp) { |
| 33 | + try { |
| 34 | + std::cout |
| 35 | + << "RE2 is unable to support things such as negative lookaheads in " |
| 36 | + << pattern << ", defaulting to std::regex."; |
| 37 | + auto std_regex = std::make_unique<StdRegex>("(" + pattern + ")"); |
| 38 | + return static_cast<std::unique_ptr<IRegex>>(std::move(std_regex)); |
| 39 | + } catch (const std::regex_error& e) { |
| 40 | + std::cerr << "std::regex failed: " << e.what() << std::endl; |
| 41 | + return tokenizers::Error::LoadFailure; |
| 42 | + } |
| 43 | + } else { |
| 44 | + std::cerr << "RE2 failed to compile pattern: " << pattern << "\n"; |
| 45 | + std::cerr << "Error: " << (re2->regex_->error()) << std::endl; |
| 46 | + return tokenizers::Error::LoadFailure; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +} // namespace tokenizers |
0 commit comments