Yaml.h 2.1 KB

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