Skip to main content

i8051_disassembler/commands/
label.rs

1use crate::address::{SpaceAddressSet, SpaceAddressValue};
2use crate::db::{Db, Error, ErrorKind};
3
4use super::{Apply, Command, Environment, boxed};
5
6#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
7pub struct SetLabel {
8    pub address: SpaceAddressValue,
9    pub label: String,
10    /// A working guess rather than a finalized name. If true, stays on the
11    /// naming worklist.
12    pub provisional: bool,
13    /// Scoped to the routine containing it.
14    pub local: bool,
15}
16
17register!(SetLabel(
18    /// Name the code `address` with `label`. Pass `provisional=True` for a
19    /// working guess: it is stored and shown like any name, but the address
20    /// stays on the naming worklist so a later pass can adjust it.
21    address: SpaceAddressValue,
22    label: String,
23    provisional: bool,
24    local: bool,
25));
26
27impl Apply for SetLabel {
28    fn apply(
29        self,
30        db: &mut Db,
31        _env: Option<&dyn Environment>,
32    ) -> Result<Vec<Box<dyn Command>>, Error> {
33        let Self {
34            address,
35            label,
36            provisional,
37            local,
38        } = self;
39        let label = normalize_label(&label)?;
40        let SpaceAddressValue { space, offset } = address;
41        let region = db.region_mut(space);
42        let before = region.get_label(offset).map(str::to_owned);
43        let was_draft = region.is_draft_label(offset);
44        let was_local = region.is_local_label(offset);
45        region.set_label(
46            offset,
47            &label,
48            crate::region::LabelAttrs { provisional, local },
49        );
50        Ok(match before {
51            Some(label) => {
52                vec![boxed(SetLabel {
53                    address,
54                    label,
55                    provisional: was_draft,
56                    local: was_local,
57                })]
58            }
59            None => vec![boxed(ClearLabel::new((space, offset)))],
60        })
61    }
62}
63
64/// Clean a caller-supplied label into something an assembler can accept.
65pub fn normalize_label(label: &str) -> Result<String, Error> {
66    let trimmed = label.trim();
67    let unquoted = trimmed
68        .strip_prefix('"')
69        .and_then(|rest| rest.strip_suffix('"'))
70        .unwrap_or(trimmed)
71        .trim();
72    let invalid = |reason| {
73        Err(ErrorKind::InvalidLabel {
74            label: label.to_string(),
75            reason,
76        }
77        .into())
78    };
79    if unquoted.is_empty() {
80        return invalid("a label cannot be empty");
81    }
82    if unquoted.chars().any(char::is_whitespace) {
83        return invalid("a label cannot contain whitespace");
84    }
85    if unquoted.contains('"') {
86        return invalid("a label cannot contain quote characters");
87    }
88    if unquoted.starts_with(|c: char| c.is_ascii_digit()) {
89        return invalid("a label cannot start with a digit");
90    }
91    Ok(unquoted.to_string())
92}
93
94#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
95pub struct ClearLabel {
96    pub addresses: SpaceAddressSet,
97}
98
99register!(ClearLabel(
100    /// Remove labels at the given `addresses`.
101    addresses: SpaceAddressSet,
102));
103
104impl Apply for ClearLabel {
105    fn apply(
106        self,
107        db: &mut Db,
108        _env: Option<&dyn Environment>,
109    ) -> Result<Vec<Box<dyn Command>>, Error> {
110        let Self { addresses } = self;
111        let space = addresses.space;
112        let region = db.region_mut(space);
113        let mut undo = Vec::new();
114        for range in addresses.ranges() {
115            for (offset, label) in region.clear_labels_in(range) {
116                undo.push(boxed(SetLabel::new((space, offset), label, false, false)));
117            }
118        }
119        Ok(undo)
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::labels::is_provisional_name;
127    use crate::platform::i8051::CODE;
128
129    #[test]
130    fn strips_extra_quotes() {
131        assert_eq!(normalize_label("\"uart_init\"").unwrap(), "uart_init");
132        assert_eq!(normalize_label("uart_init").unwrap(), "uart_init");
133        assert_eq!(normalize_label("  spaced_out  ").unwrap(), "spaced_out");
134        assert!(is_provisional_name(
135            &normalize_label("\"loc_0071\"").unwrap()
136        ));
137
138        for bad in ["", "  ", "\"\"", "two words", "mid\"quote", "9lives"] {
139            assert!(normalize_label(bad).is_err(), "{bad:?} should be rejected");
140        }
141    }
142
143    #[test]
144    fn recognizes_generated_names_only() {
145        for name in ["sub_002C", "loc_03A9", "sub_002c", "sub_10000"] {
146            assert!(is_provisional_name(name), "{name} should be provisional");
147        }
148        for name in [
149            "uart_init",
150            "sub_",
151            "sub_2C",
152            "loc_INIT",
153            "subtract_a",
154            "sub_00GG",
155        ] {
156            assert!(
157                !is_provisional_name(name),
158                "{name} should not be provisional"
159            );
160        }
161    }
162
163    #[test]
164    fn generated_name_refused() {
165        let mut db = Db::with_platform(crate::platform::i8051::platform());
166        let err = db
167            .apply(
168                boxed(SetLabel::new(
169                    (CODE, 0x2C),
170                    "sub_002C".to_string(),
171                    false,
172                    false,
173                )),
174                None,
175            )
176            .expect_err("the generated form is refused");
177        assert!(matches!(
178            &err.what,
179            crate::db::ErrorKind::GeneratedLabel { label } if label == "sub_002C"
180        ));
181        assert_eq!(db.region_mut(CODE).get_label(0x2C), None, "nothing stored");
182
183        // A real name still lands...
184        db.apply(
185            boxed(SetLabel::new(
186                (CODE, 0x2C),
187                "uart_init".to_string(),
188                false,
189                false,
190            )),
191            None,
192        )
193        .unwrap();
194        assert_eq!(db.region_mut(CODE).get_label(0x2C), Some("uart_init"));
195
196        // ...and a generated one does not overwrite it.
197        db.apply(
198            boxed(SetLabel::new(
199                (CODE, 0x2C),
200                "sub_002C".to_string(),
201                false,
202                false,
203            )),
204            None,
205        )
206        .expect_err("the generated form is refused");
207        assert_eq!(db.region_mut(CODE).get_label(0x2C), Some("uart_init"));
208    }
209
210    /// A provisional name is shown like any other, but the address stays on the
211    /// naming worklist.
212    #[test]
213    fn provisional_stays_draft() {
214        let mut db = Db::with_platform(crate::platform::i8051::platform());
215        db.apply(
216            boxed(SetLabel::new(
217                (CODE, 0x40),
218                "maybe_crc".to_string(),
219                true,
220                false,
221            )),
222            None,
223        )
224        .unwrap();
225        assert!(db.region_mut(CODE).is_draft_label(0x40));
226
227        let dsl = crate::store::to_dsl_many(&db.to_commands());
228        assert!(dsl.contains("provisional=True"), "{dsl}");
229        let mut replayed = Db::new();
230        for command in crate::store::from_dsl_many(&dsl).expect("export parses") {
231            replayed.apply(command, None).expect("export replays");
232        }
233        assert!(replayed.region_mut(CODE).is_draft_label(0x40), "{dsl}");
234
235        // Re-naming it without the flag finalizes it.
236        db.apply(
237            boxed(SetLabel::new(
238                (CODE, 0x40),
239                "crc16".to_string(),
240                false,
241                false,
242            )),
243            None,
244        )
245        .unwrap();
246        assert!(!db.region_mut(CODE).is_draft_label(0x40));
247    }
248}