-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmash
More file actions
2094 lines (1671 loc) · 71.1 KB
/
Copy pathsmash
File metadata and controls
2094 lines (1671 loc) · 71.1 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
#!/usr/bin/env python3
"""
SMASH - Simple Modern Advanced SHell
JavaScript-style shell scripting that transpiles to bash
Author: Flaneurette, Claude AI and contributors
License: MIT
"""
import re
import sys
import subprocess
import os
VERSION = "1.3-0"
# Track PID
SMASH_UNIQUE_PID = 1
# Global tracking dictionary
SMASH_PROCESSES = {} # {pid: {'var': 'nginx', 'cmd': 'systemctl start nginx'}}
# Precision of floating points
FLOAT_PRECISION = 2
# Functions
FUNC_PREFIX = "smashFunc"
FUNC_PID = 1
def transpile_smash(code):
"""
Convert JavaScript-style SMASH syntax to bash
---------------------------------------------------------
NOTE: The order of regexing is extremely important.
NOTE: If you move around rules, SMASH will fail.
NOTE: Always first run test-suite.smash before commiting
---------------------------------------------------------
"""
# SMASH HELPER FUNCTIONS
def reserved_check(code):
# we allow (int), (float), (string) for casting.
RESERVED_WORDS = [
'abstract','arguments','async','await',
'boolean','break','byte','case',
'catch','class','const',
'continue','debugge','default','delete',
'do','double','else','enum',
'eval','export','extends',
'final','finally',
'function','goto','if','implements',
'import','instanceof',
'interface','let','long',
'native','new','package',
'private','protected','public','return',
'short','static','super','switch',
'synchronized','this','throw','throws',
'transient','try','typeof',
'using','var','void','volatile',
'while','yield']
# Pre-compile reserved word pattern
ESCAPED_RESERVED = '|'.join(re.escape(word) for word in RESERVED_WORDS)
# Compile patterns once at module level
COMMENT_START_PATTERN = re.compile(r'^\s*(#|//|\/\*|\*\/)')
ECHO_START_PATTERN = re.compile(r'^\s*(echo|print)\s+')
RESERVED1 = re.compile(r'\b(var|let|const)\s+\b(' + ESCAPED_RESERVED + r')\b')
lines = code.split('\n')
for line in lines:
# Exclude comments
if COMMENT_START_PATTERN.search(line):
continue
# Exclude echo and print
if ECHO_START_PATTERN.search(line):
continue
# Search illegal keyword assignments and mistakes.
if RESERVED1.search(line):
print("Parsed line failed:" + line)
return True
return False
def heal_code(code):
"""Fix patterns broken by comment conversion"""
# Fix protocols (greedy to catch multiple on same line)
protocols = ['http', 'https', 'ftp', 'sftp', 'ssh', 'git', 'file']
for protocol in protocols:
# Match protocol:# followed by non-space (likely part of URL)
code = re.sub(
rf'{protocol}:#([^\s])',
rf'{protocol}://\\1',
code
)
# Fix shebang if it got mangled: #!#usr#bin#env -> #!/usr/bin/env
code = code.replace('#!#usr#bin#env', '#!/usr/bin/env')
code = code.replace('#!#bin#bash', '#!/bin/bash')
# Minor semicolon fix, to be certain.
code = code.replace('}";;','}";')
# Healing markers - remove these and what follows
markers = {
r':rem-brace-open:\s*\{': '',
r':rem-brace-closed:\s*\}': '',
r':rem-semi:\s*;': '',
r':rem-par-open:\s*\(': '',
r':rem-par-closed:\s*\)': '',
r':rem-par-semi:\s*\)': '',
# FIX for array indices *within* forEach loop:
r'];\s*\ndone:rem-par-semi:': ']}\n',
r']\s*\ndone:rem-par-semi:': ']}\n',
r'\ndone:rem-par-semi:': '\ndone;',
}
for marker, replacement in markers.items():
code = re.sub(marker, replacement, code)
# FIX: incomplete code
code = re.sub(
r'(let|var|const)\s+(\w+)\s*=\s+\$\{',
r'\2=${',
code
)
# At the end, do proper interpolation
# ---------------------------------------------------
# Interpolation
# ---------------------------------------------------
# Text interpolation
code = text_interpolation(code)
return code
def convert_comments(code):
"""Convert // comments to # (only at line start)"""
lines = code.split('\n')
result = []
for line in lines:
stripped = line.lstrip()
if stripped.startswith('//'):
# Get original indentation
indent = line[:len(line) - len(stripped)]
comment_text = stripped[2:] # Remove //
line = indent + '#' + comment_text
result.append(line)
return '\n'.join(result)
def convert_block_comment(match):
"""Convert /* */ to # block comments for bash"""
comment_text = match.group(1)
lines = comment_text.split('\n')
return '\n'.join('# ' + line.strip() for line in lines)
def convert_array_elements(elements):
"""Convert ["a", "b", "c"] to "a" "b" "c" for bash"""
# Split by comma, strip quotes, re-quote for bash
items = [item.strip() for item in elements.split(',')]
return ' '.join(items)
def preprocess_code(code):
"""Normalize whitespace before transpilation"""
# Convert tabs to spaces (4 spaces standard)
code = code.replace('\t', ' ')
# Normalize line endings (Windows/Mac/Linux)
code = code.replace('\r\n', '\n').replace('\r', '\n')
# Remove trailing whitespace from each line
lines = code.split('\n')
lines = [line.rstrip() for line in lines]
code = '\n'.join(lines)
# Remove excessive blank lines (more than 2 consecutive)
code = re.sub(r'\n{3,}', '\n\n', code)
return code
def convert_variable_assignment(match):
varname = match.group(2)
value = match.group(3).strip()
# Arithmetic only if STRICTLY numeric expression
if (
re.fullmatch(r'[A-Za-z0-9_+\-*/%() \t]+', value)
and re.search(r'[+\-*/%]', value)
):
return f'{varname}=$(({value}))'
return f'{varname}={value}'
# String concatenation: "text" + var + "more"
# Strategy: Find all echo statements with + operators and rebuild them
def fix_echo_concat(match):
if re.search(r'\s+awk\s+', match.group(0)):
return match.group(0)
parts = match.group(1).split('+')
result = []
for i, part in enumerate(parts):
part = part.strip()
# If it's a quoted string, remove quotes and add to result
if part.startswith('"') and part.endswith('"'):
result.append(part[1:-1])
# If it's a variable, add with $ prefix
elif part and not part.startswith('"'):
result.append(f'${part}')
# If it's just a string part, add as-is
elif part:
result.append(part.strip('"'))
return f'echo "{"".join(result)}"'
def transform_switch(code):
"""Convert JavaScript-style switch to bash case"""
lines = code.split('\n')
result = []
in_switch = False
for line in lines:
stripped = line.strip()
# switch (var) {
if stripped.startswith('switch '):
match = re.match(r'switch\s*\(\s*(\w+)\s*\)\s*\{', stripped)
if match:
var = match.group(1)
indent = line[:len(line) - len(stripped)]
result.append(f'{indent}case ${var} in')
in_switch = True
continue
if in_switch:
# case "value":
if stripped.startswith('case '):
case_match = re.match(r'case\s+"([^"]+)"\s*:', stripped)
if case_match:
value = case_match.group(1)
indent = line[:len(line) - len(stripped)]
result.append(f'{indent}"{value}")')
continue
# case variable:
var_match = re.match(r'case\s+(\w+)\s*:', stripped)
if var_match:
var = var_match.group(1)
indent = line[:len(line) - len(stripped)]
result.append(f'{indent}${var})')
continue
# default:
if stripped == 'default:':
indent = line[:len(line) - len(stripped)]
result.append(f'{indent}*)')
continue
# break; (more flexible matching)
if stripped == 'break;' or stripped == 'break':
indent = line[:len(line) - len(stripped)]
result.append(f'{indent};;')
continue
# Closing }
if stripped == '}':
indent = line[:len(line) - len(stripped)]
result.append(f'{indent}esac')
in_switch = False
continue
result.append(line)
return '\n'.join(result)
def text_interpolation(code):
global FLOAT_PRECISION
# First, handle variable assignments with backticks separately
# Pattern: let var = `...` or var = `...`
def assignment_repl(match):
global FLOAT_PRECISION
varname = match.group(1)
content = match.group(2)
# Apply all the same transformations but DON'T wrap in quotes
content = re.sub(r'(?:n|\(int\))\s*\{(\w+)\}', r'$(( ${\1//[^0-9]/} ))', content)
content = re.sub(r'(?:f|\(float\))\s*\{(\w+)\}',lambda m: f'$(printf "%.{FLOAT_PRECISION}f" "${{{m.group(1)}//[^0-9.-]/}}" 2>/dev/null || echo "0.00")',content)
content = re.sub(r'(?:s|\(string\))\s*\{(\w+)\}', r'${\1}', content)
content = re.sub(r'(?:u|\(upper\))\s*\{(\w+)\}', r'${\1^^}', content)
content = re.sub(r'(?:l|\(lower\))\s*\{(\w+)\}', r'${\1,,}', content)
content = re.sub(r'(?:b|\(basename\))\s*\{(\w+)\}', r'$(basename $\1)', content)
content = re.sub(r'(?:d|\(dirname\))\s*\{(\w+)\}', r'$(dirname $\1)', content)
content = re.sub(r'(?<!\$)\{(\w+)\}', r'${\1}', content)
content = re.sub(r'#\{(\w+)\}', r'${\1}', content)
return f'{varname}={content}' # No quotes!
# Match: var = `...`
code = re.sub(r'(\w+)\s*=\s*`([^`]+)`', assignment_repl, code)
# Then handle regular backtick interpolation (in echo, etc.)
def repl(match):
global FLOAT_PRECISION
content = match.group(1)
# Same transformations but WITH quotes
content = re.sub(r'(?:n|\(int\))\s*\{(\w+)\}', r'$(( ${\1//[^0-9]/} ))', content)
content = re.sub(r'(?:f|\(float\))\s*\{(\w+)\}',lambda m: f'$(printf "%.{FLOAT_PRECISION}f" "${{{m.group(1)}//[^0-9.-]/}}" 2>/dev/null || echo "0.00")', content)
content = re.sub(r'(?:s|\(string\))\s*\{(\w+)\}', r'${\1}', content)
content = re.sub(r'(?:u|\(upper\))\s*\{(\w+)\}', r'${\1^^}', content)
content = re.sub(r'(?:l|\(lower\))\s*\{(\w+)\}', r'${\1,,}', content)
content = re.sub(r'(?:b|\(basename\))\s*\{(\w+)\}', r'$(basename $\1)', content)
content = re.sub(r'(?:d|\(dirname\))\s*\{(\w+)\}', r'$(dirname $\1)', content)
content = re.sub(r'(?<!\$)\{(\w+)\}', r'${\1}', content)
content = re.sub(r'#\{(\w+)\}', r'${\1}', content)
return f'"{content}"' # With quotes for echo etc.
code = re.sub(r'`([^`]+)`', repl, code)
return code
def what_if(code, original_smash_code):
"""
what if (condition) { ... }
- If console.report() present: writes report to file during transpilation
- Otherwise: executes custom code inside braces
"""
# Pattern to match what if blocks
pattern = r'what\s+if\s*\(\s*(\w+)\s*(==|!=|>|<|>=|<=)\s*([^)]+)\)\s*\{([^}]+)\}'
def replace_func(match):
var_name = match.group(1)
operator = match.group(2)
value = match.group(3).strip()
body = match.group(4).strip()
# Check if console.report() is present
report_match = re.search(r'console\.report\([\'"]([^\'"]+)[\'"]\)', body)
if report_match:
log_file = report_match.group(1)
# Generate report lines
report_lines = []
report_lines.append(f"=== WHAT IF: {var_name} {operator} {value} ===")
lines = original_smash_code.split('\n')
for i, line in enumerate(lines, 1):
if var_name in line:
# Extract comment if present
comment = ""
if '//' in line:
comment_part = line.split('//')[1].strip()
comment = f" // {comment_part}"
report_lines.append(f"Line {i}: {line.strip()}{comment}")
# Write report to file NOW (during transpilation)
try:
with open(log_file, 'a') as f:
f.write('\n'.join(report_lines) + '\n')
except Exception as e:
print(f"Warning: Could not write to {log_file}: {e}")
# Remove console.report() from body and keep other commands
custom_body = re.sub(r'console\.report\([^)]+\);\s*', '', body)
# Return only the custom commands (if any)
if custom_body.strip():
return custom_body
else:
return '' # Remove the what if block entirely
else:
# No console.report - just return the body as-is (it's custom logic)
return body
code = re.sub(pattern, replace_func, code, flags=re.DOTALL)
return code
def time_travel(code):
global FUNC_PREFIX, FUNC_PID
def build_func(timetype, time, name, code_body, values=None):
val_heap = ''
func = ''
if values:
for val in values:
val_heap += f'local {val}\n'
if name:
# Build bash function
func = f'{name}() {{\n'
if val_heap:
func += val_heap
func += f'{code_body}\n'
func += '}\n'
return func
def timertype(timetype, time, func_name):
result = ''
# Convert milliseconds to seconds
time_sec = int(time) / 1000
if timetype == 'setTimeout' and time:
result += f'sleep {time_sec}\n'
result += f'{func_name}\n'
elif timetype == 'setInterval' and time:
result += f'while true; do\n'
result += f' {func_name}\n'
result += f' sleep {time_sec}\n'
result += f'done\n'
return result
new_code = code
# Patterns with closing parenthesis
m1 = r'(setTimeout|setInterval)\(\(\)\s*=>\s*\{([^}]*)}\s*,\s*([0-9]+)\)\s*(;?)'
m2 = r'(setTimeout|setInterval)\(function\s*\(\)\s*\{([^}]*)}\s*,\s*([0-9]+)\)\s*(;?)'
m3 = r'(setTimeout|setInterval)\((\w+),\s*([0-9]+)\)\s*(;?)'
# Arrow functions
timespace1 = re.search(m1, new_code)
if timespace1:
s1 = timespace1.group(1) # setTimeout or setInterval
s2 = timespace1.group(2) # code body
s3 = timespace1.group(3) # time in ms
new_func_name = FUNC_PREFIX + str(FUNC_PID)
func_def = build_func(s1, s3, new_func_name, s2)
timer_call = timertype(s1, s3, new_func_name)
replacement = func_def + '\n' + timer_call
new_code = re.sub(m1, replacement, new_code, count=1)
FUNC_PID += 1
# Function declarations
timespace2 = re.search(m2, new_code)
if timespace2:
s1 = timespace2.group(1)
s2 = timespace2.group(2)
s3 = timespace2.group(3)
new_func_name = FUNC_PREFIX + str(FUNC_PID)
func_def = build_func(s1, s3, new_func_name, s2)
timer_call = timertype(s1, s3, new_func_name)
replacement = func_def + '\n' + timer_call
new_code = re.sub(m2, replacement, new_code, count=1)
FUNC_PID += 1
# Named function references
timespace3 = re.search(m3, new_code)
if timespace3:
s1 = timespace3.group(1)
s2 = timespace3.group(2) # existing function name
s3 = timespace3.group(3)
# Just create timer call, function already exists
timer_call = timertype(s1, s3, s2)
new_code = re.sub(m3, timer_call, new_code, count=1)
return new_code
def let_it_be(code):
"""Process 'let it be' constructs"""
max_iterations = 10
iteration = 0
global FLOAT_PRECISION
while re.search(r'let\s+it\s+be;', code) and iteration < max_iterations:
iteration += 1
match_let_it_be = re.search(r'let\s+it\s+be;', code)
if not match_let_it_be:
break
let_it_be_pos = match_let_it_be.start()
code_before = code[:let_it_be_pos]
# Find the last "let it = ..."
match_it = None
for match in re.finditer(r'let\s+it\s*=\s*([^;]+);', code_before):
match_it = match
if not match_it:
break
it_value = match_it.group(1).strip()
# Find the last "be = ..."
match_be = None
for match in re.finditer(r'be\s*=\s*([^;\n]+);?', code_before):
match_be = match
if not match_be:
break
be_value = match_be.group(1).strip()
# Check if there's a loop between "let it" and "let it be"
code_between = code[match_it.end():let_it_be_pos]
# Detect both SMASH syntax and bash syntax loops
has_loop = (
'; do' in code_between or
' do\n' in code_between or
'for (let' in code_between or
'for (' in code_between or
'while (' in code_between or
'{' in code_between # Any block with braces
)
# Build replacement
type_cast_match = re.match(r'^\(?(int|float|string)\)?$', be_value)
if type_cast_match:
cast_type = type_cast_match.group(1)
if cast_type == 'int':
transform = 'it=$(( ${it//[^0-9]/} ))'
elif cast_type == 'float':
transform = 'it=$(printf "%.{FLOAT_PRECISION}f" ${it//[^0-9.-]/} 2>/dev/null || echo "0.00")'
elif cast_type == 'string':
transform = f'it="{it_value}"'
replacement = transform if has_loop else f'it={it_value}\n{transform}'
elif be_value.startswith('(') and be_value.endswith(')'):
expression = be_value[1:-1]
expression = re.sub(r'\bit\b', '$it', expression)
transform_original = f'it=$(( {expression} ))'
# Find all word-like tokens that could be variables
potential_vars = re.findall(r'\b([a-zA-Z_]\w*)\b', expression)
has_float = False
# Check if any variable is a float
for var_name in potential_vars:
if var_name != 'it':
# Check if this variable was defined as a float
a_match = r'(\$?|)' + var_name + r'\s*=\s*["\']?([0-9]+\.[0-9]+)["\']?\s*(;?)'
check_float = re.search(a_match, code)
if check_float:
has_float = True
break
# Generate the appropriate command
if has_float:
# Ensure all variables have $ for awk
awk_expression = expression
for var_name in potential_vars:
if var_name != 'it':
awk_expression = re.sub(r'(?<!\$)\b' + var_name + r'\b', '$' + var_name, awk_expression)
transform = f'it=$(awk "BEGIN {{printf \\"%.{FLOAT_PRECISION}f\\", {awk_expression}}}")'
else:
# Use $(( )) for integer arithmetic
transform = transform_original
# Replace in code
code = code.replace(transform_original, transform)
replacement = transform if has_loop else f'it={it_value}\n{transform}'
else:
replacement = f'it={be_value}' if has_loop else f'it={it_value}\nit={be_value}'
# Remove "let it = ..." only if NOT in loop
if not has_loop:
code = code.replace(match_it.group(0), '', 1)
# Remove "be = ..."
code = code.replace(match_be.group(0), '', 1)
# Replace "let it be;"
code = code.replace('let it be;', replacement, 1)
return code
def run_bird(code):
global SMASH_UNIQUE_PID
global SMASH_PROCESSES
run_pattern1 = r'(let|var|const)\s+\$?(\w+)\s*=\s*run\s+bird\s+\$\((.*?)\);'
run_pattern2 = r'(let|var|const)\s+\$?(\w+)\s*=\s*run\s+bird\s+([a-zA-Z0-9]+);'
def start_command(match):
global SMASH_UNIQUE_PID
var_name = match.group(2)
command = match.group(3)
pid_var = f"{var_name}_PID_{SMASH_UNIQUE_PID}"
# Track it
SMASH_PROCESSES[SMASH_UNIQUE_PID] = {
'var': var_name,
'cmd': command,
'pid_var': pid_var
}
SMASH_UNIQUE_PID += 1
return f"{pid_var}=$( {command} )"
def start_service(match):
global SMASH_UNIQUE_PID
var_name = match.group(2)
service_name = match.group(3) # The actual service
command = 'systemctl start ' + service_name
pid_var = f"{var_name}_PID_{SMASH_UNIQUE_PID}"
SMASH_PROCESSES[SMASH_UNIQUE_PID] = {
'var': var_name,
'cmd': command,
'pid_var': pid_var,
'service': service_name # Track service name separately
}
SMASH_UNIQUE_PID += 1
return f"{pid_var}=$(systemctl start {service_name})"
code = re.sub(run_pattern1, start_command, code)
code = re.sub(run_pattern2, start_service, code)
return code
def object_parsing(code):
pat = r'(let|var|const)\s*(\w+)\s*=\s*\{\s*([\s\S]+?)\}\s*;'
pat2 = r'\b(\w+)\s*:\s*(["\']?)((\"|\')[a-zA-Z]+(\"|\')|[0-9]+\.[0-9]+|[0-9]+)\s*,?'
for matches in re.finditer(pat, code):
if matches.group(2):
build_command = f"declare -A {matches.group(2)}\n"
block = matches.group(3)
block = re.sub(r'^\n', '', block)
for match in re.finditer(pat2, block):
key = match.group(1)
value = match.group(3)
if value.isdigit():
build_command += f"{matches.group(2)}[{key}]={value}\n"
elif value.replace('.', '', 1).isdigit():
build_command += f'{matches.group(2)}[{key}]="{value}"\n'
else:
value = value.strip('"\'')
build_command += f'{matches.group(2)}[{key}]="{value}"\n'
# matches.group(0) is the entire JS object match
# re.escape ensures special characters in the match don't break the substitution
code = re.sub(re.escape(matches.group(0)), build_command, code)
return code
def find_object_declarations(code):
pat = r'(let|var|const)\s*(\w+)\s*=\s*(\w+)\.(\w+)\s*;'
for match in re.finditer(pat, code):
var_name = match.group(2)
obj = match.group(3)
key = match.group(4)
new_command = f'{var_name}="${{{obj}[{key}]}}"'
code = code.replace(match.group(0), new_command)
return code
def find_json_first(name, code):
find = r'(var|let|const)\s+' + name + r'\s*=\s*JSON\.parse\((.*)\)\s*;'
matches = re.finditer(find, code)
# re.finditer returns an iterator, it's always truthy!
# you need to get the first match manually
first = next(matches, None)
if first:
code = re.sub(find,'\n',code)
return first.group(2).strip('"\'')
return False
def remove_json(name, code):
find = r'(var|let|const)\s+' + name + r'\s*=\s*JSON\.parse\(([^)]*)\)\s*;'
code = re.sub(find,'\n',code)
return code
def detect_object_access(code):
# First replace all JS objects with Bash associative arrays
code = object_parsing(code)
# Match: echo obj.key; or print obj.key;
pat1 = r'(echo|print)\s+(\w+)\.(\w+)\s*;'
# Match: print(obj.key);
pat2 = r'print\((\w+)\.(\w+)\)\s*;'
# Handle echo/print obj.key
for match in re.finditer(pat1, code):
obj = match.group(2)
key = match.group(3)
json_result = find_json_first(obj, code)
if json_result:
new_command = f'echo $(echo "${json_result}" | jq -r .{key})'
code = code.replace(match.group(0), new_command)
code = remove_json(obj,code)
else:
new_command = f'echo "${{{obj}[{key}]}}"'
code = code.replace(match.group(0), new_command)
# Handle print(obj.key)
for match in re.finditer(pat2, code):
obj = match.group(1)
key = match.group(2)
json_result = find_json_first(obj, code)
if json_result:
new_command = f'echo $(echo "${json_result}" | jq -r .{key})'
code = code.replace(match.group(0), new_command)
code = remove_json(obj,code)
else:
new_command = f'echo "${{{obj}[{key}]}}"'
code = code.replace(match.group(0), new_command)
# Pre-fix array.length, as smash thinks it's object access...
code = pre_fixing(code)
code = find_object_declarations(code)
return code
def pre_fixing(code):
# Find all string methods first.
code = string_methods(code)
# Maths
code = math_functions(code)
# Pre-fixing code as smash thinks it's object access... when it sees this: string.value, even if we mean: array.length
code = re.sub(r'(\w+)\.length', r'${#\1[@]}', code)
return code
def string_methods(code):
f = re.compile(r'(\w+)\.(startsWith|endsWith|includes|trim|replace|replaceAll|repeat)\(([^)]*)\)\s*;?')
def replace(m):
var = m.group(1)
method = m.group(2)
args = m.group(3)
if method == "startsWith":
val = args.strip('"\'')
return f'[[ "${var}" == {val}* ]]'
elif method == "endsWith":
val = args.strip('"\'')
return f'[[ "${var}" == *{val} ]]'
elif method == "includes":
val = args.strip('"\'')
return f'[[ "${var}" == *{val}* ]]'
elif method == "trim":
return var + '=$(echo "$' + var + '" | sed "s/^[[:space:]]*//;s/[[:space:]]*$//")'
elif method == "replace":
old = args.split(',')[0].strip().strip('"\'')
new = args.split(',')[1].strip().strip('"\'')
return var + '=$(echo "$' + var + '" | sed "s/' + old + '/' + new + '/")'
elif method == "replaceAll":
old = args.split(',')[0].strip().strip('"\'')
new = args.split(',')[1].strip().strip('"\'')
return var + '=$(echo "$' + var + '" | sed "s/' + old + '/' + new + '/g")'
elif method == "repeat":
return var + '=$(printf "$' + var + '%.0s" $(seq 1 ' + args + '))'
return m.group(0) # no match, return original
return f.sub(replace, code)
def math_functions(code):
global FLOAT_PRECISION
f1 = re.compile(r'(let|var|const)\s+(\w+)\s*=\s*(parseInt|parseFloat|Math\.floor|Math\.ceil|Math\.round|Math\.abs)\(([^)]*)\)\s*;?')
f2 = re.compile(r'(parseInt|parseFloat|Math\.floor|Math\.ceil|Math\.round|Math\.abs)\(([^)]*)\)\s*;?')
def replace(m):
global FLOAT_PRECISION
name = m.group(2)
method = m.group(3)
args = m.group(4)
val = args.strip().strip('"\'')
is_literal = not re.match(r'^\w+$', val) or args.strip().startswith(('"', "'"))
if method == "parseInt":
if is_literal:
return f'{name}={re.sub("[^0-9]", "", val)}'
return f'{name}=$(( ${{{val}%%.*}} ))'
elif method == "parseFloat":
if is_literal:
return f'{name}=$(printf "%.{FLOAT_PRECISION}f" "{val}")'
return f'{name}=$(printf "%.{FLOAT_PRECISION}f" "${{{val}//[^0-9.-]/}}" 2>/dev/null || echo "0.00")'
elif method == "Math.floor":
return f'{name}=$(echo "$' + val + '" | awk \'{print int($1)}\')'
elif method == "Math.ceil":
return f'{name}=$(echo "$' + val + '" | awk \'{print ($1==int($1))?$1:int($1) + 1}\')\n'
elif method == "Math.round":
return f'{name}=$(printf "%.0f" "$' + val + '")'
elif method == "Math.abs":
return f'{name}=${{{val}#-}}'
return m.group(0) # no match, return original
def replace2(m):
global FLOAT_PRECISION
method = m.group(1)
args = m.group(2)
val = args.strip().strip('"\'')
is_literal = not re.match(r'^\w+$', val) or args.strip().startswith(('"', "'"))
if method == "parseInt":
if is_literal:
return f'{re.sub("[^0-9]", "", val)}'
return f'$(( ${{{val}%%.*}} ))'
elif method == "parseFloat":
if is_literal:
return f'$(printf "%.{FLOAT_PRECISION}f" "{val}")'
return f'$(printf "%.{FLOAT_PRECISION}f" "${{{val}//[^0-9.-]/}}" 2>/dev/null || echo "0.00")'
elif method == "Math.floor":
return '$(echo "$' + val + '" | awk \'{print int($1)}\')'
elif method == "Math.ceil":
return f'$(echo "$' + val + '" | awk \'{print ($1==int($1))?$1:int($1) + 1}\')'
elif method == "Math.round":
return f'$(printf "%.0f" "$' + val + '")'
elif method == "Math.abs":
return f'${{{val}#-}}'
return m.group(0) # no match, return original
code = f1.sub(replace, code)
code = f2.sub(replace2, code)
return code
def alias_bird(code):
# Alias of `break`
alias_pattern = r'free\s+bird;'
alias_replace = 'break;'
code = re.sub(alias_pattern, alias_replace, code)
return code
def free_bird(code):
matches = re.finditer(r'free\s+bird\s+\$(\w+);', code)
if matches:
for match in matches:
var_name = match.group(1)
p1 = r'(let|var|const)\s+\$?' + var_name + r'\s*=\s*\[.*?\]\s*;'
p2 = r'(let|var|const)\s+\$?' + var_name + r'\s*=\s*(\"|\').*?(\"|\')\s*;'
p3 = r'(let|var|const)\s+\$?' + var_name + r'\s*=\s*[0-9]+\s*;'
is_arr = re.search(p1, code)
is_var = re.search(p2, code)
is_int = re.search(p3, code)
free_pattern = r'free\s+bird\s+\$' + var_name + r';'
if is_arr:
code = re.sub(free_pattern, f"{var_name}=[];", code)
elif is_var:
code = re.sub(free_pattern, f"{var_name}='';", code)
elif is_int:
code = re.sub(free_pattern, f"{var_name}=0;", code)
return code
def free_bird_services(code):
global SMASH_PROCESSES
free_pattern = r'free\s+bird\s+\$(\w+);'
def replace_func(match):
var_name = match.group(1)
# Find the process info
pid_to_remove = None
for pid, info in SMASH_PROCESSES.items():
if info['var'] == var_name:
cmd = info['cmd']
pid_to_remove = pid # Mark for deletion
# Generate stop command based on start command
if 'systemctl start' in cmd:
stop_cmd = cmd.replace('start', 'stop')
elif 'service' in cmd and 'start' in cmd:
stop_cmd = cmd.replace('start', 'stop')
elif 'docker run' in cmd:
stop_cmd = f"docker stop ${info['pid_var']}"
# Clean up tracking
if pid_to_remove is not None:
del SMASH_PROCESSES[pid_to_remove]
if(stop_cmd):
return f"$( {stop_cmd} )"
else:
return match.group(0)
return match.group(0)
code = re.sub(free_pattern, replace_func, code)
return code
def code_birds(code):
code = alias_bird(code)
code = run_bird(code)
code = free_bird(code)
code = free_bird_services(code)
return code
def array_spread(code):
pattern = r'(let|var|const)\s+(\w+)\s*=\s*\[(.*?)\];'
def replace(match):
var_name = match.group(2)
contents = match.group(3)
# Extract: ...arr -> arr
spread_vars = re.findall(r'\.\.\.(\w+)', contents)
if spread_vars:
bash_arrays = ' '.join([f'"${{{v}[@]}}"' for v in spread_vars])
return f'{var_name}=({bash_arrays})'
return match.group(0)
return re.sub(pattern, replace, code)
def array_slice(code):
"""Convert JavaScript array.slice() to bash - simplified version"""
# slice(start, end) - calculate length
def two_params(m):
var, arr, s1, start, s2, end = m.groups()
start, end = int(start), int(end)
# Both positive: length = end - start
if not s1 and not s2:
return f'{var}=("${{{arr}[@]:{start}:{end-start}}}")'
# Positive start, negative end: runtime calc
if not s1 and s2:
return f'{var}=("${{{arr}[@]:{start}:$((${{#{arr}[@]}} - {abs(end)} - {start}))}}")'
# Both negative: length = start - end
if s1 and s2:
return f'{var}=("${{{arr}[@]: {s1}{start}:{start-end}}}")'
# Negative start, positive end: runtime calc
return f'{var}=("${{{arr}[@]: {s1}{start}:$(({end}-(${{#{arr}[@]}}-{start})))}}")'
# slice(start) - from start to end
def one_param(m):
var, arr, sign, start = m.groups()
space = ' ' if sign else '' # Space needed before negative
return f'{var}=("${{{arr}[@]:{space}{sign or ""}{start}}}")'
# Two params first (more specific)
code = re.sub(
r'\b(?:let|var|const)\s+(\w+)\s*=\s*(\w+)\.slice\(\s*(-?)(\d+)\s*,\s*(-?)(\d+)\s*\)',
two_params, code
)
# Then one param
code = re.sub(
r'\b(?:let|var|const)\s+(\w+)\s*=\s*(\w+)\.slice\(\s*(-?)(\d+)\s*\)',
one_param, code
)