-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_zig.py
686 lines (529 loc) · 22.5 KB
/
_zig.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
from vim.rules.letter import (snake_case, proper, camel_case)
from macro_utilities import (replace_in_text, comment_choice,
execute_with_dictation, with_dictation)
from dragonfly import (Grammar, CompoundRule, Text, MappingRule,
Dictation, Function, Choice, IntegerRef)
from textwrap import (wrap)
class ZigEnabler(CompoundRule):
spec = "enable zig"
def _process_recognition(self, node, extras):
zigBootstrap.disable()
zigGrammar.enable()
print("Zig grammar enabled!")
class ZigDisabler(CompoundRule):
spec = "disable zig"
def _process_recognition(self, node, extras):
zigGrammar.disable()
zigBootstrap.enable()
print("Zig grammar disabled")
comparison_choice_map = {
"equal": "==",
"not equal": "!=",
"less or equal": "<=",
"greater or equal": ">=",
"less": "<",
"greater": ">",
}
def comparison_choice(name="comparison"):
return Choice(name, comparison_choice_map)
def output_test(test_name):
execute_with_dictation(
test_name,
lambda v: Text("test \"%s\" {\n" % v),
lambda v: replace_in_text("test \"$\" {}")
)
def output_constant(value_name, type_name):
if type_name != "":
value_type_components = str(type_name).split(" ")
if len(value_type_components) != 1:
type_name = proper(str(type_name))
output_value("const", value_name, type_name)
def output_variable(value_name, type_name, is_undefined=False):
if type_name != "":
value_type_components = str(type_name).split(" ")
if len(value_type_components) != 1:
type_name = proper(str(type_name))
else:
type_name = "_"
output_value("var", value_name, type_name, is_undefined=is_undefined)
def output_value(definition_type, value_name, type_name, is_undefined=False):
value_placeholder = "undefined" if is_undefined else "$"
if value_name == "":
command = replace_in_text("%s $ = %s;" % (definition_type, value_placeholder))
else:
value_name = format_value_name(value_name)
if type_name != "":
value_name += ": %s" % type_name
if is_undefined:
command_constructor = Text
else:
command_constructor = replace_in_text
command = command_constructor("%s %s = %s;" %
(definition_type, value_name, value_placeholder))
command.execute()
def output_type_definition(type_name, definition_type):
execute_with_dictation(
type_name,
lambda n: replace_in_text("const %s = %s {$};" % (proper(str(n)), definition_type)),
lambda n: Text("%s {}" % definition_type)
)
def output_for_loop(value_name, binding_name=None):
def output_with_value_name(name):
if binding_name is not None:
return Text("for (%s) |%s| {}" % (format_value_name(name), binding))
else:
return replace_in_text("for (%s) |$| {}" % format_value_name(name))
binding = format_value_name(binding_name) if binding_name is not None else "_"
execute_with_dictation(
value_name,
output_with_value_name,
lambda n: replace_in_text("for ($) |%s| {}" % binding)
)
def output_while_loop(value_name, binding_name=None):
maybe_unpack = "|%s| " % format_value_name(binding_name) if binding_name is not None else ""
execute_with_dictation(
value_name,
lambda n: Text("while (%s) %s{}" % (format_value_name(n), maybe_unpack)),
lambda n: replace_in_text("while ($) %s {}" % maybe_unpack)
)
def output_if(value_name, construct):
execute_with_dictation(
value_name,
lambda n: Text("%s (%s) {}" % (construct, format_value_name(n))),
lambda n: replace_in_text("%s ($) {}" % construct)
)
def output_switch(value_name):
execute_with_dictation(
value_name,
lambda n: Text("switch (%s) {}" % format_value_name(n)),
lambda n: replace_in_text("switch ($) {}")
)
def output_function(function_name, type_name, visibility_attribute=None):
attribute_string = visibility_attribute + " " if visibility_attribute is not None else ""
def output_with_type_name(name):
type_name_components = str(name).split(" ")
type_name_output = format_type_name(name) if len(type_name_components) != 1 else name
command_with_function_name = replace_in_text(
"%sfn %s($) %s {}" % (attribute_string, format_function_name(function_name), type_name_output)
)
command_without_function_name = replace_in_text(
"%sfn $(_) %s {}" % (attribute_string, type_name_output)
)
return with_dictation(
function_name,
lambda n: command_with_function_name,
lambda n: command_without_function_name
)
execute_with_dictation(
type_name,
output_with_type_name,
lambda n: output_with_type_name("_")
)
def output_if_comparison(value_name, construct, comparison=None):
if comparison is not None:
execute_with_dictation(
value_name,
lambda n: replace_in_text(
"%s (%s %s $) {}" % (construct, format_value_name(n), comparison)
),
lambda n: replace_in_text("%s ($ %s _) {}" % (construct, comparison))
)
def output_unpack_if(value_name, binding_name=None):
if binding_name is not None:
binding_name = "|%s|" % format_value_name(binding_name)
else:
if value_name == "":
binding_name = "|_|"
else:
binding_name = "|$|"
if value_name == "":
command = replace_in_text("if ($) %s {}" % binding_name)
else:
value_name = format_value_name(value_name)
command = Text("if (%s) %s {}" % (value_name, binding_name))
command.execute()
def format_value_name(name):
return snake_case(str(name).replace("-", "_"))
def output_comment(comment, comment_type=None):
if comment_type == "documentation":
output_text = "/// %s" % comment
elif comment_type is None:
output_text = "// %s" % comment
else:
output_text = "// %s %s" % (comment_type, comment)
Text(output_text).execute()
def output_comparison(value_name, comparison=None):
if comparison is not None:
execute_with_dictation(
value_name,
lambda n: Text("%s %s " % (format_value_name(n), comparison)),
lambda n: replace_in_text("$ %s _" % comparison)
)
def output_binding(value_name, is_pointer=False):
pointer_suffix = ".*" if is_pointer else ""
execute_with_dictation(
value_name,
lambda n: Text("%s%s = " % (format_value_name(n), pointer_suffix)),
lambda n: replace_in_text("$%s = " % pointer_suffix)
)
visibility_attribute_map = {
"external": "extern",
"public": "pub",
}
def format_function_name(function_name):
return camel_case(str(function_name).replace("-", ""))
def visibility_attribute_choice(name="visibility_attribute"):
return Choice(name, visibility_attribute_map)
class CastingSpec:
def __init__(self, casting_type, size, prefix):
self.casting_type = casting_type
self.size = size
self.prefix = prefix
def get_cast_expression(self, value):
type_to_cast_into = self.prefix + str(self.size)
return "%s(%s, %s)" % (self.casting_type, type_to_cast_into, value)
def get_safe_cast_expression(self, value):
type_to_cast_into = self.prefix + str(self.size)
return "@as(%s, %s)" % (type_to_cast_into, value)
class CastingFloat(CastingSpec):
def __init__(self, size):
CastingSpec.__init__(self, "@floatCast", size, "f")
class CastingSigned(CastingSpec):
def __init__(self, size):
CastingSpec.__init__(self, "@intCast", size, "i")
class CastingUnsigned(CastingSpec):
def __init__(self, size):
CastingSpec.__init__(self, "@intCast", size, "u")
typecast_choice_map = {
"you one twenty eight": CastingUnsigned(128),
"you sixty four": CastingUnsigned(64),
"you thirty two": CastingUnsigned(32),
"you sixteen": CastingUnsigned(16),
"you eight": CastingUnsigned(8),
"unsigned one twenty eight": CastingUnsigned(128),
"unsigned sixty four": CastingUnsigned(64),
"unsigned thirty two": CastingUnsigned(32),
"unsigned sixteen": CastingUnsigned(16),
"unsigned eight": CastingUnsigned(8),
"character": CastingUnsigned(8),
"char": CastingUnsigned(8),
"i one twenty eight": CastingSigned(128),
"i sixty four": CastingSigned(64),
"i thirty two": CastingSigned(32),
"i sixteen": CastingSigned(16),
"i eight": CastingSigned(8),
"signed one twenty eight": CastingSigned(128),
"signed sixty four": CastingSigned(64),
"signed thirty two": CastingSigned(32),
"signed sixteen": CastingSigned(16),
"signed eight": CastingSigned(8),
"float thirty two": CastingFloat(32),
"float sixty four": CastingFloat(64),
"float one twenty eight": CastingFloat(128),
"unsigned long": "u64",
"long": "i64",
"unsigned integer": "i32",
"integer": "i32",
"unsigned short": "u16",
"short": "i16",
}
def typecast_choice(name="type_choice"):
return Choice(name, typecast_choice_map)
def output_typecast(value_name, type_choice=None, is_safe=True):
def execute_without_type_choice(name):
execute_with_dictation(
name,
lambda n: replace_in_text("@as($, %s)" % format_value_name(n)),
lambda n: replace_in_text("@as($, _)")
)
def execute_with_type_choice(name):
def command_with_name(n):
safe_expression = type_choice.get_safe_cast_expression(n)
unsafe_expression = type_choice.get_cast_expression(n)
return Text(safe_expression if is_safe else unsafe_expression)
execute_with_dictation(
name,
lambda n: command_with_name(n),
lambda n: command_with_name("$")
)
if type_choice is None:
execute_without_type_choice(value_name)
else:
execute_with_type_choice(value_name)
calling_convention_choice_map = {
"see": ".C",
"standard": ".Stdcall",
"naked": ".Naked",
"asynchronous": ".Async",
}
def calling_convention_choice(name="calling_convention"):
return Choice(name, calling_convention_choice_map)
def output_calling_convention(calling_convention=None):
if calling_convention is None:
command = replace_in_text("callconv($)")
else:
command = Text("callconv(%s)" % calling_convention)
command.execute()
library_choice_map = {
"memory": "mem",
"standard memory": "std.mem",
"dynamic memory": "heap",
"standard dynamic memory": "std.heap",
"file system": "fs",
"standard file system": "std.fs",
"standard": "std",
}
def library_choice(name="library"):
return Choice(name, library_choice_map)
def output_library(library=None):
if library is not None:
Text(library).execute()
def format_index(index):
index_string = list(str(index))
index_string.reverse()
chunks = wrap("".join(index_string), 3)
chunks.reverse()
reversed_chunks = []
for c in chunks:
chunk_list = list(c)
chunk_list.reverse()
reversed_chunks.append("".join(chunk_list))
result = "_".join(reversed_chunks)
return result
def output_index(value_name, start=None, end=None, rest=False):
value_name = format_value_name(value_name)
if start is None and end is None:
command = replace_in_text("%s[$]" % value_name)
elif start is None:
formatted_end = format_index(end)
command = Text("%s[0..%s]" % (value_name, formatted_end))
elif end is None:
if rest:
formatted_start = format_index(start)
command = Text("%s[%s..]" % (value_name, formatted_start))
else:
formatted_start = format_index(start)
command = Text("%s[%s]" % (value_name, formatted_start))
else:
formatted_start = format_index(start)
formatted_end = format_index(end)
command = Text("%s[%s..%s]" % (value_name, formatted_start, formatted_end))
command.execute()
def output_method_call(function_name, value_name, with_try=False):
function_name = format_function_name(function_name)
value_name = format_value_name(value_name)
command_text = "try " if with_try else ""
if function_name == "" and value_name == "":
command_text += "$._()"
command = replace_in_text(command_text)
elif function_name == "":
command_text += "%s." % value_name
command = Text(command_text)
elif value_name == "":
command_text += "$.%s()" % function_name
command = replace_in_text(command_text)
else:
command_text += "%s.%s()" % (value_name, function_name)
command = Text(command_text)
command.execute()
def output_function_call(function_name, value_name, with_try=False):
function_name = format_function_name(function_name)
value_name = format_value_name(value_name)
command_text = "try " if with_try else ""
if function_name == "" and value_name == "":
command_text += "$(_)"
command = replace_in_text(command_text)
elif function_name == "":
command_text += "$(%s)" % value_name
command = replace_in_text(command_text)
elif value_name == "":
command_text += "%s($)" % function_name
command = replace_in_text(command_text)
else:
command_text += "%s(%s)" % (function_name, value_name)
command = Text(command_text)
command.execute()
build_target_name_choice_map = {
"linux": "linux",
"windows": "windows",
"free BSD": "freebsd",
"Mac OS": "macos",
"OS x": "macos",
"OS ten": "macos",
}
def build_target_name_choice(name="build_target_name"):
return Choice(name, build_target_name_choice_map)
def output_zig_build(build_target_name=None, gnu=False, optimization=None, run=False):
libc_spec = "-gnu" if gnu else ""
running = "run " if run else ""
command_output = "zig build %s" % running
if build_target_name is not None:
command_output = "zig build %s-Dtarget=native-%s%s" % (
running, build_target_name, libc_spec)
elif gnu:
command_output = "zig build %s-Dtarget=native-native-gnu" % running
if optimization is not None:
command_output += " %s" % optimization
Text(command_output).execute()
optimization_choice_map = {
"release": "-Drelease-fast=true",
"fast": "-Drelease-fast=true",
"release fast": "-Drelease-fast=true",
"safe": "-Drelease-safe=true",
"release safe": "-Drelease-safe=true",
"small": "-Drelease-small=true",
"release small": "-Drelease-small=true",
}
def optimization_choice(name="optimization"):
return Choice(name, optimization_choice_map)
initialization_type_choice_map = {
"executable": "exe",
"binary": "exe",
"library": "lib",
"lib": "lib",
}
def initialization_type_choice(name="initialization_type"):
return Choice(name, initialization_type_choice_map)
def output_zig_initialization(initialization_type=None):
if initialization_type is not None:
Text("zig init-%s" % initialization_type).execute()
def output_using_namespace(visibility_attribute=None):
visibility_prefix = "%s " % visibility_attribute if visibility_attribute is not None else ""
Text("%susingnamespace " % visibility_prefix).execute()
def output_return(value_name):
execute_with_dictation(
value_name,
lambda n: Text("return %s;" % format_value_name(n)),
lambda n: replace_in_text("return $;")
)
def output_import(value_name):
execute_with_dictation(
value_name,
lambda v: replace_in_text("const %s = import(\"$\");" % format_value_name(v)),
lambda v: replace_in_text("const $ = import(\"_\");")
)
def output_size_of(type_name):
execute_with_dictation(
type_name,
lambda n: Text("@sizeOf(%s)" % format_type_name(n)),
lambda n: replace_in_text("@sizeOf($)")
)
def output_import_package(value_name):
package_name = format_value_name(value_name)
Text("const %s = @import(\"%s\");" % (package_name, package_name)).execute()
def format_type_name(name):
return proper(str(name))
class ZigUtilities(MappingRule):
mapping = {
# control flow
"if [<value_name>]": Function(output_if, construct="if"),
"if [<value_name>] is <comparison>": Function(output_if_comparison, construct="if"),
"unpack [<value_name>] [into <binding_name>]": Function(output_unpack_if),
"else if [<value_name>]": Function(output_if, construct="else if"),
"else if [<value_name>] is <comparison>": Function(output_if_comparison,
construct="else if"),
"for loop [over <value_name>] [binding <binding_name>]": Function(output_for_loop),
"while [<value_name>]": Function(output_while_loop, binding_name=None),
"binding [<binding_name>] while [<value_name>] ": Function(output_while_loop,
binding_name="_"),
"switch [on <value_name>]": Function(output_switch),
# logic checks
"check [<value_name>] is <comparison>": Function(output_comparison),
# value and function definitions
"constant [<value_name>] [of type <type_name>]": Function(output_constant),
"variable [<value_name>] [of type <type_name>]": Function(output_variable),
"variable [<value_name>] [of type <type_name>] is undefined": Function(output_variable,
is_undefined=True),
"test [<test_name>]": Function(output_test),
"[<visibility_attribute>] function [<function_name>] [returning <type_name>]":
Function(output_function),
"(call|calling) convention [<calling_convention>]": Function(output_calling_convention),
# type definitions
"struct [<type_name>]": Function(output_type_definition, definition_type="struct"),
"union [<type_name>]": Function(output_type_definition, definition_type="union(enum)"),
"enumeration [<type_name>]": Function(output_type_definition, definition_type="enum"),
# assignment
"[<value_name>] equals": Function(output_binding),
"pointer [<value_name>] equals": Function(output_binding, is_pointer=True),
# type casts / conversions
"cast [<value_name>] [into <type_choice>]": Function(output_typecast, is_safe=False),
"[<value_name>] as [<type_choice>]": Function(output_typecast),
# calling methods and functions
"method [<function_name>] [on <value_name>]": Function(output_method_call),
"call [<function_name>] [on <value_name>]": Function(output_function_call),
"try method [<function_name>] [on <value_name>]": Function(output_method_call,
with_try=True),
"try call [<function_name>] [on <value_name>]": Function(output_function_call,
with_try=True),
# indexing into slices and arrays
"index [<start>] [to <end>]": Function(output_index),
"index [<start>] onwards": Function(output_index, rest=True),
"indexing [<start>] [to <end>] into <value_name>": Function(output_index),
"indexing [<start>] onwards into <value_name>": Function(output_index, rest=True),
# miscellaneous conveniences
"[<visibility_attribute>] using namespace": Function(output_using_namespace),
"import [<value_name>]": Function(output_import),
"import package <value_name>": Function(output_import_package),
"[<comment_type>] comment [<comment>]": Function(output_comment),
"documentation comment [<comment>]": Function(output_comment, comment_type="documentation"),
"(library|lib) <library>": Function(output_library),
"return [<value_name>]": Function(output_return),
# keyword conveniences
"size of [<type_name>]": Function(output_size_of),
"compile time": Text("comptime "),
"public": Text("pub "),
"external": Text("extern "),
"a sink": Text("async "),
"await": Text("await "),
"try": Text("try "),
"catch": Text("catch "),
"defer": Text("defer "),
"see import": replace_in_text("@cImport({$});"),
"see define": replace_in_text("@cDefine($);"),
"see include": replace_in_text("@cInclude($);"),
"arrow": Text(" => "),
"pointer": Text("ptr"),
# terminal commands
"zig build [<optimization>] [for <build_target_name>]": Function(output_zig_build,
gnu=False),
"zig build [<optimization>] [for <build_target_name>] with (freedom|fascism)":
Function(output_zig_build, gnu=True),
"zig build run [<optimization>] [for <build_target_name>]": Function(output_zig_build,
gnu=False, run=True),
"zig build run [<optimization>] [for <build_target_name>] with (freedom|fascism)":
Function(output_zig_build, gnu=True, run=True),
"zig (in it|initialize) <initialization_type>": Function(output_zig_initialization),
}
extras = [
Dictation("test_name", default=""),
Dictation("value_name", default=""),
Dictation("type_name", default=""),
Dictation("function_name", default=""),
Dictation("binding_name", default=None),
Dictation("comment", default=""),
comment_choice("comment_type"),
comparison_choice("comparison"),
visibility_attribute_choice("visibility_attribute"),
typecast_choice("type_choice"),
calling_convention_choice("calling_convention"),
library_choice("library"),
IntegerRef("start", 0, 10000000),
IntegerRef("end", 0, 10000000),
build_target_name_choice("build_target_name"),
optimization_choice("optimization"),
initialization_type_choice("initialization_type"),
]
# The main Zig grammar rules are activated here
zigBootstrap = Grammar("zig bootstrap")
zigBootstrap.add_rule(ZigEnabler())
zigBootstrap.load()
zigGrammar = Grammar("zig grammar")
zigGrammar.add_rule(ZigUtilities())
zigGrammar.add_rule(ZigDisabler())
zigGrammar.load()
zigGrammar.disable()
def unload():
global zigGrammar
if zigGrammar:
zigGrammar.unload()
zigGrammar = None