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
use crate::cache::ModuleCache;
use crate::load::ModuleLoader;
use crate::model::annotations::AnnotationOnlyBody;
use crate::model::check::MaybeIncomplete;
use crate::model::members::TypeReference;
use crate::model::References;
use crate::model::{
    annotations::Annotation,
    check::Validate,
    definitions::HasMembers,
    identifiers::{Identifier, IdentifierReference},
    members::{Cardinality, Member, DEFAULT_CARDINALITY},
    modules::Module,
    Span,
};
use std::{collections::HashSet, fmt::Debug};

use sdml_error::diagnostics::functions::IdentifierCaseConvention;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use tracing::warn;

// ------------------------------------------------------------------------------------------------
// Public Types ❱ Type Definitions ❱ Entities
// ------------------------------------------------------------------------------------------------

/// Corresponds to the grammar rule `entity_def`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct EntityDef {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    span: Option<Span>,
    name: Identifier,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    body: Option<EntityBody>,
}

/// Corresponds to the grammar rule `entity_body`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct EntityBody {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    span: Option<Span>,
    identity: EntityIdentity,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
    annotations: Vec<Annotation>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
    members: Vec<Member>,
}

// TODO make this just Member!

/// Corresponds to the grammar rules `member` and `entity_identity`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct EntityIdentity {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    span: Option<Span>,
    name: Identifier,
    kind: MemberKind,
}

/// Corresponds to the definition component within grammar rule `entity_identity`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct EntityIdentityDef {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    span: Option<Span>,
    target_type: TypeReference,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    body: Option<AnnotationOnlyBody>,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
enum MemberKind {
    PropertyReference(IdentifierReference),
    Definition(EntityIdentityDef),
}

// ------------------------------------------------------------------------------------------------
// Implementations ❱ Type Definitions ❱ Entities
// ------------------------------------------------------------------------------------------------

impl_has_name_for!(EntityDef);

impl_has_optional_body_for!(EntityDef, EntityBody);

impl_has_source_span_for!(EntityDef);

impl_references_for!(EntityDef => delegate optional body);

impl_annotation_builder!(EntityDef, optional body);

impl_maybe_invalid_for!(EntityDef);

impl Validate for EntityDef {
    fn validate(
        &self,
        top: &Module,
        cache: &ModuleCache,
        loader: &impl ModuleLoader,
        check_constraints: bool,
    ) {
        self.name
            .validate(top, loader, Some(IdentifierCaseConvention::TypeDefinition));
        if let Some(body) = &self.body {
            body.validate(top, cache, loader, check_constraints);
        }
    }
}

impl EntityDef {
    // --------------------------------------------------------------------------------------------
    // EntityDef :: Constructors
    // --------------------------------------------------------------------------------------------

    pub const fn new(name: Identifier) -> Self {
        Self {
            span: None,
            name,
            body: None,
        }
    }
}

// ------------------------------------------------------------------------------------------------

impl_has_annotations_for!(EntityBody);

impl_has_members_for!(EntityBody);

impl_has_source_span_for!(EntityBody);

impl_maybe_invalid_for!(EntityBody; over members);

impl Validate for EntityBody {
    fn validate(
        &self,
        top: &Module,
        cache: &ModuleCache,
        loader: &impl ModuleLoader,
        check_constraints: bool,
    ) {
        self.identity
            .validate(top, cache, loader, check_constraints);
        for annotation in &self.annotations {
            annotation.validate(top, cache, loader, check_constraints);
        }
        for member in &self.members {
            member.validate(top, cache, loader, check_constraints);
        }
    }
}

impl References for EntityBody {
    fn referenced_annotations<'a>(&'a self, names: &mut HashSet<&'a IdentifierReference>) {
        self.members().for_each(|m| m.referenced_annotations(names))
    }

    fn referenced_types<'a>(&'a self, names: &mut HashSet<&'a IdentifierReference>) {
        self.members().for_each(|m| m.referenced_types(names))
    }
}

impl EntityBody {
    // --------------------------------------------------------------------------------------------
    // Constructors
    // --------------------------------------------------------------------------------------------

    pub fn new(identity: EntityIdentity) -> Self {
        Self {
            span: None,
            identity,
            annotations: Default::default(),
            members: Default::default(),
        }
    }

    // --------------------------------------------------------------------------------------------
    // Fields
    // --------------------------------------------------------------------------------------------

    get_and_set!(pub identity, set_identity => EntityIdentity);
}

// ------------------------------------------------------------------------------------------------

impl_has_name_for!(EntityIdentity);

impl_has_source_span_for!(EntityIdentity);

impl MaybeIncomplete for EntityIdentity {
    fn is_incomplete(&self, top: &Module, cache: &ModuleCache) -> bool {
        match &self.kind {
            MemberKind::PropertyReference(_) => false,
            MemberKind::Definition(v) => v.is_incomplete(top, cache),
        }
    }
}

impl Validate for EntityIdentity {
    fn validate(
        &self,
        top: &Module,
        cache: &ModuleCache,
        loader: &impl ModuleLoader,
        check_constraints: bool,
    ) {
        match &self.kind {
            MemberKind::PropertyReference(_) => {
                // TODO: check this is a property reference
            }
            MemberKind::Definition(v) => v.validate(top, cache, loader, check_constraints),
        }
    }
}

impl References for EntityIdentity {
    fn referenced_annotations<'a>(&'a self, names: &mut HashSet<&'a IdentifierReference>) {
        match &self.kind {
            MemberKind::PropertyReference(v) => {
                names.insert(v);
            }
            MemberKind::Definition(v) => v.referenced_annotations(names),
        }
    }

    fn referenced_types<'a>(&'a self, names: &mut HashSet<&'a IdentifierReference>) {
        match &self.kind {
            MemberKind::PropertyReference(v) => {
                names.insert(v);
            }
            MemberKind::Definition(v) => v.referenced_types(names),
        }
    }
}

impl EntityIdentity {
    // --------------------------------------------------------------------------------------------
    // Constructors
    // --------------------------------------------------------------------------------------------

    pub fn new_property_reference(role: Identifier, in_property: IdentifierReference) -> Self {
        Self {
            span: None,
            name: role,
            kind: MemberKind::PropertyReference(in_property),
        }
    }

    pub fn new_definition(name: Identifier, definition: EntityIdentityDef) -> Self {
        Self {
            span: None,
            name,
            kind: MemberKind::Definition(definition),
        }
    }

    // --------------------------------------------------------------------------------------------
    // Variants
    // --------------------------------------------------------------------------------------------

    pub fn is_property_reference(&self) -> bool {
        matches!(self.kind, MemberKind::PropertyReference(_))
    }

    pub fn as_property_reference(&self) -> Option<&IdentifierReference> {
        if let MemberKind::PropertyReference(v) = &self.kind {
            Some(v)
        } else {
            None
        }
    }

    pub fn is_definition(&self) -> bool {
        matches!(self.kind, MemberKind::Definition(_))
    }

    pub fn as_definition(&self) -> Option<&EntityIdentityDef> {
        if let MemberKind::Definition(v) = &self.kind {
            Some(v)
        } else {
            None
        }
    }
}

// ------------------------------------------------------------------------------------------------

// No need for an implementation of Cardinality trait.

impl_has_optional_body_for!(EntityIdentityDef);

impl_has_source_span_for!(EntityIdentityDef);

impl_has_type_for!(EntityIdentityDef);

impl References for EntityIdentityDef {
    fn referenced_annotations<'a>(&'a self, names: &mut HashSet<&'a IdentifierReference>) {
        self.body
            .as_ref()
            .map(|b| b.referenced_annotations(names))
            .unwrap_or_default()
    }

    fn referenced_types<'a>(&'a self, names: &mut HashSet<&'a IdentifierReference>) {
        self.target_type.referenced_types(names);
    }
}

impl MaybeIncomplete for EntityIdentityDef {
    fn is_incomplete(&self, top: &Module, cache: &ModuleCache) -> bool {
        self.target_type.is_incomplete(top, cache)
    }
}

impl Validate for EntityIdentityDef {
    fn validate(
        &self,
        _top: &Module,
        _cache: &ModuleCache,
        _loader: &impl ModuleLoader,
        _check_constraints: bool,
    ) {
        warn!("EntityIdentityDef::Validate nope");
    }
}

impl EntityIdentityDef {
    // --------------------------------------------------------------------------------------------
    // Constructors
    // --------------------------------------------------------------------------------------------

    pub fn new<T>(target_type: T) -> Self
    where
        T: Into<TypeReference>,
    {
        Self {
            span: None,
            target_type: target_type.into(),
            body: None,
        }
    }

    pub const fn new_unknown() -> Self {
        Self {
            span: None,
            target_type: TypeReference::Unknown,
            body: None,
        }
    }

    // --------------------------------------------------------------------------------------------
    // Fields
    // --------------------------------------------------------------------------------------------

    pub const fn target_cardinality(&self) -> &Cardinality {
        &DEFAULT_CARDINALITY
    }
}