1//! The Zed Rust Extension API allows you write extensions for [Zed](https://zed.dev/) in Rust.
2
3pub mod http_client;
4pub mod process;
5pub mod settings;
6
7use core::fmt;
8
9use wit::*;
10
11pub use serde_json;
12
13// WIT re-exports.
14//
15// We explicitly enumerate the symbols we want to re-export, as there are some
16// that we may want to shadow to provide a cleaner Rust API.
17pub use wit::{
18 CodeLabel, CodeLabelSpan, CodeLabelSpanLiteral, Command, DownloadedFileType, EnvVars,
19 KeyValueStore, LanguageServerInstallationStatus, Project, Range, Worktree, download_file,
20 make_file_executable,
21 zed::extension::context_server::ContextServerConfiguration,
22 zed::extension::dap::{
23 AttachRequest, BuildTaskDefinition, BuildTaskDefinitionTemplatePayload, BuildTaskTemplate,
24 DebugAdapterBinary, DebugConfig, DebugRequest, DebugScenario, DebugTaskDefinition,
25 LaunchRequest, StartDebuggingRequestArguments, StartDebuggingRequestArgumentsRequest,
26 TaskTemplate, TcpArguments, TcpArgumentsTemplate, resolve_tcp_template,
27 },
28 zed::extension::github::{
29 GithubRelease, GithubReleaseAsset, GithubReleaseOptions, github_release_by_tag_name,
30 latest_github_release,
31 },
32 zed::extension::llm_provider::{
33 CacheConfiguration as LlmCacheConfiguration, CompletionEvent as LlmCompletionEvent,
34 CompletionRequest as LlmCompletionRequest, CredentialType as LlmCredentialType,
35 ImageData as LlmImageData, MessageContent as LlmMessageContent,
36 MessageRole as LlmMessageRole, ModelCapabilities as LlmModelCapabilities,
37 ModelInfo as LlmModelInfo, OauthHttpRequest as LlmOauthHttpRequest,
38 OauthHttpResponse as LlmOauthHttpResponse, OauthWebAuthConfig as LlmOauthWebAuthConfig,
39 OauthWebAuthResult as LlmOauthWebAuthResult, ProviderInfo as LlmProviderInfo,
40 RequestMessage as LlmRequestMessage, StopReason as LlmStopReason,
41 ThinkingContent as LlmThinkingContent, TokenUsage as LlmTokenUsage,
42 ToolChoice as LlmToolChoice, ToolDefinition as LlmToolDefinition,
43 ToolInputFormat as LlmToolInputFormat, ToolResult as LlmToolResult,
44 ToolResultContent as LlmToolResultContent, ToolUse as LlmToolUse,
45 ToolUseJsonParseError as LlmToolUseJsonParseError,
46 delete_credential as llm_delete_credential, get_credential as llm_get_credential,
47 get_env_var as llm_get_env_var, oauth_open_browser as llm_oauth_open_browser,
48 oauth_start_web_auth as llm_oauth_start_web_auth,
49 request_credential as llm_request_credential,
50 send_oauth_http_request as llm_oauth_http_request,
51 store_credential as llm_store_credential,
52 },
53 zed::extension::nodejs::{
54 node_binary_path, npm_install_package, npm_package_installed_version,
55 npm_package_latest_version,
56 },
57 zed::extension::platform::{Architecture, Os, current_platform},
58 zed::extension::slash_command::{
59 SlashCommand, SlashCommandArgumentCompletion, SlashCommandOutput, SlashCommandOutputSection,
60 },
61};
62
63// Undocumented WIT re-exports.
64//
65// These are symbols that need to be public for the purposes of implementing
66// the extension host, but aren't relevant to extension authors.
67#[doc(hidden)]
68pub use wit::Guest;
69
70/// Constructs for interacting with language servers over the
71/// Language Server Protocol (LSP).
72pub mod lsp {
73 pub use crate::wit::zed::extension::lsp::{
74 Completion, CompletionKind, InsertTextFormat, Symbol, SymbolKind,
75 };
76}
77
78/// A result returned from a Zed extension.
79pub type Result<T, E = String> = core::result::Result<T, E>;
80
81/// Updates the installation status for the given language server.
82pub fn set_language_server_installation_status(
83 language_server_id: &LanguageServerId,
84 status: &LanguageServerInstallationStatus,
85) {
86 wit::set_language_server_installation_status(&language_server_id.0, status)
87}
88
89/// A Zed extension.
90pub trait Extension: Send + Sync {
91 /// Returns a new instance of the extension.
92 fn new() -> Self
93 where
94 Self: Sized;
95
96 /// Returns the command used to start the language server for the specified
97 /// language.
98 fn language_server_command(
99 &mut self,
100 _language_server_id: &LanguageServerId,
101 _worktree: &Worktree,
102 ) -> Result<Command> {
103 Err("`language_server_command` not implemented".to_string())
104 }
105
106 /// Returns the initialization options to pass to the specified language server.
107 fn language_server_initialization_options(
108 &mut self,
109 _language_server_id: &LanguageServerId,
110 _worktree: &Worktree,
111 ) -> Result<Option<serde_json::Value>> {
112 Ok(None)
113 }
114
115 /// Returns the workspace configuration options to pass to the language server.
116 fn language_server_workspace_configuration(
117 &mut self,
118 _language_server_id: &LanguageServerId,
119 _worktree: &Worktree,
120 ) -> Result<Option<serde_json::Value>> {
121 Ok(None)
122 }
123
124 /// Returns the initialization options to pass to the other language server.
125 fn language_server_additional_initialization_options(
126 &mut self,
127 _language_server_id: &LanguageServerId,
128 _target_language_server_id: &LanguageServerId,
129 _worktree: &Worktree,
130 ) -> Result<Option<serde_json::Value>> {
131 Ok(None)
132 }
133
134 /// Returns the workspace configuration options to pass to the other language server.
135 fn language_server_additional_workspace_configuration(
136 &mut self,
137 _language_server_id: &LanguageServerId,
138 _target_language_server_id: &LanguageServerId,
139 _worktree: &Worktree,
140 ) -> Result<Option<serde_json::Value>> {
141 Ok(None)
142 }
143
144 /// Returns the label for the given completion.
145 fn label_for_completion(
146 &self,
147 _language_server_id: &LanguageServerId,
148 _completion: Completion,
149 ) -> Option<CodeLabel> {
150 None
151 }
152
153 /// Returns the label for the given symbol.
154 fn label_for_symbol(
155 &self,
156 _language_server_id: &LanguageServerId,
157 _symbol: Symbol,
158 ) -> Option<CodeLabel> {
159 None
160 }
161
162 /// Returns the completions that should be shown when completing the provided slash command with the given query.
163 fn complete_slash_command_argument(
164 &self,
165 _command: SlashCommand,
166 _args: Vec<String>,
167 ) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
168 Ok(Vec::new())
169 }
170
171 /// Returns the output from running the provided slash command.
172 fn run_slash_command(
173 &self,
174 _command: SlashCommand,
175 _args: Vec<String>,
176 _worktree: Option<&Worktree>,
177 ) -> Result<SlashCommandOutput, String> {
178 Err("`run_slash_command` not implemented".to_string())
179 }
180
181 /// Returns the command used to start a context server.
182 fn context_server_command(
183 &mut self,
184 _context_server_id: &ContextServerId,
185 _project: &Project,
186 ) -> Result<Command> {
187 Err("`context_server_command` not implemented".to_string())
188 }
189
190 /// Returns the configuration options for the specified context server.
191 fn context_server_configuration(
192 &mut self,
193 _context_server_id: &ContextServerId,
194 _project: &Project,
195 ) -> Result<Option<ContextServerConfiguration>> {
196 Ok(None)
197 }
198
199 /// Returns a list of package names as suggestions to be included in the
200 /// search results of the `/docs` slash command.
201 ///
202 /// This can be used to provide completions for known packages (e.g., from the
203 /// local project or a registry) before a package has been indexed.
204 fn suggest_docs_packages(&self, _provider: String) -> Result<Vec<String>, String> {
205 Ok(Vec::new())
206 }
207
208 /// Indexes the docs for the specified package.
209 fn index_docs(
210 &self,
211 _provider: String,
212 _package: String,
213 _database: &KeyValueStore,
214 ) -> Result<(), String> {
215 Err("`index_docs` not implemented".to_string())
216 }
217
218 /// Returns the debug adapter binary for the specified adapter name and configuration.
219 fn get_dap_binary(
220 &mut self,
221 _adapter_name: String,
222 _config: DebugTaskDefinition,
223 _user_provided_debug_adapter_path: Option<String>,
224 _worktree: &Worktree,
225 ) -> Result<DebugAdapterBinary, String> {
226 Err("`get_dap_binary` not implemented".to_string())
227 }
228
229 /// Determines whether the specified adapter configuration should *launch* a new debuggee process
230 /// or *attach* to an existing one. This function should not perform any further validation (outside of determining the kind of a request).
231 /// This function should return an error when the kind cannot be determined (rather than fall back to a known default).
232 fn dap_request_kind(
233 &mut self,
234 _adapter_name: String,
235 _config: serde_json::Value,
236 ) -> Result<StartDebuggingRequestArgumentsRequest, String> {
237 Err("`dap_request_kind` not implemented".to_string())
238 }
239 /// Converts a high-level definition of a debug scenario (originating in a new session UI) to a "low-level" configuration suitable for a particular adapter.
240 ///
241 /// In layman's terms: given a program, list of arguments, current working directory and environment variables,
242 /// create a configuration that can be used to start a debug session.
243 fn dap_config_to_scenario(&mut self, _config: DebugConfig) -> Result<DebugScenario, String> {
244 Err("`dap_config_to_scenario` not implemented".to_string())
245 }
246
247 /// Locators are entities that convert a Zed task into a debug scenario.
248 ///
249 /// They can be provided even by extensions that don't provide a debug adapter.
250 /// For all tasks applicable to a given buffer, Zed will query all locators to find one that can turn the task into a debug scenario.
251 /// A converted debug scenario can include a build task (it shouldn't contain any configuration in such case); a build task result will later
252 /// be resolved with [`Extension::run_dap_locator`].
253 ///
254 /// To work through a real-world example, take a `cargo run` task and a hypothetical `cargo` locator:
255 /// 1. We may need to modify the task; in this case, it is problematic that `cargo run` spawns a binary. We should turn `cargo run` into a debug scenario with
256 /// `cargo build` task. This is the decision we make at `dap_locator_create_scenario` scope.
257 /// 2. Then, after the build task finishes, we will run `run_dap_locator` of the locator that produced the build task to find the program to be debugged. This function
258 /// should give us a debugger-agnostic configuration for launching a debug target (that we end up resolving with [`Extension::dap_config_to_scenario`]). It's almost as if the user
259 /// found the artifact path by themselves.
260 ///
261 /// Note that you're not obliged to use build tasks with locators. Specifically, it is sufficient to provide a debug configuration directly in the return value of
262 /// `dap_locator_create_scenario` if you're able to do that. Make sure to not fill out `build` field in that case, as that will prevent Zed from running second phase of resolution in such case.
263 /// This might be of particular relevance to interpreted languages.
264 fn dap_locator_create_scenario(
265 &mut self,
266 _locator_name: String,
267 _build_task: TaskTemplate,
268 _resolved_label: String,
269 _debug_adapter_name: String,
270 ) -> Option<DebugScenario> {
271 None
272 }
273
274 /// Runs the second phase of locator resolution.
275 /// See [`Extension::dap_locator_create_scenario`] for a hefty comment on locators.
276 fn run_dap_locator(
277 &mut self,
278 _locator_name: String,
279 _build_task: TaskTemplate,
280 ) -> Result<DebugRequest, String> {
281 Err("`run_dap_locator` not implemented".to_string())
282 }
283
284 /// Returns information about language model providers offered by this extension.
285 fn llm_providers(&self) -> Vec<LlmProviderInfo> {
286 Vec::new()
287 }
288
289 /// Returns the models available for a provider.
290 fn llm_provider_models(&self, _provider_id: &str) -> Result<Vec<LlmModelInfo>, String> {
291 Ok(Vec::new())
292 }
293
294 /// Returns markdown content to display in the provider's settings UI.
295 /// This can include setup instructions, links to documentation, etc.
296 fn llm_provider_settings_markdown(&self, _provider_id: &str) -> Option<String> {
297 None
298 }
299
300 /// Check if the provider is authenticated.
301 fn llm_provider_is_authenticated(&self, _provider_id: &str) -> bool {
302 false
303 }
304
305 /// Attempt to authenticate the provider.
306 fn llm_provider_authenticate(&mut self, _provider_id: &str) -> Result<(), String> {
307 Err("`llm_provider_authenticate` not implemented".to_string())
308 }
309
310 /// Reset credentials for the provider.
311 fn llm_provider_reset_credentials(&mut self, _provider_id: &str) -> Result<(), String> {
312 Err("`llm_provider_reset_credentials` not implemented".to_string())
313 }
314
315 /// Count tokens for a request.
316 fn llm_count_tokens(
317 &self,
318 _provider_id: &str,
319 _model_id: &str,
320 _request: &LlmCompletionRequest,
321 ) -> Result<u64, String> {
322 Err("`llm_count_tokens` not implemented".to_string())
323 }
324
325 /// Start streaming a completion from the model.
326 /// Returns a stream ID that can be used with `llm_stream_completion_next` and `llm_stream_completion_close`.
327 fn llm_stream_completion_start(
328 &mut self,
329 _provider_id: &str,
330 _model_id: &str,
331 _request: &LlmCompletionRequest,
332 ) -> Result<String, String> {
333 Err("`llm_stream_completion_start` not implemented".to_string())
334 }
335
336 /// Get the next event from a completion stream.
337 /// Returns `Ok(None)` when the stream is complete.
338 fn llm_stream_completion_next(
339 &mut self,
340 _stream_id: &str,
341 ) -> Result<Option<LlmCompletionEvent>, String> {
342 Err("`llm_stream_completion_next` not implemented".to_string())
343 }
344
345 /// Close a completion stream and release its resources.
346 fn llm_stream_completion_close(&mut self, _stream_id: &str) {
347 // Default implementation does nothing
348 }
349
350 /// Get cache configuration for a model (if prompt caching is supported).
351 fn llm_cache_configuration(
352 &self,
353 _provider_id: &str,
354 _model_id: &str,
355 ) -> Option<LlmCacheConfiguration> {
356 None
357 }
358}
359
360/// Registers the provided type as a Zed extension.
361///
362/// The type must implement the [`Extension`] trait.
363#[macro_export]
364macro_rules! register_extension {
365 ($extension_type:ty) => {
366 #[cfg(target_os = "wasi")]
367 mod wasi_ext {
368 unsafe extern "C" {
369 static mut errno: i32;
370 pub static mut __wasilibc_cwd: *mut std::ffi::c_char;
371 }
372
373 pub fn init_cwd() {
374 unsafe {
375 // Ensure that our chdir function is linked, instead of the
376 // one from wasi-libc in the chdir.o translation unit. Otherwise
377 // we risk linking in `__wasilibc_find_relpath_alloc` which
378 // is a weak symbol and is being used by
379 // `__wasilibc_find_relpath`, which we do not want on
380 // Windows.
381 chdir(std::ptr::null());
382
383 __wasilibc_cwd = std::ffi::CString::new(std::env::var("PWD").unwrap())
384 .unwrap()
385 .into_raw()
386 .cast();
387 }
388 }
389
390 #[unsafe(no_mangle)]
391 pub unsafe extern "C" fn chdir(raw_path: *const std::ffi::c_char) -> i32 {
392 // Forbid extensions from changing CWD and so return an appropriate error code.
393 errno = 58; // NOTSUP
394 return -1;
395 }
396 }
397
398 #[unsafe(export_name = "init-extension")]
399 pub extern "C" fn __init_extension() {
400 #[cfg(target_os = "wasi")]
401 wasi_ext::init_cwd();
402
403 zed_extension_api::register_extension(|| {
404 Box::new(<$extension_type as zed_extension_api::Extension>::new())
405 });
406 }
407 };
408}
409
410#[doc(hidden)]
411pub fn register_extension(build_extension: fn() -> Box<dyn Extension>) {
412 unsafe { EXTENSION = Some((build_extension)()) }
413}
414
415fn extension() -> &'static mut dyn Extension {
416 #[expect(static_mut_refs)]
417 unsafe {
418 EXTENSION.as_deref_mut().unwrap()
419 }
420}
421
422static mut EXTENSION: Option<Box<dyn Extension>> = None;
423
424#[cfg(target_arch = "wasm32")]
425#[unsafe(link_section = "zed:api-version")]
426#[doc(hidden)]
427pub static ZED_API_VERSION: [u8; 6] = *include_bytes!(concat!(env!("OUT_DIR"), "/version_bytes"));
428
429mod wit {
430
431 wit_bindgen::generate!({
432 skip: ["init-extension"],
433 path: "./wit/since_v0.8.0",
434 });
435}
436
437wit::export!(Component);
438
439struct Component;
440
441impl wit::Guest for Component {
442 fn language_server_command(
443 language_server_id: String,
444 worktree: &wit::Worktree,
445 ) -> Result<wit::Command> {
446 let language_server_id = LanguageServerId(language_server_id);
447 extension().language_server_command(&language_server_id, worktree)
448 }
449
450 fn language_server_initialization_options(
451 language_server_id: String,
452 worktree: &Worktree,
453 ) -> Result<Option<String>, String> {
454 let language_server_id = LanguageServerId(language_server_id);
455 Ok(extension()
456 .language_server_initialization_options(&language_server_id, worktree)?
457 .and_then(|value| serde_json::to_string(&value).ok()))
458 }
459
460 fn language_server_workspace_configuration(
461 language_server_id: String,
462 worktree: &Worktree,
463 ) -> Result<Option<String>, String> {
464 let language_server_id = LanguageServerId(language_server_id);
465 Ok(extension()
466 .language_server_workspace_configuration(&language_server_id, worktree)?
467 .and_then(|value| serde_json::to_string(&value).ok()))
468 }
469
470 fn language_server_additional_initialization_options(
471 language_server_id: String,
472 target_language_server_id: String,
473 worktree: &Worktree,
474 ) -> Result<Option<String>, String> {
475 let language_server_id = LanguageServerId(language_server_id);
476 let target_language_server_id = LanguageServerId(target_language_server_id);
477 Ok(extension()
478 .language_server_additional_initialization_options(
479 &language_server_id,
480 &target_language_server_id,
481 worktree,
482 )?
483 .and_then(|value| serde_json::to_string(&value).ok()))
484 }
485
486 fn language_server_additional_workspace_configuration(
487 language_server_id: String,
488 target_language_server_id: String,
489 worktree: &Worktree,
490 ) -> Result<Option<String>, String> {
491 let language_server_id = LanguageServerId(language_server_id);
492 let target_language_server_id = LanguageServerId(target_language_server_id);
493 Ok(extension()
494 .language_server_additional_workspace_configuration(
495 &language_server_id,
496 &target_language_server_id,
497 worktree,
498 )?
499 .and_then(|value| serde_json::to_string(&value).ok()))
500 }
501
502 fn labels_for_completions(
503 language_server_id: String,
504 completions: Vec<Completion>,
505 ) -> Result<Vec<Option<CodeLabel>>, String> {
506 let language_server_id = LanguageServerId(language_server_id);
507 let mut labels = Vec::new();
508 for (ix, completion) in completions.into_iter().enumerate() {
509 let label = extension().label_for_completion(&language_server_id, completion);
510 if let Some(label) = label {
511 labels.resize(ix + 1, None);
512 *labels.last_mut().unwrap() = Some(label);
513 }
514 }
515 Ok(labels)
516 }
517
518 fn labels_for_symbols(
519 language_server_id: String,
520 symbols: Vec<Symbol>,
521 ) -> Result<Vec<Option<CodeLabel>>, String> {
522 let language_server_id = LanguageServerId(language_server_id);
523 let mut labels = Vec::new();
524 for (ix, symbol) in symbols.into_iter().enumerate() {
525 let label = extension().label_for_symbol(&language_server_id, symbol);
526 if let Some(label) = label {
527 labels.resize(ix + 1, None);
528 *labels.last_mut().unwrap() = Some(label);
529 }
530 }
531 Ok(labels)
532 }
533
534 fn complete_slash_command_argument(
535 command: SlashCommand,
536 args: Vec<String>,
537 ) -> Result<Vec<SlashCommandArgumentCompletion>, String> {
538 extension().complete_slash_command_argument(command, args)
539 }
540
541 fn run_slash_command(
542 command: SlashCommand,
543 args: Vec<String>,
544 worktree: Option<&Worktree>,
545 ) -> Result<SlashCommandOutput, String> {
546 extension().run_slash_command(command, args, worktree)
547 }
548
549 fn context_server_command(
550 context_server_id: String,
551 project: &Project,
552 ) -> Result<wit::Command> {
553 let context_server_id = ContextServerId(context_server_id);
554 extension().context_server_command(&context_server_id, project)
555 }
556
557 fn context_server_configuration(
558 context_server_id: String,
559 project: &Project,
560 ) -> Result<Option<ContextServerConfiguration>, String> {
561 let context_server_id = ContextServerId(context_server_id);
562 extension().context_server_configuration(&context_server_id, project)
563 }
564
565 fn suggest_docs_packages(provider: String) -> Result<Vec<String>, String> {
566 extension().suggest_docs_packages(provider)
567 }
568
569 fn index_docs(
570 provider: String,
571 package: String,
572 database: &KeyValueStore,
573 ) -> Result<(), String> {
574 extension().index_docs(provider, package, database)
575 }
576
577 fn get_dap_binary(
578 adapter_name: String,
579 config: DebugTaskDefinition,
580 user_installed_path: Option<String>,
581 worktree: &Worktree,
582 ) -> Result<wit::DebugAdapterBinary, String> {
583 extension().get_dap_binary(adapter_name, config, user_installed_path, worktree)
584 }
585
586 fn dap_request_kind(
587 adapter_name: String,
588 config: String,
589 ) -> Result<StartDebuggingRequestArgumentsRequest, String> {
590 extension().dap_request_kind(
591 adapter_name,
592 serde_json::from_str(&config).map_err(|e| format!("Failed to parse config: {e}"))?,
593 )
594 }
595 fn dap_config_to_scenario(config: DebugConfig) -> Result<DebugScenario, String> {
596 extension().dap_config_to_scenario(config)
597 }
598 fn dap_locator_create_scenario(
599 locator_name: String,
600 build_task: TaskTemplate,
601 resolved_label: String,
602 debug_adapter_name: String,
603 ) -> Option<DebugScenario> {
604 extension().dap_locator_create_scenario(
605 locator_name,
606 build_task,
607 resolved_label,
608 debug_adapter_name,
609 )
610 }
611 fn run_dap_locator(
612 locator_name: String,
613 build_task: TaskTemplate,
614 ) -> Result<DebugRequest, String> {
615 extension().run_dap_locator(locator_name, build_task)
616 }
617
618 fn llm_providers() -> Vec<LlmProviderInfo> {
619 extension().llm_providers()
620 }
621
622 fn llm_provider_models(provider_id: String) -> Result<Vec<LlmModelInfo>, String> {
623 extension().llm_provider_models(&provider_id)
624 }
625
626 fn llm_provider_settings_markdown(provider_id: String) -> Option<String> {
627 extension().llm_provider_settings_markdown(&provider_id)
628 }
629
630 fn llm_provider_is_authenticated(provider_id: String) -> bool {
631 extension().llm_provider_is_authenticated(&provider_id)
632 }
633
634 fn llm_provider_authenticate(provider_id: String) -> Result<(), String> {
635 extension().llm_provider_authenticate(&provider_id)
636 }
637
638 fn llm_provider_reset_credentials(provider_id: String) -> Result<(), String> {
639 extension().llm_provider_reset_credentials(&provider_id)
640 }
641
642 fn llm_count_tokens(
643 provider_id: String,
644 model_id: String,
645 request: LlmCompletionRequest,
646 ) -> Result<u64, String> {
647 extension().llm_count_tokens(&provider_id, &model_id, &request)
648 }
649
650 fn llm_stream_completion_start(
651 provider_id: String,
652 model_id: String,
653 request: LlmCompletionRequest,
654 ) -> Result<String, String> {
655 extension().llm_stream_completion_start(&provider_id, &model_id, &request)
656 }
657
658 fn llm_stream_completion_next(stream_id: String) -> Result<Option<LlmCompletionEvent>, String> {
659 extension().llm_stream_completion_next(&stream_id)
660 }
661
662 fn llm_stream_completion_close(stream_id: String) {
663 extension().llm_stream_completion_close(&stream_id)
664 }
665
666 fn llm_cache_configuration(
667 provider_id: String,
668 model_id: String,
669 ) -> Option<LlmCacheConfiguration> {
670 extension().llm_cache_configuration(&provider_id, &model_id)
671 }
672}
673
674/// The ID of a language server.
675#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
676pub struct LanguageServerId(String);
677
678impl AsRef<str> for LanguageServerId {
679 fn as_ref(&self) -> &str {
680 &self.0
681 }
682}
683
684impl fmt::Display for LanguageServerId {
685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686 write!(f, "{}", self.0)
687 }
688}
689
690/// The ID of a context server.
691#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
692pub struct ContextServerId(String);
693
694impl AsRef<str> for ContextServerId {
695 fn as_ref(&self) -> &str {
696 &self.0
697 }
698}
699
700impl fmt::Display for ContextServerId {
701 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702 write!(f, "{}", self.0)
703 }
704}
705
706impl CodeLabelSpan {
707 /// Returns a [`CodeLabelSpan::CodeRange`].
708 pub fn code_range(range: impl Into<wit::Range>) -> Self {
709 Self::CodeRange(range.into())
710 }
711
712 /// Returns a [`CodeLabelSpan::Literal`].
713 pub fn literal(text: impl Into<String>, highlight_name: Option<String>) -> Self {
714 Self::Literal(CodeLabelSpanLiteral {
715 text: text.into(),
716 highlight_name,
717 })
718 }
719}
720
721impl From<std::ops::Range<u32>> for wit::Range {
722 fn from(value: std::ops::Range<u32>) -> Self {
723 Self {
724 start: value.start,
725 end: value.end,
726 }
727 }
728}
729
730impl From<std::ops::Range<usize>> for wit::Range {
731 fn from(value: std::ops::Range<usize>) -> Self {
732 Self {
733 start: value.start as u32,
734 end: value.end as u32,
735 }
736 }
737}