Skip to content

Commit 968da4e

Browse files
committed
Added support for union types in function parameters & function return types
1 parent 7de81ca commit 968da4e

12 files changed

+818
-467
lines changed

src/parser/expr.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,7 @@ module.exports = {
588588
nullable = true;
589589
this.next();
590590
}
591-
returnType = this.read_type();
591+
returnType = this.read_types();
592592
}
593593
if (this.expect(this.tok.T_DOUBLE_ARROW)) this.next();
594594
const body = this.read_expr();

src/parser/function.js

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ module.exports = {
128128
nullable = true;
129129
this.next();
130130
}
131-
returnType = this.read_type();
131+
returnType = this.read_types();
132132
}
133133
if (type === 1) {
134134
// closure
@@ -202,14 +202,14 @@ module.exports = {
202202
const node = this.node("parameter");
203203
let parameterName = null;
204204
let value = null;
205-
let type = null;
205+
let types = null;
206206
let nullable = false;
207207
if (this.token === "?") {
208208
this.next();
209209
nullable = true;
210210
}
211-
type = this.read_type();
212-
if (nullable && !type) {
211+
types = this.read_types();
212+
if (nullable && !types) {
213213
this.raiseError(
214214
"Expecting a type definition combined with nullable operator"
215215
);
@@ -225,7 +225,19 @@ module.exports = {
225225
if (this.token == "=") {
226226
value = this.next().read_expr();
227227
}
228-
return node(parameterName, type, value, isRef, isVariadic, nullable);
228+
return node(parameterName, types, value, isRef, isVariadic, nullable);
229+
},
230+
read_types() {
231+
const types = [];
232+
let type = this.read_type();
233+
if (!type) return null;
234+
types.push(type);
235+
while (this.token === "|") {
236+
this.next();
237+
type = this.read_type();
238+
types.push(type);
239+
}
240+
return types.length === 0 ? null : types;
229241
},
230242
/**
231243
* Reads a list of arguments

0 commit comments

Comments
 (0)