@discord/intl-message-database 0.0.1-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.cargo/config.toml +12 -0
- package/Cargo.toml +38 -0
- package/LICENSE +21 -0
- package/README.md +7 -0
- package/bench/keyless-json.js +91 -0
- package/bench/native.js +114 -0
- package/bench/util.js +55 -0
- package/build.rs +5 -0
- package/index.d.ts +52 -0
- package/index.js +86 -0
- package/npm/darwin-arm64/README.md +3 -0
- package/npm/darwin-arm64/package.json +18 -0
- package/npm/darwin-x64/README.md +3 -0
- package/npm/darwin-x64/package.json +18 -0
- package/npm/linux-arm64-gnu/README.md +3 -0
- package/npm/linux-arm64-gnu/package.json +21 -0
- package/npm/linux-arm64-musl/README.md +3 -0
- package/npm/linux-arm64-musl/package.json +21 -0
- package/npm/linux-x64-gnu/README.md +3 -0
- package/npm/linux-x64-gnu/package.json +21 -0
- package/npm/linux-x64-musl/README.md +3 -0
- package/npm/linux-x64-musl/package.json +21 -0
- package/npm/win32-arm64-msvc/README.md +3 -0
- package/npm/win32-arm64-msvc/package.json +18 -0
- package/npm/win32-ia32-msvc/README.md +3 -0
- package/npm/win32-ia32-msvc/package.json +18 -0
- package/npm/win32-x64-msvc/README.md +3 -0
- package/npm/win32-x64-msvc/package.json +18 -0
- package/package.json +44 -0
- package/src/lib.rs +14 -0
- package/src/messages/database.rs +343 -0
- package/src/messages/error.rs +43 -0
- package/src/messages/message_definition.rs +169 -0
- package/src/messages/message_variables_visitor.rs +299 -0
- package/src/messages/meta.rs +38 -0
- package/src/messages/mod.rs +27 -0
- package/src/messages/source_file.rs +75 -0
- package/src/messages/symbols.rs +164 -0
- package/src/messages/translation.rs +64 -0
- package/src/messages/value.rs +51 -0
- package/src/napi.rs +300 -0
- package/src/services/mod.rs +9 -0
- package/src/services/precompile.rs +91 -0
- package/src/services/types.rs +237 -0
- package/src/services/validator.rs +104 -0
- package/src/sources/definitions_parser.rs +347 -0
- package/src/sources/mod.rs +87 -0
- package/src/sources/translations.rs +75 -0
- package/src/test.rs +67 -0
- package/src/threading.rs +61 -0
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
use std::ops::Deref;
|
|
2
|
+
|
|
3
|
+
use rustc_hash::FxHashSet;
|
|
4
|
+
use serde::Serialize;
|
|
5
|
+
|
|
6
|
+
use intl_markdown::{BlockNode, Document, Icu, InlineContent, TextOrPlaceholder};
|
|
7
|
+
|
|
8
|
+
use crate::messages::symbols::KeySymbolMap;
|
|
9
|
+
|
|
10
|
+
use super::{global_intern_string, KeySymbol, MessagesResult};
|
|
11
|
+
|
|
12
|
+
#[derive(Clone, Debug, Serialize, Hash, PartialEq, Eq)]
|
|
13
|
+
pub enum MessageVariableType {
|
|
14
|
+
/// Any value is accepted for this variable. Generally used when the
|
|
15
|
+
/// required type of the variable can't be determined.
|
|
16
|
+
Any,
|
|
17
|
+
/// Any type of numeric value is valid. Accepts both integers and floats.
|
|
18
|
+
Number,
|
|
19
|
+
/// A value used for a Plural evaluation. Generally a number, or something
|
|
20
|
+
/// that can be directly cast to a number.
|
|
21
|
+
Plural,
|
|
22
|
+
/// A value that must match one of the defined values in this vec. Enums
|
|
23
|
+
/// that support fallbacks are determined by the runtime, but most use the
|
|
24
|
+
/// option `"other"` to represent that.
|
|
25
|
+
Enum(Vec<String>),
|
|
26
|
+
/// A Date type must be supplied. The runtime can decide whether the type
|
|
27
|
+
/// can be parsed from a String or must be a Date object.
|
|
28
|
+
Date,
|
|
29
|
+
/// A Time type must be supplied. The runtime can decide whether the type
|
|
30
|
+
/// can be parsed from a String or must be a specific Time object.
|
|
31
|
+
Time,
|
|
32
|
+
/// A function that provides some structured replacement of content,
|
|
33
|
+
/// normally used for applying styles or injecting custom objects into the
|
|
34
|
+
/// result string.
|
|
35
|
+
HookFunction,
|
|
36
|
+
/// A specialization of [MessageVariableType::HookFunction] that represents
|
|
37
|
+
/// a Link, which requires specific handling in most cases.
|
|
38
|
+
LinkFunction,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// A representation of a single _instance_ of a variable in a message. Each
|
|
42
|
+
/// time a variable appears in a message, even if it is a variable that has
|
|
43
|
+
/// already been seen, a new MessageVariable is created.
|
|
44
|
+
#[derive(Clone, Debug, PartialEq, Serialize)]
|
|
45
|
+
pub struct MessageVariableInstance {
|
|
46
|
+
/// The location in the message where this variable is used. Each instance
|
|
47
|
+
/// of a variable in a string has its own struct, so each stores its own
|
|
48
|
+
/// span as well.
|
|
49
|
+
/// TODO: Add this back
|
|
50
|
+
pub span: Option<usize>,
|
|
51
|
+
/// The specific kind of the variable, used for generating types.
|
|
52
|
+
pub kind: MessageVariableType,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
#[derive(Clone, Debug, Serialize)]
|
|
56
|
+
#[serde(transparent)]
|
|
57
|
+
pub struct MessageVariables {
|
|
58
|
+
variables: KeySymbolMap<Vec<MessageVariableInstance>>,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
impl MessageVariables {
|
|
62
|
+
pub fn new() -> Self {
|
|
63
|
+
Self {
|
|
64
|
+
variables: KeySymbolMap::default(),
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/// Add a new instance of a variable to the set of variables in a message.
|
|
68
|
+
/// If this is the first instance of that variable, a new entry will be
|
|
69
|
+
/// allocated for it, otherwise it will be appended to the list of
|
|
70
|
+
/// instances for that name.
|
|
71
|
+
pub fn add_instance(
|
|
72
|
+
&mut self,
|
|
73
|
+
name: KeySymbol,
|
|
74
|
+
kind: MessageVariableType,
|
|
75
|
+
span: Option<usize>,
|
|
76
|
+
) {
|
|
77
|
+
let instance = MessageVariableInstance { kind, span };
|
|
78
|
+
self.variables
|
|
79
|
+
.entry(name)
|
|
80
|
+
.or_insert_with(|| vec![])
|
|
81
|
+
.push(instance);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/// Merge the variables from `other` into self by copying them over.
|
|
85
|
+
pub fn merge(&mut self, other: &Self) {
|
|
86
|
+
for (symbol, instances) in other.iter() {
|
|
87
|
+
self.variables
|
|
88
|
+
.entry(*symbol)
|
|
89
|
+
.and_modify(|existing| existing.extend(instances.clone()))
|
|
90
|
+
.or_insert(instances.clone());
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// Returns a HashSet of the names of all variables in this message.
|
|
95
|
+
pub fn get_keys(&self) -> FxHashSet<&KeySymbol> {
|
|
96
|
+
self.variables.keys().collect::<FxHashSet<&KeySymbol>>()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// Returns the count of _uniquely-named_ variables found in the message
|
|
100
|
+
pub fn count(&self) -> usize {
|
|
101
|
+
self.variables.len()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
pub fn get(&self, key: &KeySymbol) -> Option<&Vec<MessageVariableInstance>> {
|
|
105
|
+
self.variables.get(key)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
impl Deref for MessageVariables {
|
|
110
|
+
type Target = KeySymbolMap<Vec<MessageVariableInstance>>;
|
|
111
|
+
|
|
112
|
+
fn deref(&self) -> &Self::Target {
|
|
113
|
+
&self.variables
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
pub struct MessageVariablesVisitor;
|
|
118
|
+
|
|
119
|
+
impl MessageVariablesVisitor {
|
|
120
|
+
pub fn visit(ast: &Document, variables: &mut MessageVariables) -> MessagesResult<()> {
|
|
121
|
+
for child in ast.blocks() {
|
|
122
|
+
Self::visit_block(child, variables)?;
|
|
123
|
+
}
|
|
124
|
+
Ok(())
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
fn visit_block(block_node: &BlockNode, variables: &mut MessageVariables) -> MessagesResult<()> {
|
|
128
|
+
match block_node {
|
|
129
|
+
BlockNode::InlineContent(content) => Self::visit_inline_children(content, variables),
|
|
130
|
+
BlockNode::Paragraph(paragraph) => {
|
|
131
|
+
variables.add_instance(
|
|
132
|
+
global_intern_string("p")?,
|
|
133
|
+
MessageVariableType::HookFunction,
|
|
134
|
+
None,
|
|
135
|
+
);
|
|
136
|
+
Self::visit_inline_children(paragraph.content(), variables)
|
|
137
|
+
}
|
|
138
|
+
BlockNode::Heading(heading) => {
|
|
139
|
+
let heading_tag = format!("h{}", heading.level());
|
|
140
|
+
variables.add_instance(
|
|
141
|
+
global_intern_string(&heading_tag)?,
|
|
142
|
+
MessageVariableType::HookFunction,
|
|
143
|
+
None,
|
|
144
|
+
);
|
|
145
|
+
Self::visit_inline_children(heading.content(), variables)
|
|
146
|
+
}
|
|
147
|
+
// This presumes that code blocks can't contain variables, which _should_ always be true
|
|
148
|
+
BlockNode::CodeBlock(_) => {
|
|
149
|
+
variables.add_instance(
|
|
150
|
+
global_intern_string("codeBlock")?,
|
|
151
|
+
MessageVariableType::HookFunction,
|
|
152
|
+
None,
|
|
153
|
+
);
|
|
154
|
+
Ok(())
|
|
155
|
+
}
|
|
156
|
+
BlockNode::ThematicBreak => {
|
|
157
|
+
variables.add_instance(
|
|
158
|
+
global_intern_string("hr")?,
|
|
159
|
+
MessageVariableType::HookFunction,
|
|
160
|
+
None,
|
|
161
|
+
);
|
|
162
|
+
Ok(())
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
fn visit_inline_children(
|
|
168
|
+
content: &Vec<InlineContent>,
|
|
169
|
+
variables: &mut MessageVariables,
|
|
170
|
+
) -> MessagesResult<()> {
|
|
171
|
+
for child in content {
|
|
172
|
+
Self::visit_inline_content(child, variables)?;
|
|
173
|
+
}
|
|
174
|
+
Ok(())
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
fn visit_inline_content(
|
|
178
|
+
element: &InlineContent,
|
|
179
|
+
variables: &mut MessageVariables,
|
|
180
|
+
) -> MessagesResult<()> {
|
|
181
|
+
match element {
|
|
182
|
+
InlineContent::Text(_) => Ok(()),
|
|
183
|
+
// # is just a reference to an existing outer variable. It doesn't add anything new.
|
|
184
|
+
// TODO: Make this add an instance of the outer variable.
|
|
185
|
+
InlineContent::IcuPound => Ok(()),
|
|
186
|
+
InlineContent::Icu(icu) => Self::visit_icu(icu, variables),
|
|
187
|
+
// Everything else introduces a new tag directly before checking the inner content.
|
|
188
|
+
InlineContent::Emphasis(emphasis) => {
|
|
189
|
+
variables.add_instance(
|
|
190
|
+
global_intern_string("i")?,
|
|
191
|
+
MessageVariableType::HookFunction,
|
|
192
|
+
None,
|
|
193
|
+
);
|
|
194
|
+
Self::visit_inline_children(emphasis.content(), variables)
|
|
195
|
+
}
|
|
196
|
+
InlineContent::Strong(strong) => {
|
|
197
|
+
variables.add_instance(
|
|
198
|
+
global_intern_string("b")?,
|
|
199
|
+
MessageVariableType::HookFunction,
|
|
200
|
+
None,
|
|
201
|
+
);
|
|
202
|
+
Self::visit_inline_children(strong.content(), variables)
|
|
203
|
+
}
|
|
204
|
+
InlineContent::Strikethrough(strikethrough) => {
|
|
205
|
+
variables.add_instance(
|
|
206
|
+
global_intern_string("del")?,
|
|
207
|
+
MessageVariableType::HookFunction,
|
|
208
|
+
None,
|
|
209
|
+
);
|
|
210
|
+
Self::visit_inline_children(strikethrough.content(), variables)
|
|
211
|
+
}
|
|
212
|
+
InlineContent::HardLineBreak => {
|
|
213
|
+
variables.add_instance(
|
|
214
|
+
global_intern_string("br")?,
|
|
215
|
+
MessageVariableType::HookFunction,
|
|
216
|
+
None,
|
|
217
|
+
);
|
|
218
|
+
Ok(())
|
|
219
|
+
}
|
|
220
|
+
InlineContent::CodeSpan(_) => {
|
|
221
|
+
variables.add_instance(
|
|
222
|
+
global_intern_string("code")?,
|
|
223
|
+
MessageVariableType::HookFunction,
|
|
224
|
+
None,
|
|
225
|
+
);
|
|
226
|
+
Ok(())
|
|
227
|
+
}
|
|
228
|
+
// Links and hooks introduce known variables.
|
|
229
|
+
InlineContent::Hook(hook) => {
|
|
230
|
+
variables.add_instance(
|
|
231
|
+
global_intern_string(hook.name())?,
|
|
232
|
+
MessageVariableType::HookFunction,
|
|
233
|
+
None,
|
|
234
|
+
);
|
|
235
|
+
Self::visit_inline_children(hook.content(), variables)
|
|
236
|
+
}
|
|
237
|
+
InlineContent::Link(link) => {
|
|
238
|
+
variables.add_instance(
|
|
239
|
+
global_intern_string("link")?,
|
|
240
|
+
MessageVariableType::LinkFunction,
|
|
241
|
+
None,
|
|
242
|
+
);
|
|
243
|
+
Self::visit_inline_children(link.label(), variables)?;
|
|
244
|
+
match link.destination() {
|
|
245
|
+
TextOrPlaceholder::Placeholder(icu) => Self::visit_icu(icu, variables),
|
|
246
|
+
_ => Ok(()),
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
fn visit_icu(icu: &Icu, variables: &mut MessageVariables) -> MessagesResult<()> {
|
|
253
|
+
match icu {
|
|
254
|
+
Icu::IcuVariable(variable) => {
|
|
255
|
+
variables.add_instance(
|
|
256
|
+
global_intern_string(variable.name())?,
|
|
257
|
+
MessageVariableType::Any,
|
|
258
|
+
None,
|
|
259
|
+
);
|
|
260
|
+
Ok(())
|
|
261
|
+
}
|
|
262
|
+
Icu::IcuPlural(plural) => {
|
|
263
|
+
variables.add_instance(
|
|
264
|
+
global_intern_string(plural.name())?,
|
|
265
|
+
MessageVariableType::Plural,
|
|
266
|
+
None,
|
|
267
|
+
);
|
|
268
|
+
for arm in plural.arms() {
|
|
269
|
+
Self::visit_inline_children(arm.content(), variables)?;
|
|
270
|
+
}
|
|
271
|
+
Ok(())
|
|
272
|
+
}
|
|
273
|
+
Icu::IcuDate(date) => {
|
|
274
|
+
variables.add_instance(
|
|
275
|
+
global_intern_string(date.name())?,
|
|
276
|
+
MessageVariableType::Date,
|
|
277
|
+
None,
|
|
278
|
+
);
|
|
279
|
+
Ok(())
|
|
280
|
+
}
|
|
281
|
+
Icu::IcuTime(time) => {
|
|
282
|
+
variables.add_instance(
|
|
283
|
+
global_intern_string(time.name())?,
|
|
284
|
+
MessageVariableType::Time,
|
|
285
|
+
None,
|
|
286
|
+
);
|
|
287
|
+
Ok(())
|
|
288
|
+
}
|
|
289
|
+
Icu::IcuNumber(number) => {
|
|
290
|
+
variables.add_instance(
|
|
291
|
+
global_intern_string(number.name())?,
|
|
292
|
+
MessageVariableType::Number,
|
|
293
|
+
None,
|
|
294
|
+
);
|
|
295
|
+
Ok(())
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
use serde::{Deserialize, Serialize};
|
|
2
|
+
|
|
3
|
+
/// Meta information about how a message should be handled and processed.
|
|
4
|
+
/// Meta can be specified at a set level and individually per-message.
|
|
5
|
+
#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
|
|
6
|
+
pub struct MessageMeta {
|
|
7
|
+
/// Whether the message should be considered private and not suitable for
|
|
8
|
+
/// inclusion in production builds. Along with `bundle_secrets`, this will
|
|
9
|
+
/// control how the messages are bundled. `secret` messages also have
|
|
10
|
+
/// additional rules and guardrails applied to them to help ensure secrecy
|
|
11
|
+
/// while letting them be used freely in development and getting
|
|
12
|
+
/// translations prepared for synchronized launches.
|
|
13
|
+
pub secret: bool,
|
|
14
|
+
/// Whether the message is suitable to be sent for translation, and whether
|
|
15
|
+
/// existing translations should be included when building projects that
|
|
16
|
+
/// include this message. When `false`, the default message value will be
|
|
17
|
+
/// used in all locales, no matter if there is a translation present.
|
|
18
|
+
pub translate: bool,
|
|
19
|
+
/// Whether messages marked as `secret` should have their content preserved
|
|
20
|
+
/// in builds that include the message. When `false`, secret messages will
|
|
21
|
+
/// be fully obfuscated in built output. Setting to `true` allows for
|
|
22
|
+
/// testing builds with secret content as they will appear once the message
|
|
23
|
+
/// becomes non-secret.
|
|
24
|
+
pub bundle_secrets: bool,
|
|
25
|
+
/// A full path to a directory where translations for the message should be found.
|
|
26
|
+
pub translations_path: String,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
impl Default for MessageMeta {
|
|
30
|
+
fn default() -> Self {
|
|
31
|
+
Self {
|
|
32
|
+
secret: false,
|
|
33
|
+
translate: true,
|
|
34
|
+
bundle_secrets: false,
|
|
35
|
+
translations_path: "./messages".into(),
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
mod database;
|
|
2
|
+
mod error;
|
|
3
|
+
mod message_definition;
|
|
4
|
+
mod message_variables_visitor;
|
|
5
|
+
mod meta;
|
|
6
|
+
mod source_file;
|
|
7
|
+
mod symbols;
|
|
8
|
+
mod translation;
|
|
9
|
+
mod value;
|
|
10
|
+
|
|
11
|
+
pub use database::MessagesDatabase;
|
|
12
|
+
pub use error::MessagesError;
|
|
13
|
+
pub use message_definition::{FilePosition, Message, MessageKey};
|
|
14
|
+
pub use message_variables_visitor::{
|
|
15
|
+
MessageVariableInstance, MessageVariableType, MessageVariables, MessageVariablesVisitor,
|
|
16
|
+
};
|
|
17
|
+
pub use meta::MessageMeta;
|
|
18
|
+
pub use source_file::SourceFile;
|
|
19
|
+
pub use symbols::{
|
|
20
|
+
global_get_symbol, global_intern_string, global_symbol_store, read_global_symbol_store,
|
|
21
|
+
KeySymbol, KeySymbolMap,
|
|
22
|
+
};
|
|
23
|
+
pub use translation::{create_translation_map, Translation, TranslationsMap};
|
|
24
|
+
pub use value::MessageValue;
|
|
25
|
+
|
|
26
|
+
pub type MessagesResult<T> = Result<T, MessagesError>;
|
|
27
|
+
pub type LocaleId = String;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
use std::fmt::Formatter;
|
|
2
|
+
|
|
3
|
+
use rustc_hash::FxHashSet;
|
|
4
|
+
use serde::Serialize;
|
|
5
|
+
|
|
6
|
+
use super::{KeySymbol, LocaleId, MessageMeta};
|
|
7
|
+
|
|
8
|
+
#[derive(Clone, Debug, PartialEq, Serialize)]
|
|
9
|
+
pub enum SourceFileKind {
|
|
10
|
+
Definition,
|
|
11
|
+
Translation,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
impl std::fmt::Display for SourceFileKind {
|
|
15
|
+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
16
|
+
match self {
|
|
17
|
+
SourceFileKind::Definition => f.write_str("Definition"),
|
|
18
|
+
SourceFileKind::Translation => f.write_str("Translation"),
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/// Representation of a file that either defines or provides translations for
|
|
24
|
+
/// some set of messages. The file name is mapped to all of the definitions it
|
|
25
|
+
/// affects, along with extra information useful for processing that file.
|
|
26
|
+
///
|
|
27
|
+
/// SourceFiles allow interactive editing of files to automatically update all
|
|
28
|
+
/// of the affected messages safely and efficiently.
|
|
29
|
+
#[derive(Debug, Serialize)]
|
|
30
|
+
#[serde(tag = "type")]
|
|
31
|
+
pub enum SourceFile {
|
|
32
|
+
#[serde(rename = "definition")]
|
|
33
|
+
Definition {
|
|
34
|
+
file: String,
|
|
35
|
+
meta: MessageMeta,
|
|
36
|
+
#[serde(rename = "messageKeys")]
|
|
37
|
+
message_keys: FxHashSet<KeySymbol>,
|
|
38
|
+
},
|
|
39
|
+
#[serde(rename = "translation")]
|
|
40
|
+
Translation {
|
|
41
|
+
file: String,
|
|
42
|
+
locale: LocaleId,
|
|
43
|
+
#[serde(rename = "messageKeys")]
|
|
44
|
+
message_keys: FxHashSet<KeySymbol>,
|
|
45
|
+
},
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
impl SourceFile {
|
|
49
|
+
pub fn file(&self) -> &String {
|
|
50
|
+
match self {
|
|
51
|
+
SourceFile::Definition { file, .. } => file,
|
|
52
|
+
SourceFile::Translation { file, .. } => file,
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
pub fn message_keys(&self) -> &FxHashSet<KeySymbol> {
|
|
57
|
+
match self {
|
|
58
|
+
SourceFile::Definition { message_keys, .. } => message_keys,
|
|
59
|
+
SourceFile::Translation { message_keys, .. } => message_keys,
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
pub fn set_message_keys(&mut self, new_keys: FxHashSet<KeySymbol>) {
|
|
64
|
+
match self {
|
|
65
|
+
SourceFile::Definition {
|
|
66
|
+
ref mut message_keys,
|
|
67
|
+
..
|
|
68
|
+
} => *message_keys = new_keys,
|
|
69
|
+
SourceFile::Translation {
|
|
70
|
+
ref mut message_keys,
|
|
71
|
+
..
|
|
72
|
+
} => *message_keys = new_keys,
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
//! Small module for creating and working with Symbols (aka Atoms), which are
|
|
2
|
+
//! internal handles to commonly-shared values like message keys, file names
|
|
3
|
+
//! locale ids, or anything else that needs to be shared.
|
|
4
|
+
use rustc_hash::FxHasher;
|
|
5
|
+
use serde::ser::Error;
|
|
6
|
+
use serde::{Serialize, Serializer};
|
|
7
|
+
use std::collections::HashMap;
|
|
8
|
+
use std::fmt::Formatter;
|
|
9
|
+
use std::hash::BuildHasherDefault;
|
|
10
|
+
use std::sync::{OnceLock, RwLock, RwLockReadGuard};
|
|
11
|
+
use string_interner::{DefaultBackend, DefaultSymbol, StringInterner, Symbol};
|
|
12
|
+
|
|
13
|
+
use super::{MessagesError, MessagesResult};
|
|
14
|
+
|
|
15
|
+
// TODO: Propagate these errors rather than just using `.ok()?`.
|
|
16
|
+
|
|
17
|
+
/// Returns a global, mutexed symbol store
|
|
18
|
+
pub fn global_symbol_store() -> &'static RwLock<SymbolStore> {
|
|
19
|
+
static SYMBOL_STORE: OnceLock<RwLock<SymbolStore>> = OnceLock::new();
|
|
20
|
+
SYMBOL_STORE.get_or_init(|| RwLock::new(SymbolStore::new()))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/// Acquire and return a read handle on the global symbol store,
|
|
24
|
+
/// returning a MessagesError if it can't be acquired.
|
|
25
|
+
#[inline]
|
|
26
|
+
pub fn read_global_symbol_store<'a>() -> MessagesResult<RwLockReadGuard<'a, SymbolStore>> {
|
|
27
|
+
global_symbol_store()
|
|
28
|
+
.read()
|
|
29
|
+
.map_err(|_| MessagesError::SymbolStorePoisonedError)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/// Return the KeySymbol that represents the given value. If the requested
|
|
33
|
+
/// value is not currently known in the store, or if the store is poisoned,
|
|
34
|
+
/// a MessagesError is returned instead.
|
|
35
|
+
pub fn global_get_symbol(value: &str) -> MessagesResult<KeySymbol> {
|
|
36
|
+
read_global_symbol_store()?
|
|
37
|
+
.get(value)
|
|
38
|
+
.ok_or_else(|| MessagesError::ValueNotInterned(value.into()))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// Intern a new value into the global symbol store. This is thread-safe, but
|
|
42
|
+
/// will lock any reads from the store that are happening concurrently.
|
|
43
|
+
///
|
|
44
|
+
/// If the store can't be acquired or the write otherwise fails, this returns
|
|
45
|
+
/// a MessagesError.
|
|
46
|
+
pub fn global_intern_string(value: &str) -> MessagesResult<KeySymbol> {
|
|
47
|
+
let mut store = global_symbol_store()
|
|
48
|
+
.write()
|
|
49
|
+
.map_err(|_| MessagesError::SymbolStorePoisonedError)?;
|
|
50
|
+
Ok(store.intern(value))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// Resolve a symbol from the value of the given variable name to a `&str`. If the symbol can't be
|
|
54
|
+
/// found, or if the symbol store can't be read, this macro returns early with a MessagesError.
|
|
55
|
+
#[macro_export]
|
|
56
|
+
macro_rules! resolve_symbol {
|
|
57
|
+
($var:ident) => {{
|
|
58
|
+
let store = read_global_symbol_store()?;
|
|
59
|
+
store
|
|
60
|
+
.resolve($var)
|
|
61
|
+
.ok_or_else(|| MessagesError::SymbolNotFound($var))
|
|
62
|
+
}};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// A symbol representing a message key, file name, or any other frequently-
|
|
66
|
+
/// copied value. This is not the same as hashing a message key, which creates
|
|
67
|
+
/// a short _string_ representation, while this symbol is just a lightweight
|
|
68
|
+
/// integer handle for use as keys and references internally.
|
|
69
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
70
|
+
pub struct KeySymbol(DefaultSymbol);
|
|
71
|
+
|
|
72
|
+
impl KeySymbol {
|
|
73
|
+
pub fn from_usize(value: usize) -> Option<Self> {
|
|
74
|
+
let symbol = DefaultSymbol::try_from_usize(value)?;
|
|
75
|
+
Some(KeySymbol(symbol))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
pub fn value(&self) -> usize {
|
|
79
|
+
self.0.to_usize()
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
impl Serialize for KeySymbol {
|
|
84
|
+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
85
|
+
where
|
|
86
|
+
S: Serializer,
|
|
87
|
+
{
|
|
88
|
+
let symbol_store = global_symbol_store().read().map_err(Error::custom)?;
|
|
89
|
+
let value = symbol_store.resolve(*self);
|
|
90
|
+
match value {
|
|
91
|
+
Some(value) => serializer.serialize_str(value),
|
|
92
|
+
None => serializer.serialize_none(),
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
impl std::fmt::Display for KeySymbol {
|
|
98
|
+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
99
|
+
let symbol_store = global_symbol_store()
|
|
100
|
+
.read()
|
|
101
|
+
.map_err(|_| Error::custom("Could not read global symbol store"))?;
|
|
102
|
+
if let Some(value) = symbol_store.resolve(*self) {
|
|
103
|
+
f.write_str(value)?;
|
|
104
|
+
}
|
|
105
|
+
Ok(())
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
pub struct SymbolStore {
|
|
110
|
+
interner: StringInterner<DefaultBackend, BuildHasherDefault<FxHasher>>,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
impl SymbolStore {
|
|
114
|
+
pub fn new() -> Self {
|
|
115
|
+
Self {
|
|
116
|
+
interner: StringInterner::new(),
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
pub fn intern(&mut self, file_name: &str) -> KeySymbol {
|
|
121
|
+
KeySymbol(self.interner.get_or_intern(file_name))
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
pub fn get(&self, value: &str) -> Option<KeySymbol> {
|
|
125
|
+
self.interner.get(value).map(KeySymbol)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
pub fn resolve(&self, symbol: KeySymbol) -> Option<&str> {
|
|
129
|
+
self.interner.resolve(symbol.0)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/// A specialized hasher for using KeySymbols as hash keys. Since symbols are
|
|
134
|
+
/// already u64 by default (usize, but we're always 64-bit), the values don't
|
|
135
|
+
/// actually need to be hashed at all, and the value is just used as the hash
|
|
136
|
+
/// result directly.
|
|
137
|
+
#[derive(Clone, Debug, Default)]
|
|
138
|
+
pub struct KeySymbolHasher {
|
|
139
|
+
value: u64,
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
impl std::hash::Hasher for KeySymbolHasher {
|
|
143
|
+
fn finish(&self) -> u64 {
|
|
144
|
+
self.value
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
fn write(&mut self, _: &[u8]) {
|
|
148
|
+
unreachable!("KeySymbolHasher is only valid for single unsigned integer values. No other types may be written.")
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
fn write_u32(&mut self, value: u32) {
|
|
152
|
+
self.value = value as u64
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
fn write_u64(&mut self, value: u64) {
|
|
156
|
+
self.value = value;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
fn write_usize(&mut self, value: usize) {
|
|
160
|
+
self.value = value as u64;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
pub type KeySymbolMap<Value> = HashMap<KeySymbol, Value, BuildHasherDefault<KeySymbolHasher>>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
use std::ops::Range;
|
|
2
|
+
|
|
3
|
+
use crate::messages::symbols::KeySymbolMap;
|
|
4
|
+
use serde::Serialize;
|
|
5
|
+
|
|
6
|
+
use super::{symbols::KeySymbol, value::MessageValue, FilePosition};
|
|
7
|
+
|
|
8
|
+
/// A single message value in a specific locale.
|
|
9
|
+
#[derive(Debug, PartialEq, Serialize)]
|
|
10
|
+
pub struct Translation {
|
|
11
|
+
/// Content of the message in the locale
|
|
12
|
+
pub value: MessageValue,
|
|
13
|
+
/// File where the translation is loaded from
|
|
14
|
+
file_position: FilePosition,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
impl Translation {
|
|
18
|
+
pub fn new(value: MessageValue, file_position: FilePosition) -> Self {
|
|
19
|
+
Self {
|
|
20
|
+
value,
|
|
21
|
+
file_position,
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// Return the byte span of the entire message value within the source file.
|
|
26
|
+
pub fn full_span(&self) -> Range<usize> {
|
|
27
|
+
let start = self.file_position.offset as usize;
|
|
28
|
+
let length = self.value.raw.len();
|
|
29
|
+
start..(start + length)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/// Given an offset within the message value, return an absolute position
|
|
33
|
+
/// to that same offset in the message within the source file.
|
|
34
|
+
#[inline]
|
|
35
|
+
pub fn file_position_for_offset(&self, offset: u32) -> u32 {
|
|
36
|
+
self.file_position.offset + offset
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Return the key symbol of the file this translation was sourced from.
|
|
40
|
+
pub fn file(&self) -> KeySymbol {
|
|
41
|
+
self.file_position.file
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// Return the byte offset of this translation within its source file.
|
|
45
|
+
pub fn offset(&self) -> u32 {
|
|
46
|
+
self.file_position.offset
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// A Map of locales to the value for a message in that locale.
|
|
51
|
+
pub type TranslationsMap = KeySymbolMap<Translation>;
|
|
52
|
+
|
|
53
|
+
pub fn create_translation_map(
|
|
54
|
+
default_value: MessageValue,
|
|
55
|
+
default_locale: KeySymbol,
|
|
56
|
+
file_position: FilePosition,
|
|
57
|
+
) -> TranslationsMap {
|
|
58
|
+
let mut translations = TranslationsMap::default();
|
|
59
|
+
translations.insert(
|
|
60
|
+
default_locale,
|
|
61
|
+
Translation::new(default_value, file_position),
|
|
62
|
+
);
|
|
63
|
+
translations
|
|
64
|
+
}
|