PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py

https://bitbucket.org/thinker/mozilla-central
Python | 2382 lines | 1847 code | 154 blank | 381 comment | 235 complexity | e63e3625c5a6ef99f4dff4cd0bb6776e MD5 | raw file
Possible License(s): JSON, 0BSD, LGPL-3.0, BSD-2-Clause, MIT, MPL-2.0-no-copyleft-exception, BSD-3-Clause, GPL-2.0, AGPL-1.0, MPL-2.0, Apache-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. # Copyright (c) 2011 Google Inc. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. from compiler.ast import Const
  5. from compiler.ast import Dict
  6. from compiler.ast import Discard
  7. from compiler.ast import List
  8. from compiler.ast import Module
  9. from compiler.ast import Node
  10. from compiler.ast import Stmt
  11. import compiler
  12. import copy
  13. import gyp.common
  14. import optparse
  15. import os.path
  16. import re
  17. import shlex
  18. import subprocess
  19. import sys
  20. # A list of types that are treated as linkable.
  21. linkable_types = ['executable', 'shared_library', 'loadable_module']
  22. # A list of sections that contain links to other targets.
  23. dependency_sections = ['dependencies', 'export_dependent_settings']
  24. # base_path_sections is a list of sections defined by GYP that contain
  25. # pathnames. The generators can provide more keys, the two lists are merged
  26. # into path_sections, but you should call IsPathSection instead of using either
  27. # list directly.
  28. base_path_sections = [
  29. 'destination',
  30. 'files',
  31. 'include_dirs',
  32. 'inputs',
  33. 'libraries',
  34. 'outputs',
  35. 'sources',
  36. ]
  37. path_sections = []
  38. def IsPathSection(section):
  39. # If section ends in one of these characters, it's applied to a section
  40. # without the trailing characters. '/' is notably absent from this list,
  41. # because there's no way for a regular expression to be treated as a path.
  42. while section[-1:] in ('=', '+', '?', '!'):
  43. section = section[0:-1]
  44. if section in path_sections or \
  45. section.endswith('_dir') or section.endswith('_dirs') or \
  46. section.endswith('_file') or section.endswith('_files') or \
  47. section.endswith('_path') or section.endswith('_paths'):
  48. return True
  49. return False
  50. # base_non_configuraiton_keys is a list of key names that belong in the target
  51. # itself and should not be propagated into its configurations. It is merged
  52. # with a list that can come from the generator to
  53. # create non_configuration_keys.
  54. base_non_configuration_keys = [
  55. # Sections that must exist inside targets and not configurations.
  56. 'actions',
  57. 'configurations',
  58. 'copies',
  59. 'default_configuration',
  60. 'dependencies',
  61. 'dependencies_original',
  62. 'link_languages',
  63. 'libraries',
  64. 'postbuilds',
  65. 'product_dir',
  66. 'product_extension',
  67. 'product_name',
  68. 'product_prefix',
  69. 'rules',
  70. 'run_as',
  71. 'sources',
  72. 'suppress_wildcard',
  73. 'target_name',
  74. 'toolset',
  75. 'toolsets',
  76. 'type',
  77. 'variants',
  78. # Sections that can be found inside targets or configurations, but that
  79. # should not be propagated from targets into their configurations.
  80. 'variables',
  81. ]
  82. non_configuration_keys = []
  83. # Keys that do not belong inside a configuration dictionary.
  84. invalid_configuration_keys = [
  85. 'actions',
  86. 'all_dependent_settings',
  87. 'configurations',
  88. 'dependencies',
  89. 'direct_dependent_settings',
  90. 'libraries',
  91. 'link_settings',
  92. 'sources',
  93. 'target_name',
  94. 'type',
  95. ]
  96. # Controls how the generator want the build file paths.
  97. absolute_build_file_paths = False
  98. # Controls whether or not the generator supports multiple toolsets.
  99. multiple_toolsets = False
  100. def GetIncludedBuildFiles(build_file_path, aux_data, included=None):
  101. """Return a list of all build files included into build_file_path.
  102. The returned list will contain build_file_path as well as all other files
  103. that it included, either directly or indirectly. Note that the list may
  104. contain files that were included into a conditional section that evaluated
  105. to false and was not merged into build_file_path's dict.
  106. aux_data is a dict containing a key for each build file or included build
  107. file. Those keys provide access to dicts whose "included" keys contain
  108. lists of all other files included by the build file.
  109. included should be left at its default None value by external callers. It
  110. is used for recursion.
  111. The returned list will not contain any duplicate entries. Each build file
  112. in the list will be relative to the current directory.
  113. """
  114. if included == None:
  115. included = []
  116. if build_file_path in included:
  117. return included
  118. included.append(build_file_path)
  119. for included_build_file in aux_data[build_file_path].get('included', []):
  120. GetIncludedBuildFiles(included_build_file, aux_data, included)
  121. return included
  122. def CheckedEval(file_contents):
  123. """Return the eval of a gyp file.
  124. The gyp file is restricted to dictionaries and lists only, and
  125. repeated keys are not allowed.
  126. Note that this is slower than eval() is.
  127. """
  128. ast = compiler.parse(file_contents)
  129. assert isinstance(ast, Module)
  130. c1 = ast.getChildren()
  131. assert c1[0] is None
  132. assert isinstance(c1[1], Stmt)
  133. c2 = c1[1].getChildren()
  134. assert isinstance(c2[0], Discard)
  135. c3 = c2[0].getChildren()
  136. assert len(c3) == 1
  137. return CheckNode(c3[0], [])
  138. def CheckNode(node, keypath):
  139. if isinstance(node, Dict):
  140. c = node.getChildren()
  141. dict = {}
  142. for n in range(0, len(c), 2):
  143. assert isinstance(c[n], Const)
  144. key = c[n].getChildren()[0]
  145. if key in dict:
  146. raise KeyError, "Key '" + key + "' repeated at level " + \
  147. repr(len(keypath) + 1) + " with key path '" + \
  148. '.'.join(keypath) + "'"
  149. kp = list(keypath) # Make a copy of the list for descending this node.
  150. kp.append(key)
  151. dict[key] = CheckNode(c[n + 1], kp)
  152. return dict
  153. elif isinstance(node, List):
  154. c = node.getChildren()
  155. children = []
  156. for index, child in enumerate(c):
  157. kp = list(keypath) # Copy list.
  158. kp.append(repr(index))
  159. children.append(CheckNode(child, kp))
  160. return children
  161. elif isinstance(node, Const):
  162. return node.getChildren()[0]
  163. else:
  164. raise TypeError, "Unknown AST node at key path '" + '.'.join(keypath) + \
  165. "': " + repr(node)
  166. def LoadOneBuildFile(build_file_path, data, aux_data, variables, includes,
  167. is_target, check):
  168. if build_file_path in data:
  169. return data[build_file_path]
  170. if os.path.exists(build_file_path):
  171. build_file_contents = open(build_file_path).read()
  172. else:
  173. raise Exception("%s not found (cwd: %s)" % (build_file_path, os.getcwd()))
  174. build_file_data = None
  175. try:
  176. if check:
  177. build_file_data = CheckedEval(build_file_contents)
  178. else:
  179. build_file_data = eval(build_file_contents, {'__builtins__': None},
  180. None)
  181. except SyntaxError, e:
  182. e.filename = build_file_path
  183. raise
  184. except Exception, e:
  185. gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path)
  186. raise
  187. data[build_file_path] = build_file_data
  188. aux_data[build_file_path] = {}
  189. # Scan for includes and merge them in.
  190. try:
  191. if is_target:
  192. LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data,
  193. aux_data, variables, includes, check)
  194. else:
  195. LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data,
  196. aux_data, variables, None, check)
  197. except Exception, e:
  198. gyp.common.ExceptionAppend(e,
  199. 'while reading includes of ' + build_file_path)
  200. raise
  201. return build_file_data
  202. def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data,
  203. variables, includes, check):
  204. includes_list = []
  205. if includes != None:
  206. includes_list.extend(includes)
  207. if 'includes' in subdict:
  208. for include in subdict['includes']:
  209. # "include" is specified relative to subdict_path, so compute the real
  210. # path to include by appending the provided "include" to the directory
  211. # in which subdict_path resides.
  212. relative_include = \
  213. os.path.normpath(os.path.join(os.path.dirname(subdict_path), include))
  214. includes_list.append(relative_include)
  215. # Unhook the includes list, it's no longer needed.
  216. del subdict['includes']
  217. # Merge in the included files.
  218. for include in includes_list:
  219. if not 'included' in aux_data[subdict_path]:
  220. aux_data[subdict_path]['included'] = []
  221. aux_data[subdict_path]['included'].append(include)
  222. gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'" % include)
  223. MergeDicts(subdict,
  224. LoadOneBuildFile(include, data, aux_data, variables, None,
  225. False, check),
  226. subdict_path, include)
  227. # Recurse into subdictionaries.
  228. for k, v in subdict.iteritems():
  229. if v.__class__ == dict:
  230. LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, variables,
  231. None, check)
  232. elif v.__class__ == list:
  233. LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, variables,
  234. check)
  235. # This recurses into lists so that it can look for dicts.
  236. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data,
  237. variables, check):
  238. for item in sublist:
  239. if item.__class__ == dict:
  240. LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data,
  241. variables, None, check)
  242. elif item.__class__ == list:
  243. LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data,
  244. variables, check)
  245. # Processes toolsets in all the targets. This recurses into condition entries
  246. # since they can contain toolsets as well.
  247. def ProcessToolsetsInDict(data):
  248. if 'targets' in data:
  249. target_list = data['targets']
  250. new_target_list = []
  251. for target in target_list:
  252. # If this target already has an explicit 'toolset', and no 'toolsets'
  253. # list, don't modify it further.
  254. if 'toolset' in target and 'toolsets' not in target:
  255. new_target_list.append(target)
  256. continue
  257. global multiple_toolsets
  258. if multiple_toolsets:
  259. toolsets = target.get('toolsets', ['target'])
  260. else:
  261. toolsets = ['target']
  262. # Make sure this 'toolsets' definition is only processed once.
  263. if 'toolsets' in target:
  264. del target['toolsets']
  265. if len(toolsets) > 0:
  266. # Optimization: only do copies if more than one toolset is specified.
  267. for build in toolsets[1:]:
  268. new_target = copy.deepcopy(target)
  269. new_target['toolset'] = build
  270. new_target_list.append(new_target)
  271. target['toolset'] = toolsets[0]
  272. new_target_list.append(target)
  273. data['targets'] = new_target_list
  274. if 'conditions' in data:
  275. for condition in data['conditions']:
  276. if isinstance(condition, list):
  277. for condition_dict in condition[1:]:
  278. ProcessToolsetsInDict(condition_dict)
  279. # TODO(mark): I don't love this name. It just means that it's going to load
  280. # a build file that contains targets and is expected to provide a targets dict
  281. # that contains the targets...
  282. def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes,
  283. depth, check):
  284. global absolute_build_file_paths
  285. # If depth is set, predefine the DEPTH variable to be a relative path from
  286. # this build file's directory to the directory identified by depth.
  287. if depth:
  288. # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
  289. # temporary measure. This should really be addressed by keeping all paths
  290. # in POSIX until actual project generation.
  291. d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path))
  292. if d == '':
  293. variables['DEPTH'] = '.'
  294. else:
  295. variables['DEPTH'] = d.replace('\\', '/')
  296. # If the generator needs absolue paths, then do so.
  297. if absolute_build_file_paths:
  298. build_file_path = os.path.abspath(build_file_path)
  299. if build_file_path in data['target_build_files']:
  300. # Already loaded.
  301. return
  302. data['target_build_files'].add(build_file_path)
  303. gyp.DebugOutput(gyp.DEBUG_INCLUDES,
  304. "Loading Target Build File '%s'" % build_file_path)
  305. build_file_data = LoadOneBuildFile(build_file_path, data, aux_data, variables,
  306. includes, True, check)
  307. # Store DEPTH for later use in generators.
  308. build_file_data['_DEPTH'] = depth
  309. # Set up the included_files key indicating which .gyp files contributed to
  310. # this target dict.
  311. if 'included_files' in build_file_data:
  312. raise KeyError, build_file_path + ' must not contain included_files key'
  313. included = GetIncludedBuildFiles(build_file_path, aux_data)
  314. build_file_data['included_files'] = []
  315. for included_file in included:
  316. # included_file is relative to the current directory, but it needs to
  317. # be made relative to build_file_path's directory.
  318. included_relative = \
  319. gyp.common.RelativePath(included_file,
  320. os.path.dirname(build_file_path))
  321. build_file_data['included_files'].append(included_relative)
  322. # Do a first round of toolsets expansion so that conditions can be defined
  323. # per toolset.
  324. ProcessToolsetsInDict(build_file_data)
  325. # Apply "pre"/"early" variable expansions and condition evaluations.
  326. ProcessVariablesAndConditionsInDict(build_file_data, False, variables,
  327. build_file_path)
  328. # Since some toolsets might have been defined conditionally, perform
  329. # a second round of toolsets expansion now.
  330. ProcessToolsetsInDict(build_file_data)
  331. # Look at each project's target_defaults dict, and merge settings into
  332. # targets.
  333. if 'target_defaults' in build_file_data:
  334. index = 0
  335. if 'targets' in build_file_data:
  336. while index < len(build_file_data['targets']):
  337. # This procedure needs to give the impression that target_defaults is
  338. # used as defaults, and the individual targets inherit from that.
  339. # The individual targets need to be merged into the defaults. Make
  340. # a deep copy of the defaults for each target, merge the target dict
  341. # as found in the input file into that copy, and then hook up the
  342. # copy with the target-specific data merged into it as the replacement
  343. # target dict.
  344. old_target_dict = build_file_data['targets'][index]
  345. new_target_dict = copy.deepcopy(build_file_data['target_defaults'])
  346. MergeDicts(new_target_dict, old_target_dict,
  347. build_file_path, build_file_path)
  348. build_file_data['targets'][index] = new_target_dict
  349. index = index + 1
  350. else:
  351. raise Exception, \
  352. "Unable to find targets in build file %s" % build_file_path
  353. # No longer needed.
  354. del build_file_data['target_defaults']
  355. # Look for dependencies. This means that dependency resolution occurs
  356. # after "pre" conditionals and variable expansion, but before "post" -
  357. # in other words, you can't put a "dependencies" section inside a "post"
  358. # conditional within a target.
  359. if 'targets' in build_file_data:
  360. for target_dict in build_file_data['targets']:
  361. if 'dependencies' not in target_dict:
  362. continue
  363. for dependency in target_dict['dependencies']:
  364. other_build_file = \
  365. gyp.common.ResolveTarget(build_file_path, dependency, None)[0]
  366. try:
  367. LoadTargetBuildFile(other_build_file, data, aux_data, variables,
  368. includes, depth, check)
  369. except Exception, e:
  370. gyp.common.ExceptionAppend(
  371. e, 'while loading dependencies of %s' % build_file_path)
  372. raise
  373. return data
  374. # Look for the bracket that matches the first bracket seen in a
  375. # string, and return the start and end as a tuple. For example, if
  376. # the input is something like "<(foo <(bar)) blah", then it would
  377. # return (1, 13), indicating the entire string except for the leading
  378. # "<" and trailing " blah".
  379. def FindEnclosingBracketGroup(input):
  380. brackets = { '}': '{',
  381. ']': '[',
  382. ')': '(', }
  383. stack = []
  384. count = 0
  385. start = -1
  386. for char in input:
  387. if char in brackets.values():
  388. stack.append(char)
  389. if start == -1:
  390. start = count
  391. if char in brackets.keys():
  392. try:
  393. last_bracket = stack.pop()
  394. except IndexError:
  395. return (-1, -1)
  396. if last_bracket != brackets[char]:
  397. return (-1, -1)
  398. if len(stack) == 0:
  399. return (start, count + 1)
  400. count = count + 1
  401. return (-1, -1)
  402. canonical_int_re = re.compile('^(0|-?[1-9][0-9]*)$')
  403. def IsStrCanonicalInt(string):
  404. """Returns True if |string| is in its canonical integer form.
  405. The canonical form is such that str(int(string)) == string.
  406. """
  407. if not isinstance(string, str) or not canonical_int_re.match(string):
  408. return False
  409. return True
  410. # This matches things like "<(asdf)", "<!(cmd)", "<!@(cmd)", "<|(list)",
  411. # "<!interpreter(arguments)", "<([list])", and even "<([)" and "<(<())".
  412. # In the last case, the inner "<()" is captured in match['content'].
  413. early_variable_re = re.compile(
  414. '(?P<replace>(?P<type><(?:(?:!?@?)|\|)?)'
  415. '(?P<command_string>[-a-zA-Z0-9_.]+)?'
  416. '\((?P<is_array>\s*\[?)'
  417. '(?P<content>.*?)(\]?)\))')
  418. # This matches the same as early_variable_re, but with '>' instead of '<'.
  419. late_variable_re = re.compile(
  420. '(?P<replace>(?P<type>>(?:(?:!?@?)|\|)?)'
  421. '(?P<command_string>[-a-zA-Z0-9_.]+)?'
  422. '\((?P<is_array>\s*\[?)'
  423. '(?P<content>.*?)(\]?)\))')
  424. # Global cache of results from running commands so they don't have to be run
  425. # more then once.
  426. cached_command_results = {}
  427. def FixupPlatformCommand(cmd):
  428. if sys.platform == 'win32':
  429. if type(cmd) == list:
  430. cmd = [re.sub('^cat ', 'type ', cmd[0])] + cmd[1:]
  431. else:
  432. cmd = re.sub('^cat ', 'type ', cmd)
  433. return cmd
  434. def ExpandVariables(input, is_late, variables, build_file):
  435. # Look for the pattern that gets expanded into variables
  436. if not is_late:
  437. variable_re = early_variable_re
  438. expansion_symbol = '<'
  439. else:
  440. variable_re = late_variable_re
  441. expansion_symbol = '>'
  442. input_str = str(input)
  443. # Do a quick scan to determine if an expensive regex search is warranted.
  444. if expansion_symbol in input_str:
  445. # Get the entire list of matches as a list of MatchObject instances.
  446. # (using findall here would return strings instead of MatchObjects).
  447. matches = [match for match in variable_re.finditer(input_str)]
  448. else:
  449. matches = None
  450. output = input_str
  451. if matches:
  452. # Reverse the list of matches so that replacements are done right-to-left.
  453. # That ensures that earlier replacements won't mess up the string in a
  454. # way that causes later calls to find the earlier substituted text instead
  455. # of what's intended for replacement.
  456. matches.reverse()
  457. for match_group in matches:
  458. match = match_group.groupdict()
  459. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  460. "Matches: %s" % repr(match))
  461. # match['replace'] is the substring to look for, match['type']
  462. # is the character code for the replacement type (< > <! >! <| >| <@
  463. # >@ <!@ >!@), match['is_array'] contains a '[' for command
  464. # arrays, and match['content'] is the name of the variable (< >)
  465. # or command to run (<! >!). match['command_string'] is an optional
  466. # command string. Currently, only 'pymod_do_main' is supported.
  467. # run_command is true if a ! variant is used.
  468. run_command = '!' in match['type']
  469. command_string = match['command_string']
  470. # file_list is true if a | variant is used.
  471. file_list = '|' in match['type']
  472. # Capture these now so we can adjust them later.
  473. replace_start = match_group.start('replace')
  474. replace_end = match_group.end('replace')
  475. # Find the ending paren, and re-evaluate the contained string.
  476. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:])
  477. # Adjust the replacement range to match the entire command
  478. # found by FindEnclosingBracketGroup (since the variable_re
  479. # probably doesn't match the entire command if it contained
  480. # nested variables).
  481. replace_end = replace_start + c_end
  482. # Find the "real" replacement, matching the appropriate closing
  483. # paren, and adjust the replacement start and end.
  484. replacement = input_str[replace_start:replace_end]
  485. # Figure out what the contents of the variable parens are.
  486. contents_start = replace_start + c_start + 1
  487. contents_end = replace_end - 1
  488. contents = input_str[contents_start:contents_end]
  489. # Do filter substitution now for <|().
  490. # Admittedly, this is different than the evaluation order in other
  491. # contexts. However, since filtration has no chance to run on <|(),
  492. # this seems like the only obvious way to give them access to filters.
  493. if file_list:
  494. processed_variables = copy.deepcopy(variables)
  495. ProcessListFiltersInDict(contents, processed_variables)
  496. # Recurse to expand variables in the contents
  497. contents = ExpandVariables(contents, is_late,
  498. processed_variables, build_file)
  499. else:
  500. # Recurse to expand variables in the contents
  501. contents = ExpandVariables(contents, is_late, variables, build_file)
  502. # Strip off leading/trailing whitespace so that variable matches are
  503. # simpler below (and because they are rarely needed).
  504. contents = contents.strip()
  505. # expand_to_list is true if an @ variant is used. In that case,
  506. # the expansion should result in a list. Note that the caller
  507. # is to be expecting a list in return, and not all callers do
  508. # because not all are working in list context. Also, for list
  509. # expansions, there can be no other text besides the variable
  510. # expansion in the input string.
  511. expand_to_list = '@' in match['type'] and input_str == replacement
  512. if run_command or file_list:
  513. # Find the build file's directory, so commands can be run or file lists
  514. # generated relative to it.
  515. build_file_dir = os.path.dirname(build_file)
  516. if build_file_dir == '':
  517. # If build_file is just a leaf filename indicating a file in the
  518. # current directory, build_file_dir might be an empty string. Set
  519. # it to None to signal to subprocess.Popen that it should run the
  520. # command in the current directory.
  521. build_file_dir = None
  522. # Support <|(listfile.txt ...) which generates a file
  523. # containing items from a gyp list, generated at gyp time.
  524. # This works around actions/rules which have more inputs than will
  525. # fit on the command line.
  526. if file_list:
  527. if type(contents) == list:
  528. contents_list = contents
  529. else:
  530. contents_list = contents.split(' ')
  531. replacement = contents_list[0]
  532. path = replacement
  533. if not os.path.isabs(path):
  534. path = os.path.join(build_file_dir, path)
  535. f = gyp.common.WriteOnDiff(path)
  536. for i in contents_list[1:]:
  537. f.write('%s\n' % i)
  538. f.close()
  539. elif run_command:
  540. use_shell = True
  541. if match['is_array']:
  542. contents = eval(contents)
  543. use_shell = False
  544. # Check for a cached value to avoid executing commands, or generating
  545. # file lists more than once.
  546. # TODO(http://code.google.com/p/gyp/issues/detail?id=112): It is
  547. # possible that the command being invoked depends on the current
  548. # directory. For that case the syntax needs to be extended so that the
  549. # directory is also used in cache_key (it becomes a tuple).
  550. # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory,
  551. # someone could author a set of GYP files where each time the command
  552. # is invoked it produces different output by design. When the need
  553. # arises, the syntax should be extended to support no caching off a
  554. # command's output so it is run every time.
  555. cache_key = str(contents)
  556. cached_value = cached_command_results.get(cache_key, None)
  557. if cached_value is None:
  558. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  559. "Executing command '%s' in directory '%s'" %
  560. (contents,build_file_dir))
  561. replacement = ''
  562. if command_string == 'pymod_do_main':
  563. # <!pymod_do_main(modulename param eters) loads |modulename| as a
  564. # python module and then calls that module's DoMain() function,
  565. # passing ["param", "eters"] as a single list argument. For modules
  566. # that don't load quickly, this can be faster than
  567. # <!(python modulename param eters). Do this in |build_file_dir|.
  568. oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir.
  569. os.chdir(build_file_dir)
  570. parsed_contents = shlex.split(contents)
  571. py_module = __import__(parsed_contents[0])
  572. replacement = str(py_module.DoMain(parsed_contents[1:])).rstrip()
  573. os.chdir(oldwd)
  574. assert replacement != None
  575. elif command_string:
  576. raise Exception("Unknown command string '%s' in '%s'." %
  577. (command_string, contents))
  578. else:
  579. # Fix up command with platform specific workarounds.
  580. contents = FixupPlatformCommand(contents)
  581. p = subprocess.Popen(contents, shell=use_shell,
  582. stdout=subprocess.PIPE,
  583. stderr=subprocess.PIPE,
  584. stdin=subprocess.PIPE,
  585. cwd=build_file_dir)
  586. p_stdout, p_stderr = p.communicate('')
  587. if p.wait() != 0 or p_stderr:
  588. sys.stderr.write(p_stderr)
  589. # Simulate check_call behavior, since check_call only exists
  590. # in python 2.5 and later.
  591. raise Exception("Call to '%s' returned exit status %d." %
  592. (contents, p.returncode))
  593. replacement = p_stdout.rstrip()
  594. cached_command_results[cache_key] = replacement
  595. else:
  596. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  597. "Had cache value for command '%s' in directory '%s'" %
  598. (contents,build_file_dir))
  599. replacement = cached_value
  600. else:
  601. if not contents in variables:
  602. raise KeyError, 'Undefined variable ' + contents + \
  603. ' in ' + build_file
  604. replacement = variables[contents]
  605. if isinstance(replacement, list):
  606. for item in replacement:
  607. if not isinstance(item, str) and not isinstance(item, int):
  608. raise TypeError, 'Variable ' + contents + \
  609. ' must expand to a string or list of strings; ' + \
  610. 'list contains a ' + \
  611. item.__class__.__name__
  612. # Run through the list and handle variable expansions in it. Since
  613. # the list is guaranteed not to contain dicts, this won't do anything
  614. # with conditions sections.
  615. ProcessVariablesAndConditionsInList(replacement, is_late, variables,
  616. build_file)
  617. elif not isinstance(replacement, str) and \
  618. not isinstance(replacement, int):
  619. raise TypeError, 'Variable ' + contents + \
  620. ' must expand to a string or list of strings; ' + \
  621. 'found a ' + replacement.__class__.__name__
  622. if expand_to_list:
  623. # Expanding in list context. It's guaranteed that there's only one
  624. # replacement to do in |input_str| and that it's this replacement. See
  625. # above.
  626. if isinstance(replacement, list):
  627. # If it's already a list, make a copy.
  628. output = replacement[:]
  629. else:
  630. # Split it the same way sh would split arguments.
  631. output = shlex.split(str(replacement))
  632. else:
  633. # Expanding in string context.
  634. encoded_replacement = ''
  635. if isinstance(replacement, list):
  636. # When expanding a list into string context, turn the list items
  637. # into a string in a way that will work with a subprocess call.
  638. #
  639. # TODO(mark): This isn't completely correct. This should
  640. # call a generator-provided function that observes the
  641. # proper list-to-argument quoting rules on a specific
  642. # platform instead of just calling the POSIX encoding
  643. # routine.
  644. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement)
  645. else:
  646. encoded_replacement = replacement
  647. output = output[:replace_start] + str(encoded_replacement) + \
  648. output[replace_end:]
  649. # Prepare for the next match iteration.
  650. input_str = output
  651. # Look for more matches now that we've replaced some, to deal with
  652. # expanding local variables (variables defined in the same
  653. # variables block as this one).
  654. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  655. "Found output %s, recursing." % repr(output))
  656. if isinstance(output, list):
  657. new_output = []
  658. for item in output:
  659. new_output.append(ExpandVariables(item, is_late, variables, build_file))
  660. output = new_output
  661. else:
  662. output = ExpandVariables(output, is_late, variables, build_file)
  663. # Convert all strings that are canonically-represented integers into integers.
  664. if isinstance(output, list):
  665. for index in xrange(0, len(output)):
  666. if IsStrCanonicalInt(output[index]):
  667. output[index] = int(output[index])
  668. elif IsStrCanonicalInt(output):
  669. output = int(output)
  670. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  671. "Expanding %s to %s" % (repr(input), repr(output)))
  672. return output
  673. def ProcessConditionsInDict(the_dict, is_late, variables, build_file):
  674. # Process a 'conditions' or 'target_conditions' section in the_dict,
  675. # depending on is_late. If is_late is False, 'conditions' is used.
  676. #
  677. # Each item in a conditions list consists of cond_expr, a string expression
  678. # evaluated as the condition, and true_dict, a dict that will be merged into
  679. # the_dict if cond_expr evaluates to true. Optionally, a third item,
  680. # false_dict, may be present. false_dict is merged into the_dict if
  681. # cond_expr evaluates to false.
  682. #
  683. # Any dict merged into the_dict will be recursively processed for nested
  684. # conditionals and other expansions, also according to is_late, immediately
  685. # prior to being merged.
  686. if not is_late:
  687. conditions_key = 'conditions'
  688. else:
  689. conditions_key = 'target_conditions'
  690. if not conditions_key in the_dict:
  691. return
  692. conditions_list = the_dict[conditions_key]
  693. # Unhook the conditions list, it's no longer needed.
  694. del the_dict[conditions_key]
  695. for condition in conditions_list:
  696. if not isinstance(condition, list):
  697. raise TypeError, conditions_key + ' must be a list'
  698. if len(condition) != 2 and len(condition) != 3:
  699. # It's possible that condition[0] won't work in which case this
  700. # attempt will raise its own IndexError. That's probably fine.
  701. raise IndexError, conditions_key + ' ' + condition[0] + \
  702. ' must be length 2 or 3, not ' + str(len(condition))
  703. [cond_expr, true_dict] = condition[0:2]
  704. false_dict = None
  705. if len(condition) == 3:
  706. false_dict = condition[2]
  707. # Do expansions on the condition itself. Since the conditon can naturally
  708. # contain variable references without needing to resort to GYP expansion
  709. # syntax, this is of dubious value for variables, but someone might want to
  710. # use a command expansion directly inside a condition.
  711. cond_expr_expanded = ExpandVariables(cond_expr, is_late, variables,
  712. build_file)
  713. if not isinstance(cond_expr_expanded, str) and \
  714. not isinstance(cond_expr_expanded, int):
  715. raise ValueError, \
  716. 'Variable expansion in this context permits str and int ' + \
  717. 'only, found ' + expanded.__class__.__name__
  718. try:
  719. ast_code = compile(cond_expr_expanded, '<string>', 'eval')
  720. if eval(ast_code, {'__builtins__': None}, variables):
  721. merge_dict = true_dict
  722. else:
  723. merge_dict = false_dict
  724. except SyntaxError, e:
  725. syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s '
  726. 'at character %d.' %
  727. (str(e.args[0]), e.text, build_file, e.offset),
  728. e.filename, e.lineno, e.offset, e.text)
  729. raise syntax_error
  730. except NameError, e:
  731. gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' %
  732. (cond_expr_expanded, build_file))
  733. raise
  734. if merge_dict != None:
  735. # Expand variables and nested conditinals in the merge_dict before
  736. # merging it.
  737. ProcessVariablesAndConditionsInDict(merge_dict, is_late,
  738. variables, build_file)
  739. MergeDicts(the_dict, merge_dict, build_file, build_file)
  740. def LoadAutomaticVariablesFromDict(variables, the_dict):
  741. # Any keys with plain string values in the_dict become automatic variables.
  742. # The variable name is the key name with a "_" character prepended.
  743. for key, value in the_dict.iteritems():
  744. if isinstance(value, str) or isinstance(value, int) or \
  745. isinstance(value, list):
  746. variables['_' + key] = value
  747. def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key):
  748. # Any keys in the_dict's "variables" dict, if it has one, becomes a
  749. # variable. The variable name is the key name in the "variables" dict.
  750. # Variables that end with the % character are set only if they are unset in
  751. # the variables dict. the_dict_key is the name of the key that accesses
  752. # the_dict in the_dict's parent dict. If the_dict's parent is not a dict
  753. # (it could be a list or it could be parentless because it is a root dict),
  754. # the_dict_key will be None.
  755. for key, value in the_dict.get('variables', {}).iteritems():
  756. if not isinstance(value, str) and not isinstance(value, int) and \
  757. not isinstance(value, list):
  758. continue
  759. if key.endswith('%'):
  760. variable_name = key[:-1]
  761. if variable_name in variables:
  762. # If the variable is already set, don't set it.
  763. continue
  764. if the_dict_key is 'variables' and variable_name in the_dict:
  765. # If the variable is set without a % in the_dict, and the_dict is a
  766. # variables dict (making |variables| a varaibles sub-dict of a
  767. # variables dict), use the_dict's definition.
  768. value = the_dict[variable_name]
  769. else:
  770. variable_name = key
  771. variables[variable_name] = value
  772. def ProcessVariablesAndConditionsInDict(the_dict, is_late, variables_in,
  773. build_file, the_dict_key=None):
  774. """Handle all variable and command expansion and conditional evaluation.
  775. This function is the public entry point for all variable expansions and
  776. conditional evaluations. The variables_in dictionary will not be modified
  777. by this function.
  778. """
  779. # Make a copy of the variables_in dict that can be modified during the
  780. # loading of automatics and the loading of the variables dict.
  781. variables = variables_in.copy()
  782. LoadAutomaticVariablesFromDict(variables, the_dict)
  783. if 'variables' in the_dict:
  784. # Make sure all the local variables are added to the variables
  785. # list before we process them so that you can reference one
  786. # variable from another. They will be fully expanded by recursion
  787. # in ExpandVariables.
  788. for key, value in the_dict['variables'].iteritems():
  789. variables[key] = value
  790. # Handle the associated variables dict first, so that any variable
  791. # references within can be resolved prior to using them as variables.
  792. # Pass a copy of the variables dict to avoid having it be tainted.
  793. # Otherwise, it would have extra automatics added for everything that
  794. # should just be an ordinary variable in this scope.
  795. ProcessVariablesAndConditionsInDict(the_dict['variables'], is_late,
  796. variables, build_file, 'variables')
  797. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  798. for key, value in the_dict.iteritems():
  799. # Skip "variables", which was already processed if present.
  800. if key != 'variables' and isinstance(value, str):
  801. expanded = ExpandVariables(value, is_late, variables, build_file)
  802. if not isinstance(expanded, str) and not isinstance(expanded, int):
  803. raise ValueError, \
  804. 'Variable expansion in this context permits str and int ' + \
  805. 'only, found ' + expanded.__class__.__name__ + ' for ' + key
  806. the_dict[key] = expanded
  807. # Variable expansion may have resulted in changes to automatics. Reload.
  808. # TODO(mark): Optimization: only reload if no changes were made.
  809. variables = variables_in.copy()
  810. LoadAutomaticVariablesFromDict(variables, the_dict)
  811. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  812. # Process conditions in this dict. This is done after variable expansion
  813. # so that conditions may take advantage of expanded variables. For example,
  814. # if the_dict contains:
  815. # {'type': '<(library_type)',
  816. # 'conditions': [['_type=="static_library"', { ... }]]},
  817. # _type, as used in the condition, will only be set to the value of
  818. # library_type if variable expansion is performed before condition
  819. # processing. However, condition processing should occur prior to recursion
  820. # so that variables (both automatic and "variables" dict type) may be
  821. # adjusted by conditions sections, merged into the_dict, and have the
  822. # intended impact on contained dicts.
  823. #
  824. # This arrangement means that a "conditions" section containing a "variables"
  825. # section will only have those variables effective in subdicts, not in
  826. # the_dict. The workaround is to put a "conditions" section within a
  827. # "variables" section. For example:
  828. # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]],
  829. # 'defines': ['<(define)'],
  830. # 'my_subdict': {'defines': ['<(define)']}},
  831. # will not result in "IS_MAC" being appended to the "defines" list in the
  832. # current scope but would result in it being appended to the "defines" list
  833. # within "my_subdict". By comparison:
  834. # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]},
  835. # 'defines': ['<(define)'],
  836. # 'my_subdict': {'defines': ['<(define)']}},
  837. # will append "IS_MAC" to both "defines" lists.
  838. # Evaluate conditions sections, allowing variable expansions within them
  839. # as well as nested conditionals. This will process a 'conditions' or
  840. # 'target_conditions' section, perform appropriate merging and recursive
  841. # conditional and variable processing, and then remove the conditions section
  842. # from the_dict if it is present.
  843. ProcessConditionsInDict(the_dict, is_late, variables, build_file)
  844. # Conditional processing may have resulted in changes to automatics or the
  845. # variables dict. Reload.
  846. variables = variables_in.copy()
  847. LoadAutomaticVariablesFromDict(variables, the_dict)
  848. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  849. # Recurse into child dicts, or process child lists which may result in
  850. # further recursion into descendant dicts.
  851. for key, value in the_dict.iteritems():
  852. # Skip "variables" and string values, which were already processed if
  853. # present.
  854. if key == 'variables' or isinstance(value, str):
  855. continue
  856. if isinstance(value, dict):
  857. # Pass a copy of the variables dict so that subdicts can't influence
  858. # parents.
  859. ProcessVariablesAndConditionsInDict(value, is_late, variables,
  860. build_file, key)
  861. elif isinstance(value, list):
  862. # The list itself can't influence the variables dict, and
  863. # ProcessVariablesAndConditionsInList will make copies of the variables
  864. # dict if it needs to pass it to something that can influence it. No
  865. # copy is necessary here.
  866. ProcessVariablesAndConditionsInList(value, is_late, variables,
  867. build_file)
  868. elif not isinstance(value, int):
  869. raise TypeError, 'Unknown type ' + value.__class__.__name__ + \
  870. ' for ' + key
  871. def ProcessVariablesAndConditionsInList(the_list, is_late, variables,
  872. build_file):
  873. # Iterate using an index so that new values can be assigned into the_list.
  874. index = 0
  875. while index < len(the_list):
  876. item = the_list[index]
  877. if isinstance(item, dict):
  878. # Make a copy of the variables dict so that it won't influence anything
  879. # outside of its own scope.
  880. ProcessVariablesAndConditionsInDict(item, is_late, variables, build_file)
  881. elif isinstance(item, list):
  882. ProcessVariablesAndConditionsInList(item, is_late, variables, build_file)
  883. elif isinstance(item, str):
  884. expanded = ExpandVariables(item, is_late, variables, build_file)
  885. if isinstance(expanded, str) or isinstance(expanded, int):
  886. the_list[index] = expanded
  887. elif isinstance(expanded, list):
  888. del the_list[index]
  889. for expanded_item in expanded:
  890. the_list.insert(index, expanded_item)
  891. index = index + 1
  892. # index now identifies the next item to examine. Continue right now
  893. # without falling into the index increment below.
  894. continue
  895. else:
  896. raise ValueError, \
  897. 'Variable expansion in this context permits strings and ' + \
  898. 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \
  899. index
  900. elif not isinstance(item, int):
  901. raise TypeError, 'Unknown type ' + item.__class__.__name__ + \
  902. ' at index ' + index
  903. index = index + 1
  904. def BuildTargetsDict(data):
  905. """Builds a dict mapping fully-qualified target names to their target dicts.
  906. |data| is a dict mapping loaded build files by pathname relative to the
  907. current directory. Values in |data| are build file contents. For each
  908. |data| value with a "targets" key, the value of the "targets" key is taken
  909. as a list containing target dicts. Each target's fully-qualified name is
  910. constructed from the pathname of the build file (|data| key) and its
  911. "target_name" property. These fully-qualified names are used as the keys
  912. in the returned dict. These keys provide access to the target dicts,
  913. the dicts in the "targets" lists.
  914. """
  915. targets = {}
  916. for build_file in data['target_build_files']:
  917. for target in data[build_file].get('targets', []):
  918. target_name = gyp.common.QualifiedTarget(build_file,
  919. target['target_name'],
  920. target['toolset'])
  921. if target_name in targets:
  922. raise KeyError, 'Duplicate target definitions for ' + target_name
  923. targets[target_name] = target
  924. return targets
  925. def QualifyDependencies(targets):
  926. """Make dependency links fully-qualified relative to the current directory.
  927. |targets| is a dict mapping fully-qualified target names to their target
  928. dicts. For each target in this dict, keys known to contain dependency
  929. links are examined, and any dependencies referenced will be rewritten
  930. so that they are fully-qualified and relative to the current directory.
  931. All rewritten dependencies are suitable for use as keys to |targets| or a
  932. similar dict.
  933. """
  934. all_dependency_sections = [dep + op
  935. for dep in dependency_sections
  936. for op in ('', '!', '/')]
  937. for target, target_dict in targets.iteritems():
  938. target_build_file = gyp.common.BuildFile(target)
  939. toolset = target_dict['toolset']
  940. for dependency_key in all_dependency_sections:
  941. dependencies = target_dict.get(dependency_key, [])
  942. for index in xrange(0, len(dependencies)):
  943. dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget(
  944. target_build_file, dependencies[index], toolset)
  945. global multiple_toolsets
  946. if not multiple_toolsets:
  947. # Ignore toolset specification in the dependency if it is specified.
  948. dep_toolset = toolset
  949. dependency = gyp.common.QualifiedTarget(dep_file,
  950. dep_target,
  951. dep_toolset)
  952. dependencies[index] = dependency
  953. # Make sure anything appearing in a list other than "dependencies" also
  954. # appears in the "dependencies" list.
  955. if dependency_key != 'dependencies' and \
  956. dependency not in target_dict['dependencies']:
  957. raise KeyError, 'Found ' + dependency + ' in ' + dependency_key + \
  958. ' of ' + target + ', but not in dependencies'
  959. def ExpandWildcardDependencies(targets, data):
  960. """Expands dependencies specified as build_file:*.
  961. For each target in |targets|, examines sections containing links to other
  962. targets. If any such section contains a link of the form build_file:*, it
  963. is taken as a wildcard link, and is expanded to list each target in
  964. build_file. The |data| dict provides access to build file dicts.
  965. Any target that does not wish to be included by wildcard can provide an
  966. optional "suppress_wildcard" key in its target dict. When present and
  967. true, a wildcard dependency link will not include such targets.
  968. All dependency names, including the keys to |targets| and the values in each
  969. dependency list, must be qualified when this function is called.
  970. """
  971. for target, target_dict in targets.iteritems():
  972. toolset = target_dict['toolset']
  973. target_build_file = gyp.common.BuildFile(target)
  974. for dependency_key in dependency_sections:
  975. dependencies = target_dict.get(dependency_key, [])
  976. # Loop this way instead of "for dependency in" or "for index in xrange"
  977. # because the dependencies list will be modified within the loop body.
  978. index = 0
  979. while index < len(dependencies):
  980. (dependency_build_file, dependency_target, dependency_toolset) = \
  981. gyp.common.ParseQualifiedTarget(dependencies[index])
  982. if dependency_target != '*' and dependency_toolset != '*':
  983. # Not a wildcard. Keep it moving.
  984. index = index + 1
  985. continue
  986. if dependency_build_file == target_build_file:
  987. # It's an error for a target to depend on all other targets in
  988. # the same file, because a target cannot depend on itself.
  989. raise KeyError, 'Found wildcard in ' + dependency_key + ' of ' + \
  990. target + ' referring to same build file'
  991. # Take the wildcard out and adjust the index so that the next
  992. # dependency in the list will be processed the next time through the
  993. # loop.
  994. del dependencies[index]
  995. index = index - 1
  996. # Loop through the targets in the other build file, adding them to
  997. # this target's list of dependencies in place of the removed
  998. # wildcard.
  999. dependency_target_dicts = data[dependency_build_file]['targets']
  1000. for dependency_target_dict in dependency_target_dicts:
  1001. if int(dependency_target_dict.get('suppress_wildcard', False)):
  1002. continue
  1003. dependency_target_name = dependency_target_dict['target_name']
  1004. if (dependency_target != '*' and
  1005. dependency_target != dependency_target_name):
  1006. continue
  1007. dependency_target_toolset = dependency_target_dict['toolset']
  1008. if (dependency_toolset != '*' and
  1009. dependency_toolset != dependency_target_toolset):
  1010. continue
  1011. dependency = gyp.common.QualifiedTarget(dependency_build_file,
  1012. dependency_target_name,
  1013. dependency_target_toolset)
  1014. index = index + 1
  1015. dependencies.insert(index, dependency)
  1016. index = index + 1
  1017. class DependencyGraphNode(object):
  1018. """
  1019. Attributes:
  1020. ref: A reference to an object that this DependencyGraphNode represents.
  1021. dependencies: List of DependencyGraphNodes on which this one depends.
  1022. dependents: List of DependencyGraphNodes that depend on this one.
  1023. """
  1024. class CircularException(Exception):
  1025. pass
  1026. def __init__(self, ref):
  1027. self.ref = ref
  1028. self.dependencies = []
  1029. self.dependents = []
  1030. def FlattenToList(self):
  1031. # flat_list is the sorted list of dependencies - actually, the list items
  1032. # are the "ref" attributes of DependencyGraphNodes. Every target will
  1033. # appear in flat_list after all of its dependencies, and before all of its
  1034. # dependents.
  1035. flat_list = []
  1036. # in_degree_zeros is the list of DependencyGraphNodes that have no
  1037. # dependencies not in flat_list. Initially, it is a copy of the children
  1038. # of this node, because when the graph was built, nodes with no
  1039. # dependencies were made implicit dependents of the root node.
  1040. in_degree_zeros = self.dependents[:]
  1041. while in_degree_zeros:
  1042. # Nodes in in_degree_zeros have no dependencies not in flat_list, so they
  1043. # can be appended to flat_list. Take these nodes out of in_degree_zeros
  1044. # as work progresses, so that the next node to process from the list can
  1045. # always be accessed at a consistent position.
  1046. node = in_degree_zeros.pop(0)
  1047. flat_list.append(node.ref)
  1048. # Look at dependents of the node just added to flat_list. Some of them
  1049. # may now belong in in_degree_zeros.
  1050. for node_dependent in node.dependents:
  1051. is_in_degree_zero = True
  1052. for node_dependent_dependency in node_dependent.dependencies:
  1053. if not node_dependent_dependency.ref in flat_list:
  1054. # The dependent one or more dependencies not in

Large files files are truncated, but you can click here to view the full file