This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 657
/
Copy pathmodel.rs
379 lines (345 loc) · 12.7 KB
/
model.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
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
use super::*;
use rome_js_syntax::{AnyJsFunction, AnyJsRoot, JsInitializerClause, JsVariableDeclarator};
#[derive(Copy, Clone, Debug)]
pub(crate) struct BindingIndex(usize);
impl From<usize> for BindingIndex {
fn from(v: usize) -> Self {
BindingIndex(v)
}
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct ReferenceIndex(usize, usize);
impl ReferenceIndex {
pub(crate) fn binding(&self) -> BindingIndex {
BindingIndex(self.0)
}
}
impl From<(BindingIndex, usize)> for ReferenceIndex {
fn from((binding_index, index): (BindingIndex, usize)) -> Self {
ReferenceIndex(binding_index.0, index)
}
}
/// Contains all the data of the [SemanticModel] and only lives behind an [Arc].
///
/// That allows any returned struct (like [Scope], [Binding])
/// to outlive the [SemanticModel], and to not include lifetimes.
#[derive(Debug)]
pub(crate) struct SemanticModelData {
pub(crate) root: AnyJsRoot,
// All scopes of this model
pub(crate) scopes: Vec<SemanticModelScopeData>,
pub(crate) scope_by_range: rust_lapper::Lapper<usize, usize>,
// Maps the start of a node range to a scope id
pub(crate) scope_hoisted_to_by_range: FxHashMap<TextSize, usize>,
// Map to each by its range
pub(crate) node_by_range: FxHashMap<TextRange, JsSyntaxNode>,
// Maps any range in the code to its bindings (usize points to bindings vec)
pub(crate) declared_at_by_range: FxHashMap<TextRange, usize>,
// List of all the declarations
pub(crate) bindings: Vec<SemanticModelBindingData>,
// Index bindings by range
pub(crate) bindings_by_range: FxHashMap<TextRange, usize>,
// All bindings that were exported
pub(crate) exported: FxHashSet<TextRange>,
/// All references that could not be resolved
pub(crate) unresolved_references: Vec<SemanticModelUnresolvedReference>,
/// All globals references
pub(crate) globals: Vec<SemanticModelGlobalBindingData>,
}
impl SemanticModelData {
pub(crate) fn binding(&self, index: BindingIndex) -> &SemanticModelBindingData {
&self.bindings[index.0]
}
pub(crate) fn reference(&self, index: ReferenceIndex) -> &SemanticModelReference {
let binding = &self.bindings[index.0];
&binding.references[index.1]
}
pub(crate) fn next_reference(&self, index: ReferenceIndex) -> Option<&SemanticModelReference> {
let binding = &self.bindings[index.0];
binding.references.get(index.1 + 1)
}
pub(crate) fn scope(&self, range: &TextRange) -> usize {
let start = range.start().into();
let end = range.end().into();
let scopes = self
.scope_by_range
.find(start, end)
.filter(|x| !(start < x.start || end > x.stop));
// We always want the most tight scope
match scopes.map(|x| x.val).max() {
Some(val) => val,
// We always have at least one scope, the global one.
None => unreachable!("Expected global scope not present"),
}
}
fn scope_hoisted_to(&self, range: &TextRange) -> Option<usize> {
self.scope_hoisted_to_by_range.get(&range.start()).cloned()
}
pub fn is_exported(&self, range: TextRange) -> bool {
self.exported.contains(&range)
}
}
impl PartialEq for SemanticModelData {
fn eq(&self, other: &Self) -> bool {
self.root == other.root
}
}
impl Eq for SemanticModelData {}
/// The façade for all semantic information.
/// - Scope: [scope]
/// - Declarations: [declaration]
///
/// See [SemanticModelData] for more information about the internals.
#[derive(Clone, Debug)]
pub struct SemanticModel {
pub(crate) data: Arc<SemanticModelData>,
}
impl SemanticModel {
pub(crate) fn new(data: SemanticModelData) -> Self {
Self {
data: Arc::new(data),
}
}
/// Iterate all scopes
pub fn scopes(&self) -> impl Iterator<Item = Scope> + '_ {
self.data.scopes.iter().enumerate().map(|(id, _)| Scope {
data: self.data.clone(),
id,
})
}
/// Returns the global scope of the model
pub fn global_scope(&self) -> Scope {
Scope {
data: self.data.clone(),
id: 0,
}
}
/// Returns the [Scope] which the syntax is part of.
/// Can also be called from [AstNode]::scope extension method.
///
/// ```rust
/// use rome_rowan::{AstNode, SyntaxNodeCast};
/// use rome_js_syntax::{JsFileSource, JsReferenceIdentifier};
/// use rome_js_semantic::{semantic_model, SemanticModelOptions, SemanticScopeExtensions};
///
/// let r = rome_js_parser::parse("function f(){let a = arguments[0]; let b = a + 1;}", JsFileSource::js_module());
/// let model = semantic_model(&r.tree(), SemanticModelOptions::default());
///
/// let arguments_reference = r
/// .syntax()
/// .descendants()
/// .filter_map(|x| x.cast::<JsReferenceIdentifier>())
/// .find(|x| x.text() == "arguments")
/// .unwrap();
///
/// let block_scope = model.scope(&arguments_reference.syntax());
/// // or
/// let block_scope = arguments_reference.scope(&model);
/// ```
pub fn scope(&self, node: &JsSyntaxNode) -> Scope {
let range = node.text_range();
let id = self.data.scope(&range);
Scope {
data: self.data.clone(),
id,
}
}
/// Returns the [Scope] which the specified syntax node was hoisted to, if any.
/// Can also be called from [AstNode]::scope_hoisted_to extension method.
pub fn scope_hoisted_to(&self, node: &JsSyntaxNode) -> Option<Scope> {
let range = node.text_range();
let id = self.data.scope_hoisted_to(&range)?;
Some(Scope {
data: self.data.clone(),
id,
})
}
pub fn all_bindings(&self) -> impl Iterator<Item = Binding> + '_ {
self.data.bindings.iter().map(|x| Binding {
data: self.data.clone(),
index: x.id,
})
}
/// Returns the [Binding] of a reference.
/// Can also be called from "binding" extension method.
///
/// ```rust
/// use rome_rowan::{AstNode, SyntaxNodeCast};
/// use rome_js_syntax::{JsFileSource, JsReferenceIdentifier};
/// use rome_js_semantic::{semantic_model, BindingExtensions, SemanticModelOptions};
///
/// let r = rome_js_parser::parse("function f(){let a = arguments[0]; let b = a + 1;}", JsFileSource::js_module());
/// let model = semantic_model(&r.tree(), SemanticModelOptions::default());
///
/// let arguments_reference = r
/// .syntax()
/// .descendants()
/// .filter_map(|x| x.cast::<JsReferenceIdentifier>())
/// .find(|x| x.text() == "arguments")
/// .unwrap();
///
/// let arguments_binding = model.binding(&arguments_reference);
/// // or
/// let arguments_binding = arguments_reference.binding(&model);
/// ```
pub fn binding(&self, reference: &impl HasDeclarationAstNode) -> Option<Binding> {
let reference = reference.node();
let range = reference.syntax().text_range();
let id = *self.data.declared_at_by_range.get(&range)?;
Some(Binding {
data: self.data.clone(),
index: id.into(),
})
}
/// Returns an iterator of all the globals references in the program
pub fn all_global_references(
&self,
) -> std::iter::Successors<GlobalReference, fn(&GlobalReference) -> Option<GlobalReference>>
{
let first = self
.data
.globals
.get(0)
.and_then(|global| global.references.get(0))
.map(|_| GlobalReference {
data: self.data.clone(),
global_id: 0,
id: 0,
});
fn succ(current: &GlobalReference) -> Option<GlobalReference> {
let mut global_id = current.global_id;
let mut id = current.id + 1;
while global_id < current.data.globals.len() {
let reference = current
.data
.globals
.get(global_id)
.and_then(|global| global.references.get(id))
.map(|_| GlobalReference {
data: current.data.clone(),
global_id,
id,
});
match reference {
Some(reference) => return Some(reference),
None => {
global_id += 1;
id = 0;
}
}
}
None
}
std::iter::successors(first, succ)
}
/// Returns an iterator of all the unresolved references in the program
pub fn all_unresolved_references(
&self,
) -> std::iter::Successors<
UnresolvedReference,
fn(&UnresolvedReference) -> Option<UnresolvedReference>,
> {
let first = self
.data
.unresolved_references
.get(0)
.map(|_| UnresolvedReference {
data: self.data.clone(),
id: 0,
});
fn succ(current: &UnresolvedReference) -> Option<UnresolvedReference> {
let id = current.id + 1;
current
.data
.unresolved_references
.get(id)
.map(|_| UnresolvedReference {
data: current.data.clone(),
id,
})
}
std::iter::successors(first, succ)
}
/// Returns if the node is exported or is a reference to a binding
/// that is exported.
///
/// When a binding is specified this method returns a bool.
///
/// When a reference is specified this method returns Option<bool>,
/// because there is no guarantee that the corresponding declaration exists.
pub fn is_exported<T>(&self, node: &T) -> T::Result
where
T: CanBeImportedExported,
{
node.is_exported(self)
}
/// Returns if the node is imported or is a reference to a binding
/// that is imported.
///
/// When a binding is specified this method returns a bool.
///
/// When a reference is specified this method returns Option<bool>,
/// because there is no guarantee that the corresponding declaration exists.
pub fn is_imported<T>(&self, node: &T) -> T::Result
where
T: CanBeImportedExported,
{
node.is_imported(self)
}
/// Returns the [Closure] associated with the node.
pub fn closure(&self, node: &impl HasClosureAstNode) -> Closure {
Closure::from_node(self.data.clone(), node)
}
/// Returns true or false if the expression is constant, which
/// means it does not depend on any other variables.
pub fn is_constant(&self, expr: &AnyJsExpression) -> bool {
is_constant::is_constant(expr)
}
pub fn as_binding(&self, binding: &impl IsBindingAstNode) -> Binding {
let range = binding.syntax().text_range();
let id = &self.data.bindings_by_range[&range];
Binding {
data: self.data.clone(),
index: (*id).into(),
}
}
/// Returns all [Call] of a [AnyJsFunction].
///
/// ```rust
/// use rome_rowan::{AstNode, SyntaxNodeCast};
/// use rome_js_syntax::{JsFileSource, AnyJsFunction};
/// use rome_js_semantic::{semantic_model, CallsExtensions, SemanticModelOptions};
///
/// let r = rome_js_parser::parse("function f(){} f() f()", JsFileSource::js_module());
/// let model = semantic_model(&r.tree(), SemanticModelOptions::default());
///
/// let f_declaration = r
/// .syntax()
/// .descendants()
/// .filter_map(AnyJsFunction::cast)
/// .next()
/// .unwrap();
///
/// let all_calls_to_f = model.all_calls(&f_declaration);
/// assert_eq!(2, all_calls_to_f.unwrap().count());
/// // or
/// let all_calls_to_f = f_declaration.all_calls(&model);
/// assert_eq!(2, all_calls_to_f.unwrap().count());
/// ```
pub fn all_calls(&self, function: &AnyJsFunction) -> Option<AllCallsIter> {
let identifier = match function {
AnyJsFunction::JsFunctionDeclaration(declaration) => declaration.id().ok()?,
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => declaration.id()?,
AnyJsFunction::JsArrowFunctionExpression(_)
| AnyJsFunction::JsFunctionExpression(_) => {
let parent = function
.parent::<JsInitializerClause>()?
.parent::<JsVariableDeclarator>()?;
parent.id().ok()?.as_any_js_binding()?.clone()
}
};
Some(AllCallsIter {
references: identifier.all_reads(self),
})
}
}