forked from secondlife/lsl-definitions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen_definitions.py
More file actions
2062 lines (1816 loc) · 66.2 KB
/
Copy pathgen_definitions.py
File metadata and controls
2062 lines (1816 loc) · 66.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
#!/bin/env python3
# Importantly, this shebang line prevents the bytecode pre-compilation step from
# deciding that this script is Python 2. It is not.
import ast
import ctypes
import dataclasses
import enum
import itertools
import os.path
import re
import stat
import argparse
import uuid
import os
from typing import Iterable, NamedTuple, Dict, List, Set, Sequence, TypeVar, Union, Any
import llsd # noqa
import yaml
def quoted_presenter(dumper, data):
return dumper.represent_scalar("tag:yaml.org,2002:str", str(data), style='"')
yaml.add_representer(uuid.UUID, quoted_presenter)
class StringEnum(str, enum.Enum):
def __str__(self):
return self.value
class LSLType(StringEnum):
VOID = "void"
INTEGER = "integer"
FLOAT = "float"
STRING = "string"
KEY = "key"
VECTOR = "vector"
ROTATION = "rotation"
LIST = "list"
@property
def meta(self) -> "LSLTypeMeta":
return _TYPE_META_MAP[self]
class LSLTypeMeta(NamedTuple):
cil_name: str
lso_size: int
lst_name: str
cpp_name: str
library_abbr: str
cs_name: str
mono_bind_name: str
_CS_TYPE_MODULE = "[ScriptTypes]LindenLab.SecondLife"
_TYPE_META_MAP: Dict[LSLType, LSLTypeMeta] = {
LSLType.VOID: LSLTypeMeta(
cil_name="void",
lso_size=0,
lst_name="LST_NULL",
cpp_name="<wont happen>",
library_abbr="",
cs_name="void",
mono_bind_name="void",
),
LSLType.INTEGER: LSLTypeMeta(
cil_name="int32",
lso_size=4,
lst_name="LST_INTEGER",
cpp_name="int32_t",
library_abbr="i",
cs_name="int",
mono_bind_name="S32",
),
LSLType.FLOAT: LSLTypeMeta(
cil_name="float",
lso_size=4,
lst_name="LST_FLOATINGPOINT",
cpp_name="float",
library_abbr="f",
cs_name="float",
mono_bind_name="F32",
),
LSLType.STRING: LSLTypeMeta(
cil_name="string",
lso_size=4,
lst_name="LST_STRING",
cpp_name="char *",
library_abbr="s",
cs_name="string",
mono_bind_name="MonoStringType",
),
LSLType.KEY: LSLTypeMeta(
cil_name=f"valuetype {_CS_TYPE_MODULE}.Key",
lso_size=4,
lst_name="LST_KEY",
cpp_name="<wont happen>",
library_abbr="k",
cs_name="Key",
mono_bind_name="MonoKeyType",
),
LSLType.VECTOR: LSLTypeMeta(
cil_name=f"class {_CS_TYPE_MODULE}.Vector",
lso_size=4 * 3,
lst_name="LST_VECTOR",
cpp_name="LLVector3",
library_abbr="v",
cs_name="Vector",
mono_bind_name="MonoVectorType",
),
LSLType.ROTATION: LSLTypeMeta(
cil_name=f"class {_CS_TYPE_MODULE}.Quaternion",
lso_size=4 * 4,
lst_name="LST_QUATERNION",
cpp_name="LLQuaternion",
library_abbr="q",
cs_name="Quaternion",
mono_bind_name="MonoQuaternionType",
),
LSLType.LIST: LSLTypeMeta(
cil_name="class [mscorlib]System.Collections.ArrayList",
lso_size=4,
lst_name="LST_LIST",
cpp_name="<wont happen>",
library_abbr="l",
cs_name="ArrayList",
mono_bind_name="MonoListType",
),
}
class LSLConstant(NamedTuple):
name: str
type: LSLType
value: str
tooltip: str
deprecated: bool
private: bool
"""Whether this should this be included in the syntax file"""
def to_dict(self) -> dict:
return _remove_worthless(
{
"tooltip": self.tooltip,
# Will always use a <string> node, but that's fine for our purposes.
# That's already the case for vector and hex int constants, anyway.
"value": _escape_python(self.value),
"type": str(self.type),
"deprecated": self.deprecated,
}
)
@dataclasses.dataclass
class LSLArgument:
name: str
type: LSLType
tooltip: str
index_semantics: bool
@dataclasses.dataclass
class LSLEvent:
name: str
arguments: List[LSLArgument]
tooltip: str
private: bool
deprecated: bool
def to_dict(self) -> dict:
return _remove_worthless(
{
"tooltip": self.tooltip,
"deprecated": self.deprecated,
"arguments": [
{
a.name: {
"type": str(a.type),
"tooltip": a.tooltip,
}
}
for a in self.arguments
],
}
)
@dataclasses.dataclass
class LSLFunction:
name: str
energy: float
sleep: float
ret_type: LSLType
god_mode: bool
index_semantics: bool
bool_semantics: bool
arguments: List[LSLArgument]
tooltip: str
private: bool
"""
Whether or not to include this in the public-facing syntax LLSD.
Might be useful for cases where you're intending to push an un-finalized
implementation to Agni and don't want people to use it yet.
"""
deprecated: bool
func_id: int
pure: bool
"""
Whether or not the function is guaranteed side-effect free and pure
For example, llFrand() is side-effect free, but not pure. llAsin()
is generally pure, but might have the side-effect of setting a math error
for certain inputs.
pure functions may optionally be constant-folded during compilation,
and we expect that the implementations live in `lscript_library` rather
than `newsim` so that they can be unit tested by our LSL testing harness.
"""
native: bool
"""
Whether the function must have a native implementation for non-LSO VMs
For example, it makes no sense to pass through the lscript interface for llList2String(),
so it should have a native implementation in whichever VM. This mostly controls
whether or not to generate binding code for Mono, and should rarely be set to
true for new functions, unless you really want to write some C#. :)
"""
mono_sleep: float
"""Mono-specific sleep value, only used for legacy functions that had mismatched sleeps"""
def to_dict(self, include_internal: bool = False) -> dict:
return _remove_worthless(
{
"deprecated": self.deprecated,
"god-mode": self.god_mode,
"energy": self.energy,
"sleep": self.sleep,
"return": str(self.ret_type),
"arguments": [
{
a.name: {
"type": str(a.type),
"tooltip": a.tooltip,
}
}
for a in self.arguments
],
"tooltip": self.tooltip,
**(
{}
if not include_internal
else {
"func-id": self.func_id,
"private": self.private,
"pure": self.pure,
"native": self.native,
"mono-sleep": self.mono_sleep,
}
),
}
)
class LSLDefinitions(NamedTuple):
events: Dict[str, LSLEvent]
functions: Dict[str, LSLFunction]
constants: Dict[str, LSLConstant]
controls: dict
types: dict
@property
def reserved_words(self) -> Set[str]:
"""Words that may not be used as identifiers (case-sensitive)"""
return (
set(self.controls.keys())
| set(self.types.keys())
| {"class", "struct", "typeof", "valuetype"}
)
class LSLFunctionRanges(enum.IntEnum):
SCRIPT_ID_ANIMATION_STATES = 500
SCRIPT_ID_JSON = 510
SCRIPT_ID_MAINT = 520
UNIFORM_SCALE_OPERATIONS = 590
SCRIPT_ID_EXPERIENCE_TOOLS = 600
SCRIPT_ID_LINKSETKVP = 650
SCRIPT_ID_ENVIRONMENT = 700
SCRIPT_ID_EMAIL_ADDITIONS = 750
SCRIPT_ID_GLTF_MATERIALS = 760
SCRIPT_ID_LIST_ADDITIONS = 800
def _escape_python(val: str) -> str:
"""Encode a string with escapes according to repr() rules"""
# Syntax files have double-encoded values :(
return repr(repr(val)[1:-1])[1:-1]
def _unescape_python(val: str) -> str:
"""Decode a string with escapes as if it were a string literal"""
if '"' in val:
raise ValueError("Can't handle quotes here")
return ast.literal_eval('"' + ast.literal_eval('"' + val + '"') + '"')
def _to_c_str(val: str) -> str:
# Unicode characters should be replaced with hex escapes.
repr_val = repr(val.encode("utf-8"))
assert '"' not in repr_val
# Need to slice off the leading 'b' as well.
return repr_val[2:-1]
class LSLDefinitionParser:
def __init__(self):
self._definitions = LSLDefinitions({}, {}, {}, {}, {})
def parse_file(self, name: str) -> LSLDefinitions:
if name.endswith(".llsd"):
return self.parse_llsd_file(name)
return self.parse_yaml_file(name)
def parse_yaml_file(self, name: str):
with open(name, "rb") as f:
return self._parse_dict(yaml.safe_load(f.read()))
def parse_llsd_file(self, name: str) -> LSLDefinitions:
with open(name, "rb") as f:
return self.parse_llsd_blob(f.read())
def parse_llsd_blob(self, llsd_blob: bytes) -> LSLDefinitions:
return self._parse_dict(llsd.parse_xml(llsd_blob))
def _parse_dict(self, def_dict: dict) -> LSLDefinitions:
if any(x for x in self._definitions):
raise RuntimeError("Already parsed!")
# Load these first so that we can use them to check reserved words
self._definitions.controls.update(def_dict["controls"])
self._definitions.types.update(def_dict["types"])
seen_func_ids = set()
for event_name, event_data in def_dict["events"].items():
self._handle_event(event_name, event_data)
for func_name, func_data in def_dict["functions"].items():
func = self._handle_function(func_name, func_data)
if func.func_id in seen_func_ids:
raise ValueError(f"Func ID {func.func_id} was re-used by {func!r}")
seen_func_ids.add(func.func_id)
for const_name, const_data in def_dict["constants"].items():
if const_name == "default":
# This isn't a real constant, but it's in here for some reason, maybe syntax highlighting?
continue
self._handle_constant(const_name, const_data)
return self._definitions
def _handle_event(self, event_name: str, event_data: dict) -> LSLEvent:
self._validate_identifier(event_name)
event = LSLEvent(
name=event_name,
tooltip=event_data.get("tooltip", ""),
arguments=[
self._handle_argument(event_name, arg)
for arg in (event_data.get("arguments") or [])
],
private=event_data.get("private", False),
deprecated=event_data.get("deprecated", False),
)
if event.name in self._definitions.events:
raise KeyError(f"{event.name} is already defined")
self._validate_args(event)
self._definitions.events[event.name] = event
return event
def _handle_function(self, func_name: str, func_data: dict) -> LSLFunction:
self._validate_identifier(func_name)
func = LSLFunction(
name=func_name,
tooltip=func_data.get("tooltip", ""),
# These do actually need to be floats.
energy=float(func_data["energy"] or "0.0"),
sleep=float(func_data["sleep"] or "0.0"),
# 99.9% of the time this won't be specified, if it isn't, just use `sleep`'s value.
mono_sleep=float(func_data.get("mono-sleep", func_data.get("sleep")) or "0.0"),
ret_type=LSLType(func_data["return"]),
arguments=[
self._handle_argument(func_name, arg) for arg in (func_data.get("arguments") or [])
],
private=func_data.get("private", False),
god_mode=func_data.get("god-mode", False),
deprecated=func_data.get("deprecated", False),
func_id=func_data["func-id"],
pure=func_data.get("pure", False),
native=func_data.get("native", False),
index_semantics=bool(func_data.get("index-semantics", False)),
bool_semantics=bool(func_data.get("bool-semantics", False)),
)
if func.name in self._definitions.functions:
raise KeyError(f"{func.name} is already defined")
if func.index_semantics and func.ret_type != LSLType.INTEGER:
raise ValueError(
f"{func.name} has ret with index semantics, but ret type is {func.ret_type!r}"
)
if func.bool_semantics and func.ret_type != LSLType.INTEGER:
raise ValueError(
f"{func.name} has ret with bool semantics, but ret type is {func.ret_type!r}"
)
if func.bool_semantics and func.index_semantics:
raise ValueError(f"Can't have both bool and index semantics for {func.name}")
self._validate_args(func)
self._definitions.functions[func.name] = func
return func
@staticmethod
def _handle_argument(func_name: str, arg_dict: dict) -> LSLArgument:
if len(arg_dict) != 1:
# Arguments are meant to be an array of single-element dicts to keep order.
raise ValueError(f"Expected {func_name}'s {arg_dict!r} to only have one element")
arg_name, arg_data = list(arg_dict.items())[0]
arg = LSLArgument(
name=arg_name,
type=LSLType(arg_data["type"]),
index_semantics=bool(arg_data.get("index-semantics", False)),
tooltip=arg_data.get("tooltip", ""),
)
if arg.index_semantics and arg.type != LSLType.INTEGER:
raise ValueError(
f"{func_name}'s {arg_name} has index semantics, but type is {arg.type!r}"
)
return arg
def _validate_args(self, obj: Union[LSLEvent, LSLFunction]) -> None:
unique_arg_names = set(a.name for a in obj.arguments)
if len(unique_arg_names) != len(obj.arguments):
raise KeyError(f"Duplicate argument names in {obj.name}")
for name in unique_arg_names:
self._validate_identifier(name)
if obj.name.startswith("llDetected"):
if not all(x.index_semantics for x in obj.arguments):
raise ValueError(f"{obj.name} had argument without index semantics")
_IDENTIFIER_RE = re.compile(r"\A[_a-zA-Z][_a-zA-Z0-9]*\Z")
def _validate_identifier(self, name: str) -> None:
if not re.match(self._IDENTIFIER_RE, name):
raise KeyError(f"{name!r} is not a valid identifier")
if name in self._definitions.reserved_words:
raise KeyError(f"{name!r} is a reserved name")
def _handle_constant(self, const_name: str, const_data: dict) -> LSLConstant:
self._validate_identifier(const_name)
const = LSLConstant(
name=const_name,
type=LSLType(const_data["type"]),
value=str(self._massage_const_value(const_data["value"])),
tooltip=const_data.get("tooltip", ""),
private=const_data.get("private", False),
deprecated=const_data.get("deprecated", False),
)
if const.type not in {"float", "integer", "string", "vector", "rotation"}:
raise ValueError(f"Invalid constant type {const.type}")
if const.name in self._definitions.constants:
raise KeyError(f"{const.name} is already defined")
self._definitions.constants[const.name] = const
return const
@staticmethod
def _massage_const_value(val: Any) -> Any:
if not isinstance(val, str):
return val
# Unescape any Python-like string escapes in the code
return _unescape_python(val)
def _to_f32(val: float) -> float:
return ctypes.c_float(val).value
def _remove_worthless(val: dict) -> dict:
"""Remove attributes that have the same implied values when not present"""
if not val.get("deprecated"):
val.pop("deprecated", None)
if not val.get("god-mode"):
val.pop("god-mode", None)
if not val.get("private"):
val.pop("private", None)
if not val.get("pure"):
val.pop("pure", None)
if not val.get("native"):
val.pop("native", None)
if not val.get("bool-semantics"):
val.pop("bool-semantics", None)
if not val.get("index-semantics"):
val.pop("index-semantics", None)
return val
def dump_syntax(definitions: LSLDefinitions) -> bytes:
"""Write a syntax file for use by viewers"""
syntax = {
"llsd-lsl-syntax-version": 2,
"controls": definitions.controls.copy(),
"types": definitions.types.copy(),
"constants": {},
"events": {},
"functions": {},
}
for event in sorted(definitions.events.values(), key=lambda x: x.name):
if event.private:
continue
syntax["events"][event.name] = event.to_dict()
for func in sorted(definitions.functions.values(), key=lambda x: x.name):
if func.private:
continue
syntax["functions"][func.name] = func.to_dict()
# This one's a little weird because it's not a "real" constant, but it's expected to be in the
# constants section even though it has no value or type. It allows default to have a tooltip
# and a distinct color.
syntax["constants"]["default"] = {
"tooltip": "All scripts must have a default state, which is the first state entered when the script starts.\n"
"If another state is defined before the default state, the compiler will report a syntax error."
}
for const in sorted(definitions.constants.values(), key=lambda x: x.name):
if const.private:
continue
syntax["constants"][const.name] = const.to_dict()
return llsd.format_xml(syntax)
def _write_if_different(filename: str, data: Union[bytes, str]):
"""
Write, but not if it would change mtime needlessly
That may mark a file dirty for build, which we don't want
"""
if isinstance(data, str):
data = data.encode("utf8")
old_data = None
if os.path.exists(filename) and stat.S_ISREG(os.stat(filename).st_mode):
with open(filename, "rb") as f:
old_data = f.read()
if data != old_data:
with open(filename, "wb") as f:
f.write(data)
def gen_constant_lsl_script(definitions: LSLDefinitions) -> None:
"""
Generate a script so constants' effective values can be determined
This can be done by looking at the bytecode of the compiled script.
"""
keys = ['"%s"' % x for x in definitions.constants.keys()]
joined_names = ", \n".join(itertools.chain(*zip(keys, definitions.constants.keys())))
# Generate some stub event handlers as well
event_handlers = ""
for event in definitions.events.values():
event_handlers += f"{event.name}("
event_handlers += ", ".join(f"{str(x.type)} _{i}" for i, x in enumerate(event.arguments))
event_handlers += "){}\n"
print("list l = [%s];\ndefault{\n%s\n}" % (joined_names, event_handlers))
def _splice(val: str, splice_by: str, replacement: str) -> str:
split = val.split(splice_by, 1)
if len(split) != 2:
raise ValueError(f"Unable to splice by {splice_by!r}")
return "\n".join((split[0], replacement, split[1]))
_LEXER_CONST_COMMENT = "/* GENERATED LEXER CONSTANTS */"
_LEXER_EVENT_COMMENT = "/* GENERATED LEXER EVENTS */"
_LEXER_COORD_TEMPLATE = '"%(name)s" { count(); return(%(name)s); }\n'
_LEXER_NUMERIC_TEMPLATE = '"%s" { count(); yylval.%sval = %s; return(%s); }\n'
_LEXER_STR_TEMPLATE = (
'"%s" { yylval.sval = new char[%d]; strcpy(yylval.sval, "%s"); return(STRING_CONSTANT); }\n'
)
_LEXER_BLACKLIST = {
# These are special in the lexer for inexplicable reasons.
"TRUE",
"FALSE",
# These events have weird names :(
"listen",
"changed",
"linkset_data",
"on_rez",
}
def gen_lexer_file(definitions: LSLDefinitions, template_file: str, output_file: str):
"""Generate bits to include in indra.in.l"""
with open(template_file, "r") as f:
lexer_template = f.read()
generated_events = ""
for event in definitions.events.values():
if event.name in _LEXER_BLACKLIST:
continue
generated_events += '"%s" { count(); return(%s); }\n' % (event.name, event.name.upper())
lexer_template = _splice(lexer_template, _LEXER_EVENT_COMMENT, generated_events)
generated_constants = ""
for const in definitions.constants.values():
if const.name in _LEXER_BLACKLIST:
continue
if const.type in (LSLType.VECTOR, LSLType.ROTATION):
# We can't easily generate constant definitions for these, they
# _must_ be manually defined in the parser as well. Just generate the boilerplate
# to pull in their definition from the parser.
generated_constants += _LEXER_COORD_TEMPLATE % {"name": const.name}
elif const.type == LSLType.FLOAT:
generated_constants += _LEXER_NUMERIC_TEMPLATE % (
const.name,
"f",
const.value + "f",
"FP_CONSTANT",
)
elif const.type == LSLType.INTEGER:
generated_constants += _LEXER_NUMERIC_TEMPLATE % (
const.name,
"i",
const.value,
"INTEGER_CONSTANT",
)
elif const.type == LSLType.STRING:
c_str = _to_c_str(const.value)
c_str_len = len(const.value.encode("utf8")) + 1
generated_constants += _LEXER_STR_TEMPLATE % (const.name, c_str_len, c_str)
else:
raise ValueError(f"Unknown constant type {const.type!r}")
lexer_template = _splice(lexer_template, _LEXER_CONST_COMMENT, generated_constants)
_write_if_different(output_file, lexer_template)
_PARSER_EVENT_SWITCH_COMMENT = "/* GENERATED PARSER EVENT SWITCH */"
_PARSER_EVENT_TYPES_COMMENT = "/* GENERATED PARSER EVENT TYPES */"
_PARSER_EVENT_TOKENS_COMMENT = "/* GENERATED PARSER EVENT TOKENS */"
_PARSER_EVENT_DEFINITIONS_COMMENT = "/* GENERATED PARSER EVENT DEFINITIONS */"
# These have weird idiosyncrasies in their existing naming conventions, don't generate.
_PARSER_TYPES_BLACKLIST = {
"listen",
"on_rez",
"linkset_data",
"changed",
}
_PARSER_DEFINITIONS_BLACKLIST = {
"listen",
"on_rez",
"linkset_data",
"changed",
"at_target",
"not_at_target",
"at_rot_target",
"not_at_rot_target",
"run_time_permissions",
"experience_permissions",
"experience_permissions_denied",
"remote_data",
}
def _event_to_class_name(event: LSLEvent) -> str:
return event.name.title().replace("_", "").replace("Http", "HTTP")
def gen_parser_file(definitions: LSLDefinitions, template_file: str, output_file: str):
"""Generate bits to include in indra.in.y"""
with open(template_file, "r") as f:
parser_template: str = f.read()
generated_event_tokens = ""
generated_event_types = ""
generated_event_definitions = ""
generated_event_switch = ""
for event in definitions.events.values():
if event.name not in _PARSER_TYPES_BLACKLIST:
generated_event_tokens += f"%token {event.name.upper()}\n"
generated_event_types += f"%type<event> {event.name}\n"
generated_event_switch += (
"""
| %s compound_statement {
$$ = new LLScriptEventHandler(gLine, gColumn, $1, $2);
gAllocationManager->addAllocation($$);
}
"""
% event.name
)
if event.name not in _PARSER_DEFINITIONS_BLACKLIST:
generated_event_definitions += f"{event.name}\n"
generated_event_definitions += f" : {event.name.upper()} '(' "
# Generate the header with args
first_arg = True
for arg in event.arguments:
if not first_arg:
generated_event_definitions += " ',' "
type_token = str(arg.type).upper()
type_token = {
"KEY": "LLKEY",
"ROTATION": "QUATERNION",
}.get(type_token, type_token)
generated_event_definitions += f"{type_token} IDENTIFIER "
first_arg = False
generated_event_definitions += " ')'\n {\n"
# Now for the body
arg_idx = 4
for i, arg in enumerate(event.arguments):
generated_event_definitions += f"""
LLScriptIdentifier *id{i} = new LLScriptIdentifier(gLine, gColumn, ${arg_idx});
gAllocationManager->addAllocation(id{i});
"""
arg_idx += 3
event_class = _event_to_class_name(event)
arg_str = ", ".join("id%d" % x for x in range(0, len(event.arguments)))
if arg_str:
arg_str = ", " + arg_str
generated_event_definitions += (
f" $$ = new LLScript{event_class}Event(gLine, gColumn{arg_str});\n"
)
generated_event_definitions += " }\n ;\n\n"
parser_template = _splice(parser_template, _PARSER_EVENT_TOKENS_COMMENT, generated_event_tokens)
parser_template = _splice(parser_template, _PARSER_EVENT_TYPES_COMMENT, generated_event_types)
parser_template = _splice(parser_template, _PARSER_EVENT_SWITCH_COMMENT, generated_event_switch)
parser_template = _splice(
parser_template, _PARSER_EVENT_DEFINITIONS_COMMENT, generated_event_definitions
)
_write_if_different(output_file, parser_template)
def _arg_to_member_name(arg: LSLArgument) -> str:
if arg.name[0].upper() != arg.name[0]:
return "m" + arg.name.title().replace("_", "")
# Probably already title case.
return "m" + arg.name
_TREE_BLACKLIST = {
# Basically everything, except state_entry() and game_control(),
# New events are not meant to be in here, this is just meant to reduce
# a huge diff churn.
"link_message",
"touch_start",
"dataserver",
"transaction_result",
"at_target",
"experience_permissions_denied",
"http_response",
"not_at_rot_target",
"at_rot_target",
"remote_data",
"path_update",
"listen",
"money",
"email",
"run_time_permissions",
"not_at_target",
"http_request",
"collision_start",
"land_collision_end",
"no_sensor",
"state_exit",
"object_rez",
"experience_permissions",
"collision",
"linkset_data",
"collision_end",
"attach",
"touch",
"timer",
"changed",
"sensor",
"moving_start",
"touch_end",
"land_collision",
"control",
"on_rez",
"land_collision_start",
"moving_end",
}
_TREE_CLASS_DECL_TEMPLATE = """class LLScript%(class_name)sEvent : public LLScriptEvent
{
public:
LLScript%(class_name)sEvent(S32 line, S32 col%(constructor_args)s)
: LLScriptEvent(line, col, LSTT_%(event_upper)s)
%(member_initializers)s
{
}
~LLScript%(class_name)sEvent()
{
}
void recurse(LLFILE *fp, S32 tabs, S32 tabsize, LSCRIPTCompilePass pass, LSCRIPTPruneType ptype,
BOOL &prunearg, LLScriptScope *scope, LSCRIPTType &type, LSCRIPTType basetype, U64 &count,
LLScriptByteCodeChunk *chunk, LLScriptByteCodeChunk *heap, S32 stacksize,
LLScriptScopeEntry *entry, S32 entrycount, LLScriptLibData **ldata);
S32 getSize();
%(members)s
};
"""
def gen_tree_header_file(definitions: LSLDefinitions, output_file: str) -> None:
"""Generate class declarations for event nodes to include in lscript_tree.h"""
generated_tree_header = ""
for event in definitions.events.values():
if event.name in _TREE_BLACKLIST:
continue
constructor_args = "".join(f", LLScriptIdentifier *{x.name}" for x in event.arguments)
member_initializers = "\n".join(
f" , {_arg_to_member_name(x)}({x.name})" for x in event.arguments
)
members = "\n".join(
f" LLScriptIdentifier *{_arg_to_member_name(x)};" for x in event.arguments
)
generated_tree_header += _TREE_CLASS_DECL_TEMPLATE % {
"class_name": _event_to_class_name(event),
"event_upper": event.name.upper(),
"members": members,
"member_initializers": member_initializers,
"constructor_args": constructor_args,
}
_write_if_different(output_file, generated_tree_header)
_TREE_CLASS_DEF_TEMPLATE = """
void LLScript%(class_name)sEvent::recurse(
LLFILE *fp, S32 tabs, S32 tabsize, LSCRIPTCompilePass pass, LSCRIPTPruneType ptype, BOOL &prunearg,
LLScriptScope *scope, LSCRIPTType &type, LSCRIPTType basetype, U64 &count, LLScriptByteCodeChunk *chunk,
LLScriptByteCodeChunk *heap, S32 stacksize, LLScriptScopeEntry *entry, S32 entrycount, LLScriptLibData **ldata)
{
if (gErrorToText.getErrors())
{
return;
}
switch(pass)
{
case LSCP_PRETTY_PRINT:
case LSCP_EMIT_ASSEMBLY:
fdotabs(fp, tabs, tabsize);
fprintf(fp, "%(event_name)s( ");
%(emit_assembly)s
fprintf(fp, " )\\n");
break;
case LSCP_SCOPE_PASS1:
checkForDuplicateHandler(fp, this, scope, "%(event_name)s");
%(scope_pass1)s
break;
case LSCP_RESOURCE:
{
// we're just tryng to determine how much space the variable needs
if (%(first_scope_entry)s)
{
%(resource_scope_entries)s
}
}
break;
case LSCP_EMIT_BYTE_CODE:
{
#ifdef LSL_INCLUDE_DEBUG_INFO
char name[] = "%(event_name)s";
chunk->addBytes(name, strlen(name) + 1);
%(event_debug_info)s
#endif
}
break;
case LSCP_EMIT_CIL_ASSEMBLY:
fdotabs(fp, tabs, tabsize);
fprintf(fp, "%(event_name)s(");
%(emit_cil)s
fprintf(fp, ")");
break;
default:
%(default_recurse)s
break;
}
}
S32 LLScript%(class_name)sEvent::getSize()
{
return %(event_size)d;
}
"""
_RECURSE_BOILERPLATE = (
"->recurse(fp, tabs, tabsize, pass, ptype, prunearg, scope, type, basetype, count, "
"chunk, heap, stacksize, entry, entrycount, NULL);"
)
def gen_tree_source_file(definitions: LSLDefinitions, output_file: str) -> None:
"""Generate implementations of event node methods for inclusion in lscript_tree.cpp"""
generated_tree_source = ""
for event in definitions.events.values():
if event.name in _TREE_BLACKLIST:
continue
default_recurse = "\n".join(
f" {_arg_to_member_name(x)}{_RECURSE_BOILERPLATE};" for x in event.arguments
)
emit_cil = ""
event_debug_info = ""
resource_scope_entries = ""
scope_pass1 = ""
emit_assembly = ""
first_scope_entry = None
for arg in event.arguments:
emit_cil += (
f' fprintf(fp, "{", " if emit_cil else ""}{arg.type.meta.cil_name} ");\n'
)
emit_cil += f" {_arg_to_member_name(arg)}{_RECURSE_BOILERPLATE}\n"
id_name = f"{_arg_to_member_name(arg)}->mName"
event_debug_info += f" chunk->addBytes({id_name}, strlen({id_name}) + 1);\n"
id_scope_entry = f"{_arg_to_member_name(arg)}->mScopeEntry"
if not first_scope_entry:
first_scope_entry = id_scope_entry
resource_scope_entries += f" {id_scope_entry}->mOffset = (S32)count;\n"
resource_scope_entries += (
f" {id_scope_entry}->mSize = {arg.type.meta.lso_size};\n"
)
resource_scope_entries += f" count += {id_scope_entry}->mSize;\n"
emit_assembly += (
f' fprintf(fp, "{", " if emit_assembly else ""}{arg.type!s} ");\n'
)
emit_assembly += f" {_arg_to_member_name(arg)}{_RECURSE_BOILERPLATE}\n"
member_name = _arg_to_member_name(arg)
scope_pass1 += f"""
if (scope->checkEntry({_arg_to_member_name(arg)}->mName))
{{
gErrorToText.writeError(fp, this, LSERROR_DUPLICATE_NAME);
}}
else
{{
{member_name}->mScopeEntry = scope->addEntry({member_name}->mName, LIT_VARIABLE, {arg.type.meta.lst_name});
}}
"""
if emit_cil:
# If we emitted anything for arguments we need to emit a space before and after parens.
emit_cil = ' fprintf(fp, " ");\n' + emit_cil
emit_cil += ' fprintf(fp, " ");\n'
generated_tree_source += _TREE_CLASS_DEF_TEMPLATE % {
"class_name": _event_to_class_name(event),
"event_name": event.name,
"default_recurse": default_recurse,
"event_size": sum(x.type.meta.lso_size for x in event.arguments),
"first_scope_entry": first_scope_entry or "false",
"resource_scope_entries": resource_scope_entries,
"event_debug_info": event_debug_info,
"emit_cil": emit_cil,
"scope_pass1": scope_pass1,
"emit_assembly": emit_assembly,
}
_write_if_different(output_file, generated_tree_source)