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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
//! This Source Code Form is subject to the terms of the Mozilla Public
//! License, v. 2.0. If a copy of the MPL was not distributed with this file,
//! You can obtain one at http://mozilla.org/MPL/2.0/.
//!
//! Copyright (c) 2023, Olof Kraigher olof.kraigher@gmail.com

use pinned_vec::PinnedVec;
use std::cell::RefCell;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;

use fnv::FnvHashMap;
use vhdl_lang::{Source, TokenSpan};

use crate::ast::Designator;
use crate::Diagnostic;
use crate::SrcPos;

use super::AnyEnt;
use super::AnyEntKind;
use super::AttributeEnt;
use super::EntRef;
use super::Related;
use super::TypeEnt;

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct ArenaId(u32);

// Reserve 0 for standard package
static ACOUNTER: AtomicU32 = AtomicU32::new(1);

impl Default for ArenaId {
    fn default() -> Self {
        ArenaId(ACOUNTER.fetch_add(1, Ordering::Relaxed))
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct LocalId(u32);

/// Arena allocators used to store named entities

/// Local arena used for single design unit in a separate thread
struct LocalArena {
    pub id: ArenaId,
    items: PinnedVec<AnyEnt<'static>>,
}

impl LocalArena {
    pub fn new(id: ArenaId) -> Self {
        Self {
            id,
            items: PinnedVec::new(),
        }
    }

    unsafe fn alloc(&mut self, mut ent: AnyEnt) -> *const AnyEnt<'static> {
        let idx = self.items.len();

        if idx > u32::MAX as usize {
            panic!("Entity index overflow");
        }

        let ent_id = EntityId::new_arena(self.id, LocalId(idx as u32));
        ent.id = ent_id;
        self.items.push(std::mem::transmute(ent));
        self.get(ent_id.local_id())
    }

    unsafe fn get(&self, id: LocalId) -> *const AnyEnt<'static> {
        self.panic_on_missing(id);

        let item = self.items.get(id.0 as usize).unwrap();
        std::pin::Pin::into_inner(item) as *const AnyEnt
    }

    unsafe fn get_mut(&mut self, id: LocalId) -> *mut AnyEnt {
        self.panic_on_missing(id);
        let item = self.items.get_mut(id.0 as usize).unwrap();
        std::mem::transmute(std::pin::Pin::into_inner(item) as *mut AnyEnt)
    }

    pub fn contains(&self, id: LocalId) -> bool {
        (id.0 as usize) < self.items.len()
    }

    fn panic_on_missing(&self, id: LocalId) {
        if (id.0 as usize) < self.items.len() {
            return;
        }
        eprintln!("Could not find {:?} within arena {:?}", id, self.id);
        eprintln!("Found these entities:");
        for i in 0..self.items.len() {
            let ent = self.items.get(i).unwrap();
            eprintln!(
                "{:?} {:?} {}",
                ent.id().arena_id(),
                ent.id().local_id(),
                ent.describe()
            );
        }
        panic!("Panic on missing id in arena");
    }
}

/// A read-only self-contained arena that only contain self references
#[derive(Clone, Default)]
pub struct FinalArena {
    refs: FnvHashMap<u32, Arc<LocalArena>>,
}

impl<'a> FinalArena {
    pub fn get(&'a self, id: EntityId) -> EntRef<'a> {
        unsafe {
            let ent = self.refs[&id.arena_id().0].get(id.local_id());
            &*ent as &'a AnyEnt
        }
    }

    pub fn is_valid_id(&self, id: EntityId) -> bool {
        self.refs
            .get(&id.arena_id().0)
            .is_some_and(|local_arena| local_arena.contains(id.local_id()))
    }

    pub fn link(&mut self, referenced: &FinalArena) {
        for (id, arena) in referenced.refs.iter() {
            self.refs.entry(*id).or_insert_with(|| arena.clone());
        }
    }

    pub fn clear(&mut self) {
        self.refs.clear();
    }
}

/// A combination of a local mutable arena together with non-local immutable references
/// This arena is used when analyzing a design unit in a single thread
pub struct Arena {
    local: RefCell<LocalArena>,
    refs: RefCell<FinalArena>,
}

impl Arena {
    pub fn new(id: ArenaId) -> Self {
        Self {
            local: RefCell::new(LocalArena::new(id)),
            refs: Default::default(),
        }
    }

    // Pre-defined id to store standard package
    pub fn new_std() -> Self {
        Self {
            local: RefCell::new(LocalArena::new(ArenaId(0))),
            refs: Default::default(),
        }
    }

    pub fn link(&self, referenced: &FinalArena) {
        self.refs.borrow_mut().link(referenced)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn alloc<'a>(
        &'a self,
        designator: Designator,
        parent: Option<EntRef<'a>>,
        related: Related<'a>,
        kind: AnyEntKind<'a>,
        decl_pos: Option<SrcPos>,
        src_span: TokenSpan,
        source: Option<Source>,
    ) -> EntRef<'a> {
        let ent = AnyEnt {
            id: EntityId::undefined(),
            parent,
            related,
            implicits: Default::default(),
            designator,
            kind,
            decl_pos,
            src_span,
            source,
            attrs: Default::default(),
        };

        unsafe {
            let ent = self.local.borrow_mut().alloc(ent);
            &*ent as EntRef<'a>
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) unsafe fn update<'a>(
        &'a self,
        id: EntityId,
        designator: Designator,
        parent: Option<EntRef<'a>>,
        related: Related<'a>,
        kind: AnyEntKind<'a>,
        decl_pos: Option<SrcPos>,
        src_span: TokenSpan,
        source: Option<Source>,
    ) -> EntRef<'a> {
        unsafe {
            let local = self.local.borrow_mut();
            assert_eq!(id.arena_id(), local.id);
            let p = &mut *self.local.as_ptr() as &mut LocalArena;
            let eref = p.get_mut(id.local_id());
            *eref = AnyEnt {
                id,
                parent,
                related,
                implicits: Vec::new(),
                designator,
                kind,
                decl_pos,
                src_span,
                source,
                attrs: Default::default(),
            };
            &*eref as EntRef<'a>
        }
    }

    pub(crate) unsafe fn add_implicit<'a>(&'a self, id: EntityId, ent: EntRef<'a>) {
        let mut local = self.local.borrow_mut();
        assert_eq!(id.arena_id(), local.id);
        let eref = local.get_mut(id.local_id());
        unsafe {
            let eref: &mut AnyEnt = &mut *eref as &mut AnyEnt;
            eref.add_implicit(ent);
        }
    }

    pub(crate) unsafe fn add_attr<'a>(
        &'a self,
        id: EntityId,
        pos: &SrcPos,
        ent: AttributeEnt<'a>,
    ) -> Result<(), Diagnostic> {
        let mut local = self.local.borrow_mut();
        assert_eq!(id.arena_id(), local.id);
        let eref = local.get_mut(id.local_id());
        unsafe {
            let eref: &mut AnyEnt = &mut *eref as &mut AnyEnt;
            eref.add_attribute(ent, pos)
        }
    }

    pub fn get<'a>(&'a self, id: EntityId) -> EntRef<'a> {
        // Since local uses PinnedVec we do not have to worry about
        // returning a pure reference here since allocating new
        // references do not move address
        //
        // @TODO care must be taken to use get_mut though
        unsafe {
            let p = &*self.local.as_ptr() as &LocalArena;
            if p.id == id.arena_id() {
                // Try local first
                let ent = p.get(id.local_id());
                return &*ent as &'a AnyEnt;
            }
        }

        // Address of referenced entities will not move
        // When adding more referenced arenas since
        // they are behind another pointer to a read only structure
        // in DesignRoot
        unsafe {
            let p = &*self.refs.as_ptr() as &FinalArena;
            let ent = p.get(id);
            ent as &'a AnyEnt
        }
    }

    pub fn get_type(&self, id: EntityId) -> TypeEnt {
        TypeEnt::from_any(self.get(id)).unwrap()
    }

    pub fn finalize(self) -> FinalArena {
        let Arena { local, refs } = self;
        let local = local.into_inner();
        let mut refs = refs.into_inner();
        refs.refs.insert(local.id.0, Arc::new(local));
        refs
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct EntityId {
    id: usize,
}

// Using 64-bits we can create 5 * 10**9 ids per second for 100 years before wrapping
static UNDEFINED_ID: usize = usize::MAX;

impl EntityId {
    pub(crate) fn undefined() -> Self {
        EntityId { id: UNDEFINED_ID }
    }

    pub(crate) fn new_arena(arena_id: ArenaId, id: LocalId) -> Self {
        EntityId {
            id: ((arena_id.0 as usize) << u32::BITS) | (id.0 as usize),
        }
    }

    pub fn arena_id(&self) -> ArenaId {
        ArenaId((self.id >> u32::BITS) as u32)
    }

    fn local_id(&self) -> LocalId {
        LocalId((self.id & (u32::MAX as usize)) as u32)
    }

    /// Returns an `EntityId` from a raw `usize` value
    /// for deserialization purposes.
    pub(crate) fn from_raw(id: usize) -> EntityId {
        EntityId { id }
    }

    /// Converts an `EntityId` to a raw `usize` value
    /// for serialization purposes.
    pub fn to_raw(&self) -> usize {
        self.id
    }
}

/// Encode an optional entity id using 8 bytes instead of 16 bytes
pub struct Reference {
    id: AtomicUsize,
}

impl Reference {
    pub fn undefined() -> Self {
        Self {
            id: AtomicUsize::new(UNDEFINED_ID),
        }
    }

    pub fn is_undefined(&self) -> bool {
        self.raw_id() == UNDEFINED_ID
    }

    pub fn is_defined(&self) -> bool {
        !self.is_undefined()
    }

    pub fn get(&self) -> Option<EntityId> {
        let id = self.raw_id();
        if id == UNDEFINED_ID {
            None
        } else {
            Some(EntityId::from_raw(id))
        }
    }

    pub fn expect_defined(&self) -> EntityId {
        self.get().expect("Expected defined reference to EntityId")
    }

    pub fn raw_id(&self) -> usize {
        // We only clear in a single thread so relaxed ordering should be fine
        self.id.load(Ordering::Relaxed)
    }

    pub(crate) fn clear(&self) {
        // We only clear in a single thread so relaxed ordering should be fine
        self.id.store(UNDEFINED_ID, Ordering::Relaxed);
    }

    pub(crate) fn set(&mut self, id: EntityId) {
        // We only clear in a single thread so relaxed ordering should be fine
        self.id.store(id.to_raw(), Ordering::Relaxed);
    }
}

impl PartialEq for Reference {
    fn eq(&self, other: &Self) -> bool {
        self.id.load(Ordering::Relaxed) == other.id.load(Ordering::Relaxed)
    }
}

impl Eq for Reference {}

impl Clone for Reference {
    fn clone(&self) -> Self {
        Self {
            id: self.raw_id().into(),
        }
    }
}

impl std::fmt::Debug for Reference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.get().fmt(f)
    }
}