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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
mod enum_value;
mod struct_de_info;
mod token_de_info;
use crate::common;
use enum_value::*;
use quote::quote;
pub use struct_de_info::*;
use syn::Ident;
pub use token_de_info::*;
pub fn impl_token_deserialize_macro(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {
let name = &ast.ident;
let fields = common::get_struct_enum_fields(ast);
let (struct_info, struct_err) = get_struct_enum_de_info(ast);
// If this had the `enum_value` set, use different function.
if struct_info.enum_value {
return impl_token_deserialize_macro_enum_value(ast);
}
let parameter_checks = if struct_info.second_par_check {
let token_name = struct_info.token.clone().unwrap();
let match_second_par = list_match_second_par(&fields);
let allowed_second_args = list_allowed_tokens_strings(&fields, ast)
.iter()
.map(|item| format!("`{}`", item))
.collect::<Vec<String>>()
.join(", ");
quote! {
let mut token = match Token::deserialize_tokens(&mut cursor, source, &mut diagnostics){
Ok(token) => token,
Err(err) => {
// When token could not be parsed correctly.
// Token could not be parsed, so we can consume it.
// Because this will always fail.
Token::consume_token(&mut cursor).unwrap();
return (LoopControl::ErrBreak, new_self);
}
};
// Token is consumed lower down.
// Token Name
match token.check_token_name(source, &mut diagnostics, false){
Ok(_) => {},
Err(_) => {
// Go back up the stack
if *new_self == Self::default() {
return (LoopControl::ErrBreak, new_self);
}
return (LoopControl::Break, new_self);
}
};
let token_name = match token.checked_get_token_name(source, &mut diagnostics, true){
Ok(name) => name,
Err(_) => {
return (LoopControl::ErrBreak, new_self);
}
};
// Check if token name is expected name
if &token_name.value != &#token_name {
// If nothing changed
if *new_self == Self::default() {
return (LoopControl::ErrBreak, new_self);
}
return (LoopControl::Break, new_self);
}
if let Err(_) = Token::consume_token(&mut cursor) {
return (LoopControl::Break, new_self);
}
// Arg 0
let arg0 = match token.checked_get_current_arg(source, &mut diagnostics, true){
Ok(arg) => arg,
Err(_) => {
return (LoopControl::ErrBreak, new_self);
}
};
token.consume_argument();
if let Err(_) = token.check_all_arg_consumed(source, &mut diagnostics, true) {
return (LoopControl::Break, new_self);
}
match &arg0.value {
TokenArgument::TVReference(value) => {
log::debug!("Matching {} in {}", value, stringify!(#name));
match value.as_ref() as &str {
#match_second_par
object_type => {
diagnostics.add_message(DMExtraInfo {
range: arg0.node.get_range(),
message_template_data: hash_map! {
"found_parameter" => format!("`{}`", object_type),
"token_name" => format!("`{}`", #token_name),
"valid_types" => #allowed_second_args.to_owned(),
},
}, "invalid_second_par_type");
}
}
}
_ => {
log::error!("LS Error: arguments not the same type but was already checked.");
}
}
}
} else {
let match_first_par = list_match_first_par(&fields, ast);
// Primary token is the main token that has to be set before adding data. (issue #36)
let primary_token = get_primary_token(&fields);
let primary_token_check = if let Some((primary_token, primary_token_ref)) = primary_token {
let primary_token_ref = match primary_token_ref {
Some(reference) => quote! { Some(#reference.to_owned()) },
None => quote! { None },
};
quote! {
let primary_token_filled = new_self.#primary_token.is_some();
let primary_token_ref: Option<String> = #primary_token_ref;
}
} else {
quote! {
let primary_token_filled = true;
let primary_token_ref: Option<String> = None;
}
};
quote! {
let mut token = match Token::deserialize_tokens(&mut cursor, source, &mut diagnostics){
Ok(token) => token,
Err(err) => {
// When token could not be parsed correctly
// Token could not be parsed, so we can consume it.
// Because this will always fail.
Token::consume_token(&mut cursor).unwrap();
return (LoopControl::ErrBreak, new_self);
}
};
// No `Token::consume_token(&mut cursor)?;` here because the token will be consumed when
// all arguments can be stored inside of object
#primary_token_check
// Token name
if let Err(_) = token.check_token_name(source, &mut diagnostics, true) {
return (LoopControl::Break, new_self);
}
let token_name = match token.checked_get_token_name(source, &mut diagnostics, true){
Ok(name) => name,
Err(_) => {
return (LoopControl::ErrBreak, new_self);
}
};
log::debug!("Matching {} in {}", token_name.value, stringify!(#name));
match token_name.value.as_ref() as &str {
#match_first_par
_ => {
// If nothing changed
if *new_self == Self::default() {
return (LoopControl::ErrBreak, new_self);
}
// Go back up to parent
return (LoopControl::Break, new_self);
}
}
}
};
// Create the list of allowed tokens
// This is used for checking in `Vec<>`
let allowed_tokens = if struct_info.second_par_check {
let token_name = struct_info.token.unwrap();
quote! { vec![#token_name.to_owned()] }
} else {
let list = list_allowed_tokens(&fields, ast);
quote! { vec![#list] }
};
quote! {
#struct_err
impl TokenDeserialize for #name {
#[allow(unused_variables)]
fn deserialize_general_token(
mut cursor: &mut df_ls_syntax_analysis::TreeCursor,
source: &str,
mut diagnostics: &mut df_ls_diagnostics::DiagnosticsInfo,
mut new_self: Box<Self>,
) -> (df_ls_syntax_analysis::LoopControl, Box<Self>) {
use df_ls_syntax_analysis::{LoopControl, TreeCursor,
TokenArgument, Token};
use df_ls_diagnostics::{DiagnosticsInfo, DMExtraInfo, hash_map};
let node = cursor.node();
#parameter_checks
#[allow(unreachable_code)]
(LoopControl::DoNothing, new_self)
}
fn get_allowed_tokens() -> Option<Vec<String>> {
Some(#allowed_tokens)
}
}
// ------------------------- Convert a group of arguments to Self -----------------------
// TryFromArgumentGroup not implemented because it is not used
// This struct is used to deserialize 1 or more tokens, not token arguments
// -------------------------Convert one argument to Self -----------------------
// TryFromArgument not implemented because it is not used
// This struct is used to deserialize 1 or more tokens, not a token argument
}
}
fn list_match_first_par(
struct_fields: &[syn::Field],
ast: &syn::DeriveInput,
) -> proc_macro2::TokenStream {
let mut parse_gen = quote! {};
for (_i, field) in struct_fields.iter().enumerate() {
let ident = field.ident.as_ref().unwrap();
let ident_type = &field.ty;
let ident_inner_type = common::get_inner_type(&field.ty);
let (token_info, token_err) = get_token_de_info(field);
let ident_is_vec = common::check_type_is_vec(&field.ty);
let token_ref = token_info.token;
// Change what to do when duplicate is reached
let on_duplicate = if token_info.on_duplicate_to_parent {
quote! {
// Go back up to parent
return (LoopControl::Break, new_self);
}
} else {
let token_ref = token_ref.clone().unwrap_or_default();
let primary_token = match get_primary_token(struct_fields) {
Some((_, Some(token_name))) => token_name,
_ => "<unknown>".to_owned(),
};
if token_info.on_duplicate_error {
quote! {
diagnostics.add_message(DMExtraInfo {
range: node.get_range(),
message_template_data: hash_map! {
"token_name" => format!("`{}`", #token_ref),
"parent_token" => format!("`{}`", #primary_token),
},
}, "duplicate_token_error");
if let Err(_) = Token::consume_token(&mut cursor) {
return (LoopControl::Break, new_self);
}
return (LoopControl::DoNothing, new_self);
}
} else {
quote! {
diagnostics.add_message(DMExtraInfo {
range: node.get_range(),
message_template_data: hash_map! {
"token_name" => format!("`{}`", #token_ref),
"parent_token" => format!("`{}`", #primary_token),
},
}, "duplicate_token_warn");
if let Err(_) = Token::consume_token(&mut cursor) {
return (LoopControl::Break, new_self);
}
return (LoopControl::DoNothing, new_self);
}
}
};
// If this token is not the primary token, add check if that is filled. (issue #36)
let primary_token_check = if !token_info.primary_token {
quote! {
if !primary_token_filled {
if let Some(primary_token_ref) = primary_token_ref{
diagnostics.add_message(DMExtraInfo {
range: node.get_range(),
message_template_data: hash_map! {
"expected_tokens" => format!("`{}`", primary_token_ref),
},
}, "token_is_missing");
} else {
diagnostics.add_message(DMExtraInfo {
range: node.get_range(),
message_template_data: hash_map! {
"expected_tokens" => "<Unknown>".to_owned(),
},
}, "token_is_missing");
}
return (LoopControl::ErrBreak, new_self);
}
}
} else {
quote! {}
};
// Add if `token = "SOME"` is set
if let Some(token_ref) = token_ref {
match &ast.data {
syn::Data::Struct(_x) => {
if ident_is_vec {
parse_gen = quote! {
#parse_gen
#token_ref => {
#token_err
#primary_token_check
// `#ident_type` = `Vec<...>`
let value: Result<Box<#ident_type>, _> = TokenDeserialize::deserialize_tokens(
&mut cursor,
source,
&mut diagnostics,
);
if let Ok(mut value) = value {
// Append because we want to parse a whole list, not just 1 item
new_self.#ident.append(value.as_mut());
}
// Don't go to next token, we are still matching this token.
return (LoopControl::Continue, new_self);
}
};
// Alias
if let Some(alias) = token_info.alias {
parse_gen = quote! {
#parse_gen
#alias => {
#primary_token_check
diagnostics.add_message(
DMExtraInfo {
range: token_name.node.get_range(),
message_template_data: hash_map! {
"alias_name" => format!("`{}`", #alias),
"suggested_name" => format!("`{}`", #token_ref),
},
},
"alias",
);
// `#ident_type` = `Vec<...>`
let value: Result<Box<#ident_type>, _> = TokenDeserialize::deserialize_tokens(
&mut cursor,
source,
&mut diagnostics,
);
if let Ok(mut value) = value {
// Append because we want to parse a whole list, not just 1 item
new_self.#ident.append(value.as_mut());
}
// Don't go to next token, we are still matching this token.
return (LoopControl::Continue, new_self);
}
};
}
} else {
parse_gen = quote! {
#parse_gen
#token_ref => {
#token_err
if new_self.#ident.is_some() {
#on_duplicate
}
#primary_token_check
// `#ident_type` = `Option<T>` so `#ident_inner_type` will be `T`
let value: Result<Box<#ident_inner_type>, _> = TokenDeserialize::deserialize_tokens(
&mut cursor,
source,
&mut diagnostics,
);
match value {
Ok(value) => {
new_self.#ident = Some(*value);
}
Err(_) => { /* Error is already in diagnostics */ }
}
}
};
// Alias
if let Some(alias) = token_info.alias {
parse_gen = quote! {
#parse_gen
#alias => {
if new_self.#ident.is_some() {
#on_duplicate
}
#primary_token_check
diagnostics.add_message(
DMExtraInfo {
range: token_name.node.get_range(),
message_template_data: hash_map! {
"alias_name" => format!("`{}`", #alias),
"suggested_name" => format!("`{}`", #token_ref),
},
},
"alias",
);
// `#ident_type` = `Option<T>` so `#ident_inner_type` will be `T`
let value: Result<Box<#ident_inner_type>, _> = TokenDeserialize::deserialize_tokens(
&mut cursor,
source,
&mut diagnostics,
);
match value {
Ok(value) => {
new_self.#ident = Some(*value);
}
Err(_) => { /* Error is already in diagnostics */ }
}
}
};
}
}
}
syn::Data::Enum(_x) => {
parse_gen = quote! {
#parse_gen
#token_ref => {
#token_err
#primary_token_check
let value: Result<Box<#ident_type>, _> = TokenDeserialize::deserialize_tokens(
&mut cursor,
source,
&mut diagnostics,
);
match value {
Ok(value) => {
new_self = Box::new(Self::#ident(*value));
return (LoopControl::Break, new_self);
}
Err(_) => { /* Error is already in diagnostics */ }
}
return (LoopControl::Continue, new_self);
}
};
// Alias
if let Some(alias) = token_info.alias {
parse_gen = quote! {
#parse_gen
#alias => {
#primary_token_check
diagnostics.add_message(
DMExtraInfo {
range: token_name.node.get_range(),
message_template_data: hash_map! {
"alias_name" => format!("`{}`", #alias),
"suggested_name" => format!("`{}`", #token_ref),
},
},
"alias",
);
let value: Result<Box<#ident_type>, _> = TokenDeserialize::deserialize_tokens(
&mut cursor,
source,
&mut diagnostics,
);
match value {
Ok(value) => {
new_self = Box::new(Self::#ident(*value));
return (LoopControl::Break, new_self);
}
Err(_) => { /* Error is already in diagnostics */ }
}
return (LoopControl::Continue, new_self);
}
};
}
}
syn::Data::Union(_x) => {
unimplemented!("Union is not implemented for TokenDeserialize.");
}
}
}
}
parse_gen
}
fn list_match_second_par(struct_fields: &[syn::Field]) -> proc_macro2::TokenStream {
let mut parse_gen = quote! {};
for (_i, field) in struct_fields.iter().enumerate() {
let ident = field.ident.as_ref().unwrap();
let ident_type = &field.ty;
let (token_info, _) = get_token_de_info(field);
let ident_is_vec = common::check_type_is_vec(&field.ty);
let token_ref = token_info.token;
// Add if `token = "SOME"` is set
if let Some(token_ref) = token_ref {
if ident_is_vec {
parse_gen = quote! {
#parse_gen
#token_ref => {
// `#ident_type` = `Vec<...>`
let value: Result<Box<#ident_type>, _> = TokenDeserialize::deserialize_tokens(
&mut cursor,
source,
&mut diagnostics,
);
if let Ok(mut value) = value {
// Append because we want to parse a whole list, not just 1 item
new_self.#ident.append(value.as_mut());
}
// Don't go to next token, we are still matching this token.
return (LoopControl::Continue, new_self);
}
};
} else {
panic!(
"Only `Vec<>` types are supported for member \
field of a struct that uses `token_de(second_par_check)`."
);
}
}
}
parse_gen
}
pub(super) fn list_allowed_tokens(
struct_fields: &[syn::Field],
ast: &syn::DeriveInput,
) -> proc_macro2::TokenStream {
let mut parse_gen = quote! {};
for (_i, field) in struct_fields.iter().enumerate() {
let (token_info, _) = get_token_de_info(field);
let token_ref = token_info.token;
// Add if `token = "SOME"` is set
if let Some(token_ref) = token_ref {
match &ast.data {
syn::Data::Struct(_x) => {
parse_gen = quote! {
#parse_gen #token_ref.to_owned(),
};
if let Some(alias) = token_info.alias {
parse_gen = quote! {
#parse_gen #alias.to_owned(),
};
}
}
syn::Data::Enum(_x) => {
parse_gen = quote! {
#parse_gen #token_ref.to_owned(),
};
if let Some(alias) = token_info.alias {
parse_gen = quote! {
#parse_gen #alias.to_owned(),
};
}
}
syn::Data::Union(_x) => {
unimplemented!("Union is not implemented for TokenDeserialize.");
}
}
}
}
parse_gen
}
pub(super) fn list_allowed_tokens_strings(
struct_fields: &[syn::Field],
ast: &syn::DeriveInput,
) -> Vec<String> {
let mut list = vec![];
for (_i, field) in struct_fields.iter().enumerate() {
let (token_info, _) = get_token_de_info(field);
let token_ref = token_info.token;
// Add if `token = "SOME"` is set
if let Some(token_ref) = token_ref {
match &ast.data {
syn::Data::Struct(_x) => {
list.push(token_ref);
}
syn::Data::Enum(_x) => {
list.push(token_ref);
}
syn::Data::Union(_x) => {
unimplemented!("Union is not implemented for TokenDeserialize.");
}
}
}
}
list
}
fn get_primary_token(struct_fields: &[syn::Field]) -> Option<(Ident, Option<String>)> {
let mut result = None;
for (_i, field) in struct_fields.iter().enumerate() {
let ident = field.ident.as_ref().unwrap();
let (token_info, _) = get_token_de_info(field);
if token_info.primary_token {
let token_ref = token_info.token;
if result.is_none() {
result = Some((ident.clone(), token_ref));
} else {
panic!("ERROR: Only one primary_token can be set.");
}
}
}
result
}