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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#![doc(html_logo_url = "https://sixtyfps.io/resources/logo.drawio.svg")]
extern crate proc_macro;
use std::path::Path;
use proc_macro::{Spacing, TokenStream, TokenTree};
use quote::quote;
use sixtyfps_compilerlib::diagnostics::BuildDiagnostics;
use sixtyfps_compilerlib::parser::SyntaxKind;
use sixtyfps_compilerlib::*;
fn are_token_touching(token1: proc_macro::Span, token2: proc_macro::Span) -> bool {
are_token_touching_impl(&format!("{:?}", token1), &format!("{:?}", token2))
}
fn are_token_touching_impl(token1_debug: &str, token2_debug: &str) -> bool {
let is_byte_char = |c: char| c.is_numeric() || c == ':';
let not_is_byte_char = |c: char| !is_byte_char(c);
let end_of_token1 = token1_debug
.trim_end_matches(not_is_byte_char)
.rsplit(not_is_byte_char)
.next()
.map(|x| x.trim_matches(':'));
let begin_of_token2 = token2_debug
.trim_end_matches(not_is_byte_char)
.trim_end_matches(is_byte_char)
.trim_end_matches(not_is_byte_char)
.rsplit(not_is_byte_char)
.next()
.map(|x| x.trim_matches(':'));
end_of_token1.zip(begin_of_token2).map(|(a, b)| !a.is_empty() && a == b).unwrap_or(false)
}
#[test]
fn are_token_touching_impl_test() {
assert!(are_token_touching_impl("#0 bytes(6662788..6662789)", "#0 bytes(6662789..6662794)"));
assert!(!are_token_touching_impl("#0 bytes(6662788..6662789)", "#0 bytes(6662790..6662794)"));
assert!(!are_token_touching_impl("#0 bytes(6662789..6662794)", "#0 bytes(6662788..6662789)"));
assert!(!are_token_touching_impl("#0 bytes(6662788..6662789)", "#0 bytes(662789..662794)"));
assert!(are_token_touching_impl("#0 bytes(123..456)", "#0 bytes(456..789)"));
assert!(are_token_touching_impl("/foo/bar.rs:12:7: 12:18", "/foo/bar.rs:12:18: 12:19"));
assert!(are_token_touching_impl("/foo/bar.rs:2:7: 13:18", "/foo/bar.rs:13:18: 14:29"));
assert!(!are_token_touching_impl("/foo/bar.rs:2:7: 13:18", "/foo/bar.rs:14:18: 14:29"));
assert!(!are_token_touching_impl("/foo/bar.rs:2:7: 2:8", "/foo/bar.rs:2:18: 2:29"));
assert!(!are_token_touching_impl("hello", "hello"));
assert!(!are_token_touching_impl("hello42", "hello42"));
}
fn fill_token_vec(stream: impl Iterator<Item = TokenTree>, vec: &mut Vec<parser::Token>) {
let mut prev_spacing = Spacing::Alone;
let mut prev_span = proc_macro::Span::call_site();
for t in stream {
let span = t.span();
match t {
TokenTree::Ident(i) => {
if let Some(last) = vec.last_mut() {
if (last.kind == SyntaxKind::ColorLiteral && last.text.len() == 1)
|| (last.kind == SyntaxKind::Identifier
&& are_token_touching(prev_span, span))
{
last.text = format!("{}{}", last.text, i).into();
prev_span = span;
continue;
}
}
vec.push(parser::Token {
kind: SyntaxKind::Identifier,
text: i.to_string().into(),
span: Some(i.span()),
..Default::default()
});
}
TokenTree::Punct(p) => {
let kind = match p.as_char() {
':' => SyntaxKind::Colon,
'=' => {
if let Some(last) = vec.last_mut() {
let kt = match last.kind {
SyntaxKind::Star => Some((SyntaxKind::StarEqual, "*=")),
SyntaxKind::Colon => Some((SyntaxKind::ColonEqual, ":=")),
SyntaxKind::Plus => Some((SyntaxKind::PlusEqual, "+=")),
SyntaxKind::Minus => Some((SyntaxKind::MinusEqual, "-=")),
SyntaxKind::Div => Some((SyntaxKind::DivEqual, "/=")),
SyntaxKind::LAngle => Some((SyntaxKind::LessEqual, "<=")),
SyntaxKind::RAngle => Some((SyntaxKind::GreaterEqual, ">=")),
SyntaxKind::Equal => Some((SyntaxKind::EqualEqual, "==")),
SyntaxKind::Bang => Some((SyntaxKind::NotEqual, "!=")),
_ => None,
};
if let Some((k, t)) = kt {
if prev_spacing == Spacing::Joint {
last.kind = k;
last.text = t.into();
continue;
}
}
}
SyntaxKind::Equal
}
';' => SyntaxKind::Semicolon,
'!' => SyntaxKind::Bang,
'.' => SyntaxKind::Dot,
'+' => SyntaxKind::Plus,
'-' => {
if let Some(last) = vec.last_mut() {
if last.kind == SyntaxKind::Identifier
&& are_token_touching(prev_span, p.span())
{
last.text = format!("{}-", last.text).into();
prev_span = span;
continue;
}
}
SyntaxKind::Minus
}
'*' => SyntaxKind::Star,
'/' => SyntaxKind::Div,
'<' => SyntaxKind::LAngle,
'>' => {
if let Some(last) = vec.last_mut() {
if last.kind == SyntaxKind::LessEqual && prev_spacing == Spacing::Joint
{
last.kind = SyntaxKind::DoubleArrow;
last.text = "<=>".into();
continue;
} else if last.kind == SyntaxKind::Equal
&& prev_spacing == Spacing::Joint
{
last.kind = SyntaxKind::FatArrow;
last.text = "=>".into();
continue;
} else if last.kind == SyntaxKind::Minus
&& prev_spacing == Spacing::Joint
{
last.kind = SyntaxKind::Arrow;
last.text = "->".into();
continue;
}
}
SyntaxKind::RAngle
}
'#' => SyntaxKind::ColorLiteral,
'?' => SyntaxKind::Question,
',' => SyntaxKind::Comma,
'&' => {
if let Some(last) = vec.last_mut() {
if last.kind == SyntaxKind::AndAnd && prev_spacing == Spacing::Joint {
continue;
}
}
SyntaxKind::AndAnd
}
'|' => {
if let Some(last) = vec.last_mut() {
if last.kind == SyntaxKind::OrOr && prev_spacing == Spacing::Joint {
continue;
}
}
SyntaxKind::OrOr
}
'%' => {
if let Some(last) = vec.last_mut() {
if last.kind == SyntaxKind::NumberLiteral {
last.text = format!("{}%", last.text).into();
continue;
}
}
SyntaxKind::Error
}
'$' => SyntaxKind::Dollar,
'@' => SyntaxKind::At,
_ => SyntaxKind::Error,
};
prev_spacing = p.spacing();
vec.push(parser::Token {
kind,
text: p.to_string().into(),
span: Some(p.span()),
..Default::default()
});
}
TokenTree::Literal(l) => {
let s = l.to_string();
let f = s.chars().next().unwrap();
let kind = if f == '"' {
SyntaxKind::StringLiteral
} else if f.is_digit(10) {
if let Some(last) = vec.last_mut() {
if (last.kind == SyntaxKind::ColorLiteral && last.text.len() == 1)
|| (last.kind == SyntaxKind::Identifier
&& are_token_touching(prev_span, span))
{
last.text = format!("{}{}", last.text, s).into();
prev_span = span;
continue;
}
}
SyntaxKind::NumberLiteral
} else {
SyntaxKind::Error
};
vec.push(parser::Token {
kind,
text: s.into(),
span: Some(l.span()),
..Default::default()
});
}
TokenTree::Group(g) => {
use proc_macro::Delimiter::*;
use SyntaxKind::*;
let (l, r, sl, sr) = match g.delimiter() {
Parenthesis => (LParent, RParent, "(", ")"),
Brace => (LBrace, RBrace, "{", "}"),
Bracket => (LBracket, RBracket, "[", "]"),
None => todo!(),
};
vec.push(parser::Token {
kind: l,
text: sl.into(),
span: Some(g.span()),
..Default::default()
});
fill_token_vec(g.stream().into_iter(), vec);
vec.push(parser::Token {
kind: r,
text: sr.into(),
span: Some(g.span()),
..Default::default()
});
}
}
prev_span = span;
}
}
fn extract_include_paths(
mut stream: proc_macro::token_stream::IntoIter,
) -> (impl Iterator<Item = TokenTree>, Vec<std::path::PathBuf>) {
let mut include_paths = Vec::new();
let mut remaining_stream;
loop {
remaining_stream = stream.clone();
match (stream.next(), stream.next()) {
(Some(TokenTree::Punct(p)), Some(TokenTree::Group(group)))
if p.as_char() == '#' && group.delimiter() == proc_macro::Delimiter::Bracket =>
{
let mut attr_stream = group.stream().into_iter();
match (attr_stream.next(), attr_stream.next(), attr_stream.next()) {
(
Some(TokenTree::Ident(include_ident)),
Some(TokenTree::Punct(equal_punct)),
Some(TokenTree::Literal(path)),
) if include_ident.to_string() == "include_path"
&& equal_punct.as_char() == '=' =>
{
let path_with_quotes = path.to_string();
let path_with_quotes_stripped =
if let Some(p) = path_with_quotes.strip_prefix('r') {
let hash_removed = p.trim_matches('#');
hash_removed.strip_prefix('\"').unwrap().strip_suffix('\"').unwrap()
} else {
path_with_quotes.trim_matches('\"')
};
include_paths.push(path_with_quotes_stripped.into());
}
_ => break,
}
}
_ => break,
}
}
(remaining_stream, include_paths)
}
#[proc_macro]
pub fn sixtyfps(stream: TokenStream) -> TokenStream {
let token_iter = stream.into_iter();
let (token_iter, include_paths) = extract_include_paths(token_iter);
let mut tokens = vec![];
fill_token_vec(token_iter, &mut tokens);
let source_file = if let Some(cargo_manifest) = std::env::var_os("CARGO_MANIFEST_DIR") {
let mut path: std::path::PathBuf = cargo_manifest.into();
path.push("Cargo.toml");
diagnostics::SourceFileInner::from_path_only(path)
} else {
diagnostics::SourceFileInner::from_path_only(Default::default())
};
let mut diag = BuildDiagnostics::default();
let syntax_node = parser::parse_tokens(tokens.clone(), source_file, &mut diag);
if diag.has_error() {
return diag.report_macro_diagnostic(&tokens);
}
let mut compiler_config =
CompilerConfiguration::new(sixtyfps_compilerlib::generator::OutputFormat::Rust);
if std::env::var_os("SIXTYFPS_STYLE").is_none() {
let target_path = match std::env::var_os("OUT_DIR") {
Some(out_dir) => Some(
Path::new(&out_dir)
.parent()
.unwrap()
.parent()
.unwrap()
.join("SIXTYFPS_DEFAULT_STYLE.txt"),
),
None => {
let mut args = std::env::args();
let mut out_dir = None;
while let Some(arg) = args.next() {
if arg == "--out-dir" {
out_dir = args.next();
}
}
out_dir.map(|out_dir| {
Path::new(&out_dir).parent().unwrap().join("build/SIXTYFPS_DEFAULT_STYLE.txt")
})
}
};
if let Some(target_path) = target_path {
compiler_config.style =
std::fs::read_to_string(target_path).map(|style| style.trim().into()).ok()
}
}
compiler_config.include_paths = include_paths;
let (root_component, diag) =
spin_on::spin_on(compile_syntax_node(syntax_node, diag, compiler_config));
if diag.has_error() {
return diag.report_macro_diagnostic(&tokens);
}
let mut result = generator::rust::generate(&root_component);
let reload = diag
.all_loaded_files
.iter()
.filter(|path| path.is_absolute() && !path.ends_with("Cargo.toml"))
.filter_map(|p| p.to_str())
.map(|p| quote! {const _ : &'static [u8] = ::core::include_bytes!(#p);});
result.extend(reload);
result.extend(quote! {const _ : Option<&'static str> = ::core::option_env!("SIXTYFPS_STYLE");});
result.into()
}