Yaml.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKER_YAML_H
  14. #define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_YAML_H
  15. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  16. #include "llvm/Support/VirtualFileSystem.h"
  17. #include "llvm/Support/YAMLTraits.h"
  18. #include <optional>
  19. namespace clang {
  20. namespace ento {
  21. /// Read the given file from the filesystem and parse it as a yaml file. The
  22. /// template parameter must have a yaml MappingTraits.
  23. /// Emit diagnostic error in case of any failure.
  24. template <class T, class Checker>
  25. std::optional<T> getConfiguration(CheckerManager &Mgr, Checker *Chk,
  26. StringRef Option, StringRef ConfigFile) {
  27. if (ConfigFile.trim().empty())
  28. return std::nullopt;
  29. llvm::vfs::FileSystem *FS = llvm::vfs::getRealFileSystem().get();
  30. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
  31. FS->getBufferForFile(ConfigFile.str());
  32. if (std::error_code ec = Buffer.getError()) {
  33. Mgr.reportInvalidCheckerOptionValue(Chk, Option,
  34. "a valid filename instead of '" +
  35. std::string(ConfigFile) + "'");
  36. return std::nullopt;
  37. }
  38. llvm::yaml::Input Input(Buffer.get()->getBuffer());
  39. T Config;
  40. Input >> Config;
  41. if (std::error_code ec = Input.error()) {
  42. Mgr.reportInvalidCheckerOptionValue(Chk, Option,
  43. "a valid yaml file: " + ec.message());
  44. return std::nullopt;
  45. }
  46. return Config;
  47. }
  48. } // namespace ento
  49. } // namespace clang
  50. #endif // LLVM_CLANG_LIB_STATICANALYZER_CHECKER_YAML_H