What is the correct way to create a Span when inserting a new field with a Rust compiler plugin?

I want the compiler plugin to annotate a structure with some information. For example, the source structure has only one field:

struct X { x: i32 } 

And I want to add another field:

 struct X { x: i32, y: MARKTYPE } 

When I looked at the Rust compiler plugins, I decided to use MultiModifier ( SyntaxExtension ) to do my job. enum ItemKind defines Struct(VariantData, Generics) , and VariantData stores data fields:

 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum VariantData { /// Struct variant. /// /// Eg `Bar { .. }` as in `enum Foo { Bar { .. } }` Struct(Vec<StructField>, NodeId), /// Tuple variant. /// /// Eg `Bar(..)` as in `enum Foo { Bar(..) }` Tuple(Vec<StructField>, NodeId), /// Unit variant. /// /// Eg `Bar = ..` as in `enum Foo { Bar = .. }` Unit(NodeId), } 

StructField 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 StructField , but I do not know how to make a Span for the field. Each Span contains a lo and a hi BytePos . StructField information looks like this:

 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 correct way to insert a new field?


I know that it would be easier to use a macro to complete this task, but I want to know if it is possible to insert a field by changing VariantData .

+5
source share

Source: https://habr.com/ru/post/1263707/


All Articles