Skip to main content

factorio_api_gen/
schema.rs

1use serde::Deserialize;
2
3#[derive(Debug, Deserialize)]
4pub struct RuntimeApi {
5    pub application_version: String,
6    pub api_version: u32,
7    pub classes: Vec<Class>,
8    pub events: Vec<Event>,
9    pub defines: Vec<Define>,
10    pub global_objects: Vec<GlobalObject>,
11    #[serde(default)]
12    pub global_functions: Vec<Method>,
13    #[serde(default)]
14    pub concepts: Vec<Concept>,
15}
16
17#[derive(Debug, Deserialize)]
18pub struct Class {
19    pub name: String,
20    #[serde(default)]
21    pub description: String,
22    #[serde(default)]
23    pub r#abstract: bool,
24    #[serde(default)]
25    pub parent: Option<String>,
26    #[serde(default)]
27    pub methods: Vec<Method>,
28    #[serde(default)]
29    pub attributes: Vec<Attribute>,
30}
31
32#[derive(Debug, Deserialize)]
33pub struct Event {
34    pub name: String,
35    #[serde(default)]
36    pub description: String,
37    #[serde(default)]
38    pub filter: Option<String>,
39    #[serde(default)]
40    pub data: Vec<Parameter>,
41}
42
43#[derive(Debug, Deserialize)]
44pub struct Concept {
45    pub name: String,
46    #[serde(default)]
47    pub description: String,
48    #[serde(rename = "type")]
49    pub type_name: ApiType,
50}
51
52#[derive(Debug, Deserialize)]
53pub struct Define {
54    pub name: String,
55    #[serde(default)]
56    pub description: String,
57    #[serde(default)]
58    pub values: Vec<DefineValue>,
59    #[serde(default)]
60    pub subkeys: Vec<Define>,
61}
62
63#[derive(Debug, Deserialize)]
64pub struct DefineValue {
65    pub name: String,
66    #[serde(default)]
67    pub description: String,
68}
69
70#[derive(Debug, Deserialize)]
71pub struct GlobalObject {
72    pub name: String,
73    #[serde(default)]
74    pub description: String,
75    #[serde(rename = "type")]
76    pub type_name: ApiType,
77}
78
79#[derive(Debug, Deserialize)]
80pub struct Method {
81    pub name: String,
82    #[serde(default)]
83    pub description: String,
84    #[serde(default)]
85    pub parameters: Vec<Parameter>,
86    #[serde(default)]
87    pub return_values: Vec<Parameter>,
88    #[serde(default)]
89    pub format: MethodFormat,
90}
91
92#[derive(Debug, Default, Deserialize)]
93pub struct MethodFormat {
94    #[serde(default)]
95    pub takes_table: bool,
96}
97
98#[derive(Debug, Deserialize)]
99pub struct Attribute {
100    pub name: String,
101    #[serde(default)]
102    pub description: String,
103    #[serde(default)]
104    pub read_type: Option<ApiType>,
105    #[serde(default)]
106    pub write_type: Option<ApiType>,
107    #[serde(default)]
108    pub optional: bool,
109}
110
111#[derive(Debug, Deserialize)]
112pub struct Parameter {
113    #[serde(default)]
114    pub name: String,
115    #[serde(default)]
116    pub description: String,
117    #[serde(rename = "type")]
118    pub type_name: ApiType,
119    #[serde(default)]
120    pub optional: bool,
121}
122
123#[derive(Debug, Clone, Deserialize)]
124#[serde(transparent)]
125pub struct ApiType(pub serde_json::Value);
126
127impl ApiType {
128    pub fn as_simple_name(&self) -> Option<&str> {
129        self.0.as_str()
130    }
131
132    pub fn complex_type(&self) -> Option<&str> {
133        self.0.get("complex_type").and_then(|value| value.as_str())
134    }
135
136    pub fn child_type(&self, key: &str) -> Option<ApiType> {
137        self.0.get(key).cloned().map(ApiType)
138    }
139
140    pub fn options(&self) -> Vec<ApiType> {
141        self.0
142            .get("options")
143            .and_then(|value| value.as_array())
144            .map(|values| values.iter().cloned().map(ApiType).collect())
145            .unwrap_or_default()
146    }
147
148    /// Element types of a `tuple` complex type (from the `"values"` array).
149    pub fn tuple_values(&self) -> Vec<ApiType> {
150        self.0
151            .get("values")
152            .and_then(|v| v.as_array())
153            .map(|values| values.iter().cloned().map(ApiType).collect())
154            .unwrap_or_default()
155    }
156
157    /// For a `literal` complex type, returns the primitive kind: `"string"`,
158    /// `"number"`, or `"boolean"`, based on the JSON type of the `"value"` field.
159    ///
160    /// Returns `None` for non-literal types (e.g. `array`, `union`) even if they
161    /// happen to have a `"value"` key - the `complex_type` must be `"literal"`.
162    pub fn literal_kind(&self) -> Option<&'static str> {
163        // Guard: only `literal` complex types are valid here.
164        if self.complex_type() != Some("literal") {
165            return None;
166        }
167        let value = self.0.get("value")?;
168        if value.is_string() {
169            Some("string")
170        } else if value.is_number() {
171            Some("number")
172        } else if value.is_boolean() {
173            Some("boolean")
174        } else {
175            None
176        }
177    }
178
179    /// Parameters of a `table` complex type, as `(name, type, optional)` triples.
180    pub fn parameters(&self) -> Vec<(String, ApiType, bool)> {
181        self.0
182            .get("parameters")
183            .and_then(|value| value.as_array())
184            .map(|params| {
185                params
186                    .iter()
187                    .filter_map(|p| {
188                        let name = p.get("name")?.as_str()?.to_string();
189                        let ty = ApiType(p.get("type")?.clone());
190                        let optional = p.get("optional").and_then(|v| v.as_bool()).unwrap_or(false);
191                        Some((name, ty, optional))
192                    })
193                    .collect()
194            })
195            .unwrap_or_default()
196    }
197
198    /// Non-`nil` arms of a `union` complex type.
199    pub fn non_nil_options(&self) -> Vec<ApiType> {
200        self.options()
201            .into_iter()
202            .filter(|option| option.as_simple_name() != Some("nil"))
203            .collect()
204    }
205
206    /// Whether this type is a `union` whose non-nil arms are all string literals.
207    pub fn is_homog_string_literal_union(&self) -> bool {
208        if self.complex_type() != Some("union") {
209            return false;
210        }
211        let non_nil = self.non_nil_options();
212        !non_nil.is_empty() && non_nil.iter().all(|option| option.literal_kind() == Some("string"))
213    }
214
215    /// String values of a homogeneous string-literal union, in Factorio order.
216    ///
217    /// Returns an empty vec when this is not a homog string-literal union.
218    pub fn string_literal_values(&self) -> Vec<String> {
219        if !self.is_homog_string_literal_union() {
220            return Vec::new();
221        }
222        self.non_nil_options()
223            .into_iter()
224            .filter_map(|option| {
225                option
226                    .0
227                    .get("value")
228                    .and_then(|value| value.as_str())
229                    .map(str::to_string)
230            })
231            .collect()
232    }
233
234    /// Whether this union includes a `nil` arm.
235    pub fn union_has_nil(&self) -> bool {
236        self.complex_type() == Some("union")
237            && self
238                .options()
239                .iter()
240                .any(|option| option.as_simple_name() == Some("nil"))
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::ApiType;
247
248    fn parse(json: &str) -> ApiType {
249        ApiType(serde_json::from_str(json).expect("json"))
250    }
251
252    #[test]
253    fn detects_homog_string_literal_union() {
254        let ty = parse(
255            r#"{
256                "complex_type": "union",
257                "options": [
258                    {"complex_type": "literal", "value": "left"},
259                    {"complex_type": "literal", "value": "right"},
260                    "nil"
261                ]
262            }"#,
263        );
264        assert!(ty.is_homog_string_literal_union());
265        assert!(ty.union_has_nil());
266        assert_eq!(
267            ty.string_literal_values(),
268            vec!["left".to_string(), "right".to_string()]
269        );
270    }
271
272    #[test]
273    fn rejects_heterogeneous_union() {
274        let ty = parse(
275            r#"{
276                "complex_type": "union",
277                "options": ["LuaEntity", "LuaEquipment"]
278            }"#,
279        );
280        assert!(!ty.is_homog_string_literal_union());
281        assert!(ty.string_literal_values().is_empty());
282    }
283
284    #[test]
285    fn rejects_non_union() {
286        let ty = parse(r#""string""#);
287        assert!(!ty.is_homog_string_literal_union());
288    }
289}