esp-idf-sys 0.37.2

Bindings for ESP-IDF (Espressif's IoT Development Framework)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
use std::collections::HashSet;
use std::fmt::Display;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{error, fs, iter};

use anyhow::{anyhow, bail, Result};
use embuild::cargo::{self, IntoWarning};
use embuild::utils::{OsStrExt, PathExt};
use embuild::{bindgen, build, kconfig};
use strum::{Display, EnumDiscriminants, EnumString};

use crate::config::BuildConfig;

const TOOLS_WORKSPACE_INSTALL_DIR: &str = ".embuild";

pub struct EspIdfBuildOutput {
    pub cincl_args: build::CInclArgs,
    pub link_args: Option<build::LinkArgs>,
    pub kconfig_args: Box<dyn Iterator<Item = (String, kconfig::Value)>>,
    pub components: EspIdfComponents,
    pub bindgen: bindgen::Factory,
    pub env_path: Option<String>,
    pub esp_idf: PathBuf,
    #[allow(dead_code)]
    pub config: BuildConfig,
}

pub struct EspIdfComponents(Vec<String>);

impl EspIdfComponents {
    pub fn new(components: Vec<String>) -> Self {
        Self(components)
    }

    #[allow(dead_code)]
    pub fn from_esp_idf(esp_idf: &Path) -> Result<Self> {
        Self::from_dirs([esp_idf.join("components")])
    }

    #[allow(dead_code)]
    pub fn from_dirs(dirs: impl IntoIterator<Item = impl AsRef<Path>>) -> Result<Self> {
        let components = dirs
            .into_iter()
            .filter_map(|dir| Self::scan(dir.as_ref()).ok())
            .flatten()
            .collect::<Vec<_>>();

        Ok(Self::new(components))
    }

    #[allow(dead_code)]
    pub fn from(enabled: impl IntoIterator<Item = impl Into<String>>) -> Self {
        // NOTE: The components which are always enabled by ESP-IDF's CMake build (for ESP-IDF V4.4) are as follows:
        // cxx; newlib; freertos; esp_hw_support; heap; log; lwip; soc; hal; esp_rom; esp_common; esp_system;
        // esp32; <- Depends on the selected MCU
        //
        // Note also, that for now you always have to explicitly include the `pthread` component,
        // or else `esp-idf-hal` will currently fail to compile (due to its mutex and condvar being implemented on top of pthread)
        //
        // `pthread` is also mandatory when compiling with Rust STD enabled, or else you'll get linker errors
        Self::new(
            enabled
                .into_iter()
                .map(Into::into)
                // deduplicate the components
                .collect::<HashSet<_>>()
                .into_iter()
                .collect::<Vec<_>>(),
        )
    }

    fn scan(path: &Path) -> Result<Box<dyn Iterator<Item = String>>> {
        let comp_name = Self::get_comp_name(path);
        let components: Box<dyn Iterator<Item = String>> = if let Some(comp_name) = comp_name {
            if path.join("CMakeLists.txt").exists() {
                Box::new(iter::once(comp_name.to_owned()))
            } else {
                Box::new(
                    path.read_dir()?
                        .filter_map(|entry| entry.ok())
                        .filter_map(|entry| Self::scan(&entry.path()).ok())
                        .flatten(),
                )
            }
        } else {
            Box::new(iter::empty())
        };

        Ok(components)
    }

    fn get_comp_name(path: &Path) -> Option<&str> {
        if path.is_dir() {
            path.file_name()
                .and_then(|file_name| file_name.to_str())
                .and_then(|c| if c.starts_with('.') { None } else { Some(c) })
        } else {
            None
        }
    }

    #[allow(clippy::needless_lifetimes)]
    pub fn clang_args<'a>(&'a self) -> impl Iterator<Item = String> + 'a {
        self.0.iter().map(|c| {
            format!(
                "-DESP_IDF_COMP_{}_ENABLED",
                c.to_uppercase().replace('-', "_")
            )
        })
    }

    #[allow(clippy::needless_lifetimes)]
    pub fn cfg_args<'a>(&'a self) -> impl Iterator<Item = String> + 'a {
        self.0.iter().map(|c| {
            format!(
                "esp_idf_comp_{}_enabled",
                c.to_lowercase().replace('-', "_")
            )
        })
    }
}

pub struct EspIdfVersion {
    pub major: u32,
    pub minor: u32,
    pub patch: u32,
}

impl EspIdfVersion {
    pub fn parse(bindings_file: impl AsRef<Path>) -> Result<Self> {
        let bindings_content = fs::read_to_string(bindings_file.as_ref())?;

        Ok(Self {
            major: Self::grab_const(&bindings_content, "ESP_IDF_VERSION_MAJOR", "u32")?,
            minor: Self::grab_const(&bindings_content, "ESP_IDF_VERSION_MINOR", "u32")?,
            patch: Self::grab_const(bindings_content, "ESP_IDF_VERSION_PATCH", "u32")?,
        })
    }

    pub fn cfg_args(&self) -> impl Iterator<Item = String> {
        iter::once(format!(
            "esp_idf_version_full=\"{}.{}.{}\"",
            self.major, self.minor, self.patch
        ))
        .chain(iter::once(format!(
            "esp_idf_version=\"{}.{}\"",
            self.major, self.minor
        )))
        .chain(iter::once(format!(
            "esp_idf_version_major=\"{}\"",
            self.major
        )))
        .chain(iter::once(format!(
            "esp_idf_version_minor=\"{}\"",
            self.minor
        )))
        .chain(iter::once(format!(
            "esp_idf_version_patch=\"{}\"",
            self.patch
        )))
        .chain(self.atleast_version(self.major as u8, self.minor as u8, self.patch as u8))
    }

    fn grab_const<T>(
        text: impl AsRef<str>,
        const_name: impl AsRef<str>,
        const_type: impl AsRef<str>,
    ) -> Result<T>
    where
        T: FromStr,
        T::Err: error::Error + Send + Sync + 'static,
    {
        // Future: Consider using bindgen::callbacks::ParseCallbacks for grabbing macro-based constants. Should be more reliable compared to grepping

        let const_name = const_name.as_ref();

        let value = regex::Regex::new(&format!(
            r"\s+const\s+{}\s*:\s*{}\s*=\s*(\S+)\s*;",
            const_name,
            const_type.as_ref()
        ))?
        .captures(text.as_ref())
        .ok_or_else(|| anyhow!("Failed to capture constant {}", const_name))?
        .get(1)
        .ok_or_else(|| anyhow!("Failed to capture the value of constant {}", const_name))?
        .as_str()
        .parse::<T>()?;

        Ok(value)
    }

    /// Return an iterator of strings, where each string is either of the form `esp_idf_version_at_least_X_Y_Z`
    /// or of the form `esp_idf_version_patch_at_least_X_Y_Z` / `esp_idf_version_patch_at_most_X_Y_Z`.
    ///
    /// X.Y.Z denotes a released ESP-IDF version which is smaller or equal to the ESP-IDF
    /// verson against which we are compiling.
    ///
    /// Thus if we are compiling e.g. against ESP-IDF 5.2.3, the iterator will yield:
    /// - `esp_idf_version_at_least_4_4_0` .. `esp_idf_version_at_least_4_4_10`
    /// - `esp_idf_version_at_least_5_0_0` .. `esp_idf_version_at_least_5_0_10`
    /// - ... and so on, up to `esp_idf_version_at_least_5_2_3`
    ///
    /// Additionally, for e.g. ESP-IDF 5.2.3, the iterator will yield:
    /// - `esp_idf_version_patch_at_least_5_2_0` .. `esp_idf_version_patch_at_least_5_2_3`
    /// - `esp_idf_version_patch_at_most_5_2_3` .. `esp_idf_version_patch_at_most_5_2_10`
    ///
    /// This is useful for generating conditional compilation flags for version-specific ESP-IDF features
    /// which is otherwise very difficut because the Rust `cfg` syntax does not support
    /// anything else but "=" (equality)
    fn atleast_version(
        &self,
        cur_maj: u8,
        cur_min: u8,
        cur_patch: u8,
    ) -> impl Iterator<Item = String> {
        // Major, Minimum Minor for that Major, Maximum Minor for that Major
        // (Patch Level always from 0 to MAX_PATCH_LEVEL, inclusive)
        const VER_RANGES: [(u8, u8, u8); 3] = [(4, 4, 4), (5, 0, 5), (6, 0, 2)];

        // This can be increased should an ESP-IDF version with a patch level > 10 ever appears (very unlikely)
        const MAX_PATCH_LEVEL: u8 = 10;

        let versions = || {
            VER_RANGES
                .into_iter()
                .flat_map(|(maj, min_min, min_max)| (min_min..=min_max).map(move |min| (maj, min)))
                .flat_map(|(maj, min)| (0..=MAX_PATCH_LEVEL).map(move |patch| (maj, min, patch)))
        };

        versions()
            .filter(move |(maj, min, patch)| {
                cur_maj > *maj
                    || (cur_maj == *maj && cur_min > *min)
                    || (cur_maj == *maj && cur_min == *min && cur_patch >= *patch)
            })
            .map(|(maj, min, patch)| format!("esp_idf_version_at_least_{maj}_{min}_{patch}"))
            .chain(
                versions()
                    .filter(move |(maj, min, patch)| {
                        cur_maj == *maj && cur_min == *min && cur_patch >= *patch
                    })
                    .map(|(maj, min, patch)| {
                        format!("esp_idf_version_patch_at_least_{maj}_{min}_{patch}")
                    }),
            )
            .chain(
                versions()
                    .filter(move |(maj, min, patch)| {
                        cur_maj == *maj && cur_min == *min && cur_patch <= *patch
                    })
                    .map(|(maj, min, patch)| {
                        format!("esp_idf_version_patch_at_most_{maj}_{min}_{patch}")
                    }),
            )
    }
}

pub fn build_profile() -> String {
    std::env::var("PROFILE").expect("No cargo `PROFILE` environment variable")
}

/// List all appropriate sdkconfig files.
///
/// Returns an iterator of paths with the following patterns and ordering if they exist
/// and are files:
/// 1. `<path>.<profile>.<chip>`
/// 2. `<path>.<chip>`
/// 3. `<path>.<profile>`
/// 4. `<path>`
pub fn list_specific_sdkconfigs(
    path: PathBuf,
    profile: &str,
    chip: &str,
) -> impl DoubleEndedIterator<Item = PathBuf> {
    path.file_name()
        .and_then(|filename| filename.try_to_str().into_warning())
        .map(|filename| {
            let profile_specific = format!("{filename}.{profile}");
            let chip_specific = format!("{filename}.{chip}");
            let profile_chip_specific = format!("{}.{}", &profile_specific, chip);

            [
                profile_chip_specific,
                chip_specific,
                profile_specific,
                filename.to_owned(),
            ]
        })
        .into_iter()
        .flatten()
        .filter_map(move |s| {
            let path = path.with_file_name(s);
            if path.is_file() {
                Some(path)
            } else {
                None
            }
        })
}

#[derive(Clone, Debug, EnumDiscriminants)]
#[strum_discriminants(name(InstallDirLocation), derive(Display, EnumString))]
#[strum_discriminants(strum(serialize_all = "lowercase"))]
pub enum InstallDir {
    Global,
    Workspace(PathBuf),
    Out(PathBuf),
    Custom(PathBuf),
    FromEnv,
}

impl InstallDir {
    /// Get the install directory from the [`ESP_IDF_TOOLS_INSTALL_DIR_VAR`] env variable.
    ///
    /// If this env variable is unset or empty uses `default_install_dir` instead.
    pub fn try_from(location: Option<&str>) -> Result<Self> {
        let (location, path) = match &location {
            None => (crate::config::DEFAULT_TOOLS_INSTALL_DIR, None),
            Some(val) => {
                let (loc, path) = val
                    .split_once(':')
                    .map(|(l, r)| (l, Some(r)))
                    .unwrap_or((val, None));
                (InstallDirLocation::from_str(&loc.to_lowercase())?, path)
            }
        };
        let install_dir = match location {
            InstallDirLocation::Global => Self::Global,
            InstallDirLocation::Workspace => Self::Workspace(
                workspace_dir()?
                    .join(TOOLS_WORKSPACE_INSTALL_DIR)
                    .join(crate::build_driver::TOOLS_DIR),
            ),
            InstallDirLocation::Out => {
                Self::Out(cargo::out_dir().join(crate::build_driver::TOOLS_DIR))
            }
            InstallDirLocation::FromEnv => Self::FromEnv,
            _ => Self::Custom({
                if let Some(path) = path {
                    Path::new(path).abspath_relative_to(workspace_dir()?)
                } else {
                    bail!(
                        "Invalid installation directory format. \
                         Should be one of `global`, `workspace`, `out`, `fromenv` or `custom:<dir>`."
                    );
                }
            }),
        };
        Ok(install_dir)
    }

    pub fn is_from_env(&self) -> bool {
        matches!(self, Self::FromEnv)
    }

    pub fn path(&self) -> Option<&Path> {
        match self {
            Self::Global | Self::FromEnv => None,
            Self::Workspace(ref path) => Some(path.as_ref()),
            Self::Out(ref path) => Some(path.as_ref()),
            Self::Custom(ref path) => Some(path.as_ref()),
        }
    }
}

impl<'d> serde::Deserialize<'d> for InstallDir {
    fn deserialize<D>(de: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'d>,
    {
        InstallDir::try_from(Some(&String::deserialize(de)?)).map_err(serde::de::Error::custom)
    }
}

impl Display for InstallDir {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Global => write!(f, "global"),
            Self::Workspace(ref path) => write!(f, "workspace ({})", path.display()),
            Self::Out(ref path) => write!(f, "out ({})", path.display()),
            Self::Custom(ref path) => write!(f, "custom ({})", path.display()),
            Self::FromEnv => write!(f, "fromenv"),
        }
    }
}

pub fn workspace_dir() -> Result<PathBuf> {
    cargo::workspace_dir().ok_or_else(|| anyhow!("Cannot fetch crate's workspace dir"))
}

pub fn manifest_dir() -> Result<PathBuf> {
    std::env::var_os("CARGO_MANIFEST_DIR")
        .ok_or_else(|| {
            anyhow!(
                "Environment variable `CARGO_MANIFEST_DIR` unavailable: not in cargo build script"
            )
        })
        .map(PathBuf::from)
}

pub fn sanitize_c_env_vars() -> Result<()> {
    const POLICY_VAR: &str = "ESP_IDF_C_ENV_VARS_ISSUES";
    const C_ENV_VARS: &[&str] = &[
        "CC",
        "CXX",
        "CFLAGS",
        "CCFLAGS",
        "CXXFLAGS",
        "CPPFLAGS",
        "LDFLAGS",
        "GCC_EXEC_PREFIX",
        "COMPILER_PATH",
        "C_INCLUDE_PATH",
        "CPLUS_INCLUDE_PATH",
    ];

    let set_vars = C_ENV_VARS
        .iter()
        .filter_map(|var| std::env::var(var).ok().map(|value| (var, value)))
        .collect::<Vec<_>>();

    if !set_vars.is_empty() {
        let message = set_vars
            .iter()
            .map(|(key, value)| format!("{key}={value}"))
            .collect::<Vec<_>>()
            .join(";");

        let policy = std::env::var(POLICY_VAR)
            .ok()
            .unwrap_or("warnremove".into())
            .to_ascii_lowercase();

        match policy.as_str() {
            "warn" | "err" => {
                let message =
                    format!("Detected env vars that might affect the ESP IDF C build: `{message}`");

                if policy == "warn" {
                    cargo::print_warning(format!("(esp-idf-sys) {message}"));
                } else {
                    bail!(message);
                }
            }
            "warnremove" | "remove" => {
                for (var, _) in set_vars {
                    std::env::remove_var(var);
                }

                if policy == "warnremove" {
                    let message = format!(
                        "Removed env vars that might affect the ESP IDF C build: `{message}`"
                    );

                    cargo::print_warning(format!("(esp-idf-sys) {message}"));
                }
            }
            "ignore" => (),
            _ => bail!("Unsupported value for {POLICY_VAR} env var: {policy}"),
        }
    }

    Ok(())
}

pub fn sanitize_project_path() -> Result<()> {
    const POLICY_VAR: &str = "ESP_IDF_PATH_ISSUES";

    let out_dir = std::fs::canonicalize(cargo::out_dir())?
        .to_string_lossy()
        .into_owned();

    let report = |message: String| {
        let policy = std::env::var(POLICY_VAR).ok().unwrap_or("err".into());

        match policy.as_str() {
            "warn" => cargo::print_warning(format!("(esp-idf-sys) {message}")),
            "err" => bail!(message),
            "ignore" => (),
            _ => bail!("Unsupported value for {POLICY_VAR} env var: {policy}"),
        }

        Ok(())
    };

    #[cfg(windows)]
    {
        if out_dir.len() > 88 {
            report(format!("Too long output directory: `{out_dir}`. Shorten your project path down to no more than 10 characters (or use WSL2 and its native Linux filesystem). Note that tricks like Windows `subst` do NOT work!"))?;
        }
    }

    #[cfg(not(windows))]
    {
        if out_dir.contains(' ') {
            report(format!("Output directory contains spaces: `{out_dir}`."))?;
        }
    }

    Ok(())
}

pub fn setup_clang_env(path: Option<&Path>) -> Result<()> {
    if let Some(path) = path {
        // Path was provided, use that instead of relying on the `espup` symlink
        std::env::set_var("LIBCLANG_PATH", path);
    } else {
        const POLICY_VAR: &str = "ESP_IDF_ESPUP_CLANG_SYMLINK";
        let policy = std::env::var(POLICY_VAR)
            .ok()
            .unwrap_or("try".into())
            .to_lowercase();

        if policy != "ignore" {
            #[allow(deprecated)]
            let espup_clang_path =
                std::env::home_dir().map(|home| home.join(".espup").join("esp-clang"));

            let err_msg = if let Some(espup_clang_path) = espup_clang_path {
                if let Ok(real_path) = std::fs::read_link(&espup_clang_path) {
                    if real_path.is_dir() {
                        std::env::set_var("LIBCLANG_PATH", real_path.as_os_str());
                        None
                    } else {
                        Some(format!(
                            "Symlink {} points to a file",
                            espup_clang_path.display()
                        ))
                    }
                } else {
                    Some(format!(
                        "Symlink {} does not exist or points to a non-existing location",
                        espup_clang_path.display()
                    ))
                }
            } else {
                Some("Cannot locate user home directory".into())
            };

            if let Some(err_msg) = err_msg {
                if policy == "warn" {
                    cargo::print_warning(format!("(esp-idf-sys) {err_msg}"));
                } else if policy == "err" {
                    bail!(err_msg);
                }
            }
        }
    }

    Ok(())
}