Skip to main content

assembler/
symtab.rs

1//! Explicit and implicit symbol definitions.
2use std::collections::BTreeMap;
3use std::collections::HashSet;
4use std::fmt::{self, Debug, Display, Formatter};
5
6use base::prelude::*;
7
8use super::ast::{EqualityValue, Origin};
9use super::collections::OneOrMore;
10use super::eval::EvaluationFailure;
11use super::memorymap::{RcAllocator, RcWordAllocationFailure, RcWordKind, RcWordSource};
12use super::source::Source;
13use super::span::{Span, Spanned};
14use super::symbol::{InconsistentSymbolUse, SymbolContext, SymbolName};
15use super::types::{AssemblerFailure, BlockIdentifier, ProgramError};
16
17#[derive(Debug, Default, PartialEq, Eq)]
18pub(crate) struct IndexRegisterAssigner {
19    index_registers_used: Unsigned6Bit,
20}
21
22impl IndexRegisterAssigner {
23    pub(crate) fn assign_index_register(&mut self) -> Option<Unsigned6Bit> {
24        // These start at 0, but we can't assign X0 (since it is
25        // always zero), and this is why we increment
26        // `index_registers_used` first.
27        if let Some(n) = self.index_registers_used.checked_add(u6!(1)) {
28            self.index_registers_used = n;
29            Some(n)
30        } else {
31            None
32        }
33    }
34
35    pub(crate) fn is_empty(&self) -> bool {
36        self.index_registers_used == 0
37    }
38}
39
40/// Implicit definitions (e.g. index, configuration and address
41/// values), including information about the usage of symbols for
42/// which we have not yet assigned a default value.
43///
44/// The rules for how symbols which have references but no explicit
45/// definition are assigned values are indicated in "Unassigned
46/// Symexes" in section 6-2.2 of the User Handbook.
47#[derive(Debug, Default, Clone, PartialEq, Eq)]
48pub(crate) struct ImplicitSymbolTable {
49    definitions: BTreeMap<SymbolName, ImplicitDefinition>,
50}
51
52impl ImplicitSymbolTable {
53    pub(super) fn symbols(&self) -> impl Iterator<Item = &SymbolName> {
54        self.definitions.keys()
55    }
56
57    pub(crate) fn get(&self, name: &SymbolName) -> Option<&ImplicitDefinition> {
58        self.definitions.get(name)
59    }
60
61    pub(super) fn get_mut(&mut self, name: &SymbolName) -> Option<&mut ImplicitDefinition> {
62        self.definitions.get_mut(name)
63    }
64
65    pub(crate) fn remove(&mut self, name: &SymbolName) -> Option<ImplicitDefinition> {
66        self.definitions.remove(name)
67    }
68
69    pub(crate) fn record_usage_context(
70        &mut self,
71        name: &SymbolName,
72        context: &SymbolContext,
73    ) -> Result<(), InconsistentSymbolUse> {
74        self.definitions
75            .entry(name.clone())
76            .or_insert_with(|| ImplicitDefinition::Undefined(context.clone()))
77            .merge_context(name, context.clone())
78    }
79
80    pub(super) fn record_deduced_origin_value(
81        &mut self,
82        name: &SymbolName,
83        value: Address,
84        block_id: BlockIdentifier,
85        span: Span,
86    ) -> Result<(), InconsistentSymbolUse> {
87        let context = SymbolContext::origin(block_id, Origin::Deduced(span, name.clone(), value));
88        self.definitions
89            .entry(name.clone())
90            .or_insert_with(|| ImplicitDefinition::DefaultAssigned(value.into(), context.clone()))
91            .merge_context(name, context)
92    }
93
94    #[cfg(test)]
95    pub(super) fn load_test_definitions<
96        I: IntoIterator<Item = (SymbolName, ImplicitDefinition)>,
97    >(
98        &mut self,
99        defs: I,
100    ) {
101        for (name, definition) in defs {
102            self.definitions.insert(name, definition);
103        }
104    }
105}
106
107#[derive(Debug, Default, Clone, PartialEq, Eq)]
108pub(crate) struct ExplicitSymbolTable {
109    definitions: BTreeMap<SymbolName, ExplicitDefinition>,
110}
111
112#[derive(Debug, Default)]
113pub(crate) struct LookupOperation {
114    pub(super) depends_on: HashSet<SymbolName>,
115    pub(super) deps_in_order: Vec<SymbolName>,
116}
117
118// TODO: check whether we still need this at all.
119impl Spanned for (&Span, &SymbolName, &ExplicitDefinition) {
120    fn span(&self) -> Span {
121        let r1: &Span = self.0;
122        let r2: Span = self.2.span();
123        assert_eq!(r1, &r2);
124        r2
125    }
126}
127
128impl ExplicitSymbolTable {
129    pub(crate) fn new() -> ExplicitSymbolTable {
130        ExplicitSymbolTable {
131            definitions: Default::default(),
132        }
133    }
134
135    pub(crate) fn get(&self, name: &SymbolName) -> Option<&ExplicitDefinition> {
136        self.definitions.get(name)
137    }
138
139    pub(crate) fn is_defined(&self, name: &SymbolName) -> bool {
140        self.definitions.contains_key(name)
141    }
142
143    pub(crate) fn is_empty(&self) -> bool {
144        self.definitions.is_empty()
145    }
146
147    pub(crate) fn define(
148        &mut self,
149        name: SymbolName,
150        new_definition: ExplicitDefinition,
151    ) -> Result<(), BadSymbolDefinition> {
152        if let Some(existing) = self.definitions.get_mut(&name) {
153            existing.override_with(name, new_definition)
154        } else {
155            self.definitions.insert(name, new_definition);
156            Ok(())
157        }
158    }
159    pub(crate) fn merge(
160        &mut self,
161        other: ExplicitSymbolTable,
162    ) -> Result<(), OneOrMore<BadSymbolDefinition>> {
163        let mut errors: Vec<BadSymbolDefinition> = Vec::new();
164        for (name, def) in other.definitions {
165            if let Err(e) = self.define(name, def) {
166                errors.push(e);
167            }
168        }
169        match OneOrMore::try_from_vec(errors) {
170            Ok(errors) => Err(errors),
171            Err(_) => Ok(()), // errors was empty
172        }
173    }
174}
175
176#[derive(Debug, PartialEq, Eq)]
177pub(crate) enum FinalSymbolType {
178    Tag,
179    Equality,
180    Default,
181}
182
183#[derive(Debug)]
184pub(crate) enum FinalSymbolDefinition {
185    PositionIndependent(Unsigned36Bit),
186    PositionDependent,
187}
188
189#[derive(Debug, Default)]
190pub(crate) struct FinalSymbolTable {
191    definitions: BTreeMap<SymbolName, (FinalSymbolType, String, FinalSymbolDefinition)>,
192}
193
194impl FinalSymbolTable {
195    pub(crate) fn define(
196        &mut self,
197        name: SymbolName,
198        sym_type: FinalSymbolType,
199        rep: String,
200        def: FinalSymbolDefinition,
201    ) {
202        self.definitions.insert(name, (sym_type, rep, def));
203    }
204
205    pub(crate) fn define_if_undefined(
206        &mut self,
207        name: SymbolName,
208        sym_type: FinalSymbolType,
209        rep: String,
210        def: FinalSymbolDefinition,
211    ) {
212        self.definitions.entry(name).or_insert((sym_type, rep, def));
213    }
214}
215
216impl Display for FinalSymbolTable {
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        let show = |f: &mut std::fmt::Formatter<'_>,
219                    sym_type_wanted: FinalSymbolType,
220                    title: &str|
221         -> std::fmt::Result {
222            writeln!(f)?;
223            writeln!(f, "** {title}")?;
224            for (name, (_final_symbol_type, representation, definition)) in self
225                .definitions
226                .iter()
227                .filter(|(_, (symtype, _, _))| symtype == &sym_type_wanted)
228            {
229                match definition {
230                    FinalSymbolDefinition::PositionIndependent(word) => {
231                        writeln!(f, "{name:20} = {word:012} ** {representation:>20}")?;
232                    }
233                    FinalSymbolDefinition::PositionDependent => {
234                        writeln!(f, "{name:20} = {representation}")?;
235                    }
236                }
237            }
238            Ok(())
239        };
240
241        show(f, FinalSymbolType::Tag, "Tags")?;
242        show(f, FinalSymbolType::Equality, "Equalities")?;
243        show(f, FinalSymbolType::Default, "Default-assigned values")?;
244        Ok(())
245    }
246}
247
248#[derive(Debug, PartialEq, Eq, Clone)]
249pub(crate) enum TagDefinition {
250    Unresolved {
251        block_id: BlockIdentifier,
252        block_offset: Unsigned18Bit,
253        span: Span,
254    },
255    Resolved {
256        address: Address,
257        span: Span,
258    },
259}
260
261impl Spanned for TagDefinition {
262    fn span(&self) -> Span {
263        match self {
264            TagDefinition::Unresolved { span, .. } | TagDefinition::Resolved { span, .. } => *span,
265        }
266    }
267}
268
269impl Display for TagDefinition {
270    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
271        match self {
272            TagDefinition::Unresolved {
273                block_id,
274                block_offset,
275                span: _,
276            } => {
277                write!(
278                    f,
279                    "tag at offset {block_offset} in {block_id} with unspecified address"
280                )
281            }
282            TagDefinition::Resolved { address, span: _ } => {
283                write!(f, "tag with address {address:06o}")
284            }
285        }
286    }
287}
288
289#[derive(Debug, PartialEq, Eq, Clone)]
290pub(crate) enum ExplicitDefinition {
291    Tag(TagDefinition),
292    Equality(EqualityValue),
293    Origin(Origin, BlockIdentifier),
294}
295
296impl Spanned for ExplicitDefinition {
297    fn span(&self) -> Span {
298        match self {
299            ExplicitDefinition::Tag(tag_definition) => tag_definition.span(),
300            ExplicitDefinition::Equality(equality_value) => equality_value.span(),
301            ExplicitDefinition::Origin(origin, _block_identifier) => origin.span(),
302        }
303    }
304}
305
306impl Display for ExplicitDefinition {
307    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
308        match self {
309            ExplicitDefinition::Origin(origin, _block_identifier) => {
310                write!(f, "{origin}")
311            }
312            ExplicitDefinition::Tag(tagdef) => {
313                write!(f, "{tagdef}")
314            }
315            ExplicitDefinition::Equality(inst) => {
316                // TODO: print the assigned value, too?
317                write!(f, "assignment with value {inst:#?}")
318            }
319        }
320    }
321}
322
323impl ExplicitDefinition {
324    pub(crate) fn override_with(
325        &mut self,
326        name: SymbolName,
327        update: ExplicitDefinition,
328    ) -> Result<(), BadSymbolDefinition> {
329        match (self, update) {
330            (current @ ExplicitDefinition::Equality(_), new @ ExplicitDefinition::Equality(_)) => {
331                // This is always OK.
332                *current = new;
333                Ok(())
334            }
335            (current, new) => {
336                if current == &new {
337                    Ok(()) // nothing to do.
338                } else {
339                    Err(BadSymbolDefinition {
340                        symbol_name: name,
341                        span: new.span(),
342                        existing: Box::new(current.clone()),
343                        proposed: Box::new(new),
344                    })
345                }
346            }
347        }
348    }
349}
350
351#[derive(Debug, PartialEq, Eq, Clone)]
352pub(crate) enum ImplicitDefinition {
353    Undefined(SymbolContext),
354    DefaultAssigned(Unsigned36Bit, SymbolContext),
355}
356
357impl ImplicitDefinition {
358    pub(crate) fn context(&self) -> &SymbolContext {
359        match self {
360            ImplicitDefinition::Undefined(context)
361            | ImplicitDefinition::DefaultAssigned(_, context) => context,
362        }
363    }
364}
365
366impl Display for ImplicitDefinition {
367    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
368        match self {
369            ImplicitDefinition::Undefined(_context) => f.write_str("undefined"),
370            ImplicitDefinition::DefaultAssigned(value, _) => {
371                write!(f, "default-assigned as {value}")
372            }
373        }
374    }
375}
376
377#[derive(Debug, PartialEq, Eq, Clone)]
378pub(crate) struct BadSymbolDefinition {
379    /// Signals that an origin has been inconsistently defined, or a
380    /// tag has been defined in more than once place.
381    pub(crate) symbol_name: SymbolName,
382    pub(crate) span: Span,
383    // We box the two definitions here to reduce the (direct) size
384    // of the BadSymbolDefinition object itself.  Otherwise, this
385    // will give rise to large disparities between the Ok() and
386    // Err() variants of results that directly or indirectly
387    // include BadSymbolDefinition instances.
388    pub(crate) existing: Box<ExplicitDefinition>,
389    pub(crate) proposed: Box<ExplicitDefinition>,
390}
391
392impl Spanned for BadSymbolDefinition {
393    fn span(&self) -> Span {
394        self.span
395    }
396}
397
398impl Display for BadSymbolDefinition {
399    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
400        match (&*self.existing, &*self.proposed) {
401            (ExplicitDefinition::Tag(td1), ExplicitDefinition::Tag(td2)) => {
402                write!(
403                    f,
404                    "{0} is defined more than once, but this is not allowed for tags (tag defitions are {1} and {2})",
405                    self.symbol_name, td1, td2
406                )
407            }
408            _ => {
409                write!(
410                    f,
411                    "it is not allowed to override the symbol definition of {0} as {1} with a new definition {2}",
412                    self.symbol_name, self.existing, self.proposed
413                )
414            }
415        }
416    }
417}
418
419impl std::error::Error for BadSymbolDefinition {}
420
421impl ImplicitDefinition {
422    pub(crate) fn merge_context(
423        &mut self,
424        name: &SymbolName,
425        context: SymbolContext,
426    ) -> Result<(), InconsistentSymbolUse> {
427        match self {
428            ImplicitDefinition::Undefined(current) => current.merge(name, context),
429            ImplicitDefinition::DefaultAssigned(value, existing_context) => {
430                if &context == existing_context {
431                    Ok(())
432                } else {
433                    panic!(
434                        "attempting to change the recorded usage context for {name} after a default value {value:?} has been assigned; previous context was {existing_context:?}, new context is {context:?}"
435                    );
436                }
437            }
438        }
439    }
440}
441
442pub(super) fn assign_default_rc_word_tags<R: RcAllocator>(
443    implicit_symtab: &mut ImplicitSymbolTable,
444    rcblock: &mut R,
445    final_symbols: &mut FinalSymbolTable,
446) -> Result<(), RcWordAllocationFailure> {
447    for (name, def) in &mut implicit_symtab.definitions {
448        if let ImplicitDefinition::Undefined(context) = def
449            && context.requires_rc_word_allocation()
450        {
451            let span: Span = *context.any_span();
452            let value = Unsigned36Bit::ZERO;
453            let addr = rcblock.allocate(
454                RcWordSource {
455                    span,
456                    kind: RcWordKind::DefaultAssignment,
457                },
458                value,
459            )?;
460            final_symbols.define(
461                name.clone(),
462                FinalSymbolType::Equality,
463                value.to_string(),
464                FinalSymbolDefinition::PositionIndependent(value),
465            );
466            *def = ImplicitDefinition::DefaultAssigned(addr.into(), context.clone());
467        }
468    }
469    Ok(())
470}
471
472pub(super) fn record_undefined_symbol_or_return_failure(
473    source_file_body: &Source<'_>,
474    e: EvaluationFailure,
475    undefined_symbols: &mut BTreeMap<SymbolName, ProgramError>,
476) -> Result<(), AssemblerFailure> {
477    match e {
478        EvaluationFailure::SymbolDefinitionLoop {
479            span,
480            deps_in_order,
481            ..
482        } => {
483            undefined_symbols
484                .entry(deps_in_order.first().clone())
485                .or_insert_with(|| ProgramError::SymbolDefinitionLoop {
486                    symbol_names: deps_in_order,
487                    span,
488                });
489            Ok(())
490        }
491        other => Err(other
492            .into_program_error()
493            .into_assembler_failure(source_file_body)),
494    }
495}