quantalang 1.0.0

The QuantaLang compiler — an effects-oriented systems language with multi-backend codegen (C, HLSL, GLSL, SPIR-V, LLVM IR, WebAssembly, x86-64, ARM64)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// ===============================================================================
// QUANTALANG LSP DEFINITION
// ===============================================================================
// Copyright (c) 2022-2026 Zain Dana Harper. MIT License.
// ===============================================================================

//! Go to definition provider for QuantaLang.

use super::document::{Document, DocumentStore};
use super::types::*;
use std::sync::Arc;

// =============================================================================
// DEFINITION PROVIDER
// =============================================================================

/// Provides go-to-definition functionality.
pub struct DefinitionProvider {
    /// Document store reference.
    documents: Arc<DocumentStore>,
}

impl DefinitionProvider {
    /// Create a new definition provider.
    pub fn new(documents: Arc<DocumentStore>) -> Self {
        Self { documents }
    }

    /// Find definition of symbol at position.
    pub fn find_definition(&self, doc: &Document, position: Position) -> Vec<Location> {
        let Some((word, _range)) = doc.word_at(position) else {
            return Vec::new();
        };

        let mut locations = Vec::new();

        // Search in current document
        if let Some(loc) = self.find_definition_in_doc(doc, &word) {
            locations.push(loc);
        }

        // Search in other open documents
        for uri in self.documents.uris() {
            if uri != doc.uri {
                if let Some(other_doc) = self.documents.get(&uri) {
                    if let Some(loc) = self.find_definition_in_doc(&other_doc, &word) {
                        locations.push(loc);
                    }
                }
            }
        }

        locations
    }

    /// Find definition in a single document.
    fn find_definition_in_doc(&self, doc: &Document, name: &str) -> Option<Location> {
        let content = &doc.content;

        for (line_num, line) in content.lines().enumerate() {
            let trimmed = line.trim();

            // Function definition
            if let Some(loc) = self.match_function_def(doc, line, line_num, name) {
                return Some(loc);
            }

            // Struct definition
            if let Some(loc) = self.match_struct_def(doc, trimmed, line, line_num, name) {
                return Some(loc);
            }

            // Enum definition
            if let Some(loc) = self.match_enum_def(doc, trimmed, line, line_num, name) {
                return Some(loc);
            }

            // Trait definition
            if let Some(loc) = self.match_trait_def(doc, trimmed, line, line_num, name) {
                return Some(loc);
            }

            // Const definition
            if let Some(loc) = self.match_const_def(doc, trimmed, line, line_num, name) {
                return Some(loc);
            }

            // Type alias
            if let Some(loc) = self.match_type_alias(doc, trimmed, line, line_num, name) {
                return Some(loc);
            }
        }

        None
    }

    /// Match function definition.
    fn match_function_def(
        &self,
        doc: &Document,
        line: &str,
        line_num: usize,
        name: &str,
    ) -> Option<Location> {
        let trimmed = line.trim();
        let rest = trimmed
            .strip_prefix("pub ")
            .or_else(|| trimmed.strip_prefix("async "))
            .or_else(|| trimmed.strip_prefix("pub async "))
            .unwrap_or(trimmed);

        let rest = rest.strip_prefix("fn ")?;
        let paren_pos = rest.find('(')?;
        let fn_name = rest[..paren_pos].trim();

        if fn_name == name {
            let col = line.find(name)?;
            return Some(Location::new(
                doc.uri.clone(),
                Range::new(
                    Position::new(line_num as u32, col as u32),
                    Position::new(line_num as u32, (col + name.len()) as u32),
                ),
            ));
        }
        None
    }

    /// Match struct definition.
    fn match_struct_def(
        &self,
        doc: &Document,
        trimmed: &str,
        line: &str,
        line_num: usize,
        name: &str,
    ) -> Option<Location> {
        let rest = trimmed
            .strip_prefix("pub ")
            .unwrap_or(trimmed)
            .strip_prefix("struct ")?;

        let name_end = rest
            .find(|c: char| c == '<' || c == '{' || c == '(' || c == ' ')
            .unwrap_or(rest.len());
        let struct_name = rest[..name_end].trim();

        if struct_name == name {
            let col = line.find(name)?;
            return Some(Location::new(
                doc.uri.clone(),
                Range::new(
                    Position::new(line_num as u32, col as u32),
                    Position::new(line_num as u32, (col + name.len()) as u32),
                ),
            ));
        }
        None
    }

    /// Match enum definition.
    fn match_enum_def(
        &self,
        doc: &Document,
        trimmed: &str,
        line: &str,
        line_num: usize,
        name: &str,
    ) -> Option<Location> {
        let rest = trimmed
            .strip_prefix("pub ")
            .unwrap_or(trimmed)
            .strip_prefix("enum ")?;

        let name_end = rest
            .find(|c: char| c == '<' || c == '{' || c == ' ')
            .unwrap_or(rest.len());
        let enum_name = rest[..name_end].trim();

        if enum_name == name {
            let col = line.find(name)?;
            return Some(Location::new(
                doc.uri.clone(),
                Range::new(
                    Position::new(line_num as u32, col as u32),
                    Position::new(line_num as u32, (col + name.len()) as u32),
                ),
            ));
        }
        None
    }

    /// Match trait definition.
    fn match_trait_def(
        &self,
        doc: &Document,
        trimmed: &str,
        line: &str,
        line_num: usize,
        name: &str,
    ) -> Option<Location> {
        let rest = trimmed
            .strip_prefix("pub ")
            .unwrap_or(trimmed)
            .strip_prefix("trait ")?;

        let name_end = rest
            .find(|c: char| c == '<' || c == '{' || c == ':' || c == ' ')
            .unwrap_or(rest.len());
        let trait_name = rest[..name_end].trim();

        if trait_name == name {
            let col = line.find(name)?;
            return Some(Location::new(
                doc.uri.clone(),
                Range::new(
                    Position::new(line_num as u32, col as u32),
                    Position::new(line_num as u32, (col + name.len()) as u32),
                ),
            ));
        }
        None
    }

    /// Match const definition.
    fn match_const_def(
        &self,
        doc: &Document,
        trimmed: &str,
        line: &str,
        line_num: usize,
        name: &str,
    ) -> Option<Location> {
        let rest = trimmed
            .strip_prefix("pub ")
            .unwrap_or(trimmed)
            .strip_prefix("const ")?;

        let colon_pos = rest.find(':')?;
        let const_name = rest[..colon_pos].trim();

        if const_name == name {
            let col = line.find(name)?;
            return Some(Location::new(
                doc.uri.clone(),
                Range::new(
                    Position::new(line_num as u32, col as u32),
                    Position::new(line_num as u32, (col + name.len()) as u32),
                ),
            ));
        }
        None
    }

    /// Match type alias.
    fn match_type_alias(
        &self,
        doc: &Document,
        trimmed: &str,
        line: &str,
        line_num: usize,
        name: &str,
    ) -> Option<Location> {
        let rest = trimmed
            .strip_prefix("pub ")
            .unwrap_or(trimmed)
            .strip_prefix("type ")?;

        let eq_pos = rest.find('=')?;
        let name_part = rest[..eq_pos].trim();
        let name_end = name_part.find('<').unwrap_or(name_part.len());
        let type_name = name_part[..name_end].trim();

        if type_name == name {
            let col = line.find(name)?;
            return Some(Location::new(
                doc.uri.clone(),
                Range::new(
                    Position::new(line_num as u32, col as u32),
                    Position::new(line_num as u32, (col + name.len()) as u32),
                ),
            ));
        }
        None
    }

    /// Find all references to a symbol.
    pub fn find_references(
        &self,
        doc: &Document,
        position: Position,
        include_definition: bool,
    ) -> Vec<Location> {
        let Some((word, _range)) = doc.word_at(position) else {
            return Vec::new();
        };

        let mut locations = Vec::new();

        // Search in all open documents
        for uri in self.documents.uris() {
            if let Some(search_doc) = self.documents.get(&uri) {
                self.find_references_in_doc(&search_doc, &word, include_definition, &mut locations);
            }
        }

        locations
    }

    /// Find references in a document.
    fn find_references_in_doc(
        &self,
        doc: &Document,
        name: &str,
        include_definition: bool,
        locations: &mut Vec<Location>,
    ) {
        let content = &doc.content;

        for (line_num, line) in content.lines().enumerate() {
            // Skip if this is a definition and we don't want definitions
            if !include_definition {
                let trimmed = line.trim();
                if trimmed.starts_with("fn ")
                    || trimmed.starts_with("pub fn ")
                    || trimmed.starts_with("struct ")
                    || trimmed.starts_with("pub struct ")
                    || trimmed.starts_with("enum ")
                    || trimmed.starts_with("pub enum ")
                    || trimmed.starts_with("trait ")
                    || trimmed.starts_with("pub trait ")
                {
                    // Check if this line defines the symbol
                    if line.contains(&format!("fn {}", name))
                        || line.contains(&format!("struct {} ", name))
                        || line.contains(&format!("struct {}<", name))
                        || line.contains(&format!("struct {}{{", name))
                        || line.contains(&format!("enum {} ", name))
                        || line.contains(&format!("enum {}<", name))
                        || line.contains(&format!("enum {}{{", name))
                        || line.contains(&format!("trait {} ", name))
                        || line.contains(&format!("trait {}<", name))
                        || line.contains(&format!("trait {}{{", name))
                    {
                        continue;
                    }
                }
            }

            // Find all occurrences of the word
            let mut search_pos = 0;
            while let Some(pos) = line[search_pos..].find(name) {
                let abs_pos = search_pos + pos;

                // Check word boundaries
                let before_ok = abs_pos == 0
                    || !line.as_bytes()[abs_pos - 1].is_ascii_alphanumeric()
                        && line.as_bytes()[abs_pos - 1] != b'_';
                let after_pos = abs_pos + name.len();
                let after_ok = after_pos >= line.len()
                    || !line.as_bytes()[after_pos].is_ascii_alphanumeric()
                        && line.as_bytes()[after_pos] != b'_';

                if before_ok && after_ok {
                    locations.push(Location::new(
                        doc.uri.clone(),
                        Range::new(
                            Position::new(line_num as u32, abs_pos as u32),
                            Position::new(line_num as u32, after_pos as u32),
                        ),
                    ));
                }

                search_pos = abs_pos + name.len();
            }
        }
    }

    /// Find type definition (for go to type definition).
    pub fn find_type_definition(&self, doc: &Document, position: Position) -> Vec<Location> {
        // For now, this is the same as find_definition
        // In a full implementation, this would track through variable types
        self.find_definition(doc, position)
    }

    /// Find implementations of a trait or type.
    pub fn find_implementations(&self, doc: &Document, position: Position) -> Vec<Location> {
        let Some((word, _range)) = doc.word_at(position) else {
            return Vec::new();
        };

        let mut locations = Vec::new();

        // Search for impl blocks
        for uri in self.documents.uris() {
            if let Some(search_doc) = self.documents.get(&uri) {
                self.find_impl_blocks(&search_doc, &word, &mut locations);
            }
        }

        locations
    }

    /// Find impl blocks for a type or trait.
    fn find_impl_blocks(&self, doc: &Document, name: &str, locations: &mut Vec<Location>) {
        let content = &doc.content;

        for (line_num, line) in content.lines().enumerate() {
            let trimmed = line.trim();

            if let Some(rest) = trimmed.strip_prefix("impl") {
                // Check if this implements the type/trait
                let implements_type = rest.contains(&format!(" {} ", name))
                    || rest.contains(&format!(" {}<", name))
                    || rest.contains(&format!(" {}{{", name))
                    || rest.contains(&format!(" for {} ", name))
                    || rest.contains(&format!(" for {}<", name))
                    || rest.contains(&format!(" for {}{{", name))
                    || rest.trim().starts_with(name);

                if implements_type {
                    if let Some(col) = line.find("impl") {
                        locations.push(Location::new(
                            doc.uri.clone(),
                            Range::new(
                                Position::new(line_num as u32, col as u32),
                                Position::new(line_num as u32, line.len() as u32),
                            ),
                        ));
                    }
                }
            }
        }
    }
}