1 //== Yaml.h ---------------------------------------------------- -*- C++ -*--=//
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 // This file defines convenience functions for handling YAML configuration files
10 // for checkers/packages.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKER_YAML_H
15 #define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_YAML_H
16 
17 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18 #include "llvm/Support/YAMLTraits.h"
19 
20 namespace clang {
21 namespace ento {
22 
23 /// Read the given file from the filesystem and parse it as a yaml file. The
24 /// template parameter must have a yaml MappingTraits.
25 /// Emit diagnostic error in case of any failure.
26 template <class T, class Checker>
27 llvm::Optional<T> getConfiguration(CheckerManager &Mgr, Checker *Chk,
28                                    StringRef Option, StringRef ConfigFile) {
29   if (ConfigFile.trim().empty())
30     return None;
31 
32   llvm::vfs::FileSystem *FS = llvm::vfs::getRealFileSystem().get();
33   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
34       FS->getBufferForFile(ConfigFile.str());
35 
36   if (std::error_code ec = Buffer.getError()) {
37     Mgr.reportInvalidCheckerOptionValue(Chk, Option,
38                                         "a valid filename instead of '" +
39                                             std::string(ConfigFile) + "'");
40     return None;
41   }
42 
43   llvm::yaml::Input Input(Buffer.get()->getBuffer());
44   T Config;
45   Input >> Config;
46 
47   if (std::error_code ec = Input.error()) {
48     Mgr.reportInvalidCheckerOptionValue(Chk, Option,
49                                         "a valid yaml file: " + ec.message());
50     return None;
51   }
52 
53   return Config;
54 }
55 
56 } // namespace ento
57 } // namespace clang
58 
59 #endif // LLVM_CLANG_LIB_STATICANALYZER_CHECKERS_MOVE_H
60