From 97d8c1ab638326f105e2d87e66f5785749460b59 Mon Sep 17 00:00:00 2001 From: Yuichi Nishiwaki Date: Tue, 23 Oct 2012 12:25:00 +0900 Subject: [PATCH] add nullable operator --- src/parser.js | 43 ++++++++++++++++++++------------- t/run/218.nullable-notation.jsx | 22 +++++++++++++++++ 2 files changed, 48 insertions(+), 17 deletions(-) create mode 100644 t/run/218.nullable-notation.jsx diff --git a/src/parser.js b/src/parser.js index 41af9727..078d2586 100644 --- a/src/parser.js +++ b/src/parser.js @@ -1566,15 +1566,24 @@ var Parser = exports.Parser = Class.extend({ var typeDecl = this._typeDeclarationNoArrayNoVoid(); if (typeDecl == null) return null; - // [] - while (this._expectOpt("[") != null) { - if ((token = this._expect("]")) == null) - return false; - if (typeDecl instanceof NullableType) { - this._newError("Nullable. cannot be an array, should be: T[]"); - return null; + while (true) { + // ? + if (this._expectOpt("?") != null) { + if ((typeDecl = this._toNullableType(typeDecl)) == null) + return null; + } + // [] + else if (this._expectOpt("[") != null) { + if ((token = this._expect("]")) == null) + return false; + if (typeDecl instanceof NullableType) { + this._newError("Nullable. cannot be an array, should be: T[]"); + return null; + } + typeDecl = this._registerArrayTypeOf(token, typeDecl); } - typeDecl = this._registerArrayTypeOf(token, typeDecl); + else + break; } return typeDecl; }, @@ -1589,7 +1598,14 @@ var Parser = exports.Parser = Class.extend({ this._newDeprecatedWarning("use of 'MayBeUndefined' is deprecated, use 'Nullable' instead"); // falls through case "Nullable": - return this._nullableTypeDeclaration(); + if (this._expect(".") == null || this._expect("<") == null) + return null; + var baseType = this._typeDeclaration(false); + if (baseType == null) + return null; + if (this._expect(">") == null) + return null; + return this._toNullableType(baseType); case "variant": return Type.variantType; default: @@ -1597,14 +1613,7 @@ var Parser = exports.Parser = Class.extend({ } }, - _nullableTypeDeclaration: function () { - if (this._expect(".") == null || this._expect("<") == null) - return null; - var baseType = this._typeDeclaration(false); - if (baseType == null) - return null; - if (this._expect(">") == null) - return null; + _toNullableType: function (baseType) { if (baseType.equals(Type.variantType)) { this._newError("variant cannot be declared as nullable (since it is always nullable)"); return null; diff --git a/t/run/218.nullable-notation.jsx b/t/run/218.nullable-notation.jsx new file mode 100644 index 00000000..eaf8d384 --- /dev/null +++ b/t/run/218.nullable-notation.jsx @@ -0,0 +1,22 @@ +/*EXPECTED +123 +*/ + +class Klass { + + var str : string?; + + function constructor(num : number?) { + if (num == null) { + this.str = null; + } else { + this.str = num as string; + } + } +} + +class _Main { + static function main(args : string[]) : void { + log (new Klass(123)).str; + } +}