about summary refs log tree commit diff stats
path: root/js/baba-yaga/dev/vscode/out/extension.js
blob: 6e19efb0fad726623e405e863a7af962117c3123 (plain) (blame)
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
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deactivate = exports.activate = void 0;
const vscode = __importStar(require("vscode"));
// Tree-sitter parser for Baba Yaga (optional)
let parser;
let BabaYagaLanguage;
async function activate(context) {
    console.log('Baba Yaga extension is now active!');
    // Initialize Tree-sitter parser (optional)
    const enableTreeSitter = vscode.workspace.getConfiguration('baba-yaga').get('enableTreeSitter');
    if (enableTreeSitter) {
        try {
            const Parser = require('tree-sitter');
            Parser.init();
            // Note: tree-sitter-baba-yaga grammar would need to be built separately
            // For now, we'll use basic features without Tree-sitter
            console.log('Tree-sitter enabled but grammar not available');
        }
        catch (error) {
            console.warn('Tree-sitter not available, using basic features:', error);
        }
    }
    // Register commands
    context.subscriptions.push(vscode.commands.registerCommand('baba-yaga.showTypeInfo', showTypeInfo), vscode.commands.registerCommand('baba-yaga.goToDefinition', goToDefinition), vscode.commands.registerCommand('baba-yaga.findReferences', findReferences), vscode.commands.registerCommand('baba-yaga.showFunctionSignature', showFunctionSignature));
    // Register language features
    if (vscode.workspace.getConfiguration('baba-yaga').get('enableTypeHints')) {
        context.subscriptions.push(vscode.languages.registerHoverProvider('baba-yaga', new BabaYagaHoverProvider()), vscode.languages.registerCompletionItemProvider('baba-yaga', new BabaYagaCompletionProvider(), '.', ':', '>'));
    }
    if (vscode.workspace.getConfiguration('baba-yaga').get('enableFunctionReferences')) {
        context.subscriptions.push(vscode.languages.registerDefinitionProvider('baba-yaga', new BabaYagaDefinitionProvider()), vscode.languages.registerReferenceProvider('baba-yaga', new BabaYagaReferenceProvider()));
    }
    if (vscode.workspace.getConfiguration('baba-yaga').get('enableErrorChecking')) {
        context.subscriptions.push(vscode.languages.registerDiagnosticCollection('baba-yaga', new BabaYagaDiagnosticProvider()));
    }
}
exports.activate = activate;
function deactivate() { }
exports.deactivate = deactivate;
// Built-in functions and their signatures
const builtinFunctions = new Map([
    ['io.out', { name: 'io.out', kind: 'function', signature: 'io.out(value: any) -> void', description: 'Print value to console' }],
    ['io.in', { name: 'io.in', kind: 'function', signature: 'io.in() -> String', description: 'Read input from console' }],
    ['map', { name: 'map', kind: 'function', signature: 'map(func: (T) -> U, list: [T]) -> [U]', description: 'Apply function to each element' }],
    ['filter', { name: 'filter', kind: 'function', signature: 'filter(pred: (T) -> Bool, list: [T]) -> [T]', description: 'Filter list by predicate' }],
    ['reduce', { name: 'reduce', kind: 'function', signature: 'reduce(func: (acc: T, item: T) -> T, init: T, list: [T]) -> T', description: 'Fold list to single value' }],
    ['append', { name: 'append', kind: 'function', signature: 'append(list: [T], item: T) -> [T]', description: 'Add item to end of list' }],
    ['set', { name: 'set', kind: 'function', signature: 'set(table: Table, key: String, value: any) -> Table', description: 'Set table property' }],
    ['merge', { name: 'merge', kind: 'function', signature: 'merge(table1: Table, table2: Table) -> Table', description: 'Merge two tables' }],
    ['shape', { name: 'shape', kind: 'function', signature: 'shape(value: any) -> Table', description: 'Get value metadata' }]
]);
// String functions
const stringFunctions = ['concat', 'split', 'join', 'length', 'substring', 'replace', 'trim', 'upper', 'lower'];
stringFunctions.forEach(func => {
    builtinFunctions.set(`str.${func}`, {
        name: `str.${func}`,
        kind: 'function',
        signature: `str.${func}(...args) -> String`,
        description: `String ${func} operation`
    });
});
// Math functions
const mathFunctions = ['abs', 'sign', 'floor', 'ceil', 'round', 'trunc', 'min', 'max', 'clamp', 'pow', 'sqrt', 'exp', 'log', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'deg', 'rad', 'random', 'randomInt'];
mathFunctions.forEach(func => {
    builtinFunctions.set(`math.${func}`, {
        name: `math.${func}`,
        kind: 'function',
        signature: `math.${func}(...args) -> Number`,
        description: `Math ${func} operation`
    });
});
// Keywords
const keywords = new Map([
    ['when', { name: 'when', kind: 'keyword', description: 'Pattern matching expression' }],
    ['then', { name: 'then', kind: 'keyword', description: 'Pattern match result' }],
    ['is', { name: 'is', kind: 'keyword', description: 'Pattern match operator' }],
    ['Ok', { name: 'Ok', kind: 'keyword', description: 'Success result constructor' }],
    ['Err', { name: 'Err', kind: 'keyword', description: 'Error result constructor' }],
    ['true', { name: 'true', kind: 'keyword', description: 'Boolean true value' }],
    ['false', { name: 'false', kind: 'keyword', description: 'Boolean false value' }],
    ['PI', { name: 'PI', kind: 'keyword', description: 'Mathematical constant π' }],
    ['INFINITY', { name: 'INFINITY', kind: 'keyword', description: 'Positive infinity' }],
    ['and', { name: 'and', kind: 'keyword', description: 'Logical AND operator' }],
    ['or', { name: 'or', kind: 'keyword', description: 'Logical OR operator' }],
    ['xor', { name: 'xor', kind: 'keyword', description: 'Logical XOR operator' }]
]);
// Types
const types = new Map([
    ['Bool', { name: 'Bool', kind: 'type', description: 'Boolean type (true/false)' }],
    ['Int', { name: 'Int', kind: 'type', description: 'Integer type' }],
    ['Float', { name: 'Float', kind: 'type', description: 'Floating-point type' }],
    ['String', { name: 'String', kind: 'type', description: 'String type' }],
    ['List', { name: 'List', kind: 'type', description: 'List type [T]' }],
    ['Table', { name: 'Table', kind: 'type', description: 'Table type {key: value}' }],
    ['Result', { name: 'Result', kind: 'type', description: 'Result type (Ok T | Err String)' }],
    ['Number', { name: 'Number', kind: 'type', description: 'Numeric supertype (Int | Float)' }]
]);
// Hover Provider
class BabaYagaHoverProvider {
    provideHover(document, position, token) {
        const wordRange = document.getWordRangeAtPosition(position);
        if (!wordRange)
            return null;
        const word = document.getText(wordRange);
        // Check built-in functions
        const builtin = builtinFunctions.get(word);
        if (builtin) {
            return new vscode.Hover([
                `**${builtin.name}**`,
                `\`${builtin.signature}\``,
                builtin.description || ''
            ]);
        }
        // Check keywords
        const keyword = keywords.get(word);
        if (keyword) {
            return new vscode.Hover([
                `**${keyword.name}** (keyword)`,
                keyword.description || ''
            ]);
        }
        // Check types
        const type = types.get(word);
        if (type) {
            return new vscode.Hover([
                `**${type.name}** (type)`,
                type.description || ''
            ]);
        }
        // Check for function definitions in the document
        const functionDef = findFunctionDefinition(document, word);
        if (functionDef) {
            return new vscode.Hover([
                `**${word}** (function)`,
                `\`${functionDef.signature}\``,
                functionDef.description || ''
            ]);
        }
        return null;
    }
}
// Completion Provider
class BabaYagaCompletionProvider {
    provideCompletionItems(document, position, token, context) {
        const items = [];
        // Add built-in functions
        builtinFunctions.forEach((func, name) => {
            const item = new vscode.CompletionItem(name, vscode.CompletionItemKind.Function);
            item.detail = func.signature;
            item.documentation = func.description;
            items.push(item);
        });
        // Add keywords
        keywords.forEach((keyword, name) => {
            const item = new vscode.CompletionItem(name, vscode.CompletionItemKind.Keyword);
            item.documentation = keyword.description;
            items.push(item);
        });
        // Add types
        types.forEach((type, name) => {
            const item = new vscode.CompletionItem(name, vscode.CompletionItemKind.TypeParameter);
            item.documentation = type.description;
            items.push(item);
        });
        // Add operators
        const operators = ['+', '-', '*', '/', '%', '=', '!=', '>', '<', '>=', '<=', '->', '..', ':', 'and', 'or', 'xor'];
        operators.forEach(op => {
            const item = new vscode.CompletionItem(op, vscode.CompletionItemKind.Operator);
            items.push(item);
        });
        return items;
    }
}
// Definition Provider
class BabaYagaDefinitionProvider {
    provideDefinition(document, position, token) {
        const wordRange = document.getWordRangeAtPosition(position);
        if (!wordRange)
            return null;
        const word = document.getText(wordRange);
        // Find function definition in the document
        const functionDef = findFunctionDefinition(document, word);
        if (functionDef) {
            return new vscode.Location(document.uri, functionDef.range);
        }
        return null;
    }
}
// Reference Provider
class BabaYagaReferenceProvider {
    provideReferences(document, position, context, token) {
        const wordRange = document.getWordRangeAtPosition(position);
        if (!wordRange)
            return null;
        const word = document.getText(wordRange);
        const references = [];
        // Find all references in the document
        const text = document.getText();
        const regex = new RegExp(`\\b${word}\\b`, 'g');
        let match;
        while ((match = regex.exec(text)) !== null) {
            const startPos = document.positionAt(match.index);
            const endPos = document.positionAt(match.index + match[0].length);
            references.push(new vscode.Location(document.uri, new vscode.Range(startPos, endPos)));
        }
        return references;
    }
}
// Diagnostic Provider
class BabaYagaDiagnosticProvider {
    constructor() {
        this.diagnosticCollection = vscode.languages.createDiagnosticCollection('baba-yaga');
        vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this);
    }
    onDidChangeTextDocument(event) {
        if (event.document.languageId === 'baba-yaga') {
            this.updateDiagnostics(event.document);
        }
    }
    updateDiagnostics(document) {
        const diagnostics = [];
        const text = document.getText();
        // Basic syntax checking
        const lines = text.split('\n');
        lines.forEach((line, index) => {
            // Check for missing semicolons
            if (line.trim() && !line.trim().startsWith('//') && !line.trim().endsWith(';') && !line.trim().endsWith('{') && !line.trim().endsWith('}')) {
                const range = new vscode.Range(index, line.length, index, line.length);
                diagnostics.push(new vscode.Diagnostic(range, 'Missing semicolon', vscode.DiagnosticSeverity.Warning));
            }
        });
        this.diagnosticCollection.set(document.uri, diagnostics);
    }
}
// Helper functions
function findFunctionDefinition(document, functionName) {
    const text = document.getText();
    const lines = text.split('\n');
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        const match = line.match(new RegExp(`\\b${functionName}\\s*:\\s*(.+?)\\s*->\\s*(.+?)\\s*;`));
        if (match) {
            const signature = `${functionName} : ${match[1]} -> ${match[2]}`;
            const startPos = document.positionAt(text.indexOf(line));
            const endPos = document.positionAt(text.indexOf(line) + line.length);
            return {
                signature,
                range: new vscode.Range(startPos, endPos),
                description: `Function defined at line ${i + 1}`
            };
        }
    }
    return null;
}
// Command implementations
async function showTypeInfo() {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document.languageId !== 'baba-yaga')
        return;
    const position = editor.selection.active;
    const wordRange = editor.document.getWordRangeAtPosition(position);
    if (!wordRange)
        return;
    const word = editor.document.getText(wordRange);
    const type = builtinFunctions.get(word) || keywords.get(word) || types.get(word);
    if (type) {
        vscode.window.showInformationMessage(`${word}: ${type.description || type.signature || type.name}`);
    }
}
async function goToDefinition() {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document.languageId !== 'baba-yaga')
        return;
    const position = editor.selection.active;
    const wordRange = editor.document.getWordRangeAtPosition(position);
    if (!wordRange)
        return;
    const word = editor.document.getText(wordRange);
    const functionDef = findFunctionDefinition(editor.document, word);
    if (functionDef) {
        editor.selection = new vscode.Selection(functionDef.range.start, functionDef.range.end);
        editor.revealRange(functionDef.range);
    }
}
async function findReferences() {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document.languageId !== 'baba-yaga')
        return;
    const position = editor.selection.active;
    const wordRange = editor.document.getWordRangeAtPosition(position);
    if (!wordRange)
        return;
    const word = editor.document.getText(wordRange);
    await vscode.commands.executeCommand('editor.action.referenceSearch.trigger');
}
async function showFunctionSignature() {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document.languageId !== 'baba-yaga')
        return;
    const position = editor.selection.active;
    const wordRange = editor.document.getWordRangeAtPosition(position);
    if (!wordRange)
        return;
    const word = editor.document.getText(wordRange);
    const builtin = builtinFunctions.get(word);
    if (builtin) {
        vscode.window.showInformationMessage(`${word}: ${builtin.signature}`);
    }
}
//# sourceMappingURL=extension.js.map