swamp_modules/
symtbl.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/swamp
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5use crate::modules::ModuleRef;
6use seq_map::SeqMap;
7use source_map_node::Node;
8use std::fmt::Debug;
9use std::rc::Rc;
10use swamp_semantic::prelude::*;
11use swamp_types::ParameterizedTypeBlueprint;
12use swamp_types::prelude::*;
13use tiny_ver::TinyVersion;
14
15#[derive(Debug, Clone)]
16pub enum FuncDef {
17    Internal(InternalFunctionDefinitionRef),
18    Intrinsic(IntrinsicFunctionDefinitionRef),
19    External(ExternalFunctionDefinitionRef),
20}
21
22#[derive(Clone, Eq, PartialEq, Debug)]
23pub struct TypeParameterName {
24    pub resolved_node: Node,
25    pub assigned_name: String,
26}
27
28#[derive(Debug)]
29pub struct TypeParameter {
30    pub ty: Type,
31    pub debug_name: String,
32}
33
34#[derive(Clone, Debug)]
35pub enum TypeGeneratorKind {
36    Slice,
37    SlicePair,
38}
39
40#[derive(Clone, Debug)]
41pub struct TypeGenerator {
42    pub arity: usize,
43    pub kind: TypeGeneratorKind,
44}
45
46#[derive(Clone, Debug)]
47pub enum Symbol {
48    Type(Type),
49    Module(ModuleRef),
50    PackageVersion(TinyVersion),
51    Constant(ConstantRef),
52    FunctionDefinition(FuncDef),
53    Alias(AliasType),
54    Blueprint(ParameterizedTypeBlueprint),
55    TypeGenerator(TypeGenerator),
56}
57
58impl Symbol {
59    #[must_use]
60    pub const fn is_basic_type(&self) -> bool {
61        matches!(self, Self::Type(..) | Self::Alias(..))
62    }
63
64    pub const fn is_alias_type(&self) -> bool {
65        matches!(self, Self::Alias(..))
66    }
67}
68
69#[derive(Debug, Clone)]
70pub struct SymbolTable {
71    symbols: SeqMap<String, Symbol>,
72    module_path: Vec<String>,
73}
74
75impl SymbolTable {
76    pub fn internal_functions(&self) -> Vec<InternalFunctionDefinitionRef> {
77        let mut v = Vec::new();
78
79        for (_name, sym) in &self.symbols {
80            if let Symbol::FunctionDefinition(func_def) = sym {
81                if let FuncDef::Internal(internal) = func_def {
82                    v.push(internal.clone())
83                }
84            }
85        }
86
87        v
88    }
89}
90
91impl SymbolTable {
92    pub fn module_path(&self) -> Vec<String> {
93        self.module_path.clone()
94    }
95}
96
97pub type SymbolTableRef = Rc<SymbolTable>;
98
99impl SymbolTable {
100    #[must_use]
101    pub fn new(module_path: &[String]) -> Self {
102        Self {
103            symbols: SeqMap::default(),
104            module_path: module_path.to_vec(),
105        }
106    }
107
108    #[must_use]
109    pub fn is_empty(&self) -> bool {
110        self.symbols.is_empty()
111    }
112
113    #[must_use]
114    pub const fn symbols(&self) -> &SeqMap<String, Symbol> {
115        &self.symbols
116    }
117
118    pub fn structs(&self) -> SeqMap<String, NamedStructType> {
119        let mut structs = SeqMap::new();
120
121        for (name, symbol) in &self.symbols {
122            if let Symbol::Type(ty) = symbol {
123                if let Type::NamedStruct(struct_ref) = ty {
124                    structs
125                        .insert(name.to_string(), struct_ref.clone())
126                        .unwrap();
127                }
128            }
129        }
130
131        structs
132    }
133
134    /// # Errors
135    ///
136    pub fn extend_from(&mut self, symbol_table: &Self) -> Result<(), SemanticError> {
137        for (name, symbol) in symbol_table.symbols() {
138            self.add_symbol(name, symbol.clone())?;
139        }
140        Ok(())
141    }
142
143    /// # Errors
144    ///
145    pub fn extend_basic_from(&mut self, symbol_table: &Self) -> Result<(), SemanticError> {
146        for (name, symbol) in symbol_table.symbols() {
147            if symbol.is_basic_type() {
148                self.add_symbol(name, symbol.clone())?;
149            }
150        }
151        Ok(())
152    }
153
154    /// # Errors
155    ///
156    pub fn extend_alias_from(&mut self, symbol_table: &Self) -> Result<(), SemanticError> {
157        for (name, symbol) in symbol_table.symbols() {
158            if symbol.is_alias_type() {
159                self.add_symbol(name, symbol.clone())?;
160            }
161        }
162        Ok(())
163    }
164
165    pub fn extend_intrinsic_functions_from(
166        &mut self,
167        symbol_table: &Self,
168    ) -> Result<(), SemanticError> {
169        for (name, symbol) in symbol_table.symbols() {
170            if let Symbol::FunctionDefinition(func_def) = symbol {
171                if let FuncDef::Intrinsic(_intrinsic_def) = func_def {
172                    self.add_symbol(name, symbol.clone())?;
173                }
174            }
175        }
176        Ok(())
177    }
178
179    #[must_use]
180    pub fn get_package_version(&self, name: &str) -> Option<String> {
181        match self.get_symbol(name)? {
182            Symbol::PackageVersion(name) => Some(name.to_string()),
183            _ => None,
184        }
185    }
186
187    /// # Errors
188    ///
189    pub fn add_constant(&mut self, constant: Constant) -> Result<ConstantRef, SemanticError> {
190        let constant_ref = Rc::new(constant);
191
192        self.add_constant_link(constant_ref.clone())?;
193
194        Ok(constant_ref)
195    }
196
197    /// # Errors
198    ///
199    pub fn add_constant_link(&mut self, constant_ref: ConstantRef) -> Result<(), SemanticError> {
200        let name = constant_ref.assigned_name.clone();
201
202        self.symbols
203            .insert(name.to_string(), Symbol::Constant(constant_ref))
204            .map_err(|_| SemanticError::DuplicateConstName(name.to_string()))?;
205
206        Ok(())
207    }
208
209    /// # Errors
210    ///
211    pub fn add_alias(&mut self, alias_type: AliasType) -> Result<AliasType, SemanticError> {
212        self.add_alias_link(alias_type.clone())?;
213        Ok(alias_type)
214    }
215
216    /// # Errors
217    ///
218    pub fn add_alias_link(&mut self, alias_type_ref: AliasType) -> Result<(), SemanticError> {
219        let name = alias_type_ref.assigned_name.clone();
220        self.symbols
221            .insert(name.clone(), Symbol::Alias(alias_type_ref.clone()))
222            .map_err(|_| SemanticError::DuplicateStructName(name))?;
223
224        Ok(())
225    }
226
227    /// # Errors
228    ///
229    pub fn add_blueprint(
230        &mut self,
231        blueprint: ParameterizedTypeBlueprint,
232    ) -> Result<ParameterizedTypeBlueprint, SemanticError> {
233        self.add_blueprint_link(blueprint.clone())?;
234        Ok(blueprint)
235    }
236
237    /// # Errors
238    ///
239    pub fn add_blueprint_link(
240        &mut self,
241        blueprint_ref: ParameterizedTypeBlueprint,
242    ) -> Result<(), SemanticError> {
243        let name = blueprint_ref.name().clone();
244        self.symbols
245            .insert(name.clone(), Symbol::Blueprint(blueprint_ref))
246            .map_err(|_| SemanticError::DuplicateStructName(name))?;
247        Ok(())
248    }
249
250    #[must_use]
251    pub fn get_blueprint(&self, name: &str) -> Option<&ParameterizedTypeBlueprint> {
252        if let Some(found_symbol) = self.get_symbol(name) {
253            if let Symbol::Blueprint(type_ref) = found_symbol {
254                return Some(type_ref);
255            }
256        }
257
258        None
259    }
260
261    /// # Errors
262    ///
263    pub fn add_type_generator(
264        &mut self,
265        name: &str,
266        type_generator: TypeGenerator,
267    ) -> Result<TypeGenerator, SemanticError> {
268        self.add_type_generator_link(name, type_generator.clone())?;
269        Ok(type_generator)
270    }
271
272    /// # Errors
273    ///
274    pub fn add_type_generator_link(
275        &mut self,
276        name: &str,
277        type_generator: TypeGenerator,
278    ) -> Result<(), SemanticError> {
279        self.symbols
280            .insert(name.to_string(), Symbol::TypeGenerator(type_generator))
281            .map_err(|_| SemanticError::DuplicateStructName(name.to_string()))?;
282        Ok(())
283    }
284
285    #[must_use]
286    pub fn get_type_generator(&self, name: &str) -> Option<&TypeGenerator> {
287        if let Some(found_symbol) = self.get_symbol(name) {
288            if let Symbol::TypeGenerator(type_gen) = found_symbol {
289                return Some(type_gen);
290            }
291        }
292
293        None
294    }
295
296    pub fn add_external_type(
297        &mut self,
298        external: ExternalType,
299    ) -> Result<ExternalType, SemanticError> {
300        self.add_external_type_link(external.clone())?;
301        Ok(external)
302    }
303
304    /// # Errors
305    ///
306    pub fn add_external_type_link(
307        &mut self,
308        external_type_ref: ExternalType,
309    ) -> Result<(), SemanticError> {
310        let name = external_type_ref.type_name.clone();
311        self.symbols
312            .insert(
313                name.clone(),
314                Symbol::Type(Type::External(external_type_ref)),
315            )
316            .map_err(|_| SemanticError::DuplicateStructName(name))?;
317        Ok(())
318    }
319
320    /// # Errors
321    ///
322    pub fn add_struct(
323        &mut self,
324        struct_type: NamedStructType,
325    ) -> Result<NamedStructType, SemanticError> {
326        self.add_struct_link(struct_type.clone())?;
327        Ok(struct_type)
328    }
329
330    /// # Errors
331    ///
332    pub fn add_generated_struct(
333        &mut self,
334        name: &str,
335        fields: &[(&str, Type)],
336    ) -> Result<NamedStructType, SemanticError> {
337        let mut defined_fields = SeqMap::new();
338        for (name, field_type) in fields {
339            defined_fields
340                .insert(
341                    name.to_string(),
342                    StructTypeField {
343                        identifier: None,
344                        field_type: field_type.clone(),
345                    },
346                )
347                .unwrap();
348        }
349
350        let struct_type = NamedStructType {
351            name: Node::default(),
352            assigned_name: name.to_string(),
353            anon_struct_type: AnonymousStructType::new(defined_fields),
354            module_path: self.module_path.clone(),
355            instantiated_type_parameters: Vec::default(),
356            blueprint_info: None,
357        };
358
359        self.add_struct_link(struct_type.clone())?;
360
361        Ok(struct_type)
362    }
363
364    /// # Errors
365    ///
366    pub fn add_struct_link(
367        &mut self,
368        struct_type_ref: NamedStructType,
369    ) -> Result<(), SemanticError> {
370        let name = struct_type_ref.assigned_name.clone();
371        self.symbols
372            .insert(
373                name.clone(),
374                Symbol::Type(Type::NamedStruct(struct_type_ref)),
375            )
376            .map_err(|_| SemanticError::DuplicateStructName(name))?;
377        Ok(())
378    }
379
380    pub fn add_enum_type(&mut self, enum_type: EnumType) -> Result<(), SemanticError> {
381        self.add_enum_type_link(enum_type.clone())?;
382        Ok(())
383    }
384
385    pub fn add_enum_type_link(&mut self, enum_type_ref: EnumType) -> Result<(), SemanticError> {
386        let ty = Type::Enum(enum_type_ref.clone());
387        self.symbols
388            .insert(enum_type_ref.assigned_name.clone(), Symbol::Type(ty))
389            .map_err(|_| SemanticError::DuplicateEnumType(enum_type_ref.assigned_name.clone()))?;
390
391        Ok(())
392    }
393
394    pub fn add_internal_function(
395        &mut self,
396        name: &str,
397        function: InternalFunctionDefinition,
398    ) -> Result<InternalFunctionDefinitionRef, SemanticError> {
399        let function_ref = Rc::new(function);
400        self.symbols
401            .insert(
402                name.to_string(),
403                Symbol::FunctionDefinition(FuncDef::Internal(function_ref.clone())),
404            )
405            .expect("todo: add seqmap error handling");
406        Ok(function_ref)
407    }
408
409    pub fn add_internal_function_link(
410        &mut self,
411        name: &str,
412        function_ref: InternalFunctionDefinitionRef,
413    ) -> Result<(), SemanticError> {
414        self.symbols
415            .insert(
416                name.to_string(),
417                Symbol::FunctionDefinition(FuncDef::Internal(function_ref.clone())),
418            )
419            .expect("todo: add seqmap error handling");
420        Ok(())
421    }
422
423    pub fn get_symbol(&self, name: &str) -> Option<&Symbol> {
424        self.symbols.get(&name.to_string())
425    }
426
427    pub fn add_symbol(&mut self, name: &str, symbol: Symbol) -> Result<(), SemanticError> {
428        self.symbols
429            .insert(name.to_string(), symbol)
430            .map_err(|_| SemanticError::DuplicateSymbolName(name.to_string()))
431    }
432
433    pub fn get_type(&self, name: &str) -> Option<&Type> {
434        if let Some(found_symbol) = self.get_symbol(name) {
435            if let Symbol::Type(type_ref) = found_symbol {
436                return Some(type_ref);
437            }
438        }
439
440        None
441    }
442
443    pub fn get_struct(&self, name: &str) -> Option<&NamedStructType> {
444        match self.get_type(name)? {
445            Type::NamedStruct(struct_ref) => Some(struct_ref),
446            _ => None,
447        }
448    }
449
450    pub fn get_enum(&self, name: &str) -> Option<&EnumType> {
451        match self.get_type(name)? {
452            Type::Enum(enum_type) => Some(enum_type),
453            _ => None,
454        }
455    }
456
457    #[must_use]
458    pub fn get_enum_variant_type(
459        &self,
460        enum_type_name: &str,
461        variant_name: &str,
462    ) -> Option<EnumVariantType> {
463        self.get_enum(enum_type_name).as_ref().map_or_else(
464            || None,
465            |found_enum| found_enum.variants.get(&variant_name.to_string()).cloned(),
466        )
467    }
468
469    pub fn get_constant(&self, name: &str) -> Option<&ConstantRef> {
470        match self.get_symbol(name)? {
471            Symbol::Constant(constant) => Some(constant),
472            _ => None,
473        }
474    }
475
476    // Functions
477
478    #[must_use]
479    pub fn get_function(&self, name: &str) -> Option<&FuncDef> {
480        match self.get_symbol(name)? {
481            Symbol::FunctionDefinition(func_def) => Some(func_def),
482            _ => None,
483        }
484    }
485
486    #[must_use]
487    pub fn get_internal_function(&self, name: &str) -> Option<&InternalFunctionDefinitionRef> {
488        match self.get_function(name)? {
489            FuncDef::Internal(internal_fn) => Some(internal_fn),
490            FuncDef::External(_) => None,
491            FuncDef::Intrinsic(_) => None,
492        }
493    }
494
495    #[must_use]
496    pub fn get_intrinsic_function(&self, name: &str) -> Option<&IntrinsicFunctionDefinitionRef> {
497        match self.get_function(name)? {
498            FuncDef::Intrinsic(intrinsic_fn) => Some(intrinsic_fn),
499            _ => None,
500        }
501    }
502
503    #[must_use]
504    pub fn get_external_function_declaration(
505        &self,
506        name: &str,
507    ) -> Option<&ExternalFunctionDefinitionRef> {
508        match self.get_function(name)? {
509            FuncDef::External(external_def) => Some(external_def),
510            _ => None,
511        }
512    }
513
514    pub fn get_external_type(&self, name: &str) -> Option<&ExternalType> {
515        match self.get_type(name)? {
516            Type::External(ext_type) => Some(ext_type),
517            _ => None,
518        }
519    }
520
521    fn insert_symbol(&mut self, name: &str, symbol: Symbol) -> Result<(), SemanticError> {
522        self.symbols
523            .insert(name.to_string(), symbol)
524            .map_err(|_| SemanticError::DuplicateSymbolName(name.to_string()))
525    }
526
527    pub fn add_external_function_declaration(
528        &mut self,
529        decl: ExternalFunctionDefinition,
530    ) -> Result<ExternalFunctionDefinitionRef, SemanticError> {
531        let decl_ref = Rc::new(decl);
532
533        self.add_external_function_declaration_link(decl_ref.clone())?;
534
535        Ok(decl_ref)
536    }
537
538    pub fn add_external_function_declaration_link(
539        &mut self,
540        decl_ref: ExternalFunctionDefinitionRef,
541    ) -> Result<(), SemanticError> {
542        self.insert_symbol(
543            &decl_ref.assigned_name,
544            Symbol::FunctionDefinition(FuncDef::External(decl_ref.clone())),
545        )
546        .map_err(|_| {
547            SemanticError::DuplicateExternalFunction(decl_ref.assigned_name.to_string())
548        })?;
549        Ok(())
550    }
551
552    pub fn add_module_link(&mut self, name: &str, ns: ModuleRef) -> Result<(), SemanticError> {
553        self.insert_symbol(name, Symbol::Module(ns))
554            .map_err(|_| SemanticError::DuplicateNamespaceLink(name.to_string()))?;
555        Ok(())
556    }
557
558    #[must_use]
559    pub fn get_module_link(&self, name: &str) -> Option<&ModuleRef> {
560        match self.get_symbol(name)? {
561            Symbol::Module(module_ref) => Some(module_ref),
562            _ => None,
563        }
564    }
565
566    pub fn add_package_version(
567        &mut self,
568        name: &str,
569        version: TinyVersion,
570    ) -> Result<(), SemanticError> {
571        self.insert_symbol(name, Symbol::PackageVersion(version))
572            .map_err(|_| SemanticError::DuplicateNamespaceLink(name.to_string()))?;
573        Ok(())
574    }
575
576    pub fn add_intrinsic_function(
577        &mut self,
578        function: IntrinsicFunctionDefinition,
579    ) -> Result<IntrinsicFunctionDefinitionRef, SemanticError> {
580        let function_ref = Rc::new(function);
581        self.symbols
582            .insert(
583                function_ref.name.clone(),
584                Symbol::FunctionDefinition(FuncDef::Intrinsic(function_ref.clone())),
585            )
586            .expect("todo: add seqmap error handling");
587        Ok(function_ref)
588    }
589}