factorio-ir 0.5.0

Intermediate representation for factorio-rs Rust-to-Lua Factorio mod transpilation
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Transpile-time safety lints with stable identifiers for `Factorio.toml`.

use std::collections::BTreeMap;

use serde::Deserialize;

use crate::meta::span::SourceLoc;

/// Stable lint identifier used in diagnostics and `[lints]` config keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LintId {
    /// `.unwrap()` is a no-op in Lua (nil is not checked).
    Unwrap,
    /// `.expect(...)` is a no-op in Lua (message discarded, nil not checked).
    Expect,
    /// Non-`?` format specs (e.g. `{:.2}`) are ignored when lowering.
    FormatSpec,
    /// Non-literal array indices are not shifted for Lua's 1-based tables.
    VariableIndex,
    /// Obsolete: Identification constructors now lower to their payload. Kept so
    /// existing `[lints] identification_ctor = ...` keys still parse.
    IdentificationCtor,
    /// Plain `if option` / `while option` uses Lua truthiness (`Some(false)` is skipped).
    OptionIf,
    /// `?` on a value whose type is unknown; lowering assumes Result (`.err` / `.ok`).
    AmbiguousTry,
    /// Overlapping Option/Result method (`.map`, ...) without a typed binding.
    AmbiguousMethod,
    /// Nested inline `mod` without `#[factorio_rs::export]` is skipped when lowering.
    SkippedMod,
    /// Plain `if result` / `while result` is always truthy (Result is a table).
    ResultIf,
    /// `Err(nil)` / `Err(None)` collapses with Ok under the `.err == nil` discriminant.
    ErrNil,
    /// `?` on a call/method uses Result semantics; Option APIs need a typed binding or `.ok_or`.
    OptionTry,
    /// Rust integer `/` truncates; Lua `/` is always float division.
    IntegerDiv,
    /// Struct update `..rest` other than `Default::default()` drops fields silently.
    StructRest,
    /// Numeric `as` casts are transparent in Lua (no clamp/truncation).
    NumericCast,
    /// `todo!` / `unimplemented!` should be `panic!("...")` / `error(...)` in Factorio mods.
    TodoMacro,
    /// `storage["key"]` returns opaque `LuaAny`; prefer `.get` / `.set`.
    StorageIndex,
}

impl LintId {
    /// Config / diagnostic name (`unwrap`, `expect`, ...) for `Factorio.toml` `[lints]`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Unwrap => "unwrap",
            Self::Expect => "expect",
            Self::FormatSpec => "format_spec",
            Self::VariableIndex => "variable_index",
            Self::IdentificationCtor => "identification_ctor",
            Self::OptionIf => "option_if",
            Self::AmbiguousTry => "ambiguous_try",
            Self::AmbiguousMethod => "ambiguous_method",
            Self::SkippedMod => "skipped_mod",
            Self::ResultIf => "result_if",
            Self::ErrNil => "err_nil",
            Self::OptionTry => "option_try",
            Self::IntegerDiv => "integer_div",
            Self::StructRest => "struct_rest",
            Self::NumericCast => "numeric_cast",
            Self::TodoMacro => "todo_macro",
            Self::StorageIndex => "storage_index",
        }
    }

    /// Rustc-style diagnostic code shown in reports (`E0001`, ...).
    #[must_use]
    pub const fn code(self) -> &'static str {
        match self {
            Self::Unwrap => "E0001",
            Self::Expect => "E0002",
            Self::FormatSpec => "E0003",
            Self::VariableIndex => "E0004",
            Self::IdentificationCtor => "E0005",
            Self::OptionIf => "E0006",
            Self::AmbiguousTry => "E0007",
            Self::AmbiguousMethod => "E0008",
            Self::SkippedMod => "E0009",
            Self::ResultIf => "E0010",
            Self::ErrNil => "E0011",
            Self::OptionTry => "E0012",
            Self::IntegerDiv => "E0013",
            Self::StructRest => "E0014",
            Self::NumericCast => "E0015",
            Self::TodoMacro => "E0016",
            Self::StorageIndex => "E0017",
        }
    }

    /// Default severity when unset in `Factorio.toml`.
    ///
    /// Most lints default to deny (they can miscompile). `format_spec` only
    /// drops unsupported precision/width and still emits working Lua, so it
    /// defaults to warn. `integer_div` defaults to warn because Factorio math is
    /// often float and operand types are not fully tracked.
    #[must_use]
    pub const fn default_level(self) -> LintLevel {
        match self {
            Self::FormatSpec | Self::IntegerDiv | Self::NumericCast | Self::StorageIndex => {
                LintLevel::Warn
            }
            Self::Unwrap
            | Self::Expect
            | Self::VariableIndex
            | Self::OptionIf
            | Self::AmbiguousTry
            | Self::AmbiguousMethod
            | Self::SkippedMod
            | Self::ResultIf
            | Self::ErrNil
            | Self::OptionTry
            | Self::StructRest
            | Self::TodoMacro => LintLevel::Deny,
            // Constructors lower to payloads; keep the id for config compatibility only.
            Self::IdentificationCtor => LintLevel::Allow,
        }
    }

    /// Short help shown under ariadne reports.
    #[must_use]
    pub const fn help(self) -> &'static str {
        match self {
            Self::Unwrap => "use `if let Some(x) = ...` (or set `[lints] unwrap = \"allow\"`)",
            Self::Expect => "use `if let Some(x) = ...` (or set `[lints] expect = \"allow\"`)",
            #[allow(clippy::literal_string_with_formatting_args)]
            Self::FormatSpec => "only `{}`, `{:?}`, and `{:#?}` are supported when lowering",
            Self::VariableIndex => {
                "literal indices are shifted `n -> n+1`; pass a 1-based index or use a literal"
            }
            Self::IdentificationCtor => {
                "Identification constructors (`ForceID::Name(...)`) now lower to the payload; this lint is unused"
            }
            Self::OptionIf => {
                "use `if let Some(x) = opt` or `opt.is_some()` (Lua truthiness skips `Some(false)`)"
            }
            Self::AmbiguousTry => {
                "annotate as `Result` / `Option`, or convert with `.ok_or(...)?` for Options"
            }
            Self::AmbiguousMethod => {
                "bind with an explicit `Result` / `Option` type so the correct helper is chosen"
            }
            Self::SkippedMod => {
                "add `#[factorio_rs::export]` on the inline mod, or move items to a file module"
            }
            Self::ResultIf => {
                "use `if let Ok(x) = result` or `result.is_ok()` (a Result table is always truthy in Lua)"
            }
            Self::ErrNil => {
                "use a non-nil error payload (`String`, number, table); `Err(nil)` looks like Ok"
            }
            Self::OptionTry => {
                "bind `let x: Option<_> = api(...); x?` or use `.ok_or(...)?`; for Result calls bind `let r: Result<...> = ...; r?`"
            }
            Self::IntegerDiv => {
                "Lua `/` is float division; use a float operand (`n / 2.0`) or set `[lints] integer_div = \"allow\"`"
            }
            Self::StructRest => {
                "only `..Default::default()` is ignored on purpose; copy fields explicitly or use that form"
            }
            Self::NumericCast => {
                "Lua has no integer cast; remove `as` or use explicit math if you need clamping"
            }
            Self::TodoMacro => {
                "use `panic!(\"...\")` (lowers to `error(...)`) or finish the code path"
            }
            Self::StorageIndex => {
                "use `storage.get::<T>(\"key\")` / `storage.set(\"key\", value)` for typed access"
            }
        }
    }

    /// All built-in lint identifiers.
    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::Unwrap,
            Self::Expect,
            Self::FormatSpec,
            Self::VariableIndex,
            Self::IdentificationCtor,
            Self::OptionIf,
            Self::AmbiguousTry,
            Self::AmbiguousMethod,
            Self::SkippedMod,
            Self::ResultIf,
            Self::ErrNil,
            Self::OptionTry,
            Self::IntegerDiv,
            Self::StructRest,
            Self::NumericCast,
            Self::TodoMacro,
            Self::StorageIndex,
        ]
    }

    /// Parse a config key into a lint id.
    #[must_use]
    pub fn from_config_str(name: &str) -> Option<Self> {
        Self::all().iter().copied().find(|id| id.as_str() == name)
    }
}

impl std::fmt::Display for LintId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.code())
    }
}

/// How a lint is treated when it fires.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LintLevel {
    /// Do not emit the lint (disabled).
    Allow,
    /// Emit a warning; build still succeeds.
    Warn,
    /// Emit an error; build fails.
    #[default]
    Deny,
}

impl LintLevel {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Allow => "allow",
            Self::Warn => "warn",
            Self::Deny => "deny",
        }
    }
}

/// Resolved lint levels from `Factorio.toml` `[lints]` (and defaults).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintConfig {
    levels: BTreeMap<LintId, LintLevel>,
}

impl Default for LintConfig {
    fn default() -> Self {
        Self {
            levels: LintId::all()
                .iter()
                .map(|id| (*id, id.default_level()))
                .collect(),
        }
    }
}

impl LintConfig {
    /// All lints allowed (useful in unit tests that exercise transparent methods).
    #[must_use]
    pub fn allow_all() -> Self {
        Self {
            levels: LintId::all()
                .iter()
                .map(|id| (*id, LintLevel::Allow))
                .collect(),
        }
    }

    /// Apply overrides from a `[lints]` table (`unwrap = "allow"`, ...).
    ///
    /// # Errors
    /// Returns the unknown lint name when a key is not a known [`LintId`].
    pub fn with_overrides(
        mut self,
        overrides: &BTreeMap<String, LintLevel>,
    ) -> Result<Self, String> {
        for (name, level) in overrides {
            let Some(id) = LintId::from_config_str(name) else {
                let known = LintId::all()
                    .iter()
                    .copied()
                    .map(LintId::as_str)
                    .collect::<Vec<_>>()
                    .join(", ");
                return Err(format!("unknown lint `{name}` (known: {known})"));
            };
            self.levels.insert(id, *level);
        }
        Ok(self)
    }

    #[must_use]
    pub fn level(&self, id: LintId) -> LintLevel {
        self.levels
            .get(&id)
            .copied()
            .unwrap_or_else(|| id.default_level())
    }

    #[must_use]
    pub fn is_allowed(&self, id: LintId) -> bool {
        matches!(self.level(id), LintLevel::Allow)
    }

    /// Allow a single lint (builder-style).
    #[must_use]
    pub fn allowing(mut self, id: LintId) -> Self {
        self.levels.insert(id, LintLevel::Allow);
        self
    }
}

/// A single transpile diagnostic tied to a lint code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    pub id: LintId,
    pub level: LintLevel,
    pub message: String,
    pub loc: SourceLoc,
}

impl Diagnostic {
    #[must_use]
    pub fn new(
        id: LintId,
        level: LintLevel,
        message: impl Into<String>,
        loc: impl Into<SourceLoc>,
    ) -> Self {
        Self {
            id,
            level,
            message: message.into(),
            loc: loc.into(),
        }
    }

    #[must_use]
    pub const fn is_error(&self) -> bool {
        matches!(self.level, LintLevel::Deny)
    }
}

impl std::fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} {}: {} ({}) at {}",
            self.level.as_str(),
            self.id.code(),
            self.message,
            self.id.as_str(),
            self.loc
        )
    }
}

/// Raw `[lints]` table as deserialized from `Factorio.toml`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
pub struct LintsTable {
    #[serde(flatten)]
    pub levels: BTreeMap<String, LintLevel>,
}

impl LintsTable {
    /// Resolve into a [`LintConfig`], validating lint names.
    ///
    /// # Errors
    /// Unknown lint identifiers.
    pub fn into_config(self) -> Result<LintConfig, String> {
        LintConfig::default().with_overrides(&self.levels)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_levels() {
        let config = LintConfig::default();
        assert_eq!(config.level(LintId::Unwrap), LintLevel::Deny);
        assert_eq!(config.level(LintId::FormatSpec), LintLevel::Warn);
        assert_eq!(config.level(LintId::ResultIf), LintLevel::Deny);
        assert_eq!(config.level(LintId::ErrNil), LintLevel::Deny);
        assert_eq!(config.level(LintId::OptionTry), LintLevel::Deny);
        assert_eq!(config.level(LintId::IntegerDiv), LintLevel::Warn);
        assert_eq!(config.level(LintId::StructRest), LintLevel::Deny);
        assert_eq!(config.level(LintId::NumericCast), LintLevel::Warn);
        assert_eq!(config.level(LintId::TodoMacro), LintLevel::Deny);
        assert_eq!(config.level(LintId::StorageIndex), LintLevel::Warn);
        assert_eq!(config.level(LintId::IdentificationCtor), LintLevel::Allow);
    }

    #[test]
    fn overrides_allow_unwrap() {
        let mut table = BTreeMap::new();
        table.insert("unwrap".to_string(), LintLevel::Allow);
        let config = LintConfig::default().with_overrides(&table).unwrap();
        assert!(config.is_allowed(LintId::Unwrap));
        assert!(!config.is_allowed(LintId::Expect));
    }

    #[test]
    fn rejects_unknown_lint_name() {
        let mut table = BTreeMap::new();
        table.insert("not_a_lint".to_string(), LintLevel::Allow);
        let err = LintConfig::default().with_overrides(&table).unwrap_err();
        assert!(err.contains("not_a_lint"));
    }

    #[test]
    fn lint_codes_are_stable() {
        assert_eq!(LintId::Unwrap.code(), "E0001");
        assert_eq!(LintId::Expect.code(), "E0002");
        assert_eq!(LintId::FormatSpec.code(), "E0003");
        assert_eq!(LintId::VariableIndex.code(), "E0004");
        assert_eq!(LintId::IdentificationCtor.code(), "E0005");
        assert_eq!(LintId::OptionIf.code(), "E0006");
        assert_eq!(LintId::AmbiguousTry.code(), "E0007");
        assert_eq!(LintId::AmbiguousMethod.code(), "E0008");
        assert_eq!(LintId::SkippedMod.code(), "E0009");
        assert_eq!(LintId::ResultIf.code(), "E0010");
        assert_eq!(LintId::ErrNil.code(), "E0011");
        assert_eq!(LintId::OptionTry.code(), "E0012");
        assert_eq!(LintId::IntegerDiv.code(), "E0013");
        assert_eq!(LintId::StructRest.code(), "E0014");
        assert_eq!(LintId::NumericCast.code(), "E0015");
        assert_eq!(LintId::TodoMacro.code(), "E0016");
        assert_eq!(LintId::StorageIndex.code(), "E0017");
    }
}