Repository navigation
Expand file tree
/
Copy pathsemantic.cpp
More file actions
1885 lines (1595 loc) · 62.4 KB
/
Copy pathsemantic.cpp
File metadata and controls
1885 lines (1595 loc) · 62.4 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
/*
* Copyright (C) 2022-2025 Clownacy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/* TODO: Optimise EQUS by having the substitution logic search for the '\' rather than the string itself. */
#include "semantic.h"
#include <array>
#include <deque>
#include <filesystem>
#include <fstream>
#include <limits.h>
#include <memory>
#include <sstream>
#include <stack>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
#include "clowncommon/clowncommon.h"
#include "dictionary.h"
#include "error.h"
#include "expression-processor.h"
#include "global.h"
#include "instruction-processor.h"
#include "listing.h"
#include "macro-state.h"
#include "object.h"
#include "object-writer.h"
#include "p2bin.h"
#include "parser.h"
#include "program-counter.h"
#include "source-line-reader.h"
#include "substitute.h"
#include "symbol-manager.h"
#include "utilities/io.h"
#include "utilities/path.h"
#include "utilities/string.h"
struct FixUp
{
Statement statement;
std::shared_ptr<SymbolDictionary> macro_dictionary;
unsigned long program_counter;
Object::Writer::Position object_writer_position;
std::string last_global_label;
std::string source_line;
std::string label;
Options options;
std::deque<ErrorManager::Location> location;
};
struct SemanticState
{
Global global;
/* Preprocessor-specifc global stuff. */
SourceLineReader source_line_reader;
ListingWriter listing_writer;
ObjectWriter object_writer;
InstructionProcessor instruction_processor = {global, object_writer};
SymbolManager symbol_manager = {global, macro.dictionary};
Parser parser = {global.error_manager};
std::deque<ErrorManager::Location> location;
std::string_view source_line;
Substitute substitutions;
std::stack<std::string> string_stack;
MacroState macro;
unsigned int macro_depth = 0;
unsigned long current_macro_invocation = 0;
bool end = false;
/* Fix-ups. */
std::deque<FixUp> fixup_list;
/* If-statements. */
unsigned int current_if_level = 0;
unsigned int false_if_level = 0;
bool true_already_found = false;
/* OBJ directive. */
std::optional<unsigned long> obj_delta;
/* Modes. */
struct ModeNormal {};
struct ModeRept
{
unsigned long repetitions = 0;
unsigned long line_number = 0;
unsigned int nesting = 0;
SourceLineList source_line_list;
};
struct ModeMacro
{
unsigned long line_number = 0;
Macro metadata;
};
struct ModeWhile
{
Expression expression;
std::string source_line;
unsigned long line_number = 0;
unsigned int nesting = 0;
SourceLineList source_line_list;
};
std::variant<ModeNormal, ModeRept, ModeMacro, ModeWhile> mode = SemanticState::ModeNormal{};
SemanticState(
std::istream &input_stream,
std::ostream &output_stream,
std::ostream &error_stream,
std::ostream* const listing_stream,
const std::string_view &input_file_path,
Options default_options
)
: global(std::move(default_options), error_stream, location, source_line, symbol_manager, macro)
, source_line_reader(input_stream)
, listing_writer(listing_stream, global.doing_fixup_pass)
, object_writer(global, output_stream, listing_writer)
{
/* For error messages, we want to maintain a list of filenames and line
numbers that describe the location and nesting of the erroneous
line. This is the first entry in that list. */
location.emplace_front(input_file_path, 0);
}
};
/* Some forward declarations that are needed because some functions recurse into each other. */
static void AssembleFile(SemanticState &state, SourceLineReader &source_line_reader);
static void AssembleLine(SemanticState &state, const std::string_view &source_line, const bool write_line_to_listing_file);
/* Other stuff */
static void TerminateIf(SemanticState &state)
{
if (state.false_if_level == state.current_if_level || state.false_if_level == 0)
{
state.true_already_found = true;
state.false_if_level = 0;
}
--state.current_if_level;
}
static void TerminateRept(SemanticState &state, SemanticState::ModeRept &rept_state)
{
/* Back-up some state into local variables, in case a nested REPT statement clobbers it. */
auto rept_state_copy = std::move(rept_state);
/* Exit REPT mode. */
state.mode.emplace<SemanticState::ModeNormal>();
while (rept_state_copy.repetitions-- != 0)
{
/* Rewind back to the line number of the start of the REPT. */
state.location.front().line_number = rept_state_copy.line_number;
/* Process the REPT's nested statements. */
for (const auto &source_line : rept_state_copy.source_line_list)
AssembleLine(state, source_line, state.global.options->expand_all_macros);
}
/* Increment past the ENDR line number. */
++state.location.front().line_number;
}
static void TerminateMacro(SemanticState &state, SemanticState::ModeMacro ¯o_state)
{
const std::string_view &identifier = macro_state.metadata.name;
if (!identifier.empty())
{
state.symbol_manager.PurgeMacro(identifier, true);
if (state.macro.ExpansionInProgress())
{
/* See comment in PurgeMacro after the check for the same condition for more details. */
state.global.error_manager.Error("Cannot define macro '{}' during macro expansion.", identifier);
}
else
{
/* Add the macro to the symbol table. */
state.symbol_manager.AddSymbol(SymbolMacro{std::move(macro_state.metadata)});
}
}
/* Exit macro mode. */
state.mode.emplace<SemanticState::ModeNormal>();
}
static void TerminateWhile(SemanticState &state, SemanticState::ModeWhile &while_state)
{
const std::string_view old_source_line = state.source_line;
/* Back-up some state into local variables, in case a nested WHILE statement clobbers it. */
auto while_state_copy = std::move(while_state);
/* Exit WHILE mode. */
state.mode.emplace<SemanticState::ModeNormal>();
state.listing_writer.SuppressLine();
for (;;)
{
state.source_line = while_state_copy.source_line;
/* We absolutely do not want to fold (cache) this expression, because
while-loops depend on variables mutating from previous values;
without this, while-loops will never terminate. */
const auto &value = state.global.expression_processor.ResolveExpressionWithoutFolding(while_state_copy.expression, "Expression must be evaluable on the first pass.").value_or(0);
if (value == 0)
break;
/* Rewind back to the line number of the start of the WHILE. */
state.location.front().line_number = while_state_copy.line_number;
/* Process the WHILE's nested statements. */
for (const auto &source_line : while_state_copy.source_line_list)
AssembleLine(state, source_line, false);
}
/* Increment past the ENDW line number. */
++state.location.front().line_number;
state.source_line = old_source_line;
}
static void PushSubstitute(SemanticState &state, const std::string_view &identifier, const std::string_view &value)
{
SymbolDictionary *dictionary;
SymbolDictionary::Entry* const dictionary_entry = state.symbol_manager.LookupSymbolAndCreateIfNotExist<SymbolStringConstant>(identifier, &dictionary);
if (dictionary_entry != nullptr)
{
std::visit(
CC_VisitHelper{
[&](SymbolNone&)
{
auto &symbol = dictionary_entry->emplace<SymbolStringConstant>();
symbol.value = value;
auto &substitute = state.macro.dictionary != nullptr && dictionary == &*state.macro.dictionary ? state.macro.expansion->substitutions : state.substitutions;
substitute.PushSubstitute(identifier, symbol.value);
},
[&](SymbolStringConstant &symbol)
{
symbol.value = value;
},
[&](auto&)
{
// Should never be ran, since `LookupSymbolAndCreateIfNotExist` rejects mismatched types.
CC_UNREACHABLE;
},
}, *dictionary_entry
);
}
}
static void PushMacroArgumentSubstitutions(SemanticState &state)
{
const std::string_view blank_argument;
for (std::size_t argument_index = 0; argument_index < state.macro.expansion->metadata->parameter_names.size(); ++argument_index)
{
const std::string_view ¶meter = state.macro.expansion->metadata->parameter_names[argument_index];
const std::string_view &argument = argument_index >= state.macro.expansion->total_arguments ? blank_argument : state.macro.expansion->argument_list[argument_index];
SymbolDictionary::Entry &dictionary_entry = state.macro.dictionary->LookUpAndCreateIfNotExist(parameter);
/* TODO: De-duplicate this with the 'PushSubstitute' function. */
std::visit(
CC_VisitHelper{
[&](SymbolNone&)
{
auto &symbol = dictionary_entry.emplace<SymbolStringConstant>();
symbol.value = argument;
state.macro.expansion->substitutions.PushSubstitute(parameter, symbol.value);
},
[&](SymbolStringConstant &symbol)
{
symbol.value = argument;
},
[&](auto&)
{
/* TODO: This is not a common case, but it can occur if e.g. someone redefines a parameter name as a normal symbol in the macro body.
See tests/previously-crashing/redefine-macro-parameter-in-macro-body.asm for an example of this.
That'll already have caused an error to be emitted, so this error might be somewhat cascading,
but I'm not certain it's not possible to hit this in other ways,
and in any case if we get here I'm pretty sure something has gone wrong, so we should emit an error in case one hasn't already been emitted. */
state.global.error_manager.Error("Attempted to redefine symbol '{}' as a string constant.", parameter);
},
}, dictionary_entry
);
}
}
static void OutputDcValue(SemanticState &state, const Size size, unsigned long value)
{
unsigned int bytes_to_write = 0;
switch (size)
{
default:
CC_UNREACHABLE;
/* Fallthrough */
case SIZE_BYTE:
case SIZE_SHORT:
if (value > 0xFF && value < 0xFFFFFF00)
state.global.error_manager.Error("Value cannot be higher than $FF or lower than -$100, but was ${:X}.", value);
bytes_to_write = 1;
break;
case SIZE_WORD:
if (value > 0xFFFF && value < 0xFFFF0000)
state.global.error_manager.Error("Value cannot be higher than $FFFF or lower than -$10000, but was ${:X}.", value);
bytes_to_write = 2;
break;
case SIZE_LONGWORD:
bytes_to_write = 4;
break;
}
state.object_writer.WriteIntegerBE(value, bytes_to_write);
}
static void PerformEven(SemanticState &state)
{
/* Pad to the nearest even address. */
if ((state.global.program_counter & 1) != 0)
state.object_writer.WriteU8(0);
}
static bool ShouldPerformAutomaticEven(SemanticState &state, const Size size)
{
return state.global.options->automatic_even && size != SIZE_BYTE;
}
static void ProcessDc(SemanticState &state, StatementDc &dc)
{
if (ShouldPerformAutomaticEven(state, dc.size))
PerformEven(state);
for (auto &expression : dc.values)
{
const auto expression_string = std::get_if<ExpressionString>(&expression);
if (expression_string != nullptr && (dc.size == SIZE_BYTE || dc.size == SIZE_SHORT))
{
/* If this is a 'dc.b', and the value is a raw string, then output each character as a single byte. */
/* This allows 'dc.b' to be used to embed strings into the output. */
for (const char character : expression_string->string)
OutputDcValue(state, dc.size, character);
}
else
{
/* Update the program counter symbol in between values, to keep it up to date. */
state.global.expression_processor.program_counter_of_expression = state.global.program_counter;
OutputDcValue(state, dc.size, state.global.expression_processor.ResolveExpression(expression).value_or(0));
}
}
}
static void ProcessDcb(SemanticState &state, StatementDcb &dcb)
{
if (ShouldPerformAutomaticEven(state, dcb.size))
PerformEven(state);
const auto &repetitions = state.global.expression_processor.ResolveExpression(dcb.repetitions, "Repetition value must be evaluable on first pass.").value_or(0);
const auto &value = state.global.expression_processor.ResolveExpression(dcb.value).value_or(0);
for (unsigned long i = 0; i < repetitions; ++i)
OutputDcValue(state, dcb.size, value);
}
static void ProcessDs(SemanticState &state, StatementDs &ds)
{
if (ShouldPerformAutomaticEven(state, ds.size))
PerformEven(state);
const auto &length = state.global.expression_processor.ResolveExpression(ds.length, "Repetition value must be evaluable on first pass.").value_or(0);
for (unsigned long i = 0; i < length; ++i)
OutputDcValue(state, ds.size, 0);
}
static void ProcessInclude(SemanticState &state, const StatementInclude &include)
{
std::ifstream input_stream(Utilities::Path::ToStandardPath(include.path));
if (!input_stream.is_open())
{
state.global.error_manager.Error("File '{}' could not be opened.", include.path);
return;
}
/* Add file path and line number to the location list. */
state.location.emplace_front(include.path, 0);
SourceLineReader source_line_reader(input_stream);
AssembleFile(state, source_line_reader);
state.location.pop_front();
}
static void ProcessIncbin(SemanticState &state, StatementIncbin &incbin)
{
std::ifstream input_file(Utilities::Path::ToStandardPath(incbin.path), input_file.binary);
if (!input_file.is_open())
{
state.global.error_manager.Error("File '{}' could not be opened.", incbin.path);
return;
}
const auto &value = state.global.expression_processor.ResolveExpression(incbin.start, "Start value must be evaluable on the first pass.").value_or(0);
input_file.seekg(value);
if (input_file.fail())
state.global.error_manager.Error("Start value is not a valid location in the file.");
if (incbin.has_length)
{
const auto &length = state.global.expression_processor.ResolveExpression(incbin.length, "Length value must be evaluable on the first pass.").value_or(0);
for (unsigned long i = 0; i < length; ++i)
{
const int character = input_file.get();
if (input_file.gcount() == 0)
{
state.global.error_manager.Error("Length value is larger than the remaining number of bytes in the file.");
break;
}
state.object_writer.WriteU8WithoutListing(character);
}
}
else
{
for (;;)
{
const int character = input_file.get();
if (input_file.gcount() == 0)
break;
state.object_writer.WriteU8WithoutListing(character);
}
}
}
static void ProcessRept(SemanticState &state, StatementRept &rept)
{
/* Enter REPT mode. */
auto &mode = state.mode.emplace<SemanticState::ModeRept>();
mode.repetitions = state.global.expression_processor.ResolveExpression(rept.repetitions, "Repetition value must be evaluable on the first pass.").value_or(1);
mode.line_number = state.location.front().line_number;
mode.nesting = 0;
}
static void ProcessMacro(SemanticState &state, StatementMacro ¯o, const std::string_view &label, bool is_short)
{
/* Enter MACRO mode. */
auto &mode = state.mode.emplace<SemanticState::ModeMacro>();
mode.metadata.name = label;
mode.line_number = state.location.front().line_number;
mode.metadata.parameter_names = std::move(macro.parameter_names);
mode.metadata.is_short = is_short;
mode.metadata.uses_label = macro.uses_label;
}
static void ProcessIf(SemanticState &state, Expression &expression)
{
++state.current_if_level;
const auto &value = state.global.expression_processor.ResolveExpression(expression, "Condition must be evaluable on the first pass.").value_or(1);
/* If this condition is false, then mark this as the false if-level. */
if (value == 0)
state.false_if_level = state.current_if_level;
state.true_already_found = value != 0;
}
static void ProcessStatement(SemanticState &state, Statement &statement, const std::string_view &label)
{
/* Bizarrely, depending on the context, the program counter can be one
of two values, so we need to maintain two separate copies of it. */
state.global.expression_processor.program_counter_of_statement = state.global.program_counter;
state.global.expression_processor.program_counter_of_expression = state.global.program_counter;
if (CC_VariantHoldsAnyOf<
StatementEmpty,
StatementInstruction,
StatementDc,
StatementDcb,
StatementDs,
StatementInclude,
StatementIncbin,
StatementRept,
StatementIf,
StatementWhile,
StatementEven,
StatementCnop,
StatementInform,
StatementFail,
StatementEnd,
StatementPusho,
StatementPopo,
StatementOpt,
StatementPushp,
StatementPopp,
StatementShift,
StatementMexit,
StatementLocal,
StatementPurge
>(statement))
{
if (!label.empty() && !state.global.doing_fixup_pass)
{
/* Handle the label here, instead of passing it onto a later function. */
state.symbol_manager.SetLastGlobalLabel(label);
state.symbol_manager.AddSymbol(label, SymbolLabel{state.global.program_counter});
}
}
else if (CC_VariantHoldsAnyOf<
StatementEndr,
StatementEndm,
StatementElseif,
StatementElse,
StatementEndc,
StatementEndw,
StatementRsset,
StatementRsreset,
StatementObj,
StatementObjend,
StatementOrg
>(statement))
{
if (!label.empty())
state.global.error_manager.Error("There cannot be a label on this type of statement.");
}
else if (CC_VariantHoldsAnyOf<
StatementMacro,
StatementMacros,
StatementEqu,
StatementEqusString,
StatementEqusIdentifier,
StatementSubstr,
StatementSet
>(statement))
{
if (label.empty())
{
state.global.error_manager.Error("This type of statement must have a label.");
/* Bail, to avoid null pointer dereferences. */
return;
}
}
else if (CC_VariantHoldsAnyOf<
StatementRs
>(statement))
{
/* Handled later. */
}
std::visit(
CC_VisitHelper{
[&](StatementEmpty&) {},
[&](StatementInstruction &statement)
{
state.instruction_processor.Process(statement);
},
[&](StatementDc &statement)
{
ProcessDc(state, statement);
},
[&](StatementDcb &statement)
{
ProcessDcb(state, statement);
},
[&](StatementDs &statement)
{
ProcessDs(state, statement);
},
[&](StatementInclude &statement)
{
ProcessInclude(state, statement);
},
[&](StatementIncbin &statement)
{
ProcessIncbin(state, statement);
},
[&](StatementRept &statement)
{
ProcessRept(state, statement);
},
[&](StatementEndr&)
{
/* Exit REPT mode. */
const auto mode = std::get_if<SemanticState::ModeRept>(&state.mode);
if (mode == nullptr)
state.global.error_manager.Error("This stray ENDR has no preceeding REPT.");
else
TerminateRept(state, *mode);
},
[&](StatementMacro &statement)
{
ProcessMacro(state, statement, label, false);
},
[&](StatementMacros &statement)
{
ProcessMacro(state, statement.macro, label, true);
},
[&](StatementEndm&)
{
/* Exit MACRO mode. */
const auto mode = std::get_if<SemanticState::ModeMacro>(&state.mode);
if (mode == nullptr)
state.global.error_manager.Error("This stray ENDM has no preceeding MACRO.");
else if (mode->metadata.is_short)
state.global.error_manager.Error("ENDM cannot be used in a short macro.");
else
TerminateMacro(state, *mode);
},
[&](StatementEqu &statement)
{
if (state.global.options->equ_set_descope_local_labels)
state.symbol_manager.SetLastGlobalLabel(label);
const auto &value_optional = state.global.expression_processor.ResolveExpression(statement.expression);
/* Hack: We ABSOLUTELY DO NOT want this line adding to the fix-up list!!! */
state.symbol_manager.fixup_needed = false;
if (!value_optional.has_value())
{
state.symbol_manager.AddSymbol(label, SymbolExpressionConstant{std::move(statement.expression)});
// TODO: Why does removing this result in a crash?
statement.expression.emplace<ExpressionNumber>(0);
return;
}
const auto &value = *value_optional;
state.symbol_manager.AddSymbol(label, SymbolConstant{value});
state.listing_writer.WriteIdentifierValue(value);
},
[&](StatementEqusString &statement)
{
PushSubstitute(state, label, statement.string);
},
[&](StatementEqusIdentifier &statement)
{
const SymbolDictionary::Entry* const dictionary_entry = state.symbol_manager.LookupSymbol(statement.string, nullptr);
const SymbolStringConstant* const symbol_string_constant = dictionary_entry == nullptr ? nullptr : std::get_if<SymbolStringConstant>(dictionary_entry);
if (symbol_string_constant == nullptr)
state.global.error_manager.Error("String constant can only be defined as a string or another string constant.");
else
PushSubstitute(state, label, symbol_string_constant->value);
},
[&](StatementSubstr &statement)
{
auto start = state.global.expression_processor.ResolveExpression(statement.start, "Start must be evaluable on the first pass.").value_or(0);
auto end = state.global.expression_processor.ResolveExpression(statement.end, "End must be evaluable on the first pass.").value_or(statement.string.length());
if (start == 0)
{
state.global.error_manager.Error("Start cannot be zero.");
return;
}
if (end < start)
end = start - 1;
/* Clamp start and end to make it so that, if the string would go beyond the end, it is truncated appropriately instead of going out-of-bounds */
/* (this matches asm68k, as far as I can see). */
if (start > statement.string.length())
start = statement.string.length() + 1;
if (end > statement.string.length())
end = statement.string.length();
PushSubstitute(state, label, statement.string.substr(start - 1, end - start + 1));
},
[&](StatementSet &statement)
{
if (state.global.options->equ_set_descope_local_labels)
state.symbol_manager.SetLastGlobalLabel(label);
const auto &value = state.global.expression_processor.ResolveExpression(statement.expression, "Value must be evaluable on the first pass.").value_or(0);
state.symbol_manager.AddSymbol(label, SymbolVariable{value});
state.listing_writer.WriteIdentifierValue(value);
},
[&](StatementIf &statement)
{
ProcessIf(state, statement.expression);
},
[&](StatementElseif &statement)
{
if (state.current_if_level == 0)
{
state.global.error_manager.Error("This stray ELSEIF has no preceeding IF.");
return;
}
if (state.false_if_level == state.current_if_level || state.false_if_level == 0)
{
const auto &value = state.global.expression_processor.ResolveExpression(statement.expression, "Condition must be evaluable on the first pass.").value_or(1);
/* If this condition is false, then mark this as the false if-level. */
if (state.true_already_found || value == 0)
{
state.false_if_level = state.current_if_level;
}
else
{
state.false_if_level = 0;
state.true_already_found = true;
}
}
},
[&](StatementElse&)
{
if (state.current_if_level == 0)
{
state.global.error_manager.Error("This stray ELSE has no preceeding IF.");
return;
}
if (state.false_if_level == state.current_if_level || state.false_if_level == 0)
{
if (state.true_already_found)
{
state.false_if_level = state.current_if_level;
}
else
{
/* If this is the false if-level, then it isn't anymore. */
/* Likewise, if there is no false if-level, then there is now. */
if (state.false_if_level == state.current_if_level)
state.false_if_level = 0;
else /*if (state.false_if_level == 0)*/
state.false_if_level = state.current_if_level;
}
}
},
[&](StatementEndc&)
{
if (state.current_if_level == 0)
state.global.error_manager.Error("This stray ENDC/ENDIF has no preceeding IF.");
else
TerminateIf(state);
},
[&](StatementWhile &statement)
{
/* Enter WHILE mode. */
auto &mode = state.mode.emplace<SemanticState::ModeWhile>();
/* Dummy-out the statement's expression, since the state now owns it, and we don't
want its sub-expressions to be automatically freed when the statement is freed. */
mode.expression.emplace<ExpressionNumber>(0);
std::swap(mode.expression, statement.expression);
mode.source_line = state.source_line;
mode.line_number = state.location.front().line_number;
mode.nesting = 0;
},
[&](StatementEndw&)
{
/* Exit WHILE mode. */
const auto mode = std::get_if<SemanticState::ModeWhile>(&state.mode);
if (mode == nullptr)
state.global.error_manager.Error("This stray ENDW has no preceeding WHILE.");
else
TerminateWhile(state, *mode);
},
[&](StatementEven&)
{
PerformEven(state);
},
[&](StatementCnop &statement)
{
const auto &offset = state.global.expression_processor.ResolveExpression(statement.offset, "Offset must be evaluable on the first pass.").value_or(0);
const auto &size_boundary = state.global.expression_processor.ResolveExpression(statement.size_boundary, "Size boundary must be evaluable on the first pass.").value_or(1);
if (size_boundary == 0)
{
/* I don't know if there's a way to make this have meaningfully useful semantics. asm68k errors on this, so for now we will too. */
state.global.error_manager.Error("Size boundary cannot be zero.");
return;
}
const unsigned long position_within_boundary = state.global.program_counter % size_boundary;
unsigned long target = state.global.program_counter - position_within_boundary + offset;
if (position_within_boundary > offset)
target += size_boundary;
/* Pad to the desired offset. */
while (state.global.program_counter != target)
state.object_writer.WriteU8(0);
},
[&](StatementInform &statement)
{
/* Definitely an 'INFORM'... */
const auto &severity = state.global.expression_processor.ResolveExpression(statement.severity, "Severity must be evaluable on the first pass.").value_or(0);
/* TODO - Everything... */
switch (severity)
{
case 0:
state.global.error_manager.Information("INFORM: '{}'", statement.message);
break;
case 1:
state.global.error_manager.Warning("INFORM: '{}'", statement.message);
break;
case 2:
case 3: /* TODO: Halt assembly. */
state.global.error_manager.Error("INFORM: '{}'", statement.message);
break;
}
},
[&](StatementFail&)
{
/* TODO: Halt assembly. */
state.global.error_manager.Error("Assembly Failed");
},
[&](StatementEnd&)
{
state.end = true;
},
[&](StatementRs &statement)
{
if (ShouldPerformAutomaticEven(state, statement.size))
if ((state.global.expression_processor.rs & 1) != 0)
++state.global.expression_processor.rs;
auto length = state.global.expression_processor.ResolveExpression(statement.length, "Length must be evaluable on the first pass.").value_or(0);
/* Add label to symbol table. */
if (!label.empty())
{
state.symbol_manager.AddSymbol(label, SymbolConstant{state.global.expression_processor.rs});
state.listing_writer.WriteIdentifierValue(state.global.expression_processor.rs);
}
/* Advance '__rs' by the specified amount. */
switch (statement.size)
{
default:
CC_UNREACHABLE;
/* Fallthrough */
case SIZE_BYTE:
case SIZE_SHORT:
length *= 1;
break;
case SIZE_WORD:
length *= 2;
break;
case SIZE_LONGWORD:
length *= 4;
break;
}
state.global.expression_processor.rs += length;
},
[&](StatementRsset &statement)
{
/* Set '__rs' to value. */
state.global.expression_processor.rs = state.global.expression_processor.ResolveExpression(statement.expression, "Value must be evaluable on the first pass.").value_or(state.global.expression_processor.rs);
},
[&](StatementRsreset&)
{
/* Set '__rs' to 0. */
state.global.expression_processor.rs = 0;
},
[&](StatementObj &statement)
{
if (state.obj_delta.has_value())
{
state.global.error_manager.Error("OBJ statements cannot be nested.");
return;
}
const auto &value = state.global.expression_processor.ResolveExpression(statement.expression, "Value must be evaluable on the first pass.").value_or(state.global.program_counter);
state.obj_delta = value - state.global.program_counter;
state.global.program_counter += *state.obj_delta;
},
[&](StatementObjend&)
{
if (!state.obj_delta.has_value())
{
state.global.error_manager.Error("This stray OBJEND has no preceeding OBJ.");
return;
}
state.global.program_counter -= *state.obj_delta;
state.obj_delta = std::nullopt;
},
[&](StatementOrg &statement)
{
const auto &value = state.global.expression_processor.ResolveExpression(statement.expression, "Value must be evaluable on the first pass.").value_or(state.global.program_counter);
if (value > 0xFFFFFFFF)
{
state.global.error_manager.Error("Value cannot be larger than 0xFFFFFFFF (was 0x{:X}).", value);
return;
}
state.object_writer.BeginNewSegment(value);
state.global.program_counter = value;
},
[&](StatementPusho&)
{
state.global.options.Push();
},
[&](StatementPopo&)
{
state.global.options.Pop();
},
[&](StatementOpt &statement)
{
for (const auto &option : statement.options)
{
/* TODO: A lot of these are unimplemented... */
if (Utilities::CaseInsensitive::CompareStrings(option, "ae+"))
state.global.options->automatic_even = true;
else if (Utilities::CaseInsensitive::CompareStrings(option, "ae-"))
state.global.options->automatic_even = false;
else if (Utilities::CaseInsensitive::CompareStrings(option, "an+"))
;
else if (Utilities::CaseInsensitive::CompareStrings(option, "an-"))
;
else if (Utilities::CaseInsensitive::CompareStrings(option, "c+"))
state.global.options->case_insensitive = false;
else if (Utilities::CaseInsensitive::CompareStrings(option, "c-"))
state.global.options->case_insensitive = true;
else if (Utilities::CaseInsensitive::CompareStrings(option, "d+"))
state.global.options->equ_set_descope_local_labels = true;
else if (Utilities::CaseInsensitive::CompareStrings(option, "d-"))
state.global.options->equ_set_descope_local_labels = false;
else if (Utilities::CaseInsensitive::CompareStrings(option, "e+"))
;
else if (Utilities::CaseInsensitive::CompareStrings(option, "e-"))
;
else if (Utilities::CaseInsensitive::CompareStrings(option, "l+"))
state.global.options->local_signifier = '.';
else if (Utilities::CaseInsensitive::CompareStrings(option, "l-"))
state.global.options->local_signifier = '@';
else if (option.length() == 2 && (option[0] == 'l' || option[0] == 'L'))
state.global.options->local_signifier = option[1];
/*else if (Utilities::CaseInsensitive::CompareStrings(option, "s+"))
;*/
else if (Utilities::CaseInsensitive::CompareStrings(option, "s-"))
;
else if (Utilities::CaseInsensitive::CompareStrings(option, "m+"))
state.global.options->expand_all_macros = true;