-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli_def.rs
More file actions
1224 lines (1033 loc) · 44.2 KB
/
cli_def.rs
File metadata and controls
1224 lines (1033 loc) · 44.2 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::path::{Path, PathBuf};
use std::io;
use crate::ast::ScriptFile;
use crate::api::Truth;
use crate::game::{Game, LanguageKey};
use crate::error::ErrorReported;
use crate::llir::DecompileOptions;
pub fn main(version: &str) -> ! {
let mut args = std::env::args();
let _ = args.next();
truth_main(version, &args.collect::<Vec<_>>());
}
type EntryPoint = fn(version: &str, args: &[String]) -> !;
pub fn truth_main(version: &str, args: &[String]) -> ! {
cli::parse_subcommand(version, &args, Subcommands {
abbreviations: cli::Abbreviations::Forbid,
program: "truth-core",
choices: &[
SubcommandSpec { name: "truanm", entry: truanm_main, public: true },
SubcommandSpec { name: "trustd", entry: trustd_main, public: true },
SubcommandSpec { name: "trumsg", entry: trumsg_main, public: true },
SubcommandSpec { name: "truecl", entry: truecl_main, public: false },
// undocumented commands used for testing purposes;
// these are not easily discoverable, and may be removed any time
SubcommandSpec { name: "anm-benchmark", entry: anm_benchmark::main, public: false },
SubcommandSpec { name: "ecl-benchmark", entry: ecl_benchmark::main, public: false },
SubcommandSpec { name: "text-reformat", entry: text_reformat::main, public: false },
SubcommandSpec { name: "msg-redump", entry: msg_redump::main, public: false },
SubcommandSpec { name: "ecl-redump", entry: ecl_redump::main, public: false },
],
})
}
pub fn truecl_main(version: &str, args: &[String]) -> ! {
cli::parse_subcommand(version, &args, Subcommands {
abbreviations: cli::Abbreviations::Allow,
program: "truecl",
choices: &[
SubcommandSpec { name: "decompile", entry: ecl_decompile::main, public: true },
SubcommandSpec { name: "compile", entry: ecl_compile::main, public: true },
],
})
}
pub fn truanm_main(version: &str, args: &[String]) -> ! {
cli::parse_subcommand(version, &args, Subcommands {
abbreviations: cli::Abbreviations::Allow,
program: "truanm",
choices: &[
SubcommandSpec { name: "decompile", entry: anm_decompile::main, public: true },
SubcommandSpec { name: "compile", entry: anm_compile::main, public: true },
SubcommandSpec { name: "extract", entry: anm_extract::main, public: true },
SubcommandSpec { name: "xtract", entry: anm_extract::main, public: false }, // let 'x' work
],
})
}
pub fn trustd_main(version: &str, args: &[String]) -> ! {
cli::parse_subcommand(version, &args, Subcommands {
abbreviations: cli::Abbreviations::Allow,
program: "trustd",
choices: &[
SubcommandSpec { name: "decompile", entry: std_decompile::main, public: true },
SubcommandSpec { name: "compile", entry: std_compile::main, public: true },
],
})
}
pub fn trumsg_main(version: &str, args: &[String]) -> ! {
cli::parse_subcommand(version, &args, Subcommands {
abbreviations: cli::Abbreviations::Allow,
program: "trumsg",
choices: &[
SubcommandSpec { name: "decompile", entry: msg_decompile::main, public: true },
SubcommandSpec { name: "compile", entry: msg_compile::main, public: true },
],
})
}
pub mod text_reformat {
use super::*;
pub fn main(version: &str, argv: &[String]) -> ! {
let (input,) = cli::parse_args(version, argv, CmdSpec {
program: "truth-core text-reformat",
usage_args: "FILE [OPTIONS...]",
options: (cli::input(),),
});
wrap_exit_code(|truth| run(truth, input));
}
fn run(truth: &mut Truth, path: impl AsRef<Path>) -> Result<(), ErrorReported> {
let ast = truth.read_script(path.as_ref())?;
let stdout = io::stdout();
let mut f = crate::Formatter::new(io::BufWriter::new(stdout.lock()));
f.fmt(&ast).map_err(|e| truth.emit(error!("{:#}", e)))?;
Ok(())
}
}
pub mod anm_decompile {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (common_options, output, fmt_config) = cli::parse_args(version, args, CmdSpec {
program: "truanm decompile",
usage_args: "FILE -g GAME [OPTIONS...]",
options: (cli::common_decompile_options(), cli::output(), cli::fmt_config()),
});
wrap_decompile_to_stdout(fmt_config, output, |truth| {
decompile(truth, &common_options)
});
}
pub(super) fn decompile(
truth: &mut Truth,
common_options: &CommonDecompileOptions,
) -> Result<ScriptFile, ErrorReported> {
let &CommonDecompileOptions {
game, ref in_path, ref mapfile_options, ref decompile_options
} = common_options;
let mapfile_options = add_env_mapfile_for_decomp(mapfile_options, ".anmm");
load_mapfiles(truth, game, &[LanguageKey::Anm], &mapfile_options)?;
let mut truth = truth.validate_defs()?;
let anm = truth.read_anm(game, in_path, false)?;
truth.decompile_anm(game, &anm, decompile_options)
}
}
pub mod anm_extract {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (input, outdir, game) = cli::parse_args(version, args, CmdSpec {
program: "truanm extract",
usage_args: "FILE -g GAME [OPTIONS...]",
options: (cli::input(), cli::extract_outdir(), cli::game()),
});
wrap_exit_code(|truth| {
run(truth, game, input.as_ref(), &outdir)
});
}
pub(super) fn run(
truth: &mut Truth,
game: Game,
path: &Path,
outdir: &Path,
) -> Result<(), ErrorReported> {
let mut truth = truth.validate_defs()?;
let anm = truth.read_anm(game, path, true)?;
anm.extract_images(outdir, &truth.fs())
}
}
pub mod anm_compile {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (common_options, image_sources, output_thecl_defs) = cli::parse_args(version, args, CmdSpec {
program: "truanm compile",
usage_args: "SCRIPT -g GAME -o OUTPUT [OPTIONS...]",
options: (cli::common_compile_options(), cli::image_sources(), cli::output_thecl_defs()),
});
wrap_exit_code(|truth| run(truth, &common_options, &image_sources, output_thecl_defs));
}
pub(super) fn run(
truth: &mut Truth,
common_options: &CommonCompileOptions,
cli_image_source_paths: &[PathBuf],
output_thecl_defs: Option<PathBuf>,
) -> Result<(), ErrorReported> {
let &CommonCompileOptions {
ref in_path, ref out_path, game, ref mapfile_options, ref debug_info_path,
} = common_options;
load_mapfiles(truth, game, &[LanguageKey::Anm], mapfile_options)?;
let ast = truth.read_script(&in_path)?;
truth.load_mapfiles_from_pragmas(game, &ast)?;
let mut truth = truth.validate_defs()?;
let mut compiled = truth.compile_anm(game, &ast)?;
// image sources referenced in file take precedence
let mut image_source_paths = vec![];
image_source_paths.extend(ast.image_sources.iter().map(|lit| PathBuf::from(&lit.string)));
image_source_paths.extend(cli_image_source_paths.iter().cloned());
for image_source_path in &image_source_paths {
let source_anm = truth.read_image_source(game, image_source_path)?;
compiled.apply_image_source(source_anm, &truth.fs())?;
}
let compiled = truth.finalize_anm(game, compiled)?;
truth.write_anm(game, &out_path, &compiled)?;
if let Some(outpath) = output_thecl_defs {
truth.fs().write(&outpath, compiled.generate_thecl_defs()?)?
}
if let Some(debug_info_path) = debug_info_path {
truth.prepare_and_write_debug_info(debug_info_path)?;
}
Ok(())
}
}
pub mod anm_redump {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (input, output, game) = cli::parse_args(version, args, CmdSpec {
program: "truth-core anm-redump",
usage_args: "FILE -g GAME -o OUTPUT [OPTIONS...]",
options: (cli::input(), cli::required_output(), cli::game()),
});
wrap_exit_code(|truth| run(truth, game, input.as_ref(), output.as_ref()))
}
fn run(
truth: &mut Truth,
game: Game,
path: &Path,
outpath: &Path,
) -> Result<(), ErrorReported> {
let mut truth = truth.validate_defs()?;
let anm = truth.read_anm(game, path, true)?;
truth.write_anm(game, outpath, &anm)
}
}
pub mod ecl_compile {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let common_options = cli::parse_args(version, args, CmdSpec {
program: "truecl compile",
usage_args: "FILE -g GAME -o OUTPUT [OPTIONS...]",
options: cli::common_compile_options(),
});
wrap_exit_code(|truth| run(truth, &common_options));
}
pub fn run(
truth: &mut Truth,
common_options: &CommonCompileOptions,
) -> Result<(), ErrorReported> {
let &CommonCompileOptions {
ref in_path, ref out_path, game, ref mapfile_options, ref debug_info_path,
} = common_options;
load_mapfiles(truth, game, &[LanguageKey::Ecl, LanguageKey::Timeline], mapfile_options)?;
let ast = truth.read_script(&in_path)?;
truth.load_mapfiles_from_pragmas(game, &ast)?;
truth.expect_no_image_sources(&ast)?;
let mut truth = truth.validate_defs()?;
let ecl = truth.compile_ecl(game, &ast)?;
truth.write_ecl(game, out_path, &ecl)?;
if let Some(debug_info_path) = debug_info_path {
truth.prepare_and_write_debug_info(debug_info_path)?;
}
Ok(())
}
}
pub mod ecl_decompile {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (common_options, output, fmt_config) = cli::parse_args(version, args, CmdSpec {
program: "truecl decompile",
usage_args: "FILE -g GAME [OPTIONS...]",
options: (cli::common_decompile_options(), cli::output(), cli::fmt_config()),
});
wrap_decompile_to_stdout(fmt_config, output, |truth| {
decompile(truth, &common_options)
});
}
pub(super) fn decompile(
truth: &mut Truth,
common_options: &CommonDecompileOptions,
) -> Result<ScriptFile, ErrorReported> {
let &CommonDecompileOptions {
game, ref in_path, ref mapfile_options, ref decompile_options
} = common_options;
let mapfile_options = add_env_mapfile_for_decomp(mapfile_options, ".eclm");
load_mapfiles(truth, game, &[LanguageKey::Ecl, LanguageKey::Timeline], &mapfile_options)?;
let mut truth = truth.validate_defs()?;
let anm = truth.read_ecl(game, in_path)?;
truth.decompile_ecl(game, &anm, decompile_options)
}
}
pub mod ecl_redump {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (input, output, game) = cli::parse_args(version, args, CmdSpec {
program: "truth-core ecl-redump",
usage_args: "FILE -g GAME -o OUTPUT [OPTIONS...]",
options: (cli::input(), cli::required_output(), cli::game()),
});
wrap_exit_code(|truth| run(truth, game, input.as_ref(), output.as_ref()))
}
fn run(
truth: &mut Truth,
game: Game,
path: &Path,
outpath: &Path,
) -> Result<(), ErrorReported> {
let mut truth = truth.validate_defs()?;
let ecl = truth.read_ecl(game, path)?;
truth.write_ecl(game, outpath, &ecl)
}
}
pub mod anm_benchmark {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (anm_path, script_path, game, output, mapfile_options, decompile_options) = cli::parse_args(version, args, CmdSpec {
program: "truth-core anm-benchmark",
usage_args: "ANMFILE SCRIPT -g GAME -o OUTPUT [OPTIONS...]",
options: (
cli::path_arg("ANMFILE"), cli::path_arg("SCRIPT"),
cli::game(), cli::required_output(), cli::mapfile_options(), cli::decompile_options(),
),
});
wrap_exit_code(|truth| run(truth, game, &anm_path, &script_path, &output, &mapfile_options, &decompile_options))
}
fn run(
truth: &mut Truth,
game: Game,
anm_path: &Path,
script_path: &Path,
out_path: &Path,
mapfile_options: &MapfileOptions,
decompile_options: &DecompileOptions,
) -> Result<(), ErrorReported> {
let image_source_paths = [anm_path.to_owned()];
let common_decompile_options = CommonDecompileOptions {
game,
in_path: anm_path.to_owned(),
mapfile_options: mapfile_options.clone(),
decompile_options: decompile_options.clone(),
};
let common_compile_options = CommonCompileOptions {
game,
in_path: script_path.to_owned(),
out_path: out_path.to_owned(),
mapfile_options: mapfile_options.clone(),
debug_info_path: None,
};
loop {
let ast = super::anm_decompile::decompile(truth, &common_decompile_options)?;
let fmt_config = crate::fmt::Config::new().max_columns(100);
let mut script_out_utf8 = vec![];
let mut f = crate::Formatter::with_config(&mut script_out_utf8, fmt_config);
f.fmt(&ast).map_err(|e| truth.emit(error!("{:#}", e)))?;
drop(f); // flush
truth.fs().write(script_path, &script_out_utf8)?;
super::anm_compile::run(truth, &common_compile_options, &image_source_paths, None)?;
}
}
}
pub mod ecl_benchmark {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (ecl_path, script_path, game, output, mapfile_options, decompile_options) = cli::parse_args(version, args, CmdSpec {
program: "truth-core anm-benchmark",
usage_args: "ECLFILE SCRIPT -g GAME -o OUTPUT [OPTIONS...]",
options: (
cli::path_arg("ECLFILE"), cli::path_arg("SCRIPT"),
cli::game(), cli::required_output(), cli::mapfile_options(), cli::decompile_options(),
),
});
wrap_exit_code(|truth| run(truth, game, &ecl_path, &script_path, &output, &mapfile_options, &decompile_options))
}
fn run(
truth: &mut Truth,
game: Game,
ecl_path: &Path,
script_path: &Path,
out_path: &Path,
mapfile_options: &MapfileOptions,
decompile_options: &DecompileOptions,
) -> Result<(), ErrorReported> {
let common_decompile_options = CommonDecompileOptions {
game,
in_path: ecl_path.to_owned(),
mapfile_options: mapfile_options.clone(),
decompile_options: decompile_options.clone(),
};
let common_compile_options = CommonCompileOptions {
game,
in_path: script_path.to_owned(),
out_path: out_path.to_owned(),
mapfile_options: mapfile_options.clone(),
debug_info_path: None,
};
loop {
let ast = super::ecl_decompile::decompile(truth, &common_decompile_options)?;
let fmt_config = crate::fmt::Config::new().max_columns(100);
let mut script_out_utf8 = vec![];
let mut f = crate::Formatter::with_config(&mut script_out_utf8, fmt_config);
f.fmt(&ast).map_err(|e| truth.emit(error!("{:#}", e)))?;
drop(f); // flush
truth.fs().write(script_path, &script_out_utf8)?;
super::ecl_compile::run(truth, &common_compile_options)?;
}
}
}
pub mod std_compile {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let common_options = cli::parse_args(version, args, CmdSpec {
program: "trustd compile",
usage_args: "FILE -g GAME -o OUTPUT [OPTIONS...]",
options: cli::common_compile_options(),
});
wrap_exit_code(|truth| run(truth, &common_options));
}
fn run(
truth: &mut Truth,
common_options: &CommonCompileOptions,
) -> Result<(), ErrorReported> {
let &CommonCompileOptions {
ref in_path, ref out_path, game, ref mapfile_options, ref debug_info_path,
} = common_options;
load_mapfiles(truth, game, &[LanguageKey::Std], mapfile_options)?;
let ast = truth.read_script(&in_path)?;
truth.load_mapfiles_from_pragmas(game, &ast)?;
truth.expect_no_image_sources(&ast)?;
let mut truth = truth.validate_defs()?;
let std = truth.compile_std(game, &ast)?;
truth.write_std(game, out_path, &std)?;
if let Some(debug_info_path) = debug_info_path {
truth.prepare_and_write_debug_info(debug_info_path)?;
}
Ok(())
}
}
pub mod std_decompile {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (common_options, output, fmt_config) = cli::parse_args(version, args, CmdSpec {
program: "trustd decompile",
usage_args: "FILE -g GAME [OPTIONS...]",
options: (cli::common_decompile_options(), cli::output(), cli::fmt_config()),
});
wrap_decompile_to_stdout(fmt_config, output, |truth| {
decompile(truth, &common_options)
})
}
fn decompile(
truth: &mut Truth,
common_options: &CommonDecompileOptions,
) -> Result<ScriptFile, ErrorReported> {
let &CommonDecompileOptions {
game, ref in_path, ref mapfile_options, ref decompile_options
} = common_options;
let mapfile_options = add_env_mapfile_for_decomp(mapfile_options, ".stdm");
load_mapfiles(truth, game, &[LanguageKey::Std], &mapfile_options)?;
let mut truth = truth.validate_defs()?;
let std = truth.read_std(game, in_path)?;
truth.decompile_std(game, &std, decompile_options)
}
}
pub mod msg_redump {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (input, output, game) = cli::parse_args(version, args, CmdSpec {
program: "truth-core msg-redump",
usage_args: "FILE -g GAME -o OUTPUT [OPTIONS...]",
options: (cli::input(), cli::required_output(), cli::game()),
});
wrap_exit_code(|truth| run(truth, game, input.as_ref(), output.as_ref()))
}
fn run(
truth: &mut Truth,
game: Game,
path: &Path,
outpath: &Path,
) -> Result<(), ErrorReported> {
let mut truth = truth.validate_defs()?;
let msg = truth.read_msg(game, LanguageKey::Msg, path)?;
truth.write_msg(game, LanguageKey::Msg, outpath, &msg)?;
Ok(())
}
}
pub mod msg_compile {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (common_options, msg_mode) = cli::parse_args(version, args, CmdSpec {
program: "trumsg compile",
usage_args: "FILE -g GAME -o OUTPUT [OPTIONS...]",
options: (cli::common_compile_options(), cli::msg_mode()),
});
wrap_exit_code(|truth| run(truth, &common_options, msg_mode));
}
fn run(
truth: &mut Truth,
common_options: &CommonCompileOptions,
msg_mode: MsgMode,
) -> Result<(), ErrorReported> {
let &CommonCompileOptions {
ref in_path, ref out_path, game, ref mapfile_options, ref debug_info_path,
} = common_options;
let ast = truth.read_script(&in_path)?;
truth.expect_no_image_sources(&ast)?;
match msg_mode {
MsgMode::Stage => {
load_mapfiles(truth, game, &[LanguageKey::Msg], mapfile_options)?;
truth.load_mapfiles_from_pragmas(game, &ast)?;
},
MsgMode::Mission => {},
MsgMode::Ending => {
load_mapfiles(truth, game, &[LanguageKey::End], mapfile_options)?;
truth.load_mapfiles_from_pragmas(game, &ast)?;
},
}
let mut truth = truth.validate_defs()?;
match msg_mode {
MsgMode::Stage => {
let msg = truth.compile_msg(game, LanguageKey::Msg, &ast)?;
truth.write_msg(game, LanguageKey::Msg, out_path, &msg)?;
},
MsgMode::Mission => {
let msg = truth.compile_mission(game, &ast)?;
truth.write_mission(game, out_path, &msg)?;
},
MsgMode::Ending => {
let msg = truth.compile_msg(game, LanguageKey::End, &ast)?;
truth.write_msg(game, LanguageKey::End, out_path, &msg)?;
},
}
if let Some(debug_info_path) = debug_info_path {
truth.prepare_and_write_debug_info(debug_info_path)?;
}
Ok(())
}
}
pub mod msg_decompile {
use super::*;
pub fn main(version: &str, args: &[String]) -> ! {
let (common_options, output, fmt_config, msg_mode) = cli::parse_args(version, args, CmdSpec {
program: "trumsg decompile",
usage_args: "FILE -g GAME [OPTIONS...]",
options: (cli::common_decompile_options(), cli::output(), cli::fmt_config(), cli::msg_mode()),
});
wrap_decompile_to_stdout(fmt_config, output, |truth| {
decompile(truth, &common_options, msg_mode)
})
}
fn decompile(
truth: &mut Truth,
common_options: &CommonDecompileOptions,
msg_mode: MsgMode,
) -> Result<ScriptFile, ErrorReported> {
let &CommonDecompileOptions {
game, ref in_path, ref mapfile_options, ref decompile_options
} = common_options;
match msg_mode {
MsgMode::Stage => {
let mapfile_options = add_env_mapfile_for_decomp(mapfile_options, ".msgm");
load_mapfiles(truth, game, &[LanguageKey::Msg], &mapfile_options)?;
let mut truth = truth.validate_defs()?;
let msg = truth.read_msg(game, LanguageKey::Msg, in_path)?;
truth.decompile_msg(game, LanguageKey::Msg, &msg, decompile_options)
},
MsgMode::Mission => {
let mut truth = truth.validate_defs()?;
let msg = truth.read_mission(game, in_path)?;
truth.decompile_mission(game, &msg)
},
MsgMode::Ending => {
let mapfile_options = add_env_mapfile_for_decomp(mapfile_options, ".endm");
load_mapfiles(truth, game, &[LanguageKey::End], &mapfile_options)?;
let mut truth = truth.validate_defs()?;
let msg = truth.read_msg(game, LanguageKey::End, in_path)?;
truth.decompile_msg(game, LanguageKey::End, &msg, decompile_options)
},
}
}
}
// =============================================================================
/// Implements the automatic searching of the environment during decompilation.
fn add_env_mapfile_for_decomp(
mapfile_options: &MapfileOptions,
mapfile_extension: &'static str,
) -> MapfileOptions {
let mut mapfile_options = mapfile_options.clone();
if let Some(env_mapfile) = crate::Mapfile::decomp_map_file_from_env(mapfile_extension) {
mapfile_options.mapfile_args.insert(0, env_mapfile);
}
mapfile_options
}
/// Loads the user's mapfile and the core mapfile.
fn load_mapfiles(
truth: &mut Truth,
game: Game,
// this takes multiple languages (rather than expecting multiple calls) so that all core
// mapfiles can be loaded before any CLI args
core_mapfile_languages: &[LanguageKey],
mapfile_options: &MapfileOptions,
) -> Result<(), ErrorReported> {
if !mapfile_options.no_builtin_mapfiles {
for &language in core_mapfile_languages {
let core_mapfile = crate::core_mapfiles::core_mapfile(truth.ctx().emitter, game, language);
truth.apply_mapfile(&core_mapfile, game).expect("failed to apply core mapfile!?");
}
}
for path in &mapfile_options.mapfile_args {
truth.load_mapfile(path, game)?;
}
Ok(())
}
// =============================================================================
/// Basic wrapper for entry points that constructs an instance of the compiler API and converts Result into exit codes.
fn wrap_exit_code(func: impl FnOnce(&mut Truth) -> Result<(), ErrorReported>) -> ! {
let mut scope = crate::Builder::new().build();
let mut truth = scope.truth();
match func(&mut truth) {
Ok(()) => std::process::exit(0),
Err(ErrorReported) => std::process::exit(1),
}
}
/// Wraps a function that decompiles into one that writes to STDOUT and uses exit codes.
fn wrap_decompile_to_stdout(
fmt_config: crate::fmt::Config,
output: Option<PathBuf>,
func: impl FnOnce(&mut Truth) -> Result<ScriptFile, ErrorReported>,
) -> ! {
let stdout = io::stdout();
wrap_exit_code(|truth| {
let ast = func(truth)?;
let writer: Box<dyn io::Write> = match output {
Some(path) => Box::new(truth.fs().create_raw(path)?),
None => Box::new(stdout.lock()),
};
let writer = io::BufWriter::new(writer);
crate::Formatter::with_config(writer, fmt_config)
.fmt(&ast).map_err(|e| truth.emit(error!("{:#}", e)))
})
}
// =============================================================================
use cli::{CmdSpec, Subcommands, SubcommandSpec, MsgMode, CommonCompileOptions, CommonDecompileOptions, MapfileOptions};
mod cli {
use super::*;
use getopts::{Options, Matches};
/// Options shared by all 'compile' commands. This struct exists to help reduce the tedium of adding a new option.
pub struct CommonCompileOptions {
pub game: Game,
pub in_path: PathBuf,
pub out_path: PathBuf,
pub mapfile_options: MapfileOptions,
pub debug_info_path: Option<PathBuf>,
}
/// Options shared by all 'decompile' commands. This struct exists to help reduce the tedium of adding a new option.
pub struct CommonDecompileOptions {
pub game: Game,
pub in_path: PathBuf,
pub mapfile_options: MapfileOptions,
pub decompile_options: DecompileOptions,
}
/// Options related to mapfiles.
#[derive(Clone)]
pub struct MapfileOptions {
pub mapfile_args: Vec<PathBuf>,
pub no_builtin_mapfiles: bool,
}
pub fn common_compile_options() -> impl CliArg<Value=CommonCompileOptions> {
game().zip(required_output()).zip(input()).zip(mapfile_options()).zip(debug_info())
.and_then(|((((game, out_path), in_path), mapfile_options), debug_info_path)| {
Ok(CommonCompileOptions { game, out_path, in_path, mapfile_options, debug_info_path })
})
}
pub fn common_decompile_options() -> impl CliArg<Value=CommonDecompileOptions> {
game().zip(input()).zip(mapfile_options()).zip(decompile_options())
.and_then(|(((game, in_path), mapfile_options), decompile_options)| {
Ok(CommonDecompileOptions { game, in_path, mapfile_options, decompile_options })
})
}
pub fn output() -> impl CliArg<Value=Option<PathBuf>> {
opts::Opt {
short: "o", long: "output", metavar: "OUTPUT",
help: "output file",
}.map(|opt| opt.map(Into::into))
}
pub fn required_output() -> impl CliArg<Value=PathBuf> {
opts::ReqOpt(opts::Opt {
short: "o", long: "output", metavar: "OUTPUT",
help: "output file",
}).map(Into::into)
}
pub fn extract_outdir() -> impl CliArg<Value=PathBuf> {
opts::Opt {
short: "o", long: "output", metavar: "DIR",
help: "a directory to write images, which will be created if it does not exist. \
Defaults to the current directory.",
}.map(|opt| opt.map(Into::into).unwrap_or_else(|| std::env::current_dir().unwrap()))
}
pub fn game() -> impl CliArg<Value=Game> {
opts::ReqOpt(opts::Opt {
short: "g", long: "game", metavar: "GAME",
help: "game number, e.g. 'th095' or '8'. Don't include a point in point titles. Also supports 'alcostg'.",
}).and_then(|s| s.parse())
}
pub fn mapfile_options() -> impl CliArg<Value=MapfileOptions> {
let mapfile_args = opts::MultiOpt(opts::Opt {
short: "m", long: "map", metavar: "MAPFILE",
help: "use a mapfile to translate instruction names and argument types",
}).map(|opts| opts.into_iter().map(Into::into).collect());
let no_builtin_mapfiles = opts::Flag {
short: "", long: "no-builtin-mapfiles",
help: "disable core mapfiles, which provide signatures and intrinsic mappings for all vanilla games",
};
mapfile_args.zip(no_builtin_mapfiles).map(|(mapfile_args, no_builtin_mapfiles)| {
MapfileOptions { mapfile_args, no_builtin_mapfiles }
})
}
pub fn debug_info() -> impl CliArg<Value=Option<PathBuf>> {
opts::Opt {
short: "", long: "output-debug-info", metavar: "JSONFILE",
help: "write debug-info for a debugger to JSONFILE",
}.map(|opt| opt.map(Into::into))
}
pub fn fmt_config() -> impl CliArg<Value=crate::fmt::Config> {
fmt_max_columns().map(|ncol| crate::fmt::Config::new().max_columns(ncol))
}
fn fmt_max_columns() -> impl CliArg<Value=usize> {
opts::Opt {
short: "", long: "max-columns", metavar: "NUM",
help: "where possible, will attempt to break lines for < NUM columns",
}.and_then(|s| s.unwrap_or_else(|| "80".to_string()).parse().map_err(|e| error!("{}", e)))
}
pub fn path_arg(s: &'static str) -> impl CliArg<Value=PathBuf> {
opts::Positional { metavar: s }.map(Into::into)
}
pub fn input() -> impl CliArg<Value=PathBuf> { path_arg("INPUT") }
pub fn image_sources() -> impl CliArg<Value=Vec<PathBuf>> {
opts::MultiOpt(opts::Opt {
short: "i", long: "image-source", metavar: "SOURCE",
help: "supply images from the provided ANM file or directory. This can be supplied multiple times. Later sources override earlier ones.",
}).map(|strs| strs.into_iter().map(Into::into).collect())
}
pub fn output_thecl_defs() -> impl CliArg<Value=Option<PathBuf>> {
opts::Opt {
short: "", long: "output-thecl-defs", metavar: "FILE",
help: "write a file defining globals for anm scripts for use in thecl",
}.map(|opt| opt.map(Into::into))
}
pub fn decompile_options() -> impl CliArg<Value=DecompileOptions> {
let no_blocks = opts::Flag {
short: "", long: "no-blocks",
help: "prevent decompilation of loops and other control flow",
};
let no_intrinsics = opts::Flag {
short: "", long: "no-intrinsics",
help: "prevent recognition of special opcodes, so that every instruction decompiles uniformly into a simple function call",
};
let no_arguments = opts::Flag {
short: "", long: "no-arguments",
help: "prevent decompilation of arguments, leaving all instructions in their most raw format possible. A last resort for troublesome files",
};
let no_diff_switches = opts::Flag {
short: "", long: "no-diff-switches",
help: "prevent decompilation of diff switches, forcing direct usage of difficulty flags",
};
let zipped = no_intrinsics.zip(no_blocks).zip(no_arguments).zip(no_diff_switches);
zipped.map(|(((no_intrinsics, no_blocks), no_arguments), no_diff_switches)| DecompileOptions {
intrinsics: !no_intrinsics, blocks: !no_blocks, arguments: !no_arguments,
diff_switches: !no_diff_switches
})
}
pub enum MsgMode { Stage, Mission, Ending }
pub fn msg_mode() -> impl CliArg<Value=MsgMode> {
let mission_opt = opts::Flag { short: "", long: "mission", help: "parse mission.msg or titlemsg.txt" };
let ending_opt = opts::Flag { short: "", long: "ending", help: "parse an ending MSG" };
mission_opt.zip(ending_opt).and_then(|(mission, ending)| match (mission, ending) {
(true, true) => Err(error!("--mission and --ending are incompatible")),
(true, false) => Ok(MsgMode::Mission),
(false, true) => Ok(MsgMode::Ending),
(false, false) => Ok(MsgMode::Stage),
})
}
pub enum Abbreviations { Allow, Forbid }
pub struct CmdSpec<A> {
pub program: &'static str,
pub usage_args: &'static str,
pub options: A,
}
pub fn parse_args<A: CliArg>(
version: &str,
args: &[String],
CmdSpec { program, usage_args, options }: CmdSpec<A>,
) -> A::Value {
match _parse_args(args, options) {
Ok(arg_values) => arg_values,
Err(ParseError::PrintHelp(opts)) => {
print_help(&program, usage_args, &opts);
std::process::exit(0);
},
Err(ParseError::PrintVersion) => {
print_version(version);
std::process::exit(0);
},
Err(ParseError::Error(e)) => {
print_usage(&program, usage_args);
eprintln!();
// the error can't possibly have any spans if it occurred during argument parsing,
// so any instance of RootEmitter should be able to format it.
crate::diagnostic::RootEmitter::new_stderr().emit(e).ignore();
std::process::exit(1);
},
}
}
pub struct Subcommands {
pub program: &'static str,
pub abbreviations: Abbreviations,
pub choices: &'static [SubcommandSpec],
}
pub struct SubcommandSpec {
pub name: &'static str,
pub entry: EntryPoint,
/// Whether to show in usage.
pub public: bool,
}
pub fn parse_subcommand(
version: &str,
args: &[String],
subcommands: Subcommands,
) -> ! {
match _parse_args(&args, &subcommands) {
// parsing will automatically call the subcommand so this is unreachable...
Ok((entry_point, remaining_args)) => entry_point(version, &remaining_args),
Err(ParseError::PrintHelp(_)) => {
subcommands.show_usage();
std::process::exit(0);
},
Err(ParseError::PrintVersion) => {
print_version(version);
std::process::exit(0);
},
Err(ParseError::Error(e)) => {
subcommands.show_usage();
eprintln!();
// the error can't possibly have any spans if it occurred during argument parsing,
// so any instance of RootEmitter should be able to format it.
crate::diagnostic::RootEmitter::new_stderr().emit(e).ignore();
std::process::exit(1);
},
}
}
fn print_usage(program: &str, usage_args: &str) {
eprintln!("Usage: {} {}", program, usage_args);
}
fn print_help(program: &str, usage_args: &str, opts: &getopts::Options) {
eprint!("{}", opts.usage(&format!("Usage: {} {}", program, usage_args)));
}
fn print_version(version: &str) {
eprintln!("truth {}", version);
}
pub type ArgError = crate::diagnostic::Diagnostic;
pub trait CliArg {
type Value;
fn add_to_options(&self, opts: &mut getopts::Options);
/// NOTE: `matches.free` is in reverse order, so you can call `Vec::pop` to extract them.
fn extract_value(&self, matches: &mut getopts::Matches) -> Result<Self::Value, ArgError>;
fn zip<BArg: CliArg>(self, other: BArg) -> Zip<Self, BArg>
where
Self: Sized,
{ Zip(self, other) }
fn map<B, F: Fn(Self::Value) -> B>(self, func: F) -> Map<Self, F>
where
Self: Sized,