mhs-lang 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,283 +1,283 @@
1
- const {
2
- CompletionItemKind,
3
- DiagnosticSeverity,
4
- ProposedFeatures,
5
- SemanticTokensBuilder,
6
- TextDocuments,
7
- TextDocumentSyncKind,
8
- createConnection,
9
- } = require('vscode-languageserver/node');
10
- const { TextDocument } = require('vscode-languageserver-textdocument');
11
- const { transpile } = require('./transpiler');
12
-
13
- const KEYWORDS = new Set([
14
- 'asinkron', 'fungsi', 'kelas', 'jika', 'atau_jika', 'jika_tidak', 'selain_itu',
15
- 'lainnya', 'selama', 'untuk', 'dalam', 'coba', 'tangkap', 'akhirnya', 'dengan',
16
- 'kembalikan', 'hasilkan', 'berhenti', 'lanjut', 'lewat', 'lempar', 'pastikan',
17
- 'umum', 'impor', 'dari', 'sebagai', 'impor_py', 'dari_py',
18
- 'if', 'elif', 'else', 'while', 'for', 'in', 'def', 'class', 'return', 'yield',
19
- 'break', 'continue', 'pass', 'raise', 'assert', 'try', 'except', 'finally',
20
- 'with', 'import', 'from', 'as', 'async', 'await', 'global', 'nonlocal',
21
- 'lambda', 'and', 'or', 'not', 'is', 'del', 'dan', 'atau', 'bukan',
22
- 'adalah', 'bukan_adalah',
23
- ]);
24
-
25
- const BUILTINS = new Set([
26
- 'cetak', 'masukan', 'rentang', 'panjang', 'tipe', 'teks', 'angka', 'bulat',
27
- 'desimal', 'tambah', 'hapus', 'urutkan', 'balik', 'gabung', 'pisah',
28
- 'huruf_besar', 'huruf_kecil', 'potong', 'ganti', 'mengandung', 'acak',
29
- 'akar', 'pangkat', 'mutlak', 'bulatkan', 'bawah', 'atas', 'min_nilai',
30
- 'maks_nilai', 'jumlah', 'waktu_sekarang', 'tunggu', 'daftar', 'kamus',
31
- 'print', 'input', 'range', 'len', 'str', 'int', 'float', 'list', 'dict',
32
- 'set', 'tuple', 'enumerate', 'zip', 'sum', 'min', 'max', 'abs', 'round',
33
- ]);
34
-
35
- const MODULES = [
36
- 'matematika', 'modul_acak', 'waktu', 'berkas', 'sistem', 'data_json',
37
- 'pola', 'koleksi', 'kripto', 'jaringan', 'uji',
38
- ];
39
-
40
- const CONSTANTS = ['Benar', 'Salah', 'Kosong', 'True', 'False', 'None'];
41
-
42
- const COMPLETIONS = [
43
- ...Array.from(KEYWORDS, (label) => ({
44
- label,
45
- kind: CompletionItemKind.Keyword,
46
- })),
47
- ...CONSTANTS.map((label) => ({
48
- label,
49
- kind: CompletionItemKind.Constant,
50
- })),
51
- ...Array.from(BUILTINS, (label) => ({
52
- label,
53
- kind: CompletionItemKind.Function,
54
- })),
55
- ...MODULES.map((label) => ({
56
- label,
57
- kind: CompletionItemKind.Module,
58
- detail: 'Modul standar MHS',
59
- })),
60
- ];
61
-
62
- const TOKEN_TYPES = ['keyword', 'function', 'type', 'string', 'number', 'comment', 'operator'];
63
- const TOKEN_TYPE_INDEX = new Map(TOKEN_TYPES.map((name, index) => [name, index]));
64
-
65
- function collectSemanticTokens(text) {
66
- const tokens = [];
67
- const lines = text.split(/\r\n|\r|\n/);
68
-
69
- for (let lineNumber = 0; lineNumber < lines.length; lineNumber += 1) {
70
- const line = lines[lineNumber];
71
- let offset = 0;
72
- let pendingDeclaration = null;
73
-
74
- while (offset < line.length) {
75
- const character = line[offset];
76
- if (/\s/.test(character)) {
77
- offset += 1;
78
- continue;
79
- }
80
-
81
- if (character === '#') {
82
- tokens.push({
83
- line: lineNumber,
84
- start: offset,
85
- length: line.length - offset,
86
- type: 'comment',
87
- });
88
- break;
89
- }
90
-
91
- const stringStart = /[fF]/.test(character) && /["']/.test(line[offset + 1])
92
- ? offset + 1
93
- : offset;
94
- if (line[stringStart] === '"' || line[stringStart] === "'") {
95
- const quote = line[stringStart];
96
- let end = stringStart + 1;
97
- while (end < line.length) {
98
- if (line[end] === '\\') {
99
- end += 2;
100
- continue;
101
- }
102
- if (line[end] === quote) {
103
- end += 1;
104
- break;
105
- }
106
- end += 1;
107
- }
108
- tokens.push({
109
- line: lineNumber,
110
- start: offset,
111
- length: end - offset,
112
- type: 'string',
113
- });
114
- offset = end;
115
- pendingDeclaration = null;
116
- continue;
117
- }
118
-
119
- const identifier = line.slice(offset).match(/^[A-Za-z_]\w*/);
120
- if (identifier) {
121
- const label = identifier[0];
122
- let type;
123
- if (KEYWORDS.has(label)) {
124
- type = 'keyword';
125
- if (label === 'fungsi' || label === 'def') {
126
- pendingDeclaration = 'function';
127
- } else if (label === 'kelas' || label === 'class') {
128
- pendingDeclaration = 'type';
129
- }
130
- } else if (pendingDeclaration) {
131
- type = pendingDeclaration;
132
- pendingDeclaration = null;
133
- } else if (BUILTINS.has(label)) {
134
- type = 'function';
135
- } else if (['Benar', 'Salah', 'Kosong', 'True', 'False', 'None'].includes(label)) {
136
- type = 'keyword';
137
- }
138
-
139
- if (type) {
140
- tokens.push({
141
- line: lineNumber,
142
- start: offset,
143
- length: label.length,
144
- type,
145
- });
146
- }
147
- offset += label.length;
148
- continue;
149
- }
150
-
151
- const number = line.slice(offset).match(/^\d+(?:\.\d+)?/);
152
- if (number) {
153
- tokens.push({
154
- line: lineNumber,
155
- start: offset,
156
- length: number[0].length,
157
- type: 'number',
158
- });
159
- offset += number[0].length;
160
- pendingDeclaration = null;
161
- continue;
162
- }
163
-
164
- if (/[+\-*/%=<>!&|^~]/.test(character)) {
165
- let end = offset + 1;
166
- while (end < line.length && /[+\-*/%=<>!&|^~]/.test(line[end])) {
167
- end += 1;
168
- }
169
- tokens.push({
170
- line: lineNumber,
171
- start: offset,
172
- length: end - offset,
173
- type: 'operator',
174
- });
175
- offset = end;
176
- pendingDeclaration = null;
177
- continue;
178
- }
179
-
180
- pendingDeclaration = null;
181
- offset += 1;
182
- }
183
- }
184
-
185
- return tokens;
186
- }
187
-
188
- function getDiagnostics(text) {
189
- try {
190
- transpile(text);
191
- return [];
192
- } catch (error) {
193
- if (!(error instanceof SyntaxError)) {
194
- throw error;
195
- }
196
-
197
- const lineMatch = error.message.match(/\bbaris\s+(\d+)/i);
198
- const lineNumber = lineMatch ? Math.max(0, Number(lineMatch[1]) - 1) : 0;
199
- const lines = text.split(/\r\n|\r|\n/);
200
- const lineText = lines[lineNumber] || '';
201
-
202
- return [{
203
- range: {
204
- start: { line: lineNumber, character: 0 },
205
- end: { line: lineNumber, character: Math.min(1, lineText.length) },
206
- },
207
- severity: DiagnosticSeverity.Error,
208
- source: 'mhs',
209
- message: error.message,
210
- }];
211
- }
212
- }
213
-
214
- function createLanguageServer(
215
- connection = createConnection(ProposedFeatures.all, process.stdin, process.stdout)
216
- ) {
217
- const documents = new TextDocuments(TextDocument);
218
- const legend = {
219
- tokenTypes: TOKEN_TYPES,
220
- tokenModifiers: [],
221
- };
222
-
223
- connection.onInitialize(() => ({
224
- capabilities: {
225
- textDocumentSync: TextDocumentSyncKind.Incremental,
226
- completionProvider: {
227
- triggerCharacters: ['.'],
228
- },
229
- semanticTokensProvider: {
230
- legend,
231
- full: true,
232
- },
233
- },
234
- }));
235
-
236
- documents.onDidOpen(({ document }) => {
237
- connection.sendDiagnostics({
238
- uri: document.uri,
239
- diagnostics: getDiagnostics(document.getText()),
240
- });
241
- });
242
-
243
- documents.onDidChangeContent(({ document }) => {
244
- connection.sendDiagnostics({
245
- uri: document.uri,
246
- diagnostics: getDiagnostics(document.getText()),
247
- });
248
- });
249
-
250
- documents.onDidClose(({ document }) => {
251
- connection.sendDiagnostics({ uri: document.uri, diagnostics: [] });
252
- });
253
-
254
- connection.onCompletion(() => COMPLETIONS);
255
-
256
- connection.languages.semanticTokens.on(({ textDocument }) => {
257
- const document = documents.get(textDocument.uri);
258
- if (!document) {
259
- return { data: [] };
260
- }
261
-
262
- const builder = new SemanticTokensBuilder(legend);
263
- for (const token of collectSemanticTokens(document.getText())) {
264
- builder.push(
265
- token.line,
266
- token.start,
267
- token.length,
268
- TOKEN_TYPE_INDEX.get(token.type),
269
- 0
270
- );
271
- }
272
- return builder.build();
273
- });
274
-
275
- documents.listen(connection);
276
- connection.listen();
277
- }
278
-
279
- module.exports = {
280
- collectSemanticTokens,
281
- createLanguageServer,
282
- getDiagnostics,
283
- };
1
+ const {
2
+ CompletionItemKind,
3
+ DiagnosticSeverity,
4
+ ProposedFeatures,
5
+ SemanticTokensBuilder,
6
+ TextDocuments,
7
+ TextDocumentSyncKind,
8
+ createConnection,
9
+ } = require('vscode-languageserver/node');
10
+ const { TextDocument } = require('vscode-languageserver-textdocument');
11
+ const { transpile } = require('./transpiler');
12
+
13
+ const KEYWORDS = new Set([
14
+ 'asinkron', 'fungsi', 'kelas', 'jika', 'atau_jika', 'jika_tidak', 'selain_itu',
15
+ 'lainnya', 'selama', 'untuk', 'dalam', 'coba', 'tangkap', 'akhirnya', 'dengan',
16
+ 'kembalikan', 'hasilkan', 'berhenti', 'lanjut', 'lewat', 'lempar', 'pastikan',
17
+ 'umum', 'impor', 'dari', 'sebagai', 'impor_py', 'dari_py',
18
+ 'if', 'elif', 'else', 'while', 'for', 'in', 'def', 'class', 'return', 'yield',
19
+ 'break', 'continue', 'pass', 'raise', 'assert', 'try', 'except', 'finally',
20
+ 'with', 'import', 'from', 'as', 'async', 'await', 'global', 'nonlocal',
21
+ 'lambda', 'and', 'or', 'not', 'is', 'del', 'dan', 'atau', 'bukan',
22
+ 'adalah', 'bukan_adalah',
23
+ ]);
24
+
25
+ const BUILTINS = new Set([
26
+ 'cetak', 'masukan', 'rentang', 'panjang', 'tipe', 'teks', 'angka', 'bulat',
27
+ 'desimal', 'tambah', 'hapus', 'urutkan', 'balik', 'gabung', 'pisah',
28
+ 'huruf_besar', 'huruf_kecil', 'potong', 'ganti', 'mengandung', 'acak',
29
+ 'akar', 'pangkat', 'mutlak', 'bulatkan', 'bawah', 'atas', 'min_nilai',
30
+ 'maks_nilai', 'jumlah', 'waktu_sekarang', 'tunggu', 'daftar', 'kamus',
31
+ 'print', 'input', 'range', 'len', 'str', 'int', 'float', 'list', 'dict',
32
+ 'set', 'tuple', 'enumerate', 'zip', 'sum', 'min', 'max', 'abs', 'round',
33
+ ]);
34
+
35
+ const MODULES = [
36
+ 'matematika', 'modul_acak', 'waktu', 'berkas', 'sistem', 'data_json',
37
+ 'pola', 'koleksi', 'kripto', 'jaringan', 'uji',
38
+ ];
39
+
40
+ const CONSTANTS = ['Benar', 'Salah', 'Kosong', 'True', 'False', 'None'];
41
+
42
+ const COMPLETIONS = [
43
+ ...Array.from(KEYWORDS, (label) => ({
44
+ label,
45
+ kind: CompletionItemKind.Keyword,
46
+ })),
47
+ ...CONSTANTS.map((label) => ({
48
+ label,
49
+ kind: CompletionItemKind.Constant,
50
+ })),
51
+ ...Array.from(BUILTINS, (label) => ({
52
+ label,
53
+ kind: CompletionItemKind.Function,
54
+ })),
55
+ ...MODULES.map((label) => ({
56
+ label,
57
+ kind: CompletionItemKind.Module,
58
+ detail: 'Modul standar MHS',
59
+ })),
60
+ ];
61
+
62
+ const TOKEN_TYPES = ['keyword', 'function', 'type', 'string', 'number', 'comment', 'operator'];
63
+ const TOKEN_TYPE_INDEX = new Map(TOKEN_TYPES.map((name, index) => [name, index]));
64
+
65
+ function collectSemanticTokens(text) {
66
+ const tokens = [];
67
+ const lines = text.split(/\r\n|\r|\n/);
68
+
69
+ for (let lineNumber = 0; lineNumber < lines.length; lineNumber += 1) {
70
+ const line = lines[lineNumber];
71
+ let offset = 0;
72
+ let pendingDeclaration = null;
73
+
74
+ while (offset < line.length) {
75
+ const character = line[offset];
76
+ if (/\s/.test(character)) {
77
+ offset += 1;
78
+ continue;
79
+ }
80
+
81
+ if (character === '#') {
82
+ tokens.push({
83
+ line: lineNumber,
84
+ start: offset,
85
+ length: line.length - offset,
86
+ type: 'comment',
87
+ });
88
+ break;
89
+ }
90
+
91
+ const stringStart = /[fF]/.test(character) && /["']/.test(line[offset + 1])
92
+ ? offset + 1
93
+ : offset;
94
+ if (line[stringStart] === '"' || line[stringStart] === "'") {
95
+ const quote = line[stringStart];
96
+ let end = stringStart + 1;
97
+ while (end < line.length) {
98
+ if (line[end] === '\\') {
99
+ end += 2;
100
+ continue;
101
+ }
102
+ if (line[end] === quote) {
103
+ end += 1;
104
+ break;
105
+ }
106
+ end += 1;
107
+ }
108
+ tokens.push({
109
+ line: lineNumber,
110
+ start: offset,
111
+ length: end - offset,
112
+ type: 'string',
113
+ });
114
+ offset = end;
115
+ pendingDeclaration = null;
116
+ continue;
117
+ }
118
+
119
+ const identifier = line.slice(offset).match(/^[A-Za-z_]\w*/);
120
+ if (identifier) {
121
+ const label = identifier[0];
122
+ let type;
123
+ if (KEYWORDS.has(label)) {
124
+ type = 'keyword';
125
+ if (label === 'fungsi' || label === 'def') {
126
+ pendingDeclaration = 'function';
127
+ } else if (label === 'kelas' || label === 'class') {
128
+ pendingDeclaration = 'type';
129
+ }
130
+ } else if (pendingDeclaration) {
131
+ type = pendingDeclaration;
132
+ pendingDeclaration = null;
133
+ } else if (BUILTINS.has(label)) {
134
+ type = 'function';
135
+ } else if (['Benar', 'Salah', 'Kosong', 'True', 'False', 'None'].includes(label)) {
136
+ type = 'keyword';
137
+ }
138
+
139
+ if (type) {
140
+ tokens.push({
141
+ line: lineNumber,
142
+ start: offset,
143
+ length: label.length,
144
+ type,
145
+ });
146
+ }
147
+ offset += label.length;
148
+ continue;
149
+ }
150
+
151
+ const number = line.slice(offset).match(/^\d+(?:\.\d+)?/);
152
+ if (number) {
153
+ tokens.push({
154
+ line: lineNumber,
155
+ start: offset,
156
+ length: number[0].length,
157
+ type: 'number',
158
+ });
159
+ offset += number[0].length;
160
+ pendingDeclaration = null;
161
+ continue;
162
+ }
163
+
164
+ if (/[+\-*/%=<>!&|^~]/.test(character)) {
165
+ let end = offset + 1;
166
+ while (end < line.length && /[+\-*/%=<>!&|^~]/.test(line[end])) {
167
+ end += 1;
168
+ }
169
+ tokens.push({
170
+ line: lineNumber,
171
+ start: offset,
172
+ length: end - offset,
173
+ type: 'operator',
174
+ });
175
+ offset = end;
176
+ pendingDeclaration = null;
177
+ continue;
178
+ }
179
+
180
+ pendingDeclaration = null;
181
+ offset += 1;
182
+ }
183
+ }
184
+
185
+ return tokens;
186
+ }
187
+
188
+ function getDiagnostics(text) {
189
+ try {
190
+ transpile(text);
191
+ return [];
192
+ } catch (error) {
193
+ if (!(error instanceof SyntaxError)) {
194
+ throw error;
195
+ }
196
+
197
+ const lineMatch = error.message.match(/\bbaris\s+(\d+)/i);
198
+ const lineNumber = lineMatch ? Math.max(0, Number(lineMatch[1]) - 1) : 0;
199
+ const lines = text.split(/\r\n|\r|\n/);
200
+ const lineText = lines[lineNumber] || '';
201
+
202
+ return [{
203
+ range: {
204
+ start: { line: lineNumber, character: 0 },
205
+ end: { line: lineNumber, character: Math.min(1, lineText.length) },
206
+ },
207
+ severity: DiagnosticSeverity.Error,
208
+ source: 'mhs',
209
+ message: error.message,
210
+ }];
211
+ }
212
+ }
213
+
214
+ function createLanguageServer(
215
+ connection = createConnection(ProposedFeatures.all, process.stdin, process.stdout)
216
+ ) {
217
+ const documents = new TextDocuments(TextDocument);
218
+ const legend = {
219
+ tokenTypes: TOKEN_TYPES,
220
+ tokenModifiers: [],
221
+ };
222
+
223
+ connection.onInitialize(() => ({
224
+ capabilities: {
225
+ textDocumentSync: TextDocumentSyncKind.Incremental,
226
+ completionProvider: {
227
+ triggerCharacters: ['.'],
228
+ },
229
+ semanticTokensProvider: {
230
+ legend,
231
+ full: true,
232
+ },
233
+ },
234
+ }));
235
+
236
+ documents.onDidOpen(({ document }) => {
237
+ connection.sendDiagnostics({
238
+ uri: document.uri,
239
+ diagnostics: getDiagnostics(document.getText()),
240
+ });
241
+ });
242
+
243
+ documents.onDidChangeContent(({ document }) => {
244
+ connection.sendDiagnostics({
245
+ uri: document.uri,
246
+ diagnostics: getDiagnostics(document.getText()),
247
+ });
248
+ });
249
+
250
+ documents.onDidClose(({ document }) => {
251
+ connection.sendDiagnostics({ uri: document.uri, diagnostics: [] });
252
+ });
253
+
254
+ connection.onCompletion(() => COMPLETIONS);
255
+
256
+ connection.languages.semanticTokens.on(({ textDocument }) => {
257
+ const document = documents.get(textDocument.uri);
258
+ if (!document) {
259
+ return { data: [] };
260
+ }
261
+
262
+ const builder = new SemanticTokensBuilder(legend);
263
+ for (const token of collectSemanticTokens(document.getText())) {
264
+ builder.push(
265
+ token.line,
266
+ token.start,
267
+ token.length,
268
+ TOKEN_TYPE_INDEX.get(token.type),
269
+ 0
270
+ );
271
+ }
272
+ return builder.build();
273
+ });
274
+
275
+ documents.listen(connection);
276
+ connection.listen();
277
+ }
278
+
279
+ module.exports = {
280
+ collectSemanticTokens,
281
+ createLanguageServer,
282
+ getDiagnostics,
283
+ };