5cb34a7c4ecbd98a27a68078cb5401445ec14205afae420b49546a3332914a1af54d34f60190d936e8098b0aa587cdcf96cab054122a6ce497432b6945a110 124 KB

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