PageRenderTime 216ms CodeModel.GetById 34ms RepoModel.GetById 2ms app.codeStats 0ms

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

https://bitbucket.org/halwine/releases-mozilla-inbound
Python | 2382 lines | 1847 code | 154 blank | 381 comment | 235 complexity | e63e3625c5a6ef99f4dff4cd0bb6776e MD5 | raw file
Possible License(s): AGPL-1.0, JSON, 0BSD, BSD-2-Clause, GPL-2.0, Apache-2.0, LGPL-2.1, LGPL-3.0, MIT, MPL-2.0-no-copyleft-exception, MPL-2.0, BSD-3-Clause
  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 flat_list. There
  1055. # will be more chances to add it to flat_list when examining
  1056. # it again as a dependent of those other dependencies, provided
  1057. # that there are no cycles.
  1058. is_in_degree_zero = False
  1059. break
  1060. if is_in_degree_zero:
  1061. # All of the dependent's dependencies are already in flat_list. Add
  1062. # it to in_degree_zeros where it will be processed in a future
  1063. # iteration of the outer loop.
  1064. in_degree_zeros.append(node_dependent)
  1065. return flat_list
  1066. def DirectDependencies(self, dependencies=None):
  1067. """Returns a list of just direct dependencies."""
  1068. if dependencies == None:
  1069. dependencies = []
  1070. for dependency in self.dependencies:
  1071. # Check for None, corresponding to the root node.
  1072. if dependency.ref != None and dependency.ref not in dependencies:
  1073. dependencies.append(dependency.ref)
  1074. return dependencies
  1075. def _AddImportedDependencies(self, targets, dependencies=None):
  1076. """Given a list of direct dependencies, adds indirect dependencies that
  1077. other dependencies have declared to export their settings.
  1078. This method does not operate on self. Rather, it operates on the list
  1079. of dependencies in the |dependencies| argument. For each dependency in
  1080. that list, if any declares that it exports the settings of one of its
  1081. own dependencies, those dependencies whose settings are "passed through"
  1082. are added to the list. As new items are added to the list, they too will
  1083. be processed, so it is possible to import settings through multiple levels
  1084. of dependencies.
  1085. This method is not terribly useful on its own, it depends on being
  1086. "primed" with a list of direct dependencies such as one provided by
  1087. DirectDependencies. DirectAndImportedDependencies is intended to be the
  1088. public entry point.
  1089. """
  1090. if dependencies == None:
  1091. dependencies = []
  1092. index = 0
  1093. while index < len(dependencies):
  1094. dependency = dependencies[index]
  1095. dependency_dict = targets[dependency]
  1096. # Add any dependencies whose settings should be imported to the list
  1097. # if not already present. Newly-added items will be checked for
  1098. # their own imports when the list iteration reaches them.
  1099. # Rather than simply appending new items, insert them after the
  1100. # dependency that exported them. This is done to more closely match
  1101. # the depth-first method used by DeepDependencies.
  1102. add_index = 1
  1103. for imported_dependency in \
  1104. dependency_dict.get('export_dependent_settings', []):
  1105. if imported_dependency not in dependencies:
  1106. dependencies.insert(index + add_index, imported_dependency)
  1107. add_index = add_index + 1
  1108. index = index + 1
  1109. return dependencies
  1110. def DirectAndImportedDependencies(self, targets, dependencies=None):
  1111. """Returns a list of a target's direct dependencies and all indirect
  1112. dependencies that a dependency has advertised settings should be exported
  1113. through the dependency for.
  1114. """
  1115. dependencies = self.DirectDependencies(dependencies)
  1116. return self._AddImportedDependencies(targets, dependencies)
  1117. def DeepDependencies(self, dependencies=None):
  1118. """Returns a list of all of a target's dependencies, recursively."""
  1119. if dependencies == None:
  1120. dependencies = []
  1121. for dependency in self.dependencies:
  1122. # Check for None, corresponding to the root node.
  1123. if dependency.ref != None and dependency.ref not in dependencies:
  1124. dependencies.append(dependency.ref)
  1125. dependency.DeepDependencies(dependencies)
  1126. return dependencies
  1127. def LinkDependencies(self, targets, dependencies=None, initial=True):
  1128. """Returns a list of dependency targets that are linked into this target.
  1129. This function has a split personality, depending on the setting of
  1130. |initial|. Outside callers should always leave |initial| at its default
  1131. setting.
  1132. When adding a target to the list of dependencies, this function will
  1133. recurse into itself with |initial| set to False, to collect dependencies
  1134. that are linked into the linkable target for which the list is being built.
  1135. """
  1136. if dependencies == None:
  1137. dependencies = []
  1138. # Check for None, corresponding to the root node.
  1139. if self.ref == None:
  1140. return dependencies
  1141. # It's kind of sucky that |targets| has to be passed into this function,
  1142. # but that's presently the easiest way to access the target dicts so that
  1143. # this function can find target types.
  1144. if not 'target_name' in targets[self.ref]:
  1145. raise Exception("Missing 'target_name' field in target.")
  1146. try:
  1147. target_type = targets[self.ref]['type']
  1148. except KeyError, e:
  1149. raise Exception("Missing 'type' field in target %s" %
  1150. targets[self.ref]['target_name'])
  1151. is_linkable = target_type in linkable_types
  1152. if initial and not is_linkable:
  1153. # If this is the first target being examined and it's not linkable,
  1154. # return an empty list of link dependencies, because the link
  1155. # dependencies are intended to apply to the target itself (initial is
  1156. # True) and this target won't be linked.
  1157. return dependencies
  1158. # Don't traverse 'none' targets if explicitly excluded.
  1159. if (target_type == 'none' and
  1160. not targets[self.ref].get('dependencies_traverse', True)):
  1161. if self.ref not in dependencies:
  1162. dependencies.append(self.ref)
  1163. return dependencies
  1164. # Executables and loadable modules are already fully and finally linked.
  1165. # Nothing else can be a link dependency of them, there can only be
  1166. # dependencies in the sense that a dependent target might run an
  1167. # executable or load the loadable_module.
  1168. if not initial and target_type in ('executable', 'loadable_module'):
  1169. return dependencies
  1170. # The target is linkable, add it to the list of link dependencies.
  1171. if self.ref not in dependencies:
  1172. dependencies.append(self.ref)
  1173. if initial or not is_linkable:
  1174. # If this is a subsequent target and it's linkable, don't look any
  1175. # further for linkable dependencies, as they'll already be linked into
  1176. # this target linkable. Always look at dependencies of the initial
  1177. # target, and always look at dependencies of non-linkables.
  1178. for dependency in self.dependencies:
  1179. dependency.LinkDependencies(targets, dependencies, False)
  1180. return dependencies
  1181. def BuildDependencyList(targets):
  1182. # Create a DependencyGraphNode for each target. Put it into a dict for easy
  1183. # access.
  1184. dependency_nodes = {}
  1185. for target, spec in targets.iteritems():
  1186. if not target in dependency_nodes:
  1187. dependency_nodes[target] = DependencyGraphNode(target)
  1188. # Set up the dependency links. Targets that have no dependencies are treated
  1189. # as dependent on root_node.
  1190. root_node = DependencyGraphNode(None)
  1191. for target, spec in targets.iteritems():
  1192. target_node = dependency_nodes[target]
  1193. target_build_file = gyp.common.BuildFile(target)
  1194. if not 'dependencies' in spec or len(spec['dependencies']) == 0:
  1195. target_node.dependencies = [root_node]
  1196. root_node.dependents.append(target_node)
  1197. else:
  1198. dependencies = spec['dependencies']
  1199. for index in xrange(0, len(dependencies)):
  1200. try:
  1201. dependency = dependencies[index]
  1202. dependency_node = dependency_nodes[dependency]
  1203. target_node.dependencies.append(dependency_node)
  1204. dependency_node.dependents.append(target_node)
  1205. except KeyError, e:
  1206. gyp.common.ExceptionAppend(e,
  1207. 'while trying to load target %s' % target)
  1208. raise
  1209. flat_list = root_node.FlattenToList()
  1210. # If there's anything left unvisited, there must be a circular dependency
  1211. # (cycle). If you need to figure out what's wrong, look for elements of
  1212. # targets that are not in flat_list.
  1213. if len(flat_list) != len(targets):
  1214. raise DependencyGraphNode.CircularException, \
  1215. 'Some targets not reachable, cycle in dependency graph detected'
  1216. return [dependency_nodes, flat_list]
  1217. def VerifyNoGYPFileCircularDependencies(targets):
  1218. # Create a DependencyGraphNode for each gyp file containing a target. Put
  1219. # it into a dict for easy access.
  1220. dependency_nodes = {}
  1221. for target in targets.iterkeys():
  1222. build_file = gyp.common.BuildFile(target)
  1223. if not build_file in dependency_nodes:
  1224. dependency_nodes[build_file] = DependencyGraphNode(build_file)
  1225. # Set up the dependency links.
  1226. for target, spec in targets.iteritems():
  1227. build_file = gyp.common.BuildFile(target)
  1228. build_file_node = dependency_nodes[build_file]
  1229. target_dependencies = spec.get('dependencies', [])
  1230. for dependency in target_dependencies:
  1231. try:
  1232. dependency_build_file = gyp.common.BuildFile(dependency)
  1233. if dependency_build_file == build_file:
  1234. # A .gyp file is allowed to refer back to itself.
  1235. continue
  1236. dependency_node = dependency_nodes[dependency_build_file]
  1237. if dependency_node not in build_file_node.dependencies:
  1238. build_file_node.dependencies.append(dependency_node)
  1239. dependency_node.dependents.append(build_file_node)
  1240. except KeyError, e:
  1241. gyp.common.ExceptionAppend(
  1242. e, 'while computing dependencies of .gyp file %s' % build_file)
  1243. raise
  1244. # Files that have no dependencies are treated as dependent on root_node.
  1245. root_node = DependencyGraphNode(None)
  1246. for build_file_node in dependency_nodes.itervalues():
  1247. if len(build_file_node.dependencies) == 0:
  1248. build_file_node.dependencies.append(root_node)
  1249. root_node.dependents.append(build_file_node)
  1250. flat_list = root_node.FlattenToList()
  1251. # If there's anything left unvisited, there must be a circular dependency
  1252. # (cycle).
  1253. if len(flat_list) != len(dependency_nodes):
  1254. bad_files = []
  1255. for file in dependency_nodes.iterkeys():
  1256. if not file in flat_list:
  1257. bad_files.append(file)
  1258. raise DependencyGraphNode.CircularException, \
  1259. 'Some files not reachable, cycle in .gyp file dependency graph ' + \
  1260. 'detected involving some or all of: ' + \
  1261. ' '.join(bad_files)
  1262. def DoDependentSettings(key, flat_list, targets, dependency_nodes):
  1263. # key should be one of all_dependent_settings, direct_dependent_settings,
  1264. # or link_settings.
  1265. for target in flat_list:
  1266. target_dict = targets[target]
  1267. build_file = gyp.common.BuildFile(target)
  1268. if key == 'all_dependent_settings':
  1269. dependencies = dependency_nodes[target].DeepDependencies()
  1270. elif key == 'direct_dependent_settings':
  1271. dependencies = \
  1272. dependency_nodes[target].DirectAndImportedDependencies(targets)
  1273. elif key == 'link_settings':
  1274. dependencies = dependency_nodes[target].LinkDependencies(targets)
  1275. else:
  1276. raise KeyError, "DoDependentSettings doesn't know how to determine " + \
  1277. 'dependencies for ' + key
  1278. for dependency in dependencies:
  1279. dependency_dict = targets[dependency]
  1280. if not key in dependency_dict:
  1281. continue
  1282. dependency_build_file = gyp.common.BuildFile(dependency)
  1283. MergeDicts(target_dict, dependency_dict[key],
  1284. build_file, dependency_build_file)
  1285. def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes,
  1286. sort_dependencies):
  1287. # Recompute target "dependencies" properties. For each static library
  1288. # target, remove "dependencies" entries referring to other static libraries,
  1289. # unless the dependency has the "hard_dependency" attribute set. For each
  1290. # linkable target, add a "dependencies" entry referring to all of the
  1291. # target's computed list of link dependencies (including static libraries
  1292. # if no such entry is already present.
  1293. for target in flat_list:
  1294. target_dict = targets[target]
  1295. target_type = target_dict['type']
  1296. if target_type == 'static_library':
  1297. if not 'dependencies' in target_dict:
  1298. continue
  1299. target_dict['dependencies_original'] = target_dict.get(
  1300. 'dependencies', [])[:]
  1301. # A static library should not depend on another static library unless
  1302. # the dependency relationship is "hard," which should only be done when
  1303. # a dependent relies on some side effect other than just the build
  1304. # product, like a rule or action output. Further, if a target has a
  1305. # non-hard dependency, but that dependency exports a hard dependency,
  1306. # the non-hard dependency can safely be removed, but the exported hard
  1307. # dependency must be added to the target to keep the same dependency
  1308. # ordering.
  1309. dependencies = \
  1310. dependency_nodes[target].DirectAndImportedDependencies(targets)
  1311. index = 0
  1312. while index < len(dependencies):
  1313. dependency = dependencies[index]
  1314. dependency_dict = targets[dependency]
  1315. # Remove every non-hard static library dependency and remove every
  1316. # non-static library dependency that isn't a direct dependency.
  1317. if (dependency_dict['type'] == 'static_library' and \
  1318. not dependency_dict.get('hard_dependency', False)) or \
  1319. (dependency_dict['type'] != 'static_library' and \
  1320. not dependency in target_dict['dependencies']):
  1321. # Take the dependency out of the list, and don't increment index
  1322. # because the next dependency to analyze will shift into the index
  1323. # formerly occupied by the one being removed.
  1324. del dependencies[index]
  1325. else:
  1326. index = index + 1
  1327. # Update the dependencies. If the dependencies list is empty, it's not
  1328. # needed, so unhook it.
  1329. if len(dependencies) > 0:
  1330. target_dict['dependencies'] = dependencies
  1331. else:
  1332. del target_dict['dependencies']
  1333. elif target_type in linkable_types:
  1334. # Get a list of dependency targets that should be linked into this
  1335. # target. Add them to the dependencies list if they're not already
  1336. # present.
  1337. link_dependencies = dependency_nodes[target].LinkDependencies(targets)
  1338. for dependency in link_dependencies:
  1339. if dependency == target:
  1340. continue
  1341. if not 'dependencies' in target_dict:
  1342. target_dict['dependencies'] = []
  1343. if not dependency in target_dict['dependencies']:
  1344. target_dict['dependencies'].append(dependency)
  1345. # Sort the dependencies list in the order from dependents to dependencies.
  1346. # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D.
  1347. # Note: flat_list is already sorted in the order from dependencies to
  1348. # dependents.
  1349. if sort_dependencies and 'dependencies' in target_dict:
  1350. target_dict['dependencies'] = [dep for dep in reversed(flat_list)
  1351. if dep in target_dict['dependencies']]
  1352. # Initialize this here to speed up MakePathRelative.
  1353. exception_re = re.compile(r'''["']?[-/$<>]''')
  1354. def MakePathRelative(to_file, fro_file, item):
  1355. # If item is a relative path, it's relative to the build file dict that it's
  1356. # coming from. Fix it up to make it relative to the build file dict that
  1357. # it's going into.
  1358. # Exception: any |item| that begins with these special characters is
  1359. # returned without modification.
  1360. # / Used when a path is already absolute (shortcut optimization;
  1361. # such paths would be returned as absolute anyway)
  1362. # $ Used for build environment variables
  1363. # - Used for some build environment flags (such as -lapr-1 in a
  1364. # "libraries" section)
  1365. # < Used for our own variable and command expansions (see ExpandVariables)
  1366. # > Used for our own variable and command expansions (see ExpandVariables)
  1367. #
  1368. # "/' Used when a value is quoted. If these are present, then we
  1369. # check the second character instead.
  1370. #
  1371. if to_file == fro_file or exception_re.match(item):
  1372. return item
  1373. else:
  1374. # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
  1375. # temporary measure. This should really be addressed by keeping all paths
  1376. # in POSIX until actual project generation.
  1377. ret = os.path.normpath(os.path.join(
  1378. gyp.common.RelativePath(os.path.dirname(fro_file),
  1379. os.path.dirname(to_file)),
  1380. item)).replace('\\', '/')
  1381. if item[-1] == '/':
  1382. ret += '/'
  1383. return ret
  1384. def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True):
  1385. def is_hashable(x):
  1386. try:
  1387. hash(x)
  1388. except TypeError:
  1389. return False
  1390. return True
  1391. # If x is hashable, returns whether x is in s. Else returns whether x is in l.
  1392. def is_in_set_or_list(x, s, l):
  1393. if is_hashable(x):
  1394. return x in s
  1395. return x in l
  1396. prepend_index = 0
  1397. # Make membership testing of hashables in |to| (in particular, strings)
  1398. # faster.
  1399. hashable_to_set = set([x for x in to if is_hashable(x)])
  1400. for item in fro:
  1401. singleton = False
  1402. if isinstance(item, str) or isinstance(item, int):
  1403. # The cheap and easy case.
  1404. if is_paths:
  1405. to_item = MakePathRelative(to_file, fro_file, item)
  1406. else:
  1407. to_item = item
  1408. if not isinstance(item, str) or not item.startswith('-'):
  1409. # Any string that doesn't begin with a "-" is a singleton - it can
  1410. # only appear once in a list, to be enforced by the list merge append
  1411. # or prepend.
  1412. singleton = True
  1413. elif isinstance(item, dict):
  1414. # Make a copy of the dictionary, continuing to look for paths to fix.
  1415. # The other intelligent aspects of merge processing won't apply because
  1416. # item is being merged into an empty dict.
  1417. to_item = {}
  1418. MergeDicts(to_item, item, to_file, fro_file)
  1419. elif isinstance(item, list):
  1420. # Recurse, making a copy of the list. If the list contains any
  1421. # descendant dicts, path fixing will occur. Note that here, custom
  1422. # values for is_paths and append are dropped; those are only to be
  1423. # applied to |to| and |fro|, not sublists of |fro|. append shouldn't
  1424. # matter anyway because the new |to_item| list is empty.
  1425. to_item = []
  1426. MergeLists(to_item, item, to_file, fro_file)
  1427. else:
  1428. raise TypeError, \
  1429. 'Attempt to merge list item of unsupported type ' + \
  1430. item.__class__.__name__
  1431. if append:
  1432. # If appending a singleton that's already in the list, don't append.
  1433. # This ensures that the earliest occurrence of the item will stay put.
  1434. if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to):
  1435. to.append(to_item)
  1436. if is_hashable(to_item):
  1437. hashable_to_set.add(to_item)
  1438. else:
  1439. # If prepending a singleton that's already in the list, remove the
  1440. # existing instance and proceed with the prepend. This ensures that the
  1441. # item appears at the earliest possible position in the list.
  1442. while singleton and to_item in to:
  1443. to.remove(to_item)
  1444. # Don't just insert everything at index 0. That would prepend the new
  1445. # items to the list in reverse order, which would be an unwelcome
  1446. # surprise.
  1447. to.insert(prepend_index, to_item)
  1448. if is_hashable(to_item):
  1449. hashable_to_set.add(to_item)
  1450. prepend_index = prepend_index + 1
  1451. def MergeDicts(to, fro, to_file, fro_file):
  1452. # I wanted to name the parameter "from" but it's a Python keyword...
  1453. for k, v in fro.iteritems():
  1454. # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give
  1455. # copy semantics. Something else may want to merge from the |fro| dict
  1456. # later, and having the same dict ref pointed to twice in the tree isn't
  1457. # what anyone wants considering that the dicts may subsequently be
  1458. # modified.
  1459. if k in to:
  1460. bad_merge = False
  1461. if isinstance(v, str) or isinstance(v, int):
  1462. if not (isinstance(to[k], str) or isinstance(to[k], int)):
  1463. bad_merge = True
  1464. elif v.__class__ != to[k].__class__:
  1465. bad_merge = True
  1466. if bad_merge:
  1467. raise TypeError, \
  1468. 'Attempt to merge dict value of type ' + v.__class__.__name__ + \
  1469. ' into incompatible type ' + to[k].__class__.__name__ + \
  1470. ' for key ' + k
  1471. if isinstance(v, str) or isinstance(v, int):
  1472. # Overwrite the existing value, if any. Cheap and easy.
  1473. is_path = IsPathSection(k)
  1474. if is_path:
  1475. to[k] = MakePathRelative(to_file, fro_file, v)
  1476. else:
  1477. to[k] = v
  1478. elif isinstance(v, dict):
  1479. # Recurse, guaranteeing copies will be made of objects that require it.
  1480. if not k in to:
  1481. to[k] = {}
  1482. MergeDicts(to[k], v, to_file, fro_file)
  1483. elif isinstance(v, list):
  1484. # Lists in dicts can be merged with different policies, depending on
  1485. # how the key in the "from" dict (k, the from-key) is written.
  1486. #
  1487. # If the from-key has ...the to-list will have this action
  1488. # this character appended:... applied when receiving the from-list:
  1489. # = replace
  1490. # + prepend
  1491. # ? set, only if to-list does not yet exist
  1492. # (none) append
  1493. #
  1494. # This logic is list-specific, but since it relies on the associated
  1495. # dict key, it's checked in this dict-oriented function.
  1496. ext = k[-1]
  1497. append = True
  1498. if ext == '=':
  1499. list_base = k[:-1]
  1500. lists_incompatible = [list_base, list_base + '?']
  1501. to[list_base] = []
  1502. elif ext == '+':
  1503. list_base = k[:-1]
  1504. lists_incompatible = [list_base + '=', list_base + '?']
  1505. append = False
  1506. elif ext == '?':
  1507. list_base = k[:-1]
  1508. lists_incompatible = [list_base, list_base + '=', list_base + '+']
  1509. else:
  1510. list_base = k
  1511. lists_incompatible = [list_base + '=', list_base + '?']
  1512. # Some combinations of merge policies appearing together are meaningless.
  1513. # It's stupid to replace and append simultaneously, for example. Append
  1514. # and prepend are the only policies that can coexist.
  1515. for list_incompatible in lists_incompatible:
  1516. if list_incompatible in fro:
  1517. raise KeyError, 'Incompatible list policies ' + k + ' and ' + \
  1518. list_incompatible
  1519. if list_base in to:
  1520. if ext == '?':
  1521. # If the key ends in "?", the list will only be merged if it doesn't
  1522. # already exist.
  1523. continue
  1524. if not isinstance(to[list_base], list):
  1525. # This may not have been checked above if merging in a list with an
  1526. # extension character.
  1527. raise TypeError, \
  1528. 'Attempt to merge dict value of type ' + v.__class__.__name__ + \
  1529. ' into incompatible type ' + to[list_base].__class__.__name__ + \
  1530. ' for key ' + list_base + '(' + k + ')'
  1531. else:
  1532. to[list_base] = []
  1533. # Call MergeLists, which will make copies of objects that require it.
  1534. # MergeLists can recurse back into MergeDicts, although this will be
  1535. # to make copies of dicts (with paths fixed), there will be no
  1536. # subsequent dict "merging" once entering a list because lists are
  1537. # always replaced, appended to, or prepended to.
  1538. is_paths = IsPathSection(list_base)
  1539. MergeLists(to[list_base], v, to_file, fro_file, is_paths, append)
  1540. else:
  1541. raise TypeError, \
  1542. 'Attempt to merge dict value of unsupported type ' + \
  1543. v.__class__.__name__ + ' for key ' + k
  1544. def MergeConfigWithInheritance(new_configuration_dict, build_file,
  1545. target_dict, configuration, visited):
  1546. # Skip if previously visted.
  1547. if configuration in visited:
  1548. return
  1549. # Look at this configuration.
  1550. configuration_dict = target_dict['configurations'][configuration]
  1551. # Merge in parents.
  1552. for parent in configuration_dict.get('inherit_from', []):
  1553. MergeConfigWithInheritance(new_configuration_dict, build_file,
  1554. target_dict, parent, visited + [configuration])
  1555. # Merge it into the new config.
  1556. MergeDicts(new_configuration_dict, configuration_dict,
  1557. build_file, build_file)
  1558. # Drop abstract.
  1559. if 'abstract' in new_configuration_dict:
  1560. del new_configuration_dict['abstract']
  1561. def SetUpConfigurations(target, target_dict):
  1562. global non_configuration_keys
  1563. # key_suffixes is a list of key suffixes that might appear on key names.
  1564. # These suffixes are handled in conditional evaluations (for =, +, and ?)
  1565. # and rules/exclude processing (for ! and /). Keys with these suffixes
  1566. # should be treated the same as keys without.
  1567. key_suffixes = ['=', '+', '?', '!', '/']
  1568. build_file = gyp.common.BuildFile(target)
  1569. # Provide a single configuration by default if none exists.
  1570. # TODO(mark): Signal an error if default_configurations exists but
  1571. # configurations does not.
  1572. if not 'configurations' in target_dict:
  1573. target_dict['configurations'] = {'Default': {}}
  1574. if not 'default_configuration' in target_dict:
  1575. concrete = [i for i in target_dict['configurations'].keys()
  1576. if not target_dict['configurations'][i].get('abstract')]
  1577. target_dict['default_configuration'] = sorted(concrete)[0]
  1578. for configuration in target_dict['configurations'].keys():
  1579. old_configuration_dict = target_dict['configurations'][configuration]
  1580. # Skip abstract configurations (saves work only).
  1581. if old_configuration_dict.get('abstract'):
  1582. continue
  1583. # Configurations inherit (most) settings from the enclosing target scope.
  1584. # Get the inheritance relationship right by making a copy of the target
  1585. # dict.
  1586. new_configuration_dict = copy.deepcopy(target_dict)
  1587. # Take out the bits that don't belong in a "configurations" section.
  1588. # Since configuration setup is done before conditional, exclude, and rules
  1589. # processing, be careful with handling of the suffix characters used in
  1590. # those phases.
  1591. delete_keys = []
  1592. for key in new_configuration_dict:
  1593. key_ext = key[-1:]
  1594. if key_ext in key_suffixes:
  1595. key_base = key[:-1]
  1596. else:
  1597. key_base = key
  1598. if key_base in non_configuration_keys:
  1599. delete_keys.append(key)
  1600. for key in delete_keys:
  1601. del new_configuration_dict[key]
  1602. # Merge in configuration (with all its parents first).
  1603. MergeConfigWithInheritance(new_configuration_dict, build_file,
  1604. target_dict, configuration, [])
  1605. # Put the new result back into the target dict as a configuration.
  1606. target_dict['configurations'][configuration] = new_configuration_dict
  1607. # Now drop all the abstract ones.
  1608. for configuration in target_dict['configurations'].keys():
  1609. old_configuration_dict = target_dict['configurations'][configuration]
  1610. if old_configuration_dict.get('abstract'):
  1611. del target_dict['configurations'][configuration]
  1612. # Now that all of the target's configurations have been built, go through
  1613. # the target dict's keys and remove everything that's been moved into a
  1614. # "configurations" section.
  1615. delete_keys = []
  1616. for key in target_dict:
  1617. key_ext = key[-1:]
  1618. if key_ext in key_suffixes:
  1619. key_base = key[:-1]
  1620. else:
  1621. key_base = key
  1622. if not key_base in non_configuration_keys:
  1623. delete_keys.append(key)
  1624. for key in delete_keys:
  1625. del target_dict[key]
  1626. # Check the configurations to see if they contain invalid keys.
  1627. for configuration in target_dict['configurations'].keys():
  1628. configuration_dict = target_dict['configurations'][configuration]
  1629. for key in configuration_dict.keys():
  1630. if key in invalid_configuration_keys:
  1631. raise KeyError, ('%s not allowed in the %s configuration, found in '
  1632. 'target %s' % (key, configuration, target))
  1633. def ProcessListFiltersInDict(name, the_dict):
  1634. """Process regular expression and exclusion-based filters on lists.
  1635. An exclusion list is in a dict key named with a trailing "!", like
  1636. "sources!". Every item in such a list is removed from the associated
  1637. main list, which in this example, would be "sources". Removed items are
  1638. placed into a "sources_excluded" list in the dict.
  1639. Regular expression (regex) filters are contained in dict keys named with a
  1640. trailing "/", such as "sources/" to operate on the "sources" list. Regex
  1641. filters in a dict take the form:
  1642. 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
  1643. ['include', '_mac\\.cc$'] ],
  1644. The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
  1645. _win.cc. The second filter then includes all files ending in _mac.cc that
  1646. are now or were once in the "sources" list. Items matching an "exclude"
  1647. filter are subject to the same processing as would occur if they were listed
  1648. by name in an exclusion list (ending in "!"). Items matching an "include"
  1649. filter are brought back into the main list if previously excluded by an
  1650. exclusion list or exclusion regex filter. Subsequent matching "exclude"
  1651. patterns can still cause items to be excluded after matching an "include".
  1652. """
  1653. # Look through the dictionary for any lists whose keys end in "!" or "/".
  1654. # These are lists that will be treated as exclude lists and regular
  1655. # expression-based exclude/include lists. Collect the lists that are
  1656. # needed first, looking for the lists that they operate on, and assemble
  1657. # then into |lists|. This is done in a separate loop up front, because
  1658. # the _included and _excluded keys need to be added to the_dict, and that
  1659. # can't be done while iterating through it.
  1660. lists = []
  1661. del_lists = []
  1662. for key, value in the_dict.iteritems():
  1663. operation = key[-1]
  1664. if operation != '!' and operation != '/':
  1665. continue
  1666. if not isinstance(value, list):
  1667. raise ValueError, name + ' key ' + key + ' must be list, not ' + \
  1668. value.__class__.__name__
  1669. list_key = key[:-1]
  1670. if list_key not in the_dict:
  1671. # This happens when there's a list like "sources!" but no corresponding
  1672. # "sources" list. Since there's nothing for it to operate on, queue up
  1673. # the "sources!" list for deletion now.
  1674. del_lists.append(key)
  1675. continue
  1676. if not isinstance(the_dict[list_key], list):
  1677. raise ValueError, name + ' key ' + list_key + \
  1678. ' must be list, not ' + \
  1679. value.__class__.__name__ + ' when applying ' + \
  1680. {'!': 'exclusion', '/': 'regex'}[operation]
  1681. if not list_key in lists:
  1682. lists.append(list_key)
  1683. # Delete the lists that are known to be unneeded at this point.
  1684. for del_list in del_lists:
  1685. del the_dict[del_list]
  1686. for list_key in lists:
  1687. the_list = the_dict[list_key]
  1688. # Initialize the list_actions list, which is parallel to the_list. Each
  1689. # item in list_actions identifies whether the corresponding item in
  1690. # the_list should be excluded, unconditionally preserved (included), or
  1691. # whether no exclusion or inclusion has been applied. Items for which
  1692. # no exclusion or inclusion has been applied (yet) have value -1, items
  1693. # excluded have value 0, and items included have value 1. Includes and
  1694. # excludes override previous actions. All items in list_actions are
  1695. # initialized to -1 because no excludes or includes have been processed
  1696. # yet.
  1697. list_actions = list((-1,) * len(the_list))
  1698. exclude_key = list_key + '!'
  1699. if exclude_key in the_dict:
  1700. for exclude_item in the_dict[exclude_key]:
  1701. for index in xrange(0, len(the_list)):
  1702. if exclude_item == the_list[index]:
  1703. # This item matches the exclude_item, so set its action to 0
  1704. # (exclude).
  1705. list_actions[index] = 0
  1706. # The "whatever!" list is no longer needed, dump it.
  1707. del the_dict[exclude_key]
  1708. regex_key = list_key + '/'
  1709. if regex_key in the_dict:
  1710. for regex_item in the_dict[regex_key]:
  1711. [action, pattern] = regex_item
  1712. pattern_re = re.compile(pattern)
  1713. if action == 'exclude':
  1714. # This item matches an exclude regex, so set its value to 0 (exclude).
  1715. action_value = 0
  1716. elif action == 'include':
  1717. # This item matches an include regex, so set its value to 1 (include).
  1718. action_value = 1
  1719. else:
  1720. # This is an action that doesn't make any sense.
  1721. raise ValueError, 'Unrecognized action ' + action + ' in ' + name + \
  1722. ' key ' + key
  1723. for index in xrange(0, len(the_list)):
  1724. list_item = the_list[index]
  1725. if list_actions[index] == action_value:
  1726. # Even if the regex matches, nothing will change so continue (regex
  1727. # searches are expensive).
  1728. continue
  1729. if pattern_re.search(list_item):
  1730. # Regular expression match.
  1731. list_actions[index] = action_value
  1732. # The "whatever/" list is no longer needed, dump it.
  1733. del the_dict[regex_key]
  1734. # Add excluded items to the excluded list.
  1735. #
  1736. # Note that exclude_key ("sources!") is different from excluded_key
  1737. # ("sources_excluded"). The exclude_key list is input and it was already
  1738. # processed and deleted; the excluded_key list is output and it's about
  1739. # to be created.
  1740. excluded_key = list_key + '_excluded'
  1741. if excluded_key in the_dict:
  1742. raise KeyError, \
  1743. name + ' key ' + excluded_key + ' must not be present prior ' + \
  1744. ' to applying exclusion/regex filters for ' + list_key
  1745. excluded_list = []
  1746. # Go backwards through the list_actions list so that as items are deleted,
  1747. # the indices of items that haven't been seen yet don't shift. That means
  1748. # that things need to be prepended to excluded_list to maintain them in the
  1749. # same order that they existed in the_list.
  1750. for index in xrange(len(list_actions) - 1, -1, -1):
  1751. if list_actions[index] == 0:
  1752. # Dump anything with action 0 (exclude). Keep anything with action 1
  1753. # (include) or -1 (no include or exclude seen for the item).
  1754. excluded_list.insert(0, the_list[index])
  1755. del the_list[index]
  1756. # If anything was excluded, put the excluded list into the_dict at
  1757. # excluded_key.
  1758. if len(excluded_list) > 0:
  1759. the_dict[excluded_key] = excluded_list
  1760. # Now recurse into subdicts and lists that may contain dicts.
  1761. for key, value in the_dict.iteritems():
  1762. if isinstance(value, dict):
  1763. ProcessListFiltersInDict(key, value)
  1764. elif isinstance(value, list):
  1765. ProcessListFiltersInList(key, value)
  1766. def ProcessListFiltersInList(name, the_list):
  1767. for item in the_list:
  1768. if isinstance(item, dict):
  1769. ProcessListFiltersInDict(name, item)
  1770. elif isinstance(item, list):
  1771. ProcessListFiltersInList(name, item)
  1772. def ValidateTargetType(target, target_dict):
  1773. """Ensures the 'type' field on the target is one of the known types.
  1774. Arguments:
  1775. target: string, name of target.
  1776. target_dict: dict, target spec.
  1777. Raises an exception on error.
  1778. """
  1779. VALID_TARGET_TYPES = ('executable', 'loadable_module',
  1780. 'static_library', 'shared_library',
  1781. 'none')
  1782. target_type = target_dict.get('type', None)
  1783. if target_type not in VALID_TARGET_TYPES:
  1784. raise Exception("Target %s has an invalid target type '%s'. "
  1785. "Must be one of %s." %
  1786. (target, target_type, '/'.join(VALID_TARGET_TYPES)))
  1787. def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules):
  1788. """Ensures that the rules sections in target_dict are valid and consistent,
  1789. and determines which sources they apply to.
  1790. Arguments:
  1791. target: string, name of target.
  1792. target_dict: dict, target spec containing "rules" and "sources" lists.
  1793. extra_sources_for_rules: a list of keys to scan for rule matches in
  1794. addition to 'sources'.
  1795. """
  1796. # Dicts to map between values found in rules' 'rule_name' and 'extension'
  1797. # keys and the rule dicts themselves.
  1798. rule_names = {}
  1799. rule_extensions = {}
  1800. rules = target_dict.get('rules', [])
  1801. for rule in rules:
  1802. # Make sure that there's no conflict among rule names and extensions.
  1803. rule_name = rule['rule_name']
  1804. if rule_name in rule_names:
  1805. raise KeyError, 'rule %s exists in duplicate, target %s' % \
  1806. (rule_name, target)
  1807. rule_names[rule_name] = rule
  1808. rule_extension = rule['extension']
  1809. if rule_extension in rule_extensions:
  1810. raise KeyError, ('extension %s associated with multiple rules, ' +
  1811. 'target %s rules %s and %s') % \
  1812. (rule_extension, target,
  1813. rule_extensions[rule_extension]['rule_name'],
  1814. rule_name)
  1815. rule_extensions[rule_extension] = rule
  1816. # Make sure rule_sources isn't already there. It's going to be
  1817. # created below if needed.
  1818. if 'rule_sources' in rule:
  1819. raise KeyError, \
  1820. 'rule_sources must not exist in input, target %s rule %s' % \
  1821. (target, rule_name)
  1822. extension = rule['extension']
  1823. rule_sources = []
  1824. source_keys = ['sources']
  1825. source_keys.extend(extra_sources_for_rules)
  1826. for source_key in source_keys:
  1827. for source in target_dict.get(source_key, []):
  1828. (source_root, source_extension) = os.path.splitext(source)
  1829. if source_extension.startswith('.'):
  1830. source_extension = source_extension[1:]
  1831. if source_extension == extension:
  1832. rule_sources.append(source)
  1833. if len(rule_sources) > 0:
  1834. rule['rule_sources'] = rule_sources
  1835. def ValidateActionsInTarget(target, target_dict, build_file):
  1836. '''Validates the inputs to the actions in a target.'''
  1837. target_name = target_dict.get('target_name')
  1838. actions = target_dict.get('actions', [])
  1839. for action in actions:
  1840. action_name = action.get('action_name')
  1841. if not action_name:
  1842. raise Exception("Anonymous action in target %s. "
  1843. "An action must have an 'action_name' field." %
  1844. target_name)
  1845. inputs = action.get('inputs', [])
  1846. def ValidateRunAsInTarget(target, target_dict, build_file):
  1847. target_name = target_dict.get('target_name')
  1848. run_as = target_dict.get('run_as')
  1849. if not run_as:
  1850. return
  1851. if not isinstance(run_as, dict):
  1852. raise Exception("The 'run_as' in target %s from file %s should be a "
  1853. "dictionary." %
  1854. (target_name, build_file))
  1855. action = run_as.get('action')
  1856. if not action:
  1857. raise Exception("The 'run_as' in target %s from file %s must have an "
  1858. "'action' section." %
  1859. (target_name, build_file))
  1860. if not isinstance(action, list):
  1861. raise Exception("The 'action' for 'run_as' in target %s from file %s "
  1862. "must be a list." %
  1863. (target_name, build_file))
  1864. working_directory = run_as.get('working_directory')
  1865. if working_directory and not isinstance(working_directory, str):
  1866. raise Exception("The 'working_directory' for 'run_as' in target %s "
  1867. "in file %s should be a string." %
  1868. (target_name, build_file))
  1869. environment = run_as.get('environment')
  1870. if environment and not isinstance(environment, dict):
  1871. raise Exception("The 'environment' for 'run_as' in target %s "
  1872. "in file %s should be a dictionary." %
  1873. (target_name, build_file))
  1874. def TurnIntIntoStrInDict(the_dict):
  1875. """Given dict the_dict, recursively converts all integers into strings.
  1876. """
  1877. # Use items instead of iteritems because there's no need to try to look at
  1878. # reinserted keys and their associated values.
  1879. for k, v in the_dict.items():
  1880. if isinstance(v, int):
  1881. v = str(v)
  1882. the_dict[k] = v
  1883. elif isinstance(v, dict):
  1884. TurnIntIntoStrInDict(v)
  1885. elif isinstance(v, list):
  1886. TurnIntIntoStrInList(v)
  1887. if isinstance(k, int):
  1888. the_dict[str(k)] = v
  1889. del the_dict[k]
  1890. def TurnIntIntoStrInList(the_list):
  1891. """Given list the_list, recursively converts all integers into strings.
  1892. """
  1893. for index in xrange(0, len(the_list)):
  1894. item = the_list[index]
  1895. if isinstance(item, int):
  1896. the_list[index] = str(item)
  1897. elif isinstance(item, dict):
  1898. TurnIntIntoStrInDict(item)
  1899. elif isinstance(item, list):
  1900. TurnIntIntoStrInList(item)
  1901. def VerifyNoCollidingTargets(targets):
  1902. """Verify that no two targets in the same directory share the same name.
  1903. Arguments:
  1904. targets: A list of targets in the form 'path/to/file.gyp:target_name'.
  1905. """
  1906. # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'.
  1907. used = {}
  1908. for target in targets:
  1909. # Separate out 'path/to/file.gyp, 'target_name' from
  1910. # 'path/to/file.gyp:target_name'.
  1911. path, name = target.rsplit(':', 1)
  1912. # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'.
  1913. subdir, gyp = os.path.split(path)
  1914. # Use '.' for the current directory '', so that the error messages make
  1915. # more sense.
  1916. if not subdir:
  1917. subdir = '.'
  1918. # Prepare a key like 'path/to:target_name'.
  1919. key = subdir + ':' + name
  1920. if key in used:
  1921. # Complain if this target is already used.
  1922. raise Exception('Duplicate target name "%s" in directory "%s" used both '
  1923. 'in "%s" and "%s".' % (name, subdir, gyp, used[key]))
  1924. used[key] = gyp
  1925. def Load(build_files, variables, includes, depth, generator_input_info, check,
  1926. circular_check):
  1927. # Set up path_sections and non_configuration_keys with the default data plus
  1928. # the generator-specifc data.
  1929. global path_sections
  1930. path_sections = base_path_sections[:]
  1931. path_sections.extend(generator_input_info['path_sections'])
  1932. global non_configuration_keys
  1933. non_configuration_keys = base_non_configuration_keys[:]
  1934. non_configuration_keys.extend(generator_input_info['non_configuration_keys'])
  1935. # TODO(mark) handle variants if the generator doesn't want them directly.
  1936. generator_handles_variants = \
  1937. generator_input_info['generator_handles_variants']
  1938. global absolute_build_file_paths
  1939. absolute_build_file_paths = \
  1940. generator_input_info['generator_wants_absolute_build_file_paths']
  1941. global multiple_toolsets
  1942. multiple_toolsets = generator_input_info[
  1943. 'generator_supports_multiple_toolsets']
  1944. # A generator can have other lists (in addition to sources) be processed
  1945. # for rules.
  1946. extra_sources_for_rules = generator_input_info['extra_sources_for_rules']
  1947. # Load build files. This loads every target-containing build file into
  1948. # the |data| dictionary such that the keys to |data| are build file names,
  1949. # and the values are the entire build file contents after "early" or "pre"
  1950. # processing has been done and includes have been resolved.
  1951. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as
  1952. # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps
  1953. # track of the keys corresponding to "target" files.
  1954. data = {'target_build_files': set()}
  1955. aux_data = {}
  1956. for build_file in build_files:
  1957. # Normalize paths everywhere. This is important because paths will be
  1958. # used as keys to the data dict and for references between input files.
  1959. build_file = os.path.normpath(build_file)
  1960. try:
  1961. LoadTargetBuildFile(build_file, data, aux_data, variables, includes,
  1962. depth, check)
  1963. except Exception, e:
  1964. gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file)
  1965. raise
  1966. # Build a dict to access each target's subdict by qualified name.
  1967. targets = BuildTargetsDict(data)
  1968. # Fully qualify all dependency links.
  1969. QualifyDependencies(targets)
  1970. # Expand dependencies specified as build_file:*.
  1971. ExpandWildcardDependencies(targets, data)
  1972. # Apply exclude (!) and regex (/) list filters only for dependency_sections.
  1973. for target_name, target_dict in targets.iteritems():
  1974. tmp_dict = {}
  1975. for key_base in dependency_sections:
  1976. for op in ('', '!', '/'):
  1977. key = key_base + op
  1978. if key in target_dict:
  1979. tmp_dict[key] = target_dict[key]
  1980. del target_dict[key]
  1981. ProcessListFiltersInDict(target_name, tmp_dict)
  1982. # Write the results back to |target_dict|.
  1983. for key in tmp_dict:
  1984. target_dict[key] = tmp_dict[key]
  1985. if circular_check:
  1986. # Make sure that any targets in a.gyp don't contain dependencies in other
  1987. # .gyp files that further depend on a.gyp.
  1988. VerifyNoGYPFileCircularDependencies(targets)
  1989. [dependency_nodes, flat_list] = BuildDependencyList(targets)
  1990. # Check that no two targets in the same directory have the same name.
  1991. VerifyNoCollidingTargets(flat_list)
  1992. # Handle dependent settings of various types.
  1993. for settings_type in ['all_dependent_settings',
  1994. 'direct_dependent_settings',
  1995. 'link_settings']:
  1996. DoDependentSettings(settings_type, flat_list, targets, dependency_nodes)
  1997. # Take out the dependent settings now that they've been published to all
  1998. # of the targets that require them.
  1999. for target in flat_list:
  2000. if settings_type in targets[target]:
  2001. del targets[target][settings_type]
  2002. # Make sure static libraries don't declare dependencies on other static
  2003. # libraries, but that linkables depend on all unlinked static libraries
  2004. # that they need so that their link steps will be correct.
  2005. gii = generator_input_info
  2006. if gii['generator_wants_static_library_dependencies_adjusted']:
  2007. AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes,
  2008. gii['generator_wants_sorted_dependencies'])
  2009. # Apply "post"/"late"/"target" variable expansions and condition evaluations.
  2010. for target in flat_list:
  2011. target_dict = targets[target]
  2012. build_file = gyp.common.BuildFile(target)
  2013. ProcessVariablesAndConditionsInDict(target_dict, True, variables,
  2014. build_file)
  2015. # Move everything that can go into a "configurations" section into one.
  2016. for target in flat_list:
  2017. target_dict = targets[target]
  2018. SetUpConfigurations(target, target_dict)
  2019. # Apply exclude (!) and regex (/) list filters.
  2020. for target in flat_list:
  2021. target_dict = targets[target]
  2022. ProcessListFiltersInDict(target, target_dict)
  2023. # Make sure that the rules make sense, and build up rule_sources lists as
  2024. # needed. Not all generators will need to use the rule_sources lists, but
  2025. # some may, and it seems best to build the list in a common spot.
  2026. # Also validate actions and run_as elements in targets.
  2027. for target in flat_list:
  2028. target_dict = targets[target]
  2029. build_file = gyp.common.BuildFile(target)
  2030. ValidateTargetType(target, target_dict)
  2031. ValidateRulesInTarget(target, target_dict, extra_sources_for_rules)
  2032. ValidateRunAsInTarget(target, target_dict, build_file)
  2033. ValidateActionsInTarget(target, target_dict, build_file)
  2034. # Generators might not expect ints. Turn them into strs.
  2035. TurnIntIntoStrInDict(data)
  2036. # TODO(mark): Return |data| for now because the generator needs a list of
  2037. # build files that came in. In the future, maybe it should just accept
  2038. # a list, and not the whole data dict.
  2039. return [flat_list, targets, data]