Skip to main content

rust_analyzer/
config.rs

1//! Config used by the language server.
2//!
3//! Of particular interest is the `feature_flags` hash map: while other fields
4//! configure the server itself, feature flags are passed into analysis, and
5//! tweak things like automatic insertion of `()` in completions.
6use std::{env, fmt, iter, ops::Not, sync::OnceLock};
7
8use cfg::{CfgAtom, CfgDiff};
9use hir::Symbol;
10use ide::{
11    AnnotationConfig, AssistConfig, CallHierarchyConfig, CallableSnippets, CompletionConfig,
12    CompletionFieldsToResolve, DiagnosticsConfig, GenericParameterHints, GotoDefinitionConfig,
13    GotoImplementationConfig, HighlightConfig, HighlightRelatedConfig, HoverConfig, HoverDocFormat,
14    InlayFieldsToResolve, InlayHintsConfig, JoinLinesConfig, MemoryLayoutHoverConfig,
15    MemoryLayoutHoverRenderKind, RaFixtureConfig, RenameConfig, Snippet, SnippetScope,
16    SourceRootId,
17};
18use ide_db::{
19    MiniCore, SnippetCap,
20    assists::ExprFillDefaultMode,
21    imports::insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
22};
23use itertools::{Either, Itertools};
24use paths::{Utf8Path, Utf8PathBuf};
25use project_model::{
26    CargoConfig, CargoFeatures, ProjectJson, ProjectJsonData, ProjectJsonFromCommand,
27    ProjectManifest, RustLibSource, TargetDirectoryConfig,
28};
29use rustc_hash::{FxHashMap, FxHashSet};
30use semver::Version;
31use serde::{
32    Deserialize, Serialize,
33    de::{DeserializeOwned, Error},
34};
35use stdx::format_to_acc;
36use triomphe::Arc;
37use vfs::{AbsPath, AbsPathBuf, VfsPath};
38
39use crate::{
40    diagnostics::DiagnosticsMapConfig,
41    flycheck::{CargoOptions, FlycheckConfig},
42    lsp::capabilities::ClientCapabilities,
43    lsp_ext::{WorkspaceSymbolSearchKind, WorkspaceSymbolSearchScope},
44};
45
46type FxIndexMap<K, V> = indexmap::IndexMap<K, V, rustc_hash::FxBuildHasher>;
47
48mod patch_old_style;
49
50// Conventions for configuration keys to preserve maximal extendability without breakage:
51//  - Toggles (be it binary true/false or with more options in-between) should almost always suffix as `_enable`
52//    This has the benefit of namespaces being extensible, and if the suffix doesn't fit later it can be changed without breakage.
53//  - In general be wary of using the namespace of something verbatim, it prevents us from adding subkeys in the future
54//  - Don't use abbreviations unless really necessary
55//  - foo_command = overrides the subcommand, foo_overrideCommand allows full overwriting, extra args only applies for foo_command
56
57#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub enum MaxSubstitutionLength {
60    Hide,
61    #[serde(untagged)]
62    Limit(usize),
63}
64
65// Defines the server-side configuration of the rust-analyzer. We generate *parts* of VS Code's
66// `package.json` config from this. Run `cargo test` to re-generate that file.
67//
68// However, editor specific config, which the server doesn't know about, should be specified
69// directly in `package.json`.
70//
71// To deprecate an option by replacing it with another name use `new_name` | `old_name` so that we
72// keep parsing the old name.
73config_data! {
74    /// Configs that apply on a workspace-wide scope. There are 2 levels on which a global
75    /// configuration can be configured
76    ///
77    /// 1. `rust-analyzer.toml` file under user's config directory (e.g
78    ///    ~/.config/rust-analyzer/rust-analyzer.toml)
79    /// 2. Client's own configurations (e.g `settings.json` on VS Code)
80    ///
81    /// A config is searched for by traversing a "config tree" in a bottom up fashion. It is chosen
82    /// by the nearest first principle.
83    global: struct GlobalDefaultConfigData <- GlobalConfigInput -> {
84        /// Warm up caches on project load.
85        cachePriming_enable: bool = true,
86
87        /// How many worker threads to handle priming caches. The default `0` means to pick
88        /// automatically.
89        cachePriming_numThreads: NumThreads = NumThreads::Physical,
90
91        /// Custom completion snippets.
92        completion_snippets_custom: FxIndexMap<String, SnippetDef> =
93            Config::completion_snippets_default(),
94
95        /// List of files to ignore
96        ///
97        /// These paths (file/directories) will be ignored by rust-analyzer. They are relative to
98        /// the workspace root, and globs are not supported. You may also need to add the folders to
99        /// Code's `files.watcherExclude`.
100        files_exclude | files_excludeDirs: Vec<Utf8PathBuf> = vec![],
101
102        /// If this is `true`, when "Goto Implementations" and in "Implementations" lens, are triggered on a `struct` or `enum` or `union`, we filter out trait implementations that originate from `derive`s above the type.
103        gotoImplementations_filterAdjacentDerives: bool = false,
104
105        /// Highlight related return values while the cursor is on any `match`, `if`, or match arm
106        /// arrow (`=>`).
107        highlightRelated_branchExitPoints_enable: bool = true,
108
109        /// Highlight related references while the cursor is on `break`, `loop`, `while`, or `for`
110        /// keywords.
111        highlightRelated_breakPoints_enable: bool = true,
112
113        /// Highlight all captures of a closure while the cursor is on the `|` or move keyword of a closure.
114        highlightRelated_closureCaptures_enable: bool = true,
115
116        /// Highlight all exit points while the cursor is on any `return`, `?`, `fn`, or return type
117        /// arrow (`->`).
118        highlightRelated_exitPoints_enable: bool = true,
119
120        /// Highlight related references while the cursor is on any identifier.
121        highlightRelated_references_enable: bool = true,
122
123        /// Highlight all break points for a loop or block context while the cursor is on any
124        /// `async` or `await` keywords.
125        highlightRelated_yieldPoints_enable: bool = true,
126
127        /// Show `Debug` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set.
128        hover_actions_debug_enable: bool = true,
129
130        /// Show HoverActions in Rust files.
131        hover_actions_enable: bool = true,
132
133        /// Show `Go to Type Definition` action. Only applies when
134        /// `#rust-analyzer.hover.actions.enable#` is set.
135        hover_actions_gotoTypeDef_enable: bool = true,
136
137        /// Show `Implementations` action. Only applies when `#rust-analyzer.hover.actions.enable#`
138        /// is set.
139        hover_actions_implementations_enable: bool = true,
140
141        /// Show `References` action. Only applies when `#rust-analyzer.hover.actions.enable#` is
142        /// set.
143        hover_actions_references_enable: bool = false,
144
145        /// Show `Run` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set.
146        hover_actions_run_enable: bool = true,
147
148        /// Show `Update Test` action. Only applies when `#rust-analyzer.hover.actions.enable#` and
149        /// `#rust-analyzer.hover.actions.run.enable#` are set.
150        hover_actions_updateTest_enable: bool = true,
151
152        /// Show documentation on hover.
153        hover_documentation_enable: bool = true,
154
155        /// Show keyword hover popups. Only applies when
156        /// `#rust-analyzer.hover.documentation.enable#` is set.
157        hover_documentation_keywords_enable: bool = true,
158
159        /// Show drop glue information on hover.
160        hover_dropGlue_enable: bool = true,
161
162        /// Use markdown syntax for links on hover.
163        hover_links_enable: bool = true,
164
165        /// Show what types are used as generic arguments in calls etc. on hover, and limit the max
166        /// length to show such types, beyond which they will be shown with ellipsis.
167        ///
168        /// This can take three values: `null` means "unlimited", the string `"hide"` means to not
169        /// show generic substitutions at all, and a number means to limit them to X characters.
170        ///
171        /// The default is 20 characters.
172        hover_maxSubstitutionLength: Option<MaxSubstitutionLength> =
173            Some(MaxSubstitutionLength::Limit(20)),
174
175        /// How to render the align information in a memory layout hover.
176        hover_memoryLayout_alignment: Option<MemoryLayoutHoverRenderKindDef> =
177            Some(MemoryLayoutHoverRenderKindDef::Hexadecimal),
178
179        /// Show memory layout data on hover.
180        hover_memoryLayout_enable: bool = true,
181
182        /// How to render the niche information in a memory layout hover.
183        hover_memoryLayout_niches: Option<bool> = Some(false),
184
185        /// How to render the offset information in a memory layout hover.
186        hover_memoryLayout_offset: Option<MemoryLayoutHoverRenderKindDef> =
187            Some(MemoryLayoutHoverRenderKindDef::Hexadecimal),
188
189        /// How to render the padding information in a memory layout hover.
190        hover_memoryLayout_padding: Option<MemoryLayoutHoverRenderKindDef> = None,
191
192        /// How to render the size information in a memory layout hover.
193        hover_memoryLayout_size: Option<MemoryLayoutHoverRenderKindDef> =
194            Some(MemoryLayoutHoverRenderKindDef::Both),
195
196        /// How many variants of an enum to display when hovering on. Show none if empty.
197        hover_show_enumVariants: Option<usize> = Some(5),
198
199        /// How many fields of a struct, variant or union to display when hovering on. Show none if
200        /// empty.
201        hover_show_fields: Option<usize> = Some(5),
202
203        /// How many associated items of a trait to display when hovering a trait.
204        hover_show_traitAssocItems: Option<usize> = None,
205
206        /// Show inlay type hints for binding modes.
207        inlayHints_bindingModeHints_enable: bool = false,
208
209        /// Show inlay type hints for method chains.
210        inlayHints_chainingHints_enable: bool = true,
211
212        /// Show inlay hints after a closing `}` to indicate what item it belongs to.
213        inlayHints_closingBraceHints_enable: bool = true,
214
215        /// Minimum number of lines required before the `}` until the hint is shown (set to 0 or 1
216        /// to always show them).
217        inlayHints_closingBraceHints_minLines: usize = 25,
218
219        /// Show inlay hints for closure and coroutine captures.
220        inlayHints_closureCaptureHints_enable: bool = false,
221
222        /// Show inlay type hints for return types of closures.
223        inlayHints_closureReturnTypeHints_enable: ClosureReturnTypeHintsDef =
224            ClosureReturnTypeHintsDef::Never,
225
226        /// Closure notation in type and chaining inlay hints.
227        inlayHints_closureStyle: ClosureStyle = ClosureStyle::ImplFn,
228
229        /// Show enum variant discriminant hints.
230        inlayHints_discriminantHints_enable: DiscriminantHintsDef =
231            DiscriminantHintsDef::Never,
232
233        /// Disable reborrows in expression adjustments inlay hints.
234        ///
235        /// Reborrows are a pair of a builtin deref then borrow, i.e. `&*`. They are inserted by the compiler but are mostly useless to the programmer.
236        ///
237        /// Note: if the deref is not builtin (an overloaded deref), or the borrow is `&raw const`/`&raw mut`, they are not removed.
238        inlayHints_expressionAdjustmentHints_disableReborrows: bool =
239            true,
240
241        /// Show inlay hints for type adjustments.
242        inlayHints_expressionAdjustmentHints_enable: AdjustmentHintsDef =
243            AdjustmentHintsDef::Never,
244
245        /// Hide inlay hints for type adjustments outside of `unsafe` blocks.
246        inlayHints_expressionAdjustmentHints_hideOutsideUnsafe: bool = false,
247
248        /// Show inlay hints as postfix ops (`.*` instead of `*`, etc).
249        inlayHints_expressionAdjustmentHints_mode: AdjustmentHintsModeDef =
250            AdjustmentHintsModeDef::Prefix,
251
252        /// Show const generic parameter name inlay hints.
253        inlayHints_genericParameterHints_const_enable: bool = true,
254
255        /// Show generic lifetime parameter name inlay hints.
256        inlayHints_genericParameterHints_lifetime_enable: bool = false,
257
258        /// Show generic type parameter name inlay hints.
259        inlayHints_genericParameterHints_type_enable: bool = false,
260
261        /// Show implicit drop hints.
262        inlayHints_implicitDrops_enable: ImplicitDropDef = ImplicitDropDef::Never,
263
264        /// Show inlay hints for the implied type parameter `Sized` bound.
265        inlayHints_implicitSizedBoundHints_enable: bool = false,
266
267        /// Show inlay hints for the implied `dyn` keyword in trait object types.
268        inlayHints_impliedDynTraitHints_enable: bool = true,
269
270        /// Show inlay type hints for elided lifetimes in function signatures.
271        inlayHints_lifetimeElisionHints_enable: LifetimeElisionDef = LifetimeElisionDef::Never,
272
273        /// Prefer using parameter names as the name for elided lifetime hints if possible.
274        inlayHints_lifetimeElisionHints_useParameterNames: bool = false,
275
276        /// Maximum length for inlay hints. Set to null to have an unlimited length.
277        ///
278        /// **Note:** This is mostly a hint, and we don't guarantee to strictly follow the limit.
279        inlayHints_maxLength: Option<usize> = Some(25),
280
281        /// Show function parameter name inlay hints at the call site.
282        inlayHints_parameterHints_enable: bool = true,
283
284        /// Show parameter name inlay hints for missing arguments at the call site.
285        inlayHints_parameterHints_missingArguments_enable: bool = false,
286
287        /// Show exclusive range inlay hints.
288        inlayHints_rangeExclusiveHints_enable: bool = false,
289
290        /// Show inlay hints for compiler inserted reborrows.
291        ///
292        /// This setting is deprecated in favor of
293        /// #rust-analyzer.inlayHints.expressionAdjustmentHints.enable#.
294        inlayHints_reborrowHints_enable: ReborrowHintsDef = ReborrowHintsDef::Never,
295
296        /// Whether to render leading colons for type hints, and trailing colons for parameter hints.
297        inlayHints_renderColons: bool = true,
298
299        /// Show inlay type hints for variables.
300        inlayHints_typeHints_enable: bool = true,
301
302        /// Hide inlay type hints for `let` statements that initialize to a closure.
303        ///
304        /// Only applies to closures with blocks, same as
305        /// `#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`.
306        inlayHints_typeHints_hideClosureInitialization: bool = false,
307
308        /// Hide inlay parameter type hints for closures.
309        inlayHints_typeHints_hideClosureParameter: bool = false,
310
311        /// Hide inlay type hints for inferred types.
312        inlayHints_typeHints_hideInferredTypes: bool = false,
313
314        /// Hide inlay type hints for constructors.
315        inlayHints_typeHints_hideNamedConstructor: bool = false,
316
317        /// Where to render type hints relative to their binding pattern.
318        inlayHints_typeHints_location: TypeHintsLocation = TypeHintsLocation::Inline,
319
320        /// Enable the experimental support for interpreting tests.
321        interpret_tests: bool = false,
322
323        /// Join lines merges consecutive declaration and initialization of an assignment.
324        joinLines_joinAssignments: bool = true,
325
326        /// Join lines inserts else between consecutive ifs.
327        joinLines_joinElseIf: bool = true,
328
329        /// Join lines removes trailing commas.
330        joinLines_removeTrailingComma: bool = true,
331
332        /// Join lines unwraps trivial blocks.
333        joinLines_unwrapTrivialBlock: bool = true,
334
335        /// Show `Debug` lens. Only applies when `#rust-analyzer.lens.enable#` is set.
336        lens_debug_enable: bool = true,
337
338        /// Show CodeLens in Rust files.
339        lens_enable: bool = true,
340
341        /// Show `Implementations` lens. Only applies when `#rust-analyzer.lens.enable#` is set.
342        lens_implementations_enable: bool = true,
343
344        /// Where to render annotations.
345        lens_location: AnnotationLocation = AnnotationLocation::AboveName,
346
347        /// Show `References` lens for Struct, Enum, and Union. Only applies when
348        /// `#rust-analyzer.lens.enable#` is set.
349        lens_references_adt_enable: bool = false,
350
351        /// Show `References` lens for Enum Variants. Only applies when
352        /// `#rust-analyzer.lens.enable#` is set.
353        lens_references_enumVariant_enable: bool = false,
354
355        /// Show `Method References` lens. Only applies when `#rust-analyzer.lens.enable#` is set.
356        lens_references_method_enable: bool = false,
357
358        /// Show `References` lens for Trait. Only applies when `#rust-analyzer.lens.enable#` is
359        /// set.
360        lens_references_trait_enable: bool = false,
361
362        /// Show `Run` lens. Only applies when `#rust-analyzer.lens.enable#` is set.
363        lens_run_enable: bool = true,
364
365        /// Show `Update Test` lens. Only applies when `#rust-analyzer.lens.enable#` and
366        /// `#rust-analyzer.lens.run.enable#` are set.
367        lens_updateTest_enable: bool = true,
368
369        /// Disable project auto-discovery in favor of explicitly specified set of projects.
370        ///
371        /// Elements must be paths pointing to `Cargo.toml`, `rust-project.json`, `.rs` files (which
372        /// will be treated as standalone files) or JSON objects in `rust-project.json` format.
373        linkedProjects: Vec<ManifestOrProjectJson> = vec![],
374
375        /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
376        lru_capacity: Option<u16> = None,
377
378        /// The LRU capacity of the specified queries.
379        lru_query_capacities: FxHashMap<Box<str>, u16> = FxHashMap::default(),
380
381        /// Show `can't find Cargo.toml` error message.
382        notifications_cargoTomlNotFound: bool = true,
383
384        /// The number of worker threads in the main loop. The default `null` means to pick
385        /// automatically.
386        numThreads: Option<NumThreads> = None,
387
388        /// Expand attribute macros. Requires `#rust-analyzer.procMacro.enable#` to be set.
389        procMacro_attributes_enable: bool = true,
390
391        /// Enable support for procedural macros, implies `#rust-analyzer.cargo.buildScripts.enable#`.
392        procMacro_enable: bool = true,
393
394        /// Number of proc-macro server processes to spawn.
395        ///
396        /// Controls how many independent `proc-macro-srv` processes rust-analyzer
397        /// runs in parallel to handle macro expansion.
398        procMacro_processes: NumProcesses = NumProcesses::Concrete(2),
399
400        /// Internal config, path to proc-macro server executable.
401        procMacro_server: Option<Utf8PathBuf> = None,
402
403        /// The path where to save memory profiling output.
404        ///
405        /// **Note:** Memory profiling is not enabled by default in rust-analyzer builds, you need to build
406        /// from source for it.
407        profiling_memoryProfile: Option<Utf8PathBuf> = None,
408
409        /// Exclude imports from find-all-references.
410        references_excludeImports: bool = false,
411
412        /// Exclude tests from find-all-references and call-hierarchy.
413        references_excludeTests: bool = false,
414
415        /// Use semantic tokens for comments.
416        ///
417        /// In some editors (e.g. vscode) semantic tokens override other highlighting grammars.
418        /// By disabling semantic tokens for comments, other grammars can be used to highlight
419        /// their contents.
420        semanticHighlighting_comments_enable: bool = true,
421
422        /// Inject additional highlighting into doc comments.
423        ///
424        /// When enabled, rust-analyzer will highlight rust source in doc comments as well as intra
425        /// doc links.
426        semanticHighlighting_doc_comment_inject_enable: bool = true,
427
428        /// Emit non-standard tokens and modifiers
429        ///
430        /// When enabled, rust-analyzer will emit tokens and modifiers that are not part of the
431        /// standard set of semantic tokens.
432        semanticHighlighting_nonStandardTokens: bool = true,
433
434        /// Use semantic tokens for operators.
435        ///
436        /// When disabled, rust-analyzer will emit semantic tokens only for operator tokens when
437        /// they are tagged with modifiers.
438        semanticHighlighting_operator_enable: bool = true,
439
440        /// Use specialized semantic tokens for operators.
441        ///
442        /// When enabled, rust-analyzer will emit special token types for operator tokens instead
443        /// of the generic `operator` token type.
444        semanticHighlighting_operator_specialization_enable: bool = false,
445
446        /// Use semantic tokens for punctuation.
447        ///
448        /// When disabled, rust-analyzer will emit semantic tokens only for punctuation tokens when
449        /// they are tagged with modifiers or have a special role.
450        semanticHighlighting_punctuation_enable: bool = false,
451
452        /// When enabled, rust-analyzer will emit a punctuation semantic token for the `!` of macro
453        /// calls.
454        semanticHighlighting_punctuation_separate_macro_bang: bool = false,
455
456        /// Use specialized semantic tokens for punctuation.
457        ///
458        /// When enabled, rust-analyzer will emit special token types for punctuation tokens instead
459        /// of the generic `punctuation` token type.
460        semanticHighlighting_punctuation_specialization_enable: bool = false,
461
462        /// Use semantic tokens for strings.
463        ///
464        /// In some editors (e.g. vscode) semantic tokens override other highlighting grammars.
465        /// By disabling semantic tokens for strings, other grammars can be used to highlight
466        /// their contents.
467        semanticHighlighting_strings_enable: bool = true,
468
469        /// Show full signature of the callable. Only shows parameters if disabled.
470        signatureInfo_detail: SignatureDetail = SignatureDetail::Full,
471
472        /// Show documentation.
473        signatureInfo_documentation_enable: bool = true,
474
475        /// Specify the characters allowed to invoke special on typing triggers.
476        ///
477        /// - typing `=` after `let` tries to smartly add `;` if `=` is followed by an existing
478        ///   expression
479        /// - typing `=` between two expressions adds `;` when in statement position
480        /// - typing `=` to turn an assignment into an equality comparison removes `;` when in
481        ///   expression position
482        /// - typing `.` in a chain method call auto-indents
483        /// - typing `{` or `(` in front of an expression inserts a closing `}` or `)` after the
484        ///   expression
485        /// - typing `{` in a use item adds a closing `}` in the right place
486        /// - typing `>` to complete a return type `->` will insert a whitespace after it
487        /// - typing `<` in a path or type position inserts a closing `>` after the path or type.
488        typing_triggerChars: Option<String> = Some("=.".to_owned()),
489
490
491        /// Configure a command that rust-analyzer can invoke to
492        /// obtain configuration.
493        ///
494        /// This is an alternative to manually generating
495        /// `rust-project.json`: it enables rust-analyzer to generate
496        /// rust-project.json on the fly, and regenerate it when
497        /// switching or modifying projects.
498        ///
499        /// This is an object with three fields:
500        ///
501        /// * `command`: the shell command to invoke
502        ///
503        /// * `filesToWatch`: which build system-specific files should
504        /// be watched to trigger regenerating the configuration
505        ///
506        /// * `progressLabel`: the name of the command, used in
507        /// progress indicators in the IDE
508        ///
509        /// Here's an example of a valid configuration:
510        ///
511        /// ```json
512        /// "rust-analyzer.workspace.discoverConfig": {
513        ///     "command": [
514        ///         "rust-project",
515        ///         "develop-json",
516        ///         "{arg}"
517        ///     ],
518        ///     "progressLabel": "buck2/rust-project",
519        ///     "filesToWatch": [
520        ///         "BUCK"
521        ///     ]
522        /// }
523        /// ```
524        ///
525        /// ## Argument Substitutions
526        ///
527        /// If `command` includes the argument `{arg}`, that argument will be substituted
528        /// with the JSON-serialized form of the following enum:
529        ///
530        /// ```norun
531        /// #[derive(PartialEq, Clone, Debug, Serialize)]
532        /// #[serde(rename_all = "camelCase")]
533        /// pub enum DiscoverArgument {
534        ///    Path(AbsPathBuf),
535        ///    Buildfile(AbsPathBuf),
536        /// }
537        /// ```
538        ///
539        /// rust-analyzer will use the path invocation to find and
540        /// generate a `rust-project.json` and therefore a
541        /// workspace. Example:
542        ///
543        ///
544        /// ```norun
545        /// rust-project develop-json '{ "path": "myproject/src/main.rs" }'
546        /// ```
547        ///
548        /// rust-analyzer will use build file invocations to update an
549        /// existing workspace. Example:
550        ///
551        /// Or with a build file and the configuration above:
552        ///
553        /// ```norun
554        /// rust-project develop-json '{ "buildfile": "myproject/BUCK" }'
555        /// ```
556        ///
557        /// As a reference for implementors, buck2's `rust-project`
558        /// will likely be useful:
559        /// <https://github.com/facebook/buck2/tree/main/integrations/rust-project>.
560        ///
561        /// ## Discover Command Output
562        ///
563        /// **Warning**: This format is provisional and subject to change.
564        ///
565        /// The discover command should output JSON objects to stdout,
566        /// one per line (JSONL format). These objects should correspond
567        /// to this Rust data type:
568        ///
569        /// ```norun
570        /// #[derive(Debug, Clone, Deserialize, Serialize)]
571        /// #[serde(tag = "kind")]
572        /// #[serde(rename_all = "snake_case")]
573        /// enum DiscoverProjectData {
574        ///     Finished { buildfile: Utf8PathBuf, project: ProjectJsonData },
575        ///     Error { error: String, source: Option<String> },
576        ///     Progress { message: String },
577        /// }
578        /// ```
579        ///
580        /// For example, a progress event:
581        ///
582        /// ```json
583        /// {"kind":"progress","message":"generating rust-project.json"}
584        /// ```
585        ///
586        /// A finished event can look like this (expanded and
587        /// commented for readability):
588        ///
589        /// ```json
590        /// {
591        ///     // the internally-tagged representation of the enum.
592        ///     "kind": "finished",
593        ///     // the file used by a non-Cargo build system to define
594        ///     // a package or target.
595        ///     "buildfile": "rust-analyzer/BUCK",
596        ///     // the contents of a rust-project.json, elided for brevity
597        ///     "project": {
598        ///         "sysroot": "foo",
599        ///         "crates": []
600        ///     }
601        /// }
602        /// ```
603        ///
604        /// Only the finished event is required, but the other
605        /// variants are encouraged to give users more feedback about
606        /// progress or errors.
607        ///
608        /// Stderr is not parsed as JSONL. It is treated as command log
609        /// output and forwarded to rust-analyzer's own logs.
610        workspace_discoverConfig: Option<DiscoverWorkspaceConfig> = None,
611    }
612}
613
614config_data! {
615    /// Local configurations can be defined per `SourceRoot`. This almost always corresponds to a `Crate`.
616    local: struct LocalDefaultConfigData <- LocalConfigInput ->  {
617        /// Insert #[must_use] when generating `as_` methods for enum variants.
618        assist_emitMustUse: bool = false,
619
620        /// Placeholder expression to use for missing expressions in assists.
621        assist_expressionFillDefault: ExprFillDefaultDef = ExprFillDefaultDef::Todo,
622
623        /// Prefer to use `Self` over the type name when inserting a type (e.g. in "fill match arms" assist).
624        assist_preferSelf: bool = false,
625
626        /// Term search fuel in "units of work" for assists (Defaults to 1800).
627        assist_termSearch_fuel: usize = 1800,
628
629        /// Automatically add `::` when completing the module.
630        ///
631        /// Will not be completed in `use`.
632        completion_addColonsToModule: bool = true,
633
634        /// Automatically add a semicolon when completing unit-returning functions.
635        ///
636        /// In `match` arms it completes a comma instead.
637        completion_addSemicolonToUnit: bool = true,
638
639        /// Show method calls and field accesses completions with `await` prefixed to them when
640        /// completing on a future.
641        completion_autoAwait_enable: bool = true,
642
643        /// Complete traits with `dyn` prefixed to them when completing in a type position.
644        completion_autoDyn_enable: bool = true,
645
646        /// Show method call completions with `iter()` or `into_iter()` prefixed to them when
647        /// completing on a type that has them.
648        completion_autoIter_enable: bool = true,
649
650        /// Show completions that automatically add imports when completed.
651        ///
652        /// Note that your client must specify the `additionalTextEdits` LSP client capability to
653        /// truly have this feature enabled.
654        completion_autoimport_enable: bool = true,
655
656        /// A list of full paths to items to exclude from auto-importing completions.
657        ///
658        /// Traits in this list won't have their methods suggested in completions unless the trait
659        /// is in scope.
660        ///
661        /// You can either specify a string path which defaults to type "always" or use the more
662        /// verbose form `{ "path": "path::to::item", type: "always" }`.
663        ///
664        /// For traits the type "methods" can be used to only exclude the methods but not the trait
665        /// itself.
666        ///
667        /// For modules the type "sub_items" can be used to only exclude the all items in it but not the module
668        /// itself. This does not include items defined in nested modules.
669        ///
670        /// For enums the type "variants" can be used to only exclude the all variants in it but not the enum
671        /// itself.
672        ///
673        /// This setting also inherits `#rust-analyzer.completion.excludeTraits#`.
674        completion_autoimport_exclude: Vec<AutoImportExclusion> = vec![
675            AutoImportExclusion::Verbose { path: "core::borrow::Borrow".to_owned(), r#type: AutoImportExclusionType::Methods },
676            AutoImportExclusion::Verbose { path: "core::borrow::BorrowMut".to_owned(), r#type: AutoImportExclusionType::Methods },
677        ],
678
679        /// Show method calls and field access completions with `self` prefixed to them when
680        /// inside a method.
681        completion_autoself_enable: bool = true,
682
683        /// Add parenthesis and argument snippets when completing function.
684        completion_callable_snippets: CallableCompletionDef = CallableCompletionDef::FillArguments,
685
686        /// A list of full paths to traits whose methods to exclude from completion.
687        ///
688        /// Methods from these traits won't be completed, even if the trait is in scope. However,
689        /// they will still be suggested on expressions whose type is `dyn Trait`, `impl Trait` or
690        /// `T where T: Trait`.
691        ///
692        /// Note that the trait themselves can still be completed.
693        completion_excludeTraits: Vec<String> = Vec::new(),
694
695        /// Show full function / method signatures in completion docs.
696        completion_fullFunctionSignatures_enable: bool = false,
697
698        /// Omit deprecated items from completions. By default they are marked as deprecated but not
699        /// hidden.
700        completion_hideDeprecated: bool = false,
701
702        /// Maximum number of completions to return. If `None`, the limit is infinite.
703        completion_limit: Option<usize> = None,
704
705        /// Show postfix snippets like `dbg`, `if`, `not`, etc.
706        completion_postfix_enable: bool = true,
707
708        /// Show completions of private items and fields that are defined in the current workspace
709        /// even if they are not visible at the current position.
710        completion_privateEditable_enable: bool = false,
711
712        /// Enable term search based snippets like `Some(foo.bar().baz())`.
713        completion_termSearch_enable: bool = false,
714
715        /// Term search fuel in "units of work" for autocompletion (Defaults to 1000).
716        completion_termSearch_fuel: usize = 1000,
717
718        /// Complete turbofish (`::<>`) at the call site (if needed).
719        completion_turbofish_enable: bool = true,
720
721        /// List of rust-analyzer diagnostics to disable.
722        diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
723
724        /// Show native rust-analyzer diagnostics.
725        diagnostics_enable: bool = true,
726
727        /// Show experimental rust-analyzer diagnostics that might have more false positives than
728        /// usual.
729        diagnostics_experimental_enable: bool = false,
730
731        /// Map of prefixes to be substituted when parsing diagnostic file paths. This should be the
732        /// reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.
733        diagnostics_remapPrefix: FxHashMap<String, String> = FxHashMap::default(),
734
735        /// Run additional style lints.
736        diagnostics_styleLints_enable: bool = false,
737
738        /// List of warnings that should be displayed with hint severity.
739        ///
740        /// The warnings will be indicated by faded text or three dots in code and will not show up
741        /// in the `Problems Panel`.
742        diagnostics_warningsAsHint: Vec<String> = vec![],
743
744        /// List of warnings that should be displayed with info severity.
745        ///
746        /// The warnings will be indicated by a blue squiggly underline in code and a blue icon in
747        /// the `Problems Panel`.
748        diagnostics_warningsAsInfo: Vec<String> = vec![],
749
750        /// Disable support for `#[rust_analyzer::rust_fixture]` snippets.
751        ///
752        /// If you are not working on rust-analyzer itself, you should ignore this config.
753        disableFixtureSupport: bool = false,
754
755        /// Enforce the import granularity setting for all files. If set to false rust-analyzer will
756        /// try to keep import styles consistent per file.
757        imports_granularity_enforce: bool = false,
758
759        /// How imports should be grouped into use statements.
760        imports_granularity_group: ImportGranularityDef = ImportGranularityDef::Crate,
761
762        /// Group inserted imports by the [following
763        /// order](https://rust-analyzer.github.io/book/features.html#auto-import). Groups are
764        /// separated by newlines.
765        imports_group_enable: bool = true,
766
767        /// Allow import insertion to merge new imports into single path glob imports like `use
768        /// std::fmt::*;`.
769        imports_merge_glob: bool = true,
770
771        /// Prefer to unconditionally use imports of the core and alloc crate, over the std crate.
772        imports_preferNoStd | imports_prefer_no_std: bool = false,
773
774        /// Prefer import paths containing a `prelude` module.
775        imports_preferPrelude: bool = false,
776
777        /// The path structure for newly inserted paths to use.
778        imports_prefix: ImportPrefixDef = ImportPrefixDef::ByCrate,
779
780        /// Prefix external (including std, core) crate imports with `::`.
781        ///
782        /// E.g. `use ::std::io::Read;`.
783        imports_prefixExternPrelude: bool = false,
784
785        /// Whether to warn when a rename will cause conflicts (change the meaning of the code).
786        rename_showConflicts: bool = true,
787    }
788}
789
790config_data! {
791    workspace: struct WorkspaceDefaultConfigData <- WorkspaceConfigInput -> {
792        /// Pass `--all-targets` to cargo invocation.
793        cargo_allTargets: bool           = true,
794        /// Automatically refresh project info via `cargo metadata` on
795        /// `Cargo.toml` or `.cargo/config.toml` changes.
796        cargo_autoreload: bool           = true,
797        /// Run build scripts (`build.rs`) for more precise code analysis.
798        cargo_buildScripts_enable: bool  = true,
799        /// Specifies the invocation strategy to use when running the build scripts command.
800        /// If `per_workspace` is set, the command will be executed for each Rust workspace with the
801        /// workspace as the working directory.
802        /// If `once` is set, the command will be executed once with the opened project as the
803        /// working directory.
804        /// This config only has an effect when `#rust-analyzer.cargo.buildScripts.overrideCommand#`
805        /// is set.
806        cargo_buildScripts_invocationStrategy: InvocationStrategy = InvocationStrategy::PerWorkspace,
807        /// Override the command rust-analyzer uses to run build scripts and
808        /// build procedural macros. The command is required to output json
809        /// and should therefore include `--message-format=json` or a similar
810        /// option.
811        ///
812        /// If there are multiple linked projects/workspaces, this command is invoked for
813        /// each of them, with the working directory being the workspace root
814        /// (i.e., the folder containing the `Cargo.toml`). This can be overwritten
815        /// by changing `#rust-analyzer.cargo.buildScripts.invocationStrategy#`.
816        ///
817        /// By default, a cargo invocation will be constructed for the configured
818        /// targets and features, with the following base command line:
819        ///
820        /// ```bash
821        /// cargo check --quiet --workspace --message-format=json --all-targets --keep-going
822        /// ```
823        ///
824        /// Note: The option must be specified as an array of command line arguments, with
825        /// the first argument being the name of the command to run.
826        cargo_buildScripts_overrideCommand: Option<Vec<String>> = None,
827        /// Rerun proc-macros building/build-scripts running when proc-macro
828        /// or build-script sources change and are saved.
829        cargo_buildScripts_rebuildOnSave: bool = true,
830        /// Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to
831        /// avoid checking unnecessary things.
832        cargo_buildScripts_useRustcWrapper: bool = true,
833        /// List of cfg options to enable with the given values.
834        ///
835        /// To enable a name without a value, use `"key"`.
836        /// To enable a name with a value, use `"key=value"`.
837        /// To disable, prefix the entry with a `!`.
838        cargo_cfgs: Vec<String> = {
839            vec!["debug_assertions".into(), "miri".into()]
840        },
841        /// Path to a `.cargo/config.toml` style file to pass to cargo via `--config`
842        /// for every cargo invocation (metadata, build scripts, config discovery).
843        /// Useful to give rust-analyzer a consistent view of the project configuration.
844        cargo_configPath: Option<Utf8PathBuf> = None,
845        /// Extra arguments that are passed to every cargo invocation.
846        cargo_extraArgs: Vec<String> = vec![],
847        /// Extra environment variables that will be set when running cargo, rustc
848        /// or other commands within the workspace. Useful for setting RUSTFLAGS.
849        cargo_extraEnv: FxHashMap<String, Option<String>> = FxHashMap::default(),
850        /// List of features to activate.
851        ///
852        /// Set this to `"all"` to pass `--all-features` to cargo.
853        cargo_features: CargoFeaturesDef      = CargoFeaturesDef::Selected(vec![]),
854        /// Extra arguments passed only to `cargo metadata`, not to other cargo invocations.
855        /// Useful for flags like `--config` that `cargo metadata` supports.
856        cargo_metadataExtraArgs: Vec<String> = vec![],
857        /// Whether to pass `--no-default-features` to cargo.
858        cargo_noDefaultFeatures: bool    = false,
859        /// Whether to skip fetching dependencies. If set to "true", the analysis is performed
860        /// entirely offline, and Cargo metadata for dependencies is not fetched.
861        cargo_noDeps: bool = false,
862        /// Relative path to the sysroot, or "discover" to try to automatically find it via
863        /// "rustc --print sysroot".
864        ///
865        /// Unsetting this disables sysroot loading.
866        ///
867        /// This option does not take effect until rust-analyzer is restarted.
868        cargo_sysroot: Option<String>    = Some("discover".to_owned()),
869        /// Relative path to the sysroot library sources. If left unset, this will default to
870        /// `{cargo.sysroot}/lib/rustlib/src/rust/library`.
871        ///
872        /// This option does not take effect until rust-analyzer is restarted.
873        cargo_sysrootSrc: Option<String>    = None,
874        /// Compilation target override (target tuple).
875        // FIXME(@poliorcetics): move to multiple targets here too, but this will need more work
876        // than `checkOnSave_target`
877        cargo_target: Option<String>     = None,
878        /// Optional path to a rust-analyzer specific target directory.
879        /// This prevents rust-analyzer's `cargo check` and initial build-script and proc-macro
880        /// building from locking the `Cargo.lock` at the expense of duplicating build artifacts.
881        ///
882        /// Set to `true` to use a subdirectory of the existing target directory or
883        /// set to a path relative to the workspace to use that path.
884        cargo_targetDir | rust_analyzerTargetDir: Option<TargetDirectory> = None,
885
886        /// Set `cfg(test)` for local crates. Defaults to true.
887        cfg_setTest: bool = true,
888
889        /// Run the check command for diagnostics on save.
890        checkOnSave | checkOnSave_enable: bool                         = true,
891
892
893        /// Check all targets and tests (`--all-targets`). Defaults to
894        /// `#rust-analyzer.cargo.allTargets#`.
895        check_allTargets | checkOnSave_allTargets: Option<bool>          = None,
896        /// Cargo command to use for `cargo check`.
897        check_command | checkOnSave_command: String                      = "check".to_owned(),
898        /// Extra arguments for `cargo check`.
899        check_extraArgs | checkOnSave_extraArgs: Vec<String>             = vec![],
900        /// Extra environment variables that will be set when running `cargo check`.
901        /// Extends `#rust-analyzer.cargo.extraEnv#`.
902        check_extraEnv | checkOnSave_extraEnv: FxHashMap<String, Option<String>> = FxHashMap::default(),
903        /// List of features to activate. Defaults to
904        /// `#rust-analyzer.cargo.features#`.
905        ///
906        /// Set to `"all"` to pass `--all-features` to Cargo.
907        check_features | checkOnSave_features: Option<CargoFeaturesDef>  = None,
908        /// List of `cargo check` (or other command specified in `check.command`) diagnostics to ignore.
909        ///
910        /// For example for `cargo check`: `dead_code`, `unused_imports`, `unused_variables`,...
911        check_ignore: FxHashSet<String> = FxHashSet::default(),
912        /// Specifies the invocation strategy to use when running the check command.
913        /// If `per_workspace` is set, the command will be executed for each workspace.
914        /// If `once` is set, the command will be executed once.
915        /// This config only has an effect when `#rust-analyzer.check.overrideCommand#`
916        /// is set.
917        check_invocationStrategy | checkOnSave_invocationStrategy: InvocationStrategy = InvocationStrategy::PerWorkspace,
918        /// Whether to pass `--no-default-features` to Cargo. Defaults to
919        /// `#rust-analyzer.cargo.noDefaultFeatures#`.
920        check_noDefaultFeatures | checkOnSave_noDefaultFeatures: Option<bool>         = None,
921        /// Override the command rust-analyzer uses instead of `cargo check` for
922        /// diagnostics on save. The command is required to output json and
923        /// should therefore include `--message-format=json` or a similar option
924        /// (if your client supports the `colorDiagnosticOutput` experimental
925        /// capability, you can use `--message-format=json-diagnostic-rendered-ansi`).
926        ///
927        /// If you're changing this because you're using some tool wrapping
928        /// Cargo, you might also want to change
929        /// `#rust-analyzer.cargo.buildScripts.overrideCommand#`.
930        ///
931        /// If there are multiple linked projects/workspaces, this command is invoked for
932        /// each of them, with the working directory being the workspace root
933        /// (i.e., the folder containing the `Cargo.toml`). This can be overwritten
934        /// by changing `#rust-analyzer.check.invocationStrategy#`.
935        ///
936        /// It supports two interpolation syntaxes, both mainly intended to be used with
937        /// [non-Cargo build systems](./non_cargo_based_projects.md):
938        ///
939        /// - If `{saved_file}` is part of the command, rust-analyzer will pass
940        ///   the absolute path of the saved file to the provided command.
941        ///   (A previous version, `$saved_file`, also works.)
942        /// - If `{label}` is part of the command, rust-analyzer will pass the
943        ///   Cargo package ID, which can be used with `cargo check -p`, or a build label from
944        ///   `rust-project.json`. If `{label}` is included, rust-analyzer behaves much like
945        ///   [`"rust-analyzer.check.workspace": false`](#check.workspace).
946        ///
947        ///
948        ///
949        /// An example command would be:
950        ///
951        /// ```bash
952        /// cargo check --workspace --message-format=json --all-targets
953        /// ```
954        ///
955        /// Note: The option must be specified as an array of command line arguments, with
956        /// the first argument being the name of the command to run.
957        check_overrideCommand | checkOnSave_overrideCommand: Option<Vec<String>>             = None,
958        /// Check for specific targets. Defaults to `#rust-analyzer.cargo.target#` if empty.
959        ///
960        /// Can be a single target, e.g. `"x86_64-unknown-linux-gnu"` or a list of targets, e.g.
961        /// `["aarch64-apple-darwin", "x86_64-apple-darwin"]`.
962        ///
963        /// Aliased as `"checkOnSave.targets"`.
964        check_targets | checkOnSave_targets | checkOnSave_target: Option<CheckOnSaveTargets> = None,
965        /// Whether `--workspace` should be passed to `cargo check`.
966        /// If false, `-p <package>` will be passed instead if applicable. In case it is not, no
967        /// check will be performed.
968        check_workspace: bool = true,
969
970        /// Exclude all locals from document symbol search.
971        document_symbol_search_excludeLocals: bool = true,
972
973        /// These proc-macros will be ignored when trying to expand them.
974        ///
975        /// This config takes a map of crate names with the exported proc-macro names to ignore as values.
976        procMacro_ignored: FxHashMap<Box<str>, Box<[Box<str>]>>          = FxHashMap::default(),
977
978        /// Subcommand used for bench runnables instead of `bench`.
979        runnables_bench_command: String = "bench".to_owned(),
980        /// Override the command used for bench runnables.
981        /// The first element of the array should be the program to execute (for example, `cargo`).
982        ///
983        /// Use the placeholders:
984        /// - `${package}`: package name.
985        /// - `${target_arg}`: target option such as `--bin`, `--test`, `--lib`, etc.
986        /// - `${target}`: target name (empty for `--lib`).
987        /// - `${test_name}`: the test path filter, e.g. `module::bench_func`.
988        /// - `${exact}`: `--exact` for single benchmarks, empty for modules.
989        /// - `${include_ignored}`: always empty for benchmarks.
990        /// - `${executable_args}`: all of the above binary args bundled together
991        ///   (includes `rust-analyzer.runnables.extraTestBinaryArgs`).
992        runnables_bench_overrideCommand: Option<Vec<String>> = None,
993        /// Command to be executed instead of 'cargo' for runnables.
994        runnables_command: Option<String> = None,
995        /// Override the command used for doc-test runnables.
996        /// The first element of the array should be the program to execute (for example, `cargo`).
997        ///
998        /// Use the placeholders:
999        /// - `${package}`: package name.
1000        /// - `${target_arg}`: target option such as `--bin`, `--test`, `--lib`, etc.
1001        /// - `${target}`: target name (empty for `--lib`).
1002        /// - `${test_name}`: the test path filter, e.g. `module::func`.
1003        /// - `${exact}`: always empty for doc-tests.
1004        /// - `${include_ignored}`: always empty for doc-tests.
1005        /// - `${executable_args}`: all of the above binary args bundled together
1006        ///   (includes `rust-analyzer.runnables.extraTestBinaryArgs`).
1007        runnables_doctest_overrideCommand: Option<Vec<String>> = None,
1008        /// Additional arguments to be passed to cargo for runnables such as
1009        /// tests or binaries. For example, it may be `--release`.
1010        runnables_extraArgs: Vec<String>   = vec![],
1011        /// Additional arguments to be passed through Cargo to launched tests, benchmarks, or
1012        /// doc-tests.
1013        ///
1014        /// Unless the launched target uses a
1015        /// [custom test harness](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-harness-field),
1016        /// they will end up being interpreted as options to
1017        /// [`rustc`’s built-in test harness (“libtest”)](https://doc.rust-lang.org/rustc/tests/index.html#cli-arguments).
1018        runnables_extraTestBinaryArgs: Vec<String> = vec!["--nocapture".to_owned()],
1019        /// Subcommand used for test runnables instead of `test`.
1020        runnables_test_command: String = "test".to_owned(),
1021        /// Override the command used for test runnables.
1022        /// The first element of the array should be the program to execute (for example, `cargo`).
1023        ///
1024        /// Available placeholders:
1025        /// - `${package}`: package name.
1026        /// - `${target_arg}`: target option such as `--bin`, `--test`, `--lib`, etc.
1027        /// - `${target}`: target name (empty for `--lib`).
1028        /// - `${test_name}`: the test path filter, e.g. `module::test_func`.
1029        /// - `${exact}`: `--exact` for single tests, empty for modules.
1030        /// - `${include_ignored}`: `--include-ignored` for single tests, empty otherwise.
1031        /// - `${executable_args}`: all of the above binary args bundled together
1032        ///   (includes `rust-analyzer.runnables.extraTestBinaryArgs`).
1033        runnables_test_overrideCommand: Option<Vec<String>> = None,
1034
1035        /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
1036        /// projects, or "discover" to try to automatically find it if the `rustc-dev` component
1037        /// is installed.
1038        ///
1039        /// Any project which uses rust-analyzer with the rustcPrivate
1040        /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
1041        ///
1042        /// This option does not take effect until rust-analyzer is restarted.
1043        rustc_source: Option<String> = None,
1044
1045        /// Additional arguments to `rustfmt`.
1046        rustfmt_extraArgs: Vec<String>               = vec![],
1047        /// Advanced option, fully override the command rust-analyzer uses for
1048        /// formatting. This should be the equivalent of `rustfmt` here, and
1049        /// not that of `cargo fmt`. The file contents will be passed on the
1050        /// standard input and the formatted result will be read from the
1051        /// standard output.
1052        ///
1053        /// Note: The option must be specified as an array of command line arguments, with
1054        /// the first argument being the name of the command to run.
1055        rustfmt_overrideCommand: Option<Vec<String>> = None,
1056        /// Enables the use of rustfmt's unstable range formatting command for the
1057        /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
1058        /// available on a nightly build.
1059        rustfmt_rangeFormatting_enable: bool = false,
1060
1061        /// Additional paths to include in the VFS. Generally for code that is
1062        /// generated or otherwise managed by a build system outside of Cargo,
1063        /// though Cargo might be the eventual consumer.
1064        vfs_extraIncludes: Vec<String> = vec![],
1065
1066        /// Exclude all imports from workspace symbol search.
1067        ///
1068        /// In addition to regular imports (which are always excluded),
1069        /// this option removes public imports (better known as re-exports)
1070        /// and removes imports that rename the imported symbol.
1071        workspace_symbol_search_excludeImports: bool = false,
1072        /// Workspace symbol search kind.
1073        workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = WorkspaceSymbolSearchKindDef::OnlyTypes,
1074        /// Limits the number of items returned from a workspace symbol search (Defaults to 128).
1075        /// Some clients like vs-code issue new searches on result filtering and don't require all results to be returned in the initial search.
1076        /// Other clients requires all results upfront and might require a higher limit.
1077        workspace_symbol_search_limit: usize = 128,
1078        /// Workspace symbol search scope.
1079        workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = WorkspaceSymbolSearchScopeDef::Workspace,
1080    }
1081}
1082
1083config_data! {
1084    /// Configs that only make sense when they are set by a client. As such they can only be defined
1085    /// by setting them using client's settings (e.g `settings.json` on VS Code).
1086    client: struct ClientDefaultConfigData <- ClientConfigInput -> {
1087
1088        /// Controls file watching implementation.
1089        files_watcher: FilesWatcherDef = FilesWatcherDef::Client,
1090
1091
1092    }
1093}
1094
1095#[derive(Debug)]
1096pub enum RatomlFileKind {
1097    Workspace,
1098    Crate,
1099}
1100
1101#[derive(Debug, Clone)]
1102#[allow(clippy::large_enum_variant)]
1103enum RatomlFile {
1104    Workspace(WorkspaceLocalConfigInput),
1105    Crate(LocalConfigInput),
1106}
1107
1108#[derive(Clone, Debug)]
1109struct ClientInfo {
1110    name: String,
1111    version: Option<Version>,
1112}
1113
1114/// The configuration of this rust-analyzer instance.
1115#[derive(Clone)]
1116pub struct Config {
1117    /// Projects that have a Cargo.toml or a rust-project.json in a
1118    /// parent directory, so we can discover them by walking the
1119    /// file system.
1120    discovered_projects_from_filesystem: Vec<ProjectManifest>,
1121    /// Projects whose configuration was generated by a command
1122    /// configured in discoverConfig.
1123    discovered_projects_from_command: Vec<ProjectJsonFromCommand>,
1124    /// The workspace roots as registered by the LSP client.
1125    workspace_roots: Vec<AbsPathBuf>,
1126    caps: ClientCapabilities,
1127
1128    /// The root of the first project encountered. This is deprecated
1129    /// because rust-analyzer might be handling multiple projects.
1130    ///
1131    /// Prefer `workspace_roots` and `workspace_root_for()`.
1132    root_path: AbsPathBuf,
1133
1134    snippets: Vec<Snippet>,
1135    client_info: Option<ClientInfo>,
1136
1137    default_config: &'static DefaultConfigData,
1138    /// Config node that obtains its initial value during the server initialization and
1139    /// by receiving a [`lsp_types::DidChangeConfigurationNotification`].
1140    client_config: (FullConfigInput, ConfigErrors),
1141
1142    /// Config node whose values apply to **every** Rust project.
1143    user_config: Option<(GlobalWorkspaceLocalConfigInput, ConfigErrors)>,
1144
1145    ratoml_file: FxHashMap<SourceRootId, (RatomlFile, ConfigErrors)>,
1146
1147    /// Clone of the value that is stored inside a `GlobalState`.
1148    source_root_parent_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
1149
1150    /// Use case : It is an error to have an empty value for `check_command`.
1151    /// Since it is a `global` command at the moment, its final value can only be determined by
1152    /// traversing through `global` configs and the `client` config. However the non-null value constraint
1153    /// is config level agnostic, so this requires an independent error storage
1154    validation_errors: ConfigErrors,
1155
1156    detached_files: Vec<AbsPathBuf>,
1157}
1158
1159impl fmt::Debug for Config {
1160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1161        f.debug_struct("Config")
1162            .field("discovered_projects_from_filesystem", &self.discovered_projects_from_filesystem)
1163            .field("discovered_projects_from_command", &self.discovered_projects_from_command)
1164            .field("workspace_roots", &self.workspace_roots)
1165            .field("caps", &self.caps)
1166            .field("root_path", &self.root_path)
1167            .field("snippets", &self.snippets)
1168            .field("client_info", &self.client_info)
1169            .field("client_config", &self.client_config)
1170            .field("user_config", &self.user_config)
1171            .field("ratoml_file", &self.ratoml_file)
1172            .field("source_root_parent_map", &self.source_root_parent_map)
1173            .field("validation_errors", &self.validation_errors)
1174            .field("detached_files", &self.detached_files)
1175            .finish()
1176    }
1177}
1178
1179// Delegate capability fetching methods
1180impl std::ops::Deref for Config {
1181    type Target = ClientCapabilities;
1182
1183    fn deref(&self) -> &Self::Target {
1184        &self.caps
1185    }
1186}
1187
1188impl Config {
1189    /// Path to the user configuration dir. This can be seen as a generic way to define what would be `$XDG_CONFIG_HOME/rust-analyzer` in Linux.
1190    pub fn user_config_dir_path() -> Option<AbsPathBuf> {
1191        let user_config_path = if let Some(path) = env::var_os("__TEST_RA_USER_CONFIG_DIR") {
1192            std::path::PathBuf::from(path)
1193        } else {
1194            dirs::config_dir()?.join("rust-analyzer")
1195        };
1196        Some(AbsPathBuf::assert_utf8(user_config_path))
1197    }
1198
1199    pub fn same_source_root_parent_map(
1200        &self,
1201        other: &Arc<FxHashMap<SourceRootId, SourceRootId>>,
1202    ) -> bool {
1203        Arc::ptr_eq(&self.source_root_parent_map, other)
1204    }
1205
1206    // FIXME @alibektas : Server's health uses error sink but in other places it is not used atm.
1207    /// Changes made to client and global configurations will partially not be reflected even after `.apply_change()` was called.
1208    /// The return tuple's bool component signals whether the `GlobalState` should call its `update_configuration()` method.
1209    fn apply_change_with_sink(&self, change: ConfigChange) -> (Config, bool) {
1210        let mut config = self.clone();
1211        config.validation_errors = ConfigErrors::default();
1212
1213        let mut should_update = false;
1214
1215        if let Some(change) = change.user_config_change {
1216            tracing::info!("updating config from user config toml: {:#}", change);
1217            if let Ok(table) = toml::from_str(&change) {
1218                let mut toml_errors = vec![];
1219                validate_toml_table(
1220                    GlobalWorkspaceLocalConfigInput::FIELDS,
1221                    &table,
1222                    &mut String::new(),
1223                    &mut toml_errors,
1224                );
1225                config.user_config = Some((
1226                    GlobalWorkspaceLocalConfigInput::from_toml(table, &mut toml_errors),
1227                    ConfigErrors(
1228                        toml_errors
1229                            .into_iter()
1230                            .map(|(a, b)| ConfigErrorInner::Toml { config_key: a, error: b })
1231                            .map(Arc::new)
1232                            .collect(),
1233                    ),
1234                ));
1235                should_update = true;
1236            }
1237        }
1238
1239        if let Some(mut json) = change.client_config_change {
1240            tracing::info!("updating config from JSON: {:#}", json);
1241
1242            if !(json.is_null() || json.as_object().is_some_and(|it| it.is_empty())) {
1243                let detached_files = get_field_json::<Vec<Utf8PathBuf>>(
1244                    &mut json,
1245                    &mut Vec::new(),
1246                    "detachedFiles",
1247                    None,
1248                )
1249                .unwrap_or_default()
1250                .into_iter()
1251                .map(AbsPathBuf::assert)
1252                .collect();
1253
1254                patch_old_style::patch_json_for_outdated_configs(&mut json);
1255
1256                let mut json_errors = vec![];
1257
1258                let input = FullConfigInput::from_json(json, &mut json_errors);
1259
1260                // IMPORTANT : This holds as long as ` completion_snippets_custom` is declared `client`.
1261                config.snippets.clear();
1262
1263                let snips = input
1264                    .global
1265                    .completion_snippets_custom
1266                    .as_ref()
1267                    .unwrap_or(&self.default_config.global.completion_snippets_custom);
1268                #[allow(dead_code)]
1269                let _ = Self::completion_snippets_custom;
1270                for (name, def) in snips.iter() {
1271                    if def.prefix.is_empty() && def.postfix.is_empty() {
1272                        continue;
1273                    }
1274                    let scope = match def.scope {
1275                        SnippetScopeDef::Expr => SnippetScope::Expr,
1276                        SnippetScopeDef::Type => SnippetScope::Type,
1277                        SnippetScopeDef::Item => SnippetScope::Item,
1278                    };
1279                    match Snippet::new(
1280                        &def.prefix,
1281                        &def.postfix,
1282                        &def.body,
1283                        def.description.as_ref().unwrap_or(name),
1284                        &def.requires,
1285                        scope,
1286                    ) {
1287                        Some(snippet) => config.snippets.push(snippet),
1288                        None => json_errors.push((
1289                            name.to_owned(),
1290                            <serde_json::Error as serde::de::Error>::custom(format!(
1291                                "snippet {name} is invalid or triggers are missing",
1292                            )),
1293                        )),
1294                    }
1295                }
1296
1297                config.client_config = (
1298                    input,
1299                    ConfigErrors(
1300                        json_errors
1301                            .into_iter()
1302                            .map(|(a, b)| ConfigErrorInner::Json { config_key: a, error: b })
1303                            .map(Arc::new)
1304                            .collect(),
1305                    ),
1306                );
1307                config.detached_files = detached_files;
1308            }
1309            should_update = true;
1310        }
1311
1312        if let Some(change) = change.ratoml_file_change {
1313            for (source_root_id, (kind, _, text)) in change {
1314                match kind {
1315                    RatomlFileKind::Crate => {
1316                        if let Some(text) = text {
1317                            let mut toml_errors = vec![];
1318                            tracing::info!("updating ra-toml crate config: {:#}", text);
1319                            match toml::from_str(&text) {
1320                                Ok(table) => {
1321                                    validate_toml_table(
1322                                        &[LocalConfigInput::FIELDS],
1323                                        &table,
1324                                        &mut String::new(),
1325                                        &mut toml_errors,
1326                                    );
1327                                    config.ratoml_file.insert(
1328                                        source_root_id,
1329                                        (
1330                                            RatomlFile::Crate(LocalConfigInput::from_toml(
1331                                                &table,
1332                                                &mut toml_errors,
1333                                            )),
1334                                            ConfigErrors(
1335                                                toml_errors
1336                                                    .into_iter()
1337                                                    .map(|(a, b)| ConfigErrorInner::Toml {
1338                                                        config_key: a,
1339                                                        error: b,
1340                                                    })
1341                                                    .map(Arc::new)
1342                                                    .collect(),
1343                                            ),
1344                                        ),
1345                                    );
1346                                }
1347                                Err(e) => {
1348                                    config.validation_errors.0.push(
1349                                        ConfigErrorInner::ParseError {
1350                                            reason: e.message().to_owned(),
1351                                        }
1352                                        .into(),
1353                                    );
1354                                }
1355                            }
1356                        }
1357                    }
1358                    RatomlFileKind::Workspace => {
1359                        if let Some(text) = text {
1360                            tracing::info!("updating ra-toml workspace config: {:#}", text);
1361                            let mut toml_errors = vec![];
1362                            match toml::from_str(&text) {
1363                                Ok(table) => {
1364                                    validate_toml_table(
1365                                        WorkspaceLocalConfigInput::FIELDS,
1366                                        &table,
1367                                        &mut String::new(),
1368                                        &mut toml_errors,
1369                                    );
1370                                    config.ratoml_file.insert(
1371                                        source_root_id,
1372                                        (
1373                                            RatomlFile::Workspace(
1374                                                WorkspaceLocalConfigInput::from_toml(
1375                                                    table,
1376                                                    &mut toml_errors,
1377                                                ),
1378                                            ),
1379                                            ConfigErrors(
1380                                                toml_errors
1381                                                    .into_iter()
1382                                                    .map(|(a, b)| ConfigErrorInner::Toml {
1383                                                        config_key: a,
1384                                                        error: b,
1385                                                    })
1386                                                    .map(Arc::new)
1387                                                    .collect(),
1388                                            ),
1389                                        ),
1390                                    );
1391                                    should_update = true;
1392                                }
1393                                Err(e) => {
1394                                    config.validation_errors.0.push(
1395                                        ConfigErrorInner::ParseError {
1396                                            reason: e.message().to_owned(),
1397                                        }
1398                                        .into(),
1399                                    );
1400                                }
1401                            }
1402                        }
1403                    }
1404                }
1405            }
1406        }
1407
1408        if let Some(source_root_map) = change.source_map_change {
1409            config.source_root_parent_map = source_root_map;
1410        }
1411
1412        if config.check_command(None).is_empty() {
1413            config.validation_errors.0.push(Arc::new(ConfigErrorInner::Json {
1414                config_key: "/check/command".to_owned(),
1415                error: serde_json::Error::custom("expected a non-empty string"),
1416            }));
1417        }
1418
1419        (config, should_update)
1420    }
1421
1422    /// Given `change` this generates a new `Config`, thereby collecting errors of type `ConfigError`.
1423    /// If there are changes that have global/client level effect, the last component of the return type
1424    /// will be set to `true`, which should be used by the `GlobalState` to update itself.
1425    pub fn apply_change(&self, change: ConfigChange) -> (Config, ConfigErrors, bool) {
1426        let (config, should_update) = self.apply_change_with_sink(change);
1427        let e = ConfigErrors(
1428            config
1429                .client_config
1430                .1
1431                .0
1432                .iter()
1433                .chain(config.user_config.as_ref().into_iter().flat_map(|it| it.1.0.iter()))
1434                .chain(config.ratoml_file.values().flat_map(|it| it.1.0.iter()))
1435                .chain(config.validation_errors.0.iter())
1436                .cloned()
1437                .collect(),
1438        );
1439        (config, e, should_update)
1440    }
1441
1442    pub fn add_discovered_project_from_command(
1443        &mut self,
1444        data: ProjectJsonData,
1445        buildfile: AbsPathBuf,
1446    ) {
1447        for proj in self.discovered_projects_from_command.iter_mut() {
1448            if proj.buildfile == buildfile {
1449                proj.data = data;
1450                return;
1451            }
1452        }
1453
1454        self.discovered_projects_from_command.push(ProjectJsonFromCommand { data, buildfile });
1455    }
1456
1457    pub fn workspace_roots(&self) -> &[AbsPathBuf] {
1458        &self.workspace_roots
1459    }
1460}
1461
1462#[derive(Default, Debug)]
1463pub struct ConfigChange {
1464    user_config_change: Option<Arc<str>>,
1465    client_config_change: Option<serde_json::Value>,
1466    ratoml_file_change:
1467        Option<FxHashMap<SourceRootId, (RatomlFileKind, VfsPath, Option<Arc<str>>)>>,
1468    source_map_change: Option<Arc<FxHashMap<SourceRootId, SourceRootId>>>,
1469}
1470
1471impl ConfigChange {
1472    pub fn change_ratoml(
1473        &mut self,
1474        source_root: SourceRootId,
1475        vfs_path: VfsPath,
1476        content: Option<Arc<str>>,
1477    ) -> Option<(RatomlFileKind, VfsPath, Option<Arc<str>>)> {
1478        self.ratoml_file_change
1479            .get_or_insert_with(Default::default)
1480            .insert(source_root, (RatomlFileKind::Crate, vfs_path, content))
1481    }
1482
1483    pub fn change_user_config(&mut self, content: Option<Arc<str>>) {
1484        assert!(self.user_config_change.is_none()); // Otherwise it is a double write.
1485        self.user_config_change = content;
1486    }
1487
1488    pub fn change_workspace_ratoml(
1489        &mut self,
1490        source_root: SourceRootId,
1491        vfs_path: VfsPath,
1492        content: Option<Arc<str>>,
1493    ) -> Option<(RatomlFileKind, VfsPath, Option<Arc<str>>)> {
1494        self.ratoml_file_change
1495            .get_or_insert_with(Default::default)
1496            .insert(source_root, (RatomlFileKind::Workspace, vfs_path, content))
1497    }
1498
1499    pub fn change_client_config(&mut self, change: serde_json::Value) {
1500        self.client_config_change = Some(change);
1501    }
1502
1503    pub fn change_source_root_parent_map(
1504        &mut self,
1505        source_root_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
1506    ) {
1507        assert!(self.source_map_change.is_none());
1508        self.source_map_change = Some(source_root_map);
1509    }
1510}
1511
1512#[derive(Debug, Clone, Eq, PartialEq)]
1513pub enum LinkedProject {
1514    ProjectManifest(ProjectManifest),
1515    InlineProjectJson(ProjectJson),
1516}
1517
1518impl From<ProjectManifest> for LinkedProject {
1519    fn from(v: ProjectManifest) -> Self {
1520        LinkedProject::ProjectManifest(v)
1521    }
1522}
1523
1524impl From<ProjectJson> for LinkedProject {
1525    fn from(v: ProjectJson) -> Self {
1526        LinkedProject::InlineProjectJson(v)
1527    }
1528}
1529
1530#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1531#[serde(rename_all = "camelCase")]
1532pub struct DiscoverWorkspaceConfig {
1533    pub command: Vec<String>,
1534    pub progress_label: String,
1535    pub files_to_watch: Vec<String>,
1536}
1537
1538pub struct CallInfoConfig {
1539    pub params_only: bool,
1540    pub docs: bool,
1541}
1542
1543#[derive(Clone, Debug, PartialEq, Eq)]
1544pub struct LensConfig {
1545    // runnables
1546    pub run: bool,
1547    pub debug: bool,
1548    pub update_test: bool,
1549    pub interpret: bool,
1550
1551    // implementations
1552    pub implementations: bool,
1553
1554    // references
1555    pub method_refs: bool,
1556    pub refs_adt: bool,   // for Struct, Enum, Union and Trait
1557    pub refs_trait: bool, // for Struct, Enum, Union and Trait
1558    pub enum_variant_refs: bool,
1559
1560    pub refs_exclude_imports: bool,
1561    pub refs_exclude_tests: bool,
1562
1563    // annotations
1564    pub location: AnnotationLocation,
1565    pub filter_adjacent_derive_implementations: bool,
1566
1567    disable_ra_fixture: bool,
1568}
1569
1570#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1571#[serde(rename_all = "snake_case")]
1572pub enum AnnotationLocation {
1573    AboveName,
1574    AboveWholeItem,
1575}
1576
1577impl From<AnnotationLocation> for ide::AnnotationLocation {
1578    fn from(location: AnnotationLocation) -> Self {
1579        match location {
1580            AnnotationLocation::AboveName => ide::AnnotationLocation::AboveName,
1581            AnnotationLocation::AboveWholeItem => ide::AnnotationLocation::AboveWholeItem,
1582        }
1583    }
1584}
1585
1586impl LensConfig {
1587    pub fn any(&self) -> bool {
1588        self.run
1589            || self.debug
1590            || self.update_test
1591            || self.implementations
1592            || self.method_refs
1593            || self.refs_adt
1594            || self.refs_trait
1595            || self.enum_variant_refs
1596    }
1597
1598    pub fn none(&self) -> bool {
1599        !self.any()
1600    }
1601
1602    pub fn runnable(&self) -> bool {
1603        self.run || self.debug || self.update_test
1604    }
1605
1606    pub fn into_annotation_config<'a>(
1607        self,
1608        binary_target: bool,
1609        minicore: MiniCore<'a>,
1610    ) -> AnnotationConfig<'a> {
1611        AnnotationConfig {
1612            binary_target,
1613            annotate_runnables: self.runnable(),
1614            annotate_impls: self.implementations,
1615            annotate_references: self.refs_adt,
1616            annotate_method_references: self.method_refs,
1617            annotate_enum_variant_references: self.enum_variant_refs,
1618            references_exclude_imports: self.refs_exclude_imports,
1619            references_exclude_tests: self.refs_exclude_tests,
1620            location: self.location.into(),
1621            ra_fixture: RaFixtureConfig { minicore, disable_ra_fixture: self.disable_ra_fixture },
1622            filter_adjacent_derive_implementations: self.filter_adjacent_derive_implementations,
1623        }
1624    }
1625}
1626
1627#[derive(Clone, Debug, PartialEq, Eq)]
1628pub struct HoverActionsConfig {
1629    pub implementations: bool,
1630    pub references: bool,
1631    pub run: bool,
1632    pub debug: bool,
1633    pub update_test: bool,
1634    pub goto_type_def: bool,
1635}
1636
1637impl HoverActionsConfig {
1638    pub const NO_ACTIONS: Self = Self {
1639        implementations: false,
1640        references: false,
1641        run: false,
1642        debug: false,
1643        update_test: false,
1644        goto_type_def: false,
1645    };
1646
1647    pub fn any(&self) -> bool {
1648        self.implementations || self.references || self.runnable() || self.goto_type_def
1649    }
1650
1651    pub fn none(&self) -> bool {
1652        !self.any()
1653    }
1654
1655    pub fn runnable(&self) -> bool {
1656        self.run || self.debug || self.update_test
1657    }
1658}
1659
1660#[derive(Debug, Clone)]
1661pub struct FilesConfig {
1662    pub watcher: FilesWatcher,
1663    pub exclude: Vec<AbsPathBuf>,
1664}
1665
1666#[derive(Debug, Clone)]
1667pub enum FilesWatcher {
1668    Client,
1669    Server,
1670}
1671
1672/// Configuration for document symbol search requests.
1673#[derive(Debug, Clone)]
1674pub struct DocumentSymbolConfig {
1675    /// Should locals be excluded.
1676    pub search_exclude_locals: bool,
1677}
1678
1679#[derive(Debug, Clone)]
1680pub struct NotificationsConfig {
1681    pub cargo_toml_not_found: bool,
1682}
1683
1684#[derive(Debug, Clone)]
1685pub enum RustfmtConfig {
1686    Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
1687    CustomCommand { command: String, args: Vec<String> },
1688}
1689
1690/// Configuration for runnable items, such as `main` function or tests.
1691#[derive(Debug, Clone)]
1692pub struct RunnablesConfig {
1693    /// Custom command to be executed instead of `cargo` for runnables.
1694    pub override_cargo: Option<String>,
1695    /// Additional arguments for the `cargo`, e.g. `--release`.
1696    pub cargo_extra_args: Vec<String>,
1697    /// Path to an extra config file passed to cargo via `--config`.
1698    pub config_path: Option<AbsPathBuf>,
1699    /// Additional arguments for the binary being run, if it is a test or benchmark.
1700    pub extra_test_binary_args: Vec<String>,
1701    /// Subcommand used for doctest runnables instead of `test`.
1702    pub test_command: String,
1703    /// Override the command used for test runnables.
1704    pub test_override_command: Option<Vec<String>>,
1705    /// Subcommand used for doctest runnables instead of `bench`.
1706    pub bench_command: String,
1707    /// Override the command used for bench runnables.
1708    pub bench_override_command: Option<Vec<String>>,
1709    /// Override the command used for doctest runnables.
1710    pub doc_test_override_command: Option<Vec<String>>,
1711}
1712
1713/// Configuration for workspace symbol search requests.
1714#[derive(Debug, Clone)]
1715pub struct WorkspaceSymbolConfig {
1716    /// Should imports be excluded.
1717    pub search_exclude_imports: bool,
1718    /// In what scope should the symbol be searched in.
1719    pub search_scope: WorkspaceSymbolSearchScope,
1720    /// What kind of symbol is being searched for.
1721    pub search_kind: WorkspaceSymbolSearchKind,
1722    /// How many items are returned at most.
1723    pub search_limit: usize,
1724}
1725#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1726pub struct ClientCommandsConfig {
1727    pub run_single: bool,
1728    pub debug_single: bool,
1729    pub show_reference: bool,
1730    pub goto_location: bool,
1731    pub trigger_parameter_hints: bool,
1732    pub rename: bool,
1733}
1734
1735#[derive(Debug)]
1736pub enum ConfigErrorInner {
1737    Json { config_key: String, error: serde_json::Error },
1738    Toml { config_key: String, error: toml::de::Error },
1739    ParseError { reason: String },
1740}
1741
1742#[derive(Clone, Debug, Default)]
1743pub struct ConfigErrors(Vec<Arc<ConfigErrorInner>>);
1744
1745impl ConfigErrors {
1746    pub fn is_empty(&self) -> bool {
1747        self.0.is_empty()
1748    }
1749}
1750
1751impl fmt::Display for ConfigErrors {
1752    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1753        let errors = self.0.iter().format_with("\n", |inner, f| {
1754            match &**inner {
1755                ConfigErrorInner::Json { config_key: key, error: e } => {
1756                    f(key)?;
1757                    f(&": ")?;
1758                    f(e)
1759                }
1760                ConfigErrorInner::Toml { config_key: key, error: e } => {
1761                    f(key)?;
1762                    f(&": ")?;
1763                    f(e)
1764                }
1765                ConfigErrorInner::ParseError { reason } => f(reason),
1766            }?;
1767            f(&";")
1768        });
1769        write!(f, "invalid config value{}:\n{}", if self.0.len() == 1 { "" } else { "s" }, errors)
1770    }
1771}
1772
1773impl std::error::Error for ConfigErrors {}
1774
1775impl Config {
1776    pub fn new(
1777        root_path: AbsPathBuf,
1778        caps: lsp_types::ClientCapabilities,
1779        workspace_roots: Vec<AbsPathBuf>,
1780        client_info: Option<lsp_types::ClientInfo>,
1781    ) -> Self {
1782        static DEFAULT_CONFIG_DATA: OnceLock<&'static DefaultConfigData> = OnceLock::new();
1783
1784        Config {
1785            caps: ClientCapabilities::new(caps),
1786            discovered_projects_from_filesystem: Vec::new(),
1787            discovered_projects_from_command: Vec::new(),
1788            root_path,
1789            snippets: Default::default(),
1790            workspace_roots,
1791            client_info: client_info.map(|it| ClientInfo {
1792                name: it.name,
1793                version: it.version.as_deref().map(Version::parse).and_then(Result::ok),
1794            }),
1795            client_config: (FullConfigInput::default(), ConfigErrors(vec![])),
1796            default_config: DEFAULT_CONFIG_DATA.get_or_init(|| Box::leak(Box::default())),
1797            source_root_parent_map: Arc::new(FxHashMap::default()),
1798            user_config: None,
1799            detached_files: Default::default(),
1800            validation_errors: Default::default(),
1801            ratoml_file: Default::default(),
1802        }
1803    }
1804
1805    pub fn rediscover_workspaces(&mut self) {
1806        let discovered = ProjectManifest::discover_all(&self.workspace_roots);
1807        tracing::info!("discovered projects: {:?}", discovered);
1808        if discovered.is_empty() {
1809            tracing::error!("failed to find any projects in {:?}", &self.workspace_roots);
1810        }
1811        self.discovered_projects_from_filesystem = discovered;
1812    }
1813
1814    pub fn remove_workspace(&mut self, path: &AbsPath) {
1815        if let Some(position) = self.workspace_roots.iter().position(|it| it == path) {
1816            self.workspace_roots.remove(position);
1817        }
1818    }
1819
1820    pub fn add_workspaces(&mut self, paths: impl Iterator<Item = AbsPathBuf>) {
1821        self.workspace_roots.extend(paths);
1822    }
1823
1824    pub fn json_schema() -> serde_json::Value {
1825        let mut s = FullConfigInput::json_schema();
1826
1827        fn sort_objects_by_field(json: &mut serde_json::Value) {
1828            if let serde_json::Value::Object(object) = json {
1829                let old = std::mem::take(object);
1830                old.into_iter().sorted_by(|(k, _), (k2, _)| k.cmp(k2)).for_each(|(k, mut v)| {
1831                    sort_objects_by_field(&mut v);
1832                    object.insert(k, v);
1833                });
1834            }
1835        }
1836        sort_objects_by_field(&mut s);
1837        s
1838    }
1839
1840    /// Find the workspace root that contains the given path, using the
1841    /// longest prefix match.
1842    pub fn workspace_root_for(&self, path: &AbsPath) -> &AbsPathBuf {
1843        self.workspace_roots
1844            .iter()
1845            .filter(|root| path.starts_with(root.as_path()))
1846            .max_by_key(|root| root.as_str().len())
1847            .unwrap_or(self.default_root_path())
1848    }
1849
1850    /// Best-effort root path for the current project.
1851    ///
1852    /// Use `workspace_root_for` where possible, because
1853    /// `default_root_path` may return the wrong path when a user has
1854    /// multiple workspaces.
1855    pub fn default_root_path(&self) -> &AbsPathBuf {
1856        self.workspace_roots.first().unwrap_or(&self.root_path)
1857    }
1858
1859    pub fn caps(&self) -> &ClientCapabilities {
1860        &self.caps
1861    }
1862
1863    pub fn assist(&self, source_root: Option<SourceRootId>) -> AssistConfig {
1864        AssistConfig {
1865            snippet_cap: self.snippet_cap(),
1866            allowed: None,
1867            insert_use: self.insert_use_config(source_root),
1868            prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
1869            assist_emit_must_use: self.assist_emitMustUse(source_root).to_owned(),
1870            prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
1871            prefer_absolute: self.imports_prefixExternPrelude(source_root).to_owned(),
1872            term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
1873            code_action_grouping: self.code_action_group(),
1874            expr_fill_default: match self.assist_expressionFillDefault(source_root) {
1875                ExprFillDefaultDef::Todo => ExprFillDefaultMode::Todo,
1876                ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
1877                ExprFillDefaultDef::Underscore => ExprFillDefaultMode::Underscore,
1878            },
1879            prefer_self_ty: *self.assist_preferSelf(source_root),
1880            show_rename_conflicts: *self.rename_showConflicts(source_root),
1881        }
1882    }
1883
1884    pub fn rename(&self, source_root: Option<SourceRootId>) -> RenameConfig {
1885        RenameConfig {
1886            prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
1887            prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
1888            prefer_absolute: self.imports_prefixExternPrelude(source_root).to_owned(),
1889            show_conflicts: *self.rename_showConflicts(source_root),
1890        }
1891    }
1892
1893    pub fn ra_fixture<'a>(&self, minicore: MiniCore<'a>) -> RaFixtureConfig<'a> {
1894        RaFixtureConfig { minicore, disable_ra_fixture: *self.disableFixtureSupport(None) }
1895    }
1896
1897    pub fn call_hierarchy<'a>(&self, minicore: MiniCore<'a>) -> CallHierarchyConfig<'a> {
1898        CallHierarchyConfig {
1899            exclude_tests: self.references_excludeTests().to_owned(),
1900            ra_fixture: self.ra_fixture(minicore),
1901        }
1902    }
1903
1904    pub fn completion<'a>(
1905        &'a self,
1906        source_root: Option<SourceRootId>,
1907        minicore: MiniCore<'a>,
1908    ) -> CompletionConfig<'a> {
1909        let client_capability_fields = self.completion_resolve_support_properties();
1910        CompletionConfig {
1911            enable_postfix_completions: self.completion_postfix_enable(source_root).to_owned(),
1912            enable_imports_on_the_fly: self.completion_autoimport_enable(source_root).to_owned()
1913                && self.caps.has_completion_item_resolve_additionalTextEdits(),
1914            enable_self_on_the_fly: self.completion_autoself_enable(source_root).to_owned(),
1915            enable_auto_iter: *self.completion_autoIter_enable(source_root),
1916            enable_auto_await: *self.completion_autoAwait_enable(source_root),
1917            enable_auto_dyn: *self.completion_autoDyn_enable(source_root),
1918            enable_private_editable: self.completion_privateEditable_enable(source_root).to_owned(),
1919            full_function_signatures: self
1920                .completion_fullFunctionSignatures_enable(source_root)
1921                .to_owned(),
1922            callable: match self.completion_callable_snippets(source_root) {
1923                CallableCompletionDef::FillArguments => Some(CallableSnippets::FillArguments),
1924                CallableCompletionDef::AddParentheses => Some(CallableSnippets::AddParentheses),
1925                CallableCompletionDef::None => None,
1926            },
1927            add_colons_to_module: *self.completion_addColonsToModule(source_root),
1928            add_semicolon_to_unit: *self.completion_addSemicolonToUnit(source_root),
1929            snippet_cap: SnippetCap::new(self.completion_snippet()),
1930            insert_use: self.insert_use_config(source_root),
1931            prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
1932            prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
1933            prefer_absolute: self.imports_prefixExternPrelude(source_root).to_owned(),
1934            snippets: self.snippets.clone().to_vec(),
1935            limit: self.completion_limit(source_root).to_owned(),
1936            enable_term_search: self.completion_termSearch_enable(source_root).to_owned(),
1937            term_search_fuel: self.completion_termSearch_fuel(source_root).to_owned() as u64,
1938            enable_turbofish: self.completion_turbofish_enable(source_root).to_owned(),
1939            fields_to_resolve: if self.client_is_neovim() {
1940                CompletionFieldsToResolve::empty()
1941            } else {
1942                CompletionFieldsToResolve::from_client_capabilities(&client_capability_fields)
1943            },
1944            exclude_flyimport: self
1945                .completion_autoimport_exclude(source_root)
1946                .iter()
1947                .map(|it| match it {
1948                    AutoImportExclusion::Path(path) => {
1949                        (path.clone(), ide_completion::AutoImportExclusionType::Always)
1950                    }
1951                    AutoImportExclusion::Verbose { path, r#type } => (
1952                        path.clone(),
1953                        match r#type {
1954                            AutoImportExclusionType::Always => {
1955                                ide_completion::AutoImportExclusionType::Always
1956                            }
1957                            AutoImportExclusionType::Methods => {
1958                                ide_completion::AutoImportExclusionType::Methods
1959                            }
1960                            AutoImportExclusionType::SubItems => {
1961                                ide_completion::AutoImportExclusionType::SubItems
1962                            }
1963                            AutoImportExclusionType::Variants => {
1964                                ide_completion::AutoImportExclusionType::Variants
1965                            }
1966                        },
1967                    ),
1968                })
1969                .collect(),
1970            exclude_traits: self.completion_excludeTraits(source_root),
1971            ra_fixture: self.ra_fixture(minicore),
1972        }
1973    }
1974
1975    pub fn completion_hide_deprecated(&self) -> bool {
1976        *self.completion_hideDeprecated(None)
1977    }
1978
1979    pub fn detached_files(&self) -> &Vec<AbsPathBuf> {
1980        // FIXME @alibektas : This is the only config that is confusing. If it's a proper configuration
1981        // why is it not among the others? If it's client only which I doubt it is current state should be alright
1982        &self.detached_files
1983    }
1984
1985    pub fn diagnostics(&self, source_root: Option<SourceRootId>) -> DiagnosticsConfig {
1986        DiagnosticsConfig {
1987            enabled: *self.diagnostics_enable(source_root),
1988            proc_attr_macros_enabled: self.expand_proc_attr_macros(),
1989            proc_macros_enabled: *self.procMacro_enable(),
1990            disable_experimental: !self.diagnostics_experimental_enable(source_root),
1991            disabled: self.diagnostics_disabled(source_root).clone(),
1992            expr_fill_default: match self.assist_expressionFillDefault(source_root) {
1993                ExprFillDefaultDef::Todo => ExprFillDefaultMode::Todo,
1994                ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
1995                ExprFillDefaultDef::Underscore => ExprFillDefaultMode::Underscore,
1996            },
1997            snippet_cap: self.snippet_cap(),
1998            insert_use: self.insert_use_config(source_root),
1999            prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
2000            prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
2001            prefer_absolute: self.imports_prefixExternPrelude(source_root).to_owned(),
2002            style_lints: self.diagnostics_styleLints_enable(source_root).to_owned(),
2003            term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
2004            show_rename_conflicts: *self.rename_showConflicts(source_root),
2005        }
2006    }
2007
2008    pub fn diagnostic_fixes(&self, source_root: Option<SourceRootId>) -> DiagnosticsConfig {
2009        // We always want to show quickfixes for diagnostics, even when diagnostics/experimental diagnostics are disabled.
2010        DiagnosticsConfig {
2011            enabled: true,
2012            disable_experimental: false,
2013            ..self.diagnostics(source_root)
2014        }
2015    }
2016
2017    pub fn expand_proc_attr_macros(&self) -> bool {
2018        self.procMacro_enable().to_owned() && self.procMacro_attributes_enable().to_owned()
2019    }
2020
2021    pub fn highlight_related(&self, _source_root: Option<SourceRootId>) -> HighlightRelatedConfig {
2022        HighlightRelatedConfig {
2023            references: self.highlightRelated_references_enable().to_owned(),
2024            break_points: self.highlightRelated_breakPoints_enable().to_owned(),
2025            exit_points: self.highlightRelated_exitPoints_enable().to_owned(),
2026            yield_points: self.highlightRelated_yieldPoints_enable().to_owned(),
2027            closure_captures: self.highlightRelated_closureCaptures_enable().to_owned(),
2028            branch_exit_points: self.highlightRelated_branchExitPoints_enable().to_owned(),
2029        }
2030    }
2031
2032    pub fn hover_actions(&self) -> HoverActionsConfig {
2033        let enable = self.caps.hover_actions() && self.hover_actions_enable().to_owned();
2034        HoverActionsConfig {
2035            implementations: enable && self.hover_actions_implementations_enable().to_owned(),
2036            references: enable && self.hover_actions_references_enable().to_owned(),
2037            run: enable && self.hover_actions_run_enable().to_owned(),
2038            debug: enable && self.hover_actions_debug_enable().to_owned(),
2039            update_test: enable
2040                && self.hover_actions_run_enable().to_owned()
2041                && self.hover_actions_updateTest_enable().to_owned(),
2042            goto_type_def: enable && self.hover_actions_gotoTypeDef_enable().to_owned(),
2043        }
2044    }
2045
2046    pub fn hover<'a>(&self, minicore: MiniCore<'a>) -> HoverConfig<'a> {
2047        let mem_kind = |kind| match kind {
2048            MemoryLayoutHoverRenderKindDef::Both => MemoryLayoutHoverRenderKind::Both,
2049            MemoryLayoutHoverRenderKindDef::Decimal => MemoryLayoutHoverRenderKind::Decimal,
2050            MemoryLayoutHoverRenderKindDef::Hexadecimal => MemoryLayoutHoverRenderKind::Hexadecimal,
2051        };
2052        HoverConfig {
2053            links_in_hover: self.hover_links_enable().to_owned(),
2054            memory_layout: self.hover_memoryLayout_enable().then_some(MemoryLayoutHoverConfig {
2055                size: self.hover_memoryLayout_size().map(mem_kind),
2056                offset: self.hover_memoryLayout_offset().map(mem_kind),
2057                alignment: self.hover_memoryLayout_alignment().map(mem_kind),
2058                padding: self.hover_memoryLayout_padding().map(mem_kind),
2059                niches: self.hover_memoryLayout_niches().unwrap_or_default(),
2060            }),
2061            documentation: self.hover_documentation_enable().to_owned(),
2062            format: {
2063                if self.caps.hover_markdown_support() {
2064                    HoverDocFormat::Markdown
2065                } else {
2066                    HoverDocFormat::PlainText
2067                }
2068            },
2069            keywords: self.hover_documentation_keywords_enable().to_owned(),
2070            max_trait_assoc_items_count: self.hover_show_traitAssocItems().to_owned(),
2071            max_fields_count: self.hover_show_fields().to_owned(),
2072            max_enum_variants_count: self.hover_show_enumVariants().to_owned(),
2073            max_subst_ty_len: match self.hover_maxSubstitutionLength() {
2074                Some(MaxSubstitutionLength::Hide) => ide::SubstTyLen::Hide,
2075                Some(MaxSubstitutionLength::Limit(limit)) => ide::SubstTyLen::LimitTo(*limit),
2076                None => ide::SubstTyLen::Unlimited,
2077            },
2078            show_drop_glue: *self.hover_dropGlue_enable(),
2079            ra_fixture: self.ra_fixture(minicore),
2080        }
2081    }
2082
2083    pub fn goto_definition<'a>(&self, minicore: MiniCore<'a>) -> GotoDefinitionConfig<'a> {
2084        GotoDefinitionConfig { ra_fixture: self.ra_fixture(minicore) }
2085    }
2086
2087    pub fn inlay_hints<'a>(&self, minicore: MiniCore<'a>) -> InlayHintsConfig<'a> {
2088        let client_capability_fields = self.inlay_hint_resolve_support_properties();
2089
2090        InlayHintsConfig {
2091            render_colons: self.inlayHints_renderColons().to_owned(),
2092            type_hints: self.inlayHints_typeHints_enable().to_owned(),
2093            type_hints_placement: match self.inlayHints_typeHints_location() {
2094                TypeHintsLocation::Inline => ide::TypeHintsPlacement::Inline,
2095                TypeHintsLocation::EndOfLine => ide::TypeHintsPlacement::EndOfLine,
2096            },
2097            sized_bound: self.inlayHints_implicitSizedBoundHints_enable().to_owned(),
2098            parameter_hints: self.inlayHints_parameterHints_enable().to_owned(),
2099            parameter_hints_for_missing_arguments: self
2100                .inlayHints_parameterHints_missingArguments_enable()
2101                .to_owned(),
2102            generic_parameter_hints: GenericParameterHints {
2103                type_hints: self.inlayHints_genericParameterHints_type_enable().to_owned(),
2104                lifetime_hints: self.inlayHints_genericParameterHints_lifetime_enable().to_owned(),
2105                const_hints: self.inlayHints_genericParameterHints_const_enable().to_owned(),
2106            },
2107            chaining_hints: self.inlayHints_chainingHints_enable().to_owned(),
2108            discriminant_hints: match self.inlayHints_discriminantHints_enable() {
2109                DiscriminantHintsDef::Always => ide::DiscriminantHints::Always,
2110                DiscriminantHintsDef::Never => ide::DiscriminantHints::Never,
2111                DiscriminantHintsDef::Fieldless => ide::DiscriminantHints::Fieldless,
2112            },
2113            closure_return_type_hints: match self.inlayHints_closureReturnTypeHints_enable() {
2114                ClosureReturnTypeHintsDef::Always => ide::ClosureReturnTypeHints::Always,
2115                ClosureReturnTypeHintsDef::Never => ide::ClosureReturnTypeHints::Never,
2116                ClosureReturnTypeHintsDef::WithBlock => ide::ClosureReturnTypeHints::WithBlock,
2117            },
2118            lifetime_elision_hints: match self.inlayHints_lifetimeElisionHints_enable() {
2119                LifetimeElisionDef::Always => ide::LifetimeElisionHints::Always,
2120                LifetimeElisionDef::Never => ide::LifetimeElisionHints::Never,
2121                LifetimeElisionDef::SkipTrivial => ide::LifetimeElisionHints::SkipTrivial,
2122            },
2123            hide_named_constructor_hints: self
2124                .inlayHints_typeHints_hideNamedConstructor()
2125                .to_owned(),
2126            hide_inferred_type_hints: self.inlayHints_typeHints_hideInferredTypes().to_owned(),
2127            hide_closure_initialization_hints: self
2128                .inlayHints_typeHints_hideClosureInitialization()
2129                .to_owned(),
2130            hide_closure_parameter_hints: self
2131                .inlayHints_typeHints_hideClosureParameter()
2132                .to_owned(),
2133            closure_style: match self.inlayHints_closureStyle() {
2134                ClosureStyle::ImplFn => hir::ClosureStyle::ImplFn,
2135                ClosureStyle::RustAnalyzer => hir::ClosureStyle::RANotation,
2136                ClosureStyle::WithId => hir::ClosureStyle::ClosureWithId,
2137                ClosureStyle::Hide => hir::ClosureStyle::Hide,
2138            },
2139            closure_capture_hints: self.inlayHints_closureCaptureHints_enable().to_owned(),
2140            adjustment_hints: match self.inlayHints_expressionAdjustmentHints_enable() {
2141                AdjustmentHintsDef::Always => ide::AdjustmentHints::Always,
2142                AdjustmentHintsDef::Never => match self.inlayHints_reborrowHints_enable() {
2143                    ReborrowHintsDef::Always | ReborrowHintsDef::Mutable => {
2144                        ide::AdjustmentHints::BorrowsOnly
2145                    }
2146                    ReborrowHintsDef::Never => ide::AdjustmentHints::Never,
2147                },
2148                AdjustmentHintsDef::Borrows => ide::AdjustmentHints::BorrowsOnly,
2149            },
2150            adjustment_hints_disable_reborrows: *self
2151                .inlayHints_expressionAdjustmentHints_disableReborrows(),
2152            adjustment_hints_mode: match self.inlayHints_expressionAdjustmentHints_mode() {
2153                AdjustmentHintsModeDef::Prefix => ide::AdjustmentHintsMode::Prefix,
2154                AdjustmentHintsModeDef::Postfix => ide::AdjustmentHintsMode::Postfix,
2155                AdjustmentHintsModeDef::PreferPrefix => ide::AdjustmentHintsMode::PreferPrefix,
2156                AdjustmentHintsModeDef::PreferPostfix => ide::AdjustmentHintsMode::PreferPostfix,
2157            },
2158            adjustment_hints_hide_outside_unsafe: self
2159                .inlayHints_expressionAdjustmentHints_hideOutsideUnsafe()
2160                .to_owned(),
2161            binding_mode_hints: self.inlayHints_bindingModeHints_enable().to_owned(),
2162            param_names_for_lifetime_elision_hints: self
2163                .inlayHints_lifetimeElisionHints_useParameterNames()
2164                .to_owned(),
2165            max_length: self.inlayHints_maxLength().to_owned(),
2166            closing_brace_hints_min_lines: if self.inlayHints_closingBraceHints_enable().to_owned()
2167            {
2168                Some(self.inlayHints_closingBraceHints_minLines().to_owned())
2169            } else {
2170                None
2171            },
2172            fields_to_resolve: InlayFieldsToResolve::from_client_capabilities(
2173                &client_capability_fields,
2174            ),
2175            implicit_drop_hints: match self.inlayHints_implicitDrops_enable() {
2176                ImplicitDropDef::Always => ide::ImplicitDropHints::Always,
2177                ImplicitDropDef::WithDropGlue => ide::ImplicitDropHints::WithDropGlue,
2178                ImplicitDropDef::Never => ide::ImplicitDropHints::Never,
2179            },
2180            implied_dyn_trait_hints: self.inlayHints_impliedDynTraitHints_enable().to_owned(),
2181            range_exclusive_hints: self.inlayHints_rangeExclusiveHints_enable().to_owned(),
2182            ra_fixture: self.ra_fixture(minicore),
2183        }
2184    }
2185
2186    fn insert_use_config(&self, source_root: Option<SourceRootId>) -> InsertUseConfig {
2187        InsertUseConfig {
2188            granularity: match self.imports_granularity_group(source_root) {
2189                ImportGranularityDef::Item | ImportGranularityDef::Preserve => {
2190                    ImportGranularity::Item
2191                }
2192                ImportGranularityDef::Crate => ImportGranularity::Crate,
2193                ImportGranularityDef::Module => ImportGranularity::Module,
2194                ImportGranularityDef::One => ImportGranularity::One,
2195            },
2196            enforce_granularity: self.imports_granularity_enforce(source_root).to_owned(),
2197            prefix_kind: match self.imports_prefix(source_root) {
2198                ImportPrefixDef::Plain => PrefixKind::Plain,
2199                ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
2200                ImportPrefixDef::BySelf => PrefixKind::BySelf,
2201            },
2202            group: self.imports_group_enable(source_root).to_owned(),
2203            skip_glob_imports: !self.imports_merge_glob(source_root),
2204        }
2205    }
2206
2207    pub fn join_lines(&self) -> JoinLinesConfig {
2208        JoinLinesConfig {
2209            join_else_if: self.joinLines_joinElseIf().to_owned(),
2210            remove_trailing_comma: self.joinLines_removeTrailingComma().to_owned(),
2211            unwrap_trivial_blocks: self.joinLines_unwrapTrivialBlock().to_owned(),
2212            join_assignments: self.joinLines_joinAssignments().to_owned(),
2213        }
2214    }
2215
2216    pub fn highlighting_non_standard_tokens(&self) -> bool {
2217        self.semanticHighlighting_nonStandardTokens().to_owned()
2218    }
2219
2220    pub fn highlighting_config<'a>(&self, minicore: MiniCore<'a>) -> HighlightConfig<'a> {
2221        HighlightConfig {
2222            strings: self.semanticHighlighting_strings_enable().to_owned(),
2223            comments: self.semanticHighlighting_comments_enable().to_owned(),
2224            punctuation: self.semanticHighlighting_punctuation_enable().to_owned(),
2225            specialize_punctuation: self
2226                .semanticHighlighting_punctuation_specialization_enable()
2227                .to_owned(),
2228            macro_bang: self.semanticHighlighting_punctuation_separate_macro_bang().to_owned(),
2229            operator: self.semanticHighlighting_operator_enable().to_owned(),
2230            specialize_operator: self
2231                .semanticHighlighting_operator_specialization_enable()
2232                .to_owned(),
2233            inject_doc_comment: self.semanticHighlighting_doc_comment_inject_enable().to_owned(),
2234            syntactic_name_ref_highlighting: false,
2235            ra_fixture: self.ra_fixture(minicore),
2236        }
2237    }
2238
2239    pub fn has_linked_projects(&self) -> bool {
2240        !self.linkedProjects().is_empty()
2241    }
2242
2243    pub fn linked_manifests(&self) -> impl Iterator<Item = &Utf8Path> + '_ {
2244        self.linkedProjects().iter().filter_map(|it| match it {
2245            ManifestOrProjectJson::Manifest(p) => Some(&**p),
2246            // despite having a buildfile, using this variant as a manifest
2247            // will fail.
2248            ManifestOrProjectJson::DiscoveredProjectJson { .. } => None,
2249            ManifestOrProjectJson::ProjectJson { .. } => None,
2250        })
2251    }
2252
2253    pub fn has_linked_project_jsons(&self) -> bool {
2254        self.linkedProjects()
2255            .iter()
2256            .any(|it| matches!(it, ManifestOrProjectJson::ProjectJson { .. }))
2257    }
2258
2259    pub fn discover_workspace_config(&self) -> Option<&DiscoverWorkspaceConfig> {
2260        self.workspace_discoverConfig().as_ref()
2261    }
2262
2263    fn discovered_projects(&self) -> Vec<ManifestOrProjectJson> {
2264        let exclude_dirs: Vec<_> =
2265            self.files_exclude().iter().map(|p| self.root_path.join(p)).collect();
2266
2267        let mut projects = vec![];
2268        for fs_proj in &self.discovered_projects_from_filesystem {
2269            let manifest_path = fs_proj.manifest_path();
2270            if exclude_dirs.iter().any(|p| manifest_path.starts_with(p)) {
2271                continue;
2272            }
2273
2274            let buf: Utf8PathBuf = manifest_path.to_path_buf().into();
2275            projects.push(ManifestOrProjectJson::Manifest(buf));
2276        }
2277
2278        for dis_proj in &self.discovered_projects_from_command {
2279            projects.push(ManifestOrProjectJson::DiscoveredProjectJson {
2280                data: dis_proj.data.clone(),
2281                buildfile: dis_proj.buildfile.clone(),
2282            });
2283        }
2284
2285        projects
2286    }
2287
2288    pub fn linked_or_discovered_projects(&self) -> Vec<LinkedProject> {
2289        let linked_projects = self.linkedProjects();
2290        let projects = if linked_projects.is_empty() {
2291            self.discovered_projects()
2292        } else {
2293            linked_projects.clone()
2294        };
2295
2296        projects
2297            .iter()
2298            .filter_map(|linked_project| match linked_project {
2299                ManifestOrProjectJson::Manifest(it) => {
2300                    let path = self.root_path.join(it);
2301                    ProjectManifest::from_manifest_file(path)
2302                        .map_err(|e| tracing::error!("failed to load linked project: {}", e))
2303                        .ok()
2304                        .map(Into::into)
2305                }
2306                ManifestOrProjectJson::DiscoveredProjectJson { data, buildfile } => {
2307                    let root_path = buildfile.parent().expect("Unable to get parent of buildfile");
2308
2309                    Some(ProjectJson::new(None, root_path, data.clone()).into())
2310                }
2311                ManifestOrProjectJson::ProjectJson(it) => {
2312                    Some(ProjectJson::new(None, &self.root_path, it.clone()).into())
2313                }
2314            })
2315            .collect()
2316    }
2317
2318    pub fn prefill_caches(&self) -> bool {
2319        self.cachePriming_enable().to_owned()
2320    }
2321
2322    pub fn publish_diagnostics(&self, source_root: Option<SourceRootId>) -> bool {
2323        self.diagnostics_enable(source_root).to_owned()
2324    }
2325
2326    pub fn diagnostics_map(&self, source_root: Option<SourceRootId>) -> DiagnosticsMapConfig {
2327        DiagnosticsMapConfig {
2328            remap_prefix: self.diagnostics_remapPrefix(source_root).clone(),
2329            warnings_as_info: self.diagnostics_warningsAsInfo(source_root).clone(),
2330            warnings_as_hint: self.diagnostics_warningsAsHint(source_root).clone(),
2331            check_ignore: self.check_ignore(source_root).clone(),
2332        }
2333    }
2334
2335    pub fn extra_args(&self, source_root: Option<SourceRootId>) -> &Vec<String> {
2336        self.cargo_extraArgs(source_root)
2337    }
2338
2339    pub fn extra_env(
2340        &self,
2341        source_root: Option<SourceRootId>,
2342    ) -> &FxHashMap<String, Option<String>> {
2343        self.cargo_extraEnv(source_root)
2344    }
2345
2346    pub fn check_extra_args(&self, source_root: Option<SourceRootId>) -> Vec<String> {
2347        let mut extra_args = self.extra_args(source_root).clone();
2348        extra_args.extend_from_slice(self.check_extraArgs(source_root));
2349        extra_args
2350    }
2351
2352    pub fn check_extra_env(
2353        &self,
2354        source_root: Option<SourceRootId>,
2355    ) -> FxHashMap<String, Option<String>> {
2356        let mut extra_env = self.cargo_extraEnv(source_root).clone();
2357        extra_env.extend(self.check_extraEnv(source_root).clone());
2358        extra_env
2359    }
2360
2361    pub fn lru_parse_query_capacity(&self) -> Option<u16> {
2362        self.lru_capacity().to_owned()
2363    }
2364
2365    pub fn lru_query_capacities_config(&self) -> Option<&FxHashMap<Box<str>, u16>> {
2366        self.lru_query_capacities().is_empty().not().then(|| self.lru_query_capacities())
2367    }
2368
2369    pub fn proc_macro_srv(&self) -> Option<AbsPathBuf> {
2370        let path = self.procMacro_server().clone()?;
2371        Some(AbsPathBuf::try_from(path).unwrap_or_else(|path| self.root_path.join(path)))
2372    }
2373
2374    pub fn dhat_output_file(&self) -> Option<AbsPathBuf> {
2375        let path = self.profiling_memoryProfile().clone()?;
2376        Some(AbsPathBuf::try_from(path).unwrap_or_else(|path| self.root_path.join(path)))
2377    }
2378
2379    pub fn ignored_proc_macros(
2380        &self,
2381        source_root: Option<SourceRootId>,
2382    ) -> &FxHashMap<Box<str>, Box<[Box<str>]>> {
2383        self.procMacro_ignored(source_root)
2384    }
2385
2386    pub fn expand_proc_macros(&self) -> bool {
2387        self.procMacro_enable().to_owned()
2388    }
2389
2390    pub fn files(&self) -> FilesConfig {
2391        FilesConfig {
2392            watcher: match self.files_watcher() {
2393                FilesWatcherDef::Client if self.did_change_watched_files_dynamic_registration() => {
2394                    FilesWatcher::Client
2395                }
2396                _ => FilesWatcher::Server,
2397            },
2398            exclude: self.excluded().collect(),
2399        }
2400    }
2401
2402    pub fn excluded(&self) -> impl Iterator<Item = AbsPathBuf> + use<'_> {
2403        self.files_exclude().iter().map(|it| self.root_path.join(it))
2404    }
2405
2406    pub fn notifications(&self) -> NotificationsConfig {
2407        NotificationsConfig {
2408            cargo_toml_not_found: self.notifications_cargoTomlNotFound().to_owned(),
2409        }
2410    }
2411
2412    pub fn cargo_autoreload_config(&self, source_root: Option<SourceRootId>) -> bool {
2413        self.cargo_autoreload(source_root).to_owned()
2414    }
2415
2416    pub fn run_build_scripts(&self, source_root: Option<SourceRootId>) -> bool {
2417        self.cargo_buildScripts_enable(source_root).to_owned() || self.procMacro_enable().to_owned()
2418    }
2419
2420    pub fn cargo(&self, source_root: Option<SourceRootId>) -> CargoConfig {
2421        let rustc_source = self.rustc_source(source_root).as_ref().map(|rustc_src| {
2422            if rustc_src == "discover" {
2423                RustLibSource::Discover
2424            } else {
2425                RustLibSource::Path(self.root_path.join(rustc_src))
2426            }
2427        });
2428        let sysroot = self.cargo_sysroot(source_root).as_ref().map(|sysroot| {
2429            if sysroot == "discover" {
2430                RustLibSource::Discover
2431            } else {
2432                RustLibSource::Path(self.root_path.join(sysroot))
2433            }
2434        });
2435        let sysroot_src =
2436            self.cargo_sysrootSrc(source_root).as_ref().map(|sysroot| self.root_path.join(sysroot));
2437        let config_path = self.cargo_config_path(source_root);
2438        let extra_includes = self
2439            .vfs_extraIncludes(source_root)
2440            .iter()
2441            .map(String::as_str)
2442            .map(AbsPathBuf::try_from)
2443            .filter_map(Result::ok)
2444            .collect();
2445
2446        CargoConfig {
2447            all_targets: *self.cargo_allTargets(source_root),
2448            features: match &self.cargo_features(source_root) {
2449                CargoFeaturesDef::All => CargoFeatures::All,
2450                CargoFeaturesDef::Selected(features) => CargoFeatures::Selected {
2451                    features: features.clone(),
2452                    no_default_features: self.cargo_noDefaultFeatures(source_root).to_owned(),
2453                },
2454            },
2455            target: self.cargo_target(source_root).clone(),
2456            sysroot,
2457            sysroot_src,
2458            rustc_source,
2459            extra_includes,
2460            cfg_overrides: project_model::CfgOverrides {
2461                global: {
2462                    let (enabled, disabled): (Vec<_>, Vec<_>) =
2463                        self.cargo_cfgs(source_root).iter().partition_map(|s| {
2464                            s.strip_prefix("!").map_or(Either::Left(s), Either::Right)
2465                        });
2466                    CfgDiff::new(
2467                        enabled
2468                            .into_iter()
2469                            // parse any cfg setting formatted as key=value or just key (without value)
2470                            .map(|s| match s.split_once("=") {
2471                                Some((key, val)) => CfgAtom::KeyValue {
2472                                    key: Symbol::intern(key),
2473                                    value: Symbol::intern(val),
2474                                },
2475                                None => CfgAtom::Flag(Symbol::intern(s)),
2476                            })
2477                            .collect(),
2478                        disabled
2479                            .into_iter()
2480                            .map(|s| match s.split_once("=") {
2481                                Some((key, val)) => CfgAtom::KeyValue {
2482                                    key: Symbol::intern(key),
2483                                    value: Symbol::intern(val),
2484                                },
2485                                None => CfgAtom::Flag(Symbol::intern(s)),
2486                            })
2487                            .collect(),
2488                    )
2489                },
2490                selective: Default::default(),
2491            },
2492            wrap_rustc_in_build_scripts: *self.cargo_buildScripts_useRustcWrapper(source_root),
2493            invocation_strategy: match self.cargo_buildScripts_invocationStrategy(source_root) {
2494                InvocationStrategy::Once => project_model::InvocationStrategy::Once,
2495                InvocationStrategy::PerWorkspace => project_model::InvocationStrategy::PerWorkspace,
2496            },
2497            run_build_script_command: self.cargo_buildScripts_overrideCommand(source_root).clone(),
2498            extra_args: self.cargo_extraArgs(source_root).clone(),
2499            extra_env: self.cargo_extraEnv(source_root).clone(),
2500            target_dir_config: self.target_dir_from_config(source_root),
2501            set_test: *self.cfg_setTest(source_root),
2502            no_deps: *self.cargo_noDeps(source_root),
2503            metadata_extra_args: self.cargo_metadataExtraArgs(source_root).clone(),
2504            config_path,
2505        }
2506    }
2507
2508    pub fn cfg_set_test(&self, source_root: Option<SourceRootId>) -> bool {
2509        *self.cfg_setTest(source_root)
2510    }
2511
2512    pub(crate) fn completion_snippets_default() -> FxIndexMap<String, SnippetDef> {
2513        serde_json::from_str(
2514            r#"{
2515            "Ok": {
2516                "postfix": "ok",
2517                "body": "Ok(${receiver})",
2518                "description": "Wrap the expression in a `Result::Ok`",
2519                "scope": "expr"
2520            },
2521            "Box::pin": {
2522                "postfix": "pinbox",
2523                "body": "Box::pin(${receiver})",
2524                "requires": "std::boxed::Box",
2525                "description": "Put the expression into a pinned `Box`",
2526                "scope": "expr"
2527            },
2528            "Arc::new": {
2529                "postfix": "arc",
2530                "body": "Arc::new(${receiver})",
2531                "requires": "std::sync::Arc",
2532                "description": "Put the expression into an `Arc`",
2533                "scope": "expr"
2534            },
2535            "Some": {
2536                "postfix": "some",
2537                "body": "Some(${receiver})",
2538                "description": "Wrap the expression in an `Option::Some`",
2539                "scope": "expr"
2540            },
2541            "Err": {
2542                "postfix": "err",
2543                "body": "Err(${receiver})",
2544                "description": "Wrap the expression in a `Result::Err`",
2545                "scope": "expr"
2546            },
2547            "Rc::new": {
2548                "postfix": "rc",
2549                "body": "Rc::new(${receiver})",
2550                "requires": "std::rc::Rc",
2551                "description": "Put the expression into an `Rc`",
2552                "scope": "expr"
2553            }
2554        }"#,
2555        )
2556        .unwrap()
2557    }
2558
2559    pub fn rustfmt(&self, source_root_id: Option<SourceRootId>) -> RustfmtConfig {
2560        match &self.rustfmt_overrideCommand(source_root_id) {
2561            Some(args) if !args.is_empty() => {
2562                let mut args = args.clone();
2563                let command = args.remove(0);
2564                RustfmtConfig::CustomCommand { command, args }
2565            }
2566            Some(_) | None => RustfmtConfig::Rustfmt {
2567                extra_args: self.rustfmt_extraArgs(source_root_id).clone(),
2568                enable_range_formatting: *self.rustfmt_rangeFormatting_enable(source_root_id),
2569            },
2570        }
2571    }
2572
2573    pub fn flycheck_workspace(&self, source_root: Option<SourceRootId>) -> bool {
2574        *self.check_workspace(source_root)
2575    }
2576
2577    pub(crate) fn cargo_test_options(&self, source_root: Option<SourceRootId>) -> CargoOptions {
2578        CargoOptions {
2579            // Might be nice to allow users to specify test_command = "nextest"
2580            subcommand: "test".into(),
2581            target_tuples: self.cargo_target(source_root).clone().into_iter().collect(),
2582            all_targets: false,
2583            no_default_features: *self.cargo_noDefaultFeatures(source_root),
2584            all_features: matches!(self.cargo_features(source_root), CargoFeaturesDef::All),
2585            features: match self.cargo_features(source_root).clone() {
2586                CargoFeaturesDef::All => vec![],
2587                CargoFeaturesDef::Selected(it) => it,
2588            },
2589            extra_args: self.extra_args(source_root).clone(),
2590            extra_test_bin_args: self.runnables_extraTestBinaryArgs(source_root).clone(),
2591            extra_env: self.extra_env(source_root).clone(),
2592            target_dir_config: self.target_dir_from_config(source_root),
2593            set_test: true,
2594            config_path: self.cargo_config_path(source_root),
2595        }
2596    }
2597
2598    pub(crate) fn flycheck(&self, source_root: Option<SourceRootId>) -> FlycheckConfig {
2599        match &self.check_overrideCommand(source_root) {
2600            Some(args) if !args.is_empty() => {
2601                let mut args = args.clone();
2602                let command = args.remove(0);
2603                FlycheckConfig::CustomCommand {
2604                    command,
2605                    args,
2606                    extra_env: self.check_extra_env(source_root),
2607                    invocation_strategy: match self.check_invocationStrategy(source_root) {
2608                        InvocationStrategy::Once => crate::flycheck::InvocationStrategy::Once,
2609                        InvocationStrategy::PerWorkspace => {
2610                            crate::flycheck::InvocationStrategy::PerWorkspace
2611                        }
2612                    },
2613                }
2614            }
2615            Some(_) | None => FlycheckConfig::Automatic {
2616                cargo_options: CargoOptions {
2617                    subcommand: self.check_command(source_root).clone(),
2618                    target_tuples: self
2619                        .check_targets(source_root)
2620                        .clone()
2621                        .and_then(|targets| match &targets.0[..] {
2622                            [] => None,
2623                            targets => Some(targets.into()),
2624                        })
2625                        .unwrap_or_else(|| {
2626                            self.cargo_target(source_root).clone().into_iter().collect()
2627                        }),
2628                    all_targets: self
2629                        .check_allTargets(source_root)
2630                        .unwrap_or(*self.cargo_allTargets(source_root)),
2631                    no_default_features: self
2632                        .check_noDefaultFeatures(source_root)
2633                        .unwrap_or(*self.cargo_noDefaultFeatures(source_root)),
2634                    all_features: matches!(
2635                        self.check_features(source_root)
2636                            .as_ref()
2637                            .unwrap_or(self.cargo_features(source_root)),
2638                        CargoFeaturesDef::All
2639                    ),
2640                    features: match self
2641                        .check_features(source_root)
2642                        .clone()
2643                        .unwrap_or_else(|| self.cargo_features(source_root).clone())
2644                    {
2645                        CargoFeaturesDef::All => vec![],
2646                        CargoFeaturesDef::Selected(it) => it,
2647                    },
2648                    extra_args: self.check_extra_args(source_root),
2649                    extra_test_bin_args: self.runnables_extraTestBinaryArgs(source_root).clone(),
2650                    extra_env: self.check_extra_env(source_root),
2651                    config_path: self.cargo_config_path(source_root),
2652                    target_dir_config: self.target_dir_from_config(source_root),
2653                    set_test: *self.cfg_setTest(source_root),
2654                },
2655                ansi_color_output: self.color_diagnostic_output(),
2656            },
2657        }
2658    }
2659
2660    fn cargo_config_path(&self, source_root: Option<SourceRootId>) -> Option<AbsPathBuf> {
2661        self.cargo_configPath(source_root).as_ref().map(|path| self.root_path.join(path))
2662    }
2663
2664    fn target_dir_from_config(&self, source_root: Option<SourceRootId>) -> TargetDirectoryConfig {
2665        match &self.cargo_targetDir(source_root) {
2666            Some(TargetDirectory::UseSubdirectory(true)) => TargetDirectoryConfig::UseSubdirectory,
2667            Some(TargetDirectory::UseSubdirectory(false)) | None => TargetDirectoryConfig::None,
2668            Some(TargetDirectory::Directory(dir)) => TargetDirectoryConfig::Directory(dir.clone()),
2669        }
2670    }
2671
2672    pub fn check_on_save(&self, source_root: Option<SourceRootId>) -> bool {
2673        *self.checkOnSave(source_root)
2674    }
2675
2676    pub fn script_rebuild_on_save(&self, source_root: Option<SourceRootId>) -> bool {
2677        *self.cargo_buildScripts_rebuildOnSave(source_root)
2678    }
2679
2680    pub fn runnables(&self, source_root: Option<SourceRootId>) -> RunnablesConfig {
2681        RunnablesConfig {
2682            override_cargo: self.runnables_command(source_root).clone(),
2683            cargo_extra_args: self.runnables_extraArgs(source_root).clone(),
2684            config_path: self.cargo_config_path(source_root),
2685            extra_test_binary_args: self.runnables_extraTestBinaryArgs(source_root).clone(),
2686            test_command: self.runnables_test_command(source_root).clone(),
2687            test_override_command: self.runnables_test_overrideCommand(source_root).clone(),
2688            bench_command: self.runnables_bench_command(source_root).clone(),
2689            bench_override_command: self.runnables_bench_overrideCommand(source_root).clone(),
2690            doc_test_override_command: self.runnables_doctest_overrideCommand(source_root).clone(),
2691        }
2692    }
2693
2694    pub fn find_all_refs_exclude_imports(&self) -> bool {
2695        *self.references_excludeImports()
2696    }
2697
2698    pub fn find_all_refs_exclude_tests(&self) -> bool {
2699        *self.references_excludeTests()
2700    }
2701
2702    pub fn snippet_cap(&self) -> Option<SnippetCap> {
2703        // FIXME: Also detect the proposed lsp version at caps.workspace.workspaceEdit.snippetEditSupport
2704        // once lsp-types has it.
2705        SnippetCap::new(self.snippet_text_edit())
2706    }
2707
2708    pub fn call_info(&self) -> CallInfoConfig {
2709        CallInfoConfig {
2710            params_only: matches!(self.signatureInfo_detail(), SignatureDetail::Parameters),
2711            docs: *self.signatureInfo_documentation_enable(),
2712        }
2713    }
2714
2715    pub fn lens(&self) -> LensConfig {
2716        let enable = *self.lens_enable();
2717        LensConfig {
2718            run: enable && *self.lens_run_enable(),
2719            debug: enable && *self.lens_debug_enable(),
2720            update_test: enable && *self.lens_updateTest_enable() && *self.lens_run_enable(),
2721            interpret: enable && *self.lens_run_enable() && *self.interpret_tests(),
2722            implementations: enable && *self.lens_implementations_enable(),
2723            method_refs: enable && *self.lens_references_method_enable(),
2724            refs_adt: enable && *self.lens_references_adt_enable(),
2725            refs_trait: enable && *self.lens_references_trait_enable(),
2726            enum_variant_refs: enable && *self.lens_references_enumVariant_enable(),
2727            refs_exclude_imports: *self.references_excludeImports(),
2728            refs_exclude_tests: *self.references_excludeTests(),
2729            location: *self.lens_location(),
2730            filter_adjacent_derive_implementations: *self
2731                .gotoImplementations_filterAdjacentDerives(),
2732            disable_ra_fixture: *self.disableFixtureSupport(None),
2733        }
2734    }
2735
2736    pub fn goto_implementation(&self) -> GotoImplementationConfig {
2737        GotoImplementationConfig {
2738            filter_adjacent_derive_implementations: *self
2739                .gotoImplementations_filterAdjacentDerives(),
2740        }
2741    }
2742
2743    pub fn document_symbol(&self, source_root: Option<SourceRootId>) -> DocumentSymbolConfig {
2744        DocumentSymbolConfig {
2745            search_exclude_locals: *self.document_symbol_search_excludeLocals(source_root),
2746        }
2747    }
2748
2749    pub fn workspace_symbol(&self, source_root: Option<SourceRootId>) -> WorkspaceSymbolConfig {
2750        WorkspaceSymbolConfig {
2751            search_exclude_imports: *self.workspace_symbol_search_excludeImports(source_root),
2752            search_scope: match self.workspace_symbol_search_scope(source_root) {
2753                WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
2754                WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
2755                    WorkspaceSymbolSearchScope::WorkspaceAndDependencies
2756                }
2757            },
2758            search_kind: match self.workspace_symbol_search_kind(source_root) {
2759                WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
2760                WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
2761            },
2762            search_limit: *self.workspace_symbol_search_limit(source_root),
2763        }
2764    }
2765
2766    pub fn client_commands(&self) -> ClientCommandsConfig {
2767        let commands = self.commands().map(|it| it.commands).unwrap_or_default();
2768
2769        let get = |name: &str| commands.iter().any(|it| it == name);
2770
2771        ClientCommandsConfig {
2772            run_single: get("rust-analyzer.runSingle"),
2773            debug_single: get("rust-analyzer.debugSingle"),
2774            show_reference: get("rust-analyzer.showReferences"),
2775            goto_location: get("rust-analyzer.gotoLocation"),
2776            trigger_parameter_hints: get("rust-analyzer.triggerParameterHints"),
2777            rename: get("rust-analyzer.rename"),
2778        }
2779    }
2780
2781    pub fn prime_caches_num_threads(&self) -> usize {
2782        match self.cachePriming_numThreads() {
2783            NumThreads::Concrete(0) | NumThreads::Physical => num_cpus::get_physical(),
2784            &NumThreads::Concrete(n) => n,
2785            NumThreads::Logical => num_cpus::get(),
2786        }
2787    }
2788
2789    pub fn proc_macro_num_processes(&self) -> usize {
2790        match self.procMacro_processes() {
2791            NumProcesses::Concrete(0) | NumProcesses::Physical => num_cpus::get_physical(),
2792            &NumProcesses::Concrete(n) => n,
2793        }
2794    }
2795
2796    pub fn main_loop_num_threads(&self) -> usize {
2797        match self.numThreads() {
2798            Some(NumThreads::Concrete(0)) | None | Some(NumThreads::Physical) => {
2799                num_cpus::get_physical()
2800            }
2801            &Some(NumThreads::Concrete(n)) => n,
2802            Some(NumThreads::Logical) => num_cpus::get(),
2803        }
2804    }
2805
2806    pub fn typing_trigger_chars(&self) -> &str {
2807        self.typing_triggerChars().as_deref().unwrap_or_default()
2808    }
2809
2810    // VSCode is our reference implementation, so we allow ourselves to work around issues by
2811    // special casing certain versions
2812    pub fn visual_studio_code_version(&self) -> Option<&Version> {
2813        self.client_info
2814            .as_ref()
2815            .filter(|it| it.name.starts_with("Visual Studio Code"))
2816            .and_then(|it| it.version.as_ref())
2817    }
2818
2819    pub fn client_is_neovim(&self) -> bool {
2820        self.client_info.as_ref().map(|it| it.name == "Neovim").unwrap_or_default()
2821    }
2822}
2823// Deserialization definitions
2824
2825macro_rules! create_bool_or_string_serde {
2826    ($ident:ident<$bool:literal, $string:literal>) => {
2827        mod $ident {
2828            pub(super) fn deserialize<'de, D>(d: D) -> Result<(), D::Error>
2829            where
2830                D: serde::Deserializer<'de>,
2831            {
2832                struct V;
2833                impl<'de> serde::de::Visitor<'de> for V {
2834                    type Value = ();
2835
2836                    fn expecting(
2837                        &self,
2838                        formatter: &mut std::fmt::Formatter<'_>,
2839                    ) -> std::fmt::Result {
2840                        formatter.write_str(concat!(
2841                            stringify!($bool),
2842                            " or \"",
2843                            stringify!($string),
2844                            "\""
2845                        ))
2846                    }
2847
2848                    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
2849                    where
2850                        E: serde::de::Error,
2851                    {
2852                        match v {
2853                            $bool => Ok(()),
2854                            _ => Err(serde::de::Error::invalid_value(
2855                                serde::de::Unexpected::Bool(v),
2856                                &self,
2857                            )),
2858                        }
2859                    }
2860
2861                    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
2862                    where
2863                        E: serde::de::Error,
2864                    {
2865                        match v {
2866                            $string => Ok(()),
2867                            _ => Err(serde::de::Error::invalid_value(
2868                                serde::de::Unexpected::Str(v),
2869                                &self,
2870                            )),
2871                        }
2872                    }
2873
2874                    fn visit_enum<A>(self, a: A) -> Result<Self::Value, A::Error>
2875                    where
2876                        A: serde::de::EnumAccess<'de>,
2877                    {
2878                        use serde::de::VariantAccess;
2879                        let (variant, va) = a.variant::<&'de str>()?;
2880                        va.unit_variant()?;
2881                        match variant {
2882                            $string => Ok(()),
2883                            _ => Err(serde::de::Error::invalid_value(
2884                                serde::de::Unexpected::Str(variant),
2885                                &self,
2886                            )),
2887                        }
2888                    }
2889                }
2890                d.deserialize_any(V)
2891            }
2892
2893            pub(super) fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error>
2894            where
2895                S: serde::Serializer,
2896            {
2897                serializer.serialize_str($string)
2898            }
2899        }
2900    };
2901}
2902create_bool_or_string_serde!(true_or_always<true, "always">);
2903create_bool_or_string_serde!(false_or_never<false, "never">);
2904
2905#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
2906#[serde(rename_all = "snake_case")]
2907#[derive(Default)]
2908enum SnippetScopeDef {
2909    #[default]
2910    Expr,
2911    Item,
2912    Type,
2913}
2914
2915#[derive(Serialize, Deserialize, Debug, Clone, Default)]
2916#[serde(default)]
2917#[serde(try_from = "SnippetDefRepr")]
2918pub(crate) struct SnippetDef {
2919    #[serde(with = "single_or_array")]
2920    #[serde(skip_serializing_if = "Vec::is_empty")]
2921    prefix: Vec<String>,
2922
2923    #[serde(with = "single_or_array")]
2924    #[serde(skip_serializing_if = "Vec::is_empty")]
2925    postfix: Vec<String>,
2926
2927    #[serde(with = "single_or_array")]
2928    #[serde(skip_serializing_if = "Vec::is_empty")]
2929    body: Vec<String>,
2930
2931    #[serde(with = "single_or_array")]
2932    #[serde(skip_serializing_if = "Vec::is_empty")]
2933    requires: Vec<String>,
2934
2935    #[serde(skip_serializing_if = "Option::is_none")]
2936    description: Option<String>,
2937
2938    scope: SnippetScopeDef,
2939}
2940
2941/// Plain deserialization target for [`SnippetDef`]. Both the client JSON
2942/// config and `rust-analyzer.toml` configs deserialize a `SnippetDef` per
2943/// map entry, so validating the field combination here (via `TryFrom`)
2944/// covers both config sources instead of only one.
2945#[derive(Deserialize, Default)]
2946#[serde(default)]
2947struct SnippetDefRepr {
2948    #[serde(with = "single_or_array")]
2949    prefix: Vec<String>,
2950    #[serde(with = "single_or_array")]
2951    postfix: Vec<String>,
2952    #[serde(with = "single_or_array")]
2953    body: Vec<String>,
2954    #[serde(with = "single_or_array")]
2955    requires: Vec<String>,
2956    description: Option<String>,
2957    scope: SnippetScopeDef,
2958}
2959
2960impl TryFrom<SnippetDefRepr> for SnippetDef {
2961    type Error = String;
2962
2963    fn try_from(repr: SnippetDefRepr) -> Result<Self, Self::Error> {
2964        if repr.scope == SnippetScopeDef::Item && !repr.postfix.is_empty() {
2965            return Err(
2966                "'postfix' is not supported together with '\"scope\": \"item\"'; postfix snippets are not supported in item scope"
2967                    .to_owned(),
2968            );
2969        }
2970        Ok(SnippetDef {
2971            prefix: repr.prefix,
2972            postfix: repr.postfix,
2973            body: repr.body,
2974            requires: repr.requires,
2975            description: repr.description,
2976            scope: repr.scope,
2977        })
2978    }
2979}
2980
2981mod single_or_array {
2982    use serde::{Deserialize, Serialize};
2983
2984    pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
2985    where
2986        D: serde::Deserializer<'de>,
2987    {
2988        struct SingleOrVec;
2989
2990        impl<'de> serde::de::Visitor<'de> for SingleOrVec {
2991            type Value = Vec<String>;
2992
2993            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2994                formatter.write_str("string or array of strings")
2995            }
2996
2997            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2998            where
2999                E: serde::de::Error,
3000            {
3001                Ok(vec![value.to_owned()])
3002            }
3003
3004            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
3005            where
3006                A: serde::de::SeqAccess<'de>,
3007            {
3008                Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
3009            }
3010        }
3011
3012        deserializer.deserialize_any(SingleOrVec)
3013    }
3014
3015    pub(super) fn serialize<S>(vec: &[String], serializer: S) -> Result<S::Ok, S::Error>
3016    where
3017        S: serde::Serializer,
3018    {
3019        match vec {
3020            // []  case is handled by skip_serializing_if
3021            [single] => serializer.serialize_str(single),
3022            slice => slice.serialize(serializer),
3023        }
3024    }
3025}
3026
3027#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3028#[serde(untagged)]
3029enum ManifestOrProjectJson {
3030    Manifest(Utf8PathBuf),
3031    ProjectJson(ProjectJsonData),
3032    DiscoveredProjectJson {
3033        data: ProjectJsonData,
3034        #[serde(serialize_with = "serialize_abs_pathbuf")]
3035        #[serde(deserialize_with = "deserialize_abs_pathbuf")]
3036        buildfile: AbsPathBuf,
3037    },
3038}
3039
3040fn deserialize_abs_pathbuf<'de, D>(de: D) -> std::result::Result<AbsPathBuf, D::Error>
3041where
3042    D: serde::de::Deserializer<'de>,
3043{
3044    let path = String::deserialize(de)?;
3045
3046    AbsPathBuf::try_from(path.as_ref())
3047        .map_err(|err| serde::de::Error::custom(format!("invalid path name: {err:?}")))
3048}
3049
3050fn serialize_abs_pathbuf<S>(path: &AbsPathBuf, se: S) -> Result<S::Ok, S::Error>
3051where
3052    S: serde::Serializer,
3053{
3054    let path: &Utf8Path = path.as_ref();
3055    se.serialize_str(path.as_str())
3056}
3057
3058#[derive(Serialize, Deserialize, Debug, Clone)]
3059#[serde(rename_all = "snake_case")]
3060enum ExprFillDefaultDef {
3061    Todo,
3062    Default,
3063    Underscore,
3064}
3065
3066#[derive(Serialize, Deserialize, Debug, Clone)]
3067#[serde(untagged)]
3068#[serde(rename_all = "snake_case")]
3069pub enum AutoImportExclusion {
3070    Path(String),
3071    Verbose { path: String, r#type: AutoImportExclusionType },
3072}
3073
3074#[derive(Serialize, Deserialize, Debug, Clone)]
3075#[serde(rename_all = "snake_case")]
3076pub enum AutoImportExclusionType {
3077    Always,
3078    Methods,
3079    SubItems,
3080    Variants,
3081}
3082
3083#[derive(Serialize, Deserialize, Debug, Clone)]
3084#[serde(rename_all = "snake_case")]
3085enum ImportGranularityDef {
3086    Preserve,
3087    Item,
3088    Crate,
3089    Module,
3090    One,
3091}
3092
3093#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
3094#[serde(rename_all = "snake_case")]
3095pub(crate) enum CallableCompletionDef {
3096    FillArguments,
3097    AddParentheses,
3098    None,
3099}
3100
3101#[derive(Serialize, Deserialize, Debug, Clone)]
3102#[serde(rename_all = "snake_case")]
3103enum CargoFeaturesDef {
3104    All,
3105    #[serde(untagged)]
3106    Selected(Vec<String>),
3107}
3108
3109#[derive(Serialize, Deserialize, Debug, Clone)]
3110#[serde(rename_all = "snake_case")]
3111pub(crate) enum InvocationStrategy {
3112    Once,
3113    PerWorkspace,
3114}
3115
3116#[derive(Serialize, Deserialize, Debug, Clone)]
3117struct CheckOnSaveTargets(#[serde(with = "single_or_array")] Vec<String>);
3118
3119#[derive(Serialize, Deserialize, Debug, Clone)]
3120#[serde(rename_all = "snake_case")]
3121enum LifetimeElisionDef {
3122    SkipTrivial,
3123    #[serde(with = "true_or_always")]
3124    #[serde(untagged)]
3125    Always,
3126    #[serde(with = "false_or_never")]
3127    #[serde(untagged)]
3128    Never,
3129}
3130
3131#[derive(Serialize, Deserialize, Debug, Clone)]
3132#[serde(rename_all = "snake_case")]
3133enum ImplicitDropDef {
3134    WithDropGlue,
3135    #[serde(with = "true_or_always")]
3136    #[serde(untagged)]
3137    Always,
3138    #[serde(with = "false_or_never")]
3139    #[serde(untagged)]
3140    Never,
3141}
3142
3143#[derive(Serialize, Deserialize, Debug, Clone)]
3144#[serde(rename_all = "snake_case")]
3145enum ClosureReturnTypeHintsDef {
3146    WithBlock,
3147    #[serde(with = "true_or_always")]
3148    #[serde(untagged)]
3149    Always,
3150    #[serde(with = "false_or_never")]
3151    #[serde(untagged)]
3152    Never,
3153}
3154
3155#[derive(Serialize, Deserialize, Debug, Clone)]
3156#[serde(rename_all = "snake_case")]
3157enum ClosureStyle {
3158    ImplFn,
3159    RustAnalyzer,
3160    WithId,
3161    Hide,
3162}
3163
3164#[derive(Serialize, Deserialize, Debug, Clone)]
3165#[serde(rename_all = "snake_case")]
3166enum TypeHintsLocation {
3167    Inline,
3168    EndOfLine,
3169}
3170
3171#[derive(Serialize, Deserialize, Debug, Clone)]
3172#[serde(rename_all = "snake_case")]
3173enum ReborrowHintsDef {
3174    Mutable,
3175    #[serde(with = "true_or_always")]
3176    #[serde(untagged)]
3177    Always,
3178    #[serde(with = "false_or_never")]
3179    #[serde(untagged)]
3180    Never,
3181}
3182
3183#[derive(Serialize, Deserialize, Debug, Clone)]
3184#[serde(rename_all = "snake_case")]
3185enum AdjustmentHintsDef {
3186    #[serde(alias = "reborrow")]
3187    Borrows,
3188    #[serde(with = "true_or_always")]
3189    #[serde(untagged)]
3190    Always,
3191    #[serde(with = "false_or_never")]
3192    #[serde(untagged)]
3193    Never,
3194}
3195
3196#[derive(Serialize, Deserialize, Debug, Clone)]
3197#[serde(rename_all = "snake_case")]
3198enum DiscriminantHintsDef {
3199    Fieldless,
3200    #[serde(with = "true_or_always")]
3201    #[serde(untagged)]
3202    Always,
3203    #[serde(with = "false_or_never")]
3204    #[serde(untagged)]
3205    Never,
3206}
3207
3208#[derive(Serialize, Deserialize, Debug, Clone)]
3209#[serde(rename_all = "snake_case")]
3210enum AdjustmentHintsModeDef {
3211    Prefix,
3212    Postfix,
3213    PreferPrefix,
3214    PreferPostfix,
3215}
3216
3217#[derive(Serialize, Deserialize, Debug, Clone)]
3218#[serde(rename_all = "snake_case")]
3219enum FilesWatcherDef {
3220    Client,
3221    Notify,
3222    Server,
3223}
3224
3225#[derive(Serialize, Deserialize, Debug, Clone)]
3226#[serde(rename_all = "snake_case")]
3227enum ImportPrefixDef {
3228    Plain,
3229    #[serde(rename = "self")]
3230    #[serde(alias = "by_self")]
3231    BySelf,
3232    #[serde(rename = "crate")]
3233    #[serde(alias = "by_crate")]
3234    ByCrate,
3235}
3236
3237#[derive(Serialize, Deserialize, Debug, Clone)]
3238#[serde(rename_all = "snake_case")]
3239enum WorkspaceSymbolSearchScopeDef {
3240    Workspace,
3241    WorkspaceAndDependencies,
3242}
3243
3244#[derive(Serialize, Deserialize, Debug, Clone)]
3245#[serde(rename_all = "snake_case")]
3246enum SignatureDetail {
3247    Full,
3248    Parameters,
3249}
3250
3251#[derive(Serialize, Deserialize, Debug, Clone)]
3252#[serde(rename_all = "snake_case")]
3253enum WorkspaceSymbolSearchKindDef {
3254    OnlyTypes,
3255    AllSymbols,
3256}
3257
3258#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)]
3259#[serde(rename_all = "snake_case")]
3260enum MemoryLayoutHoverRenderKindDef {
3261    Decimal,
3262    Hexadecimal,
3263    Both,
3264}
3265
3266#[test]
3267fn untagged_option_hover_render_kind() {
3268    let hex = MemoryLayoutHoverRenderKindDef::Hexadecimal;
3269
3270    let ser = serde_json::to_string(&Some(hex)).unwrap();
3271    assert_eq!(&ser, "\"hexadecimal\"");
3272
3273    let opt: Option<_> = serde_json::from_str("\"hexadecimal\"").unwrap();
3274    assert_eq!(opt, Some(hex));
3275}
3276
3277#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3278#[serde(rename_all = "snake_case")]
3279#[serde(untagged)]
3280pub enum TargetDirectory {
3281    UseSubdirectory(bool),
3282    Directory(Utf8PathBuf),
3283}
3284
3285#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3286#[serde(rename_all = "snake_case")]
3287pub enum NumThreads {
3288    Physical,
3289    Logical,
3290    #[serde(untagged)]
3291    Concrete(usize),
3292}
3293
3294#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3295#[serde(rename_all = "snake_case")]
3296pub enum NumProcesses {
3297    Physical,
3298    #[serde(untagged)]
3299    Concrete(usize),
3300}
3301
3302macro_rules! _default_val {
3303    ($default:expr, $ty:ty) => {{
3304        let default_: $ty = $default;
3305        default_
3306    }};
3307}
3308use _default_val as default_val;
3309
3310macro_rules! _default_str {
3311    ($default:expr, $ty:ty) => {{
3312        let val = default_val!($default, $ty);
3313        serde_json::to_string_pretty(&val).unwrap()
3314    }};
3315}
3316use _default_str as default_str;
3317
3318macro_rules! _impl_for_config_data {
3319    (local, $(
3320            $(#[doc=$doc:literal])*
3321            $vis:vis $field:ident : $ty:ty = $default:expr,
3322        )*
3323    ) => {
3324        impl Config {
3325            $(
3326                $($doc)*
3327                #[allow(non_snake_case)]
3328                $vis fn $field(&self, source_root: Option<SourceRootId>) -> &$ty {
3329                    let mut source_root = source_root.as_ref();
3330                    while let Some(sr) = source_root {
3331                        if let Some((file, _)) = self.ratoml_file.get(&sr) {
3332                            match file {
3333                                RatomlFile::Workspace(config) => {
3334                                    if let Some(v) = config.local.$field.as_ref() {
3335                                        return &v;
3336                                    }
3337                                },
3338                                RatomlFile::Crate(config) => {
3339                                    if let Some(value) = config.$field.as_ref() {
3340                                        return value;
3341                                    }
3342                                }
3343                            }
3344                        }
3345                        source_root = self.source_root_parent_map.get(&sr);
3346                    }
3347
3348                    if let Some(v) = self.client_config.0.local.$field.as_ref() {
3349                        return &v;
3350                    }
3351
3352                    if let Some((user_config, _)) = self.user_config.as_ref() {
3353                        if let Some(v) = user_config.local.$field.as_ref() {
3354                            return &v;
3355                        }
3356                    }
3357
3358                    &self.default_config.local.$field
3359                }
3360            )*
3361        }
3362    };
3363    (workspace, $(
3364            $(#[doc=$doc:literal])*
3365            $vis:vis $field:ident : $ty:ty = $default:expr,
3366        )*
3367    ) => {
3368        impl Config {
3369            $(
3370                $($doc)*
3371                #[allow(non_snake_case)]
3372                $vis fn $field(&self, source_root: Option<SourceRootId>) -> &$ty {
3373                    let mut source_root = source_root.as_ref();
3374                    while let Some(sr) = source_root {
3375                        if let Some((RatomlFile::Workspace(config), _)) = self.ratoml_file.get(&sr) {
3376                            if let Some(v) = config.workspace.$field.as_ref() {
3377                                return &v;
3378                            }
3379                        }
3380                        source_root = self.source_root_parent_map.get(&sr);
3381                    }
3382
3383                    if let Some(v) = self.client_config.0.workspace.$field.as_ref() {
3384                        return &v;
3385                    }
3386
3387                    if let Some((user_config, _)) = self.user_config.as_ref() {
3388                        if let Some(v) = user_config.workspace.$field.as_ref() {
3389                            return &v;
3390                        }
3391                    }
3392
3393                    &self.default_config.workspace.$field
3394                }
3395            )*
3396        }
3397    };
3398    (global, $(
3399            $(#[doc=$doc:literal])*
3400            $vis:vis $field:ident : $ty:ty = $default:expr,
3401        )*
3402    ) => {
3403        impl Config {
3404            $(
3405                $($doc)*
3406                #[allow(non_snake_case)]
3407                $vis fn $field(&self) -> &$ty {
3408                    if let Some(v) = self.client_config.0.global.$field.as_ref() {
3409                        return &v;
3410                    }
3411
3412                    if let Some((user_config, _)) = self.user_config.as_ref() {
3413                        if let Some(v) = user_config.global.$field.as_ref() {
3414                            return &v;
3415                        }
3416                    }
3417
3418
3419                    &self.default_config.global.$field
3420                }
3421            )*
3422        }
3423    };
3424    (client, $(
3425            $(#[doc=$doc:literal])*
3426            $vis:vis $field:ident : $ty:ty = $default:expr,
3427       )*
3428    ) => {
3429        impl Config {
3430            $(
3431                $($doc)*
3432                #[allow(non_snake_case)]
3433                $vis fn $field(&self) -> &$ty {
3434                    if let Some(v) = self.client_config.0.client.$field.as_ref() {
3435                        return &v;
3436                    }
3437
3438                    &self.default_config.client.$field
3439                }
3440            )*
3441        }
3442    };
3443}
3444use _impl_for_config_data as impl_for_config_data;
3445
3446macro_rules! _config_data {
3447    // modname is for the tests
3448    ($(#[doc=$dox:literal])* $modname:ident: struct $name:ident <- $input:ident -> {
3449        $(
3450            $(#[doc=$doc:literal])*
3451            $vis:vis $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
3452        )*
3453    }) => {
3454        /// Default config values for this grouping.
3455        #[allow(non_snake_case)]
3456        #[derive(Debug, Clone)]
3457        struct $name { $($field: $ty,)* }
3458
3459        impl_for_config_data!{
3460            $modname,
3461            $(
3462                $vis $field : $ty = $default,
3463            )*
3464        }
3465
3466        /// All fields `Option<T>`, `None` representing fields not set in a particular JSON/TOML blob.
3467        #[allow(non_snake_case)]
3468        #[derive(Clone, Default)]
3469        struct $input { $(
3470            $field: Option<$ty>,
3471        )* }
3472
3473        impl std::fmt::Debug for $input {
3474            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3475                let mut s = f.debug_struct(stringify!($input));
3476                $(
3477                    if let Some(val) = self.$field.as_ref() {
3478                        s.field(stringify!($field), val);
3479                    }
3480                )*
3481                s.finish()
3482            }
3483        }
3484
3485        impl Default for $name {
3486            fn default() -> Self {
3487                $name {$(
3488                    $field: default_val!($default, $ty),
3489                )*}
3490            }
3491        }
3492
3493        #[allow(unused, clippy::ptr_arg)]
3494        impl $input {
3495            const FIELDS: &'static [&'static str] = &[$(stringify!($field)),*];
3496
3497            fn from_json(json: &mut serde_json::Value, error_sink: &mut Vec<(String, serde_json::Error)>) -> Self {
3498                Self {$(
3499                    $field: get_field_json(
3500                        json,
3501                        error_sink,
3502                        stringify!($field),
3503                        None$(.or(Some(stringify!($alias))))*,
3504                    ),
3505                )*}
3506            }
3507
3508            fn from_toml(toml: &toml::Table, error_sink: &mut Vec<(String, toml::de::Error)>) -> Self {
3509                Self {$(
3510                    $field: get_field_toml::<$ty>(
3511                        toml,
3512                        error_sink,
3513                        stringify!($field),
3514                        None$(.or(Some(stringify!($alias))))*,
3515                    ),
3516                )*}
3517            }
3518
3519            fn schema_fields(sink: &mut Vec<SchemaField>) {
3520                sink.extend_from_slice(&[
3521                    $({
3522                        let field = stringify!($field);
3523                        let ty = stringify!($ty);
3524                        let default = default_str!($default, $ty);
3525
3526                        (field, ty, &[$($doc),*], default)
3527                    },)*
3528                ])
3529            }
3530        }
3531
3532        mod $modname {
3533            #[test]
3534            fn fields_are_sorted() {
3535                super::$input::FIELDS.windows(2).for_each(|w| assert!(w[0] <= w[1], "{} <= {} does not hold", w[0], w[1]));
3536            }
3537        }
3538    };
3539}
3540use _config_data as config_data;
3541
3542#[derive(Default, Debug, Clone)]
3543struct DefaultConfigData {
3544    global: GlobalDefaultConfigData,
3545    workspace: WorkspaceDefaultConfigData,
3546    local: LocalDefaultConfigData,
3547    client: ClientDefaultConfigData,
3548}
3549
3550/// All of the config levels, all fields `Option<T>`, to describe fields that are actually set by
3551/// some rust-analyzer.toml file or JSON blob. An empty rust-analyzer.toml corresponds to
3552/// all fields being None.
3553#[derive(Debug, Clone, Default)]
3554struct FullConfigInput {
3555    global: GlobalConfigInput,
3556    workspace: WorkspaceConfigInput,
3557    local: LocalConfigInput,
3558    client: ClientConfigInput,
3559}
3560
3561impl FullConfigInput {
3562    fn from_json(
3563        mut json: serde_json::Value,
3564        error_sink: &mut Vec<(String, serde_json::Error)>,
3565    ) -> FullConfigInput {
3566        FullConfigInput {
3567            global: GlobalConfigInput::from_json(&mut json, error_sink),
3568            local: LocalConfigInput::from_json(&mut json, error_sink),
3569            client: ClientConfigInput::from_json(&mut json, error_sink),
3570            workspace: WorkspaceConfigInput::from_json(&mut json, error_sink),
3571        }
3572    }
3573
3574    fn schema_fields() -> Vec<SchemaField> {
3575        let mut fields = Vec::new();
3576        GlobalConfigInput::schema_fields(&mut fields);
3577        LocalConfigInput::schema_fields(&mut fields);
3578        ClientConfigInput::schema_fields(&mut fields);
3579        WorkspaceConfigInput::schema_fields(&mut fields);
3580        fields.sort_by_key(|&(x, ..)| x);
3581        fields
3582            .iter()
3583            .array_windows()
3584            .for_each(|[a, b]| assert!(a.0 != b.0, "{a:?} duplicate field"));
3585        fields
3586    }
3587
3588    fn json_schema() -> serde_json::Value {
3589        schema(&Self::schema_fields())
3590    }
3591
3592    #[cfg(test)]
3593    fn manual() -> String {
3594        manual(&Self::schema_fields())
3595    }
3596}
3597
3598/// All of the config levels, all fields `Option<T>`, to describe fields that are actually set by
3599/// some rust-analyzer.toml file or JSON blob. An empty rust-analyzer.toml corresponds to
3600/// all fields being None.
3601#[derive(Debug, Clone, Default)]
3602struct GlobalWorkspaceLocalConfigInput {
3603    global: GlobalConfigInput,
3604    local: LocalConfigInput,
3605    workspace: WorkspaceConfigInput,
3606}
3607
3608impl GlobalWorkspaceLocalConfigInput {
3609    const FIELDS: &'static [&'static [&'static str]] =
3610        &[GlobalConfigInput::FIELDS, LocalConfigInput::FIELDS];
3611    fn from_toml(
3612        toml: toml::Table,
3613        error_sink: &mut Vec<(String, toml::de::Error)>,
3614    ) -> GlobalWorkspaceLocalConfigInput {
3615        GlobalWorkspaceLocalConfigInput {
3616            global: GlobalConfigInput::from_toml(&toml, error_sink),
3617            local: LocalConfigInput::from_toml(&toml, error_sink),
3618            workspace: WorkspaceConfigInput::from_toml(&toml, error_sink),
3619        }
3620    }
3621}
3622
3623/// Workspace and local config levels, all fields `Option<T>`, to describe fields that are actually set by
3624/// some rust-analyzer.toml file or JSON blob. An empty rust-analyzer.toml corresponds to
3625/// all fields being None.
3626#[derive(Debug, Clone, Default)]
3627#[allow(dead_code)]
3628struct WorkspaceLocalConfigInput {
3629    workspace: WorkspaceConfigInput,
3630    local: LocalConfigInput,
3631}
3632
3633impl WorkspaceLocalConfigInput {
3634    #[allow(dead_code)]
3635    const FIELDS: &'static [&'static [&'static str]] =
3636        &[WorkspaceConfigInput::FIELDS, LocalConfigInput::FIELDS];
3637    fn from_toml(toml: toml::Table, error_sink: &mut Vec<(String, toml::de::Error)>) -> Self {
3638        Self {
3639            workspace: WorkspaceConfigInput::from_toml(&toml, error_sink),
3640            local: LocalConfigInput::from_toml(&toml, error_sink),
3641        }
3642    }
3643}
3644
3645fn get_field_json<T: DeserializeOwned>(
3646    json: &mut serde_json::Value,
3647    error_sink: &mut Vec<(String, serde_json::Error)>,
3648    field: &'static str,
3649    alias: Option<&'static str>,
3650) -> Option<T> {
3651    // XXX: check alias first, to work around the VS Code where it pre-fills the
3652    // defaults instead of sending an empty object.
3653    alias
3654        .into_iter()
3655        .chain(iter::once(field))
3656        .filter_map(move |field| {
3657            let mut pointer = field.replace('_', "/");
3658            pointer.insert(0, '/');
3659            json.pointer_mut(&pointer)
3660                .map(|it| serde_json::from_value(it.take()).map_err(|e| (e, pointer)))
3661        })
3662        .flat_map(|res| match res {
3663            Ok(it) => Some(it),
3664            Err((e, pointer)) => {
3665                tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
3666                error_sink.push((pointer, e));
3667                None
3668            }
3669        })
3670        .next()
3671}
3672
3673fn get_field_toml<T: DeserializeOwned>(
3674    toml: &toml::Table,
3675    error_sink: &mut Vec<(String, toml::de::Error)>,
3676    field: &'static str,
3677    alias: Option<&'static str>,
3678) -> Option<T> {
3679    // XXX: check alias first, to work around the VS Code where it pre-fills the
3680    // defaults instead of sending an empty object.
3681    alias
3682        .into_iter()
3683        .chain(iter::once(field))
3684        .filter_map(move |field| {
3685            let mut pointer = field.replace('_', "/");
3686            pointer.insert(0, '/');
3687            toml_pointer(toml, &pointer)
3688                .map(|it| <_>::deserialize(it.clone()).map_err(|e| (e, pointer)))
3689        })
3690        .find(Result::is_ok)
3691        .and_then(|res| match res {
3692            Ok(it) => Some(it),
3693            Err((e, pointer)) => {
3694                tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
3695                error_sink.push((pointer, e));
3696                None
3697            }
3698        })
3699}
3700
3701fn toml_pointer<'a>(toml: &'a toml::Table, pointer: &str) -> Option<&'a toml::Value> {
3702    fn parse_index(s: &str) -> Option<usize> {
3703        if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
3704            return None;
3705        }
3706        s.parse().ok()
3707    }
3708
3709    if pointer.is_empty() {
3710        return None;
3711    }
3712    if !pointer.starts_with('/') {
3713        return None;
3714    }
3715    let mut parts = pointer.split('/').skip(1);
3716    let first = parts.next()?;
3717    let init = toml.get(first)?;
3718    parts.map(|x| x.replace("~1", "/").replace("~0", "~")).try_fold(init, |target, token| {
3719        match target {
3720            toml::Value::Table(table) => table.get(&token),
3721            toml::Value::Array(list) => parse_index(&token).and_then(move |x| list.get(x)),
3722            _ => None,
3723        }
3724    })
3725}
3726
3727type SchemaField = (&'static str, &'static str, &'static [&'static str], String);
3728
3729fn schema(fields: &[SchemaField]) -> serde_json::Value {
3730    let map = fields
3731        .iter()
3732        .map(|(field, ty, doc, default)| {
3733            let name = field.replace('_', ".");
3734            let category = name
3735                .split_once(".")
3736                .map(|(category, _name)| to_title_case(category))
3737                .unwrap_or("rust-analyzer".into());
3738            let name = format!("rust-analyzer.{name}");
3739            let props = field_props(field, ty, doc, default);
3740            serde_json::json!({
3741                "title": category,
3742                "properties": {
3743                    name: props
3744                }
3745            })
3746        })
3747        .collect::<Vec<_>>();
3748    map.into()
3749}
3750
3751/// Translate a field name to a title case string suitable for use in the category names on the
3752/// vscode settings page.
3753///
3754/// First letter of word should be uppercase, if an uppercase letter is encountered, add a space
3755/// before it e.g. "fooBar" -> "Foo Bar", "fooBarBaz" -> "Foo Bar Baz", "foo" -> "Foo"
3756///
3757/// This likely should be in stdx (or just use heck instead), but it doesn't handle any edge cases
3758/// and is intentionally simple.
3759fn to_title_case(s: &str) -> String {
3760    let mut result = String::with_capacity(s.len());
3761    let mut chars = s.chars();
3762    if let Some(first) = chars.next() {
3763        result.push(first.to_ascii_uppercase());
3764        for c in chars {
3765            if c.is_uppercase() {
3766                result.push(' ');
3767            }
3768            result.push(c);
3769        }
3770    }
3771    result
3772}
3773
3774fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
3775    let doc = doc_comment_to_string(doc);
3776    let doc = doc.trim_end_matches('\n');
3777    assert!(
3778        doc.ends_with('.') && doc.starts_with(char::is_uppercase),
3779        "bad docs for {field}: {doc:?}"
3780    );
3781    let default = default.parse::<serde_json::Value>().unwrap();
3782
3783    let mut map = serde_json::Map::default();
3784    macro_rules! set {
3785        ($($key:literal: $value:tt),*$(,)?) => {{$(
3786            map.insert($key.into(), serde_json::json!($value));
3787        )*}};
3788    }
3789    set!("markdownDescription": doc);
3790    set!("default": default);
3791
3792    match ty {
3793        "bool" => set!("type": "boolean"),
3794        "usize" => set!("type": "integer", "minimum": 0),
3795        "String" => set!("type": "string"),
3796        "Vec<String>" => set! {
3797            "type": "array",
3798            "items": { "type": "string" },
3799        },
3800        "Vec<Utf8PathBuf>" => set! {
3801            "type": "array",
3802            "items": { "type": "string" },
3803        },
3804        "FxHashSet<String>" => set! {
3805            "type": "array",
3806            "items": { "type": "string" },
3807            "uniqueItems": true,
3808        },
3809        "FxHashMap<Box<str>, Box<[Box<str>]>>" => set! {
3810            "type": "object",
3811        },
3812        "FxIndexMap<String, SnippetDef>" => set! {
3813            "type": "object",
3814        },
3815        "FxHashMap<String, String>" => set! {
3816            "type": "object",
3817        },
3818        "FxHashMap<Box<str>, u16>" => set! {
3819            "type": "object",
3820        },
3821        "FxHashMap<String, Option<String>>" => set! {
3822            "type": "object",
3823        },
3824        "Option<usize>" => set! {
3825            "type": ["null", "integer"],
3826            "minimum": 0,
3827        },
3828        "Option<u16>" => set! {
3829            "type": ["null", "integer"],
3830            "minimum": 0,
3831            "maximum": 65535,
3832        },
3833        "Option<String>" => set! {
3834            "type": ["null", "string"],
3835        },
3836        "Option<Utf8PathBuf>" => set! {
3837            "type": ["null", "string"],
3838        },
3839        "Option<bool>" => set! {
3840            "type": ["null", "boolean"],
3841        },
3842        "Option<Vec<String>>" => set! {
3843            "type": ["null", "array"],
3844            "items": { "type": "string" },
3845        },
3846        "ExprFillDefaultDef" => set! {
3847            "type": "string",
3848            "enum": ["todo", "default"],
3849            "enumDescriptions": [
3850                "Fill missing expressions with the `todo` macro",
3851                "Fill missing expressions with reasonable defaults, `new` or `default` constructors."
3852            ],
3853        },
3854        "ImportGranularityDef" => set! {
3855            "type": "string",
3856            "enum": ["crate", "module", "item", "one", "preserve"],
3857            "enumDescriptions": [
3858                "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
3859                "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
3860                "Flatten imports so that each has its own use statement.",
3861                "Merge all imports into a single use statement as long as they have the same visibility and attributes.",
3862                "Deprecated - unless `enforceGranularity` is `true`, the style of the current file is preferred over this setting. Behaves like `item`."
3863            ],
3864        },
3865        "ImportPrefixDef" => set! {
3866            "type": "string",
3867            "enum": [
3868                "plain",
3869                "self",
3870                "crate"
3871            ],
3872            "enumDescriptions": [
3873                "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
3874                "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item. Prefixes `self` in front of the path if it starts with a module.",
3875                "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
3876            ],
3877        },
3878        "Vec<ManifestOrProjectJson>" => set! {
3879            "type": "array",
3880            "items": { "type": ["string", "object"] },
3881        },
3882        "WorkspaceSymbolSearchScopeDef" => set! {
3883            "type": "string",
3884            "enum": ["workspace", "workspace_and_dependencies"],
3885            "enumDescriptions": [
3886                "Search in current workspace only.",
3887                "Search in current workspace and dependencies."
3888            ],
3889        },
3890        "WorkspaceSymbolSearchKindDef" => set! {
3891            "type": "string",
3892            "enum": ["only_types", "all_symbols"],
3893            "enumDescriptions": [
3894                "Search for types only.",
3895                "Search for all symbols kinds."
3896            ],
3897        },
3898        "LifetimeElisionDef" => set! {
3899            "type": "string",
3900            "enum": [
3901                "always",
3902                "never",
3903                "skip_trivial"
3904            ],
3905            "enumDescriptions": [
3906                "Always show lifetime elision hints.",
3907                "Never show lifetime elision hints.",
3908                "Only show lifetime elision hints if a return type is involved."
3909            ]
3910        },
3911        "ImplicitDropDef" => set! {
3912            "type":"string",
3913            "enum": [
3914                "always",
3915                "never",
3916                "with_drop_glue"
3917            ],
3918            "enumDescriptions": [
3919                "Always show drop hints.",
3920                "Never show drop hints.",
3921                "Only show drop hints for values with drop glue."
3922            ]
3923        },
3924        "ClosureReturnTypeHintsDef" => set! {
3925            "type": "string",
3926            "enum": [
3927                "always",
3928                "never",
3929                "with_block"
3930            ],
3931            "enumDescriptions": [
3932                "Always show type hints for return types of closures.",
3933                "Never show type hints for return types of closures.",
3934                "Only show type hints for return types of closures with blocks."
3935            ]
3936        },
3937        "ReborrowHintsDef" => set! {
3938            "type": "string",
3939            "enum": [
3940                "always",
3941                "never",
3942                "mutable"
3943            ],
3944            "enumDescriptions": [
3945                "Always show reborrow hints.",
3946                "Never show reborrow hints.",
3947                "Only show mutable reborrow hints."
3948            ]
3949        },
3950        "AdjustmentHintsDef" => set! {
3951            "type": "string",
3952            "enum": [
3953                "always",
3954                "never",
3955                "reborrow"
3956            ],
3957            "enumDescriptions": [
3958                "Always show all adjustment hints.",
3959                "Never show adjustment hints.",
3960                "Only show auto borrow and dereference adjustment hints."
3961            ]
3962        },
3963        "DiscriminantHintsDef" => set! {
3964            "type": "string",
3965            "enum": [
3966                "always",
3967                "never",
3968                "fieldless"
3969            ],
3970            "enumDescriptions": [
3971                "Always show all discriminant hints.",
3972                "Never show discriminant hints.",
3973                "Only show discriminant hints on fieldless enum variants."
3974            ]
3975        },
3976        "AdjustmentHintsModeDef" => set! {
3977            "type": "string",
3978            "enum": [
3979                "prefix",
3980                "postfix",
3981                "prefer_prefix",
3982                "prefer_postfix",
3983            ],
3984            "enumDescriptions": [
3985                "Always show adjustment hints as prefix (`*expr`).",
3986                "Always show adjustment hints as postfix (`expr.*`).",
3987                "Show prefix or postfix depending on which uses less parenthesis, preferring prefix.",
3988                "Show prefix or postfix depending on which uses less parenthesis, preferring postfix.",
3989            ]
3990        },
3991        "CargoFeaturesDef" => set! {
3992            "anyOf": [
3993                {
3994                    "type": "string",
3995                    "enum": [
3996                        "all"
3997                    ],
3998                    "enumDescriptions": [
3999                        "Pass `--all-features` to cargo",
4000                    ]
4001                },
4002                {
4003                    "type": "array",
4004                    "items": { "type": "string" }
4005                }
4006            ],
4007        },
4008        "Option<CargoFeaturesDef>" => set! {
4009            "anyOf": [
4010                {
4011                    "type": "string",
4012                    "enum": [
4013                        "all"
4014                    ],
4015                    "enumDescriptions": [
4016                        "Pass `--all-features` to cargo",
4017                    ]
4018                },
4019                {
4020                    "type": "array",
4021                    "items": { "type": "string" }
4022                },
4023                { "type": "null" }
4024            ],
4025        },
4026        "CallableCompletionDef" => set! {
4027            "type": "string",
4028            "enum": [
4029                "fill_arguments",
4030                "add_parentheses",
4031                "none",
4032            ],
4033            "enumDescriptions": [
4034                "Add call parentheses and pre-fill arguments.",
4035                "Add call parentheses.",
4036                "Do no snippet completions for callables."
4037            ]
4038        },
4039        "SignatureDetail" => set! {
4040            "type": "string",
4041            "enum": ["full", "parameters"],
4042            "enumDescriptions": [
4043                "Show the entire signature.",
4044                "Show only the parameters."
4045            ],
4046        },
4047        "FilesWatcherDef" => set! {
4048            "type": "string",
4049            "enum": ["client", "server"],
4050            "enumDescriptions": [
4051                "Use the client (editor) to watch files for changes",
4052                "Use server-side file watching",
4053            ],
4054        },
4055        "AnnotationLocation" => set! {
4056            "type": "string",
4057            "enum": ["above_name", "above_whole_item"],
4058            "enumDescriptions": [
4059                "Render annotations above the name of the item.",
4060                "Render annotations above the whole item, including documentation comments and attributes."
4061            ],
4062        },
4063        "InvocationStrategy" => set! {
4064            "type": "string",
4065            "enum": ["per_workspace", "once"],
4066            "enumDescriptions": [
4067                "The command will be executed for each Rust workspace with the workspace as the working directory.",
4068                "The command will be executed once with the opened project as the working directory.\
4069                \n\n**Warning:** This can cause errors when the Cargo configuration of the opened workspaces is different \
4070                or even only different than the default. Enabling this is not recommended."
4071            ],
4072        },
4073        "Option<CheckOnSaveTargets>" => set! {
4074            "anyOf": [
4075                {
4076                    "type": "null"
4077                },
4078                {
4079                    "type": "string",
4080                },
4081                {
4082                    "type": "array",
4083                    "items": { "type": "string" }
4084                },
4085            ],
4086        },
4087        "ClosureStyle" => set! {
4088            "type": "string",
4089            "enum": ["impl_fn", "rust_analyzer", "with_id", "hide"],
4090            "enumDescriptions": [
4091                "`impl_fn`: `impl FnMut(i32, u64) -> i8`",
4092                "`rust_analyzer`: `|i32, u64| -> i8`",
4093                "`with_id`: `{closure#14352}`, where that id is the unique number of the closure in r-a internals",
4094                "`hide`: Shows `...` for every closure type",
4095            ],
4096        },
4097        "TypeHintsLocation" => set! {
4098            "type": "string",
4099            "enum": ["inline", "end_of_line"],
4100            "enumDescriptions": [
4101                "Render type hints directly after the binding identifier.",
4102                "Render type hints after the end of the containing `let` statement when possible.",
4103            ],
4104        },
4105        "Option<MemoryLayoutHoverRenderKindDef>" => set! {
4106            "anyOf": [
4107                {
4108                    "type": "null"
4109                },
4110                {
4111                    "type": "string",
4112                    "enum": ["both", "decimal", "hexadecimal", ],
4113                    "enumDescriptions": [
4114                        "Render as 12 (0xC)",
4115                        "Render as 12",
4116                        "Render as 0xC"
4117                    ],
4118                },
4119            ],
4120        },
4121        "Option<TargetDirectory>" => set! {
4122            "anyOf": [
4123                {
4124                    "type": "null"
4125                },
4126                {
4127                    "type": "boolean"
4128                },
4129                {
4130                    "type": "string"
4131                },
4132            ],
4133        },
4134        "NumThreads" => set! {
4135            "anyOf": [
4136                {
4137                    "type": "number",
4138                    "minimum": 0,
4139                    "maximum": 255
4140                },
4141                {
4142                    "type": "string",
4143                    "enum": ["physical", "logical", ],
4144                    "enumDescriptions": [
4145                        "Use the number of physical cores",
4146                        "Use the number of logical cores",
4147                    ],
4148                },
4149            ],
4150        },
4151        "NumProcesses" => set! {
4152            "anyOf": [
4153                {
4154                    "type": "number",
4155                    "minimum": 0,
4156                    "maximum": 255
4157                },
4158                {
4159                    "type": "string",
4160                    "enum": ["physical"],
4161                    "enumDescriptions": [
4162                        "Use the number of physical cores",
4163                    ],
4164                },
4165            ],
4166        },
4167        "Option<NumThreads>" => set! {
4168            "anyOf": [
4169                {
4170                    "type": "null"
4171                },
4172                {
4173                    "type": "number",
4174                    "minimum": 0,
4175                    "maximum": 255
4176                },
4177                {
4178                    "type": "string",
4179                    "enum": ["physical", "logical", ],
4180                    "enumDescriptions": [
4181                        "Use the number of physical cores",
4182                        "Use the number of logical cores",
4183                    ],
4184                },
4185            ],
4186        },
4187        "Option<DiscoverWorkspaceConfig>" => set! {
4188            "anyOf": [
4189                {
4190                    "type": "null"
4191                },
4192                {
4193                    "type": "object",
4194                    "properties": {
4195                        "command": {
4196                            "type": "array",
4197                            "items": { "type": "string" }
4198                        },
4199                        "progressLabel": {
4200                            "type": "string"
4201                        },
4202                        "filesToWatch": {
4203                            "type": "array",
4204                            "items": { "type": "string" }
4205                        },
4206                    }
4207                }
4208            ]
4209        },
4210        "Option<MaxSubstitutionLength>" => set! {
4211            "anyOf": [
4212                {
4213                    "type": "null"
4214                },
4215                {
4216                    "type": "string",
4217                    "enum": ["hide"]
4218                },
4219                {
4220                    "type": "integer"
4221                }
4222            ]
4223        },
4224        "Vec<AutoImportExclusion>" => set! {
4225            "type": "array",
4226            "items": {
4227                "anyOf": [
4228                    {
4229                        "type": "string",
4230                    },
4231                    {
4232                        "type": "object",
4233                        "properties": {
4234                            "path": {
4235                                "type": "string",
4236                            },
4237                            "type": {
4238                                "type": "string",
4239                                "enum": ["always", "methods", "sub_items", "variants"],
4240                                "enumDescriptions": [
4241                                    "Do not show this item or its methods (if it is a trait) in auto-import completions.",
4242                                    "Do not show this trait's methods in auto-import completions.",
4243                                    "Do not show this module's all items in it in auto-import completions.",
4244                                    "Do not show this enum's variants in auto-import completions."
4245                                ],
4246                            },
4247                        }
4248                    }
4249                ]
4250             }
4251        },
4252        _ => panic!("missing entry for {ty}: {default} (field {field})"),
4253    }
4254
4255    map.into()
4256}
4257
4258fn validate_toml_table(
4259    known_ptrs: &[&[&'static str]],
4260    toml: &toml::Table,
4261    ptr: &mut String,
4262    error_sink: &mut Vec<(String, toml::de::Error)>,
4263) {
4264    let verify = |ptr: &String| known_ptrs.iter().any(|ptrs| ptrs.contains(&ptr.as_str()));
4265
4266    let l = ptr.len();
4267    for (k, v) in toml {
4268        if !ptr.is_empty() {
4269            ptr.push('_');
4270        }
4271        ptr.push_str(k);
4272
4273        match v {
4274            // This is a table config, any entry in it is therefore valid
4275            toml::Value::Table(_) if verify(ptr) => (),
4276            toml::Value::Table(table) => validate_toml_table(known_ptrs, table, ptr, error_sink),
4277            _ if !verify(ptr) => error_sink
4278                .push((ptr.replace('_', "/"), toml::de::Error::custom("unexpected field"))),
4279            _ => (),
4280        }
4281
4282        ptr.truncate(l);
4283    }
4284}
4285
4286#[cfg(test)]
4287fn manual(fields: &[SchemaField]) -> String {
4288    fields.iter().fold(String::new(), |mut acc, (field, _ty, doc, default)| {
4289        let id = field.replace('_', ".");
4290        let name = format!("rust-analyzer.{id}");
4291        let doc = doc_comment_to_string(doc);
4292        if default.contains('\n') {
4293            format_to_acc!(
4294                acc,
4295                "## {name} {{#{id}}}\n\nDefault:\n```json\n{default}\n```\n\n{doc}\n\n"
4296            )
4297        } else {
4298            format_to_acc!(acc, "## {name} {{#{id}}}\n\nDefault: `{default}`\n\n{doc}\n\n")
4299        }
4300    })
4301}
4302
4303fn doc_comment_to_string(doc: &[&str]) -> String {
4304    doc.iter()
4305        .map(|it| it.strip_prefix(' ').unwrap_or(it))
4306        .fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n"))
4307}
4308
4309#[cfg(test)]
4310mod tests {
4311    use std::{borrow::Cow, fs};
4312
4313    use test_utils::{ensure_file_contents, project_root};
4314
4315    use super::*;
4316
4317    #[test]
4318    fn generate_package_json_config() {
4319        let s = Config::json_schema();
4320
4321        let schema = format!("{s:#}");
4322        let mut schema = schema
4323            .trim_start_matches('[')
4324            .trim_end_matches(']')
4325            .replace("  ", "    ")
4326            .replace('\n', "\n        ")
4327            .trim_start_matches('\n')
4328            .trim_end()
4329            .to_owned();
4330        schema.push_str(",\n");
4331
4332        // Transform the asciidoc form link to markdown style.
4333        //
4334        // https://link[text] => [text](https://link)
4335        let url_matches = schema.match_indices("https://");
4336        let mut url_offsets = url_matches.map(|(idx, _)| idx).collect::<Vec<usize>>();
4337        url_offsets.reverse();
4338        for idx in url_offsets {
4339            let link = &schema[idx..];
4340            // matching on whitespace to ignore normal links
4341            if let Some(link_end) = link.find([' ', '['])
4342                && link.chars().nth(link_end) == Some('[')
4343                && let Some(link_text_end) = link.find(']')
4344            {
4345                let link_text = link[link_end..(link_text_end + 1)].to_string();
4346
4347                schema.replace_range((idx + link_end)..(idx + link_text_end + 1), "");
4348                schema.insert(idx, '(');
4349                schema.insert(idx + link_end + 1, ')');
4350                schema.insert_str(idx, &link_text);
4351            }
4352        }
4353
4354        let package_json_path = project_root().join("editors/code/package.json");
4355        let mut package_json = fs::read_to_string(&package_json_path).unwrap();
4356
4357        let start_marker =
4358            "            {\n                \"title\": \"$generated-start\"\n            },\n";
4359        let end_marker =
4360            "            {\n                \"title\": \"$generated-end\"\n            }\n";
4361
4362        let start = package_json.find(start_marker).unwrap() + start_marker.len();
4363        let end = package_json.find(end_marker).unwrap();
4364
4365        let p = remove_ws(&package_json[start..end]);
4366        let s = remove_ws(&schema);
4367        if !p.contains(&s) {
4368            package_json.replace_range(start..end, &schema);
4369            ensure_file_contents(package_json_path.as_std_path(), &package_json)
4370        }
4371    }
4372
4373    #[test]
4374    fn generate_config_documentation() {
4375        let docs_path = project_root().join("docs/book/src/configuration_generated.md");
4376        let expected = FullConfigInput::manual();
4377        ensure_file_contents(docs_path.as_std_path(), &expected);
4378    }
4379
4380    fn remove_ws(text: &str) -> String {
4381        text.replace(char::is_whitespace, "")
4382    }
4383
4384    #[test]
4385    fn proc_macro_srv_null() {
4386        let mut config =
4387            Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4388
4389        let mut change = ConfigChange::default();
4390        change.change_client_config(serde_json::json!({
4391            "procMacro" : {
4392                "server": null,
4393        }}));
4394
4395        (config, _, _) = config.apply_change(change);
4396        assert_eq!(config.proc_macro_srv(), None);
4397    }
4398
4399    #[test]
4400    fn proc_macro_srv_abs() {
4401        let mut config =
4402            Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4403        let mut change = ConfigChange::default();
4404        change.change_client_config(serde_json::json!({
4405        "procMacro" : {
4406            "server": project_root().to_string(),
4407        }}));
4408
4409        (config, _, _) = config.apply_change(change);
4410        assert_eq!(config.proc_macro_srv(), Some(AbsPathBuf::assert(project_root())));
4411    }
4412
4413    #[test]
4414    fn proc_macro_srv_rel() {
4415        let mut config =
4416            Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4417
4418        let mut change = ConfigChange::default();
4419
4420        change.change_client_config(serde_json::json!({
4421        "procMacro" : {
4422            "server": "./server"
4423        }}));
4424
4425        (config, _, _) = config.apply_change(change);
4426
4427        assert_eq!(
4428            config.proc_macro_srv(),
4429            Some(AbsPathBuf::try_from(project_root().join("./server")).unwrap())
4430        );
4431    }
4432
4433    #[test]
4434    fn cargo_target_dir_unset() {
4435        let mut config =
4436            Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4437
4438        let mut change = ConfigChange::default();
4439
4440        change.change_client_config(serde_json::json!({
4441            "rust" : { "analyzerTargetDir" : null }
4442        }));
4443
4444        (config, _, _) = config.apply_change(change);
4445        assert_eq!(config.cargo_targetDir(None), &None);
4446        assert!(matches!(
4447            config.flycheck(None),
4448            FlycheckConfig::Automatic {
4449                cargo_options: CargoOptions { target_dir_config: TargetDirectoryConfig::None, .. },
4450                ..
4451            }
4452        ));
4453    }
4454
4455    #[test]
4456    fn cargo_target_dir_subdir() {
4457        let mut config =
4458            Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4459
4460        let mut change = ConfigChange::default();
4461        change.change_client_config(serde_json::json!({
4462            "rust" : { "analyzerTargetDir" : true }
4463        }));
4464
4465        (config, _, _) = config.apply_change(change);
4466
4467        assert_eq!(config.cargo_targetDir(None), &Some(TargetDirectory::UseSubdirectory(true)));
4468        let ws_target_dir =
4469            Utf8PathBuf::from(std::env::var("CARGO_TARGET_DIR").unwrap_or("target".to_owned()));
4470        assert!(matches!(
4471            config.flycheck(None),
4472            FlycheckConfig::Automatic {
4473                cargo_options: CargoOptions { target_dir_config, .. },
4474                ..
4475            } if target_dir_config.target_dir(Some(&ws_target_dir)).map(Cow::into_owned)
4476                == Some(ws_target_dir.join("rust-analyzer"))
4477        ));
4478    }
4479
4480    #[test]
4481    fn cargo_target_dir_relative_dir() {
4482        let mut config =
4483            Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4484
4485        let mut change = ConfigChange::default();
4486        change.change_client_config(serde_json::json!({
4487            "rust" : { "analyzerTargetDir" : "other_folder" }
4488        }));
4489
4490        (config, _, _) = config.apply_change(change);
4491
4492        assert_eq!(
4493            config.cargo_targetDir(None),
4494            &Some(TargetDirectory::Directory(Utf8PathBuf::from("other_folder")))
4495        );
4496        assert!(matches!(
4497            config.flycheck(None),
4498            FlycheckConfig::Automatic {
4499                cargo_options: CargoOptions { target_dir_config, .. },
4500                ..
4501            } if target_dir_config.target_dir(None).map(Cow::into_owned)
4502                == Some(Utf8PathBuf::from("other_folder"))
4503        ));
4504    }
4505    #[test]
4506    fn postfix_snippet_item_scope_is_invalid() {
4507        let mut config =
4508            Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4509        let mut change = ConfigChange::default();
4510        change.change_client_config(serde_json::json!({
4511            "completion":{
4512                "snippets": {
4513                    "custom":{
4514                        "foo": {
4515                            "postfix": "foo",
4516                            "body": "foo",
4517                            "scope": "item"
4518                        }
4519                    }
4520                }
4521            }
4522        }));
4523        let errors;
4524        (config, errors, _) = config.apply_change(change);
4525        assert!(!errors.0.is_empty(), "expected a config error for postfix+item scope");
4526        assert!(
4527            config.snippets.iter().all(|s| s.postfix_triggers.iter().all(|t| &**t != "foo")),
4528            "invalid snippet should not have been registered"
4529        );
4530    }
4531}