summaryrefslogtreecommitdiff
path: root/components/rust/tools/build_component.py
blob: 3a1871f6c6af3290691c0d80360419f8c65f2a7d (plain)
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
import os
import subprocess
from SCons.Subst import quote_spaces


# Configuration to feature mapping table for components
# This table defines which RT-Thread configurations should enable which component features
# All feature configurations are now defined in feature_config_component.py
CONFIG_COMPONENT_FEATURE_MAP = {
}


class ComponentBuildError(Exception):
    pass


def load_toml_module():
    try:
        import toml
        return toml
    except ImportError as e:
        raise ComponentBuildError("Missing toml module required to parse component Cargo.toml") from e


def normalize_component_build_root(build_root, cwd):
    """
    Normalize the component build root directory.

    Args:
        build_root: Optional build root directory
        cwd: Current working directory (component directory)

    Returns:
        str: Absolute build root path
    """
    if build_root is None:
        if not cwd:
            raise ComponentBuildError("Invalid build_root: cwd is required when build_root is None")
        build_root = os.path.join(cwd, "build", "rust", "component")

    try:
        build_root = os.fspath(build_root)
    except TypeError:
        raise ComponentBuildError("Invalid build_root: expected a non-empty path")

    if not isinstance(build_root, str) or not build_root:
        raise ComponentBuildError("Invalid build_root: expected a non-empty path")

    return os.path.abspath(build_root)


def get_component_staticlib_artifact_name(rust_dir):
    cargo_toml_path = os.path.join(rust_dir, "Cargo.toml")
    lib_name = "em_component_registry"

    try:
        import toml
        with open(cargo_toml_path, "r") as f:
            cargo_data = toml.load(f)

        package_name = cargo_data.get("package", {}).get("name")
        lib_name = cargo_data.get("lib", {}).get("name") or package_name or lib_name
    except Exception as e:
        print(f"Warning: Failed to parse Rust component static library metadata from {cargo_toml_path}: {e}")

    if not isinstance(lib_name, str) or not lib_name:
        lib_name = "em_component_registry"

    lib_name = lib_name.replace("-", "_")
    return f"lib{lib_name}.a"


def get_component_staticlib_link_name(rust_dir):
    cargo_toml_path = os.path.join(rust_dir, "Cargo.toml")
    lib_name = "em_component_registry"

    try:
        import toml
        with open(cargo_toml_path, "r") as f:
            cargo_data = toml.load(f)

        package_name = cargo_data.get("package", {}).get("name")
        lib_name = cargo_data.get("lib", {}).get("name") or package_name or lib_name
    except Exception as e:
        print(f"Warning: Failed to parse Rust component static library metadata from {cargo_toml_path}: {e}")

    if not isinstance(lib_name, str) or not lib_name:
        lib_name = "em_component_registry"

    return lib_name.replace("-", "_")


def get_staticlib_link_name_from_artifact(lib_path):
    """
    Derive the linker library name from the actual staticlib artifact file name.

    Args:
        lib_path: Path to the built staticlib artifact

    Returns:
        str: Link name (artifact name without the leading 'lib' and trailing
             '.a'), or None if the artifact does not follow that convention.
    """
    artifact_name = os.path.basename(os.fspath(lib_path))
    if artifact_name.startswith("lib") and artifact_name.endswith(".a"):
        return artifact_name[3:-2]
    return None


def get_component_export_symbols(features):
    enabled_features = set(features or [])
    symbols = []
    for config_info in CONFIG_COMPONENT_FEATURE_MAP.values():
        if config_info['feature'] in enabled_features:
            export_symbols = config_info.get('export_symbols', [])
            if not export_symbols:
                raise ComponentBuildError(
                    f"No link anchor metadata registered for enabled component feature '{config_info['feature']}'"
                )
            symbols.extend(export_symbols)
    return symbols


def check_component_dependencies(component_dir, required_dependencies):
    """
    Check if a component has the required dependencies
    
    Args:
        component_dir: Component directory path
        required_dependencies: List of dependency names to check
        
    Returns:
        bool: True if all required dependencies are present
    """
    if not component_dir or not required_dependencies:
        return True
    
    cargo_toml_path = os.path.join(component_dir, 'Cargo.toml')
    if not os.path.exists(cargo_toml_path):
        return False
    
    try:
        import toml
        with open(cargo_toml_path, 'r') as f:
            cargo_data = toml.load(f)
        
        dependencies = cargo_data.get('dependencies', {})
        
        # Check if all required dependencies are present
        for dep in required_dependencies:
            if dep not in dependencies:
                return False
        
        return True
        
    except Exception as e:
        print(f"Warning: Failed to parse {cargo_toml_path}: {e}")
        return False


def collect_component_features(has_func, component_dir=None):
    """
    Collect component features based on RT-Thread configuration using extensible mapping table
    
    Args:
        has_func: Function to check if a configuration is enabled
        component_dir: Component directory to check dependencies (optional)
        
    Returns:
        list: List of features to enable
    """
    features = []
    
    # Iterate through all configured mappings
    for config_name, config_info in CONFIG_COMPONENT_FEATURE_MAP.items():
        # Check if this RT-Thread configuration is enabled
        if has_func(config_name) or has_func('RT_RUST_BUILD_ALL_EXAMPLES'):
            feature_name = config_info['feature']
            required_deps = config_info.get('dependencies', [])
            
            # If component_dir is provided, check dependencies
            if component_dir:
                if check_component_dependencies(component_dir, required_deps):
                    features.append(feature_name)
                    print(f"Enabling component feature '{feature_name}' for {config_name} in {os.path.basename(component_dir)}")
            else:
                # If no component_dir provided, enable for all (backward compatibility)
                features.append(feature_name)
                print(f"Enabling component feature '{feature_name}' for {config_name}")
    
    return features


def declared_component_features(component_dir):
    cargo_toml_path = os.path.join(component_dir, 'Cargo.toml')
    if not os.path.isfile(cargo_toml_path):
        raise ComponentBuildError(f"Component Cargo.toml not found: {cargo_toml_path}")

    toml = load_toml_module()
    try:
        with open(cargo_toml_path, 'r') as f:
            cargo_data = toml.load(f)
        return set(cargo_data.get('features', {}).keys())
    except Exception as e:
        raise ComponentBuildError(f"Failed to parse component features from {cargo_toml_path}: {e}") from e


def filter_declared_component_features(component_dir, features):
    declared_features = declared_component_features(component_dir)
    return [feature for feature in features if feature in declared_features]


def cargo_build_component_staticlib(rust_dir, target, features, debug, rustflags=None, build_root=None, cargo_extra_args=None):
    """
    Build a Rust component as a static library using Cargo.
    
    Args:
        rust_dir: Directory containing the Rust component
        target: Rust target architecture
        features: List of features to enable
        debug: Whether this is a debug build
        rustflags: Additional Rust compilation flags
        build_root: Build root directory
        
    Returns:
        str: Path to the built library file, or None if build failed
    """
    build_root = normalize_component_build_root(build_root, None)
    os.makedirs(build_root, exist_ok=True)

    env = os.environ.copy()
    if rustflags:
        prev = env.get("RUSTFLAGS", "").strip()
        env["RUSTFLAGS"] = (prev + " " + rustflags).strip() if prev else rustflags
    env["CARGO_TARGET_DIR"] = build_root

    cmd = [
        "cargo", "build", 
        "--target", target, 
        "--manifest-path", os.path.join(rust_dir, "Cargo.toml")
    ]
    
    if not debug:
        cmd.insert(2, "--release")
    if cargo_extra_args:
        cmd[2:2] = cargo_extra_args
    
    if features:
        cmd += ["--no-default-features", "--features", ",".join(features)]

    print("Building example component log (cargo)…")
    try:
        res = subprocess.run(cmd, cwd=rust_dir, env=env, capture_output=True, text=True)
    except FileNotFoundError:
        print("Error: cargo executable not found. Please install Rust/Cargo and ensure it is in PATH.")
        return None
    
    if res.returncode != 0:
        print(f"Warning: Example component build failed for {rust_dir}")
        print(f"Target: {target}")
        print(f"Command: {' '.join(cmd)}")
        print(f"Return code: {res.returncode}")
        if res.stdout:
            print(res.stdout)
        if res.stderr:
            print(res.stderr)
        return None

    mode = "debug" if debug else "release"
    
    # Try target-specific path first, then fallback to direct path
    artifact_name = get_component_staticlib_artifact_name(rust_dir)
    lib_path = os.path.join(build_root, target, mode, artifact_name)
    if os.path.isfile(lib_path) and os.path.getsize(lib_path) > 0:
        print("Example component log built successfully")
        return lib_path
    
    print("Warning: Rust component static library artifact not found, is not a file, or is empty")
    print(f"Expected: {lib_path}")
    return None


def build_example_component(cwd, has_func, rtconfig, build_root=None):
    """
    Build the example component.
    
    Args:
        cwd: Current working directory (component directory)
        has_func: Function to check if a configuration is enabled
        rtconfig: RT-Thread configuration module
        build_root: Optional build root directory
        
    Returns:
        tuple: (LIBS, LIBPATH, LINKFLAGS) for SCons
    """
    LIBS = []
    LIBPATH = []
    LINKFLAGS = []

    # Import build support functions
    import sys
    tools_dir = os.path.abspath(os.path.join(cwd, '..', '..', 'tools'))
    if tools_dir not in sys.path:
        sys.path.append(tools_dir)
    from build_support import (
        detect_rust_target,
        ensure_rust_target_installed,
        collect_features,
        make_rustflags,
        make_cargo_build_std_args,
    )
    
    target = detect_rust_target(has_func, rtconfig)
    if not target:
        raise ComponentBuildError(f'Could not detect Rust target for example component build in {cwd}')
    
    # Build mode and features
    debug = bool(has_func('RUST_DEBUG_BUILD'))
    features = collect_features(has_func)
    
    # Build the component registry
    registry_dir = os.path.join(cwd, 'component_registry')
    features += collect_component_features(has_func, registry_dir)
    features = filter_declared_component_features(registry_dir, features)
    
    rustflags = make_rustflags(rtconfig, target)
    cargo_extra_args = make_cargo_build_std_args(rtconfig, target)
    build_root = normalize_component_build_root(build_root, cwd)
    if not ensure_rust_target_installed(target):
        raise ComponentBuildError(f"Rust target '{target}' is not installed; example component build failed")
    
    rust_lib = cargo_build_component_staticlib(
        rust_dir=registry_dir, 
        target=target, 
        features=features, 
        debug=debug, 
        rustflags=rustflags,
        build_root=build_root,
        cargo_extra_args=cargo_extra_args
    )
    
    if rust_lib:
        lib_dir = os.path.dirname(rust_lib)
        # Derive the link name from the actual artifact so it always matches
        # the file that was built. Only fall back to re-parsing Cargo.toml when
        # the artifact name does not follow the lib<name>.a convention.
        link_lib_name = get_staticlib_link_name_from_artifact(rust_lib)
        if not link_lib_name:
            link_lib_name = get_component_staticlib_link_name(registry_dir)
        LIBS = [link_lib_name]
        LIBPATH = [lib_dir]
        platform = getattr(rtconfig, 'PLATFORM', None)
        if platform == 'armclang':
            if not (os.path.isfile(rust_lib) and os.path.getsize(rust_lib) > 0):
                raise ComponentBuildError(
                    f"ArmClang Rust component link requires a non-empty archive, but got: {rust_lib}"
                )
            anchors = get_component_export_symbols(features)
            LINKFLAGS = [f"--undefined={symbol}" for symbol in anchors]
            LINKFLAGS.append(quote_spaces(os.fspath(rust_lib)))
            LINKFLAGS = " " + " ".join(LINKFLAGS)
            LIBS = []
            LIBPATH = []
        else:
            LINKFLAGS = [
                quote_spaces(f"-L{os.fspath(lib_dir)}"),
                "-Wl,--whole-archive",
                f"-l{link_lib_name}",
                "-Wl,--no-whole-archive",
                "-Wl,--allow-multiple-definition",
            ]
            LINKFLAGS = " " + " ".join(LINKFLAGS)
        print('Example component registry library linked successfully')
    else:
        raise ComponentBuildError(f"Failed to build example component registry library in {registry_dir} for target {target}")
    
    return LIBS, LIBPATH, LINKFLAGS