diff --git a/pkgs/ffigen/CHANGELOG.md b/pkgs/ffigen/CHANGELOG.md index ef719cbd6d..d1b683cbc7 100644 --- a/pkgs/ffigen/CHANGELOG.md +++ b/pkgs/ffigen/CHANGELOG.md @@ -1,6 +1,9 @@ ## 22.0.0-wip - __Breaking change__: Major overhaul of Dart config API: + - Consolidate `imported` fields and `importedTypesByUsr` into + `FfiGenerator.importType`, switching it to a callback pattern + - Deleted empty `Integers` class - Rename `Headers` to `Input` - Remove `libraryImports`, which was dead code - Remove `useSupportedTypedefs`, treating it as always true diff --git a/pkgs/ffigen/lib/ffigen.dart b/pkgs/ffigen/lib/ffigen.dart index aad3ad8098..da396ee043 100644 --- a/pkgs/ffigen/lib/ffigen.dart +++ b/pkgs/ffigen/lib/ffigen.dart @@ -32,7 +32,6 @@ export 'src/config_provider.dart' Functions, Globals, Input, - Integers, Interfaces, Macros, NativeExternalBindings, diff --git a/pkgs/ffigen/lib/src/code_generator/objc_built_in_functions.dart b/pkgs/ffigen/lib/src/code_generator/objc_built_in_functions.dart index 58ffc1791c..0717574dca 100644 --- a/pkgs/ffigen/lib/src/code_generator/objc_built_in_functions.dart +++ b/pkgs/ffigen/lib/src/code_generator/objc_built_in_functions.dart @@ -237,7 +237,7 @@ class ObjCBuiltInFunctions { // A unique (but not human readable) ID for the generated library based on // a hash of parts of the config. - static String _libraryIdFromConfigHash(Config config) => fnvHash32( + static String _libraryIdFromConfigHash(FfiGenerator config) => fnvHash32( [ ...config.input.entryPoints, config.output.dartFile, diff --git a/pkgs/ffigen/lib/src/config_provider/config.dart b/pkgs/ffigen/lib/src/config_provider/config.dart index c20340786c..7559ca9ae3 100644 --- a/pkgs/ffigen/lib/src/config_provider/config.dart +++ b/pkgs/ffigen/lib/src/config_provider/config.dart @@ -27,9 +27,6 @@ final class FfiGenerator { /// Configuration for globals. final Globals globals; - /// Configuration for integer types. - final Integers integers; - /// Configuration for macro constants. final Macros macros; @@ -61,16 +58,11 @@ final class FfiGenerator { /// The configuration for outputting bindings. final Output output; - /// Types imported from other Dart files, specified via the - /// unique-resource-identifer used in Clang. - /// - /// Applies to all kinds of definitions. - // TODO(https://github.com/dart-lang/native/issues/2596): Remove this. - @Deprecated( - 'Will be folded into imported fields of the various declarations. See ' - 'https://github.com/dart-lang/native/issues/2596.', - ) - final Map importedTypesByUsr; + /// Returns an [ImportedType] if the given [Declaration] should be imported + /// from another Dart library, or `null` otherwise. + final ImportedType? Function(Declaration declaration) importType; + + static ImportedType? _defaultImportType(Declaration declaration) => null; /// Path to the clang library. /// @@ -83,7 +75,6 @@ final class FfiGenerator { this.enums = Enums.excludeAll, this.functions = Functions.excludeAll, this.globals = Globals.excludeAll, - this.integers = const Integers(), this.macros = Macros.excludeAll, this.structs = Structs.excludeAll, this.cpp, @@ -92,11 +83,7 @@ final class FfiGenerator { this.unnamedEnums = UnnamedEnums.excludeAll, this.objectiveC, required this.output, - @Deprecated( - 'Will be folded into imported fields of the various declarations. See ' - 'https://github.com/dart-lang/native/issues/2596.', - ) - this.importedTypesByUsr = const {}, + this.importType = _defaultImportType, @Deprecated('Only visible for YamlConfig plumbing.') this.libclangDylib, }); @@ -378,25 +365,6 @@ final class Globals extends Declarations { Globals(include: Declarations.includeSet(names)); } -/// Configuration for integer types. -final class Integers { - /// Integer types imported from other Dart files. - // TODO(https://github.com/dart-lang/native/issues/2595): Change type. - @Deprecated( - 'This field will change type. See ' - 'https://github.com/dart-lang/native/issues/2595.', - ) - final List imported; - - const Integers({ - @Deprecated( - 'This field will change type. See ' - 'https://github.com/dart-lang/native/issues/2595.', - ) - this.imported = const [], - }); -} - /// Configuration for macros. final class Macros extends Declarations { const Macros({super.rename, super.include}); @@ -414,14 +382,6 @@ final class Structs extends Declarations { /// Whether structs that are dependencies should be included. final CompoundDependencies dependencies; - /// Structs imported from other Dart files. - // TODO(https://github.com/dart-lang/native/issues/2595): Change type. - @Deprecated( - 'This field will change type. See ' - 'https://github.com/dart-lang/native/issues/2595.', - ) - final List imported; - /// Whether, and how, to override struct packing for the given struct. final PackingValue? Function(Declaration declaration) packingOverride; @@ -432,11 +392,6 @@ final class Structs extends Declarations { super.rename, super.renameMember, this.dependencies = CompoundDependencies.opaque, - @Deprecated( - 'This field will change type. See ' - 'https://github.com/dart-lang/native/issues/2595.', - ) - this.imported = const [], this.packingOverride = _packingOverrideDefault, }); @@ -450,24 +405,17 @@ final class Structs extends Declarations { /// Configuration for typedefs. final class Typedefs extends Declarations { - /// Typedefs imported from other Dart files. - @Deprecated( - 'This field will change type. See ' - 'https://github.com/dart-lang/native/issues/2595.', - ) - final List imported; - /// If enabled, unused typedefs will also be generated. final bool includeUnused; + /// If enabled, supported typedefs (such as size_t, uint8_t, etc.) will be + /// mapped to their supported types. + final bool useSupportedTypedefs; + const Typedefs({ super.rename, super.include, - @Deprecated( - 'This field will change type. See ' - 'https://github.com/dart-lang/native/issues/2595.', - ) - this.imported = const [], + this.useSupportedTypedefs = true, this.includeUnused = false, }); @@ -503,23 +451,11 @@ final class Unions extends Declarations { /// Whether unions that are dependencies should be included. final CompoundDependencies dependencies; - /// Unions imported from other Dart files. - @Deprecated( - 'This field will change type. See ' - 'https://github.com/dart-lang/native/issues/2595.', - ) - final List imported; - const Unions({ super.include, super.rename, super.renameMember, this.dependencies = CompoundDependencies.opaque, - @Deprecated( - 'This field will change type. See ' - 'https://github.com/dart-lang/native/issues/2595.', - ) - this.imported = const [], }); static const excludeAll = Unions(include: Declarations.excludeAll); @@ -744,43 +680,3 @@ final class DynamicLibraryBindings implements BindingStyle { this.wrapperDocComment, }); } - -extension type Config(FfiGenerator ffiGen) implements FfiGenerator { - // ignore: deprecated_member_use_from_same_package - Map get importedTypesByUsr => ffiGen.importedTypesByUsr; - - // Override declarative user spec with what FFIgen internals expect. - Map get typedefTypeMappings => - Map.fromEntries( - // ignore: deprecated_member_use_from_same_package - ffiGen.typedefs.imported.map( - (import) => MapEntry(import.nativeType, import), - ), - ); - - Map get structTypeMappings => - Map.fromEntries( - // ignore: deprecated_member_use_from_same_package - ffiGen.structs.imported.map( - (import) => MapEntry(import.nativeType, import), - ), - ); - - // Override declarative user spec with what FFIgen internals expect. - Map get unionTypeMappings => - Map.fromEntries( - // ignore: deprecated_member_use_from_same_package - ffiGen.unions.imported.map( - (import) => MapEntry(import.nativeType, import), - ), - ); - - // Override declarative user spec with what FFIgen internals expect. - Map get importedIntegers => - Map.fromEntries( - // ignore: deprecated_member_use_from_same_package - ffiGen.integers.imported.map( - (import) => MapEntry(import.nativeType, import), - ), - ); -} diff --git a/pkgs/ffigen/lib/src/config_provider/yaml_config.dart b/pkgs/ffigen/lib/src/config_provider/yaml_config.dart index 6cf2f82e95..5a63d0edcb 100644 --- a/pkgs/ffigen/lib/src/config_provider/yaml_config.dart +++ b/pkgs/ffigen/lib/src/config_provider/yaml_config.dart @@ -117,6 +117,11 @@ final class YamlConfig { bool get includeUnusedTypedefs => _includeUnusedTypedefs; late bool _includeUnusedTypedefs; + /// If enabled, supported typedefs (such as size_t, uint8_t, etc.) will be + /// mapped to their supported types. + bool get useSupportedTypedefs => _useSupportedTypedefs; + late bool _useSupportedTypedefs; + /// If enabled, Objective C interfaces that are not explicitly included by the /// [YamlDeclarationFilters], but are transitively included by other bindings, /// will be code-genned as if they were included. If disabled, these @@ -832,6 +837,8 @@ final class YamlConfig { HeterogeneousMapEntry( key: strings.useSupportedTypedefs, valueConfigSpec: BoolConfigSpec(), + defaultValue: (node) => true, + resultOrDefault: (node) => _useSupportedTypedefs = node.value as bool, ), HeterogeneousMapEntry( key: strings.comments, @@ -1220,119 +1227,127 @@ final class YamlConfig { ); } - FfiGenerator configAdapter() => FfiGenerator( - input: Input( - compilerOptions: compilerOpts, - entryPoints: entryPoints, - include: shouldIncludeHeader, - ignoreSourceErrors: ignoreSourceErrors, - ), - output: Output( - dartFile: output, - objectiveCFile: outputObjC, - symbolFile: symbolFile, - commentType: commentType, - preamble: preamble, - format: formatOutput, - style: ffiNativeConfig.enabled - ? NativeExternalBindings(assetId: ffiNativeConfig.assetId) - : DynamicLibraryBindings( - wrapperName: wrapperName, - wrapperDocComment: wrapperDocComment, - ), - ), - functions: Functions( - include: functionDecl.shouldInclude, - includeSymbolAddress: functionDecl.shouldIncludeSymbolAddress, - rename: functionDecl.rename, - renameMember: functionDecl.renameMember, - varArgs: varArgFunctions, - includeTypedef: shouldExposeFunctionTypedef, - isLeaf: isLeafFunction, - ), - structs: Structs( - include: _structDecl.shouldInclude, - rename: _structDecl.rename, - renameMember: _structDecl.renameMember, - dependencies: _structDependencies, - packingOverride: (decl) => - _structPackingOverride.getOverridenPackValue(decl.originalName), - // ignore: deprecated_member_use_from_same_package - imported: structTypeMappings.values.toList(), - ), - enums: Enums( - include: _enumClassDecl.shouldInclude, - rename: _enumClassDecl.rename, - renameMember: _enumClassDecl.renameMember, - silenceWarning: silenceEnumWarning, - style: (e, suggestedStyle) { - if (suggestedStyle != null) return suggestedStyle; - return switch (enumShouldBeInt(e)) { - true => EnumStyle.intConstants, - false => EnumStyle.dartEnum, - }; - }, - ), - unions: Unions( - include: _unionDecl.shouldInclude, - rename: _unionDecl.rename, - renameMember: _unionDecl.renameMember, - dependencies: _unionDependencies, - // ignore: deprecated_member_use_from_same_package - imported: unionTypeMappings.values.toList(), - ), - unnamedEnums: UnnamedEnums( - include: _unnamedEnumConstants.shouldInclude, - rename: _unnamedEnumConstants.rename, - ), - globals: Globals( - include: globals.shouldInclude, - includeSymbolAddress: globals.shouldIncludeSymbolAddress, - rename: globals.rename, - ), - macros: Macros(include: macroDecl.shouldInclude, rename: macroDecl.rename), - typedefs: Typedefs( - include: typedefs.shouldInclude, - rename: typedefs.rename, - includeUnused: includeUnusedTypedefs, + FfiGenerator configAdapter() { + ImportedType? importType(Declaration decl) { + if (decl.usr.isNotEmpty) { + final importedByUsr = usrTypeMappings[decl.usr]; + if (importedByUsr != null) return importedByUsr; + } + return typedefTypeMappings[decl.originalName] ?? + structTypeMappings[decl.originalName] ?? + unionTypeMappings[decl.originalName] ?? + nativeTypeMappings[decl.originalName]; + } + + return FfiGenerator( + input: Input( + compilerOptions: compilerOpts, + entryPoints: entryPoints, + include: shouldIncludeHeader, + ignoreSourceErrors: ignoreSourceErrors, + ), + output: Output( + dartFile: output, + objectiveCFile: outputObjC, + symbolFile: symbolFile, + commentType: commentType, + preamble: preamble, + format: formatOutput, + style: ffiNativeConfig.enabled + ? NativeExternalBindings(assetId: ffiNativeConfig.assetId) + : DynamicLibraryBindings( + wrapperName: wrapperName, + wrapperDocComment: wrapperDocComment, + ), + ), + functions: Functions( + include: functionDecl.shouldInclude, + includeSymbolAddress: functionDecl.shouldIncludeSymbolAddress, + rename: functionDecl.rename, + renameMember: functionDecl.renameMember, + varArgs: varArgFunctions, + includeTypedef: shouldExposeFunctionTypedef, + isLeaf: isLeafFunction, + ), + structs: Structs( + include: _structDecl.shouldInclude, + rename: _structDecl.rename, + renameMember: _structDecl.renameMember, + dependencies: _structDependencies, + packingOverride: (decl) => + _structPackingOverride.getOverridenPackValue(decl.originalName), + ), + enums: Enums( + include: _enumClassDecl.shouldInclude, + rename: _enumClassDecl.rename, + renameMember: _enumClassDecl.renameMember, + silenceWarning: silenceEnumWarning, + style: (e, suggestedStyle) { + if (suggestedStyle != null) return suggestedStyle; + return switch (enumShouldBeInt(e)) { + true => EnumStyle.intConstants, + false => EnumStyle.dartEnum, + }; + }, + ), + unions: Unions( + include: _unionDecl.shouldInclude, + rename: _unionDecl.rename, + renameMember: _unionDecl.renameMember, + dependencies: _unionDependencies, + ), + unnamedEnums: UnnamedEnums( + include: _unnamedEnumConstants.shouldInclude, + rename: _unnamedEnumConstants.rename, + ), + globals: Globals( + include: globals.shouldInclude, + includeSymbolAddress: globals.shouldIncludeSymbolAddress, + rename: globals.rename, + ), + macros: Macros( + include: macroDecl.shouldInclude, + rename: macroDecl.rename, + ), + typedefs: Typedefs( + include: typedefs.shouldInclude, + rename: typedefs.rename, + useSupportedTypedefs: useSupportedTypedefs, + includeUnused: includeUnusedTypedefs, + ), + importType: importType, + objectiveC: language == Language.objc + ? ObjectiveC( + interfaces: Interfaces( + include: objcInterfaces.shouldInclude, + includeMember: objcInterfaces.shouldIncludeMember, + rename: objcInterfaces.rename, + renameMember: objcInterfaces.renameMember, + includeTransitive: includeTransitiveObjCInterfaces, + module: interfaceModule, + ), + protocols: Protocols( + include: objcProtocols.shouldInclude, + includeMember: objcProtocols.shouldIncludeMember, + rename: objcProtocols.rename, + renameMember: objcProtocols.renameMember, + includeTransitive: includeTransitiveObjCProtocols, + module: protocolModule, + ), + categories: Categories( + include: objcCategories.shouldInclude, + includeMember: objcCategories.shouldIncludeMember, + rename: objcCategories.rename, + renameMember: objcCategories.renameMember, + includeTransitive: includeTransitiveObjCCategories, + ), + externalVersions: externalVersions, + // ignore: deprecated_member_use_from_same_package + generateForPackageObjectiveC: generateForPackageObjectiveC, + ) + : null, // ignore: deprecated_member_use_from_same_package - imported: typedefTypeMappings.values.toList(), - ), - objectiveC: language == Language.objc - ? ObjectiveC( - interfaces: Interfaces( - include: objcInterfaces.shouldInclude, - includeMember: objcInterfaces.shouldIncludeMember, - rename: objcInterfaces.rename, - renameMember: objcInterfaces.renameMember, - includeTransitive: includeTransitiveObjCInterfaces, - module: interfaceModule, - ), - protocols: Protocols( - include: objcProtocols.shouldInclude, - includeMember: objcProtocols.shouldIncludeMember, - rename: objcProtocols.rename, - renameMember: objcProtocols.renameMember, - includeTransitive: includeTransitiveObjCProtocols, - module: protocolModule, - ), - categories: Categories( - include: objcCategories.shouldInclude, - includeMember: objcCategories.shouldIncludeMember, - rename: objcCategories.rename, - renameMember: objcCategories.renameMember, - includeTransitive: includeTransitiveObjCCategories, - ), - externalVersions: externalVersions, - // ignore: deprecated_member_use_from_same_package - generateForPackageObjectiveC: generateForPackageObjectiveC, - ) - : null, - // ignore: deprecated_member_use_from_same_package - importedTypesByUsr: usrTypeMappings, - // ignore: deprecated_member_use_from_same_package - integers: Integers(imported: nativeTypeMappings.values.toList()), - // ignore: deprecated_member_use_from_same_package - libclangDylib: libclangDylib, - ); + libclangDylib: libclangDylib, + ); + } } diff --git a/pkgs/ffigen/lib/src/context.dart b/pkgs/ffigen/lib/src/context.dart index 93b9bbb043..b67b899891 100644 --- a/pkgs/ffigen/lib/src/context.dart +++ b/pkgs/ffigen/lib/src/context.dart @@ -18,7 +18,7 @@ import 'header_parser/utils.dart'; /// Wrapper around various FFIgen-wide variables. class Context { final Logger logger; - final Config config; + final FfiGenerator config; final CursorIndex cursorIndex; final bindingsIndex = BindingsIndex(); final savedMacros = {}; @@ -34,25 +34,20 @@ class Context { late final ExtraSymbols extraSymbols; final String tmpDir; - Context( - this.logger, - FfiGenerator generator, { - Uri? libclangDylib, - String? tmpDir, - }) : config = Config(generator), - cursorIndex = CursorIndex(logger), - tmpDir = - tmpDir ?? - Directory.systemTemp.createTempSync('ffigen temp dir ').path { + Context(this.logger, this.config, {Uri? libclangDylib, String? tmpDir}) + : cursorIndex = CursorIndex(logger), + tmpDir = + tmpDir ?? + Directory.systemTemp.createTempSync('ffigen temp dir ').path { objCBuiltInFunctions = ObjCBuiltInFunctions( this, // ignore: deprecated_member_use_from_same_package - generator.objectiveC?.generateForPackageObjectiveC ?? false, + config.objectiveC?.generateForPackageObjectiveC ?? false, ); final libclangDylibPath = // ignore: deprecated_member_use_from_same_package - generator.libclangDylib?.toFilePath() ?? + config.libclangDylib?.toFilePath() ?? libclangDylib?.toFilePath() ?? findDylibAtDefaultLocations(logger); diff --git a/pkgs/ffigen/lib/src/ffigen.dart b/pkgs/ffigen/lib/src/ffigen.dart index 3ddd2a0a7c..ea881bc646 100644 --- a/pkgs/ffigen/lib/src/ffigen.dart +++ b/pkgs/ffigen/lib/src/ffigen.dart @@ -7,7 +7,7 @@ import 'dart:io'; import 'package:cli_util/cli_logging.dart' show Ansi; import 'package:logging/logging.dart'; -import 'config_provider.dart' show Config, FfiGenerator; +import 'config_provider.dart' show FfiGenerator; import 'context.dart'; import 'header_parser.dart' show parse; import 'logger.dart'; @@ -21,20 +21,19 @@ extension FfiGenGenerator on FfiGenerator { /// logger that streams [Level.WARNING] to stdout and higher levels to stderr. void generate({Logger? logger, Uri? libclangDylib}) { logger ??= createDefaultLogger(); - final config = Config(this); - final context = Context(logger, config, libclangDylib: libclangDylib); + final context = Context(logger, this, libclangDylib: libclangDylib); // Parse the bindings according to config object provided. final library = parse(context); // Generate files for the parsed bindings. - final gen = File(config.output.dartFile.toFilePath()); - library.generateFile(gen, format: config.ffiGen.output.format); + final gen = File(output.dartFile.toFilePath()); + library.generateFile(gen, format: output.format); logger.info( _successPen('Finished, Bindings generated in ${gen.absolute.path}'), ); - final objCGen = File(config.output.objCFile.toFilePath()); + final objCGen = File(output.objCFile.toFilePath()); if (library.generateObjCFile(objCGen)) { logger.info( _successPen( @@ -44,7 +43,7 @@ extension FfiGenGenerator on FfiGenerator { ); } - final cppGen = File(config.output.cppBindingsFile.toFilePath()); + final cppGen = File(output.cppBindingsFile.toFilePath()); if (library.generateCppFile(cppGen)) { logger.info( _successPen( @@ -53,12 +52,12 @@ extension FfiGenGenerator on FfiGenerator { ); } - final recordUseMappingFile = config.output.recordUseMapping; + final recordUseMappingFile = output.recordUseMapping; if (recordUseMappingFile != null) { final recordUseMappingGen = File(recordUseMappingFile.toFilePath()); if (library.generateRecordUseMappingFile( recordUseMappingGen, - format: config.output.format, + format: output.format, )) { logger.info( _successPen( @@ -69,7 +68,7 @@ extension FfiGenGenerator on FfiGenerator { } } - final symbolFile = config.output.symbolFile; + final symbolFile = output.symbolFile; if (symbolFile != null) { final symbolFileGen = File(symbolFile.output.toFilePath()); library.generateSymbolOutputFile( diff --git a/pkgs/ffigen/lib/src/header_parser/parser.dart b/pkgs/ffigen/lib/src/header_parser/parser.dart index 985377976d..b4c5b60aac 100644 --- a/pkgs/ffigen/lib/src/header_parser/parser.dart +++ b/pkgs/ffigen/lib/src/header_parser/parser.dart @@ -176,7 +176,7 @@ List transformBindings(List rawBindings, Context context) { visit(context, CopyMethodsFromSuperTypesVisitation(), allBindings); visit(context, FixOverriddenMethodsVisitation(context), allBindings); - final applyConfigFiltersVisitation = ApplyConfigFiltersVisitation(config); + final applyConfigFiltersVisitation = ApplyConfigFiltersVisitation(context); visit(context, applyConfigFiltersVisitation, allBindings); final directlyIncluded = applyConfigFiltersVisitation.directlyIncluded; final included = directlyIncluded.union( diff --git a/pkgs/ffigen/lib/src/header_parser/type_extractor/extractor.dart b/pkgs/ffigen/lib/src/header_parser/type_extractor/extractor.dart index e4906e76f3..13cc157a00 100644 --- a/pkgs/ffigen/lib/src/header_parser/type_extractor/extractor.dart +++ b/pkgs/ffigen/lib/src/header_parser/type_extractor/extractor.dart @@ -6,6 +6,7 @@ library; import '../../code_generator.dart'; +import '../../config_provider/config_types.dart'; import '../../context.dart'; import '../../strings.dart' as strings; import '../clang_bindings/clang_bindings.dart' as clang_types; @@ -149,10 +150,11 @@ Type getCodeGenType( if (typeSpellKey.startsWith('const ')) { typeSpellKey = typeSpellKey.replaceFirst('const ', ''); } - if (context.config.importedIntegers.containsKey(typeSpellKey)) { - context.logger.fine(' Type $typeSpellKey mapped from type-map.'); - return context.config.importedIntegers[typeSpellKey]!; - } else if (cxTypeKindToImportedTypes.containsKey(typeSpellKey)) { + final imported = context.config.importType( + Declaration(usr: '', originalName: typeSpellKey), + ); + if (imported != null) return imported; + if (cxTypeKindToImportedTypes.containsKey(typeSpellKey)) { return cxTypeKindToImportedTypes[typeSpellKey]!; } else { context.logger.fine( @@ -172,10 +174,10 @@ Type? _createTypeFromCursor( final logger = context.logger; final config = context.config; final usr = cursor.usr(); - if (config.importedTypesByUsr.containsKey(usr)) { - logger.fine(' Type $usr mapped from usr'); - return config.importedTypesByUsr[usr]!; - } + final imported = context.config.importType( + Declaration(usr: usr, originalName: cursor.spelling()), + ); + if (imported != null) return imported; switch (cxtype.kind) { case clang_types.CXTypeKind.CXType_Typedef: final spelling = clang.clang_getTypedefName(cxtype).toStringAndDispose(); @@ -185,17 +187,19 @@ Type? _createTypeFromCursor( // those two types are ABI compatible, so just return bool regardless. return BooleanType(); } - if (config.typedefTypeMappings.containsKey(spelling)) { - logger.fine(' Type $spelling mapped from type-map'); - return config.typedefTypeMappings[spelling]!; - } - // Get name from supported typedef name. - if (suportedTypedefToSuportedNativeType.containsKey(spelling)) { - logger.fine(' Type Mapped from supported typedef'); - return NativeType(suportedTypedefToSuportedNativeType[spelling]!); - } else if (supportedTypedefToImportedType.containsKey(spelling)) { - logger.fine(' Type Mapped from supported typedef'); - return supportedTypedefToImportedType[spelling]!; + final importedTypedef = context.config.importType( + Declaration(usr: usr, originalName: spelling), + ); + if (importedTypedef != null) return importedTypedef; + // Get name from supported typedef name if config allows. + if (config.typedefs.useSupportedTypedefs) { + if (suportedTypedefToSuportedNativeType.containsKey(spelling)) { + logger.fine(' Type Mapped from supported typedef'); + return NativeType(suportedTypedefToSuportedNativeType[spelling]!); + } else if (supportedTypedefToImportedType.containsKey(spelling)) { + logger.fine(' Type Mapped from supported typedef'); + return supportedTypedefToImportedType[spelling]!; + } } final typealias = parseTypedefDeclaration(context, cursor); @@ -265,16 +269,16 @@ Type? _extractfromRecord( } if (cursorKind == clang_types.CXCursorKind.CXCursor_StructDecl) { - if (config.structTypeMappings.containsKey(declSpelling)) { - logger.fine(' Type Mapped from type-map'); - return config.structTypeMappings[declSpelling]!; - } + final imported = context.config.importType( + Declaration(usr: cursor.usr(), originalName: declSpelling), + ); + if (imported != null) return imported; return parseStructDeclaration(cursor, context); } else if (cursorKind == clang_types.CXCursorKind.CXCursor_UnionDecl) { - if (config.unionTypeMappings.containsKey(declSpelling)) { - logger.fine(' Type Mapped from type-map'); - return config.unionTypeMappings[declSpelling]!; - } + final imported = context.config.importType( + Declaration(usr: cursor.usr(), originalName: declSpelling), + ); + if (imported != null) return imported; return parseUnionDeclaration(cursor, context); } diff --git a/pkgs/ffigen/lib/src/visitor/apply_config_filters.dart b/pkgs/ffigen/lib/src/visitor/apply_config_filters.dart index d9f34e25bc..345f28d390 100644 --- a/pkgs/ffigen/lib/src/visitor/apply_config_filters.dart +++ b/pkgs/ffigen/lib/src/visitor/apply_config_filters.dart @@ -3,53 +3,54 @@ // BSD-style license that can be found in the LICENSE file. import '../code_generator.dart'; -import '../config_provider/config.dart' show Config, Declarations; +import '../config_provider/config.dart' show Declarations; +import '../context.dart'; import 'ast.dart'; class ApplyConfigFiltersVisitation extends Visitation { - final Config config; + final Context context; final directlyIncluded = {}; final indirectlyIncluded = {}; - ApplyConfigFiltersVisitation(this.config); + ApplyConfigFiltersVisitation(this.context); void _visitImpl(Binding node, Declarations filters) { node.visitChildren(visitor); if (node.originalName == '') return; - if (config.importedTypesByUsr.containsKey(node.usr)) return; + if (context.config.importType(node) != null) return; if (filters.include(node)) directlyIncluded.add(node); } @override - void visitStruct(Struct node) => _visitImpl(node, config.structs); + void visitStruct(Struct node) => _visitImpl(node, context.config.structs); @override - void visitUnion(Union node) => _visitImpl(node, config.unions); + void visitUnion(Union node) => _visitImpl(node, context.config.unions); @override void visitEnumClass(EnumClass node) { if (node.isAnonymous) return; - _visitImpl(node, config.enums); + _visitImpl(node, context.config.enums); } @override void visitCppClass(CppClass node) { - final cppClasses = config.cpp?.classes; + final cppClasses = context.config.cpp?.classes; if (cppClasses == null) return; _visitImpl(node, cppClasses); } @override - void visitFunc(Func node) => _visitImpl(node, config.functions); + void visitFunc(Func node) => _visitImpl(node, context.config.functions); @override void visitMacroConstant(MacroConstant node) => - _visitImpl(node, config.macros); + _visitImpl(node, context.config.macros); @override void visitObjCInterface(ObjCInterface node) { if (node.unavailable) return; - final objcInterfaces = config.objectiveC?.interfaces; + final objcInterfaces = context.config.objectiveC?.interfaces; if (objcInterfaces == null) return; if (!node.isInternal) { @@ -71,7 +72,7 @@ class ApplyConfigFiltersVisitation extends Visitation { @override void visitObjCCategory(ObjCCategory node) { - final objcCategories = config.objectiveC?.categories; + final objcCategories = context.config.objectiveC?.categories; if (objcCategories == null) return; node.filterMethods((m) { if (m.unavailable) return false; @@ -84,7 +85,7 @@ class ApplyConfigFiltersVisitation extends Visitation { @override void visitObjCProtocol(ObjCProtocol node) { if (node.unavailable) return; - final objcProtocols = config.objectiveC?.protocols; + final objcProtocols = context.config.objectiveC?.protocols; if (objcProtocols == null) return; node.filterMethods((m) { @@ -102,21 +103,21 @@ class ApplyConfigFiltersVisitation extends Visitation { @override void visitUnnamedEnumConstant(UnnamedEnumConstant node) => - _visitImpl(node, config.unnamedEnums); + _visitImpl(node, context.config.unnamedEnums); @override - void visitGlobal(Global node) => _visitImpl(node, config.globals); + void visitGlobal(Global node) => _visitImpl(node, context.config.globals); @override void visitConstant(Constant node) { // MacroConstant and UnnamedEnumConstant have their own overrides, so this // only applies to base Constants (e.g. from static const variables). - _visitImpl(node, config.globals); + _visitImpl(node, context.config.globals); } @override void visitTypealias(Typealias node) { if (node.isAnonymous) return; - _visitImpl(node, config.typedefs); + _visitImpl(node, context.config.typedefs); } } diff --git a/pkgs/ffigen/lib/src/visitor/find_transitive_deps.dart b/pkgs/ffigen/lib/src/visitor/find_transitive_deps.dart index e251850ea5..236d65072c 100644 --- a/pkgs/ffigen/lib/src/visitor/find_transitive_deps.dart +++ b/pkgs/ffigen/lib/src/visitor/find_transitive_deps.dart @@ -3,7 +3,7 @@ // BSD-style license that can be found in the LICENSE file. import '../code_generator.dart'; -import '../config_provider/config.dart' show Config; +import '../config_provider/config.dart' show FfiGenerator; import 'ast.dart'; @@ -31,7 +31,7 @@ class FindTransitiveDepsVisitation extends Visitation { } class FindDirectTransitiveDepsVisitation extends Visitation { - final Config config; + final FfiGenerator config; final Set includes; final Set directIncludes; final directTransitives = {}; diff --git a/pkgs/ffigen/lib/src/visitor/list_bindings.dart b/pkgs/ffigen/lib/src/visitor/list_bindings.dart index ab07d88893..6f9bfa6888 100644 --- a/pkgs/ffigen/lib/src/visitor/list_bindings.dart +++ b/pkgs/ffigen/lib/src/visitor/list_bindings.dart @@ -3,7 +3,7 @@ // BSD-style license that can be found in the LICENSE file. import '../code_generator.dart'; -import '../config_provider/config.dart' show Config; +import '../config_provider/config.dart' show FfiGenerator; import '../strings.dart' as strings; import 'ast.dart'; @@ -17,7 +17,7 @@ enum _IncludeBehavior { } class ListBindingsVisitation extends Visitation { - final Config config; + final FfiGenerator config; final Set includes; final Set transitives; final Set directTransitives; diff --git a/pkgs/ffigen/lib/src/visitor/opaque_compounds.dart b/pkgs/ffigen/lib/src/visitor/opaque_compounds.dart index 7fa06bbabb..5f873e9574 100644 --- a/pkgs/ffigen/lib/src/visitor/opaque_compounds.dart +++ b/pkgs/ffigen/lib/src/visitor/opaque_compounds.dart @@ -3,7 +3,7 @@ // BSD-style license that can be found in the LICENSE file. import '../code_generator.dart'; -import '../config_provider/config.dart' show Config; +import '../config_provider/config.dart' show FfiGenerator; import '../config_provider/config_types.dart' show CompoundDependencies; import 'ast.dart'; @@ -36,7 +36,7 @@ class FindByValueCompoundsVisitation extends Visitation { } class ClearOpaqueCompoundMembersVisitation extends Visitation { - final Config config; + final FfiGenerator config; final Set byValueCompounds; final Set included; diff --git a/pkgs/ffigen/test/large_integration_tests/large_test.dart b/pkgs/ffigen/test/large_integration_tests/large_test.dart index f221f684e3..b73d43b1c1 100644 --- a/pkgs/ffigen/test/large_integration_tests/large_test.dart +++ b/pkgs/ffigen/test/large_integration_tests/large_test.dart @@ -67,11 +67,10 @@ void main() { structs: Structs.includeAll, enums: Enums.includeAll, macros: Macros.includeAll, - typedefs: Typedefs( - include: (_) => true, - // ignore: deprecated_member_use_from_same_package - imported: [ImportedType(ffiImport, 'Int64', 'int', 'time_t')], - ), + typedefs: Typedefs(include: (_) => true), + importType: (decl) => decl.originalName == 'time_t' + ? ImportedType(ffiImport, 'Int64', 'int', 'time_t') + : null, ); final library = parse(Context(logger, generator)); final context = testContext(); diff --git a/pkgs/swiftgen/lib/src/config.dart b/pkgs/swiftgen/lib/src/config.dart index d2ff5f86c0..62dfec8f01 100644 --- a/pkgs/swiftgen/lib/src/config.dart +++ b/pkgs/swiftgen/lib/src/config.dart @@ -234,9 +234,6 @@ class FfiGeneratorOptions { /// [ffigen.FfiGenerator.globals] final ffigen.Globals globals; - /// Configuration for integer types. - final ffigen.Integers integers; - /// [ffigen.FfiGenerator.macros] final ffigen.Macros macros; @@ -253,7 +250,6 @@ class FfiGeneratorOptions { this.enums = ffigen.Enums.excludeAll, this.unnamedEnums = ffigen.UnnamedEnums.excludeAll, this.globals = ffigen.Globals.excludeAll, - this.integers = const ffigen.Integers(), this.macros = ffigen.Macros.excludeAll, this.typedefs = ffigen.Typedefs.excludeAll, this.objectiveC = const ffigen.ObjectiveC(), diff --git a/pkgs/swiftgen/lib/src/generator.dart b/pkgs/swiftgen/lib/src/generator.dart index 27bcce9a15..b46119c2a3 100644 --- a/pkgs/swiftgen/lib/src/generator.dart +++ b/pkgs/swiftgen/lib/src/generator.dart @@ -93,7 +93,6 @@ extension SwiftGenGenerator on SwiftGenerator { enums: ffigen.enums, unnamedEnums: ffigen.unnamedEnums, globals: ffigen.globals, - integers: ffigen.integers, macros: ffigen.macros, typedefs: ffigen.typedefs, objectiveC: fg.ObjectiveC(