Skip to content

Standardize .config format: int/hex without quotes, proper type generation - #3

Merged
guoweikang merged 3 commits into
mainfrom
copilot/update-config-writer-format
Feb 10, 2026
Merged

Standardize .config format: int/hex without quotes, proper type generation#3
guoweikang merged 3 commits into
mainfrom
copilot/update-config-writer-format

Conversation

Copilot AI commented Feb 10, 2026

Copy link
Copy Markdown
Contributor

Int and hex values were written with quotes in .config files, causing cargo-kbuild to incorrectly generate string types instead of numeric types for constants.

Changes

ConfigWriter (xtask/xconfig/src/config/writer.rs)

  • Int values: no quotes, decimal format (MAX_CPUS=102)
  • Hex values: no quotes, 0x format (MEMORY_BASE=0x80000000)
    • Converts decimal inputs to hex automatically
  • String values: preserve quotes (KERNEL_VERSION="0.0.1")

cargo-kbuild (xtask/cargo-kbuild/src/main.rs)

  • parse_config(): strips quotes for backward compatibility with old configs
  • generate_config_rs(): enhanced type detection
    • 0x prefix → u64
    • Unsigned integers → u64
    • Signed integers → i64
    • All else → &str
  • Fixed parsing order (u64 before i64) to avoid unreachable code

Tests (xtask/xconfig/tests/config_tests.rs)

  • Added 6 tests covering int/hex/string formatting and backward compatibility

Impact

Before:

pub const MEMORY_BASE: &str = "2147483648";  // Wrong type

After:

pub const MEMORY_BASE: u64 = 0x80000000;     // Correct type and format

Old .config files with quotes continue to work via quote-stripping in the parser.

Original prompt

Problem: Int and Hex values need proper format in .config for cargo-kbuild integration

Currently:

  • Int values saved with quotes: MAX_CPUS="102"
  • Hex values saved with quotes: MEMORY_BASE="2147483648"
  • cargo-kbuild has complex parsing logic to handle quoted/unquoted values

Goal

Standardize .config format for seamless cargo-kbuild integration:

  • Int values: NO quotes, decimal format: MAX_CPUS=102
  • Hex values: NO quotes, hex format: MEMORY_BASE=0x80000000
  • String values: Keep quotes: KERNEL_VERSION="0.0.1"

Part 1: Update ConfigWriter to save int/hex without quotes

File: xtask/xconfig/src/config/writer.rs

Replace lines 18-37 with:

for (name, symbol) in symbols.all_symbols() {
    let clean_name = name.strip_prefix("CONFIG_").unwrap_or(name);
    
    if let Some(value) = &symbol.value {
        match value.as_str() {
            "y" | "m" => {
                writeln!(file, "{}={}", clean_name, value)?;
            }
            "n" => {
                writeln!(file, "# {} is not set", clean_name)?;
            }
            _ => {
                use crate::kconfig::ast::SymbolType;
                match symbol.symbol_type {
                    SymbolType::Hex => {
                        // Hex: NO quotes, normalize to 0x format
                        let normalized_hex = if value.starts_with("0x") || value.starts_with("0X") {
                            format!("0x{}", value[2..].to_lowercase())
                        } else {
                            match value.parse::<i64>() {
                                Ok(num) if num >= 0 => format!("0x{:x}", num),
                                Ok(num) => format!("-0x{:x}", num.unsigned_abs()),
                                Err(_) => value.to_string(),
                            }
                        };
                        writeln!(file, "{}={}", clean_name, normalized_hex)?;
                    }
                    SymbolType::Int => {
                        // Int: NO quotes, decimal format
                        writeln!(file, "{}={}", clean_name, value)?;
                    }
                    SymbolType::String => {
                        // String: Keep quotes
                        writeln!(file, "{}=\"{}\"", clean_name, value)?;
                    }
                    _ => {
                        // Fallback for other types
                        writeln!(file, "{}=\"{}\"", clean_name, value)?;
                    }
                }
            }
        }
    } else {
        writeln!(file, "# {} is not set", clean_name)?;
    }
}

Part 2: Update cargo-kbuild to handle standardized format

File: xtask/cargo-kbuild/src/main.rs

Change 1: Update parse_config function (around line 275-293)

Replace with:

/// Parse .config file
/// Now expects standardized format:
/// - Bool: CONFIG_X=y or # CONFIG_X is not set
/// - Int: CONFIG_X=123 (no quotes)
/// - Hex: CONFIG_X=0xff (no quotes)
/// - String: CONFIG_X="value" (with quotes)
fn parse_config(config_path: &Path) -> Result<HashMap<String, String>, String> {
    let content = fs::read_to_string(config_path)
        .map_err(|e| format!("Failed to read .config: {}", e))?;

    let mut config = HashMap::new();
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        if let Some((key, value)) = line.split_once('=') {
            let key = key.trim();
            let value = value.trim();
            
            // Remove quotes if present (for backward compatibility)
            let value = if value.starts_with('"') && value.ends_with('"') {
                &value[1..value.len()-1]
            } else {
                value
            };
            
            config.insert(key.to_string(), value.to_string());
        }
    }

    Ok(config)
}

Change 2: Update generate_config_rs function (around line 310-353)

Replace with:

/// Generate config.rs file with constants
/// Handles three types:
/// - Int: decimal numbers (e.g., 123)
/// - Hex: 0x-prefixed numbers (e.g., 0xff)
/// - String: everything else with quotes
fn generate_config_rs(workspace_root: &Path, config: &HashMap<String, String>) -> Result<(), String> {
    let target_dir = workspace_root.join("target/kbuild");
    fs::create_dir_all(&target_dir)
        .map_err(|e| format!("Failed to create target/kbuild: {}", e))?;

    let config_rs_path = target_dir.join("config.rs");

    let mut content = String::new();
    content.push_str("// Auto-generated by cargo-kbuild from .config\n");
    content.push_str("// DO NOT EDIT MANUALLY\n\n");

    for (key, value) in config {
        // Skip boolean configs (y/n/m) - handled via --cfg
        if value == "y" || value == "n" || value == "m" {
            continue;
        }

        content.push_str(&format!("#[allow(dead_code)]\n"));

        // Check if it's a hex...

</details>



<!-- START COPILOT CODING AGENT SUFFIX -->

*This pull request was created from Copilot chat.*
>

<!-- START COPILOT CODING AGENT TIPS -->
---

💬 We'd love your input! Share your thoughts on Copilot coding agent in our [2 minute survey](https://gh.io/copilot-coding-agent-survey).

Copilot AI and others added 2 commits February 10, 2026 07:59
- Part 1: Update ConfigWriter to handle Int/Hex/String types
  - Int values: NO quotes, decimal format (MAX_CPUS=102)
  - Hex values: NO quotes, 0x format (MEMORY_BASE=0x80000000)
  - String values: Keep quotes (KERNEL_VERSION="0.0.1")

- Part 2: Update cargo-kbuild for standardized format
  - parse_config: Remove quotes for backward compatibility
  - generate_config_rs: Correct type detection (i64/u64/&str)

- Part 3: Add comprehensive tests
  - Test int/hex/string format handling
  - Test backward compatibility with quoted values
  - Verify generated config.rs has correct Rust types

Co-authored-by: guoweikang <18571063+guoweikang@users.noreply.github.com>
…rder

- Simplify hex handling: use u64 instead of i64 (negative hex not standard)
- Fix parsing order in generate_config_rs: check u64 before i64
- Avoid duplicate parsing by using match instead of is_ok()

Co-authored-by: guoweikang <18571063+guoweikang@users.noreply.github.com>
Copilot AI changed the title [WIP] Update ConfigWriter to save int and hex values without quotes Standardize .config format: int/hex without quotes, proper type generation Feb 10, 2026
Copilot AI requested a review from guoweikang February 10, 2026 08:07
@guoweikang
guoweikang marked this pull request as ready for review February 10, 2026 08:11
@guoweikang
guoweikang merged commit c9692db into main Feb 10, 2026
2 of 7 checks passed
@guoweikang
guoweikang deleted the copilot/update-config-writer-format branch March 10, 2026 07:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants