-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathrunner_impl.cpp
More file actions
1674 lines (1480 loc) · 48.2 KB
/
runner_impl.cpp
File metadata and controls
1674 lines (1480 loc) · 48.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
/* Copyright (c) 2024 Julian Benda
*
* This file is part of inkCPP which is released under MIT license.
* See file LICENSE.txt or go to
* https://github.com/JBenda/inkcpp for full license details.
*/
#include "runner_impl.h"
#include "choice.h"
#include "command.h"
#include "globals_impl.h"
#include "header.h"
#include "snapshot_impl.h"
#include "story_impl.h"
#include "system.h"
#include "value.h"
#ifdef INK_ENABLE_STL
# include <iomanip>
#endif
namespace ink::runtime
{
#ifdef INK_ENABLE_STL
static void write_hash(std::ostream& out, ink::hash_t value)
{
using namespace std;
ios::fmtflags state{out.flags()};
out << "0x" << hex << setfill('0') << setw(8) << static_cast<uint32_t>(value);
out.flags(state);
}
#endif
const choice* runner_interface::get_choice(size_t index) const
{
inkAssert(index < num_choices(), "Choice out of bounds!");
return begin() + index;
}
size_t runner_interface::num_choices() const { return static_cast<size_t>(end() - begin()); }
} // namespace ink::runtime
namespace ink::runtime::internal
{
hash_t runner_impl::get_current_knot() const
{
return _current_knot_id == ~0U ? 0 : _story->container_hash(_current_knot_id);
}
template<>
value* runner_impl::get_var<runner_impl::Scope::GLOBAL>(hash_t variableName)
{
return _globals->get_variable(variableName);
}
template<>
value* runner_impl::get_var<runner_impl::Scope::LOCAL>(hash_t variableName)
{
value* ret = _stack.get(variableName);
if (! ret) {
return nullptr;
}
if (ret->type() == value_type::value_pointer) {
auto [name, ci] = ret->get<value_type::value_pointer>();
inkAssert(ci == 0, "only Global pointer are allowd on the _stack!");
return get_var<runner_impl::Scope::GLOBAL>(name);
}
return ret;
}
template<>
value* runner_impl::get_var<runner_impl::Scope::NONE>(hash_t variableName)
{
value* ret = get_var<Scope::LOCAL>(variableName);
if (ret) {
return ret;
}
return get_var<Scope::GLOBAL>(variableName);
}
template<runner_impl::Scope Hint>
const value* runner_impl::get_var(hash_t variableName) const
{
return const_cast<runner_impl*>(this)->get_var<Hint>(variableName);
}
template<>
void runner_impl::set_var<runner_impl::Scope::GLOBAL>(
hash_t variableName, const value& val, bool is_redef
)
{
if (is_redef) {
value* src = _globals->get_variable(variableName);
_globals->set_variable(variableName, src->redefine(val, _globals->lists()));
} else {
_globals->set_variable(variableName, val);
}
}
const value* runner_impl::dereference(const value& val)
{
if (val.type() != value_type::value_pointer) {
return &val;
}
auto [name, ci] = val.get<value_type::value_pointer>();
if (ci == 0) {
return get_var<Scope::GLOBAL>(name);
}
return _stack.get_from_frame(ci, name);
}
template<>
void runner_impl::set_var<runner_impl::Scope::LOCAL>(
hash_t variableName, const value& val, bool is_redef
)
{
if (val.type() == value_type::value_pointer) {
inkAssert(is_redef == false, "value pointer can only use to initelize variable!");
auto [name, ci] = val.get<value_type::value_pointer>();
if (ci == 0) {
_stack.set(variableName, val);
} else {
const value* dref = dereference(val);
if (dref == nullptr) {
value v = val;
auto ref = v.get<value_type::value_pointer>();
v.set<value_type::value_pointer>(ref.name, 0);
_stack.set(variableName, v);
} else {
_ref_stack.set(variableName, val);
_stack.set(variableName, *dref);
}
}
} else {
if (is_redef) {
value* src = _stack.get(variableName);
if (src->type() == value_type::value_pointer) {
auto [name, ci] = src->get<value_type::value_pointer>();
inkAssert(ci == 0, "Only global pointer are allowed on _stack!");
set_var<Scope::GLOBAL>(
name, get_var<Scope::GLOBAL>(name)->redefine(val, _globals->lists()), true
);
} else {
_stack.set(variableName, src->redefine(val, _globals->lists()));
}
} else {
_stack.set(variableName, val);
}
}
}
template<>
void runner_impl::set_var<runner_impl::Scope::NONE>(
hash_t variableName, const value& val, bool is_redef
)
{
inkAssert(is_redef, "define set scopeless variables!");
if (_stack.get(variableName)) {
return set_var<Scope::LOCAL>(variableName, val, is_redef);
} else {
return set_var<Scope::GLOBAL>(variableName, val, is_redef);
}
}
template<typename T>
inline T runner_impl::read()
{
using header = ink::internal::header;
// Sanity
inkAssert(_ptr + sizeof(T) <= _story->end(), "Unexpected EOF in Ink execution");
// Read memory
T val = *( const T* ) _ptr;
if (_story->get_header().endien == header::endian_types::differ) {
val = header::swap_bytes(val);
}
// Advance ip
_ptr += sizeof(T);
// Return
return val;
}
template<>
inline const char* runner_impl::read()
{
offset_t str = read<offset_t>();
return _story->string(str);
}
choice& runner_impl::add_choice()
{
inkAssert(
config::maxChoices < 0 || _choices.size() < static_cast<size_t>(abs(config::maxChoices)),
"Ran out of choice storage!"
);
return _choices.push();
}
void runner_impl::clear_choices()
{
// TODO: Garbage collection? ? which garbage ?
_fallback_choice = nullopt;
_choices.clear();
}
snap_tag& runner_impl::add_tag(const char* value, tags_level where)
{
int end = static_cast<int>(where) + 1;
int position = _tags_begin[end];
for (size_t i = end; i < _tags_begin.capacity(); ++i) {
_tags_begin.set(i, _tags_begin[i] + 1);
}
return _tags.insert(position) = value;
}
void runner_impl::copy_tags(tags_level src, tags_level dst)
{
inkAssert(dst < src, "Only support copieng to higher state!");
size_t old_size = _tags.size();
size_t idx = _tags_begin[static_cast<int>(src)];
size_t n = _tags_begin[static_cast<int>(src) + 1] - idx;
size_t idy = _tags_begin[static_cast<int>(dst) + 1];
for (size_t i = 0; i < n; ++i) {
_tags.insert(idy + n) = _tags[idx + i * 2];
}
for (size_t i = static_cast<int>(dst) + 1; i < _tags_begin.capacity(); ++i) {
_tags_begin.set(i, _tags_begin[i] + n);
}
inkAssert(_tags.size() == old_size + n, "Expected n new elements");
}
void runner_impl::assign_tags(std::initializer_list<tags_level> wheres)
{
size_t old_size = _tags.size();
size_t idy = _tags_begin[static_cast<int>(tags_level::UNKNOWN)];
size_t end = _tags_begin[static_cast<int>(tags_level::UNKNOWN) + 1];
size_t n = end - idy;
if (n == 0) {
return;
}
for (const tags_level& where : wheres) {
size_t idx = _tags_begin[static_cast<int>(where) + 1];
idy = _tags_begin[static_cast<int>(tags_level::UNKNOWN)];
end = _tags_begin[static_cast<int>(tags_level::UNKNOWN) + 1];
inkAssert(n == end - idy, "Same size in each iteration");
for (size_t i = 0; i < n; ++i) {
const char* tag = _tags[idy + i * 2];
_tags.insert(idx + i) = tag;
}
for (size_t i = static_cast<int>(where) + 1; i < _tags_begin.capacity(); ++i) {
_tags_begin.set(i, _tags_begin[i] + n);
}
}
_tags_begin.set(
static_cast<int>(tags_level::UNKNOWN) + 1, _tags_begin[static_cast<int>(tags_level::UNKNOWN)]
);
_tags.resize(_tags_begin[static_cast<int>(tags_level::UNKNOWN)]);
inkAssert(_tags.size() == old_size + (wheres.size() - 1) * n, "Expected to preserve size!");
}
void runner_impl::clear_tags(tags_clear_level which)
{
// clear all tags begin which we do not want to keep
//
// resize to first other field which begins which should not be cleared
switch (which) {
case tags_clear_level::KEEP_NONE:
_tags.clear();
for (size_t i = 0; i < _tags_begin.capacity(); ++i) {
_tags_begin.set(i, 0);
}
break;
case tags_clear_level::KEEP_GLOBAL_AND_UNKNOWN:
_tags.remove(
_tags_begin[static_cast<int>(tags_level::KNOT)],
_tags_begin[static_cast<int>(tags_level::UNKNOWN)]
);
for (size_t i = static_cast<int>(tags_level::KNOT); i < _tags_begin.capacity(); ++i) {
_tags_begin.set(i, _tags_begin[static_cast<int>(tags_level::KNOT)]);
}
_tags_begin.set(static_cast<int>(tags_level::UNKNOWN) + 1, _tags.size());
break;
case tags_clear_level::KEEP_KNOT:
_tags.resize(_tags_begin[static_cast<int>(tags_level::KNOT) + 1]);
for (size_t i = static_cast<int>(tags_level::KNOT) + 2; i < _tags_begin.capacity(); ++i) {
_tags_begin.set(i, _tags_begin[static_cast<int>(tags_level::KNOT) + 1]);
}
break;
default: inkAssert(false, "Unhandeld clear type %d for tags.", static_cast<int>(which));
}
}
void runner_impl::jump(ip_t dest, bool record_visits, bool track_knot_visit)
{
// Optimization: if we are _is_falling, then we can
// _should be_ able to safely assume that there is nothing to do here. A falling
// divert should only be taking us from a container to that same container's end point
// without entering any other containers
// OR IF is target is same position do nothing
// could happened if jumping to and of an unnamed container
if (dest == _ptr) {
_ptr = dest;
return;
}
const uint32_t* iter = nullptr;
container_t id;
ip_t offset = nullptr;
bool reversed = _ptr > dest;
// number of container which were already on the stack at current position
size_t comm_end = _container.size();
iter = nullptr;
while (_story->iterate_containers(iter, id, offset)) {
if (offset >= _ptr) {
break;
}
}
if (! reversed) {
_story->iterate_containers(iter, id, offset, true);
}
optional<ContainerData> last_pop = nullopt;
while (_story->iterate_containers(iter, id, offset, reversed)) {
if ((! reversed && offset >= dest) || (reversed && offset < dest)) {
break;
}
if (_container.empty() || _container.top().id != id) {
const uint32_t* iter2 = nullptr;
container_t id2;
ip_t offset2;
while (_story->iterate_containers(iter2, id2, offset2) && id2 != id) {}
_container.push({id, offset2 - _story->instructions()});
} else {
if (_container.size() == comm_end) {
last_pop = _container.pop();
comm_end -= 1;
} else {
_container.pop();
}
}
}
iter = nullptr;
while (_story->iterate_containers(iter, id, offset)) {
if (offset >= dest) {
break;
}
}
// if we jump directly to a named container start, go inside, if it's a ONLY_FIRST container
// it will get visited in the next step
// todo: check if a while is needed
if (offset == dest && static_cast<Command>(offset[0]) == Command::START_CONTAINER_MARKER) {
if (track_knot_visit
&& static_cast<CommandFlag>(offset[1]) & CommandFlag::CONTAINER_MARKER_IS_KNOT) {
_current_knot_id = id;
_entered_knot = true;
}
dest += 6;
_container.push({id, offset - _story->instructions()});
// if we entered a knot we just left, do not recount enter
if (reversed && comm_end == _container.size() - 1 && last_pop.has_value()
&& last_pop.value().id == id) {
comm_end += 1;
}
}
_ptr = dest;
// iff all container (until now) are entered at first position
bool allEnteredAtStart = true;
ip_t child_position = dest;
if (record_visits) {
const ContainerData* iData = nullptr;
size_t level = _container.size();
while (_container.iter(iData)) {
if (level > comm_end
|| _story->container_flag(iData->offset + _story->instructions())
& CommandFlag::CONTAINER_MARKER_ONLY_FIRST) {
auto parrent_offset = _story->instructions() + iData->offset;
inkAssert(child_position >= parrent_offset, "Container stack order is broken");
// 6 == len of START_CONTAINER_SIGNAL, if its 6 bytes behind the container it is a
// unnnamed subcontainers first child check if child_positino is the first child of
// current container
allEnteredAtStart = allEnteredAtStart && ((child_position - parrent_offset) <= 6);
child_position = parrent_offset;
_globals->visit(iData->id, allEnteredAtStart);
}
level -= 1;
}
}
}
template<frame_type type>
void runner_impl::start_frame(uint32_t target)
{
if constexpr (type == frame_type::function) {
// add a function start marker
_output << values::func_start;
}
// Push next address onto the callstack
{
offset_t address = static_cast<offset_t>(_ptr - _story->instructions());
_stack.push_frame<type>(address, _evaluation_mode);
_ref_stack.push_frame<type>(address, _evaluation_mode);
}
_evaluation_mode = false; // unset eval mode when enter function or tunnel
// Do the jump
inkAssert(_story->instructions() + target < _story->end(), "Diverting past end of story data!");
jump(_story->instructions() + target, true, false);
}
frame_type runner_impl::execute_return()
{
// Pop the callstack
_ref_stack.fetch_values(_stack);
frame_type type;
offset_t offset = _stack.pop_frame(&type, _evaluation_mode);
_ref_stack.push_values(_stack);
{
frame_type t;
bool eval;
// TODO: write all refs to new frame
offset_t o = _ref_stack.pop_frame(&t, eval);
inkAssert(
o == offset && t == type && eval == _evaluation_mode,
"_ref_stack and _stack should be in frame sync!"
);
}
// SPECIAL: On function, do a trim
if (type == frame_type::function) {
_output << values::func_end;
} else if (type == frame_type::tunnel) {
// if we return but there is a divert target on top of
// the evaluation stack, we should follow this instead
// inkproof: I060
if (! _eval.is_empty() && _eval.top().type() == value_type::divert) {
start_frame<frame_type::tunnel>(_eval.pop().get<value_type::divert>());
return type;
}
}
// Jump to the old offset
inkAssert(
_story->instructions() + offset < _story->end(),
"Callstack return is outside bounds of story!"
);
jump(_story->instructions() + offset, false, false);
// Return frame type
return type;
}
runner_impl::runner_impl(const story_impl* data, globals global)
: _story(data)
, _globals(global.cast<globals_impl>())
, _operations(
global.cast<globals_impl>()->strings(), global.cast<globals_impl>()->lists(), _rng,
*global.cast<globals_impl>(), *data, static_cast<const runner_interface&>(*this)
)
, _ptr(_story->instructions())
, _backup(nullptr)
, _done(nullptr)
, _evaluation_mode{false}
, _choices()
, _tags_begin(0, ~0)
, _container(ContainerData{})
#ifdef INK_ENABLE_CSTD
, _rng(static_cast<uint32_t>(time(NULL)))
#else
, _rng()
#endif
{
// register with globals
_globals->add_runner(this);
if (_globals->lists()) {
_output.set_list_meta(_globals->lists());
}
// initialize globals if necessary
if (! _globals->are_globals_initialized()) {
_globals->initialize_globals(this);
// Set us back to the beginning of the story
reset();
_ptr = _story->instructions();
}
}
runner_impl::~runner_impl()
{
// unregister with globals
if (_globals.is_valid()) {
_globals->remove_runner(this);
}
}
#if defined(INK_ENABLE_STL) || defined(INK_ENABLE_UNREAL)
runner_impl::line_type runner_impl::getline()
{
// Advance interpreter one line and write to output
advance_line();
# ifdef INK_ENABLE_STL
line_type result{_output.get()};
# elif defined(INK_ENABLE_UNREAL)
line_type result{ANSI_TO_TCHAR(_output.get_alloc(_globals->strings(), _globals->lists()))};
# else
# error unsupported constraints for getline
# endif
// Fall through the fallback choice, if available
if (! has_choices() && _fallback_choice) {
choose(~0U);
}
inkAssert(_output.is_empty(), "Output should be empty after getline!");
return result;
}
runner_impl::line_type runner_impl::getall()
{
# ifdef INK_ENABLE_STL
if (_debug_stream != nullptr) {
_debug_stream->clear();
}
# endif
line_type result{};
while (can_continue()) {
result += getline();
}
inkAssert(_output.is_empty(), "Output should be empty after getall!");
return result;
}
#endif
#ifdef INK_ENABLE_STL
void runner_impl::getline(std::ostream& out) { out << getline(); }
void runner_impl::getall(std::ostream& out)
{
// Advance interpreter and write lines to output
while (can_continue()) {
out << getline();
}
inkAssert(_output.is_empty(), "Output should be empty after getall!");
}
#endif
void runner_impl::advance_line()
{
clear_tags(tags_clear_level::KEEP_KNOT);
// Step while we still have instructions to execute
while (_ptr != nullptr) {
// Stop if we hit a new line
if (line_step()) {
break;
}
}
// can be in save state becaues of choice
// Garbage collection TODO: How often do we want to do this?
if (_saved) {
restore();
}
_globals->gc();
if (_output.saved()) {
_output.restore();
}
}
bool runner_impl::can_continue() const { return _ptr != nullptr && ! has_choices(); }
void runner_impl::choose(size_t index)
{
if (has_choices()) {
inkAssert(index < _choices.size(), "Choice index out of range");
} else if (! _fallback_choice) {
inkAssert(false, "No choice and no Fallbackchoice!! can not choose");
}
_globals->turn();
// Get the choice
const auto& c = has_choices() ? _choices[index] : _fallback_choice.value();
// Get its thread
thread_t choiceThread = c._thread;
// Figure out where our previous pointer was for that thread
ip_t prev = nullptr;
if (choiceThread == ~0U) {
prev = _done;
} else {
prev = _threads.get(choiceThread);
}
// Make sure we have a previous pointer
inkAssert(prev != nullptr, "No 'done' point recorded before finishing choice output");
// Move to the previous pointer so we track our movements correctly
jump(prev, false, false);
_done = nullptr;
// Collapse callstacks to the correct thread
_stack.collapse_to_thread(choiceThread);
_ref_stack.collapse_to_thread(choiceThread);
_threads.clear();
_eval.clear();
// Jump to destination and clear choice list
jump(_story->instructions() + c.path(), true, false);
clear_choices();
_entered_knot = false;
}
void runner_impl::getline_silent()
{
// advance and clear output stream
advance_line();
_output.clear();
}
snapshot* runner_impl::create_snapshot() const { return _globals->create_snapshot(); }
size_t runner_impl::snap(unsigned char* data, snapper& snapper) const
{
unsigned char* ptr = data;
bool should_write = data != nullptr;
std::uintptr_t offset = _ptr != nullptr ? _ptr - _story->instructions() : 0;
ptr = snap_write(ptr, offset, should_write);
offset = _backup - _story->instructions();
ptr = snap_write(ptr, offset, should_write);
offset = _done - _story->instructions();
ptr = snap_write(ptr, offset, should_write);
ptr = snap_write(ptr, _rng.get_state(), should_write);
ptr = snap_write(ptr, _evaluation_mode, should_write);
ptr = snap_write(ptr, _string_mode, should_write);
ptr = snap_write(ptr, _saved_evaluation_mode, should_write);
ptr = snap_write(ptr, _saved, should_write);
ptr = snap_write(ptr, _is_falling, should_write);
ptr += _output.snap(data ? ptr : nullptr, snapper);
ptr += _stack.snap(data ? ptr : nullptr, snapper);
ptr += _ref_stack.snap(data ? ptr : nullptr, snapper);
ptr += _eval.snap(data ? ptr : nullptr, snapper);
ptr += _tags_begin.snap(data ? ptr : nullptr, snapper);
ptr += _tags.snap(data ? ptr : nullptr, snapper);
snapper.runner_tags = _tags.data();
ptr = snap_write(ptr, _entered_global, should_write);
ptr = snap_write(ptr, _entered_knot, should_write);
ptr = snap_write(ptr, _current_knot_id, should_write);
ptr = snap_write(ptr, _current_knot_id_backup, should_write);
ptr += _container.snap(data ? ptr : nullptr, snapper);
ptr += _threads.snap(data ? ptr : nullptr, snapper);
ptr = snap_write(ptr, _fallback_choice.has_value(), should_write);
if (_fallback_choice) {
ptr += _fallback_choice.value().snap(data ? ptr : nullptr, snapper);
}
ptr += _choices.snap(data ? ptr : nullptr, snapper);
return static_cast<size_t>(ptr - data);
}
const unsigned char* runner_impl::snap_load(const unsigned char* data, loader& loader)
{
auto ptr = data;
std::uintptr_t offset;
ptr = snap_read(ptr, offset);
_ptr = offset == 0 ? nullptr : _story->instructions() + offset;
ptr = snap_read(ptr, offset);
_backup = _story->instructions() + offset;
ptr = snap_read(ptr, offset);
_done = _story->instructions() + offset;
int32_t seed;
ptr = snap_read(ptr, seed);
_rng.srand(seed);
ptr = snap_read(ptr, _evaluation_mode);
ptr = snap_read(ptr, _string_mode);
ptr = snap_read(ptr, _saved_evaluation_mode);
ptr = snap_read(ptr, _saved);
ptr = snap_read(ptr, _is_falling);
ptr = _output.snap_load(ptr, loader);
ptr = _stack.snap_load(ptr, loader);
ptr = _ref_stack.snap_load(ptr, loader);
ptr = _eval.snap_load(ptr, loader);
ptr = _tags_begin.snap_load(ptr, loader);
ptr = _tags.snap_load(ptr, loader);
loader.runner_tags = _tags.data();
ptr = snap_read(ptr, _entered_global);
ptr = snap_read(ptr, _entered_knot);
ptr = snap_read(ptr, _current_knot_id);
ptr = snap_read(ptr, _current_knot_id_backup);
ptr = _container.snap_load(ptr, loader);
ptr = _threads.snap_load(ptr, loader);
bool has_fallback_choice;
ptr = snap_read(ptr, has_fallback_choice);
_fallback_choice = nullopt;
if (has_fallback_choice) {
_fallback_choice.emplace();
ptr = _fallback_choice.value().snap_load(ptr, loader);
}
ptr = _choices.snap_load(ptr, loader);
return ptr;
}
const char* runner_impl::getline_alloc()
{
advance_line();
const char* res = _output.get_alloc(_globals->strings(), _globals->lists());
if (! has_choices() && _fallback_choice) {
choose(~0U);
}
inkAssert(_output.is_empty(), "Output should be empty after getline!");
return res;
}
bool runner_impl::move_to(hash_t path)
{
// find the path
ip_t destination = _story->find_offset_for(path);
if (destination == nullptr) {
// TODO: Error state?
return false;
}
// Clear state and move to destination
reset();
_ptr = _story->instructions();
jump(destination, false, true);
return true;
}
void runner_impl::internal_bind(hash_t name, internal::function_base* function)
{
_functions.add(name, function);
}
runner_impl::change_type runner_impl::detect_change() const
{
inkAssert(_output.saved(), "Cannot detect changes in non-saved stream.");
// Check if the old newline is still present (hasn't been glu'd) and
// if there is new text (non-whitespace) in the stream since saving
bool stillHasNewline = _output.ends_with(value_type::newline, _output.save_offset());
bool hasAddedNewText = _output.text_past_save() || _tags.last_size() < _tags.size();
// Newline is still there and there's no new text
if (stillHasNewline && ! hasAddedNewText) {
return change_type::no_change;
}
// If the newline is gone, we got glue'd. Continue as if we never had that newline
if (! stillHasNewline) {
return change_type::newline_removed;
}
// If there's new text content, we went too far
if (hasAddedNewText) {
return change_type::extended_past_newline;
}
inkFail("Invalid change detction. Never should be here!");
return change_type::no_change;
}
bool runner_impl::line_step()
{
// Track if added tags are global ones
if (_ptr == _story->instructions()) {
// Step the interpreter until we've parsed all tags for the line
_entered_global = true;
_current_knot_id = ~0U;
_entered_knot = false;
}
// Step the interpreter
// Copy global tags to the first line
size_t o_size = _output.filled();
step();
if ((o_size < _output.filled() && _output.find_first_of(value_type::marker) == _output.npos
&& ! _evaluation_mode && ! _saved)
|| (_entered_knot && _entered_global)) {
if (_entered_global) {
assign_tags({tags_level::LINE, tags_level::GLOBAL});
_entered_global = false;
} else if (_entered_knot) {
if (has_knot_tags()) {
clear_tags(tags_clear_level::KEEP_GLOBAL_AND_UNKNOWN
); // clear knot tags since whe are entering another knot
}
// Next tags are always added to the line
assign_tags({tags_level::LINE, tags_level::KNOT});
// Unless we are out of content, we are going to try
// to continue a little further. This is to check for
// glue (which means there is potentially more content
// in this line) OR for non-text content such as choices.
// Save a snapshot
_entered_knot = false;
}
}
// If we're not within string evaluation
if (_output.find_first_of(value_type::marker) == _output.npos) {
// Haven't added more text
// If we have a saved state after a previous newline
// don't do this if we behind choice
if (_saved && ! has_choices() && ! _fallback_choice) {
// Check for changes in the output stream
switch (detect_change()) {
case change_type::extended_past_newline:
// We've gone too far. Restore to before we moved past the newline and return that we are
// done
restore();
assign_tags({tags_level::LINE});
return true;
case change_type::newline_removed:
// Newline was removed. Proceed as if we never hit it
forget();
break;
case change_type::no_change: break;
}
}
// If we're on a newline
if (_output.ends_with(value_type::newline)) {
// Unless we are out of content, we are going to try
// to continue a little further. This is to check for
// glue (which means there is potentially more content
// in this line) OR for non-text content such as choices.
if (_ptr != nullptr) {
// Save a snapshot of the current runtime state so we
// can return here if we end up hitting a new line
if (! _saved) {
assign_tags({tags_level::LINE});
save();
}
}
// Otherwise, make sure we don't have any snapshots hanging around
// expect we are in choice handleing
else if (! has_choices() && ! _fallback_choice) {
forget();
} else {
_output.forget();
}
}
}
return false;
}
void runner_impl::step()
{
#ifdef INK_ENABLE_EXCEPTIONS
try
#endif
{
inkAssert(_ptr != nullptr, "Can not step! Do not have a valid pointer");
// Load current command
Command cmd = read<Command>();
CommandFlag flag = read<CommandFlag>();
#ifdef INK_ENABLE_STL
if (_debug_stream != nullptr) {
*_debug_stream << "cmd " << cmd << " flags " << flag << " ";
}
#endif
// If we're falling and we hit a non-fallthrough command, stop the fall.
if (_is_falling
&& ! (
(cmd == Command::DIVERT && flag & CommandFlag::DIVERT_IS_FALLTHROUGH)
|| cmd == Command::END_CONTAINER_MARKER
)) {
_is_falling = false;
set_done_ptr(nullptr);
}
if (cmd >= Command::OP_BEGIN && cmd < Command::OP_END) {
_operations(cmd, _eval);
} else {
switch (cmd) {
// == Value Commands ==
case Command::STR: {
const char* str = read<const char*>();
#ifdef INK_ENABLE_STL
if (_debug_stream != nullptr) {
*_debug_stream << "str \"" << str << "\"";
}
#endif
if (_evaluation_mode) {
_eval.push(value{}.set<value_type::string>(str));
} else {
_output << value{}.set<value_type::string>(str);
}
} break;
case Command::INT: {
int val = read<int>();
#ifdef INK_ENABLE_STL
if (_debug_stream != nullptr) {
*_debug_stream << "int " << val;
}
#endif
if (_evaluation_mode) {
_eval.push(value{}.set<value_type::int32>(static_cast<int32_t>(val)));
}
// TEST-CASE B006 don't print integers
} break;
case Command::BOOL: {
bool val = read<int>() ? true : false;
#ifdef INK_ENABLE_STL
if (_debug_stream != nullptr) {
*_debug_stream << "bool " << (val ? "true" : "false");
}
#endif
if (_evaluation_mode) {
_eval.push(value{}.set<value_type::boolean>(val));
} else {
_output << value{}.set<value_type::boolean>(val);
}
} break;
case Command::FLOAT: {
float val = read<float>();
#ifdef INK_ENABLE_STL
if (_debug_stream != nullptr) {
*_debug_stream << "float " << val;
}
#endif
if (_evaluation_mode) {
_eval.push(value{}.set<value_type::float32>(val));
}
// TEST-CASE B006 don't print floats
} break;
case Command::VALUE_POINTER: {
hash_t val = read<hash_t>();
#ifdef INK_ENABLE_STL
if (_debug_stream != nullptr) {
*_debug_stream << "value_pointer ";
write_hash(*_debug_stream, val);
}
#endif
if (_evaluation_mode) {
_eval.push(value{}.set<value_type::value_pointer>(val, static_cast<char>(flag) - 1));
} else {
inkFail("never conciderd what should happend here! (value pointer print)");
}
} break;
case Command::LIST: {
list_table::list list(read<int>());
#ifdef INK_ENABLE_STL
if (_debug_stream != nullptr) {
*_debug_stream << "list " << list.lid;
}
#endif
if (_evaluation_mode) {
_eval.push(value{}.set<value_type::list>(list));
} else {
char* str = _globals->strings().create(_globals->lists().stringLen(list) + 1);
_globals->lists().toString(str, list)[0] = 0;
_output << value{}.set<value_type::string>(str);
}
} break;
case Command::DIVERT_VAL: {
inkAssert(_evaluation_mode, "Can not push divert value into the output stream!");
// Push the divert target onto the stack
uint32_t target = read<uint32_t>();
_eval.push(value{}.set<value_type::divert>(target));
} break;
case Command::NEWLINE: {
if (_evaluation_mode) {
_eval.push(values::newline);