-
Notifications
You must be signed in to change notification settings - Fork 518
/
array.rs
93 lines (79 loc) · 3.06 KB
/
array.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
use cairo_lang_defs::patcher::PatchBuilder;
use cairo_lang_defs::plugin::{
InlineMacroExprPlugin, InlinePluginResult, MacroPluginMetadata, NamedPlugin,
PluginGeneratedFile,
};
use cairo_lang_defs::plugin_utils::unsupported_bracket_diagnostic;
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::{ast, TypedSyntaxNode};
#[derive(Debug, Default)]
pub struct ArrayMacro;
impl NamedPlugin for ArrayMacro {
const NAME: &'static str = "array";
}
impl InlineMacroExprPlugin for ArrayMacro {
fn generate_code(
&self,
db: &dyn SyntaxGroup,
syntax: &ast::ExprInlineMacro,
_metadata: &MacroPluginMetadata<'_>,
) -> InlinePluginResult {
let ast::WrappedArgList::BracketedArgList(args) = syntax.arguments(db) else {
return unsupported_bracket_diagnostic(db, syntax);
};
let mut builder = PatchBuilder::new(db, syntax);
builder.add_str(
"{
let mut __array_builder_macro_result__ = core::array::ArrayTrait::new();",
);
for arg in args.arguments(db).elements(db) {
builder.add_str(
"\n core::array::ArrayTrait::append(ref __array_builder_macro_result__,",
);
builder.add_node(arg.as_syntax_node());
builder.add_str(");");
}
builder.add_str(
"\n __array_builder_macro_result__
}",
);
let (content, code_mappings) = builder.build();
InlinePluginResult {
code: Some(PluginGeneratedFile {
name: "array_inline_macro".into(),
content,
code_mappings,
aux_data: None,
}),
diagnostics: vec![],
}
}
fn documentation(&self) -> Option<String> {
Some(
indoc! {r#"
Creates a new array containing the provided elements.
The `array!` macro allows you to create an array by specifying a list of elements. \
The elements are added to a new array in the order they are provided.
# Syntax
```cairo
array![element1, element2, element3, ...]
```
# Returns
An array containing the specified elements.
# Examples
```cairo
let arr = array![]; // Creates an empty array.
let arr = array![1, 2, 3]; // Creates an array containing 1, 2, and 3.
let x = 5;
let y = 10;
let arr = array![x, y, x + y]; // Creates an array containing 5, 10, and 15.
```
# Notes
- All elements must be of the same type or compatible types that can be coerced to a common type.
- The macro internally uses `ArrayTrait::new()` to create a new array and `ArrayTrait::append()` to add each element.
- The order of the elements in the array is the same as the order they are provided in the macro.
"#}
.to_string(),
)
}
}