rustc_target/spec/
json.rs

1use std::borrow::Cow;
2use std::collections::BTreeMap;
3use std::str::FromStr;
4
5use serde_json::Value;
6
7use super::{Target, TargetKind, TargetOptions, TargetWarnings};
8use crate::json::{Json, ToJson};
9
10impl Target {
11    /// Loads a target descriptor from a JSON object.
12    pub fn from_json(obj: Json) -> Result<(Target, TargetWarnings), String> {
13        // While ugly, this code must remain this way to retain
14        // compatibility with existing JSON fields and the internal
15        // expected naming of the Target and TargetOptions structs.
16        // To ensure compatibility is retained, the built-in targets
17        // are round-tripped through this code to catch cases where
18        // the JSON parser is not updated to match the structs.
19
20        let mut obj = match obj {
21            Value::Object(obj) => obj,
22            _ => return Err("Expected JSON object for target")?,
23        };
24
25        let mut get_req_field = |name: &str| {
26            obj.remove(name)
27                .and_then(|j| j.as_str().map(str::to_string))
28                .ok_or_else(|| format!("Field {name} in target specification is required"))
29        };
30
31        let mut base = Target {
32            llvm_target: get_req_field("llvm-target")?.into(),
33            metadata: Default::default(),
34            pointer_width: get_req_field("target-pointer-width")?
35                .parse::<u32>()
36                .map_err(|_| "target-pointer-width must be an integer".to_string())?,
37            data_layout: get_req_field("data-layout")?.into(),
38            arch: get_req_field("arch")?.into(),
39            options: Default::default(),
40        };
41
42        // FIXME: This doesn't properly validate anything and just ignores the data if it's invalid.
43        // That's okay for now, the only use of this is when generating docs, which we don't do for
44        // custom targets.
45        if let Some(Json::Object(mut metadata)) = obj.remove("metadata") {
46            base.metadata.description = metadata
47                .remove("description")
48                .and_then(|desc| desc.as_str().map(|desc| desc.to_owned().into()));
49            base.metadata.tier = metadata
50                .remove("tier")
51                .and_then(|tier| tier.as_u64())
52                .filter(|tier| (1..=3).contains(tier));
53            base.metadata.host_tools =
54                metadata.remove("host_tools").and_then(|host| host.as_bool());
55            base.metadata.std = metadata.remove("std").and_then(|host| host.as_bool());
56        }
57
58        let mut incorrect_type = vec![];
59
60        macro_rules! key {
61            ($key_name:ident) => ( {
62                let name = (stringify!($key_name)).replace("_", "-");
63                if let Some(s) = obj.remove(&name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
64                    base.$key_name = s;
65                }
66            } );
67            ($key_name:ident = $json_name:expr) => ( {
68                let name = $json_name;
69                if let Some(s) = obj.remove(name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
70                    base.$key_name = s;
71                }
72            } );
73            ($key_name:ident, bool) => ( {
74                let name = (stringify!($key_name)).replace("_", "-");
75                if let Some(s) = obj.remove(&name).and_then(|b| b.as_bool()) {
76                    base.$key_name = s;
77                }
78            } );
79            ($key_name:ident = $json_name:expr, bool) => ( {
80                let name = $json_name;
81                if let Some(s) = obj.remove(name).and_then(|b| b.as_bool()) {
82                    base.$key_name = s;
83                }
84            } );
85            ($key_name:ident, u32) => ( {
86                let name = (stringify!($key_name)).replace("_", "-");
87                if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
88                    if s < 1 || s > 5 {
89                        return Err("Not a valid DWARF version number".into());
90                    }
91                    base.$key_name = s as u32;
92                }
93            } );
94            ($key_name:ident, Option<bool>) => ( {
95                let name = (stringify!($key_name)).replace("_", "-");
96                if let Some(s) = obj.remove(&name).and_then(|b| b.as_bool()) {
97                    base.$key_name = Some(s);
98                }
99            } );
100            ($key_name:ident, Option<u64>) => ( {
101                let name = (stringify!($key_name)).replace("_", "-");
102                if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
103                    base.$key_name = Some(s);
104                }
105            } );
106            ($key_name:ident, BinaryFormat) => ( {
107                let name = (stringify!($key_name)).replace("_", "-");
108                obj.remove(&name).and_then(|f| f.as_str().and_then(|s| {
109                    match s.parse::<super::BinaryFormat>() {
110                        Ok(binary_format) => base.$key_name = binary_format,
111                        _ => return Some(Err(format!(
112                            "'{s}' is not a valid value for binary_format. \
113                            Use 'coff', 'elf', 'mach-o', 'wasm' or 'xcoff' "
114                        ))),
115                    }
116                    Some(Ok(()))
117                })).unwrap_or(Ok(()))
118            } );
119            ($key_name:ident, MergeFunctions) => ( {
120                let name = (stringify!($key_name)).replace("_", "-");
121                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
122                    match s.parse::<super::MergeFunctions>() {
123                        Ok(mergefunc) => base.$key_name = mergefunc,
124                        _ => return Some(Err(format!("'{}' is not a valid value for \
125                                                      merge-functions. Use 'disabled', \
126                                                      'trampolines', or 'aliases'.",
127                                                      s))),
128                    }
129                    Some(Ok(()))
130                })).unwrap_or(Ok(()))
131            } );
132            ($key_name:ident, FloatAbi) => ( {
133                let name = (stringify!($key_name)).replace("_", "-");
134                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
135                    match s.parse::<super::FloatAbi>() {
136                        Ok(float_abi) => base.$key_name = Some(float_abi),
137                        _ => return Some(Err(format!("'{}' is not a valid value for \
138                                                      llvm-floatabi. Use 'soft' or 'hard'.",
139                                                      s))),
140                    }
141                    Some(Ok(()))
142                })).unwrap_or(Ok(()))
143            } );
144            ($key_name:ident, RustcAbi) => ( {
145                let name = (stringify!($key_name)).replace("_", "-");
146                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
147                    match s.parse::<super::RustcAbi>() {
148                        Ok(rustc_abi) => base.$key_name = Some(rustc_abi),
149                        _ => return Some(Err(format!(
150                            "'{s}' is not a valid value for rustc-abi. \
151                            Use 'x86-softfloat' or leave the field unset."
152                        ))),
153                    }
154                    Some(Ok(()))
155                })).unwrap_or(Ok(()))
156            } );
157            ($key_name:ident, RelocModel) => ( {
158                let name = (stringify!($key_name)).replace("_", "-");
159                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
160                    match s.parse::<super::RelocModel>() {
161                        Ok(relocation_model) => base.$key_name = relocation_model,
162                        _ => return Some(Err(format!("'{}' is not a valid relocation model. \
163                                                      Run `rustc --print relocation-models` to \
164                                                      see the list of supported values.", s))),
165                    }
166                    Some(Ok(()))
167                })).unwrap_or(Ok(()))
168            } );
169            ($key_name:ident, CodeModel) => ( {
170                let name = (stringify!($key_name)).replace("_", "-");
171                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
172                    match s.parse::<super::CodeModel>() {
173                        Ok(code_model) => base.$key_name = Some(code_model),
174                        _ => return Some(Err(format!("'{}' is not a valid code model. \
175                                                      Run `rustc --print code-models` to \
176                                                      see the list of supported values.", s))),
177                    }
178                    Some(Ok(()))
179                })).unwrap_or(Ok(()))
180            } );
181            ($key_name:ident, TlsModel) => ( {
182                let name = (stringify!($key_name)).replace("_", "-");
183                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
184                    match s.parse::<super::TlsModel>() {
185                        Ok(tls_model) => base.$key_name = tls_model,
186                        _ => return Some(Err(format!("'{}' is not a valid TLS model. \
187                                                      Run `rustc --print tls-models` to \
188                                                      see the list of supported values.", s))),
189                    }
190                    Some(Ok(()))
191                })).unwrap_or(Ok(()))
192            } );
193            ($key_name:ident, SmallDataThresholdSupport) => ( {
194                obj.remove("small-data-threshold-support").and_then(|o| o.as_str().and_then(|s| {
195                    match s.parse::<super::SmallDataThresholdSupport>() {
196                        Ok(support) => base.small_data_threshold_support = support,
197                        _ => return Some(Err(format!("'{s}' is not a valid value for small-data-threshold-support."))),
198                    }
199                    Some(Ok(()))
200                })).unwrap_or(Ok(()))
201            } );
202            ($key_name:ident, PanicStrategy) => ( {
203                let name = (stringify!($key_name)).replace("_", "-");
204                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
205                    match s {
206                        "unwind" => base.$key_name = super::PanicStrategy::Unwind,
207                        "abort" => base.$key_name = super::PanicStrategy::Abort,
208                        _ => return Some(Err(format!("'{}' is not a valid value for \
209                                                      panic-strategy. Use 'unwind' or 'abort'.",
210                                                     s))),
211                }
212                Some(Ok(()))
213            })).unwrap_or(Ok(()))
214            } );
215            ($key_name:ident, RelroLevel) => ( {
216                let name = (stringify!($key_name)).replace("_", "-");
217                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
218                    match s.parse::<super::RelroLevel>() {
219                        Ok(level) => base.$key_name = level,
220                        _ => return Some(Err(format!("'{}' is not a valid value for \
221                                                      relro-level. Use 'full', 'partial, or 'off'.",
222                                                      s))),
223                    }
224                    Some(Ok(()))
225                })).unwrap_or(Ok(()))
226            } );
227            ($key_name:ident, Option<SymbolVisibility>) => ( {
228                let name = (stringify!($key_name)).replace("_", "-");
229                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
230                    match s.parse::<super::SymbolVisibility>() {
231                        Ok(level) => base.$key_name = Some(level),
232                        _ => return Some(Err(format!("'{}' is not a valid value for \
233                                                      symbol-visibility. Use 'hidden', 'protected, or 'interposable'.",
234                                                      s))),
235                    }
236                    Some(Ok(()))
237                })).unwrap_or(Ok(()))
238            } );
239            ($key_name:ident, DebuginfoKind) => ( {
240                let name = (stringify!($key_name)).replace("_", "-");
241                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
242                    match s.parse::<super::DebuginfoKind>() {
243                        Ok(level) => base.$key_name = level,
244                        _ => return Some(Err(
245                            format!("'{s}' is not a valid value for debuginfo-kind. Use 'dwarf', \
246                                  'dwarf-dsym' or 'pdb'.")
247                        )),
248                    }
249                    Some(Ok(()))
250                })).unwrap_or(Ok(()))
251            } );
252            ($key_name:ident, SplitDebuginfo) => ( {
253                let name = (stringify!($key_name)).replace("_", "-");
254                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
255                    match s.parse::<super::SplitDebuginfo>() {
256                        Ok(level) => base.$key_name = level,
257                        _ => return Some(Err(format!("'{}' is not a valid value for \
258                                                      split-debuginfo. Use 'off' or 'dsymutil'.",
259                                                      s))),
260                    }
261                    Some(Ok(()))
262                })).unwrap_or(Ok(()))
263            } );
264            ($key_name:ident, list) => ( {
265                let name = (stringify!($key_name)).replace("_", "-");
266                if let Some(j) = obj.remove(&name) {
267                    if let Some(v) = j.as_array() {
268                        base.$key_name = v.iter()
269                            .map(|a| a.as_str().unwrap().to_string().into())
270                            .collect();
271                    } else {
272                        incorrect_type.push(name)
273                    }
274                }
275            } );
276            ($key_name:ident, opt_list) => ( {
277                let name = (stringify!($key_name)).replace("_", "-");
278                if let Some(j) = obj.remove(&name) {
279                    if let Some(v) = j.as_array() {
280                        base.$key_name = Some(v.iter()
281                            .map(|a| a.as_str().unwrap().to_string().into())
282                            .collect());
283                    } else {
284                        incorrect_type.push(name)
285                    }
286                }
287            } );
288            ($key_name:ident, fallible_list) => ( {
289                let name = (stringify!($key_name)).replace("_", "-");
290                obj.remove(&name).and_then(|j| {
291                    if let Some(v) = j.as_array() {
292                        match v.iter().map(|a| FromStr::from_str(a.as_str().unwrap())).collect() {
293                            Ok(l) => { base.$key_name = l },
294                            // FIXME: `fallible_list` can't re-use the `key!` macro for list
295                            // elements and the error messages from that macro, so it has a bad
296                            // generic message instead
297                            Err(_) => return Some(Err(
298                                format!("`{:?}` is not a valid value for `{}`", j, name)
299                            )),
300                        }
301                    } else {
302                        incorrect_type.push(name)
303                    }
304                    Some(Ok(()))
305                }).unwrap_or(Ok(()))
306            } );
307            ($key_name:ident, optional) => ( {
308                let name = (stringify!($key_name)).replace("_", "-");
309                if let Some(o) = obj.remove(&name) {
310                    base.$key_name = o
311                        .as_str()
312                        .map(|s| s.to_string().into());
313                }
314            } );
315            ($key_name:ident = $json_name:expr, LldFlavor) => ( {
316                let name = $json_name;
317                obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
318                    if let Some(flavor) = super::LldFlavor::from_str(&s) {
319                        base.$key_name = flavor;
320                    } else {
321                        return Some(Err(format!(
322                            "'{}' is not a valid value for lld-flavor. \
323                             Use 'darwin', 'gnu', 'link' or 'wasm'.",
324                            s)))
325                    }
326                    Some(Ok(()))
327                })).unwrap_or(Ok(()))
328            } );
329            ($key_name:ident = $json_name:expr, LinkerFlavorCli) => ( {
330                let name = $json_name;
331                obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
332                    match super::LinkerFlavorCli::from_str(s) {
333                        Some(linker_flavor) => base.$key_name = linker_flavor,
334                        _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
335                                                      Use {}", s, super::LinkerFlavorCli::one_of()))),
336                    }
337                    Some(Ok(()))
338                })).unwrap_or(Ok(()))
339            } );
340            ($key_name:ident, StackProbeType) => ( {
341                let name = (stringify!($key_name)).replace("_", "-");
342                obj.remove(&name).and_then(|o| match super::StackProbeType::from_json(&o) {
343                    Ok(v) => {
344                        base.$key_name = v;
345                        Some(Ok(()))
346                    },
347                    Err(s) => Some(Err(
348                        format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
349                    )),
350                }).unwrap_or(Ok(()))
351            } );
352            ($key_name:ident, SanitizerSet) => ( {
353                let name = (stringify!($key_name)).replace("_", "-");
354                if let Some(o) = obj.remove(&name) {
355                    if let Some(a) = o.as_array() {
356                        for s in a {
357                            use super::SanitizerSet;
358                            base.$key_name |= match s.as_str() {
359                                Some("address") => SanitizerSet::ADDRESS,
360                                Some("cfi") => SanitizerSet::CFI,
361                                Some("dataflow") => SanitizerSet::DATAFLOW,
362                                Some("kcfi") => SanitizerSet::KCFI,
363                                Some("kernel-address") => SanitizerSet::KERNELADDRESS,
364                                Some("leak") => SanitizerSet::LEAK,
365                                Some("memory") => SanitizerSet::MEMORY,
366                                Some("memtag") => SanitizerSet::MEMTAG,
367                                Some("safestack") => SanitizerSet::SAFESTACK,
368                                Some("shadow-call-stack") => SanitizerSet::SHADOWCALLSTACK,
369                                Some("thread") => SanitizerSet::THREAD,
370                                Some("hwaddress") => SanitizerSet::HWADDRESS,
371                                Some(s) => return Err(format!("unknown sanitizer {}", s)),
372                                _ => return Err(format!("not a string: {:?}", s)),
373                            };
374                        }
375                    } else {
376                        incorrect_type.push(name)
377                    }
378                }
379                Ok::<(), String>(())
380            } );
381            ($key_name:ident, link_self_contained_components) => ( {
382                // Skeleton of what needs to be parsed:
383                //
384                // ```
385                // $name: {
386                //     "components": [
387                //         <array of strings>
388                //     ]
389                // }
390                // ```
391                let name = (stringify!($key_name)).replace("_", "-");
392                if let Some(o) = obj.remove(&name) {
393                    if let Some(o) = o.as_object() {
394                        let component_array = o.get("components")
395                            .ok_or_else(|| format!("{name}: expected a \
396                                JSON object with a `components` field."))?;
397                        let component_array = component_array.as_array()
398                            .ok_or_else(|| format!("{name}.components: expected a JSON array"))?;
399                        let mut components = super::LinkSelfContainedComponents::empty();
400                        for s in component_array {
401                            components |= match s.as_str() {
402                                Some(s) => {
403                                    super::LinkSelfContainedComponents::from_str(s)
404                                        .ok_or_else(|| format!("unknown \
405                                        `-Clink-self-contained` component: {s}"))?
406                                },
407                                _ => return Err(format!("not a string: {:?}", s)),
408                            };
409                        }
410                        base.$key_name = super::LinkSelfContainedDefault::WithComponents(components);
411                    } else {
412                        incorrect_type.push(name)
413                    }
414                }
415                Ok::<(), String>(())
416            } );
417            ($key_name:ident = $json_name:expr, link_self_contained_backwards_compatible) => ( {
418                let name = $json_name;
419                obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
420                    match s.parse::<super::LinkSelfContainedDefault>() {
421                        Ok(lsc_default) => base.$key_name = lsc_default,
422                        _ => return Some(Err(format!("'{}' is not a valid `-Clink-self-contained` default. \
423                                                      Use 'false', 'true', 'musl' or 'mingw'", s))),
424                    }
425                    Some(Ok(()))
426                })).unwrap_or(Ok(()))
427            } );
428            ($key_name:ident = $json_name:expr, link_objects) => ( {
429                let name = $json_name;
430                if let Some(val) = obj.remove(name) {
431                    let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
432                        JSON object with fields per CRT object kind.", name))?;
433                    let mut args = super::CrtObjects::new();
434                    for (k, v) in obj {
435                        let kind = super::LinkOutputKind::from_str(&k).ok_or_else(|| {
436                            format!("{}: '{}' is not a valid value for CRT object kind. \
437                                     Use '(dynamic,static)-(nopic,pic)-exe' or \
438                                     '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
439                        })?;
440
441                        let v = v.as_array().ok_or_else(||
442                            format!("{}.{}: expected a JSON array", name, k)
443                        )?.iter().enumerate()
444                            .map(|(i,s)| {
445                                let s = s.as_str().ok_or_else(||
446                                    format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
447                                Ok(s.to_string().into())
448                            })
449                            .collect::<Result<Vec<_>, String>>()?;
450
451                        args.insert(kind, v);
452                    }
453                    base.$key_name = args;
454                }
455            } );
456            ($key_name:ident = $json_name:expr, link_args) => ( {
457                let name = $json_name;
458                if let Some(val) = obj.remove(name) {
459                    let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
460                        JSON object with fields per linker-flavor.", name))?;
461                    let mut args = super::LinkArgsCli::new();
462                    for (k, v) in obj {
463                        let flavor = super::LinkerFlavorCli::from_str(&k).ok_or_else(|| {
464                            format!("{}: '{}' is not a valid value for linker-flavor. \
465                                     Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
466                        })?;
467
468                        let v = v.as_array().ok_or_else(||
469                            format!("{}.{}: expected a JSON array", name, k)
470                        )?.iter().enumerate()
471                            .map(|(i,s)| {
472                                let s = s.as_str().ok_or_else(||
473                                    format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
474                                Ok(s.to_string().into())
475                            })
476                            .collect::<Result<Vec<_>, String>>()?;
477
478                        args.insert(flavor, v);
479                    }
480                    base.$key_name = args;
481                }
482            } );
483            ($key_name:ident, env) => ( {
484                let name = (stringify!($key_name)).replace("_", "-");
485                if let Some(o) = obj.remove(&name) {
486                    if let Some(a) = o.as_array() {
487                        for o in a {
488                            if let Some(s) = o.as_str() {
489                                if let [k, v] = *s.split('=').collect::<Vec<_>>() {
490                                    base.$key_name
491                                        .to_mut()
492                                        .push((k.to_string().into(), v.to_string().into()))
493                                }
494                            }
495                        }
496                    } else {
497                        incorrect_type.push(name)
498                    }
499                }
500            } );
501            ($key_name:ident, target_families) => ( {
502                if let Some(value) = obj.remove("target-family") {
503                    if let Some(v) = value.as_array() {
504                        base.$key_name = v.iter()
505                            .map(|a| a.as_str().unwrap().to_string().into())
506                            .collect();
507                    } else if let Some(v) = value.as_str() {
508                        base.$key_name = vec![v.to_string().into()].into();
509                    }
510                }
511            } );
512            ($key_name:ident, Conv) => ( {
513                let name = (stringify!($key_name)).replace("_", "-");
514                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
515                    match super::Conv::from_str(s) {
516                        Ok(c) => {
517                            base.$key_name = c;
518                            Some(Ok(()))
519                        }
520                        Err(e) => Some(Err(e))
521                    }
522                })).unwrap_or(Ok(()))
523            } );
524        }
525
526        if let Some(j) = obj.remove("target-endian") {
527            if let Some(s) = j.as_str() {
528                base.endian = s.parse()?;
529            } else {
530                incorrect_type.push("target-endian".into())
531            }
532        }
533
534        if let Some(fp) = obj.remove("frame-pointer") {
535            if let Some(s) = fp.as_str() {
536                base.frame_pointer = s
537                    .parse()
538                    .map_err(|()| format!("'{s}' is not a valid value for frame-pointer"))?;
539            } else {
540                incorrect_type.push("frame-pointer".into())
541            }
542        }
543
544        key!(c_int_width = "target-c-int-width");
545        key!(c_enum_min_bits, Option<u64>); // if None, matches c_int_width
546        key!(os);
547        key!(env);
548        key!(abi);
549        key!(vendor);
550        key!(linker, optional);
551        key!(linker_flavor_json = "linker-flavor", LinkerFlavorCli)?;
552        key!(lld_flavor_json = "lld-flavor", LldFlavor)?;
553        key!(linker_is_gnu_json = "linker-is-gnu", bool);
554        key!(pre_link_objects = "pre-link-objects", link_objects);
555        key!(post_link_objects = "post-link-objects", link_objects);
556        key!(pre_link_objects_self_contained = "pre-link-objects-fallback", link_objects);
557        key!(post_link_objects_self_contained = "post-link-objects-fallback", link_objects);
558        // Deserializes the backwards-compatible variants of `-Clink-self-contained`
559        key!(
560            link_self_contained = "crt-objects-fallback",
561            link_self_contained_backwards_compatible
562        )?;
563        // Deserializes the components variant of `-Clink-self-contained`
564        key!(link_self_contained, link_self_contained_components)?;
565        key!(pre_link_args_json = "pre-link-args", link_args);
566        key!(late_link_args_json = "late-link-args", link_args);
567        key!(late_link_args_dynamic_json = "late-link-args-dynamic", link_args);
568        key!(late_link_args_static_json = "late-link-args-static", link_args);
569        key!(post_link_args_json = "post-link-args", link_args);
570        key!(link_script, optional);
571        key!(link_env, env);
572        key!(link_env_remove, list);
573        key!(asm_args, list);
574        key!(cpu);
575        key!(need_explicit_cpu, bool);
576        key!(features);
577        key!(dynamic_linking, bool);
578        key!(direct_access_external_data, Option<bool>);
579        key!(dll_tls_export, bool);
580        key!(only_cdylib, bool);
581        key!(executables, bool);
582        key!(relocation_model, RelocModel)?;
583        key!(code_model, CodeModel)?;
584        key!(tls_model, TlsModel)?;
585        key!(disable_redzone, bool);
586        key!(function_sections, bool);
587        key!(dll_prefix);
588        key!(dll_suffix);
589        key!(exe_suffix);
590        key!(staticlib_prefix);
591        key!(staticlib_suffix);
592        key!(families, target_families);
593        key!(abi_return_struct_as_int, bool);
594        key!(is_like_aix, bool);
595        key!(is_like_osx, bool);
596        key!(is_like_solaris, bool);
597        key!(is_like_windows, bool);
598        key!(is_like_msvc, bool);
599        key!(is_like_wasm, bool);
600        key!(is_like_android, bool);
601        key!(binary_format, BinaryFormat)?;
602        key!(default_dwarf_version, u32);
603        key!(allows_weak_linkage, bool);
604        key!(has_rpath, bool);
605        key!(no_default_libraries, bool);
606        key!(position_independent_executables, bool);
607        key!(static_position_independent_executables, bool);
608        key!(plt_by_default, bool);
609        key!(relro_level, RelroLevel)?;
610        key!(archive_format);
611        key!(allow_asm, bool);
612        key!(main_needs_argc_argv, bool);
613        key!(has_thread_local, bool);
614        key!(obj_is_bitcode, bool);
615        key!(bitcode_llvm_cmdline);
616        key!(max_atomic_width, Option<u64>);
617        key!(min_atomic_width, Option<u64>);
618        key!(atomic_cas, bool);
619        key!(panic_strategy, PanicStrategy)?;
620        key!(crt_static_allows_dylibs, bool);
621        key!(crt_static_default, bool);
622        key!(crt_static_respected, bool);
623        key!(stack_probes, StackProbeType)?;
624        key!(min_global_align, Option<u64>);
625        key!(default_codegen_units, Option<u64>);
626        key!(trap_unreachable, bool);
627        key!(requires_lto, bool);
628        key!(singlethread, bool);
629        key!(no_builtins, bool);
630        key!(default_visibility, Option<SymbolVisibility>)?;
631        key!(emit_debug_gdb_scripts, bool);
632        key!(requires_uwtable, bool);
633        key!(default_uwtable, bool);
634        key!(simd_types_indirect, bool);
635        key!(limit_rdylib_exports, bool);
636        key!(override_export_symbols, opt_list);
637        key!(merge_functions, MergeFunctions)?;
638        key!(mcount = "target-mcount");
639        key!(llvm_mcount_intrinsic, optional);
640        key!(llvm_abiname);
641        key!(llvm_floatabi, FloatAbi)?;
642        key!(rustc_abi, RustcAbi)?;
643        key!(relax_elf_relocations, bool);
644        key!(llvm_args, list);
645        key!(use_ctors_section, bool);
646        key!(eh_frame_header, bool);
647        key!(has_thumb_interworking, bool);
648        key!(debuginfo_kind, DebuginfoKind)?;
649        key!(split_debuginfo, SplitDebuginfo)?;
650        key!(supported_split_debuginfo, fallible_list)?;
651        key!(supported_sanitizers, SanitizerSet)?;
652        key!(generate_arange_section, bool);
653        key!(supports_stack_protector, bool);
654        key!(small_data_threshold_support, SmallDataThresholdSupport)?;
655        key!(entry_name);
656        key!(entry_abi, Conv)?;
657        key!(supports_xray, bool);
658
659        base.update_from_cli();
660        base.check_consistency(TargetKind::Json)?;
661
662        // Each field should have been read using `Json::remove` so any keys remaining are unused.
663        let remaining_keys = obj.keys();
664        Ok((
665            base,
666            TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
667        ))
668    }
669}
670
671impl ToJson for Target {
672    fn to_json(&self) -> Json {
673        let mut d = serde_json::Map::new();
674        let default: TargetOptions = Default::default();
675        let mut target = self.clone();
676        target.update_to_cli();
677
678        macro_rules! target_val {
679            ($attr:ident) => {{
680                let name = (stringify!($attr)).replace("_", "-");
681                d.insert(name, target.$attr.to_json());
682            }};
683        }
684
685        macro_rules! target_option_val {
686            ($attr:ident) => {{
687                let name = (stringify!($attr)).replace("_", "-");
688                if default.$attr != target.$attr {
689                    d.insert(name, target.$attr.to_json());
690                }
691            }};
692            ($attr:ident, $json_name:expr) => {{
693                let name = $json_name;
694                if default.$attr != target.$attr {
695                    d.insert(name.into(), target.$attr.to_json());
696                }
697            }};
698            (link_args - $attr:ident, $json_name:expr) => {{
699                let name = $json_name;
700                if default.$attr != target.$attr {
701                    let obj = target
702                        .$attr
703                        .iter()
704                        .map(|(k, v)| (k.desc().to_string(), v.clone()))
705                        .collect::<BTreeMap<_, _>>();
706                    d.insert(name.to_string(), obj.to_json());
707                }
708            }};
709            (env - $attr:ident) => {{
710                let name = (stringify!($attr)).replace("_", "-");
711                if default.$attr != target.$attr {
712                    let obj = target
713                        .$attr
714                        .iter()
715                        .map(|&(ref k, ref v)| format!("{k}={v}"))
716                        .collect::<Vec<_>>();
717                    d.insert(name, obj.to_json());
718                }
719            }};
720        }
721
722        target_val!(llvm_target);
723        target_val!(metadata);
724        d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
725        target_val!(arch);
726        target_val!(data_layout);
727
728        target_option_val!(endian, "target-endian");
729        target_option_val!(c_int_width, "target-c-int-width");
730        target_option_val!(os);
731        target_option_val!(env);
732        target_option_val!(abi);
733        target_option_val!(vendor);
734        target_option_val!(linker);
735        target_option_val!(linker_flavor_json, "linker-flavor");
736        target_option_val!(lld_flavor_json, "lld-flavor");
737        target_option_val!(linker_is_gnu_json, "linker-is-gnu");
738        target_option_val!(pre_link_objects);
739        target_option_val!(post_link_objects);
740        target_option_val!(pre_link_objects_self_contained, "pre-link-objects-fallback");
741        target_option_val!(post_link_objects_self_contained, "post-link-objects-fallback");
742        target_option_val!(link_args - pre_link_args_json, "pre-link-args");
743        target_option_val!(link_args - late_link_args_json, "late-link-args");
744        target_option_val!(link_args - late_link_args_dynamic_json, "late-link-args-dynamic");
745        target_option_val!(link_args - late_link_args_static_json, "late-link-args-static");
746        target_option_val!(link_args - post_link_args_json, "post-link-args");
747        target_option_val!(link_script);
748        target_option_val!(env - link_env);
749        target_option_val!(link_env_remove);
750        target_option_val!(asm_args);
751        target_option_val!(cpu);
752        target_option_val!(need_explicit_cpu);
753        target_option_val!(features);
754        target_option_val!(dynamic_linking);
755        target_option_val!(direct_access_external_data);
756        target_option_val!(dll_tls_export);
757        target_option_val!(only_cdylib);
758        target_option_val!(executables);
759        target_option_val!(relocation_model);
760        target_option_val!(code_model);
761        target_option_val!(tls_model);
762        target_option_val!(disable_redzone);
763        target_option_val!(frame_pointer);
764        target_option_val!(function_sections);
765        target_option_val!(dll_prefix);
766        target_option_val!(dll_suffix);
767        target_option_val!(exe_suffix);
768        target_option_val!(staticlib_prefix);
769        target_option_val!(staticlib_suffix);
770        target_option_val!(families, "target-family");
771        target_option_val!(abi_return_struct_as_int);
772        target_option_val!(is_like_aix);
773        target_option_val!(is_like_osx);
774        target_option_val!(is_like_solaris);
775        target_option_val!(is_like_windows);
776        target_option_val!(is_like_msvc);
777        target_option_val!(is_like_wasm);
778        target_option_val!(is_like_android);
779        target_option_val!(binary_format);
780        target_option_val!(default_dwarf_version);
781        target_option_val!(allows_weak_linkage);
782        target_option_val!(has_rpath);
783        target_option_val!(no_default_libraries);
784        target_option_val!(position_independent_executables);
785        target_option_val!(static_position_independent_executables);
786        target_option_val!(plt_by_default);
787        target_option_val!(relro_level);
788        target_option_val!(archive_format);
789        target_option_val!(allow_asm);
790        target_option_val!(main_needs_argc_argv);
791        target_option_val!(has_thread_local);
792        target_option_val!(obj_is_bitcode);
793        target_option_val!(bitcode_llvm_cmdline);
794        target_option_val!(min_atomic_width);
795        target_option_val!(max_atomic_width);
796        target_option_val!(atomic_cas);
797        target_option_val!(panic_strategy);
798        target_option_val!(crt_static_allows_dylibs);
799        target_option_val!(crt_static_default);
800        target_option_val!(crt_static_respected);
801        target_option_val!(stack_probes);
802        target_option_val!(min_global_align);
803        target_option_val!(default_codegen_units);
804        target_option_val!(trap_unreachable);
805        target_option_val!(requires_lto);
806        target_option_val!(singlethread);
807        target_option_val!(no_builtins);
808        target_option_val!(default_visibility);
809        target_option_val!(emit_debug_gdb_scripts);
810        target_option_val!(requires_uwtable);
811        target_option_val!(default_uwtable);
812        target_option_val!(simd_types_indirect);
813        target_option_val!(limit_rdylib_exports);
814        target_option_val!(override_export_symbols);
815        target_option_val!(merge_functions);
816        target_option_val!(mcount, "target-mcount");
817        target_option_val!(llvm_mcount_intrinsic);
818        target_option_val!(llvm_abiname);
819        target_option_val!(llvm_floatabi);
820        target_option_val!(rustc_abi);
821        target_option_val!(relax_elf_relocations);
822        target_option_val!(llvm_args);
823        target_option_val!(use_ctors_section);
824        target_option_val!(eh_frame_header);
825        target_option_val!(has_thumb_interworking);
826        target_option_val!(debuginfo_kind);
827        target_option_val!(split_debuginfo);
828        target_option_val!(supported_split_debuginfo);
829        target_option_val!(supported_sanitizers);
830        target_option_val!(c_enum_min_bits);
831        target_option_val!(generate_arange_section);
832        target_option_val!(supports_stack_protector);
833        target_option_val!(small_data_threshold_support);
834        target_option_val!(entry_name);
835        target_option_val!(entry_abi);
836        target_option_val!(supports_xray);
837
838        // Serializing `-Clink-self-contained` needs a dynamic key to support the
839        // backwards-compatible variants.
840        d.insert(self.link_self_contained.json_key().into(), self.link_self_contained.to_json());
841
842        Json::Object(d)
843    }
844}