input.py 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897
  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 gyp.common
  13. import gyp.simple_copy
  14. import multiprocessing
  15. import optparse
  16. import os.path
  17. import re
  18. import shlex
  19. import signal
  20. import subprocess
  21. import sys
  22. import threading
  23. import time
  24. import traceback
  25. from gyp.common import GypError
  26. from gyp.common import OrderedSet
  27. # A list of types that are treated as linkable.
  28. linkable_types = [
  29. 'executable',
  30. 'shared_library',
  31. 'loadable_module',
  32. 'mac_kernel_extension',
  33. ]
  34. # A list of sections that contain links to other targets.
  35. dependency_sections = ['dependencies', 'export_dependent_settings']
  36. # base_path_sections is a list of sections defined by GYP that contain
  37. # pathnames. The generators can provide more keys, the two lists are merged
  38. # into path_sections, but you should call IsPathSection instead of using either
  39. # list directly.
  40. base_path_sections = [
  41. 'destination',
  42. 'files',
  43. 'include_dirs',
  44. 'inputs',
  45. 'libraries',
  46. 'outputs',
  47. 'sources',
  48. ]
  49. path_sections = set()
  50. # These per-process dictionaries are used to cache build file data when loading
  51. # in parallel mode.
  52. per_process_data = {}
  53. per_process_aux_data = {}
  54. def IsPathSection(section):
  55. # If section ends in one of the '=+?!' characters, it's applied to a section
  56. # without the trailing characters. '/' is notably absent from this list,
  57. # because there's no way for a regular expression to be treated as a path.
  58. while section and section[-1:] in '=+?!':
  59. section = section[:-1]
  60. if section in path_sections:
  61. return True
  62. # Sections mathing the regexp '_(dir|file|path)s?$' are also
  63. # considered PathSections. Using manual string matching since that
  64. # is much faster than the regexp and this can be called hundreds of
  65. # thousands of times so micro performance matters.
  66. if "_" in section:
  67. tail = section[-6:]
  68. if tail[-1] == 's':
  69. tail = tail[:-1]
  70. if tail[-5:] in ('_file', '_path'):
  71. return True
  72. return tail[-4:] == '_dir'
  73. return False
  74. # base_non_configuration_keys is a list of key names that belong in the target
  75. # itself and should not be propagated into its configurations. It is merged
  76. # with a list that can come from the generator to
  77. # create non_configuration_keys.
  78. base_non_configuration_keys = [
  79. # Sections that must exist inside targets and not configurations.
  80. 'actions',
  81. 'configurations',
  82. 'copies',
  83. 'default_configuration',
  84. 'dependencies',
  85. 'dependencies_original',
  86. 'libraries',
  87. 'postbuilds',
  88. 'product_dir',
  89. 'product_extension',
  90. 'product_name',
  91. 'product_prefix',
  92. 'rules',
  93. 'run_as',
  94. 'sources',
  95. 'standalone_static_library',
  96. 'suppress_wildcard',
  97. 'target_name',
  98. 'toolset',
  99. 'toolsets',
  100. 'type',
  101. # Sections that can be found inside targets or configurations, but that
  102. # should not be propagated from targets into their configurations.
  103. 'variables',
  104. ]
  105. non_configuration_keys = []
  106. # Keys that do not belong inside a configuration dictionary.
  107. invalid_configuration_keys = [
  108. 'actions',
  109. 'all_dependent_settings',
  110. 'configurations',
  111. 'dependencies',
  112. 'direct_dependent_settings',
  113. 'libraries',
  114. 'link_settings',
  115. 'sources',
  116. 'standalone_static_library',
  117. 'target_name',
  118. 'type',
  119. ]
  120. # Controls whether or not the generator supports multiple toolsets.
  121. multiple_toolsets = False
  122. # Paths for converting filelist paths to output paths: {
  123. # toplevel,
  124. # qualified_output_dir,
  125. # }
  126. generator_filelist_paths = None
  127. def GetIncludedBuildFiles(build_file_path, aux_data, included=None):
  128. """Return a list of all build files included into build_file_path.
  129. The returned list will contain build_file_path as well as all other files
  130. that it included, either directly or indirectly. Note that the list may
  131. contain files that were included into a conditional section that evaluated
  132. to false and was not merged into build_file_path's dict.
  133. aux_data is a dict containing a key for each build file or included build
  134. file. Those keys provide access to dicts whose "included" keys contain
  135. lists of all other files included by the build file.
  136. included should be left at its default None value by external callers. It
  137. is used for recursion.
  138. The returned list will not contain any duplicate entries. Each build file
  139. in the list will be relative to the current directory.
  140. """
  141. if included == None:
  142. included = []
  143. if build_file_path in included:
  144. return included
  145. included.append(build_file_path)
  146. for included_build_file in aux_data[build_file_path].get('included', []):
  147. GetIncludedBuildFiles(included_build_file, aux_data, included)
  148. return included
  149. def CheckedEval(file_contents):
  150. """Return the eval of a gyp file.
  151. The gyp file is restricted to dictionaries and lists only, and
  152. repeated keys are not allowed.
  153. Note that this is slower than eval() is.
  154. """
  155. ast = compiler.parse(file_contents)
  156. assert isinstance(ast, Module)
  157. c1 = ast.getChildren()
  158. assert c1[0] is None
  159. assert isinstance(c1[1], Stmt)
  160. c2 = c1[1].getChildren()
  161. assert isinstance(c2[0], Discard)
  162. c3 = c2[0].getChildren()
  163. assert len(c3) == 1
  164. return CheckNode(c3[0], [])
  165. def CheckNode(node, keypath):
  166. if isinstance(node, Dict):
  167. c = node.getChildren()
  168. dict = {}
  169. for n in range(0, len(c), 2):
  170. assert isinstance(c[n], Const)
  171. key = c[n].getChildren()[0]
  172. if key in dict:
  173. raise GypError("Key '" + key + "' repeated at level " +
  174. repr(len(keypath) + 1) + " with key path '" +
  175. '.'.join(keypath) + "'")
  176. kp = list(keypath) # Make a copy of the list for descending this node.
  177. kp.append(key)
  178. dict[key] = CheckNode(c[n + 1], kp)
  179. return dict
  180. elif isinstance(node, List):
  181. c = node.getChildren()
  182. children = []
  183. for index, child in enumerate(c):
  184. kp = list(keypath) # Copy list.
  185. kp.append(repr(index))
  186. children.append(CheckNode(child, kp))
  187. return children
  188. elif isinstance(node, Const):
  189. return node.getChildren()[0]
  190. else:
  191. raise TypeError("Unknown AST node at key path '" + '.'.join(keypath) +
  192. "': " + repr(node))
  193. def LoadOneBuildFile(build_file_path, data, aux_data, includes,
  194. is_target, check):
  195. if build_file_path in data:
  196. return data[build_file_path]
  197. if os.path.exists(build_file_path):
  198. # Open the build file for read ('r') with universal-newlines mode ('U')
  199. # to make sure platform specific newlines ('\r\n' or '\r') are converted to '\n'
  200. # which otherwise will fail eval()
  201. build_file_contents = open(build_file_path, 'rU').read()
  202. else:
  203. raise GypError("%s not found (cwd: %s)" % (build_file_path, os.getcwd()))
  204. build_file_data = None
  205. try:
  206. if check:
  207. build_file_data = CheckedEval(build_file_contents)
  208. else:
  209. build_file_data = eval(build_file_contents, {'__builtins__': None},
  210. None)
  211. except SyntaxError, e:
  212. e.filename = build_file_path
  213. raise
  214. except Exception, e:
  215. gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path)
  216. raise
  217. if type(build_file_data) is not dict:
  218. raise GypError("%s does not evaluate to a dictionary." % build_file_path)
  219. data[build_file_path] = build_file_data
  220. aux_data[build_file_path] = {}
  221. # Scan for includes and merge them in.
  222. if ('skip_includes' not in build_file_data or
  223. not build_file_data['skip_includes']):
  224. try:
  225. if is_target:
  226. LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data,
  227. aux_data, includes, check)
  228. else:
  229. LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data,
  230. aux_data, None, check)
  231. except Exception, e:
  232. gyp.common.ExceptionAppend(e,
  233. 'while reading includes of ' + build_file_path)
  234. raise
  235. return build_file_data
  236. def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data,
  237. includes, check):
  238. includes_list = []
  239. if includes != None:
  240. includes_list.extend(includes)
  241. if 'includes' in subdict:
  242. for include in subdict['includes']:
  243. # "include" is specified relative to subdict_path, so compute the real
  244. # path to include by appending the provided "include" to the directory
  245. # in which subdict_path resides.
  246. relative_include = \
  247. os.path.normpath(os.path.join(os.path.dirname(subdict_path), include))
  248. includes_list.append(relative_include)
  249. # Unhook the includes list, it's no longer needed.
  250. del subdict['includes']
  251. # Merge in the included files.
  252. for include in includes_list:
  253. if not 'included' in aux_data[subdict_path]:
  254. aux_data[subdict_path]['included'] = []
  255. aux_data[subdict_path]['included'].append(include)
  256. gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'", include)
  257. MergeDicts(subdict,
  258. LoadOneBuildFile(include, data, aux_data, None, False, check),
  259. subdict_path, include)
  260. # Recurse into subdictionaries.
  261. for k, v in subdict.iteritems():
  262. if type(v) is dict:
  263. LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data,
  264. None, check)
  265. elif type(v) is list:
  266. LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data,
  267. check)
  268. # This recurses into lists so that it can look for dicts.
  269. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, check):
  270. for item in sublist:
  271. if type(item) is dict:
  272. LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data,
  273. None, check)
  274. elif type(item) is list:
  275. LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, check)
  276. # Processes toolsets in all the targets. This recurses into condition entries
  277. # since they can contain toolsets as well.
  278. def ProcessToolsetsInDict(data):
  279. if 'targets' in data:
  280. target_list = data['targets']
  281. new_target_list = []
  282. for target in target_list:
  283. # If this target already has an explicit 'toolset', and no 'toolsets'
  284. # list, don't modify it further.
  285. if 'toolset' in target and 'toolsets' not in target:
  286. new_target_list.append(target)
  287. continue
  288. if multiple_toolsets:
  289. toolsets = target.get('toolsets', ['target'])
  290. else:
  291. toolsets = ['target']
  292. # Make sure this 'toolsets' definition is only processed once.
  293. if 'toolsets' in target:
  294. del target['toolsets']
  295. if len(toolsets) > 0:
  296. # Optimization: only do copies if more than one toolset is specified.
  297. for build in toolsets[1:]:
  298. new_target = gyp.simple_copy.deepcopy(target)
  299. new_target['toolset'] = build
  300. new_target_list.append(new_target)
  301. target['toolset'] = toolsets[0]
  302. new_target_list.append(target)
  303. data['targets'] = new_target_list
  304. if 'conditions' in data:
  305. for condition in data['conditions']:
  306. if type(condition) is list:
  307. for condition_dict in condition[1:]:
  308. if type(condition_dict) is dict:
  309. ProcessToolsetsInDict(condition_dict)
  310. # TODO(mark): I don't love this name. It just means that it's going to load
  311. # a build file that contains targets and is expected to provide a targets dict
  312. # that contains the targets...
  313. def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes,
  314. depth, check, load_dependencies):
  315. # If depth is set, predefine the DEPTH variable to be a relative path from
  316. # this build file's directory to the directory identified by depth.
  317. if depth:
  318. # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
  319. # temporary measure. This should really be addressed by keeping all paths
  320. # in POSIX until actual project generation.
  321. d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path))
  322. if d == '':
  323. variables['DEPTH'] = '.'
  324. else:
  325. variables['DEPTH'] = d.replace('\\', '/')
  326. # The 'target_build_files' key is only set when loading target build files in
  327. # the non-parallel code path, where LoadTargetBuildFile is called
  328. # recursively. In the parallel code path, we don't need to check whether the
  329. # |build_file_path| has already been loaded, because the 'scheduled' set in
  330. # ParallelState guarantees that we never load the same |build_file_path|
  331. # twice.
  332. if 'target_build_files' in data:
  333. if build_file_path in data['target_build_files']:
  334. # Already loaded.
  335. return False
  336. data['target_build_files'].add(build_file_path)
  337. gyp.DebugOutput(gyp.DEBUG_INCLUDES,
  338. "Loading Target Build File '%s'", build_file_path)
  339. build_file_data = LoadOneBuildFile(build_file_path, data, aux_data,
  340. includes, True, check)
  341. # Store DEPTH for later use in generators.
  342. build_file_data['_DEPTH'] = depth
  343. # Set up the included_files key indicating which .gyp files contributed to
  344. # this target dict.
  345. if 'included_files' in build_file_data:
  346. raise GypError(build_file_path + ' must not contain included_files key')
  347. included = GetIncludedBuildFiles(build_file_path, aux_data)
  348. build_file_data['included_files'] = []
  349. for included_file in included:
  350. # included_file is relative to the current directory, but it needs to
  351. # be made relative to build_file_path's directory.
  352. included_relative = \
  353. gyp.common.RelativePath(included_file,
  354. os.path.dirname(build_file_path))
  355. build_file_data['included_files'].append(included_relative)
  356. # Do a first round of toolsets expansion so that conditions can be defined
  357. # per toolset.
  358. ProcessToolsetsInDict(build_file_data)
  359. # Apply "pre"/"early" variable expansions and condition evaluations.
  360. ProcessVariablesAndConditionsInDict(
  361. build_file_data, PHASE_EARLY, variables, build_file_path)
  362. # Since some toolsets might have been defined conditionally, perform
  363. # a second round of toolsets expansion now.
  364. ProcessToolsetsInDict(build_file_data)
  365. # Look at each project's target_defaults dict, and merge settings into
  366. # targets.
  367. if 'target_defaults' in build_file_data:
  368. if 'targets' not in build_file_data:
  369. raise GypError("Unable to find targets in build file %s" %
  370. build_file_path)
  371. index = 0
  372. while index < len(build_file_data['targets']):
  373. # This procedure needs to give the impression that target_defaults is
  374. # used as defaults, and the individual targets inherit from that.
  375. # The individual targets need to be merged into the defaults. Make
  376. # a deep copy of the defaults for each target, merge the target dict
  377. # as found in the input file into that copy, and then hook up the
  378. # copy with the target-specific data merged into it as the replacement
  379. # target dict.
  380. old_target_dict = build_file_data['targets'][index]
  381. new_target_dict = gyp.simple_copy.deepcopy(
  382. build_file_data['target_defaults'])
  383. MergeDicts(new_target_dict, old_target_dict,
  384. build_file_path, build_file_path)
  385. build_file_data['targets'][index] = new_target_dict
  386. index += 1
  387. # No longer needed.
  388. del build_file_data['target_defaults']
  389. # Look for dependencies. This means that dependency resolution occurs
  390. # after "pre" conditionals and variable expansion, but before "post" -
  391. # in other words, you can't put a "dependencies" section inside a "post"
  392. # conditional within a target.
  393. dependencies = []
  394. if 'targets' in build_file_data:
  395. for target_dict in build_file_data['targets']:
  396. if 'dependencies' not in target_dict:
  397. continue
  398. for dependency in target_dict['dependencies']:
  399. dependencies.append(
  400. gyp.common.ResolveTarget(build_file_path, dependency, None)[0])
  401. if load_dependencies:
  402. for dependency in dependencies:
  403. try:
  404. LoadTargetBuildFile(dependency, data, aux_data, variables,
  405. includes, depth, check, load_dependencies)
  406. except Exception, e:
  407. gyp.common.ExceptionAppend(
  408. e, 'while loading dependencies of %s' % build_file_path)
  409. raise
  410. else:
  411. return (build_file_path, dependencies)
  412. def CallLoadTargetBuildFile(global_flags,
  413. build_file_path, variables,
  414. includes, depth, check,
  415. generator_input_info):
  416. """Wrapper around LoadTargetBuildFile for parallel processing.
  417. This wrapper is used when LoadTargetBuildFile is executed in
  418. a worker process.
  419. """
  420. try:
  421. signal.signal(signal.SIGINT, signal.SIG_IGN)
  422. # Apply globals so that the worker process behaves the same.
  423. for key, value in global_flags.iteritems():
  424. globals()[key] = value
  425. SetGeneratorGlobals(generator_input_info)
  426. result = LoadTargetBuildFile(build_file_path, per_process_data,
  427. per_process_aux_data, variables,
  428. includes, depth, check, False)
  429. if not result:
  430. return result
  431. (build_file_path, dependencies) = result
  432. # We can safely pop the build_file_data from per_process_data because it
  433. # will never be referenced by this process again, so we don't need to keep
  434. # it in the cache.
  435. build_file_data = per_process_data.pop(build_file_path)
  436. # This gets serialized and sent back to the main process via a pipe.
  437. # It's handled in LoadTargetBuildFileCallback.
  438. return (build_file_path,
  439. build_file_data,
  440. dependencies)
  441. except GypError, e:
  442. sys.stderr.write("gyp: %s\n" % e)
  443. return None
  444. except Exception, e:
  445. print >>sys.stderr, 'Exception:', e
  446. print >>sys.stderr, traceback.format_exc()
  447. return None
  448. class ParallelProcessingError(Exception):
  449. pass
  450. class ParallelState(object):
  451. """Class to keep track of state when processing input files in parallel.
  452. If build files are loaded in parallel, use this to keep track of
  453. state during farming out and processing parallel jobs. It's stored
  454. in a global so that the callback function can have access to it.
  455. """
  456. def __init__(self):
  457. # The multiprocessing pool.
  458. self.pool = None
  459. # The condition variable used to protect this object and notify
  460. # the main loop when there might be more data to process.
  461. self.condition = None
  462. # The "data" dict that was passed to LoadTargetBuildFileParallel
  463. self.data = None
  464. # The number of parallel calls outstanding; decremented when a response
  465. # was received.
  466. self.pending = 0
  467. # The set of all build files that have been scheduled, so we don't
  468. # schedule the same one twice.
  469. self.scheduled = set()
  470. # A list of dependency build file paths that haven't been scheduled yet.
  471. self.dependencies = []
  472. # Flag to indicate if there was an error in a child process.
  473. self.error = False
  474. def LoadTargetBuildFileCallback(self, result):
  475. """Handle the results of running LoadTargetBuildFile in another process.
  476. """
  477. self.condition.acquire()
  478. if not result:
  479. self.error = True
  480. self.condition.notify()
  481. self.condition.release()
  482. return
  483. (build_file_path0, build_file_data0, dependencies0) = result
  484. self.data[build_file_path0] = build_file_data0
  485. self.data['target_build_files'].add(build_file_path0)
  486. for new_dependency in dependencies0:
  487. if new_dependency not in self.scheduled:
  488. self.scheduled.add(new_dependency)
  489. self.dependencies.append(new_dependency)
  490. self.pending -= 1
  491. self.condition.notify()
  492. self.condition.release()
  493. def LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth,
  494. check, generator_input_info):
  495. parallel_state = ParallelState()
  496. parallel_state.condition = threading.Condition()
  497. # Make copies of the build_files argument that we can modify while working.
  498. parallel_state.dependencies = list(build_files)
  499. parallel_state.scheduled = set(build_files)
  500. parallel_state.pending = 0
  501. parallel_state.data = data
  502. try:
  503. parallel_state.condition.acquire()
  504. while parallel_state.dependencies or parallel_state.pending:
  505. if parallel_state.error:
  506. break
  507. if not parallel_state.dependencies:
  508. parallel_state.condition.wait()
  509. continue
  510. dependency = parallel_state.dependencies.pop()
  511. parallel_state.pending += 1
  512. global_flags = {
  513. 'path_sections': globals()['path_sections'],
  514. 'non_configuration_keys': globals()['non_configuration_keys'],
  515. 'multiple_toolsets': globals()['multiple_toolsets']}
  516. if not parallel_state.pool:
  517. parallel_state.pool = multiprocessing.Pool(multiprocessing.cpu_count())
  518. parallel_state.pool.apply_async(
  519. CallLoadTargetBuildFile,
  520. args = (global_flags, dependency,
  521. variables, includes, depth, check, generator_input_info),
  522. callback = parallel_state.LoadTargetBuildFileCallback)
  523. except KeyboardInterrupt, e:
  524. parallel_state.pool.terminate()
  525. raise e
  526. parallel_state.condition.release()
  527. parallel_state.pool.close()
  528. parallel_state.pool.join()
  529. parallel_state.pool = None
  530. if parallel_state.error:
  531. sys.exit(1)
  532. # Look for the bracket that matches the first bracket seen in a
  533. # string, and return the start and end as a tuple. For example, if
  534. # the input is something like "<(foo <(bar)) blah", then it would
  535. # return (1, 13), indicating the entire string except for the leading
  536. # "<" and trailing " blah".
  537. LBRACKETS= set('{[(')
  538. BRACKETS = {'}': '{', ']': '[', ')': '('}
  539. def FindEnclosingBracketGroup(input_str):
  540. stack = []
  541. start = -1
  542. for index, char in enumerate(input_str):
  543. if char in LBRACKETS:
  544. stack.append(char)
  545. if start == -1:
  546. start = index
  547. elif char in BRACKETS:
  548. if not stack:
  549. return (-1, -1)
  550. if stack.pop() != BRACKETS[char]:
  551. return (-1, -1)
  552. if not stack:
  553. return (start, index + 1)
  554. return (-1, -1)
  555. def IsStrCanonicalInt(string):
  556. """Returns True if |string| is in its canonical integer form.
  557. The canonical form is such that str(int(string)) == string.
  558. """
  559. if type(string) is str:
  560. # This function is called a lot so for maximum performance, avoid
  561. # involving regexps which would otherwise make the code much
  562. # shorter. Regexps would need twice the time of this function.
  563. if string:
  564. if string == "0":
  565. return True
  566. if string[0] == "-":
  567. string = string[1:]
  568. if not string:
  569. return False
  570. if '1' <= string[0] <= '9':
  571. return string.isdigit()
  572. return False
  573. # This matches things like "<(asdf)", "<!(cmd)", "<!@(cmd)", "<|(list)",
  574. # "<!interpreter(arguments)", "<([list])", and even "<([)" and "<(<())".
  575. # In the last case, the inner "<()" is captured in match['content'].
  576. early_variable_re = re.compile(
  577. r'(?P<replace>(?P<type><(?:(?:!?@?)|\|)?)'
  578. r'(?P<command_string>[-a-zA-Z0-9_.]+)?'
  579. r'\((?P<is_array>\s*\[?)'
  580. r'(?P<content>.*?)(\]?)\))')
  581. # This matches the same as early_variable_re, but with '>' instead of '<'.
  582. late_variable_re = re.compile(
  583. r'(?P<replace>(?P<type>>(?:(?:!?@?)|\|)?)'
  584. r'(?P<command_string>[-a-zA-Z0-9_.]+)?'
  585. r'\((?P<is_array>\s*\[?)'
  586. r'(?P<content>.*?)(\]?)\))')
  587. # This matches the same as early_variable_re, but with '^' instead of '<'.
  588. latelate_variable_re = re.compile(
  589. r'(?P<replace>(?P<type>[\^](?:(?:!?@?)|\|)?)'
  590. r'(?P<command_string>[-a-zA-Z0-9_.]+)?'
  591. r'\((?P<is_array>\s*\[?)'
  592. r'(?P<content>.*?)(\]?)\))')
  593. # Global cache of results from running commands so they don't have to be run
  594. # more then once.
  595. cached_command_results = {}
  596. def FixupPlatformCommand(cmd):
  597. if sys.platform == 'win32':
  598. if type(cmd) is list:
  599. cmd = [re.sub('^cat ', 'type ', cmd[0])] + cmd[1:]
  600. else:
  601. cmd = re.sub('^cat ', 'type ', cmd)
  602. return cmd
  603. PHASE_EARLY = 0
  604. PHASE_LATE = 1
  605. PHASE_LATELATE = 2
  606. def ExpandVariables(input, phase, variables, build_file):
  607. # Look for the pattern that gets expanded into variables
  608. if phase == PHASE_EARLY:
  609. variable_re = early_variable_re
  610. expansion_symbol = '<'
  611. elif phase == PHASE_LATE:
  612. variable_re = late_variable_re
  613. expansion_symbol = '>'
  614. elif phase == PHASE_LATELATE:
  615. variable_re = latelate_variable_re
  616. expansion_symbol = '^'
  617. else:
  618. assert False
  619. input_str = str(input)
  620. if IsStrCanonicalInt(input_str):
  621. return int(input_str)
  622. # Do a quick scan to determine if an expensive regex search is warranted.
  623. if expansion_symbol not in input_str:
  624. return input_str
  625. # Get the entire list of matches as a list of MatchObject instances.
  626. # (using findall here would return strings instead of MatchObjects).
  627. matches = list(variable_re.finditer(input_str))
  628. if not matches:
  629. return input_str
  630. output = input_str
  631. # Reverse the list of matches so that replacements are done right-to-left.
  632. # That ensures that earlier replacements won't mess up the string in a
  633. # way that causes later calls to find the earlier substituted text instead
  634. # of what's intended for replacement.
  635. matches.reverse()
  636. for match_group in matches:
  637. match = match_group.groupdict()
  638. gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %r", match)
  639. # match['replace'] is the substring to look for, match['type']
  640. # is the character code for the replacement type (< > <! >! <| >| <@
  641. # >@ <!@ >!@), match['is_array'] contains a '[' for command
  642. # arrays, and match['content'] is the name of the variable (< >)
  643. # or command to run (<! >!). match['command_string'] is an optional
  644. # command string. Currently, only 'pymod_do_main' is supported.
  645. # run_command is true if a ! variant is used.
  646. run_command = '!' in match['type']
  647. command_string = match['command_string']
  648. # file_list is true if a | variant is used.
  649. file_list = '|' in match['type']
  650. # Capture these now so we can adjust them later.
  651. replace_start = match_group.start('replace')
  652. replace_end = match_group.end('replace')
  653. # Find the ending paren, and re-evaluate the contained string.
  654. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:])
  655. # Adjust the replacement range to match the entire command
  656. # found by FindEnclosingBracketGroup (since the variable_re
  657. # probably doesn't match the entire command if it contained
  658. # nested variables).
  659. replace_end = replace_start + c_end
  660. # Find the "real" replacement, matching the appropriate closing
  661. # paren, and adjust the replacement start and end.
  662. replacement = input_str[replace_start:replace_end]
  663. # Figure out what the contents of the variable parens are.
  664. contents_start = replace_start + c_start + 1
  665. contents_end = replace_end - 1
  666. contents = input_str[contents_start:contents_end]
  667. # Do filter substitution now for <|().
  668. # Admittedly, this is different than the evaluation order in other
  669. # contexts. However, since filtration has no chance to run on <|(),
  670. # this seems like the only obvious way to give them access to filters.
  671. if file_list:
  672. processed_variables = gyp.simple_copy.deepcopy(variables)
  673. ProcessListFiltersInDict(contents, processed_variables)
  674. # Recurse to expand variables in the contents
  675. contents = ExpandVariables(contents, phase,
  676. processed_variables, build_file)
  677. else:
  678. # Recurse to expand variables in the contents
  679. contents = ExpandVariables(contents, phase, variables, build_file)
  680. # Strip off leading/trailing whitespace so that variable matches are
  681. # simpler below (and because they are rarely needed).
  682. contents = contents.strip()
  683. # expand_to_list is true if an @ variant is used. In that case,
  684. # the expansion should result in a list. Note that the caller
  685. # is to be expecting a list in return, and not all callers do
  686. # because not all are working in list context. Also, for list
  687. # expansions, there can be no other text besides the variable
  688. # expansion in the input string.
  689. expand_to_list = '@' in match['type'] and input_str == replacement
  690. if run_command or file_list:
  691. # Find the build file's directory, so commands can be run or file lists
  692. # generated relative to it.
  693. build_file_dir = os.path.dirname(build_file)
  694. if build_file_dir == '' and not file_list:
  695. # If build_file is just a leaf filename indicating a file in the
  696. # current directory, build_file_dir might be an empty string. Set
  697. # it to None to signal to subprocess.Popen that it should run the
  698. # command in the current directory.
  699. build_file_dir = None
  700. # Support <|(listfile.txt ...) which generates a file
  701. # containing items from a gyp list, generated at gyp time.
  702. # This works around actions/rules which have more inputs than will
  703. # fit on the command line.
  704. if file_list:
  705. if type(contents) is list:
  706. contents_list = contents
  707. else:
  708. contents_list = contents.split(' ')
  709. replacement = contents_list[0]
  710. if os.path.isabs(replacement):
  711. raise GypError('| cannot handle absolute paths, got "%s"' % replacement)
  712. if not generator_filelist_paths:
  713. path = os.path.join(build_file_dir, replacement)
  714. else:
  715. if os.path.isabs(build_file_dir):
  716. toplevel = generator_filelist_paths['toplevel']
  717. rel_build_file_dir = gyp.common.RelativePath(build_file_dir, toplevel)
  718. else:
  719. rel_build_file_dir = build_file_dir
  720. qualified_out_dir = generator_filelist_paths['qualified_out_dir']
  721. path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement)
  722. gyp.common.EnsureDirExists(path)
  723. replacement = gyp.common.RelativePath(path, build_file_dir)
  724. f = gyp.common.WriteOnDiff(path)
  725. for i in contents_list[1:]:
  726. f.write('%s\n' % i)
  727. f.close()
  728. elif run_command:
  729. use_shell = True
  730. if match['is_array']:
  731. contents = eval(contents)
  732. use_shell = False
  733. # Check for a cached value to avoid executing commands, or generating
  734. # file lists more than once. The cache key contains the command to be
  735. # run as well as the directory to run it from, to account for commands
  736. # that depend on their current directory.
  737. # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory,
  738. # someone could author a set of GYP files where each time the command
  739. # is invoked it produces different output by design. When the need
  740. # arises, the syntax should be extended to support no caching off a
  741. # command's output so it is run every time.
  742. cache_key = (str(contents), build_file_dir)
  743. cached_value = cached_command_results.get(cache_key, None)
  744. if cached_value is None:
  745. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  746. "Executing command '%s' in directory '%s'",
  747. contents, build_file_dir)
  748. replacement = ''
  749. if command_string == 'pymod_do_main':
  750. # <!pymod_do_main(modulename param eters) loads |modulename| as a
  751. # python module and then calls that module's DoMain() function,
  752. # passing ["param", "eters"] as a single list argument. For modules
  753. # that don't load quickly, this can be faster than
  754. # <!(python modulename param eters). Do this in |build_file_dir|.
  755. oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir.
  756. if build_file_dir: # build_file_dir may be None (see above).
  757. os.chdir(build_file_dir)
  758. try:
  759. parsed_contents = shlex.split(contents)
  760. try:
  761. py_module = __import__(parsed_contents[0])
  762. except ImportError as e:
  763. raise GypError("Error importing pymod_do_main"
  764. "module (%s): %s" % (parsed_contents[0], e))
  765. replacement = str(py_module.DoMain(parsed_contents[1:])).rstrip()
  766. finally:
  767. os.chdir(oldwd)
  768. assert replacement != None
  769. elif command_string:
  770. raise GypError("Unknown command string '%s' in '%s'." %
  771. (command_string, contents))
  772. else:
  773. # Fix up command with platform specific workarounds.
  774. contents = FixupPlatformCommand(contents)
  775. try:
  776. p = subprocess.Popen(contents, shell=use_shell,
  777. stdout=subprocess.PIPE,
  778. stderr=subprocess.PIPE,
  779. stdin=subprocess.PIPE,
  780. cwd=build_file_dir)
  781. except Exception, e:
  782. raise GypError("%s while executing command '%s' in %s" %
  783. (e, contents, build_file))
  784. p_stdout, p_stderr = p.communicate('')
  785. if p.wait() != 0 or p_stderr:
  786. sys.stderr.write(p_stderr)
  787. # Simulate check_call behavior, since check_call only exists
  788. # in python 2.5 and later.
  789. raise GypError("Call to '%s' returned exit status %d while in %s." %
  790. (contents, p.returncode, build_file))
  791. replacement = p_stdout.rstrip()
  792. cached_command_results[cache_key] = replacement
  793. else:
  794. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  795. "Had cache value for command '%s' in directory '%s'",
  796. contents,build_file_dir)
  797. replacement = cached_value
  798. else:
  799. if not contents in variables:
  800. if contents[-1] in ['!', '/']:
  801. # In order to allow cross-compiles (nacl) to happen more naturally,
  802. # we will allow references to >(sources/) etc. to resolve to
  803. # and empty list if undefined. This allows actions to:
  804. # 'action!': [
  805. # '>@(_sources!)',
  806. # ],
  807. # 'action/': [
  808. # '>@(_sources/)',
  809. # ],
  810. replacement = []
  811. else:
  812. raise GypError('Undefined variable ' + contents +
  813. ' in ' + build_file)
  814. else:
  815. replacement = variables[contents]
  816. if type(replacement) is list:
  817. for item in replacement:
  818. if not contents[-1] == '/' and type(item) not in (str, int):
  819. raise GypError('Variable ' + contents +
  820. ' must expand to a string or list of strings; ' +
  821. 'list contains a ' +
  822. item.__class__.__name__)
  823. # Run through the list and handle variable expansions in it. Since
  824. # the list is guaranteed not to contain dicts, this won't do anything
  825. # with conditions sections.
  826. ProcessVariablesAndConditionsInList(replacement, phase, variables,
  827. build_file)
  828. elif type(replacement) not in (str, int):
  829. raise GypError('Variable ' + contents +
  830. ' must expand to a string or list of strings; ' +
  831. 'found a ' + replacement.__class__.__name__)
  832. if expand_to_list:
  833. # Expanding in list context. It's guaranteed that there's only one
  834. # replacement to do in |input_str| and that it's this replacement. See
  835. # above.
  836. if type(replacement) is list:
  837. # If it's already a list, make a copy.
  838. output = replacement[:]
  839. else:
  840. # Split it the same way sh would split arguments.
  841. output = shlex.split(str(replacement))
  842. else:
  843. # Expanding in string context.
  844. encoded_replacement = ''
  845. if type(replacement) is list:
  846. # When expanding a list into string context, turn the list items
  847. # into a string in a way that will work with a subprocess call.
  848. #
  849. # TODO(mark): This isn't completely correct. This should
  850. # call a generator-provided function that observes the
  851. # proper list-to-argument quoting rules on a specific
  852. # platform instead of just calling the POSIX encoding
  853. # routine.
  854. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement)
  855. else:
  856. encoded_replacement = replacement
  857. output = output[:replace_start] + str(encoded_replacement) + \
  858. output[replace_end:]
  859. # Prepare for the next match iteration.
  860. input_str = output
  861. if output == input:
  862. gyp.DebugOutput(gyp.DEBUG_VARIABLES,
  863. "Found only identity matches on %r, avoiding infinite "
  864. "recursion.",
  865. output)
  866. else:
  867. # Look for more matches now that we've replaced some, to deal with
  868. # expanding local variables (variables defined in the same
  869. # variables block as this one).
  870. gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output)
  871. if type(output) is list:
  872. if output and type(output[0]) is list:
  873. # Leave output alone if it's a list of lists.
  874. # We don't want such lists to be stringified.
  875. pass
  876. else:
  877. new_output = []
  878. for item in output:
  879. new_output.append(
  880. ExpandVariables(item, phase, variables, build_file))
  881. output = new_output
  882. else:
  883. output = ExpandVariables(output, phase, variables, build_file)
  884. # Convert all strings that are canonically-represented integers into integers.
  885. if type(output) is list:
  886. for index in xrange(0, len(output)):
  887. if IsStrCanonicalInt(output[index]):
  888. output[index] = int(output[index])
  889. elif IsStrCanonicalInt(output):
  890. output = int(output)
  891. return output
  892. # The same condition is often evaluated over and over again so it
  893. # makes sense to cache as much as possible between evaluations.
  894. cached_conditions_asts = {}
  895. def EvalCondition(condition, conditions_key, phase, variables, build_file):
  896. """Returns the dict that should be used or None if the result was
  897. that nothing should be used."""
  898. if type(condition) is not list:
  899. raise GypError(conditions_key + ' must be a list')
  900. if len(condition) < 2:
  901. # It's possible that condition[0] won't work in which case this
  902. # attempt will raise its own IndexError. That's probably fine.
  903. raise GypError(conditions_key + ' ' + condition[0] +
  904. ' must be at least length 2, not ' + str(len(condition)))
  905. i = 0
  906. result = None
  907. while i < len(condition):
  908. cond_expr = condition[i]
  909. true_dict = condition[i + 1]
  910. if type(true_dict) is not dict:
  911. raise GypError('{} {} must be followed by a dictionary, not {}'.format(
  912. conditions_key, cond_expr, type(true_dict)))
  913. if len(condition) > i + 2 and type(condition[i + 2]) is dict:
  914. false_dict = condition[i + 2]
  915. i = i + 3
  916. if i != len(condition):
  917. raise GypError('{} {} has {} unexpected trailing items'.format(
  918. conditions_key, cond_expr, len(condition) - i))
  919. else:
  920. false_dict = None
  921. i = i + 2
  922. if result == None:
  923. result = EvalSingleCondition(
  924. cond_expr, true_dict, false_dict, phase, variables, build_file)
  925. return result
  926. def EvalSingleCondition(
  927. cond_expr, true_dict, false_dict, phase, variables, build_file):
  928. """Returns true_dict if cond_expr evaluates to true, and false_dict
  929. otherwise."""
  930. # Do expansions on the condition itself. Since the conditon can naturally
  931. # contain variable references without needing to resort to GYP expansion
  932. # syntax, this is of dubious value for variables, but someone might want to
  933. # use a command expansion directly inside a condition.
  934. cond_expr_expanded = ExpandVariables(cond_expr, phase, variables,
  935. build_file)
  936. if type(cond_expr_expanded) not in (str, int):
  937. raise ValueError(
  938. 'Variable expansion in this context permits str and int ' + \
  939. 'only, found ' + cond_expr_expanded.__class__.__name__)
  940. try:
  941. if cond_expr_expanded in cached_conditions_asts:
  942. ast_code = cached_conditions_asts[cond_expr_expanded]
  943. else:
  944. ast_code = compile(cond_expr_expanded, '<string>', 'eval')
  945. cached_conditions_asts[cond_expr_expanded] = ast_code
  946. if eval(ast_code, {'__builtins__': None}, variables):
  947. return true_dict
  948. return false_dict
  949. except SyntaxError, e:
  950. syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s '
  951. 'at character %d.' %
  952. (str(e.args[0]), e.text, build_file, e.offset),
  953. e.filename, e.lineno, e.offset, e.text)
  954. raise syntax_error
  955. except NameError, e:
  956. gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' %
  957. (cond_expr_expanded, build_file))
  958. raise GypError(e)
  959. def ProcessConditionsInDict(the_dict, phase, variables, build_file):
  960. # Process a 'conditions' or 'target_conditions' section in the_dict,
  961. # depending on phase.
  962. # early -> conditions
  963. # late -> target_conditions
  964. # latelate -> no conditions
  965. #
  966. # Each item in a conditions list consists of cond_expr, a string expression
  967. # evaluated as the condition, and true_dict, a dict that will be merged into
  968. # the_dict if cond_expr evaluates to true. Optionally, a third item,
  969. # false_dict, may be present. false_dict is merged into the_dict if
  970. # cond_expr evaluates to false.
  971. #
  972. # Any dict merged into the_dict will be recursively processed for nested
  973. # conditionals and other expansions, also according to phase, immediately
  974. # prior to being merged.
  975. if phase == PHASE_EARLY:
  976. conditions_key = 'conditions'
  977. elif phase == PHASE_LATE:
  978. conditions_key = 'target_conditions'
  979. elif phase == PHASE_LATELATE:
  980. return
  981. else:
  982. assert False
  983. if not conditions_key in the_dict:
  984. return
  985. conditions_list = the_dict[conditions_key]
  986. # Unhook the conditions list, it's no longer needed.
  987. del the_dict[conditions_key]
  988. for condition in conditions_list:
  989. merge_dict = EvalCondition(condition, conditions_key, phase, variables,
  990. build_file)
  991. if merge_dict != None:
  992. # Expand variables and nested conditinals in the merge_dict before
  993. # merging it.
  994. ProcessVariablesAndConditionsInDict(merge_dict, phase,
  995. variables, build_file)
  996. MergeDicts(the_dict, merge_dict, build_file, build_file)
  997. def LoadAutomaticVariablesFromDict(variables, the_dict):
  998. # Any keys with plain string values in the_dict become automatic variables.
  999. # The variable name is the key name with a "_" character prepended.
  1000. for key, value in the_dict.iteritems():
  1001. if type(value) in (str, int, list):
  1002. variables['_' + key] = value
  1003. def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key):
  1004. # Any keys in the_dict's "variables" dict, if it has one, becomes a
  1005. # variable. The variable name is the key name in the "variables" dict.
  1006. # Variables that end with the % character are set only if they are unset in
  1007. # the variables dict. the_dict_key is the name of the key that accesses
  1008. # the_dict in the_dict's parent dict. If the_dict's parent is not a dict
  1009. # (it could be a list or it could be parentless because it is a root dict),
  1010. # the_dict_key will be None.
  1011. for key, value in the_dict.get('variables', {}).iteritems():
  1012. if type(value) not in (str, int, list):
  1013. continue
  1014. if key.endswith('%'):
  1015. variable_name = key[:-1]
  1016. if variable_name in variables:
  1017. # If the variable is already set, don't set it.
  1018. continue
  1019. if the_dict_key is 'variables' and variable_name in the_dict:
  1020. # If the variable is set without a % in the_dict, and the_dict is a
  1021. # variables dict (making |variables| a varaibles sub-dict of a
  1022. # variables dict), use the_dict's definition.
  1023. value = the_dict[variable_name]
  1024. else:
  1025. variable_name = key
  1026. variables[variable_name] = value
  1027. def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in,
  1028. build_file, the_dict_key=None):
  1029. """Handle all variable and command expansion and conditional evaluation.
  1030. This function is the public entry point for all variable expansions and
  1031. conditional evaluations. The variables_in dictionary will not be modified
  1032. by this function.
  1033. """
  1034. # Make a copy of the variables_in dict that can be modified during the
  1035. # loading of automatics and the loading of the variables dict.
  1036. variables = variables_in.copy()
  1037. LoadAutomaticVariablesFromDict(variables, the_dict)
  1038. if 'variables' in the_dict:
  1039. # Make sure all the local variables are added to the variables
  1040. # list before we process them so that you can reference one
  1041. # variable from another. They will be fully expanded by recursion
  1042. # in ExpandVariables.
  1043. for key, value in the_dict['variables'].iteritems():
  1044. variables[key] = value
  1045. # Handle the associated variables dict first, so that any variable
  1046. # references within can be resolved prior to using them as variables.
  1047. # Pass a copy of the variables dict to avoid having it be tainted.
  1048. # Otherwise, it would have extra automatics added for everything that
  1049. # should just be an ordinary variable in this scope.
  1050. ProcessVariablesAndConditionsInDict(the_dict['variables'], phase,
  1051. variables, build_file, 'variables')
  1052. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  1053. for key, value in the_dict.iteritems():
  1054. # Skip "variables", which was already processed if present.
  1055. if key != 'variables' and type(value) is str:
  1056. expanded = ExpandVariables(value, phase, variables, build_file)
  1057. if type(expanded) not in (str, int):
  1058. raise ValueError(
  1059. 'Variable expansion in this context permits str and int ' + \
  1060. 'only, found ' + expanded.__class__.__name__ + ' for ' + key)
  1061. the_dict[key] = expanded
  1062. # Variable expansion may have resulted in changes to automatics. Reload.
  1063. # TODO(mark): Optimization: only reload if no changes were made.
  1064. variables = variables_in.copy()
  1065. LoadAutomaticVariablesFromDict(variables, the_dict)
  1066. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  1067. # Process conditions in this dict. This is done after variable expansion
  1068. # so that conditions may take advantage of expanded variables. For example,
  1069. # if the_dict contains:
  1070. # {'type': '<(library_type)',
  1071. # 'conditions': [['_type=="static_library"', { ... }]]},
  1072. # _type, as used in the condition, will only be set to the value of
  1073. # library_type if variable expansion is performed before condition
  1074. # processing. However, condition processing should occur prior to recursion
  1075. # so that variables (both automatic and "variables" dict type) may be
  1076. # adjusted by conditions sections, merged into the_dict, and have the
  1077. # intended impact on contained dicts.
  1078. #
  1079. # This arrangement means that a "conditions" section containing a "variables"
  1080. # section will only have those variables effective in subdicts, not in
  1081. # the_dict. The workaround is to put a "conditions" section within a
  1082. # "variables" section. For example:
  1083. # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]],
  1084. # 'defines': ['<(define)'],
  1085. # 'my_subdict': {'defines': ['<(define)']}},
  1086. # will not result in "IS_MAC" being appended to the "defines" list in the
  1087. # current scope but would result in it being appended to the "defines" list
  1088. # within "my_subdict". By comparison:
  1089. # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]},
  1090. # 'defines': ['<(define)'],
  1091. # 'my_subdict': {'defines': ['<(define)']}},
  1092. # will append "IS_MAC" to both "defines" lists.
  1093. # Evaluate conditions sections, allowing variable expansions within them
  1094. # as well as nested conditionals. This will process a 'conditions' or
  1095. # 'target_conditions' section, perform appropriate merging and recursive
  1096. # conditional and variable processing, and then remove the conditions section
  1097. # from the_dict if it is present.
  1098. ProcessConditionsInDict(the_dict, phase, variables, build_file)
  1099. # Conditional processing may have resulted in changes to automatics or the
  1100. # variables dict. Reload.
  1101. variables = variables_in.copy()
  1102. LoadAutomaticVariablesFromDict(variables, the_dict)
  1103. LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
  1104. # Recurse into child dicts, or process child lists which may result in
  1105. # further recursion into descendant dicts.
  1106. for key, value in the_dict.iteritems():
  1107. # Skip "variables" and string values, which were already processed if
  1108. # present.
  1109. if key == 'variables' or type(value) is str:
  1110. continue
  1111. if type(value) is dict:
  1112. # Pass a copy of the variables dict so that subdicts can't influence
  1113. # parents.
  1114. ProcessVariablesAndConditionsInDict(value, phase, variables,
  1115. build_file, key)
  1116. elif type(value) is list:
  1117. # The list itself can't influence the variables dict, and
  1118. # ProcessVariablesAndConditionsInList will make copies of the variables
  1119. # dict if it needs to pass it to something that can influence it. No
  1120. # copy is necessary here.
  1121. ProcessVariablesAndConditionsInList(value, phase, variables,
  1122. build_file)
  1123. elif type(value) is not int:
  1124. raise TypeError('Unknown type ' + value.__class__.__name__ + \
  1125. ' for ' + key)
  1126. def ProcessVariablesAndConditionsInList(the_list, phase, variables,
  1127. build_file):
  1128. # Iterate using an index so that new values can be assigned into the_list.
  1129. index = 0
  1130. while index < len(the_list):
  1131. item = the_list[index]
  1132. if type(item) is dict:
  1133. # Make a copy of the variables dict so that it won't influence anything
  1134. # outside of its own scope.
  1135. ProcessVariablesAndConditionsInDict(item, phase, variables, build_file)
  1136. elif type(item) is list:
  1137. ProcessVariablesAndConditionsInList(item, phase, variables, build_file)
  1138. elif type(item) is str:
  1139. expanded = ExpandVariables(item, phase, variables, build_file)
  1140. if type(expanded) in (str, int):
  1141. the_list[index] = expanded
  1142. elif type(expanded) is list:
  1143. the_list[index:index+1] = expanded
  1144. index += len(expanded)
  1145. # index now identifies the next item to examine. Continue right now
  1146. # without falling into the index increment below.
  1147. continue
  1148. else:
  1149. raise ValueError(
  1150. 'Variable expansion in this context permits strings and ' + \
  1151. 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \
  1152. index)
  1153. elif type(item) is not int:
  1154. raise TypeError('Unknown type ' + item.__class__.__name__ + \
  1155. ' at index ' + index)
  1156. index = index + 1
  1157. def BuildTargetsDict(data):
  1158. """Builds a dict mapping fully-qualified target names to their target dicts.
  1159. |data| is a dict mapping loaded build files by pathname relative to the
  1160. current directory. Values in |data| are build file contents. For each
  1161. |data| value with a "targets" key, the value of the "targets" key is taken
  1162. as a list containing target dicts. Each target's fully-qualified name is
  1163. constructed from the pathname of the build file (|data| key) and its
  1164. "target_name" property. These fully-qualified names are used as the keys
  1165. in the returned dict. These keys provide access to the target dicts,
  1166. the dicts in the "targets" lists.
  1167. """
  1168. targets = {}
  1169. for build_file in data['target_build_files']:
  1170. for target in data[build_file].get('targets', []):
  1171. target_name = gyp.common.QualifiedTarget(build_file,
  1172. target['target_name'],
  1173. target['toolset'])
  1174. if target_name in targets:
  1175. raise GypError('Duplicate target definitions for ' + target_name)
  1176. targets[target_name] = target
  1177. return targets
  1178. def QualifyDependencies(targets):
  1179. """Make dependency links fully-qualified relative to the current directory.
  1180. |targets| is a dict mapping fully-qualified target names to their target
  1181. dicts. For each target in this dict, keys known to contain dependency
  1182. links are examined, and any dependencies referenced will be rewritten
  1183. so that they are fully-qualified and relative to the current directory.
  1184. All rewritten dependencies are suitable for use as keys to |targets| or a
  1185. similar dict.
  1186. """
  1187. all_dependency_sections = [dep + op
  1188. for dep in dependency_sections
  1189. for op in ('', '!', '/')]
  1190. for target, target_dict in targets.iteritems():
  1191. target_build_file = gyp.common.BuildFile(target)
  1192. toolset = target_dict['toolset']
  1193. for dependency_key in all_dependency_sections:
  1194. dependencies = target_dict.get(dependency_key, [])
  1195. for index in xrange(0, len(dependencies)):
  1196. dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget(
  1197. target_build_file, dependencies[index], toolset)
  1198. if not multiple_toolsets:
  1199. # Ignore toolset specification in the dependency if it is specified.
  1200. dep_toolset = toolset
  1201. dependency = gyp.common.QualifiedTarget(dep_file,
  1202. dep_target,
  1203. dep_toolset)
  1204. dependencies[index] = dependency
  1205. # Make sure anything appearing in a list other than "dependencies" also
  1206. # appears in the "dependencies" list.
  1207. if dependency_key != 'dependencies' and \
  1208. dependency not in target_dict['dependencies']:
  1209. raise GypError('Found ' + dependency + ' in ' + dependency_key +
  1210. ' of ' + target + ', but not in dependencies')
  1211. def ExpandWildcardDependencies(targets, data):
  1212. """Expands dependencies specified as build_file:*.
  1213. For each target in |targets|, examines sections containing links to other
  1214. targets. If any such section contains a link of the form build_file:*, it
  1215. is taken as a wildcard link, and is expanded to list each target in
  1216. build_file. The |data| dict provides access to build file dicts.
  1217. Any target that does not wish to be included by wildcard can provide an
  1218. optional "suppress_wildcard" key in its target dict. When present and
  1219. true, a wildcard dependency link will not include such targets.
  1220. All dependency names, including the keys to |targets| and the values in each
  1221. dependency list, must be qualified when this function is called.
  1222. """
  1223. for target, target_dict in targets.iteritems():
  1224. toolset = target_dict['toolset']
  1225. target_build_file = gyp.common.BuildFile(target)
  1226. for dependency_key in dependency_sections:
  1227. dependencies = target_dict.get(dependency_key, [])
  1228. # Loop this way instead of "for dependency in" or "for index in xrange"
  1229. # because the dependencies list will be modified within the loop body.
  1230. index = 0
  1231. while index < len(dependencies):
  1232. (dependency_build_file, dependency_target, dependency_toolset) = \
  1233. gyp.common.ParseQualifiedTarget(dependencies[index])
  1234. if dependency_target != '*' and dependency_toolset != '*':
  1235. # Not a wildcard. Keep it moving.
  1236. index = index + 1
  1237. continue
  1238. if dependency_build_file == target_build_file:
  1239. # It's an error for a target to depend on all other targets in
  1240. # the same file, because a target cannot depend on itself.
  1241. raise GypError('Found wildcard in ' + dependency_key + ' of ' +
  1242. target + ' referring to same build file')
  1243. # Take the wildcard out and adjust the index so that the next
  1244. # dependency in the list will be processed the next time through the
  1245. # loop.
  1246. del dependencies[index]
  1247. index = index - 1
  1248. # Loop through the targets in the other build file, adding them to
  1249. # this target's list of dependencies in place of the removed
  1250. # wildcard.
  1251. dependency_target_dicts = data[dependency_build_file]['targets']
  1252. for dependency_target_dict in dependency_target_dicts:
  1253. if int(dependency_target_dict.get('suppress_wildcard', False)):
  1254. continue
  1255. dependency_target_name = dependency_target_dict['target_name']
  1256. if (dependency_target != '*' and
  1257. dependency_target != dependency_target_name):
  1258. continue
  1259. dependency_target_toolset = dependency_target_dict['toolset']
  1260. if (dependency_toolset != '*' and
  1261. dependency_toolset != dependency_target_toolset):
  1262. continue
  1263. dependency = gyp.common.QualifiedTarget(dependency_build_file,
  1264. dependency_target_name,
  1265. dependency_target_toolset)
  1266. index = index + 1
  1267. dependencies.insert(index, dependency)
  1268. index = index + 1
  1269. def Unify(l):
  1270. """Removes duplicate elements from l, keeping the first element."""
  1271. seen = {}
  1272. return [seen.setdefault(e, e) for e in l if e not in seen]
  1273. def RemoveDuplicateDependencies(targets):
  1274. """Makes sure every dependency appears only once in all targets's dependency
  1275. lists."""
  1276. for target_name, target_dict in targets.iteritems():
  1277. for dependency_key in dependency_sections:
  1278. dependencies = target_dict.get(dependency_key, [])
  1279. if dependencies:
  1280. target_dict[dependency_key] = Unify(dependencies)
  1281. def Filter(l, item):
  1282. """Removes item from l."""
  1283. res = {}
  1284. return [res.setdefault(e, e) for e in l if e != item]
  1285. def RemoveSelfDependencies(targets):
  1286. """Remove self dependencies from targets that have the prune_self_dependency
  1287. variable set."""
  1288. for target_name, target_dict in targets.iteritems():
  1289. for dependency_key in dependency_sections:
  1290. dependencies = target_dict.get(dependency_key, [])
  1291. if dependencies:
  1292. for t in dependencies:
  1293. if t == target_name:
  1294. if targets[t].get('variables', {}).get('prune_self_dependency', 0):
  1295. target_dict[dependency_key] = Filter(dependencies, target_name)
  1296. def RemoveLinkDependenciesFromNoneTargets(targets):
  1297. """Remove dependencies having the 'link_dependency' attribute from the 'none'
  1298. targets."""
  1299. for target_name, target_dict in targets.iteritems():
  1300. for dependency_key in dependency_sections:
  1301. dependencies = target_dict.get(dependency_key, [])
  1302. if dependencies:
  1303. for t in dependencies:
  1304. if target_dict.get('type', None) == 'none':
  1305. if targets[t].get('variables', {}).get('link_dependency', 0):
  1306. target_dict[dependency_key] = \
  1307. Filter(target_dict[dependency_key], t)
  1308. class DependencyGraphNode(object):
  1309. """
  1310. Attributes:
  1311. ref: A reference to an object that this DependencyGraphNode represents.
  1312. dependencies: List of DependencyGraphNodes on which this one depends.
  1313. dependents: List of DependencyGraphNodes that depend on this one.
  1314. """
  1315. class CircularException(GypError):
  1316. pass
  1317. def __init__(self, ref):
  1318. self.ref = ref
  1319. self.dependencies = []
  1320. self.dependents = []
  1321. def __repr__(self):
  1322. return '<DependencyGraphNode: %r>' % self.ref
  1323. def FlattenToList(self):
  1324. # flat_list is the sorted list of dependencies - actually, the list items
  1325. # are the "ref" attributes of DependencyGraphNodes. Every target will
  1326. # appear in flat_list after all of its dependencies, and before all of its
  1327. # dependents.
  1328. flat_list = OrderedSet()
  1329. # in_degree_zeros is the list of DependencyGraphNodes that have no
  1330. # dependencies not in flat_list. Initially, it is a copy of the children
  1331. # of this node, because when the graph was built, nodes with no
  1332. # dependencies were made implicit dependents of the root node.
  1333. in_degree_zeros = set(self.dependents[:])
  1334. while in_degree_zeros:
  1335. # Nodes in in_degree_zeros have no dependencies not in flat_list, so they
  1336. # can be appended to flat_list. Take these nodes out of in_degree_zeros
  1337. # as work progresses, so that the next node to process from the list can
  1338. # always be accessed at a consistent position.
  1339. node = in_degree_zeros.pop()
  1340. flat_list.add(node.ref)
  1341. # Look at dependents of the node just added to flat_list. Some of them
  1342. # may now belong in in_degree_zeros.
  1343. for node_dependent in node.dependents:
  1344. is_in_degree_zero = True
  1345. # TODO: We want to check through the
  1346. # node_dependent.dependencies list but if it's long and we
  1347. # always start at the beginning, then we get O(n^2) behaviour.
  1348. for node_dependent_dependency in node_dependent.dependencies:
  1349. if not node_dependent_dependency.ref in flat_list:
  1350. # The dependent one or more dependencies not in flat_list. There
  1351. # will be more chances to add it to flat_list when examining
  1352. # it again as a dependent of those other dependencies, provided
  1353. # that there are no cycles.
  1354. is_in_degree_zero = False
  1355. break
  1356. if is_in_degree_zero:
  1357. # All of the dependent's dependencies are already in flat_list. Add
  1358. # it to in_degree_zeros where it will be processed in a future
  1359. # iteration of the outer loop.
  1360. in_degree_zeros.add(node_dependent)
  1361. return list(flat_list)
  1362. def FindCycles(self):
  1363. """
  1364. Returns a list of cycles in the graph, where each cycle is its own list.
  1365. """
  1366. results = []
  1367. visited = set()
  1368. def Visit(node, path):
  1369. for child in node.dependents:
  1370. if child in path:
  1371. results.append([child] + path[:path.index(child) + 1])
  1372. elif not child in visited:
  1373. visited.add(child)
  1374. Visit(child, [child] + path)
  1375. visited.add(self)
  1376. Visit(self, [self])
  1377. return results
  1378. def DirectDependencies(self, dependencies=None):
  1379. """Returns a list of just direct dependencies."""
  1380. if dependencies == None:
  1381. dependencies = []
  1382. for dependency in self.dependencies:
  1383. # Check for None, corresponding to the root node.
  1384. if dependency.ref != None and dependency.ref not in dependencies:
  1385. dependencies.append(dependency.ref)
  1386. return dependencies
  1387. def _AddImportedDependencies(self, targets, dependencies=None):
  1388. """Given a list of direct dependencies, adds indirect dependencies that
  1389. other dependencies have declared to export their settings.
  1390. This method does not operate on self. Rather, it operates on the list
  1391. of dependencies in the |dependencies| argument. For each dependency in
  1392. that list, if any declares that it exports the settings of one of its
  1393. own dependencies, those dependencies whose settings are "passed through"
  1394. are added to the list. As new items are added to the list, they too will
  1395. be processed, so it is possible to import settings through multiple levels
  1396. of dependencies.
  1397. This method is not terribly useful on its own, it depends on being
  1398. "primed" with a list of direct dependencies such as one provided by
  1399. DirectDependencies. DirectAndImportedDependencies is intended to be the
  1400. public entry point.
  1401. """
  1402. if dependencies == None:
  1403. dependencies = []
  1404. index = 0
  1405. while index < len(dependencies):
  1406. dependency = dependencies[index]
  1407. dependency_dict = targets[dependency]
  1408. # Add any dependencies whose settings should be imported to the list
  1409. # if not already present. Newly-added items will be checked for
  1410. # their own imports when the list iteration reaches them.
  1411. # Rather than simply appending new items, insert them after the
  1412. # dependency that exported them. This is done to more closely match
  1413. # the depth-first method used by DeepDependencies.
  1414. add_index = 1
  1415. for imported_dependency in \
  1416. dependency_dict.get('export_dependent_settings', []):
  1417. if imported_dependency not in dependencies:
  1418. dependencies.insert(index + add_index, imported_dependency)
  1419. add_index = add_index + 1
  1420. index = index + 1
  1421. return dependencies
  1422. def DirectAndImportedDependencies(self, targets, dependencies=None):
  1423. """Returns a list of a target's direct dependencies and all indirect
  1424. dependencies that a dependency has advertised settings should be exported
  1425. through the dependency for.
  1426. """
  1427. dependencies = self.DirectDependencies(dependencies)
  1428. return self._AddImportedDependencies(targets, dependencies)
  1429. def DeepDependencies(self, dependencies=None):
  1430. """Returns an OrderedSet of all of a target's dependencies, recursively."""
  1431. if dependencies is None:
  1432. # Using a list to get ordered output and a set to do fast "is it
  1433. # already added" checks.
  1434. dependencies = OrderedSet()
  1435. for dependency in self.dependencies:
  1436. # Check for None, corresponding to the root node.
  1437. if dependency.ref is None:
  1438. continue
  1439. if dependency.ref not in dependencies:
  1440. dependency.DeepDependencies(dependencies)
  1441. dependencies.add(dependency.ref)
  1442. return dependencies
  1443. def _LinkDependenciesInternal(self, targets, include_shared_libraries,
  1444. dependencies=None, initial=True):
  1445. """Returns an OrderedSet of dependency targets that are linked
  1446. into this target.
  1447. This function has a split personality, depending on the setting of
  1448. |initial|. Outside callers should always leave |initial| at its default
  1449. setting.
  1450. When adding a target to the list of dependencies, this function will
  1451. recurse into itself with |initial| set to False, to collect dependencies
  1452. that are linked into the linkable target for which the list is being built.
  1453. If |include_shared_libraries| is False, the resulting dependencies will not
  1454. include shared_library targets that are linked into this target.
  1455. """
  1456. if dependencies is None:
  1457. # Using a list to get ordered output and a set to do fast "is it
  1458. # already added" checks.
  1459. dependencies = OrderedSet()
  1460. # Check for None, corresponding to the root node.
  1461. if self.ref is None:
  1462. return dependencies
  1463. # It's kind of sucky that |targets| has to be passed into this function,
  1464. # but that's presently the easiest way to access the target dicts so that
  1465. # this function can find target types.
  1466. if 'target_name' not in targets[self.ref]:
  1467. raise GypError("Missing 'target_name' field in target.")
  1468. if 'type' not in targets[self.ref]:
  1469. raise GypError("Missing 'type' field in target %s" %
  1470. targets[self.ref]['target_name'])
  1471. target_type = targets[self.ref]['type']
  1472. is_linkable = target_type in linkable_types
  1473. if initial and not is_linkable:
  1474. # If this is the first target being examined and it's not linkable,
  1475. # return an empty list of link dependencies, because the link
  1476. # dependencies are intended to apply to the target itself (initial is
  1477. # True) and this target won't be linked.
  1478. return dependencies
  1479. # Don't traverse 'none' targets if explicitly excluded.
  1480. if (target_type == 'none' and
  1481. not targets[self.ref].get('dependencies_traverse', True)):
  1482. dependencies.add(self.ref)
  1483. return dependencies
  1484. # Executables, mac kernel extensions and loadable modules are already fully
  1485. # and finally linked. Nothing else can be a link dependency of them, there
  1486. # can only be dependencies in the sense that a dependent target might run
  1487. # an executable or load the loadable_module.
  1488. if not initial and target_type in ('executable', 'loadable_module',
  1489. 'mac_kernel_extension'):
  1490. return dependencies
  1491. # Shared libraries are already fully linked. They should only be included
  1492. # in |dependencies| when adjusting static library dependencies (in order to
  1493. # link against the shared_library's import lib), but should not be included
  1494. # in |dependencies| when propagating link_settings.
  1495. # The |include_shared_libraries| flag controls which of these two cases we
  1496. # are handling.
  1497. if (not initial and target_type == 'shared_library' and
  1498. not include_shared_libraries):
  1499. return dependencies
  1500. # The target is linkable, add it to the list of link dependencies.
  1501. if self.ref not in dependencies:
  1502. dependencies.add(self.ref)
  1503. if initial or not is_linkable:
  1504. # If this is a subsequent target and it's linkable, don't look any
  1505. # further for linkable dependencies, as they'll already be linked into
  1506. # this target linkable. Always look at dependencies of the initial
  1507. # target, and always look at dependencies of non-linkables.
  1508. for dependency in self.dependencies:
  1509. dependency._LinkDependenciesInternal(targets,
  1510. include_shared_libraries,
  1511. dependencies, False)
  1512. return dependencies
  1513. def DependenciesForLinkSettings(self, targets):
  1514. """
  1515. Returns a list of dependency targets whose link_settings should be merged
  1516. into this target.
  1517. """
  1518. # TODO(sbaig) Currently, chrome depends on the bug that shared libraries'
  1519. # link_settings are propagated. So for now, we will allow it, unless the
  1520. # 'allow_sharedlib_linksettings_propagation' flag is explicitly set to
  1521. # False. Once chrome is fixed, we can remove this flag.
  1522. include_shared_libraries = \
  1523. targets[self.ref].get('allow_sharedlib_linksettings_propagation', True)
  1524. return self._LinkDependenciesInternal(targets, include_shared_libraries)
  1525. def DependenciesToLinkAgainst(self, targets):
  1526. """
  1527. Returns a list of dependency targets that are linked into this target.
  1528. """
  1529. return self._LinkDependenciesInternal(targets, True)
  1530. def BuildDependencyList(targets):
  1531. # Create a DependencyGraphNode for each target. Put it into a dict for easy
  1532. # access.
  1533. dependency_nodes = {}
  1534. for target, spec in targets.iteritems():
  1535. if target not in dependency_nodes:
  1536. dependency_nodes[target] = DependencyGraphNode(target)
  1537. # Set up the dependency links. Targets that have no dependencies are treated
  1538. # as dependent on root_node.
  1539. root_node = DependencyGraphNode(None)
  1540. for target, spec in targets.iteritems():
  1541. target_node = dependency_nodes[target]
  1542. target_build_file = gyp.common.BuildFile(target)
  1543. dependencies = spec.get('dependencies')
  1544. if not dependencies:
  1545. target_node.dependencies = [root_node]
  1546. root_node.dependents.append(target_node)
  1547. else:
  1548. for dependency in dependencies:
  1549. dependency_node = dependency_nodes.get(dependency)
  1550. if not dependency_node:
  1551. raise GypError("Dependency '%s' not found while "
  1552. "trying to load target %s" % (dependency, target))
  1553. target_node.dependencies.append(dependency_node)
  1554. dependency_node.dependents.append(target_node)
  1555. flat_list = root_node.FlattenToList()
  1556. # If there's anything left unvisited, there must be a circular dependency
  1557. # (cycle).
  1558. if len(flat_list) != len(targets):
  1559. if not root_node.dependents:
  1560. # If all targets have dependencies, add the first target as a dependent
  1561. # of root_node so that the cycle can be discovered from root_node.
  1562. target = targets.keys()[0]
  1563. target_node = dependency_nodes[target]
  1564. target_node.dependencies.append(root_node)
  1565. root_node.dependents.append(target_node)
  1566. cycles = []
  1567. for cycle in root_node.FindCycles():
  1568. paths = [node.ref for node in cycle]
  1569. cycles.append('Cycle: %s' % ' -> '.join(paths))
  1570. raise DependencyGraphNode.CircularException(
  1571. 'Cycles in dependency graph detected:\n' + '\n'.join(cycles))
  1572. return [dependency_nodes, flat_list]
  1573. def VerifyNoGYPFileCircularDependencies(targets):
  1574. # Create a DependencyGraphNode for each gyp file containing a target. Put
  1575. # it into a dict for easy access.
  1576. dependency_nodes = {}
  1577. for target in targets.iterkeys():
  1578. build_file = gyp.common.BuildFile(target)
  1579. if not build_file in dependency_nodes:
  1580. dependency_nodes[build_file] = DependencyGraphNode(build_file)
  1581. # Set up the dependency links.
  1582. for target, spec in targets.iteritems():
  1583. build_file = gyp.common.BuildFile(target)
  1584. build_file_node = dependency_nodes[build_file]
  1585. target_dependencies = spec.get('dependencies', [])
  1586. for dependency in target_dependencies:
  1587. try:
  1588. dependency_build_file = gyp.common.BuildFile(dependency)
  1589. except GypError, e:
  1590. gyp.common.ExceptionAppend(
  1591. e, 'while computing dependencies of .gyp file %s' % build_file)
  1592. raise
  1593. if dependency_build_file == build_file:
  1594. # A .gyp file is allowed to refer back to itself.
  1595. continue
  1596. dependency_node = dependency_nodes.get(dependency_build_file)
  1597. if not dependency_node:
  1598. raise GypError("Dependancy '%s' not found" % dependency_build_file)
  1599. if dependency_node not in build_file_node.dependencies:
  1600. build_file_node.dependencies.append(dependency_node)
  1601. dependency_node.dependents.append(build_file_node)
  1602. # Files that have no dependencies are treated as dependent on root_node.
  1603. root_node = DependencyGraphNode(None)
  1604. for build_file_node in dependency_nodes.itervalues():
  1605. if len(build_file_node.dependencies) == 0:
  1606. build_file_node.dependencies.append(root_node)
  1607. root_node.dependents.append(build_file_node)
  1608. flat_list = root_node.FlattenToList()
  1609. # If there's anything left unvisited, there must be a circular dependency
  1610. # (cycle).
  1611. if len(flat_list) != len(dependency_nodes):
  1612. if not root_node.dependents:
  1613. # If all files have dependencies, add the first file as a dependent
  1614. # of root_node so that the cycle can be discovered from root_node.
  1615. file_node = dependency_nodes.values()[0]
  1616. file_node.dependencies.append(root_node)
  1617. root_node.dependents.append(file_node)
  1618. cycles = []
  1619. for cycle in root_node.FindCycles():
  1620. paths = [node.ref for node in cycle]
  1621. cycles.append('Cycle: %s' % ' -> '.join(paths))
  1622. raise DependencyGraphNode.CircularException(
  1623. 'Cycles in .gyp file dependency graph detected:\n' + '\n'.join(cycles))
  1624. def DoDependentSettings(key, flat_list, targets, dependency_nodes):
  1625. # key should be one of all_dependent_settings, direct_dependent_settings,
  1626. # or link_settings.
  1627. for target in flat_list:
  1628. target_dict = targets[target]
  1629. build_file = gyp.common.BuildFile(target)
  1630. if key == 'all_dependent_settings':
  1631. dependencies = dependency_nodes[target].DeepDependencies()
  1632. elif key == 'direct_dependent_settings':
  1633. dependencies = \
  1634. dependency_nodes[target].DirectAndImportedDependencies(targets)
  1635. elif key == 'link_settings':
  1636. dependencies = \
  1637. dependency_nodes[target].DependenciesForLinkSettings(targets)
  1638. else:
  1639. raise GypError("DoDependentSettings doesn't know how to determine "
  1640. 'dependencies for ' + key)
  1641. for dependency in dependencies:
  1642. dependency_dict = targets[dependency]
  1643. if not key in dependency_dict:
  1644. continue
  1645. dependency_build_file = gyp.common.BuildFile(dependency)
  1646. MergeDicts(target_dict, dependency_dict[key],
  1647. build_file, dependency_build_file)
  1648. def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes,
  1649. sort_dependencies):
  1650. # Recompute target "dependencies" properties. For each static library
  1651. # target, remove "dependencies" entries referring to other static libraries,
  1652. # unless the dependency has the "hard_dependency" attribute set. For each
  1653. # linkable target, add a "dependencies" entry referring to all of the
  1654. # target's computed list of link dependencies (including static libraries
  1655. # if no such entry is already present.
  1656. for target in flat_list:
  1657. target_dict = targets[target]
  1658. target_type = target_dict['type']
  1659. if target_type == 'static_library':
  1660. if not 'dependencies' in target_dict:
  1661. continue
  1662. target_dict['dependencies_original'] = target_dict.get(
  1663. 'dependencies', [])[:]
  1664. # A static library should not depend on another static library unless
  1665. # the dependency relationship is "hard," which should only be done when
  1666. # a dependent relies on some side effect other than just the build
  1667. # product, like a rule or action output. Further, if a target has a
  1668. # non-hard dependency, but that dependency exports a hard dependency,
  1669. # the non-hard dependency can safely be removed, but the exported hard
  1670. # dependency must be added to the target to keep the same dependency
  1671. # ordering.
  1672. dependencies = \
  1673. dependency_nodes[target].DirectAndImportedDependencies(targets)
  1674. index = 0
  1675. while index < len(dependencies):
  1676. dependency = dependencies[index]
  1677. dependency_dict = targets[dependency]
  1678. # Remove every non-hard static library dependency and remove every
  1679. # non-static library dependency that isn't a direct dependency.
  1680. if (dependency_dict['type'] == 'static_library' and \
  1681. not dependency_dict.get('hard_dependency', False)) or \
  1682. (dependency_dict['type'] != 'static_library' and \
  1683. not dependency in target_dict['dependencies']):
  1684. # Take the dependency out of the list, and don't increment index
  1685. # because the next dependency to analyze will shift into the index
  1686. # formerly occupied by the one being removed.
  1687. del dependencies[index]
  1688. else:
  1689. index = index + 1
  1690. # Update the dependencies. If the dependencies list is empty, it's not
  1691. # needed, so unhook it.
  1692. if len(dependencies) > 0:
  1693. target_dict['dependencies'] = dependencies
  1694. else:
  1695. del target_dict['dependencies']
  1696. elif target_type in linkable_types:
  1697. # Get a list of dependency targets that should be linked into this
  1698. # target. Add them to the dependencies list if they're not already
  1699. # present.
  1700. link_dependencies = \
  1701. dependency_nodes[target].DependenciesToLinkAgainst(targets)
  1702. for dependency in link_dependencies:
  1703. if dependency == target:
  1704. continue
  1705. if not 'dependencies' in target_dict:
  1706. target_dict['dependencies'] = []
  1707. if not dependency in target_dict['dependencies']:
  1708. target_dict['dependencies'].append(dependency)
  1709. # Sort the dependencies list in the order from dependents to dependencies.
  1710. # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D.
  1711. # Note: flat_list is already sorted in the order from dependencies to
  1712. # dependents.
  1713. if sort_dependencies and 'dependencies' in target_dict:
  1714. target_dict['dependencies'] = [dep for dep in reversed(flat_list)
  1715. if dep in target_dict['dependencies']]
  1716. # Initialize this here to speed up MakePathRelative.
  1717. exception_re = re.compile(r'''["']?[-/$<>^]''')
  1718. def MakePathRelative(to_file, fro_file, item):
  1719. # If item is a relative path, it's relative to the build file dict that it's
  1720. # coming from. Fix it up to make it relative to the build file dict that
  1721. # it's going into.
  1722. # Exception: any |item| that begins with these special characters is
  1723. # returned without modification.
  1724. # / Used when a path is already absolute (shortcut optimization;
  1725. # such paths would be returned as absolute anyway)
  1726. # $ Used for build environment variables
  1727. # - Used for some build environment flags (such as -lapr-1 in a
  1728. # "libraries" section)
  1729. # < Used for our own variable and command expansions (see ExpandVariables)
  1730. # > Used for our own variable and command expansions (see ExpandVariables)
  1731. # ^ Used for our own variable and command expansions (see ExpandVariables)
  1732. #
  1733. # "/' Used when a value is quoted. If these are present, then we
  1734. # check the second character instead.
  1735. #
  1736. if to_file == fro_file or exception_re.match(item):
  1737. return item
  1738. else:
  1739. # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
  1740. # temporary measure. This should really be addressed by keeping all paths
  1741. # in POSIX until actual project generation.
  1742. ret = os.path.normpath(os.path.join(
  1743. gyp.common.RelativePath(os.path.dirname(fro_file),
  1744. os.path.dirname(to_file)),
  1745. item)).replace('\\', '/')
  1746. if item[-1] == '/':
  1747. ret += '/'
  1748. return ret
  1749. def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True):
  1750. # Python documentation recommends objects which do not support hash
  1751. # set this value to None. Python library objects follow this rule.
  1752. is_hashable = lambda val: val.__hash__
  1753. # If x is hashable, returns whether x is in s. Else returns whether x is in l.
  1754. def is_in_set_or_list(x, s, l):
  1755. if is_hashable(x):
  1756. return x in s
  1757. return x in l
  1758. prepend_index = 0
  1759. # Make membership testing of hashables in |to| (in particular, strings)
  1760. # faster.
  1761. hashable_to_set = set(x for x in to if is_hashable(x))
  1762. for item in fro:
  1763. singleton = False
  1764. if type(item) in (str, int):
  1765. # The cheap and easy case.
  1766. if is_paths:
  1767. to_item = MakePathRelative(to_file, fro_file, item)
  1768. else:
  1769. to_item = item
  1770. if not (type(item) is str and item.startswith('-')):
  1771. # Any string that doesn't begin with a "-" is a singleton - it can
  1772. # only appear once in a list, to be enforced by the list merge append
  1773. # or prepend.
  1774. singleton = True
  1775. elif type(item) is dict:
  1776. # Make a copy of the dictionary, continuing to look for paths to fix.
  1777. # The other intelligent aspects of merge processing won't apply because
  1778. # item is being merged into an empty dict.
  1779. to_item = {}
  1780. MergeDicts(to_item, item, to_file, fro_file)
  1781. elif type(item) is list:
  1782. # Recurse, making a copy of the list. If the list contains any
  1783. # descendant dicts, path fixing will occur. Note that here, custom
  1784. # values for is_paths and append are dropped; those are only to be
  1785. # applied to |to| and |fro|, not sublists of |fro|. append shouldn't
  1786. # matter anyway because the new |to_item| list is empty.
  1787. to_item = []
  1788. MergeLists(to_item, item, to_file, fro_file)
  1789. else:
  1790. raise TypeError(
  1791. 'Attempt to merge list item of unsupported type ' + \
  1792. item.__class__.__name__)
  1793. if append:
  1794. # If appending a singleton that's already in the list, don't append.
  1795. # This ensures that the earliest occurrence of the item will stay put.
  1796. if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to):
  1797. to.append(to_item)
  1798. if is_hashable(to_item):
  1799. hashable_to_set.add(to_item)
  1800. else:
  1801. # If prepending a singleton that's already in the list, remove the
  1802. # existing instance and proceed with the prepend. This ensures that the
  1803. # item appears at the earliest possible position in the list.
  1804. while singleton and to_item in to:
  1805. to.remove(to_item)
  1806. # Don't just insert everything at index 0. That would prepend the new
  1807. # items to the list in reverse order, which would be an unwelcome
  1808. # surprise.
  1809. to.insert(prepend_index, to_item)
  1810. if is_hashable(to_item):
  1811. hashable_to_set.add(to_item)
  1812. prepend_index = prepend_index + 1
  1813. def MergeDicts(to, fro, to_file, fro_file):
  1814. # I wanted to name the parameter "from" but it's a Python keyword...
  1815. for k, v in fro.iteritems():
  1816. # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give
  1817. # copy semantics. Something else may want to merge from the |fro| dict
  1818. # later, and having the same dict ref pointed to twice in the tree isn't
  1819. # what anyone wants considering that the dicts may subsequently be
  1820. # modified.
  1821. if k in to:
  1822. bad_merge = False
  1823. if type(v) in (str, int):
  1824. if type(to[k]) not in (str, int):
  1825. bad_merge = True
  1826. elif type(v) is not type(to[k]):
  1827. bad_merge = True
  1828. if bad_merge:
  1829. raise TypeError(
  1830. 'Attempt to merge dict value of type ' + v.__class__.__name__ + \
  1831. ' into incompatible type ' + to[k].__class__.__name__ + \
  1832. ' for key ' + k)
  1833. if type(v) in (str, int):
  1834. # Overwrite the existing value, if any. Cheap and easy.
  1835. is_path = IsPathSection(k)
  1836. if is_path:
  1837. to[k] = MakePathRelative(to_file, fro_file, v)
  1838. else:
  1839. to[k] = v
  1840. elif type(v) is dict:
  1841. # Recurse, guaranteeing copies will be made of objects that require it.
  1842. if not k in to:
  1843. to[k] = {}
  1844. MergeDicts(to[k], v, to_file, fro_file)
  1845. elif type(v) is list:
  1846. # Lists in dicts can be merged with different policies, depending on
  1847. # how the key in the "from" dict (k, the from-key) is written.
  1848. #
  1849. # If the from-key has ...the to-list will have this action
  1850. # this character appended:... applied when receiving the from-list:
  1851. # = replace
  1852. # + prepend
  1853. # ? set, only if to-list does not yet exist
  1854. # (none) append
  1855. #
  1856. # This logic is list-specific, but since it relies on the associated
  1857. # dict key, it's checked in this dict-oriented function.
  1858. ext = k[-1]
  1859. append = True
  1860. if ext == '=':
  1861. list_base = k[:-1]
  1862. lists_incompatible = [list_base, list_base + '?']
  1863. to[list_base] = []
  1864. elif ext == '+':
  1865. list_base = k[:-1]
  1866. lists_incompatible = [list_base + '=', list_base + '?']
  1867. append = False
  1868. elif ext == '?':
  1869. list_base = k[:-1]
  1870. lists_incompatible = [list_base, list_base + '=', list_base + '+']
  1871. else:
  1872. list_base = k
  1873. lists_incompatible = [list_base + '=', list_base + '?']
  1874. # Some combinations of merge policies appearing together are meaningless.
  1875. # It's stupid to replace and append simultaneously, for example. Append
  1876. # and prepend are the only policies that can coexist.
  1877. for list_incompatible in lists_incompatible:
  1878. if list_incompatible in fro:
  1879. raise GypError('Incompatible list policies ' + k + ' and ' +
  1880. list_incompatible)
  1881. if list_base in to:
  1882. if ext == '?':
  1883. # If the key ends in "?", the list will only be merged if it doesn't
  1884. # already exist.
  1885. continue
  1886. elif type(to[list_base]) is not list:
  1887. # This may not have been checked above if merging in a list with an
  1888. # extension character.
  1889. raise TypeError(
  1890. 'Attempt to merge dict value of type ' + v.__class__.__name__ + \
  1891. ' into incompatible type ' + to[list_base].__class__.__name__ + \
  1892. ' for key ' + list_base + '(' + k + ')')
  1893. else:
  1894. to[list_base] = []
  1895. # Call MergeLists, which will make copies of objects that require it.
  1896. # MergeLists can recurse back into MergeDicts, although this will be
  1897. # to make copies of dicts (with paths fixed), there will be no
  1898. # subsequent dict "merging" once entering a list because lists are
  1899. # always replaced, appended to, or prepended to.
  1900. is_paths = IsPathSection(list_base)
  1901. MergeLists(to[list_base], v, to_file, fro_file, is_paths, append)
  1902. else:
  1903. raise TypeError(
  1904. 'Attempt to merge dict value of unsupported type ' + \
  1905. v.__class__.__name__ + ' for key ' + k)
  1906. def MergeConfigWithInheritance(new_configuration_dict, build_file,
  1907. target_dict, configuration, visited):
  1908. # Skip if previously visted.
  1909. if configuration in visited:
  1910. return
  1911. # Look at this configuration.
  1912. configuration_dict = target_dict['configurations'][configuration]
  1913. # Merge in parents.
  1914. for parent in configuration_dict.get('inherit_from', []):
  1915. MergeConfigWithInheritance(new_configuration_dict, build_file,
  1916. target_dict, parent, visited + [configuration])
  1917. # Merge it into the new config.
  1918. MergeDicts(new_configuration_dict, configuration_dict,
  1919. build_file, build_file)
  1920. # Drop abstract.
  1921. if 'abstract' in new_configuration_dict:
  1922. del new_configuration_dict['abstract']
  1923. def SetUpConfigurations(target, target_dict):
  1924. # key_suffixes is a list of key suffixes that might appear on key names.
  1925. # These suffixes are handled in conditional evaluations (for =, +, and ?)
  1926. # and rules/exclude processing (for ! and /). Keys with these suffixes
  1927. # should be treated the same as keys without.
  1928. key_suffixes = ['=', '+', '?', '!', '/']
  1929. build_file = gyp.common.BuildFile(target)
  1930. # Provide a single configuration by default if none exists.
  1931. # TODO(mark): Signal an error if default_configurations exists but
  1932. # configurations does not.
  1933. if not 'configurations' in target_dict:
  1934. target_dict['configurations'] = {'Default': {}}
  1935. if not 'default_configuration' in target_dict:
  1936. concrete = [i for (i, config) in target_dict['configurations'].iteritems()
  1937. if not config.get('abstract')]
  1938. target_dict['default_configuration'] = sorted(concrete)[0]
  1939. merged_configurations = {}
  1940. configs = target_dict['configurations']
  1941. for (configuration, old_configuration_dict) in configs.iteritems():
  1942. # Skip abstract configurations (saves work only).
  1943. if old_configuration_dict.get('abstract'):
  1944. continue
  1945. # Configurations inherit (most) settings from the enclosing target scope.
  1946. # Get the inheritance relationship right by making a copy of the target
  1947. # dict.
  1948. new_configuration_dict = {}
  1949. for (key, target_val) in target_dict.iteritems():
  1950. key_ext = key[-1:]
  1951. if key_ext in key_suffixes:
  1952. key_base = key[:-1]
  1953. else:
  1954. key_base = key
  1955. if not key_base in non_configuration_keys:
  1956. new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val)
  1957. # Merge in configuration (with all its parents first).
  1958. MergeConfigWithInheritance(new_configuration_dict, build_file,
  1959. target_dict, configuration, [])
  1960. merged_configurations[configuration] = new_configuration_dict
  1961. # Put the new configurations back into the target dict as a configuration.
  1962. for configuration in merged_configurations.keys():
  1963. target_dict['configurations'][configuration] = (
  1964. merged_configurations[configuration])
  1965. # Now drop all the abstract ones.
  1966. for configuration in target_dict['configurations'].keys():
  1967. old_configuration_dict = target_dict['configurations'][configuration]
  1968. if old_configuration_dict.get('abstract'):
  1969. del target_dict['configurations'][configuration]
  1970. # Now that all of the target's configurations have been built, go through
  1971. # the target dict's keys and remove everything that's been moved into a
  1972. # "configurations" section.
  1973. delete_keys = []
  1974. for key in target_dict:
  1975. key_ext = key[-1:]
  1976. if key_ext in key_suffixes:
  1977. key_base = key[:-1]
  1978. else:
  1979. key_base = key
  1980. if not key_base in non_configuration_keys:
  1981. delete_keys.append(key)
  1982. for key in delete_keys:
  1983. del target_dict[key]
  1984. # Check the configurations to see if they contain invalid keys.
  1985. for configuration in target_dict['configurations'].keys():
  1986. configuration_dict = target_dict['configurations'][configuration]
  1987. for key in configuration_dict.keys():
  1988. if key in invalid_configuration_keys:
  1989. raise GypError('%s not allowed in the %s configuration, found in '
  1990. 'target %s' % (key, configuration, target))
  1991. def ProcessListFiltersInDict(name, the_dict):
  1992. """Process regular expression and exclusion-based filters on lists.
  1993. An exclusion list is in a dict key named with a trailing "!", like
  1994. "sources!". Every item in such a list is removed from the associated
  1995. main list, which in this example, would be "sources". Removed items are
  1996. placed into a "sources_excluded" list in the dict.
  1997. Regular expression (regex) filters are contained in dict keys named with a
  1998. trailing "/", such as "sources/" to operate on the "sources" list. Regex
  1999. filters in a dict take the form:
  2000. 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
  2001. ['include', '_mac\\.cc$'] ],
  2002. The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
  2003. _win.cc. The second filter then includes all files ending in _mac.cc that
  2004. are now or were once in the "sources" list. Items matching an "exclude"
  2005. filter are subject to the same processing as would occur if they were listed
  2006. by name in an exclusion list (ending in "!"). Items matching an "include"
  2007. filter are brought back into the main list if previously excluded by an
  2008. exclusion list or exclusion regex filter. Subsequent matching "exclude"
  2009. patterns can still cause items to be excluded after matching an "include".
  2010. """
  2011. # Look through the dictionary for any lists whose keys end in "!" or "/".
  2012. # These are lists that will be treated as exclude lists and regular
  2013. # expression-based exclude/include lists. Collect the lists that are
  2014. # needed first, looking for the lists that they operate on, and assemble
  2015. # then into |lists|. This is done in a separate loop up front, because
  2016. # the _included and _excluded keys need to be added to the_dict, and that
  2017. # can't be done while iterating through it.
  2018. lists = []
  2019. del_lists = []
  2020. for key, value in the_dict.iteritems():
  2021. operation = key[-1]
  2022. if operation != '!' and operation != '/':
  2023. continue
  2024. if type(value) is not list:
  2025. raise ValueError(name + ' key ' + key + ' must be list, not ' + \
  2026. value.__class__.__name__)
  2027. list_key = key[:-1]
  2028. if list_key not in the_dict:
  2029. # This happens when there's a list like "sources!" but no corresponding
  2030. # "sources" list. Since there's nothing for it to operate on, queue up
  2031. # the "sources!" list for deletion now.
  2032. del_lists.append(key)
  2033. continue
  2034. if type(the_dict[list_key]) is not list:
  2035. value = the_dict[list_key]
  2036. raise ValueError(name + ' key ' + list_key + \
  2037. ' must be list, not ' + \
  2038. value.__class__.__name__ + ' when applying ' + \
  2039. {'!': 'exclusion', '/': 'regex'}[operation])
  2040. if not list_key in lists:
  2041. lists.append(list_key)
  2042. # Delete the lists that are known to be unneeded at this point.
  2043. for del_list in del_lists:
  2044. del the_dict[del_list]
  2045. for list_key in lists:
  2046. the_list = the_dict[list_key]
  2047. # Initialize the list_actions list, which is parallel to the_list. Each
  2048. # item in list_actions identifies whether the corresponding item in
  2049. # the_list should be excluded, unconditionally preserved (included), or
  2050. # whether no exclusion or inclusion has been applied. Items for which
  2051. # no exclusion or inclusion has been applied (yet) have value -1, items
  2052. # excluded have value 0, and items included have value 1. Includes and
  2053. # excludes override previous actions. All items in list_actions are
  2054. # initialized to -1 because no excludes or includes have been processed
  2055. # yet.
  2056. list_actions = list((-1,) * len(the_list))
  2057. exclude_key = list_key + '!'
  2058. if exclude_key in the_dict:
  2059. for exclude_item in the_dict[exclude_key]:
  2060. for index in xrange(0, len(the_list)):
  2061. if exclude_item == the_list[index]:
  2062. # This item matches the exclude_item, so set its action to 0
  2063. # (exclude).
  2064. list_actions[index] = 0
  2065. # The "whatever!" list is no longer needed, dump it.
  2066. del the_dict[exclude_key]
  2067. regex_key = list_key + '/'
  2068. if regex_key in the_dict:
  2069. for regex_item in the_dict[regex_key]:
  2070. [action, pattern] = regex_item
  2071. pattern_re = re.compile(pattern)
  2072. if action == 'exclude':
  2073. # This item matches an exclude regex, so set its value to 0 (exclude).
  2074. action_value = 0
  2075. elif action == 'include':
  2076. # This item matches an include regex, so set its value to 1 (include).
  2077. action_value = 1
  2078. else:
  2079. # This is an action that doesn't make any sense.
  2080. raise ValueError('Unrecognized action ' + action + ' in ' + name + \
  2081. ' key ' + regex_key)
  2082. for index in xrange(0, len(the_list)):
  2083. list_item = the_list[index]
  2084. if list_actions[index] == action_value:
  2085. # Even if the regex matches, nothing will change so continue (regex
  2086. # searches are expensive).
  2087. continue
  2088. if pattern_re.search(list_item):
  2089. # Regular expression match.
  2090. list_actions[index] = action_value
  2091. # The "whatever/" list is no longer needed, dump it.
  2092. del the_dict[regex_key]
  2093. # Add excluded items to the excluded list.
  2094. #
  2095. # Note that exclude_key ("sources!") is different from excluded_key
  2096. # ("sources_excluded"). The exclude_key list is input and it was already
  2097. # processed and deleted; the excluded_key list is output and it's about
  2098. # to be created.
  2099. excluded_key = list_key + '_excluded'
  2100. if excluded_key in the_dict:
  2101. raise GypError(name + ' key ' + excluded_key +
  2102. ' must not be present prior '
  2103. ' to applying exclusion/regex filters for ' + list_key)
  2104. excluded_list = []
  2105. # Go backwards through the list_actions list so that as items are deleted,
  2106. # the indices of items that haven't been seen yet don't shift. That means
  2107. # that things need to be prepended to excluded_list to maintain them in the
  2108. # same order that they existed in the_list.
  2109. for index in xrange(len(list_actions) - 1, -1, -1):
  2110. if list_actions[index] == 0:
  2111. # Dump anything with action 0 (exclude). Keep anything with action 1
  2112. # (include) or -1 (no include or exclude seen for the item).
  2113. excluded_list.insert(0, the_list[index])
  2114. del the_list[index]
  2115. # If anything was excluded, put the excluded list into the_dict at
  2116. # excluded_key.
  2117. if len(excluded_list) > 0:
  2118. the_dict[excluded_key] = excluded_list
  2119. # Now recurse into subdicts and lists that may contain dicts.
  2120. for key, value in the_dict.iteritems():
  2121. if type(value) is dict:
  2122. ProcessListFiltersInDict(key, value)
  2123. elif type(value) is list:
  2124. ProcessListFiltersInList(key, value)
  2125. def ProcessListFiltersInList(name, the_list):
  2126. for item in the_list:
  2127. if type(item) is dict:
  2128. ProcessListFiltersInDict(name, item)
  2129. elif type(item) is list:
  2130. ProcessListFiltersInList(name, item)
  2131. def ValidateTargetType(target, target_dict):
  2132. """Ensures the 'type' field on the target is one of the known types.
  2133. Arguments:
  2134. target: string, name of target.
  2135. target_dict: dict, target spec.
  2136. Raises an exception on error.
  2137. """
  2138. VALID_TARGET_TYPES = ('executable', 'loadable_module',
  2139. 'static_library', 'shared_library',
  2140. 'mac_kernel_extension', 'none')
  2141. target_type = target_dict.get('type', None)
  2142. if target_type not in VALID_TARGET_TYPES:
  2143. raise GypError("Target %s has an invalid target type '%s'. "
  2144. "Must be one of %s." %
  2145. (target, target_type, '/'.join(VALID_TARGET_TYPES)))
  2146. if (target_dict.get('standalone_static_library', 0) and
  2147. not target_type == 'static_library'):
  2148. raise GypError('Target %s has type %s but standalone_static_library flag is'
  2149. ' only valid for static_library type.' % (target,
  2150. target_type))
  2151. def ValidateSourcesInTarget(target, target_dict, build_file,
  2152. duplicate_basename_check):
  2153. if not duplicate_basename_check:
  2154. return
  2155. if target_dict.get('type', None) != 'static_library':
  2156. return
  2157. sources = target_dict.get('sources', [])
  2158. basenames = {}
  2159. for source in sources:
  2160. name, ext = os.path.splitext(source)
  2161. is_compiled_file = ext in [
  2162. '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S']
  2163. if not is_compiled_file:
  2164. continue
  2165. basename = os.path.basename(name) # Don't include extension.
  2166. basenames.setdefault(basename, []).append(source)
  2167. error = ''
  2168. for basename, files in basenames.iteritems():
  2169. if len(files) > 1:
  2170. error += ' %s: %s\n' % (basename, ' '.join(files))
  2171. if error:
  2172. print('static library %s has several files with the same basename:\n' %
  2173. target + error + 'libtool on Mac cannot handle that. Use '
  2174. '--no-duplicate-basename-check to disable this validation.')
  2175. raise GypError('Duplicate basenames in sources section, see list above')
  2176. def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules):
  2177. """Ensures that the rules sections in target_dict are valid and consistent,
  2178. and determines which sources they apply to.
  2179. Arguments:
  2180. target: string, name of target.
  2181. target_dict: dict, target spec containing "rules" and "sources" lists.
  2182. extra_sources_for_rules: a list of keys to scan for rule matches in
  2183. addition to 'sources'.
  2184. """
  2185. # Dicts to map between values found in rules' 'rule_name' and 'extension'
  2186. # keys and the rule dicts themselves.
  2187. rule_names = {}
  2188. rule_extensions = {}
  2189. rules = target_dict.get('rules', [])
  2190. for rule in rules:
  2191. # Make sure that there's no conflict among rule names and extensions.
  2192. rule_name = rule['rule_name']
  2193. if rule_name in rule_names:
  2194. raise GypError('rule %s exists in duplicate, target %s' %
  2195. (rule_name, target))
  2196. rule_names[rule_name] = rule
  2197. rule_extension = rule['extension']
  2198. if rule_extension.startswith('.'):
  2199. rule_extension = rule_extension[1:]
  2200. if rule_extension in rule_extensions:
  2201. raise GypError(('extension %s associated with multiple rules, ' +
  2202. 'target %s rules %s and %s') %
  2203. (rule_extension, target,
  2204. rule_extensions[rule_extension]['rule_name'],
  2205. rule_name))
  2206. rule_extensions[rule_extension] = rule
  2207. # Make sure rule_sources isn't already there. It's going to be
  2208. # created below if needed.
  2209. if 'rule_sources' in rule:
  2210. raise GypError(
  2211. 'rule_sources must not exist in input, target %s rule %s' %
  2212. (target, rule_name))
  2213. rule_sources = []
  2214. source_keys = ['sources']
  2215. source_keys.extend(extra_sources_for_rules)
  2216. for source_key in source_keys:
  2217. for source in target_dict.get(source_key, []):
  2218. (source_root, source_extension) = os.path.splitext(source)
  2219. if source_extension.startswith('.'):
  2220. source_extension = source_extension[1:]
  2221. if source_extension == rule_extension:
  2222. rule_sources.append(source)
  2223. if len(rule_sources) > 0:
  2224. rule['rule_sources'] = rule_sources
  2225. def ValidateRunAsInTarget(target, target_dict, build_file):
  2226. target_name = target_dict.get('target_name')
  2227. run_as = target_dict.get('run_as')
  2228. if not run_as:
  2229. return
  2230. if type(run_as) is not dict:
  2231. raise GypError("The 'run_as' in target %s from file %s should be a "
  2232. "dictionary." %
  2233. (target_name, build_file))
  2234. action = run_as.get('action')
  2235. if not action:
  2236. raise GypError("The 'run_as' in target %s from file %s must have an "
  2237. "'action' section." %
  2238. (target_name, build_file))
  2239. if type(action) is not list:
  2240. raise GypError("The 'action' for 'run_as' in target %s from file %s "
  2241. "must be a list." %
  2242. (target_name, build_file))
  2243. working_directory = run_as.get('working_directory')
  2244. if working_directory and type(working_directory) is not str:
  2245. raise GypError("The 'working_directory' for 'run_as' in target %s "
  2246. "in file %s should be a string." %
  2247. (target_name, build_file))
  2248. environment = run_as.get('environment')
  2249. if environment and type(environment) is not dict:
  2250. raise GypError("The 'environment' for 'run_as' in target %s "
  2251. "in file %s should be a dictionary." %
  2252. (target_name, build_file))
  2253. def ValidateActionsInTarget(target, target_dict, build_file):
  2254. '''Validates the inputs to the actions in a target.'''
  2255. target_name = target_dict.get('target_name')
  2256. actions = target_dict.get('actions', [])
  2257. for action in actions:
  2258. action_name = action.get('action_name')
  2259. if not action_name:
  2260. raise GypError("Anonymous action in target %s. "
  2261. "An action must have an 'action_name' field." %
  2262. target_name)
  2263. inputs = action.get('inputs', None)
  2264. if inputs is None:
  2265. raise GypError('Action in target %s has no inputs.' % target_name)
  2266. action_command = action.get('action')
  2267. if action_command and not action_command[0]:
  2268. raise GypError("Empty action as command in target %s." % target_name)
  2269. def TurnIntIntoStrInDict(the_dict):
  2270. """Given dict the_dict, recursively converts all integers into strings.
  2271. """
  2272. # Use items instead of iteritems because there's no need to try to look at
  2273. # reinserted keys and their associated values.
  2274. for k, v in the_dict.items():
  2275. if type(v) is int:
  2276. v = str(v)
  2277. the_dict[k] = v
  2278. elif type(v) is dict:
  2279. TurnIntIntoStrInDict(v)
  2280. elif type(v) is list:
  2281. TurnIntIntoStrInList(v)
  2282. if type(k) is int:
  2283. del the_dict[k]
  2284. the_dict[str(k)] = v
  2285. def TurnIntIntoStrInList(the_list):
  2286. """Given list the_list, recursively converts all integers into strings.
  2287. """
  2288. for index in xrange(0, len(the_list)):
  2289. item = the_list[index]
  2290. if type(item) is int:
  2291. the_list[index] = str(item)
  2292. elif type(item) is dict:
  2293. TurnIntIntoStrInDict(item)
  2294. elif type(item) is list:
  2295. TurnIntIntoStrInList(item)
  2296. def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets,
  2297. data):
  2298. """Return only the targets that are deep dependencies of |root_targets|."""
  2299. qualified_root_targets = []
  2300. for target in root_targets:
  2301. target = target.strip()
  2302. qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list)
  2303. if not qualified_targets:
  2304. raise GypError("Could not find target %s" % target)
  2305. qualified_root_targets.extend(qualified_targets)
  2306. wanted_targets = {}
  2307. for target in qualified_root_targets:
  2308. wanted_targets[target] = targets[target]
  2309. for dependency in dependency_nodes[target].DeepDependencies():
  2310. wanted_targets[dependency] = targets[dependency]
  2311. wanted_flat_list = [t for t in flat_list if t in wanted_targets]
  2312. # Prune unwanted targets from each build_file's data dict.
  2313. for build_file in data['target_build_files']:
  2314. if not 'targets' in data[build_file]:
  2315. continue
  2316. new_targets = []
  2317. for target in data[build_file]['targets']:
  2318. qualified_name = gyp.common.QualifiedTarget(build_file,
  2319. target['target_name'],
  2320. target['toolset'])
  2321. if qualified_name in wanted_targets:
  2322. new_targets.append(target)
  2323. data[build_file]['targets'] = new_targets
  2324. return wanted_targets, wanted_flat_list
  2325. def VerifyNoCollidingTargets(targets):
  2326. """Verify that no two targets in the same directory share the same name.
  2327. Arguments:
  2328. targets: A list of targets in the form 'path/to/file.gyp:target_name'.
  2329. """
  2330. # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'.
  2331. used = {}
  2332. for target in targets:
  2333. # Separate out 'path/to/file.gyp, 'target_name' from
  2334. # 'path/to/file.gyp:target_name'.
  2335. path, name = target.rsplit(':', 1)
  2336. # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'.
  2337. subdir, gyp = os.path.split(path)
  2338. # Use '.' for the current directory '', so that the error messages make
  2339. # more sense.
  2340. if not subdir:
  2341. subdir = '.'
  2342. # Prepare a key like 'path/to:target_name'.
  2343. key = subdir + ':' + name
  2344. if key in used:
  2345. # Complain if this target is already used.
  2346. raise GypError('Duplicate target name "%s" in directory "%s" used both '
  2347. 'in "%s" and "%s".' % (name, subdir, gyp, used[key]))
  2348. used[key] = gyp
  2349. def SetGeneratorGlobals(generator_input_info):
  2350. # Set up path_sections and non_configuration_keys with the default data plus
  2351. # the generator-specific data.
  2352. global path_sections
  2353. path_sections = set(base_path_sections)
  2354. path_sections.update(generator_input_info['path_sections'])
  2355. global non_configuration_keys
  2356. non_configuration_keys = base_non_configuration_keys[:]
  2357. non_configuration_keys.extend(generator_input_info['non_configuration_keys'])
  2358. global multiple_toolsets
  2359. multiple_toolsets = generator_input_info[
  2360. 'generator_supports_multiple_toolsets']
  2361. global generator_filelist_paths
  2362. generator_filelist_paths = generator_input_info['generator_filelist_paths']
  2363. def Load(build_files, variables, includes, depth, generator_input_info, check,
  2364. circular_check, duplicate_basename_check, parallel, root_targets):
  2365. SetGeneratorGlobals(generator_input_info)
  2366. # A generator can have other lists (in addition to sources) be processed
  2367. # for rules.
  2368. extra_sources_for_rules = generator_input_info['extra_sources_for_rules']
  2369. # Load build files. This loads every target-containing build file into
  2370. # the |data| dictionary such that the keys to |data| are build file names,
  2371. # and the values are the entire build file contents after "early" or "pre"
  2372. # processing has been done and includes have been resolved.
  2373. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as
  2374. # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps
  2375. # track of the keys corresponding to "target" files.
  2376. data = {'target_build_files': set()}
  2377. # Normalize paths everywhere. This is important because paths will be
  2378. # used as keys to the data dict and for references between input files.
  2379. build_files = set(map(os.path.normpath, build_files))
  2380. if parallel:
  2381. LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth,
  2382. check, generator_input_info)
  2383. else:
  2384. aux_data = {}
  2385. for build_file in build_files:
  2386. try:
  2387. LoadTargetBuildFile(build_file, data, aux_data,
  2388. variables, includes, depth, check, True)
  2389. except Exception, e:
  2390. gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file)
  2391. raise
  2392. # Build a dict to access each target's subdict by qualified name.
  2393. targets = BuildTargetsDict(data)
  2394. # Fully qualify all dependency links.
  2395. QualifyDependencies(targets)
  2396. # Remove self-dependencies from targets that have 'prune_self_dependencies'
  2397. # set to 1.
  2398. RemoveSelfDependencies(targets)
  2399. # Expand dependencies specified as build_file:*.
  2400. ExpandWildcardDependencies(targets, data)
  2401. # Remove all dependencies marked as 'link_dependency' from the targets of
  2402. # type 'none'.
  2403. RemoveLinkDependenciesFromNoneTargets(targets)
  2404. # Apply exclude (!) and regex (/) list filters only for dependency_sections.
  2405. for target_name, target_dict in targets.iteritems():
  2406. tmp_dict = {}
  2407. for key_base in dependency_sections:
  2408. for op in ('', '!', '/'):
  2409. key = key_base + op
  2410. if key in target_dict:
  2411. tmp_dict[key] = target_dict[key]
  2412. del target_dict[key]
  2413. ProcessListFiltersInDict(target_name, tmp_dict)
  2414. # Write the results back to |target_dict|.
  2415. for key in tmp_dict:
  2416. target_dict[key] = tmp_dict[key]
  2417. # Make sure every dependency appears at most once.
  2418. RemoveDuplicateDependencies(targets)
  2419. if circular_check:
  2420. # Make sure that any targets in a.gyp don't contain dependencies in other
  2421. # .gyp files that further depend on a.gyp.
  2422. VerifyNoGYPFileCircularDependencies(targets)
  2423. [dependency_nodes, flat_list] = BuildDependencyList(targets)
  2424. if root_targets:
  2425. # Remove, from |targets| and |flat_list|, the targets that are not deep
  2426. # dependencies of the targets specified in |root_targets|.
  2427. targets, flat_list = PruneUnwantedTargets(
  2428. targets, flat_list, dependency_nodes, root_targets, data)
  2429. # Check that no two targets in the same directory have the same name.
  2430. VerifyNoCollidingTargets(flat_list)
  2431. # Handle dependent settings of various types.
  2432. for settings_type in ['all_dependent_settings',
  2433. 'direct_dependent_settings',
  2434. 'link_settings']:
  2435. DoDependentSettings(settings_type, flat_list, targets, dependency_nodes)
  2436. # Take out the dependent settings now that they've been published to all
  2437. # of the targets that require them.
  2438. for target in flat_list:
  2439. if settings_type in targets[target]:
  2440. del targets[target][settings_type]
  2441. # Make sure static libraries don't declare dependencies on other static
  2442. # libraries, but that linkables depend on all unlinked static libraries
  2443. # that they need so that their link steps will be correct.
  2444. gii = generator_input_info
  2445. if gii['generator_wants_static_library_dependencies_adjusted']:
  2446. AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes,
  2447. gii['generator_wants_sorted_dependencies'])
  2448. # Apply "post"/"late"/"target" variable expansions and condition evaluations.
  2449. for target in flat_list:
  2450. target_dict = targets[target]
  2451. build_file = gyp.common.BuildFile(target)
  2452. ProcessVariablesAndConditionsInDict(
  2453. target_dict, PHASE_LATE, variables, build_file)
  2454. # Move everything that can go into a "configurations" section into one.
  2455. for target in flat_list:
  2456. target_dict = targets[target]
  2457. SetUpConfigurations(target, target_dict)
  2458. # Apply exclude (!) and regex (/) list filters.
  2459. for target in flat_list:
  2460. target_dict = targets[target]
  2461. ProcessListFiltersInDict(target, target_dict)
  2462. # Apply "latelate" variable expansions and condition evaluations.
  2463. for target in flat_list:
  2464. target_dict = targets[target]
  2465. build_file = gyp.common.BuildFile(target)
  2466. ProcessVariablesAndConditionsInDict(
  2467. target_dict, PHASE_LATELATE, variables, build_file)
  2468. # Make sure that the rules make sense, and build up rule_sources lists as
  2469. # needed. Not all generators will need to use the rule_sources lists, but
  2470. # some may, and it seems best to build the list in a common spot.
  2471. # Also validate actions and run_as elements in targets.
  2472. for target in flat_list:
  2473. target_dict = targets[target]
  2474. build_file = gyp.common.BuildFile(target)
  2475. ValidateTargetType(target, target_dict)
  2476. ValidateSourcesInTarget(target, target_dict, build_file,
  2477. duplicate_basename_check)
  2478. ValidateRulesInTarget(target, target_dict, extra_sources_for_rules)
  2479. ValidateRunAsInTarget(target, target_dict, build_file)
  2480. ValidateActionsInTarget(target, target_dict, build_file)
  2481. # Generators might not expect ints. Turn them into strs.
  2482. TurnIntIntoStrInDict(data)
  2483. # TODO(mark): Return |data| for now because the generator needs a list of
  2484. # build files that came in. In the future, maybe it should just accept
  2485. # a list, and not the whole data dict.
  2486. return [flat_list, targets, data]