-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
executable file
·637 lines (534 loc) · 22.4 KB
/
main.js
File metadata and controls
executable file
·637 lines (534 loc) · 22.4 KB
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
#!/usr/bin/env node
const {
createConnection,
Range,
TextDocuments,
TextDocumentSyncKind,
CompletionItemKind,
} = require('vscode-languageserver/node');
const { TextDocument } = require('vscode-languageserver-textdocument');
const { URI } = require('vscode-uri');
const path = require('path');
const packageJson = require('./package.json');
const projectPath = process.argv[2];
// Crear conexión con el cliente
const connection = createConnection();
connection.console.info(`Boriel Basic LSP server is running - Version ${packageJson.version}`);
console.log(`[LSP] Boriel Basic LSP server started - Version ${packageJson.version}`);
// Manejo de documentos abiertos
const documents = new TextDocuments(TextDocument);
documents.listen(connection);
const { borielBasicKeywords } = require('./const');
const { formatBorielBasicCode } = require('./formatter');
const {
globalDefinitions,
globalReferences,
globalVariables,
analyzeProjectFiles,
analyzeFileForDefinitions,
analyzeFileForReferences,
stripComments,
} = require('./analyzer');
// Manejar el evento de formato de documentos
connection.onDocumentFormatting((params) => {
const { formatKeywords: formatKeywords } = connection.workspaceConfig;
console.log(`Formateando documento con formatKeywords: ${formatKeywords}`);
const document = documents.get(params.textDocument.uri);
if (!document) {
return [];
}
// Aplicar las reglas de formato
return formatBorielBasicCode(document, { formatKeywords: formatKeywords });
});
// Manejar solicitud de definición
connection.onDefinition((params) => {
const document = documents.get(params.textDocument.uri);
const position = params.position;
// Obtener la línea de texto en la posición actual
const lineText = document.getText({
start: { line: position.line, character: 0 },
end: { line: position.line, character: Number.MAX_SAFE_INTEGER }
});
// Verificar si la posición está dentro de un comentario
const strippedLine = stripComments(lineText);
if (position.character >= strippedLine.length) {
return null; // Está en un comentario
}
// Extraer la palabra en la posición actual
const words = lineText.trim().split(/\s+/);
let wordAtPosition = words.find((word) => {
const startIndex = lineText.indexOf(word);
const endIndex = startIndex + word.length;
return position.character >= startIndex && position.character <= endIndex;
});
if (!wordAtPosition) {
console.log('No se encontró ninguna palabra en la posición actual.');
return null;
}
// Normalizar la palabra eliminando paréntesis y parámetros
if (wordAtPosition.includes('(')) {
wordAtPosition = wordAtPosition.split('(')[0].trim();
}
console.log(`Buscando definición para: ${wordAtPosition}`);
// Buscar en definiciones de funciones
if (globalDefinitions.has(wordAtPosition)) {
const definition = globalDefinitions.get(wordAtPosition);
console.log(`Definición encontrada para ${wordAtPosition}:`, definition.uri);
return {
uri: definition.uri,
range: definition.range
};
}
console.log(`No se encontró definición para: ${wordAtPosition}`);
return null;
});
// Manejar solicitud de referencias
connection.onReferences((params) => {
const position = params.position;
const document = documents.get(params.textDocument.uri);
if (!document) {
return [];
}
const lineText = document.getText(Range.create(position.line, 0, position.line, document.getText().length));
// Verificar si la posición está dentro de un comentario
const strippedLine = stripComments(lineText);
if (position.character >= strippedLine.length) {
return []; // Está en un comentario
}
const words = lineText.trim().split(/\s+/).map(word => word.replace(/[^\w]/g, ''));
console.log(`Palabras detectadas en la línea ${position.line + 1}:`, words);
for (const word of words) {
if (globalReferences.has(word)) {
console.log(`Referencias globales encontradas para: ${word}`);
return globalReferences.get(word);
}
}
console.log('No se encontraron referencias globales');
return [];
});
// Manejar solicitud de información al pasar el mouse (Hover)
connection.onHover((params) => {
const position = params.position;
const document = documents.get(params.textDocument.uri);
if (!document) {
return null;
}
const lineText = document.getText({
start: { line: position.line, character: 0 },
end: { line: position.line, character: Number.MAX_SAFE_INTEGER }
});
// Verificar si la posición está dentro de un comentario
const strippedLine = stripComments(lineText);
if (position.character >= strippedLine.length) {
return null; // Está en un comentario
}
// Encontrar la palabra en la posición del cursor
// Usamos una regex que incluya caracteres válidos para identificadores
const wordRegex = /[a-zA-Z0-9_$]+/g;
let match;
let wordAtPosition = null;
while ((match = wordRegex.exec(lineText)) !== null) {
const startIndex = match.index;
const endIndex = startIndex + match[0].length;
if (position.character >= startIndex && position.character <= endIndex) {
wordAtPosition = match[0];
break;
}
}
if (!wordAtPosition) {
return null;
}
// Priorizar definiciones globales (incluye builtins)
if (globalDefinitions.has(wordAtPosition)) {
const def = globalDefinitions.get(wordAtPosition);
const headerText = def.header || wordAtPosition;
const docText = def.doc || '';
const contents = {
kind: 'markdown',
// Mostrar la cabecera como bloque de código freebasic para que el cliente
// aplique resaltado de sintaxis (FreeBasic es el más similar a Boriel Basic)
value: '\n\n```freebasic\n' + headerText + '\n```\n\n' + docText
};
return { contents };
}
// Si no es una definición global, buscar en las palabras clave de Boriel Basic
const keyword = borielBasicKeywords.find(k => k.label.toUpperCase() === wordAtPosition.toUpperCase());
if (keyword) {
let signature = '';
if (keyword.type === 'function' && keyword.parameters) {
signature = `\`${keyword.label}(${keyword.parameters}) -> ${keyword.returnType || 'void'}\`\n\n`;
} else if (keyword.type === 'function') {
signature = `\`${keyword.label}() -> ${keyword.returnType || 'void'}\`\n\n`;
}
const contents = {
kind: 'markdown',
value: `**${keyword.label}**\n\n${signature}${keyword.detail}`
};
return { contents };
}
return null;
});
// Inicialización del servidor
connection.onInitialize((params) => {
// Recoger las opciones de inicialización
const formatOptions = params.initializationOptions?.formatOptions || {};
const formatKeywords = formatOptions.formatKeywords || false;
console.log(`Opción formatKeywords recibida: ${formatKeywords}`);
// Guardar la configuración para usarla más tarde
connection.workspaceConfig = {
formatKeywords
};
analyzeProjectFiles();
return {
capabilities: {
textDocumentSync: {
openClose: true,
change: TextDocumentSyncKind.Incremental,
save: { includeText: true } // Habilitar eventos de guardado
},
completionProvider: {
resolveProvider: true // Permite resolver detalles adicionales de los ítems
},
signatureHelpProvider: {
triggerCharacters: ['(', ','] // Activar al escribir '(' o ','
},
documentFormattingProvider: true, // Habilitar el formato de documentos
definitionProvider: true, // Habilitar ir a la definición
referencesProvider: true, // Habilitar encontrar referencias
semanticTokensProvider: {
legend: {
tokenTypes: ['keyword', 'function', 'variable', 'string', 'number', 'comment'],
tokenModifiers: []
},
full: true
}
}
};
});
const { watchBasicFiles } = require('./watcher');
watchBasicFiles();
const { validateBorielBasic } = require('./validator');
// Validar documentos al abrir o cambiar contenido
documents.onDidOpen((event) => {
validateBorielBasic(event.document, connection);
});
documents.onDidChangeContent((event) => {
validateBorielBasic(event.document, connection);
});
// Manejar el evento de guardar un documento
documents.onDidSave((event) => {
const document = event.document;
const uri = document.uri;
const filePath = URI.parse(uri).fsPath;
console.log(`Archivo guardado: ${filePath}. Reanalizando definiciones y referencias...`);
console.log(`URI: ${uri}`);
// Volver a analizar el archivo para encontrar definiciones y referencias
analyzeFileForDefinitions(filePath, uri);
analyzeFileForReferences(filePath, uri);
console.log(`Análisis completado para el archivo guardado: ${filePath}`);
});
// Proveer autocompletado
connection.onCompletion(() => {
console.log('Generando sugerencias de autocompletado...');
console.log('CompletionItemKind:', CompletionItemKind);
// Agregar funciones definidas por el desarrollador
const functionCompletions = Array.from(globalDefinitions.keys()).map(funcName => {
const funcData = globalDefinitions.get(funcName);
if (funcData) {
return {
label: funcName,
kind: CompletionItemKind.Function,
detail: funcData.header,
};
}
});
// Agregar variables definidas por el desarrollador
const variableCompletions = Array.from(globalVariables.keys()).map(varName => {
console.log(globalVariables.get(varName));
const varType = globalVariables.get(varName).type;
return {
label: varName,
kind: CompletionItemKind.Variable,
detail: varType,
documentation: `Variable definida por el usuario`
};
});
// Retornar las palabras clave, funciones y variables como sugerencias de autocompletado
const keywordCompletions = borielBasicKeywords.map(keyword => ({
label: toPascalCase(keyword.label),
kind: keyword.kind || CompletionItemKind.Keyword,
detail: keyword.parameters ? `${keyword.detail}\n(${keyword.parameters})` : keyword.detail
}));
return [...keywordCompletions, ...functionCompletions, ...variableCompletions];
});
function toPascalCase(str) {
return str
.toLowerCase()
.replace(/(?:^|_|\s|-)(\w)/g, (_, c) => (c ? c.toUpperCase() : ''));
}
// Resolver detalles adicionales de los ítems de autocompletado
connection.onCompletionResolve((item) => {
// Puedes agregar más detalles aquí si es necesario
return item;
});
connection.onSignatureHelp((params) => {
const document = documents.get(params.textDocument.uri);
const position = params.position;
if (!document) {
return null;
}
// Obtener la línea de texto en la posición actual
const lineText = document.getText({
start: { line: position.line, character: 0 },
end: { line: position.line, character: Number.MAX_SAFE_INTEGER }
});
// Verificar si la posición está dentro de un comentario
const strippedLine = stripComments(lineText);
if (position.character >= strippedLine.length) {
return null; // Está en un comentario
}
// Extraer la palabra antes del paréntesis de apertura
const match = lineText.match(/(\w+)\s*\(/);
if (!match) {
return null;
}
const funcName = match[1];
console.log(`Buscando firma para la función: ${funcName}`);
// Buscar la función en las definiciones globales
let funcData = globalDefinitions.get(funcName);
let isUserDefined = true;
if (!funcData) {
// Buscar en las palabras clave de Boriel Basic
const keyword = borielBasicKeywords.find(k => k.label.toUpperCase() === funcName.toUpperCase() && k.type === 'function');
if (keyword) {
funcData = {
parameters: keyword.parameters || '',
returnType: keyword.returnType || 'void',
detail: keyword.detail
};
isUserDefined = false;
}
}
if (!funcData) {
console.log(`No se encontró la función: ${funcName}`);
return null;
}
// Crear la respuesta de ayuda de firma
const parameters = funcData.parameters ? funcData.parameters.split(',').map(param => param.trim()) : [];
const signature = {
label: `${funcName}(${funcData.parameters}) -> ${funcData.returnType}`,
documentation: isUserDefined
? `Función definida por el usuario.\n\nRetorna: ${funcData.returnType}`
: `${funcData.detail}\n\nRetorna: ${funcData.returnType}`,
parameters: parameters.map(param => ({
label: param,
documentation: `Parámetro: ${param}`
}))
};
return {
signatures: [signature],
activeSignature: 0,
activeParameter: Math.max(0, params.context?.triggerCharacter === ',' ? parameters.length - 1 : 0)
};
});
connection.languages.semanticTokens.on((params) => {
const document = documents.get(params.textDocument.uri);
if (!document) {
return { data: [] };
}
const text = document.getText();
const lines = text.split(/\r?\n/);
const tokens = [];
lines.forEach((line, lineIndex) => {
let remainingLine = line;
let currentCharIndex = 0;
let commentToken = null;
// Detectar comentarios de forma robusta
const strippedLine = stripComments(line);
if (strippedLine.length < line.length) {
const commentStart = strippedLine.length;
commentToken = {
line: lineIndex,
startChar: commentStart,
length: line.length - commentStart,
tokenType: 5, // 'comment'
tokenModifiers: []
};
// Truncar la línea para no procesar el comentario como código
remainingLine = strippedLine;
}
// Detectar tokens compuestos
borielBasicKeywords
.filter(k => k.label.includes(' ')) // Filtrar solo tokens compuestos
.forEach(keyword => {
const keywordIndex = remainingLine.toUpperCase().indexOf(keyword.label.toUpperCase());
if (keywordIndex !== -1) {
tokens.push({
line: lineIndex,
startChar: keywordIndex,
length: keyword.label.length,
tokenType: getTokenType(keyword.type),
tokenModifiers: []
});
// Eliminar el token compuesto de la línea para evitar procesarlo dos veces
remainingLine = remainingLine.slice(0, keywordIndex) + ' '.repeat(keyword.label.length) + remainingLine.slice(keywordIndex + keyword.label.length);
}
});
// Detectar cabeceras de funciones o subrutinas
if (/^\s*(Sub|Function)\b/i.test(line)) {
const match = line.match(/^\s*(Sub|Function)\s+(\w+)\s*\((.*)\)\s*(As\s+\w+)?/i);
if (match) {
const [, keyword, functionName, parameters, returnType] = match;
// Agregar el token para la palabra clave (Sub o Function)
tokens.push({
line: lineIndex,
startChar: line.indexOf(keyword),
length: keyword.length,
tokenType: 0, // 'keyword'
tokenModifiers: []
});
// Agregar el token para el nombre de la función
tokens.push({
line: lineIndex,
startChar: line.indexOf(functionName),
length: functionName.length,
tokenType: 1, // 'function'
tokenModifiers: []
});
// Procesar los parámetros
const params = parameters.split(',').map(param => param.trim());
params.forEach(param => {
const paramMatch = param.match(/(\w+)\s+As\s+(\w+)/i);
if (paramMatch) {
const [, paramName, paramType] = paramMatch;
// Buscar la posición del nombre del parámetro
const paramNameStart = line.indexOf(paramName, currentCharIndex);
// Agregar el token para el nombre del parámetro
tokens.push({
line: lineIndex,
startChar: paramNameStart,
length: paramName.length,
tokenType: 2, // 'variable'
tokenModifiers: []
});
// Buscar la posición de "As" y el tipo
const asIndex = line.indexOf('As', paramNameStart + paramName.length);
const typeStartChar = line.indexOf(paramType, asIndex + 2);
// Agregar el token para el tipo del parámetro
tokens.push({
line: lineIndex,
startChar: typeStartChar,
length: paramType.length,
tokenType: 4, // 'type'
tokenModifiers: []
});
// Actualizar el índice actual para evitar conflictos con parámetros posteriores
currentCharIndex = typeStartChar + paramType.length;
}
});
// Procesar el tipo de retorno
if (returnType) {
const returnTypeMatch = returnType.match(/As\s+(\w+)/i);
if (returnTypeMatch) {
const [, returnTypeName] = returnTypeMatch;
// Buscar la posición de "As" y el tipo de retorno
const returnAsIndex = line.indexOf('As', line.indexOf(')') + 1);
const returnTypeStartChar = line.indexOf(returnTypeName, returnAsIndex + 2);
// Agregar el token para el tipo de retorno
tokens.push({
line: lineIndex,
startChar: returnTypeStartChar,
length: returnTypeName.length,
tokenType: 4, // 'type'
tokenModifiers: []
});
}
}
}
}
// Detectar palabras clave y otros tokens
const words = remainingLine.split(/\s+/);
words.forEach((word, wordIndex) => {
// Eliminar paréntesis y su contenido del nombre
// Si la palabra contiene un paréntesis de apertura, nos quedamos con lo que hay antes
if (word.includes('(')) {
word = word.split('(')[0];
}
// También limpiar paréntesis de cierre si quedaron (por si acaso)
word = word.replace(/\)/g, '');
const startChar = line.indexOf(word, wordIndex > 0 ? line.indexOf(words[wordIndex - 1]) + words[wordIndex - 1].length : 0);
const length = word.length;
// Detectar palabras clave
const keyword = borielBasicKeywords.find(k => k.label.toUpperCase() === word.toUpperCase());
if (keyword) {
tokens.push({
line: lineIndex,
startChar,
length,
tokenType: getTokenType(keyword.type),
tokenModifiers: []
});
return;
}
// Detectar variables
if (globalVariables.has(word)) {
tokens.push({
line: lineIndex,
startChar,
length,
tokenType: 2, // 'variable'
tokenModifiers: []
});
return;
}
});
// Detectar palabras clave de tipo 'type' en cualquier contexto
borielBasicKeywords
.filter(k => k.type === 'type') // Filtrar solo palabras clave de tipo 'type'
.forEach(typeKeyword => {
let typeIndex = remainingLine.toUpperCase().indexOf(typeKeyword.label.toUpperCase());
while (typeIndex !== -1) {
tokens.push({
line: lineIndex,
startChar: typeIndex,
length: typeKeyword.label.length,
tokenType: 4, // 'type'
tokenModifiers: []
});
// Continuar buscando más ocurrencias en la misma línea
typeIndex = remainingLine.toUpperCase().indexOf(typeKeyword.label.toUpperCase(), typeIndex + typeKeyword.label.length);
}
});
// Agregar el token de comentario al final, si existe
if (commentToken) {
tokens.push(commentToken);
}
});
// Convertir los tokens al formato esperado
const data = [];
let lastLine = 0;
let lastChar = 0;
tokens.forEach(token => {
const deltaLine = token.line - lastLine;
const deltaStart = deltaLine === 0 ? token.startChar - lastChar : token.startChar;
data.push(deltaLine, deltaStart, token.length, token.tokenType, 0);
lastLine = token.line;
lastChar = token.startChar;
});
return { data };
});
// Función para obtener el tipo de token
function getTokenType(type) {
switch (type) {
case 'logic': return 0; // 'keyword'
case 'control': return 3; // 'control'
case 'type': return 4; // 'type'
case 'definition': return 5; // 'definition'
case 'io': return 6; // 'io'
case 'function': return 1; // 'function'
case 'keyword': return 0; // 'keyword'
default: return 0; // Default to 'keyword'
}
}
// Escuchar la conexión
connection.listen();