-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompiler.py
2193 lines (1944 loc) · 98.4 KB
/
Compiler.py
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
import argparse
from collections import namedtuple, Counter, defaultdict
import contextlib
from functools import cache, cached_property, partial
import itertools
import logging
import math
import os
import pathlib
import re
import subprocess
import sys
import yaml
# TODO: pyspellchecker to check for issues with item names
logging.basicConfig(level=logging.INFO, format='{relativeCreated:09.2f} {levelname}: {message}', style='{')
import antlr4
import igraph as ig
import inflection
import jinja2
import leidenalg as la
from grammar import parseRule, parseAction, ParseResult
from grammar.visitors import *
from grammar.visitors.PossibleVisitor import Result as PossibleResult
from FlagProcessor import BitFlagProcessor
from Utils import *
templates_dir = os.path.join(base_dir, 'games', 'templates')
MAIN_FILENAME = 'Game.yaml'
GAME_FIELDS = {'name', 'objectives', 'base_movements', 'movements', 'exit_movements',
'warps', 'actions', 'time', 'context', 'start', 'load', 'data',
'rules', 'helpers', 'collect', 'settings', 'special', '_filename'}
REGION_FIELDS = {'name', 'short', 'data', 'graph_offset'}
AREA_FIELDS = {'name', 'enter', 'spots', 'data', 'map'}
SPOT_FIELDS = {'name', 'coord', 'actions', 'locations', 'exits', 'hybrid', 'local', 'data',
'keep', 'enter'}
LOCATION_FIELDS = {'name', 'item', 'req', 'canon'}
TYPEHINT_FIELDS = {'type', 'max', 'opts', 'default'}
MOVEMENT_DIMS = {'free', 'xy', 'x', 'y'}
TRIGGER_RULES = ['enter', 'load', 'reset']
GLOBAL_TRIGGER_RULES = ['load']
PENALTY_SUBFIELDS = {'add', 'calc', 'jumps', 'jumps_down', 'movement', 'tags'}
ON_ENTRY_ARGS = {'newpos': 'SpotId'}
SPOT_NON_FIELDS = {
inflection.pluralize(n) if n != inflection.pluralize(n) else inflection.singularize(n): n
for n in SPOT_FIELDS
}
RULES_EXAMPLE = """
rules:
$victory:
default: Victory
"""
LOCAL_REFERENCE_RE = re.compile(r'\^(_[a-zA-Z_0-9.]+)')
TYPED_NAME_RE = re.compile(r'(?P<name>\$?[^:()]+)(?::(?P<type>\w+))?')
TypedVar = namedtuple('TypedVar', ['name', 'type'])
TypedRule = namedtuple('TypedRule', ['rule', 'args', 'variants'])
def load_data_from_file(file: str):
try:
with open(file) as f:
res = list(yaml.safe_load_all(f))
for r in res:
r['_filename'] = os.path.basename(file)
return res
except Exception as e:
raise Exception(f'Error reading from {file}') from e
def load_game_yaml(game_dir: str):
yfiles = [file for file in os.listdir(game_dir)
if file.endswith('.yaml')]
game_file = os.path.join(game_dir, MAIN_FILENAME)
if MAIN_FILENAME not in yfiles:
raise Exception(f'Game not found: expecting {game_file}')
yfiles.remove(MAIN_FILENAME)
with open(os.path.join(game_dir, MAIN_FILENAME)) as f:
game = yaml.safe_load(f)
unexp = game.keys() - GAME_FIELDS
if unexp:
raise Exception(f'Unexpected top-level fields in {game_file}: {", ".join(sorted(unexp))}')
if 'rules' not in game or not any(r for r in game['rules'] if r.startswith('$victory')):
raise Exception(f'Must define top-level field "rules" with "$victory" entry in {game_file}, e.g.\n{RULES_EXAMPLE}')
game['regions'] = list(itertools.chain.from_iterable(
load_data_from_file(os.path.join(game_dir, file))
for file in sorted(yfiles)))
return game
def _parseExpression(logic: str, name: str, category: str, sep:str=':', rule:str='boolExpr') -> ParseResult:
# TODO: turn the whole thing into a regex
if m := TYPED_NAME_RE.match(name):
rule = m.group('type') or rule
name = m.group('name')
return parseRule(rule, logic, name=f'{category}{sep}{name}')
def get_func_rule(helper_key:str, default='boolExpr') -> str:
if m := TYPED_NAME_RE.match(helper_key):
return m.group('type') or default
return default
def get_func_name(helper_key: str) -> str:
if m := TYPED_NAME_RE.match(helper_key):
return m.group('name')
return helper_key
def get_arg_with_type(arg: str) -> str:
if m := TYPED_NAME_RE.match(arg):
return TypedVar(m.group('name'), m.group('type'))
return TypedVar(arg, '')
def get_func_args(helper_key: str) -> list[str]:
if '(' in helper_key:
return [get_arg_with_type(arg.strip()) for arg in helper_key[:-1].split('(', 1)[1].split(',')]
return []
def trim_type_prefix(s: str) -> str:
if '::' in s:
return s[s.index('::') + 2:]
return s
def str_to_rusttype(val: str, t: str) -> str:
if t.startswith('enums::'):
return f'{t}::{inflection.camelize(val)}'
if isinstance(val, str) and '::' in val:
return f'{t}::{trim_type_prefix(val)}'
if t == 'SpotId':
return construct_place_id(val)
if 'Id' in t:
return f'{t}::{construct_id(val)}'
if t == 'bool':
return str(val).lower()
return val
def treeToString(tree: antlr4.ParserRuleContext):
return StringVisitor().visit(tree)
def get_spot_reference_names(target, source):
if not target:
return []
local = [source.get('region') or source.get('name'), source.get('area') or source.get('name'),
source.get('spot') or source.get('name')]
targ = target.split('>')
# targ length = 1 (just spot) => leave 2 (reg/area), 2 (spot+area) => leave 1 (region)
# 3 => 0.
return local[:-len(targ)] + [t.strip() for t in targ]
def get_spot_reference(target, source):
return construct_id(*get_spot_reference_names(target, source))
def get_map_reference(tilename, source):
return construct_id('map', *get_spot_reference_names(tilename, source))
def get_exit_target(ex):
return get_spot_reference(ex['to'], ex) if 'to' in ex else None
def get_exit_target_id(ex):
return construct_spot_id(*get_spot_reference_names(ex['to'], ex))
def worst_case_penalty_time(point):
return float(point['time'] + max((p.get('add', 0) for p in point.get('penalties', ())), default=0))
@contextlib.contextmanager
def processcontext(*args):
try:
yield
except Exception as e:
raise Exception(f'Exception thrown while processing {" > ".join(args)}') from e
class GameLogic(object):
def __init__(self, game: str):
if '/' in game or '\\' in game:
path = pathlib.PurePath(game)
game = path.parts[1] if path.parts[0] == 'games' else path.parts[0]
self.game = game
self.package = inflection.underscore(game)
self.game_dir = os.path.join(base_dir, 'games', game)
self._errors = []
self._info = load_game_yaml(self.game_dir)
self.game_name = self._info['name']
self.examiner = None
self.helpers = {
get_func_name(name): {
'args': get_func_args(name),
'pr': _parseExpression(logic, name, 'helpers'),
'rule': get_func_rule(name),
}
for name, logic in self._info.get('helpers', {}).items()
}
self.rules = {}
for key, variants in self._info['rules'].items():
name = get_func_name(key)
rule = get_func_rule(key, 'itemList')
self.rules[name] = TypedRule(rule, (), {
variant: {
'pr': _parseExpression(logic, f'{name}_{variant}', 'rules', rule=rule),
}
for variant, logic in variants.items()
})
self.allowed_funcs = self.helpers.keys() | self.rules.keys() | BUILTINS.keys()
self.access_funcs = {}
self.action_funcs = {}
self.num_funcs = {}
for typed_rule in self.rules.values():
for details in typed_rule.variants.values():
details['func_id'] = self.make_funcid(details)
self.collect = {}
for name, logic in self._info.get('collect', {}).items():
pr = parseAction(logic, 'collect:' + name)
self.collect[name] = {'act': pr}
self.collect[name]['action_id'] = self.make_funcid(self.collect[name], 'act')
# these are {name: {...}} dicts
self.base_movements = self._info['base_movements']
self.movements = self._info.get('movements', {})
if len(self.movements) > 8:
self._errors.append(f'Max 8 non-base non-exit movements supported; move rest to exit_movements and use in exits only')
self.exit_movements = self._info.get('exit_movements', {})
for md in self.base_movements[1:]:
if 'data' not in md:
self._errors.append(f'base movements beyond the first must have data restrictions')
if overlap := self.movements.keys() & self.exit_movements.keys():
self._errors.append(f'Movement/exit_movement names cannot overlap: {overlap.join(", ")}')
self.all_movements = dict(self.exit_movements)
self.all_movements.update(self.movements)
self.time = self._info['time']
for name, info in self.movements.items():
if 'req' in info:
info['pr'] = _parseExpression(info['req'], name, 'movements')
info['access_id'] = self.make_funcid(info)
else:
self._errors.append(f'movement {name} must have req or be in base_movements/exit_movements')
self.id_lookup = {}
self.special = self._info.get('special', {})
self.data = self._info.get('data', {})
self.data_defaults = self._info.get('data', {})
self.map_defs = self._info.get('map', {})
self.named_spots = set()
self.process_regions()
self.process_canon()
self.process_context()
self.process_warps()
self.process_global_actions()
self._errors.extend(itertools.chain.from_iterable(pr.errors for pr in self.all_parse_results()))
self.process_exit_movements()
self.process_times()
self.process_parsed_code()
self.process_items()
self.process_bitflags()
self.process_special()
def process_regions(self):
# TODO: move interesting tags to Game.yaml for customization
interesting_tags = ['interior', 'exterior']
self.canon_places = defaultdict(list)
# regions/areas/etc are dicts {name: blah, req: blah} (at whatever level)
self.regions = self._info['regions']
num_locs = 0
num_locals = 0
for region in self.regions:
if 'name' not in region:
self._errors.append(f'Region in {region["_filename"]} requires name')
continue
rname = region.get('short', region['name'])
with processcontext(rname):
region['id'] = construct_id(rname)
self.id_lookup[region['id']] = region
region['loc_ids'] = []
region['all_data'] = dict(self.data)
region['all_data'].update(region.get('data', {}))
if 'on_entry' in region:
region['act'] = parseAction(
region['on_entry'], name=f'{region["name"]}:on_entry')
region['action_id'] = self.make_funcid(region, 'act', 'on_entry', ON_ENTRY_ARGS)
if c := region.get('graph_offset'):
self._validate_pair(c, f'graph offset for {region["name"]}')
for area in region['areas']:
if 'name' not in area:
self._errors.append(f'Area in {rname} requires name')
area["fullname"] = f'{rname} > Area without name'
continue
aname = area['name']
area['fullname'] = f'{rname} > {aname}'
with processcontext(rname, aname):
area['region'] = rname
area['id'] = construct_id(rname, aname)
if other := self.id_lookup.get(area['id']):
if other['fullname'] == area['fullname']:
self._errors.append(f'Duplicate area name: {area["fullname"]}')
else:
self._errors.append(f'Area names cause id conflict: {other["fullname"]!r} and {area["fullname"]!r}')
self.id_lookup[area['id']] = area
area['spot_ids'] = []
area['loc_ids'] = []
area['all_data'] = dict(region['all_data'])
area['all_data'].update(area.get('data', {}))
if 'on_entry' in area:
area['act'] = parseAction(
area['on_entry'], name=f'{area["fullname"]}:on_entry')
area['action_id'] = self.make_funcid(area, 'act', 'on_entry', ON_ENTRY_ARGS)
if c := area.get('graph_offset'):
self._validate_pair(c, f'graph offset for {area["fullname"]}')
self.process_area_map(area)
for spot in area['spots']:
if 'name' not in spot:
self._errors.append(f'Spot in {area["fullname"]} requires name')
spot["fullname"] = f'{area["fullname"]} > Spot without name'
continue
sname = spot['name']
fullname = f'{rname} > {aname} > {sname}'
unexp = spot.keys() - SPOT_FIELDS
for uk in unexp:
if uk.startswith('_'):
continue
if uk in SPOT_NON_FIELDS:
logging.warning(f'Unknown field {uk!r} in {fullname} (did you mean {SPOT_NON_FIELDS[uk]!r}?)')
else:
logging.warning(f'Unknown field {uk!r} in {fullname}')
with processcontext(rname, aname, sname):
spot['area'] = aname
spot['region'] = rname
spot['id'] = construct_id(rname, aname, sname)
if other := self.id_lookup.get(spot['id']):
if other['fullname'] == fullname:
self._errors.append(f'Spot name is a duplicate: {fullname}')
else:
self._errors.append(f'Spot names cause id conflict: {other["fullname"]!r} and {fullname!r}')
self.id_lookup[spot['id']] = spot
spot['fullname'] = fullname
area['spot_ids'].append(spot['id'])
spot['loc_ids'] = []
spot['exit_ids'] = []
spot['action_ids'] = []
spot['all_data'] = dict(area['all_data'])
self.update_tile_data(area, spot)
spot['all_data'].update(spot.get('data', {}))
spot['base_movement'] = self.spot_base_movement(spot['all_data'])
if 'on_entry' in spot:
spot['act'] = parseAction(
spot['on_entry'], name=f'{spot["fullname"]}:on_entry')
spot['action_id'] = self.make_funcid(spot, 'act', 'on_entry', ON_ENTRY_ARGS)
if all_to_update := area.get('all'):
if lcl := all_to_update.get('local'):
if 'local' in spot:
spot['local'].extend(lcl)
else:
spot['local'] = list(lcl)
num_locals += len(spot.get('local', ()))
# hybrid spots are locations that have dests
for loc in spot.get('locations', []) + spot.get('hybrid', []):
if 'name' not in loc:
self._errors.append(f'Location in {spot["fullname"]} requires name')
loc["fullname"] = f'{spot["fullname"]} > Location without name'
continue
with processcontext(rname, aname, sname, loc['name']):
loc['spot'] = sname
loc['area'] = aname
loc['region'] = rname
loc['fullname'] = f'{spot["fullname"]} > {loc["name"]}'
loc['id'] = construct_id(rname, aname, sname, loc['name'])
if loc['id'] in self.id_lookup:
self._errors.append(f'Duplicate id: Location {loc["fullname"]} conflicts with {self.id_lookup[loc["id"]]["fullname"]}')
self.id_lookup[loc['id']] = loc
spot['loc_ids'].append(loc['id'])
area['loc_ids'].append(loc['id'])
region['loc_ids'].append(loc['id'])
if 'canon' in loc:
self.canon_places[construct_id(loc['canon'])].append(loc['id'])
loc['canon_id'] = construct_id(loc['canon'])
if 'req' in loc:
loc['pr'] = _parseExpression(
loc['req'], loc['name'], spot['fullname'], ': ')
loc['access_id'] = self.make_funcid(loc)
if 'penalties' in loc:
self._handle_penalties(loc, spot['fullname'])
if 'maps' in loc:
loc['_tiles'] = [get_map_reference(tilename, loc) for tilename in loc['maps']]
if dest := loc.get('to'):
if dest.startswith('^'):
if d := spot['all_data'].get(dest[1:]):
if self.data_types[dest[1:]] != 'SpotId':
self._errors.append(f'Hybrid location {loc["fullname"]} exits to non-spot data: {dest}')
else:
loc['raw_to'] = dest
loc['to'] = d
else:
self._errors.append(f'Hybrid location {loc["fullname"]} attempts exit to ctx but only data is supported: {dest}')
elif m := loc.get('movement'):
self._errors.append(f'Hybrid location {loc["fullname"]} has movement {m!r} but no dest')
# We need a counter for exits in case of alternates
ec = Counter()
for eh in spot.get('exits', []):
if 'to' not in eh or not eh['to']:
self._errors.append(f'Exit {eh["fullname"]} has no destination')
continue
dest = eh['to']
eh['spot'] = sname
eh['area'] = aname
eh['region'] = rname
ec[dest] += 1
eh['fullname'] = f'{spot["fullname"]} ==> {dest} ({ec[dest]})'
with processcontext(eh['fullname']):
eh['id'] = construct_id(rname, aname, sname, 'ex',
f'{dest}_{ec[dest]}')
self.id_lookup[eh['id']] = eh
spot['exit_ids'].append(eh['id'])
if dest.startswith('^'):
if d := spot['all_data'].get(dest[1:]):
if self.data_types[dest[1:]] != 'SpotId':
self._errors.append(f'Exit {eh["fullname"]} exits to non-spot data: {dest}')
else:
eh['raw_to'] = dest
dest = d
else:
self._errors.append(f'Exit {eh["fullname"]} attempts exit to ctx but only data is supported: {dest}')
# Limit to in-Area by marking exits across Areas as keep
# Maybe later we can try changing to in-Region or global
eh['keep'] = '>' in dest or ('tags' in eh and any(t in interesting_tags for t in eh['tags']))
if 'req' in eh:
eh['pr'] = _parseExpression(
eh['req'], eh['to'], spot['fullname'], ' ==> ')
eh['access_id'] = self.make_funcid(eh)
if 'penalties' in eh:
self._handle_penalties(eh, spot['fullname'])
if 'maps' in eh:
eh['_tiles'] = [get_map_reference(tilename, eh) for tilename in eh['maps']]
eh['to'] = dest
for act in spot.get('actions', ()):
if 'name' not in act:
self._errors.append(f'Action in {spot["fullname"]} requires name')
act["fullname"] = f'{spot["fullname"]} > Action without name'
continue
with processcontext(rname, aname, sname, act['name']):
act['spot'] = sname
act['area'] = aname
act['region'] = rname
act['id'] = construct_id(rname, aname, sname, act['name'])
act['fullname'] = f'{spot["fullname"]} > {act["name"]}'
if act['id'] in self.id_lookup:
self._errors.append(f'Duplicate id: Action {act["fullname"]} conflicts with {self.id_lookup[act["id"]]["fullname"]}')
self.id_lookup[act['id']] = act
spot['action_ids'].append(act['id'])
if 'req' in act:
act['pr'] = _parseExpression(
act['req'], act['name'] + ' req', spot['fullname'], ': ')
act['access_id'] = self.make_funcid(act)
if 'penalties' in act:
self._handle_penalties(act, spot['fullname'])
if 'maps' in act:
act['_tiles'] = [get_map_reference(tilename, act) for tilename in act['maps']]
act['act'] = parseAction(
act['do'], name=f'{act["fullname"]}:do')
act['action_id'] = self.make_funcid(act, 'act', 'do')
if 'after' in act:
act['act_post'] = parseAction(
act['after'], name=f'{act["name"]}:after')
act['after_id'] = self.make_funcid(act, 'act_post', 'after')
if dest := act.get('to'):
if dest.startswith('^'):
if d := spot['all_data'].get(dest[1:]):
if self.data_types[dest[1:]] != 'SpotId':
self._errors.append(f'Action {act["fullname"]} moves to non-spot data: {dest}')
else:
act['raw_to'] = dest
act['to'] = d
num_locs += len(region['loc_ids'])
self.num_locations = num_locs
self.num_locals = num_locals
def _handle_penalties(self, info, category:str):
for i, pen in enumerate(info['penalties']):
penaltyname = f'penalty{i + 1}'
infoname = info['fullname'] if 'fullname' in info else info['name']
pen['id'] = construct_id(info['id'], penaltyname)
if 'when' in pen:
pen['pr'] = _parseExpression(
pen['when'], f'{infoname} ({penaltyname})', category, ': ')
pen['access_id'] = self.make_funcid_from(info, pen['pr'], 'when')
if 'calc' in pen:
pen['cpr'] = _parseExpression(
pen['calc'], f'{infoname} ({penaltyname})', category, ': ', rule='num')
pen['calc_id'] = self.make_funcid_from(info, pen['cpr'], field='calc', ret='f32')
elif not PENALTY_SUBFIELDS.intersection(pen.keys()):
self._errors.append(f'{infoname} {penaltyname} requires one of: {", ".join(sorted(PENALTY_SUBFIELDS))}')
def _calculate_penalty_tags(self, tags, name):
penalty = 0
for tag in tags:
if tag[0] == '-':
if tag[1:] not in self.time:
logging.warning(f'Unrecognized tag {tag[1:]!r} in {name}')
else:
penalty -= self.time[tag[1:]]
elif tag not in self.time:
logging.warning(f'Unrecognized tag {tag!r} in {name}')
else:
penalty += self.time[tag]
return penalty
def process_canon(self):
for loc in self.locations():
if 'canon' not in loc:
cname = f'Loc_{loc["id"]}'
if cname in self.canon_places:
self._errors.append(f'Cannot use canon name {cname!r} which collides with default canon name for {loc["fullname"]}')
else:
self.canon_places[cname] = [loc['id']]
loc['canon_id'] = cname
def process_exit_movements(self):
for spot in self.spots():
points = [('exit', e) for e in spot.get('exits', ())] + [('hybrid loc', h) for h in spot.get('hybrid', []) + spot.get('locations', [])] + [('action', a) for a in spot.get('actions', ())]
for (ptype, exit) in points:
if 'time' not in exit and 'movement' in exit:
if 'to' not in exit:
# check_all will add an error for this, if it's not an action/loc that doesn't need a dest
continue
target = get_exit_target(exit)
if target not in self.id_lookup:
# check_all will add an error for this
continue
dest = self.id_lookup[get_exit_target(exit)]
if 'coord' not in spot:
self._errors.append(f'Expected coord for spot {spot["fullname"]} used in {ptype} with movement: {exit["fullname"]}')
continue
elif 'coord' not in dest:
self._errors.append(f'Expected coord for dest {dest["fullname"]} used in {ptype} with movement: {exit["fullname"]}')
continue
base = spot['base_movement']
sx, sy = spot['coord']
tx, ty = dest['coord']
jumps = exit.get('jumps', 0)
jumps_down = exit.get('jumps_down', 0)
m = exit['movement']
if m == 'base':
exit['time'] = self.movement_time([], base, abs(tx - sx), ty - sy, jumps, jumps_down)
elif m in self.all_movements:
mvmt = self.all_movements[m]
exit['time'] = self.movement_time([m], None if mvmt.get('ignore_base') else base,
abs(tx - sx), ty - sy, jumps, jumps_down)
if 'price' not in exit and 'price_per_sec' in mvmt:
# Price is handled in rust now, just validate here
if costs := mvmt.get('costs'):
if 'costs' in exit and exit['costs'] != costs:
logging.warning(f'field "costs" in {ptype} {exit["fullname"]} overridden by movement {m!r}: {costs}')
exit['costs'] = costs
elif 'costs' in exit:
logging.warning(f'field "costs" in {ptype} {exit["fullname"]} overridden by movement {m!r}: default ({self.default_price_type})')
del exit['costs']
else:
self._errors.append(f'Unrecognized movement type in {ptype} {exit["fullname"]}: {m!r}')
continue
if exit['time'] is None:
self._errors.append(f'Unable to determine movement time for {ptype} {exit["fullname"]} with movement {m!r}: missing jumps?')
continue
for i, pen in enumerate(exit.get('penalties', ())):
pen['add'] = pen.get('add', 0)
if 'movement' in pen or 'jumps' in pen or 'jumps_down' in pen:
pm = pen.get('movement', m)
if pm == 'base':
t = self.movement_time([], base, abs(tx - sx), ty - sy,
jumps + pen.get('jumps', 0),
jumps_down + pen.get('jumps_down', 0))
elif mvmt := self.all_movements.get(pm):
t = self.movement_time([pm], None if mvmt.get('ignore_base') else base, abs(tx - sx), ty - sy,
jumps + pen.get('jumps', 0),
jumps_down + pen.get('jumps_down', 0))
else:
self._errors.append(f'Unrecognized movement type in {ptype} {exit["fullname"]} penalty {i+1}: {pm!r}')
continue
if tags := pen.get('tags'):
t += self._calculate_penalty_tags(tags, f'{exit["fullname"]} penalty {i+1}')
if t < exit['time']:
self._errors.append(f'Movement penalty is actually improvement (try swapping movements): {ptype} {exit["fullname"]} penalty {i+1}: {t - exit["time"]}')
else:
# allow also adding an additional constant
pen['add'] += t - exit['time']
elif tags := pen.get('tags'):
pen['add'] += self._calculate_penalty_tags(tags, f'{exit["fullname"]} penalty {i+1}')
if pen['add'] < 0:
self._errors.append(f'Total penalties must be positive: {exit["fullname"]} penalty {i+1}: total {pen["add"]}')
continue
if always_penalty(pen):
exit['time'] += pen['add']
pen['add'] = 0
if 'movement' not in exit and any('movement' in p for p in exit.get('penalties', ())):
self._errors.append(f'movement must be defined in {ptype} {exit["fullname"]} to use movement in penalties')
def process_times(self):
"""Adds default times if time is not present, and constant-time penalties."""
for point in self.all_points():
if 'time' not in point:
point['time'] = max(
(self.time[k] for k in point.get('tags', []) if k in self.time),
default=self.time['default'])
if point['time'] is None:
continue
if tags := point.get('penalty_tags'):
penalty = self._calculate_penalty_tags(tags, f'{point["fullname"]} penalty_tags')
if penalty < 0:
self._errors.append(f'Total penalties must be positive: {point["fullname"]}: {tags} total {penalty}')
continue
point['time'] += penalty
for act in self.global_actions:
if 'time' not in act:
act['time'] = max(
(self.time[k] for k in act.get('tags', []) if k in self.time),
default=self.time['default'])
if tags := act.get('penalty_tags'):
penalty = self._calculate_penalty_tags(tags, f'{act["fullname"]} penalty_tags')
if penalty < 0:
self._errors.append(f'Total penalties must be positive: {act["fullname"]}: {tags} total {penalty}')
continue
act['time'] += penalty
def process_warps(self):
self.warps = self._info['warps']
for name, info in self.warps.items():
info['name'] = inflection.camelize(name)
info['id'] = construct_id(info['name'])
if 'time' not in info:
self._errors.append(f'Warp {name} requires explicit "time" setting')
if info['to'].startswith('^'):
val = info['to'][1:]
if vtype := self.context_types.get(val):
if vtype != 'SpotId':
self._errors.append(f'Warp {name} goes to invalid ctx dest: ^{val} (of type {vtype})')
info['target_id'] = f'ctx.{val}()'
elif vtype := self.data_types.get(val):
if vtype != 'SpotId':
self._errors.append(f'Warp {name} goes to invalid data dest: ^{val} (of type {vtype})')
info['target_id'] = f'data::{val}(ctx.position())'
else:
self._errors.append(f'Warp {name} goes to undefined ctx dest: ^{val}')
else:
id = construct_id(info['to'])
if not any(info['id'] == id for info in self.spots()):
self._errors.append(f'Warp {name} goes to unrecognized spot: {info["to"]}')
info['target_id'] = self.target_id_from_id(id)
if 'req' in info:
info['pr'] = _parseExpression(info['req'], name, 'warps')
info['access_id'] = self.make_funcid(info)
if 'before' in info:
info['act_pre'] = parseAction(
info['before'], name=f'{info["name"]}:before')
info['before_id'] = self.make_funcid(info, 'act_pre', 'before')
if 'after' in info:
info['act_post'] = parseAction(
info['after'], name=f'{info["name"]}:after')
info['after_id'] = self.make_funcid(info, 'act_post', 'after')
if 'penalties' in info:
self._handle_penalties(info, 'warps')
def process_global_actions(self):
self.global_actions = self._info.get('actions', [])
for act in self.global_actions:
name = act['name']
act['id'] = construct_id('Global', name)
self.id_lookup[act['id']] = act
if 'req' not in act and 'price' not in act:
self._errors.append(f'Global actions must have req or price: {name}')
elif 'req' in act:
act['pr'] = _parseExpression(
act['req'], name + ' req', 'actions', ': ')
act['access_id'] = self.make_funcid(act)
act['act'] = parseAction(
act['do'], name=f'{name}:do')
act['action_id'] = self.make_funcid(act, 'act')
if 'after' in act:
act['act_post'] = parseAction(
act['after'], name=f'{act["name"]}:after')
act['after_id'] = self.make_funcid(act, 'act_post', 'after')
if 'penalties' in act:
self._handle_penalties(act, 'actions')
def process_area_map(self, area):
if 'map' not in area:
return
map_defs = area['map']
if isinstance(map_defs, str):
area['_tiles'] = [construct_id('map', area['id'].lower(), map_defs)]
return
elif isinstance(map_defs, (list, tuple)):
area['_tiles'] = [construct_id('map', area['id'].lower(), tile) for tile in map_defs]
return
elif not isinstance(map_defs, dict):
self._errors.append(f'Invalid map entry for {area["fullname"]}: must be dict')
return
tile_defs = []
for tile, box in map_defs.items():
if self._validate_box(box, f'{area["fullname"]} map tile "{tile}"'):
tile_defs.append((construct_id('map', area['id'].lower(), tile), tile, box))
for spot in area['spots']:
if 'coord' not in spot:
continue
c1, c2 = spot['coord']
tiles = []
short_names = []
for (tile, tsname, box) in tile_defs:
if box[0] <= c1 <= box[2] and box[1] <= c2 <= box[3]:
tiles.append(tile)
short_names.append(tsname)
if tiles:
spot['_tiles'] = sorted(tiles)
spot['_tilenames'] = sorted(short_names)
def update_tile_data(self, area, spot):
if 'datamap' not in area or '_tilenames' not in spot:
return
for key, valuemap in area['datamap'].items():
# Only applies the first one
for tilename in spot['_tilenames']:
if tilename in valuemap:
spot['all_data'][key] = valuemap[tilename]
break
def process_parsed_code(self):
# Check settings
def _visit(visitor, reverse=False):
def _do_non_points():
for info in self.helpers.values():
visitor.visit(info['pr'].tree, info['pr'].name, self.get_default_ctx(), dict(info['args']))
for pr in self.nonpoint_parse_results():
visitor.visit(pr.tree, pr.name, self.get_default_ctx())
if not reverse:
_do_non_points()
for pt in self.all_points():
if 'pr' in pt:
visitor.visit(pt['pr'].tree, pt['pr'].name, self.get_local_ctx(pt))
if 'act' in pt:
visitor.visit(pt['act'].tree, pt['act'].name, self.get_local_ctx(pt))
if penalties := pt.get('penalties'):
for pen in penalties:
if 'pr' in pen:
visitor.visit(pen['pr'].tree, pen['pr'].name, self.get_local_ctx(pt))
if 'cpr' in pen:
visitor.visit(pen['cpr'].tree, pen['cpr'].name, self.get_local_ctx(pt))
if reverse:
_do_non_points()
self._errors.extend(visitor.errors)
sv = SettingVisitor(self.context_types, self.settings)
_visit(sv)
self.used_settings = sv.setting_options
for s in self.settings.keys() - self.used_settings.keys():
logging.warning(f'Did not find usage of setting {s}')
hv = HelperVisitor(self.helpers, self.rules, self.context_types, self.data_types, self.settings)
_visit(hv, True)
cv = ContextVisitor(self.context_types, self.context_values,
self.data_types, self.data_values, self.data_defaults)
_visit(cv)
self.context_str_values = cv.values
self.swap_pairs = cv.swap_pairs
self.named_spots.update(cv.named_spots)
self.used_map_tiles = cv.used_map_tiles
self.unused_map_tiles = self.all_map_tiles - self.used_map_tiles
def process_bitflags(self):
self.bfp = BitFlagProcessor(self.context_values, self.settings, self.item_max_counts,
self.canon_places, self.unused_map_tiles)
self.bfp.process()
def process_special(self):
if sc := self.special.get('graph_scale'):
self._validate_scale(sc, 'graph_scale')
if sc := self.special.get('map_scale'):
self._validate_scale(sc, 'map_scale')
if p := self.special.get('map_min'):
self._validate_pair(p, 'map_min')
self._validate_all_numeric(p, 'map_min')
if t := self.special.get('graph_exclude_tags'):
self._validate_list(t, 'graph_exclude_tags')
def _validate_scale(self, sc, name):
if not self._validate_pair(sc, name):
pass
elif sc[0] == 0 or sc[1] == 0:
self._errors.append(f'Invalid {name}: 0 not allowed: {sc}')
else:
return self._validate_all_numeric(sc, name)
return False
def _validate_all_numeric(self, p, name):
for x in p:
if not isinstance(x, (int, float)):
self._errors.append(f'Invalid {name}: elements must be numeric: {x}')
return False
return True
def _validate_pair(self, p, name):
if isinstance(p, str):
self._errors.append(f'Invalid {name}: {p!r} '
f'(did you mean [{p}] ?)')
elif not isinstance(p, (list, tuple)) or len(p) != 2:
self._errors.append(f'Invalid {name}: {p!r}')
else:
return True
return False
def _validate_box(self, box, name):
if isinstance(box, str):
self._errors.append(f'Invalid {name}: {box!r} '
f'(did you mean [{box}] ?)')
elif not isinstance(box, (list, tuple)) or len(box) != 4:
self._errors.append(f'Invalid {name}: {box!r}')
elif self._validate_all_numeric(box, name):
if box[0] == box[2] or box[1] == box[3]:
logging.warning(f'Box in {name} may be a line: {box!r}')
return True
return False
def _validate_list(self, t, name):
if isinstance(t, str):
self._errors.append(f'Invalid {name}: {t!r} '
f'(did you mean [{t}] ?)')
elif not isinstance(t, (list, tuple)):
self._errors.append(f'Invalid {name}: {t!r}')
else:
return True
return False
def exclude_by_tag(self, info):
if exc := self.special.get('graph_exclude_tags'):
if tags := info.get('tags'):
return any(x in exc for x in tags)
return False
def exclude_local(self, info):
return info.get('graph_exclude_local_edges', False) or self.exclude_by_tag(info)
def spot_base_movement(self, spot_data):
d = dict(self.base_movements[0])
for md in self.base_movements[1:]:
if 'data' in md and all(d in spot_data and spot_data[d] == v for d, v in md['data'].items()):
# Later movements override previous ones
d.update(md)
if 'data' in d:
del d['data']
return d
@cache
def region_id_from_id(self, id):
return construct_id(self.id_lookup[id]['region'])
@cache
def target_id_from_id(self, spot_id):
return f'SpotId::{spot_id}'
@cached_property
def spot_id_list(self):
return sorted(s['id'] for s in self.spots())
@cache
def spot_id_index(self, spot_id):
return self.spot_id_list.index(spot_id) + 1
@cached_property
def movements_by_type(self):
"""Returns a mapping of movement type to movement names (excluding exit-movements)."""
d = defaultdict(list)
for m, info in self.movements.items():
found = False
# 'x' and 'y' can be on the same movement
for mt in MOVEMENT_DIMS:
if mt in info:
d[mt].append(m)
found = True
if not found:
self._errors.append(f'Movement {m} does not define a movement dimension: '
f'must be one of {", ".join(MOVEMENT_DIMS)}')
return d
def movement_time(self, mset, base, a, b, jumps=0, jumps_down=0, jmvmt=None):
times = []
xtimes = []
ytimes = []
defallt = base.get('fall', 0) if base else None
dejumpt = base.get('jump', 0) if base else None
dejumpdownt = base.get('jump_down', 0) if base else None
mp = [(m, self.all_movements[m]) for m in mset]
if base:
mp.append(('base', base))
for m, mvmt in mp:
# TODO: This is all cacheable (per pair of spots, per movement type, per pair of points)
# instead of calculating the times lists for a,b for m, once per powerset of movements
if s := mvmt.get('free'):
times.append(math.sqrt(a**2 + b**2) / s)
continue
if s := mvmt.get('xy'):
times.append((abs(a) + abs(b)) / s)
continue
if sx := mvmt.get('x'):
xtimes.append(abs(a) / sx)
# x, y, fall: not mutually exclusive
if sy := mvmt.get('y'):
ytimes.append(abs(b) / sy)
if sfall := mvmt.get('fall', defallt):
# fall speed must be the same direction as "down"
if (t := b / sfall) > 0 and (jd := mvmt.get('jump_down', dejumpdownt)):
t += jumps_down * jd
ytimes.append(t)
elif (jumps and t < 0 and (jmvmt is None or m == jmvmt)
and (sjump := mvmt.get('jump', dejumpt))):
# Direction is negative but jumps is just time taken
ytimes.append(jumps * sjump)
# An exit movement (eg) may not have a fall speed
elif (jumps and (jmvmt is None or m == jmvmt)
and (sjump := mvmt.get('jump', dejumpt))):
# Direction is negative but jumps is just time taken
ytimes.append(jumps * sjump)
if xtimes and ytimes:
times.append(max(min(xtimes), min(ytimes)))
elif xtimes and b == 0:
times.append(min(xtimes))
elif ytimes and a == 0:
times.append(min(ytimes))
return min(times, default=None)
@cached_property
def movement_sets(self):
"""Returns a set of movement tuples that might be considered at the same time.
Possible relevant movement sets:
1. any movement on its own
2. any 'x' or 'x+y' with any 'y' or 'x+y'
Exit-only movements are not considered at all here.
"""
# -- free and xy are not compatible with x and y alone (could they be?)
# All movement sets:
# - any combination of available movements (2^n) only needs to consider these subsets
# to find which is the best option for any travel between two points
# for a distance of (a,b):
# - free: sqrt(a**2 + b**2)/s
# - xy: (a+b)/s
# - x+y: max(a/s_x, b/s_y)
# But is it consistent for all travel?
# - obviously the fastest free is faster than other frees, etc.
# - if s_free > s_xy then free is always faster than xy. This should also be true
# at lower s_free but it becomes dependent on (a,b); so the answer is no overall.
s = {(m,) for m in self.movements}
for xm in self.movements_by_type.get('x', []):
for ym in self.movements_by_type.get('y', []):
s.add((xm, ym))
return s
@cached_property
def non_default_movements(self):
return sorted(m for m in self.movements)