forked from rust-lang/rust-analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
189 lines (159 loc) · 6.08 KB
/
lib.rs
File metadata and controls
189 lines (159 loc) · 6.08 KB
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
pub mod error;
use std::path::PathBuf;
use std::{env, fs, io};
use error::FluentBuildError;
use fluent_syntax::ast;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
fn get_cargo_manifest() -> String {
env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| panic!("Running on non cargo environment"))
}
pub fn build_fluent_src() -> io::Result<()> {
let mut output = "//! This file is generated by `fluent-build`".to_owned();
for entry in fs::read_dir("src")? {
let entry = entry?.path();
if !entry.extension().is_none_or(|e| e.to_string_lossy().to_string() == "ftl") {
continue;
}
let output_mod = entry
.file_stem()
.unwrap()
.to_string_lossy()
.to_string()
.replace("-", "_")
.replace(".", "_");
let output_file =
entry.with_extension("rs").file_name().unwrap().to_string_lossy().to_string();
output +=
&format!("\n#[path = \"{output_file}\"]\nmod {output_mod};\npub use {output_mod}::*;");
build_fluent_file(entry).map_err(|e| match e {
FluentBuildError::Io(error) => return error,
FluentBuildError::Parser(_) => todo!("parse error"),
FluentBuildError::Custom(c) => panic!("{c}"),
})?;
}
let absolute_path = PathBuf::from(get_cargo_manifest()).join("src/generated.rs");
fs::write(absolute_path, output)?;
Ok(())
}
pub fn build_fluent_file(relative_path: PathBuf) -> Result<(), FluentBuildError> {
let absolute_path = PathBuf::from(get_cargo_manifest()).join(relative_path);
let resource = fs::read_to_string(&absolute_path)
.map_err(|e| FluentBuildError::Custom(format!("{absolute_path:#?}: {e}")))?;
for esc in ["\\n", "\\\"", "\\'"] {
if resource.contains(esc) {
return Err(FluentBuildError::Custom(format!(
"invalid escape `{esc}` in Fluent resource.\nFluent does not interpret these escape sequences (<https://projectfluent.org/fluent/guide/special.html>)"
)));
}
}
// Use parse_runtime because we don't need debug info
let resource = fluent_syntax::parser::parse_runtime(resource)?.body;
let entries = resource
.into_iter()
.filter_map(|entry| {
let (name, value, attributes, comment) = match entry {
ast::Entry::Message(ast::Message {
id,
value: Some(value),
attributes,
comment,
}) => (id.name, value, attributes, comment),
ast::Entry::Term(ast::Term { id, value, attributes, comment }) => {
(id.name, value, attributes, comment)
}
_ => return None,
};
let children = attributes
.into_iter()
.map(|ast::Attribute { id, value }| {
entry_to_code(format!("{name}-{}", id.name), value, None)
})
.collect::<Vec<_>>();
let mut code = entry_to_code(name, value, comment).to_string();
for child in children {
code.push('\n');
code += &child.to_string();
}
Some(code)
})
.collect::<Vec<_>>();
let code = entries.join("\n");
let result_file = absolute_path.with_extension("rs");
fs::write(result_file, code)?;
Ok(())
}
fn entry_to_code(
name: String,
pattern: ast::Pattern<String>,
comment: Option<ast::Comment<String>>,
) -> TokenStream {
let name = format_ident!("{}", name.replace("-", "_"));
let is_dynamic =
pattern.elements.iter().any(|elm| matches!(elm, ast::PatternElement::Placeable { .. }));
let comment = comment
.map(|comment| {
let content = comment.content.into_iter().map(|c| quote! {#[doc = #c]});
quote! {#(#content)*}
})
.unwrap_or(quote! {});
if is_dynamic {
let (args, format_str) = pattern.elements.into_iter().fold(
(Vec::new(), String::new()),
|(mut args, mut body), elm| {
resolve_pattern_element(&mut args, &mut body, elm);
(args, body)
},
);
quote! {
#comment
pub fn #name(#(#args),*) -> String {
format!(#format_str)
}
}
} else {
// Collect all static elements
let body = pattern
.elements
.into_iter()
.filter_map(|elm| match elm {
ast::PatternElement::TextElement { value } => Some(value),
_ => None,
})
.collect::<String>();
quote! {
#comment
#[allow(non_upper_case_globals)]
pub const #name: &str = #body;
}
}
}
fn resolve_pattern_element(
args: &mut Vec<TokenStream>,
body: &mut String,
elm: ast::PatternElement<String>,
) {
match elm {
ast::PatternElement::TextElement { value } => {
*body += &value;
}
ast::PatternElement::Placeable { expression } => match expression {
ast::Expression::Select { .. } => todo!(),
ast::Expression::Inline(inline_expression) => match inline_expression {
ast::InlineExpression::StringLiteral { .. } => todo!(),
ast::InlineExpression::NumberLiteral { .. } => todo!(),
ast::InlineExpression::FunctionReference { .. } => todo!(),
ast::InlineExpression::MessageReference { .. } => todo!(),
ast::InlineExpression::TermReference { .. } => todo!(),
ast::InlineExpression::VariableReference { id } => {
let arg = format_ident!("{}", id.name);
args.push(quote! { #arg : impl ::std::fmt::Display });
body.push('{');
body.push_str(&id.name);
body.push('}');
}
ast::InlineExpression::Placeable { .. } => todo!("Expression inception"),
},
},
}
}