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
//! Import resolver visitor
//!
//! This visitor resolves import clauses by rewriting function calls
//! to use their fully qualified names based on the imports in scope.
use crate::ir::ast::{ClassDefinition, ComponentReference, Expression, Import, StoredDefinition};
use crate::ir::visitor::MutVisitor;
use indexmap::IndexMap;
/// Visitor that resolves imported names to their fully qualified forms
pub struct ImportResolver {
/// Map from short name to fully qualified name
name_map: IndexMap<String, String>,
}
impl ImportResolver {
/// Create a new import resolver for a class with the given stored definition context
pub fn new(class: &ClassDefinition, stored_def: &StoredDefinition) -> Self {
let mut name_map = IndexMap::new();
for import in &class.imports {
match import {
Import::Qualified { path, .. } => {
// import A.B.C; -> C maps to A.B.C
let full_path = path.to_string();
if let Some(last_part) = path.name.last() {
name_map.insert(last_part.text.clone(), full_path);
}
}
Import::Renamed { alias, path, .. } => {
// import D = A.B.C; -> D maps to A.B.C
let full_path = path.to_string();
name_map.insert(alias.text.clone(), full_path);
}
Import::Unqualified { path, .. } => {
// import A.B.*; -> all names from A.B are imported
let package_path = path.to_string();
// Find the package and import all its public names
if let Some(package) = find_class_by_path(stored_def, &package_path) {
// Import all functions and classes from the package
for (name, _) in &package.classes {
let full_path = format!("{}.{}", package_path, name);
name_map.insert(name.clone(), full_path);
}
}
}
Import::Selective { path, names, .. } => {
// import A.B.{C, D}; -> C maps to A.B.C, D maps to A.B.D
let package_path = path.to_string();
for name_token in names {
let full_path = format!("{}.{}", package_path, name_token.text);
name_map.insert(name_token.text.clone(), full_path);
}
}
}
}
Self { name_map }
}
/// Resolve a function name using the import map
pub fn resolve(&self, name: &str) -> Option<&String> {
self.name_map.get(name)
}
}
/// Find a class by its dot-separated path in the stored definition
fn find_class_by_path<'a>(
stored_def: &'a StoredDefinition,
path: &str,
) -> Option<&'a ClassDefinition> {
let parts: Vec<&str> = path.split('.').collect();
if parts.is_empty() {
return None;
}
// Start with the first part at the top level
let mut current = stored_def.class_list.get(parts[0])?;
// Navigate through the remaining parts
for part in parts.iter().skip(1) {
current = current.classes.get(*part)?;
}
Some(current)
}
impl MutVisitor for ImportResolver {
fn exit_expression(&mut self, expr: &mut Expression) {
match expr {
Expression::FunctionCall { comp, args: _ } => {
// Get the function name
let func_name = comp.to_string();
// If this is a simple name (no dots) and we have a mapping, resolve it
if !func_name.contains('.')
&& let Some(full_path) = self.name_map.get(&func_name)
{
// Rewrite the component reference to use the full path
let parts: Vec<&str> = full_path.split('.').collect();
let new_parts: Vec<crate::ir::ast::ComponentRefPart> = parts
.iter()
.map(|p| crate::ir::ast::ComponentRefPart {
ident: crate::ir::ast::Token {
text: p.to_string(),
..Default::default()
},
subs: None,
})
.collect();
*comp = ComponentReference {
local: false,
parts: new_parts,
};
}
}
Expression::ComponentReference(comp_ref) => {
// Handle import aliases for component references (e.g., L.'U' where L is an import alias)
if !comp_ref.parts.is_empty() {
let first_part = &comp_ref.parts[0].ident.text;
// Check if the first part is an import alias
if let Some(full_path) = self.name_map.get(first_part).cloned() {
// Build the new parts: full_path + remaining parts from original
let path_parts: Vec<&str> = full_path.split('.').collect();
let mut new_parts: Vec<crate::ir::ast::ComponentRefPart> = path_parts
.iter()
.map(|p| crate::ir::ast::ComponentRefPart {
ident: crate::ir::ast::Token {
text: p.to_string(),
..Default::default()
},
subs: None,
})
.collect();
// Add the remaining parts from the original reference (after the alias)
for part in comp_ref.parts.iter().skip(1) {
new_parts.push(part.clone());
}
*comp_ref = ComponentReference {
local: false,
parts: new_parts,
};
}
}
}
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::ast::{ComponentRefPart, Token};
use crate::ir::visitor::MutVisitable;
fn make_comp_ref(name: &str) -> Expression {
let parts: Vec<ComponentRefPart> = name
.split('.')
.map(|p| ComponentRefPart {
ident: Token {
text: p.to_string(),
..Default::default()
},
subs: None,
})
.collect();
Expression::ComponentReference(ComponentReference {
local: false,
parts,
})
}
#[test]
fn test_resolve_component_reference_with_import_alias() {
// Create a resolver with an import alias: L = Modelica.Logic
let mut resolver = ImportResolver {
name_map: IndexMap::new(),
};
resolver
.name_map
.insert("L".to_string(), "Modelica.Logic".to_string());
// Test that L.'U' becomes Modelica.Logic.'U'
let mut expr = make_comp_ref("L.'U'");
expr.accept_mut(&mut resolver);
if let Expression::ComponentReference(comp_ref) = &expr {
let resolved = comp_ref.to_string();
assert_eq!(resolved, "Modelica.Logic.'U'");
} else {
panic!("Expected ComponentReference expression");
}
}
#[test]
fn test_resolve_component_reference_no_alias() {
// Create a resolver with an unrelated import alias
let mut resolver = ImportResolver {
name_map: IndexMap::new(),
};
resolver
.name_map
.insert("X".to_string(), "Modelica.Other".to_string());
// Test that L.'U' stays unchanged (no alias for L)
let mut expr = make_comp_ref("L.'U'");
expr.accept_mut(&mut resolver);
if let Expression::ComponentReference(comp_ref) = &expr {
let resolved = comp_ref.to_string();
assert_eq!(resolved, "L.'U'");
} else {
panic!("Expected ComponentReference expression");
}
}
#[test]
fn test_find_class_by_path() {
// Create a simple stored definition with nested packages
let mut stored_def = StoredDefinition::default();
let mut math_package = ClassDefinition::default();
math_package.name.text = "MathLib".to_string();
let mut add_func = ClassDefinition::default();
add_func.name.text = "add".to_string();
math_package.classes.insert("add".to_string(), add_func);
stored_def
.class_list
.insert("MathLib".to_string(), math_package);
// Test finding MathLib
let found = find_class_by_path(&stored_def, "MathLib");
assert!(found.is_some());
assert_eq!(found.unwrap().name.text, "MathLib");
// Test finding MathLib.add
let found = find_class_by_path(&stored_def, "MathLib.add");
assert!(found.is_some());
assert_eq!(found.unwrap().name.text, "add");
// Test not finding non-existent path
let found = find_class_by_path(&stored_def, "NonExistent");
assert!(found.is_none());
}
}