@sdkgen/parser 1.6.1 → 2.0.1

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 (37) hide show
  1. package/README.md +1 -3
  2. package/dist/spec/lexer.spec.js +1 -3
  3. package/dist/spec/parser.spec.js +305 -30
  4. package/dist/src/ast.d.ts +17 -15
  5. package/dist/src/ast.js +23 -21
  6. package/dist/src/compatibility/index.js +17 -7
  7. package/dist/src/index.js +5 -1
  8. package/dist/src/json.d.ts +10 -18
  9. package/dist/src/json.js +100 -62
  10. package/dist/src/lexer.js +1 -7
  11. package/dist/src/parser.js +92 -40
  12. package/dist/src/semantic/{06_give_struct_and_enum_names.d.ts → 02_give_struct_and_enum_names.d.ts} +0 -0
  13. package/dist/src/semantic/{06_give_struct_and_enum_names.js → 02_give_struct_and_enum_names.js} +6 -1
  14. package/dist/src/semantic/{02_match_type_definitions.d.ts → 03_match_type_definitions.d.ts} +0 -0
  15. package/dist/src/semantic/{02_match_type_definitions.js → 03_match_type_definitions.js} +0 -0
  16. package/dist/src/semantic/04_check_dont_return_secret.d.ts +1 -0
  17. package/dist/src/semantic/04_check_dont_return_secret.js +7 -1
  18. package/dist/src/semantic/05_expand_spreads.d.ts +9 -0
  19. package/dist/src/semantic/05_expand_spreads.js +60 -0
  20. package/dist/src/semantic/{07_check_empty_struct_or_enum.d.ts → 06_check_empty_struct_or_enum.d.ts} +0 -0
  21. package/dist/src/semantic/{07_check_empty_struct_or_enum.js → 06_check_empty_struct_or_enum.js} +1 -1
  22. package/dist/src/semantic/07_validate_recursive_types.d.ts +8 -0
  23. package/dist/src/semantic/07_validate_recursive_types.js +49 -0
  24. package/dist/src/semantic/{10_validate_annotations.d.ts → 09_validate_annotations.d.ts} +0 -0
  25. package/dist/src/semantic/{10_validate_annotations.js → 09_validate_annotations.js} +5 -1
  26. package/dist/src/semantic/analyser.js +12 -14
  27. package/dist/src/semantic/visitor.js +19 -3
  28. package/dist/src/token.d.ts +1 -4
  29. package/dist/src/token.js +4 -10
  30. package/dist/tsconfig.tsbuildinfo +1 -2191
  31. package/package.json +6 -6
  32. package/dist/src/semantic/03_check_no_recursive_types.d.ts +0 -7
  33. package/dist/src/semantic/03_check_no_recursive_types.js +0 -36
  34. package/dist/src/semantic/05_check_naming_for_getters_returning_bool.d.ts +0 -5
  35. package/dist/src/semantic/05_check_naming_for_getters_returning_bool.js +0 -21
  36. package/dist/src/semantic/09_apply_struct_spreads.d.ts +0 -7
  37. package/dist/src/semantic/09_apply_struct_spreads.js +0 -42
@@ -1,19 +1,11 @@
1
1
  import { AstRoot } from "./ast";
2
2
  import type { DeepReadonly } from "./utils";
3
- export declare type TypeDescription = string | string[] | {
4
- [name: string]: TypeDescription;
5
- };
6
- interface TypeTable {
7
- [name: string]: TypeDescription | undefined;
8
- }
9
- interface FunctionTable {
10
- [name: string]: {
11
- args: {
12
- [arg: string]: TypeDescription;
13
- };
14
- ret: TypeDescription;
15
- } | undefined;
16
- }
3
+ export declare type TypeDescription = string | Array<string | [string, string]> | Record<string, string>;
4
+ declare type TypeTable = Record<string, TypeDescription | undefined>;
5
+ declare type FunctionTable = Record<string, {
6
+ args: Record<string, string>;
7
+ ret: TypeDescription;
8
+ } | undefined>;
17
9
  declare type AnnotationJson = {
18
10
  type: "description";
19
11
  value: string;
@@ -27,17 +19,17 @@ declare type AnnotationJson = {
27
19
  type: "rest";
28
20
  value: {
29
21
  bodyVariable: string | null;
30
- headers: Array<[string, string]>;
22
+ headers: ReadonlyArray<[string, string]>;
31
23
  method: string;
32
24
  path: string;
33
- pathVariables: string[];
34
- queryVariables: string[];
25
+ pathVariables: readonly string[];
26
+ queryVariables: readonly string[];
35
27
  };
36
28
  };
37
29
  export interface AstJson {
38
30
  typeTable: TypeTable;
39
31
  functionTable: FunctionTable;
40
- errors: Array<string | string[]>;
32
+ errors: Array<string | [string, string]>;
41
33
  annotations: Record<string, AnnotationJson[] | undefined>;
42
34
  }
43
35
  export declare function astToJson(ast: AstRoot): AstJson;
package/dist/src/json.js CHANGED
@@ -4,74 +4,112 @@ exports.jsonToAst = exports.astToJson = void 0;
4
4
  const ast_1 = require("./ast");
5
5
  const analyser_1 = require("./semantic/analyser");
6
6
  const utils_1 = require("./utils");
7
+ function annotationToJson(ann) {
8
+ if (ann instanceof ast_1.DescriptionAnnotation) {
9
+ return { type: "description", value: ann.text };
10
+ }
11
+ else if (ann instanceof ast_1.ThrowsAnnotation) {
12
+ return { type: "throws", value: ann.error };
13
+ }
14
+ else if (ann instanceof ast_1.RestAnnotation) {
15
+ return {
16
+ type: "rest",
17
+ value: {
18
+ bodyVariable: ann.bodyVariable,
19
+ headers: [...ann.headers.entries()].sort(([a], [b]) => a.localeCompare(b)),
20
+ method: ann.method,
21
+ path: ann.path,
22
+ pathVariables: [...ann.pathVariables].sort((a, b) => a.localeCompare(b)),
23
+ queryVariables: [...ann.queryVariables].sort((a, b) => a.localeCompare(b)),
24
+ },
25
+ };
26
+ }
27
+ else if (ann instanceof ast_1.HiddenAnnotation) {
28
+ return { type: "hidden", value: null };
29
+ }
30
+ throw new Error(`BUG: annotationToJson with ${ann.constructor.name}`);
31
+ }
32
+ function annotationFromJson(json) {
33
+ switch (json.type) {
34
+ case "description":
35
+ return new ast_1.DescriptionAnnotation(json.value);
36
+ case "throws":
37
+ return new ast_1.ThrowsAnnotation(json.value);
38
+ case "rest": {
39
+ const { method, path, pathVariables, queryVariables, headers, bodyVariable } = json.value;
40
+ return new ast_1.RestAnnotation(method, path, pathVariables, queryVariables, new Map(headers), bodyVariable);
41
+ }
42
+ case "hidden":
43
+ return new ast_1.HiddenAnnotation();
44
+ default:
45
+ throw new Error(`BUG: annotationFromJson with ${json.type}`);
46
+ }
47
+ }
7
48
  function astToJson(ast) {
49
+ var _a, _b, _c;
8
50
  const annotations = {};
9
51
  const typeTable = {};
52
+ function processType(type) {
53
+ if (type instanceof ast_1.ArrayType) {
54
+ return `${processType(type.base)}[]`;
55
+ }
56
+ else if (type instanceof ast_1.OptionalType) {
57
+ return `${processType(type.base)}?`;
58
+ }
59
+ return type.name;
60
+ }
10
61
  for (const { name, fields } of ast.structTypes) {
11
62
  typeTable[name] = {};
12
63
  const obj = typeTable[name];
13
64
  for (const field of fields) {
14
- obj[field.name] = field.type.name;
65
+ obj[field.name] = processType(field.type);
15
66
  for (const ann of field.annotations) {
16
67
  if (ann instanceof ast_1.DescriptionAnnotation) {
17
68
  const target = `type.${name}.${field.name}`;
18
- annotations[target] || (annotations[target] = []);
19
- const list = annotations[target];
20
- list.push({ type: "description", value: ann.text });
69
+ (_a = annotations[target]) !== null && _a !== void 0 ? _a : (annotations[target] = []);
70
+ annotations[target].push(annotationToJson(ann));
21
71
  }
22
72
  }
23
73
  }
24
74
  }
25
75
  for (const { name, values } of ast.enumTypes) {
26
- typeTable[name] = values.map(v => v.value);
76
+ typeTable[name] = values.map(v => {
77
+ if (!v.struct) {
78
+ return v.value;
79
+ }
80
+ return [v.value, v.struct.name];
81
+ });
82
+ }
83
+ for (const { name, type } of ast.typeDefinitions) {
84
+ if (type instanceof ast_1.StructType || type instanceof ast_1.EnumType) {
85
+ continue;
86
+ }
87
+ typeTable[name] = processType(type);
27
88
  }
28
89
  const functionTable = {};
29
90
  for (const op of ast.operations) {
30
91
  const args = {};
31
92
  for (const arg of op.args) {
32
- args[arg.name] = arg.type.name;
93
+ args[arg.name] = processType(arg.type);
33
94
  for (const ann of arg.annotations) {
34
95
  if (ann instanceof ast_1.DescriptionAnnotation) {
35
- const target = `fn.${op.prettyName}.${arg.name}`;
36
- annotations[target] || (annotations[target] = []);
37
- const list = annotations[target];
38
- list.push({ type: "description", value: ann.text });
96
+ const target = `fn.${op.name}.${arg.name}`;
97
+ (_b = annotations[target]) !== null && _b !== void 0 ? _b : (annotations[target] = []);
98
+ annotations[target].push(annotationToJson(ann));
39
99
  }
40
100
  }
41
101
  }
42
- functionTable[op.prettyName] = {
102
+ functionTable[op.name] = {
43
103
  args,
44
- ret: op.returnType.name,
104
+ ret: processType(op.returnType),
45
105
  };
46
106
  for (const ann of op.annotations) {
47
- const target = `fn.${op.prettyName}`;
48
- annotations[target] || (annotations[target] = []);
49
- const list = annotations[target];
50
- if (ann instanceof ast_1.DescriptionAnnotation) {
51
- list.push({ type: "description", value: ann.text });
52
- }
53
- if (ann instanceof ast_1.ThrowsAnnotation) {
54
- list.push({ type: "throws", value: ann.error });
55
- }
56
- if (ann instanceof ast_1.RestAnnotation) {
57
- list.push({
58
- type: "rest",
59
- value: {
60
- bodyVariable: ann.bodyVariable,
61
- headers: [...ann.headers.entries()],
62
- method: ann.method,
63
- path: ann.path,
64
- pathVariables: ann.pathVariables,
65
- queryVariables: ann.queryVariables,
66
- },
67
- });
68
- }
69
- if (ann instanceof ast_1.HiddenAnnotation) {
70
- list.push({ type: "hidden", value: null });
71
- }
107
+ const target = `fn.${op.name}`;
108
+ (_c = annotations[target]) !== null && _c !== void 0 ? _c : (annotations[target] = []);
109
+ annotations[target].push(annotationToJson(ann));
72
110
  }
73
111
  }
74
- const errors = ast.errors.map(error => (error.dataType instanceof ast_1.VoidPrimitiveType ? error.name : [error.name, error.dataType.name]));
112
+ const errors = ast.errors.map(error => error.dataType instanceof ast_1.VoidPrimitiveType ? error.name : [error.name, error.dataType.name]);
75
113
  return {
76
114
  annotations,
77
115
  errors,
@@ -81,9 +119,10 @@ function astToJson(ast) {
81
119
  }
82
120
  exports.astToJson = astToJson;
83
121
  function jsonToAst(json) {
84
- var _a;
122
+ var _a, _b;
85
123
  const operations = [];
86
124
  const typeDefinition = [];
125
+ const solveEnumValueStructRef = [];
87
126
  function processType(description, typeName) {
88
127
  var _a;
89
128
  if (typeof description === "string") {
@@ -100,7 +139,15 @@ function jsonToAst(json) {
100
139
  return new ast_1.TypeReference(description);
101
140
  }
102
141
  else if (Array.isArray(description)) {
103
- return new ast_1.EnumType(description.map(v => new ast_1.EnumValue(v)));
142
+ return new ast_1.EnumType(description.map(v => {
143
+ if (Array.isArray(v)) {
144
+ const [value, structName] = v;
145
+ const enumValue = new ast_1.EnumValue(value);
146
+ solveEnumValueStructRef.push([enumValue, structName]);
147
+ return enumValue;
148
+ }
149
+ return new ast_1.EnumValue(v);
150
+ }));
104
151
  }
105
152
  const fields = [];
106
153
  for (const fieldName of Object.keys(description)) {
@@ -108,14 +155,12 @@ function jsonToAst(json) {
108
155
  if (typeName) {
109
156
  const target = `type.${typeName}.${fieldName}`;
110
157
  for (const annotationJson of (_a = json.annotations[target]) !== null && _a !== void 0 ? _a : []) {
111
- if (annotationJson.type === "description") {
112
- field.annotations.push(new ast_1.DescriptionAnnotation(annotationJson.value));
113
- }
158
+ field.annotations.push(annotationFromJson(annotationJson));
114
159
  }
115
160
  }
116
161
  fields.push(field);
117
162
  }
118
- return new ast_1.StructType(fields, []);
163
+ return new ast_1.StructType(fields);
119
164
  }
120
165
  for (const [typeName, description] of Object.entries(json.typeTable)) {
121
166
  const type = processType(description, typeName);
@@ -127,39 +172,32 @@ function jsonToAst(json) {
127
172
  const field = new ast_1.Field(argName, processType(func.args[argName]));
128
173
  const target = `fn.${functionName}.${argName}`;
129
174
  for (const annotationJson of (_a = json.annotations[target]) !== null && _a !== void 0 ? _a : []) {
130
- if (annotationJson.type === "description") {
131
- field.annotations.push(new ast_1.DescriptionAnnotation(annotationJson.value));
132
- }
175
+ field.annotations.push(annotationFromJson(annotationJson));
133
176
  }
134
177
  return field;
135
178
  });
136
179
  const op = new ast_1.FunctionOperation(functionName, args, processType(func.ret));
137
180
  const target = `fn.${functionName}`;
138
181
  for (const annotationJson of (_a = json.annotations[target]) !== null && _a !== void 0 ? _a : []) {
139
- if (annotationJson.type === "description") {
140
- op.annotations.push(new ast_1.DescriptionAnnotation(annotationJson.value));
141
- }
142
- else if (annotationJson.type === "throws") {
143
- op.annotations.push(new ast_1.ThrowsAnnotation(annotationJson.value));
144
- }
145
- else if (annotationJson.type === "rest" && typeof annotationJson.value === "object") {
146
- const { method, path, pathVariables, queryVariables, headers, bodyVariable } = annotationJson.value;
147
- op.annotations.push(new ast_1.RestAnnotation(method, path, pathVariables, queryVariables, new Map(headers), bodyVariable));
148
- }
149
- else if (annotationJson.type === "hidden") {
150
- op.annotations.push(new ast_1.HiddenAnnotation());
151
- }
182
+ op.annotations.push(annotationFromJson(annotationJson));
152
183
  }
153
184
  operations.push(op);
154
185
  }
186
+ for (const [enumValue, structName] of solveEnumValueStructRef) {
187
+ const struct = (_b = typeDefinition.find(def => def.name === structName)) === null || _b === void 0 ? void 0 : _b.type;
188
+ if (struct instanceof ast_1.StructType) {
189
+ enumValue.struct = struct;
190
+ }
191
+ }
155
192
  const errors = json.errors.map(error => {
156
193
  if (Array.isArray(error)) {
157
- return new ast_1.ErrorNode(error[0], processType(error[1]));
194
+ const [name, type] = error;
195
+ return new ast_1.ErrorNode(name, processType(type));
158
196
  }
159
197
  return new ast_1.ErrorNode(error, new ast_1.VoidPrimitiveType());
160
198
  });
161
199
  const ast = new ast_1.AstRoot(typeDefinition, operations, errors);
162
- analyser_1.analyse(ast);
200
+ (0, analyser_1.analyse)(ast);
163
201
  return ast;
164
202
  }
165
203
  exports.jsonToAst = jsonToAst;
package/dist/src/lexer.js CHANGED
@@ -230,14 +230,8 @@ class Lexer {
230
230
  case "import":
231
231
  token = new token_1.ImportKeywordToken();
232
232
  break;
233
- case "get":
234
- token = new token_1.GetKeywordToken();
235
- break;
236
- case "function":
237
- token = new token_1.FunctionKeywordToken("function");
238
- break;
239
233
  case "fn":
240
- token = new token_1.FunctionKeywordToken("fn");
234
+ token = new token_1.FnKeywordToken();
241
235
  break;
242
236
  case "true":
243
237
  token = new token_1.TrueKeywordToken();
@@ -92,10 +92,7 @@ class Parser {
92
92
  ErrorKeywordToken: () => {
93
93
  errors.push(this.parseError());
94
94
  },
95
- FunctionKeywordToken: () => {
96
- operations.push(this.parseOperation());
97
- },
98
- GetKeywordToken: () => {
95
+ FnKeywordToken: () => {
99
96
  operations.push(this.parseOperation());
100
97
  },
101
98
  ImportKeywordToken: () => {
@@ -113,7 +110,7 @@ class Parser {
113
110
  }
114
111
  const ast = new ast_1.AstRoot(typeDefinition, operations, errors);
115
112
  ast.warnings = this.warnings;
116
- analyser_1.analyse(ast);
113
+ (0, analyser_1.analyse)(ast);
117
114
  return ast;
118
115
  }
119
116
  acceptAnnotations() {
@@ -132,7 +129,7 @@ class Parser {
132
129
  break;
133
130
  case "rest":
134
131
  try {
135
- this.annotations.push(restparser_1.parseRestAnnotation(body).at(this.token));
132
+ this.annotations.push((0, restparser_1.parseRestAnnotation)(body).at(this.token));
136
133
  }
137
134
  catch (error) {
138
135
  throw new ParserError(`${error instanceof Error ? error.message : error} at ${this.token.location}`);
@@ -161,7 +158,7 @@ class Parser {
161
158
  const nameToken = this.expect(token_1.IdentifierToken);
162
159
  const name = nameToken.value;
163
160
  if (!/[A-Z]/u.test(name[0])) {
164
- throw new ParserError(`The custom type name must start with an uppercase letter, but found '${JSON.stringify(name)}' at ${nameToken.location}`);
161
+ throw new ParserError(`The custom type name must start with an uppercase letter, but found ${JSON.stringify(name)} at ${nameToken.location}`);
165
162
  }
166
163
  this.nextToken();
167
164
  const { annotations } = this;
@@ -178,7 +175,7 @@ class Parser {
178
175
  const nameToken = this.expect(token_1.IdentifierToken);
179
176
  const name = nameToken.value;
180
177
  if (!/[A-Z]/u.test(name[0])) {
181
- throw new ParserError(`Error name must start with an uppercase letter, but found '${JSON.stringify(name)}' at ${nameToken.location}`);
178
+ throw new ParserError(`Error name must start with an uppercase letter, but found ${JSON.stringify(name)} at ${nameToken.location}`);
182
179
  }
183
180
  this.nextToken();
184
181
  let type = new ast_1.VoidPrimitiveType();
@@ -193,37 +190,67 @@ class Parser {
193
190
  parseOperation() {
194
191
  let { annotations } = this;
195
192
  this.annotations = [];
196
- const openingToken = this.multiExpect({
197
- FunctionKeywordToken: token => token,
198
- GetKeywordToken: token => token,
199
- });
193
+ this.expect(token_1.FnKeywordToken);
200
194
  this.nextToken();
201
- if (["get", "function"].includes(openingToken.maybeAsIdentifier().value)) {
202
- this.warnings.push(`Keyword '${openingToken.maybeAsIdentifier().value}' is deprecated at ${openingToken.location}. Use 'fn' instead.`);
203
- }
204
195
  const name = this.expect(token_1.IdentifierToken).value;
205
196
  this.nextToken();
206
197
  this.expect(token_1.ParensOpenSymbolToken);
207
198
  this.nextToken();
208
199
  const argNames = new Set();
209
- const args = [];
210
- while (this.token && this.token.maybeAsIdentifier() instanceof token_1.IdentifierToken) {
211
- const field = this.parseField();
212
- if (argNames.has(field.name)) {
213
- throw new ParserError(`Cannot redeclare argument '${field.name}'`);
214
- }
215
- argNames.add(field.name);
216
- args.push(field);
217
- if (this.token instanceof token_1.CommaSymbolToken) {
218
- this.nextToken();
219
- }
220
- else {
221
- break;
222
- }
200
+ const fieldsAndSpreads = [];
201
+ let finished = false;
202
+ let parensCloseToken;
203
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
204
+ while (!finished) {
205
+ this.acceptAnnotations();
206
+ this.multiExpect({
207
+ ParensCloseSymbolToken: token => {
208
+ this.checkCannotHaveAnnotationsHere();
209
+ this.nextToken();
210
+ finished = true;
211
+ parensCloseToken = token;
212
+ },
213
+ IdentifierToken: () => {
214
+ const field = this.parseField();
215
+ if (argNames.has(field.name)) {
216
+ throw new ParserError(`Cannot redeclare argument '${field.name}'`);
217
+ }
218
+ argNames.add(field.name);
219
+ fieldsAndSpreads.push(field);
220
+ this.multiExpect({
221
+ ParensCloseSymbolToken: token => {
222
+ this.checkCannotHaveAnnotationsHere();
223
+ this.nextToken();
224
+ finished = true;
225
+ parensCloseToken = token;
226
+ },
227
+ CommaSymbolToken: () => this.nextToken(),
228
+ });
229
+ },
230
+ SpreadSymbolToken: () => {
231
+ this.checkCannotHaveAnnotationsHere();
232
+ this.nextToken();
233
+ const identToken = this.expect(token_1.IdentifierToken);
234
+ this.nextToken();
235
+ if (!/[A-Z]/u.test(identToken.value[0])) {
236
+ throw new ParserError(`Expected a type but found ${JSON.stringify(identToken.value)} at ${identToken.location}`);
237
+ }
238
+ fieldsAndSpreads.push(new ast_1.Spread(new ast_1.TypeReference(identToken.value).at(identToken)).at(identToken));
239
+ this.multiExpect({
240
+ ParensCloseSymbolToken: token => {
241
+ this.checkCannotHaveAnnotationsHere();
242
+ this.nextToken();
243
+ finished = true;
244
+ parensCloseToken = token;
245
+ },
246
+ CommaSymbolToken: () => this.nextToken(),
247
+ });
248
+ },
249
+ });
223
250
  }
224
251
  for (const annotation of annotations) {
225
252
  if (annotation instanceof ast_1.ArgDescriptionAnnotation) {
226
- const arg = args.find(x => x.name === annotation.argName);
253
+ const arg = fieldsAndSpreads.find(x => x instanceof ast_1.Field && x.name === annotation.argName);
227
254
  if (!arg) {
228
255
  throw new ParserError(`Argument '${annotation.argName}' not found, at ${annotation.location}`);
229
256
  }
@@ -231,14 +258,12 @@ class Parser {
231
258
  }
232
259
  }
233
260
  annotations = annotations.filter(ann => !(ann instanceof ast_1.ArgDescriptionAnnotation));
234
- const parensCloseToken = this.expect(token_1.ParensCloseSymbolToken);
235
- this.nextToken();
236
261
  let returnType = new ast_1.VoidPrimitiveType().at(parensCloseToken);
237
262
  if (this.token instanceof token_1.ColonSymbolToken) {
238
263
  this.nextToken();
239
264
  returnType = this.parseType();
240
265
  }
241
- const op = openingToken instanceof token_1.GetKeywordToken ? new ast_1.GetOperation(name, args, returnType) : new ast_1.FunctionOperation(name, args, returnType);
266
+ const op = new ast_1.FunctionOperation(name, fieldsAndSpreads, returnType);
242
267
  op.annotations = annotations;
243
268
  return op;
244
269
  }
@@ -265,6 +290,34 @@ class Parser {
265
290
  this.annotations = [];
266
291
  enumType.values.push(enumValue);
267
292
  this.nextToken();
293
+ if (!(this.token instanceof token_1.ParensOpenSymbolToken)) {
294
+ return;
295
+ }
296
+ this.nextToken();
297
+ const fieldNames = new Set();
298
+ const fields = [];
299
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
300
+ while (this.token && this.token.maybeAsIdentifier() instanceof token_1.IdentifierToken) {
301
+ const field = this.parseField();
302
+ // "tag" is a reserved name on tagged enum fields and can't be used.
303
+ if (field.name === "tag") {
304
+ field.name = "_tag";
305
+ }
306
+ if (fieldNames.has(field.name)) {
307
+ throw new ParserError(`Cannot redeclare argument '${field.name}'`);
308
+ }
309
+ fieldNames.add(field.name);
310
+ fields.push(field);
311
+ if (this.token instanceof token_1.CommaSymbolToken) {
312
+ this.nextToken();
313
+ }
314
+ else {
315
+ break;
316
+ }
317
+ }
318
+ enumValue.struct = new ast_1.StructType(fields).atLocation(enumValue.location);
319
+ this.expect(token_1.ParensCloseSymbolToken);
320
+ this.nextToken();
268
321
  },
269
322
  });
270
323
  }
@@ -296,8 +349,7 @@ class Parser {
296
349
  parseStruct() {
297
350
  const openingToken = this.expect(token_1.CurlyOpenSymbolToken);
298
351
  this.nextToken();
299
- const fields = [];
300
- const spreads = [];
352
+ const fieldsAndSpreads = [];
301
353
  const fieldNames = new Set();
302
354
  let finished = false;
303
355
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
@@ -315,7 +367,7 @@ class Parser {
315
367
  throw new ParserError(`Cannot redeclare field '${field.name}'`);
316
368
  }
317
369
  fieldNames.add(field.name);
318
- fields.push(field);
370
+ fieldsAndSpreads.push(field);
319
371
  },
320
372
  SpreadSymbolToken: () => {
321
373
  this.checkCannotHaveAnnotationsHere();
@@ -323,13 +375,13 @@ class Parser {
323
375
  const identToken = this.expect(token_1.IdentifierToken);
324
376
  this.nextToken();
325
377
  if (!/[A-Z]/u.test(identToken.value[0])) {
326
- throw new ParserError(`Expected a type but found '${JSON.stringify(identToken.value)}' at ${identToken.location}`);
378
+ throw new ParserError(`Expected a type but found ${JSON.stringify(identToken.value)} at ${identToken.location}`);
327
379
  }
328
- spreads.push(new ast_1.TypeReference(identToken.value).at(identToken));
380
+ fieldsAndSpreads.push(new ast_1.Spread(new ast_1.TypeReference(identToken.value).at(identToken)).at(identToken));
329
381
  },
330
382
  });
331
383
  }
332
- return new ast_1.StructType(fields, spreads).at(openingToken);
384
+ return new ast_1.StructType(fieldsAndSpreads).at(openingToken);
333
385
  }
334
386
  parseType() {
335
387
  this.checkCannotHaveAnnotationsHere();
@@ -339,7 +391,7 @@ class Parser {
339
391
  IdentifierToken: token => {
340
392
  this.nextToken();
341
393
  if (!/[A-Z]/u.test(token.value[0])) {
342
- throw new ParserError(`Expected a type but found '${JSON.stringify(token.value)}' at ${token.location}`);
394
+ throw new ParserError(`Expected a type but found ${JSON.stringify(token.value)} at ${token.location}`);
343
395
  }
344
396
  return new ast_1.TypeReference(token.value).at(token);
345
397
  },
@@ -18,7 +18,7 @@ class GiveStructAndEnumNamesVisitor extends visitor_1.Visitor {
18
18
  this.path = [`${node.name}Data`];
19
19
  super.visit(node);
20
20
  }
21
- else if (node instanceof ast_1.Operation) {
21
+ else if (node instanceof ast_1.FunctionOperation) {
22
22
  this.path = [node.name];
23
23
  super.visit(node);
24
24
  }
@@ -27,6 +27,11 @@ class GiveStructAndEnumNamesVisitor extends visitor_1.Visitor {
27
27
  super.visit(node);
28
28
  this.path.pop();
29
29
  }
30
+ else if (node instanceof ast_1.EnumValue) {
31
+ this.path.push(node.value);
32
+ super.visit(node);
33
+ this.path.pop();
34
+ }
30
35
  else if (node instanceof ast_1.StructType || node instanceof ast_1.EnumType) {
31
36
  node.name = this.path.map(s => s[0].toUpperCase() + s.slice(1)).join("");
32
37
  const previous = this.names.get(node.name);
@@ -3,5 +3,6 @@ import { Visitor } from "./visitor";
3
3
  export declare class CheckDontReturnSecretVisitor extends Visitor {
4
4
  isInReturn: boolean;
5
5
  path: string[];
6
+ visited: Set<AstNode>;
6
7
  visit(node: AstNode): void;
7
8
  }
@@ -8,10 +8,16 @@ class CheckDontReturnSecretVisitor extends visitor_1.Visitor {
8
8
  super(...arguments);
9
9
  this.isInReturn = false;
10
10
  this.path = [];
11
+ this.visited = new Set();
11
12
  }
12
13
  visit(node) {
13
- if (node instanceof ast_1.Operation) {
14
+ if (this.visited.has(node)) {
15
+ return;
16
+ }
17
+ this.visited.add(node);
18
+ if (node instanceof ast_1.FunctionOperation) {
14
19
  this.isInReturn = true;
20
+ this.visited.clear();
15
21
  this.path.push(`${node.name}(...)`);
16
22
  this.visit(node.returnType);
17
23
  this.path.pop();
@@ -0,0 +1,9 @@
1
+ import type { Spread } from "..";
2
+ import type { AstNode } from "../ast";
3
+ import { Field, StructType } from "../ast";
4
+ import { Visitor } from "./visitor";
5
+ export declare class ExpandSpreadsVisitor extends Visitor {
6
+ processed: Set<StructType>;
7
+ expandSpread(fields: Field[], fieldsAndSpreads: Array<Field | Spread>): void;
8
+ visit(node: AstNode): void;
9
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExpandSpreadsVisitor = void 0;
4
+ const ast_1 = require("../ast");
5
+ const visitor_1 = require("./visitor");
6
+ class ExpandSpreadsVisitor extends visitor_1.Visitor {
7
+ constructor() {
8
+ super(...arguments);
9
+ /*
10
+ * Here we may visit the same struct multiple times
11
+ * We must make sure we only process each one once
12
+ */
13
+ this.processed = new Set();
14
+ }
15
+ expandSpread(fields, fieldsAndSpreads) {
16
+ const fieldIndex = new Map();
17
+ for (const fieldOrSpread of fieldsAndSpreads) {
18
+ let fieldsToAdd;
19
+ if (fieldOrSpread instanceof ast_1.Field) {
20
+ fieldsToAdd = [fieldOrSpread];
21
+ }
22
+ else {
23
+ const struct = fieldOrSpread.typeReference.type;
24
+ if (!(struct instanceof ast_1.StructType)) {
25
+ throw new visitor_1.SemanticError(`A spread operator can't refer to something that is not a struct, in '${fieldOrSpread.typeReference.name}' at ${fieldOrSpread.location}.`);
26
+ }
27
+ this.visit(struct); // Recursion!
28
+ fieldsToAdd = struct.fields;
29
+ }
30
+ for (const field of fieldsToAdd) {
31
+ const index = fieldIndex.get(field.name);
32
+ if (index) {
33
+ fields[index] = field;
34
+ }
35
+ else {
36
+ fieldIndex.set(field.name, fields.length);
37
+ fields.push(field);
38
+ }
39
+ }
40
+ }
41
+ }
42
+ visit(node) {
43
+ if (node instanceof ast_1.StructType) {
44
+ if (this.processed.has(node)) {
45
+ return;
46
+ }
47
+ this.processed.add(node);
48
+ }
49
+ super.visit(node);
50
+ if (node instanceof ast_1.StructType) {
51
+ this.expandSpread(node.fields, node.fieldsAndSpreads);
52
+ node.fieldsAndSpreads = [];
53
+ }
54
+ else if (node instanceof ast_1.FunctionOperation) {
55
+ this.expandSpread(node.args, node.fieldsAndSpreads);
56
+ node.fieldsAndSpreads = [];
57
+ }
58
+ }
59
+ }
60
+ exports.ExpandSpreadsVisitor = ExpandSpreadsVisitor;