1use std::collections::BTreeMap;
2
3use glam::{Vec3, Mat4};
4use themelios::text::{Text, TextSegment};
5use themelios::types::*;
6use themelios::lookup::Lookup;
7
8use super::diag::*;
9use super::lex::{Line, Token, TextToken};
10use crate::span::{Spanned as S, Span};
12
13pub mod scena;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum FileType {
17 Scena,
18}
19
20#[derive(Debug, Copy, Clone, PartialEq, Eq)]
21pub enum Unit {
22 None,
23 Mm,
24 MmPerS,
25 Ms,
26 Deg,
27 DegPerS,
28 MDeg,
29}
30
31#[derive(Clone, Copy)]
32pub struct Context<'a> {
33 pub game: Game,
34 pub ty: FileType,
35 pub lookup: &'a dyn Lookup,
36}
37
38impl<'a> std::fmt::Debug for Context<'a> {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 f.debug_struct("Context")
41 .field("game", &self.game)
42 .field("ty", &self.ty)
43 .field("lookup", &format_args!("_"))
44 .finish()
45 }
46}
47
48#[derive(Debug, Clone)]
49pub struct Error;
50type Result<T, E=Error> = std::result::Result<T, E>;
51
52macro test {
53 ($q:expr, $p:pat $(if $e:expr)? => $v:expr) => {
54 $q.next_if(|a| {
55 match a {
56 $p $(if $e)? => Some($v),
57 _ => None
58 }
59 })
60 },
61 ($q:expr, $p:pat $(if $e:expr)? ) => {
62 test!($q, $p $(if $e)? => ()).is_some()
63 },
64}
65
66#[derive(Clone, Debug)]
67pub struct Parse<'a> {
68 tokens: &'a [S<Token<'a>>],
69 pos: usize,
70 body: Option<&'a [Line<'a>]>,
71 context: &'a Context<'a>,
72 eol: Span,
73}
74
75impl<'a> Parse<'a> {
76 fn new(line: &'a Line, context: &'a Context) -> Self {
77 Parse {
78 tokens: &line.head,
79 pos: 0,
80 body: line.body.as_deref(),
81 context,
82 eol: line.eol,
83 }
84 }
85
86 fn new_inner(tokens: &'a [S<Token<'a>>], eol: Span, context: &'a Context) -> Self {
87 Parse {
88 tokens,
89 pos: 0,
90 body: None,
91 context,
92 eol,
93 }
94 }
95
96 fn parse_comma<T: ValComma>(mut self) -> Result<T> {
97 let v = T::parse_comma(&mut self)?;
98 self.finish();
99 Ok(v)
100 }
101
102 fn parse_with<T>(mut self, f: impl FnOnce(&mut Parse) -> T) -> T {
103 let v = f(&mut self);
104 self.finish();
105 v
106 }
107
108 fn finish(&self) {
109 if self.pos < self.tokens.len() {
110 Diag::error(self.tokens[self.pos].0, "expected end of data").emit();
111 }
112
113 if self.body.is_some() {
114 Diag::error(self.eol, "body not expected here").emit();
115 }
116 }
117
118 fn body(&mut self) -> &'a [Line<'a>] {
119 match self.body.take() {
120 Some(a) => a,
121 None => {
122 Diag::error(self.eol, "expected a body").emit();
123 &[]
124 },
125 }
126 }
127
128 fn space(&self) -> Option<Span> {
129 if self.pos == 0 { return None }
130 if self.pos == self.tokens.len() { return None }
131 let s0 = self.tokens[self.pos-1].0;
132 let s1 = self.tokens[self.pos].0;
133 if s0.connects(s1) {
134 None
135 } else {
136 Some(s0.at_end() | s1.at_start())
137 }
138 }
139
140 fn head_span(&self) -> Span {
141 self.tokens.get(0).map_or(self.eol, |a| a.0 | self.eol)
142 }
143
144 fn prev_span(&self) -> Span {
145 if self.pos == 0 {
146 self.next_span().at_start()
147 } else {
148 self.tokens[self.pos-1].0
149 }
150 }
151
152 fn next_span(&self) -> Span {
153 self.tokens.get(self.pos).map_or(self.eol, |a| a.0)
154 }
155
156 fn next_if<T>(&mut self, f: impl FnOnce(&'a Token<'a>) -> Option<T>) -> Option<T> {
157 if let Some(S(_, t)) = self.tokens.get(self.pos) && let Some(x) = f(t) {
158 self.pos += 1;
159 Some(x)
160 } else {
161 None
162 }
163 }
164
165 fn word(&mut self, name: &str) -> bool {
166 test!(self, Token::Ident(a) if *a == name)
167 }
168
169 fn tuple<T: ValComma>(&mut self) -> Result<Option<T>> {
170 if let Some(d) = test!(self, Token::Paren(d) => d) {
171 Parse::new_inner(&d.tokens, d.close, self.context).parse_comma().map(Some)
172 } else {
173 Ok(None)
174 }
175 }
176
177 fn term<T: ValComma>(&mut self, name: &str) -> Result<Option<T>> {
178 if self.word(name) {
179 let space = self.space();
180 if let Some(d) = test!(self, Token::Bracket(d) => d) {
181 if let Some(s) = space {
182 Diag::error(s, "no space allowed here").emit()
183 }
184 if d.tokens.is_empty() {
185 Diag::error(d.open | d.close, "this cannot be empty")
186 .note(d.open | d.close, "maybe remove the brackets?")
187 .emit()
188 }
189 Parse::new_inner(&d.tokens, d.close, self.context).parse_comma().map(Some)
190 } else {
191 Parse::new_inner(&[], self.prev_span().at_end(), self.context).parse_comma().map(Some)
192 }
193 } else {
194 Ok(None)
195 }
196 }
197
198 fn remaining(&self) -> &'a [S<Token<'a>>] {
199 &self.tokens[self.pos..]
200 }
201}
202
203trait Val: Sized {
204 fn parse(p: &mut Parse) -> Result<Self>;
205}
206
207trait TryVal: Sized {
208 fn desc() -> String;
209
210 fn try_parse(p: &mut Parse) -> Result<Option<Self>>;
211}
212
213impl<T: TryVal> Val for T {
214 fn parse(p: &mut Parse) -> Result<Self> {
215 if let Some(v) = Self::try_parse(p)? {
216 Ok(v)
217 } else {
218 Diag::error(p.next_span(), format_args!("expected {}", Self::desc())).emit();
219 Err(Error)
220 }
221 }
222}
223
224trait ValComma: Sized {
225 fn parse_comma(p: &mut Parse) -> Result<Self>;
226}
227
228impl<T: TryVal> TryVal for S<T> {
229 fn desc() -> String { T::desc() }
230
231 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
232 let p1 = p.pos;
233 let v = T::try_parse(p)?;
234 let p2 = p.pos;
235 let s = if p1 == p2 {
236 p.next_span().at_start()
237 } else {
238 p.tokens[p1].0 | p.tokens[p2-1].0
239 };
240 Ok(v.map(|a| S(s, a)))
241 }
242}
243
244macro tuple($($T:ident)*) {
245 #[allow(non_snake_case)]
246 impl<$($T: Val),*> Val for ($($T,)*) {
247 fn parse(_p: &mut Parse) -> Result<Self> {
248 Ok(($($T::parse(_p)?,)*))
249 }
250 }
251
252 #[allow(non_snake_case)]
253 impl<$($T: Val),*> ValComma for ($($T,)*) {
254 fn parse_comma(_p: &mut Parse) -> Result<Self> {
255 $(
256 let $T = $T::parse(_p)?;
257 if _p.pos < _p.tokens.len() && !test!(_p, Token::Comma) {
258 Diag::error(_p.next_span().at_start(), "expected comma").emit();
259 }
260 )*
261 Ok(($($T,)*))
262 }
263 }
264}
265
266tuple!();
267tuple!(A);
268tuple!(A B);
269tuple!(A B C);
270tuple!(A B C D);
271
272impl<T: TryVal> Val for Vec<T> {
273 fn parse(p: &mut Parse) -> Result<Self> {
274 let mut v = Vec::new();
275 while let Some(a) = T::try_parse(p)? {
276 v.push(a);
277 }
278 Ok(v)
279 }
280}
281
282impl<const N: usize, T: Val> Val for [T; N] {
283 fn parse(p: &mut Parse) -> Result<Self> {
284 [(); N].try_map(|()| T::parse(p))
285 }
286}
287
288impl<T: TryVal> TryVal for Option<T> {
289 fn desc() -> String { format!("{}, 'null'", T::desc()) }
290
291 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
292 if let Some(()) = p.term("null")? {
293 Ok(Some(None))
294 } else {
295 T::try_parse(p).map(Some)
296 }
297 }
298}
299
300fn parse_unit(p: &mut Parse) -> Result<S<Unit>> {
301 let s0 = p.prev_span().at_end();
302 let (s, u1, u2) = match p.remaining() {
303 [S(s1, Token::Ident(u1)), S(s2, Token::Slash), S(s3, Token::Ident(u2)), ..]
304 if s0.connects(*s1) && s1.connects(*s2) && s2.connects(*s3) => {
305 let v = (*s1 | *s3, *u1, Some(*u2));
306 p.pos += 3;
307 v
308 }
309 [S(s1, Token::Ident(u1)), ..]
310 if s0.connects(*s1) => {
311 let v = (*s1, *u1, None);
312 p.pos += 1;
313 v
314 }
315 _ => return Ok(S(s0, Unit::None))
316 };
317 let u = match (u1, u2) {
318 ("mm", None) => Unit::Mm,
319 ("mm", Some("s")) => Unit::MmPerS,
320 ("ms", None) => Unit::Ms,
321 ("deg", None) => Unit::Deg,
322 ("deg", Some("s")) => Unit::DegPerS,
323 ("mdeg", None) => Unit::MDeg,
324 _ => {
325 Diag::error(s, "invalid unit").emit();
326 return Err(Error)
327 }
328 };
329 Ok(S(s, u))
330}
331
332fn parse_int(p: &mut Parse) -> Result<Option<(S<i64>, S<Unit>)>> {
333 match p.remaining() {
334 [S(s, Token::Int(n)), ..] => {
335 p.pos += 1;
336 Ok(Some((S(*s, *n as i64), parse_unit(p)?)))
337 }
338 [S(s1, Token::Minus), S(s, Token::Int(n)), ..] if s1.connects(*s) => {
339 p.pos += 2;
340 Ok(Some((S(*s1 | *s, -(*n as i64)), parse_unit(p)?)))
341 }
342 _ => {
343 Ok(None)
344 }
345 }
346}
347
348fn parse_float(p: &mut Parse) -> Result<Option<(S<f64>, S<Unit>)>> {
349 match p.remaining() {
350 [S(s, Token::Float(n)), ..] => {
351 p.pos += 1;
352 Ok(Some((S(*s, *n), parse_unit(p)?)))
353 }
354 [S(s1, Token::Minus), S(s, Token::Float(n)), ..] if s1.connects(*s) => {
355 p.pos += 2;
356 Ok(Some((S(*s1 | *s, -*n), parse_unit(p)?)))
357 }
358 _ => {
359 Ok(None)
360 }
361 }
362}
363
364macro int($T:ident) {
365 impl TryVal for $T {
366 fn desc() -> String { "int".to_owned() }
367
368 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
369 if let Some((s, u)) = parse_int(p)? {
370 if u.1 != Unit::None {
371 Diag::warn(u.0, "this should be unitless").emit();
372 }
373 let v = s.1.try_into().map_err(|e| {
374 Diag::error(s.0, e).emit();
375 Error
376 })?;
377 Ok(Some(v))
378 } else {
379 Ok(None)
380 }
381 }
382 }
383}
384
385macro newtype_val($T:ident) {
386 impl TryVal for $T {
387 fn desc() -> String { "int".to_owned() }
388
389 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
390 let v = TryVal::try_parse(p)?;
391 Ok(v.map($T))
392 }
393 }
394}
395
396int!(u8);
397int!(u16);
398int!(u32);
399int!(u64);
400int!(i8);
401int!(i16);
402int!(i32);
403int!(i64);
404
405newtype_val!(SystemFlags);
406newtype_val!(CharFlags);
407newtype_val!(QuestFlags);
408newtype_val!(ObjectFlags);
409newtype_val!(LookPointFlags);
410newtype_val!(TriggerFlags);
411newtype_val!(EntryFlags);
412
413newtype_val!(Color);
414newtype_val!(TcMembers);
415
416newtype_val!(QuestTask);
417
418impl TryVal for String {
419 fn desc() -> String { "string".to_owned() }
420
421 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
422 if let Some(s) = test!(p, Token::String(s) => s) {
423 Ok(Some(s.to_owned()))
424 } else {
425 Ok(None)
426 }
427 }
428}
429
430impl TryVal for TString {
431 fn desc() -> String { "string".to_owned() }
432
433 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
434 if let Some(s) = test!(p, Token::String(s) => s) {
435 Ok(Some(TString(s.to_owned())))
436 } else {
437 Ok(None)
438 }
439 }
440}
441
442impl TryVal for Text {
443 fn desc() -> String { "dialogue text".to_owned() }
444
445 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
446 let mut pages = Vec::new();
447 while let Some(d) = test!(p, Token::Brace(s) => s) {
448 pages.push(parse_text_chunk(p.context, &d.tokens));
449 }
450 Ok(Some(Text(pages)))
451 }
452}
453
454fn parse_text_chunk(ctx: &Context, d: &[S<TextToken>]) -> Vec<themelios::text::TextSegment> {
455 let mut out = Vec::new();
456 for S(_, t) in d {
457 match t {
458 TextToken::Text(s) => {
459 out.push(TextSegment::String(s.to_owned()))
460 }
461 TextToken::Newline => {
462 out.push(TextSegment::Line)
463 }
464 TextToken::Brace(d) => {
465 Parse::new_inner(&d.tokens, d.close, ctx).parse_with(|p| {
466 if p.pos == p.tokens.len() {
467 return
468 }
469
470 if let Some(n) = test!(p, Token::Int(a) => *a) {
471 match n.try_into() {
472 Ok(n) => out.push(TextSegment::Byte(n)),
473 Err(e) => Diag::error(p.prev_span(), e).emit()
474 }
475 return
476 }
477
478 let Some(key) = test!(p, Token::Ident(a) => a) else {
479 Diag::error(p.next_span(), "expected word").emit();
480 p.pos = p.tokens.len();
481 return;
482 };
483 if test!(p, Token::Bracket(_)) {
484 p.pos -= 2;
485 }
486
487 match *key {
488 "wait" => {
489 out.push(TextSegment::Wait)
490 }
491 "color" => {
492 if let Some(c) = test!(p, Token::Int(i) if *i <= 255 => *i) {
493 out.push(TextSegment::Color(c as u8))
494 } else {
495 Diag::error(p.next_span(), "expected u8").emit();
496 p.pos = p.tokens.len();
497 }
498 }
499 "item" => {
500 if let Ok(c) = ItemId::parse(p) {
501 out.push(TextSegment::Item(c))
502 }
503 }
504 _ => {
505 Diag::error(p.prev_span(), "expected u8, 'wait', 'color', 'item'").emit();
506 }
507 }
508 })
509 }
510 }
511 }
512 out
513}
514
515macro unit($T:ident, $unit:ident, $unit_str:literal) {
516 impl TryVal for $T {
517 fn desc() -> String { format!("'{}' number", $unit_str) }
518
519 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
520 if let Some((s, u)) = parse_int(p)? {
521 if u.1 != Unit::$unit {
522 Diag::warn(u.0, format_args!("unit should be '{}'", $unit_str)).emit();
523 }
524 let v = s.1.try_into().map_err(|e| {
525 Diag::error(s.0, e).emit();
526 Error
527 })?;
528 Ok(Some(Self(v)))
529 } else {
530 Ok(None)
531 }
532 }
533 }
534}
535
536unit!(Angle, Deg, "deg");
537unit!(AngularSpeed, DegPerS, "deg/s");
538unit!(Angle32, MDeg, "mdeg");
539unit!(Time, Ms, "ms");
540unit!(Length, Mm, "mm");
541unit!(Speed, MmPerS, "mm/s");
542
543impl TryVal for f32 {
544 fn desc() -> String { "float".to_owned() }
545
546 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
547 if let Some((s, u)) = parse_float(p)? {
548 if u.1 != Unit::None {
549 Diag::warn(u.0, "this should be unitless").emit();
550 }
551 Ok(Some(s.1 as f32))
552 } else if let Some((s, u)) = parse_int(p)? {
553 if u.1 != Unit::None {
554 Diag::warn(u.0, "this should be unitless").emit();
555 }
556 Ok(Some(s.1 as f32))
557 } else {
558 Ok(None)
559 }
560 }
561}
562
563impl TryVal for Pos3 {
564 fn desc() -> String { "pos3".to_owned() }
565
566 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
567 if let Some((x, y, z)) = p.tuple()? {
568 Ok(Some(Pos3 { x, y, z }))
569 } else {
570 Ok(None)
571 }
572 }
573}
574
575struct Null;
576impl TryVal for Null {
577 fn desc() -> String { "'null'".to_owned() }
578
579 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
580 if let Some(()) = p.term("null")? {
581 Ok(Some(Null))
582 } else {
583 Ok(None)
584 }
585 }
586}
587
588impl TryVal for Pos2 {
589 fn desc() -> String { "pos2".to_owned() }
590
591 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
592 if let Some((x, Null, z)) = p.tuple()? {
593 Ok(Some(Pos2 { x, z }))
594 } else {
595 Ok(None)
596 }
597 }
598}
599
600impl TryVal for Vec3 {
601 fn desc() -> String { "pos3".to_owned() }
602
603 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
604 if let Some((x, y, z)) = p.tuple()? {
605 Ok(Some(Vec3 { x, y, z }))
606 } else {
607 Ok(None)
608 }
609 }
610}
611
612impl Val for Mat4 {
613 fn parse(p: &mut Parse) -> Result<Self> {
614 let v = <[f32; 16]>::parse(p)?;
615 Ok(Mat4::from_cols_array(&v).transpose())
616 }
617}
618
619impl TryVal for FuncId {
620 fn desc() -> String { "'fn'".to_owned() }
621
622 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
623 if let Some((a, b)) = p.term("fn")? {
624 Ok(Some(FuncId(a, b)))
625 } else {
626 Ok(None)
627 }
628 }
629}
630
631impl TryVal for CharAttr {
632 fn desc() -> String { CharId::desc() }
633
634 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
635 if let Some(chid) = CharId::try_parse(p)? {
636 if let Some(s) = p.space() {
637 Diag::error(s, "no space allowed here").emit()
638 }
639 if !test!(p, Token::Dot) {
640 Diag::error(p.next_span().at_start(), "expected dot").emit();
641 }
642 if let Some(s) = p.space() {
643 Diag::error(s, "no space allowed here").emit()
644 }
645 let n = u8::parse(p)?;
646 Ok(Some(CharAttr(chid, n)))
647 } else {
648 Ok(None)
649 }
650 }
651}
652
653impl TryVal for FileId {
654 fn desc() -> String { "string, 'null', 'file'".to_owned() }
655
656 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
657 if let Some(s) = test!(p, Token::String(s) => s) {
658 Ok(Some(FileId(p.context.lookup.index(s).unwrap_or_else(|| {
659 Diag::error(p.prev_span(), "could not resolve file id").emit();
660 0x00000000
661 }))))
662 } else if let Some(()) = p.term("null")? {
663 Ok(Some(FileId(0)))
664 } else if let Some((s,)) = p.term("file")? {
665 Ok(Some(FileId(s)))
666 } else {
667 Ok(None)
668 }
669 }
670}
671
672impl TryVal for CharId {
673 fn desc() -> String { "'self', 'null', 'name', 'char', 'field_party', 'party', 'custom'".to_owned() }
674
675 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
676 let span = p.next_span();
677 if let Some(()) = p.term("self")? {
678 Ok(Some(CharId::Self_))
679 } else if let Some(()) = p.term("null")? {
680 Ok(Some(CharId::Null))
681 } else if let Some(n) = NameId::try_parse(p)? {
682 Ok(Some(CharId::Name(n)))
683 } else if let Some(l) = LocalCharId::try_parse(p)? {
684 Ok(Some(CharId::Local(l)))
685 } else if let Some((s,)) = p.term::<(u16,)>("field_party")? {
686 Ok(Some(CharId::FieldParty(s)))
687 } else if let Some((s,)) = p.term::<(u16,)>("party")? {
688 Ok(Some(CharId::Party(s)))
689 } else if let Some((s,)) = p.term::<(u16,)>("custom")? {
690 if p.context.game.base() != BaseGame::Ao {
691 Diag::error(span, "'custom' is only supported on Azure").emit();
692 }
693 Ok(Some(CharId::Custom(s)))
694 } else {
695 Ok(None)
696 }
697 }
698}
699
700macro newtype($T:ident, $s:literal) {
701 impl TryVal for $T {
702 fn desc() -> String { format!("'{}'", $s) }
703
704 fn try_parse(p: &mut Parse) -> Result<Option<Self>> {
705 if let Some((v,)) = p.term($s)? {
706 Ok(Some(Self(v)))
707 } else {
708 Ok(None)
709 }
710 }
711 }
712}
713
714newtype!(Flag, "flag");
715newtype!(Attr, "system");
716newtype!(Var, "var");
717newtype!(Global, "global");
718
719newtype!(NameId, "name");
720newtype!(BgmId, "bgm");
721newtype!(MagicId, "magic");
722newtype!(QuestId, "quest");
723newtype!(ShopId, "shop");
724newtype!(SoundId, "sound");
725newtype!(TownId, "town");
726newtype!(BattleId, "battle");
727newtype!(ItemId, "item");
728
729newtype!(LocalCharId, "char");
730newtype!(LookPointId, "look_point");
731newtype!(EntranceId, "entrance");
732newtype!(ObjectId, "object");
733newtype!(TriggerId, "trigger");
734newtype!(LabelId, "label");
735newtype!(AnimId, "anim");
736
737newtype!(ChipId, "chip");
738newtype!(VisId, "vis");
739newtype!(ForkId, "fork");
740newtype!(EffId, "eff");
741newtype!(EffInstanceId, "eff_instance");
742newtype!(MenuId, "menu");
743
744macro when {
745 ($t1:tt) => {},
746 ($t1:tt, $($t:tt)*) => { $($t)* }
747}
748macro unless {
749 (, {$($v:tt)*}) => { $($v)* },
750 ({$($t:tt)*},{$($v:tt)*}) => { $($t)* },
751}
752
753macro parse_data($d:ident => { $($k:ident $(=> $e:expr)?),* $(,)? }) {
754 $(unless!($({when!($e);})?, {
755 let mut $k = One::default();
756 });)*
757
758 for line in $d.body() {
759 Parse::new(line, $d.context).parse_with(|p| {
760 let Some(key) = test!(p, Token::Ident(a) => a) else {
761 Diag::error(p.next_span(), "expected word").emit();
762 return
763 };
764 match *key {
765 $(stringify!($k) => {
766 unless!($({
767 let v: Result<()> = $e(p);
768 if v.is_err() {
769 p.pos = p.tokens.len();
770 }
771 })?, {
772 $k.mark(p.prev_span());
773 match Val::parse(p) {
774 Ok(v) => $k.set(v),
775 Err(_) => p.pos = p.tokens.len()
776 }
777 });
778 })*
779 _ => {
780 let fields: &[&str] = &[
781 $(concat!("'", stringify!($k), "'"),)*
782 ];
783 Diag::error(p.prev_span(), "unknown field")
784 .note(p.prev_span(), format_args!("allowed fields are {}", &fields.join(", ")))
785 .emit();
786 p.pos = p.tokens.len();
787 }
788 }
789 })
790 }
791
792 #[allow(unused_mut)]
793 let mut failures: Vec<&str> = Vec::new();
794 $(unless!($({when!($e);})?, {
795 if !$k.is_present() {
796 failures.push(concat!("'", stringify!($k), "'"));
797 }
798 });)*
799
800 if !failures.is_empty() {
801 Diag::error($d.head_span(), "missing fields")
802 .note($d.head_span(), failures.join(", "))
803 .emit();
804 Err(Error)?;
805 unreachable!()
806 }
807
808 $(unless!($({when!($e);})?, {
809 let Some($k) = $k.get() else { Err(Error)?; unreachable!() };
810 });)*
811}
812
813fn parse_type(line: &Line) -> Result<(Game, FileType)> {
814 let dummy_ctx = &Context {
815 game: Game::Fc,
816 ty: FileType::Scena,
817 lookup: &themelios::lookup::NullLookup,
818 };
819 Parse::new(line, dummy_ctx).parse_with(|p| {
820 if !p.word("calmare") {
821 Diag::error(p.prev_span(), "expected 'calmare'").emit();
822 return Err(Error);
823 }
824 let Some(a) = test!(p, Token::Ident(a) => a) else {
825 Diag::error(p.prev_span(), "expected a game").emit();
826 return Err(Error);
827 };
828 let Some(b) = test!(p, Token::Ident(a) => a) else {
829 Diag::error(p.prev_span(), "expected a type").emit();
830 return Err(Error);
831 };
832 let game = match *a {
833 "fc" => Game::Fc, "fc_e" => Game::FcEvo, "fc_k" => Game::FcKai,
834 "sc" => Game::Sc, "sc_e" => Game::ScEvo, "sc_k" => Game::ScKai,
835 "tc" => Game::Tc, "tc_e" => Game::TcEvo, "tc_k" => Game::TcKai,
836 "zero" => Game::Zero, "zero_e" => Game::ZeroEvo, "zero_k" => Game::ZeroKai,
837 "ao" => Game::Ao, "ao_e" => Game::AoEvo, "ao_k" => Game::AoKai,
838 _ => {
839 Diag::error(p.prev_span(), "unknown game").emit();
840 return Err(Error);
841 }
842 };
843 let ty = match *b {
844 "scena" => FileType::Scena,
845 _ => {
846 Diag::error(p.prev_span(), "unknown file type").emit();
847 return Err(Error);
848 }
849 };
850 Ok((game, ty))
851 })
852}
853
854#[derive(Debug, Clone)]
855struct One<T>(Option<S<Option<T>>>);
856
857impl<T> Default for One<T> {
858 fn default() -> Self {
859 Self(None)
860 }
861}
862
863impl<T> One<T> {
864 fn mark(&mut self, s: Span) {
865 if let Some(S(prev, _)) = &self.0 {
866 Diag::error(s, "duplicate item")
867 .note(*prev, "previous here")
868 .emit();
869 }
870 self.0 = Some(S(s, None));
871 }
872
873 fn set(&mut self, v: T) {
874 if let Some(S(_, q)) = &mut self.0 {
875 *q = Some(v)
876 } else {
877 panic!("not marked")
878 }
879 }
880
881 fn is_present(&self) -> bool {
882 self.0.is_some()
883 }
884
885 fn get(self) -> Option<T> {
886 match self.0 {
887 Some(S(_, Some(v))) => Some(v),
888 _ => None,
889 }
890 }
891}
892
893#[derive(Debug, Clone)]
894struct Many<K, V>(BTreeMap<K, S<Option<V>>>);
895
896impl<K, V> Default for Many<K, V> {
897 fn default() -> Self {
898 Self(Default::default())
899 }
900}
901
902impl<K: Ord, V> Many<K, V> {
903 fn mark(&mut self, s: Span, n: K) {
904 if let Some(S(prev, _)) = self.0.insert(n, S(s, None)) {
905 Diag::error(s, "duplicate item")
906 .note(prev, "previous here")
907 .emit();
908 }
909 }
910
911 fn insert(&mut self, n: K, v: V) {
912 if let Some(S(_, q)) = self.0.get_mut(&n) {
913 *q = Some(v)
914 } else {
915 panic!("not marked")
916 }
917 }
918
919 fn get(self, f: impl Fn(K) -> usize) -> Vec<V> {
920 let mut vs = Vec::with_capacity(self.0.len());
921 let mut expect = 0;
922 for (k, S(s, v)) in self.0 {
923 let k = f(k);
924 if k != expect {
925 Diag::error(s, "gap in list")
926 .note(s, format_args!("missing index {expect}"))
927 .emit();
928 }
929 expect = k + 1;
930 vs.extend(v)
931 }
932 vs
933 }
934}
935
936pub fn parse(lines: &[Line], lookup: Option<&dyn Lookup>) -> Result<(Game, crate::Content)> {
937 if lines.is_empty() {
938 Diag::error(Span::new_at(0), "no type declaration").emit();
939 return Err(Error);
940 }
941
942 let (game, ty) = parse_type(&lines[0])?;
943 let ctx = &Context {
944 game,
945 ty,
946 lookup: lookup.unwrap_or_else(|| themelios::lookup::default_for(game)),
947 };
948
949 match ty {
950 FileType::Scena => {
951 if game.is_ed7() {
952 Ok((game, crate::Content::ED7Scena(scena::ed7::parse(&lines[1..], ctx)?)))
953 } else {
954 Ok((game, crate::Content::ED6Scena(scena::ed6::parse(&lines[1..], ctx)?)))
955 }
956 }
957 }
958}
959
960
961#[test]
962fn main() {
963 let src = include_str!("/tmp/kiseki/ao_gf_en/c1200");
964 let (v, diag) = super::diag::diagnose(|| {
965 let tok = crate::parse::lex::lex(src);
966 parse(&tok, None)
967 });
968 println!("{:#?}", v);
969 super::diag::print_diags("<input>", src, &diag);
970}