1 //===- CommonConfig.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/ObjCopy/CommonConfig.h"
10 #include "llvm/Support/Errc.h"
11 
12 namespace llvm {
13 namespace objcopy {
14 
15 Expected<NameOrPattern>
16 NameOrPattern::create(StringRef Pattern, MatchStyle MS,
17                       function_ref<Error(Error)> ErrorCallback) {
18   switch (MS) {
19   case MatchStyle::Literal:
20     return NameOrPattern(Pattern);
21   case MatchStyle::Wildcard: {
22     SmallVector<char, 32> Data;
23     bool IsPositiveMatch = true;
24     if (Pattern[0] == '!') {
25       IsPositiveMatch = false;
26       Pattern = Pattern.drop_front();
27     }
28     Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
29 
30     // If we couldn't create it as a glob, report the error, but try again
31     // with a literal if the error reporting is non-fatal.
32     if (!GlobOrErr) {
33       if (Error E = ErrorCallback(GlobOrErr.takeError()))
34         return std::move(E);
35       return create(Pattern, MatchStyle::Literal, ErrorCallback);
36     }
37 
38     return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
39                          IsPositiveMatch);
40   }
41   case MatchStyle::Regex: {
42     Regex RegEx(Pattern);
43     std::string Err;
44     if (!RegEx.isValid(Err))
45       return createStringError(errc::invalid_argument,
46                                "cannot compile regular expression \'" +
47                                    Pattern + "\': " + Err);
48     SmallVector<char, 32> Data;
49     return NameOrPattern(std::make_shared<Regex>(
50         ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
51   }
52   }
53   llvm_unreachable("Unhandled llvm.objcopy.MatchStyle enum");
54 }
55 
56 } // end namespace objcopy
57 } // end namespace llvm
58