1use crate::modules::ModuleRef;
6use seq_map::SeqMap;
7use source_map_node::Node;
8use std::fmt::Debug;
9use std::rc::Rc;
10use swamp_refs::ModuleSymbolReferences;
11use swamp_semantic::prelude::*;
12use swamp_symbol::TopLevelSymbolId;
13use swamp_types::prelude::*;
14use swamp_types::TypeRef;
15
16#[derive(Debug, Clone)]
17pub enum FuncDef {
18 Internal(InternalFunctionDefinitionRef),
19 Intrinsic(IntrinsicFunctionDefinitionRef),
20 External(ExternalFunctionDefinitionRef),
21}
22
23impl FuncDef {
24 #[must_use] pub fn symbol_id(&self) -> TopLevelSymbolId {
25 match self {
26 Self::Internal(internal) => {
27 internal.symbol_id
28 }
29 Self::Intrinsic(_) => { TopLevelSymbolId::new_illegal() }
30 Self::External(_) => { TopLevelSymbolId::new_illegal() }
31 }
32 }
33}
34
35impl FuncDef {
36 #[must_use]
37 pub fn signature(&self) -> &Signature {
38 match self {
39 Self::Internal(internal) => &internal.signature,
40 Self::Intrinsic(intrinsic_fn) => &intrinsic_fn.signature,
41 Self::External(host_fn) => &host_fn.signature,
42 }
43 }
44}
45
46#[derive(Clone, Eq, PartialEq, Debug)]
47pub struct TypeParameterName {
48 pub resolved_node: Node,
49 pub assigned_name: String,
50}
51
52#[derive(Debug)]
53pub struct TypeParameter {
54 pub ty: TypeRef,
55 pub debug_name: String,
56}
57
58#[derive(Clone, Debug)]
59pub struct AliasType {
60 pub symbol_id: TopLevelSymbolId,
61 pub name: Node,
62 pub assigned_name: String,
63 pub ty: TypeRef,
64}
65
66#[derive(Clone, Debug)]
67pub enum ModuleDefinitionKind {
68 Type(TopLevelSymbolId, TypeRef),
69 Module(ModuleRef),
70 Constant(ConstantRef),
71 FunctionDefinition(FuncDef),
72 Alias(AliasType),
73}
74
75
76impl ModuleDefinitionKind {
77 #[must_use]
78 pub const fn is_basic_type(&self) -> bool {
79 matches!(
80 self,
81 Self::Type(..) | Self::Alias(..) | Self::FunctionDefinition(..)
82 )
83 }
84
85 #[must_use]
86 pub const fn is_alias_type(&self) -> bool {
87 matches!(self, Self::Alias(..))
88 }
89
90 pub(crate) const fn is_function(&self) -> bool {
91 matches!(self, Self::FunctionDefinition(..))
92 }
93}
94
95#[derive(Debug, Clone)]
96pub struct ModuleDefinition {
97 pub kind: ModuleDefinitionKind,
98 pub range: Node,
99 pub name: Node,
100}
101
102impl ModuleDefinition {
103 #[must_use]
104 pub const fn is_basic_type(&self) -> bool {
105 self.kind.is_basic_type()
106 }
107
108 #[must_use]
109 pub const fn is_alias_type(&self) -> bool {
110 self.kind.is_alias_type()
111 }
112
113 pub(crate) const fn is_function(&self) -> bool {
114 self.kind.is_function()
115 }
116}
117
118#[derive(Debug, Clone)]
119pub struct DefinitionTable {
120 definitions: SeqMap<String, ModuleDefinition>,
121 pub refs: ModuleSymbolReferences,
122 module_path: Vec<String>,
123}
124
125impl DefinitionTable {
126 #[must_use]
127 pub fn internal_functions(&self) -> Vec<InternalFunctionDefinitionRef> {
128 let mut v = Vec::new();
129
130 for (_name, sym) in &self.definitions {
131 if let ModuleDefinitionKind::FunctionDefinition(func_def) = &sym.kind
132 && let FuncDef::Internal(internal) = func_def
133 {
134 v.push(internal.clone());
135 }
136 }
137
138 v
139 }
140}
141
142impl DefinitionTable {
143 #[must_use]
144 pub fn module_path(&self) -> Vec<String> {
145 self.module_path.clone()
146 }
147}
148
149pub type SymbolTableRef = Rc<DefinitionTable>;
150
151impl DefinitionTable {
152 #[must_use]
153 pub fn new(module_path: &[String]) -> Self {
154 Self {
155 refs: ModuleSymbolReferences::new(),
156 definitions: SeqMap::default(),
157 module_path: module_path.to_vec(),
158 }
159 }
160
161 #[must_use]
162 pub fn is_empty(&self) -> bool {
163 self.definitions.is_empty()
164 }
165
166 #[must_use]
167 pub const fn definitions(&self) -> &SeqMap<String, ModuleDefinition> {
168 &self.definitions
169 }
170
171 #[must_use]
172 pub fn structs(&self) -> SeqMap<String, NamedStructType> {
173 let mut structs = SeqMap::new();
174
175 for (name, symbol) in &self.definitions {
176 if let ModuleDefinitionKind::Type(_, ty) = &symbol.kind
177 && let TypeKind::NamedStruct(struct_ref) = &*ty.kind
178 {
179 structs
180 .insert(name.to_string(), struct_ref.clone())
181 .unwrap();
182 }
183 }
184
185 structs
186 }
187
188 #[must_use]
189 pub fn enums(&self) -> SeqMap<String, EnumType> {
190 let mut enums = SeqMap::new();
191
192 for (name, symbol) in &self.definitions {
193 if let ModuleDefinitionKind::Type(_, ty) = &symbol.kind
194 && let TypeKind::Enum(enum_type) = &*ty.kind
195 {
196 enums.insert(name.to_string(), enum_type.clone()).unwrap();
197 }
198 }
199
200 enums
201 }
202
203 pub fn extend_from(&mut self, symbol_table: &Self) -> Result<(), SemanticError> {
206 for (name, symbol) in symbol_table.definitions() {
207 self.add_symbol(name, symbol.clone())?;
208 }
209 Ok(())
210 }
211
212 pub fn extend_basic_from(&mut self, symbol_table: &Self) -> Result<(), SemanticError> {
215 for (name, symbol) in symbol_table.definitions() {
216 if symbol.is_basic_type() {
217 self.add_symbol(name, symbol.clone())?;
218 }
219 }
220 Ok(())
221 }
222
223 pub fn extend_alias_from(&mut self, symbol_table: &Self) -> Result<(), SemanticError> {
226 for (name, symbol) in symbol_table.definitions() {
227 if symbol.is_alias_type() || symbol.is_function() {
228 self.add_symbol(name, symbol.clone())?;
229 }
230 }
231 Ok(())
232 }
233
234 pub fn extend_intrinsic_functions_from(
235 &mut self,
236 symbol_table: &Self,
237 ) -> Result<(), SemanticError> {
238 for (name, symbol) in symbol_table.definitions() {
239 if let ModuleDefinitionKind::FunctionDefinition(func_def) = &symbol.kind
240 && let FuncDef::Intrinsic(_intrinsic_def) = func_def
241 {
242 self.add_symbol(name, symbol.clone())?;
243 }
244 }
245 Ok(())
246 }
247
248
249 pub fn add_constant(&mut self, constant: Constant) -> Result<ConstantRef, SemanticError> {
252 let constant_ref = Rc::new(constant);
253
254 self.add_constant_link(constant_ref.clone())?;
255
256 Ok(constant_ref)
257 }
258
259 pub fn add_constant_link(&mut self, constant_ref: ConstantRef) -> Result<(), SemanticError> {
262 self.insert(&constant_ref.assigned_name, &constant_ref.name, &constant_ref.name, ModuleDefinitionKind::Constant(constant_ref.clone()))
263 }
264
265 pub fn insert(&mut self, name: &str, name_node: &Node, range: &Node, kind: ModuleDefinitionKind) -> Result<(), SemanticError> {
266 let mod_def = ModuleDefinition {
267 kind,
268 range: range.clone(),
269 name: name_node.clone(),
270 };
271
272 self.definitions
273 .insert(name.to_string(), mod_def)
274 .map_err(|_| SemanticError::DuplicateDefinition(name.to_string()))
275 }
276
277 pub fn add_alias(&mut self, alias_type: AliasType) -> Result<AliasType, SemanticError> {
280 self.add_alias_link(alias_type.clone())?;
281 Ok(alias_type)
282 }
283
284 pub fn add_alias_link(&mut self, alias_type_ref: AliasType) -> Result<(), SemanticError> {
287 self.insert(&alias_type_ref.assigned_name, &alias_type_ref.name, &alias_type_ref.name, ModuleDefinitionKind::Alias(alias_type_ref.clone()))
288 }
289
290 pub fn add_internal_function(
291 &mut self,
292 name: &str,
293 function: InternalFunctionDefinition,
294 ) -> Result<InternalFunctionDefinitionRef, SemanticError> {
295 let function_ref = Rc::new(function);
296
297 self.insert(&function_ref.assigned_name, &function_ref.name.0, &function_ref.name.0, ModuleDefinitionKind::FunctionDefinition(FuncDef::Internal(function_ref.clone())))?;
298
299 Ok(function_ref)
300 }
301
302 pub fn add_internal_function_link(
303 &mut self,
304 name: &str,
305 function_ref: InternalFunctionDefinitionRef,
306 ) -> Result<(), SemanticError> {
307 self.insert(&function_ref.assigned_name, &function_ref.name.0, &function_ref.name.0, ModuleDefinitionKind::FunctionDefinition(FuncDef::Internal(function_ref.clone())))
308 }
309
310 #[must_use]
311 pub fn get_symbol(&self, name: &str) -> Option<&ModuleDefinition> {
312 self.definitions.get(&name.to_string())
313 }
314
315 pub fn add_symbol(&mut self, name: &str, symbol: ModuleDefinition) -> Result<(), SemanticError> {
316 self.definitions
317 .insert(name.to_string(), symbol)
318 .map_err(|_| SemanticError::DuplicateSymbolName(name.to_string()))
319 }
320
321 #[must_use]
322 pub fn get_type(&self, name: &str) -> Option<&TypeRef> {
323 if let ModuleDefinitionKind::Type(_, type_ref) = &self.get_symbol(name)?.kind {
324 Some(type_ref)
325 } else {
326 None
327 }
328 }
329
330 #[must_use]
331 pub fn get_struct(&self, name: &str) -> Option<&TypeRef> {
332 self.get_type(name)
333 }
334
335 #[must_use]
336 pub fn get_enum(&self, name: &str) -> Option<&TypeRef> {
337 self.get_type(name)
338 }
339
340 #[must_use]
341 pub fn get_enum_variant_type(
342 &self,
343 enum_type_name: &str,
344 variant_name: &str,
345 ) -> Option<EnumVariantType> {
346 self.get_enum(enum_type_name).as_ref().map_or_else(
347 || None,
348 |found_type| {
349 if let TypeKind::Enum(found_enum) = &*found_type.kind {
350 found_enum.variants.get(&variant_name.to_string()).cloned()
351 } else {
352 panic!("internal error: expected enum type")
353 }
354 },
355 )
356 }
357
358 #[must_use]
359 pub fn get_constant(&self, name: &str) -> Option<&ConstantRef> {
360 match &self.get_symbol(name)?.kind {
361 ModuleDefinitionKind::Constant(constant) => Some(constant),
362 _ => None,
363 }
364 }
365
366 #[must_use]
369 pub fn get_function(&self, name: &str) -> Option<&FuncDef> {
370 match &self.get_symbol(name)?.kind {
371 ModuleDefinitionKind::FunctionDefinition(func_def) => Some(func_def),
372 _ => None,
373 }
374 }
375
376 #[must_use]
377 pub fn get_internal_function(&self, name: &str) -> Option<&InternalFunctionDefinitionRef> {
378 match self.get_function(name)? {
379 FuncDef::Internal(internal_fn) => Some(internal_fn),
380 FuncDef::External(_) => None,
381 FuncDef::Intrinsic(_) => None,
382 }
383 }
384
385 #[must_use]
386 pub fn get_intrinsic_function(&self, name: &str) -> Option<&IntrinsicFunctionDefinitionRef> {
387 match self.get_function(name)? {
388 FuncDef::Intrinsic(intrinsic_fn) => Some(intrinsic_fn),
389 _ => None,
390 }
391 }
392
393 #[must_use]
394 pub fn get_external_function_declaration(
395 &self,
396 name: &str,
397 ) -> Option<&ExternalFunctionDefinitionRef> {
398 match self.get_function(name)? {
399 FuncDef::External(external_def) => Some(external_def),
400 _ => None,
401 }
402 }
403
404 fn insert_definition(&mut self, name: &str, symbol: ModuleDefinition) -> Result<(), SemanticError> {
405 self.definitions
406 .insert(name.to_string(), symbol)
407 .map_err(|_| SemanticError::DuplicateSymbolName(name.to_string()))
408 }
409
410 pub fn add_named_type(&mut self, ty: TypeRef) -> Result<(), SemanticError> {
411 let name = match &*ty.kind {
412 TypeKind::NamedStruct(named) => named.assigned_name.clone(),
413 TypeKind::Enum(enum_type) => enum_type.assigned_name.clone(),
414 _ => panic!("not a named type"),
415 };
416
417 let symbol_id = match &*ty.kind {
418 TypeKind::NamedStruct(named) => named.symbol_id,
419 TypeKind::Enum(enum_type) => enum_type.symbol_id,
420 _ => panic!("not a named type"),
421 };
422
423 let name_node = match &*ty.kind {
424 TypeKind::NamedStruct(named) => &named.name,
425 TypeKind::Enum(enum_type) => &enum_type.name,
426 _ => panic!("not a named type"),
427 };
428
429 self.insert(&name, name_node, name_node, ModuleDefinitionKind::Type(symbol_id, ty.clone()))
430 }
431
432 pub fn add_external_function_declaration(
433 &mut self,
434 decl: ExternalFunctionDefinition,
435 ) -> Result<ExternalFunctionDefinitionRef, SemanticError> {
436 let decl_ref = Rc::new(decl);
437
438 self.add_external_function_declaration_link(decl_ref.clone())?;
439
440 Ok(decl_ref)
441 }
442
443 pub fn add_external_function_declaration_link(
444 &mut self,
445 decl_ref: ExternalFunctionDefinitionRef,
446 ) -> Result<(), SemanticError> {
447 self.insert(
448 &decl_ref.assigned_name,
449 &decl_ref.name,
450 &decl_ref.name,
451 ModuleDefinitionKind::FunctionDefinition(FuncDef::External(decl_ref.clone())),
452 )
453 .map_err(|_| {
454 SemanticError::DuplicateExternalFunction(decl_ref.assigned_name.to_string())
455 })?;
456 Ok(())
457 }
458
459 pub fn add_module_link(&mut self, name: &str, name_node: &Node, ns: ModuleRef) -> Result<(), SemanticError> {
460 self.insert(name, name_node, name_node, ModuleDefinitionKind::Module(ns))
461 }
462
463 #[must_use]
464 pub fn get_module_link(&self, name: &str) -> Option<&ModuleRef> {
465 match &self.get_symbol(name)?.kind {
466 ModuleDefinitionKind::Module(module_ref) => Some(module_ref),
467 _ => None,
468 }
469 }
470
471
472 pub fn add_intrinsic_function(
473 &mut self,
474 function: IntrinsicFunctionDefinition,
475 ) -> Result<IntrinsicFunctionDefinitionRef, SemanticError> {
476 let function_ref = Rc::new(function);
477 let fake_node = Node::new_unknown();
478 self.insert(
479 &function_ref.name,
480 &fake_node,
481 &fake_node,
482 ModuleDefinitionKind::FunctionDefinition(FuncDef::Intrinsic(function_ref.clone())),
483 )
484 .expect("todo: add seqmap error handling");
485
486 Ok(function_ref)
487 }
488}