Debian Codegraph @

mesonbuild/backend/xcodebackend.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2014-2021 The Meson development team
3
4 from __future__ import annotations
5
6 import functools, uuid, os, operator, re
7 import typing as T
8
9 from . import backends
10 from .. import build
11 from .. import compilers
12 from .. import mesonlib
13 from .. import mlog
14 from ..arglist import CompilerArgs
15 from ..dependencies.platform import AppleFrameworks
16 from ..mesonlib import MesonBugException, MesonException
17 from ..linkers import StaticLinker
18 from ..options import OptionKey
19
20 if T.TYPE_CHECKING:
21 from ..build import BuildTarget
22 from ..compilers import Compiler
23
24 PbxDictItemTypes = T.TypeVar('PbxDictItemTypes', 'PbxArray', 'PbxDict', str, int)
25
26 INDENT = '\t'
27
28 XCODETYPEMAP: T.Mapping[str, str] = {
29 'c': 'sourcecode.c.c',
30 'a': 'archive.ar',
31 'cc': 'sourcecode.cpp.cpp',
32 'cxx': 'sourcecode.cpp.cpp',
33 'cpp': 'sourcecode.cpp.cpp',
34 'c++': 'sourcecode.cpp.cpp',
35 'm': 'sourcecode.c.objc',
36 'mm': 'sourcecode.cpp.objcpp',
37 'h': 'sourcecode.c.h',
38 'hpp': 'sourcecode.cpp.h',
39 'hxx': 'sourcecode.cpp.h',
40 'hh': 'sourcecode.cpp.hh',
41 'inc': 'sourcecode.c.h',
42 'swift': 'sourcecode.swift',
43 'dylib': 'compiled.mach-o.dylib',
44 'o': 'compiled.mach-o.objfile',
45 's': 'sourcecode.asm',
46 'asm': 'sourcecode.nasm',
47 'metal': 'sourcecode.metal',
48 'glsl': 'sourcecode.glsl',
49 }
50
51 NEEDS_CUSTOM_RULES: T.Mapping[str, str] = {
52 'nasm': 'sourcecode.nasm',
53 }
54
55 LANGNAMEMAP: T.Mapping[str, str] = {
56 'c': 'C',
57 'cpp': 'CPLUSPLUS',
58 'objc': 'OBJC',
59 'objcpp': 'OBJCPLUSPLUS',
60 'swift': 'SWIFT_'
61 }
62
63 OPT2XCODEOPT: T.Mapping[str, str | None] = {
64 'plain': None,
65 '0': '0',
66 'g': '0',
67 '1': '1',
68 '2': '2',
69 '3': '3',
70 's': 's',
71 }
72
73 BOOL2XCODEBOOL: T.Mapping[bool, str] = {True: 'YES', False: 'NO'}
74
75 LINKABLE_EXTENSIONS: T.AbstractSet[str] = {'.o', '.a', '.obj', '.so', '.dylib'}
76
77 XCODEVERSIONS: T.Mapping[str, tuple[str, int]] = {
78 '1500': ('Xcode 15.0', 60),
79 '1400': ('Xcode 14.0', 56),
80 '1300': ('Xcode 13.0', 55),
81 '1200': ('Xcode 12.0', 54),
82 '1140': ('Xcode 11.4', 53),
83 '1100': ('Xcode 11.0', 52),
84 '1000': ('Xcode 10.0', 51),
85 '930': ('Xcode 9.3', 50),
86 '800': ('Xcode 8.0', 48),
87 '630': ('Xcode 6.3', 47),
88 '320': ('Xcode 3.2', 46),
89 '310': ('Xcode 3.1', 45)
90 }
91
92 def autodetect_xcode_version() -> T.Tuple[str, int]:
93 try:
94 pc, stdout, stderr = mesonlib.Popen_safe(['xcodebuild', '-version'])
95 except FileNotFoundError:
96 raise MesonException('Could not detect Xcode. Please install it if you wish to use the Xcode backend.')
97 if pc.returncode != 0:
98 raise MesonException(f'An error occurred while detecting Xcode: {stderr}')
99 version = int(''.join(re.search(r'\d*\.\d*\.*\d*', stdout).group(0).split('.')))
100 # If the version number does not have two decimal points, pretend it does.
101 if stdout.count('.') < 2:
102 version *= 10
103 for v, r in XCODEVERSIONS.items():
104 if int(v) <= version:
105 return r
106 raise MesonException('Your Xcode installation is too old and is not supported.')
107
108 class FileTreeEntry:
109
110 def __init__(self) -> None:
111 self.subdirs: T.Dict[str, FileTreeEntry] = {}
112 self.targets: T.List[build.BuildTarget] = []
113
114 class PbxArray:
115 def __init__(self) -> None:
116 self.items: T.List[PbxArrayItem] = []
117
118 def add_item(self, item: T.Union[PbxArrayItem, str], comment: str = '') -> None:
119 if isinstance(item, PbxArrayItem):
120 self.items.append(item)
121 else:
122 self.items.append(PbxArrayItem(item, comment))
123
124 def write(self, ofile: T.TextIO, indent_level: int) -> None:
125 ofile.write('(\n')
126 indent_level += 1
127 for i in self.items:
128 if i.comment:
129 ofile.write(indent_level*INDENT + f'{i.value} {i.comment},\n')
130 else:
131 ofile.write(indent_level*INDENT + f'{i.value},\n')
132 indent_level -= 1
133 ofile.write(indent_level*INDENT + ');\n')
134
135 class PbxArrayItem:
136 def __init__(self, value: str, comment: str = ''):
137 self.value = value
138 if comment:
139 if '/*' in comment:
140 self.comment = comment
141 else:
142 self.comment = f'/* {comment} */'
143 else:
144 self.comment = comment
145
146 class PbxComment:
147 def __init__(self, text: str):
148 assert '/*' not in text
149 self.text = f'/* {text} */'
150
151 def write(self, ofile: T.TextIO, indent_level: int) -> None:
152 ofile.write(f'\n{self.text}\n')
153
154 class PbxDictItem:
155 value: PbxArray | PbxDict | str | int
156
157 def __init__(self, key: str, value: T.Union[PbxArray, PbxDict, str, int], comment: str = ''):
158 self.key = key
159 if isinstance(value, str):
160 self.value = self.quote_value(value)
161 else:
162 self.value = value
163
164 if comment:
165 if '/*' in comment:
166 self.comment = comment
167 else:
168 self.comment = f'/* {comment} */'
169 else:
170 self.comment = comment
171
172 def quote_value(self, value: str) -> str:
173 quoted = f'"{value}"'
174
175 if not value:
176 return quoted
177
178 if set(' +@$<>/').isdisjoint(value) or value[0] == '"':
179 return value
180
181 return quoted
182
183
184 class PbxDict:
185 def __init__(self) -> None:
186 # This class is a bit weird, because we want to write PBX dicts in
187 # defined order _and_ we want to write intermediate comments also in order.
188 self.keys: T.Set[str] = set()
189 self.items: T.List[T.Union[PbxDictItem, PbxComment]] = []
190
191 def add_item(self, key: str, value: T.Union[PbxArray, PbxDict, str, int], comment: str = '') -> None:
192 assert key not in self.keys
193 item = PbxDictItem(key, value, comment)
194 self.keys.add(key)
195 self.items.append(item)
196
197 def get_item(self, key: str) -> PbxDictItem:
198 assert key in self.keys
199 for item in self.items:
200 if not isinstance(item, PbxDictItem):
201 continue
202 if item.key == key:
203 return item
204 return None
205
206 def get_item_value(self, key: str, type_: type[PbxDictItemTypes]) -> PbxDictItemTypes:
207 i = self.get_item(key).value
208 if not isinstance(i, type_):
209 raise MesonBugException(f'Attempted to get the wrong type for key {key}, expected {type_} but got {type(i)}')
210 return i
211
212 def has_item(self, key: str) -> bool:
213 return key in self.keys
214
215 def add_comment(self, comment: PbxComment) -> None:
216 assert isinstance(comment, PbxComment)
217 self.items.append(comment)
218
219 def write(self, ofile: T.TextIO, indent_level: int) -> None:
220 ofile.write('{\n')
221 indent_level += 1
222 for i in self.items:
223 if isinstance(i, PbxComment):
224 i.write(ofile, indent_level)
225 elif isinstance(i, PbxDictItem):
226 if isinstance(i.value, (str, int)):
227 if i.comment:
228 ofile.write(indent_level*INDENT + f'{i.key} = {i.value} {i.comment};\n')
229 else:
230 ofile.write(indent_level*INDENT + f'{i.key} = {i.value};\n')
231 elif isinstance(i.value, PbxDict):
232 if i.comment:
233 ofile.write(indent_level*INDENT + f'{i.key} {i.comment} = ')
234 else:
235 ofile.write(indent_level*INDENT + f'{i.key} = ')
236 i.value.write(ofile, indent_level)
237 elif isinstance(i.value, PbxArray):
238 if i.comment:
239 ofile.write(indent_level*INDENT + f'{i.key} {i.comment} = ')
240 else:
241 ofile.write(indent_level*INDENT + f'{i.key} = ')
242 i.value.write(ofile, indent_level)
243 else:
244 print(i)
245 print(i.key)
246 print(i.value)
247 raise RuntimeError('missing code')
248 else:
249 print(i)
250 raise RuntimeError('missing code2')
251
252 indent_level -= 1
253 ofile.write(indent_level*INDENT + '}')
254 if indent_level == 0:
255 ofile.write('\n')
256 else:
257 ofile.write(';\n')
258
259 class XCodeBackend(backends.Backend):
260
261 name = 'xcode'
262
263 def __init__(self, build: T.Optional[build.Build]):
264 super().__init__(build)
265 self.project_uid = self.environment.coredata.lang_guids['default'].replace('-', '')[:24]
266 self.buildtype = T.cast('str', self.environment.coredata.optstore.get_value_for(OptionKey('buildtype')))
267 self.project_conflist = self.gen_id()
268 self.maingroup_id = self.gen_id()
269 self.all_id = self.gen_id()
270 self.all_buildconf_id = self.gen_id()
271 self.buildtypes = [self.buildtype]
272 self.test_id = self.gen_id()
273 self.test_command_id = self.gen_id()
274 self.test_buildconf_id = self.gen_id()
275 self.regen_id = self.gen_id()
276 self.regen_command_id = self.gen_id()
277 self.regen_buildconf_id = self.gen_id()
278 self.regen_dependency_id = self.gen_id()
279 self.top_level_dict = PbxDict()
280 self.generator_outputs: dict[tuple[str, int], list[str]] = {}
281 self.set_arch()
282 self.xcodeversion, self.objversion = autodetect_xcode_version()
283 # In Xcode files are not accessed via their file names, but rather every one of them
284 # gets an unique id. More precisely they get one unique id per target they are used
285 # in. If you generate only one id per file and use them, compilation will work but the
286 # UI will only show the file in one target but not the others. Thus they key is
287 # a tuple containing the target and filename.
288 self.buildfile_ids: dict[tuple[str, str] | str, str] = {}
289 # That is not enough, though. Each target/file combination also gets a unique id
290 # in the file reference section. Because why not. This means that a source file
291 # that is used in two targets gets a total of four unique ID numbers.
292 self.fileref_ids: dict[tuple[str, str] | str, str] = {}
293
294 self.buildphase_map: dict[str, dict[str, str]] = {}
295
296 def write_pbxfile(self, top_level_dict: PbxDict, ofilename: str) -> None:
297 tmpname = ofilename + '.tmp'
298 with open(tmpname, 'w', encoding='utf-8') as ofile:
299 ofile.write('// !$*UTF8*$!\n')
300 top_level_dict.write(ofile, 0)
301 os.replace(tmpname, ofilename)
302
303 def gen_id(self) -> str:
304 return str(uuid.uuid4()).upper().replace('-', '')[:24]
305
306 @functools.lru_cache(maxsize=None)
307 def get_target_dir_cached(self, target: build.Target) -> str:
308 dirname = os.path.join(target.get_subdir(), T.cast('str', self.environment.coredata.optstore.get_value_for(OptionKey('buildtype'))))
309 return dirname
310
311 def get_custom_target_output_dir(self, target: build.AnyTargetType) -> str:
312 dirname = target.get_subdir()
313 os.makedirs(os.path.join(self.environment.get_build_dir(), dirname), exist_ok=True)
314 return dirname
315
316 def object_filename_from_source(self, target: build.BuildTarget, compiler: Compiler,
317 source: mesonlib.File, targetdir: T.Optional[str] = None) -> str:
318 # Xcode has the following naming scheme:
319 # projectname.build/debug/[email protected]/Objects-normal/x86_64/func.o
320 project = self.build.project_name
321 buildtype = self.buildtype
322 tname = target.get_id()
323 stem = os.path.splitext(os.path.basename(source.fname))[0]
324 # Append "build" before the actual object path to match OBJROOT
325 obj_path = f'build/{project}.build/{buildtype}/{tname}.build/Objects-normal/{self.arch}/{stem}.o'
326 return obj_path
327
328 def determine_swift_dep_dirs(self, target: build.BuildTarget) -> T.List[str]:
329 result: T.List[str] = []
330 for l in target.link_targets:
331 # Xcode does not recognize our private directories, so we have to use its build directories instead.
332 result.append(os.path.join(self.environment.get_build_dir(), self.get_target_dir(l)))
333 return result
334
335 def set_arch(self) -> None:
336 self.arch = self.build.environment.machines.host.cpu
337 if self.arch == 'aarch64':
338 self.arch = 'arm64'
339
340 def generate(self, capture: bool = False, vslite_ctx: T.Optional[T.Dict] = None) -> None:
341 if self.arch is None: # The host machine arch may not be set when backend is created
342 self.set_arch()
343 # Check for (currently) unexpected capture arg use cases -
344 if capture:
345 raise MesonBugException('We do not expect the xcode backend to generate with \'capture = True\'')
346 if vslite_ctx:
347 raise MesonBugException('We do not expect the xcode backend to be given a valid \'vslite_ctx\'')
348 self.serialize_tests()
349 # Cache the result as the method rebuilds the array every time it is called.
350 self.build_targets = self.build.get_build_targets()
351 self.custom_targets = self.build.get_custom_targets()
352 self.generate_filemap()
353 if self.objversion < 50:
354 self.generate_buildstylemap()
355 self.generate_build_phase_map()
356 self.generate_build_configuration_map()
357 self.generate_build_configurationlist_map()
358 self.generate_project_configurations_map()
359 self.generate_buildall_configurations_map()
360 self.generate_test_configurations_map()
361 self.generate_native_target_map()
362 self.generate_native_frameworks_map()
363 self.generate_custom_target_map()
364 self.generate_native_target_build_rules_map()
365 self.generate_generator_target_map()
366 self.generate_source_phase_map()
367 self.generate_target_dependency_map()
368 self.generate_pbxdep_map()
369 self.generate_containerproxy_map()
370 self.generate_target_file_maps()
371 self.generate_build_file_maps()
372 self.proj_dir = os.path.join(self.environment.get_build_dir(), self.build.project_name + '.xcodeproj')
373 os.makedirs(self.proj_dir, exist_ok=True)
374 self.proj_file = os.path.join(self.proj_dir, 'project.pbxproj')
375 objects_dict = self.generate_prefix(self.top_level_dict)
376 objects_dict.add_comment(PbxComment('Begin PBXAggregateTarget section'))
377 self.generate_pbx_aggregate_target(objects_dict)
378 objects_dict.add_comment(PbxComment('End PBXAggregateTarget section'))
379 objects_dict.add_comment(PbxComment('Begin PBXBuildFile section'))
380 self.generate_pbx_build_file(objects_dict)
381 objects_dict.add_comment(PbxComment('End PBXBuildFile section'))
382 objects_dict.add_comment(PbxComment('Begin PBXBuildRule section'))
383 self.generate_pbx_build_rule(objects_dict)
384 objects_dict.add_comment(PbxComment('End PBXBuildRule section'))
385 objects_dict.add_comment(PbxComment('Begin PBXBuildStyle section'))
386 if self.objversion < 50:
387 self.generate_pbx_build_style(objects_dict)
388 objects_dict.add_comment(PbxComment('End PBXBuildStyle section'))
389 objects_dict.add_comment(PbxComment('Begin PBXContainerItemProxy section'))
390 self.generate_pbx_container_item_proxy(objects_dict)
391 objects_dict.add_comment(PbxComment('End PBXContainerItemProxy section'))
392 objects_dict.add_comment(PbxComment('Begin PBXFileReference section'))
393 self.generate_pbx_file_reference(objects_dict)
394 objects_dict.add_comment(PbxComment('End PBXFileReference section'))
395 objects_dict.add_comment(PbxComment('Begin PBXFrameworksBuildPhase section'))
396 self.generate_pbx_frameworks_buildphase(objects_dict)
397 objects_dict.add_comment(PbxComment('End PBXFrameworksBuildPhase section'))
398 objects_dict.add_comment(PbxComment('Begin PBXGroup section'))
399 self.generate_pbx_group(objects_dict)
400 objects_dict.add_comment(PbxComment('End PBXGroup section'))
401 objects_dict.add_comment(PbxComment('Begin PBXNativeTarget section'))
402 self.generate_pbx_native_target(objects_dict)
403 objects_dict.add_comment(PbxComment('End PBXNativeTarget section'))
404 objects_dict.add_comment(PbxComment('Begin PBXProject section'))
405 self.generate_pbx_project(objects_dict)
406 objects_dict.add_comment(PbxComment('End PBXProject section'))
407 objects_dict.add_comment(PbxComment('Begin PBXShellScriptBuildPhase section'))
408 self.generate_pbx_shell_build_phase(objects_dict)
409 objects_dict.add_comment(PbxComment('End PBXShellScriptBuildPhase section'))
410 objects_dict.add_comment(PbxComment('Begin PBXSourcesBuildPhase section'))
411 self.generate_pbx_sources_build_phase(objects_dict)
412 objects_dict.add_comment(PbxComment('End PBXSourcesBuildPhase section'))
413 objects_dict.add_comment(PbxComment('Begin PBXTargetDependency section'))
414 self.generate_pbx_target_dependency(objects_dict)
415 objects_dict.add_comment(PbxComment('End PBXTargetDependency section'))
416 objects_dict.add_comment(PbxComment('Begin XCBuildConfiguration section'))
417 self.generate_xc_build_configuration(objects_dict)
418 objects_dict.add_comment(PbxComment('End XCBuildConfiguration section'))
419 objects_dict.add_comment(PbxComment('Begin XCConfigurationList section'))
420 self.generate_xc_configurationList(objects_dict)
421 objects_dict.add_comment(PbxComment('End XCConfigurationList section'))
422 self.generate_suffix(self.top_level_dict)
423 self.write_pbxfile(self.top_level_dict, self.proj_file)
424 self.generate_regen_info()
425
426 def get_xcodetype(self, fname: str) -> str:
427 extension = fname.split('.')[-1]
428 if extension == 'C':
429 extension = 'cpp'
430 xcodetype = XCODETYPEMAP.get(extension.lower())
431 if not xcodetype:
432 xcodetype = 'sourcecode.unknown'
433 return xcodetype
434
435 def generate_filemap(self) -> None:
436 self.filemap: dict[str, str] = {} # Key is source file relative to src root.
437 self.foldermap: dict[tuple[str, build.BuildTarget], str] = {}
438 self.target_filemap: dict[str, str] = {}
439 for name, t in self.build_targets.items():
440 for s in t.sources:
441 if isinstance(s, mesonlib.File):
442 if '/' in s.fname:
443 # From the top level down, add the folders containing the source file.
444 folder = os.path.split(os.path.dirname(s.fname))
445 while folder:
446 fpath = os.path.join(*folder)
447 # Multiple targets might use the same folders, so store their targets with them.
448 # Otherwise, folders and their source files will appear in the wrong places in Xcode.
449 if (fpath, t) not in self.foldermap:
450 self.foldermap[(fpath, t)] = self.gen_id()
451 else:
452 break
453 folder = folder[:-1]
454 s = os.path.join(s.subdir, s.fname)
455 self.filemap[s] = self.gen_id()
456 for o in t.objects:
457 if isinstance(o, str):
458 o = os.path.join(t.subdir, o)
459 self.filemap[o] = self.gen_id()
460 for e in t.extra_files:
461 if isinstance(e, mesonlib.File):
462 e = os.path.join(e.subdir, e.fname)
463 self.filemap[e] = self.gen_id()
464 else:
465 e = os.path.join(t.subdir, e)
466 self.filemap[e] = self.gen_id()
467 self.target_filemap[name] = self.gen_id()
468
469 def generate_buildstylemap(self) -> None:
470 self.buildstylemap = {self.buildtype: self.gen_id()}
471
472 def generate_build_phase_map(self) -> None:
473 for tname, t in self.build_targets.items():
474 # generate id for our own target-name
475 self.buildphase_map[t.id] = {
476 tname: self.gen_id(),
477 # each target can have its own Frameworks/Sources/..., generate
478 # id's for those
479 'Frameworks': self.gen_id(),
480 'Resources': self.gen_id(),
481 'Sources': self.gen_id(),
482 }
483
484 def generate_build_configuration_map(self) -> None:
485 self.buildconfmap = {}
486 for t in self.build_targets:
487 bconfs = {self.buildtype: self.gen_id()}
488 self.buildconfmap[t] = bconfs
489 for t in self.custom_targets:
490 bconfs = {self.buildtype: self.gen_id()}
491 self.buildconfmap[t] = bconfs
492
493 def generate_project_configurations_map(self) -> None:
494 self.project_configurations = {self.buildtype: self.gen_id()}
495
496 def generate_buildall_configurations_map(self) -> None:
497 self.buildall_configurations = {self.buildtype: self.gen_id()}
498
499 def generate_test_configurations_map(self) -> None:
500 self.test_configurations = {self.buildtype: self.gen_id()}
501
502 def generate_build_configurationlist_map(self) -> None:
503 self.buildconflistmap = {}
504 for t in self.build_targets:
505 self.buildconflistmap[t] = self.gen_id()
506 for t in self.custom_targets:
507 self.buildconflistmap[t] = self.gen_id()
508
509 def generate_native_target_map(self) -> None:
510 self.native_targets = {}
511 for t in self.build_targets:
512 self.native_targets[t] = self.gen_id()
513
514 def generate_native_target_build_rules_map(self) -> None:
515 self.build_rules = {}
516 for name, target in self.build_targets.items():
517 languages = {}
518 for language in target.compilers:
519 if language not in NEEDS_CUSTOM_RULES:
520 continue
521 languages[language] = self.gen_id()
522 self.build_rules[name] = languages
523
524 def generate_custom_target_map(self) -> None:
525 self.shell_targets: T.Dict[T.Union[str, T.Tuple[str, int]], str] = {}
526 self.custom_target_output_buildfile = {}
527 self.custom_target_output_fileref = {}
528 for tname, t in self.custom_targets.items():
529 self.shell_targets[tname] = self.gen_id()
530 if not isinstance(t, build.CustomTarget):
531 continue
532 (srcs, ofilenames, cmd) = self.eval_custom_target_command(t)
533 for o in ofilenames:
534 self.custom_target_output_buildfile[o] = self.gen_id()
535 self.custom_target_output_fileref[o] = self.gen_id()
536
537 def generate_generator_target_map(self) -> None:
538 # Generator objects do not have natural unique ids
539 # so use a counter.
540 self.generator_fileref_ids: dict[tuple[str, int], list[str]] = {}
541 self.generator_buildfile_ids: dict[tuple[str, int], list[str]] = {}
542 for tname, t in self.build_targets.items():
543 generator_id = 0
544 for genlist in t.generated:
545 if not isinstance(genlist, build.GeneratedList):
546 continue
547 self.gen_single_target_map(genlist, tname, t, generator_id)
548 generator_id += 1
549 # FIXME add outputs.
550 for tname, t in self.custom_targets.items():
551 generator_id = 0
552 for genlist in t.sources:
553 if not isinstance(genlist, build.GeneratedList):
554 continue
555 self.gen_single_target_map(genlist, tname, t, generator_id)
556 generator_id += 1
557
558 def gen_single_target_map(self, genlist: build.GeneratedList, tname: str,
559 t: build.AnyTargetType, generator_id: int) -> None:
560 k = (tname, generator_id)
561 assert k not in self.shell_targets
562 if genlist.extra_depends:
563 raise NotImplementedError('XCode backend does not support depends for generator.process')
564 self.shell_targets[k] = self.gen_id()
565 ofile_abs: list[str] = []
566 for i in genlist.get_inputs():
567 for o_base in genlist.get_outputs_for(i):
568 o = os.path.join(self.get_target_private_dir(t), o_base)
569 ofile_abs.append(os.path.join(self.environment.get_build_dir(), o))
570 assert k not in self.generator_outputs
571 self.generator_outputs[k] = ofile_abs
572 buildfile_ids: list[str] = []
573 fileref_ids: list[str] = []
574 for i in range(len(ofile_abs)):
575 buildfile_ids.append(self.gen_id())
576 fileref_ids.append(self.gen_id())
577 self.generator_buildfile_ids[k] = buildfile_ids
578 self.generator_fileref_ids[k] = fileref_ids
579
580 def generate_native_frameworks_map(self) -> None:
581 self.native_frameworks = {}
582 self.native_frameworks_fileref = {}
583 for t in self.build_targets.values():
584 for dep in t.get_external_deps():
585 if dep.found() and isinstance(dep, AppleFrameworks):
586 for f in dep.frameworks:
587 self.native_frameworks[f] = self.gen_id()
588 self.native_frameworks_fileref[f] = self.gen_id()
589
590 def generate_target_dependency_map(self) -> None:
591 self.target_dependency_map: T.Dict[T.Union[str, T.Tuple[str, str]], str] = {}
592 for tname, t in self.build_targets.items():
593 for target in t.link_targets:
594 k = (tname, target.get_basename())
595 assert k not in self.target_dependency_map
596 self.target_dependency_map[k] = self.gen_id()
597 for tname, t in self.custom_targets.items():
598 k = tname
599 assert k not in self.target_dependency_map
600 self.target_dependency_map[k] = self.gen_id()
601
602 def generate_pbxdep_map(self) -> None:
603 self.pbx_dep_map = {}
604 self.pbx_custom_dep_map = {}
605 for t in self.build_targets:
606 self.pbx_dep_map[t] = self.gen_id()
607 for t in self.custom_targets:
608 self.pbx_custom_dep_map[t] = self.gen_id()
609
610 def generate_containerproxy_map(self) -> None:
611 self.containerproxy_map = {}
612 for t in self.build_targets:
613 self.containerproxy_map[t] = self.gen_id()
614
615 def generate_target_file_maps(self) -> None:
616 self.generate_target_file_maps_impl(self.build_targets)
617 self.generate_target_file_maps_impl(self.custom_targets)
618
619 def generate_target_file_maps_impl(
620 self, targets: T.Mapping[str, build.BuildTarget | build.CustomTarget]
621 ) -> None:
622 for tname, t in targets.items():
623 for s in t.sources:
624 if not isinstance(s, mesonlib.File):
625 continue
626 s = os.path.join(s.subdir, s.fname)
627 k = (tname, s)
628 assert k not in self.buildfile_ids
629 self.buildfile_ids[k] = self.gen_id()
630 assert k not in self.fileref_ids
631 self.fileref_ids[k] = self.gen_id()
632 if isinstance(t, build.CustomTarget):
633 continue
634 for o in t.objects:
635 if isinstance(o, build.ExtractedObjects):
636 # Extracted objects do not live in "the Xcode world".
637 continue
638 if isinstance(o, mesonlib.File):
639 o = os.path.join(o.subdir, o.fname)
640 if isinstance(o, str):
641 o = os.path.join(t.subdir, o)
642 k = (tname, o)
643 assert k not in self.buildfile_ids
644 self.buildfile_ids[k] = self.gen_id()
645 assert k not in self.fileref_ids
646 self.fileref_ids[k] = self.gen_id()
647 else:
648 raise RuntimeError('Unknown input type ' + str(o))
649 for e in t.extra_files:
650 if isinstance(e, mesonlib.File):
651 e = os.path.join(e.subdir, e.fname)
652 if isinstance(e, str):
653 e = os.path.join(t.subdir, e)
654 k = (tname, e)
655 assert k not in self.buildfile_ids
656 self.buildfile_ids[k] = self.gen_id()
657 assert k not in self.fileref_ids
658 self.fileref_ids[k] = self.gen_id()
659
660 def generate_build_file_maps(self) -> None:
661 for buildfile in self.build.def_files:
662 self.buildfile_ids[buildfile] = self.gen_id()
663 self.fileref_ids[buildfile] = self.gen_id()
664
665 def generate_source_phase_map(self) -> None:
666 self.source_phase = {}
667 for t in self.build_targets:
668 self.source_phase[t] = self.gen_id()
669
670 def generate_pbx_aggregate_target(self, objects_dict: PbxDict) -> None:
671 self.custom_aggregate_targets = {}
672 self.build_all_tdep_id = self.gen_id()
673 target_dependencies = []
674 custom_target_dependencies = []
675 for tname, t in self.get_build_by_default_targets().items():
676 if isinstance(t, build.CustomTarget):
677 custom_target_dependencies.append(self.pbx_custom_dep_map[t.get_id()])
678 elif isinstance(t, build.BuildTarget):
679 target_dependencies.append(self.pbx_dep_map[t.get_id()])
680 aggregated_targets: list[tuple[str, str, str, list[str], list[str]]] = []
681 aggregated_targets.append((self.all_id,
682 'ALL_BUILD',
683 self.all_buildconf_id,
684 [],
685 [self.regen_dependency_id] + target_dependencies + custom_target_dependencies))
686 aggregated_targets.append((self.test_id,
687 'RUN_TESTS',
688 self.test_buildconf_id,
689 [self.test_command_id],
690 [self.regen_dependency_id, self.build_all_tdep_id]))
691 aggregated_targets.append((self.regen_id,
692 'REGENERATE',
693 self.regen_buildconf_id,
694 [self.regen_command_id],
695 []))
696 for tname, t in self.build.get_custom_targets().items():
697 ct_id = self.gen_id()
698 self.custom_aggregate_targets[tname] = ct_id
699 build_phases = []
700 dependencies = [self.regen_dependency_id]
701 generator_id = 0
702 for d in t.dependencies:
703 if isinstance(d, build.CustomTarget):
704 dependencies.append(self.pbx_custom_dep_map[d.get_id()])
705 elif isinstance(d, build.BuildTarget):
706 dependencies.append(self.pbx_dep_map[d.get_id()])
707 for s in t.sources:
708 if isinstance(s, build.GeneratedList):
709 build_phases.append(self.shell_targets[(tname, generator_id)])
710 for d in s.depends:
711 if isinstance(d, build.GeneratedList):
712 # TODO: what to do about this
713 raise MesonBugException('Not implemented, patches highly welcome')
714 dependencies.append(self.pbx_custom_dep_map[d.get_id()])
715 generator_id += 1
716 elif isinstance(s, build.ExtractedObjects):
717 source_target_id = self.pbx_dep_map[s.target.get_id()]
718 if source_target_id not in dependencies:
719 dependencies.append(source_target_id)
720 build_phases.append(self.shell_targets[tname])
721 aggregated_targets.append((ct_id, tname, self.buildconflistmap[tname], build_phases, dependencies))
722
723 # Sort objects by ID before writing
724 sorted_aggregated_targets = sorted(aggregated_targets, key=operator.itemgetter(0))
725 for t in sorted_aggregated_targets:
726 agt_dict = PbxDict()
727 name = t[1]
728 buildconf_id = t[2]
729 build_phases = t[3]
730 dependencies = t[4]
731 agt_dict.add_item('isa', 'PBXAggregateTarget')
732 agt_dict.add_item('buildConfigurationList', buildconf_id, f'Build configuration list for PBXAggregateTarget "{name}"')
733 bp_arr = PbxArray()
734 agt_dict.add_item('buildPhases', bp_arr)
735 for bp in build_phases:
736 bp_arr.add_item(bp, 'ShellScript')
737 dep_arr = PbxArray()
738 agt_dict.add_item('dependencies', dep_arr)
739 for td in dependencies:
740 dep_arr.add_item(td, 'PBXTargetDependency')
741 agt_dict.add_item('name', name)
742 agt_dict.add_item('productName', name)
743 objects_dict.add_item(t[0], agt_dict, name)
744
745 def generate_pbx_build_file(self, objects_dict: PbxDict) -> None:
746 for tname, t in self.build_targets.items():
747 for dep in t.get_external_deps():
748 if dep.found() and isinstance(dep, AppleFrameworks):
749 for f in dep.frameworks:
750 fw_dict = PbxDict()
751 fwkey = self.native_frameworks[f]
752 if fwkey not in objects_dict.keys:
753 objects_dict.add_item(fwkey, fw_dict, f'{f}.framework in Frameworks')
754 fw_dict.add_item('isa', 'PBXBuildFile')
755 fw_dict.add_item('fileRef', self.native_frameworks_fileref[f], f)
756
757 for s in t.sources:
758 if not isinstance(s, mesonlib.File):
759 continue
760 in_build_dir = s.is_built
761 s = os.path.join(s.subdir, s.fname)
762 sdict = PbxDict()
763 k = (tname, s)
764 idval = self.buildfile_ids[k]
765 fileref = self.fileref_ids[k]
766 if in_build_dir:
767 fullpath = os.path.join(self.environment.get_build_dir(), s)
768 else:
769 fullpath = os.path.join(self.environment.get_source_dir(), s)
770 sdict.add_item('isa', 'PBXBuildFile')
771 sdict.add_item('fileRef', fileref, fullpath)
772 objects_dict.add_item(idval, sdict)
773
774 for o in t.objects:
775 if isinstance(o, build.ExtractedObjects):
776 # Object files are not source files as such. We add them
777 # by hand in linker flags. It is also not particularly
778 # clear how to define build files in Xcode's file format.
779 continue
780 if isinstance(o, mesonlib.File):
781 o = os.path.join(o.subdir, o.fname)
782 elif isinstance(o, str):
783 o = os.path.join(t.subdir, o)
784 else:
785 # TODO: handle CustomTarget | CustomTargetIndex | GeneratedList
786 raise MesonBugException('Not implemented, patches highly welcome')
787 idval = self.buildfile_ids[(tname, o)]
788 k = (tname, o)
789 fileref = self.fileref_ids[k]
790 assert o not in self.filemap
791 self.filemap[o] = idval
792 fullpath = os.path.join(self.environment.get_source_dir(), o)
793 fullpath2 = fullpath
794 o_dict = PbxDict()
795 objects_dict.add_item(idval, o_dict, fullpath)
796 o_dict.add_item('isa', 'PBXBuildFile')
797 o_dict.add_item('fileRef', fileref, fullpath2)
798
799 generator_id = 0
800 for g in t.generated:
801 if not isinstance(g, build.GeneratedList):
802 continue
803 self.create_generator_shellphase(objects_dict, tname, generator_id)
804 generator_id += 1
805
806 # Custom targets are shell build phases in Xcode terminology.
807 for tname, t in self.custom_targets.items():
808 if not isinstance(t, build.CustomTarget):
809 continue
810 (srcs, ofilenames, cmd) = self.eval_custom_target_command(t)
811 for o in ofilenames:
812 custom_dict = PbxDict()
813 objects_dict.add_item(self.custom_target_output_buildfile[o], custom_dict, f'/* {o} */')
814 custom_dict.add_item('isa', 'PBXBuildFile')
815 custom_dict.add_item('fileRef', self.custom_target_output_fileref[o])
816 generator_id = 0
817 for g in t.sources:
818 if not isinstance(g, build.GeneratedList):
819 continue
820 self.create_generator_shellphase(objects_dict, tname, generator_id)
821 generator_id += 1
822
823 def create_generator_shellphase(self, objects_dict: PbxDict, tname: str, generator_id: int) -> None:
824 file_ids = self.generator_buildfile_ids[(tname, generator_id)]
825 ref_ids = self.generator_fileref_ids[(tname, generator_id)]
826 assert len(ref_ids) == len(file_ids)
827 for file_o, ref_id in zip(file_ids, ref_ids):
828 odict = PbxDict()
829 objects_dict.add_item(file_o, odict)
830 odict.add_item('isa', 'PBXBuildFile')
831 odict.add_item('fileRef', ref_id)
832
833 # This is skipped if Xcode 9 or above is installed, as PBXBuildStyle was removed on that version.
834 def generate_pbx_build_style(self, objects_dict: PbxDict) -> None:
835 for name, idval in self.buildstylemap.items():
836 styledict = PbxDict()
837 objects_dict.add_item(idval, styledict, name)
838 styledict.add_item('isa', 'PBXBuildStyle')
839 settings_dict = PbxDict()
840 styledict.add_item('buildSettings', settings_dict)
841 settings_dict.add_item('COPY_PHASE_STRIP', 'NO')
842 styledict.add_item('name', name)
843
844 def to_shell_script(self, args: CompilerArgs) -> str:
845 quoted_cmd = []
846 for c in args:
847 quoted_cmd.append(c.replace('"', chr(92) + '"'))
848 cmd = ' '.join(quoted_cmd)
849 return f"\"#!/bin/sh\\n{cmd}\\n\""
850
851 def generate_pbx_build_rule(self, objects_dict: PbxDict) -> None:
852 for name, languages in self.build_rules.items():
853 target: BuildTarget = self.build_targets[name]
854 for language, idval in languages.items():
855 compiler: Compiler = target.compilers[language]
856 buildrule = PbxDict()
857 buildrule.add_item('isa', 'PBXBuildRule')
858 buildrule.add_item('compilerSpec', 'com.apple.compilers.proxy.script')
859 if compiler.get_id() != 'yasm':
860 # Yasm doesn't generate escaped build rules
861 buildrule.add_item('dependencyFile', '$(DERIVED_FILE_DIR)/$(INPUT_FILE_BASE).d')
862 buildrule.add_item('fileType', NEEDS_CUSTOM_RULES[language])
863 inputfiles = PbxArray()
864 buildrule.add_item('inputFiles', inputfiles)
865 buildrule.add_item('isEditable', '0')
866 outputfiles = PbxArray()
867 outputfiles.add_item('$(DERIVED_FILE_DIR)/$(INPUT_FILE_BASE).o')
868 buildrule.add_item('outputFiles', outputfiles)
869 # Do NOT use this parameter. Xcode will accept it from the UI,
870 # but the parser will break down inconsistently upon next
871 # opening. rdar://FB12144055
872 # outputargs = PbxArray()
873 # args = self.generate_basic_compiler_args(target, compiler)
874 # outputargs.add_item(self.to_shell_script(args))
875 # buildrule.add_item('outputFilesCompilerFlags', outputargs)
876 commands = CompilerArgs(compiler)
877 commands += compiler.get_exelist()
878 if compiler.get_id() == 'yasm':
879 # Yasm doesn't generate escaped build rules
880 commands += self.compiler_to_generator_args(target, compiler, output='"$SCRIPT_OUTPUT_FILE_0"', input='"$SCRIPT_INPUT_FILE"', depfile=None)
881 else:
882 commands += self.compiler_to_generator_args(target,
883 compiler,
884 output='"$SCRIPT_OUTPUT_FILE_0"',
885 input='"$SCRIPT_INPUT_FILE"',
886 depfile='"$(dirname "$SCRIPT_OUTPUT_FILE_0")/$(basename "$SCRIPT_OUTPUT_FILE_0" .o).d"',
887 extras=['$OTHER_INPUT_FILE_FLAGS'])
888 buildrule.add_item('script', self.to_shell_script(commands))
889 objects_dict.add_item(idval, buildrule, 'PBXBuildRule')
890
891 def generate_pbx_container_item_proxy(self, objects_dict: PbxDict) -> None:
892 for t in self.build_targets:
893 proxy_dict = PbxDict()
894 objects_dict.add_item(self.containerproxy_map[t], proxy_dict, 'PBXContainerItemProxy')
895 proxy_dict.add_item('isa', 'PBXContainerItemProxy')
896 proxy_dict.add_item('containerPortal', self.project_uid, 'Project object')
897 proxy_dict.add_item('proxyType', '1')
898 proxy_dict.add_item('remoteGlobalIDString', self.native_targets[t])
899 proxy_dict.add_item('remoteInfo', t)
900
901 def generate_pbx_file_reference(self, objects_dict: PbxDict) -> None:
902 for tname, t in self.build_targets.items():
903 for dep in t.get_external_deps():
904 if dep.found() and isinstance(dep, AppleFrameworks):
905 for f in dep.frameworks:
906 fw_dict = PbxDict()
907 framework_fileref = self.native_frameworks_fileref[f]
908 if objects_dict.has_item(framework_fileref):
909 continue
910 objects_dict.add_item(framework_fileref, fw_dict, f)
911 fw_dict.add_item('isa', 'PBXFileReference')
912 fw_dict.add_item('lastKnownFileType', 'wrapper.framework')
913 fw_dict.add_item('name', f'{f}.framework')
914 fw_dict.add_item('path', f'System/Library/Frameworks/{f}.framework')
915 fw_dict.add_item('sourceTree', 'SDKROOT')
916 for s in t.sources:
917 if not isinstance(s, mesonlib.File):
918 continue
919 in_build_dir = s.is_built
920 s = os.path.join(s.subdir, s.fname)
921 idval = self.fileref_ids[(tname, s)]
922 fullpath = os.path.join(self.environment.get_source_dir(), s)
923 src_dict = PbxDict()
924 xcodetype = self.get_xcodetype(s)
925 name = os.path.basename(s)
926 path = s
927 objects_dict.add_item(idval, src_dict, fullpath)
928 src_dict.add_item('isa', 'PBXFileReference')
929 src_dict.add_item('explicitFileType', xcodetype)
930 src_dict.add_item('fileEncoding', '4')
931 if in_build_dir:
932 src_dict.add_item('name', name)
933 # This makes no sense. This should say path instead of name
934 # but then the path gets added twice.
935 src_dict.add_item('path', name)
936 src_dict.add_item('sourceTree', 'BUILD_ROOT')
937 else:
938 src_dict.add_item('name', name)
939 src_dict.add_item('path', path)
940 src_dict.add_item('sourceTree', 'SOURCE_ROOT')
941
942 generator_id = 0
943 for g in t.generated:
944 if not isinstance(g, build.GeneratedList):
945 continue
946 outputs = self.generator_outputs[(tname, generator_id)]
947 ref_ids = self.generator_fileref_ids[tname, generator_id]
948 assert len(ref_ids) == len(outputs)
949 for o, ref_id in zip(outputs, ref_ids):
950 odict = PbxDict()
951 name = os.path.basename(o)
952 objects_dict.add_item(ref_id, odict, o)
953 xcodetype = self.get_xcodetype(o)
954 rel_name = mesonlib.relpath(o, self.environment.get_source_dir())
955 odict.add_item('isa', 'PBXFileReference')
956 odict.add_item('explicitFileType', xcodetype)
957 odict.add_item('fileEncoding', '4')
958 odict.add_item('name', name)
959 odict.add_item('path', rel_name)
960 odict.add_item('sourceTree', 'SOURCE_ROOT')
961
962 generator_id += 1
963
964 for o in t.objects:
965 if isinstance(o, build.ExtractedObjects):
966 # Same as with pbxbuildfile.
967 continue
968 if isinstance(o, mesonlib.File):
969 fullpath = o.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir())
970 o = os.path.join(o.subdir, o.fname)
971 elif isinstance(o, str):
972 o = os.path.join(t.subdir, o)
973 fullpath = os.path.join(self.environment.get_source_dir(), o)
974 else:
975 # TODO: handle CustomTarget, CustomTargeIndex, and GeneratedList
976 raise MesonBugException('Not implemented, patches highly welcome')
977 idval = self.fileref_ids[(tname, o)]
978 rel_name = mesonlib.relpath(fullpath, self.environment.get_source_dir())
979 o_dict = PbxDict()
980 name = os.path.basename(o)
981 objects_dict.add_item(idval, o_dict, fullpath)
982 o_dict.add_item('isa', 'PBXFileReference')
983 o_dict.add_item('explicitFileType', self.get_xcodetype(o))
984 o_dict.add_item('fileEncoding', '4')
985 o_dict.add_item('name', name)
986 o_dict.add_item('path', rel_name)
987 o_dict.add_item('sourceTree', 'SOURCE_ROOT')
988
989 for e in t.extra_files:
990 if isinstance(e, mesonlib.File):
991 e = os.path.join(e.subdir, e.fname)
992 else:
993 e = os.path.join(t.subdir, e)
994 idval = self.fileref_ids[(tname, e)]
995 fullpath = os.path.join(self.environment.get_source_dir(), e)
996 e_dict = PbxDict()
997 xcodetype = self.get_xcodetype(e)
998 name = os.path.basename(e)
999 path = e
1000 objects_dict.add_item(idval, e_dict, fullpath)
1001 e_dict.add_item('isa', 'PBXFileReference')
1002 e_dict.add_item('explicitFileType', xcodetype)
1003 e_dict.add_item('name', name)
1004 e_dict.add_item('path', path)
1005 e_dict.add_item('sourceTree', 'SOURCE_ROOT')
1006 for tname, idval in self.target_filemap.items():
1007 target_dict = PbxDict()
1008 objects_dict.add_item(idval, target_dict, tname)
1009 t = self.build_targets[tname]
1010 fname = t.get_filename()
1011 reftype = 0
1012 if isinstance(t, build.Executable):
1013 typestr = 'compiled.mach-o.executable'
1014 path = fname
1015 elif isinstance(t, build.SharedLibrary):
1016 typestr = self.get_xcodetype('dummy.dylib')
1017 path = fname
1018 else:
1019 typestr = self.get_xcodetype(fname)
1020 path = '"%s"' % t.get_filename()
1021 target_dict.add_item('isa', 'PBXFileReference')
1022 target_dict.add_item('explicitFileType', typestr)
1023 target_dict.add_item('path', path)
1024 target_dict.add_item('refType', reftype)
1025 target_dict.add_item('sourceTree', 'BUILT_PRODUCTS_DIR')
1026
1027 for tname, t in self.custom_targets.items():
1028 if not isinstance(t, build.CustomTarget):
1029 continue
1030 (srcs, ofilenames, cmd) = self.eval_custom_target_command(t)
1031 for s in t.sources:
1032 if not isinstance(s, mesonlib.File):
1033 continue
1034 s = os.path.join(s.subdir, s.fname)
1035 custom_dict = PbxDict()
1036 typestr = self.get_xcodetype(s)
1037 custom_dict.add_item('isa', 'PBXFileReference')
1038 custom_dict.add_item('explicitFileType', typestr)
1039 custom_dict.add_item('name', s)
1040 custom_dict.add_item('path', s)
1041 custom_dict.add_item('refType', 0)
1042 custom_dict.add_item('sourceTree', 'SOURCE_ROOT')
1043 objects_dict.add_item(self.fileref_ids[(tname, s)], custom_dict)
1044 for o in ofilenames:
1045 custom_dict = PbxDict()
1046 typestr = self.get_xcodetype(o)
1047 custom_dict.add_item('isa', 'PBXFileReference')
1048 custom_dict.add_item('explicitFileType', typestr)
1049 custom_dict.add_item('name', o)
1050 custom_dict.add_item('path', os.path.join(self.src_to_build, o))
1051 custom_dict.add_item('refType', 0)
1052 custom_dict.add_item('sourceTree', 'SOURCE_ROOT')
1053 objects_dict.add_item(self.custom_target_output_fileref[o], custom_dict)
1054
1055 for buildfile in self.build.def_files:
1056 basename = os.path.split(buildfile)[1]
1057 buildfile_dict = PbxDict()
1058 typestr = self.get_xcodetype(buildfile)
1059 buildfile_dict.add_item('isa', 'PBXFileReference')
1060 buildfile_dict.add_item('explicitFileType', typestr)
1061 buildfile_dict.add_item('name', basename)
1062 buildfile_dict.add_item('path', buildfile)
1063 buildfile_dict.add_item('refType', 0)
1064 buildfile_dict.add_item('sourceTree', 'SOURCE_ROOT')
1065 objects_dict.add_item(self.fileref_ids[buildfile], buildfile_dict)
1066
1067 def generate_pbx_frameworks_buildphase(self, objects_dict: PbxDict) -> None:
1068 for t in self.build_targets.values():
1069 bt_dict = PbxDict()
1070 objects_dict.add_item(self.buildphase_map[t.id]['Frameworks'], bt_dict, 'Frameworks')
1071 bt_dict.add_item('isa', 'PBXFrameworksBuildPhase')
1072 bt_dict.add_item('buildActionMask', 2147483647)
1073 file_list = PbxArray()
1074 bt_dict.add_item('files', file_list)
1075 for dep in t.get_external_deps():
1076 if dep.found() and isinstance(dep, AppleFrameworks):
1077 for f in dep.frameworks:
1078 file_list.add_item(self.native_frameworks[f], f'{f}.framework in Frameworks')
1079 bt_dict.add_item('runOnlyForDeploymentPostprocessing', 0)
1080
1081 def generate_pbx_group(self, objects_dict: PbxDict) -> None:
1082 groupmap = {}
1083 target_src_map = {}
1084 for t in self.build_targets:
1085 groupmap[t] = self.gen_id()
1086 target_src_map[t] = self.gen_id()
1087 for t in self.custom_targets:
1088 groupmap[t] = self.gen_id()
1089 target_src_map[t] = self.gen_id()
1090 projecttree_id = self.gen_id()
1091 resources_id = self.gen_id()
1092 products_id = self.gen_id()
1093 frameworks_id = self.gen_id()
1094 main_dict = PbxDict()
1095 objects_dict.add_item(self.maingroup_id, main_dict)
1096 main_dict.add_item('isa', 'PBXGroup')
1097 main_children = PbxArray()
1098 main_dict.add_item('children', main_children)
1099 main_children.add_item(projecttree_id, 'Project tree')
1100 main_children.add_item(resources_id, 'Resources')
1101 main_children.add_item(products_id, 'Products')
1102 main_children.add_item(frameworks_id, 'Frameworks')
1103 main_dict.add_item('sourceTree', '<group>')
1104
1105 # Define each folder as a group in Xcode. That way, it can build the file tree correctly.
1106 # This must be done before the project tree group is generated, as source files are added during that phase.
1107 for (path, target), id in self.foldermap.items():
1108 folder_dict = PbxDict()
1109 objects_dict.add_item(id, folder_dict, path)
1110 folder_dict.add_item('isa', 'PBXGroup')
1111 folder_children = PbxArray()
1112 folder_dict.add_item('children', folder_children)
1113 folder_dict.add_item('name', '"{}"'.format(path.rsplit('/', 1)[-1]))
1114 folder_dict.add_item('path', f'"{path}"')
1115 folder_dict.add_item('sourceTree', 'SOURCE_ROOT')
1116
1117 # Add any detected subdirectories (not declared as subdir()) here, but only one level higher.
1118 # Example: In "root", add "root/sub", but not "root/sub/subtwo".
1119 for path_dep, target_dep in self.foldermap:
1120 if path_dep.startswith(path) and path_dep.split('/', 1)[0] == path.split('/', 1)[0] and path_dep != path and path_dep.count('/') == path.count('/') + 1 and target == target_dep:
1121 folder_children.add_item(self.foldermap[(path_dep, target)], path_dep)
1122
1123 self.add_projecttree(objects_dict, projecttree_id)
1124
1125 resource_dict = PbxDict()
1126 objects_dict.add_item(resources_id, resource_dict, 'Resources')
1127 resource_dict.add_item('isa', 'PBXGroup')
1128 resource_children = PbxArray()
1129 resource_dict.add_item('children', resource_children)
1130 resource_dict.add_item('name', 'Resources')
1131 resource_dict.add_item('sourceTree', '<group>')
1132
1133 frameworks_dict = PbxDict()
1134 objects_dict.add_item(frameworks_id, frameworks_dict, 'Frameworks')
1135 frameworks_dict.add_item('isa', 'PBXGroup')
1136 frameworks_children = PbxArray()
1137 frameworks_dict.add_item('children', frameworks_children)
1138 # write frameworks
1139
1140 for t in self.build_targets.values():
1141 for dep in t.get_external_deps():
1142 if dep.found() and isinstance(dep, AppleFrameworks):
1143 for f in dep.frameworks:
1144 frameworks_children.add_item(self.native_frameworks_fileref[f], f)
1145
1146 frameworks_dict.add_item('name', 'Frameworks')
1147 frameworks_dict.add_item('sourceTree', '<group>')
1148
1149 for tname, t in self.custom_targets.items():
1150 target_dict = PbxDict()
1151 objects_dict.add_item(groupmap[tname], target_dict, tname)
1152 target_dict.add_item('isa', 'PBXGroup')
1153 target_children = PbxArray()
1154 target_dict.add_item('children', target_children)
1155 target_children.add_item(target_src_map[tname], 'Source files')
1156 if t.subproject:
1157 target_dict.add_item('name', f'{t.subproject} • {t.name}')
1158 else:
1159 target_dict.add_item('name', t.name)
1160 target_dict.add_item('sourceTree', '<group>')
1161 source_files_dict = PbxDict()
1162 objects_dict.add_item(target_src_map[tname], source_files_dict, 'Source files')
1163 source_files_dict.add_item('isa', 'PBXGroup')
1164 source_file_children = PbxArray()
1165 source_files_dict.add_item('children', source_file_children)
1166 for s in t.sources:
1167 if not isinstance(s, mesonlib.File):
1168 continue
1169 s = os.path.join(s.subdir, s.fname)
1170 source_file_children.add_item(self.fileref_ids[(tname, s)], s)
1171 source_files_dict.add_item('name', 'Source files')
1172 source_files_dict.add_item('sourceTree', '<group>')
1173
1174 # And finally products
1175 product_dict = PbxDict()
1176 objects_dict.add_item(products_id, product_dict, 'Products')
1177 product_dict.add_item('isa', 'PBXGroup')
1178 product_children = PbxArray()
1179 product_dict.add_item('children', product_children)
1180 for t in self.build_targets:
1181 product_children.add_item(self.target_filemap[t], t)
1182 product_dict.add_item('name', 'Products')
1183 product_dict.add_item('sourceTree', '<group>')
1184
1185 def write_group_target_entry(self, objects_dict: PbxDict, t: build.BuildTarget) -> str:
1186 tid = t.get_id()
1187 group_id = self.gen_id()
1188 target_dict = PbxDict()
1189 folder_ids = set()
1190 objects_dict.add_item(group_id, target_dict, tid)
1191 target_dict.add_item('isa', 'PBXGroup')
1192 target_children = PbxArray()
1193 target_dict.add_item('children', target_children)
1194 target_dict.add_item('name', f'{t} · target')
1195 target_dict.add_item('sourceTree', '<group>')
1196 source_files_dict = PbxDict()
1197 for s in t.sources:
1198 if not isinstance(s, mesonlib.File):
1199 continue
1200 # If the file is in a folder, add it to the group representing that folder.
1201 if '/' in s.fname:
1202 folder = '/'.join(s.fname.split('/')[:-1])
1203 folder_dict = objects_dict.get_item_value(self.foldermap[(folder, t)], PbxDict)
1204 folder_children = folder_dict.get_item_value('children', PbxArray)
1205 temp = os.path.join(s.subdir, s.fname)
1206 folder_children.add_item(self.fileref_ids[(tid, temp)], temp)
1207 if self.foldermap[(folder, t)] in folder_ids:
1208 continue
1209 if len(folder.split('/')) == 1:
1210 target_children.add_item(self.foldermap[(folder, t)], folder)
1211 folder_ids.add(self.foldermap[(folder, t)])
1212 continue
1213 s = os.path.join(s.subdir, s.fname)
1214 target_children.add_item(self.fileref_ids[(tid, s)], s)
1215 for o in t.objects:
1216 if isinstance(o, build.ExtractedObjects):
1217 # Do not show built object files in the project tree.
1218 continue
1219 if isinstance(o, mesonlib.File):
1220 o = os.path.join(o.subdir, o.fname)
1221 elif isinstance(o, str):
1222 o = os.path.join(t.subdir, o)
1223 else:
1224 # TODO: handle CustomTarget, CustomTargeIndex, and GeneratedList
1225 raise MesonBugException('Not implemented, patches highly welcome')
1226 target_children.add_item(self.fileref_ids[(tid, o)], o)
1227 for e in t.extra_files:
1228 if isinstance(e, mesonlib.File):
1229 e = os.path.join(e.subdir, e.fname)
1230 elif isinstance(e, str):
1231 e = os.path.join(t.subdir, e)
1232 else:
1233 continue
1234 target_children.add_item(self.fileref_ids[(tid, e)], e)
1235 source_files_dict.add_item('name', 'Source files')
1236 source_files_dict.add_item('sourceTree', '<group>')
1237 return group_id
1238
1239 def add_projecttree(self, objects_dict: PbxDict, projecttree_id: str) -> None:
1240 root_dict = PbxDict()
1241 objects_dict.add_item(projecttree_id, root_dict, "Root of project tree")
1242 root_dict.add_item('isa', 'PBXGroup')
1243 target_children = PbxArray()
1244 root_dict.add_item('children', target_children)
1245 root_dict.add_item('name', 'Project root')
1246 root_dict.add_item('sourceTree', '<group>')
1247
1248 project_tree = self.generate_project_tree()
1249 self.write_tree(objects_dict, project_tree, target_children, '')
1250
1251 def write_tree(self, objects_dict: PbxDict, tree_node: FileTreeEntry, children_array: PbxArray, current_subdir: str) -> None:
1252 for subdir_name, subdir_node in tree_node.subdirs.items():
1253 subdir_dict = PbxDict()
1254 subdir_children = PbxArray()
1255 subdir_id = self.gen_id()
1256 objects_dict.add_item(subdir_id, subdir_dict)
1257 children_array.add_item(subdir_id)
1258 subdir_dict.add_item('isa', 'PBXGroup')
1259 subdir_dict.add_item('children', subdir_children)
1260 subdir_dict.add_item('name', subdir_name)
1261 subdir_dict.add_item('sourceTree', '<group>')
1262 self.write_tree(objects_dict, subdir_node, subdir_children, os.path.join(current_subdir, subdir_name))
1263 for target in tree_node.targets:
1264 group_id = self.write_group_target_entry(objects_dict, target)
1265 children_array.add_item(group_id)
1266 potentials = [os.path.join(current_subdir, 'meson.build'),
1267 os.path.join(current_subdir, 'meson.options'),
1268 os.path.join(current_subdir, 'meson_options.txt')]
1269 for bf in potentials:
1270 i = self.fileref_ids.get(bf, None)
1271 if i:
1272 children_array.add_item(i)
1273
1274 def generate_project_tree(self) -> FileTreeEntry:
1275 tree_info = FileTreeEntry()
1276 for tname, t in self.build_targets.items():
1277 self.add_target_to_tree(tree_info, t)
1278 return tree_info
1279
1280 def add_target_to_tree(self, tree_root: FileTreeEntry, t: build.BuildTarget) -> None:
1281 current_node = tree_root
1282 path_segments = t.subdir.split('/')
1283 for s in path_segments:
1284 if not s:
1285 continue
1286 if s not in current_node.subdirs:
1287 current_node.subdirs[s] = FileTreeEntry()
1288 current_node = current_node.subdirs[s]
1289 current_node.targets.append(t)
1290
1291 def generate_pbx_native_target(self, objects_dict: PbxDict) -> None:
1292 for tname, idval in self.native_targets.items():
1293 ntarget_dict = PbxDict()
1294 t = self.build_targets[tname]
1295 objects_dict.add_item(idval, ntarget_dict, tname)
1296 ntarget_dict.add_item('isa', 'PBXNativeTarget')
1297 ntarget_dict.add_item('buildConfigurationList', self.buildconflistmap[tname], f'Build configuration list for PBXNativeTarget "{tname}"')
1298 buildphases_array = PbxArray()
1299 ntarget_dict.add_item('buildPhases', buildphases_array)
1300 generator_id = 0
1301 for g in t.generated:
1302 # Custom target are handled via inter-target dependencies.
1303 # Generators are built as a shellscriptbuildphase.
1304 if isinstance(g, build.GeneratedList):
1305 buildphases_array.add_item(self.shell_targets[(tname, generator_id)], f'Generator {generator_id}/{tname}')
1306 generator_id += 1
1307 for bpname, bpval in self.buildphase_map[t.id].items():
1308 buildphases_array.add_item(bpval, f'{bpname} yyy')
1309 build_rules = PbxArray()
1310 for language, build_rule_idval in self.build_rules[tname].items():
1311 build_rules.add_item(build_rule_idval, f'{language}')
1312 ntarget_dict.add_item('buildRules', build_rules)
1313 dep_array = PbxArray()
1314 ntarget_dict.add_item('dependencies', dep_array)
1315 dep_array.add_item(self.regen_dependency_id)
1316 # These dependencies only tell Xcode that the deps must be built
1317 # before this one. They don't set up linkage or anything
1318 # like that. Those are set up in the XCBuildConfiguration.
1319 for lt in self.build_targets[tname].link_targets:
1320 # NOT DOCUMENTED, may need to make different links
1321 # to same target have different targetdependency item.
1322 if isinstance(lt, (build.CustomTarget, build.CustomTargetIndex)):
1323 dep_array.add_item(self.pbx_custom_dep_map[lt.get_id()], lt.get_basename())
1324 else:
1325 idval = self.pbx_dep_map[lt.get_id()]
1326 dep_array.add_item(idval, 'PBXTargetDependency')
1327 for o in t.objects:
1328 if isinstance(o, build.ExtractedObjects):
1329 source_target_id = o.target.get_id()
1330 idval = self.pbx_dep_map[source_target_id]
1331 dep_array.add_item(idval, 'PBXTargetDependency')
1332 generator_id = 0
1333 for o in t.generated:
1334 if isinstance(o, (build.CustomTarget, build.CustomTargetIndex)):
1335 dep_array.add_item(self.pbx_custom_dep_map[o.get_id()], o.get_basename())
1336
1337 generator_id += 1
1338
1339 # xcode backend does not support link_early_args
1340 if isinstance(t, build.BuildTarget) and not isinstance(t, build.StaticLibrary) and t.link_early_args:
1341 raise MesonException(f'XCode backend does not support link_early_args for {t.get_basename()}')
1342
1343 ntarget_dict.add_item('name', tname)
1344 ntarget_dict.add_item('productName', tname)
1345 ntarget_dict.add_item('productReference', self.target_filemap[tname], tname)
1346 if isinstance(t, build.Executable):
1347 typestr = 'com.apple.product-type.tool'
1348 elif isinstance(t, build.StaticLibrary):
1349 typestr = 'com.apple.product-type.library.static'
1350 elif isinstance(t, build.SharedLibrary):
1351 typestr = 'com.apple.product-type.library.dynamic'
1352 else:
1353 raise MesonException('Unknown target type for %s' % tname)
1354 ntarget_dict.add_item('productType', f'"{typestr}"')
1355
1356 def generate_pbx_project(self, objects_dict: PbxDict) -> None:
1357 project_dict = PbxDict()
1358 objects_dict.add_item(self.project_uid, project_dict, 'Project object')
1359 project_dict.add_item('isa', 'PBXProject')
1360 attr_dict = PbxDict()
1361 project_dict.add_item('attributes', attr_dict)
1362 attr_dict.add_item('BuildIndependentTargetsInParallel', 'YES')
1363 project_dict.add_item('buildConfigurationList', self.project_conflist, f'Build configuration list for PBXProject "{self.build.project_name}"')
1364 project_dict.add_item('buildSettings', PbxDict())
1365 if self.objversion < 50:
1366 style_arr = PbxArray()
1367 project_dict.add_item('buildStyles', style_arr)
1368 for name, idval in self.buildstylemap.items():
1369 style_arr.add_item(idval, name)
1370 project_dict.add_item('compatibilityVersion', self.xcodeversion)
1371 project_dict.add_item('hasScannedForEncodings', 0)
1372 project_dict.add_item('mainGroup', self.maingroup_id)
1373 project_dict.add_item('projectDirPath', self.environment.get_source_dir())
1374 project_dict.add_item('projectRoot', '')
1375 targets_arr = PbxArray()
1376 project_dict.add_item('targets', targets_arr)
1377 targets_arr.add_item(self.all_id, 'ALL_BUILD')
1378 targets_arr.add_item(self.test_id, 'RUN_TESTS')
1379 targets_arr.add_item(self.regen_id, 'REGENERATE')
1380 for t in self.build_targets:
1381 targets_arr.add_item(self.native_targets[t], t)
1382 for t in self.custom_targets:
1383 targets_arr.add_item(self.custom_aggregate_targets[t], t)
1384
1385 def generate_pbx_shell_build_phase(self, objects_dict: PbxDict) -> None:
1386 self.generate_test_shell_build_phase(objects_dict)
1387 self.generate_regen_shell_build_phase(objects_dict)
1388 self.generate_custom_target_shell_build_phases(objects_dict)
1389 self.generate_generator_target_shell_build_phases(objects_dict)
1390
1391 def generate_test_shell_build_phase(self, objects_dict: PbxDict) -> None:
1392 shell_dict = PbxDict()
1393 objects_dict.add_item(self.test_command_id, shell_dict, 'ShellScript')
1394 shell_dict.add_item('isa', 'PBXShellScriptBuildPhase')
1395 shell_dict.add_item('buildActionMask', 2147483647)
1396 shell_dict.add_item('files', PbxArray())
1397 shell_dict.add_item('inputPaths', PbxArray())
1398 shell_dict.add_item('outputPaths', PbxArray())
1399 shell_dict.add_item('runOnlyForDeploymentPostprocessing', 0)
1400 shell_dict.add_item('shellPath', '/bin/sh')
1401 cmd = mesonlib.get_meson_command() + ['test', '--no-rebuild', '-C', self.environment.get_build_dir()]
1402 cmdstr = ' '.join(["'%s'" % i for i in cmd])
1403 shell_dict.add_item('shellScript', cmdstr)
1404 shell_dict.add_item('showEnvVarsInLog', 0)
1405
1406 def generate_regen_shell_build_phase(self, objects_dict: PbxDict) -> None:
1407 shell_dict = PbxDict()
1408 objects_dict.add_item(self.regen_command_id, shell_dict, 'ShellScript')
1409 shell_dict.add_item('isa', 'PBXShellScriptBuildPhase')
1410 shell_dict.add_item('buildActionMask', 2147483647)
1411 shell_dict.add_item('files', PbxArray())
1412 shell_dict.add_item('inputPaths', PbxArray())
1413 shell_dict.add_item('outputPaths', PbxArray())
1414 shell_dict.add_item('runOnlyForDeploymentPostprocessing', 0)
1415 shell_dict.add_item('shellPath', '/bin/sh')
1416 cmd = mesonlib.get_meson_command() + ['--internal', 'regencheck', os.path.join(self.environment.get_build_dir(), 'meson-private')]
1417 cmdstr = ' '.join(["'%s'" % i for i in cmd])
1418 shell_dict.add_item('shellScript', cmdstr)
1419 shell_dict.add_item('showEnvVarsInLog', 0)
1420
1421 def generate_custom_target_shell_build_phases(self, objects_dict: PbxDict) -> None:
1422 # Custom targets are shell build phases in Xcode terminology.
1423 for tname, t in self.custom_targets.items():
1424 if not isinstance(t, build.CustomTarget):
1425 continue
1426 (srcs, ofilenames, cmd) = self.eval_custom_target_command(t, absolute_outputs=True)
1427 fixed_cmd, _ = self.as_meson_exe_cmdline(cmd[0],
1428 cmd[1:],
1429 capture=ofilenames[0] if t.capture else None,
1430 feed=srcs[0] if t.feed else None,
1431 env=t.env)
1432 custom_dict = PbxDict()
1433 objects_dict.add_item(self.shell_targets[tname], custom_dict, f'/* Custom target {tname} */')
1434 custom_dict.add_item('isa', 'PBXShellScriptBuildPhase')
1435 custom_dict.add_item('buildActionMask', 2147483647)
1436 custom_dict.add_item('files', PbxArray())
1437 custom_dict.add_item('inputPaths', PbxArray())
1438 outarray = PbxArray()
1439 custom_dict.add_item('name', '"Generate {}."'.format(ofilenames[0]))
1440 custom_dict.add_item('outputPaths', outarray)
1441 for o in ofilenames:
1442 outarray.add_item(os.path.join(self.environment.get_build_dir(), o))
1443 custom_dict.add_item('runOnlyForDeploymentPostprocessing', 0)
1444 custom_dict.add_item('shellPath', '/bin/sh')
1445 workdir = self.environment.get_build_dir()
1446 quoted_cmd = []
1447 for c in fixed_cmd:
1448 quoted_cmd.append(c.replace('"', chr(92) + '"'))
1449 cmdstr = ' '.join([f"\\'{x}\\'" for x in quoted_cmd])
1450 custom_dict.add_item('shellScript', f'cd \'{workdir}\'; {cmdstr}')
1451 custom_dict.add_item('showEnvVarsInLog', 0)
1452
1453 def generate_generator_target_shell_build_phases(self, objects_dict: PbxDict) -> None:
1454 for tname, t in self.build_targets.items():
1455 generator_id = 0
1456 for genlist in t.generated:
1457 if isinstance(genlist, build.GeneratedList):
1458 self.generate_single_generator_phase(tname, t, genlist, generator_id, objects_dict)
1459 generator_id += 1
1460 for tname, t in self.custom_targets.items():
1461 generator_id = 0
1462 for genlist in t.sources:
1463 if isinstance(genlist, build.GeneratedList):
1464 self.generate_single_generator_phase(tname, t, genlist, generator_id, objects_dict)
1465 generator_id += 1
1466
1467 def generate_single_generator_phase(self, tname: str, t: build.AnyTargetType,
1468 genlist: build.GeneratedList, generator_id: int, objects_dict: PbxDict) -> None:
1469 # TODO: this should be rewritten to use the meson wrapper, like the other generators do
1470 # Currently it doesn't handle a host binary that requires an exe wrapper correctly.
1471 generator = genlist.get_generator()
1472 exe = generator.get_exe()
1473 exe_arr = self.build_target_to_cmd_array(exe)
1474 workdir = self.environment.get_build_dir()
1475 target_private_dir = self.relpath(self.get_target_private_dir(t), self.get_target_dir(t))
1476 gen_dict = PbxDict()
1477 objects_dict.add_item(self.shell_targets[(tname, generator_id)], gen_dict, f'Generator {generator_id}/{tname}')
1478 infilelist = genlist.get_inputs()
1479 outfilelist = genlist.get_outputs()
1480 gen_dict.add_item('isa', 'PBXShellScriptBuildPhase')
1481 gen_dict.add_item('buildActionMask', 2147483647)
1482 gen_dict.add_item('files', PbxArray())
1483 gen_dict.add_item('inputPaths', PbxArray())
1484 gen_dict.add_item('name', f'Generator {generator_id}/{tname}')
1485 commands = [["cd", workdir]] # Array of arrays, each one a single command, will get concatenated below.
1486 k = (tname, generator_id)
1487 ofile_abs = self.generator_outputs[k]
1488 outarray = PbxArray()
1489 gen_dict.add_item('outputPaths', outarray)
1490 for of in ofile_abs:
1491 outarray.add_item(of)
1492 for i in infilelist:
1493 # This might be needed to be added to inputPaths. It's not done yet as it is
1494 # unclear whether it is necessary, what actually happens when it is defined
1495 # and currently the build works without it.
1496 #infile_abs = i.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir())
1497 infilename = i.rel_to_builddir(self.build_to_src, target_private_dir)
1498 base_args = generator.get_arglist(infilename)
1499 for o_base in genlist.get_outputs_for(i):
1500 o = os.path.join(self.get_target_private_dir(t), o_base)
1501 args = []
1502 for arg in base_args:
1503 arg = arg.replace("@INPUT@", infilename)
1504 arg = arg.replace('@OUTPUT@', o).replace('@BUILD_DIR@', self.get_target_private_dir(t))
1505 arg = arg.replace("@CURRENT_SOURCE_DIR@", os.path.join(self.build_to_src, t.subdir))
1506 args.append(arg)
1507 args = self.replace_outputs(args, self.get_target_private_dir(t), outfilelist)
1508 args = self.replace_extra_args(args, genlist)
1509 if generator.capture:
1510 # When capturing, stdout is the output. Forward it with the shell.
1511 full_command = ['('] + exe_arr + args + ['>', o, ')']
1512 else:
1513 full_command = exe_arr + args
1514 commands.append(full_command)
1515 gen_dict.add_item('runOnlyForDeploymentPostprocessing', 0)
1516 gen_dict.add_item('shellPath', '/bin/sh')
1517 quoted_cmds = []
1518 for cmnd in commands:
1519 q = []
1520 for c in cmnd:
1521 if ' ' in c:
1522 q.append(f'\\"{c}\\"')
1523 else:
1524 q.append(c)
1525 quoted_cmds.append(' '.join(q))
1526 cmdstr = ' && '.join(quoted_cmds)
1527 gen_dict.add_item('shellScript', cmdstr)
1528 gen_dict.add_item('showEnvVarsInLog', 0)
1529
1530 def generate_pbx_sources_build_phase(self, objects_dict: PbxDict) -> None:
1531 for name in self.source_phase:
1532 phase_dict = PbxDict()
1533 t = self.build_targets[name]
1534 objects_dict.add_item(self.buildphase_map[t.id][name], phase_dict, 'Sources')
1535 phase_dict.add_item('isa', 'PBXSourcesBuildPhase')
1536 phase_dict.add_item('buildActionMask', 2147483647)
1537 file_arr = PbxArray()
1538 phase_dict.add_item('files', file_arr)
1539 for s in self.build_targets[name].sources:
1540 s = os.path.join(s.subdir, s.fname)
1541 if not compilers.is_header(s):
1542 file_arr.add_item(self.buildfile_ids[(name, s)], os.path.join(self.environment.get_source_dir(), s))
1543 generator_id = 0
1544 for gt in t.generated:
1545 if isinstance(gt, build.CustomTarget):
1546 (srcs, ofilenames, cmd) = self.eval_custom_target_command(gt)
1547 for o in ofilenames:
1548 file_arr.add_item(self.custom_target_output_buildfile[o],
1549 os.path.join(self.environment.get_build_dir(), o))
1550 elif isinstance(gt, build.CustomTargetIndex):
1551 output_dir = self.get_custom_target_output_dir(gt)
1552 for o in gt.get_outputs():
1553 o = os.path.join(output_dir, o)
1554 file_arr.add_item(self.custom_target_output_buildfile[o],
1555 os.path.join(self.environment.get_build_dir(), o))
1556 elif isinstance(gt, build.GeneratedList):
1557 genfiles = self.generator_buildfile_ids[(name, generator_id)]
1558 generator_id += 1
1559 for o in genfiles:
1560 file_arr.add_item(o)
1561 else:
1562 raise RuntimeError('Unknown input type: ' + str(gt))
1563 phase_dict.add_item('runOnlyForDeploymentPostprocessing', 0)
1564
1565 def generate_pbx_target_dependency(self, objects_dict: PbxDict) -> None:
1566 all_dict = PbxDict()
1567 objects_dict.add_item(self.build_all_tdep_id, all_dict, 'ALL_BUILD')
1568 all_dict.add_item('isa', 'PBXTargetDependency')
1569 all_dict.add_item('target', self.all_id)
1570 targets: list[tuple[str, str, str, str | None]] = []
1571 targets.append((self.regen_dependency_id, self.regen_id, 'REGEN', None))
1572 for t in self.build_targets:
1573 idval = self.pbx_dep_map[t] # VERIFY: is this correct?
1574 targets.append((idval, self.native_targets[t], t, self.containerproxy_map[t]))
1575
1576 for t in self.custom_targets:
1577 idval = self.pbx_custom_dep_map[t]
1578 targets.append((idval, self.custom_aggregate_targets[t], t, None)) # self.containerproxy_map[t]))
1579
1580 # Sort object by ID
1581 sorted_targets = sorted(targets, key=operator.itemgetter(0))
1582 for t in sorted_targets:
1583 t_dict = PbxDict()
1584 objects_dict.add_item(t[0], t_dict, 'PBXTargetDependency')
1585 t_dict.add_item('isa', 'PBXTargetDependency')
1586 t_dict.add_item('target', t[1], t[2])
1587 if t[3] is not None:
1588 t_dict.add_item('targetProxy', t[3], 'PBXContainerItemProxy')
1589
1590 def generate_xc_build_configuration(self, objects_dict: PbxDict) -> None:
1591 # First the setup for the toplevel project.
1592 for buildtype in self.buildtypes:
1593 bt_dict = PbxDict()
1594 objects_dict.add_item(self.project_configurations[buildtype], bt_dict, buildtype)
1595 bt_dict.add_item('isa', 'XCBuildConfiguration')
1596 settings_dict = PbxDict()
1597 bt_dict.add_item('buildSettings', settings_dict)
1598 settings_dict.add_item('ARCHS', self.arch)
1599 settings_dict.add_item('BUILD_DIR', self.environment.get_build_dir())
1600 settings_dict.add_item('BUILD_ROOT', '$(BUILD_DIR)')
1601 settings_dict.add_item('ONLY_ACTIVE_ARCH', 'YES')
1602 settings_dict.add_item('SWIFT_VERSION', '5.0')
1603 settings_dict.add_item('SDKROOT', 'macosx')
1604 settings_dict.add_item('OBJROOT', '$(BUILD_DIR)/build')
1605 bt_dict.add_item('name', buildtype)
1606
1607 # Then the all target.
1608 for buildtype in self.buildtypes:
1609 bt_dict = PbxDict()
1610 objects_dict.add_item(self.buildall_configurations[buildtype], bt_dict, buildtype)
1611 bt_dict.add_item('isa', 'XCBuildConfiguration')
1612 settings_dict = PbxDict()
1613 bt_dict.add_item('buildSettings', settings_dict)
1614 warn_array = PbxArray()
1615 warn_array.add_item('"$(inherited)"')
1616 settings_dict.add_item('WARNING_CFLAGS', warn_array)
1617
1618 bt_dict.add_item('name', buildtype)
1619
1620 # Then the test target.
1621 for buildtype in self.buildtypes:
1622 bt_dict = PbxDict()
1623 objects_dict.add_item(self.test_configurations[buildtype], bt_dict, buildtype)
1624 bt_dict.add_item('isa', 'XCBuildConfiguration')
1625 settings_dict = PbxDict()
1626 bt_dict.add_item('buildSettings', settings_dict)
1627 warn_array = PbxArray()
1628 settings_dict.add_item('WARNING_CFLAGS', warn_array)
1629 warn_array.add_item('"$(inherited)"')
1630 bt_dict.add_item('name', buildtype)
1631
1632 # Now finally targets.
1633 for target_name, target in self.build_targets.items():
1634 self.generate_single_build_target(objects_dict, target_name, target)
1635
1636 for target_name, target in self.custom_targets.items():
1637 bt_dict = PbxDict()
1638 objects_dict.add_item(self.buildconfmap[target_name][buildtype], bt_dict, buildtype)
1639 bt_dict.add_item('isa', 'XCBuildConfiguration')
1640 settings_dict = PbxDict()
1641 bt_dict.add_item('buildSettings', settings_dict)
1642 settings_dict.add_item('ARCHS', self.arch)
1643 settings_dict.add_item('ONLY_ACTIVE_ARCH', 'YES')
1644 settings_dict.add_item('SDKROOT', 'macosx')
1645 bt_dict.add_item('name', buildtype)
1646
1647 def determine_internal_dep_link_args(self, target: build.BuildTarget, buildtype: str) -> T.Tuple[T.List[str], bool]:
1648 links_dylib = False
1649 dep_libs = []
1650 for l in target.link_targets:
1651 if isinstance(target, build.SharedModule) and isinstance(l, build.Executable):
1652 continue
1653 if isinstance(l, (build.CustomTarget, build.CustomTargetIndex)):
1654 rel_dir = self.get_custom_target_output_dir(l.get_target())
1655 libname = l.get_filename()
1656 else:
1657 rel_dir = self.get_target_dir(l)
1658 libname = l.get_filename()
1659 abs_path = os.path.join(self.environment.get_build_dir(), rel_dir, libname)
1660 dep_libs.append("'%s'" % abs_path)
1661 if isinstance(l, build.SharedLibrary):
1662 links_dylib = True
1663 if isinstance(l, build.StaticLibrary):
1664 (sub_libs, sub_links_dylib) = self.determine_internal_dep_link_args(l, buildtype)
1665 dep_libs += sub_libs
1666 links_dylib = links_dylib or sub_links_dylib
1667 return (dep_libs, links_dylib)
1668
1669 def generate_single_build_target(self, objects_dict: PbxDict, target_name: str, target: build.BuildTarget) -> None:
1670 for buildtype in self.buildtypes:
1671 dep_libs: T.List[str] = []
1672 links_dylib = False
1673 headerdirs = []
1674 bridging_header = ""
1675 is_swift = self.is_swift_target(target)
1676 langs = set()
1677 for d in target.include_dirs:
1678 headerdirs.extend(d.abs_string_list(self.environment.get_source_dir(), self.environment.get_build_dir()))
1679 # Swift can import declarations from C-based code using bridging headers.
1680 # There can only be one header, and it must be included as a source file.
1681 for i in target.get_sources():
1682 if compilers.is_header(i) and is_swift:
1683 relh = i.rel_to_builddir(self.build_to_src)
1684 bridging_header = os.path.normpath(os.path.join(self.environment.get_build_dir(), relh))
1685 break
1686 (dep_libs, links_dylib) = self.determine_internal_dep_link_args(target, buildtype)
1687 if links_dylib:
1688 dep_libs = ['-Wl,-search_paths_first', '-Wl,-headerpad_max_install_names'] + dep_libs
1689 dylib_version = None
1690 if isinstance(target, build.SharedLibrary):
1691 if isinstance(target, build.SharedModule):
1692 ldargs = []
1693 else:
1694 ldargs = ['-dynamiclib']
1695 ldargs += ['-Wl,-headerpad_max_install_names'] + dep_libs
1696 install_path = os.path.join(self.environment.get_build_dir(), target.subdir, buildtype)
1697 dylib_version = target.soversion
1698 else:
1699 ldargs = dep_libs
1700 install_path = ''
1701 if dylib_version is not None:
1702 product_name = target.get_basename() + '.' + dylib_version
1703 else:
1704 product_name = target.get_basename()
1705 ldargs += target.link_args
1706 # Swift is special. Again. You can't mix Swift with other languages
1707 # in the same target. Thus for Swift we only use
1708 # TODO: is this still true?
1709 stdlib_args: list[str]
1710 if is_swift:
1711 linker, stdlib_args = target.compilers['swift'], []
1712 else:
1713 linker, stdlib_args = self.determine_linker_and_stdlib_args(target)
1714 if not isinstance(linker, StaticLinker):
1715 ldargs += linker.get_build_link_args(target, self.build)
1716 cargs = []
1717 for dep in target.get_external_deps():
1718 cargs += dep.get_compile_args()
1719 ldargs += dep.get_link_args()
1720 for o in target.objects:
1721 # Add extracted objects to the link line by hand.
1722 if isinstance(o, build.ExtractedObjects):
1723 added_objs = set()
1724 for objname_rel in self.determine_ext_objs(o):
1725 objname_abs = os.path.join(self.environment.get_build_dir(), o.target.subdir, objname_rel)
1726 if objname_abs not in added_objs:
1727 added_objs.add(objname_abs)
1728 ldargs += [r'\"' + objname_abs + r'\"']
1729 generator_id = 0
1730 for o in target.generated:
1731 if isinstance(o, build.GeneratedList):
1732 outputs = self.generator_outputs[target_name, generator_id]
1733 generator_id += 1
1734 for o_abs in outputs:
1735 if o_abs.endswith('.o') or o_abs.endswith('.obj'):
1736 ldargs += [r'\"' + o_abs + r'\"']
1737 else:
1738 if isinstance(o, build.CustomTarget):
1739 (srcs, ofilenames, cmd) = self.eval_custom_target_command(o)
1740 for ofname in ofilenames:
1741 if os.path.splitext(ofname)[-1] in LINKABLE_EXTENSIONS:
1742 ldargs += [r'\"' + os.path.join(self.environment.get_build_dir(), ofname) + r'\"']
1743 elif isinstance(o, build.CustomTargetIndex):
1744 for ofname in o.get_outputs():
1745 if os.path.splitext(ofname)[-1] in LINKABLE_EXTENSIONS:
1746 ldargs += [r'\"' + os.path.join(self.environment.get_build_dir(), ofname) + r'\"']
1747 else:
1748 raise RuntimeError(o)
1749 if isinstance(target, build.SharedModule):
1750 assert not isinstance(linker, StaticLinker), 'for mypy'
1751 ldargs += linker.get_std_shared_module_link_args(target)
1752 elif isinstance(target, build.SharedLibrary):
1753 assert not isinstance(linker, StaticLinker), 'for mypy'
1754 ldargs += linker.get_std_shared_lib_link_args()
1755 ldstr = ' '.join(ldargs)
1756 valid = self.buildconfmap[target_name][buildtype]
1757 langargs: T.Dict[str, T.List[str]] = {}
1758 for lang in self.environment.coredata.compilers[target.for_machine]:
1759 if lang not in LANGNAMEMAP:
1760 continue
1761 compiler = target.compilers.get(lang)
1762 if compiler is None:
1763 continue
1764 # Start with warning args
1765 _warn_level = self.get_target_option(target, 'warning_level')
1766 assert isinstance(_warn_level, str), 'for mypy'
1767 warn_args = compiler.get_warn_args(_warn_level)
1768 std_args = compiler.get_option_compile_args(target, target.subproject)
1769 std_args += compiler.get_option_std_args(target, target.subproject)
1770 # Add compile args added using add_project_arguments()
1771 pargs = self.build.get_project_args(compiler, target)
1772 # Add compile args added using add_global_arguments()
1773 # These override per-project arguments
1774 gargs = self.build.global_args[target.for_machine].get(lang, [])
1775 targs = target.get_extra_args(lang)
1776 args = warn_args + std_args + pargs + gargs + targs
1777 if lang == 'swift':
1778 # For some reason putting Swift module dirs in HEADER_SEARCH_PATHS does not work,
1779 # but adding -I/path to manual args does work.
1780 swift_dep_dirs = self.determine_swift_dep_dirs(target)
1781 for d in swift_dep_dirs:
1782 args += compiler.get_include_args(d, False)
1783 if args:
1784 cti_args = []
1785 if compiler and target.implicit_include_directories:
1786 # It is unclear what is the cwd when xcode runs. -I. does not seem to
1787 # add the root build dir to the search path. So add an absolute path instead.
1788 # This may break reproducible builds, in which case patches are welcome.
1789 cti_args = self.get_custom_target_dir_include_args(target, compiler, absolute_path=True)
1790 # Xcode cannot handle separate compilation flags for C and ObjectiveC. They are both
1791 # put in OTHER_CFLAGS. Same with C++ and ObjectiveC++.
1792 if lang == 'objc':
1793 lang = 'c'
1794 elif lang == 'objcpp':
1795 lang = 'cpp'
1796 langs.add(lang)
1797 langname = LANGNAMEMAP[lang]
1798 langargs.setdefault(langname, [])
1799 langargs[langname] = cargs + cti_args + args
1800 symroot = os.path.join(self.environment.get_build_dir(), target.subdir).rstrip('/')
1801 bt_dict = PbxDict()
1802 objects_dict.add_item(valid, bt_dict, buildtype)
1803 bt_dict.add_item('isa', 'XCBuildConfiguration')
1804 settings_dict = PbxDict()
1805 bt_dict.add_item('buildSettings', settings_dict)
1806 settings_dict.add_item('COMBINE_HIDPI_IMAGES', 'YES')
1807 if isinstance(target, build.SharedModule):
1808 settings_dict.add_item('DYLIB_CURRENT_VERSION', '')
1809 settings_dict.add_item('DYLIB_COMPATIBILITY_VERSION', '')
1810 else:
1811 if dylib_version is not None:
1812 settings_dict.add_item('DYLIB_CURRENT_VERSION', str(dylib_version))
1813 if target.prefix:
1814 settings_dict.add_item('EXECUTABLE_PREFIX', target.prefix)
1815 if target.suffix:
1816 suffix = '.' + target.suffix
1817 settings_dict.add_item('EXECUTABLE_SUFFIX', suffix)
1818 debug = self.get_target_option(target, 'debug')
1819 assert isinstance(debug, bool), 'for mypy'
1820 settings_dict.add_item('GCC_GENERATE_DEBUGGING_SYMBOLS', BOOL2XCODEBOOL[debug])
1821 settings_dict.add_item('GCC_INLINES_ARE_PRIVATE_EXTERN', 'NO')
1822 opt = self.get_target_option(target, 'optimization')
1823 assert isinstance(opt, str), 'for mypy'
1824 opt_flag = OPT2XCODEOPT[opt]
1825 if opt_flag is not None:
1826 settings_dict.add_item('GCC_OPTIMIZATION_LEVEL', opt_flag)
1827 if target.has_pch:
1828 # Xcode uses GCC_PREFIX_HEADER which only allows one file per target/executable. Precompiling various header files and
1829 # applying a particular pch to each source file will require custom scripts (as a build phase) and build flags per each
1830 # file. Since Xcode itself already discourages precompiled headers in favor of modules we don't try much harder here.
1831 pchs = [t[0] for t in [target.pch['c'], target.pch['cpp']] if t is not None]
1832 if pchs:
1833 if len(pchs) > 1:
1834 mlog.warning(f'Unsupported Xcode configuration: More than 1 precompiled header found "{pchs!s}". Target "{target.name}" might not compile correctly.')
1835 relative_pch_path = os.path.join(target.get_subdir(), pchs[0]) # Path relative to target so it can be used with "$(PROJECT_DIR)"
1836 settings_dict.add_item('GCC_PRECOMPILE_PREFIX_HEADER', 'YES')
1837 settings_dict.add_item('GCC_PREFIX_HEADER', f'$(PROJECT_DIR)/{relative_pch_path}')
1838 settings_dict.add_item('GCC_PREPROCESSOR_DEFINITIONS', '')
1839 settings_dict.add_item('GCC_SYMBOLS_PRIVATE_EXTERN', 'NO')
1840 unquoted_headers = [self.get_target_private_dir_abs(target)]
1841 if target.implicit_include_directories:
1842 unquoted_headers.append(os.path.join(self.environment.get_build_dir(), target.get_builddir()))
1843 unquoted_headers.append(os.path.join(self.environment.get_source_dir(), target.get_subdir()))
1844 unquoted_headers += headerdirs
1845 settings_dict.add_item('HEADER_SEARCH_PATHS', self.normalize_header_search_paths(unquoted_headers))
1846 settings_dict.add_item('INSTALL_PATH', install_path)
1847 settings_dict.add_item('LIBRARY_SEARCH_PATHS', '')
1848 if isinstance(target, build.SharedModule):
1849 settings_dict.add_item('LIBRARY_STYLE', 'BUNDLE')
1850 settings_dict.add_item('MACH_O_TYPE', 'mh_bundle')
1851 elif isinstance(target, build.SharedLibrary):
1852 settings_dict.add_item('LIBRARY_STYLE', 'DYNAMIC')
1853 self.add_otherargs(settings_dict, langargs)
1854 settings_dict.add_item('OTHER_LDFLAGS', ldstr)
1855 settings_dict.add_item('OTHER_REZFLAGS', '')
1856 settings_dict.add_item('PRODUCT_NAME', product_name)
1857 settings_dict.add_item('SECTORDER_FLAGS', '')
1858 if is_swift and bridging_header:
1859 settings_dict.add_item('SWIFT_OBJC_BRIDGING_HEADER', bridging_header)
1860 if self.objversion >= 60 and target.uses_swift_cpp_interop():
1861 settings_dict.add_item('SWIFT_OBJC_INTEROP_MODE', 'objcxx')
1862 settings_dict.add_item('BUILD_DIR', symroot)
1863 settings_dict.add_item('OBJROOT', f'{symroot}/build')
1864 sysheader_arr = PbxArray()
1865 # XCode will change every -I flag that points inside these directories
1866 # to an -isystem. Thus set nothing in it since we control our own
1867 # include flags.
1868 settings_dict.add_item('SYSTEM_HEADER_SEARCH_PATHS', sysheader_arr)
1869 settings_dict.add_item('USE_HEADERMAP', 'NO')
1870 warn_array = PbxArray()
1871 settings_dict.add_item('WARNING_CFLAGS', warn_array)
1872 warn_array.add_item('"$(inherited)"')
1873 bt_dict.add_item('name', buildtype)
1874
1875 def normalize_header_search_paths(self, header_dirs: T.List[str]) -> PbxArray:
1876 header_arr = PbxArray()
1877 for i in header_dirs:
1878 np = os.path.normpath(i)
1879 # Make sure Xcode will not split single path into separate entries, escaping space with a slash is not enough
1880 item = f'"\\\"{np}\\\""' if ' ' in np else f'"{np}"'
1881 header_arr.add_item(item)
1882 return header_arr
1883
1884 def add_otherargs(self, settings_dict: PbxDict, langargs: T.Dict[str, T.List[str]]) -> None:
1885 for langname, args in langargs.items():
1886 if args:
1887 quoted_args = []
1888 for a in args:
1889 # This works but
1890 # a) it's ugly as sin
1891 # b) I don't know why it works or why every backslash must be escaped into eight backslashes
1892 a = a.replace(chr(92), 8*chr(92)) # chr(92) is backslash, this how we smuggle it in without Python's quoting grabbing it.
1893 a = a.replace(r'"', r'\\\"')
1894 if ' ' in a or "'" in a:
1895 a = r'\"' + a + r'\"'
1896 quoted_args.append(a)
1897 settings_dict.add_item(f'OTHER_{langname}FLAGS', ' '.join(quoted_args))
1898
1899 def generate_xc_configurationList(self, objects_dict: PbxDict) -> None:
1900 # FIXME: sort items
1901 conf_dict = PbxDict()
1902 objects_dict.add_item(self.project_conflist, conf_dict, f'Build configuration list for PBXProject "{self.build.project_name}"')
1903 conf_dict.add_item('isa', 'XCConfigurationList')
1904 confs_arr = PbxArray()
1905 conf_dict.add_item('buildConfigurations', confs_arr)
1906 for buildtype in self.buildtypes:
1907 confs_arr.add_item(self.project_configurations[buildtype], buildtype)
1908 conf_dict.add_item('defaultConfigurationIsVisible', 0)
1909 conf_dict.add_item('defaultConfigurationName', self.buildtype)
1910
1911 # Now the all target
1912 all_dict = PbxDict()
1913 objects_dict.add_item(self.all_buildconf_id, all_dict, 'Build configuration list for PBXAggregateTarget "ALL_BUILD"')
1914 all_dict.add_item('isa', 'XCConfigurationList')
1915 conf_arr = PbxArray()
1916 all_dict.add_item('buildConfigurations', conf_arr)
1917 for buildtype in self.buildtypes:
1918 conf_arr.add_item(self.buildall_configurations[buildtype], buildtype)
1919 all_dict.add_item('defaultConfigurationIsVisible', 0)
1920 all_dict.add_item('defaultConfigurationName', self.buildtype)
1921
1922 # Test target
1923 test_dict = PbxDict()
1924 objects_dict.add_item(self.test_buildconf_id, test_dict, 'Build configuration list for PBXAggregateTarget "RUN_TEST"')
1925 test_dict.add_item('isa', 'XCConfigurationList')
1926 conf_arr = PbxArray()
1927 test_dict.add_item('buildConfigurations', conf_arr)
1928 for buildtype in self.buildtypes:
1929 conf_arr.add_item(self.test_configurations[buildtype], buildtype)
1930 test_dict.add_item('defaultConfigurationIsVisible', 0)
1931 test_dict.add_item('defaultConfigurationName', self.buildtype)
1932
1933 # Regen target
1934 regen_dict = PbxDict()
1935 objects_dict.add_item(self.regen_buildconf_id, test_dict, 'Build configuration list for PBXAggregateTarget "REGENERATE"')
1936 regen_dict.add_item('isa', 'XCConfigurationList')
1937 conf_arr = PbxArray()
1938 regen_dict.add_item('buildConfigurations', conf_arr)
1939 for buildtype in self.buildtypes:
1940 conf_arr.add_item(self.test_configurations[buildtype], buildtype)
1941 regen_dict.add_item('defaultConfigurationIsVisible', 0)
1942 regen_dict.add_item('defaultConfigurationName', self.buildtype)
1943
1944 for target_name in self.build_targets:
1945 t_dict = PbxDict()
1946 listid = self.buildconflistmap[target_name]
1947 objects_dict.add_item(listid, t_dict, f'Build configuration list for PBXNativeTarget "{target_name}"')
1948 t_dict.add_item('isa', 'XCConfigurationList')
1949 conf_arr = PbxArray()
1950 t_dict.add_item('buildConfigurations', conf_arr)
1951 idval = self.buildconfmap[target_name][self.buildtype]
1952 conf_arr.add_item(idval, self.buildtype)
1953 t_dict.add_item('defaultConfigurationIsVisible', 0)
1954 t_dict.add_item('defaultConfigurationName', self.buildtype)
1955
1956 for target_name in self.custom_targets:
1957 t_dict = PbxDict()
1958 listid = self.buildconflistmap[target_name]
1959 objects_dict.add_item(listid, t_dict, f'Build configuration list for PBXAggregateTarget "{target_name}"')
1960 t_dict.add_item('isa', 'XCConfigurationList')
1961 conf_arr = PbxArray()
1962 t_dict.add_item('buildConfigurations', conf_arr)
1963 idval = self.buildconfmap[target_name][self.buildtype]
1964 conf_arr.add_item(idval, self.buildtype)
1965 t_dict.add_item('defaultConfigurationIsVisible', 0)
1966 t_dict.add_item('defaultConfigurationName', self.buildtype)
1967
1968 def generate_prefix(self, pbxdict: PbxDict) -> PbxDict:
1969 pbxdict.add_item('archiveVersion', '1')
1970 pbxdict.add_item('classes', PbxDict())
1971 pbxdict.add_item('objectVersion', self.objversion)
1972 objects_dict = PbxDict()
1973 pbxdict.add_item('objects', objects_dict)
1974
1975 return objects_dict
1976
1977 def generate_suffix(self, pbxdict: PbxDict) -> None:
1978 pbxdict.add_item('rootObject', self.project_uid, 'Project object')