-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathdb.rs
218 lines (202 loc) · 8.12 KB
/
db.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
use crate::compiler::plugin::proc_macro::{ProcMacroHost, ProcMacroHostPlugin};
use crate::compiler::{CairoCompilationUnit, CompilationUnitAttributes, CompilationUnitComponent};
use crate::core::Workspace;
use crate::DEFAULT_MODULE_MAIN_FILE;
use anyhow::{anyhow, Result};
use cairo_lang_compiler::db::{RootDatabase, RootDatabaseBuilder};
use cairo_lang_compiler::project::{AllCratesConfig, ProjectConfig, ProjectConfigContent};
use cairo_lang_defs::db::DefsGroup;
use cairo_lang_defs::ids::ModuleId;
use cairo_lang_defs::plugin::MacroPlugin;
use cairo_lang_filesystem::db::{
AsFilesGroupMut, CrateIdentifier, CrateSettings, DependencySettings, FilesGroup, FilesGroupEx,
};
use cairo_lang_filesystem::ids::CrateLongId;
use cairo_lang_semantic::plugin::PluginSuite;
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use smol_str::SmolStr;
use std::path::PathBuf;
use std::sync::Arc;
use tracing::trace;
pub struct ScarbDatabase {
pub db: RootDatabase,
pub proc_macro_host: Arc<ProcMacroHostPlugin>,
}
pub(crate) fn build_scarb_root_database(
unit: &CairoCompilationUnit,
ws: &Workspace<'_>,
additional_plugins: Vec<PluginSuite>,
) -> Result<ScarbDatabase> {
let mut b = RootDatabase::builder();
b.with_project_config(build_project_config(unit)?);
b.with_cfg(unit.cfg_set.clone());
b.with_inlining_strategy(unit.compiler_config.inlining_strategy.clone().into());
let proc_macro_host = load_plugins(unit, ws, &mut b, additional_plugins)?;
if !unit.compiler_config.enable_gas {
b.skip_auto_withdraw_gas();
}
if unit.compiler_config.add_redeposit_gas {
b.with_add_redeposit_gas();
}
let mut db = b.build()?;
inject_virtual_wrapper_lib(&mut db, unit)?;
Ok(ScarbDatabase {
db,
proc_macro_host,
})
}
fn load_plugins(
unit: &CairoCompilationUnit,
ws: &Workspace<'_>,
builder: &mut RootDatabaseBuilder,
additional_plugins: Vec<PluginSuite>,
) -> Result<Arc<ProcMacroHostPlugin>> {
let mut proc_macros = ProcMacroHost::default();
for plugin_info in &unit.cairo_plugins {
if plugin_info.builtin {
let package_id = plugin_info.package.id;
let plugin = ws.config().cairo_plugins().fetch(package_id)?;
let instance = plugin.instantiate()?;
builder.with_plugin_suite(instance.plugin_suite());
} else if let Some(prebuilt) = &plugin_info.prebuilt {
proc_macros.register_instance(prebuilt.clone());
} else {
proc_macros.register_new(plugin_info.package.clone(), ws.config())?;
}
}
for plugin in additional_plugins {
builder.with_plugin_suite(plugin);
}
let macro_host = Arc::new(proc_macros.into_plugin()?);
builder.with_plugin_suite(ProcMacroHostPlugin::build_plugin_suite(macro_host.clone()));
Ok(macro_host)
}
/// Generates a wrapper lib file for appropriate compilation units.
///
/// This approach allows compiling crates that do not define `lib.cairo` file.
/// For example, single file crates can be created this way.
/// The actual single file modules are defined as `mod` items in created lib file.
fn inject_virtual_wrapper_lib(db: &mut RootDatabase, unit: &CairoCompilationUnit) -> Result<()> {
let components: Vec<&CompilationUnitComponent> = unit
.components
.iter()
.filter(|component| !component.package.id.is_core())
// Skip components defining the default source path, as they already define lib.cairo files.
.filter(|component| {
!component.targets.is_empty()
&& (component.targets.len() > 1
|| component
.first_target()
.source_path
.file_name()
.map(|file_name| file_name != DEFAULT_MODULE_MAIN_FILE)
.unwrap_or(false))
})
.collect();
for component in components {
let name = component.cairo_package_name();
let crate_id = db.intern_crate(CrateLongId::Real {
name,
discriminator: component.id.to_discriminator(),
});
let file_stems = component
.targets
.iter()
.map(|target| {
target
.source_path
.file_stem()
.map(|file_stem| format!("mod {file_stem};"))
.ok_or_else(|| {
anyhow!(
"failed to get file stem for component {}",
target.source_path
)
})
})
.collect::<Result<Vec<_>>>()?;
let content = file_stems.join("\n");
let module_id = ModuleId::CrateRoot(crate_id);
let file_id = db.module_main_file(module_id).unwrap();
// Inject virtual lib file wrapper.
db.as_files_group_mut()
.override_file_content(file_id, Some(Arc::from(content.as_str())));
}
Ok(())
}
fn build_project_config(unit: &CairoCompilationUnit) -> Result<ProjectConfig> {
let crate_roots: OrderedHashMap<CrateIdentifier, PathBuf> = unit
.components
.iter()
.map(|component| {
(
component.id.to_crate_identifier(),
component.first_target().source_root().into(),
)
})
.collect();
let crates_config = unit
.components
.iter()
.map(|component| {
let experimental_features = component.package.manifest.experimental_features.clone();
let experimental_features = experimental_features.unwrap_or_default();
let dependencies = component
.dependencies
.iter()
.map(|compilation_unit_component_id| {
let compilation_unit_component = unit.components.iter().find(|component| component.id == *compilation_unit_component_id)
.expect("dependency of a component is guaranteed to exist in compilation unit components");
(
compilation_unit_component.cairo_package_name().to_string(),
DependencySettings {
discriminator: compilation_unit_component.id.to_discriminator()
},
)
})
.collect();
(
component.id.to_crate_identifier(),
CrateSettings {
name: Some(component.cairo_package_name()),
edition: component.package.manifest.edition,
cfg_set: component.cfg_set.clone(),
version: Some(component.package.id.version.clone()),
dependencies,
// TODO (#1040): replace this with a macro
experimental_features: cairo_lang_filesystem::db::ExperimentalFeaturesConfig {
negative_impls: experimental_features
.contains(&SmolStr::new_inline("negative_impls")),
coupons: experimental_features.contains(&SmolStr::new_inline("coupons")),
associated_item_constraints: experimental_features
.contains(&SmolStr::new_static("associated_item_constraints")),
},
},
)
})
.collect();
let crates_config = AllCratesConfig {
override_map: crates_config,
..Default::default()
};
let content = ProjectConfigContent {
crate_roots,
crates_config,
};
let project_config = ProjectConfig {
base_path: unit.main_component().package.root().into(),
content,
};
trace!(?project_config);
Ok(project_config)
}
pub(crate) fn has_starknet_plugin(db: &RootDatabase) -> bool {
db.macro_plugins()
.iter()
.any(|plugin| is_starknet_plugin(&**plugin))
}
fn is_starknet_plugin(plugin: &dyn MacroPlugin) -> bool {
// Can this be done in less "hacky" way? TypeId is not working here, because we deal with
// trait objects.
format!("{:?}", plugin).contains("StarkNetPlugin")
}