-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate.rs
324 lines (296 loc) · 10.9 KB
/
generate.rs
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use std::borrow::Cow;
use std::env::var;
use std::fmt::Write;
use std::fs::OpenOptions;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use blake2::digest::FixedOutput;
use blake2::Digest;
use darling::FromDeriveInput;
use proc_macro::TokenStream;
use quote::quote;
use syn::DeriveInput;
use crate::compile_error::{CompileError, IoOp};
use crate::nate_span::SpanStatic;
use crate::parse::{input_into_blocks, Block, DataSection};
use crate::{Context, Settings};
pub(crate) type SpanInput = SpanStatic<(), Option<Cow<'static, Path>>>;
#[derive(Debug)]
enum ParsedData {
Code(Vec<SpanInput>),
Data(Vec<DataSection>),
}
const TAIL: &str = r#"
::nate::details::std::fmt::Result::Ok(())
}
}
}
"#;
pub(crate) fn generate(input: TokenStream) -> Result<TokenStream, CompileError> {
let ast: DeriveInput = syn::parse(input)?;
let mut ctx = Context {
settings: Settings::from_derive_input(&ast)?,
..Default::default()
};
let (impl_generics, type_generics, where_clause) = ast.generics.split_for_impl();
let ident = ast.ident;
let base = var("CARGO_MANIFEST_DIR").unwrap();
let path = Path::new(&base).join(&ctx.settings.path);
let output = ctx
.settings
.generated
.as_ref()
.map(|s| Path::new(&base).join(s));
let mut content = String::new();
write!(
content,
r#"{{
#[automatically_derived]
#[allow(unused_qualifications)]
impl {impl_generics} ::nate::details::std::fmt::Display
for {ident} {type_generics} {where_clause}
{{
#[inline]
fn fmt(
&self,
output: &mut ::nate::details::std::fmt::Formatter<'_>,
) -> ::nate::details::std::fmt::Result {{
::nate::RenderInto::render_fmt(self, output)
}}
}}
#[automatically_derived]
#[allow(unused_qualifications)]
#[allow(clippy::suspicious_else_formatting)]
impl {impl_generics} ::nate::RenderInto
for {ident} {type_generics} {where_clause}
{{
fn render_into(
&self,
mut output: impl ::nate::WriteAny,
) -> ::nate::details::std::fmt::Result {{
#[allow(unused_imports)]
use ::nate::details::{{RawKind as _, EscapeKind as _}};
"#,
impl_generics = quote!(#impl_generics),
type_generics = quote!(#type_generics),
where_clause = quote!(#where_clause),
ident = quote!(#ident),
)?;
parse_file(path, &mut content, &mut ctx)?;
write!(content, "{}", TAIL)?;
let output = match output {
Some(output) => output,
None => {
ctx.strings_hash.update(content.as_bytes());
let out_dir = AsRef::<Path>::as_ref(&env!("NATE_DERIVE_OUTDIR"));
let mut temp_name = hex::encode(ctx.strings_hash.finalize_fixed());
temp_name.push_str(".rs");
out_dir.join(temp_name)
},
};
let f = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&output);
let mut f = match f {
Ok(f) => f,
Err(err) => return Err(CompileError::IoError(IoOp::Open, output, err)),
};
if let Err(err) = write!(f, "{}", &content) {
return Err(CompileError::IoError(IoOp::Write, output, err));
}
let output = output.to_str().unwrap();
let content = quote! {
const _: () = ::core::include!(#output);
};
Ok(content.into())
}
fn push_address(span: &SpanInput, output: &mut impl Write) -> Result<(), CompileError> {
let path = match span.get_shared() {
Some(path) => path.as_os_str(),
None => return Ok(()),
};
writeln!(
output,
r"// #[::nate::addr(path={path:?}, offset={offset:?}, row={row:?}, col={col:?})]",
path = path,
offset = span.location_offset(),
row = span.location_line(),
col = span.naive_get_utf8_column(),
)?;
Ok(())
}
fn parse_file(
path: PathBuf,
mut output: impl Write,
ctx: &mut Context,
) -> Result<(), CompileError> {
use DataSection::*;
let i = ctx.load_file(&path)?;
for (block_index, blocks) in parse(path, i, ctx)?.into_iter().enumerate() {
match blocks {
ParsedData::Code(blocks) => {
for code in blocks.into_iter() {
push_address(&code, &mut output)?;
writeln!(output, "{}", code.as_str())?;
}
},
ParsedData::Data(blocks) => {
match &blocks[0] {
Data(s) | Raw(s) | Escaped(s) | Debug(s) | Verbose(s) => {
push_address(s, &mut output)?;
},
}
writeln!(output, "{{")?;
for (data_index, data) in blocks.iter().enumerate() {
match data {
Data(_) => continue,
Raw(s) | Escaped(s) | Debug(s) | Verbose(s) => {
push_address(s, &mut output)?;
writeln!(
output,
" let _nate_{block}_{data} = &({expr});",
block = block_index,
data = data_index,
expr = s.as_str(),
)?;
},
}
match data {
Data(_) | Raw(_) => {},
Escaped(_) => {
writeln!(
output,
" let _nate_{block}_{data} = \
(&::nate::details::TagWrapper::new(_nate_{block}_{data})).\
wrap(_nate_{block}_{data});",
block = block_index,
data = data_index,
)?;
},
Debug(_) | Verbose(_) => {
writeln!(
output,
" let _nate_{block}_{data} = \
::nate::XmlEscape(_nate_{block}_{data});",
block = block_index,
data = data_index,
)?;
},
}
}
match &blocks[0] {
Data(s) | Raw(s) | Escaped(s) | Debug(s) | Verbose(s) => {
push_address(s, &mut output)?;
},
}
writeln!(output, " <_ as ::nate::WriteAny>::write_fmt(")?;
writeln!(output, " &mut output,")?;
writeln!(output, " ::nate::details::std::format_args!(")?;
write!(output, " \"")?;
for (data_index, data) in blocks.iter().enumerate() {
match data {
Data(s) => {
let s = format!("{:#?}", s.as_str())
.replace('{', "{{")
.replace('}', "}}");
write!(output, "{}", &s[1..s.len() - 1])?;
},
Raw(_) | Escaped(_) => write!(
output,
"{{_nate_{block}_{data}}}",
block = block_index,
data = data_index
)?,
Debug(_) => write!(
output,
"{{_nate_{block}_{data}:?}}",
block = block_index,
data = data_index
)?,
Verbose(_) => write!(
output,
"{{_nate_{block}_{data}:#?}}",
block = block_index,
data = data_index
)?,
}
}
writeln!(output, "\",")?;
for (data_index, data) in blocks.into_iter().enumerate() {
match data {
Data(_) => {},
Raw(_) | Escaped(_) | Debug(_) | Verbose(_) => writeln!(
output,
" _nate_{block}_{data} = _nate_{block}_{data},",
block = block_index,
data = data_index
)?,
}
}
writeln!(output, " ),")?;
writeln!(output, " )?;")?;
writeln!(output, "}}")?;
},
}
}
Ok(())
}
fn parse(path: PathBuf, i: String, ctx: &mut Context) -> Result<Vec<ParsedData>, CompileError> {
let mut output = Vec::new();
parse_into(path, i, &mut output, ctx)?;
Ok(output)
}
fn parse_into(
path: PathBuf,
i: String,
accu: &mut Vec<ParsedData>,
ctx: &mut Context,
) -> Result<(), CompileError> {
let span = SpanInput::new_with_shared(i, Some(path.into()));
let path = span.get_rc();
let path = path.1.as_ref().unwrap().as_ref();
let s = SpanInput::new(format!(
"\
{{\n\
const _: &[::nate::details::std::primitive::u8] = \
::nate::details::std::include_bytes!({:?});",
path
));
match accu.last_mut() {
Some(ParsedData::Code(blocks)) => blocks.push(s),
_ => accu.push(ParsedData::Code(vec![s])),
}
for block in input_into_blocks(span) {
match block? {
Block::Comment => {},
Block::Code(s) => match accu.last_mut() {
Some(ParsedData::Code(blocks)) => blocks.push(s),
_ => accu.push(ParsedData::Code(vec![s])),
},
Block::Data(data) => match accu.last_mut() {
Some(ParsedData::Data(blocks)) => blocks.push(data),
_ => accu.push(ParsedData::Data(vec![data])),
},
Block::Include(include_path) => {
let include_path = include_path.as_str().trim();
let include_path = match Path::new(include_path).iter().next() {
Some(d) if d.eq(".") || d.eq("..") => {
path.parent().unwrap_or(path).join(include_path)
},
_ => Path::new(&var("CARGO_MANIFEST_DIR").map_err(|_| std::fmt::Error)?)
.join(include_path),
};
let buf = ctx.load_file(&include_path)?;
parse_into(include_path, buf, accu, ctx)?;
},
}
}
let s = SpanInput::new("}");
match accu.last_mut() {
Some(ParsedData::Code(blocks)) => blocks.push(s),
_ => accu.push(ParsedData::Code(vec![s])),
}
Ok(())
}