-
Notifications
You must be signed in to change notification settings - Fork 72
/
class_C.ahk
3398 lines (3181 loc) · 116 KB
/
class_C.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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C interface library
;; Copyright (C) 2012 Adrian Hawryluk
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#include <lexer>
#include <tokelex>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C interface library
;;
;; This is a alpha test to create a c type interface. This is going to move on
;; to a full c interface module.
;;
;; USAGE
;; Declare your types:
;;
;; c.typedef("<type> <altName0> [, <altName1> [...] , ;]")
;;
;; c.struct("
;; (
;; <name> {
;; [<type0> <name0a> [, <name0b> [...] ] [,];]
;; [<type1> <name1a> [, <name1b> [...] ] [,];]
;; }[;]
;; )")
;;
;; c.union("
;; (
;; <name> {
;; [<type0> <name0a> [, <name0b> [...] ] [,];]
;; [<type1> <name1a> [, <name1b> [...] ] [,];]
;; }[;]
;; )")
;;
;; NOTE that all whitespaces, including carrage returns and line feeds are
;; ignored, except to seperate words. This uses an almost fully functioning
;; C parser. What it lacks are the ability to read function pointers and
;; functions. It even has a limited preprocessor, where you can define
;; macros that take no parameters.
;;
;; c.define("<name> <replacement string is till end of line>")
;;
;; In the case of defines, all whitespaces are colapsed to a single space,
;; except for new lines. That is where the macro ends.
;;
;; Once a type is defined, you bring an instance of it into being by using
;; the command:
;;
;; new c.object("<name>")
;;
;; which returns the new object.
;;
;; Getting/setting array elements can be done by using:
;;
;; var.<elementNumber>
;; var.<elementNumber> := <new value>
;; or (this has been disabled, may reenable later)
;; var[<elementNumber>].
;; var[<elementNumber>] := <new value>
;;
;; Getting/setting structure or union members is done by using
;;
;; var.<memberName> := <new value>
;; var.<memberName> := assignedValue.
;;
;; I've disabled the retreival of the hidden __Class member. If you want to
;; get the type of the object, i.e. the hidden __Class member, use
;; object_getBase() function instead. From that you can get the __Class member,
;; or just directly compare with the class name. E.g.
;;
;; class x
;; {
;; }
;; xx := new x()
;; if (object_getBase(xx) == x)
;; MsgBox xx is of class x type
;;
;; To Be Done:
;; 1. Anonymous types need to be made so that an array need not be declared
;; as a type. Also may help in migrating others who use only anonymous
;; types in their code previously.
;; 2. Accept and ignore comments. *DONE* with new parser
;; 3. Allow for specifying the minimum size of a type so that types which
;; are just headers, can be created.
;; 4. Function pointers need to be understood.
;; 5. Being able to parse general C header file.
;; TESTING -----------------------------------------------------------------
;; Would be nice to make some regression testing. However, in any case, I
;; still need to test the following:
;; 1. Anonymous structs/unions *done*
;; 2. Assign object x to object y of same and different type
;; 3. Str type
;;
;; Full regression testing would include:
;; 1. testing of setting elemnts and getting of the same elements.
;; 2. memory layout being correct for different stucture layouts.
;;
;; INTERNALS ---------------------------------------------------------------
;; class c
;; {
;; types := {} ; associative array of all structs, unions and typedefs
;; defines := {} ; associative array of all define macros
;; }
;;
;; The c.types is a associative array of types objects, keyed by their name.
;; 1. A base type is defined by a tuple (name, size)
;; 2. A typedef is defined by a tuple (name, type)
;; 3. A union is defined by an array of tuples (name, type)
;; 4. A struct is defined by an array of triples (name, type, offset)
;;
;; In addition to the tuples and triples, there may also exist:
;; 1. an arraySize specifying how many elements are there.
;; 2. an indirectionCount specifying if the type is a pointer
;;
;; A define is defined by an associative array of strings (replacementString)
;;
;; name coming off of any type member or off of c.types will be the
;; name of the type.
;; name coming off the array defining a struct or union membefs will be the
;; name of the member variable.
;; name coming off of anything else will be the name of the typedef.
;;
;; PERFORMANCE
;; This is kinda slow at the moment (~16000us for member access), at around 3
;; times slower then HotKeyIt's _Struct class (~5300us for member access), so
;; has a lot of room for improvment.
;;
;; Such improvements include:
;; 1. Asking if an object has a member using .hasKey() is actually slower
;; then getting the value of the variable directly. So need to switch
;; from asking if a member exists to just getting the variable where
;; possible and have a debug and a release mode for when such tests are
;; not practical.
;; 2. Using caching of frequently used data such as size and simplerType.
;; 3. Remove use of extra object indirection to get to c.object's members.
;; I used an object member " " to stop any name clashing with possible C
;; identifiers, but I can do the same by prepending a " " before each
;; name.
;; 4. Unrolling function calls
;;
;; - Have cached the type of c object which helps by about 2000us bringing
;; it down to about 14300us.
;; - Swapping check between array and struct in get and set functions does
;; about the same as caching the c object type.
;; - Doing a direct test instead of a test through a member function call
;; saves about 1000us.
;; - In type[" simplestType"] function, doing direct tests instad of
;; through helper member functions saved about 2500us
;; - Now at around 11560us to access member.
;; - Caching simpler type drops access to 9360us
;; - Without getSimplerType() function overhead, this drops to 7500us
;; - Caching size of type doesn't seem to do anything for simple types.
;; Most likly will be faster for more complex types (nested) which will
;; rarely occur for most windows stuff.
;; - Currently at 7180-7500us
;; - Unrolled c.type[" isBaseType"] dropping access to 6540us.
;; - Unrolled c._retrive() dropping access to 4980-5300us. This is BETTER
;; THAN _STRUCT!!
;; - At some point I removed the test to see if key = "__Class" since I
;; started using object_getBase() to compare against instead of doing
;; a string compare against the class name. With the extra compare,
;; this has a get member time equivilant to that of _Struct class.
;; - At some point I removed the extra object " " from the c.object and
;; put its elements in the c.object directly prepending a space infront
;; of them. IIRC, this didn't seem to increase the speed as I would have
;; hoped.
;; - Now Set time is around 7800us, with _Struct's set time at 5150-5300us.
;; Lets push this a little.
;; - Unrolling _assign() dropped speed to 6860-7180us.
;; - Removing debug statments dropped it to 6540-6860us.
;; - Removing address checks drops it around 6240-6560us.
;; - Rearranging things from the unrolling of _assign() drops it down to
;; 5940us.
;; - Removing check to see if array method is used (a[1]) instead of member
;; method (a.1) speeds up to 5620us
;; - Current speed of _Struct get/set is 5150-5300us/5140-5310us.
;; Current speed of CStruct get/set is 4980-5320us/5920-6240us.
;; - Removing the objects BASETYPE, TYPEDEForMEMBER, STRUCT, UNION, COMPLEX
;; and replacing ctype and ctype_ with just a flag for each allows for
;; only retreival and test of the recreived value instead of retreaval and
;; test to see if the retreived value is one of the objects.
;; - These are min-max out of 8 tests:
;; Current speed of _Struct get/set is 5300-5460us/5300-5460us.
;; Current speed of CStruct get/set is 4380-4980us/5310-5620us.
;; - Removed optimised code to switch back to debug code. i.e. removed
;; function unrolling.
;; - a.b.c is slower than a[b,c]. Increases speed by about 320us/360-620us.
;; - switching from linear search to dict increases performance from
;; 5920-6240us/7180us to 4680-5000us/5600-6240us. Get already better than
;; _Struct. Will scream when functions are unrolled.
;;
;; LOG -------------------------------------------------------------------------
;; Nov 30, 2012
;; - Allow for creating base c types e.g. int, float, etc.
;; - The setting and getting of base type objects can be done by using
;; .Get() and .Set(value) member functions for c.object's.
;; - Fixed ambiguity allowing the assignment of a c.object's initial value
;; from the constructor, in case the c.object is a base numeric type.
;;
;; New syntax is:
;; x := new c.object("int", C.ASSIGN_VALUE, 6)
;; y := new c.object("int", C.ASSIGN_ADDRESS, address)
;;
;; Complex and array types can still be initialised using the old syntax:
;; c.struct("mystruct { int a, b, c; }")
;; x := new c.object("mystruct", {a: 1, b: 2, c: 3})
;;
;; - Can now iterate over members of a struct/union or over the elements
;; of an array using the "for index, [key] in object" syntax.
;;
;; - Added more checks to give programmer more information as to what went
;; wrong.
;;
;; - Can now jump between Release and Debug code using c.use("ReleaseCode")
;; or c.use("DebugCode"). Relase doesn't have as many checks as it
;; assumes its internal data structues are valid and not being changed
;; by external infulances. It also has optimised code to speed things up.
;; Such optimisations are function unrolling, and removal of c.ndebug
;; statements.
;;
;; - Removed internal _repeat() function and now using external repeat()
;; function in misc.ahk
;;
;; - Increased lookup for structs/unions by using the object's intrnal
;; dictionary capability. Had to prepend a space to all variables used
;; inside of type to make sure they wouldn't be accedentily used by
;; a programmer accessing a C member. This is now entirly not case
;; sensitive.
;;
;; - Bug found where when setting an element in an array, it wasn't getting
;; the simpler type. Not sure how it got past the test, but fixed now.
;;
;; - Now accepts:
;; typedef struct <sname> { /* stuff */ } <tname1>, <tname2>...
;; NOTE: Comments are not accepted.
;;
;; - Pointer size bug caused size to be miscalculated. Fixed.
;;
;; - Unions and structs have been tested as well as their anonymous
;; equivilants.
;;
;; - C.ASSIGN_VALUE was being assigned to operation as a string instead of
;; a value. Fixed.
;;
;; - Using type.description() function to describe in more detail a type
;; instead of having this copy code differently everywhere.
;;
;; - Element list had some bugs where it wasn't using the simpler type when
;; it should have. Fixed.
;;
;; - Changed c.newName() so that it would have a different counter for
;; structs and unions.
;;
;; - Union wasn't workign proprely since offset wasn't specified and code
;; relied on it. Didn't test unions so didn't see this till now. Just
;; set it to 0. Faster processing if I don't to a check.
;;
;; Dec 16, 2012
;; - Implemented full lexer. Currently side by side with original half
;; assed lexer. Will phase out the HA lexer after running some additioal
;; performance tests.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#Include <DllCallCheck>
#Include <misc>
#include <ClassCheck>
;; Using class as a namespace. Not ideal, but sufficiant.
;; Because of this, it has no member variables, just static ones.
;; Don't bother creating a new c object. Do create a new c.object.
class c extends checkCallNameExists
{
defineType(command)
{
}
typedef__(command)
{
lexer_ := new c.lexer(new stringLineReader(command))
c.typedef_parser__(lexer_)
}
typedef(command)
{
tokens := c.preprocess_macroReplace(c.tokenizer(command, c.operators, c.whitespace))
position := 1
c.typedef_parser(tokens, position)
}
typedef___(command)
{
tokens := c.preprocess_macroReplace___(new tokelex("c tokenizer", tokelex.KEEP_NEWLINE).string(command))
position := 1
c.typedef_parser___(tokens, position)
}
typedef____(command)
{
tokens := c.preprocess_macroReplace____(new tokelex("c lexer", tokelex.KEEP_NEWLINE).string(command))
position := 1
c.typedef_parser____(tokens, position)
}
struct(command)
{
tokens := c.preprocess_macroReplace(c.tokenizer(command, c.operators, c.whitespace))
name := tokens[1]
if (name == "{")
FAIL("Cannot directly create an anonymous structure.")
position := 2
c.struct_parser(name, tokens, position)
}
struct___(command)
{
tokens := c.preprocess_macroReplace___(new tokelex("c tokenizer", tokelex.KEEP_NEWLINE).string(command))
name := tokens[1]
if (name == "{")
FAIL("Cannot directly create an anonymous structure.")
position := 2
c.struct_parser___(name, tokens, position)
}
struct____(command)
{
tokens := c.preprocess_macroReplace____(new tokelex("c lexer", tokelex.KEEP_NEWLINE).string(command))
name := tokens[1].string
if (name == "{")
FAIL("Cannot directly create an anonymous structure.")
position := 2
c.struct_parser____(name, tokens, position)
}
struct__(command)
{
lexer_ := new c.lexer(new stringLineReader(command))
name := lexer_.get().value
if (name == "{")
FAIL("Cannot directly create an anonymous structure.")
lexer_.t_pos := 2
c.struct_parser__(name, lexer_)
}
union(command)
{
tokens := c.preprocess_macroReplace(c.tokenizer(command, c.operators, c.whitespace))
name := tokens[1]
if (name == "{")
FAIL("Cannot directly create an anonymous union.")
position := 2
c.union_parser(name, tokens, position)
}
union___(command)
{
tokens := c.preprocess_macroReplace___(new tokelex("c tokenizer", tokelex.KEEP_NEWLINE).string(command))
name := tokens[1]
if (name == "{")
FAIL("Cannot directly create an anonymous union.")
position := 2
c.union_parser___(name, tokens, position)
}
union____(command)
{
tokens := c.preprocess_macroReplace____(new tokelex("c lexer", tokelex.KEEP_NEWLINE).string(command))
name := tokens[1].string
if (name == "{")
FAIL("Cannot directly create an anonymous union.")
position := 2
c.union_parser____(name, tokens, position)
}
union__(command)
{
lexer_ := new c.lexer(new stringLineReader(command))
name := lexer_.get().value
if (name == "{")
FAIL("Cannot directly create an anonymous union.")
lexer_.t_pos := 2
c.union_parser__(name, lexer_)
}
;; add a define to the set of defines
define(command)
{
tokens := c.preprocess_macroReplace(c.tokenizer(command, c.operatorsWithLF, c.whitespaceSansLF))
position := 1
while position <= tokens.MaxIndex() and tokens[position] != "`n"
{
token := tokens[position++]
if(token != "`n")
{
name := token
replace := []
while position <= tokens.MaxIndex() and tokens[position] != "`n"
{
replace.Insert(tokens[position++])
}
c.defines[name] := replace
}
}
}
;; add a define to the set of defines
define___(command)
{
tokens := c.preprocess_macroReplace___(new tokelex("c tokenizer", tokelex.KEEP_WHITESPACE | tokelex.COLLAPSE_H_WHITESPACE).string(command))
position := 1
while (position <= tokens.MaxIndex() or tokens.tokenAvailable(position)) and !instr("`r`n", substr(tokens[position], 1, 1))
{
token := tokens[position++]
if (!instr("`r`n", substr(token, 1, 1)))
{
name := token
replace := []
while (position <= tokens.MaxIndex() or tokens.tokenAvailable(position)) and !instr("`r`n", substr(tokens[position], 1, 1))
{
replace.Insert(tokens[position++])
}
c.defines[name] := replace
}
}
}
;; add a define to the set of defines
define____(command)
{
tokens := c.preprocess_macroReplace____(new tokelex("c lexer", tokelex.KEEP_WHITESPACE | tokelex.COLLAPSE_H_WHITESPACE).string(command))
position := 1
while (position <= tokens.MaxIndex() or tokens.tokenAvailable(position)) and !tokens[position, 11]
{
token := tokens[position++]
if(!token[11])
{ ; do nothing
}
else
{
name := token
replace := []
while (position <= tokens.MaxIndex() or tokens.tokenAvailable(position)) and !tokens[position, 11]
{
replace.Insert(tokens[position++])
}
c.defines[name] := replace
}
}
}
;; add a define to the set of defines
define__(command)
{
lexer_ := new c.lexer(new stringLineReader("#define " command))
while (lexer_.hasMoreTokens())
{
++lexer_.t_pos
}
}
static TOKENIZER_RE_ := "SxmP`a)
(
(?:(?:[lL](?!"")|[a-km-zA-KM-Z_])[a-zA-Z_0-9]*) # WORD
| (?:[ \t]+) # WHITESPACE
| (?:==?|\+[+=]?|-[-=]?|&[&=]?|\|[|=]?|\*=?|/(?![/*])=?|\^=?|!=?|<=?|>=?|`%=?|\.(?![0-9])|\#\#?|[(){}\[\],?:;]) # OPERATORS
| (?:\\$(?:\r\n?|\n\r?)?) # QUOTED NEWLINE
| (?://.*$) # COMMENT LINE
| (?:/\*(?:\r\n?|\n\r?|.)*?\*/) # COMMENT BLOCK
| (?:/\*(?:\r\n?|\n\r?|.)*$) # COMMENT BLOCK INCOMPLETE
| (?:[lL]?""(?:\\""|\\(?:\r\n?|\n\r?)|.)*?"") # STRING LITERAL
| (?: # some parts here are duplicated to prevent backtracking.
0(?:
(?:
\.[0-9]* # float/double
(?:[Ee][+-]?[0-9]+)? # possible exponential notaion
[Ff]? # possible float suffix
`)
| (?:
[0-7]+ # octal dec and hex
| [xX][0-9a-fA-F]+ # hex
| # just zero
`)[Uu]?[Ll]? # possible U or L suffix
`)
| [1-9][0-9]* # int or
(?:
\.[0-9]* # float/double
(?:[Ee][+-]?[0-9]+)? # possible exponential notaion
[Ff]? # possible float suffix
| [Uu]?[Ll]? # possible U or L suffix
`)
|
\.[0-9]* # float/double
(?:[Ee][+-]?[0-9]+)? # possible exponential notaion
[Ff]? # possible float suffix
`)\b # end on a word boundry
# NUMERIC LITERAL
| (?:'(?:\\'|.)+') # CHARACTER LITERAL
| (?:\r\n?|\n\r?) # NEW LINE
)"
, TOKENIZER_RE := (removeCommentsAndWhitespaceFromRegEx(c.TOKENIZER_RE_), tokelex.Register("c tokenizer", removeCommentsAndWhitespaceFromRegEx(c.TOKENIZER_RE_), { whitespaceId: 2, newlineId: 11
, remapTokenString: { "`r": "`n", "`r`n": "`n" } } ))
static LEXER_RE_ := "SxmP`a)
(
((?:[lL](?!"")|[a-km-zA-KM-Z_])[a-zA-Z_0-9]*) # WORD
| ([ \t]+) # WHITESPACE
| (==?|\+[+=]?|-[-=]?|&[&=]?|\|[|=]?|\*=?|/(?![/*])=?|\^=?|!=?|<=?|>=?|`%=?|\.(?![0-9])|\#\#?|[(){}\[\],?:;]) # OPERATORS
| (\\$(?:\r\n?|\n\r?)?) # QUOTED NEWLINE
| (//.*$) # COMMENT LINE
| (/\*(?:\r\n?|\n\r?|.)*?\*/) # COMMENT BLOCK
| (/\*(?:\r\n?|\n\r?|.)*$) # COMMENT BLOCK INCOMPLETE
| ([lL]?""(?:\\""|\\(?:\r\n?|\n\r?)|.)*?"") # STRING LITERAL
| ( # some parts here are duplicated to prevent backtracking.
0(?:
(?:
\.[0-9]* # float/double
(?:[Ee][+-]?[0-9]+)? # possible exponential notaion
[Ff]? # possible float suffix
`)
| (?:
[0-7]+ # octal dec and hex
| [xX][0-9a-fA-F]+ # hex
| # just zero
`)[Uu]?[Ll]? # possible U or L suffix
`)
| [1-9][0-9]* # int or
(?:
\.[0-9]* # float/double
(?:[Ee][+-]?[0-9]+)? # possible exponential notaion
[Ff]? # possible float suffix
| [Uu]?[Ll]? # possible U or L suffix
`)
|
\.[0-9]* # float/double
(?:[Ee][+-]?[0-9]+)? # possible exponential notaion
[Ff]? # possible float suffix
`)\b # end on a word boundry
# NUMERIC LITERAL
| ('(?:\\'|.)+') # CHARACTER LITERAL
| (\r\n?|\n\r?) # NEW LINE
)"
, LEXER_RE := (removeCommentsAndWhitespaceFromRegEx(c.LEXER_RE_), tokelex.Register("c lexer", removeCommentsAndWhitespaceFromRegEx(c.LEXER_RE_), { whitespaceId: 2, newlineId: 11
, remapTokenString: { struct: { isStruct: 1 }
, union: { isUnion: 1 }
, "{": { isOpenBrace: 1 }
, "}": { isCloseBrace: 1 }
, "[": { isOpenBracket: 1 }
, "]": { isCloseBracket: 1 }
, "*": { isAstrix: 1 }
, ",": { isComma: 1, isCommaOrSemicolon: 1 }
, ";": { isSemicolon: 1, isCommaOrSemicolon: 1 }
, "`r" : { isNewline: 1 }
, "`r`n" : { isNewline: 1 }
, "`n" : { isNewline: 1 }
, typedef: { isTypedef: 1 } } } ))
sizeof(typeNameOrObject)
{
if (object_getBaseAddress(typeNameOrObject) = &c.object)
return typeNameOrObject[" size"]
else if (IsObject(type := c.types[typeNameOrObject]))
return type[" size"]
else if (IsFunc(typeNameOrObject))
FAIL("Can only call c.sizeof() on an already defined type or an allocated c.object. Was passed a Func object pointing at '" typeNameOrObject[" name"] "'.")
else if (IsObject(typeNameOrObject))
FAIL("Can only call c.sizeof() on an already defined type or an allocated c.object. Was passed an object of class '" object_getBase(typeNameOrObject).__Class "'.")
else
FAIL("Unknown type name '" typeNameOrObject "'.")
}
static ALLOCATE := 0
, ASSIGN_ADDRESS := 1
, ASSIGN_VALUE := 2
, MIN_ALLOC := 3 ; TBD: for later to allow allocating extra space for those structs that end in an array of 0 elements.
static parseType__ := c.parseType___DebugCode
;; C Object that is passed around
class object extends checkCallNameExists
{
static __Get := c.object.__Get_DebugCode
, __Set := c.object.__Set_DebugCode
, Get := c.object.Get_DebugCode
, Set := c.object.Set_DebugCode
; If a pointer is passed, then point at that instead of allocating new space.
__New(typeName, operation = 0, byref value = 0)
{
if(!c.types.hasKey(typeName))
FAIL("Type name '" typeName "' is not a defined c type.")
this.init(c.types[typeName], operation, value)
}
init(type, operation, byref value)
{
sizeofType := type[" size"]
ObjInsert(this, " type", type) ? 0 : FAIL("Out of memory")
ObjInsert(this, " size", type[" size"]) ? 0 : FAIL("Out of memory")
if (IsObject(operation))
{
value := operation
operation := C.ASSIGN_VALUE
}
if (operation = C.ASSIGN_ADDRESS)
if value is Integer
ObjInsert(this, " address", value) ? 0 : FAIL("Out of memory")
else
FAIL("Address must be an integer, not '" value "'.")
else
{
if ("" == ObjSetCapacity(this, " binary", sizeofType))
FAIL("Didn't set the capacity of element binary")
address := ObjGetAddress(this, " binary")
ObjInsert(this, " address", address) ? 0 : FAIL("Out of memory")
memset(address, 0, sizeofType) ; setting elements of object to zero
if (operation = C.ASSIGN_VALUE)
this._assign(type, address, value)
}
}
IsOwner()
{
return this.hasKey(" binary")
}
_retrive(type, address)
{
c.ndebug ? 0 : c.debug("_retrive(" object_elementList(type, "type") ", " hex(address, 8) ")")
type := type[" simplestType"]
if (type[" isBaseType"])
if (type[" name"] = "Str")
return StrGet(NumGet(address+0))
else
return NumGet(address+0, 0, type[" name"])
else
return c.object._tmp(type, address)
}
Get_DebugCode()
{
type := this[" type"]
if (type[" simplestType", " isBaseType"])
return c.object._retrive(type, this[" address"])
else
FAIL("No reason to Get() from a non-base type.")
}
Get_ReleaseCode()
{
; excluding test to see if this is a base typed element. Assumed this has been tested for in Debug mode previously.
type := this[" type", " simplestType"]
if (type[" name"] = "Str")
return StrGet(NumGet(this[" address"])+0)
else
return NumGet(this[" address"]+0, 0, type[" name"])
}
__Get_DebugCode(key="", p*)
{
if (p.MaxIndex())
return this[key][p.1]
address := this[" address"]
c.ndebug ? 0 : c.debug("GET: " hex(address, 8))
if (key == "")
return address
type := this[" type", " simplestType"]
if (type[" isComplex"])
if (IsObject(elementType := type[key]))
{
return c.object._retrive(elementType, address + elementType[" offset"])
}
else
FAIL("Attempt to access member <value> which doesn't exist for type '" type.description() "'." object_elementList(key, "value", OBJECT_SHOW.DEFAULT, "`n "))
else if (type[" arraySize"])
if key is integer
if (0 < key and key <= type[" arraySize"])
{
return c.object._retrive(type[" type"], address + (key-1) * type[" type", " size"])
}
else
FAIL("Attempt to access element " key " when array has " type[" arraySize"] " elements.")
else
FAIL("Attempt to access element <value> when the C language doesn't have associative arrays." object_elementList(key, "value", OBJECT_SHOW.DEFAULT, "`n "))
else ;; should be a base type from here out
{
c.object._retrive(type, address)
}
}
__Get_ReleaseCode(key="", p*)
{
if (p.MaxIndex())
return this[key][p.1]
address := this[" address"]
;c.ndebug ? 0 : c.debug("GET: " hex(address, 8))
if (key == "")
return address
type := this[" type", " simplestType"]
if (type[" isComplex"])
if (IsObject(elementType := type[key]))
{
;return c.object._retrive(elementType, address + elementType[" offset"])
;_retrive(type, address)
{
; c.ndebug ? 0 : c.debug("_retrive(" object_elementList(type, "type") ", " hex(address, 8) ")")
;type := elementType
;address := address + elementType[" offset"]
type := elementType[" simplestType"]
return (type[" isBaseType"])
? (type[" name"] = "Str")
? StrGet(NumGet(address + elementType[" offset"]))
: NumGet(address + elementType[" offset"], 0, type[" name"])
: { " type": type, " address": address + elementType[" offset"], base: c.object }
if (type[" isBaseType"])
if (type[" name"] = "Str")
return StrGet(NumGet(address + elementType[" offset"]))
else
return NumGet(address + elementType[" offset"], 0, type[" name"])
else
return { " type": type, " address": address + elementType[" offset"], base: c.object }
}
}
else
FAIL("Attempt to access member <value> which doesn't exist for type '" type.description() "'." object_elementList(key, "value", OBJECT_SHOW.DEFAULT, "`n "))
else if (type[" arraySize"])
if key is integer
if (0 < key and key <= type[" arraySize"])
{
;return c.object._retrive(type[" type"], address + (key-1) * type[" type", " size"])
;_retrive(type, address)
{
; c.ndebug ? 0 : c.debug("_retrive(" object_elementList(type, "type") ", " hex(address, 8) ")")
;type := type[" type"]
type := type[" type", " simplestType"]
return (type[" isBaseType"])
? (type[" name"] = "Str")
? StrGet(address + (key-1) * type[" size"])
: NumGet(address + (key-1) * type[" size"], 0, type[" name"])
: { " type": type, " address": address + (key-1) * type[" size"], base: c.object }
if (type[" isBaseType"])
if (type[" name"] = "Str")
return StrGet(address + (key-1) * type[" size"])
else
return NumGet(address + (key-1) * type[" size"], 0, type[" name"])
else
return { " type": type, " address": address + (key-1) * type[" size"], base: c.object }
}
}
else
FAIL("Attempt to access element " key " when array has " type[" arraySize"] " elements.")
else
FAIL("Attempt to access element <value> when the C language doesn't have associative arrays." object_elementList(key, "value", OBJECT_SHOW.DEFAULT, "`n "))
else ;; should be a base type from here out
{
;c.object._retrive(type, address)
;_retrive(type, address)
{
; c.ndebug ? 0 : c.debug("_retrive(" object_elementList(type, "type") ", " hex(address, 8) ")")
type := type[" simplestType"]
return (type[" isBaseType"])
? (type[" name"] = "Str")
? StrGet(NumGet(address+0))
: NumGet(address+0, 0, type[" name"])
: { " type": type, " address": address, base: c.object }
if (type[" isBaseType"])
if (type[" name"] = "Str")
return StrGet(NumGet(address+0))
else
return NumGet(address+0, 0, type[" name"])
else
return c.object._tmp(type, address)
}
}
}
_assign(_type_, address, value)
{
c.ndebug ? 0 : c.debug("_assign (" object_elementList(_type_, "type") ", " hex(address, 8) ", " (object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n ")) ")")
if address is not integer
FAIL("Address must be an integer, found '" address "' instead.")
if (0 == address)
FAIL("Cannot assign anything through a NULL pointer")
_type := _type_
_type_ := _type_[" simplestType"]
if (_type_[" isBaseType"])
if (_type_[" name"] = "Str")
if (IsObject(value))
FAIL("Attempt to put non number <value> into a number field '" _type.description() "'." object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n "))
else
return StrPut(value, NumGet(address+0))
else if value is number
return NumPut(value, address+0, 0, _type_[" name"])
else
FAIL("Attempt to put non number <value> into a number field '" _type.description() "'." object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n "))
else if (IsObject(value))
if (object_getBaseAddress(value) == &c.object)
if (_type_ == value[" type", " simplestType"])
{
srcAddress := value[" address"]
if (srcAddress != 0)
memcpy(address, srcAddress, _type_[" size"])
else
FAIL("Attempt to copy from NULL address.")
}
else
FAIL("Cannot copy data from type " value[" type", " simplestType"].description() " to type " _type_[" type"].description() " as they are different types.")
else
{
tmp := c.object._tmp(_type_, address)
for key, val in value
tmp[key] := val
}
else
FAIL("Cannot assign <value> to object of type '" _type.description() "'." object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n "))
return this
}
Set_DebugCode(value)
{
return c.object._assign(this[" type"], this[" address"], value)
}
Set_ReleaseCode(value)
{
;_assign(_type_, address, value)
{
; c.ndebug ? 0 : c.debug("_assign (" object_elementList(_type_, "type") ", " hex(address, 8) ", " (object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n ")) ")")
; if address is not integer
; FAIL("Address must be an integer, found '" address "' instead.")
if (0 == address := this[" address"])
FAIL("Cannot assign anything through a NULL pointer")
_type_ := this[" type", " simplestType"]
if (_type_[" isBaseType"])
if (_type_[" name"] = "Str")
if (IsObject(value))
FAIL("Attempt to put non number <value> into a number field '" this[" type"].description() "'." object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n "))
else
return StrPut(value, NumGet(address+0))
else if value is number
return NumPut(value, address+0, 0, _type_[" name"])
else
FAIL("Attempt to put non number <value> into a number field '" this[" type"].description() "'." object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n "))
else if (IsObject(value))
if (object_getBaseAddress(value) == &c.object)
if (_type_ == value[" type", " simplestType"])
{
srcAddress := value[" address"]
if (srcAddress != 0)
memcpy(address, srcAddress, _type_[" size"])
else
FAIL("Attempt to copy from NULL address.")
}
else
FAIL("Cannot copy data from type " value[" type", " simplestType"].description() " to type " _type_[" type"].description() " as they are different types.")
else
{
;tmp := c.object._tmp(_type_, address)
tmp := { " type": _type_, " address": address, base: c.object }
for key, val in value
tmp[key] := val
}
else
FAIL("Cannot assign <value> to object of type '" this[" type"].description() "'." object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n "))
return this
}
}
__Set_DebugCode(key, value, values*)
{
if (values.MaxIndex()) ; Handle "a.b[c] := d" as "a.b.c := d"
return this[key][value] := values.1
c.ndebug ? 0 : c.debug("SET: " hex(address, 8) " := " value)
if (key == "") ; set address
{
if value is integer
{
this.Remove(" binary")
return this[" address"] := value
}
else
FAIL("An address must be a integer, not '" value "'.")
}
else
{
type := this[" type", " simplestType"]
if (0 == address := this[" address"])
FAIL("Cannot assign anything through a NULL pointer")
if (type[" isComplex"])
if (IsObject(elementType := type[key]))
return c.object._assign(elementType, address + elementType[" offset"], value)
else
FAIL("Attempt to access member <value> which doesn't exist for type '" type.description() "'." object_elementList(key, "value", OBJECT_SHOW.DEFAULT, "`n "))
else if (type[" arraySize"])
if key is integer
if (0 < key and key <= type[" arraySize"])
return c.object._assign(type[" type"], address + (key-1) * type[" type", " size"], value)
else
FAIL("Attempt to write to element " key " when array has " type[" arraySize"] " elements.")
else
FAIL("Attempt to access element <value> when the C language doesn't have associative arrays." object_elementList(key, "value", OBJECT_SHOW.DEFAULT, "`n "))
else ;; should be a base type from here out
return c.object._assign(type, address, value)
}
}
__Set_ReleaseCode(key, value, values*)
{
if (values.MaxIndex()) ; Handle "a.b[c] := d" as "a.b.c := d"
return this[key][value] := values.1
; c.ndebug ? 0 : c.debug("SET: " hex(address, 8) " := " value)
if (key == "") ; set address
{
if value is integer
{
this.Remove(" binary")
return this[" address"] := value
}
else
FAIL("An address must be a integer, not '" value "'.")
}
else
{
type := this[" type", " simplestType"]
if (0 == address := this[" address"])
FAIL("Cannot assign anything through a NULL pointer")
if (type[" isComplex"])
if (IsObject(elementType := type[key]))
{
;return c.object._assign(elementType, address + elementType[" offset"], value)
;_assign(_type_, address, value)
{
;c.ndebug ? 0 : c.debug("_assign (" object_elementList(_type_, "type") ", " hex(address, 8) ", " (object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n ")) ")")
;if address is not integer
; FAIL("Address must be an integer, found '" address "' instead.")
;if (0 == address)
; FAIL("Cannot assign anything through a NULL pointer")
;; NEW VERSION ;;
_type_ := elementType[" simplestType"]
if (_type_[" isBaseType"])
if (_type_[" name"] = "Str")
if (IsObject(value))
FAIL("Attempt to put non number <value> into a number field '" elementType.description() "'." object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n "))
else
return StrPut(value, NumGet(address + elementType[" offset"]))
else if value is number
return NumPut(value, address + elementType[" offset"], 0, _type_[" name"])
else
FAIL("Attempt to put non number <value> into a number field '" elementType.description() "'." object_elementList(value, "value", OBJECT_SHOW.DEFAULT, "`n "))
else if (IsObject(value))
if (object_getBaseAddress(value) == &c.object)
if (_type_ == value[" type", " simplestType"])
{
if (0 != srcAddress := value[" address"])
{
tmp := { " type": _type_, " address": dstAddress := address + elementType[" offset"], base: c.object }
memcpy(dstAddress, srcAddress, _type_[" size"])
return tmp
}
else
FAIL("Attempt to copy from NULL address.")
}
else
FAIL("Cannot copy data from type " value[" type", " simplestType"].description() " to type " _type_[" type"].description() " as they are different types.")
else
{
;tmp := c.object._tmp(_type_, address + elementType[" offset"])
tmp := { " type": _type_, " address": address + elementType[" offset"], base: c.object }
for key, val in value
tmp[key] := val
return tmp