forked from mmikeww/AHK-v2-script-converter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertFuncs.ahk
3494 lines (3212 loc) · 138 KB
/
ConvertFuncs.ahk
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
#Requires AutoHotKey v2.0-beta.3
#SingleInstance Force
; to do: strsplit (old command)
; requires should change the version :D
global dbg:=0
#Include lib/ClassOrderedMap.ahk
#Include lib/dbg.ahk
#Include Convert/1Commands.ahk
#Include Convert/2Functions.ahk
#Include Convert/3Methods.ahk
#Include Convert/4ArrayMethods.ahk
#Include Convert/5Keywords.ahk
Convert(ScriptString)
{
global ScriptStringsUsed := Array() ; Keeps an array of interesting strings used in the script
ScriptStringsUsed.ErrorLevel := InStr(ScriptString, "ErrorLevel")
global aListPseudoArray := Array() ; list of strings that should be converted from pseudoArray to Array
global aListMatchObject := Array() ; list of strings that should be converted from Match Object V1 to Match Object V2
global aListLabelsToFunction := Array() ; array of objects with the properties [label] and [parameters] that should be converted from label to Function
global Orig_Line
global Orig_Line_NoComment
global Orig_ScriptString := ScriptString
global oScriptString ; array of all the lines
global O_Index := 0 ; current index of the lines
global Indentation
global SingleIndent := RegExMatch(ScriptString, "(^|[\r\n])( +|\t)", &SingleIndent) ? SingleIndent[2] : " " ; First spaces or single tab found.
global GuiNameDefault
global GuiList
global GuiVList ; Used to list all variable names defined in a Gui
global MenuList
global mAltLabel := GetAltLabelsMap(ScriptString) ; Create a map of labels who are identical
global mGuiCType := map() ; Create a map to return the type of control
global mGuiCObject := map() ; Create a map to return the object of a control
global NL_Func := "" ; _Funcs can use this to add New Previous Line
global EOLComment_Func := "" ; _Funcs can use this to add comments at EOL
global grePostFuncMatch := False ; ... to know their regex matched
global noSideEffect := False ; ... to not change global variables
global ListViewNameDefault
global TreeViewNameDefault
global StatusBarNameDefault
global gFunctPar
global CommandsToConvertM
global FunctionsToConvertM
global MethodsToConvertM
global ArrayMethodsToConvertM
global KeywordsToRenameM
GuiNameDefault := "myGui"
ListViewNameDefault := "LV"
TreeViewNameDefault := "TV"
StatusBarNameDefault := "SB"
GuiList := "|"
MenuList := "|"
GuiVList := Map()
;Directives := "#Warn UseUnsetLocal`r`n#Warn UseUnsetGlobal"
; Splashtexton and Splashtextoff is removed, but alternative gui code is available
Remove := "
(
#AllowSameLineComments
#CommentFlag
#Delimiter
#DerefChar
#EscapeChar
#LTrim
#MaxMem
#NoEnv
SetBatchLines
SetFormat
SoundGetWaveVolume
SoundSetWaveVolume
SplashImage
A_FormatInteger
A_FormatFloat
AutoTrim
)"
ScriptOutput := ""
InCommentBlock := false
InCont := 0
Cont_String := 0
oScriptString := {}
oScriptString := StrSplit(ScriptString, "`n", "`r")
; parse each line of the input script
Loop
{
O_Index++
if (oScriptString.Length < O_Index) {
; This allows the user to add or remove lines if necessary
; Do not forget to change the O_index if you want to remove or add the line above or lines below
break
}
O_Loopfield := oScriptString[O_Index]
Skip := false
Line := O_Loopfield
Orig_Line := Line
RegExMatch(Line, "^(\s*)", &Indentation)
Indentation := Indentation[1]
;msgbox, % "Line:`n" Line "`n`nIndentation=[" Indentation "]`nStrLen(Indentation)=" StrLen(Indentation)
FirstChar := SubStr(Trim(Line), 1, 1)
FirstTwo := SubStr(LTrim(Line), 1, 2)
;msgbox, FirstChar=%FirstChar%`nFirstTwo=%FirstTwo%
if RegExMatch(Line, "(\s+`;.*)$", &EOLComment)
{
EOLComment := EOLComment[1]
Line := RegExReplace(Line, "(\s+`;.*)$", "")
;msgbox, % "Line:`n" Line "`n`nEOLComment:`n" EOLComment
} else if (FirstChar == ";")
{
EOLComment := Line
Line := ""
} else
EOLComment := ""
CommandMatch := -1
; get PreLine of line with hotkey and hotstring definition, String will be temporary removed form the line
; Prelines is code that does not need to changes anymore, but coud prevent correct command conversion
PreLine := ""
if RegExMatch(Line, "^\s*(.*[^\s]::).*$") {
LineNoHotkey := RegExReplace(Line, "(^\s*).+::(.*$)", "$2")
if (LineNoHotkey != "") {
PreLine .= RegExReplace(Line, "^(\s*.+::).*$", "$1")
Line := LineNoHotkey
}
}
if RegExMatch(Line, "^\s*({\s*).*$") {
LineNoHotkey := RegExReplace(Line, "(^\s*)({\s*)(.*$)", "$3")
if (LineNoHotkey != "") {
PreLine .= RegExReplace(Line, "(^\s*)({\s*)(.*$)", "$1$2")
Line := LineNoHotkey
}
}
if RegExMatch(Line, "i)^\s*(}?\s*(Try|Else)\s*[\s{]\s*).*$") {
LineNoHotkey := RegExReplace(Line, "i)(^\s*)(}?\s*(Try|Else)\s*[\s{]\s*)(.*$)", "$4")
if (LineNoHotkey != "") {
PreLine .= RegExReplace(Line, "i)(^\s*)(}?\s*(Try|Else)\s*[\s{]\s*)(.*$)", "$1$2")
Line := LineNoHotkey
}
}
Orig_Line := Line
; Remove comma after flow commands
If RegExMatch(Line, "i)^(.*)(else|for|if|loop|return|while)(\s*,\s*|\s+)(.*)$", &Equation) {
Line := Equation[1] Equation[2] " " Equation[4]
}
; Handle return % var -> return var
If RegExMatch(Line, "i)^(.*)(return)(\s+%\s*\s+)(.*)$", &Equation) {
Line := Equation[1] Equation[2] " " Equation[4]
}
; -------------------------------------------------------------------------------
;
; skip comment blocks with one statement
;
else if (FirstTwo == "/*") {
line .= EOLComment ; done here because of the upcoming "continue"
EOLComment := ""
loop {
O_Index++
if (oScriptString.Length < O_Index) {
break
}
LineContSect := oScriptString[O_Index]
Line .= "`r`n" . LineContSect
FirstTwo := SubStr(LTrim(LineContSect), 1, 2)
if (FirstTwo == "*/") {
; End Comment block
break
}
}
ScriptOutput .= Line . "`r`n"
; Output and NewInput should become arrays, NewInput is a copy of the Input, but with empty lines added for easier comparison.
LastLine := Line
continue ; continue with the next line
}
; Check for , continuation sections add them to the line
; https://www.autohotkey.com/docs/Scripts.htm#continuation
loop
{
if (oScriptString.Length < O_Index + 1) {
break
}
FirstNextLine := SubStr(LTrim(oScriptString[O_Index + 1]), 1, 1)
FirstTwoNextLine := SubStr(LTrim(oScriptString[O_Index + 1]), 1, 1)
TreeNextLine := SubStr(LTrim(oScriptString[O_Index + 1]), 1, 1)
if (FirstNextLine ~= "[,\.]" or FirstTwoNextLine ~= "[\?:]\s" or FirstTwoNextLine = "||" or FirstTwoNextLine = "&&" or FirstTwoNextLine = "or" or TreeNextLine = "and") {
O_Index++
; Known effect : removes the linefeeds and comments of continuation sections
Line .= RegExReplace(oScriptString[O_Index], "(\s+`;.*)$", "")
} else {
break
}
}
; Loop the functions
noSideEffect := False
subLoopFunctions(ScriptString, Line, &LineFuncV2, &gotFunc:=False)
if gotFunc {
Line := LineFuncV2
}
; -------------------------------------------------------------------------------
;
; replace any renamed vars
; Known Error: converts also the text
for v1, v2 in KeywordsToRenameM
{
srchtxt := Trim(v1)
rplctxt := Trim(v2)
if InStr(Line, srchtxt)
{
Line := RegExReplace(Line, "i)([^\w]|^)\Q" . srchtxt . "\E([^\w]|$)", "$1" . rplctxt . "$2")
;MsgBox(Line "`n" srchtxt "`n" rplctxt)
}
}
Orig_Line_NoComment := Line
; -------------------------------------------------------------------------------
;
; check if this starts a continuation section
;
; no idea what that RegEx does, but it works to prevent detection of ternaries
; got that RegEx from Coco here: https://github.com/cocobelgica/AutoHotkey-Util/blob/master/EnumIncludes.ahk#L65
; and modified it slightly
;
if (FirstChar == "(")
&& RegExMatch(Line, "i)^\s*\((?:\s*(?(?<=\s)(?!;)|(?<=\())(\bJoin\S*|[^\s)]+))*(?<!:)(?:\s+;.*)?$")
{
InCont := 1
;If RegExMatch(Line, "i)join(.+?)(LTrim|RTrim|Comment|`%|,|``)?", &Join)
;JoinBy := Join[1]
;else
;JoinBy := "``n"
;MsgBox, Start of continuation section`nLine:`n%Line%`n`nLastLine:`n%LastLine%`n`nScriptOutput:`n[`n%ScriptOutput%`n]
If InStr(LastLine, ':= ""')
{
; if LastLine was something like: var := ""
; that means that the line before conversion was: var =
; and this new line is an opening ( for continuation section
; so remove the last quote and the newline `r`n chars so we get: var := "
; and then re-add the newlines
ScriptOutput := SubStr(ScriptOutput, 1, -3) . "`r`n"
;MsgBox, Output after removing one quote mark:`n[`n%ScriptOutput%`n]
Cont_String := 1
;;;Output.Seek(-4, 1) ; Remove the newline characters and double quotes
} else
{
;;;Output.Seek(-2, 1)
;;;Output.Write(" `% ")
}
;continue ; Don't add to the output file
} else if (FirstChar == ")")
{
;MsgBox, End Cont. Section`n`nLine:`n%Line%`n`nLastLine:`n%LastLine%`n`nScriptOutput:`n[`n%ScriptOutput%`n]
InCont := 0
if (Cont_String = 1)
{
if (FirstTwo != ")`"") { ; added as an exception for quoted continuation sections
Line := RegExReplace(Line, "\)", ")`"", , 1)
}
ScriptOutput .= Line . "`r`n"
LastLine := Line
continue
}
} else if InCont
{
;Line := ToExp(Line . JoinBy)
;If InCont > 1
;Line := ". " . Line
;InCont++
;MsgBox, Inside Cont. Section`n`nLine:`n%Line%`n`nLastLine:`n%LastLine%`n`nScriptOutput:`n[`n%ScriptOutput%`n]
ScriptOutput .= Line . "`r`n"
LastLine := Line
continue
}
; -------------------------------------------------------------------------------
;
; Replace = with := expression equivilents in "var = value" assignment lines
;
; var = 3 will be replaced with var := "3"
; lexikos says var=value should always be a string, even numbers
; https://autohotkey.com/boards/viewtopic.php?p=118181#p118181
;
else If RegExMatch(Line, "i)^([\s]*[a-z_][a-z_0-9]*[\s]*)=([^;]*)", &Equation) ; Thanks Lexikos
{
; msgbox("assignment regex`norigLine: " Line "`norig_left=" Equation[1] "`norig_right=" Equation[2] "`nconv_right=" ToStringExpr(Equation[2]))
Line := RTrim(Equation[1]) . " := " . ToStringExpr(Equation[2]) ; regex above keeps the indentation already
}
; -------------------------------------------------------------------------------
;
; Traditional-if to Expression-if
;
else If RegExMatch(Line, "i)^\s*(else\s+)?if\s+(not\s+)?([a-z_][a-z_0-9]*[\s]*)(!=|=|<>|>=|<=|<|>)([^{;]*)(\s*{?\s*)(.*)", &Equation)
{
;msgbox if regex`nLine: %Line%`n1: %Equation[1]%`n2: %Equation[2]%`n3: %Equation[3]%`n4: %Equation[4]%`n5: %Equation[5]%`n6: %Equation[6]%
; Line := Indentation . format_v("{else}if {not}({variable} {op} {value}){otb}"
; , { else: Equation[1]
; , not: Equation[2]
; , variable: RTrim(Equation[3])
; , op: Equation[4]
; , value: ToExp(Equation[5])
; , otb: Equation[6] } )
op := (Equation[4] = "<>") ? "!=" : Equation[4]
; not used,
; Line := Indentation . format("{1}if {2}({3} {4} {5}){6}"
; , Equation[1] ;else
; , Equation[2] ;not
; , RTrim(Equation[3]) ;variable
; , op ;op
; , ToExp(Equation[5]) ;value
; , Equation[6] ) ;otb
; Preline hack for furter commands
PreLine := Indentation PreLine . format("{1}if {2}({3} {4} {5}){6}"
, Equation[1] ;else
, Equation[2] ;not
, RTrim(Equation[3]) ;variable
, op ;op
, ToExp(Equation[5]) ;value
, Equation[6]) ;otb
Line := Equation[7]
}
; -------------------------------------------------------------------------------
;
; if var between
;
else If RegExMatch(Line, "i)^\s*(else\s+)?if\s+([a-z_][a-z_0-9]*) (\s*not\s+)?between ([^{;]*) and ([^{;]*)(\s*{?\s*)(.*)", &Equation)
{
;msgbox if regex`nLine: %Line%`n1: %Equation[1]%`n2: %Equation[2]%`n3: %Equation[3]%`n4: %Equation[4]%`n5: %Equation[5]%
; Line := Indentation . format_v("{else}if {not}({var} >= {val1} && {var} <= {val2}){otb}"
; , { else: Equation[1]
; , var: Equation[2]
; , not: (Equation[3]) ? "!" : ""
; , val1: ToExp(Equation[4])
; , val2: ToExp(Equation[5])
; , otb: Equation[6] } )
val1 := ToExp(Equation[4])
val2 := ToExp(Equation[5])
if (isNumber(val1) && isNumber(val2)) || InStr(Equation[4], "%") || InStr(Equation[5], "%")
{
PreLine .= Indentation . format("{1}if {3}({2} >= {4} && {2} <= {5}){6}"
, Equation[1] ;else
, Equation[2] ;var
, (Equation[3]) ? "!" : "" ;not
, val1 ;val1
, val2 ;val2
, Equation[6]) ;otb
} else ; if not numbers or variables, then compare alphabetically with StrCompare()
{
;if ((StrCompare(var, "blue") > 0) && (StrCompare(var, "red") < 0))
PreLine .= Indentation . format("{1}if {3}((StrCompare({2}, {4}) > 0) && (StrCompare({2}, {5}) < 0)){6}"
, Equation[1] ;else
, Equation[2] ;var
, (Equation[3]) ? "!" : "" ;not
, val1 ;val1
, val2 ;val2
, Equation[6]) ;otb
}
Line := Equation[7]
}
; -------------------------------------------------------------------------------
;
; if var in
;
else If RegExMatch(Line, "i)^\s*(else\s+)?if\s+([a-z_][a-z_0-9]*) (\s*not\s+)?in ([^{;]*)(\s*{?\s*)(.*)", &Equation)
{
;msgbox if regex`nLine: %Line%`n1: %Equation[1]%`n2: %Equation[2]%`n3: %Equation[3]%`n4: %Equation[4]%`n5: %Equation[5]%
; Line := Indentation . format_v("{else}if {not}({var} in {val1}){otb}"
; , { else: Equation[1]
; , var: Equation[2]
; , not: (Equation[3]) ? "!" : ""
; , val1: ToExp(Equation[4])
; , otb: Equation[6] } )
if RegExMatch(Equation[4], "^%") {
val1 := "`"^(?i:`" RegExReplace(RegExReplace(" ToExp(Equation[4]) ",`"[\\\.\*\?\+\[\{\|\(\)\^\$]`",`"\$0`"),`"\s*,\s*`",`"|`") `")$`""
} else if RegExMatch(Equation[4], "^[^\\\.\*\?\+\[\{\|\(\)\^\$]*$") {
val1 := "`"^(?i:" RegExReplace(Equation[4], "\s*,\s*", "|") ")$`""
} else {
val1 := "`"^(?i:" RegExReplace(RegExReplace(Equation[4], "[\\\.\*\?\+\[\{\|\(\)\^\$]", "\$0"), "\s*,\s*", "|") ")$`""
}
PreLine .= Indentation . format("{1}if {3}({2} ~= {4}){5}"
, Equation[1] ;else
, Equation[2] ;var
, (Equation[3]) ? "!" : "" ;not
, val1 ;val1
, Equation[5]) ;otb
Line := Equation[6]
}
; -------------------------------------------------------------------------------
;
; if var contains
;
else If RegExMatch(Line, "i)^\s*(else\s+)?if\s+([a-z_][a-z_0-9]*) (\s*not\s+)?contains ([^{;]*)(\s*{?\s*)(.*)", &Equation)
{
;msgbox if regex`nLine: %Line%`n1: %Equation[1]%`n2: %Equation[2]%`n3: %Equation[3]%`n4: %Equation[4]%`n5: %Equation[5]%
; Line := Indentation . format_v("{else}if {not}({var} contains {val1}){otb}"
; , { else: Equation[1]
; , var: Equation[2]
; , not: (Equation[3]) ? "!" : ""
; , val1: ToExp(Equation[4])
; , otb: Equation[6] } )
if RegExMatch(Equation[4], "^%") {
val1 := "`"i)(`" RegExReplace(RegExReplace(" ToExp(Equation[4]) ",`"[\\\.\*\?\+\[\{\|\(\)\^\$]`",`"\$0`"),`"\s*,\s*`",`"|`") `")`""
} else if RegExMatch(Equation[4], "^[^\\\.\*\?\+\[\{\|\(\)\^\$]*$") {
val1 := "`"i)(" RegExReplace(Equation[4], "\s*,\s*", "|") ")`""
} else {
val1 := "`"i)(" RegExReplace(RegExReplace(Equation[4], "[\\\.\*\?\+\[\{\|\(\)\^\$]", "\$0"), "\s*,\s*", "|") ")`""
}
PreLine .= Indentation . format("{1}if {3}({2} ~= {4}){5}"
, Equation[1] ;else
, Equation[2] ;var
, (Equation[3]) ? "!" : "" ;not
, val1 ;val1
, Equation[5]) ;otb
Line := Equation[6]
}
; -------------------------------------------------------------------------------
;
; if var is type
;
else If RegExMatch(Line, "i)^\s*(else\s+)?if\s+([a-z_][a-z_0-9]*) is (not\s+)?([^{;]*)(\s*{?\s*)(.*)", &Equation)
{
;msgbox if regex`nLine: %Line%`n1: %Equation[1]%`n2: %Equation[2]%`n3: %Equation[3]%`n4: %Equation[4]%`n5: %Equation[5]%
; Line := Indentation . format_v("{else}if {not}({variable} is {type}){otb}"
; , { else: Equation[1]
; , not: (Equation[3]) ? "!" : ""
; , variable: Equation[2]
; , type: ToStringExpr(Equation[4])
; , otb: Equation[5] } )
PreLine .= Indentation . format("{1}if {3}is{4}({2}){5}"
, Equation[1] ;else
, Equation[2] ;var
, (Equation[3]) ? "!" : "" ;not
, StrTitle(Equation[4]) ;type
, Equation[5]) ;otb
Line := Equation[6]
}
; -------------------------------------------------------------------------------
;
; Replace = with := in function default params
;
else if RegExMatch(Line, "i)^\s*(\w+)\((.+)\)", &MatchFunc)
&& !(MatchFunc[1] ~= "i)(if|while)") ; skip if(expr) and while(expr) when no space before paren
; this regex matches anything inside the parentheses () for both func definitions, and func calls :(
{
; Changing the ByRef parameters to & signs.
Line := RegExReplace(Line, "i)(\bByRef\s+)", "&")
AllParams := MatchFunc[2]
;msgbox, % "function line`n`nLine:`n" Line "`n`nAllParams:`n" AllParams
; first replace all commas and question marks inside quoted strings with placeholders
; - commas: because we will use comma as delimeter to parse each individual param
; - question mark: because we will use that to determine if there is a ternary
pos := 1, quoted_string_match := ""
while (pos := RegExMatch(AllParams, '".*?"', &MatchObj, pos + StrLen(quoted_string_match))) ; for each quoted string
{
quoted_string_match := MatchObj[0]
;msgbox, % "quoted_string_match=" quoted_string_match "`nlen=" StrLen(quoted_string_match) "`npos=" pos
string_with_placeholders := StrReplace(quoted_string_match, ",", "MY_COMMª_PLA¢E_HOLDER")
string_with_placeholders := StrReplace(string_with_placeholders, "?", "MY_¿¿¿_PLA¢E_HOLDER")
string_with_placeholders := StrReplace(string_with_placeholders, "=", "MY_ÈQÜAL§_PLA¢E_HOLDER")
;msgbox, %string_with_placeholders%
Line := StrReplace(Line, quoted_string_match, string_with_placeholders, "Off", &Cnt, 1)
}
;msgbox, % "Line:`n" Line
; get all the params again, this time from our line with the placeholders
if RegExMatch(Line, "i)^\s*\w+\((.+)\)", &MatchFunc2)
{
AllParams2 := MatchFunc2[1]
pos := 1, match := ""
Loop Parse, AllParams2, "," ; for each individual param (separate by comma)
{
thisprm := A_LoopField
;msgbox, % "Line:`n" Line "`n`nthisparam:`n" thisprm
if RegExMatch(A_LoopField, "i)([\s]*[a-z_][a-z_0-9]*[\s]*)=([^,\)]*)", &ParamWithEquals)
{
;msgbox, % "Line:`n" Line "`n`nParamWithEquals:`n" ParamWithEquals[0] "`n" ParamWithEquals[1] "`n" ParamWithEquals[2]
; replace the = with :=
; question marks were already replaced above if they were within quotes
; so if a questionmark still exists then it must be for ternary during a func call
; which we will exclude. for example: MyFunc((var=5) ? 5 : 0)
if !InStr(A_LoopField, "?")
{
TempParam := ParamWithEquals[1] . ":=" . ParamWithEquals[2]
;msgbox, % "Line:`n" Line "`n`nParamWithEquals:`n" ParamWithEquals[0] "`n" TempParam
Line := StrReplace(Line, ParamWithEquals[0], TempParam, "Off", &Cnt, 1)
;msgbox, % "Line after replacing = with :=`n" Line
}
}
}
}
; deref the placeholders
Line := StrReplace(Line, "MY_COMMª_PLA¢E_HOLDER", ",")
Line := StrReplace(Line, "MY_¿¿¿_PLA¢E_HOLDER", "?")
Line := StrReplace(Line, "MY_ÈQÜAL§_PLA¢E_HOLDER", "=")
}
; -------------------------------------------------------------------------------
;
; Fix return %var% -> return var
;
; we use the same parsing method as the next else clause below
;
else if (Trim(SubStr(Line, 1, FirstDelim := RegExMatch(Line, "\w[,\s]"))) = "return")
{
Params := SubStr(Line, FirstDelim + 2)
if RegExMatch(Params, "^%\w+%$") ; if the var is wrapped in %%, then remove them
{
Params := SubStr(Params, 2, -1)
Line := Indentation . "return " . Params . EOLComment ; 'return' is the only command that we won't use a comma before the 1st param
}
}
; Moving the if/else/While statement to the preline
;
else If RegExMatch(Line, "i)(^\s*[\}]?\s*(else|while|if)[\s\(][^\{]*{\s*)(.*$)", &Equation) {
PreLine .= Equation[1]
Line := Equation[3]
}
If RegExMatch(Line, "i)(^\s*)([a-z_][a-z_0-9]*)\s*\+=\s*(.*?)\s*,\s*([SMHD]\w*)(.*$)", &Equation) {
Line := Equation[1] Equation[2] " := DateAdd(" Equation[2] ", " ParameterFormat("ValueCBE2E", Equation[3]) ", '" Equation[4] "')" Equation[5]
} else If RegExMatch(Line, "i)(^\s*)([a-z_][a-z_0-9]*)\s*\-=\s*(.*?)\s*,\s*([SMHD]\w*)(.*$)", &Equation) {
Line := Equation[1] Equation[2] " := DateDiff(" Equation[2] ", " ParameterFormat("ValueCBE2E", Equation[3]) ", '" Equation[4] "')" Equation[5]
}
; Convert Assiociated Arrays to Map Maybe not always wanted...
If RegExMatch(Line, "i)^(\s*)((global|local|static)\s+)?([a-z_0-9]+)(\s*:=\s*)(\{[^;]*)", &Equation) {
; Only convert to a map if for in statement is used for it
if RegExMatch(ScriptString, "is).*for\s[\s,a-z0-9_]*\sin\s" Equation[4] "[^\.].*") {
Line := AssArr2Map(Line)
}
}
;
LabelRedoCommandReplacing:
; -------------------------------------------------------------------------------
;
; Command replacing
;if (!InCont)
; To add commands to be checked for, modify the list at the top of this file
{
CommandMatch := 0
FirstDelim := RegExMatch(Line, "\w([ \t]*[, \t])", &Match) ; doesn't use \s to not consume line jumps
if (FirstDelim > 0)
{
Command := Trim(SubStr(Line, 1, FirstDelim))
Params := SubStr(Line, FirstDelim + StrLen(Match[1])+1)
} else
{
Command := Trim(SubStr(Line, 1))
Params := ""
}
; msgbox("Line=" Line "`nFirstDelim=" FirstDelim "`nCommand=" Command "`nParams=" Params)
; Now we format the parameters into their v2 equivilents
if (Command~="i)^#?[a-z]+$" and FindCommandDefinitions(Command, &v1, &v2))
{
ListDelim := RegExMatch(v1, "[,\s]|$")
ListCommand := Trim(SubStr(v1, 1, ListDelim - 1))
If (ListCommand = Command)
{
CommandMatch := 1
same_line_action := false
ListParams := RTrim(SubStr(v1, ListDelim + 1))
ListParam := Array()
Param := Array() ; Parameters in expression form
Param.Extra := {} ; To attach helpful info that can be read by custom functions
Loop Parse, ListParams, ","
ListParam.Push(A_LoopField)
oParam := V1ParSplit(Params)
Loop oParam.Length
Param.Push(oParam[A_index])
; Checks for continuation section
if (oScriptString.Length > O_Index and (SubStr(Trim(oScriptString[O_Index + 1]), 1, 1) = "(" or RegExMatch(Trim(oScriptString[O_Index + 1]), "i)^\s*\((?:\s*(?(?<=\s)(?!;)|(?<=\())(\bJoin\S*|[^\s)]+))*(?<!:)(?:\s+;.*)?$"))) {
ContSect := oParam[oParam.Length] "`r`n"
loop {
O_Index++
if (oScriptString.Length < O_Index) {
break
}
LineContSect := oScriptString[O_Index]
FirstChar := SubStr(Trim(LineContSect), 1, 1)
if ((A_index = 1) && (FirstChar != "(" or !RegExMatch(LineContSect, "i)^\s*\((?:\s*(?(?<=\s)(?!;)|(?<=\())(\bJoin\S*|[^\s)]+))*(?<!:)(?:\s+;.*)?$"))) {
; no continuation section found
O_Index--
return ""
}
if (FirstChar == ")") {
; to simplify, we just add the comments to the back
if RegExMatch(LineContSect, "(\s+`;.*)$", &EOLComment2)
{
EOLComment := EOLComment " " EOLComment2[1]
LineContSect := RegExReplace(LineContSect, "(\s+`;.*)$", "")
} else
EOLComment2 := ""
Params .= "`r`n" LineContSect
oParam2 := V1ParSplit(LineContSect)
Param[Param.Length] := ContSect oParam2[1]
Loop oParam2.Length - 1
Param.Push(oParam2[A_index + 1])
break
}
ContSect .= LineContSect "`r`n"
Params .= "`r`n" LineContSect
}
}
; save a copy of some data before formating
Param.Extra.OrigArr := Param.Clone()
Param.Extra.OrigStr := Params
; Params := StrReplace(Params, "``,", "ESCAPED_COMMª_PLA¢E_HOLDER") ; ugly hack
; Loop Parse, Params, ","
; {
; populate array with the params
; only trim preceeding spaces off each param if the param index is within the
; command's number of allowable params. otherwise, dont trim the spaces
; for ex: `IfEqual, x, h, e, l, l, o` should be `if (x = "h, e, l, l, o")`
; see ~10 lines below
; if (A_Index <= ListParam.Length)
; Param.Push(LTrim(A_LoopField)) ; trim leading spaces off each param
; else
; Param.Push(A_LoopField)
; }
; msgbox("Line:`n`n" Line "`n`nParam.Length=" Param.Length "`nListParam.Length=" ListParam.Length)
; if we detect TOO MANY PARAMS, could be for 2 reasons
if ((param_num_diff := Param.Length - ListParam.Length) > 0)
{
; msgbox("too many params")
extra_params := ""
Loop param_num_diff
extra_params .= "," . Param[ListParam.Length + A_Index]
extra_params := SubStr(extra_params, 2)
extra_params := StrReplace(extra_params, "ESCAPED_COMMª_PLA¢E_HOLDER", "``,")
;msgbox, % "Line:`n" Line "`n`nCommand=" Command "`nparam_num_diff=" param_num_diff "`nListParam.Length=" ListParam.Length "`nParam[ListParam.Length]=" Param[ListParam.Length] "`nextra_params=" extra_params
; 1. could be because of IfCommand with a same line action
; such as `IfEqual, x, 1, Sleep, 1`
; in which case we need to append these extra params later
same_line_action := false
if_cmds_allowing_sameline_action := "IfEqual|IfNotEqual|IfGreater|IfGreaterOrEqual|"
. "IfLess|IfLessOrEqual|IfInString|IfNotInString|IfMsgBox"
if RegExMatch(Command, "i)^(?:" if_cmds_allowing_sameline_action ")$")
{
if RegExMatch(extra_params, "^\s*(\w+)([\s,]|$)", &next_word)
{
next_word := next_word[1]
if (next_word ~= "i)^(break|continue|return|throw)$")
same_line_action := true
else
same_line_action := FindCommandDefinitions(next_word)
}
if (same_line_action)
extra_params := LTrim(extra_params)
}
; 2. could be this:
; "Commas that appear within the last parameter of a command do not need
; to be escaped because the program knows to treat them literally."
; from: https://autohotkey.com/docs/commands/_EscapeChar.htm
if (not same_line_action and ListParam.Length != 0)
{
Param[ListParam.Length] .= "," extra_params
;msgbox, % "Line:`n" Line "`n`nCommand=" Command "`nparam_num_diff=" param_num_diff "`nListParam.Length=" ListParam.Length "`nParam[ListParam.Length]=" Param[ListParam.Length] "`nextra_params=" extra_params
}
}
; if we detect TOO FEW PARAMS, fill with empty strings (see Issue #5)
if ((param_num_diff := ListParam.Length - Param.Length) > 0)
{
;msgbox, % "Line:`n`n" Line "`n`nParam.Length=" Param.Length "`nListParam.Length=" ListParam.Length "`ndiff=" param_num_diff
Loop param_num_diff
Param.Push("")
}
; convert the params to expression or not
Loop Param.Length
{
this_param := Param[A_Index]
this_param := StrReplace(this_param, "ESCAPED_COMMª_PLA¢E_HOLDER", "``,")
if (A_Index > ListParam.Length)
{
Param[A_Index] := this_param
continue
}
if (A_Index > 1 and InStr(ListParam[A_Index - 1], "*")) {
ListParam.InsertAt(A_Index, ListParam[A_Index - 1])
}
; uses a function to format the parameters
; trimming is also being handled here
Param[A_Index] := ParameterFormat(ListParam[A_Index], Param[A_Index])
}
v2 := Trim(v2)
If (SubStr(v2, 1, 1) == "*") ; if using a special function
{
FuncName := SubStr(v2, 2)
;msgbox("FuncName=" FuncName)
FuncObj := %FuncName% ;// https://www.autohotkey.com/boards/viewtopic.php?p=382662#p382662
If FuncObj is Func
Line := Indentation . FuncObj(Param)
} else ; else just using the replacement defined at the top
{
Line := Indentation . format(v2, Param*)
; msgbox("Line after format:`n`n" Line)
; if empty trailing optional params caused the line to end with extra commas, remove them
if SubStr(LTrim(Line), 1, 1) = "#"
Line := RegExReplace(Line, "[\s\,]*$", "")
else
Line := RegExReplace(Line, "[\s\,]*\)$", ")")
}
if (same_line_action) {
PreLine .= Line "`r`n"
Indentation .= SingleIndent
Line := Indentation . extra_params
Goto LabelRedoCommandReplacing
}
}
}
}
; Remove lines we can't use
If CommandMatch = 0 && !InCommentBlock
{
Loop Parse, Remove, "`n", "`r"
{
If InStr(Orig_Line, A_LoopField)
{
;msgbox, skip removed line`nOrig_Line=%Orig_Line%`nA_LoopField=%A_LoopField%
Skip := true
}
}
if (Line ~= "^\s*(local)\s*$") ; only force-local
Skip := true
}
; Put the directives after the first non-comment line
;If !FoundNonComment && !InCommentBlock && A_Index != 1 && FirstChar != ";" && FirstTwo != "*/"
;{
;Output.Write(Directives . "`r`n")
;msgbox, directives
;ScriptOutput .= Directives . "`r`n"
;FoundNonComment := true
;}
If Skip
{
;msgbox Skipping`n%Line%
Line := format("; REMOVED: {1}", Line)
}
Line := PreLine Line
; Correction PseudoArray to Array
Loop aListPseudoArray.Length {
if (InStr(Line, aListPseudoArray[A_Index].name))
Line := ConvertPseudoArray(Line, aListPseudoArray[A_Index])
}
; Correction MatchObject to Array
Loop aListMatchObject.Length {
if (InStr(Line, aListMatchObject[A_Index]))
Line := ConvertMatchObject(Line, aListMatchObject[A_Index])
}
; VerCompare when using A_AhkVersion.
Line := RegExReplace(Line, 'i)\b(A_AhkVersion)(\s*[!=<>]+\s*)"?(\d[\w\-\.]*)"?', 'VerCompare($1, "$3")${2}0')
if NL_Func { ; add a newline if exists
NL_Func .= "`r`n"
}
if EOLComment_Func { ; prepend a `; comment symbol if missing
if SubStr(StrReplace(EOLComment_Func, A_Space), 1, 1) != "`;" {
EOLComment_Func := " `; " . EOLComment_Func
}
}
ScriptOutput .= NL_Func . Line . EOLComment . EOLComment_Func . "`r`n"
NL_Func:="", EOLComment_Func:="" ; reset global variables
; Output and NewInput should become arrays, NewInput is a copy of the Input, but with empty lines added for easier comparison.
LastLine := Line
}
; Convert labels listed in aListLabelsToFunction
Loop aListLabelsToFunction.Length {
if aListLabelsToFunction[A_Index].label
ScriptOutput := ConvertLabel2Func(ScriptOutput, aListLabelsToFunction[A_Index].label, aListLabelsToFunction[A_Index].parameters, aListLabelsToFunction[A_Index].HasOwnProp("NewFunctionName") ? aListLabelsToFunction[A_Index].NewFunctionName : "", aListLabelsToFunction[A_Index].HasOwnProp("aRegexReplaceList") ? aListLabelsToFunction[A_Index].aRegexReplaceList : "")
}
If InStr(ScriptOutput, "OnClipboardChange:") {
;ScriptOutput := RegExReplace(ScriptOutput, "is)^(.*\n[\s\t]*)(OnClipboardChange:)(.*)$" , "$1ClipChanged:$3")
ScriptOutput := "OnClipboardChange(ClipChanged)`r`n" ConvertLabel2Func(ScriptOutput, "OnClipboardChange", "Type", "ClipChanged", [{NeedleRegEx: "i)^(.*)\b\QA_EventInfo\E\b(.*)$", Replacement: "$1Type$2"}])
}
; trim the very last newline that we add to every line (a few code lines above)
if (SubStr(ScriptOutput, -2) = "`r`n")
ScriptOutput := SubStr(ScriptOutput, 1, -2)
; Add Brackets to Hotkeys
ScriptOutput := AddBracket(ScriptOutput)
return ScriptOutput
}
; =================================================================================
; Convert a v1 function in a single script line to v2
; Can be used from inside _Funcs for nested checks (e.g., function in a DllCall)
; Set noSideEffect to 1 to make some callable _Funcs to not change global vars
; =================================================================================
subLoopFunctions(ScriptString, Line, &retV2, &gotFunc) {
global gFunctPar, grePostFuncMatch
loop {
oResult := V1ParSplitfunctions(Line, A_Index)
if (oResult.Found = 0) {
break
}
if (oResult.Hook_Status > 0) {
; This means that the function dit not close, probably a continuation section
;MsgBox("Hook_Status: " oResult.Hook_Status "line:" line)
break
}
if (oResult.Func = "") {
continue ; Not a function only parenthesis
}
oPar := V1ParSplit(oResult.Parameters)
gFunctPar := oResult.Parameters
ConvertList := FunctionsToConvertM
if RegExMatch(oResult.Pre, "(\w+)\.$", &Match) {
ObjectName := Match[1]
If RegExMatch(ScriptString, "i)(?<!\w)(\Q" ObjectName "\E)\s*:=\s*(\[|(Array|StrSplit)\()") { ; Type Array().
ConvertList := ArrayMethodsToConvertM
} else If RegExMatch(ScriptString, "i)(?<!\w)(\Q" ObjectName "\E)\s*:=\s*(\{|(Object)\()") { ; Type Object().
ConvertList := MethodsToConvertM
} else If RegExMatch(ScriptString, "i)(?<!\w)(\Q" ObjectName "\E)\s*:=\s*(new\s+|(FileOpen|Func|ObjBindMethod|\w*\.Bind)\()") { ; Type instance of class.
ConvertList := [] ; Unspecified conversion patterns.
} else If RegExMatch(ScriptString, "i)(?<!\w)class\s(\Q" ObjectName "\E)(?!\w)") { ; Type Class.
ConvertList := [] ; Unspecified conversion patterns.
} else {
ConvertList := MethodsToConvertM
Loop aListMatchObject.Length {
if (ObjectName = aListMatchObject[A_Index]) {
ConvertList := [] ; Conversions handled elsewhere.
Break
}
}
Loop aListPseudoArray.Length {
if (ObjectName = aListPseudoArray[A_Index].name) {
ConvertList := [] ; Conversions handled elsewhere.
Break
}
}
}
}
for v1, v2 in ConvertList
{
grePostFuncMatch := False
ListDelim := InStr(v1, "(")
ListFunction := Trim(SubStr(v1, 1, ListDelim - 1))
rePostFunc := ""
If (ListFunction = oResult.func) {
;MsgBox(ListFunction)
ListParam := SubStr(v1, ListDelim + 1, InStr(v1, ")") - ListDelim - 1)
rePostFunc := SubStr(v1, InStr(v1,")")+1)
oListParam := StrSplit(ListParam, "`,", " ")
; Fix for when ListParam is empty
if (ListParam = "") {
oListParam.Push("")
}
v1 := trim(v1)
v2 := trim(v2)
loop oPar.Length
{
if (A_Index > 1 and InStr(oListParam[A_Index - 1], "*")) {
oListParam.InSertAt(A_Index, oListParam[A_Index - 1])
}
; Uses a function to format the parameters
oPar[A_Index] := ParameterFormat(oListParam[A_Index], oPar[A_Index])
}
loop oListParam.Length
{
if !oPar.Has(A_Index) {
oPar.Push("")
}
}
If (SubStr(v2, 1, 1) == "*") ; if using a special function
{
If (rePostFunc != "")
{
; move post-function's regex match to _Func (it should return back if needed)
RegExMatch(oResult.Post, rePostFunc, &grePostFuncMatch)
oResult.Post := RegExReplace(oResult.Post, rePostFunc)
}
FuncName := SubStr(v2, 2)
FuncObj := %FuncName% ;// https://www.autohotkey.com/boards/viewtopic.php?p=382662#p382662
If FuncObj is Func {
NewFunction := FuncObj(oPar)
}
} Else {
FormatString := Trim(v2)
NewFunction := Format(FormatString, oPar*)
}
; Remove the empty variables
NewFunction := RegExReplace(NewFunction, "[\s\,]*\)$", ")")
; MsgBox("found:" A_LoopField)
Line := oResult.Pre NewFunction oResult.Post
retV2 := Line
gotFunc:=True
break ; Function/Method just found and processed.
}
}
; msgbox("[" oResult.Pre "]`n[" oResult.func "]`n[" oResult.Parameters "]`n[" oResult.Post "]`n[" oResult.Separator "]`n")
; Line := oResult.Pre oResult.func "(" oResult.Parameters ")" oResult.Post
}
}
; =============================================================================
; Convert traditional statements to expressions
; Don't pass whole commands, instead pass one parameter at a time
; =============================================================================
ToExp(Text)
{
static qu := '"' ; Constant for double quotes
static bt := "``" ; Constant for backtick to escape
Text := Trim(Text, " `t")
If (Text = "") ; If text is empty
return (qu . qu) ; Two double quotes
else if (SubStr(Text, 1, 2) = "`% ") ; if this param was a forced expression
return SubStr(Text, 3) ; then just return it without the %
Text := StrReplace(Text, qu, bt . qu) ; first escape literal quotes
Text := StrReplace(Text, bt . ",", ",") ; then remove escape char for comma
;msgbox text=%text%
if InStr(Text, "%") ; deref %var% -> var
{
;msgbox %text%
TOut := ""