|
| 1 | +//===-- Shared/EnvironmentVar.h - Environment variable handling -*- 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 | +//===----------------------------------------------------------------------===// |
| 10 | + |
| 11 | +#ifndef OMPTARGET_SHARED_ENVIRONMENT_VAR_H |
| 12 | +#define OMPTARGET_SHARED_ENVIRONMENT_VAR_H |
| 13 | + |
| 14 | +#include "Debug.h" |
| 15 | + |
| 16 | +#include "llvm/ADT/StringRef.h" |
| 17 | +#include "llvm/Support/Error.h" |
| 18 | + |
| 19 | +#include <sstream> |
| 20 | +#include <string> |
| 21 | + |
| 22 | +/// Utility class for parsing strings to other types. |
| 23 | +struct StringParser { |
| 24 | + /// Parse a string to another type. |
| 25 | + template <typename Ty> static bool parse(const char *Value, Ty &Result); |
| 26 | +}; |
| 27 | + |
| 28 | +/// Class for reading and checking environment variables. Currently working with |
| 29 | +/// integer, floats, std::string and bool types. |
| 30 | +template <typename Ty> class Envar { |
| 31 | + Ty Data; |
| 32 | + bool IsPresent; |
| 33 | + bool Initialized; |
| 34 | + |
| 35 | +public: |
| 36 | + /// Auxiliary function to safely create envars. This static function safely |
| 37 | + /// creates envars using fallible constructors. See the constructors to know |
| 38 | + /// more details about the creation parameters. |
| 39 | + template <typename... ArgsTy> |
| 40 | + static llvm::Expected<Envar> create(ArgsTy &&...Args) { |
| 41 | + llvm::Error Err = llvm::Error::success(); |
| 42 | + Envar Envar(std::forward<ArgsTy>(Args)..., Err); |
| 43 | + if (Err) |
| 44 | + return std::move(Err); |
| 45 | + return std::move(Envar); |
| 46 | + } |
| 47 | + |
| 48 | + /// Create an empty envar. Cannot be consulted. This constructor is merely |
| 49 | + /// for convenience. This constructor is not fallible. |
| 50 | + Envar() : Data(Ty()), IsPresent(false), Initialized(false) {} |
| 51 | + |
| 52 | + /// Create an envar with a name and an optional default. The Envar object will |
| 53 | + /// take the value read from the environment variable, or the default if it |
| 54 | + /// was not set or not correct. This constructor is not fallible. |
| 55 | + Envar(llvm::StringRef Name, Ty Default = Ty()) |
| 56 | + : Data(Default), IsPresent(false), Initialized(true) { |
| 57 | + |
| 58 | + if (const char *EnvStr = getenv(Name.data())) { |
| 59 | + // Check whether the envar is defined and valid. |
| 60 | + IsPresent = StringParser::parse<Ty>(EnvStr, Data); |
| 61 | + |
| 62 | + if (!IsPresent) { |
| 63 | + DP("Ignoring invalid value %s for envar %s\n", EnvStr, Name.data()); |
| 64 | + Data = Default; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + Envar<Ty> &operator=(const Ty &V) { |
| 70 | + Data = V; |
| 71 | + Initialized = true; |
| 72 | + return *this; |
| 73 | + } |
| 74 | + |
| 75 | + /// Get the definitive value. |
| 76 | + const Ty &get() const { |
| 77 | + // Throw a runtime error in case this envar is not initialized. |
| 78 | + if (!Initialized) |
| 79 | + FATAL_MESSAGE0(1, "Consulting envar before initialization"); |
| 80 | + |
| 81 | + return Data; |
| 82 | + } |
| 83 | + |
| 84 | + /// Get the definitive value. |
| 85 | + operator Ty() const { return get(); } |
| 86 | + |
| 87 | + /// Indicate whether the environment variable was defined and valid. |
| 88 | + bool isPresent() const { return IsPresent; } |
| 89 | + |
| 90 | +private: |
| 91 | + /// This constructor should never fail but we provide it for convenience. This |
| 92 | + /// way, the constructor can be used by the Envar::create() static function |
| 93 | + /// to safely create this kind of envars. |
| 94 | + Envar(llvm::StringRef Name, Ty Default, llvm::Error &Err) |
| 95 | + : Envar(Name, Default) { |
| 96 | + llvm::ErrorAsOutParameter EAO(&Err); |
| 97 | + Err = llvm::Error::success(); |
| 98 | + } |
| 99 | + |
| 100 | + /// Create an envar with a name, getter function and a setter function. The |
| 101 | + /// Envar object will take the value read from the environment variable if |
| 102 | + /// this value is accepted by the setter function. Otherwise, the getter |
| 103 | + /// function will be executed to get the default value. The getter should be |
| 104 | + /// of the form Error GetterFunctionTy(Ty &Value) and the setter should |
| 105 | + /// be of the form Error SetterFunctionTy(Ty Value). This constructor has a |
| 106 | + /// private visibility because is a fallible constructor. Please use the |
| 107 | + /// Envar::create() static function to safely create this object instead. |
| 108 | + template <typename GetterFunctor, typename SetterFunctor> |
| 109 | + Envar(llvm::StringRef Name, GetterFunctor Getter, SetterFunctor Setter, |
| 110 | + llvm::Error &Err) |
| 111 | + : Data(Ty()), IsPresent(false), Initialized(true) { |
| 112 | + llvm::ErrorAsOutParameter EAO(&Err); |
| 113 | + Err = init(Name, Getter, Setter); |
| 114 | + } |
| 115 | + |
| 116 | + template <typename GetterFunctor, typename SetterFunctor> |
| 117 | + llvm::Error init(llvm::StringRef Name, GetterFunctor Getter, |
| 118 | + SetterFunctor Setter); |
| 119 | +}; |
| 120 | + |
| 121 | +/// Define some common envar types. |
| 122 | +using IntEnvar = Envar<int>; |
| 123 | +using Int32Envar = Envar<int32_t>; |
| 124 | +using Int64Envar = Envar<int64_t>; |
| 125 | +using UInt32Envar = Envar<uint32_t>; |
| 126 | +using UInt64Envar = Envar<uint64_t>; |
| 127 | +using StringEnvar = Envar<std::string>; |
| 128 | +using BoolEnvar = Envar<bool>; |
| 129 | + |
| 130 | +template <> |
| 131 | +inline bool StringParser::parse(const char *ValueStr, bool &Result) { |
| 132 | + std::string Value(ValueStr); |
| 133 | + |
| 134 | + // Convert the string to lowercase. |
| 135 | + std::transform(Value.begin(), Value.end(), Value.begin(), |
| 136 | + [](unsigned char c) { return std::tolower(c); }); |
| 137 | + |
| 138 | + // May be implemented with fancier C++ features, but let's keep it simple. |
| 139 | + if (Value == "true" || Value == "yes" || Value == "on" || Value == "1") |
| 140 | + Result = true; |
| 141 | + else if (Value == "false" || Value == "no" || Value == "off" || Value == "0") |
| 142 | + Result = false; |
| 143 | + else |
| 144 | + return false; |
| 145 | + |
| 146 | + // Parsed correctly. |
| 147 | + return true; |
| 148 | +} |
| 149 | + |
| 150 | +template <typename Ty> |
| 151 | +inline bool StringParser::parse(const char *Value, Ty &Result) { |
| 152 | + assert(Value && "Parsed value cannot be null"); |
| 153 | + |
| 154 | + std::istringstream Stream(Value); |
| 155 | + Stream >> Result; |
| 156 | + |
| 157 | + return !Stream.fail(); |
| 158 | +} |
| 159 | + |
| 160 | +template <typename Ty> |
| 161 | +template <typename GetterFunctor, typename SetterFunctor> |
| 162 | +inline llvm::Error Envar<Ty>::init(llvm::StringRef Name, GetterFunctor Getter, |
| 163 | + SetterFunctor Setter) { |
| 164 | + // Get the default value. |
| 165 | + Ty Default; |
| 166 | + if (llvm::Error Err = Getter(Default)) |
| 167 | + return Err; |
| 168 | + |
| 169 | + if (const char *EnvStr = getenv(Name.data())) { |
| 170 | + IsPresent = StringParser::parse<Ty>(EnvStr, Data); |
| 171 | + if (IsPresent) { |
| 172 | + // Check whether the envar value is actually valid. |
| 173 | + llvm::Error Err = Setter(Data); |
| 174 | + if (Err) { |
| 175 | + // The setter reported an invalid value. Mark the user-defined value as |
| 176 | + // not present and reset to the getter value (default). |
| 177 | + IsPresent = false; |
| 178 | + Data = Default; |
| 179 | + DP("Setter of envar %s failed, resetting to %s\n", Name.data(), |
| 180 | + std::to_string(Data).data()); |
| 181 | + consumeError(std::move(Err)); |
| 182 | + } |
| 183 | + } else { |
| 184 | + DP("Ignoring invalid value %s for envar %s\n", EnvStr, Name.data()); |
| 185 | + Data = Default; |
| 186 | + } |
| 187 | + } else { |
| 188 | + Data = Default; |
| 189 | + } |
| 190 | + |
| 191 | + return llvm::Error::success(); |
| 192 | +} |
| 193 | + |
| 194 | +#endif // OMPTARGET_SHARED_ENVIRONMENT_VAR_H |
0 commit comments