2025-06-29 16:00:17 +08:00
< ? php
declare ( strict_types = 1 );
namespace SPC\toolchain ;
2025-07-01 14:01:48 +07:00
use SPC\exception\WrongUsageException ;
use SPC\store\pkg\Zig ;
use SPC\util\GlobalEnvManager ;
2025-06-29 16:00:17 +08:00
class ZigToolchain implements ToolchainInterface
{
2025-07-01 14:01:48 +07:00
public function initEnv () : void
{
2025-07-01 17:08:19 +07:00
// Set environment variables for zig toolchain
2025-07-01 14:02:10 +07:00
GlobalEnvManager :: putenv ( 'SPC_LINUX_DEFAULT_CC=zig-cc' );
GlobalEnvManager :: putenv ( 'SPC_LINUX_DEFAULT_CXX=zig-c++' );
GlobalEnvManager :: putenv ( 'SPC_LINUX_DEFAULT_AR=ar' );
GlobalEnvManager :: putenv ( 'SPC_LINUX_DEFAULT_LD=ld' );
2025-07-05 10:48:56 +08:00
2025-07-22 13:16:26 +08:00
// Generate additional object needed for zig toolchain
2025-07-05 10:48:56 +08:00
$paths = [ '/usr/lib/gcc' , '/usr/local/lib/gcc' ];
$objects = [ 'crtbeginS.o' , 'crtendS.o' ];
$found = [];
foreach ( $objects as $obj ) {
$located = null ;
foreach ( $paths as $base ) {
$output = shell_exec ( " find { $base } -name { $obj } 2>/dev/null | grep -v '/32/' | head -n 1 " );
$line = trim (( string ) $output );
if ( $line !== '' ) {
$located = $line ;
break ;
}
}
if ( $located ) {
$found [] = $located ;
}
}
2025-07-22 13:16:26 +08:00
GlobalEnvManager :: putenv ( 'SPC_EXTRA_RUNTIME_OBJECTS=' . implode ( ' ' , $found ));
$extra_libs = getenv ( 'SPC_EXTRA_LIBS' ) ? : '' ;
if ( ! str_contains ( $extra_libs , '-lunwind' )) {
// Add unwind library if not already present
$extra_libs = trim ( $extra_libs . ' -lunwind' );
GlobalEnvManager :: putenv ( " SPC_EXTRA_LIBS= { $extra_libs } " );
}
}
2025-07-05 10:48:56 +08:00
2025-07-22 13:16:26 +08:00
/**
* @ throws WrongUsageException
*/
public function afterInit () : void
{
if ( ! is_dir ( Zig :: getEnvironment ()[ 'PATH' ])) {
throw new WrongUsageException ( 'You are building with zig, but zig is not installed, please install zig first. (You can use `doctor` command to install it)' );
}
GlobalEnvManager :: addPathIfNotExists ( Zig :: getEnvironment ()[ 'PATH' ]);
2025-07-05 10:48:56 +08:00
}
2025-06-29 16:00:17 +08:00
}