PageRenderTime 72ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/hsoft/mozilla-central
Python | 2485 lines | 1939 code | 158 blank | 388 comment | 241 complexity | bedff01491c70c87df2a339c97f5846c MD5 | raw file
Possible License(s): JSON, LGPL-2.1, LGPL-3.0, AGPL-1.0, MIT, MPL-2.0-no-copyleft-exception, Apache-2.0, GPL-2.0, BSD-2-Clause, MPL-2.0, BSD-3-Clause, 0BSD
  1. # Copyright (c) 2012 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. if multiple_toolsets:
  258. toolsets = target.get('toolsets', ['target'])
  259. else:
  260. toolsets = ['target']
  261. # Make sure this 'toolsets' definition is only processed once.
  262. if 'toolsets' in target:
  263. del target['toolsets']
  264. if len(toolsets) > 0:
  265. # Optimization: only do copies if more than one toolset is specified.
  266. for build in toolsets[1:]:
  267. new_target = copy.deepcopy(target)
  268. new_target['toolset'] = build
  269. new_target_list.append(new_target)
  270. target['toolset'] = toolsets[0]
  271. new_target_list.append(target)
  272. data['targets'] = new_target_list
  273. if 'conditions' in data:
  274. for condition in data['conditions']:
  275. if isinstance(condition, list):
  276. for condition_dict in condition[1:]:
  277. ProcessToolsetsInDict(condition_dict)
  278. # TODO(mark): I don't love this name. It just means that it's going to load
  279. # a build file that contains targets and is expected to provide a targets dict
  280. # that contains the targets...
  281. def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes,
  282. depth, check):
  283. # If depth is set, predefine the DEPTH variable to be a relative path from
  284. # this build file's directory to the directory identified by depth.
  285. if depth:
  286. # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
  287. # temporary measure. This should really be addressed by keeping all paths
  288. # in POSIX until actual project generation.
  289. d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path))
  290. if d == '':
  291. variables['DEPTH'] = '.'
  292. else:
  293. variables['DEPTH'] = d.replace('\\', '/')
  294. # If the generator needs absolue paths, then do so.
  295. if absolute_build_file_paths:
  296. build_file_path = os.path.abspath(build_file_path)
  297. if build_file_path in data['target_build_files']:
  298. # Already loaded.
  299. return
  300. data['target_build_files'].add(build_file_path)
  301. gyp.DebugOutput(gyp.DEBUG_INCLUDES,
  302. "Loading Target Build File '%s'" % build_file_path)
  303. build_file_data = LoadOneBuildFile(build_file_path, data, aux_data, variables,
  304. includes, True, check)
  305. # Store DEPTH for later use in generators.
  306. build_file_data['_DEPTH'] = depth
  307. # Set up the included_files key indicating which .gyp files contributed to
  308. # this target dict.
  309. if 'included_files' in build_file_data:
  310. raise KeyError, build_file_path + ' must not contain included_files key'
  311. included = GetIncludedBuildFiles(build_file_path, aux_data)
  312. build_file_data['included_files'] = []
  313. for included_file in included:
  314. # included_file is relative to the current directory, but it needs to
  315. # be made relative to build_file_path's directory.
  316. included_relative = \
  317. gyp.common.RelativePath(included_file,
  318. os.path.dirname(build_file_path))
  319. build_file_data['included_files'].append(included_relative)
  320. # Do a first round of toolsets expansion so that conditions can be defined
  321. # per toolset.
  322. ProcessToolsetsInDict(build_file_data)
  323. # Apply "pre"/"early" variable expansions and condition evaluations.
  324. ProcessVariablesAndConditionsInDict(
  325. build_file_data, PHASE_EARLY, variables, build_file_path)
  326. # Since some toolsets might have been defined conditionally, perform
  327. # a second round of toolsets expansion now.
  328. ProcessToolsetsInDict(build_file_data)
  329. # Look at each project's target_defaults dict, and merge settings into
  330. # targets.
  331. if 'target_defaults' in build_file_data:
  332. index = 0
  333. if 'targets' in build_file_data:
  334. while index < len(build_file_data['targets']):
  335. # This procedure needs to give the impression that target_defaults is
  336. # used as defaults, and the individual targets inherit from that.
  337. # The individual targets need to be merged into the defaults. Make
  338. # a deep copy of the defaults for each target, merge the target dict
  339. # as found in the input file into that copy, and then hook up the
  340. # copy with the target-specific data merged into it as the replacement
  341. # target dict.
  342. old_target_dict = build_file_data['targets'][index]
  343. new_target_dict = copy.deepcopy(build_file_data['target_defaults'])
  344. MergeDicts(new_target_dict, old_target_dict,
  345. build_file_path, build_file_path)
  346. build_file_data['targets'][index] = new_target_dict
  347. index = index + 1
  348. else:
  349. raise Exception, \
  350. "Unable to find targets in build file %s" % build_file_path
  351. # No longer needed.
  352. del build_file_data['target_defaults']
  353. # Look for dependencies. This means that dependency resolution occurs
  354. # after "pre" conditionals and variable expansion, but before "post" -
  355. # in other words, you can't put a "dependencies" section inside a "post"
  356. # conditional within a target.
  357. if 'targets' in build_file_data:
  358. for target_dict in build_file_data['targets']:
  359. if 'dependencies' not in target_dict:
  360. continue
  361. for dependency in target_dict['dependencies']:
  362. other_build_file = \
  363. gyp.common.ResolveTarget(build_file_path, dependency, None)[0]
  364. try:
  365. LoadTargetBuildFile(other_build_file, data, aux_data, variables,
  366. includes, depth, check)
  367. except Exception, e:
  368. gyp.common.ExceptionAppend(
  369. e, 'while loading dependencies of %s' % build_file_path)
  370. raise
  371. return data
  372. # Look for the bracket that matches the first bracket seen in a
  373. # string, and return the start and end as a tuple. For example, if
  374. # the input is something like "<(foo <(bar)) blah", then it would
  375. # return (1, 13), indicating the entire string except for the leading
  376. # "<" and trailing " blah".
  377. def FindEnclosingBracketGroup(input):
  378. brackets = { '}': '{',
  379. ']': '[',
  380. ')': '(', }
  381. stack = []
  382. count = 0
  383. start = -1
  384. for char in input:
  385. if char in brackets.values():
  386. stack.append(char)
  387. if start == -1:
  388. start = count
  389. if char in brackets.keys():
  390. try:
  391. last_bracket = stack.pop()
  392. except IndexError:
  393. return (-1, -1)
  394. if last_bracket != brackets[char]:
  395. return (-1, -1)
  396. if len(stack) == 0:
  397. return (start, count + 1)
  398. count = count + 1
  399. return (-1, -1)
  400. canonical_int_re = re.compile('^(0|-?[1-9][0-9]*)$')
  401. def IsStrCanonicalInt(string):
  402. """Returns True if |string| is in its canonical integer form.
  403. The canonical form is such that str(int(string)) == string.
  404. """
  405. if not isinstance(string, str) or not canonical_int_re.match(string):
  406. return False
  407. return True
  408. # This matches things like "<(asdf)", "<!(cmd)", "<!@(cmd)", "<|(list)",
  409. # "<!interpreter(arguments)", "<([list])", and even "<([)" and "<(<())".
  410. # In the last case, the inner "<()" is captured in match['content'].
  411. early_variable_re = re.compile(
  412. '(?P<replace>(?P<type><(?:(?:!?@?)|\|)?)'
  413. '(?P<command_string>[-a-zA-Z0-9_.]+)?'
  414. '\((?P<is_array>\s*\[?)'
  415. '(?P<content>.*?)(\]?)\))')
  416. # This matches the same as early_variable_re, but with '>' instead of '<'.
  417. late_variable_re = re.compile(
  418. '(?P<replace>(?P<type>>(?:(?:!?@?)|\|)?)'
  419. '(?P<command_string>[-a-zA-Z0-9_.]+)?'
  420. '\((?P<is_array>\s*\[?)'
  421. '(?P<content>.*?)(\]?)\))')
  422. # This matches the same as early_variable_re, but with '^' instead of '<'.
  423. latelate_variable_re = re.compile(
  424. '(?P<replace>(?P<type>[\^](?:(?:!?@?)|\|)?)'
  425. '(?P<command_string>[-a-zA-Z0-9_.]+)?'
  426. '\((?P<is_array>\s*\[?)'
  427. '(?P<content>.*?)(\]?)\))')
  428. # Global cache of results from running commands so they don't have to be run
  429. # more then once.
  430. cached_command_results = {}
  431. def FixupPlatformCommand(cmd):
  432. if sys.platform == 'win32':
  433. if type(cmd) == list:
  434. cmd = [re.sub('^cat ', 'type ', cmd[0])] + cmd[1:]
  435. else:
  436. cmd = re.sub('^cat ', 'type ', cmd)
  437. return cmd
  438. PHASE_EARLY = 0
  439. PHASE_LATE = 1
  440. PHASE_LATELATE = 2
  441. def ExpandVariables(input, phase, variables, build_file):
  442. # Look for the pattern that gets expanded into variables
  443. if phase == PHASE_EARLY:
  444. variable_re = early_variable_re
  445. expansion_symbol = '<'
  446. elif phase == PHASE_LATE:
  447. variable_re = late_variable_re
  448. expansion_symbol = '>'
  449. elif phase == PHASE_LATELATE:
  450. variable_re = latelate_variable_re
  451. expansion_symbol = '^'
  452. else:
  453. assert False
  454. input_str = str(input)
  455. if IsStrCanonicalInt(input_str):
  456. return int(input_str)
  457. # Do a quick scan to determine if an expensive regex search is warranted.
  458. if expansion_symbol not in input_str:
  459. return input_str
  460. # Get the entire list of matches as a list of MatchObject instances.
  461. # (using findall here would return strings instead of MatchObjects).
  462. matches = [match for match in variable_re.finditer(input_str)]
  463. if not matches:
  464. return input_str
  465. output = input_str
  466. # Reverse the list of matches so that replacements are done right-to-left.
  467. # That ensures that earlier replacements won't mess up the string in a
  468. # way that causes later calls to find the earlier substituted text instead
  469. # of what's intended for replacement.
  470. matches.reverse()
  471. for match_group in matches:
  472. match = match_group.groupdict()
  473. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  474. "Matches: %s" % repr(match))
  475. # match['replace'] is the substring to look for, match['type']
  476. # is the character code for the replacement type (< > <! >! <| >| <@
  477. # >@ <!@ >!@), match['is_array'] contains a '[' for command
  478. # arrays, and match['content'] is the name of the variable (< >)
  479. # or command to run (<! >!). match['command_string'] is an optional
  480. # command string. Currently, only 'pymod_do_main' is supported.
  481. # run_command is true if a ! variant is used.
  482. run_command = '!' in match['type']
  483. command_string = match['command_string']
  484. # file_list is true if a | variant is used.
  485. file_list = '|' in match['type']
  486. # Capture these now so we can adjust them later.
  487. replace_start = match_group.start('replace')
  488. replace_end = match_group.end('replace')
  489. # Find the ending paren, and re-evaluate the contained string.
  490. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:])
  491. # Adjust the replacement range to match the entire command
  492. # found by FindEnclosingBracketGroup (since the variable_re
  493. # probably doesn't match the entire command if it contained
  494. # nested variables).
  495. replace_end = replace_start + c_end
  496. # Find the "real" replacement, matching the appropriate closing
  497. # paren, and adjust the replacement start and end.
  498. replacement = input_str[replace_start:replace_end]
  499. # Figure out what the contents of the variable parens are.
  500. contents_start = replace_start + c_start + 1
  501. contents_end = replace_end - 1
  502. contents = input_str[contents_start:contents_end]
  503. # Do filter substitution now for <|().
  504. # Admittedly, this is different than the evaluation order in other
  505. # contexts. However, since filtration has no chance to run on <|(),
  506. # this seems like the only obvious way to give them access to filters.
  507. if file_list:
  508. processed_variables = copy.deepcopy(variables)
  509. ProcessListFiltersInDict(contents, processed_variables)
  510. # Recurse to expand variables in the contents
  511. contents = ExpandVariables(contents, phase,
  512. processed_variables, build_file)
  513. else:
  514. # Recurse to expand variables in the contents
  515. contents = ExpandVariables(contents, phase, variables, build_file)
  516. # Strip off leading/trailing whitespace so that variable matches are
  517. # simpler below (and because they are rarely needed).
  518. contents = contents.strip()
  519. # expand_to_list is true if an @ variant is used. In that case,
  520. # the expansion should result in a list. Note that the caller
  521. # is to be expecting a list in return, and not all callers do
  522. # because not all are working in list context. Also, for list
  523. # expansions, there can be no other text besides the variable
  524. # expansion in the input string.
  525. expand_to_list = '@' in match['type'] and input_str == replacement
  526. if run_command or file_list:
  527. # Find the build file's directory, so commands can be run or file lists
  528. # generated relative to it.
  529. build_file_dir = os.path.dirname(build_file)
  530. if build_file_dir == '':
  531. # If build_file is just a leaf filename indicating a file in the
  532. # current directory, build_file_dir might be an empty string. Set
  533. # it to None to signal to subprocess.Popen that it should run the
  534. # command in the current directory.
  535. build_file_dir = None
  536. # Support <|(listfile.txt ...) which generates a file
  537. # containing items from a gyp list, generated at gyp time.
  538. # This works around actions/rules which have more inputs than will
  539. # fit on the command line.
  540. if file_list:
  541. if type(contents) == list:
  542. contents_list = contents
  543. else:
  544. contents_list = contents.split(' ')
  545. replacement = contents_list[0]
  546. path = replacement
  547. if not os.path.isabs(path):
  548. path = os.path.join(build_file_dir, path)
  549. f = gyp.common.WriteOnDiff(path)
  550. for i in contents_list[1:]:
  551. f.write('%s\n' % i)
  552. f.close()
  553. elif run_command:
  554. use_shell = True
  555. if match['is_array']:
  556. contents = eval(contents)
  557. use_shell = False
  558. # Check for a cached value to avoid executing commands, or generating
  559. # file lists more than once.
  560. # TODO(http://code.google.com/p/gyp/issues/detail?id=112): It is
  561. # possible that the command being invoked depends on the current
  562. # directory. For that case the syntax needs to be extended so that the
  563. # directory is also used in cache_key (it becomes a tuple).
  564. # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory,
  565. # someone could author a set of GYP files where each time the command
  566. # is invoked it produces different output by design. When the need
  567. # arises, the syntax should be extended to support no caching off a
  568. # command's output so it is run every time.
  569. cache_key = str(contents)
  570. cached_value = cached_command_results.get(cache_key, None)
  571. if cached_value is None:
  572. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  573. "Executing command '%s' in directory '%s'" %
  574. (contents,build_file_dir))
  575. replacement = ''
  576. if command_string == 'pymod_do_main':
  577. # <!pymod_do_main(modulename param eters) loads |modulename| as a
  578. # python module and then calls that module's DoMain() function,
  579. # passing ["param", "eters"] as a single list argument. For modules
  580. # that don't load quickly, this can be faster than
  581. # <!(python modulename param eters). Do this in |build_file_dir|.
  582. oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir.
  583. os.chdir(build_file_dir)
  584. parsed_contents = shlex.split(contents)
  585. py_module = __import__(parsed_contents[0])
  586. replacement = str(py_module.DoMain(parsed_contents[1:])).rstrip()
  587. os.chdir(oldwd)
  588. assert replacement != None
  589. elif command_string:
  590. raise Exception("Unknown command string '%s' in '%s'." %
  591. (command_string, contents))
  592. else:
  593. # Fix up command with platform specific workarounds.
  594. contents = FixupPlatformCommand(contents)
  595. p = subprocess.Popen(contents, shell=use_shell,
  596. stdout=subprocess.PIPE,
  597. stderr=subprocess.PIPE,
  598. stdin=subprocess.PIPE,
  599. cwd=build_file_dir)
  600. p_stdout, p_stderr = p.communicate('')
  601. if p.wait() != 0 or p_stderr:
  602. sys.stderr.write(p_stderr)
  603. # Simulate check_call behavior, since check_call only exists
  604. # in python 2.5 and later.
  605. raise Exception("Call to '%s' returned exit status %d." %
  606. (contents, p.returncode))
  607. replacement = p_stdout.rstrip()
  608. cached_command_results[cache_key] = replacement
  609. else:
  610. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  611. "Had cache value for command '%s' in directory '%s'" %
  612. (contents,build_file_dir))
  613. replacement = cached_value
  614. else:
  615. if not contents in variables:
  616. if contents[-1] in ['!', '/']:
  617. # In order to allow cross-compiles (nacl) to happen more naturally,
  618. # we will allow references to >(sources/) etc. to resolve to
  619. # and empty list if undefined. This allows actions to:
  620. # 'action!': [
  621. # '>@(_sources!)',
  622. # ],
  623. # 'action/': [
  624. # '>@(_sources/)',
  625. # ],
  626. replacement = []
  627. else:
  628. raise KeyError, 'Undefined variable ' + contents + \
  629. ' in ' + build_file
  630. else:
  631. replacement = variables[contents]
  632. if isinstance(replacement, list):
  633. for item in replacement:
  634. if (not contents[-1] == '/' and
  635. not isinstance(item, str) and not isinstance(item, int)):
  636. raise TypeError, 'Variable ' + contents + \
  637. ' must expand to a string or list of strings; ' + \
  638. 'list contains a ' + \
  639. item.__class__.__name__
  640. # Run through the list and handle variable expansions in it. Since
  641. # the list is guaranteed not to contain dicts, this won't do anything
  642. # with conditions sections.
  643. ProcessVariablesAndConditionsInList(replacement, phase, variables,
  644. build_file)
  645. elif not isinstance(replacement, str) and \
  646. not isinstance(replacement, int):
  647. raise TypeError, 'Variable ' + contents + \
  648. ' must expand to a string or list of strings; ' + \
  649. 'found a ' + replacement.__class__.__name__
  650. if expand_to_list:
  651. # Expanding in list context. It's guaranteed that there's only one
  652. # replacement to do in |input_str| and that it's this replacement. See
  653. # above.
  654. if isinstance(replacement, list):
  655. # If it's already a list, make a copy.
  656. output = replacement[:]
  657. else:
  658. # Split it the same way sh would split arguments.
  659. output = shlex.split(str(replacement))
  660. else:
  661. # Expanding in string context.
  662. encoded_replacement = ''
  663. if isinstance(replacement, list):
  664. # When expanding a list into string context, turn the list items
  665. # into a string in a way that will work with a subprocess call.
  666. #
  667. # TODO(mark): This isn't completely correct. This should
  668. # call a generator-provided function that observes the
  669. # proper list-to-argument quoting rules on a specific
  670. # platform instead of just calling the POSIX encoding
  671. # routine.
  672. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement)
  673. else:
  674. encoded_replacement = replacement
  675. output = output[:replace_start] + str(encoded_replacement) + \
  676. output[replace_end:]
  677. # Prepare for the next match iteration.
  678. input_str = output
  679. # Look for more matches now that we've replaced some, to deal with
  680. # expanding local variables (variables defined in the same
  681. # variables block as this one).
  682. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  683. "Found output %s, recursing." % repr(output))
  684. if isinstance(output, list):
  685. if output and isinstance(output[0], list):
  686. # Leave output alone if it's a list of lists.
  687. # We don't want such lists to be stringified.
  688. pass
  689. else:
  690. new_output = []
  691. for item in output:
  692. new_output.append(
  693. ExpandVariables(item, phase, variables, build_file))
  694. output = new_output
  695. else:
  696. output = ExpandVariables(output, phase, variables, build_file)
  697. # Convert all strings that are canonically-represented integers into integers.
  698. if isinstance(output, list):
  699. for index in xrange(0, len(output)):
  700. if IsStrCanonicalInt(output[index]):
  701. output[index] = int(output[index])
  702. elif IsStrCanonicalInt(output):
  703. output = int(output)
  704. return output
  705. def ProcessConditionsInDict(the_dict, phase, variables, build_file):
  706. # Process a 'conditions' or 'target_conditions' section in the_dict,
  707. # depending on phase.
  708. # early -> conditions
  709. # late -> target_conditions
  710. # latelate -> no conditions
  711. #
  712. # Each item in a conditions list consists of cond_expr, a string expression
  713. # evaluated as the condition, and true_dict, a dict that will be merged into
  714. # the_dict if cond_expr evaluates to true. Optionally, a third item,
  715. # false_dict, may be present. false_dict is merged into the_dict if
  716. # cond_expr evaluates to false.
  717. #
  718. # Any dict merged into the_dict will be recursively processed for nested
  719. # conditionals and other expansions, also according to phase, immediately
  720. # prior to being merged.
  721. if phase == PHASE_EARLY:
  722. conditions_key = 'conditions'
  723. elif phase == PHASE_LATE:
  724. conditions_key = 'target_conditions'
  725. elif phase == PHASE_LATELATE:
  726. return
  727. else:
  728. assert False
  729. if not conditions_key in the_dict:
  730. return
  731. conditions_list = the_dict[conditions_key]
  732. # Unhook the conditions list, it's no longer needed.
  733. del the_dict[conditions_key]
  734. for condition in conditions_list:
  735. if not isinstance(condition, list):
  736. raise TypeError, conditions_key + ' must be a list'
  737. if len(condition) != 2 and len(condition) != 3:
  738. # It's possible that condition[0] won't work in which case this
  739. # attempt will raise its own IndexError. That's probably fine.
  740. raise IndexError, conditions_key + ' ' + condition[0] + \
  741. ' must be length 2 or 3, not ' + str(len(condition))
  742. [cond_expr, true_dict] = condition[0:2]
  743. false_dict = None
  744. if len(condition) == 3:
  745. false_dict = condition[2]
  746. # Do expansions on the condition itself. Since the conditon can naturally
  747. # contain variable references without needing to resort to GYP expansion
  748. # syntax, this is of dubious value for variables, but someone might want to
  749. # use a command expansion directly inside a condition.
  750. cond_expr_expanded = ExpandVariables(cond_expr, phase, variables,
  751. build_file)
  752. if not isinstance(cond_expr_expanded, str) and \
  753. not isinstance(cond_expr_expanded, int):
  754. raise ValueError, \
  755. 'Variable expansion in this context permits str and int ' + \
  756. 'only, found ' + expanded.__class__.__name__
  757. try:
  758. ast_code = compile(cond_expr_expanded, '<string>', 'eval')
  759. if eval(ast_code, {'__builtins__': None}, variables):
  760. merge_dict = true_dict
  761. else:
  762. merge_dict = false_dict
  763. except SyntaxError, e:
  764. syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s '
  765. 'at character %d.' %
  766. (str(e.args[0]), e.text, build_file, e.offset),
  767. e.filename, e.lineno, e.offset, e.text)
  768. raise syntax_error
  769. except NameError, e:
  770. gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' %
  771. (cond_expr_expanded, build_file))
  772. raise
  773. if merge_dict != None:
  774. # Expand variables and nested conditinals in the merge_dict before
  775. # merging it.
  776. ProcessVariablesAndConditionsInDict(merge_dict, phase,
  777. variables, build_file)
  778. MergeDicts(the_dict, merge_dict, build_file, build_file)
  779. def LoadAutomaticVariablesFromDict(variables, the_dict):
  780. # Any keys with plain string values in the_dict become automatic variables.
  781. # The variable name is the key name with a "_" character prepended.
  782. for key, value in the_dict.iteritems():
  783. if isinstance(value, str) or isinstance(value, int) or \
  784. isinstance(value, list):
  785. variables['_' + key] = value
  786. def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key):
  787. # Any keys in the_dict's "variables" dict, if it has one, becomes a
  788. # variable. The variable name is the key name in the "variables" dict.
  789. # Variables that end with the % character are set only if they are unset in
  790. # the variables dict. the_dict_key is the name of the key that accesses
  791. # the_dict in the_dict's parent dict. If the_dict's parent is not a dict
  792. # (it could be a list or it could be parentless because it is a root dict),
  793. # the_dict_key will be None.
  794. for key, value in the_dict.get('variables', {}).iteritems():
  795. if not isinstance(value, str) and not isinstance(value, int) and \
  796. not isinstance(value, list):
  797. continue
  798. if key.endswith('%'):
  799. variable_name = key[:-1]
  800. if variable_name in variables:
  801. # If the variable is already set, don't set it.
  802. continue
  803. if the_dict_key is 'variables' and variable_name in the_dict:
  804. # If the variable is set without a % in the_dict, and the_dict is a
  805. # variables dict (making |variables| a varaibles sub-dict of a
  806. # variables dict), use the_dict's definition.
  807. value = the_dict[variable_name]
  808. else:
  809. variable_name = key
  810. variables[variable_name] = value
  811. def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in,
  812. build_file, the_dict_key=None):
  813. """Handle all variable and command expansion and conditional evaluation.
  814. This function is the public entry point for all variable expansions and
  815. conditional evaluations. The variables_in dictionary will not be modified
  816. by this function.
  817. """
  818. # Make a copy of the variables_in dict that can be modified during the
  819. # loading of automatics and the loading of the variables dict.
  820. variables = variables_in.copy()
  821. LoadAutomaticVariablesFromDict(variables, the_dict)
  822. if 'variables' in the_dict:
  823. # Make sure all the local variables are added to the variables
  824. # list before we process them so that you can reference one
  825. # variable from another. They will be fully expanded by recursion
  826. # in ExpandVariables.
  827. for key, value in the_dict['variables'].iteritems():
  828. variables[key] = value
  829. # Handle the associated variables dict first, so that any variable
  830. # references within can be resolved prior to using them as variables.
  831. # Pass a copy of the variables dict to avoid having it be tainted.
  832. # Otherwise, it would have extra automatics added for everything that
  833. # should just be an ordinary variable in this scope.
  834. ProcessVariablesAndConditionsInDict(the_dict['variables'], phase,
  835. variables, build_file, 'variables')
  836. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  837. for key, value in the_dict.iteritems():
  838. # Skip "variables", which was already processed if present.
  839. if key != 'variables' and isinstance(value, str):
  840. expanded = ExpandVariables(value, phase, variables, build_file)
  841. if not isinstance(expanded, str) and not isinstance(expanded, int):
  842. raise ValueError, \
  843. 'Variable expansion in this context permits str and int ' + \
  844. 'only, found ' + expanded.__class__.__name__ + ' for ' + key
  845. the_dict[key] = expanded
  846. # Variable expansion may have resulted in changes to automatics. Reload.
  847. # TODO(mark): Optimization: only reload if no changes were made.
  848. variables = variables_in.copy()
  849. LoadAutomaticVariablesFromDict(variables, the_dict)
  850. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  851. # Process conditions in this dict. This is done after variable expansion
  852. # so that conditions may take advantage of expanded variables. For example,
  853. # if the_dict contains:
  854. # {'type': '<(library_type)',
  855. # 'conditions': [['_type=="static_library"', { ... }]]},
  856. # _type, as used in the condition, will only be set to the value of
  857. # library_type if variable expansion is performed before condition
  858. # processing. However, condition processing should occur prior to recursion
  859. # so that variables (both automatic and "variables" dict type) may be
  860. # adjusted by conditions sections, merged into the_dict, and have the
  861. # intended impact on contained dicts.
  862. #
  863. # This arrangement means that a "conditions" section containing a "variables"
  864. # section will only have those variables effective in subdicts, not in
  865. # the_dict. The workaround is to put a "conditions" section within a
  866. # "variables" section. For example:
  867. # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]],
  868. # 'defines': ['<(define)'],
  869. # 'my_subdict': {'defines': ['<(define)']}},
  870. # will not result in "IS_MAC" being appended to the "defines" list in the
  871. # current scope but would result in it being appended to the "defines" list
  872. # within "my_subdict". By comparison:
  873. # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]},
  874. # 'defines': ['<(define)'],
  875. # 'my_subdict': {'defines': ['<(define)']}},
  876. # will append "IS_MAC" to both "defines" lists.
  877. # Evaluate conditions sections, allowing variable expansions within them
  878. # as well as nested conditionals. This will process a 'conditions' or
  879. # 'target_conditions' section, perform appropriate merging and recursive
  880. # conditional and variable processing, and then remove the conditions section
  881. # from the_dict if it is present.
  882. ProcessConditionsInDict(the_dict, phase, variables, build_file)
  883. # Conditional processing may have resulted in changes to automatics or the
  884. # variables dict. Reload.
  885. variables = variables_in.copy()
  886. LoadAutomaticVariablesFromDict(variables, the_dict)
  887. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  888. # Recurse into child dicts, or process child lists which may result in
  889. # further recursion into descendant dicts.
  890. for key, value in the_dict.iteritems():
  891. # Skip "variables" and string values, which were already processed if
  892. # present.
  893. if key == 'variables' or isinstance(value, str):
  894. continue
  895. if isinstance(value, dict):
  896. # Pass a copy of the variables dict so that subdicts can't influence
  897. # parents.
  898. ProcessVariablesAndConditionsInDict(value, phase, variables,
  899. build_file, key)
  900. elif isinstance(value, list):
  901. # The list itself can't influence the variables dict, and
  902. # ProcessVariablesAndConditionsInList will make copies of the variables
  903. # dict if it needs to pass it to something that can influence it. No
  904. # copy is necessary here.
  905. ProcessVariablesAndConditionsInList(value, phase, variables,
  906. build_file)
  907. elif not isinstance(value, int):
  908. raise TypeError, 'Unknown type ' + value.__class__.__name__ + \
  909. ' for ' + key
  910. def ProcessVariablesAndConditionsInList(the_list, phase, variables,
  911. build_file):
  912. # Iterate using an index so that new values can be assigned into the_list.
  913. index = 0
  914. while index < len(the_list):
  915. item = the_list[index]
  916. if isinstance(item, dict):
  917. # Make a copy of the variables dict so that it won't influence anything
  918. # outside of its own scope.
  919. ProcessVariablesAndConditionsInDict(item, phase, variables, build_file)
  920. elif isinstance(item, list):
  921. ProcessVariablesAndConditionsInList(item, phase, variables, build_file)
  922. elif isinstance(item, str):
  923. expanded = ExpandVariables(item, phase, variables, build_file)
  924. if isinstance(expanded, str) or isinstance(expanded, int):
  925. the_list[index] = expanded
  926. elif isinstance(expanded, list):
  927. the_list[index:index+1] = expanded
  928. index += len(expanded)
  929. # index now identifies the next item to examine. Continue right now
  930. # without falling into the index increment below.
  931. continue
  932. else:
  933. raise ValueError, \
  934. 'Variable expansion in this context permits strings and ' + \
  935. 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \
  936. index
  937. elif not isinstance(item, int):
  938. raise TypeError, 'Unknown type ' + item.__class__.__name__ + \
  939. ' at index ' + index
  940. index = index + 1
  941. def BuildTargetsDict(data):
  942. """Builds a dict mapping fully-qualified target names to their target dicts.
  943. |data| is a dict mapping loaded build files by pathname relative to the
  944. current directory. Values in |data| are build file contents. For each
  945. |data| value with a "targets" key, the value of the "targets" key is taken
  946. as a list containing target dicts. Each target's fully-qualified name is
  947. constructed from the pathname of the build file (|data| key) and its
  948. "target_name" property. These fully-qualified names are used as the keys
  949. in the returned dict. These keys provide access to the target dicts,
  950. the dicts in the "targets" lists.
  951. """
  952. targets = {}
  953. for build_file in data['target_build_files']:
  954. for target in data[build_file].get('targets', []):
  955. target_name = gyp.common.QualifiedTarget(build_file,
  956. target['target_name'],
  957. target['toolset'])
  958. if target_name in targets:
  959. raise KeyError, 'Duplicate target definitions for ' + target_name
  960. targets[target_name] = target
  961. return targets
  962. def QualifyDependencies(targets):
  963. """Make dependency links fully-qualified relative to the current directory.
  964. |targets| is a dict mapping fully-qualified target names to their target
  965. dicts. For each target in this dict, keys known to contain dependency
  966. links are examined, and any dependencies referenced will be rewritten
  967. so that they are fully-qualified and relative to the current directory.
  968. All rewritten dependencies are suitable for use as keys to |targets| or a
  969. similar dict.
  970. """
  971. all_dependency_sections = [dep + op
  972. for dep in dependency_sections
  973. for op in ('', '!', '/')]
  974. for target, target_dict in targets.iteritems():
  975. target_build_file = gyp.common.BuildFile(target)
  976. toolset = target_dict['toolset']
  977. for dependency_key in all_dependency_sections:
  978. dependencies = target_dict.get(dependency_key, [])
  979. for index in xrange(0, len(dependencies)):
  980. dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget(
  981. target_build_file, dependencies[index], toolset)
  982. if not multiple_toolsets:
  983. # Ignore toolset specification in the dependency if it is specified.
  984. dep_toolset = toolset
  985. dependency = gyp.common.QualifiedTarget(dep_file,
  986. dep_target,
  987. dep_toolset)
  988. dependencies[index] = dependency
  989. # Make sure anything appearing in a list other than "dependencies" also
  990. # appears in the "dependencies" list.
  991. if dependency_key != 'dependencies' and \
  992. dependency not in target_dict['dependencies']:
  993. raise KeyError, 'Found ' + dependency + ' in ' + dependency_key + \
  994. ' of ' + target + ', but not in dependencies'
  995. def ExpandWildcardDependencies(targets, data):
  996. """Expands dependencies specified as build_file:*.
  997. For each target in |targets|, examines sections containing links to other
  998. targets. If any such section contains a link of the form build_file:*, it
  999. is taken as a wildcard link, and is expanded to list each target in
  1000. build_file. The |data| dict provides access to build file dicts.
  1001. Any target that does not wish to be included by wildcard can provide an
  1002. optional "suppress_wildcard" key in its target dict. When present and
  1003. true, a wildcard dependency link will not include such targets.
  1004. All dependency names, including the keys to |targets| and the values in each
  1005. dependency list, must be qualified when this function is called.
  1006. """
  1007. for target, target_dict in targets.iteritems():
  1008. toolset = target_dict['toolset']
  1009. target_build_file = gyp.common.BuildFile(target)
  1010. for dependency_key in dependency_sections:
  1011. dependencies = target_dict.get(dependency_key, [])
  1012. # Loop this way instead of "for dependency in" or "for index in xrange"
  1013. # because the dependencies list will be modified within the loop body.
  1014. index = 0
  1015. while index < len(dependencies):
  1016. (dependency_build_file, dependency_target, dependency_toolset) = \
  1017. gyp.common.ParseQualifiedTarget(dependencies[index])
  1018. if dependency_target != '*' and dependency_toolset != '*':
  1019. # Not a wildcard. Keep it moving.
  1020. index = index + 1
  1021. continue
  1022. if dependency_build_file == target_build_file:
  1023. # It's an error for a target to depend on all other targets in
  1024. # the same file, because a target cannot depend on itself.
  1025. raise KeyError, 'Found wildcard in ' + dependency_key + ' of ' + \
  1026. target + ' referring to same build file'
  1027. # Take the wildcard out and adjust the index so that the next
  1028. # dependency in the list will be processed the next time through the
  1029. # loop.
  1030. del dependencies[index]
  1031. index = index - 1
  1032. # Loop through the targets in the other build file, adding them to
  1033. # this target's list of dependencies in place of the removed
  1034. # wildcard.
  1035. dependency_target_dicts = data[dependency_build_file]['targets']
  1036. for dependency_target_dict in dependency_target_dicts:
  1037. if int(dependency_target_dict.get('suppress_wildcard', False)):
  1038. continue
  1039. dependency_target_name = dependency_target_dict['target_name']
  1040. if (dependency_target != '*' and
  1041. dependency_target != dependency_target_name):
  1042. continue
  1043. dependency_target_toolset = dependency_target_dict['toolset']
  1044. if (dependency_toolset != '*' and
  1045. dependency_toolset != dependency_target_toolset):
  1046. continue
  1047. dependency = gyp.common.QualifiedTarget(dependency_build_file,
  1048. dependency_target_name,
  1049. dependency_target_toolset)
  1050. index = index + 1
  1051. dependencies.insert(index, dependency)
  1052. index = index + 1
  1053. def Unify(l):
  1054. """Removes duplicate elements from l, keeping the first element."""
  1055. seen = {}
  1056. return [seen.setdefault(e, e) for e in l if e not in seen]
  1057. def RemoveDuplicateDependencies(targets):
  1058. """Makes sure every dependency appears only once in all targets's dependency
  1059. lists."""
  1060. for target_name, target_dict in targets.iteritems():
  1061. for dependency_key in dependency_sections:
  1062. dependencies = target_dict.get(dependency_key, [])
  1063. if dependencies:
  1064. target_dict[dependency_key] = Unify(dependencies)
  1065. class DependencyGraphNode(object):
  1066. """
  1067. Attributes:
  1068. ref: A reference to an object that this DependencyGraphNode represents.
  1069. dependencies: List of DependencyGraphNodes on which this one depends.
  1070. dependents: List of DependencyGraphNodes that depend on this one.
  1071. """
  1072. class CircularException(Exception):
  1073. pass
  1074. def __init__(self, ref):
  1075. self.ref = ref
  1076. self.dependencies = []
  1077. self.dependents = []
  1078. def FlattenToList(self):
  1079. # flat_list is the sorted list of dependencies - actually, the list items
  1080. # are the "ref" attributes of DependencyGraphNodes. Every target will
  1081. # appear in flat_list after all of its dependencies, and before all of its
  1082. # dependents.
  1083. flat_list = []
  1084. # in_degree_zeros is the list of DependencyGraphNodes that have no
  1085. # dependencies not in flat_list. Initially, it is a copy of the children
  1086. # of this node, because when the graph was built, nodes with no
  1087. # dependencies were made implicit dependents of the root node.
  1088. in_degree_zeros = set(self.dependents[:])
  1089. while in_degree_zeros:
  1090. # Nodes in in_degree_zeros have no dependencies not in flat_list, so they
  1091. # can be appended to flat_list. Take these nodes out of in_degree_zeros
  1092. # as work progresses, so that the next node to process from the list can
  1093. # always be accessed at a consistent position.
  1094. node = in_degree_zeros.pop()
  1095. flat_list.append(node.ref)
  1096. # Look at dependents of the node just added to flat_list. Some of them
  1097. # may now belong in in_degree_zeros.
  1098. for node_dependent in node.dependents:
  1099. is_in_degree_zero = True
  1100. for node_dependent_dependency in node_dependent.dependencies:
  1101. if not node_dependent_dependency.ref in flat_list:
  1102. # The dependent one or more dependencies not in flat_list. There
  1103. # will be more chances to add it to flat_list when examining
  1104. # it again as a dependent of those other dependencies, provided
  1105. # that there are no cycles.
  1106. is_in_degree_zero = False
  1107. break
  1108. if is_in_degree_zero:
  1109. # All of the dependent's dependencies are already in flat_list. Add
  1110. # it to in_degree_zeros where it will be processed in a future
  1111. # iteration of the outer loop.
  1112. in_degree_zeros.add(node_dependent)
  1113. return flat_list
  1114. def DirectDependencies(self, dependencies=None):
  1115. """Returns a list of just direct dependencies."""
  1116. if dependencies == None:
  1117. dependencies = []
  1118. for dependency in self.dependencies:
  1119. # Check for None, corresponding to the root node.
  1120. if dependency.ref != None and dependency.ref not in dependencies:
  1121. dependencies.append(dependency.ref)
  1122. return dependencies
  1123. def _AddImportedDependencies(self, targets, dependencies=None):
  1124. """Given a list of direct dependencies, adds indirect dependencies that
  1125. other dependencies have declared to export their settings.
  1126. This method does not operate on self. Rather, it operates on the list
  1127. of dependencies in the |dependencies| argument. For each dependency in
  1128. that list, if any declares that it exports the settings of one of its
  1129. own dependencies, those dependencies whose settings are "passed through"
  1130. are added to the list. As new items are added to the list, they too will
  1131. be processed, so it is possible to import settings through multiple levels
  1132. of dependencies.
  1133. This method is not terribly useful on its own, it depends on being
  1134. "primed" with a list of direct dependencies such as one provided by
  1135. DirectDependencies. DirectAndImportedDependencies is intended to be the
  1136. public entry point.
  1137. """
  1138. if dependencies == None:
  1139. dependencies = []
  1140. index = 0
  1141. while index < len(dependencies):
  1142. dependency = dependencies[index]
  1143. dependency_dict = targets[dependency]
  1144. # Add any dependencies whose settings should be imported to the list
  1145. # if not already present. Newly-added items will be checked for
  1146. # their own imports when the list iteration reaches them.
  1147. # Rather than simply appending new items, insert them after the
  1148. # dependency that exported them. This is done to more closely match
  1149. # the depth-first method used by DeepDependencies.
  1150. add_index = 1
  1151. for imported_dependency in \
  1152. dependency_dict.get('export_dependent_settings', []):
  1153. if imported_dependency not in dependencies:
  1154. dependencies.insert(index + add_index, imported_dependency)
  1155. add_index = add_index + 1
  1156. index = index + 1
  1157. return dependencies
  1158. def DirectAndImportedDependencies(self, targets, dependencies=None):
  1159. """Returns a list of a target's direct dependencies and all indirect
  1160. dependencies that a dependency has advertised settings should be exported
  1161. through the dependency for.
  1162. """
  1163. dependencies = self.DirectDependencies(dependencies)
  1164. return self._AddImportedDependencies(targets, dependencies)
  1165. def DeepDependencies(self, dependencies=None):
  1166. """Returns a list of all of a target's dependencies, recursively."""
  1167. if dependencies == None:
  1168. dependencies = []
  1169. for dependency in self.dependencies:
  1170. # Check for None, corresponding to the root node.
  1171. if dependency.ref != None and dependency.ref not in dependencies:
  1172. dependencies.append(dependency.ref)
  1173. dependency.DeepDependencies(dependencies)
  1174. return dependencies
  1175. def LinkDependencies(self, targets, dependencies=None, initial=True):
  1176. """Returns a list of dependency targets that are linked into this target.
  1177. This function has a split personality, depending on the setting of
  1178. |initial|. Outside callers should always leave |initial| at its default
  1179. setting.
  1180. When adding a target to the list of dependencies, this function will
  1181. recurse into itself with |initial| set to False, to collect dependencies
  1182. that are linked into the linkable target for which the list is being built.
  1183. """
  1184. if dependencies == None:
  1185. dependencies = []
  1186. # Check for None, corresponding to the root node.
  1187. if self.ref == None:
  1188. return dependencies
  1189. # It's kind of sucky that |targets| has to be passed into this function,
  1190. # but that's presently the easiest way to access the target dicts so that
  1191. # this function can find target types.
  1192. if not 'target_name' in targets[self.ref]:
  1193. raise Exception("Missing 'target_name' field in target.")
  1194. try:
  1195. target_type = targets[self.ref]['type']
  1196. except KeyError, e:
  1197. raise Exception("Missing 'type' field in target %s" %
  1198. targets[self.ref]['target_name'])
  1199. is_linkable = target_type in linkable_types
  1200. if initial and not is_linkable:
  1201. # If this is the first target being examined and it's not linkable,
  1202. # return an empty list of link dependencies, because the link
  1203. # dependencies are intended to apply to the target itself (initial is
  1204. # True) and this target won't be linked.
  1205. return dependencies
  1206. # Don't traverse 'none' targets if explicitly excluded.
  1207. if (target_type == 'none' and
  1208. not targets[self.ref].get('dependencies_traverse', True)):
  1209. if self.ref not in dependencies:
  1210. dependencies.append(self.ref)
  1211. return dependencies
  1212. # Executables and loadable modules are already fully and finally linked.
  1213. # Nothing else can be a link dependency of them, there can only be
  1214. # dependencies in the sense that a dependent target might run an
  1215. # executable or load the loadable_module.
  1216. if not initial and target_type in ('executable', 'loadable_module'):
  1217. return dependencies
  1218. # The target is linkable, add it to the list of link dependencies.
  1219. if self.ref not in dependencies:
  1220. dependencies.append(self.ref)
  1221. if initial or not is_linkable:
  1222. # If this is a subsequent target and it's linkable, don't look any
  1223. # further for linkable dependencies, as they'll already be linked into
  1224. # this target linkable. Always look at dependencies of the initial
  1225. # target, and always look at dependencies of non-linkables.
  1226. for dependency in self.dependencies:
  1227. dependency.LinkDependencies(targets, dependencies, False)
  1228. return dependencies
  1229. def BuildDependencyList(targets):
  1230. # Create a DependencyGraphNode for each target. Put it into a dict for easy
  1231. # access.
  1232. dependency_nodes = {}
  1233. for target, spec in targets.iteritems():
  1234. if not target in dependency_nodes:
  1235. dependency_nodes[target] = DependencyGraphNode(target)
  1236. # Set up the dependency links. Targets that have no dependencies are treated
  1237. # as dependent on root_node.
  1238. root_node = DependencyGraphNode(None)
  1239. for target, spec in targets.iteritems():
  1240. target_node = dependency_nodes[target]
  1241. target_build_file = gyp.common.BuildFile(target)
  1242. if not 'dependencies' in spec or len(spec['dependencies']) == 0:
  1243. target_node.dependencies = [root_node]
  1244. root_node.dependents.append(target_node)
  1245. else:
  1246. dependencies = spec['dependencies']
  1247. for index in xrange(0, len(dependencies)):
  1248. try:
  1249. dependency = dependencies[index]
  1250. dependency_node = dependency_nodes[dependency]
  1251. target_node.dependencies.append(dependency_node)
  1252. dependency_node.dependents.append(target_node)
  1253. except KeyError, e:
  1254. gyp.common.ExceptionAppend(e,
  1255. 'while trying to load target %s' % target)
  1256. raise
  1257. flat_list = root_node.FlattenToList()
  1258. # If there's anything left unvisited, there must be a circular dependency
  1259. # (cycle). If you need to figure out what's wrong, look for elements of
  1260. # targets that are not in flat_list.
  1261. if len(flat_list) != len(targets):
  1262. raise DependencyGraphNode.CircularException, \
  1263. 'Some targets not reachable, cycle in dependency graph detected: ' + \
  1264. ' '.join(set(flat_list) ^ set(targets))
  1265. return [dependency_nodes, flat_list]
  1266. def VerifyNoGYPFileCircularDependencies(targets):
  1267. # Create a DependencyGraphNode for each gyp file containing a target. Put
  1268. # it into a dict for easy access.
  1269. dependency_nodes = {}
  1270. for target in targets.iterkeys():
  1271. build_file = gyp.common.BuildFile(target)
  1272. if not build_file in dependency_nodes:
  1273. dependency_nodes[build_file] = DependencyGraphNode(build_file)
  1274. # Set up the dependency links.
  1275. for target, spec in targets.iteritems():
  1276. build_file = gyp.common.BuildFile(target)
  1277. build_file_node = dependency_nodes[build_file]
  1278. target_dependencies = spec.get('dependencies', [])
  1279. for dependency in target_dependencies:
  1280. try:
  1281. dependency_build_file = gyp.common.BuildFile(dependency)
  1282. if dependency_build_file == build_file:
  1283. # A .gyp file is allowed to refer back to itself.
  1284. continue
  1285. dependency_node = dependency_nodes[dependency_build_file]
  1286. if dependency_node not in build_file_node.dependencies:
  1287. build_file_node.dependencies.append(dependency_node)
  1288. dependency_node.dependents.append(build_file_node)
  1289. except KeyError, e:
  1290. gyp.common.ExceptionAppend(
  1291. e, 'while computing dependencies of .gyp file %s' % build_file)
  1292. raise
  1293. # Files that have no dependencies are treated as dependent on root_node.
  1294. root_node = DependencyGraphNode(None)
  1295. for build_file_node in dependency_nodes.itervalues():
  1296. if len(build_file_node.dependencies) == 0:
  1297. build_file_node.dependencies.append(root_node)
  1298. root_node.dependents.append(build_file_node)
  1299. flat_list = root_node.FlattenToList()
  1300. # If there's anything left unvisited, there must be a circular dependency
  1301. # (cycle).
  1302. if len(flat_list) != len(dependency_nodes):
  1303. bad_files = []
  1304. for file in dependency_nodes.iterkeys():
  1305. if not file in flat_list:
  1306. bad_files.append(file)
  1307. raise DependencyGraphNode.CircularException, \
  1308. 'Some files not reachable, cycle in .gyp file dependency graph ' + \
  1309. 'detected involving some or all of: ' + \
  1310. ' '.join(bad_files)
  1311. def DoDependentSettings(key, flat_list, targets, dependency_nodes):
  1312. # key should be one of all_dependent_settings, direct_dependent_settings,
  1313. # or link_settings.
  1314. for target in flat_list:
  1315. target_dict = targets[target]
  1316. build_file = gyp.common.BuildFile(target)
  1317. if key == 'all_dependent_settings':
  1318. dependencies = dependency_nodes[target].DeepDependencies()
  1319. elif key == 'direct_dependent_settings':
  1320. dependencies = \
  1321. dependency_nodes[target].DirectAndImportedDependencies(targets)
  1322. elif key == 'link_settings':
  1323. dependencies = dependency_nodes[target].LinkDependencies(targets)
  1324. else:
  1325. raise KeyError, "DoDependentSettings doesn't know how to determine " + \
  1326. 'dependencies for ' + key
  1327. for dependency in dependencies:
  1328. dependency_dict = targets[dependency]
  1329. if not key in dependency_dict:
  1330. continue
  1331. dependency_build_file = gyp.common.BuildFile(dependency)
  1332. MergeDicts(target_dict, dependency_dict[key],
  1333. build_file, dependency_build_file)
  1334. def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes,
  1335. sort_dependencies):
  1336. # Recompute target "dependencies" properties. For each static library
  1337. # target, remove "dependencies" entries referring to other static libraries,
  1338. # unless the dependency has the "hard_dependency" attribute set. For each
  1339. # linkable target, add a "dependencies" entry referring to all of the
  1340. # target's computed list of link dependencies (including static libraries
  1341. # if no such entry is already present.
  1342. for target in flat_list:
  1343. target_dict = targets[target]
  1344. target_type = target_dict['type']
  1345. if target_type == 'static_library':
  1346. if not 'dependencies' in target_dict:
  1347. continue
  1348. target_dict['dependencies_original'] = target_dict.get(
  1349. 'dependencies', [])[:]
  1350. # A static library should not depend on another static library unless
  1351. # the dependency relationship is "hard," which should only be done when
  1352. # a dependent relies on some side effect other than just the build
  1353. # product, like a rule or action output. Further, if a target has a
  1354. # non-hard dependency, but that dependency exports a hard dependency,
  1355. # the non-hard dependency can safely be removed, but the exported hard
  1356. # dependency must be added to the target to keep the same dependency
  1357. # ordering.
  1358. dependencies = \
  1359. dependency_nodes[target].DirectAndImportedDependencies(targets)
  1360. index = 0
  1361. while index < len(dependencies):
  1362. dependency = dependencies[index]
  1363. dependency_dict = targets[dependency]
  1364. # Remove every non-hard static library dependency and remove every
  1365. # non-static library dependency that isn't a direct dependency.
  1366. if (dependency_dict['type'] == 'static_library' and \
  1367. not dependency_dict.get('hard_dependency', False)) or \
  1368. (dependency_dict['type'] != 'static_library' and \
  1369. not dependency in target_dict['dependencies']):
  1370. # Take the dependency out of the list, and don't increment index
  1371. # because the next dependency to analyze will shift into the index
  1372. # formerly occupied by the one being removed.
  1373. del dependencies[index]
  1374. else:
  1375. index = index + 1
  1376. # Update the dependencies. If the dependencies list is empty, it's not
  1377. # needed, so unhook it.
  1378. if len(dependencies) > 0:
  1379. target_dict['dependencies'] = dependencies
  1380. else:
  1381. del target_dict['dependencies']
  1382. elif target_type in linkable_types:
  1383. # Get a list of dependency targets that should be linked into this
  1384. # target. Add them to the dependencies list if they're not already
  1385. # present.
  1386. link_dependencies = dependency_nodes[target].LinkDependencies(targets)
  1387. for dependency in link_dependencies:
  1388. if dependency == target:
  1389. continue
  1390. if not 'dependencies' in target_dict:
  1391. target_dict['dependencies'] = []
  1392. if not dependency in target_dict['dependencies']:
  1393. target_dict['dependencies'].append(dependency)
  1394. # Sort the dependencies list in the order from dependents to dependencies.
  1395. # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D.
  1396. # Note: flat_list is already sorted in the order from dependencies to
  1397. # dependents.
  1398. if sort_dependencies and 'dependencies' in target_dict:
  1399. target_dict['dependencies'] = [dep for dep in reversed(flat_list)
  1400. if dep in target_dict['dependencies']]
  1401. # Initialize this here to speed up MakePathRelative.
  1402. exception_re = re.compile(r'''["']?[-/$<>^]''')
  1403. def MakePathRelative(to_file, fro_file, item):
  1404. # If item is a relative path, it's relative to the build file dict that it's
  1405. # coming from. Fix it up to make it relative to the build file dict that
  1406. # it's going into.
  1407. # Exception: any |item| that begins with these special characters is
  1408. # returned without modification.
  1409. # / Used when a path is already absolute (shortcut optimization;
  1410. # such paths would be returned as absolute anyway)
  1411. # $ Used for build environment variables
  1412. # - Used for some build environment flags (such as -lapr-1 in a
  1413. # "libraries" section)
  1414. # < Used for our own variable and command expansions (see ExpandVariables)
  1415. # > Used for our own variable and command expansions (see ExpandVariables)
  1416. # ^ Used for our own variable and command expansions (see ExpandVariables)
  1417. #
  1418. # "/' Used when a value is quoted. If these are present, then we
  1419. # check the second character instead.
  1420. #
  1421. if to_file == fro_file or exception_re.match(item):
  1422. return item
  1423. else:
  1424. # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
  1425. # temporary measure. This should really be addressed by keeping all paths
  1426. # in POSIX until actual project generation.
  1427. ret = os.path.normpath(os.path.join(
  1428. gyp.common.RelativePath(os.path.dirname(fro_file),
  1429. os.path.dirname(to_file)),
  1430. item)).replace('\\', '/')
  1431. if item[-1] == '/':
  1432. ret += '/'
  1433. return ret
  1434. def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True):
  1435. def is_hashable(x):
  1436. try:
  1437. hash(x)
  1438. except TypeError:
  1439. return False
  1440. return True
  1441. # If x is hashable, returns whether x is in s. Else returns whether x is in l.
  1442. def is_in_set_or_list(x, s, l):
  1443. if is_hashable(x):
  1444. return x in s
  1445. return x in l
  1446. prepend_index = 0
  1447. # Make membership testing of hashables in |to| (in particular, strings)
  1448. # faster.
  1449. hashable_to_set = set([x for x in to if is_hashable(x)])
  1450. for item in fro:
  1451. singleton = False
  1452. if isinstance(item, str) or isinstance(item, int):
  1453. # The cheap and easy case.
  1454. if is_paths:
  1455. to_item = MakePathRelative(to_file, fro_file, item)
  1456. else:
  1457. to_item = item
  1458. if not isinstance(item, str) or not item.startswith('-'):
  1459. # Any string that doesn't begin with a "-" is a singleton - it can
  1460. # only appear once in a list, to be enforced by the list merge append
  1461. # or prepend.
  1462. singleton = True
  1463. elif isinstance(item, dict):
  1464. # Make a copy of the dictionary, continuing to look for paths to fix.
  1465. # The other intelligent aspects of merge processing won't apply because
  1466. # item is being merged into an empty dict.
  1467. to_item = {}
  1468. MergeDicts(to_item, item, to_file, fro_file)
  1469. elif isinstance(item, list):
  1470. # Recurse, making a copy of the list. If the list contains any
  1471. # descendant dicts, path fixing will occur. Note that here, custom
  1472. # values for is_paths and append are dropped; those are only to be
  1473. # applied to |to| and |fro|, not sublists of |fro|. append shouldn't
  1474. # matter anyway because the new |to_item| list is empty.
  1475. to_item = []
  1476. MergeLists(to_item, item, to_file, fro_file)
  1477. else:
  1478. raise TypeError, \
  1479. 'Attempt to merge list item of unsupported type ' + \
  1480. item.__class__.__name__
  1481. if append:
  1482. # If appending a singleton that's already in the list, don't append.
  1483. # This ensures that the earliest occurrence of the item will stay put.
  1484. if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to):
  1485. to.append(to_item)
  1486. if is_hashable(to_item):
  1487. hashable_to_set.add(to_item)
  1488. else:
  1489. # If prepending a singleton that's already in the list, remove the
  1490. # existing instance and proceed with the prepend. This ensures that the
  1491. # item appears at the earliest possible position in the list.
  1492. while singleton and to_item in to:
  1493. to.remove(to_item)
  1494. # Don't just insert everything at index 0. That would prepend the new
  1495. # items to the list in reverse order, which would be an unwelcome
  1496. # surprise.
  1497. to.insert(prepend_index, to_item)
  1498. if is_hashable(to_item):
  1499. hashable_to_set.add(to_item)
  1500. prepend_index = prepend_index + 1
  1501. def MergeDicts(to, fro, to_file, fro_file):
  1502. # I wanted to name the parameter "from" but it's a Python keyword...
  1503. for k, v in fro.iteritems():
  1504. # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give
  1505. # copy semantics. Something else may want to merge from the |fro| dict
  1506. # later, and having the same dict ref pointed to twice in the tree isn't
  1507. # what anyone wants considering that the dicts may subsequently be
  1508. # modified.
  1509. if k in to:
  1510. bad_merge = False
  1511. if isinstance(v, str) or isinstance(v, int):
  1512. if not (isinstance(to[k], str) or isinstance(to[k], int)):
  1513. bad_merge = True
  1514. elif v.__class__ != to[k].__class__:
  1515. bad_merge = True
  1516. if bad_merge:
  1517. raise TypeError, \
  1518. 'Attempt to merge dict value of type ' + v.__class__.__name__ + \
  1519. ' into incompatible type ' + to[k].__class__.__name__ + \
  1520. ' for key ' + k
  1521. if isinstance(v, str) or isinstance(v, int):
  1522. # Overwrite the existing value, if any. Cheap and easy.
  1523. is_path = IsPathSection(k)
  1524. if is_path:
  1525. to[k] = MakePathRelative(to_file, fro_file, v)
  1526. else:
  1527. to[k] = v
  1528. elif isinstance(v, dict):
  1529. # Recurse, guaranteeing copies will be made of objects that require it.
  1530. if not k in to:
  1531. to[k] = {}
  1532. MergeDicts(to[k], v, to_file, fro_file)
  1533. elif isinstance(v, list):
  1534. # Lists in dicts can be merged with different policies, depending on
  1535. # how the key in the "from" dict (k, the from-key) is written.
  1536. #
  1537. # If the from-key has ...the to-list will have this action
  1538. # this character appended:... applied when receiving the from-list:
  1539. # = replace
  1540. # + prepend
  1541. # ? set, only if to-list does not yet exist
  1542. # (none) append
  1543. #
  1544. # This logic is list-specific, but since it relies on the associated
  1545. # dict key, it's checked in this dict-oriented function.
  1546. ext = k[-1]
  1547. append = True
  1548. if ext == '=':
  1549. list_base = k[:-1]
  1550. lists_incompatible = [list_base, list_base + '?']
  1551. to[list_base] = []
  1552. elif ext == '+':
  1553. list_base = k[:-1]
  1554. lists_incompatible = [list_base + '=', list_base + '?']
  1555. append = False
  1556. elif ext == '?':
  1557. list_base = k[:-1]
  1558. lists_incompatible = [list_base, list_base + '=', list_base + '+']
  1559. else:
  1560. list_base = k
  1561. lists_incompatible = [list_base + '=', list_base + '?']
  1562. # Some combinations of merge policies appearing together are meaningless.
  1563. # It's stupid to replace and append simultaneously, for example. Append
  1564. # and prepend are the only policies that can coexist.
  1565. for list_incompatible in lists_incompatible:
  1566. if list_incompatible in fro:
  1567. raise KeyError, 'Incompatible list policies ' + k + ' and ' + \
  1568. list_incompatible
  1569. if list_base in to:
  1570. if ext == '?':
  1571. # If the key ends in "?", the list will only be merged if it doesn't
  1572. # already exist.
  1573. continue
  1574. if not isinstance(to[list_base], list):
  1575. # This may not have been checked above if merging in a list with an
  1576. # extension character.
  1577. raise TypeError, \
  1578. 'Attempt to merge dict value of type ' + v.__class__.__name__ + \
  1579. ' into incompatible type ' + to[list_base].__class__.__name__ + \
  1580. ' for key ' + list_base + '(' + k + ')'
  1581. else:
  1582. to[list_base] = []
  1583. # Call MergeLists, which will make copies of objects that require it.
  1584. # MergeLists can recurse back into MergeDicts, although this will be
  1585. # to make copies of dicts (with paths fixed), there will be no
  1586. # subsequent dict "merging" once entering a list because lists are
  1587. # always replaced, appended to, or prepended to.
  1588. is_paths = IsPathSection(list_base)
  1589. MergeLists(to[list_base], v, to_file, fro_file, is_paths, append)
  1590. else:
  1591. raise TypeError, \
  1592. 'Attempt to merge dict value of unsupported type ' + \
  1593. v.__class__.__name__ + ' for key ' + k
  1594. def MergeConfigWithInheritance(new_configuration_dict, build_file,
  1595. target_dict, configuration, visited):
  1596. # Skip if previously visted.
  1597. if configuration in visited:
  1598. return
  1599. # Look at this configuration.
  1600. configuration_dict = target_dict['configurations'][configuration]
  1601. # Merge in parents.
  1602. for parent in configuration_dict.get('inherit_from', []):
  1603. MergeConfigWithInheritance(new_configuration_dict, build_file,
  1604. target_dict, parent, visited + [configuration])
  1605. # Merge it into the new config.
  1606. MergeDicts(new_configuration_dict, configuration_dict,
  1607. build_file, build_file)
  1608. # Drop abstract.
  1609. if 'abstract' in new_configuration_dict:
  1610. del new_configuration_dict['abstract']
  1611. def SetUpConfigurations(target, target_dict):
  1612. # key_suffixes is a list of key suffixes that might appear on key names.
  1613. # These suffixes are handled in conditional evaluations (for =, +, and ?)
  1614. # and rules/exclude processing (for ! and /). Keys with these suffixes
  1615. # should be treated the same as keys without.
  1616. key_suffixes = ['=', '+', '?', '!', '/']
  1617. build_file = gyp.common.BuildFile(target)
  1618. # Provide a single configuration by default if none exists.
  1619. # TODO(mark): Signal an error if default_configurations exists but
  1620. # configurations does not.
  1621. if not 'configurations' in target_dict:
  1622. target_dict['configurations'] = {'Default': {}}
  1623. if not 'default_configuration' in target_dict:
  1624. concrete = [i for i in target_dict['configurations'].keys()
  1625. if not target_dict['configurations'][i].get('abstract')]
  1626. target_dict['default_configuration'] = sorted(concrete)[0]
  1627. for configuration in target_dict['configurations'].keys():
  1628. old_configuration_dict = target_dict['configurations'][configuration]
  1629. # Skip abstract configurations (saves work only).
  1630. if old_configuration_dict.get('abstract'):
  1631. continue
  1632. # Configurations inherit (most) settings from the enclosing target scope.
  1633. # Get the inheritance relationship right by making a copy of the target
  1634. # dict.
  1635. new_configuration_dict = copy.deepcopy(target_dict)
  1636. # Take out the bits that don't belong in a "configurations" section.
  1637. # Since configuration setup is done before conditional, exclude, and rules
  1638. # processing, be careful with handling of the suffix characters used in
  1639. # those phases.
  1640. delete_keys = []
  1641. for key in new_configuration_dict:
  1642. key_ext = key[-1:]
  1643. if key_ext in key_suffixes:
  1644. key_base = key[:-1]
  1645. else:
  1646. key_base = key
  1647. if key_base in non_configuration_keys:
  1648. delete_keys.append(key)
  1649. for key in delete_keys:
  1650. del new_configuration_dict[key]
  1651. # Merge in configuration (with all its parents first).
  1652. MergeConfigWithInheritance(new_configuration_dict, build_file,
  1653. target_dict, configuration, [])
  1654. # Put the new result back into the target dict as a configuration.
  1655. target_dict['configurations'][configuration] = new_configuration_dict
  1656. # Now drop all the abstract ones.
  1657. for configuration in target_dict['configurations'].keys():
  1658. old_configuration_dict = target_dict['configurations'][configuration]
  1659. if old_configuration_dict.get('abstract'):
  1660. del target_dict['configurations'][configuration]
  1661. # Now that all of the target's configurations have been built, go through
  1662. # the target dict's keys and remove everything that's been moved into a
  1663. # "configurations" section.
  1664. delete_keys = []
  1665. for key in target_dict:
  1666. key_ext = key[-1:]
  1667. if key_ext in key_suffixes:
  1668. key_base = key[:-1]
  1669. else:
  1670. key_base = key
  1671. if not key_base in non_configuration_keys:
  1672. delete_keys.append(key)
  1673. for key in delete_keys:
  1674. del target_dict[key]
  1675. # Check the configurations to see if they contain invalid keys.
  1676. for configuration in target_dict['configurations'].keys():
  1677. configuration_dict = target_dict['configurations'][configuration]
  1678. for key in configuration_dict.keys():
  1679. if key in invalid_configuration_keys:
  1680. raise KeyError, ('%s not allowed in the %s configuration, found in '
  1681. 'target %s' % (key, configuration, target))
  1682. def ProcessListFiltersInDict(name, the_dict):
  1683. """Process regular expression and exclusion-based filters on lists.
  1684. An exclusion list is in a dict key named with a trailing "!", like
  1685. "sources!". Every item in such a list is removed from the associated
  1686. main list, which in this example, would be "sources". Removed items are
  1687. placed into a "sources_excluded" list in the dict.
  1688. Regular expression (regex) filters are contained in dict keys named with a
  1689. trailing "/", such as "sources/" to operate on the "sources" list. Regex
  1690. filters in a dict take the form:
  1691. 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
  1692. ['include', '_mac\\.cc$'] ],
  1693. The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
  1694. _win.cc. The second filter then includes all files ending in _mac.cc that
  1695. are now or were once in the "sources" list. Items matching an "exclude"
  1696. filter are subject to the same processing as would occur if they were listed
  1697. by name in an exclusion list (ending in "!"). Items matching an "include"
  1698. filter are brought back into the main list if previously excluded by an
  1699. exclusion list or exclusion regex filter. Subsequent matching "exclude"
  1700. patterns can still cause items to be excluded after matching an "include".
  1701. """
  1702. # Look through the dictionary for any lists whose keys end in "!" or "/".
  1703. # These are lists that will be treated as exclude lists and regular
  1704. # expression-based exclude/include lists. Collect the lists that are
  1705. # needed first, looking for the lists that they operate on, and assemble
  1706. # then into |lists|. This is done in a separate loop up front, because
  1707. # the _included and _excluded keys need to be added to the_dict, and that
  1708. # can't be done while iterating through it.
  1709. lists = []
  1710. del_lists = []
  1711. for key, value in the_dict.iteritems():
  1712. operation = key[-1]
  1713. if operation != '!' and operation != '/':
  1714. continue
  1715. if not isinstance(value, list):
  1716. raise ValueError, name + ' key ' + key + ' must be list, not ' + \
  1717. value.__class__.__name__
  1718. list_key = key[:-1]
  1719. if list_key not in the_dict:
  1720. # This happens when there's a list like "sources!" but no corresponding
  1721. # "sources" list. Since there's nothing for it to operate on, queue up
  1722. # the "sources!" list for deletion now.
  1723. del_lists.append(key)
  1724. continue
  1725. if not isinstance(the_dict[list_key], list):
  1726. raise ValueError, name + ' key ' + list_key + \
  1727. ' must be list, not ' + \
  1728. value.__class__.__name__ + ' when applying ' + \
  1729. {'!': 'exclusion', '/': 'regex'}[operation]
  1730. if not list_key in lists:
  1731. lists.append(list_key)
  1732. # Delete the lists that are known to be unneeded at this point.
  1733. for del_list in del_lists:
  1734. del the_dict[del_list]
  1735. for list_key in lists:
  1736. the_list = the_dict[list_key]
  1737. # Initialize the list_actions list, which is parallel to the_list. Each
  1738. # item in list_actions identifies whether the corresponding item in
  1739. # the_list should be excluded, unconditionally preserved (included), or
  1740. # whether no exclusion or inclusion has been applied. Items for which
  1741. # no exclusion or inclusion has been applied (yet) have value -1, items
  1742. # excluded have value 0, and items included have value 1. Includes and
  1743. # excludes override previous actions. All items in list_actions are
  1744. # initialized to -1 because no excludes or includes have been processed
  1745. # yet.
  1746. list_actions = list((-1,) * len(the_list))
  1747. exclude_key = list_key + '!'
  1748. if exclude_key in the_dict:
  1749. for exclude_item in the_dict[exclude_key]:
  1750. for index in xrange(0, len(the_list)):
  1751. if exclude_item == the_list[index]:
  1752. # This item matches the exclude_item, so set its action to 0
  1753. # (exclude).
  1754. list_actions[index] = 0
  1755. # The "whatever!" list is no longer needed, dump it.
  1756. del the_dict[exclude_key]
  1757. regex_key = list_key + '/'
  1758. if regex_key in the_dict:
  1759. for regex_item in the_dict[regex_key]:
  1760. [action, pattern] = regex_item
  1761. pattern_re = re.compile(pattern)
  1762. if action == 'exclude':
  1763. # This item matches an exclude regex, so set its value to 0 (exclude).
  1764. action_value = 0
  1765. elif action == 'include':
  1766. # This item matches an include regex, so set its value to 1 (include).
  1767. action_value = 1
  1768. else:
  1769. # This is an action that doesn't make any sense.
  1770. raise ValueError, 'Unrecognized action ' + action + ' in ' + name + \
  1771. ' key ' + regex_key
  1772. for index in xrange(0, len(the_list)):
  1773. list_item = the_list[index]
  1774. if list_actions[index] == action_value:
  1775. # Even if the regex matches, nothing will change so continue (regex
  1776. # searches are expensive).
  1777. continue
  1778. if pattern_re.search(list_item):
  1779. # Regular expression match.
  1780. list_actions[index] = action_value
  1781. # The "whatever/" list is no longer needed, dump it.
  1782. del the_dict[regex_key]
  1783. # Add excluded items to the excluded list.
  1784. #
  1785. # Note that exclude_key ("sources!") is different from excluded_key
  1786. # ("sources_excluded"). The exclude_key list is input and it was already
  1787. # processed and deleted; the excluded_key list is output and it's about
  1788. # to be created.
  1789. excluded_key = list_key + '_excluded'
  1790. if excluded_key in the_dict:
  1791. raise KeyError, \
  1792. name + ' key ' + excluded_key + ' must not be present prior ' + \
  1793. ' to applying exclusion/regex filters for ' + list_key
  1794. excluded_list = []
  1795. # Go backwards through the list_actions list so that as items are deleted,
  1796. # the indices of items that haven't been seen yet don't shift. That means
  1797. # that things need to be prepended to excluded_list to maintain them in the
  1798. # same order that they existed in the_list.
  1799. for index in xrange(len(list_actions) - 1, -1, -1):
  1800. if list_actions[index] == 0:
  1801. # Dump anything with action 0 (exclude). Keep anything with action 1
  1802. # (include) or -1 (no include or exclude seen for the item).
  1803. excluded_list.insert(0, the_list[index])
  1804. del the_list[index]
  1805. # If anything was excluded, put the excluded list into the_dict at
  1806. # excluded_key.
  1807. if len(excluded_list) > 0:
  1808. the_dict[excluded_key] = excluded_list
  1809. # Now recurse into subdicts and lists that may contain dicts.
  1810. for key, value in the_dict.iteritems():
  1811. if isinstance(value, dict):
  1812. ProcessListFiltersInDict(key, value)
  1813. elif isinstance(value, list):
  1814. ProcessListFiltersInList(key, value)
  1815. def ProcessListFiltersInList(name, the_list):
  1816. for item in the_list:
  1817. if isinstance(item, dict):
  1818. ProcessListFiltersInDict(name, item)
  1819. elif isinstance(item, list):
  1820. ProcessListFiltersInList(name, item)
  1821. def ValidateTargetType(target, target_dict):
  1822. """Ensures the 'type' field on the target is one of the known types.
  1823. Arguments:
  1824. target: string, name of target.
  1825. target_dict: dict, target spec.
  1826. Raises an exception on error.
  1827. """
  1828. VALID_TARGET_TYPES = ('executable', 'loadable_module',
  1829. 'static_library', 'shared_library',
  1830. 'none')
  1831. target_type = target_dict.get('type', None)
  1832. if target_type not in VALID_TARGET_TYPES:
  1833. raise Exception("Target %s has an invalid target type '%s'. "
  1834. "Must be one of %s." %
  1835. (target, target_type, '/'.join(VALID_TARGET_TYPES)))
  1836. def ValidateSourcesInTarget(target, target_dict, build_file):
  1837. # TODO: Check if MSVC allows this for non-static_library targets.
  1838. if target_dict.get('type', None) != 'static_library':
  1839. return
  1840. sources = target_dict.get('sources', [])
  1841. basenames = {}
  1842. for source in sources:
  1843. name, ext = os.path.splitext(source)
  1844. is_compiled_file = ext in [
  1845. '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S']
  1846. if not is_compiled_file:
  1847. continue
  1848. basename = os.path.basename(name) # Don't include extension.
  1849. basenames.setdefault(basename, []).append(source)
  1850. error = ''
  1851. for basename, files in basenames.iteritems():
  1852. if len(files) > 1:
  1853. error += ' %s: %s\n' % (basename, ' '.join(files))
  1854. if error:
  1855. print ('static library %s has several files with the same basename:\n' %
  1856. target + error + 'Some build systems, e.g. MSVC08, '
  1857. 'cannot handle that.')
  1858. raise KeyError, 'Duplicate basenames in sources section, see list above'
  1859. def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules):
  1860. """Ensures that the rules sections in target_dict are valid and consistent,
  1861. and determines which sources they apply to.
  1862. Arguments:
  1863. target: string, name of target.
  1864. target_dict: dict, target spec containing "rules" and "sources" lists.
  1865. extra_sources_for_rules: a list of keys to scan for rule matches in
  1866. addition to 'sources'.
  1867. """
  1868. # Dicts to map between values found in rules' 'rule_name' and 'extension'
  1869. # keys and the rule dicts themselves.
  1870. rule_names = {}
  1871. rule_extensions = {}
  1872. rules = target_dict.get('rules', [])
  1873. for rule in rules:
  1874. # Make sure that there's no conflict among rule names and extensions.
  1875. rule_name = rule['rule_name']
  1876. if rule_name in rule_names:
  1877. raise KeyError, 'rule %s exists in duplicate, target %s' % \
  1878. (rule_name, target)
  1879. rule_names[rule_name] = rule
  1880. rule_extension = rule['extension']
  1881. if rule_extension in rule_extensions:
  1882. raise KeyError, ('extension %s associated with multiple rules, ' +
  1883. 'target %s rules %s and %s') % \
  1884. (rule_extension, target,
  1885. rule_extensions[rule_extension]['rule_name'],
  1886. rule_name)
  1887. rule_extensions[rule_extension] = rule
  1888. # Make sure rule_sources isn't already there. It's going to be
  1889. # created below if needed.
  1890. if 'rule_sources' in rule:
  1891. raise KeyError, \
  1892. 'rule_sources must not exist in input, target %s rule %s' % \
  1893. (target, rule_name)
  1894. extension = rule['extension']
  1895. rule_sources = []
  1896. source_keys = ['sources']
  1897. source_keys.extend(extra_sources_for_rules)
  1898. for source_key in source_keys:
  1899. for source in target_dict.get(source_key, []):
  1900. (source_root, source_extension) = os.path.splitext(source)
  1901. if source_extension.startswith('.'):
  1902. source_extension = source_extension[1:]
  1903. if source_extension == extension:
  1904. rule_sources.append(source)
  1905. if len(rule_sources) > 0:
  1906. rule['rule_sources'] = rule_sources
  1907. def ValidateRunAsInTarget(target, target_dict, build_file):
  1908. target_name = target_dict.get('target_name')
  1909. run_as = target_dict.get('run_as')
  1910. if not run_as:
  1911. return
  1912. if not isinstance(run_as, dict):
  1913. raise Exception("The 'run_as' in target %s from file %s should be a "
  1914. "dictionary." %
  1915. (target_name, build_file))
  1916. action = run_as.get('action')
  1917. if not action:
  1918. raise Exception("The 'run_as' in target %s from file %s must have an "
  1919. "'action' section." %
  1920. (target_name, build_file))
  1921. if not isinstance(action, list):
  1922. raise Exception("The 'action' for 'run_as' in target %s from file %s "
  1923. "must be a list." %
  1924. (target_name, build_file))
  1925. working_directory = run_as.get('working_directory')
  1926. if working_directory and not isinstance(working_directory, str):
  1927. raise Exception("The 'working_directory' for 'run_as' in target %s "
  1928. "in file %s should be a string." %
  1929. (target_name, build_file))
  1930. environment = run_as.get('environment')
  1931. if environment and not isinstance(environment, dict):
  1932. raise Exception("The 'environment' for 'run_as' in target %s "
  1933. "in file %s should be a dictionary." %
  1934. (target_name, build_file))
  1935. def ValidateActionsInTarget(target, target_dict, build_file):
  1936. '''Validates the inputs to the actions in a target.'''
  1937. target_name = target_dict.get('target_name')
  1938. actions = target_dict.get('actions', [])
  1939. for action in actions:
  1940. action_name = action.get('action_name')
  1941. if not action_name:
  1942. raise Exception("Anonymous action in target %s. "
  1943. "An action must have an 'action_name' field." %
  1944. target_name)
  1945. inputs = action.get('inputs', None)
  1946. if inputs is None:
  1947. raise Exception('Action in target %s has no inputs.' % target_name)
  1948. action_command = action.get('action')
  1949. if action_command and not action_command[0]:
  1950. raise Exception("Empty action as command in target %s." % target_name)
  1951. def TurnIntIntoStrInDict(the_dict):
  1952. """Given dict the_dict, recursively converts all integers into strings.
  1953. """
  1954. # Use items instead of iteritems because there's no need to try to look at
  1955. # reinserted keys and their associated values.
  1956. for k, v in the_dict.items():
  1957. if isinstance(v, int):
  1958. v = str(v)
  1959. the_dict[k] = v
  1960. elif isinstance(v, dict):
  1961. TurnIntIntoStrInDict(v)
  1962. elif isinstance(v, list):
  1963. TurnIntIntoStrInList(v)
  1964. if isinstance(k, int):
  1965. the_dict[str(k)] = v
  1966. del the_dict[k]
  1967. def TurnIntIntoStrInList(the_list):
  1968. """Given list the_list, recursively converts all integers into strings.
  1969. """
  1970. for index in xrange(0, len(the_list)):
  1971. item = the_list[index]
  1972. if isinstance(item, int):
  1973. the_list[index] = str(item)
  1974. elif isinstance(item, dict):
  1975. TurnIntIntoStrInDict(item)
  1976. elif isinstance(item, list):
  1977. TurnIntIntoStrInList(item)
  1978. def VerifyNoCollidingTargets(targets):
  1979. """Verify that no two targets in the same directory share the same name.
  1980. Arguments:
  1981. targets: A list of targets in the form 'path/to/file.gyp:target_name'.
  1982. """
  1983. # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'.
  1984. used = {}
  1985. for target in targets:
  1986. # Separate out 'path/to/file.gyp, 'target_name' from
  1987. # 'path/to/file.gyp:target_name'.
  1988. path, name = target.rsplit(':', 1)
  1989. # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'.
  1990. subdir, gyp = os.path.split(path)
  1991. # Use '.' for the current directory '', so that the error messages make
  1992. # more sense.
  1993. if not subdir:
  1994. subdir = '.'
  1995. # Prepare a key like 'path/to:target_name'.
  1996. key = subdir + ':' + name
  1997. if key in used:
  1998. # Complain if this target is already used.
  1999. raise Exception('Duplicate target name "%s" in directory "%s" used both '
  2000. 'in "%s" and "%s".' % (name, subdir, gyp, used[key]))
  2001. used[key] = gyp
  2002. def Load(build_files, variables, includes, depth, generator_input_info, check,
  2003. circular_check):
  2004. # Set up path_sections and non_configuration_keys with the default data plus
  2005. # the generator-specifc data.
  2006. global path_sections
  2007. path_sections = base_path_sections[:]
  2008. path_sections.extend(generator_input_info['path_sections'])
  2009. global non_configuration_keys
  2010. non_configuration_keys = base_non_configuration_keys[:]
  2011. non_configuration_keys.extend(generator_input_info['non_configuration_keys'])
  2012. # TODO(mark) handle variants if the generator doesn't want them directly.
  2013. generator_handles_variants = \
  2014. generator_input_info['generator_handles_variants']
  2015. global absolute_build_file_paths
  2016. absolute_build_file_paths = \
  2017. generator_input_info['generator_wants_absolute_build_file_paths']
  2018. global multiple_toolsets
  2019. multiple_toolsets = generator_input_info[
  2020. 'generator_supports_multiple_toolsets']
  2021. # A generator can have other lists (in addition to sources) be processed
  2022. # for rules.
  2023. extra_sources_for_rules = generator_input_info['extra_sources_for_rules']
  2024. # Load build files. This loads every target-containing build file into
  2025. # the |data| dictionary such that the keys to |data| are build file names,
  2026. # and the values are the entire build file contents after "early" or "pre"
  2027. # processing has been done and includes have been resolved.
  2028. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as
  2029. # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps
  2030. # track of the keys corresponding to "target" files.
  2031. data = {'target_build_files': set()}
  2032. aux_data = {}
  2033. for build_file in build_files:
  2034. # Normalize paths everywhere. This is important because paths will be
  2035. # used as keys to the data dict and for references between input files.
  2036. build_file = os.path.normpath(build_file)
  2037. try:
  2038. LoadTargetBuildFile(build_file, data, aux_data, variables, includes,
  2039. depth, check)
  2040. except Exception, e:
  2041. gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file)
  2042. raise
  2043. # Build a dict to access each target's subdict by qualified name.
  2044. targets = BuildTargetsDict(data)
  2045. # Fully qualify all dependency links.
  2046. QualifyDependencies(targets)
  2047. # Expand dependencies specified as build_file:*.
  2048. ExpandWildcardDependencies(targets, data)
  2049. # Apply exclude (!) and regex (/) list filters only for dependency_sections.
  2050. for target_name, target_dict in targets.iteritems():
  2051. tmp_dict = {}
  2052. for key_base in dependency_sections:
  2053. for op in ('', '!', '/'):
  2054. key = key_base + op
  2055. if key in target_dict:
  2056. tmp_dict[key] = target_dict[key]
  2057. del target_dict[key]
  2058. ProcessListFiltersInDict(target_name, tmp_dict)
  2059. # Write the results back to |target_dict|.
  2060. for key in tmp_dict:
  2061. target_dict[key] = tmp_dict[key]
  2062. # Make sure every dependency appears at most once.
  2063. RemoveDuplicateDependencies(targets)
  2064. if circular_check:
  2065. # Make sure that any targets in a.gyp don't contain dependencies in other
  2066. # .gyp files that further depend on a.gyp.
  2067. VerifyNoGYPFileCircularDependencies(targets)
  2068. [dependency_nodes, flat_list] = BuildDependencyList(targets)
  2069. # Check that no two targets in the same directory have the same name.
  2070. VerifyNoCollidingTargets(flat_list)
  2071. # Handle dependent settings of various types.
  2072. for settings_type in ['all_dependent_settings',
  2073. 'direct_dependent_settings',
  2074. 'link_settings']:
  2075. DoDependentSettings(settings_type, flat_list, targets, dependency_nodes)
  2076. # Take out the dependent settings now that they've been published to all
  2077. # of the targets that require them.
  2078. for target in flat_list:
  2079. if settings_type in targets[target]:
  2080. del targets[target][settings_type]
  2081. # Make sure static libraries don't declare dependencies on other static
  2082. # libraries, but that linkables depend on all unlinked static libraries
  2083. # that they need so that their link steps will be correct.
  2084. gii = generator_input_info
  2085. if gii['generator_wants_static_library_dependencies_adjusted']:
  2086. AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes,
  2087. gii['generator_wants_sorted_dependencies'])
  2088. # Apply "post"/"late"/"target" variable expansions and condition evaluations.
  2089. for target in flat_list:
  2090. target_dict = targets[target]
  2091. build_file = gyp.common.BuildFile(target)
  2092. ProcessVariablesAndConditionsInDict(
  2093. target_dict, PHASE_LATE, variables, build_file)
  2094. # Move everything that can go into a "configurations" section into one.
  2095. for target in flat_list:
  2096. target_dict = targets[target]
  2097. SetUpConfigurations(target, target_dict)
  2098. # Apply exclude (!) and regex (/) list filters.
  2099. for target in flat_list:
  2100. target_dict = targets[target]
  2101. ProcessListFiltersInDict(target, target_dict)
  2102. # Apply "latelate" variable expansions and condition evaluations.
  2103. for target in flat_list:
  2104. target_dict = targets[target]
  2105. build_file = gyp.common.BuildFile(target)
  2106. ProcessVariablesAndConditionsInDict(
  2107. target_dict, PHASE_LATELATE, variables, build_file)
  2108. # Make sure that the rules make sense, and build up rule_sources lists as
  2109. # needed. Not all generators will need to use the rule_sources lists, but
  2110. # some may, and it seems best to build the list in a common spot.
  2111. # Also validate actions and run_as elements in targets.
  2112. for target in flat_list:
  2113. target_dict = targets[target]
  2114. build_file = gyp.common.BuildFile(target)
  2115. ValidateTargetType(target, target_dict)
  2116. # TODO(thakis): Get vpx_scale/arm/scalesystemdependent.c to be renamed to
  2117. # scalesystemdependent_arm_additions.c or similar.
  2118. if 'arm' not in variables.get('target_arch', ''):
  2119. ValidateSourcesInTarget(target, target_dict, build_file)
  2120. ValidateRulesInTarget(target, target_dict, extra_sources_for_rules)
  2121. ValidateRunAsInTarget(target, target_dict, build_file)
  2122. ValidateActionsInTarget(target, target_dict, build_file)
  2123. # Generators might not expect ints. Turn them into strs.
  2124. TurnIntIntoStrInDict(data)
  2125. # TODO(mark): Return |data| for now because the generator needs a list of
  2126. # build files that came in. In the future, maybe it should just accept
  2127. # a list, and not the whole data dict.
  2128. return [flat_list, targets, data]