Skip to content

Commit

Permalink
[native_toolchain_c] Format with tall style
Browse files Browse the repository at this point in the history
  • Loading branch information
dcharkes committed Feb 14, 2025
1 parent f478b31 commit 130f9c6
Show file tree
Hide file tree
Showing 47 changed files with 1,288 additions and 1,396 deletions.
5 changes: 1 addition & 4 deletions pkgs/native_toolchain_c/lib/src/cbuilder/build_mode.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ final class BuildMode {
static const release = BuildMode._('release');

/// All known build modes.
static const values = [
debug,
release,
];
static const values = [debug, release];

/// The name of this [BuildMode].
///
Expand Down
57 changes: 32 additions & 25 deletions pkgs/native_toolchain_c/lib/src/cbuilder/cbuilder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ class CBuilder extends CTool implements Builder {
super.optimizationLevel = OptimizationLevel.o3,
this.buildMode = BuildMode.release,
}) : super(
type: OutputType.executable,
assetName: null,
installName: null,
pic: pie,
linkModePreference: null,
);
type: OutputType.executable,
assetName: null,
installName: null,
pic: pie,
linkModePreference: null,
);

/// Runs the C Compiler with on this C build spec.
///
Expand All @@ -118,8 +118,10 @@ class CBuilder extends CTool implements Builder {
String? linkInPackage,
}) async {
if (!input.config.buildCodeAssets) {
logger?.info('buildAssetTypes did not contain "${CodeAsset.type}", '
'skipping CodeAsset $assetName build.');
logger?.info(
'buildAssetTypes did not contain "${CodeAsset.type}", '
'skipping CodeAsset $assetName build.',
);
return;
}
assert(
Expand All @@ -130,12 +132,15 @@ class CBuilder extends CTool implements Builder {
final outDir = input.outputDirectory;
final packageRoot = input.packageRoot;
await Directory.fromUri(outDir).create(recursive: true);
final linkMode =
getLinkMode(linkModePreference ?? input.config.code.linkModePreference);
final libUri = outDir
.resolve(input.config.code.targetOS.libraryFileName(name, linkMode));
final exeUri =
outDir.resolve(input.config.code.targetOS.executableFileName(name));
final linkMode = getLinkMode(
linkModePreference ?? input.config.code.linkModePreference,
);
final libUri = outDir.resolve(
input.config.code.targetOS.libraryFileName(name, linkMode),
);
final exeUri = outDir.resolve(
input.config.code.targetOS.executableFileName(name),
);
final sources = [
for (final source in this.sources)
packageRoot.resolveUri(Uri.file(source)),
Expand Down Expand Up @@ -167,9 +172,10 @@ class CBuilder extends CTool implements Builder {
type == OutputType.library && linkMode == DynamicLoadingBundled()
? libUri
: null,
staticLibrary: type == OutputType.library && linkMode == StaticLinking()
? libUri
: null,
staticLibrary:
type == OutputType.library && linkMode == StaticLinking()
? libUri
: null,
executable: type == OutputType.executable ? exeUri : null,
// ignore: invalid_use_of_visible_for_testing_member
installName: installName,
Expand Down Expand Up @@ -205,14 +211,15 @@ class CBuilder extends CTool implements Builder {
}
// ignore: deprecated_member_use
if (!input.config.dryRun) {
final includeFiles = await Stream.fromIterable(includes)
.asyncExpand(
(include) => Directory(include.toFilePath())
.list(recursive: true)
.where((entry) => entry is File)
.map((file) => file.uri),
)
.toList();
final includeFiles =
await Stream.fromIterable(includes)
.asyncExpand(
(include) => Directory(include.toFilePath())
.list(recursive: true)
.where((entry) => entry is File)
.map((file) => file.uri),
)
.toList();

output.addDependencies({
// Note: We use a Set here to deduplicate the dependencies.
Expand Down
51 changes: 29 additions & 22 deletions pkgs/native_toolchain_c/lib/src/cbuilder/clinker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,20 @@ class CLinker extends CTool implements Linker {
required Logger? logger,
}) async {
if (OS.current != OS.linux || input.config.code.targetOS != OS.linux) {
throw UnsupportedError('Currently, only linux is supported for this '
'feature. See also https://github.com/dart-lang/native/issues/1376');
throw UnsupportedError(
'Currently, only linux is supported for this '
'feature. See also https://github.com/dart-lang/native/issues/1376',
);
}
final outDir = input.outputDirectory;
final packageRoot = input.packageRoot;
await Directory.fromUri(outDir).create(recursive: true);
final linkMode =
getLinkMode(linkModePreference ?? input.config.code.linkModePreference);
final libUri = outDir
.resolve(input.config.code.targetOS.libraryFileName(name, linkMode));
final linkMode = getLinkMode(
linkModePreference ?? input.config.code.linkModePreference,
);
final libUri = outDir.resolve(
input.config.code.targetOS.libraryFileName(name, linkMode),
);
final sources = [
for (final source in this.sources)
packageRoot.resolveUri(Uri.file(source)),
Expand Down Expand Up @@ -99,23 +103,26 @@ class CLinker extends CTool implements Linker {
await task.run();

if (assetName != null) {
output.assets.code.add(CodeAsset(
package: input.packageName,
name: assetName!,
file: libUri,
linkMode: linkMode,
os: input.config.code.targetOS,
architecture: input.config.code.targetArchitecture,
));
output.assets.code.add(
CodeAsset(
package: input.packageName,
name: assetName!,
file: libUri,
linkMode: linkMode,
os: input.config.code.targetOS,
architecture: input.config.code.targetArchitecture,
),
);
}
final includeFiles = await Stream.fromIterable(includes)
.asyncExpand(
(include) => Directory(include.toFilePath())
.list(recursive: true)
.where((entry) => entry is File)
.map((file) => file.uri),
)
.toList();
final includeFiles =
await Stream.fromIterable(includes)
.asyncExpand(
(include) => Directory(include.toFilePath())
.list(recursive: true)
.where((entry) => entry is File)
.map((file) => file.uri),
)
.toList();

output.addDependencies({
// Note: We use a Set here to deduplicate the dependencies.
Expand Down
41 changes: 25 additions & 16 deletions pkgs/native_toolchain_c/lib/src/cbuilder/compiler_resolver.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ class CompilerResolver {
required this.logger,
OS? hostOS, // Only visible for testing.
Architecture? hostArchitecture, // Only visible for testing.
}) : hostOS = hostOS ?? OS.current,
hostArchitecture = hostArchitecture ?? Architecture.current;
}) : hostOS = hostOS ?? OS.current,
hostArchitecture = hostArchitecture ?? Architecture.current;

Future<ToolInstance> resolveCompiler() async {
// First, check if the launcher provided a direct path to the compiler.
Expand Down Expand Up @@ -103,20 +103,24 @@ class CompilerResolver {
final inputCcUri = codeConfig.cCompiler?.compiler;
if (inputCcUri != null) {
assert(await File.fromUri(inputCcUri).exists());
logger?.finer('Using compiler ${inputCcUri.toFilePath()} '
'from BuildInput.cCompiler.cc.');
return (await CompilerRecognizer(inputCcUri).resolve(logger: logger))
.first;
logger?.finer(
'Using compiler ${inputCcUri.toFilePath()} '
'from BuildInput.cCompiler.cc.',
);
return (await CompilerRecognizer(
inputCcUri,
).resolve(logger: logger)).first;
}
logger?.finer('No compiler set in BuildInput.cCompiler.cc.');
return null;
}

Future<ToolInstance?> _tryLoadToolFromNativeToolchain(Tool tool) async {
final resolved = (await tool.defaultResolver!.resolve(logger: logger))
.where((i) => i.tool == tool)
.toList()
..sort();
final resolved =
(await tool.defaultResolver!.resolve(
logger: logger,
)).where((i) => i.tool == tool).toList()
..sort();
return resolved.isEmpty ? null : resolved.first;
}

Expand Down Expand Up @@ -188,10 +192,13 @@ class CompilerResolver {
final inputArUri = codeConfig.cCompiler?.archiver;
if (inputArUri != null) {
assert(await File.fromUri(inputArUri).exists());
logger?.finer('Using archiver ${inputArUri.toFilePath()} '
'from BuildInput.cCompiler.ar.');
return (await ArchiverRecognizer(inputArUri).resolve(logger: logger))
.first;
logger?.finer(
'Using archiver ${inputArUri.toFilePath()} '
'from BuildInput.cCompiler.ar.',
);
return (await ArchiverRecognizer(
inputArUri,
).resolve(logger: logger)).first;
}
logger?.finer('No archiver set in BuildInput.cCompiler.ar.');
return null;
Expand Down Expand Up @@ -262,8 +269,10 @@ class CompilerResolver {
final inputLdUri = codeConfig.cCompiler?.linker;
if (inputLdUri != null) {
assert(await File.fromUri(inputLdUri).exists());
logger?.finer('Using linker ${inputLdUri.toFilePath()} '
'from cCompiler.ld.');
logger?.finer(
'Using linker ${inputLdUri.toFilePath()} '
'from cCompiler.ld.',
);
final tools = await LinkerRecognizer(inputLdUri).resolve(logger: logger);
return tools.first;
}
Expand Down
6 changes: 1 addition & 5 deletions pkgs/native_toolchain_c/lib/src/cbuilder/language.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,7 @@ class Language {
static const Language objectiveC = Language._('objective c');

/// Known values for [Language].
static const List<Language> values = [
c,
cpp,
objectiveC,
];
static const List<Language> values = [c, cpp, objectiveC];

@override
String toString() => name;
Expand Down
57 changes: 27 additions & 30 deletions pkgs/native_toolchain_c/lib/src/cbuilder/linker_options.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,25 @@ class LinkerOptions {
List<String>? flags,
bool? gcSections,
this.linkerScript,
}) : _linkerFlags = flags ?? [],
gcSections = gcSections ?? true,
_wholeArchiveSandwich = false;
}) : _linkerFlags = flags ?? [],
gcSections = gcSections ?? true,
_wholeArchiveSandwich = false;

/// Create linking options to tree-shake symbols from the input files.
///
/// The [symbols] specify the symbols which should be kept.
LinkerOptions.treeshake({
Iterable<String>? flags,
required Iterable<String>? symbols,
}) : _linkerFlags = <String>[
...flags ?? [],
'--strip-debug',
if (symbols != null) ...symbols.expand((e) => ['-u', e]),
].toList(),
gcSections = true,
_wholeArchiveSandwich = symbols == null,
linkerScript = _createLinkerScript(symbols);
}) : _linkerFlags =
<String>[
...flags ?? [],
'--strip-debug',
if (symbols != null) ...symbols.expand((e) => ['-u', e]),
].toList(),
gcSections = true,
_wholeArchiveSandwich = symbols == null,
linkerScript = _createLinkerScript(symbols);

Iterable<String> _toLinkerSyntax(Tool linker, List<String> flagList) {
if (linker.isClangLike) {
Expand Down Expand Up @@ -92,16 +93,14 @@ extension LinkerOptionsExt on LinkerOptions {
/// trick, which includes all symbols when linking object files.
///
/// Throws if the [linker] is not supported.
Iterable<String> preSourcesFlags(
Tool linker,
Iterable<String> sourceFiles,
) =>
Iterable<String> preSourcesFlags(Tool linker, Iterable<String> sourceFiles) =>
_toLinkerSyntax(
linker,
sourceFiles.any((source) => source.endsWith('.a')) ||
_wholeArchiveSandwich
? ['--whole-archive']
: []);
linker,
sourceFiles.any((source) => source.endsWith('.a')) ||
_wholeArchiveSandwich
? ['--whole-archive']
: [],
);

/// The flags for the specified [linker], which are inserted _after_ the
/// sources.
Expand All @@ -113,14 +112,12 @@ extension LinkerOptionsExt on LinkerOptions {
Iterable<String> postSourcesFlags(
Tool linker,
Iterable<String> sourceFiles,
) =>
_toLinkerSyntax(linker, [
..._linkerFlags,
if (gcSections) '--gc-sections',
if (linkerScript != null)
'--version-script=${linkerScript!.toFilePath()}',
if (sourceFiles.any((source) => source.endsWith('.a')) ||
_wholeArchiveSandwich)
'--no-whole-archive',
]);
) => _toLinkerSyntax(linker, [
..._linkerFlags,
if (gcSections) '--gc-sections',
if (linkerScript != null) '--version-script=${linkerScript!.toFilePath()}',
if (sourceFiles.any((source) => source.endsWith('.a')) ||
_wholeArchiveSandwich)
'--no-whole-archive',
]);
}
6 changes: 4 additions & 2 deletions pkgs/native_toolchain_c/lib/src/cbuilder/linkmode.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ LinkMode getLinkMode(LinkModePreference preference) {
preference == LinkModePreference.preferDynamic) {
return DynamicLoadingBundled();
}
assert(preference == LinkModePreference.static ||
preference == LinkModePreference.preferStatic);
assert(
preference == LinkModePreference.static ||
preference == LinkModePreference.preferStatic,
);
return StaticLinking();
}
11 changes: 6 additions & 5 deletions pkgs/native_toolchain_c/lib/src/cbuilder/optimization_level.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ final class OptimizationLevel {
static const OptimizationLevel oS = OptimizationLevel._('Os');

/// Unspecified optimization level; the default or compiler-chosen level.
static const OptimizationLevel unspecified =
OptimizationLevel._('unspecified');
static const OptimizationLevel unspecified = OptimizationLevel._(
'unspecified',
);

/// Returns the string representation of the optimization level.
@override
Expand All @@ -41,9 +42,9 @@ final class OptimizationLevel {
String clangFlag() => '-$_level';

String msvcFlag() => switch (this) {
o3 => o2.msvcFlag(),
_ => '/$_level',
};
o3 => o2.msvcFlag(),
_ => '/$_level',
};

static const List<OptimizationLevel> values = [
o0,
Expand Down
5 changes: 1 addition & 4 deletions pkgs/native_toolchain_c/lib/src/cbuilder/output_type.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,4 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

enum OutputType {
executable,
library,
}
enum OutputType { executable, library }
Loading

0 comments on commit 130f9c6

Please sign in to comment.