-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslator.py
2255 lines (1536 loc) · 71.4 KB
/
translator.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
#!/usr/bin/env python
"""
Translate programs.
Copyright (C) 2015, 2016, 2017, 2018 Paul Boddie <paul@boddie.org.uk>
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/>.
"""
from common import AccessLocation, CommonModule, CommonOutput, Location, \
first, get_builtin_class, init_item, is_newer, \
predefined_constants
from encoders import encode_access_instruction, encode_access_instruction_arg, \
encode_function_pointer, encode_literal_instantiator, \
encode_instantiator_pointer, encode_path, encode_symbol, \
encode_type_attribute, is_type_attribute, \
type_ops, typename_ops
from errors import InspectError, TranslateError
from os.path import exists, join
from os import makedirs
from referencing import Reference, combine_types
from results import Result
from transresults import TrConstantValueRef, TrInstanceRef, \
TrLiteralSequenceRef, TrResolvedNameRef, \
AliasResult, AttrResult, Expression, InstantiationResult, \
InvocationResult, LogicalOperationResult, \
LogicalResult, NegationResult, PredefinedConstantRef, \
ReturnRef
from StringIO import StringIO
import compiler
import sys
class Translator(CommonOutput):
"A program translator."
def __init__(self, importer, deducer, optimiser, output):
self.importer = importer
self.deducer = deducer
self.optimiser = optimiser
self.output = output
def to_output(self, reset=False, debug=False, gc_sections=False):
"Write a program to the configured output directory."
# Make a directory for the final sources.
output = join(self.output, "src")
if not exists(output):
makedirs(output)
# Clean the output directory of irrelevant data.
self.check_output("debug=%r gc_sections=%r" % (debug, gc_sections))
for module in self.importer.modules.values():
output_filename = join(output, "%s.c" % module.name)
# Do not generate modules in the native package. They are provided
# by native functionality source files.
parts = module.name.split(".")
if parts[0] != "native" and \
(reset or is_newer(module.filename, output_filename)):
tm = TranslatedModule(module.name, self.importer, self.deducer, self.optimiser)
tm.translate(module.filename, output_filename)
def make_expression(expr):
"Make a new expression from the existing 'expr'."
if isinstance(expr, Result):
return expr
else:
return Expression(str(expr))
# The actual translation process itself.
class TranslatedModule(CommonModule):
"A module translator."
def __init__(self, name, importer, deducer, optimiser):
CommonModule.__init__(self, name, importer)
self.deducer = deducer
self.optimiser = optimiser
# Output stream.
self.out_toplevel = self.out = None
self.indent = 0
self.tabstop = " "
# Recorded namespaces.
self.namespaces = []
self.in_conditional = False
self.in_parameter_list = False
# Exception raising adjustments.
self.in_try_finally = False
self.in_try_except = False
# Attribute access and accessor counting.
self.attr_accesses = {}
self.attr_accessors = {}
# Special variable usage.
self.temp_usage = {}
# Initialise some data used for attribute access generation.
self.init_substitutions()
def __repr__(self):
return "TranslatedModule(%r, %r)" % (self.name, self.importer)
def translate(self, filename, output_filename):
"""
Parse the file having the given 'filename', writing the translation to
the given 'output_filename'.
"""
self.parse_file(filename)
# Collect function namespaces for separate processing.
self.record_namespaces(self.astnode)
# Reset the lambda naming (in order to obtain the same names again) and
# translate the program.
self.reset_lambdas()
self.out_toplevel = self.out = open(output_filename, "w")
try:
self.start_output()
# Process namespaces, writing the translation.
for path, node in self.namespaces:
self.process_namespace(path, node)
# Process the module namespace including class namespaces.
self.process_namespace([], self.astnode)
finally:
self.out.close()
def have_object(self):
"Return whether a namespace is a recorded object."
return self.importer.objects.get(self.get_namespace_path())
def get_builtin_class(self, name):
"Return a reference to the actual object providing 'name'."
return self.importer.get_object(get_builtin_class(name))
def is_method(self, path):
"Return whether 'path' is a method."
class_name, method_name = path.rsplit(".", 1)
return self.importer.classes.has_key(class_name) and class_name or None
def in_method(self):
"Return whether the current namespace provides a method."
return self.in_function and self.is_method(self.get_namespace_path())
# Namespace recording.
def record_namespaces(self, node):
"Process the program structure 'node', recording namespaces."
for n in node.getChildNodes():
self.record_namespaces_in_node(n)
def record_namespaces_in_node(self, node):
"Process the program structure 'node', recording namespaces."
# Function namespaces within modules, classes and other functions.
# Functions appearing within conditional statements are given arbitrary
# names.
if isinstance(node, compiler.ast.Function):
self.record_function_node(node, (self.in_conditional or self.in_function) and self.get_lambda_name() or node.name)
elif isinstance(node, compiler.ast.Lambda):
self.record_function_node(node, self.get_lambda_name())
# Classes are visited, but may be ignored if inside functions.
elif isinstance(node, compiler.ast.Class):
self.enter_namespace(node.name)
if self.have_object():
self.record_namespaces(node)
self.exit_namespace()
# Conditional nodes are tracked so that function definitions may be
# handled. Since "for" loops are converted to "while" loops, they are
# included here.
elif isinstance(node, (compiler.ast.For, compiler.ast.If, compiler.ast.While)):
in_conditional = self.in_conditional
self.in_conditional = True
self.record_namespaces(node)
self.in_conditional = in_conditional
# All other nodes are processed depth-first.
else:
self.record_namespaces(node)
def record_function_node(self, n, name):
"""
Record the given function, lambda, if expression or list comprehension
node 'n' with the given 'name'.
"""
self.in_function = True
self.enter_namespace(name)
if self.have_object():
# Record the namespace path and the node itself.
self.namespaces.append((self.namespace_path[:], n))
self.record_namespaces_in_node(n.code)
self.exit_namespace()
self.in_function = False
# Constant referencing.
def get_literal_instance(self, n, name=None):
"""
For node 'n', return a reference for the type of the given 'name', or if
'name' is not specified, deduce the type from the value.
"""
# Handle stray None constants (Sliceobj seems to produce them).
if name is None and n.value is None:
return self.process_name_node(compiler.ast.Name("None"))
if name in ("dict", "list", "tuple"):
ref = self.get_builtin_class(name)
return self.process_literal_sequence_node(n, name, ref, TrLiteralSequenceRef)
else:
value, typename, encoding = self.get_constant_value(n.value, n.literals)
ref = self.get_builtin_class(typename)
value_type = ref.get_origin()
path = self.get_namespace_path()
# Obtain the local numbering of the constant and thus the
# locally-qualified name.
local_number = self.importer.all_constants[path][(value, value_type, encoding)]
constant_name = "$c%d" % local_number
objpath = self.get_object_path(constant_name)
# Obtain the unique identifier for the constant.
number = self.optimiser.constant_numbers[objpath]
return TrConstantValueRef(constant_name, ref.instance_of(), value, number)
# Namespace translation.
def process_namespace(self, path, node):
"""
Process the namespace for the given 'path' defined by the given 'node'.
"""
self.namespace_path = path
if isinstance(node, (compiler.ast.Function, compiler.ast.Lambda)):
self.in_function = True
self.process_function_body_node(node)
else:
self.in_function = False
self.function_target = 0
self.max_function_target = 0
self.context_index = 0
self.max_context_index = 0
self.accessor_index = 0
self.max_accessor_index = 0
self.start_module()
self.process_structure(node)
self.end_module()
def process_structure(self, node):
"Process the given 'node' or result."
# Handle processing requests on results.
if isinstance(node, Result):
return node
# Handle processing requests on nodes.
else:
l = CommonModule.process_structure(self, node)
# Return indications of return statement usage.
if l and isinstance(l[-1], ReturnRef):
return l[-1]
else:
return None
def process_structure_node(self, n):
"Process the individual node 'n'."
# Plain statements emit their expressions.
if isinstance(n, compiler.ast.Discard):
expr = self.process_structure_node(n.expr)
self.statement(expr)
# Module import declarations.
elif isinstance(n, compiler.ast.From):
self.process_from_node(n)
# Nodes using operator module functions.
elif isinstance(n, compiler.ast.Operator):
return self.process_operator_node(n)
elif isinstance(n, compiler.ast.AugAssign):
self.process_augassign_node(n)
elif isinstance(n, compiler.ast.Compare):
return self.process_compare_node(n)
elif isinstance(n, compiler.ast.Slice):
return self.process_slice_node(n)
elif isinstance(n, compiler.ast.Sliceobj):
return self.process_sliceobj_node(n)
elif isinstance(n, compiler.ast.Subscript):
return self.process_subscript_node(n)
# Classes are visited, but may be ignored if inside functions.
elif isinstance(n, compiler.ast.Class):
self.process_class_node(n)
# Functions within namespaces have any dynamic defaults initialised.
elif isinstance(n, compiler.ast.Function):
self.process_function_node(n)
# Lambdas are replaced with references to separately-generated
# functions.
elif isinstance(n, compiler.ast.Lambda):
return self.process_lambda_node(n)
# Assignments.
elif isinstance(n, compiler.ast.Assign):
# Handle each assignment node.
for node in n.nodes:
self.process_assignment_node(node, n.expr)
# Accesses.
elif isinstance(n, compiler.ast.Getattr):
return self.process_attribute_access(n)
# Names.
elif isinstance(n, compiler.ast.Name):
return self.process_name_node(n)
# Loops and conditionals.
elif isinstance(n, compiler.ast.For):
self.process_for_node(n)
elif isinstance(n, compiler.ast.While):
self.process_while_node(n)
elif isinstance(n, compiler.ast.If):
self.process_if_node(n)
elif isinstance(n, (compiler.ast.And, compiler.ast.Or)):
return self.process_logical_node(n)
elif isinstance(n, compiler.ast.Not):
return self.process_not_node(n)
# Exception control-flow tracking.
elif isinstance(n, compiler.ast.TryExcept):
self.process_try_node(n)
elif isinstance(n, compiler.ast.TryFinally):
self.process_try_finally_node(n)
# Control-flow modification statements.
elif isinstance(n, compiler.ast.Break):
self.writestmt("break;")
elif isinstance(n, compiler.ast.Continue):
self.writestmt("continue;")
elif isinstance(n, compiler.ast.Raise):
self.process_raise_node(n)
elif isinstance(n, compiler.ast.Return):
return self.process_return_node(n)
# Print statements.
elif isinstance(n, (compiler.ast.Print, compiler.ast.Printnl)):
self.statement(self.process_print_node(n))
# Invocations.
elif isinstance(n, compiler.ast.CallFunc):
return self.process_invocation_node(n)
elif isinstance(n, compiler.ast.Keyword):
return self.process_structure_node(n.expr)
# Constant usage.
elif isinstance(n, compiler.ast.Const):
return self.get_literal_instance(n)
elif isinstance(n, compiler.ast.Dict):
return self.get_literal_instance(n, "dict")
elif isinstance(n, compiler.ast.List):
return self.get_literal_instance(n, "list")
elif isinstance(n, compiler.ast.Tuple):
return self.get_literal_instance(n, "tuple")
# All other nodes are processed depth-first.
else:
return self.process_structure(n)
def process_assignment_node(self, n, expr):
"Process the individual node 'n' to be assigned the contents of 'expr'."
# Names and attributes are assigned the entire expression.
if isinstance(n, compiler.ast.AssName):
name_ref = self.process_name_node(n, self.process_structure_node(expr))
self.statement(name_ref)
# Employ guards after assignments if required.
if expr and name_ref.is_name():
self.generate_guard(name_ref.name)
elif isinstance(n, compiler.ast.AssAttr):
in_assignment = self.in_assignment
self.in_assignment = self.process_structure_node(expr)
self.statement(self.process_attribute_access(n))
self.in_assignment = in_assignment
# Lists and tuples are matched against the expression and their
# items assigned to expression items.
elif isinstance(n, (compiler.ast.AssList, compiler.ast.AssTuple)):
self.process_assignment_node_items(n, expr)
# Slices and subscripts are permitted within assignment nodes.
elif isinstance(n, compiler.ast.Slice):
self.statement(self.process_slice_node(n, expr))
elif isinstance(n, compiler.ast.Subscript):
self.statement(self.process_subscript_node(n, expr))
def process_attribute_access(self, n):
"Process the given attribute access node 'n'."
# Obtain any completed chain and return the reference to it.
attr_expr = self.process_attribute_chain(n)
if self.have_access_expression(n):
return attr_expr
# Where the start of the chain of attributes has been reached, process
# the complete access.
name_ref = attr_expr and attr_expr.is_name() and attr_expr
name = name_ref and self.get_name_for_tracking(name_ref.name, name_ref) or None
location = self.get_access_location(name, self.attrs)
refs = self.get_referenced_attributes(location)
# Generate access instructions.
subs = {
"<expr>" : attr_expr,
"<name>" : attr_expr,
"<assexpr>" : self.in_assignment,
}
subs.update(self.temp_subs)
subs.update(self.op_subs)
output = []
substituted = set()
# The context set or retrieved will be that used by any enclosing
# invocation.
accessor_index = self.accessor_index
context_index = self.context_index
context_identity = None
context_identity_verified = False
final_identity = None
accessor_test = False
accessor_stored = False
# Obtain encoded versions of each instruction, accumulating temporary
# variables.
for instruction in self.deducer.access_instructions[location]:
# Intercept a special instruction identifying the context.
if instruction[0] in ("<context_identity>", "<context_identity_verified>"):
context_identity, _substituted = \
encode_access_instruction_arg(instruction[1], subs, instruction[0],
accessor_index, context_index)
context_identity_verified = instruction[0] == "<context_identity_verified>"
continue
# Intercept a special instruction identifying the target. The value
# is not encoded since it is used internally.
elif instruction[0] == "<final_identity>":
final_identity = instruction[1]
continue
# Modify test instructions.
elif instruction[0] in typename_ops or instruction[0] in type_ops:
instruction = ("__to_error", instruction)
accessor_test = True
# Intercept accessor storage.
elif instruction[0] == "<set_accessor>":
accessor_stored = True
# Collect the encoded instruction, noting any temporary variables
# required by it.
encoded, _substituted = encode_access_instruction(instruction, subs,
accessor_index, context_index)
output.append(encoded)
substituted.update(_substituted)
# Record temporary name usage.
for sub in substituted:
if self.temp_subs.has_key(sub):
self.record_temp(self.temp_subs[sub])
# Get full final identity details.
if final_identity and not refs:
refs = set([self.importer.identify(final_identity)])
del self.attrs[0]
return AttrResult(output, refs, location,
context_identity, context_identity_verified,
accessor_test, accessor_stored)
def init_substitutions(self):
"""
Initialise substitutions, defining temporary variable mappings, some of
which are also used as substitutions, together with operation mappings
used as substitutions in instructions defined by the optimiser.
"""
self.temp_subs = {
# Substitutions used by instructions.
"<private_context>" : "__tmp_private_context",
"<target_accessor>" : "__tmp_target_value",
# Mappings to be replaced by those given below.
"<accessor>" : "__tmp_values",
"<context>" : "__tmp_contexts",
"<test_context_revert>" : "__tmp_contexts",
"<test_context_static>" : "__tmp_contexts",
"<set_context>" : "__tmp_contexts",
"<set_private_context>" : "__tmp_private_context",
"<set_accessor>" : "__tmp_values",
"<set_target_accessor>" : "__tmp_target_value",
}
self.op_subs = {
"<accessor>" : "__get_accessor",
"<context>" : "__get_context",
"<test_context_revert>" : "__test_context_revert",
"<test_context_static>" : "__test_context_static",
"<set_context>" : "__set_context",
"<set_private_context>" : "__set_private_context",
"<set_accessor>" : "__set_accessor",
"<set_target_accessor>" : "__set_target_accessor",
}
def get_referenced_attributes(self, location):
"""
Convert 'location' to the form used by the deducer and retrieve any
identified attributes.
"""
# Determine whether any deduced references refer to the accessed
# attribute.
attrnames = location.attrnames
attrnames = attrnames and attrnames.split(".")
remaining = attrnames and len(attrnames) > 1
access_location = self.deducer.const_accesses.get(location)
if remaining and not access_location:
return set()
return self.deducer.get_references_for_access(access_location or location)
def get_referenced_attribute_invocations(self, location):
"""
Convert 'location' to the form used by the deducer and retrieve any
identified attribute invocation details.
"""
access_location = self.deducer.const_accesses.get(location)
return self.deducer.reference_invocations_unsuitable.get(access_location or location)
def get_accessor_kinds(self, location):
"Return the accessor kinds for 'location'."
return self.deducer.accessor_kinds.get(location)
def get_access_location(self, name, attrnames=None):
"""
Using the current namespace, the given 'name', and the 'attrnames'
employed in an access, return the access location.
"""
path = self.get_path_for_access()
# Get the location used by the deducer and optimiser and find any
# recorded access.
attrnames = attrnames and ".".join(self.attrs)
access_number = self.get_access_number(path, name, attrnames)
self.update_access_number(path, name, attrnames)
return AccessLocation(path, name, attrnames, access_number)
def get_access_number(self, path, name, attrnames):
access = name, attrnames
if self.attr_accesses.has_key(path) and self.attr_accesses[path].has_key(access):
return self.attr_accesses[path][access]
else:
return 0
def update_access_number(self, path, name, attrnames):
access = name, attrnames
if name:
init_item(self.attr_accesses, path, dict)
init_item(self.attr_accesses[path], access, lambda: 0)
self.attr_accesses[path][access] += 1
def get_accessor_location(self, name):
"""
Using the current namespace and the given 'name', return the accessor
location.
"""
path = self.get_path_for_access()
# Get the location used by the deducer and optimiser and find any
# recorded accessor.
version = self.get_accessor_number(path, name)
self.update_accessor_number(path, name)
return Location(path, name, None, version)
def get_accessor_number(self, path, name):
if self.attr_accessors.has_key(path) and self.attr_accessors[path].has_key(name):
return self.attr_accessors[path][name]
else:
return 0
def update_accessor_number(self, path, name):
if name:
init_item(self.attr_accessors, path, dict)
init_item(self.attr_accessors[path], name, lambda: 0)
self.attr_accessors[path][name] += 1
def process_class_node(self, n):
"Process the given class node 'n'."
class_name = self.get_object_path(n.name)
# Where a class is set conditionally or where the name may refer to
# different values, assign the name.
ref = self.importer.identify(class_name)
if not ref.static():
self.process_assignment_for_object(n.name,
make_expression("__ATTRVALUE(&%s)" % encode_path(class_name)))
self.enter_namespace(n.name)
if self.have_object():
self.write_comment("Class: %s" % class_name)
self.initialise_inherited_members(class_name)
self.process_structure(n)
self.write_comment("End class: %s" % class_name)
self.exit_namespace()
def initialise_inherited_members(self, class_name):
"Initialise members of 'class_name' inherited from its ancestors."
for name, path in self.importer.all_class_attrs[class_name].items():
target = "%s.%s" % (class_name, name)
# Ignore attributes with definitions.
ref = self.importer.identify(target)
if ref:
continue
# Ignore special type attributes.
if is_type_attribute(name):
continue
# Reference inherited attributes.
ref = self.importer.identify(path)
if ref and not ref.static():
parent, attrname = path.rsplit(".", 1)
self.writestmt("__store_via_object(&%s, %s, __load_via_object(&%s, %s));" % (
encode_path(class_name), name,
encode_path(parent), attrname
))
def process_from_node(self, n):
"Process the given node 'n', importing from another module."
path = self.get_namespace_path()
# Attempt to obtain the referenced objects.
for name, alias in n.names:
if name == "*":
raise InspectError("Only explicitly specified names can be imported from modules.", path, n)
# Obtain the path of the assigned name.
objpath = self.get_object_path(alias or name)
# Obtain the identity of the name.
ref = self.importer.identify(objpath)
# Where the name is not static, assign the value.
if ref and not ref.static() and ref.get_name():
self.writestmt("%s;" %
TrResolvedNameRef(alias or name, Reference("<var>", None, objpath),
expr=TrResolvedNameRef(name, ref)))
def process_function_body_node(self, n):
"""
Process the given function, lambda, if expression or list comprehension
node 'n', generating the body.
"""
function_name = self.get_namespace_path()
self.start_function(function_name)
# Process the function body.
in_conditional = self.in_conditional
self.in_conditional = False
self.function_target = 0
self.max_function_target = 0
self.context_index = 0
self.max_context_index = 0
self.accessor_index = 0
self.max_accessor_index = 0
# Volatile locals for exception handling.
self.volatile_locals = set()
# Process any guards defined for the parameters.
for name in self.importer.function_parameters.get(function_name):
self.generate_guard(name)
# Also support self in methods, since some mix-in methods may only work
# with certain descendant classes.
if self.in_method():
self.generate_guard("self")
# Make assignments for .name entries in the parameters, provided this is
# a method.
if self.in_method():
for name in self.importer.function_attr_initialisers.get(function_name) or []:
self.process_assignment_node(
compiler.ast.AssAttr(compiler.ast.Name("self"), name, "OP_ASSIGN"),
compiler.ast.Name(name))
# Produce the body and any additional return statement.
expr = self.process_structure_node(n.code) or \
self.in_method() and \
function_name.rsplit(".", 1)[-1] == "__init__" and \
TrResolvedNameRef("self", self.importer.function_locals[function_name]["self"]) or \
PredefinedConstantRef("None")
if not isinstance(expr, ReturnRef):
self.writestmt("return %s;" % expr)
self.in_conditional = in_conditional
self.end_function(function_name)
def generate_guard(self, name):
"""
Get the accessor details for 'name', found in the current namespace, and
generate any guards defined for it.
"""
# Obtain the location, keeping track of assignment versions.
location = self.get_accessor_location(name)
test = self.deducer.accessor_guard_tests.get(location)
# Generate any guard from the deduced information.
if test:
guard, guard_type = test
if guard == "specific":
ref = first(self.deducer.accessor_all_types[location])
argstr = "&%s" % encode_path(ref.get_origin())
elif guard == "common":
ref = first(self.deducer.accessor_all_general_types[location])
argstr = encode_path(encode_type_attribute(ref.get_origin()))
else:
return
# Write a test that raises a TypeError upon failure.
self.writestmt("if (!__test_%s_%s(__VALUE(%s), %s)) __raise_type_error();" % (
guard, guard_type, encode_path(name), argstr))
def process_function_node(self, n):
"""
Process the given function, lambda, if expression or list comprehension
node 'n', generating any initialisation statements.
"""
# Where a function is declared conditionally, use a separate name for
# the definition, and assign the definition to the stated name.
original_name = n.name
if self.in_conditional or self.in_function:
name = self.get_lambda_name()
else:
name = n.name
objpath = self.get_object_path(name)
# Obtain details of the defaults.
defaults = self.process_function_defaults(n, name, objpath)
if defaults:
for default in defaults:
self.writeline("%s;" % default)
# Where a function is set conditionally or where the name may refer to
# different values, assign the name.
ref = self.importer.identify(objpath)
if self.in_conditional or self.in_function:
self.process_assignment_for_object(original_name, compiler.ast.Name(name))
elif not ref.static():
context = self.is_method(objpath)
self.process_assignment_for_object(original_name,
make_expression("__ATTRVALUE(&%s)" % encode_path(objpath)))
def process_function_defaults(self, n, name, objpath, instance_name=None):
"""
Process the given function or lambda node 'n', initialising defaults
that are dynamically set. The given 'name' indicates the name of the
function. The given 'objpath' indicates the origin of the function.
The given 'instance_name' indicates the name of any separate instance
of the function created to hold the defaults.
Return a list of operations setting defaults on a function instance.
"""
function_name = self.get_object_path(name)
function_defaults = self.importer.function_defaults.get(function_name)
if not function_defaults:
return None
# Determine whether any unidentified defaults are involved.
for argname, default in function_defaults:
if not default.static():
break
else:
return None
# Handle bound methods.
if not instance_name:
instance_name = "&%s" % encode_path(objpath)
else: