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
use std::sync::Arc;
use cairo_lang_defs::plugin::{
DynGeneratedFileAuxData, MacroPlugin, PluginDiagnostic, PluginGeneratedFile, PluginResult,
};
use cairo_lang_semantic::plugin::{AsDynMacroPlugin, SemanticPlugin, TrivialPluginAuxData};
use cairo_lang_syntax::node::ast::AttributeList;
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::{ast, Terminal, TypedSyntaxNode};
#[derive(Debug)]
pub struct DerivePlugin {}
impl MacroPlugin for DerivePlugin {
fn generate_code(&self, db: &dyn SyntaxGroup, item_ast: ast::Item) -> PluginResult {
match item_ast {
ast::Item::Struct(struct_ast) => {
generate_derive_code_for_type(db, struct_ast.name(db), struct_ast.attributes(db))
}
ast::Item::Enum(enum_ast) => {
generate_derive_code_for_type(db, enum_ast.name(db), enum_ast.attributes(db))
}
ast::Item::ExternType(extern_type_ast) => generate_derive_code_for_type(
db,
extern_type_ast.name(db),
extern_type_ast.attributes(db),
),
_ => PluginResult::default(),
}
}
}
impl AsDynMacroPlugin for DerivePlugin {
fn as_dyn_macro_plugin<'a>(self: Arc<Self>) -> Arc<dyn MacroPlugin + 'a>
where
Self: 'a,
{
self
}
}
impl SemanticPlugin for DerivePlugin {}
fn generate_derive_code_for_type(
db: &dyn SyntaxGroup,
ident: ast::TerminalIdentifier,
attributes: AttributeList,
) -> PluginResult {
let mut diagnostics = vec![];
let mut impls = vec![];
for attr in attributes.elements(db) {
if attr.attr(db).text(db) == "derive" {
if let ast::OptionAttributeArgs::AttributeArgs(args) = attr.args(db) {
for arg in args.arg_list(db).elements(db) {
if let ast::Expr::Path(expr) = arg {
if let [ast::PathSegment::Simple(segment)] = &expr.elements(db)[..] {
let name = ident.text(db);
let derived = segment.ident(db).text(db);
if matches!(derived.as_str(), "Copy" | "Drop") {
impls.push(format!(
"impl {name}{derived} of {derived}::<{name}>;\n"
));
}
} else {
diagnostics.push(PluginDiagnostic {
stable_ptr: expr.stable_ptr().untyped(),
message: "Expected a single segment.".into(),
});
}
} else {
diagnostics.push(PluginDiagnostic {
stable_ptr: arg.stable_ptr().untyped(),
message: "Expected path.".into(),
});
}
}
} else {
diagnostics.push(PluginDiagnostic {
stable_ptr: attr.args(db).stable_ptr().untyped(),
message: "Expected args.".into(),
});
}
}
}
PluginResult {
code: if impls.is_empty() {
None
} else {
Some(PluginGeneratedFile {
name: "impls".into(),
content: impls.join(""),
aux_data: DynGeneratedFileAuxData(Arc::new(TrivialPluginAuxData {})),
})
},
diagnostics,
remove_original_item: false,
}
}