swamp_modules/
symtbl.rs

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