1use std::str::pattern::Pattern;
2use crate::span::{Spanned, Span};
3use super::diag::Diag;
4
5use unicode_xid::UnicodeXID;
6
7pub fn range_of<T>(slice: &[T], subslice: &[T]) -> Option<std::ops::Range<usize>> {
9 let range = slice.as_ptr_range();
10 let subrange = subslice.as_ptr_range();
11 if subrange.start >= range.start && subrange.end <= range.end {
12 unsafe {
13 Some(std::ops::Range {
14 start: subrange.start.offset_from(range.start) as usize,
15 end: subrange.end.offset_from(range.start) as usize,
16 })
17 }
18 } else {
19 None
20 }
21}
22
23#[derive(Debug, Clone, Copy, Eq)]
24struct Indent<'a>(&'a str);
25
26impl<'a, 'b> PartialEq<Indent<'b>> for Indent<'a> {
27 fn eq(&self, other: &Indent<'b>) -> bool {
28 self.0 == other.0
29 }
30}
31
32impl<'a, 'b> PartialOrd<Indent<'b>> for Indent<'a> {
33 fn partial_cmp(&self, other: &Indent<'b>) -> Option<std::cmp::Ordering> {
34 use std::cmp::Ordering::*;
35 let a = self.0;
36 let b = other.0;
37 if a == b {
38 Some(Equal)
39 } else if a.starts_with(b) {
40 Some(Greater)
41 } else if b.starts_with(a) {
42 Some(Less)
43 } else {
44 None
45 }
46 }
47}
48
49impl<'a, 'b> PartialEq<Indent<'b>> for Option<Indent<'a>> {
50 fn eq(&self, other: &Indent<'b>) -> bool {
51 self.as_ref().map_or(false, |a| a == other)
52 }
53}
54
55impl<'a, 'b> PartialOrd<Indent<'b>> for Option<Indent<'a>> {
56 fn partial_cmp(&self, other: &Indent<'b>) -> Option<std::cmp::Ordering> {
57 use std::cmp::Ordering::*;
58 self.as_ref().map_or(Some(Greater), |a| a.partial_cmp(other))
59 }
60}
61
62#[derive(Clone)]
63struct Lex<'a> {
64 src: &'a str,
65 pos: &'a str,
66 last_indent: Option<Indent<'a>>,
67}
68
69impl<'a> Lex<'a> {
70 fn new(src: &'a str) -> Self {
71 let mut new = Lex {
72 src,
73 pos: src,
74 last_indent: None,
75 };
76 new.space();
77 if new.last_indent.is_none() {
78 new.last_indent = Some(Indent(""));
79 }
80 new
81 }
82
83 fn is_empty(&self) -> bool {
84 self.pos.is_empty()
85 }
86
87 fn pos(&self) -> Span {
91 let r = range_of(self.src.as_bytes(), self.pos.as_bytes()).unwrap();
92 Span::new_at(r.start)
93 }
94
95 fn pat_<P: Pattern + 'a>(&mut self, p: P) -> Option<Span> {
96 let i0 = self.pos();
97 self.pos = self.pos.strip_prefix(p)?;
98 self.last_indent = None;
99 Some(i0 | self.pos())
100 }
101
102 fn pat<P: Pattern + 'a>(&mut self, p: P) -> Option<&'a str> {
103 self.pat_(p).map(|s| self.span_text(s))
104 }
105
106 fn pat_mul<P: Pattern + Clone + 'a>(&mut self, p: P) -> &'a str {
107 let mut s = self.pos();
108 while let Some(s1) = self.pat_(p.clone()) {
109 s |= s1;
110 }
111 self.span_text(s)
112 }
113
114 fn any(&mut self) -> Option<char> {
115 self.pat(|_| true).map(|a| a.chars().next().unwrap())
116 }
117
118 fn span_text(&self, s: Span) -> &'a str {
119 &self.src[s.as_range()]
120 }
121
122 fn space(&mut self) -> Option<Indent<'a>> {
123 if self.last_indent.is_none() {
124 self.space_inner();
125 while self.pat('\n').is_some() {
126 self.last_indent = Some(self.space_inner())
127 }
128 if self.is_empty() {
129 self.last_indent = Some(Indent(""))
130 }
131 }
132 self.last_indent
133 }
134
135 fn space_inner(&mut self) -> Indent<'a> {
136 let i0 = self.pos();
137 self.pat_mul([' ', '\t']);
138 if self.pat("//").is_some() {
139 self.pat_mul(|c| c != '\n');
140 }
141 Indent(self.span_text(i0 | self.pos()))
142 }
143
144 fn clear_space(&mut self) {
145 self.last_indent = None;
146 }
147}
148
149enum Number {
150 Int(u64),
151 Float(f64),
152}
153
154fn number(i: &mut Lex) -> Option<Number> {
155 i.clone().pat(|c| char::is_ascii_digit(&c))?;
156 let i0 = i.pos();
157
158 Some(if i.pat("0x").is_some() {
159 let s = i.pat_mul(UnicodeXID::is_xid_continue);
160 match u64::from_str_radix(s, 16) {
161 Ok(v) => Number::Int(v),
162 Err(e) => {
163 Diag::error(i0 | i.pos(), e).emit();
164 Number::Int(0)
165 }
166 }
167 } else {
168 i.pat_mul(|a| char::is_ascii_digit(&a));
169 if i.pat('.').is_some() {
170 i.pat_mul(|a| char::is_ascii_digit(&a));
171 let s = i.span_text(i0|i.pos());
172 match s.parse::<f64>() {
173 Ok(v) => Number::Float(v),
174 Err(e) => {
175 Diag::error(i0 | i.pos(), e).emit();
176 Number::Float(0.)
177 }
178 }
179 } else {
180 let s = i.span_text(i0|i.pos());
181 match s.parse::<u64>() {
182 Ok(v) => Number::Int(v),
183 Err(e) => {
184 Diag::error(i0 | i.pos(), e).emit();
185 Number::Int(0)
186 }
187 }
188 }
189 })
190}
191
192fn ident<'a>(i: &mut Lex<'a>) -> Option<&'a str> {
193 i.clone().pat(|c| UnicodeXID::is_xid_start(c) || c == '_')?;
194 Some(i.pat_mul(UnicodeXID::is_xid_continue))
195}
196
197fn string(i: &mut Lex) -> Option<String> {
198 let i0 = i.pos();
199 i.pat('"')?;
200 let mut s = String::new();
201 loop {
202 let i1 = i.pos();
203 match i.any() {
204 None | Some('\n') => {
205 Diag::error(i0 | i.pos(), "unterminated string").emit();
206 break;
207 }
208 Some('"') => break,
209 Some('\\') => match i.any() {
210 None | Some('\n') => {
211 Diag::error(i0 | i.pos(), "unterminated string").emit();
212 break;
213 }
214 Some('"') => s.push('"'),
215 Some('\\') => s.push('\\'),
216 _ => Diag::error(i1 | i.pos(), "invalid escape sequence").emit(),
217 },
218 Some(c) => s.push(c),
219 }
220 }
221 Some(s)
222}
223
224#[derive(Debug, Clone, PartialEq)]
225pub struct Line<'a> {
226 pub span: Span,
227 pub head: Vec<Spanned<Token<'a>>>,
228 pub eol: Span, pub body: Option<Vec<Line<'a>>>,
230}
231
232impl Line<'_> {
233 pub fn head_span(&self) -> Span {
234 if let Some(a) = self.head.first() {
235 a.0 | self.eol
236 } else {
237 self.eol
238 }
239 }
240}
241
242#[derive(Clone, PartialEq)]
243pub struct Delimited<T> {
244 pub open: Span,
245 pub tokens: Vec<Spanned<T>>,
246 pub close: Span,
247}
248
249impl<T: std::fmt::Debug> std::fmt::Debug for Delimited<T> {
250 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251 if f.alternate() {
252 self.open.fmt(f)?;
253 }
254 f.write_str("@")?;
255 self.tokens.fmt(f)?;
256 f.write_str("@")?;
257 if f.alternate() {
258 self.close.fmt(f)?;
259 }
260 Ok(())
261 }
262}
263
264#[derive(Clone, PartialEq)]
265pub enum Token<'a> {
266 Ident(&'a str),
267 Int(u64),
268 Float(f64),
269 String(String),
270 Var(&'a str),
271
272 Paren(Delimited<Token<'a>>),
273 Bracket(Delimited<Token<'a>>),
274 Brace(Delimited<TextToken<'a>>),
275
276 Comma, Dot, At, Plus, Minus, Star, Slash, Percent, Excl, Eq, Lt, Gt, Amp, Pipe, Caret, Tilde, }
294
295impl std::fmt::Debug for Token<'_> {
296 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297 match self {
298 Self::Ident(v) => { write!(f, "Ident(")?; v.fmt(f)?; write!(f, ")") }
299 Self::Int(v) => { write!(f, "Int(")?; v.fmt(f)?; write!(f, ")") }
300 Self::Float(v) => { write!(f, "Float(")?; v.fmt(f)?; write!(f, ")") }
301 Self::String(v) => { write!(f, "String(")?; v.fmt(f)?; write!(f, ")") }
302 Self::Var(v) => { write!(f, "Var(")?; v.fmt(f)?; write!(f, ")") }
303 Self::Paren(v) => { write!(f, "Paren(")?; v.fmt(f)?; write!(f, ")") }
304 Self::Bracket(v) => { write!(f, "Bracket(")?; v.fmt(f)?; write!(f, ")") }
305 Self::Brace(v) => { write!(f, "Brace(")?; v.fmt(f)?; write!(f, ")") }
306 Self::Comma => write!(f, "Comma"),
307 Self::Dot => write!(f, "Dot"),
308 Self::At => write!(f, "At"),
309 Self::Plus => write!(f, "Plus"),
310 Self::Minus => write!(f, "Minus"),
311 Self::Star => write!(f, "Star"),
312 Self::Slash => write!(f, "Slash"),
313 Self::Percent => write!(f, "Percent"),
314 Self::Excl => write!(f, "Excl"),
315 Self::Eq => write!(f, "Eq"),
316 Self::Lt => write!(f, "Lt"),
317 Self::Gt => write!(f, "Gt"),
318 Self::Amp => write!(f, "Amp"),
319 Self::Pipe => write!(f, "Pipe"),
320 Self::Caret => write!(f, "Caret"),
321 Self::Tilde => write!(f, "Tilde"),
322 }
323 }
324}
325
326#[derive(Clone, PartialEq)]
327pub enum TextToken<'a> {
328 Text(String),
329 Newline,
330 Brace(Delimited<Token<'a>>),
331}
332
333fn tokens<'a>(indent: Indent, i: &mut Lex<'a>) -> Option<Vec<Spanned<Token<'a>>>> {
334 let mut out = Vec::new();
335
336 macro test($e:expr => $f:expr) {
337 let i0 = i.pos();
338 let x = $e;
339 if let Some(x) = x {
340 let f = $f;
341 out.push(Spanned(i0 | i.pos(), f(x)));
342 continue
343 } else if i.pos() != i0 {
344 return None
345 }
346 }
347
348 i.clear_space();
349 while continue_line(indent, i) {
350 test!(ident(i) => Token::Ident);
351 test!(number(i) => |s| match s {
352 Number::Int(x) => Token::Int(x),
353 Number::Float(x) => Token::Float(x),
354 });
355 test!(string(i) => Token::String);
356
357 test!(i.pat('$').and_then(|_| ident(i)) => Token::Var);
358
359 test!(delim(indent, i, '(', tokens, ')', "parenthesis") => Token::Paren);
360 test!(delim(indent, i, '[', tokens, ']', "bracket") => Token::Bracket);
361 test!(delim(indent, i, '{', text_tokens, '}', "brace") => Token::Brace);
362
363 test!(i.pat(',') => |_| Token::Comma);
364 test!(i.pat('.') => |_| Token::Dot);
365 test!(i.pat('@') => |_| Token::At);
366
367 test!(i.pat('+') => |_| Token::Plus);
368 test!(i.pat('-') => |_| Token::Minus);
369 test!(i.pat('*') => |_| Token::Star);
370 test!(i.pat('/') => |_| Token::Slash);
371 test!(i.pat('%') => |_| Token::Percent);
372 test!(i.pat('!') => |_| Token::Excl);
373
374 test!(i.pat('=') => |_| Token::Eq);
375 test!(i.pat('<') => |_| Token::Lt);
376 test!(i.pat('>') => |_| Token::Gt);
377 test!(i.pat('&') => |_| Token::Amp);
378 test!(i.pat('|') => |_| Token::Pipe);
379 test!(i.pat('^') => |_| Token::Caret);
380 test!(i.pat('~') => |_| Token::Tilde);
381
382 break
383 }
384 Some(out)
385}
386
387impl std::fmt::Debug for TextToken<'_> {
388 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
389 match self {
390 Self::Text(v) => { write!(f, "Text(")?; v.fmt(f)?; write!(f, ")") }
391 Self::Newline => { write!(f, "Newline") }
392 Self::Brace(v) => { write!(f, "Brace(")?; v.fmt(f)?; write!(f, ")") }
393 }
394 }
395}
396
397fn text_tokens<'a>(indent: Indent, i: &mut Lex<'a>) -> Option<Vec<Spanned<TextToken<'a>>>> {
398 let mut out = Vec::new();
399
400 let p = i.pos;
401 i.pat_mul([' ', '\t']);
402 if i.pat('\n').is_some() {
403 i.last_indent = Some(Indent(i.pat_mul([' ', '\t'])));
404 } else {
405 i.pos = p;
406 }
407
408 let mut i0 = i.pos();
409 let mut s = String::new();
410
411 macro push {
412 () => {
413 if !s.is_empty() {
414 out.push(Spanned(i0 | i.pos(), TextToken::Text(s)));
415 #[allow(unused_assignments)]
416 {
417 s = String::new();
418 i0 = i.pos();
419 }
420 }
421 },
422 ($($tt:tt)*) => {
423 push!();
424 let i1 = i.pos();
425 let v = { $($tt)* };
426 out.push(Spanned(i1 | i.pos(), v));
427 i0 = i.pos();
428 }
429 }
430
431 while i.last_indent > indent || i.clone().pat_('\n').is_some() {
432 if i.clone().pat('}').is_some() {
433 break
434 }
435
436 if i.clone().pat('{').is_some() {
437 push! {
438 let body = delim(Indent("-"), i, '{', tokens, '}', "brace")?;
439 TextToken::Brace(body)
440 };
441 }
442
443 if i.clone().pat_('\n').is_some() {
444 push!();
445 let i1 = i.pos();
446 i.pat('\n');
447 i.last_indent = Some(Indent(i.pat_mul([' ', '\t'])));
448 i0 = i.pos();
449 if i.clone().pat('}').is_some() {
450 break
451 }
452 out.push(Spanned(i1 | i.pos(), TextToken::Newline));
453 }
454
455 if i.clone().pat_('\\').is_some() {
456 let i1 = i.pos();
457 i.pat('\\');
458
459 if let Some(s2) = i.pat(['\\', '{', '}']) {
460 s.push_str(s2)
461 } else if i.pat('\n').is_some() {
462 i.last_indent = Some(Indent(i.pat_mul([' ', '\t'])));
463 i0 = i.pos();
464 if i.clone().pat('}').is_some() {
465 break
466 }
467 i0 = i.pos();
468 } else {
469 Diag::error(i1 | i.pos(), "invalid escape").emit();
470 }
471 }
472
473 s.push_str(i.pat_mul(|a| !"{}\\\n".contains(a)));
474 }
475 push!();
476 Some(out)
477}
478
479fn delim<'a, T: 'a>(
480 indent: Indent,
481 i: &mut Lex<'a>,
482 c1: char,
483 tokens: fn(Indent, &mut Lex<'a>) -> Option<Vec<Spanned<T>>>,
484 c2: char,
485 name: &str,
486) -> Option<Delimited<T>> {
487 let i0 = i.pos();
488 i.pat(c1)?;
489 let open = i0 | i.pos();
490
491 let tokens = tokens(indent, i)?;
492
493 let i0 = i.pos();
494 #[allow(clippy::neg_cmp_op_on_partial_ord)]
495 if !(i.space() >= indent) && !i.is_empty() {
496 Diag::error(i0, "invalid indentation")
497 .note(open, format_args!("inside {name} opened here"))
498 .emit();
499 return None
500 } else if i.pat(c2).is_none() {
501 Diag::error(i0, format_args!("expected closing {name}"))
502 .note(open, "opened here")
503 .emit();
504 return None
505 }
506 let close = i0 | i.pos();
507 Some(Delimited {
508 open,
509 tokens,
510 close,
511 })
512}
513
514fn continue_line(indent: Indent, i: &mut Lex) -> bool {
515 let ind = i.space();
516 ind > indent || ind == indent && i.clone().pat(['{', ')', ']', '}']).is_some()
517}
518
519fn line<'a>(indent: Indent, i: &mut Lex<'a>, out: &mut Vec<Line<'a>>) {
520 let i0 = i.pos();
521 let head = tokens(indent, i).unwrap_or_default();
522
523 if i.space() <= indent || i.is_empty() {
524 if !head.is_empty() {
525 let eol = head.last().unwrap().0.at_end();
526 out.push(Line { span: i0 | i.pos(), head, eol, body: None });
527 }
528 } else {
529 let i1 = i.pos();
530 while continue_line(indent, i) && i.clone().pat([':', ';']).is_none() {
531 i.pat_mul(|a| a != '\n' && a != ':' && a != ';');
532 }
533 if i1 != i.pos() {
534 Diag::error(i1, "unexpected character").emit();
535 }
536
537 if let Some(eol) = i.pat_(':') {
538 let ind = i.space();
539 #[allow(clippy::unnecessary_unwrap)]
540 let body = if ind.is_none() {
541 let mut lines2 = Vec::new();
542 line(indent, i, &mut lines2);
543 lines2
544 } else if ind > indent {
545 lines(ind.unwrap(), i)
546 } else {
547 Vec::new()
548 };
549 out.push(Line { span: i0 | i.pos(), head, eol, body: Some(body) })
550 } else if let Some(eol) = i.pat_(';') {
551 out.push(Line { span: i0 | i.pos(), head, eol, body: None });
552 line(indent, i, out);
553 } else {
554 out.push(Line { span: i0 | i.pos(), head, eol: i1, body: None })
555 }
556 };
557}
558
559fn lines<'a>(indent: Indent, i: &mut Lex<'a>) -> Vec<Line<'a>> {
560 let mut indent_pos = i.pos();
561 let mut lines = Vec::new();
562 while {i.space(); !i.is_empty()} {
563 let ind = i.space().expect("lines() can only be called at start of line");
564 if ind > indent {
565 Diag::error(i.pos(), "unexpected indent")
568 .note(indent_pos, "should perhaps be equal to here")
569 .emit();
570 } else if ind == indent {
571 indent_pos = i.pos(); }
573
574 if ind >= indent {
575 line(ind, i, &mut lines);
576 } else {
577 break
578 }
579 }
580 lines
581}
582
583pub fn lex(src: &str) -> Vec<Line> {
584 let mut i = Lex::new(src);
585 let v = lines(Indent(""), &mut i);
586 assert!(i.is_empty());
587 v
588}
589
590#[test]
591fn main() {
592 let src = include_str!("/tmp/kiseki/tc/t1121");
593 let (ast, diag) = super::diag::diagnose(|| lex(src));
594 println!("{:#?}", ast);
595 super::diag::print_diags("<input>", src, &diag);
596}