forge-parser 0.1.21

OpenAPI 3.0 JSON parser producing forge-ir
Documentation
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
403
404
405
406
407
408
409
410
411
//! Schema normalization passes.
//!
//! Currently: eager `allOf` flattening into a single `ObjectType`. Walks
//! every sub-schema, resolves `$ref`s into already-parsed component
//! objects, and merges properties / required / additional-properties /
//! constraints. Conflicts emit `parser/W-ALLOF-CONFLICT`; non-object
//! parts emit `parser/E-COMPOSITION-ALLOF` (Stage 4 keeps allOf scoped to
//! object inheritance).

use forge_ir::{
    AdditionalProperties, NamedType, ObjectConstraints, ObjectType, PatternProperty, Property,
    TypeDef, TypeRef,
};
use indexmap::IndexMap;
use serde_json::Value as J;

use crate::ctx::Ctx;
use crate::diag;
use crate::pointer::Ptr;
use crate::schema::{alloc_id, maybe_wrap_nullable, original_name, parse_schema, NameHint};

#[derive(Debug)]
struct Acc {
    /// Insertion order preserved on first occurrence, even when later parts
    /// re-declare a property.
    properties: IndexMap<String, Property>,
    /// Tracks the union of `required` across parts. Stored as Vec to keep
    /// the original declaration order from sub-parts; deduped on insert.
    required: Vec<String>,
    additional: AdditionalProperties,
    /// `patternProperties` accumulated across parts, keyed by regex.
    /// First-occurrence insertion order; a later part re-declaring the
    /// same regex overwrites the value (and warns on a type conflict),
    /// mirroring how `properties` coalesce.
    pattern_properties: IndexMap<String, PatternProperty>,
    /// `propertyNames` schema. Multiple parts each constrain key names
    /// (logically an AND); the IR can't express that, so we keep the
    /// latest non-conflicting one and warn on a conflict.
    property_names: Option<TypeRef>,
    min_properties: Option<u64>,
    max_properties: Option<u64>,
}

impl Acc {
    fn new() -> Self {
        Self {
            properties: IndexMap::new(),
            required: Vec::new(),
            additional: AdditionalProperties::Any,
            pattern_properties: IndexMap::new(),
            property_names: None,
            min_properties: None,
            max_properties: None,
        }
    }

    fn add_required(&mut self, name: &str) {
        if !self.required.iter().any(|r| r == name) {
            self.required.push(name.to_string());
        }
    }
}

/// Flatten a schema with `allOf` into a single `ObjectType`. Registers the
/// flattened type and returns its id. Sub-parts are walked through the
/// regular schema walker so any inline objects they contain still land in
/// the type pool.
pub(crate) fn parse_all_of(
    ctx: &mut Ctx,
    map: &serde_json::Map<String, J>,
    ptr: &mut Ptr,
    hint: NameHint,
    nullable: bool,
) -> Option<TypeRef> {
    let parts = match map.get("allOf") {
        Some(J::Array(items)) if !items.is_empty() => items.clone(),
        _ => {
            ptr.with_token("allOf", |ptr| {
                ctx.push_diag(diag::err(
                    diag::E_COMPOSITION_ALLOF,
                    "`allOf` must be a non-empty array",
                    ptr.loc(ctx.file),
                ));
            });
            return None;
        }
    };

    let id = alloc_id(ctx, &hint);
    let mut acc = Acc::new();
    let mut got_anything = false;
    // Synthetic "part" container objects we lifted via parse_schema. After
    // merging their fields into the accumulator they're orphaned (no
    // other type points at them), so we drop them from the pool to keep
    // the IR — and downstream TS — clean. Their *property* types stay
    // because the flattened object still references them by id.
    let mut synthetic_parts: Vec<String> = Vec::new();

    ptr.with_token("allOf", |ptr| {
        for (i, sub) in parts.iter().enumerate() {
            ptr.with_index(i, |ptr| {
                if let Some(part_ref) = merge_part(ctx, sub, ptr, &id, i, &mut acc) {
                    got_anything = true;
                    // Only synthesised inline parts ($ref parts return the
                    // component's own id, which we must NOT drop).
                    if part_ref.starts_with(&format!("{id}_allof_part_")) {
                        synthetic_parts.push(part_ref);
                    }
                }
            });
        }
    });

    // If the parent schema also declares its own properties / required at
    // the same level (a common 3.0 idiom for "extend X with these extra
    // fields"), merge them in too.
    merge_inline_object_fields(ctx, map, ptr, &id, &mut acc);

    if !got_anything && acc.properties.is_empty() {
        return None;
    }

    // Materialise per-property `required` from the accumulator's
    // required-name set (issue #110). The same name appears in
    // multiple `allOf` parts coalesces here.
    let mut properties: Vec<Property> = acc.properties.into_values().collect();
    for p in properties.iter_mut() {
        if acc.required.contains(&p.name) {
            p.required = true;
        }
    }
    let obj = ObjectType {
        properties,
        pattern_properties: acc.pattern_properties.into_values().collect(),
        additional_properties: acc.additional,
        property_names: acc.property_names,
        constraints: ObjectConstraints {
            min_properties: acc.min_properties,
            max_properties: acc.max_properties,
        },
    };
    let (read_only, write_only) = crate::schema::read_write_only(map);
    let extensions = crate::operations::collect_extensions(ctx, map, ptr);
    let nt = NamedType {
        id,
        original_name: original_name(&hint),
        title: crate::schema::title(map),
        description: crate::schema::description(map),
        deprecated: crate::schema::deprecated(map),
        read_only,
        write_only,
        external_docs: crate::parse_external_docs(ctx, map.get("externalDocs"), ptr),
        default: crate::parse_default(ctx, map, ptr, "schema"),
        examples: crate::parse_examples(ctx, map, ptr),
        xml: crate::parse_xml(ctx, map, ptr),
        definition: TypeDef::Object(obj),
        extensions,
        location: Some(ptr.loc(ctx.file)),
    };
    let outer_id = maybe_wrap_nullable(ctx, nt, nullable);
    for part in synthetic_parts {
        ctx.types.shift_remove(&part);
    }
    Some(outer_id)
}

/// Returns the part's TypeRef on a successful merge so the caller can drop
/// it from the pool when it's a redundant inline container.
fn merge_part(
    ctx: &mut Ctx,
    sub: &J,
    ptr: &mut Ptr,
    owner_id: &str,
    index: usize,
    acc: &mut Acc,
) -> Option<TypeRef> {
    let role = format!("allof_part_{index}");
    let part_ref = parse_schema(ctx, sub, ptr, NameHint::inline(owner_id, &role))?;
    let nt = ctx.types.get(&part_ref)?.clone();
    let part_obj = match &nt.definition {
        TypeDef::Object(o) => o.clone(),
        _ => {
            ctx.push_diag(diag::err(
                diag::E_COMPOSITION_ALLOF,
                format!(
                    "allOf part {index} resolves to a non-object type (`{part_ref}`); only \
                     object composition is supported"
                ),
                ptr.loc(ctx.file),
            ));
            return None;
        }
    };

    for prop in &part_obj.properties {
        if let Some(existing) = acc.properties.get(&prop.name) {
            if existing.r#type != prop.r#type {
                ctx.push_diag(diag::warn(
                    diag::W_ALLOF_CONFLICT,
                    format!(
                        "allOf merge: property `{}` declared with conflicting types `{}` and `{}`; using the latter",
                        prop.name, existing.r#type, prop.r#type
                    ),
                    ptr.loc(ctx.file),
                ));
            }
        }
        acc.properties.insert(prop.name.clone(), prop.clone());
        // Lifted: if this part's property is required, accumulate it
        // (the per-property `required` flag is materialised at the
        // end of merging).
        if prop.required {
            acc.add_required(&prop.name);
        }
    }
    acc.additional = restrict_additional(acc.additional.clone(), part_obj.additional_properties);
    merge_pattern_properties(ctx, ptr, acc, part_obj.pattern_properties);
    merge_property_names(ctx, ptr, acc, part_obj.property_names);
    if let Some(m) = part_obj.constraints.min_properties {
        acc.min_properties = Some(acc.min_properties.map(|x| x.max(m)).unwrap_or(m));
    }
    if let Some(m) = part_obj.constraints.max_properties {
        acc.max_properties = Some(acc.max_properties.map(|x| x.min(m)).unwrap_or(m));
    }
    Some(part_ref)
}

/// Union `incoming` `patternProperties` into the accumulator. A regex
/// already present with a different value type emits `W-ALLOF-CONFLICT`
/// and the later entry wins (matching `properties` coalescing).
fn merge_pattern_properties(
    ctx: &mut Ctx,
    ptr: &mut Ptr,
    acc: &mut Acc,
    incoming: Vec<PatternProperty>,
) {
    for pp in incoming {
        if let Some(existing) = acc.pattern_properties.get(&pp.pattern) {
            if existing.r#type != pp.r#type {
                ctx.push_diag(diag::warn(
                    diag::W_ALLOF_CONFLICT,
                    format!(
                        "allOf merge: patternProperties `{}` declared with conflicting types `{}` and `{}`; using the latter",
                        pp.pattern, existing.r#type, pp.r#type
                    ),
                    ptr.loc(ctx.file),
                ));
            }
        }
        acc.pattern_properties.insert(pp.pattern.clone(), pp);
    }
}

/// Fold an `incoming` `propertyNames` schema into the accumulator. The
/// IR can't express the AND of two key schemas, so a conflicting second
/// declaration emits `W-ALLOF-CONFLICT` and the later one wins.
fn merge_property_names(ctx: &mut Ctx, ptr: &mut Ptr, acc: &mut Acc, incoming: Option<TypeRef>) {
    let Some(t) = incoming else { return };
    match &acc.property_names {
        Some(existing) if *existing != t => {
            ctx.push_diag(diag::warn(
                diag::W_ALLOF_CONFLICT,
                format!(
                    "allOf merge: propertyNames declared with conflicting schemas `{existing}` and `{t}`; using the latter"
                ),
                ptr.loc(ctx.file),
            ));
        }
        _ => {}
    }
    acc.property_names = Some(t);
}

/// If the parent schema has sibling `properties`/`required`/etc at the same
/// level as `allOf`, merge them in. We do this by walking those fields
/// directly (rather than synthesizing another inline object) so we don't
/// pollute the type pool with a redundant `_self` part.
fn merge_inline_object_fields(
    ctx: &mut Ctx,
    map: &serde_json::Map<String, J>,
    ptr: &mut Ptr,
    owner_id: &str,
    acc: &mut Acc,
) {
    if let Some(J::Object(props)) = map.get("properties") {
        ptr.with_token("properties", |ptr| {
            for (name, schema) in props {
                ptr.with_token(name, |ptr| {
                    let role = format!("property_{}", crate::sanitize::ident(name));
                    if let Some(t) =
                        parse_schema(ctx, schema, ptr, NameHint::inline(owner_id, &role))
                    {
                        let (
                            prop_title,
                            prop_desc,
                            prop_dep,
                            prop_ro,
                            prop_wo,
                            prop_extdocs,
                            prop_default,
                            prop_examples,
                        ) = match schema {
                            J::Object(m) => (
                                crate::schema::title(m),
                                crate::schema::description(m),
                                crate::schema::deprecated(m),
                                m.get("readOnly").and_then(J::as_bool).unwrap_or(false),
                                m.get("writeOnly").and_then(J::as_bool).unwrap_or(false),
                                crate::parse_external_docs(ctx, m.get("externalDocs"), ptr),
                                crate::parse_default(ctx, m, ptr, "property"),
                                crate::parse_examples(ctx, m, ptr),
                            ),
                            _ => (None, None, false, false, false, None, None, vec![]),
                        };
                        if let Some(existing) = acc.properties.get(name) {
                            if existing.r#type != t {
                                ctx.push_diag(diag::warn(
                                    diag::W_ALLOF_CONFLICT,
                                    format!(
                                        "allOf merge: property `{}` declared with conflicting types `{}` and `{}`; using the latter",
                                        name, existing.r#type, t
                                    ),
                                    ptr.loc(ctx.file),
                                ));
                            }
                        }
                        let extensions = match schema {
                            J::Object(m) => crate::operations::collect_extensions(ctx, m, ptr),
                            _ => Vec::new(),
                        };
                        acc.properties.insert(
                            name.clone(),
                            Property {
                                name: name.clone(),
                                r#type: t,
                                required: false, // patched from acc.required at merge end
                                title: prop_title,
                                description: prop_desc,
                                deprecated: prop_dep,
                                read_only: prop_ro,
                                write_only: prop_wo,
                                external_docs: prop_extdocs,
                                default: prop_default,
                                examples: prop_examples,
                                extensions,
                            },
                        );
                    }
                });
            }
        });
    }
    if let Some(J::Array(items)) = map.get("required") {
        for v in items {
            if let Some(s) = v.as_str() {
                acc.add_required(s);
            }
        }
    }
    if let Some(m) = map.get("minProperties").and_then(J::as_u64) {
        acc.min_properties = Some(acc.min_properties.map(|x| x.max(m)).unwrap_or(m));
    }
    if let Some(m) = map.get("maxProperties").and_then(J::as_u64) {
        acc.max_properties = Some(acc.max_properties.map(|x| x.min(m)).unwrap_or(m));
    }
    match map.get("additionalProperties") {
        Some(J::Bool(false)) => {
            acc.additional =
                restrict_additional(acc.additional.clone(), AdditionalProperties::Forbidden);
        }
        Some(J::Bool(true)) | None => {}
        Some(J::Object(_)) => {
            if let Some(t) = ptr.with_token("additionalProperties", |ptr| {
                parse_schema(
                    ctx,
                    map.get("additionalProperties").unwrap(),
                    ptr,
                    NameHint::inline(owner_id, "additional_properties"),
                )
            }) {
                acc.additional = restrict_additional(
                    acc.additional.clone(),
                    AdditionalProperties::Typed { r#type: t },
                );
            }
        }
        Some(_) => {}
    }
    let pattern_properties = crate::schema::parse_pattern_properties(ctx, map, ptr, owner_id);
    merge_pattern_properties(ctx, ptr, acc, pattern_properties);
    let property_names = crate::schema::parse_property_names(ctx, map, ptr, owner_id);
    merge_property_names(ctx, ptr, acc, property_names);
}

/// Most-restrictive merge: `Forbidden` > `Typed` > `Any`. Two `Typed` with
/// different element types is a conflict and we keep the first (warning).
fn restrict_additional(a: AdditionalProperties, b: AdditionalProperties) -> AdditionalProperties {
    use AdditionalProperties as A;
    match (a, b) {
        (A::Forbidden, _) | (_, A::Forbidden) => A::Forbidden,
        (A::Typed { r#type: t }, A::Any) | (A::Any, A::Typed { r#type: t }) => {
            A::Typed { r#type: t }
        }
        // Two `Typed` parts: we keep the first regardless. Different
        // element types are a structural conflict, but property-level
        // merging surfaces the same condition via `W-ALLOF-CONFLICT`
        // already, so we don't double-emit at this layer.
        (A::Typed { r#type: a_t }, A::Typed { .. }) => A::Typed { r#type: a_t },
        (A::Any, A::Any) => A::Any,
    }
}