@sdkgen/parser 0.0.0-dev.20231002144112 → 0.0.0-dev.20231002191238

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.
Files changed (100) hide show
  1. package/dist/ast.js +298 -0
  2. package/dist/compatibility/index.js +206 -0
  3. package/dist/helpers.js +20 -0
  4. package/dist/index.js +9 -0
  5. package/dist/json.js +225 -0
  6. package/dist/lexer.js +283 -0
  7. package/dist/parser.js +419 -0
  8. package/dist/restparser.js +59 -0
  9. package/dist/semantic/01_check_multiple_declaration.js +19 -0
  10. package/dist/semantic/02_give_struct_and_enum_names.js +58 -0
  11. package/dist/semantic/03_match_type_definitions.js +15 -0
  12. package/dist/semantic/04_check_dont_return_secret.js +39 -0
  13. package/dist/semantic/05_expand_spreads.js +57 -0
  14. package/dist/semantic/06_check_empty_struct_or_enum.js +18 -0
  15. package/dist/semantic/07_validate_recursive_types.js +46 -0
  16. package/dist/semantic/08_collect_struct_and_enum_types.js +22 -0
  17. package/dist/semantic/09_validate_annotations.js +122 -0
  18. package/dist/semantic/10_check_duplicate_members_on_enum.js +13 -0
  19. package/dist/semantic/analyser.js +27 -0
  20. package/dist/semantic/transformer.js +46 -0
  21. package/dist/semantic/visitor.js +61 -0
  22. package/dist/token.js +93 -0
  23. package/dist/utils.js +25 -0
  24. package/package.json +11 -4
  25. package/.eslintrc.json +0 -3
  26. package/.prettierrc +0 -12
  27. package/dist/spec/lexer.spec.d.ts +0 -1
  28. package/dist/spec/lexer.spec.js +0 -152
  29. package/dist/spec/parser.spec.d.ts +0 -1
  30. package/dist/spec/parser.spec.js +0 -967
  31. package/dist/src/ast.js +0 -355
  32. package/dist/src/compatibility/index.js +0 -211
  33. package/dist/src/helpers.js +0 -23
  34. package/dist/src/index.js +0 -29
  35. package/dist/src/json.js +0 -234
  36. package/dist/src/lexer.js +0 -287
  37. package/dist/src/parser.js +0 -423
  38. package/dist/src/restparser.js +0 -65
  39. package/dist/src/semantic/01_check_multiple_declaration.js +0 -22
  40. package/dist/src/semantic/02_give_struct_and_enum_names.js +0 -61
  41. package/dist/src/semantic/03_match_type_definitions.js +0 -18
  42. package/dist/src/semantic/04_check_dont_return_secret.js +0 -42
  43. package/dist/src/semantic/05_expand_spreads.js +0 -60
  44. package/dist/src/semantic/06_check_empty_struct_or_enum.js +0 -21
  45. package/dist/src/semantic/07_validate_recursive_types.js +0 -49
  46. package/dist/src/semantic/08_collect_struct_and_enum_types.js +0 -25
  47. package/dist/src/semantic/09_validate_annotations.js +0 -125
  48. package/dist/src/semantic/10_check_duplicate_members_on_enum.js +0 -16
  49. package/dist/src/semantic/analyser.js +0 -30
  50. package/dist/src/semantic/transformer.js +0 -50
  51. package/dist/src/semantic/visitor.js +0 -65
  52. package/dist/src/token.js +0 -119
  53. package/dist/src/utils.js +0 -27
  54. package/dist/tsconfig.tsbuildinfo +0 -1
  55. package/src/ast.ts +0 -273
  56. package/src/compatibility/index.ts +0 -273
  57. package/src/helpers.ts +0 -28
  58. package/src/index.ts +0 -8
  59. package/src/json.ts +0 -350
  60. package/src/lexer.ts +0 -343
  61. package/src/parser.ts +0 -604
  62. package/src/restparser.ts +0 -81
  63. package/src/semantic/01_check_multiple_declaration.ts +0 -21
  64. package/src/semantic/02_give_struct_and_enum_names.ts +0 -57
  65. package/src/semantic/03_match_type_definitions.ts +0 -19
  66. package/src/semantic/04_check_dont_return_secret.ts +0 -40
  67. package/src/semantic/05_expand_spreads.ts +0 -67
  68. package/src/semantic/06_check_empty_struct_or_enum.ts +0 -21
  69. package/src/semantic/07_validate_recursive_types.ts +0 -47
  70. package/src/semantic/08_collect_struct_and_enum_types.ts +0 -23
  71. package/src/semantic/09_validate_annotations.ts +0 -158
  72. package/src/semantic/10_check_duplicate_members_on_enum.ts +0 -15
  73. package/src/semantic/analyser.ts +0 -29
  74. package/src/semantic/transformer.ts +0 -41
  75. package/src/semantic/visitor.ts +0 -60
  76. package/src/token.ts +0 -92
  77. package/src/utils.ts +0 -63
  78. /package/dist/{src/ast.d.ts → ast.d.ts} +0 -0
  79. /package/dist/{src/compatibility → compatibility}/index.d.ts +0 -0
  80. /package/dist/{src/helpers.d.ts → helpers.d.ts} +0 -0
  81. /package/dist/{src/index.d.ts → index.d.ts} +0 -0
  82. /package/dist/{src/json.d.ts → json.d.ts} +0 -0
  83. /package/dist/{src/lexer.d.ts → lexer.d.ts} +0 -0
  84. /package/dist/{src/parser.d.ts → parser.d.ts} +0 -0
  85. /package/dist/{src/restparser.d.ts → restparser.d.ts} +0 -0
  86. /package/dist/{src/semantic → semantic}/01_check_multiple_declaration.d.ts +0 -0
  87. /package/dist/{src/semantic → semantic}/02_give_struct_and_enum_names.d.ts +0 -0
  88. /package/dist/{src/semantic → semantic}/03_match_type_definitions.d.ts +0 -0
  89. /package/dist/{src/semantic → semantic}/04_check_dont_return_secret.d.ts +0 -0
  90. /package/dist/{src/semantic → semantic}/05_expand_spreads.d.ts +0 -0
  91. /package/dist/{src/semantic → semantic}/06_check_empty_struct_or_enum.d.ts +0 -0
  92. /package/dist/{src/semantic → semantic}/07_validate_recursive_types.d.ts +0 -0
  93. /package/dist/{src/semantic → semantic}/08_collect_struct_and_enum_types.d.ts +0 -0
  94. /package/dist/{src/semantic → semantic}/09_validate_annotations.d.ts +0 -0
  95. /package/dist/{src/semantic → semantic}/10_check_duplicate_members_on_enum.d.ts +0 -0
  96. /package/dist/{src/semantic → semantic}/analyser.d.ts +0 -0
  97. /package/dist/{src/semantic → semantic}/transformer.d.ts +0 -0
  98. /package/dist/{src/semantic → semantic}/visitor.d.ts +0 -0
  99. /package/dist/{src/token.d.ts → token.d.ts} +0 -0
  100. /package/dist/{src/utils.d.ts → utils.d.ts} +0 -0
package/src/parser.ts DELETED
@@ -1,604 +0,0 @@
1
- /* eslint-disable no-sync */
2
- /* eslint-disable no-loop-func */
3
-
4
- import type { Annotation, Type } from "./ast";
5
- import {
6
- StatusCodeAnnotation,
7
- ArgDescriptionAnnotation,
8
- ArrayType,
9
- AstRoot,
10
- DescriptionAnnotation,
11
- EnumType,
12
- EnumValue,
13
- ErrorNode,
14
- Field,
15
- FunctionOperation,
16
- HiddenAnnotation,
17
- OptionalType,
18
- Spread,
19
- StructType,
20
- ThrowsAnnotation,
21
- TypeDefinition,
22
- TypeReference,
23
- VoidPrimitiveType,
24
- } from "./ast";
25
- import { Lexer } from "./lexer";
26
- import { parseRestAnnotation } from "./restparser";
27
- import { analyse } from "./semantic/analyser";
28
- import type { CurlyCloseSymbolToken, FalseKeywordToken, ImportKeywordToken, SpreadSymbolToken, Token, TrueKeywordToken } from "./token";
29
- import {
30
- AnnotationToken,
31
- ArraySymbolToken,
32
- ColonSymbolToken,
33
- CurlyOpenSymbolToken,
34
- EnumKeywordToken,
35
- ErrorKeywordToken,
36
- ExclamationMarkSymbolToken,
37
- FnKeywordToken,
38
- IdentifierToken,
39
- OptionalSymbolToken,
40
- ParensOpenSymbolToken,
41
- PrimitiveTypeToken,
42
- StringLiteralToken,
43
- TypeKeywordToken,
44
- CommaSymbolToken,
45
- ParensCloseSymbolToken,
46
- } from "./token";
47
- import { primitiveToAstClass } from "./utils";
48
-
49
- export class ParserError extends Error {}
50
-
51
- interface MultiExpectMatcher<T> {
52
- ArraySymbolToken?(token: ArraySymbolToken): T;
53
- CommaSymbolToken?(token: CommaSymbolToken): T;
54
- CurlyCloseSymbolToken?(token: CurlyCloseSymbolToken): T;
55
- CurlyOpenSymbolToken?(token: CurlyOpenSymbolToken): T;
56
- EnumKeywordToken?(token: EnumKeywordToken): T;
57
- ErrorKeywordToken?(token: ErrorKeywordToken): T;
58
- FalseKeywordToken?(token: FalseKeywordToken): T;
59
- FnKeywordToken?(token: FnKeywordToken): T;
60
- IdentifierToken?(token: IdentifierToken): T;
61
- ImportKeywordToken?(token: ImportKeywordToken): T;
62
- OptionalSymbolToken?(token: OptionalSymbolToken): T;
63
- ParensCloseSymbolToken?(token: ParensCloseSymbolToken): T;
64
- PrimitiveTypeToken?(token: PrimitiveTypeToken): T;
65
- SpreadSymbolToken?(token: SpreadSymbolToken): T;
66
- TrueKeywordToken?(token: TrueKeywordToken): T;
67
- TypeKeywordToken?(token: TypeKeywordToken): T;
68
- }
69
-
70
- export class Parser {
71
- private readonly lexers: Lexer[];
72
-
73
- private token: Token | null = null;
74
-
75
- private annotations: Annotation[] = [];
76
-
77
- private warnings: string[] = [];
78
-
79
- private readFileSync: (path: string) => { toString(): string } = () => {
80
- throw "Not implemented";
81
- };
82
-
83
- constructor(source: Lexer | string | Array<Lexer | string>) {
84
- try {
85
- // eslint-disable-next-line
86
- this.readFileSync = require("fs").readFileSync;
87
- } catch (e) {
88
- // do nothing
89
- }
90
-
91
- const sources = Array.isArray(source) ? [...source].reverse() : [source];
92
-
93
- this.lexers = sources.map(x => (x instanceof Lexer ? x : new Lexer(this.readFileSync(x).toString(), x)));
94
-
95
- this.nextToken();
96
- }
97
-
98
- private nextToken() {
99
- while (this.lexers.length > 0) {
100
- this.token = this.lexers[this.lexers.length - 1].nextToken();
101
- if (this.token) {
102
- return;
103
- }
104
-
105
- this.lexers.pop();
106
- }
107
- }
108
-
109
- private multiExpect<T>(matcher: MultiExpectMatcher<T>) {
110
- if (!this.token) {
111
- throw new ParserError(
112
- `Expected ${Object.keys(matcher)
113
- .map(x => x.replace("Token", ""))
114
- .join(" or ")}, but found end of file`,
115
- );
116
- }
117
-
118
- const tokenName = this.token.constructor.name;
119
-
120
- if (tokenName in matcher) {
121
- return (matcher as Record<string, (token: Token) => T>)[tokenName](this.token);
122
- } else if (matcher.IdentifierToken) {
123
- const tokenAsIdent = this.token.maybeAsIdentifier();
124
-
125
- if (tokenAsIdent instanceof IdentifierToken) {
126
- return matcher.IdentifierToken(tokenAsIdent);
127
- }
128
- }
129
-
130
- throw new ParserError(
131
- `Expected ${Object.keys(matcher)
132
- .map(x => x.replace("Token", ""))
133
- .join(" or ")} at ${this.token.location}, but found ${this.token}`,
134
- );
135
- }
136
-
137
- private expect(x: typeof IdentifierToken): IdentifierToken;
138
-
139
- private expect(x: typeof StringLiteralToken): StringLiteralToken;
140
-
141
- private expect(type: Function): Token {
142
- if (this.token === null) {
143
- throw new ParserError(`Expected ${type.name.replace("Token", "")}, but found end of file`);
144
- } else if (this.token instanceof type) {
145
- return this.token;
146
- } else {
147
- if (type === IdentifierToken) {
148
- const tokenAsIdent = this.token.maybeAsIdentifier();
149
-
150
- if (tokenAsIdent instanceof IdentifierToken) {
151
- return tokenAsIdent;
152
- }
153
- }
154
-
155
- throw new ParserError(`Expected ${type.name.replace("Token", "")} at ${this.token.location}, but found ${this.token}`);
156
- }
157
- }
158
-
159
- parse(): AstRoot {
160
- const operations: FunctionOperation[] = [];
161
- const typeDefinition: TypeDefinition[] = [];
162
- const errors: ErrorNode[] = [];
163
-
164
- this.warnings = [];
165
-
166
- while (this.token) {
167
- this.acceptAnnotations();
168
- this.multiExpect({
169
- ErrorKeywordToken: () => {
170
- errors.push(this.parseError());
171
- },
172
- FnKeywordToken: () => {
173
- operations.push(this.parseOperation());
174
- },
175
- ImportKeywordToken: () => {
176
- this.checkCannotHaveAnnotationsHere();
177
- this.nextToken();
178
- const pathToken = this.expect(StringLiteralToken);
179
- const resolvedPath = pathToken.location.filename.replace(/[^/\\]+$/u, `${pathToken.value}.sdkgen`);
180
-
181
- this.lexers.push(new Lexer(this.readFileSync(resolvedPath).toString(), resolvedPath));
182
- this.nextToken();
183
- },
184
- TypeKeywordToken: () => {
185
- typeDefinition.push(this.parseTypeDefinition());
186
- },
187
- });
188
- }
189
-
190
- const ast = new AstRoot(typeDefinition, operations, errors);
191
-
192
- ast.warnings = this.warnings;
193
- analyse(ast);
194
- return ast;
195
- }
196
-
197
- private acceptAnnotations() {
198
- while (this.token instanceof AnnotationToken) {
199
- const words = this.token.value.split(" ");
200
- const body = this.token.value.slice(words[0].length).trim();
201
-
202
- switch (words[0]) {
203
- case "description":
204
- this.annotations.push(new DescriptionAnnotation(body).at(this.token));
205
- break;
206
- case "arg":
207
- this.annotations.push(
208
- new ArgDescriptionAnnotation(words[1], this.token.value.slice(words[0].length + 1 + words[1].length).trim()).at(this.token),
209
- );
210
- break;
211
- case "throws":
212
- this.annotations.push(new ThrowsAnnotation(body).at(this.token));
213
- break;
214
- case "rest":
215
- try {
216
- this.annotations.push(parseRestAnnotation(body).at(this.token));
217
- } catch (error: unknown) {
218
- throw new ParserError(`${error instanceof Error ? error.message : error} at ${this.token.location}`);
219
- }
220
-
221
- break;
222
- case "hidden":
223
- if (body !== "") {
224
- throw new ParserError(`@hidden annotation doesn't take any argument`);
225
- }
226
-
227
- this.annotations.push(new HiddenAnnotation().at(this.token));
228
-
229
- break;
230
- case "statusCode": {
231
- const statusCode = parseInt(body, 10);
232
-
233
- if (statusCode.toString() !== body.trim()) {
234
- throw new ParserError(`@statusCode annotation takes an integer as argument`);
235
- }
236
-
237
- this.annotations.push(new StatusCodeAnnotation(statusCode).at(this.token));
238
- break;
239
- }
240
-
241
- default:
242
- throw new ParserError(`Unknown annotation '${words[0]}' at ${this.token.location}`);
243
- }
244
-
245
- this.nextToken();
246
- }
247
- }
248
-
249
- private checkCannotHaveAnnotationsHere() {
250
- if (this.annotations.length > 0) {
251
- throw new ParserError(`Cannot have annotations at ${this.annotations[0].location}`);
252
- }
253
- }
254
-
255
- private parseTypeDefinition(): TypeDefinition {
256
- const typeToken = this.expect(TypeKeywordToken);
257
-
258
- this.nextToken();
259
-
260
- const nameToken = this.expect(IdentifierToken);
261
- const name = nameToken.value;
262
-
263
- if (!/[A-Z]/u.test(name[0])) {
264
- throw new ParserError(`The custom type name must start with an uppercase letter, but found ${JSON.stringify(name)} at ${nameToken.location}`);
265
- }
266
-
267
- this.nextToken();
268
-
269
- const { annotations } = this;
270
-
271
- this.annotations = [];
272
-
273
- const type = this.parseType();
274
- const definitions = new TypeDefinition(name, type).at(typeToken);
275
-
276
- definitions.annotations = annotations;
277
-
278
- return definitions;
279
- }
280
-
281
- private parseError(): ErrorNode {
282
- const errorToken = this.expect(ErrorKeywordToken);
283
-
284
- this.nextToken();
285
-
286
- const nameToken = this.expect(IdentifierToken);
287
- const name = nameToken.value;
288
-
289
- if (!/[A-Z]/u.test(name[0])) {
290
- throw new ParserError(`Error name must start with an uppercase letter, but found ${JSON.stringify(name)} at ${nameToken.location}`);
291
- }
292
-
293
- this.nextToken();
294
-
295
- let type: Type = new VoidPrimitiveType();
296
-
297
- if (
298
- this.token instanceof CurlyOpenSymbolToken ||
299
- this.token instanceof EnumKeywordToken ||
300
- this.token instanceof IdentifierToken ||
301
- this.token instanceof PrimitiveTypeToken
302
- ) {
303
- type = this.parseType();
304
- }
305
-
306
- const node = new ErrorNode(name, type).at(errorToken);
307
-
308
- node.annotations = this.annotations;
309
- this.annotations = [];
310
- return node;
311
- }
312
-
313
- private parseOperation() {
314
- let { annotations } = this;
315
-
316
- this.annotations = [];
317
-
318
- this.expect(FnKeywordToken);
319
-
320
- this.nextToken();
321
-
322
- const name = this.expect(IdentifierToken).value;
323
-
324
- this.nextToken();
325
-
326
- this.expect(ParensOpenSymbolToken);
327
- this.nextToken();
328
-
329
- const argNames = new Set<string>();
330
- const fieldsAndSpreads: Array<Field | Spread> = [];
331
- let finished = false;
332
- let parensCloseToken!: ParensCloseSymbolToken;
333
-
334
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
335
- while (!finished) {
336
- this.acceptAnnotations();
337
- this.multiExpect({
338
- ParensCloseSymbolToken: token => {
339
- this.checkCannotHaveAnnotationsHere();
340
- this.nextToken();
341
- finished = true;
342
- parensCloseToken = token;
343
- },
344
- IdentifierToken: () => {
345
- const field = this.parseField();
346
-
347
- if (argNames.has(field.name)) {
348
- throw new ParserError(`Cannot redeclare argument '${field.name}'`);
349
- }
350
-
351
- argNames.add(field.name);
352
- fieldsAndSpreads.push(field);
353
-
354
- this.multiExpect({
355
- ParensCloseSymbolToken: token => {
356
- this.checkCannotHaveAnnotationsHere();
357
- this.nextToken();
358
- finished = true;
359
- parensCloseToken = token;
360
- },
361
- CommaSymbolToken: () => this.nextToken(),
362
- });
363
- },
364
- SpreadSymbolToken: () => {
365
- this.checkCannotHaveAnnotationsHere();
366
- this.nextToken();
367
- const identToken = this.expect(IdentifierToken);
368
-
369
- this.nextToken();
370
- if (!/[A-Z]/u.test(identToken.value[0])) {
371
- throw new ParserError(`Expected a type but found ${JSON.stringify(identToken.value)} at ${identToken.location}`);
372
- }
373
-
374
- fieldsAndSpreads.push(new Spread(new TypeReference(identToken.value).at(identToken)).at(identToken));
375
-
376
- this.multiExpect({
377
- ParensCloseSymbolToken: token => {
378
- this.checkCannotHaveAnnotationsHere();
379
- this.nextToken();
380
- finished = true;
381
- parensCloseToken = token;
382
- },
383
- CommaSymbolToken: () => this.nextToken(),
384
- });
385
- },
386
- });
387
- }
388
-
389
- for (const annotation of annotations) {
390
- if (annotation instanceof ArgDescriptionAnnotation) {
391
- const arg = fieldsAndSpreads.find(x => x instanceof Field && x.name === annotation.argName) as Field | undefined;
392
-
393
- if (!arg) {
394
- throw new ParserError(`Argument '${annotation.argName}' not found, at ${annotation.location}`);
395
- }
396
-
397
- arg.annotations.push(new DescriptionAnnotation(annotation.text).atLocation(annotation.location));
398
- }
399
- }
400
-
401
- annotations = annotations.filter(ann => !(ann instanceof ArgDescriptionAnnotation));
402
-
403
- let returnType: Type = new VoidPrimitiveType().at(parensCloseToken);
404
-
405
- if (this.token instanceof ColonSymbolToken) {
406
- this.nextToken();
407
- returnType = this.parseType();
408
- }
409
-
410
- const op = new FunctionOperation(name, fieldsAndSpreads, returnType);
411
-
412
- op.annotations = annotations;
413
-
414
- return op;
415
- }
416
-
417
- private parseEnum(): EnumType {
418
- this.checkCannotHaveAnnotationsHere();
419
- const enumToken = this.expect(EnumKeywordToken);
420
-
421
- this.nextToken();
422
-
423
- this.expect(CurlyOpenSymbolToken);
424
- this.nextToken();
425
-
426
- const enumType = new EnumType([]).at(enumToken);
427
-
428
- let finished = false;
429
-
430
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
431
- while (!finished) {
432
- this.acceptAnnotations();
433
- this.multiExpect({
434
- CurlyCloseSymbolToken: () => {
435
- this.checkCannotHaveAnnotationsHere();
436
- this.nextToken();
437
- finished = true;
438
- },
439
- IdentifierToken: token => {
440
- const enumValue = new EnumValue(token.value).at(token);
441
-
442
- enumValue.annotations = this.annotations;
443
- this.annotations = [];
444
- enumType.values.push(enumValue);
445
- this.nextToken();
446
-
447
- if (!(this.token instanceof ParensOpenSymbolToken)) {
448
- return;
449
- }
450
-
451
- this.nextToken();
452
- const fieldNames = new Set<string>();
453
- const fields = [];
454
-
455
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
456
- while (this.token && this.token.maybeAsIdentifier() instanceof IdentifierToken) {
457
- const field = this.parseField();
458
-
459
- // "tag" is a reserved name on tagged enum fields and can't be used.
460
- if (field.name === "tag") {
461
- field.name = "_tag";
462
- }
463
-
464
- if (fieldNames.has(field.name)) {
465
- throw new ParserError(`Cannot redeclare argument '${field.name}'`);
466
- }
467
-
468
- fieldNames.add(field.name);
469
- fields.push(field);
470
-
471
- if (this.token instanceof CommaSymbolToken) {
472
- this.nextToken();
473
- } else {
474
- break;
475
- }
476
- }
477
-
478
- enumValue.struct = new StructType(fields).atLocation(enumValue.location);
479
-
480
- this.expect(ParensCloseSymbolToken);
481
- this.nextToken();
482
- },
483
- });
484
- }
485
-
486
- return enumType;
487
- }
488
-
489
- private parseField(): Field {
490
- const nameToken = this.expect(IdentifierToken);
491
-
492
- this.nextToken();
493
-
494
- this.expect(ColonSymbolToken);
495
- this.nextToken();
496
-
497
- const { annotations } = this;
498
-
499
- this.annotations = [];
500
-
501
- const type = this.parseType();
502
- const field = new Field(nameToken.value, type).at(nameToken);
503
-
504
- field.annotations = annotations;
505
-
506
- while (this.token instanceof ExclamationMarkSymbolToken) {
507
- this.nextToken();
508
- switch (this.expect(IdentifierToken).value) {
509
- case "secret":
510
- field.secret = true;
511
- break;
512
- default:
513
- throw new ParserError(`Unknown field mark !${this.token.value} at ${this.token.location}`);
514
- }
515
-
516
- this.nextToken();
517
- }
518
-
519
- return field;
520
- }
521
-
522
- private parseStruct(): StructType {
523
- const openingToken = this.expect(CurlyOpenSymbolToken);
524
-
525
- this.nextToken();
526
-
527
- const fieldsAndSpreads: Array<Field | Spread> = [];
528
- const fieldNames = new Set<string>();
529
-
530
- let finished = false;
531
-
532
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
533
- while (!finished) {
534
- this.acceptAnnotations();
535
- this.multiExpect({
536
- CurlyCloseSymbolToken: () => {
537
- this.checkCannotHaveAnnotationsHere();
538
- this.nextToken();
539
- finished = true;
540
- },
541
- IdentifierToken: () => {
542
- const field = this.parseField();
543
-
544
- if (fieldNames.has(field.name)) {
545
- throw new ParserError(`Cannot redeclare field '${field.name}'`);
546
- }
547
-
548
- fieldNames.add(field.name);
549
- fieldsAndSpreads.push(field);
550
- },
551
- SpreadSymbolToken: () => {
552
- this.checkCannotHaveAnnotationsHere();
553
- this.nextToken();
554
- const identToken = this.expect(IdentifierToken);
555
-
556
- this.nextToken();
557
- if (!/[A-Z]/u.test(identToken.value[0])) {
558
- throw new ParserError(`Expected a type but found ${JSON.stringify(identToken.value)} at ${identToken.location}`);
559
- }
560
-
561
- fieldsAndSpreads.push(new Spread(new TypeReference(identToken.value).at(identToken)).at(identToken));
562
- },
563
- });
564
- }
565
-
566
- return new StructType(fieldsAndSpreads).at(openingToken);
567
- }
568
-
569
- private parseType(): Type {
570
- this.checkCannotHaveAnnotationsHere();
571
- let result = this.multiExpect<Type>({
572
- CurlyOpenSymbolToken: () => this.parseStruct(),
573
- EnumKeywordToken: () => this.parseEnum(),
574
- IdentifierToken: token => {
575
- this.nextToken();
576
- if (!/[A-Z]/u.test(token.value[0])) {
577
- throw new ParserError(`Expected a type but found ${JSON.stringify(token.value)} at ${token.location}`);
578
- }
579
-
580
- return new TypeReference(token.value).at(token);
581
- },
582
- PrimitiveTypeToken: token => {
583
- this.nextToken();
584
- const primitiveClass = primitiveToAstClass.get(token.value);
585
-
586
- if (primitiveClass) {
587
- return new primitiveClass().at(token);
588
- }
589
-
590
- throw new ParserError(`BUG! Should handle primitive ${token.value}`);
591
- },
592
- });
593
-
594
- while (this.token instanceof ArraySymbolToken || this.token instanceof OptionalSymbolToken) {
595
- this.multiExpect({
596
- ArraySymbolToken: token => (result = new ArrayType(result).at(token)),
597
- OptionalSymbolToken: token => (result = new OptionalType(result).at(token)),
598
- });
599
- this.nextToken();
600
- }
601
-
602
- return result;
603
- }
604
- }
package/src/restparser.ts DELETED
@@ -1,81 +0,0 @@
1
- import { RestAnnotation } from "./ast";
2
-
3
- function scanHeaders(text: string) {
4
- // Header name: https://tools.ietf.org/html/rfc2616#section-4.2
5
- const headerRegex = /\[header (?<header>[^()<>@,;:\\"/[\]?={}\s\t]+): \{(?<name>\w+)\}\]/gu;
6
- const headers = new Map<string, string>();
7
-
8
- let match: RegExpExecArray | null;
9
-
10
- while ((match = headerRegex.exec(text)) !== null) {
11
- if (match.groups?.header && match.groups.name) {
12
- headers.set(match.groups.header.toLowerCase(), match.groups.name);
13
- }
14
- }
15
-
16
- return headers;
17
- }
18
-
19
- function scanBody(text: string) {
20
- const match = /\[body \{(?<name>\w+)\}\]/u.exec(text);
21
-
22
- if (match?.groups?.name) {
23
- return match.groups.name;
24
- }
25
-
26
- return null;
27
- }
28
-
29
- function scanVariables(text: string) {
30
- const variableRegex = /\{(?<name>\w+)\}/gu;
31
- const variables: string[] = [];
32
-
33
- let match: RegExpExecArray | null;
34
-
35
- while ((match = variableRegex.exec(text)) !== null) {
36
- if (match.groups?.name) {
37
- variables.push(match.groups.name);
38
- }
39
- }
40
-
41
- return variables;
42
- }
43
-
44
- export function parseRestAnnotation(text: string): RestAnnotation {
45
- const fragments = text.split(" ");
46
- const method = fragments[0].toUpperCase();
47
-
48
- if (!["GET", "POST", "PUT", "DELETE", "PATCH"].includes(method)) {
49
- throw new Error(`Unsupported method '${method}'`);
50
- }
51
-
52
- // eslint-disable-next-line prefer-destructuring
53
- let path = fragments[1];
54
-
55
- if (!path.startsWith("/")) {
56
- throw new Error(`Invalid path`);
57
- }
58
-
59
- let queryVariables: string[] = [];
60
-
61
- if (path.includes("?")) {
62
- const [base, ...queryArray] = path.split("?");
63
-
64
- path = base;
65
- const query = queryArray.join("?");
66
-
67
- if (!/^\{\w+\}(?:&\{\w+\})*$/u.test(query)) {
68
- throw new Error(`Invalid querystring on path`);
69
- }
70
-
71
- queryVariables = scanVariables(query);
72
- }
73
-
74
- const pathVariables = scanVariables(path);
75
-
76
- const remaining = fragments.slice(2).join(" ");
77
- const headers = scanHeaders(remaining);
78
- const bodyVariable = scanBody(remaining);
79
-
80
- return new RestAnnotation(method, path, pathVariables, queryVariables, headers, bodyVariable);
81
- }
@@ -1,21 +0,0 @@
1
- import { SemanticError, Visitor } from "./visitor";
2
- import type { AstNode, Type } from "../ast";
3
- import { TypeDefinition } from "../ast";
4
-
5
- export class CheckMultipleDeclarationVisitor extends Visitor {
6
- nameToType = new Map<string, Type>();
7
-
8
- visit(node: AstNode): void {
9
- if (node instanceof TypeDefinition) {
10
- const previousType = this.nameToType.get(node.name);
11
-
12
- if (previousType && JSON.stringify(previousType) !== JSON.stringify(node.type)) {
13
- throw new SemanticError(`Type '${node.name}' at ${node.location} is defined multiple times (also at ${previousType.location})`);
14
- }
15
-
16
- this.nameToType.set(node.name, node.type);
17
- }
18
-
19
- super.visit(node);
20
- }
21
- }