version.tmpl.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "common/version.h"
  5. #include <string_view>
  6. namespace Carbon {
  7. // A simplistic string-to-integer routine that is consteval for compile-time
  8. // extracting specific components of the version from the string form. We use
  9. // `std::string_view` for its broader `constexpr` API.
  10. static consteval auto ToInt(std::string_view str) -> int {
  11. int result = 0;
  12. while (true) {
  13. result += str.front() - '0';
  14. str.remove_prefix(1);
  15. if (str.empty()) {
  16. break;
  17. }
  18. result *= 10;
  19. }
  20. return result;
  21. }
  22. static consteval auto MajorVersion(std::string_view str) -> int {
  23. return ToInt(str.substr(0, str.find('.')));
  24. }
  25. static consteval auto MinorVersion(std::string_view str) -> int {
  26. str.remove_prefix(str.find('.') + 1);
  27. return ToInt(str.substr(0, str.find('.')));
  28. }
  29. static consteval auto PatchVersion(std::string_view str) -> int {
  30. str.remove_prefix(str.find('.') + 1);
  31. str.remove_prefix(str.find('.') + 1);
  32. // Note that searching for `-` may find the end of the string if there is no
  33. // pre-release component, but that produces the correct result here.
  34. return ToInt(str.substr(0, str.find('-')));
  35. }
  36. // The major, minor, and patch versions are always provided and stable. They
  37. // don't depend on build stamping or introduce caching issues. Provide normal
  38. // strong definitions.
  39. constexpr int Version::Major = MajorVersion("$VERSION");
  40. constexpr int Version::Minor = MinorVersion("$VERSION");
  41. constexpr int Version::Patch = PatchVersion("$VERSION");
  42. } // namespace Carbon