feat: implement generator for named annotation

This commit is contained in:
Sergey Penkovsky
2025-05-17 14:31:52 +03:00
parent 3d071626e5
commit ea6eb536dd
3 changed files with 35 additions and 10 deletions

View File

@@ -7,5 +7,6 @@ export 'src/module.dart';
export 'src/bind.dart';
export 'src/provide.dart';
export 'src/singleton.dart';
export 'src/named.dart';
// TODO: Export any libraries intended for clients of this package.

View File

@@ -0,0 +1,5 @@
// ignore: camel_case_types
class named {
final String value;
const named(this.value);
}

View File

@@ -17,7 +17,6 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
element: element,
);
}
final classElement = element;
final className = classElement.displayName;
final generatedClassName = r'$' + className;
@@ -26,7 +25,6 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
buffer.writeln('final class $generatedClassName extends $className {');
buffer.writeln(' @override');
buffer.writeln(' void builder(Scope currentScope) {');
for (final method in classElement.methods.where((m) => !m.isAbstract)) {
final hasSingleton = method.metadata.any(
(m) =>
@@ -38,7 +36,28 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
.contains('singleton') ??
false,
);
ElementAnnotation? namedMeta;
try {
namedMeta = method.metadata.firstWhere(
(m) =>
m
.computeConstantValue()
?.type
?.getDisplayString(withNullability: false)
.toLowerCase()
.contains('named') ??
false,
);
} catch (_) {
namedMeta = null;
}
String? nameArg;
if (namedMeta != null) {
final cv = namedMeta.computeConstantValue();
if (cv != null) {
nameArg = cv.getField('value')?.toStringValue();
}
}
final returnType =
method.returnType.getDisplayString(withNullability: false);
final methodName = method.displayName;
@@ -46,18 +65,18 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
.map((p) =>
"currentScope.resolve<${p.type.getDisplayString(withNullability: false)}>()")
.join(', ');
buffer.write(' bind<$returnType>()'
'.toProvide(() => $methodName($args))');
if (nameArg != null) {
buffer.write(".withName('$nameArg')");
}
if (hasSingleton) {
buffer.write('.singleton()');
}
buffer.write(';\n');
}
buffer.writeln(' }');
buffer.writeln('}');
return buffer.toString();
}
}