cpclib_asm/parser/
source.rs

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
use std::fmt::Display;
use std::ops::{Deref, DerefMut};

use cpclib_common::smol_str::SmolStr;
use cpclib_common::winnow::stream::{AsBStr, Offset};
use cpclib_common::winnow::{BStr, Located, Stateful};
use cpclib_tokens::symbols::{Source, Symbol};
use line_span::LineSpanExt;

use super::context::ParserContext;
use super::ParsingState;

// This type is only handled by the parser
pub type InnerZ80Span = Stateful<
    Located<
        // the type of data, owned by the base listing of interest
        &'static BStr
    >,
    // The parsing context
    // TODO remove it an pass it over the parse arguments
    &'static ParserContext
>;

#[derive(Clone, PartialEq, Eq)]
pub struct Z80Span(pub(crate) InnerZ80Span);

impl From<InnerZ80Span> for Z80Span {
    fn from(value: InnerZ80Span) -> Self {
        Self(value)
    }
}

impl From<Z80Span> for InnerZ80Span {
    fn from(val: Z80Span) -> Self {
        val.0
    }
}

impl AsRef<str> for Z80Span {
    #[inline]
    fn as_ref(&self) -> &str {
        unsafe { std::str::from_utf8_unchecked(self.0.as_bstr()) }
    }
}

impl<'a> From<&'a Z80Span> for &'a str {
    fn from(val: &'a Z80Span) -> Self {
        AsRef::as_ref(val)
    }
}

pub trait SourceString: Display {
    fn as_str(&self) -> &str;
}

impl From<&dyn SourceString> for Symbol {
    fn from(val: &dyn SourceString) -> Self {
        val.as_str().into()
    }
}

impl From<&Z80Span> for Symbol {
    fn from(val: &Z80Span) -> Self {
        val.as_str().into()
    }
}

impl SourceString for &Z80Span {
    fn as_str(&self) -> &str {
        self.as_ref()
    }
}

impl SourceString for Z80Span {
    fn as_str(&self) -> &str {
        self.as_ref()
    }
}

impl SourceString for &String {
    fn as_str(&self) -> &str {
        self.as_ref()
    }
}

impl SourceString for &SmolStr {
    fn as_str(&self) -> &str {
        self.as_ref()
    }
}

impl SourceString for SmolStr {
    fn as_str(&self) -> &str {
        self.as_ref()
    }
}

impl Z80Span {
    #[inline]
    pub fn complete_source(&self) -> &str {
        self.0.state.complete_source()
    }

    /// Get the offset from the start of the string (when considered to be a array of bytes)
    #[inline]
    pub fn offset_from_start(&self) -> usize {
        let src = self.complete_source();
        let src = src.as_bstr();
        self.as_bstr().offset_from(&src)
    }

    /// Get the line and column relatively to the source start
    #[inline]
    pub fn relative_line_and_column(&self) -> (usize, usize) {
        let offset = self.offset_from_start();
        self.context().relative_line_and_column(offset)
    }

    #[inline]
    pub fn location_line(&self) -> u32 {
        self.relative_line_and_column().0 as _
    }

    /// Get the full line from the whole source code that contains the following span
    #[inline]
    pub fn complete_line(&self) -> &str {
        let offset = self.offset_from_start();
        let range = self.complete_source().find_line_range(offset);
        let line = &self.complete_source().as_bytes()[range.start..range.end];
        unsafe { std::str::from_utf8_unchecked(line) }
    }

    #[inline]
    pub fn get_line_beginning(&self) -> &str {
        self.complete_line()
    }

    #[inline]
    pub fn filename(&self) -> &str {
        self.state
            .filename()
            .as_ref()
            .map(|p| p.as_os_str().to_str().unwrap_or("[Invalid file name]"))
            .unwrap_or_else(|| {
                self.state
                    .context_name
                    .as_ref()
                    .map(|s| s.as_ref())
                    .unwrap_or_else(|| "no file specified")
            })
    }
}

impl std::fmt::Display for Z80Span {
    // This trait requires `fmt` with this exact signature.
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        // Write strictly the first element into the supplied output
        // stream: `f`. Returns `fmt::Result` which indicates whether the
        // operation succeeded or failed. Note that `write!` uses syntax which
        // is very similar to `println!`.
        write!(f, "{}", self.as_str())
    }
}

impl std::fmt::Debug for Z80Span {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (line, column) = self.relative_line_and_column();
        write!(
            f,
            "{}:{}:{} <{}>",
            self.context()
                .current_filename
                .as_ref()
                .map(|p| p.as_str())
                .unwrap_or("<unknown filename>"),
            line,
            column,
            self.as_str()
        )
    }
}

impl From<&Z80Span> for SmolStr {
    fn from(val: &Z80Span) -> Self {
        SmolStr::from(val.as_str())
    }
}

impl From<&Z80Span> for Source {
    #[inline]
    fn from(val: &Z80Span) -> Self {
        let (line, column) = val.relative_line_and_column();

        Source::new(
            val.context()
                .current_filename
                .as_ref()
                .map(|fname| fname.as_str().to_owned())
                .unwrap_or_else(|| "<INLINE>".into()),
            line as _,
            column
        )
    }
}

// Impossible as the string MUST exist more than the span
// impl From<String> for Z80Span {
// fn from(s: String) -> Self {
// let src = Arc::new(s);
// let ctx = Arc::default();
//
// Self(LocatedSpan::new_extra(
// The string is safe on the heap
// unsafe { &*(src.as_str() as *const str) as &'static str },
// (src, ctx)
// ))
// }
// }

// check if still needed
// impl Z80Span {
// pub fn from_standard_span(
// span: LocatedSpan<&'static str, ()>,
// extra: (Arc<String>, Arc<ParserContext>)
// ) -> Self {
// {
// let _span_addr = span.fragment().as_ptr();
// let _extra_addr = extra.as_ptr();
// TODO; no idea why it fails :()
//   assert!(std::ptr::eq(span_addr, extra_addr));
// }
//
// Self(unsafe {
// LocatedSpan::new_from_raw_offset(
// span.location_offset(),
// span.location_line(),
// span.fragment(),
// extra
// )
// })
// }
// }

impl Deref for Z80Span {
    type Target = InnerZ80Span;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl DerefMut for Z80Span {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}
impl AsRef<InnerZ80Span> for Z80Span {
    #[inline]
    fn as_ref(&self) -> &InnerZ80Span {
        self.deref()
    }
}

impl Z80Span {
    pub fn new_extra<S: ?Sized + AsRef<[u8]>>(src: &S, ctx: &ParserContext) -> Self {
        let src = unsafe { std::mem::transmute(BStr::new(src)) };
        let ctx = unsafe { &*(ctx as *const ParserContext) as &'static ParserContext };

        Self(Stateful {
            input: Located::new(src),
            state: ctx
        })
    }

    pub fn context(&self) -> &ParserContext {
        self.state
    }
}

impl Z80Span {
    // Used when the state is changing (it controls the parsing)
    // pub fn clone_with_state(&self, state: ParsingState) -> Self {
    // eprintln!("Z80Span::clone_with_state used. Need to check if it could be done differently as the state is supposed to be hold by the listing");
    // let ctx = self.context().clone_with_state(state);
    // let mut clone = self.clone();
    // clone.extra =  w(ctx);
    // clone
    // }
    pub fn state(&self) -> &ParsingState {
        self.context().state()
    }
}