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
use std::io::Write;
use std::str::FromStr;

use cpclib_common::itertools::Itertools;
use cpclib_sna::{AceSymbol, AceSymbolChunk, AceSymbolType, RemuChunk, RemuEntry};
use cpclib_tokens::symbols::{Symbol, SymbolsTableTrait, Value};
use cpclib_tokens::ExprResult;

pub enum SymbolOutputFormat {
    Basm,
    Winape
}

impl SymbolOutputFormat {
    pub fn format(&self, k: &Symbol, v: &Value) -> String {
        match self {
            SymbolOutputFormat::Basm => {
                match v {
                    Value::Address(a) => {
                        format!("{} equ #{:04X}", k.value(), a.address())
                    },
                    Value::Expr(ExprResult::Value(i)) => {
                        format!("{} equ #{:04X}", k.value(), i)
                    },
                    Value::Expr(ExprResult::Bool(b)) => {
                        format!("{} equ {}", k.value(), *b)
                    },
                    Value::Expr(e @ ExprResult::Float(_f)) => {
                        format!("{} equ #{:04X}", k.value(), e.int().unwrap())
                    },
                    Value::Expr(ExprResult::String(s)) => {
                        format!("{} equ {}", k.value(), s)
                    },
                    Value::Expr(l @ ExprResult::List(_)) => {
                        format!("{} equ {}", k.value(), l)
                    },
                    Value::Expr(m @ ExprResult::Matrix { .. }) => {
                        format!("{} equ {}", k.value(), m)
                    },

                    _ => unimplemented!("{:?}", v)
                }
            },
            SymbolOutputFormat::Winape => {
                match v {
                    Value::Address(a) => {
                        format!("{} #{:X}", k.value(), a.address())
                    },
                    Value::Expr(ExprResult::Value(i)) => {
                        format!("{} #{:X}", k.value(), i)
                    },
                    Value::Expr(ExprResult::Bool(b)) => {
                        format!("{} {}", k.value(), *b)
                    },
                    Value::Expr(e @ ExprResult::Float(_f)) => {
                        format!("{} #{:X}", k.value(), e.int().unwrap())
                    },
                    Value::Expr(ExprResult::String(_s)) => {
                        "".to_owned() // ignored by winape
                    },
                    Value::Expr(_l @ ExprResult::List(_)) => {
                        "".to_owned() // ignored by winape
                    },
                    Value::Expr(_m @ ExprResult::Matrix { .. }) => {
                        "".to_owned() // ignored by winape
                    },

                    _ => unimplemented!("{:?}", v)
                }
            }
        }
    }
}

impl FromStr for SymbolOutputFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "basm" => Ok(Self::Basm),
            "winape" => Ok(Self::Winape),
            _ => Err(format!("Wrong symbol format {s}"))
        }
    }
}

/// Manage the generation of the symbols output.
/// Could be parametrize by some directives
#[derive(Clone)]
pub struct SymbolOutputGenerator {
    forbidden: Vec<Symbol>,
    allowed: Vec<Symbol>,

    all_forbidden: bool,
    all_allowed: bool
}

impl Default for SymbolOutputGenerator {
    fn default() -> Self {
        Self {
            forbidden: Vec::new(),
            allowed: Vec::new(),

            all_forbidden: false,
            all_allowed: true
        }
    }
}

impl SymbolOutputGenerator {
    fn symbol_to_u16(v: &Value) -> Option<u16> {
        match v {
            Value::Address(a) => Some(a.address()),
            Value::Expr(ExprResult::Value(i)) => Some(*i as u16),
            Value::Expr(ExprResult::Bool(b)) => Some(*b as u16),
            Value::Expr(_e @ ExprResult::Float(_f)) => None,
            Value::Expr(ExprResult::String(_s)) => None,
            Value::Expr(_l @ ExprResult::List(_)) => None,
            Value::Expr(_m @ ExprResult::Matrix { .. }) => None,

            _ => None
        }
    }

    pub fn build_ace_snapshot_chunk(&self, symbs: &impl SymbolsTableTrait) -> AceSymbolChunk {
        let mut symbols = Vec::new();

        for (k, v) in symbs
            .expression_symbol()
            .iter()
            .filter(|(s, _v)| self.keep_symbol(s))
        //    .sorted_by_key(|(s, _v)| s.to_string().to_ascii_lowercase())
        {
            // Get the symbol
            let k = k.value();

            // get a possible value when using u16
            let v = Self::symbol_to_u16(v);

            // TODO properly create the value by specifying a correct mem map type and symb type
            // store if we have a representation
            if let Some(v) = v {
                let symb = AceSymbol::new(
                    &k,
                    v,
                    cpclib_sna::AceMemMapType::Undefined,
                    AceSymbolType::Absolute
                );
                symbols.push(symb);
            }
        }

        let mut chunk = AceSymbolChunk::empty();
        chunk.add_symbols(symbols.into_iter());
        chunk
    }

    pub fn fill_remu_snapshot_chunk(&self, symbs: &impl SymbolsTableTrait, remu: &mut RemuChunk) {
        for (k, v) in symbs
            .expression_symbol()
            .iter()
            .filter(|(s, _v)| self.keep_symbol(s))
        {
            // Get the symbol
            let k = k.value();

            // get a possible value when using u16
            let v = Self::symbol_to_u16(v);

            // TODO handle aliases
            if let Some(v) = v {
                let entry = RemuEntry::new_label(k.to_string(), v, 0);
                remu.add_entry(&entry);
            }
        }
    }

    /// Generate the symbol table in w
    pub fn generate<W: Write>(
        &self,
        w: &mut W,
        symbs: &impl SymbolsTableTrait,
        format: SymbolOutputFormat
    ) -> std::io::Result<()> {
        for (k, v) in symbs
            .expression_symbol()
            .iter()
            .filter(|(s, _v)| self.keep_symbol(s))
            .sorted_by_key(|(s, _v)| s.to_string().to_ascii_lowercase())
        {
            writeln!(w, "{}", format.format(k, v))?;
        }

        Ok(())
    }

    /// Returns true if the symbol needs to be printed
    pub fn keep_symbol(&self, sym: &Symbol) -> bool {
        assert!(self.all_allowed ^ self.all_forbidden);

        if sym.value() == "$" {
            return false;
        }
        if sym.value() == "$$" {
            return false;
        }
        else if self.all_allowed {
            !Self::is_included(&self.forbidden, sym)
        }
        else
        // if self.all_forbidden
        {
            Self::is_included(&self.allowed, sym)
        }
    }

    fn is_included(list: &[Symbol], sym: &Symbol) -> bool {
        list.iter()
            .find(|s2| {
                if **s2 == *sym {
                    return true;
                }
                // if !s2.value().contains(".") {return false;}
                sym.value().starts_with(&format!("{}.", s2.value()))
            })
            .is_some()
    }

    pub fn forbid_all_symbols(&mut self) {
        self.forbidden.clear();
        self.all_forbidden = true;
        self.all_allowed = false;
    }

    pub fn allow_all_symbols(&mut self) {
        self.allowed.clear();
        self.all_allowed = true;
        self.all_forbidden = false;
    }

    pub fn forbid_symbol<S: Into<Symbol>>(&mut self, s: S) {
        self.forbidden.push(s.into());
    }

    pub fn allow_symbol<S: Into<Symbol>>(&mut self, s: S) {
        self.allowed.push(s.into());
    }
}