PageRenderTime 86ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/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

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

  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

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