-
Notifications
You must be signed in to change notification settings - Fork 164
/
gen_mpy.py
3065 lines (2683 loc) · 121 KB
/
gen_mpy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
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
# TODO
# - Array conversion improvements:
# - return custom iterable object instead of Blob when converting to array
# - check array dim on conversion
# - On print extensions, print the reflected internal representation of the object (worth the extra ROM?)
# - Verify that when mp_obj is given it is indeed the right type (mp_lv_obj_t). Report error if not. can be added to mp_to_lv.
# - Implement inheritance instead of embed base methods (how? seems it's not supported, see https://github.com/micropython/micropython/issues/1159)
# - When converting mp to ptr (and vice versa), verify that types are compatible. Now all pointers are casted to void*.
from __future__ import print_function
import collections
import sys
import struct
import copy
from itertools import chain
from functools import lru_cache
import json
import os
def memoize(func):
@lru_cache(maxsize=1000000)
def memoized(*args, **kwargs):
return func(*args, **kwargs)
return memoized
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# from pudb.remote import set_trace
# set_trace(term_size=(180, 50))
from sys import argv
from argparse import ArgumentParser
import subprocess, re
from os.path import dirname, abspath
from os.path import commonprefix
script_path = dirname(abspath(__file__))
sys.path.insert(0, '%s/../pycparser' % script_path)
from pycparser import c_parser, c_ast, c_generator
#
# Argument parsing
#
argParser = ArgumentParser()
argParser.add_argument('-I', '--include', dest='include', help='Preprocesor include path', metavar='<Include Path>', action='append')
argParser.add_argument('-D', '--define', dest='define', help='Define preprocessor macro', metavar='<Macro Name>', action='append')
argParser.add_argument('-E', '--external-preprocessing', dest='ep', help='Prevent preprocessing. Assume input file is already preprocessed', metavar='<Preprocessed File>', action='store')
argParser.add_argument('-J', '--lvgl-json', dest='json', help='Provde a JSON from the LVGL JSON generator for missing information', metavar='<JSON file>', action='store')
argParser.add_argument('-M', '--module_name', dest='module_name', help='Module name', metavar='<Module name string>', action='store')
argParser.add_argument('-MP', '--module_prefix', dest='module_prefix', help='Module prefix that starts every function name', metavar='<Prefix string>', action='store')
argParser.add_argument('-MD', '--metadata', dest='metadata', help='Optional file to emit metadata (introspection)', metavar='<MetaData File Name>', action='store')
argParser.add_argument('input', nargs='+')
argParser.set_defaults(include=[], define=[], ep=None, json=None, input=[])
args = argParser.parse_args()
module_name = args.module_name
module_prefix = args.module_prefix if args.module_prefix else args.module_name
#
# C proceprocessing, if needed, or just read the input files.
#
if not args.ep:
pp_cmd = 'gcc -E -std=c99 -DPYCPARSER {macros} {include} {input} {first_input}'.format(
input=' '.join('-include %s' % inp for inp in args.input),
first_input= '%s' % args.input[0],
macros = ' '.join('-D%s' % define for define in args.define),
include=' '.join('-I %s' % inc for inc in args.include))
s = subprocess.check_output(pp_cmd.split()).decode()
else:
pp_cmd = 'Preprocessing was disabled.'
s = ''
with open(args.ep, 'r') as f:
s += f.read()
#
# AST parsing helper functions
#
@memoize
def remove_declname(ast):
if hasattr(ast, 'declname'):
ast.declname = None
if isinstance(ast, tuple):
remove_declname(ast[1])
return
for i, c1 in enumerate(ast.children()):
child = ast.children()[i]
remove_declname(child)
@memoize
def add_default_declname(ast, name):
if hasattr(ast, 'declname'):
if (ast.declname == None):
ast.declname = name
if isinstance(ast, tuple):
add_default_declname(ast[1], name)
return
for i, c1 in enumerate(ast.children()):
child = ast.children()[i]
add_default_declname(child, name)
@memoize
def convert_array_to_ptr(ast):
if hasattr(ast, 'type') and isinstance(ast.type, c_ast.ArrayDecl):
ast.type = c_ast.PtrDecl(ast.type.quals if hasattr(ast.type, 'quals') else [], ast.type.type)
if isinstance(ast, tuple):
return convert_array_to_ptr(ast[1])
for i, c1 in enumerate(ast.children()):
child = ast.children()[i]
convert_array_to_ptr(child)
@memoize
def remove_quals(ast):
if hasattr(ast,'quals'):
ast.quals = []
if hasattr(ast,'dim_quals'):
ast.dim_quals = []
if isinstance(ast, tuple):
return remove_quals(ast[1])
for i, c1 in enumerate(ast.children()):
child = ast.children()[i]
if not isinstance(child, c_ast.FuncDecl): # Don't remove quals which change function prototype
remove_quals(child)
@memoize
def remove_explicit_struct(ast):
if isinstance(ast, c_ast.TypeDecl) and isinstance(ast.type, c_ast.Struct):
explicit_struct_name = ast.type.name
# eprint('--> replace %s by %s in:\n%s' % (explicit_struct_name, explicit_structs[explicit_struct_name] if explicit_struct_name in explicit_structs else '???', ast))
if explicit_struct_name:
if explicit_struct_name in explicit_structs:
ast.type = c_ast.IdentifierType([explicit_structs[explicit_struct_name]])
elif explicit_struct_name in structs:
ast.type = c_ast.IdentifierType([explicit_struct_name])
if isinstance(ast, tuple):
return remove_explicit_struct(ast[1])
for i, c1 in enumerate(ast.children()):
child = ast.children()[i]
remove_explicit_struct(child)
@memoize
def get_type(arg, **kwargs):
if isinstance(arg, str):
return arg
remove_quals_arg = 'remove_quals' in kwargs and kwargs['remove_quals']
arg_ast = copy.deepcopy(arg)
remove_explicit_struct(arg_ast)
if remove_quals_arg: remove_quals(arg_ast)
return gen.visit(arg_ast)
@memoize
def get_name(type):
if isinstance(type, c_ast.Decl):
return type.name
if isinstance(type, c_ast.Struct) and type.name and type.name in explicit_structs:
return explicit_structs[type.name]
if isinstance(type, c_ast.Struct):
return type.name
if isinstance(type, c_ast.TypeDecl):
return type.declname
if isinstance(type, c_ast.IdentifierType):
return type.names[0]
if isinstance(type, c_ast.FuncDecl):
return type.type.declname
# if isinstance(type, (c_ast.PtrDecl, c_ast.ArrayDecl)) and hasattr(type.type, 'declname'):
# return type.type.declname
if isinstance(type, (c_ast.PtrDecl, c_ast.ArrayDecl)):
return get_type(type, remove_quals=True)
else:
return gen.visit(type)
@memoize
def remove_arg_names(ast):
if isinstance(ast, c_ast.TypeDecl):
ast.declname = None
remove_arg_names(ast.type)
elif isinstance(ast, c_ast.Decl): remove_arg_names(ast.type)
elif isinstance(ast, c_ast.FuncDecl): remove_arg_names(ast.args)
elif isinstance(ast, c_ast.ParamList):
for param in ast.params: remove_arg_names(param)
# Create a function prototype AST from a function AST
@memoize
def function_prototype(func):
bare_func = copy.deepcopy(func)
remove_declname(bare_func)
ptr_decl = c_ast.PtrDecl(
quals=[],
type=bare_func.type)
func_proto = c_ast.Typename(
name=None,
quals=[],
align=[],
type=ptr_decl)
return func_proto
#
# module specific text patterns
# IGNORECASE and "lower" are used to match both function and enum names
#
base_obj_name = 'obj'
base_obj_type = '%s_%s_t' % (module_prefix, base_obj_name)
lv_ext_pattern = re.compile('^{prefix}_([^_]+)_ext_t'.format(prefix=module_prefix))
lv_obj_pattern = re.compile('^{prefix}_([^_]+)'.format(prefix=module_prefix), re.IGNORECASE)
lv_func_pattern = re.compile('^{prefix}_(.+)'.format(prefix=module_prefix), re.IGNORECASE)
create_obj_pattern = re.compile('^{prefix}_(.+)_create$'.format(prefix=module_prefix))
lv_method_pattern = re.compile('^{prefix}_[^_]+_(.+)'.format(prefix=module_prefix), re.IGNORECASE)
lv_base_obj_pattern = re.compile('^(struct _){{0,1}}{prefix}_{base_name}_t( [*]){{0,1}}'.format(prefix=module_prefix, base_name = base_obj_name))
lv_str_enum_pattern = re.compile('^_?{prefix}_STR_(.+)'.format(prefix=module_prefix.upper()))
lv_callback_type_pattern = re.compile('({prefix}_){{0,1}}(.+)_cb(_t){{0,1}}'.format(prefix=module_prefix))
lv_global_callback_pattern = re.compile('.*g_cb_t')
lv_func_returns_array = re.compile('.*_array$')
lv_enum_name_pattern = re.compile('^(ENUM_){{0,1}}({prefix}_){{0,1}}(.*)'.format(prefix=module_prefix.upper()))
# Prevent identifier names which are Python reserved words (add underscore in such case)
def sanitize(id, kwlist =
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']):
if id in kwlist:
result = "_%s" % id
else:
result = id
result = result.strip()
result = result.replace(' ','_')
result = result.replace('*','_ptr')
return result
@memoize
def simplify_identifier(id):
match_result = lv_func_pattern.match(id)
return match_result.group(1) if match_result else id
def obj_name_from_ext_name(ext_name):
return lv_ext_pattern.match(ext_name).group(1)
def obj_name_from_func_name(func_name):
return lv_obj_pattern.match(func_name).group(1)
def ctor_name_from_obj_name(obj_name):
return '{prefix}_{obj}_create'.format(prefix=module_prefix, obj=obj_name)
def is_method_of(func_name, obj_name):
return func_name.lower().startswith('{prefix}_{obj}_'.format(prefix=module_prefix, obj=obj_name).lower())
def method_name_from_func_name(func_name):
res = lv_method_pattern.match(func_name).group(1)
return res if res != "del" else "delete" # del is a reserved name, don't use it
def get_enum_name(enum):
match_result = lv_enum_name_pattern.match(enum)
return match_result.group(3) if match_result else enum
def str_enum_to_str(str_enum):
res = lv_str_enum_pattern.match(str_enum).group(1)
return ('%s_' % module_prefix.upper()) + res
def is_obj_ctor(func):
# ctor name must match pattern
if not create_obj_pattern.match(func.name): return False
# ctor must return a base_obj type
if not lv_base_obj_pattern.match(get_type(func.type.type, remove_quals=True)): return False
# ctor must receive (at least) one base obj parameters
args = func.type.args.params
if len(args) < 1: return False
if not lv_base_obj_pattern.match(get_type(args[0].type, remove_quals=True)): return False
return True
def is_global_callback(arg_type):
arg_type_str = get_name(arg_type.type)
# print('/* --> is_global_callback %s: %s */' % (lv_global_callback_pattern.match(arg_type_str), arg_type_str))
result = lv_global_callback_pattern.match(arg_type_str)
return result
#
# Initialization, data structures, helper functions
#
# We consider union as a struct, for simplicity
def is_struct(type):
return isinstance(type, c_ast.Struct) or isinstance(type, c_ast.Union)
obj_metadata = collections.OrderedDict()
func_metadata = collections.OrderedDict()
callback_metadata = collections.OrderedDict()
func_prototypes = {}
parser = c_parser.CParser()
gen = c_generator.CGenerator()
ast = parser.parse(s, filename='<none>')
if args.json is not None:
with open(args.json, "r") as f:
lvgl_json = json.load(f)
if not lvgl_json:
# if the json is an empty dictionary
lvgl_json = None
else:
lvgl_json = None
# *************** Fix ***********************************
# this is a fix for structures not getting populated properly from
# forward declarations. pycparser doesn't make the connection between
# a forwrd declaration and the actual declaration so the structures get created
# without any fields. Since there are no fields things like callbacks break
# because the generation code looks for specific field names
# to know if it is valid to be used as a callback.
forward_struct_decls = {}
for item in ast.ext[:]:
# Locate a forward declaration
if (
isinstance(item, c_ast.Decl) and
item.name is None and
isinstance(item.type, c_ast.Struct) and
item.type.name is not None
):
# check to see if there are no fields , and of not store the structure
# as a foward declaration. If it does have fields then build a single
# object that represents the structure with the fiels.
if item.type.decls is None:
forward_struct_decls[item.type.name] = [item]
else:
if item.type.name in forward_struct_decls:
decs = forward_struct_decls[item.type.name]
if len(decs) == 2:
decl, td = decs
td.type.type.decls = item.type.decls[:]
ast.ext.remove(decl)
ast.ext.remove(item)
# there are 3 objects that get created for a formard declaration.
# a structure without any fields, a typedef pointing to that structure.
# and the last is another structure that has fields. So we need to capture
# all 3 parts to build a single object that represents a structure.
elif (
isinstance(item, c_ast.Typedef) and
isinstance(item.type, c_ast.TypeDecl) and
item.name and
item.type.declname and
item.name == item.type.declname and
isinstance(item.type.type, c_ast.Struct) and
item.type.type.decls is None
):
if item.type.type.name in forward_struct_decls:
forward_struct_decls[item.type.type.name].append(item)
# ********************************************************************
# Types and structs
typedefs = [x.type for x in ast.ext if isinstance(x, c_ast.Typedef)] # and not (hasattr(x.type, 'declname') and lv_base_obj_pattern.match(x.type.declname))]
# print('/* %s */' % str(typedefs))
synonym = {}
for t in typedefs:
if isinstance(t, c_ast.TypeDecl) and isinstance(t.type, c_ast.IdentifierType):
if t.declname != t.type.names[0]:
synonym[t.declname] = t.type.names[0]
# eprint('%s === %s' % (t.declname, t.type.names[0]))
if isinstance(t, c_ast.TypeDecl) and isinstance(t.type, c_ast.Struct):
if t.declname != t.type.name:
synonym[t.declname] = t.type.name
# eprint('%s === struct %s' % (t.declname, t.type.name))
struct_typedefs = [typedef for typedef in typedefs if is_struct(typedef.type)]
structs_without_typedef = collections.OrderedDict((decl.type.name, decl.type) for decl in ast.ext if hasattr(decl, 'type') and is_struct(decl.type))
# for typedefs that referenced to a forward declaration struct, replace it with the real definition.
for typedef in struct_typedefs:
if typedef.type.decls is None: # None means it's a forward declaration
struct_name = typedef.type.name
# check if it's found in `structs_without_typedef`. It actually has the typedef. Replace type with it.
if typedef.type.name in structs_without_typedef:
typedef.type = structs_without_typedef[struct_name]
structs = collections.OrderedDict((typedef.declname, typedef.type) for typedef in struct_typedefs if typedef.declname and typedef.type.decls) # and not lv_base_obj_pattern.match(typedef.declname))
structs.update(structs_without_typedef) # This is for struct without typedef
explicit_structs = collections.OrderedDict((typedef.type.name, typedef.declname) for typedef in struct_typedefs if typedef.type.name) # and not lv_base_obj_pattern.match(typedef.type.name))
opaque_structs = collections.OrderedDict((typedef.declname, c_ast.Struct(name=typedef.declname, decls=[])) for typedef in typedefs if isinstance(typedef.type, c_ast.Struct) and typedef.type.decls == None)
structs.update({k:v for k,v in opaque_structs.items() if k not in structs})
# print('/* --> opaque structs len = %d */' % len(opaque_structs))
# print('/* --> opaque structs %s */' % ',\n'.join([struct_name for struct_name in opaque_structs]))
# print('/* --> structs:\n%s */' % ',\n'.join(sorted(str(structs[struct_name]) for struct_name in structs if struct_name)))
# print('/* --> structs_without_typedef:\n%s */' % ',\n'.join(sorted(str(structs_without_typedef[struct_name]) for struct_name in structs_without_typedef if struct_name)))
# print('/* --> explicit_structs:\n%s */' % ',\n'.join(sorted(struct_name + " = " + str(explicit_structs[struct_name]) for struct_name in explicit_structs if struct_name)))
# print('/* --> structs without typedef:\n%s */' % ',\n'.join(sorted(str(structs[struct_name]) for struct_name in structs_without_typedef)))
# Functions and objects
func_defs = [x.decl for x in ast.ext if isinstance(x, c_ast.FuncDef)]
func_decls = [x for x in ast.ext if isinstance(x, c_ast.Decl) and isinstance(x.type, c_ast.FuncDecl)]
all_funcs = func_defs + func_decls
funcs = [f for f in all_funcs if not f.name.startswith('_')] # functions that start with underscore are usually internal
# eprint('... %s' % ',\n'.join(sorted('%s' % func.name for func in funcs)))
obj_ctors = [func for func in funcs if is_obj_ctor(func)]
# eprint('CTORS(%d): %s' % (len(obj_ctors), ', '.join(sorted('%s' % ctor.name for ctor in obj_ctors))))
for obj_ctor in obj_ctors:
funcs.remove(obj_ctor)
obj_names = [create_obj_pattern.match(ctor.name).group(1) for ctor in obj_ctors]
def has_ctor(obj_name):
return ctor_name_from_obj_name(obj_name) in [ctor.name for ctor in obj_ctors]
def get_ctor(obj_name):
global obj_ctors
return next(ctor for ctor in obj_ctors if ctor.name == ctor_name_from_obj_name(obj_name))
def get_methods(obj_name):
global funcs
return [func for func in funcs \
if is_method_of(func.name,obj_name) and \
(not func.name == ctor_name_from_obj_name(obj_name))]
@memoize
def noncommon_part(member_name, stem_name):
common_part = commonprefix([member_name, stem_name])
n = len(common_part) - 1
while n > 0 and member_name[n] != '_': n-=1
return member_name[n+1:]
@memoize
def get_first_arg(func):
if not func.type.args:
return None
if not len(func.type.args.params) >= 1:
return None
if not func.type.args.params[0].type:
return None
return func.type.args.params[0].type
@memoize
def get_first_arg_type(func):
first_arg = get_first_arg(func)
if not first_arg:
return None
if not first_arg.type:
return None
return get_type(first_arg.type, remove_quals = True)
def get_base_struct_name(struct_name):
return struct_name[:-2] if struct_name.endswith('_t') else struct_name
# "struct function" starts with struct name (without _t), and their first argument is a pointer to the struct
# Need also to take into account struct functions of aliases of current struct.
@memoize
def get_struct_functions(struct_name):
global funcs
if not struct_name:
return []
base_struct_name = get_base_struct_name(struct_name)
# eprint("get_struct_functions %s: %s" % (struct_name, [get_type(func.type.args.params[0].type.type, remove_quals = True) for func in funcs if func.name.startswith(base_struct_name)]))
# eprint("get_struct_functions %s: %s" % (struct_name, struct_aliases[struct_name] if struct_name in struct_aliases else ""))
# for func in funcs:
# print("/* get_struct_functions: func=%s, struct=%s, noncommon part=%s */" % (simplify_identifier(func.name), simplify_identifier(struct_name),
# noncommon_part(simplify_identifier(func.name), simplify_identifier(struct_name))))
reverse_aliases = [alias for alias in struct_aliases if struct_aliases[alias] == struct_name]
return ([func for func in funcs \
if noncommon_part(simplify_identifier(func.name), simplify_identifier(struct_name)) != simplify_identifier(func.name) \
and get_first_arg_type(func) == struct_name] if (struct_name in structs or len(reverse_aliases) > 0) else []) + \
(get_struct_functions(struct_aliases[struct_name]) if struct_name in struct_aliases else [])
@memoize
def is_struct_function(func):
return func in get_struct_functions(get_first_arg_type(func))
# is_static_member returns true if function does not receive the obj as the first argument
# and the object is not a struct function
@memoize
def is_static_member(func, obj_type=base_obj_type):
first_arg = get_first_arg(func)
# print("/* %s : get_first_arg = %s */" % (get_name(func), first_arg))
if first_arg:
if isinstance(first_arg, c_ast.ArrayDecl):
return True # Arrays cannot have non static members
if is_struct_function(func):
return False
first_arg_type = get_first_arg_type(func)
return (first_arg_type == None) or (first_arg_type != obj_type)
# All object should inherit directly from base_obj, and not according to lv_ext, as disccussed on https://github.com/littlevgl/lv_binding_micropython/issues/19
parent_obj_names = {child_name: base_obj_name for child_name in obj_names if child_name != base_obj_name}
parent_obj_names[base_obj_name] = None
# Populate inheritance hierarchy according to lv_ext structures
# exts = {obj_name_from_ext_name(ext.name): ext for ext in ast.ext if hasattr(ext, 'name') and ext.name is not None and lv_ext_pattern.match(ext.name)}
# for obj_name, ext in exts.items():
# try:
# parent_ext_name = ext.type.type.decls[0].type.type.names[0]
# if lv_ext_pattern.match(parent_ext_name):
# parent_obj_names[obj_name] = obj_name_from_ext_name(parent_ext_name)
# except AttributeError:
# pass
# Parse Enums
enum_defs = [x for x in ast.ext if hasattr(x,'type') and isinstance(x.type, c_ast.Enum)]
enum_defs += [x.type for x in ast.ext if hasattr(x, 'type') and hasattr(x.type, 'type') and isinstance(x.type, c_ast.TypeDecl) and isinstance(x.type.type, c_ast.Enum)]
# Enum member access functions.
def get_enum_members(obj_name):
global enums
if not obj_name in enums:
return []
return [enum_member_name for enum_member_name, value in enums[obj_name].items()]
def get_enum_member_name(enum_member):
if enum_member[0].isdigit():
enum_member = '_' + enum_member # needs to be a valid attribute name
return enum_member
def get_enum_value(obj_name, enum_member):
return enums[obj_name][enum_member]
# eprint(enums)
# parse function pointers
func_typedefs = collections.OrderedDict((t.name, t) for t in ast.ext if isinstance(t, c_ast.Typedef) and isinstance(t.type, c_ast.PtrDecl) and isinstance(t.type.type, c_ast.FuncDecl))
# Global blobs
blobs = collections.OrderedDict((decl.name, decl.type.type) for decl in ast.ext \
if isinstance(decl, c_ast.Decl) \
and 'extern' in decl.storage \
and hasattr(decl, 'type') \
and isinstance(decl.type, c_ast.TypeDecl)
and not decl.name.startswith('_'))
blobs['_nesting'] = parser.parse('extern int _nesting;').ext[0].type.type
int_constants = []
#
# Type convertors
#
class MissingConversionException(ValueError):
pass
mp_to_lv = {
'mp_obj_t' : '(mp_obj_t)',
'va_list' : None,
'void *' : 'mp_to_ptr',
'const uint8_t *' : 'mp_to_ptr',
'const void *' : 'mp_to_ptr',
'bool' : 'mp_obj_is_true',
'char *' : '(char*)convert_from_str',
'char **' : 'mp_write_ptr_C_Pointer',
'const char *' : 'convert_from_str',
'const char **' : 'mp_write_ptr_C_Pointer',
'%s_obj_t *'% module_prefix : 'mp_to_lv',
'uint8_t' : '(uint8_t)mp_obj_get_int',
'uint16_t' : '(uint16_t)mp_obj_get_int',
'uint32_t' : '(uint32_t)mp_obj_get_int',
'uint64_t' : '(uint64_t)mp_obj_get_ull',
'unsigned' : '(unsigned)mp_obj_get_int',
'unsigned int' : '(unsigned int)mp_obj_get_int',
'unsigned char' : '(unsigned char)mp_obj_get_int',
'unsigned short' : '(unsigned short)mp_obj_get_int',
'unsigned long' : '(unsigned long)mp_obj_get_int',
'unsigned long int' : '(unsigned long int)mp_obj_get_int',
'unsigned long long' : '(unsigned long long)mp_obj_get_ull',
'unsigned long long int' : '(unsigned long long int)mp_obj_get_ull',
'int8_t' : '(int8_t)mp_obj_get_int',
'int16_t' : '(int16_t)mp_obj_get_int',
'int32_t' : '(int32_t)mp_obj_get_int',
'int64_t' : '(int64_t)mp_obj_get_ull',
'size_t' : '(size_t)mp_obj_get_int',
'int' : '(int)mp_obj_get_int',
'char' : '(char)mp_obj_get_int',
'short' : '(short)mp_obj_get_int',
'long' : '(long)mp_obj_get_int',
'long int' : '(long int)mp_obj_get_int',
'long long' : '(long long)mp_obj_get_ull',
'long long int' : '(long long int)mp_obj_get_ull',
'float' : '(float)mp_obj_get_float',
}
lv_to_mp = {
'mp_obj_t' : '(mp_obj_t)',
'va_list' : None,
'void *' : 'ptr_to_mp',
'const uint8_t *' : 'ptr_to_mp',
'const void *' : 'ptr_to_mp',
'bool' : 'convert_to_bool',
'char *' : 'convert_to_str',
'char **' : 'mp_read_ptr_C_Pointer',
'const char *' : 'convert_to_str',
'const char **' : 'mp_read_ptr_C_Pointer',
'%s_obj_t *'% module_prefix : 'lv_to_mp',
'uint8_t' : 'mp_obj_new_int_from_uint',
'uint16_t' : 'mp_obj_new_int_from_uint',
'uint32_t' : 'mp_obj_new_int_from_uint',
'uint64_t' : 'mp_obj_new_int_from_ull',
'unsigned' : 'mp_obj_new_int_from_uint',
'unsigned int' : 'mp_obj_new_int_from_uint',
'unsigned char' : 'mp_obj_new_int_from_uint',
'unsigned short' : 'mp_obj_new_int_from_uint',
'unsigned long' : 'mp_obj_new_int_from_uint',
'unsigned long int' : 'mp_obj_new_int_from_uint',
'unsigned long long' : 'mp_obj_new_int_from_ull',
'unsigned long long int' : 'mp_obj_new_int_from_ull',
'int8_t' : 'mp_obj_new_int',
'int16_t' : 'mp_obj_new_int',
'int32_t' : 'mp_obj_new_int',
'int64_t' : 'mp_obj_new_int_from_ll',
'size_t' : 'mp_obj_new_int_from_uint',
'int' : 'mp_obj_new_int',
'char' : 'mp_obj_new_int',
'short' : 'mp_obj_new_int',
'long' : 'mp_obj_new_int',
'long int' : 'mp_obj_new_int',
'long long' : 'mp_obj_new_int_from_ll',
'long long int' : 'mp_obj_new_int_from_ll',
'float' : 'mp_obj_new_float',
}
lv_mp_type = {
'mp_obj_t' : '%s*' % base_obj_type,
'va_list' : None,
'void *' : 'void*',
'const uint8_t *' : 'void*',
'const void *' : 'void*',
'bool' : 'bool',
'char *' : 'char*',
'char **' : 'char**',
'const char *' : 'char*',
'const char **' : 'char**',
'%s_obj_t *'% module_prefix : '%s*' % base_obj_type,
'uint8_t' : 'int',
'uint16_t' : 'int',
'uint32_t' : 'int',
'uint64_t' : 'int',
'unsigned' : 'int',
'unsigned int' : 'int',
'unsigned char' : 'int',
'unsigned short' : 'int',
'unsigned long' : 'int',
'unsigned long int' : 'int',
'unsigned long long' : 'int',
'unsigned long long int' : 'int',
'int8_t' : 'int',
'int16_t' : 'int',
'int32_t' : 'int',
'int64_t' : 'int',
'size_t' : 'int',
'int' : 'int',
'char' : 'int',
'short' : 'int',
'long' : 'int',
'long int' : 'int',
'long long' : 'int',
'long long int' : 'int',
'void' : None,
'float' : 'float',
}
lv_to_mp_byref = {}
lv_to_mp_funcptr = {}
# Add native array supported types
# These types would be converted automatically to/from array type.
# Supported array (pointer) types are signed/unsigned int: 8bit, 16bit, 32bit and 64bit.
def register_int_ptr_type(convertor, *types):
for ptr_type in types:
for qualified_ptr_type in [ptr_type, 'const '+ptr_type]:
mp_to_lv[qualified_ptr_type] = 'mp_array_to_%s' % (convertor)
lv_to_mp[qualified_ptr_type] = 'mp_array_from_%s' % (convertor)
lv_mp_type[qualified_ptr_type] = 'void*'
register_int_ptr_type('u8ptr',
'unsigned char *',
'uint8_t *')
# char* is considered as string, not int ptr!
'''
register_int_ptr_type('i8ptr',
'char *',
'int8_t *')
'''
register_int_ptr_type('u16ptr',
'unsigned short *',
'uint16_t *')
register_int_ptr_type('i16ptr',
'short *',
'int16_t *')
register_int_ptr_type('u32ptr',
'uint32_t *',
'unsigned *',
'unsigned int *',
'unsigned long *',
'unsigned long int *',
'size_t *')
register_int_ptr_type('i32ptr',
'int32_t *',
'signed *',
'signed int *',
'signed long *',
'signed long int *',
'long *',
'long int *',
'int *')
register_int_ptr_type('u64ptr',
'int64_t *',
'signed long long *',
'long long *',
'long long int *')
register_int_ptr_type('i64ptr',
'uint64_t *',
'unsigned long long *',
'unsigned long long int *')
#
# Emit Header
#
headers = args.input
for header in headers:
if 'lvgl.h' in header:
path, _ = os.path.split(header)
if path and path != 'lvgl.h':
path = os.path.join(path, 'src', 'lvgl_private.h')
else:
path = 'src/lvgl_private.h'
headers.append(path)
break
print ("""
/*
* Auto-Generated file, DO NOT EDIT!
*
* Command line:
* {cmd_line}
*
* Preprocessing command:
* {pp_cmd}
*
* Generating Objects: {objs}
*/
/*
* Mpy includes
*/
#include <stdlib.h>
#include <string.h>
#include "py/obj.h"
#include "py/objint.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "py/binary.h"
#include "py/objarray.h"
#include "py/objtype.h"
#include "py/objexcept.h"
/*
* {module_name} includes
*/
{lv_headers}
""".format(
module_name = module_name,
cmd_line=' '.join(argv),
pp_cmd=pp_cmd,
objs=", ".join(['%s(%s)' % (objname, parent_obj_names[objname]) for objname in obj_names]),
lv_headers='\n'.join('#include "%s"' % header for header in headers)))
#
# Enable objects, if supported
#
if len(obj_names) > 0:
print("""
#define LV_OBJ_T {obj_type}
typedef struct mp_lv_obj_type_t {{
const lv_obj_class_t *lv_obj_class;
const mp_obj_type_t *mp_obj_type;
}} mp_lv_obj_type_t;
STATIC const mp_lv_obj_type_t mp_lv_{base_obj}_type;
STATIC const mp_lv_obj_type_t *mp_lv_obj_types[];
STATIC inline const mp_obj_type_t *get_BaseObj_type()
{{
return mp_lv_{base_obj}_type.mp_obj_type;
}}
MP_DEFINE_EXCEPTION(LvReferenceError, Exception)
""".format(
obj_type = base_obj_type,
base_obj = base_obj_name
))
#
# Emit Mpy helper functions
#
print("""
/*
* Helper functions
*/
#ifndef GENMPY_UNUSED
#ifdef __GNUC__
#define GENMPY_UNUSED __attribute__ ((unused))
#else
#define GENMPY_UNUSED
#endif // __GNUC__
#endif // GENMPY_UNUSED
// Custom function mp object
typedef mp_obj_t (*mp_fun_ptr_var_t)(size_t n, const mp_obj_t *, void *ptr);
typedef struct mp_lv_obj_fun_builtin_var_t {
mp_obj_base_t base;
mp_uint_t n_args;
mp_fun_ptr_var_t mp_fun;
void *lv_fun;
} mp_lv_obj_fun_builtin_var_t;
STATIC mp_obj_t lv_fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args);
STATIC mp_int_t mp_func_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags);
GENMPY_UNUSED STATIC MP_DEFINE_CONST_OBJ_TYPE(
mp_lv_type_fun_builtin_var,
MP_QSTR_function,
MP_TYPE_FLAG_BINDS_SELF | MP_TYPE_FLAG_BUILTIN_FUN,
call, lv_fun_builtin_var_call,
unary_op, mp_generic_unary_op,
buffer, mp_func_get_buffer
);
GENMPY_UNUSED STATIC MP_DEFINE_CONST_OBJ_TYPE(
mp_lv_type_fun_builtin_static_var,
MP_QSTR_function,
MP_TYPE_FLAG_BUILTIN_FUN,
call, lv_fun_builtin_var_call,
unary_op, mp_generic_unary_op,
buffer, mp_func_get_buffer
);
STATIC mp_obj_t lv_fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
assert(MP_OBJ_IS_TYPE(self_in, &mp_lv_type_fun_builtin_var) ||
MP_OBJ_IS_TYPE(self_in, &mp_lv_type_fun_builtin_static_var));
mp_lv_obj_fun_builtin_var_t *self = MP_OBJ_TO_PTR(self_in);
mp_arg_check_num(n_args, n_kw, self->n_args, self->n_args, false);
return self->mp_fun(n_args, args, self->lv_fun);
}
STATIC mp_int_t mp_func_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
(void)flags;
assert(MP_OBJ_IS_TYPE(self_in, &mp_lv_type_fun_builtin_var) ||
MP_OBJ_IS_TYPE(self_in, &mp_lv_type_fun_builtin_static_var));
mp_lv_obj_fun_builtin_var_t *self = MP_OBJ_TO_PTR(self_in);
bufinfo->buf = &self->lv_fun;
bufinfo->len = sizeof(self->lv_fun);
bufinfo->typecode = BYTEARRAY_TYPECODE;
return 0;
}
#define MP_DEFINE_CONST_LV_FUN_OBJ_VAR(obj_name, n_args, mp_fun, lv_fun) \\
const mp_lv_obj_fun_builtin_var_t obj_name = \\
{{&mp_lv_type_fun_builtin_var}, n_args, mp_fun, lv_fun}
#define MP_DEFINE_CONST_LV_FUN_OBJ_STATIC_VAR(obj_name, n_args, mp_fun, lv_fun) \\
const mp_lv_obj_fun_builtin_var_t obj_name = \\
{{&mp_lv_type_fun_builtin_static_var}, n_args, mp_fun, lv_fun}
// Casting
typedef struct mp_lv_struct_t
{
mp_obj_base_t base;
void *data;
} mp_lv_struct_t;
STATIC const mp_lv_struct_t mp_lv_null_obj;
#ifdef LV_OBJ_T
STATIC mp_int_t mp_lv_obj_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags);
#else
STATIC mp_int_t mp_lv_obj_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags){ return 0; }
#endif
STATIC mp_int_t mp_blob_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags);
STATIC mp_obj_t get_native_obj(mp_obj_t mp_obj)
{
if (!MP_OBJ_IS_OBJ(mp_obj)) return mp_obj;
const mp_obj_type_t *native_type = ((mp_obj_base_t*)mp_obj)->type;
if (native_type == NULL)
return NULL;
if (MP_OBJ_TYPE_GET_SLOT_OR_NULL(native_type, parent) == NULL ||
(MP_OBJ_TYPE_GET_SLOT_OR_NULL(native_type, buffer) == mp_blob_get_buffer) ||
(MP_OBJ_TYPE_GET_SLOT_OR_NULL(native_type, buffer) == mp_lv_obj_get_buffer))
return mp_obj;
while (MP_OBJ_TYPE_GET_SLOT_OR_NULL(native_type, parent)) native_type = MP_OBJ_TYPE_GET_SLOT(native_type, parent);
return mp_obj_cast_to_native_base(mp_obj, MP_OBJ_FROM_PTR(native_type));
}
STATIC mp_obj_t dict_to_struct(mp_obj_t dict, const mp_obj_type_t *type);
STATIC mp_obj_t make_new_lv_struct(
const mp_obj_type_t *type,
size_t n_args,
size_t n_kw,
const mp_obj_t *args);
STATIC mp_obj_t cast(mp_obj_t mp_obj, const mp_obj_type_t *mp_type)
{
mp_obj_t res = NULL;
if (mp_obj == mp_const_none && MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_type, make_new) == &make_new_lv_struct) {
res = MP_OBJ_FROM_PTR(&mp_lv_null_obj);
} else if (MP_OBJ_IS_OBJ(mp_obj)) {
res = get_native_obj(mp_obj);
if (res){
const mp_obj_type_t *res_type = ((mp_obj_base_t*)res)->type;
if (res_type != mp_type){
if (res_type == &mp_type_dict &&
MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_type, make_new) == &make_new_lv_struct)
res = dict_to_struct(res, mp_type);
else res = NULL;
}
}
}
if (res == NULL) nlr_raise(
mp_obj_new_exception_msg_varg(
&mp_type_SyntaxError, MP_ERROR_TEXT("Can't convert %s to %s!"), mp_obj_get_type_str(mp_obj), qstr_str(mp_type->name)));
return res;
}
// object handling
// This section is enabled only when objects are supported
#ifdef LV_OBJ_T
typedef struct mp_lv_obj_t {
mp_obj_base_t base;
LV_OBJ_T *lv_obj;
LV_OBJ_T *callbacks;
} mp_lv_obj_t;
STATIC inline LV_OBJ_T *mp_to_lv(mp_obj_t mp_obj)
{
if (mp_obj == NULL || mp_obj == mp_const_none) return NULL;
mp_obj_t native_obj = get_native_obj(mp_obj);
if (MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_obj_get_type(native_obj), buffer) != mp_lv_obj_get_buffer)
return NULL;
mp_lv_obj_t *mp_lv_obj = MP_OBJ_TO_PTR(native_obj);
if (mp_lv_obj->lv_obj == NULL) {
nlr_raise(
mp_obj_new_exception_msg(
&mp_type_LvReferenceError, MP_ERROR_TEXT("Referenced object was deleted!")));
}
return mp_lv_obj->lv_obj;
}
STATIC inline LV_OBJ_T *mp_get_callbacks(mp_obj_t mp_obj)
{
if (mp_obj == NULL || mp_obj == mp_const_none) return NULL;
mp_lv_obj_t *mp_lv_obj = MP_OBJ_TO_PTR(get_native_obj(mp_obj));
if (mp_lv_obj == NULL)
nlr_raise(
mp_obj_new_exception_msg(
&mp_type_SyntaxError, MP_ERROR_TEXT("'user_data' argument must be either a dict or None!")));
if (!mp_lv_obj->callbacks) mp_lv_obj->callbacks = mp_obj_new_dict(0);
return mp_lv_obj->callbacks;
}
STATIC inline const mp_obj_type_t *get_BaseObj_type();
STATIC void mp_lv_delete_cb(lv_event_t * e)
{
LV_OBJ_T *lv_obj = e->current_target;
if (lv_obj){
mp_lv_obj_t *self = lv_obj->user_data;
if (self) {
self->lv_obj = NULL;