Skip to content

Commit fa0ed4a

Browse files
cclaussrvagg
authored andcommitted
build: more Python 3 compat, replace compile with ast
Make Python 3 compatiblity changes so the code works in both Python 2 and Python 3. Especially, make changes required because the compiler module was removed in Python 3 in favor of the ast module that exists in both Python 2 and Python 3. PR-URL: #1820 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Rod Vagg <[email protected]> Reviewed-By: Richard Lau <[email protected]>
1 parent 18d5c7c commit fa0ed4a

File tree

7 files changed

+50
-56
lines changed

7 files changed

+50
-56
lines changed

gyp/pylib/gyp/generator/analyzer.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -671,7 +671,7 @@ def find_matching_compile_target_names(self):
671671
assert self.is_build_impacted();
672672
# Compile targets are found by searching up from changed targets.
673673
# Reset the visited status for _GetBuildTargets.
674-
for target in self._name_to_target.itervalues():
674+
for target in self._name_to_target.values():
675675
target.visited = False
676676

677677
supplied_targets = _LookupTargets(self._supplied_target_names_no_all(),

gyp/pylib/gyp/generator/eclipse.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ def WriteMacros(out, eclipse_langs, defines):
272272
out.write(' <language name="holder for library settings"></language>\n')
273273
for lang in eclipse_langs:
274274
out.write(' <language name="%s">\n' % lang)
275-
for key in sorted(defines.iterkeys()):
275+
for key in sorted(defines):
276276
out.write(' <macro><name>%s</name><value>%s</value></macro>\n' %
277277
(escape(key), escape(defines[key])))
278278
out.write(' </language>\n')

gyp/pylib/gyp/generator/make.py

+19-19
Original file line numberDiff line numberDiff line change
@@ -821,7 +821,7 @@ def Write(self, qualified_target, base_path, output_filename, spec, configs,
821821
gyp.xcode_emulation.MacPrefixHeader(
822822
self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)),
823823
self.Pchify))
824-
sources = filter(Compilable, all_sources)
824+
sources = list(filter(Compilable, all_sources))
825825
if sources:
826826
self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1)
827827
extensions = set([os.path.splitext(s)[1] for s in sources])
@@ -950,7 +950,7 @@ def WriteActions(self, actions, extra_sources, extra_outputs,
950950
'%s%s'
951951
% (name, cd_action, command))
952952
self.WriteLn()
953-
outputs = map(self.Absolutify, outputs)
953+
outputs = [self.Absolutify(output) for output in outputs]
954954
# The makefile rules are all relative to the top dir, but the gyp actions
955955
# are defined relative to their containing dir. This replaces the obj
956956
# variable for the action rule with an absolute version so that the output
@@ -974,7 +974,7 @@ def WriteActions(self, actions, extra_sources, extra_outputs,
974974
outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs]
975975
inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs]
976976

977-
self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)),
977+
self.WriteDoCmd(outputs, [Sourceify(self.Absolutify(i)) for i in inputs],
978978
part_of_all=part_of_all, command=name)
979979

980980
# Stuff the outputs in a variable so we can refer to them later.
@@ -1023,8 +1023,8 @@ def WriteRules(self, rules, extra_sources, extra_outputs,
10231023
extra_sources += outputs
10241024
if int(rule.get('process_outputs_as_mac_bundle_resources', False)):
10251025
extra_mac_bundle_resources += outputs
1026-
inputs = map(Sourceify, map(self.Absolutify, [rule_source] +
1027-
rule.get('inputs', [])))
1026+
inputs = [Sourceify(self.Absolutify(i)) for i
1027+
in [rule_source] + rule.get('inputs', [])]
10281028
actions = ['$(call do_cmd,%s_%d)' % (name, count)]
10291029

10301030
if name == 'resources_grit':
@@ -1040,7 +1040,7 @@ def WriteRules(self, rules, extra_sources, extra_outputs,
10401040
outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs]
10411041
inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs]
10421042

1043-
outputs = map(self.Absolutify, outputs)
1043+
outputs = [self.Absolutify(output) for output in outputs]
10441044
all_outputs += outputs
10451045
# Only write the 'obj' and 'builddir' rules for the "primary" output
10461046
# (:1); it's superfluous for the "extra outputs", and this avoids
@@ -1147,7 +1147,7 @@ def WriteCopies(self, copies, extra_outputs, part_of_all):
11471147
path = gyp.xcode_emulation.ExpandEnvVars(path, env)
11481148
self.WriteDoCmd([output], [path], 'copy', part_of_all)
11491149
outputs.append(output)
1150-
self.WriteLn('%s = %s' % (variable, ' '.join(map(QuoteSpaces, outputs))))
1150+
self.WriteLn('%s = %s' % (variable, ' '.join(QuoteSpaces(o) for o in outputs)))
11511151
extra_outputs.append('$(%s)' % variable)
11521152
self.WriteLn()
11531153

@@ -1158,7 +1158,7 @@ def WriteMacBundleResources(self, resources, bundle_deps):
11581158

11591159
for output, res in gyp.xcode_emulation.GetMacBundleResources(
11601160
generator_default_variables['PRODUCT_DIR'], self.xcode_settings,
1161-
map(Sourceify, map(self.Absolutify, resources))):
1161+
[Sourceify(self.Absolutify(r)) for r in resources]):
11621162
_, ext = os.path.splitext(output)
11631163
if ext != '.xcassets':
11641164
# Make does not supports '.xcassets' emulation.
@@ -1238,11 +1238,11 @@ def WriteSources(self, configs, deps, sources,
12381238
self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname)
12391239
includes = config.get('include_dirs')
12401240
if includes:
1241-
includes = map(Sourceify, map(self.Absolutify, includes))
1241+
includes = [Sourceify(self.Absolutify(i)) for i in includes]
12421242
self.WriteList(includes, 'INCS_%s' % configname, prefix='-I')
12431243

1244-
compilable = filter(Compilable, sources)
1245-
objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable)))
1244+
compilable = list(filter(Compilable, sources))
1245+
objs = [self.Objectify(self.Absolutify(Target(c))) for c in compilable]
12461246
self.WriteList(objs, 'OBJS')
12471247

12481248
for obj in objs:
@@ -1314,7 +1314,7 @@ def WriteSources(self, configs, deps, sources,
13141314

13151315
# If there are any object files in our input file list, link them into our
13161316
# output.
1317-
extra_link_deps += filter(Linkable, sources)
1317+
extra_link_deps += list(filter(Linkable, sources))
13181318

13191319
self.WriteLn()
13201320

@@ -1564,7 +1564,7 @@ def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps,
15641564

15651565
# Bundle dependencies. Note that the code below adds actions to this
15661566
# target, so if you move these two lines, move the lines below as well.
1567-
self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS')
1567+
self.WriteList([QuoteSpaces(dep) for dep in bundle_deps], 'BUNDLE_DEPS')
15681568
self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output))
15691569

15701570
# After the framework is built, package it. Needs to happen before
@@ -1598,7 +1598,7 @@ def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps,
15981598
if self.type == 'executable':
15991599
self.WriteLn('%s: LD_INPUTS := %s' % (
16001600
QuoteSpaces(self.output_binary),
1601-
' '.join(map(QuoteSpaces, link_deps))))
1601+
' '.join(QuoteSpaces(dep) for dep in link_deps)))
16021602
if self.toolset == 'host' and self.flavor == 'android':
16031603
self.WriteDoCmd([self.output_binary], link_deps, 'link_host',
16041604
part_of_all, postbuilds=postbuilds)
@@ -1620,7 +1620,7 @@ def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps,
16201620
elif self.type == 'shared_library':
16211621
self.WriteLn('%s: LD_INPUTS := %s' % (
16221622
QuoteSpaces(self.output_binary),
1623-
' '.join(map(QuoteSpaces, link_deps))))
1623+
' '.join(QuoteSpaces(dep) for dep in link_deps)))
16241624
self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all,
16251625
postbuilds=postbuilds)
16261626
elif self.type == 'loadable_module':
@@ -1746,8 +1746,8 @@ def WriteMakeRule(self, outputs, inputs, actions=None, comment=None,
17461746
output is just a name to run the rule
17471747
command: (optional) command name to generate unambiguous labels
17481748
"""
1749-
outputs = map(QuoteSpaces, outputs)
1750-
inputs = map(QuoteSpaces, inputs)
1749+
outputs = [QuoteSpaces(o) for o in outputs]
1750+
inputs = [QuoteSpaces(i) for i in inputs]
17511751

17521752
if comment:
17531753
self.WriteLn('# ' + comment)
@@ -1836,7 +1836,7 @@ def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps):
18361836
default_cpp_ext = ext
18371837
self.WriteLn('LOCAL_CPP_EXTENSION := ' + default_cpp_ext)
18381838

1839-
self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)),
1839+
self.WriteList(list(map(self.Absolutify, filter(Compilable, all_sources))),
18401840
'LOCAL_SRC_FILES')
18411841

18421842
# Filter out those which do not match prefix and suffix and produce
@@ -1979,7 +1979,7 @@ def WriteAutoRegenerationRule(params, root_makefile, makefile_name,
19791979
"%(makefile_name)s: %(deps)s\n"
19801980
"\t$(call do_cmd,regen_makefile)\n\n" % {
19811981
'makefile_name': makefile_name,
1982-
'deps': ' '.join(map(SourceifyAndQuoteSpaces, build_files)),
1982+
'deps': ' '.join(SourceifyAndQuoteSpaces(bf) for bf in build_files),
19831983
'cmd': gyp.common.EncodePOSIXShellList(
19841984
[gyp_binary, '-fmake'] +
19851985
gyp.RegenerateFlags(options) +

gyp/pylib/gyp/generator/msvs.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2691,7 +2691,7 @@ def _GetMSBuildGlobalProperties(spec, guid, gyp_file_name):
26912691

26922692
platform_name = None
26932693
msvs_windows_target_platform_version = None
2694-
for configuration in spec['configurations'].itervalues():
2694+
for configuration in spec['configurations'].values():
26952695
platform_name = platform_name or _ConfigPlatform(configuration)
26962696
msvs_windows_target_platform_version = \
26972697
msvs_windows_target_platform_version or \
@@ -3252,7 +3252,7 @@ def _GetMSBuildProjectReferences(project):
32523252
['Project', guid],
32533253
['ReferenceOutputAssembly', 'false']
32543254
]
3255-
for config in dependency.spec.get('configurations', {}).itervalues():
3255+
for config in dependency.spec.get('configurations', {}).values():
32563256
if config.get('msvs_use_library_dependency_inputs', 0):
32573257
project_ref.append(['UseLibraryDependencyInputs', 'true'])
32583258
break
@@ -3321,7 +3321,7 @@ def _GenerateMSBuildProject(project, options, version, generator_flags):
33213321
extension_to_rule_name, _GetUniquePlatforms(spec))
33223322
missing_sources = _VerifySourcesExist(sources, project_dir)
33233323

3324-
for configuration in configurations.itervalues():
3324+
for configuration in configurations.values():
33253325
_FinalizeMSBuildSettings(spec, configuration)
33263326

33273327
# Add attributes to root element

gyp/pylib/gyp/input.py

+24-30
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,8 @@
44

55
from __future__ import print_function
66

7-
from compiler.ast import Const
8-
from compiler.ast import Dict
9-
from compiler.ast import Discard
10-
from compiler.ast import List
11-
from compiler.ast import Module
12-
from compiler.ast import Node
13-
from compiler.ast import Stmt
14-
import compiler
7+
import ast
8+
159
import gyp.common
1610
import gyp.simple_copy
1711
import multiprocessing
@@ -184,43 +178,39 @@ def CheckedEval(file_contents):
184178
Note that this is slower than eval() is.
185179
"""
186180

187-
ast = compiler.parse(file_contents)
188-
assert isinstance(ast, Module)
189-
c1 = ast.getChildren()
190-
assert c1[0] is None
191-
assert isinstance(c1[1], Stmt)
192-
c2 = c1[1].getChildren()
193-
assert isinstance(c2[0], Discard)
194-
c3 = c2[0].getChildren()
195-
assert len(c3) == 1
196-
return CheckNode(c3[0], [])
181+
syntax_tree = ast.parse(file_contents)
182+
assert isinstance(syntax_tree, ast.Module)
183+
c1 = syntax_tree.body
184+
assert len(c1) == 1
185+
c2 = c1[0]
186+
assert isinstance(c2, ast.Expr)
187+
return CheckNode(c2.value, [])
197188

198189

199190
def CheckNode(node, keypath):
200-
if isinstance(node, Dict):
191+
if isinstance(node, ast.Dict):
201192
c = node.getChildren()
202193
dict = {}
203-
for n in range(0, len(c), 2):
204-
assert isinstance(c[n], Const)
205-
key = c[n].getChildren()[0]
194+
for key, value in zip(node.keys, node.values):
195+
assert isinstance(key, ast.Str)
196+
key = key.s
206197
if key in dict:
207198
raise GypError("Key '" + key + "' repeated at level " +
208199
repr(len(keypath) + 1) + " with key path '" +
209200
'.'.join(keypath) + "'")
210201
kp = list(keypath) # Make a copy of the list for descending this node.
211202
kp.append(key)
212-
dict[key] = CheckNode(c[n + 1], kp)
203+
dict[key] = CheckNode(value, kp)
213204
return dict
214-
elif isinstance(node, List):
215-
c = node.getChildren()
205+
elif isinstance(node, ast.List):
216206
children = []
217-
for index, child in enumerate(c):
207+
for index, child in enumerate(node.elts):
218208
kp = list(keypath) # Copy list.
219209
kp.append(repr(index))
220210
children.append(CheckNode(child, kp))
221211
return children
222-
elif isinstance(node, Const):
223-
return node.getChildren()[0]
212+
elif isinstance(node, ast.Str):
213+
return node.s
224214
else:
225215
raise TypeError("Unknown AST node at key path '" + '.'.join(keypath) +
226216
"': " + repr(node))
@@ -954,8 +944,12 @@ def ExpandVariables(input, phase, variables, build_file):
954944
else:
955945
replacement = variables[contents]
956946

947+
if isinstance(replacement, bytes) and not isinstance(replacement, str):
948+
replacement = replacement.decode("utf-8") # done on Python 3 only
957949
if type(replacement) is list:
958950
for item in replacement:
951+
if isinstance(item, bytes) and not isinstance(item, str):
952+
item = item.decode("utf-8") # done on Python 3 only
959953
if not contents[-1] == '/' and type(item) not in (str, int):
960954
raise GypError('Variable ' + contents +
961955
' must expand to a string or list of strings; ' +
@@ -1847,7 +1841,7 @@ def VerifyNoGYPFileCircularDependencies(targets):
18471841
# Create a DependencyGraphNode for each gyp file containing a target. Put
18481842
# it into a dict for easy access.
18491843
dependency_nodes = {}
1850-
for target in targets.iterkeys():
1844+
for target in targets:
18511845
build_file = gyp.common.BuildFile(target)
18521846
if not build_file in dependency_nodes:
18531847
dependency_nodes[build_file] = DependencyGraphNode(build_file)
@@ -1878,7 +1872,7 @@ def VerifyNoGYPFileCircularDependencies(targets):
18781872

18791873
# Files that have no dependencies are treated as dependent on root_node.
18801874
root_node = DependencyGraphNode(None)
1881-
for build_file_node in dependency_nodes.itervalues():
1875+
for build_file_node in dependency_nodes.values():
18821876
if len(build_file_node.dependencies) == 0:
18831877
build_file_node.dependencies.append(root_node)
18841878
root_node.dependents.append(build_file_node)

gyp/pylib/gyp/xcode_emulation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1636,7 +1636,7 @@ def _HasIOSTarget(targets):
16361636
def _AddIOSDeviceConfigurations(targets):
16371637
"""Clone all targets and append -iphoneos to the name. Configure these targets
16381638
to build for iOS devices and use correct architectures for those builds."""
1639-
for target_dict in targets.itervalues():
1639+
for target_dict in targets.values():
16401640
toolset = target_dict['toolset']
16411641
configs = target_dict['configurations']
16421642
for config_name, config_dict in dict(configs).items():

gyp/pylib/gyp/xcode_ninja.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def _TargetFromSpec(old_spec, params):
8585
"%s/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)" % ninja_toplevel
8686

8787
if 'configurations' in old_spec:
88-
for config in old_spec['configurations'].iterkeys():
88+
for config in old_spec['configurations']:
8989
old_xcode_settings = \
9090
old_spec['configurations'][config].get('xcode_settings', {})
9191
if 'IPHONEOS_DEPLOYMENT_TARGET' in old_xcode_settings:

0 commit comments

Comments
 (0)