Wiki

Ticket #230: assign-empty-type-lits.patch

File assign-empty-type-lits.patch, 39.7 KB (added by hopscc, 14 years ago)
  • Source/Expr.cobra

     
    27612761class CompositeLiteral 
    27622762    inherits Literal 
    27632763 
     2764    var _typeInferred = false 
     2765 
    27642766    cue init(token as IToken) 
    27652767        base.init(token) 
    27662768 
     2769    get isTentativelyTyped as bool 
     2770        return false 
    27672771 
    27682772class SequenceLit 
    27692773    is abstract, partial 
    27702774    inherits CompositeLiteral 
    27712775 
    27722776    var _exprs as List<of Expr> 
    2773  
     2777    var _typeNode as ITypeProxy? 
     2778     
    27742779    cue init(token as IToken, exprs as List<of Expr>) 
    27752780        base.init(token) 
    27762781        _exprs = exprs 
     
    27892794    get willChangeVar as bool is override 
    27902795        for expr in _exprs, if expr.willChangeVar, return true 
    27912796        return false 
    2792  
     2797         
     2798    get isTentativelyTyped as bool is override 
     2799        # empty sequence and type not explicitly set 
     2800        assert .didBindImp 
     2801        return _exprs.count == 0 and _typeInferred == true 
     2802     
    27932803    def _bindImp is override 
    27942804        base._bindImp 
    27952805        exceptions = List<of NodeException>() 
     
    28002810                exceptions.add(ne) 
    28012811        if exceptions.count 
    28022812            throw NodeMultiException(exceptions) 
     2813        if _typeNode    # optional explicit type 
     2814            _type = _convertTypeNode #_typeNode.realType 
     2815            assert _type, _typeNode 
     2816        seqType = _genExprsType 
    28032817        if _type is nil 
    2804             exprs = _exprs 
    2805             if exprs.count == 0 
    2806                 type = .compiler.defaultType 
    2807             else 
    2808                 type = exprs[0].type to ! 
    2809                 for i in 1 : exprs.count 
    2810                     exprs[i].bindImp 
    2811                     type = exprs[i].type.greatestCommonDenominatorWith(type) 
     2818            _type = seqType 
     2819            _typeInferred = true 
     2820        else if _exprs.count > 0   # type set from [...] as List<of TYPE> 
     2821            if not seqType.isAssignableTo(_type to !) 
     2822                .throwError('The common type of the sequence of expressions is [seqType.name] which is not assignable to the explicitly declared type [_type.name].') 
     2823                 
     2824    def _genExprsType as IType           
     2825        exprs = _exprs 
     2826        if exprs.count == 0 
     2827            type = .compiler.defaultType 
     2828        else 
     2829            type = exprs[0].type to ! 
     2830            for i in 1 : exprs.count 
     2831                #exprs[i].bindImp   # is this necessary - done earlier in bindImp? 
     2832                assert exprs[i].didBindImp 
     2833                type = exprs[i].type.greatestCommonDenominatorWith(type) 
    28122834                if type.isSystemObjectClass  # make dynamic if heterogenous and all non Object 
    28132835                    allObj = all for expr in exprs get expr.type.isSystemObjectClass 
    28142836                    if not allObj, type = .compiler.dynamicType  
    2815             if type inherits NilType, type = .compiler.defaultType 
    2816             _type = _makeTypeWith(type) 
    2817  
     2837        if type inherits NilType, type = .compiler.defaultType 
     2838        type = _makeTypeWith(type) 
     2839        return type  
     2840     
     2841    def _convertTypeNode as IType 
     2842        return _typeNode.realType    
     2843             
    28182844    def _makeTypeWith(type as IType) as IType is abstract 
    28192845 
    28202846    get brackets as List<of String> is abstract 
     
    28342860class ListLit 
    28352861    is partial 
    28362862    inherits SequenceLit 
    2837  
     2863     
    28382864    # CC: should just inherit this because no initializers are defined 
    28392865    cue init(token as IToken, exprs as List<of Expr>) 
    28402866        base.init(token, exprs) 
    28412867 
     2868    cue init(token as IToken, exprs as List<of Expr>, typeNode as ITypeProxy?) 
     2869        base.init(token, exprs) 
     2870        _typeNode = typeNode 
     2871     
     2872    def _convertTypeNode as IType is override 
     2873        type = _typeNode.realType    
     2874        if not type.isGenericListLike 
     2875            sugg = ' Perhaps you meant "IList or List<of [type.name]>".' 
     2876            .throwError('An explicit list literal type must be of form "List<of someType>" not "[type.name]".[sugg]') 
     2877        return type 
     2878         
    28422879    def _makeTypeWith(type as IType) as IType is override 
    28432880        return .compiler.listOfType.constructedTypeFor([type]) 
    28442881 
    28452882    get brackets as List<of String> is override 
    28462883        return [r'[', ']'] 
     2884         
    28472885 
    2848  
    28492886class ArrayLit inherits SequenceLit is partial 
    28502887 
    28512888    # CC: should just inherit this because no initializers are defined 
    28522889    cue init(token as IToken, exprs as List<of Expr>) 
    28532890        base.init(token, exprs) 
    28542891 
     2892    cue init(token as IToken, exprs as List<of Expr>, typeNode as ITypeProxy?) 
     2893        base.init(token, exprs) 
     2894        _typeNode = typeNode 
     2895         
     2896    def _convertTypeNode as IType is override 
     2897        if not _typeNode inherits ArrayTypeIdentifier 
     2898            name = (_typeNode to AbstractTypeIdentifier).name 
     2899            sugg = ' Perhaps you meant "[name]\[]".' 
     2900            .throwError('An explicitly declared array type must be of form "someType\[]" not "[name]".[sugg]') 
     2901        return _typeNode.realType    
     2902         
    28552903    def _makeTypeWith(type as IType) as IType is override 
    28562904        return .typeProvider.arrayType(type) 
    28572905 
     
    28762924    cue init(token as IToken, exprs as List<of Expr>) 
    28772925        base.init(token, exprs) 
    28782926 
     2927    cue init(token as IToken, exprs as List<of Expr>, typeNode as ITypeProxy?) 
     2928        base.init(token, exprs) 
     2929        _typeNode = typeNode 
     2930         
     2931    def _convertTypeNode as IType is override 
     2932        type = _typeNode.realType    
     2933        if not type.isSetLike 
     2934            sugg = ' Perhaps you meant "Set<of [type.name]>".' 
     2935            .throwError('An explicit set literal type must be of form "Set<of someType>" not "[type.name]".[sugg]') 
     2936        return type 
     2937 
    28792938    def _makeTypeWith(type as IType) as IType is override 
    28802939        return .compiler.setOfType.constructedTypeFor([type]) 
    28812940 
     
    29002959class DictLit inherits CompositeLiteral is partial 
    29012960 
    29022961    var _entries as List<of List<of Expr>> 
     2962    var _typeNode as ITypeProxy? 
    29032963 
    29042964    cue init(token as IToken, entries as List<of List<of Expr>>) 
    29052965        base.init(token) 
     
    29082968                assert entry.count == 2 
    29092969        _entries = entries 
    29102970 
     2971    cue init(token as IToken, entries as List<of List<of Expr>>, typeNode as ITypeProxy?) 
     2972        .init(token, entries) 
     2973        _typeNode = typeNode 
     2974         
    29112975    def addSubFields is override 
    29122976        base.addSubFields 
    29132977        .addField('entries', _entries) 
     
    29242988        return false 
    29252989 
    29262990    get entries from var 
     2991     
     2992    get isTentativelyTyped as bool is override 
     2993        # empty DictLit and type not explicitly set 
     2994        assert .didBindImp 
     2995        return _entries.count == 0 and _typeInferred == true 
    29272996 
    29282997    def replaceChild(find as INode, replace as INode) as bool 
    29292998        didReplace = base.replaceChild(find, replace) 
     
    29533022                hadError = true 
    29543023        if hadError 
    29553024            return 
     3025        if _typeNode    # optional explicit type 
     3026            type = _typeNode.realType 
     3027            if not type.isDictionaryLike 
     3028                .throwError('An explicit dict literal type must be of form "Dictionary<of keyType,valueType>" not "[type.name]".') 
     3029            _type = type 
     3030        entType = _genEntriesType 
    29563031        if .type is nil 
    2957             entries = _entries 
    2958             if _entries.count == 0 
    2959                 keyType = valueType = .compiler.defaultType 
    2960             else 
    2961                 keyType   = entries[0][0].type to ! 
    2962                 valueType = entries[0][1].type to ! 
    2963                 i = 1 
    2964                 keysAllSysObject = valuesAllSysObject = true 
    2965                 while i < entries.count 
    2966                     keyType   = entries[i][0].type.greatestCommonDenominatorWith(keyType) 
    2967                     if not entries[i][0].type.isSystemObjectClass, keysAllSysObject = false 
    2968                     valueType = entries[i][1].type.greatestCommonDenominatorWith(valueType) 
    2969                     if not entries[i][1].type.isSystemObjectClass, valuesAllSysObject = false  
    2970                     i += 1 
    2971                 # make types dynamic if heterogenous and all non Object 
    2972                 if keyType.isSystemObjectClass and not keysAllSysObject 
    2973                     keyType = .compiler.dynamicType  
    2974                 if valueType.isSystemObjectClass and not valuesAllSysObject 
    2975                     valueType = .compiler.dynamicType  
    2976             if keyType inherits NilType, keyType = .compiler.defaultType 
    2977             if valueType inherits NilType, valueType = .compiler.defaultType 
    2978             _type = .compiler.dictionaryOfType.constructedTypeFor([keyType, valueType]) 
     3032            _type = entType 
     3033            _typeInferred = true 
     3034        else if _entries.count > 0   # type set from {...} as Dictionary<of TYPE,TYPE> 
     3035            if not entType.isAssignableTo(_type to !) 
     3036                .throwError('The common type of the dictionary literal expressions is [entType.name] which is not assignable to the explicitly declared type [_type.name].') 
     3037         
     3038    def _genEntriesType as IType         
     3039        entries = _entries 
     3040        if _entries.count == 0 
     3041            keyType = valueType = .compiler.defaultType 
     3042        else 
     3043            keyType   = entries[0][0].type to ! 
     3044            valueType = entries[0][1].type to ! 
     3045            i = 1 
     3046            keysAllSysObject = valuesAllSysObject = true 
     3047            while i < entries.count 
     3048                keyType   = entries[i][0].type.greatestCommonDenominatorWith(keyType) 
     3049                if not entries[i][0].type.isSystemObjectClass, keysAllSysObject = false 
     3050                valueType = entries[i][1].type.greatestCommonDenominatorWith(valueType) 
     3051                if not entries[i][1].type.isSystemObjectClass, valuesAllSysObject = false  
     3052                i += 1 
     3053            # make types dynamic if heterogenous and all non Object 
     3054            if keyType.isSystemObjectClass and not keysAllSysObject 
     3055                keyType = .compiler.dynamicType  
     3056            if valueType.isSystemObjectClass and not valuesAllSysObject 
     3057                valueType = .compiler.dynamicType  
     3058        if keyType inherits NilType, keyType = .compiler.defaultType 
     3059        if valueType inherits NilType, valueType = .compiler.defaultType 
     3060        entType = .compiler.dictionaryOfType.constructedTypeFor([keyType, valueType]) 
     3061        return entType 
    29793062 
    2980  
    29813063class ToNilableOrNotExpr 
    29823064    is abstract, partial 
    29833065    inherits Expr 
  • Source/Types.cobra

     
    18691869            return true 
    18701870        return false 
    18711871 
     1872    def isGenericListLike as bool 
     1873        """ 
     1874        Returns true if the receiver is like a generic List, such as being an actual generic List type or a nilable version thereof. 
     1875        The dynamic type will also return true because at compile-time, dynamic is considered to be like everything. 
     1876        Requires Node.getCompiler 
     1877        """ 
     1878        type = this 
     1879        if type inherits NilableType 
     1880            return type.nonNil.isGenericListLike 
     1881        tp = Node.getCompiler  # 'tp' for 'type provider'  
     1882        genericList = tp.listOfType 
     1883        if type.isDescendantOf(genericList) 
     1884            return true 
     1885        if type inherits Box 
     1886            if type.genericDef is genericList 
     1887                return true 
     1888        genericIList = tp.ilistOfType 
     1889        if type.isDescendantOf(genericIList) 
     1890            return true 
     1891        if type inherits Box 
     1892            if type.genericDef is genericIList 
     1893                return true 
     1894        if type.isDynamic 
     1895            return true 
     1896        return false 
     1897     
     1898    def isSetLike as bool 
     1899        """ 
     1900        Returns true if the receiver is like a Set, such as being an actual Set type or a nilable version thereof. 
     1901        The dynamic type will also return true because at compile-time, dynamic is considered to be like everything. 
     1902        Requires Node.getCompiler 
     1903        """ 
     1904        type = this 
     1905        if type inherits NilableType 
     1906            return type.nonNil.isSetLike 
     1907        tp = Node.getCompiler  # 'tp' for 'type provider'  
     1908        genericSet = tp.setOfType 
     1909        if type.isDescendantOf(genericSet) 
     1910            return true 
     1911        if type inherits Box 
     1912            if type.genericDef is genericSet 
     1913                return true 
     1914        # probably should also check/test for ISet as well, provide accessor in Compiler         
     1915        if type.isDynamic 
     1916            return true 
     1917        return false 
     1918         
    18721919    def isDictionaryLike as bool 
    18731920        """ 
    18741921        Returns true if the receiver is like a dictionary, such as being an actual dictionary type or a nilable version thereof. 
  • Source/CobraTokenizer.cobra

     
    881881                on 'skip', pass 
    882882                on 'warning', pass 
    883883                on 'warning-lax', pass 
    884                 else, .throwError('Unrecognized compiler directive "[name]".') 
     884                else, .throwError('Unrecognized compiler directive "[name]". Known directives: "no-warnings" "args"') 
    885885            return true 
    886886        return false 
    887887 
  • Source/BinaryOpExpr.cobra

     
    222222            left = _left 
    223223            if left inherits IdentifierExpr 
    224224                if left.definition is nil 
    225                     definition = LocalVar(left.token, .compiler.passThroughType).bindAll to LocalVar  # CC: axe cast when supporting 'as this' 
    226                     .compiler.codeMemberStack.peek.addLocal(definition) 
    227                     left.setDefinition(definition) 
    228                     left.type = definition.type 
     225                    _inferVariableType(left, .compiler.passThroughType) 
    229226            if _type is nil 
    230227                _type = .compiler.passThroughType 
    231228            throw 
     
    242239                    if right.hasError 
    243240                        # for a type inference situation, create a var of type passthrough for the left hand side 
    244241                        # to prevent superfluous errors in subsequent statements 
    245                         definition = LocalVar(left.token, .compiler.passThroughType).bindAll to LocalVar  # CC: axe cast when supporting 'as this' 
    246                         .compiler.codeMemberStack.peek.addLocal(definition) 
    247                         left.setDefinition(definition) 
    248                         left.type = definition.type 
     242                        _inferVariableType(left, .compiler.passThroughType) 
    249243                        _type = left.type 
    250244                        return 
    251245                    else 
     
    253247                if left.name.startsWith('_') 
    254248                    .throwError('No class variable named "[left.name]" exists and local variable declarations cannot start with an underscore (_).') 
    255249                inferredType = if(right.type inherits NilType, .compiler.nilableDynamicType, right.type)  # `x = nil` for a new local var `x` is inferred as `dynamic?` 
    256                 definition = LocalVar(left.token, inferredType).bindAll to LocalVar  # CC: axe cast when supporting 'as this' 
    257                 .compiler.codeMemberStack.peek.addLocal(definition) 
    258                 left.setDefinition(definition) 
    259                 left.type = definition.type 
     250                _inferVariableType(left, inferredType to !) 
    260251            if left.definition is nil 
    261252                left.throwUnknownIdError 
    262253        if not right.canBeAssignedTo(left.type to !) 
     
    268259                        okay = true 
    269260            if not okay 
    270261                .throwError('Incompatible types. Cannot assign value of type [right.type.name] on the right to [left.type.name] on the left.') 
     262                 
     263        # Retype the emptyLit expression to allow  
     264        #   var as TYPE? ... var = emptyLit   and 
     265        #   var as TYPE = emptyLit 
     266        # emptyLit is one of [], @[], {}, {:}, {,} 
     267        if left inherits IdentifierExpr or left inherits AsExpr 
     268            if right inherits CompositeLiteral 
     269                if right.isTentativelyTyped  
     270                    right.type = left.type.nonNil 
     271                 
    271272        _type = left.type 
    272273        right.contextType = _type 
    273274 
     275    # define a local var of the name of the Identifier Expr with the given type 
     276    def _inferVariableType(left as IdentifierExpr, type as IType) 
     277        definition = LocalVar(left.token, type).bindAll to LocalVar  # CC: axe cast when supporting 'as this' 
     278        .compiler.codeMemberStack.peek.addLocal(definition) 
     279        left.setDefinition(definition) 
     280        left.type = definition.type 
     281 
    274282    def checkAfterBindImp 
    275283        base.checkAfterBindImp 
    276284        if not .hasError and _left.definition inherits Param 
  • Source/CobraParser.cobra

     
    32113211    def literalList as ListLit 
    32123212        token = .expect('LBRACKET') 
    32133213        exprs = .commaSepExprs('RBRACKET.', true) 
    3214         return ListLit(token, exprs) 
     3214        if .peek.which=='AS'  # [] as List<of TYPE> 
     3215            .grab 
     3216            listType = .typeId 
     3217        return  ListLit(token, exprs, listType) 
    32153218 
    32163219    def literalArray as ArrayLit 
    32173220        token = .expect('ARRAY_OPEN') 
    32183221        exprs = .commaSepExprs('RBRACKET.', true) 
    3219         return ArrayLit(token, exprs) 
     3222        if .peek.which=='AS'  # @[] as TYPE[] 
     3223            .grab 
     3224            type = .typeId 
     3225        return ArrayLit(token, exprs, type) 
    32203226 
    32213227    def literalDictOrSet as CompositeLiteral 
    32223228        token = .expect('LCURLY') 
     
    32303236            on 'RCURLY' 
    32313237                .grab 
    32323238                _warning('Assuming empty dictionary, but please use "{:}" for empty dictionary or "{,}" for empty set') 
    3233                 return DictLit(token, List<of List<of Expr>>()) 
     3239                if .optional('AS')  # {:} as Dictionary<of TYPE,TYPE> 
     3240                    type = .typeId 
     3241                return DictLit(token, List<of List<of Expr>>(), type) 
    32343242        expr = .expression 
    32353243        _spaceAgnostic 
    32363244        branch .peek.which 
     
    32613269                _spaceAgnostic 
    32623270                if .optional('RCURLY') 
    32633271                    break 
    3264             return SetLit(token, exprs) 
    32653272        else 
    32663273            .expect('COMMA') 
    32673274            _spaceAgnostic 
    32683275            .expect('RCURLY') 
    3269             return SetLit(token, List<of Expr>()) 
     3276            exprs = List<of Expr>() 
    32703277 
     3278        if .optional('AS')  # {,} as Set<of TYPE> 
     3279            type = .typeId 
     3280        return SetLit(token, exprs, type) 
     3281 
    32713282    def _literalDict(token as IToken, expr as Expr?) as DictLit 
     3283        entries = List<of List<of Expr>>() 
    32723284        if expr 
    32733285            expectComma = false 
    3274             entries = List<of List<of Expr>>() 
    32753286            first = true 
    32763287            while true 
    32773288                if first 
     
    32963307                value = .expression 
    32973308                entries.add([key, value]) 
    32983309                expectComma = true 
    3299             return DictLit(token, entries) 
     3310            #return DictLit(token, entries) 
    33003311        else 
    33013312            .expect('COLON') 
    33023313            _spaceAgnostic 
    33033314            .expect('RCURLY') 
    3304             return DictLit(token, List<of List<of Expr>>()) 
     3315 
     3316        if .peek.which=='AS'  # {:} as Dictionary<of TYPE,TYPE> 
     3317            .grab 
     3318            type = .typeId 
     3319        return DictLit(token, entries, type) 
    33053320         
    33063321    def nameExpr as NameExpr 
    33073322        nameToken = .expect('ID') 
  • Tests/820-errors/400-declarations/600-typed-literals/102-list-literal-error-assign1.cobra

     
     1# List literal explicit typing mismatch declared type and later assignment 
     2class ListLitAs 
     3    def main is shared 
     4        l = [] as List<of MyClass> 
     5        l = ['hi'] # .error. Incompatible types. Cannot assign 
     6        CobraCore.noOp(l) 
     7         
     8class MyClass 
     9    pass 
  • Tests/820-errors/400-declarations/600-typed-literals/200-array-literal-typed-error-type.cobra

     
     1# tests for explicit typing of Array literals 
     2class ListLitAs 
     3    def main is shared 
     4        cerr = @[] as String # .error. array type must be of form "someType[]" 
     5        CobraCore.noOp(cerr) 
  • Tests/820-errors/400-declarations/600-typed-literals/203-array-literal-typed-assign1.cobra

     
     1# tests for explicit typing of Array literals 
     2class ListLitAs 
     3    def main is shared 
     4        l = @[] as MyClass[] 
     5        l = @['hi'] # .error. Incompatible types. Cannot assign value of type String[] on the right to MyClass[] on the left 
     6        CobraCore.noOp(l) 
     7         
     8class MyClass 
     9    pass 
     10 
  • Tests/820-errors/400-declarations/600-typed-literals/101-list-literal-error-assignable.cobra

     
     1# List literal explicit typing mismatch expression types and declared type 
     2class ListLitAs 
     3    def main is shared 
     4        d = [1,2,3] as List<of String> # .error. List<of int> which is not assignable to the explicitly declared type List<of String> 
     5        CobraCore.noOp(d) 
  • Tests/820-errors/400-declarations/600-typed-literals/304-set-literal-typed-error-assign2.cobra

     
     1# tests for explicit typing of Set literals 
     2class SetLitAs 
     3    def main is shared 
     4        l = {'hi',} as Set<of MyClass> # .error. The common type of the sequence of expressions is Set<of String> which is not assignable to the explicitly declared type Set<of MyClass> 
     5        CobraCore.noOp(l) 
     6         
     7class MyClass 
     8    pass 
     9 
  • Tests/820-errors/400-declarations/600-typed-literals/400-dict-literal-typed-error-type.cobra

     
     1# tests for explicit typing of Dict literals 
     2class DictLitAs 
     3    def main is shared 
     4        d = {:} as String # .error. dict literal type must be of form "Dictionary<of keyType,valueType>" 
     5        CobraCore.noOp(d) 
     6 
  • Tests/820-errors/400-declarations/600-typed-literals/204-array-literal-types-error-assign2.cobra

     
     1# tests for explicit typing of Array literals expr list type mismatch to declared User type 
     2class ListLitAs 
     3    def main is shared 
     4        l = @['hi'] as MyClass[] # .error. String[] which is not assignable to the explicitly declared type MyClass[] 
     5        CobraCore.noOp(l) 
     6         
     7class MyClass 
     8    pass 
     9 
  • Tests/820-errors/400-declarations/600-typed-literals/100-list-literal-error-type.cobra

     
     1# List literal explicit typing unreasonable declared type 
     2class ListLitAs 
     3    def main is shared 
     4        cerr = [] as String # .error.  An explicit list literal type must be of form "List<of someType>" not "String" 
     5        CobraCore.noOp(cerr) 
  • Tests/820-errors/400-declarations/600-typed-literals/402-dict-literal-typed-error-assign.cobra

     
     1# tests for explicit typing of Dict literals 
     2class DictLitAs 
     3    def main is shared 
     4        d = {1:1, 2:1, 3:1} as Dictionary<of int,String> # .error. not assignable  
     5        CobraCore.noOp(d) 
     6 
  • Tests/820-errors/400-declarations/600-typed-literals/403-dict-literal-typed-error-assign.cobra

     
     1# tests for explicit typing of Dict literals 
     2class DictLitAs 
     3    def main is shared 
     4        d = {:} as Dictionary<of int, MyClass> 
     5        d = { 'hi':MyClass() }  #.error. Incompatible types. Cannot assign value of type Dictionary<of String,MyClass> on the right to Dictionary<of int,MyClass> on the left 
     6        CobraCore.noOp(d) 
     7         
     8class MyClass 
     9    pass 
  • Tests/820-errors/400-declarations/600-typed-literals/404-dict-literal-typed-error-assign.cobra

     
     1# tests for explicit typing of Dict literals 
     2class DictLitAs 
     3    def main is shared 
     4        d = {'hi':10} as Dictionary<of int,MyClass> #.error. Dictionary<of String,int> which is not assignable to the explicitly declared type Dictionary<of int,MyClass>. 
     5        CobraCore.noOp(d) 
     6        #l1 = {'hi':10} as Dictionary<of String,MyClass> 
     7         
     8class MyClass 
     9    pass 
  • Tests/820-errors/400-declarations/600-typed-literals/300-set-literal-typed-error-type.cobra

     
     1# tests for explicit typing of Set literals 
     2class SetLitAs 
     3    def main is shared 
     4        c = {,} as String # .error. set literal type must be of form "Set<of someType>" 
     5        CobraCore.noOp(c) 
     6 
  • Tests/820-errors/400-declarations/600-typed-literals/405-dict-literal-typed-error-assign.cobra

     
     1# tests for explicit typing of Dict literals 
     2class DictLitAs 
     3    def main is shared 
     4        d = {'hi':10} as Dictionary<of String,MyClass> # .error. The common type of the dictionary literal expressions is Dictionary<of String,int> which is not assignable to the explicitly declared type Dictionary<of String,MyClass> 
     5        CobraCore.noOp(d) 
     6         
     7class MyClass 
     8    pass 
  • Tests/820-errors/400-declarations/600-typed-literals/103-list-literal-error-assign.cobra

     
     1# List literal explicit typing mismatch expression and declared User type  
     2class ListLitAs 
     3    def main is shared 
     4        l = ['hi'] as List<of MyClass> #.error. not assignable 
     5        CobraCore.noOp(l) 
     6         
     7class MyClass 
     8    pass 
  • Tests/820-errors/400-declarations/600-typed-literals/301-set-literal-typed-assignable.cobra

     
     1# tests for explicit typing of Set literals 
     2class SetLitAs 
     3    def main is shared 
     4        d = {1,2,3} as Set<of String> # .error. not assignable 
     5        CobraCore.noOp(d) 
  • Tests/820-errors/400-declarations/600-typed-literals/303-set-literal-types-error-assign1.cobra

     
     1# tests for explicit typing of Set literals 
     2class SetLitAs 
     3    def main is shared 
     4        l = {,} as Set<of MyClass> 
     5        l = {'hi'}  # .error. Cannot assign value of type Set<of String> on the right to Set<of MyClass> on the left 
     6        CobraCore.noOp(l) 
     7         
     8class MyClass 
     9    pass 
  • Tests/820-errors/400-declarations/600-typed-literals/201-array-literal-typed-error-assignable.cobra

     
     1# tests for explicit typing of Array literals 
     2class ListLitAs 
     3    def main is shared 
     4        d = @[1,2,3] as String[] # .error. not assignable to the explicitly declared type 
     5        CobraCore.noOp(d) 
  • Tests/820-errors/400-declarations/600-typed-literals/401-dict-literal-typed-error-type1.cobra

     
     1# tests for explicit typing of Dict literals 
     2class DictLitAs 
     3    def main is shared 
     4        d = {:} as List<of int> # .error. dict literal type must be of form "Dictionary<of keyType,valueType>" 
     5        CobraCore.noOp(d) 
  • Tests/700-command-line/900-check-complier-message-format/200-check-compiler-message-format.cobra

     
    1919        .check('120-bind-error.cobra') 
    2020 
    2121    def check(sourceName as String) 
    22         re = Regex(r"[A-Za-z\.]+cobra\(\d+\): (error|warning): [^\(]+$", RegexOptions(Compiled, CultureInvariant)) 
     22        re = Regex(r"[A-Za-z\.]+cobra\(\d+(,\d+)?\): (error|warning): [^\(]+$", RegexOptions(Compiled, CultureInvariant)) 
    2323        # example output for regex ta match: 
    2424        # bind-error.cobra(4): error: Cannot find "y". There is a member named ".getType" with a similar name. 
    2525 
  • Tests/300-type-inference/900-literals/600-explicitly-typed/200-array-literal-typed.cobra

     
     1# tests for explicit typing of Array literals 
     2class ListLitAs 
     3    def main is shared 
     4        # below array typenames specific to .Net family 
     5        elObject = r'System.Object[]' 
     6        elString = r'System.String[]' 
     7        elInt    = r'System.Int32[]' 
     8        elMyClass= r'MyClass[]' 
     9         
     10        a = @[] 
     11        #print a.typeOf 
     12        assert elObject in a.typeOf.toString 
     13        assert a.length ==0 
     14         
     15        b = @[] as int[] 
     16        #print b.typeOf 
     17        assert elInt in b.typeOf.toString 
     18        assert b.length ==0 
     19        b = @[3,4] 
     20        assert b == @[3,4] 
     21         
     22        c = @[] as String[] 
     23        assert elString in c.typeOf.toString 
     24        c = @['My'] 
     25        assert c == @['My'] 
     26        c = @['a', 'b'] 
     27        assert c == @['a', 'b'] 
     28         
     29        l = @[] as MyClass[] 
     30        assert elMyClass in l.typeOf.toString 
     31        l = @[MyClass(), MyClass()] 
     32        assert l.length == 2 
     33     
     34        lf = @[FunkClass()] as MyClass[] 
     35        assert elMyClass in lf.typeOf.toString 
     36        assert lf.length == 1 
     37        assert 'FunkClass' in lf[0].typeOf.toString 
     38     
     39class MyClass 
     40    pass 
     41 
     42class FunkClass inherits MyClass 
     43    def wotAmI 
     44        print "I'm a funkyClass" 
     45 
  • Tests/300-type-inference/900-literals/600-explicitly-typed/400-dict-literal-typed.cobra

     
     1# tests for explicit typing of Dict literals 
     2class DictLitAs 
     3    def main is shared 
     4        # below element typenames specific to .Net family 
     5        elObject = r'[System.Object,System.Object]' 
     6        elString = r'[System.String,System.Int32]' 
     7        elInt    = r'[System.Int32,System.String]' 
     8        elMyClass= r'[System.String,MyClass]' 
     9         
     10        a = {:} 
     11        #print a.typeOf 
     12        assert elObject in a.typeOf.toString 
     13        assert a.count ==0 
     14         
     15        b0 = {} as Dictionary<of int,String> #.warning. Assuming empty dictionary 
     16        #print b0.typeOf 
     17        assert elInt in b0.typeOf.toString 
     18        assert b0.count ==0 
     19        b0 = {3:'x0',4:'y0'} 
     20        assert b0.count == 2 
     21        assert b0[3] == 'x0' and b0[4] == 'y0' 
     22         
     23        b = {:} as Dictionary<of int,String> 
     24        #print b.typeOf 
     25        assert elInt in b.typeOf.toString 
     26        assert b.count ==0 
     27        b = {3:'x',4:'y'} 
     28        assert b.count == 2 
     29        assert b[3] == 'x' and b[4] == 'y' 
     30 
     31        c = {:} as Dictionary<of String, int> 
     32        assert elString in c.typeOf.toString 
     33        c['My'] = 1 
     34        assert c.count ==1 
     35        assert c['My'] == 1 
     36        c = {'a':1, 'b':2} 
     37        assert c.count == 2 
     38        assert c['a'] == 1 and c['b'] == 2 
     39         
     40        c1 = {'aa':1, 'bb':2} as Dictionary<of String, int> 
     41        assert elString in c1.typeOf.toString 
     42        assert c1.count == 2 
     43        assert c1['aa'] == 1 and c1['bb'] == 2 
     44         
     45        l = {:} as Dictionary<of String, MyClass> 
     46        assert elMyClass in l.typeOf.toString 
     47        l = {'cl0':MyClass(), 'cl1':MyClass()} 
     48        assert l.count == 2 
     49     
     50        fcls = FunkClass() 
     51        lf = {'mc':fcls} as Dictionary<of String, MyClass> 
     52        assert elMyClass in lf.typeOf.toString 
     53        assert lf.count == 1 
     54        assert lf['mc'] is fcls 
     55        #print 'done' 
     56         
     57class MyClass 
     58    pass 
     59 
     60class FunkClass inherits MyClass 
     61    def wotAmI 
     62        print "I'm a funkyClass" 
     63 
  • Tests/300-type-inference/900-literals/600-explicitly-typed/100-list-literal-typed.cobra

     
     1# tests for explicit typing of List literals 
     2class ListLitAs 
     3    def main is shared 
     4        # below element typenames specific to .Net family 
     5        elObject = r'[System.Object]' 
     6        elString = r'[System.String]' 
     7        elInt    = r'[System.Int32]' 
     8        elMyClass= r'[MyClass]' 
     9         
     10        a = [] 
     11        assert elObject in a.typeOf.toString 
     12        assert a.count ==0 
     13         
     14        b = [] as List<of int> 
     15        #print b.typeOf 
     16        assert elInt in b.typeOf.toString 
     17        assert b.count ==0 
     18        b = [3,4] 
     19        assert b == [3,4] 
     20         
     21        c = [] as List<of String> 
     22        assert elString in c.typeOf.toString 
     23        c.add('My') 
     24        assert c == ['My'] 
     25        c = ['a', 'b'] 
     26        assert c == ['a', 'b'] 
     27         
     28        l = [] as List<of MyClass> 
     29        assert elMyClass in l.typeOf.toString 
     30        l = [MyClass(), MyClass()] 
     31        assert l.count == 2 
     32     
     33        lf = [FunkClass()] as List<of MyClass> 
     34        assert elMyClass in lf.typeOf.toString 
     35        assert lf.count == 1 
     36        assert 'FunkClass' in lf[0].typeOf.toString 
     37     
     38        #TODO: IList 
     39        #ib = [] as IList<of > 
     40         
     41class MyClass 
     42    pass 
     43 
     44class FunkClass inherits MyClass 
     45    def wotAmI 
     46        print "I'm a funkyClass" 
     47 
  • Tests/300-type-inference/900-literals/600-explicitly-typed/300-set-literal-typed.cobra

     
     1# tests for explicit typing of Set literals 
     2class SetLitAs 
     3    def main is shared 
     4        # below element typenames specific to .Net family 
     5        elObject = r'[System.Object]' 
     6        elString = r'[System.String]' 
     7        elInt    = r'[System.Int32]' 
     8        elMyClass= r'[MyClass]' 
     9         
     10        a = {,} 
     11        assert elObject in a.typeOf.toString 
     12        assert a.count ==0 
     13         
     14        b = {,} as Set<of int> 
     15        #print b.typeOf 
     16        assert elInt in b.typeOf.toString 
     17        assert b.count ==0 
     18        b = {3,4} 
     19        assert b == {3,4} 
     20         
     21        c = {,} as Set<of String> 
     22        assert elString in c.typeOf.toString 
     23        c.add('My') 
     24        assert c == {'My',} 
     25        c = {'a', 'b'} 
     26        assert c == {'a', 'b'} 
     27         
     28        l = {,} as Set<of MyClass> 
     29        assert elMyClass in l.typeOf.toString 
     30        l = {MyClass(), MyClass()} 
     31        assert l.count == 2 
     32     
     33        fcls = FunkClass() 
     34        lf = {fcls,} as Set<of MyClass> 
     35        assert elMyClass in lf.typeOf.toString 
     36        assert lf.count == 1 
     37        assert lf.contains(fcls) 
     38     
     39class MyClass 
     40    pass 
     41 
     42class FunkClass inherits MyClass 
     43    def wotAmI 
     44        print "I'm a funkyClass" 
     45 
  • Tests/300-type-inference/900-literals/600-explicitly-typed/500-assign-empty-lit.cobra

     
     1# Allow untyped empty literals to be assigned to explicitly typed variable - ticket 230 
     2use System.Text.RegularExpressions 
     3 
     4class DotNet_RETypes 
     5    # Regexp strings to match Types specific to .Net family 
     6    var reListOfInt         = r'List.*\[[A-Za-z.]*Int32\]' 
     7    var reSetOfInt          = r'Set.*\[[A-Za-z.]*Int32\]' 
     8    var reArrayOfInt        = r'Int32\[\]' 
     9    var reDictOfStringInt   = r'Dictionary.*\[[A-Za-z.]*String,.*Int32\]' 
     10    var reDictOfStringString= r'Dictionary.*\[[A-Za-z.]*String,.*String\]' 
     11         
     12class AssignEmptyList 
     13     
     14    def main  
     15        .dclLaterAssignEmpty 
     16        .dclAndAssign 
     17         
     18    def dclLaterAssignEmpty 
     19     
     20        #if CobraCore.compileTarget =='.Net' 
     21        m = DotNet_RETypes() 
     22        #else if CobraCore.compileTarget =='Java' 
     23        #   m = Java_RETypes() 
     24        #... 
     25         
     26        # List 
     27        alist as List<of int>? 
     28        alist = [] 
     29        .chkPrintMatch(alist.typeOf, m.reListOfInt) 
     30        #print alist 
     31        #print alist.typeOf 
     32             
     33        # set 
     34        aset as Set<of int>? 
     35        aset = {,} 
     36        .chkPrintMatch(aset.typeOf, m.reSetOfInt) 
     37        #print aset 
     38        #print aset.typeOf 
     39     
     40        # array 
     41        arr as int[]? 
     42        arr = @[] 
     43        .chkPrintMatch(arr.typeOf, m.reArrayOfInt) 
     44        #print arr 
     45        #print arr.typeOf 
     46     
     47        # dict 
     48        ad as Dictionary<of String, int>?  
     49        ad = {} #.no-warnings. 
     50        .chkPrintMatch(ad.typeOf, m.reDictOfStringInt) 
     51        #print ad 
     52        #print ad.typeOf 
     53 
     54        ad1 as Dictionary<of String, String>?  
     55        ad1 = {:} 
     56        #print ad1 
     57        #print ad1.typeOf 
     58        .chkPrintMatch(ad1.typeOf, m.reDictOfStringString) 
     59         
     60         
     61    def dclAndAssign 
     62        #if CobraCore.compileTarget =='.Net' 
     63        m = DotNet_RETypes() 
     64        #else ... 
     65         
     66        alist as List<of int> = [] 
     67        .chkPrintMatch(alist.typeOf, m.reListOfInt) 
     68        #print alist 
     69        #print alist.typeOf 
     70         
     71        # set 
     72        aset as Set<of int> = {,} 
     73        .chkPrintMatch(aset.typeOf, m.reSetOfInt) 
     74        #print aset 
     75        #print aset.typeOf 
     76     
     77        # array 
     78        arr as int[] = @[] 
     79        .chkPrintMatch(arr.typeOf, m.reArrayOfInt) 
     80        #print arr 
     81        #print arr.typeOf 
     82        #arr=@[1,2] 
     83        #print arr 
     84     
     85        # dict 
     86        ad as Dictionary<of String, int> = {} #.no-warnings. 
     87        .chkPrintMatch(ad.typeOf, m.reDictOfStringInt) 
     88        #print ad 
     89        #print ad.typeOf 
     90 
     91        ad1 as Dictionary<of String, String> = {:} 
     92        .chkPrintMatch(ad1.typeOf, m.reDictOfStringString) 
     93        #print ad1 
     94        #print ad1.typeOf 
     95         
     96         
     97    def chkPrintMatch(t, ptn as String) 
     98        using sw = StringWriter() 
     99            print to sw 
     100                print t 
     101            assert Regex.isMatch(sw.toString, ptn) 
     102         
  • Developer/IntermediateReleaseNotes.text

     
    6565* Generate warning on use of deprecated `$sharp('...')` syntax in favor of newer alternate sharp-string-literal form: `sharp'...'` and `sharp"..."`. 
    6666 
    6767 
     68* Fixed: Make "a = []" do the right thing when a is of a known type: ticket:230 
     69  Includes allowing explicit typing of Composite Literals 
     70  e.g avar = [] as List<of RedBugs>    
     71      avar as List<of RedBugs> = [] 
     72 
     73      shapes = {} as Set<of Shapes> 
     74      shapes as Set<of Shapes> = {} 
     75      shapes = {Circle()} as Set<of Shapes> # otherwise infer as Set<of Circle> 
     76 
     77      iArr = @[] as int[] 
     78      iArr as int[] = @[] 
     79 
     80      d = {:} as Dictionary<of String, int> 
     81      d as Dictionary<of String, int> = {:} 
     82 
    6883================================================================================ 
    6984Library 
    7085================================================================================