-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathLocalizationFormat.cpp
293 lines (255 loc) · 9.19 KB
/
LocalizationFormat.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
//===-- LocalizationFormat.cpp - Format for Diagnostic Messages -*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the format for localized diagnostic messages.
//
//===----------------------------------------------------------------------===//
#include "swift/Localization/LocalizationFormat.h"
#include "swift/Basic/Range.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitstream/BitstreamReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/YAMLParser.h"
#include "llvm/Support/YAMLTraits.h"
#include <cstdint>
#include <string>
#include <system_error>
#include <type_traits>
namespace {
enum LocalDiagID : uint32_t {
#define DIAG(KIND, ID, Options, Text, Signature) ID,
#include "swift/AST/DiagnosticsAll.def"
NumDiags
};
static constexpr const char *const diagnosticNameStrings[] = {
#define DIAG(KIND, ID, Options, Text, Signature) " [" #ID "]",
#include "swift/AST/DiagnosticsAll.def"
"<not a diagnostic>",
};
} // namespace
namespace llvm {
namespace yaml {
template <> struct ScalarEnumerationTraits<LocalDiagID> {
static void enumeration(IO &io, LocalDiagID &value) {
#define DIAG(KIND, ID, Options, Text, Signature) \
io.enumCase(value, #ID, LocalDiagID::ID);
#include "swift/AST/DiagnosticsAll.def"
// Ignore diagnostic IDs that are available in the YAML file and not
// available in the `.def` file.
if (io.matchEnumFallback())
value = LocalDiagID::NumDiags;
}
};
} // namespace yaml
} // namespace llvm
namespace swift {
namespace diag {
void SerializedLocalizationWriter::insert(swift::DiagID id,
llvm::StringRef translation) {
generator.insert(static_cast<uint32_t>(id), translation);
}
bool SerializedLocalizationWriter::emit(llvm::StringRef filePath) {
assert(llvm::sys::path::extension(filePath) == ".db");
std::error_code error;
llvm::raw_fd_ostream OS(filePath, error, llvm::sys::fs::F_None);
if (OS.has_error()) {
return true;
}
offset_type offset;
{
llvm::support::endian::write<offset_type>(OS, 0, llvm::support::little);
offset = generator.Emit(OS);
}
OS.seek(0);
llvm::support::endian::write(OS, offset, llvm::support::little);
OS.close();
return OS.has_error();
}
void LocalizationProducer::initializeIfNeeded() {
if (state != NotInitialized)
return;
if (initializeImpl())
state = Initialized;
else
state = FailedInitialization;
}
llvm::StringRef
LocalizationProducer::getMessageOr(swift::DiagID id,
llvm::StringRef defaultMessage) {
initializeIfNeeded();
if (getState() == FailedInitialization) {
return defaultMessage;
}
auto localizedMessage = getMessage(id);
if (localizedMessage.empty())
return defaultMessage;
if (printDiagnosticNames) {
llvm::StringRef diagnosticName(diagnosticNameStrings[(unsigned)id]);
auto localizedDebugDiagnosticMessage =
localizationSaver.save(localizedMessage.str() + diagnosticName.str());
return localizedDebugDiagnosticMessage;
}
return localizedMessage;
}
LocalizationProducerState LocalizationProducer::getState() const {
return state;
}
SerializedLocalizationProducer::SerializedLocalizationProducer(
std::unique_ptr<llvm::MemoryBuffer> buffer, bool printDiagnosticNames)
: LocalizationProducer(printDiagnosticNames), Buffer(std::move(buffer)) {
}
bool SerializedLocalizationProducer::initializeImpl() {
auto base =
reinterpret_cast<const unsigned char *>(Buffer.get()->getBufferStart());
auto tableOffset = endian::read<offset_type>(base, little);
SerializedTable.reset(SerializedLocalizationTable::Create(
base + tableOffset, base + sizeof(offset_type), base));
return true;
}
llvm::StringRef
SerializedLocalizationProducer::getMessage(swift::DiagID id) const {
auto value = SerializedTable.get()->find(id);
if (value.getDataLen() == 0)
return llvm::StringRef();
return {(const char *)value.getDataPtr(), value.getDataLen()};
}
YAMLLocalizationProducer::YAMLLocalizationProducer(llvm::StringRef filePath,
bool printDiagnosticNames)
: LocalizationProducer(printDiagnosticNames), filePath(filePath) {
}
bool YAMLLocalizationProducer::initializeImpl() {
auto FileBufOrErr = llvm::MemoryBuffer::getFileOrSTDIN(filePath);
llvm::MemoryBuffer *document = FileBufOrErr->get();
diag::LocalizationInput yin(document->getBuffer());
yin >> diagnostics;
unknownIDs = std::move(yin.unknownIDs);
return true;
}
llvm::StringRef YAMLLocalizationProducer::getMessage(swift::DiagID id) const {
return diagnostics[(unsigned)id];
}
void YAMLLocalizationProducer::forEachAvailable(
llvm::function_ref<void(swift::DiagID, llvm::StringRef)> callback) {
initializeIfNeeded();
if (getState() == FailedInitialization) {
return;
}
for (uint32_t i = 0, n = diagnostics.size(); i != n; ++i) {
auto translation = diagnostics[i];
if (!translation.empty())
callback(static_cast<swift::DiagID>(i), translation);
}
}
std::unique_ptr<LocalizationProducer>
LocalizationProducer::producerFor(llvm::StringRef locale, llvm::StringRef path,
bool printDiagnosticNames) {
std::unique_ptr<LocalizationProducer> producer;
llvm::SmallString<128> filePath(path);
llvm::sys::path::append(filePath, locale);
llvm::sys::path::replace_extension(filePath, ".db");
// If the serialized diagnostics file not available,
// fallback to the `YAML` file.
if (llvm::sys::fs::exists(filePath)) {
if (auto file = llvm::MemoryBuffer::getFile(filePath)) {
producer = std::make_unique<diag::SerializedLocalizationProducer>(
std::move(file.get()), printDiagnosticNames);
}
} else {
llvm::sys::path::replace_extension(filePath, ".yaml");
// In case of missing localization files, we should fallback to messages
// from `.def` files.
if (llvm::sys::fs::exists(filePath)) {
producer = std::make_unique<diag::YAMLLocalizationProducer>(
filePath.str(), printDiagnosticNames);
}
}
return producer;
}
llvm::Optional<uint32_t> LocalizationInput::readID(llvm::yaml::IO &io) {
LocalDiagID diagID;
io.mapRequired("id", diagID);
if (diagID == LocalDiagID::NumDiags)
return llvm::None;
return static_cast<uint32_t>(diagID);
}
template <typename T, typename Context>
typename std::enable_if<llvm::yaml::has_SequenceTraits<T>::value, void>::type
readYAML(llvm::yaml::IO &io, T &Seq, T &unknownIDs, bool, Context &Ctx) {
unsigned count = io.beginSequence();
if (count) {
Seq.resize(LocalDiagID::NumDiags);
}
for (unsigned i = 0; i < count; ++i) {
void *SaveInfo;
if (io.preflightElement(i, SaveInfo)) {
io.beginMapping();
// If the current diagnostic ID is available in YAML and in `.def`, add it
// to the diagnostics array. Otherwise, re-parse the current diagnnostic
// id as a string and store it in `unknownIDs` array.
if (auto id = LocalizationInput::readID(io)) {
// YAML file isn't guaranteed to have diagnostics in order of their
// declaration in `.def` files, to accommodate that we need to leave
// holes in diagnostic array for diagnostics which haven't yet been
// localized and for the ones that have `id` indicates their position.
io.mapRequired("msg", Seq[*id]);
} else {
std::string unknownID, message;
// Read "raw" id since it doesn't exist in `.def` file.
io.mapRequired("id", unknownID);
io.mapRequired("msg", message);
unknownIDs.push_back(unknownID);
}
io.endMapping();
io.postflightElement(SaveInfo);
}
}
io.endSequence();
}
template <typename T>
typename std::enable_if<llvm::yaml::has_SequenceTraits<T>::value,
LocalizationInput &>::type
operator>>(LocalizationInput &yin, T &diagnostics) {
llvm::yaml::EmptyContext Ctx;
if (yin.setCurrentDocument()) {
// If YAML file's format doesn't match the current format in
// DiagnosticMessageFormat, will throw an error.
readYAML(yin, diagnostics, yin.unknownIDs, true, Ctx);
}
return yin;
}
void DefToYAMLConverter::convert(llvm::raw_ostream &out) {
for (auto i : swift::indices(IDs)) {
out << "- id: " << IDs[i] << "\n";
const std::string &msg = Messages[i];
out << " msg: \"";
// Add an escape character before a double quote `"` or a backslash `\`.
for (unsigned j = 0; j < msg.length(); ++j) {
if (msg[j] == '"') {
out << '\\';
out << '"';
} else if (msg[j] == '\\') {
out << '\\';
out << '\\';
} else {
out << msg[j];
}
}
out << "\"\r\n";
}
}
} // namespace diag
} // namespace swift