1use std::ops::Range;
7
8use egui::{Color32, FontId, Response, Stroke, TextStyle, Ui};
9pub use eure;
10use eure::query::{
11 CollectDiagnosticTargets, DiagnosticSeverity as EureSeverity, GetAllDiagnostics,
12 GetFileDiagnostics, GetFileErrorReports, GetSemanticTokens, SemanticToken, SemanticTokenType,
13 TextFile, TextFileContent,
14};
15pub use eure::query_flow::QueryError;
16use eure::query_flow::{DurabilityLevel, QueryRuntime};
17use eure::report::format_error_reports;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum DiagnosticSeverity {
22 Error,
23 Warning,
24 Info,
25 Hint,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct EditorColors {
33 pub plain: Option<Color32>,
34 pub keyword: Color32,
35 pub number: Color32,
36 pub string: Color32,
37 pub comment: Color32,
38 pub operator: Color32,
39 pub property: Color32,
40 pub punctuation: Color32,
41 pub macro_: Color32,
42 pub decorator: Color32,
43 pub section_marker: Color32,
44 pub extension_marker: Color32,
45 pub extension_ident: Color32,
46 pub error: Color32,
47 pub warning: Color32,
48 pub info: Color32,
49 pub hint: Color32,
50}
51
52impl Default for EditorColors {
53 fn default() -> Self {
54 Self {
55 plain: None,
56 keyword: Color32::from_rgb(197, 134, 192),
57 number: Color32::from_rgb(181, 206, 168),
58 string: Color32::from_rgb(206, 145, 120),
59 comment: Color32::from_rgb(106, 153, 85),
60 operator: Color32::from_rgb(212, 212, 212),
61 property: Color32::from_rgb(156, 220, 254),
62 punctuation: Color32::from_rgb(215, 186, 125),
63 macro_: Color32::from_rgb(214, 157, 133),
64 decorator: Color32::from_rgb(78, 201, 176),
65 section_marker: Color32::from_rgb(220, 220, 170),
66 extension_marker: Color32::from_rgb(197, 134, 192),
67 extension_ident: Color32::from_rgb(220, 220, 170),
68 error: Color32::from_rgb(235, 87, 87),
69 warning: Color32::from_rgb(232, 181, 72),
70 info: Color32::from_rgb(86, 156, 214),
71 hint: Color32::from_rgb(120, 180, 150),
72 }
73 }
74}
75
76impl EditorColors {
77 fn diagnostic(self, severity: DiagnosticSeverity) -> Color32 {
78 match severity {
79 DiagnosticSeverity::Error => self.error,
80 DiagnosticSeverity::Warning => self.warning,
81 DiagnosticSeverity::Info => self.info,
82 DiagnosticSeverity::Hint => self.hint,
83 }
84 }
85
86 fn semantic(self, token: Option<SemanticTokenType>, fallback: Color32) -> Color32 {
87 match token {
88 Some(SemanticTokenType::Keyword) => self.keyword,
89 Some(SemanticTokenType::Number) => self.number,
90 Some(SemanticTokenType::String) => self.string,
91 Some(SemanticTokenType::Comment) => self.comment,
92 Some(SemanticTokenType::Operator) => self.operator,
93 Some(SemanticTokenType::Property) => self.property,
94 Some(SemanticTokenType::Punctuation) => self.punctuation,
95 Some(SemanticTokenType::Macro) => self.macro_,
96 Some(SemanticTokenType::Decorator) => self.decorator,
97 Some(SemanticTokenType::SectionMarker) => self.section_marker,
98 Some(SemanticTokenType::ExtensionMarker) => self.extension_marker,
99 Some(SemanticTokenType::ExtensionIdent) => self.extension_ident,
100 None => self.plain.unwrap_or(fallback),
101 }
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Diagnostic {
108 pub range: Range<usize>,
109 pub message: String,
110 pub severity: DiagnosticSeverity,
111}
112
113pub struct EditorOutput {
115 pub response: Response,
116 pub diagnostics: Vec<Diagnostic>,
117 pub query_error: Option<QueryError>,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct FileDiagnostic {
123 pub file: TextFile,
124 pub diagnostic: Diagnostic,
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct FormattedFileDiagnostics {
130 pub file: TextFile,
131 pub formatted: String,
132}
133
134pub fn file_diagnostics(
136 runtime: &QueryRuntime,
137 file: &TextFile,
138 source: &str,
139) -> Result<Vec<Diagnostic>, QueryError> {
140 runtime
141 .query(GetFileDiagnostics::new(file.clone()))
142 .map(|messages| {
143 messages
144 .iter()
145 .filter(|message| message.file == *file)
146 .map(|message| map_diagnostic(source, message))
147 .collect()
148 })
149}
150
151pub fn formatted_file_diagnostics(
153 runtime: &QueryRuntime,
154 file: &TextFile,
155) -> Result<String, QueryError> {
156 format_file_diagnostics(runtime, file, false)
157}
158
159pub fn styled_file_diagnostics(
161 runtime: &QueryRuntime,
162 file: &TextFile,
163) -> Result<String, QueryError> {
164 format_file_diagnostics(runtime, file, true)
165}
166
167fn format_file_diagnostics(
168 runtime: &QueryRuntime,
169 file: &TextFile,
170 styled: bool,
171) -> Result<String, QueryError> {
172 let reports = runtime.query(GetFileErrorReports::new(file.clone()))?;
173 format_error_reports(runtime, reports.as_ref(), styled)
174}
175
176pub fn formatted_workspace_diagnostics(
178 runtime: &QueryRuntime,
179) -> Result<Vec<FormattedFileDiagnostics>, QueryError> {
180 format_workspace_diagnostics(runtime, false)
181}
182
183pub fn styled_workspace_diagnostics(
185 runtime: &QueryRuntime,
186) -> Result<Vec<FormattedFileDiagnostics>, QueryError> {
187 format_workspace_diagnostics(runtime, true)
188}
189
190fn format_workspace_diagnostics(
191 runtime: &QueryRuntime,
192 styled: bool,
193) -> Result<Vec<FormattedFileDiagnostics>, QueryError> {
194 let targets = runtime.query(CollectDiagnosticTargets::new())?;
195 let mut formatted = Vec::new();
196 for file in targets.iter() {
197 let reports = runtime.query(GetFileErrorReports::new(file.clone()))?;
198 if reports.is_empty() {
199 continue;
200 }
201 formatted.push(FormattedFileDiagnostics {
202 file: file.clone(),
203 formatted: format_error_reports(runtime, reports.as_ref(), styled)?,
204 });
205 }
206 Ok(formatted)
207}
208
209pub fn workspace_diagnostics(runtime: &QueryRuntime) -> Result<Vec<FileDiagnostic>, QueryError> {
211 runtime.query(GetAllDiagnostics::new()).map(|by_file| {
212 let mut diagnostics = Vec::new();
213 for messages in by_file.values() {
214 for message in messages {
215 diagnostics.push(FileDiagnostic {
216 file: message.file.clone(),
217 diagnostic: map_unbounded_diagnostic(message),
218 });
219 }
220 }
221 diagnostics
222 })
223}
224
225pub struct EureEditor<'a> {
231 source: &'a mut String,
232 runtime: &'a QueryRuntime,
233 file: &'a TextFile,
234 colors: EditorColors,
235 desired_rows: usize,
236 id_salt: Option<egui::Id>,
237}
238
239impl<'a> EureEditor<'a> {
240 pub fn new(source: &'a mut String, runtime: &'a QueryRuntime, file: &'a TextFile) -> Self {
242 Self {
243 source,
244 runtime,
245 file,
246 colors: EditorColors::default(),
247 desired_rows: 16,
248 id_salt: None,
249 }
250 }
251
252 #[must_use]
254 pub fn colors(mut self, colors: EditorColors) -> Self {
255 self.colors = colors;
256 self
257 }
258
259 #[must_use]
260 pub fn desired_rows(mut self, rows: usize) -> Self {
261 self.desired_rows = rows.max(1);
262 self
263 }
264
265 #[must_use]
266 pub fn id_salt(mut self, salt: impl std::hash::Hash) -> Self {
267 self.id_salt = Some(egui::Id::new(salt));
268 self
269 }
270
271 pub fn show(self, ui: &mut Ui) -> EditorOutput {
272 let (mut analysis, mut query_error) = match self.analysis() {
273 Ok(analysis) => (analysis, None),
274 Err(error) => (Analysis::default(), Some(error)),
275 };
276 let colors = self.colors;
277 let fallback_color = colors.plain.unwrap_or_else(|| ui.visuals().text_color());
278 let font_id = TextStyle::Monospace.resolve(ui.style());
279 let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {
280 let mut job = layout_job(
281 text.as_str(),
282 &analysis,
283 font_id.clone(),
284 colors,
285 fallback_color,
286 );
287 job.wrap.max_width = wrap_width;
288 ui.fonts_mut(|fonts| fonts.layout_job(job))
289 };
290
291 let mut edit = egui::TextEdit::multiline(self.source)
292 .font(TextStyle::Monospace)
293 .desired_width(f32::INFINITY)
294 .desired_rows(self.desired_rows)
295 .layouter(&mut layouter);
296 if let Some(id_salt) = self.id_salt {
297 edit = edit.id_salt(("eure-egui-editor", id_salt));
301 }
302
303 let output = edit.show(ui);
304 let response = output.response.response.clone();
305
306 if response.changed() {
307 match self.analysis() {
308 Ok(updated) => {
309 analysis = updated;
310 query_error = None;
311 }
312 Err(error) => {
313 analysis = Analysis::default();
314 query_error = Some(error);
315 }
316 }
317 }
318
319 if let Some(pointer) = response.hover_pos() {
320 let local = pointer - output.galley_pos;
321 let char_index = output.galley.cursor_from_pos(local).index;
322 let byte_index = char_to_byte(self.source, char_index);
323 let hovered: Vec<_> = analysis
324 .diagnostics
325 .iter()
326 .filter(|diagnostic| range_contains(&diagnostic.range, byte_index))
327 .collect();
328 if !hovered.is_empty() {
329 response.clone().on_hover_ui_at_pointer(|ui| {
330 for diagnostic in hovered {
331 ui.colored_label(
332 colors.diagnostic(diagnostic.severity),
333 &diagnostic.message,
334 );
335 }
336 });
337 }
338 }
339
340 EditorOutput {
341 response,
342 diagnostics: analysis.diagnostics,
343 query_error,
344 }
345 }
346
347 fn analysis(&self) -> Result<Analysis, QueryError> {
348 analyze_file(self.runtime, self.file, self.source)
349 }
350}
351
352#[derive(Default)]
353struct Analysis {
354 tokens: Vec<SemanticToken>,
355 diagnostics: Vec<Diagnostic>,
356}
357
358fn analyze_file(
359 runtime: &QueryRuntime,
360 file: &TextFile,
361 source: &str,
362) -> Result<Analysis, QueryError> {
363 runtime.resolve_asset(
364 file.clone(),
365 TextFileContent(source.to_owned()),
366 DurabilityLevel::Volatile,
367 );
368 let tokens = runtime
369 .query(GetSemanticTokens::new(file.clone()))?
370 .as_ref()
371 .clone();
372 let diagnostics = file_diagnostics(runtime, file, source)?;
373 Ok(Analysis {
374 tokens,
375 diagnostics,
376 })
377}
378
379fn map_diagnostic(source: &str, message: &eure::query::DiagnosticMessage) -> Diagnostic {
380 Diagnostic {
381 range: normalized_range(source, message.start, message.end),
382 message: message.message.clone(),
383 severity: map_eure_severity(message.severity),
384 }
385}
386
387fn map_unbounded_diagnostic(message: &eure::query::DiagnosticMessage) -> Diagnostic {
388 Diagnostic {
389 range: message.start..message.end.max(message.start.saturating_add(1)),
390 message: message.message.clone(),
391 severity: map_eure_severity(message.severity),
392 }
393}
394
395fn layout_job(
396 source: &str,
397 analysis: &Analysis,
398 font_id: FontId,
399 colors: EditorColors,
400 fallback_color: Color32,
401) -> egui::text::LayoutJob {
402 let mut boundaries = vec![0, source.len()];
403 for token in &analysis.tokens {
404 boundaries.push((token.start as usize).min(source.len()));
405 boundaries.push((token.start as usize + token.length as usize).min(source.len()));
406 }
407 for diagnostic in &analysis.diagnostics {
408 boundaries.push(diagnostic.range.start.min(source.len()));
409 boundaries.push(diagnostic.range.end.min(source.len()));
410 }
411 boundaries.retain(|offset| source.is_char_boundary(*offset));
412 boundaries.sort_unstable();
413 boundaries.dedup();
414
415 let mut job = egui::text::LayoutJob::default();
416 for pair in boundaries.windows(2) {
417 let range = pair[0]..pair[1];
418 if range.is_empty() {
419 continue;
420 }
421 let token_type = analysis
422 .tokens
423 .iter()
424 .find(|token| {
425 let start = token.start as usize;
426 start <= range.start && range.start < start + token.length as usize
427 })
428 .map(|token| token.token_type);
429 let diagnostic = analysis
430 .diagnostics
431 .iter()
432 .find(|diagnostic| range_contains(&diagnostic.range, range.start));
433 let mut format = egui::TextFormat {
434 font_id: font_id.clone(),
435 color: colors.semantic(token_type, fallback_color),
436 ..Default::default()
437 };
438 if let Some(diagnostic) = diagnostic {
439 format.underline = Stroke::new(1.5_f32, colors.diagnostic(diagnostic.severity));
440 }
441 job.append(&source[range], 0.0, format);
442 }
443 job
444}
445
446fn normalized_range(source: &str, start: usize, end: usize) -> Range<usize> {
447 let mut start = start.min(source.len());
448 let mut end = end.max(start.saturating_add(1)).min(source.len());
449 while start > 0 && !source.is_char_boundary(start) {
450 start -= 1;
451 }
452 while end < source.len() && !source.is_char_boundary(end) {
453 end += 1;
454 }
455 if source.is_empty() {
456 0..0
457 } else if start == end {
458 if end < source.len() {
459 let next = source[end..]
460 .chars()
461 .next()
462 .map_or(source.len(), |character| end + character.len_utf8());
463 end..next
464 } else {
465 let previous = source[..end]
466 .char_indices()
467 .next_back()
468 .map_or(0, |(offset, _)| offset);
469 previous..end
470 }
471 } else {
472 start..end
473 }
474}
475
476fn range_contains(range: &Range<usize>, offset: usize) -> bool {
477 if range.is_empty() {
478 offset == range.start
479 } else {
480 range.start <= offset && offset < range.end
481 }
482}
483
484fn char_to_byte(text: &str, char_index: usize) -> usize {
485 text.char_indices()
486 .nth(char_index)
487 .map_or(text.len(), |(offset, _)| offset)
488}
489
490fn map_eure_severity(severity: EureSeverity) -> DiagnosticSeverity {
491 match severity {
492 EureSeverity::Error => DiagnosticSeverity::Error,
493 EureSeverity::Warning => DiagnosticSeverity::Warning,
494 EureSeverity::Info => DiagnosticSeverity::Info,
495 EureSeverity::Hint => DiagnosticSeverity::Hint,
496 }
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502 use eure::query::{OpenDocuments, OpenDocumentsList, Workspace, WorkspaceId, build_runtime};
503
504 fn text_file(name: &str) -> TextFile {
505 TextFile::parse(&format!("memory/{name}")).expect("test text file is valid")
506 }
507
508 fn runtime_with_file(source: &str) -> (QueryRuntime, TextFile) {
509 let runtime = build_runtime();
510 let document = text_file("demo.eure");
511 let config = text_file("Eure.eure");
512 runtime.resolve_asset(
513 WorkspaceId("test-workspace".to_owned()),
514 Workspace {
515 path: "memory".into(),
516 config_path: "memory/Eure.eure".into(),
517 },
518 DurabilityLevel::Static,
519 );
520 runtime.resolve_asset(
521 config,
522 TextFileContent(String::new()),
523 DurabilityLevel::Volatile,
524 );
525 runtime.resolve_asset(
526 document.clone(),
527 TextFileContent(source.to_owned()),
528 DurabilityLevel::Volatile,
529 );
530 runtime.resolve_asset(
531 OpenDocuments,
532 OpenDocumentsList(vec![document.clone()]),
533 DurabilityLevel::Volatile,
534 );
535 (runtime, document)
536 }
537
538 #[test]
539 fn valid_document_has_tokens_and_no_diagnostics() {
540 let source = "name = \"Alice\"\nage = 30\n";
541 let (runtime, document) = runtime_with_file(source);
542 let analysis = analyze_file(&runtime, &document, source).expect("analysis should resolve");
543 assert!(!analysis.tokens.is_empty());
544 assert!(
545 analysis.diagnostics.is_empty(),
546 "{:?}",
547 analysis.diagnostics
548 );
549 }
550
551 #[test]
552 fn syntax_errors_are_reported() {
553 let source = "user {\n name = \"Alice\"\n";
554 let (runtime, document) = runtime_with_file(source);
555 let analysis = analyze_file(&runtime, &document, source).expect("analysis should resolve");
556 assert!(!analysis.diagnostics.is_empty());
557 }
558
559 #[test]
560 fn referenced_schema_validates_without_io() {
561 let schema = "name = `text`\nage = `integer`\n";
562 let source = "$schema: demo.schema.eure\nname = \"Alice\"\nage = \"old\"\n";
563 let (runtime, document) = runtime_with_file(source);
564 runtime.resolve_asset(
565 text_file("demo.schema.eure"),
566 TextFileContent(schema.to_owned()),
567 DurabilityLevel::Volatile,
568 );
569 let analysis = analyze_file(&runtime, &document, source).expect("analysis should resolve");
570 assert!(
571 analysis
572 .diagnostics
573 .iter()
574 .any(|diagnostic| diagnostic.severity == DiagnosticSeverity::Error),
575 "{:?}",
576 analysis.diagnostics
577 );
578 }
579
580 #[test]
581 fn registered_schema_is_not_applied_without_schema_extension() {
582 let schema = "name = `text`\nage = `integer`\n";
583 let source = "name = \"Alice\"\nage = \"old\"\n";
584 let (runtime, document) = runtime_with_file(source);
585 runtime.resolve_asset(
586 text_file("demo.schema.eure"),
587 TextFileContent(schema.to_owned()),
588 DurabilityLevel::Volatile,
589 );
590 let analysis = analyze_file(&runtime, &document, source).expect("analysis should resolve");
591 assert!(
592 analysis.diagnostics.is_empty(),
593 "{:?}",
594 analysis.diagnostics
595 );
596 }
597
598 #[test]
599 fn workspace_diagnostics_are_grouped_by_virtual_file() {
600 let source = "$schema: demo.schema.eure\nname = Alice\nage = old\n";
601 let (runtime, document) = runtime_with_file(source);
602 runtime.resolve_asset(
603 text_file("demo.schema.eure"),
604 TextFileContent("name = `text`\nage = `integer`\n".to_owned()),
605 DurabilityLevel::Volatile,
606 );
607
608 let diagnostics = workspace_diagnostics(&runtime).expect("diagnostics should resolve");
609 assert!(
610 diagnostics.iter().any(|item| item.file == document),
611 "{diagnostics:?}"
612 );
613 let formatted =
614 formatted_file_diagnostics(&runtime, &document).expect("diagnostics should format");
615 assert!(formatted.contains("age"), "{formatted}");
616 let workspace_formatted =
617 formatted_workspace_diagnostics(&runtime).expect("workspace diagnostics should format");
618 assert!(
619 workspace_formatted
620 .iter()
621 .any(|group| group.file == document && group.formatted.contains("age")),
622 "{workspace_formatted:?}"
623 );
624 }
625
626 #[test]
627 fn workspace_diagnostics_preserve_query_suspension() {
628 let runtime = build_runtime();
629 let document = text_file("demo.eure");
630 runtime.resolve_asset(
631 WorkspaceId("test-workspace".to_owned()),
632 Workspace {
633 path: "memory".into(),
634 config_path: "memory/Eure.eure".into(),
635 },
636 DurabilityLevel::Static,
637 );
638 runtime.resolve_asset(
639 document.clone(),
640 TextFileContent("name = \"Alice\"\n".to_owned()),
641 DurabilityLevel::Volatile,
642 );
643 runtime.resolve_asset(
644 OpenDocuments,
645 OpenDocumentsList(vec![document]),
646 DurabilityLevel::Volatile,
647 );
648
649 assert!(matches!(
650 workspace_diagnostics(&runtime),
651 Err(QueryError::Suspend { .. })
652 ));
653 }
654
655 #[test]
656 fn unicode_char_offsets_map_to_bytes() {
657 assert_eq!(char_to_byte("a日b", 2), 4);
658 assert_eq!(normalized_range("日", 3, 3), 0..3);
659 }
660}