1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
//! Implements attribute macros for `lsp_msg` crate.
//!
//! These macros remove much of the repetition from the LSP definitions.
extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote;
use spec::spec;
use std::ops::Index;
use syn::{
    parse_macro_input, AttributeArgs, Fields, Ident, Item, ItemStruct, Lit, Meta, NestedMeta, Type,
};

/// Generates **LSP objects** from structs.
#[spec(
    name = "serde",
    shall = "add the `Deserialize` and `Serialize` traits.",
    cert {
        use lsp_msg_derive::lsp_object;
        use serde::{Deserialize, Serialize};

        #[lsp_object]
        struct LspObj {}
    }
)]
#[spec(
    name = "allow_missing",
    cond = "receives `allow_missing`, when deserializing the **LSP object**, any missing field shall be set to its respective default value",
    cert {
        use lsp_msg_derive::lsp_object;
        use serde::{Deserialize, Serialize};

        #[lsp_object(allow_missing)]
        struct LspObj {}
    }
)]
#[spec(
    name = "dynamic_registration",
    cond = "recieves `dynamic_registration = \"..\"`, a `dynamic_registration` field with type `bool` and documentation ``Supports dynamic registration of the {..}.`` is added to the **LSP object**",
    cert {
        use lsp_msg_derive::lsp_object;
        use serde::{Deserialize, Serialize};

        #[lsp_object(dynamic_registration = "test")]
        struct LspObj {}
        let lsp_obj = LspObj {
            dynamic_registration: bool::default(),
        };
    }
)]
#[spec(
    name = "link_support",
    cond = "receives `link_support = \"..\"`, a `link_support` field with type `bool` and documentation ``Supports additional metadata in the form of {..} links.`` is added to the **LSP object**",
    cert {
        use lsp_msg_derive::lsp_object;
        use serde::{Deserialize, Serialize};

        #[lsp_object(link_support = "test")]
        struct LspObj {}
        let lsp_obj = LspObj {
            link_support: bool::default(),
        };
    }
)]
#[spec(
    name = "trigger_characters",
    cond = "recieves `trigger_characters = \"..\"`, a `trigger_characters` field with type `Vec<String>` and documentation ``Characters that trigger {..} automatically.`` is added to the **LSP object**",
    cert {
        use lsp_msg_derive::lsp_object;
        use serde::{Deserialize, Serialize};

        #[lsp_object(trigger_characters = "test")]
        struct LspObj {}
        let lsp_obj = LspObj {
            trigger_characters: vec![String::default()],
        };
    }
)]
#[spec(
    name = "resolve_provider",
    cond = "receives `resolve_provider = \"..\"`, a `resolve_provider` field with type `bool` and documentation ``Provides support to resolve additional information for a {..} item.`` is added to the **LSP object",
    cert {
        use lsp_msg_derive::lsp_object;
        use serde::{Deserialize, Serialize};

        #[lsp_object(resolve_provider = "test")]
        struct LspObj {}
        let lsp_obj = LspObj {
            resolve_provider: bool::default(),
        };
    }
)]
#[spec(
    name = "static_registration",
    cond = "receives `static_registration`, an `id` field with type `Elective<String>` and documentation ``The id used to register the request.`` is added to the **LSP object**",
    cert {
        use lsp_msg_derive::lsp_object;
        use lsp_msg_internal::Elective;
        use serde::{Deserialize, Serialize};

        //#[lsp_object(static_registration)]
        //struct LspObj {}
        //let lsp_obj = LspObj {
        //    id: Elective::Present(String::default()),
        //};
    }
)]
#[spec(
    name = "markup_kind_list",
    cond = "receives `markup_kind_list = \"..\"`, a `{..}_format` field with type `Vec<MarkupKind>` and documentation ``The supported `MarkupKind`s for the `{..}` property.\\n\\nThe order describes the preferred format.`` is added to the **LSP object**",
    cert {
        use lsp_msg_derive::lsp_object;
        use lsp_msg_internal::MarkupKind;
        use serde::{Deserialize, Serialize};

        //#[lsp_object(markup_kind_list = "test")]
        //struct LspObj {}
        //let lsp_obj = LspObj {
        //    test_format: vec![MarkupKind::Plaintext],
        //};
    }
)]
#[proc_macro_attribute]
#[inline]
pub fn lsp_object(args: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as AttributeArgs);
    let item = parse_macro_input!(item as ItemStruct);

    let name = item.ident;
    let vis = item.vis;
    let generics = item.generics;
    let attrs = item.attrs;
    let old_fields = if let Fields::Named(fields_named) = item.fields {
        fields_named.named
    } else {
        panic!("Error");
    };
    let mut allow_missing_fields_attr = quote! {};
    let mut registration_id_field = quote! {};
    let mut dynamic_registration_field = quote! {};
    let mut link_support_field = quote! {};
    let mut markup_kind_list_field = quote! {};
    let mut trigger_characters_field = quote! {};
    let mut resolve_provider_field = quote! {};
    let mut value_set_field = quote! {};

    let mut fields: Vec<TokenStream2> = Vec::new();

    for metaitem in args {
        if let NestedMeta::Meta(meta) = metaitem {
            match meta {
                Meta::Word(word) => match word.to_string().as_str() {
                    "allow_missing" => {
                        allow_missing_fields_attr = quote! {
                            #[serde(default)]
                        };
                    }
                    "static_registration" => {
                        registration_id_field = quote! {
                            #[serde(default, skip_serializing_if = "Elective::is_absent")]
                            /// The id used to register the request.
                            id: Elective<String>,
                        };
                    }
                    _ => {}
                },
                Meta::NameValue(name_value) => match name_value.ident.to_string().as_str() {
                    "dynamic_registration" => {
                        if let Lit::Str(literal) = name_value.lit {
                            let doc = format!(
                                "Supports dynamic registration of the {}.",
                                literal.value()
                            );
                            dynamic_registration_field = quote! {
                                #[doc = #doc]
                                dynamic_registration: bool,
                            };
                        }
                    }
                    "link_support" => {
                        if let Lit::Str(literal) = name_value.lit {
                            let doc = format!(
                                "Supports additional metadata in the form of {} links.",
                                literal.value()
                            );
                            link_support_field = quote! {
                                #[doc = #doc]
                                link_support: bool,
                            };
                        }
                    }
                    "markup_kind_list" => {
                        if let Lit::Str(literal) = name_value.lit {
                            let doc = format!("The supported `MarkupKind`s for the `{}` property.\n\nThe order describes the preferred format.", literal.value());
                            let name = Ident::new(
                                &format!("{}_format", literal.value()),
                                Span::call_site(),
                            );
                            markup_kind_list_field = quote! {
                                #[doc = #doc]
                                #name: Vec<MarkupKind>,
                            };
                        }
                    }
                    "trigger_characters" => {
                        if let Lit::Str(literal) = name_value.lit {
                            let doc = format!(
                                "Characters that trigger {} automatically.",
                                literal.value()
                            );
                            trigger_characters_field = quote! {
                                #[doc = #doc]
                                trigger_characters: Vec<String>,
                            };
                        }
                    }
                    "resolve_provider" => {
                        if let Lit::Str(literal) = name_value.lit {
                            let doc = format!(
                                "Provides support to resolve additional information for a {} item.",
                                literal.value()
                            );
                            resolve_provider_field = quote! {
                                #[doc = #doc]
                                resolve_provider: bool,
                            };
                        }
                    }
                    value => {
                        panic!("Meta NameValue '{}' is not supported.", value);
                    }
                },
                Meta::List(list) => match list.ident.to_string().as_str() {
                    "value_set" => {
                        let len = list.nested.len();
                        let mut valid_doc = String::new();

                        if len == 2 {
                            if let NestedMeta::Literal(Lit::Str(valid)) = &list.nested.index(1) {
                                valid_doc = format!(
                                    " Else, only supports values where `{}`.",
                                    valid.value()
                                );
                            }
                        }

                        if len == 1 || len == 2 {
                            if let NestedMeta::Literal(Lit::Str(kind)) = &list.nested.index(0) {
                                let kind_ident = Ident::new(&kind.value(), Span::call_site());
                                let doc = format!("The supported `{0}` values.\n\nIf `Elective::is_absent()` is false, unknown values fall back to `{0}::default()`.{1}", kind.value(), valid_doc);
                                value_set_field = quote! {
                                    #[doc = #doc]
                                    value_set: Elective<Vec<#kind_ident>>,
                                };
                            }
                        }
                    }
                    value => {
                        panic!("Meta List '{}' is not supported.", value);
                    }
                },
            }
        }
    }

    for field in old_fields {
        let mut elective_attr = quote! {};
        let ty = field.ty;

        if let Type::Path(ref p) = ty {
            if let Some(segment) = p.path.segments.first() {
                if segment.value().ident == "Elective" {
                    elective_attr = quote! {
                        #[serde(default, skip_serializing_if = "Elective::is_absent")]
                    };
                }
            }
        }
        let name = field.ident;
        let attrs = field.attrs;
        let vis = field.vis;
        fields.push(quote! {
            #elective_attr
            #(#attrs)*
            #vis #name: #ty
        });
    }

    let output = quote! {
        #[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
        #[serde(rename_all = "camelCase")]
        #allow_missing_fields_attr
        #(#attrs)*
        #vis struct #name #generics {
            #registration_id_field
            #dynamic_registration_field
            #link_support_field
            #markup_kind_list_field
            #trigger_characters_field
            #resolve_provider_field
            #value_set_field
            #(#fields),*
        }
    };

    TokenStream::from(output)
}

/// Defines LSP kinds from enums.
#[spec(
    name = "serde",
    shall = "add the `Deserialize` and `Serialize` traits."
)]
#[proc_macro_attribute]
#[inline]
pub fn lsp_kind(args: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as AttributeArgs);
    let default_derives = quote! {
        Debug, PartialEq
    };
    let mut derives = quote! {
        Deserialize, Serialize
    };
    let mut serde_attrs = quote! {
        #[serde(untagged)]
    };

    for arg in args {
        if let NestedMeta::Meta(meta) = arg {
            if let Meta::NameValue(name_value) = meta {
                if name_value.ident.to_string().as_str() == "type" {
                    if let Lit::Str(literal) = name_value.lit {
                        match literal.value().as_str() {
                            "string" => {
                                serde_attrs = quote! {
                                    #[serde(rename_all = "camelCase")]
                                };
                            }
                            "number" => {
                                derives = quote! {
                                    Deserialize_repr, Serialize_repr
                                };
                                serde_attrs = quote! {
                                    #[repr(u8)]
                                };
                            }
                            "language_id" => {
                                serde_attrs = quote! {
                                    #[serde(rename_all = "kebab-case")]
                                };
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
    }

    let input = if let Item::Enum(item_enum) = parse_macro_input!(item as Item) {
        item_enum
    } else {
        panic!("Error");
    };

    let output = quote! {
        #[derive(#default_derives, #derives)]
        #serde_attrs
        #input
    };

    TokenStream::from(output)
}