toEnum function
Implementation
Spec toEnum(String className, ts.ObjectType obj, GenOption option) {
final values = <EnumValue>[];
final getters = <Method>[];
for (final e in obj.children) {
final child = e.child;
final idlName = child.id!;
var fieldName = idlName.camelCase;
if (kDartKeywordsAndInternalTypes.contains(fieldName)) {
fieldName += '_';
}
values.add(
EnumValue(
(b) => b
..name = fieldName
..arguments = ListBuilder([CodeExpression(Code("'$idlName'"))]),
),
);
getters.add(
Method(
(b) => b
..name = 'is_$fieldName'.camelCase
..lambda = true
..type = MethodType.getter
..returns = const Reference('\nbool')
..body = Code('this == $className.$fieldName'),
),
);
}
return Enum(
(b) => b
..name = className
..docs = ListBuilder(['/// [$className] defined in Candid', obj.doc])
..values = ListBuilder(values)
..fields = ListBuilder([
Field(
(b) => b
..name = 'name'
..modifier = FieldModifier.final$
..type = const Reference('String'),
),
])
..constructors = ListBuilder([
Constructor(
(b) => b
..constant = true
..requiredParameters = ListBuilder([
Parameter(
(p) => p
..name = 'name'
..toThis = true,
),
]),
),
if (option.explicitSerializationMethods)
Constructor(
(b) => b
..docs = ListBuilder([
'/// An extra method for the deserialization with `packages:agent_dart`.',
])
..name = 'fromIDLDeserializable'
..factory = true
..body = Code(
'final key = obj.keys.first; return $className.values.firstWhere((e) => e.name == key);',
)
..requiredParameters = ListBuilder([
Parameter(
(b) => b
..type = const Reference('Map')
..name = 'obj',
),
]),
),
Constructor(
(b) => b
..name = 'fromJson'
..factory = true
..body = Code(
'final key = ${option.explicitSerializationMethods ? 'json' : 'json.keys.first'}; '
'return $className.values.firstWhere((e) => e.name == key);',
)
..requiredParameters = ListBuilder([
Parameter(
(b) => b
..type = Reference(
option.explicitSerializationMethods ? 'String' : 'Map',
)
..name = 'json',
),
]),
),
])
..methods = ListBuilder([
...getters,
if (option.explicitSerializationMethods)
Method(
(b) => b
..name = 'toIDLSerializable'
..docs = ListBuilder([
'/// An extra method for the serialization with `packages:agent_dart`.',
])
..body = const Code('return {name: null};')
..returns = const Reference('Map<String, Null>'),
),
Method(
(b) => b
..name = 'toJson'
..body = Code(
option.explicitSerializationMethods
? 'return name;'
: 'return {name: null};',
)
..returns = Reference(
option.explicitSerializationMethods
? 'String'
: '${option.explicitSerializationMethods ? '' : '\n'}'
'Map<String, Null>',
),
),
toStringMethod,
]),
);
}