I want a compiler plugin to annotate a structure with some information. For example, the original struct has only one field:
struct X { x: i32 }
And I want to add another field:
struct X { x: i32, y: MARKTYPE }
As I looked into Rust compiler plugins, I decided to use the MultiModifier
(SyntaxExtension
) to do my work. enum ItemKind
defines Struct(VariantData, Generics)
and the VariantData
stores the data fields:
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum VariantData {
/// Struct variant.
///
/// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
Struct(Vec<StructField>, NodeId),
/// Tuple variant.
///
/// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
Tuple(Vec<StructField>, NodeId),
/// Unit variant.
///
/// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
Unit(NodeId),
}
StructField
is defined as:
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct StructField {
pub span: Span,
pub ident: Option<Ident>,
pub vis: Visibility,
pub id: NodeId,
pub ty: P<Ty>,
pub attrs: Vec<Attribute>,
}
I planned to insert a StructField
, but I don't know how to make a Span
for the field. Each Span
contains a lo
and a hi
BytePos
. The StructField
s information looks like:
Fields 0: StructField {
span: Span {
lo: BytePos(432),
hi: BytePos(437),
expn_id: ExpnId(4294967295)
},
ident: Some(x#0),
vis: Inherited,
id: NodeId(4294967295),
ty: type(i32),
attrs: []
}
What is the proper way to insert the new field?
I know it would be easier to use a macro to do this job, but I want to know if it is plausible to insert the field by modifying the VariantData
.