Wiki

Ticket #275: java-jvm-6.patch

File java-jvm-6.patch, 66.3 KB (added by hopscc, 12 years ago)
  • Source/Members.cobra

     
    6363    var _matchingBaseMember as IBoxCodeMember? 
    6464    var _sharedMethodBacking as String? 
    6565    var _sharedMethodBackingIsAlias as bool 
     66    var _aliasedMethodBacking as String? 
    6667    var _binaryName as String? 
    6768 
    6869    cue init(token as IToken, idToken as IToken, parentBox as Box, name as String, isNames as String*, attribs as AttributeList) 
     
    108109 
    109110    pro sharedMethodBackingIsAlias from var 
    110111 
     112    pro aliasedMethodBacking from var 
     113     
    111114    get testMethods as IList<of TestMethod> 
    112115        if _testMethods is nil, _testMethods = List<of TestMethod>() 
    113116        return _testMethods to ! 
  • Source/BackEndObjC/ObjcBackEnd.cobra

     
    8686    def cobraNameForNativeBoxName(nativeBoxName as String) as String is override 
    8787        return nativeBoxName # TODO 
    8888         
     89    def isRunnableFile( fullExeFileName as String) as bool is override 
     90        return true # may need extending 
     91 
    8992    # Types 
    9093    get objectTypeProxy as AbstractTypeProxy  is override 
    9194        """Type proxy for BE root of Object hierarchy.""" 
  • Source/Compiler.cobra

     
    146146        on the instance. 
    147147        """ 
    148148             
     149    def isRunnableFile( fullExeFileName as String) as bool is abstract 
     150        """Test if given filename is an executable ( vs a library or something else) """ 
     151 
    149152    # Native Types access 
    150153    def cobraNameForNativeBoxName(name as String) as String is abstract 
    151154        """ 
     
    259262    def installNativeMethods(box as Box, nativeType as NativeType) is override 
    260263        pass 
    261264         
     265    def isRunnableFile(fullExeFileName as String) as bool is override 
     266        return true 
     267         
    262268    # Native Type access 
    263269    def cobraNameForNativeBoxName(name as String) as String is override 
    264270        return name + '_BBE' 
     
    658664            .options = options 
    659665            bar = '----------------------------------------------------------------------------------------------------' 
    660666            .initBackEnd 
     667             
    661668            .defaultOutName = if(.options.buildStandardLibrary, 'Cobra.Lang.dll', fileNames[0]) 
    662669            _pathsToCompile = fileNames 
    663670            hasErrors = false 
     
    13491356        return type to ! 
    13501357 
    13511358    def _libraryType(names as vari String) as IType 
    1352         #print names 
     1359        #trace names 
    13531360        ns as IContainer = _globalNS 
    13541361        thing as IContainer? = nil 
    13551362        for name in names 
    13561363            possible = (thing ? ns).declForName(name) 
    13571364            #print name 
     1365            # dbg 
     1366            #if not possible 
     1367            #   trace thing ? ns 
     1368            #   ((thing ? ns) to NameSpace).dumpDeclsNameKeys 
    13581369            assert possible, name 
    13591370            if possible inherits IContainer 
    13601371                thing = possible 
  • Source/Cobra.Lang/Java/InvariantException.java

     
     1/*  
     2 * java code for cobra Invariant exception  
     3 *  thrown when an invariant failure detected (Contracts) 
     4 *  
     5 *  
     6 */ 
     7 
     8package cobra.lang; 
     9 
     10import java.util.*; 
     11 
     12 
     13public class InvariantException extends AssertException  
     14{ 
     15    public InvariantException(/*SourceSite*/ Object sourceSite,  
     16              java.util.List<Object> expressions /*dynamic */,  Object thiss, Object info /*dynamic? */)  
     17    { 
     18        this(sourceSite, expressions, thiss, info, null); 
     19    } 
     20     
     21    public InvariantException(/*SourceSite*/ Object sourceSite,  
     22              java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*dynamic? */,  
     23              Exception cause) 
     24    { 
     25        super(sourceSite, expressions, thiss, info, cause); 
     26    } 
     27} 
  • Source/Cobra.Lang/Java/AssertException.java

     
    11/*  
    2  * java code for cobra assert exception ( placeholder currently) 
    3  * Initially using java assertion till this is working 
     2 * java code for cobra assert exception  
     3 *  ( Root class of Cobra Assertions and contracts exceptions) 
    44 *  
    55 * Exceptions for Assertions, contracts, etc. 
    66 */ 
     
    1010import java.util.*; 
    1111 
    1212 
    13 class AssertException extends RuntimeException //implements IHasSourceSite, HasAppendNonPropertyKeyValues 
     13public class AssertException extends RuntimeException //implements IHasSourceSite, HasAppendNonPropertyKeyValues 
    1414//      has DetailedStackTrace(false) 
    1515{ 
    1616    protected Object _this; 
     
    3636        _info = info; 
    3737    } 
    3838     
     39    public AssertException(/*SourceSite*/ Object sourceSite, Object[] expressionsArr /*dynamic */,  
     40              Object thiss, Object info /*dynamic? */) 
     41    { 
     42        this(sourceSite, expressionsArr, thiss, info, null); 
     43    } 
     44 
     45    public AssertException(/*SourceSite*/ Object sourceSite, Object[] expressionsArr /*dynamic */,  
     46              Object thiss, Object info /*dynamic?*/, Exception innerExc) 
     47    { 
     48        super("assert", innerExc); 
     49        _sourceSite = sourceSite; 
     50        _expressions = Arrays.asList(expressionsArr); 
     51        _this = thiss; 
     52        _info = info; 
     53    } 
     54 
    3955    // Property this 
    4056    public Object getThis() { return _this; } 
    4157     
     
    142158*/ 
    143159 
    144160} 
    145  
    146 class InvariantException extends AssertException  
    147 { 
    148     public InvariantException(/*SourceSite*/ Object sourceSite,  
    149               java.util.List<Object> expressions /*dynamic */,  Object thiss, Object info /*dynamic? */)  
    150     { 
    151         this(sourceSite, expressions, thiss, info, null); 
    152     } 
    153      
    154     public InvariantException(/*SourceSite*/ Object sourceSite,  
    155               java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*dynamic? */,  
    156               Exception cause) 
    157     { 
    158         super(sourceSite, expressions, thiss, info, cause); 
    159     } 
    160 } 
    161  
    162 class RequireException extends AssertException 
    163 { 
    164     protected RequireException _next; 
    165  
    166     public RequireException(/*SourceSite*/ Object sourceSite,  
    167               java.util.List<Object> expressions /*dynamic */,  
    168               Object thiss,  
    169               Object info /*dynamic? */)  
    170     { 
    171         this(sourceSite, expressions, thiss, info, null); 
    172     } 
    173      
    174     public RequireException(/*SourceSite*/ Object sourceSite,  
    175               java.util.List<Object> expressions /*dynamic */,   
    176               Object thiss,  
    177               Object info /*dynamic? */, 
    178               Exception cause ) 
    179           { 
    180               super(sourceSite, expressions, thiss, info, cause); 
    181           }     
    182      
    183     //Property RequireException next 
    184     public RequireException getNext() { return this._next;} 
    185     public void setNext(RequireException value) { this._next = value; } 
    186 } 
    187  
    188  
    189 class EnsureException extends AssertException 
    190 { 
    191  
    192     public EnsureException(/*SourceSite*/ Object sourceSite,  
    193               java.util.List<Object> expressions /*dynamic */,  
    194               Object thiss,  
    195               Object info /*dynamic? */)  
    196     { 
    197         this(sourceSite, expressions, thiss, info, null); 
    198     } 
    199  
    200     public EnsureException(/*SourceSite*/ Object sourceSite,  
    201               java.util.List<Object> expressions /*dynamic */,   
    202               Object thiss,  
    203               Object info /*dynamic? */, 
    204               Exception cause) 
    205           { 
    206               super(sourceSite, expressions, thiss, info, cause); 
    207           }     
    208 } 
    209  
    210 class NonNilCastException extends AssertException 
    211 { 
    212  
    213     public NonNilCastException(/*SourceSite*/ Object sourceSite,  
    214               java.util.List<Object> expressions /*dynamic */,  
    215               Object thiss,  
    216               Object info /*dynamic? */)  
    217     { 
    218         this(sourceSite, expressions, thiss, info, null); 
    219     } 
    220  
    221  
    222     public NonNilCastException(/*SourceSite*/ Object sourceSite,  
    223               java.util.List<Object> expressions /*dynamic */,   
    224               Object thiss,  
    225               Object info /*dynamic? */, 
    226               Exception cause ) 
    227           { 
    228               super(sourceSite, expressions, thiss, info, cause); 
    229           }     
    230  
    231     @Override 
    232     public String getMessage() { 
    233         return String.format("Cast to non-nil failed.%s%s", this.nl, super.getMessage() ) ; 
    234     } 
    235 } 
    236  
    237  
    238  
    239 /*  ## Misc exceptions 
    240  
    241     class ExpectException inherits Exception 
    242  
    243         cue init(expectedExceptionType as Type, actualException as Exception?) 
    244             base.init 
    245             _expectedExceptionType = expectedExceptionType 
    246             _actualException = actualException 
    247      
    248         get expectedExceptionType from var as Type 
    249      
    250         get actualException from var as Exception? 
    251  
    252         get message as String? is override 
    253             sb = StringBuilder() 
    254             sb.append('Expecting exception: [_expectedExceptionType.name], but ') 
    255             if _actualException 
    256                 sb.append('a different exception was thrown: [_actualException]') 
    257             else 
    258                 sb.append('no exception was thrown.') 
    259             return sb.toString 
    260  
    261  
    262     class FallThroughException inherits Exception 
    263  
    264         cue init 
    265             .init(nil) 
    266             pass 
    267  
    268         cue init(info as Object?) 
    269             base.init 
    270             _info = info 
    271  
    272         cue init(info as Object?, innerExc as Exception?) 
    273             base.init(nil, innerExc) 
    274             _info = info 
    275  
    276         get message as String is override 
    277             return 'info=[CobraCore.toTechString(_info)]' 
    278  
    279         get info from var as Object? 
    280  
    281  
    282     class SliceException inherits SystemException 
    283  
    284         cue init(msg as String?) 
    285             base.init 
    286 */ 
  • Source/Cobra.Lang/Java/EnsureException.java

     
     1/*  
     2 * java code for cobra Ensure exception 
     3 * thrown when a contracts postcondition fails. 
     4 */ 
     5 
     6package cobra.lang; 
     7 
     8import java.util.*; 
     9 
     10 
     11public class EnsureException extends AssertException 
     12{ 
     13 
     14    public EnsureException(/*SourceSite*/ Object sourceSite,  
     15              java.util.List<Object> expressions /*dynamic */,  
     16              Object thiss,  
     17              Object info /*dynamic? */)  
     18    { 
     19        this(sourceSite, expressions, thiss, info, null); 
     20    } 
     21 
     22    public EnsureException(/*SourceSite*/ Object sourceSite,  
     23              java.util.List<Object> expressions /*dynamic */,   
     24              Object thiss,  
     25              Object info /*dynamic? */, 
     26              Exception cause) 
     27          { 
     28              super(sourceSite, expressions, thiss, info, cause); 
     29          }     
     30} 
     31 
  • Source/Cobra.Lang/Java/PkgSig.java

     
    279279        int m = theClass.getModifiers(); 
    280280        //if( java.lang.reflect.Modifier.isPublic(m) ) 
    281281        //if( ! java.lang.reflect.Modifier.isPrivate(m) ) 
    282         if(  Modifier.isPublic(m) || Modifier.isProtected(m) ) 
     282        if(  Modifier.isPublic(m) || Modifier.isProtected(m) ) { 
    283283            allClasses.add( theClass ); 
    284  
     284        } 
     285                                     
     286        // special case for pkgPrivate java.lang.AbstractStringBuilder parent of public String{Buffer,Builder} 
     287        if ( ClassSig.isPkgPrivate(m) && theClass.getName().equals("java.lang.AbstractStringBuilder") ) { 
     288            allClasses.add( theClass ); 
     289        } 
     290                                           
    285291        // skip interfaces 
    286292        //if( theClass.isInterface() ){ 
    287293        //  continue; 
     
    475481        this.indent--; 
    476482    } 
    477483     
    478     public boolean isPkgPrivate(int m) { 
     484    static public boolean isPkgPrivate(int m) { 
    479485        // if (!cobraGen) 
    480486        //  return false 
    481487 
     
    601607                printIndent(); 
    602608                String typeName = f.getType().getName(); 
    603609                System.out.printf("%s\n", typeName); 
    604                 if ( f.getType().isEnum()) { 
     610                //if ( f.getType().isEnum()) { 
     611                if ( f.isEnumConstant()) { 
    605612                    this.indent++; 
    606613                    printIndent(); 
    607614                    System.out.printf("%d\n", Enum.valueOf( this.cls, f.getName()).ordinal() ); 
  • Source/Cobra.Lang/Java/DynamicOperationException.java

     
    1414   // The base class for all dynamic operation exceptions. 
    1515   //""" 
    1616 
    17     public DynamicOperationException(String message) { this(message, nil); } 
    18     public DynamicOperationException(String message, cause as Exception ) {super(message, cause); } 
     17    public DynamicOperationException(String message) { this(message, null); } 
     18    public DynamicOperationException(String message, Exception cause) {super(message, cause); } 
    1919} 
    2020 
    2121class CannotEnumerateException extends DynamicOperationException  
    2222{ 
    23     public CannotEnumerateException (String message) {this(message, nil); } 
     23    public CannotEnumerateException (String message) {this(message, null); } 
    2424    public CannotEnumerateException (String message, Exception cause) {super(message, cause); } 
    2525}        
    2626         
     
    3030    protected String _name; 
    3131    Class _type; 
    3232 
    33     public UnknownMemberException(Object obj, String name as String, Class type) {  this(obj, name, type, nil);} 
    34     public UnknownMemberException(Object obj, String name as String, Class type, Exception cause)  
     33    public UnknownMemberException(Object obj, String name, Class type) {  this(obj, name, type, null);} 
     34    public UnknownMemberException(Object obj, String name, Class type, Exception cause)  
    3535    { 
    3636    super(String.format("obj=%s, name=%s, type=%s",  
    3737                  CobraCore.toTechString(obj), CobraCore.toTechString(name), type), 
    3838              cause); 
    3939        this._obj = obj; 
    4040        this._name = name; 
    41         this.type = type; 
     41        this._type = type; 
    4242    } 
    4343} 
    4444 
  • Source/Cobra.Lang/Java/mkjarOnly

     
    55 
    66[ -d classes ] || mkdir classes 
    77[ -d classes/cobra/lang ] && rm -rf classes/cobra/lang/* 
    8 javac -d classes SourceSite.java CobraImp.java CobraCore.java Delegate.java AssertException.java CobraDirectString.java 
     8EXCEPTIONS="AssertException.java InvariantException.java RequireException.java EnsureException.java NonNilCastException.java DynamicOperationException.java" 
     9javac -d classes SourceSite.java CobraImp.java CobraCore.java Delegate.java ${EXCEPTIONS} CobraDirectString.java 
    910[ $? == 0 ] || exit 
    1011jar cvf CobraLang.jar -C classes . 
    1112[ $? == 0 ] || exit 
  • Source/Cobra.Lang/Java/NonNilCastException.java

     
     1/*  
     2 * java code for cobra NonNil Cast exception. 
     3 * Thrown when Null check for non nullable instance fails.  
     4 */ 
     5 
     6package cobra.lang; 
     7 
     8import java.util.*; 
     9 
     10 
     11public class NonNilCastException extends AssertException 
     12{ 
     13 
     14    public NonNilCastException(/*SourceSite*/ Object sourceSite,  
     15              java.util.List<Object> expressions /*dynamic */,  
     16              Object thiss,  
     17              Object info /*dynamic? */)  
     18    { 
     19        this(sourceSite, expressions, thiss, info, null); 
     20    } 
     21 
     22 
     23    public NonNilCastException(/*SourceSite*/ Object sourceSite,  
     24              java.util.List<Object> expressions /*dynamic */,   
     25              Object thiss,  
     26              Object info /*dynamic? */, 
     27              Exception cause ) 
     28          { 
     29              super(sourceSite, expressions, thiss, info, cause); 
     30          }     
     31 
     32    @Override 
     33    public String getMessage() { 
     34        return String.format("Cast to non-nil failed.%s%s", this.nl, super.getMessage() ) ; 
     35    } 
     36} 
     37 
     38 
     39 
     40/*  ## Misc exceptions 
     41 
     42    class ExpectException inherits Exception 
     43 
     44        cue init(expectedExceptionType as Type, actualException as Exception?) 
     45            base.init 
     46            _expectedExceptionType = expectedExceptionType 
     47            _actualException = actualException 
     48     
     49        get expectedExceptionType from var as Type 
     50     
     51        get actualException from var as Exception? 
     52 
     53        get message as String? is override 
     54            sb = StringBuilder() 
     55            sb.append('Expecting exception: [_expectedExceptionType.name], but ') 
     56            if _actualException 
     57                sb.append('a different exception was thrown: [_actualException]') 
     58            else 
     59                sb.append('no exception was thrown.') 
     60            return sb.toString 
     61 
     62 
     63    class FallThroughException inherits Exception 
     64 
     65        cue init 
     66            .init(nil) 
     67            pass 
     68 
     69        cue init(info as Object?) 
     70            base.init 
     71            _info = info 
     72 
     73        cue init(info as Object?, innerExc as Exception?) 
     74            base.init(nil, innerExc) 
     75            _info = info 
     76 
     77        get message as String is override 
     78            return 'info=[CobraCore.toTechString(_info)]' 
     79 
     80        get info from var as Object? 
     81 
     82 
     83    class SliceException inherits SystemException 
     84 
     85        cue init(msg as String?) 
     86            base.init 
     87*/ 
  • Source/Cobra.Lang/Java/RequireException.java

     
     1/*  
     2 * java code for cobra Require exception   
     3 * thrown when a contract precondition test fails 
     4 */ 
     5 
     6package cobra.lang; 
     7 
     8import java.util.*; 
     9 
     10 
     11public class RequireException extends AssertException 
     12{ 
     13    protected RequireException _next; 
     14 
     15    public RequireException(/*SourceSite*/ Object sourceSite,  
     16              java.util.List<Object> expressions /*dynamic */,  
     17              Object thiss,  
     18              Object info /*dynamic? */)  
     19    { 
     20        this(sourceSite, expressions, thiss, info, null); 
     21    } 
     22     
     23    public RequireException(/*SourceSite*/ Object sourceSite,  
     24              java.util.List<Object> expressions /*dynamic */,   
     25              Object thiss,  
     26              Object info /*dynamic? */, 
     27              Exception cause ) 
     28          { 
     29              super(sourceSite, expressions, thiss, info, cause); 
     30          }     
     31     
     32    //Property RequireException next 
     33    public RequireException getNext() { return this._next;} 
     34    public void setNext(RequireException value) { this._next = value; } 
     35} 
     36 
  • Source/Cobra.Lang/Java/CobraImp.java

     
    7777        return s; 
    7878    } 
    7979     
    80     static public Object checkNonNil(Object obj, String sourceCode, Object value, /* SourceSite */ String fileName, int lineNum, String className, String memberName, Object thiss)  
     80    @SuppressWarnings("unchecked") 
     81    static public <T> List<T> makeList(T... args) { 
     82    return new ArrayList<T>(Arrays.asList(args)); 
     83    } 
     84     
     85    /* 
     86    @SuppressWarnings("unchecked") 
     87    static public <T> List<T> makeList(T... args) { 
     88    List<T> l = new ArrayList<T>(); 
     89        for (T arg : args) { 
     90            l.add(arg); 
     91        } 
     92        return l; 
     93    } 
     94    */ 
     95     
     96    @SuppressWarnings("unchecked") 
     97    static public <T> Set<T> makeSet(T... args) { 
     98        return new HashSet<T>(Arrays.asList(args)); 
     99    } 
     100     
     101    @SuppressWarnings("unchecked")  
     102    static public <K,V> Map<K,V> makeDict( Object... args) { 
     103    Map<K,V>  d = new HashMap<K,V>(); 
     104    for (int i=0; i<args.length; i+=2) 
     105            d.put((K)args[i], (V)args[i+1]); //[unchecked] warning here 
     106    return d; 
     107    } 
     108     
     109 
     110    static public <T> T checkNonNil(Object obj, String sourceCode, T value, /* SourceSite */ String fileName, int lineNum, String className, String memberName, Object thiss)  
    81111    { 
    82112        // used for "x to !" and "someNilable to SomethingNotNilable" 
    83113        if (value == null) { 
  • Source/Container.cobra

     
    169169        body 
    170170            #print _declsByName.keys 
    171171            return if(_declsByName.containsKey(name), _declsByName[name], nil) 
    172  
     172             
     173    # for debug 
     174    def dumpDeclsNameKeys 
     175        print _declsByName.keys 
     176         
    173177    def declForName(name as String) as IMember? 
    174178        implements IContainer 
    175179        return if(_declsByName.containsKey(name), _declsByName[name], nil) 
  • Source/BackEndClr/ClrBackEnd.cobra

     
    142142    def fixMemberSigs is override 
    143143        .compiler.dotNetFixNilableMemberSigs # in ScanClrType 
    144144         
     145    def isRunnableFile(fullExeFileName as String) as bool is override 
     146        """Test if filename is runnable ( vs a library or something else) """ 
     147        return fullExeFileName.endsWith('.exe') 
     148 
    145149    # Types 
    146150    get objectTypeProxy from var  is override 
    147151        """Type proxy for BE root of Object hierarchy.""" 
  • Source/Types.cobra

     
    13401340 
    13411341    def isDescendantOf(type as IType) as bool 
    13421342        return base.isDescendantOf(type) and _wrappedType.isDescendantOf(type) 
    1343          
     1343        # shouldnt the above conjunction be an 'or' ?? 
     1344 
    13441345    def isEquatableTo(b as IType) as bool is override 
    13451346        if b inherits NilType 
    13461347            return true 
  • Source/BackEndJvm/JvmJarSig.cobra

     
    2626            """All classes found in all jars keyed by canonical/full name.""" 
    2727             
    2828     
    29         var nameRemaps = { 
     29        var virtualNameRemaps = { 
    3030            'java.lang.Decimal' : 'java.lang.Double', # BigDecimal eventually with (lotta) codegen support 
    3131            'java.lang.UByte'   : 'java.lang.Short', 
    3232            'java.lang.UShort'  : 'java.lang.Integer', 
     
    4242            This is intended to be the only way to access the JarSig classCache contents from outside this file. 
    4343            """ 
    4444            assert fullCobraName[0].isUpper 
    45             #fullCobraName = .nameRemaps.get(fullCobraName, fullCobraName) 
     45            #fullCobraName = .virtualNameRemaps.get(fullCobraName, fullCobraName) 
    4646            parts = fullCobraName.split('.') 
    4747            for i in 0: parts.length-1 
    4848                parts[i] = parts[i][0].toLower.toString + parts[i][1:] 
     
    188188        _genTypesList 
    189189        _aliasPrimitives 
    190190 
     191        if jarName == 'rt.jar'  # special for system jarfile 
     192            # these name remaps will probably need some codegen special handling.  
     193            _dupVirtuals 
     194            _nonGenericCommon 
     195 
     196             
     197 
    191198    def _genTypesList 
    192199        jarName = if(.name.endsWith('.sig'), .name[:-4], .name) 
    193200        fileName = JarSig.sigFile(jarName) 
     
    236243        JarSig.classByNameCache['float']   = JarSig.classByNameCache['java.lang.Float']  
    237244        JarSig.classByNameCache['double']  = JarSig.classByNameCache['java.lang.Double']  
    238245             
    239         # these name remaps will probably need some codegen special handling.  
    240         _dupVirtuals 
    241         _nonGenericCommon 
    242  
    243246    def _dupVirtuals 
    244         for dupName in .nameRemaps.keys 
    245             dupOf = .nameRemaps[dupName] 
     247        # Make cache and jar export entries for virtualised types that dont exist in java 
     248        # but cobra has and expects to be distinct. They get remapped to an existing Java Type 
     249        for dupName in .virtualNameRemaps.keys 
     250            dupOf = .virtualNameRemaps[dupName] 
    246251            _dupClassTo(dupOf, dupName) 
    247252             
    248253    def _nonGenericCommon        
    249         #pass 
     254        # spoof generic Instances for cobra non generic Types that java genericises 
    250255        #   'java.util.Collection'   : 'java.util.Collection<Object>', 
    251256        #_dupClassTo( 'java.util.Collection', 'java.util.Collection<Object>') 
    252257        _makeGenericInstance('java.util.Collection<Object>')  # for ICollection/Java.Util.Collection<of Object> 
    253258        # probably others yet 
    254259                 
    255260    def _dupClassTo(dupOfName as String, asName as String) 
    256         ct = JarSig.classByNameCache[dupOfName]  
    257         parts = asName.split('.') 
    258         name = parts[parts.length-1] 
    259         package = parts[0:-1].join('.') # all but last 
    260         ct = ct.copy(name, package) 
    261         JarSig.classByNameCache[asName] = ct 
     261        if JarSig.classByNameCache.containsKey(asName) # already cached 
     262            ct = JarSig.classByNameCache[asName]  
     263        else 
     264            ct = JarSig.classByNameCache[dupOfName]  
     265            parts = asName.split('.') 
     266            name = parts[parts.length-1] 
     267            package = parts[0:-1].join('.') # all but last 
     268            ct = ct.copy(name, package) 
     269            JarSig.classByNameCache[asName] = ct 
    262270        _javaTypes.add(ct) 
    263271         
    264272    def _makeGenericInstance(fullName as String) 
    265273        # cached AND exposed to namespace 
    266274        assert fullName.contains('<') 
    267         .addGenericInstClass(fullName) 
     275        if not JarSig.classByNameCache.containsKey(fullName) # already cached 
     276            .addGenericInstClass(fullName) 
    268277        giCls = JarSig.classByNameCache[fullName] 
    269         print giCls.canonicalName 
     278        #print giCls.canonicalName 
    270279        _javaTypes.add(giCls) 
    271             #_registerClassType(giCls)   
    272280         
    273281    def getExportedTypes as JavaClassType* 
    274282        return _javaTypes 
     
    403411                field.modifiers = _parseList(_popTop(lines), [c' ']) 
    404412                field.typeName = _popTop(lines) 
    405413                if type == JavaType.JavaEnum  and field.typeName == absName #'[pkg].[name]' 
    406                     field.value = _popTop(lines)     
     414                    t = _peekTop(lines) 
     415                    if t.length - t.trimStart.length > 8  
     416                        field.value = _popTop(lines)     
    407417                #field.attributes = _parseList(_popTop(lines)) 
    408418                fieldList.add(field) 
    409419 
     
    486496                if not e.length, continue 
    487497            break 
    488498        return e.trim 
     499 
     500    def _peekTop(content as List<of String>) as String is shared     
     501        if content.count == 0 
     502            return '' 
     503        return content[0] 
     504             
    489505         
    490506    # property: get<Propname> and no paramList and returnType is Property Type or 
    491507    #           is<PropName> and no paramList and returnType is bool 
     
    602618        # special case naming weirdnesses of Java lib classes 
    603619        if .canonicalName == 'java.lang.String' 
    604620            getterName, setterName = 'charAt', '' 
     621        else if .canonicalName.startsWith('java.util.List`') 
     622            getterName, setterName = 'get', 'set' 
     623        else if .canonicalName.startsWith('java.util.Map`') 
     624            getterName, setterName = 'get', 'put' 
    605625        else  
    606626            for ifcName in .interfaceNames # TODO also chase up interface inheritance tree 
    607                 if ifcName.startsWith('java.util.List') 
     627                if ifcName.startsWith('java.util.List`') 
    608628                    getterName, setterName = 'get', 'set' 
    609                 else if ifcName.startsWith('java.util.Map') 
     629                else if ifcName.startsWith('java.util.Map`') 
    610630                    getterName, setterName = 'get', 'put' 
    611631 
    612632        #TODO also check for specially annotated methods 
     
    614634        assert getterName.length 
    615635        getMethod, setMethod = _lookForMethods(getterName, setterName) 
    616636        if getMethod or setMethod 
    617             idxrProp = _genAProp('_synthesizedIdxr', getMethod, setMethod, true) 
     637            idxrProp =  _genAProp('[.canonicalName]_synthesizedIdxr', getMethod, setMethod, true) 
    618638            _props.add(idxrProp) 
    619639            _indexer = idxrProp 
    620             print 'dbg: [.canonicalName] has IndexerMethods [getterName] and [setterName] ' 
     640            sb = StringBuilder('= ') 
     641            if getMethod 
     642                sb.append(getterName) 
     643                if setMethod, sb.append(',') 
     644            if setMethod 
     645                sb.append(setterName) 
     646            print 'dbg: [.canonicalName] indexerMethods [sb.toString] ' 
    621647        #else 
    622648        #   print 'dbg: No IndexerMethods [getterName]/[setterName] on [.canonicalName]' 
    623649                 
     
    11501176        sb = StringBuilder('def [nampar] ') 
    11511177        if .returnTypeName.length 
    11521178            sb.append('as [.returnTypeName] ') 
     1179        else 
     1180            sb.append('as ??? ') 
    11531181        if .modifiers.count  
    11541182            sb.append('is ') 
    11551183            sep='' 
  • Source/BackEndJvm/to-do.text

     
    33Require Base version Java to be java7 
    44    gain strings in case stmt for free (!) 
    55 
     6Indexers on Generics ( List<of String>) 
     7    - Not recognising/setup indexer record on JavaClass (or searching inheritance hier List<String> ^ List<E>... 
     8    - seems to be missing NativeType entry should be List<of String> -> List<String> 
     9    - (unfortunately) like commandLineArgs (065j-indexing.cobra) 
    610 
     11Add code for generating attributes from 'has XXXXX' 
     12    -  chk cobra syntax allows AttribName(value[, value]) like ctor not just AttribName ? 
     13 
     14executable autgen jarfile 
     15    gen srcs into own dir ./java 
     16    compile classes into own dir    ./classes 
     17    generate exe jarfile ( auto manifest file)  ./<exename>.jar 
     18        remove unlise -kif generated java files 
     19        remove intermediate classfiles 
     20   run as  java -cp '<otherRefs...>' -jar App.jar args....     
     21 
    722include-tests:no - remove Test invocation call 
    823 
    924 
    1025_fixNativeMethods - static method entries on box instance 
    1126 
    1227 
    13 fixup Object namespace for X-compile so items like System.Object are rooted off 
    14 java.lang namespace ( rather than .Net system) 
    15     DONE  June-2011 
     28Get Testifyrunner working on java gen 
    1629 
    1730passthru compilation of *.java files  
    1831    - seems to work for single files But 
    1932        - calc of main class fm passthru *.java files 
    2033     
    21 computeOutName from name of main class (or first/only) class in file rather 
    22 than permutation of input name 
    23     DONE 31-Jan-2011 
    24      
    2534 
    2635cobra namespaces capitalized (as .Net) Java all lowercase 
    2736    - convert namespaces in java code to lowcase 
     
    4150        ( look for calls to .capitalized)        
    4251        DONE (I think) 
    4352 
    44 remove all uses of ClrNativeType in core compiler ( ->NativeType??) 
    45     Compiler/Enums/Types.cobra 
    46     DONE 
    47  
    4853properties - pro/get/set 
    4954    - auto convert to java getters/setters and map calls 
    5055    - Whats the equiv for indexers? 
     
    107112    If lookup for name fails see if sig matches extension and remap call to extn static class method 
    108113 
    109114 
    110 Parse error lines fm java giving source line, find (trailing comment) cobra 
    111 line number and modify the java error msg line with the cobra lineno 
    112 printing  that in any java error mesages so to relate the java error back  
    113 to the generating cobra code line. 
    114   - start with just spew the javac lines to output 
    115     - assemble into ErrorMessage Line and 'supporting lines associated with it - keeps error line count in sync 
    116     DONE 
    117115 
    118116 
    119117single file: 
     
    122120    run class file 
    123121  
    124122If specify multiple files 
    125     generate thm all to java src in in namespace dir hier 
    126     compile to class files ( in class dir hier) 
     123    generate them all to java src in in namespace dir hier 
     124    compile to class files (in class dir hier) 
    127125    generate manifest file and generate classfiles to jar file 
    128126    Leave jar file at root of hierarchy 
    129      
     127 -> single or multiple files just gen an executable jarfile    
    130128 
    131129add synonym for sharp''/sharp"" -> java''/java"" 
    132130    or general be''/be""/backend'' (for backend) 
     
    145143    java specify with @interface and Metainfo  
    146144        e.g @Documented //we want the annotation to show up in the Javadocs  
    147145            @Retention(RetentionPolicy.RUNTIME)) 
    148  
     146         
    149147Java has Set in its collections framework so use that instead of Cobra lib version. 
    150148 
    151149Cobra methods nonVirtual (C# not marked virtual) in java mark as final (Cannot redefine or override). 
     
    217215 
    218216    Instead use google collections/Guava 
    219217        - support for List, Set and Map literals 
     218            com.google.common.collect 
     219            l = [lit,lit,...]   List<InferredType> l = Lists.newArrayList<InferredType>( lit, lit, ....); 
     220                OR        (immutable)      List<InferredType> l = new ArrayList<InferredType>( Arrays.asList(lit, lit, ....));             
     221                          (mutable)        List<InferredType> l = new ArrayList<InferredType>( new ArrayList(Arrays.asList(lit, lit, ....)));             
     222 
     223            m = {a:b, ...}      Map<InferredK, InferredV> m = Maps.newHashMap<>(); m.put(a,b); ... 
     224                (Immutable - up to 5 entries)    ImmutableMap<InferredfTypeKey,InferredTypeValue> m = ImmutableMap.of(a, b, ...); 
     225                (Immutable any #)  ImmutableMap<InferredfTypeKey,InferredTypeValue> m = ImmutableMap.Builder<InferredfTypeKey,InferredTypeValue>().put(a, b)... (.put(c.d)...}.build(); 
     226                (Mutable) Make immutable map and  
     227                          Map m = new HashMap<inferredK,inferredV>(immutableMap) OR 
     228                          Map m = Maps.newHashMap<inferredK,inferredV>(mutableMap) 
     229                OR 
     230                add CobraMutableMap<K,V> inherits HashMap - adds ctor taking varargs list of k,v) 
     231                    Map m = new CobraMutableMap<K,V>(a,b,...) 
     232                OR static factory  
     233                    CobraCore.fillHashMap(new HashMap<K,V>(), a,b,...) 
     234                OR  (http://blogs.steeplesoft.com/2011/10/funky-object-initialization/ ) 
     235                    Map m = new HashMap<inferredK,inferredV>() { {  
     236                    put(a,b);  
     237                    ...; 
     238                    } };    
     239            Wait for Java8 and hope have implemented List and Map literals    
     240               
    220241        - Simple file reading API 
    221242 
     243 
     244 
    222245ensure support ( as builtin alternative) for jikes compiler. 
    223246        https://sourceforge.net/projects/jikes/files/Jikes/     
    224247 
     
    484507 
    485508= Other back ends = 
    486509Fantom : compile to jvm or dotNet 
     510 
     511----------------------------------------------- 
     512Done 
     513fixup Object namespace for X-compile so items like System.Object are rooted off 
     514java.lang namespace ( rather than .Net system) 
     515    DONE  June-2011 
     516 
     517 
     518computeOutName from name of main class (or first/only) class in file rather 
     519than permutation of input name 
     520    DONE 31-Jan-2011 
     521     
     522remove all uses of ClrNativeType in core compiler ( ->NativeType??) 
     523    Compiler/Enums/Types.cobra 
     524    DONE 
     525 
     526Parse error lines fm java giving source line, find (trailing comment) cobra 
     527line number and modify the java error msg line with the cobra lineno 
     528printing  that in any java error mesages so to relate the java error back  
     529to the generating cobra code line. 
     530  - start with just spew the javac lines to output 
     531    - assemble into ErrorMessage Line and 'supporting lines associated with it - keeps error line count in sync 
     532    DONE 
     533 
  • Source/BackEndJvm/ScanJvmType.cobra

     
    184184        _fix('Java.Lang.Object', 'toString getClass clone') 
    185185            # ^ regarding .toString, not technically true, but common enough and life is too painful when the return type is nilable 
    186186        #_fix('java.lang.System', 'out') #stdout 
    187         _fix('Java.Lang.String', 'concat remove replace replaceAll replaceFirst substring toLowerCase toUpperCase trim format') 
     187        _fix('Java.Lang.String', r'[] length charAt concat remove replace replaceAll replaceFirst substring toLowerCase toUpperCase trim format') 
    188188        #_fix('System.Type', 'assembly name toString') 
    189189            # namespace can return nil if the Type is a generic parameter 
    190190        #_fix('System.Environment', 'commandLine currentDirectory newLine version') 
     
    340340        return .name == 'Exception' and .parentNameSpace and .parentNameSpace.fullName == 'Java.Lang' 
    341341 
    342342    def prepSystemObjectClassJvm 
    343         # TODO chk thats this has desired result. 
     343        # TODO chk thats this has desired result.  
    344344        # map method getType to java getClass 
    345345        # C#'s typeof(X) is X.getType in Cobra. 
    346346        #existing = .declForName('getClass') to BoxMember 
    347347        #overload = MemberOverload(existing) 
    348348        #.registerOverload(overload) 
    349349        meth = Method(TokenFix.empty, TokenFix.empty, this, 'getType', List<of Param>(), .compiler.typeTypeProxy, nil, ['shared'], AttributeList(), 'Returns the Type instance that defines this type.') 
    350         meth.sharedMethodBacking = 'getClass'  
     350        meth.aliasedMethodBacking = 'getClass'  
    351351        #meth.sharedMethodBackingIsAlias = true # not static 
    352352        #overload.addMember(meth) 
    353353        .addDecl(meth) 
     
    398398            if (lastDecl to Object).getType.getProperty('ParentBox')  # CC: if lastDecl responds to (get parentBox as Box?) 
    399399                lastDecl.parentBox = this 
    400400 
    401  
     401    def _isStaticConstant( fi as JavaFieldInfo) as bool 
     402        return fi.isStatic or fi.name == fi.name.toUpper 
     403         
    402404    def _scanJvmFields 
    403405        for fieldInfo in _jvmType.getFields 
    404406            #if fieldInfo.declaringType is not _jvmType, continue 
    405407            if fieldInfo.isDefault, continue    # pkgprivate 
    406408            if fieldInfo.isPrivate, continue 
    407             name = Utils.cobraNameForNativeMemberName(fieldInfo.name) 
     409            # Unlike C# leave all static constant fieldnames ((mostly) upcase) as is 
     410            name = if( _isStaticConstant(fieldInfo), fieldInfo.name, Utils.cobraNameForNativeMemberName(fieldInfo.name)) 
    408411            type = _jvmMemberTypeResultProxy(fieldInfo, fieldInfo.type) 
    409412            attrs = AttributeList() 
    410413            if fieldInfo.isProtected 
     
    490493            if propInfo.isWritable 
    491494                prop.makeSetPart(TokenFix.empty) 
    492495            if _declsByName.containsKey(prop.name) # for            # Double.naN 
    493                 print 'DUP name exists already for property "[prop.name]" on', /#_declsByName[prop.name],#/ .name 
     496                # unfortunately its common for java libs to use method length() rather than getLength() 
     497                # lose this when enable postSigFixups handling 
     498                if prop.name <> 'length' 
     499                    print 'DUP name exists already for property "[prop.name]" on', /#_declsByName[prop.name],#/ .name 
    494500                return # just drop the property; field or method still available 
    495501            .addDecl(prop) 
    496502 
  • Source/BackEndJvm/JvmBackEnd.cobra

     
    4141            'bool'  :  'Java.Lang.Boolean',  # boolean 
    4242            'char'  :  'Java.Lang.Character',# char 
    4343            'decimal': 'Java.Lang.Decimal', #  virtualised -> Double 
     44            'float':   'Java.Lang.Float',   # float  
     45            'float32': 'Java.Lang.Float',   # float  
     46            'float64': 'Java.Lang.Double',  # double     
    4447            'single':  'Java.Lang.Float',   # float  
    4548            'double':  'Java.Lang.Double',  # double     
    4649            'sbyte' :  'Java.Lang.Byte',    # byte 
     
    169172    def cobraNameForNativeBoxName(nativeBoxName as String) as String is override 
    170173        return JvmTypeProxy.cobraNameForJvmBoxName(nativeBoxName) 
    171174     
     175    def isRunnableFile( fullExeFileName as String) as bool is override 
     176        """Test if filename is runnable ( vs a library or something else) """ 
     177        return fullExeFileName.endsWith('.class') or fullExeFileName.endsWith('.jar') 
     178 
    172179    # Types 
    173180    get objectTypeProxy as AbstractTypeProxy  is override 
    174181        """Type proxy for BE root of Object hierarchy.""" 
  • Source/BackEndJvm/JavaCompilationMessage.cobra

     
    1717    var _fileName as String? 
    1818    var _lineNum as int? 
    1919    var _isError as bool 
    20  
     20    var _lpad = -1 
     21     
    2122    cue init(line as String, compiler as Compiler) 
    2223        require not .willSkipMessage(line) 
    2324        base.init(line) 
     
    3536        _message = _cleanUp(line) 
    3637 
    3738    def append(line as String, compiler as Compiler) 
    38         line = line.trim 
     39        #line = line.trim 
     40        if _lpad == -1 
     41            lineTrim = line.trimStart 
     42            _lpad = line.length - lineTrim.length 
     43            line = line.trim 
     44        else if line.trim == '^' 
     45            line = line[_lpad:] 
    3946        _message += '\n >: ' + line 
    4047        if System.Text.RegularExpressions.Regex.isMatch(line, r'// \d+\s*$') 
    4148            lidx = line.lastIndexOf('//') 
  • Source/BackEndJvm/JavaGenerator.cobra

     
    178178    def _parseJavaCompilerOutput(output as String) 
    179179        jcm as JavaCompilationMessage? = nil 
    180180        for line in output.split(c'\n') 
    181             line = line.trim 
    182             if not line.length, continue 
     181            line0 = line.trim 
     182            if not line0.length, continue 
    183183            if JavaCompilationMessage.willSkipMessage(line) 
    184184                if jcm, jcm.append(line, this) 
    185185                continue 
     
    511511        return .fullName + .javaSuffix 
    512512 
    513513    get javaQualifier as String 
    514         ensure result.endsWith('.') 
    515         # TODO : Fix this with correct Namespace setup for java 
    516         #if .fullName == 'System' 
    517         #   return 'java.lang.' 
     514        ensure result.endsWith('.') or result.length == 0 
     515        # suppress naming of 'global' default namespace 
     516        if .fullName.toLower == 'global' 
     517            return '' 
    518518        javaName =  .fullName.toLower # java idiom is all lowercase for packages 
    519519        return  javaName + .javaSuffix + '.' 
    520520     
     
    19141914        .writeJavaSetLine(sw) 
    19151915        .writeJavaDef(sw) 
    19161916 
    1917  
    19181917class AssertStmt is partial 
    19191918 
    19201919    def writeJavaDef(sw as CurlyWriter) 
     
    19221921        if not .compiler.options.boolValue('include-asserts') 
    19231922            return 
    19241923        sw.write('if (cobra.lang.CobraCore._willCheckAssert') 
    1925         # TODO - implement cobra assertions - needs cobra assertException + Sourcesite 
    1926         /#  
     1924          
    19271925        sw.write(' && !') 
    19281926        _expr.writeJavaDef(sw) 
    19291927        sw.write(')\n') 
    19301928        sw.indent 
    19311929         
    1932         # TODO later Implement SourceSite and CobraLang AssertException  
    19331930        sw.write('throw new cobra.lang.AssertException([.javaSourceSite], ') 
    19341931        _expr.writeJavaBreakdown(sw) 
    19351932        sw.write('[.javaThis], ') 
     
    19391936            sw.write('null') 
    19401937        sw.write(');\n') 
    19411938        sw.dedent 
    1942         #/ 
    19431939         
     1940        /# 
    19441941        # use java asserts initially at least 
    19451942        sw.write(')\n') 
    19461943        sw.indent 
     
    19621959            _info.writeJavaDef(sw) 
    19631960        sw.write(';\n') 
    19641961        sw.dedent 
     1962        #/ 
    19651963 
    1966  
    19671964class BlockStmt is partial 
    19681965 
    19691966    def writeJavaDef(sw as CurlyWriter) 
     
    20942091 
    20952092 
    20962093class OldForNumericStmt is partial 
     2094    # We dont support this in Java 
    20972095 
    2098     def writeJavaDef(sw as CurlyWriter) 
     2096    def writeJavaDef(sw as CurlyWriter) is override 
     2097        varName = _var.javaName 
     2098        sw.write('Error-Old-Numeric-Form-unsupported;\n') 
     2099        sw.write('// Old Numeric For form is obsolete and not supported - convert cobra code to new form "for [varName] in start : stop : step "\n') 
     2100        sw.write('// Should become something like "for [varName] in ') 
     2101        _start.writeJavaDef(sw) 
     2102        sw.write(':') 
     2103        _stop.writeJavaDef(sw) 
     2104        if _step 
     2105            sw.write(':') 
     2106            _step.writeJavaDef(sw, false)            
     2107        sw.write('"\n') 
     2108        /# 
    20992109        base.writeJavaDef(sw) 
    21002110        varName = _var.javaName 
    21012111        trackLocals = .compiler.willTrackLocals 
     
    21292139                else, sw.write('[varName]--') 
    21302140        sw.write(')') 
    21312141        _block.writeJavaDef(sw) 
     2142        #/ 
    21322143 
    2133  
    21342144class ForNumericStmt is partial 
    21352145 
    21362146    def writeJavaDef(sw as CurlyWriter) 
     
    23752385                sw.write(';\n') 
    23762386        else 
    23772387            sw.write('return;\n') 
     2388             
     2389class TraceStmt 
     2390    is partial 
    23782391 
     2392    pass 
    23792393 
     2394 
     2395class TraceLocationStmt 
     2396    is partial 
     2397 
     2398    def writeJavaDef(sw as CurlyWriter) 
     2399        base.writeJavaDef(sw) 
     2400        if .includeTraces 
     2401            sw.write('CobraLangInternal.CobraCore.Tracer.Trace([.javaSourceSite]);\n') 
     2402 
     2403 
     2404class TraceAllStmt 
     2405    is partial 
     2406 
     2407    def writeJavaDef(sw as CurlyWriter) 
     2408        base.writeJavaDef(sw) 
     2409        if .includeTraces 
     2410            sw.write('CobraLangInternal.CobraCore.Tracer.Trace([.javaSourceSite], "this", [_codePart.javaThis]') 
     2411            for param in _codePart.params 
     2412                sw.write(', "[param.name]", [param.javaName]') 
     2413            for local in _codePart.locals 
     2414                sw.write(', "[local.name]", [local.javaName]') 
     2415            sw.write(');\n') 
     2416 
     2417 
     2418class TraceExprsStmt 
     2419    is partial 
     2420 
     2421    def writeJavaDef(sw as CurlyWriter) 
     2422        base.writeJavaDef(sw) 
     2423        if .includeTraces 
     2424            sw.write('CobraLangInternal.CobraCore.Tracer.Trace([.javaSourceSite]') 
     2425            sep = ', ' 
     2426            for expr in _exprs 
     2427                sw.write('[sep][Utils.javaStringLiteralFor(expr.toCobraSource)][sep]') 
     2428                expr.writeJavaDef(sw, false) 
     2429            sw.write(');\n') 
     2430             
     2431 
     2432class UsingStmt 
     2433    is partial 
     2434 
     2435    def writeJavaDef(sw as CurlyWriter) 
     2436        base.writeJavaDef(sw) 
     2437        name = _var.javaName 
     2438        sw.write('// using - needs work\n') 
     2439        # should extend this so takes an initialisation block rather than single initExpr 
     2440        sw.write('try ') 
     2441        sw.write('[name] = ') 
     2442        _initExpr.writeJavaDef(sw) 
     2443        sw.write(';\n') 
     2444        _block.writeJavaDef(sw) 
     2445         
     2446        # by hand ( w/o java7 
     2447        if false 
     2448            sw.write('[name] = ') 
     2449            _initExpr.writeJavaDef(sw) 
     2450            sw.write(';try\n') 
     2451            _block.writeJavaDef(sw) 
     2452            sw.write('finally {\n') 
     2453            sw.indent 
     2454            if _var.type.isReference 
     2455                sw.write('if ([name]!=null) { ((java.lang.AutoCloseable)[name]).close(); [name] = null; }\n') 
     2456            else 
     2457                sw.write('((java.lang.AutoCloseable)[name]).close();\n') 
     2458            sw.dedentAndWrite('}\n') 
     2459 
     2460 
     2461class WhileStmt 
     2462    is partial 
     2463 
     2464    def writeJavaDef(sw as CurlyWriter) 
     2465        base.writeJavaDef(sw) 
     2466        sw.write('while (') 
     2467        _expr.writeJavaDef(sw, false) 
     2468        sw.write(')') 
     2469        _block.writeJavaDef(sw) 
     2470 
     2471 
     2472class PostWhileStmt 
     2473    is partial 
     2474 
     2475    def writeJavaDef(sw as CurlyWriter) is override 
     2476        # base.writeSharpDef(sw) - don't generate the other form of while loop 
     2477        sw.write('do') 
     2478        _block.writeJavaDef(sw, false) 
     2479        sw.dedent 
     2480        sw.write('} while (') 
     2481        _expr.writeJavaDef(sw, false) 
     2482        sw.write(');\n') 
     2483         
     2484class YieldStmt 
     2485    is partial 
     2486 
     2487    pass 
     2488 
     2489 
     2490class YieldBreakStmt 
     2491    is partial 
     2492 
     2493    def writeJavaDef(sw as CurlyWriter) 
     2494        base.writeJavaDef(sw) 
     2495        sw.write('yield break;\n') 
     2496 
     2497 
     2498class YieldReturnStmt 
     2499    is partial 
     2500 
     2501    def writeJavaDef(sw as CurlyWriter) 
     2502        base.writeJavaDef(sw) 
     2503        ensurePart = .compiler.curCodeMember.ensurePart 
     2504        willEnsure = ensurePart and ensurePart.willGenerateCode 
     2505        if willEnsure 
     2506            sw.write('_lh_canEnsure = true;\n') 
     2507        if _expr 
     2508            backEndResultVarName = .compiler.curCodeMember.backEndResultVarName 
     2509            if willEnsure and backEndResultVarName.length 
     2510                # TODO: resolve yield return with ensure 
     2511                # sw.write('yield return [backEndResultVarName]=') 
     2512                # so for now: 
     2513                sw.write('yield return ') 
     2514                _expr.writeJavaDefInContext(sw) 
     2515                sw.write(';\n') 
     2516            else 
     2517                sw.write('yield return ') 
     2518                _expr.writeJavaDefInContext(sw) 
     2519                sw.write(';\n') 
     2520        else 
     2521            sw.write('yield return;\n') 
     2522 
     2523         
     2524             
     2525             
     2526 
    23802527## 
    23812528## Expressions 
    23822529## 
     
    24432590        sw.write(';\n') 
    24442591 
    24452592    def writeJavaBreakdown(sw as CurlyWriter) 
    2446         sw.write(r'new object[] { 0') 
     2593        sw.write(r'new Object[] { 0') 
    24472594        .writeJavaBreakdownItems(sw) 
    24482595        sw.write('}, ') 
    24492596 
     
    24592606    def writeJavaDefForBreakdown(sw as CurlyWriter) 
    24602607        .writeJavaDef(sw) 
    24612608 
    2462  
     2609    def _mapJavaTypeToClass(typeName as String, defaultSuffix as String) as String 
     2610        # support for getClass and primitive mapping 
     2611        if typeName == 'int', typeName = 'Integer.TYPE' 
     2612        else if typeName == 'bool', typeName = 'Boolean.TYPE' 
     2613        else if typeName == 'char', typeName = 'Character.TYPE' 
     2614        else, typeName = typeName + defaultSuffix 
     2615        #else if typeName == 'byte', typeName = 'Byte.TYPE' 
     2616        #else if typeName == 'sbyte', typeName = 'Byte.TYPE' 
     2617        #else if typeName == 'short', typeName = 'Short.TYPE' 
     2618        #else if typeName == 'int16', typeName = 'Short.TYPE' 
     2619        #else if typeName == 'int32', typeName = 'Integer.TYPE' 
     2620        #else if typeName == 'long', typeName = 'Long.TYPE' 
     2621        #else if typeName == 'int64', typeName = 'Long.TYPE' 
     2622        #else if typeName == 'float', typeName = 'Float.TYPE' 
     2623        #else if typeName == 'float32', typeName = 'Float.TYPE' 
     2624        #else if typeName == 'double', typeName = 'Double.TYPE' 
     2625        #else if typeName == 'float64', typeName = 'Double.TYPE' 
     2626        #else, typeName = typeName + defaultSuffix 
     2627        return typeName 
     2628         
    24632629class NameExpr is partial 
    24642630 
    24652631    get asJava as String 
     
    25602726 
    25612727    def writeJavaDef(sw as CurlyWriter, parens as bool) is override 
    25622728        # recall that this cannot be the right side of "foo.bar" since that is a MemberExpr 
    2563         javaRef = .javaQualification + .javaName 
    2564         if _requiresGetClass, javaRef = javaRef + '.getClass()' 
    2565         #print 'Dbg: IdExpr::', javaRef 
    2566         sw.write(javaRef) 
    2567  
     2729        name = .javaQualification + .javaName 
     2730        if _requiresGetClass  
     2731            name = _getClass(name) 
     2732        #name = _mapJavaTypeToClass(name, '') 
     2733        sw.write(name) 
     2734         
    25682735    get javaQualification as String 
    25692736        qual = '' 
    25702737        if .definition inherits IVar 
     
    25732740        else 
    25742741            pn = .definition.parentNameSpace 
    25752742            if pn, qual = pn.javaQualifier 
    2576         #print 'Dbg: IdExpr.qual::', qual 
    25772743        return qual 
    25782744         
    25792745    get javaName as String 
     
    25912757        if not .isTypeReference, return false 
    25922758        superNode = .superNode 
    25932759        if superNode inherits DotExpr, return false 
    2594         if superNode inherits InheritsExpr, return false 
     2760        #if superNode inherits InheritsExpr, return false 
    25952761        if superNode inherits PostCallExpr 
    25962762            if superNode.expr is this 
    25972763                return false 
     
    26142780    def writeJavaDefForBreakdown(sw as CurlyWriter) is override 
    26152781        name = .javaQualification + .javaName 
    26162782        # _requiresGetClass may return false, but in the java def breakdown, .getClass is always required 
    2617         if .isTypeReference, name = name + '.getClass()' 
     2783        if .isTypeReference, name = _getClass(name) 
     2784        #name = _mapJavaTypeToClass(name, '') 
    26182785        sw.write(name) 
     2786         
     2787    def _getClass(name as String) as String 
     2788        if .javaName.endsWith('.TYPE') # primitive already typed 
     2789            return name 
     2790        if not .javaName.startsWithLowerLetter  
     2791            name = name + '.class' 
     2792        else 
     2793            name = _mapJavaTypeToClass(name, '.getClass()') 
     2794        return name 
     2795         
    26192796 
    2620  
    26212797class IfExpr is partial 
    26222798 
    26232799    def writeJavaDef(sw as CurlyWriter, parens as bool) is override 
     
    26952871        if parens, sw.write(')') 
    26962872 
    26972873    def _lookupReadIndexer as JavaFieldInfo? 
    2698         nt = JvmNativeType.nativeType(_target.type) 
     2874        nt = JvmNativeType.nativeType(_target.type.nonNil) 
     2875        #print 'dbg', _target.type.nonNil, nt 
    26992876        if nt  
    27002877            ntIdxr = nt.indexer 
    27012878            if ntIdxr and ntIdxr.isReadable 
     
    27312908        sw.write('(') 
    27322909        _expr.writeJavaDef(sw) 
    27332910        sw.write(')') 
    2734         sw.write('==null') 
     2911        sw.write('== null') 
    27352912        if parens, sw.write(')') 
    27362913 
    27372914    def writeJavaBreakdownItems(sw as CurlyWriter) 
     
    27462923        sw.write('(') 
    27472924        _expr.writeJavaDef(sw) 
    27482925        sw.write(')') 
    2749         sw.write('!=null') 
     2926        sw.write('!= null') 
    27502927        if parens, sw.write(')') 
    27512928 
    27522929    def writeJavaBreakdownItems(sw as CurlyWriter) 
     
    27992976            #sw.write('typeof(') 
    28002977            sw.write('(') 
    28012978            sw.write(javaRef) 
    2802             sw.write('.getClass()') 
     2979            sw.write('.getClassX()') 
    28032980            sw.write(')') 
    2804         else 
     2981        else if _requiresRawType() 
     2982            sw.write(javaRef)  # might need to map cobratypes like [u]int{8,16,32,64} 
     2983        else     
     2984            javaRef = _mapJavaTypeToClass(javaRef, '.class') 
    28052985            sw.write(javaRef) 
    28062986 
    28072987    def _requiresGetClass as bool 
    28082988        return false    # may need to extend later 
    28092989         
     2990    def _requiresRawType as bool 
     2991        # In Java some places require class refs amd the Type of any primitives being used 
     2992        superNode = .superNode 
     2993        if superNode is nil 
     2994            return false 
     2995        if superNode inherits BinaryOpExpr   
     2996            if this is superNode.right 
     2997                if superNode inherits InheritsExpr 
     2998                    return false 
     2999        return true 
     3000 
    28103001/#  def _requiresTypeOf as bool 
    28113002        # Cobra never requires that you wrap a type reference in typeof(Foo). 
    28123003        # C# requires typeof() in a variety of circumstances and won't accept it in a variety of others. 
     
    28313022    def writeJavaDefForBreakdown(sw as CurlyWriter) is override 
    28323023        #requiresTypeOf = _requiresTypeOf # using C# version currently - chop ? 
    28333024        #if not requiresTypeOf, sw.write('typeof(') 
    2834         .writeJavaDef(sw) 
     3025        #.writeJavaDef(sw) 
    28353026        #if not requiresTypeOf, sw.write(')') 
     3027         
     3028        # Handle mapping primitives to their classes 
     3029        #javaRef = _containedType.javaRef  
     3030        javaRef = _mapJavaTypeToClass(_containedType.javaRef, '.class') 
     3031        sw.write(javaRef) 
    28363032 
    28373033         
    28383034class UnaryOpExpr 
     
    33143510        javaNot = if(_op=='OR', '', '!') 
    33153511        sw.write(', [src], new cobra.lang.CobraDirectString([javaNot]') 
    33163512        _left.writeJavaDefForBreakdown(sw) 
    3317         sw.write(' ? "(short-circuited)" : cobra.lang.CobraCore.ToTechString(') 
     3513        sw.write(' ? "(short-circuited)" : cobra.lang.CobraCore.toTechString(') 
    33183514        _right.writeJavaDefForBreakdown(sw) 
    33193515        sw.write('))') 
    33203516 
     
    36103806                            sep = ', ' 
    36113807                    sw.write(')') 
    36123808                    return 
     3809                aliasedName = _dotRightExpr.definition.aliasedMethodBacking 
    36133810            # handle static typing 
    36143811            # don't write 'this' for shared members 
    36153812            writeThis = true 
     
    36263823                    _left.writeJavaDef(sw, not _left inherits DotExpr) 
    36273824                sw.write('.') 
    36283825            #print 'Dbg: dotExpr::', _left.toCobraSource, _right.toCobraSource 
    3629             _right.writeJavaDef(sw, false) 
     3826            if aliasedName 
     3827                sw.write(aliasedName+'()')  # FTM assume no args 
     3828            else 
     3829                _right.writeJavaDef(sw, false) 
    36303830            if didSetInInitCall 
    36313831                Stmt.inInitCall = false 
    36323832 
     
    36383838    is partial 
    36393839                 
    36403840    def _writeJavaDef(sw as CurlyWriter) is override 
     3841        #_left.writeJavaDef(sw) 
     3842        #sw.write(' instanceof ') 
     3843        #_right.writeJavaDef(sw, false) 
     3844 
     3845        # Compiler generates error with instanceof for non intersecting instance and Type so 
     3846        # instead use runtime instance lookup 
     3847        #  instead of 'e instanceof T'  becomes 'T.class.isInstance(e)' 
     3848        _right.writeJavaDef(sw, false) 
     3849        #sw.write('.class.isInstance(') 
     3850        sw.write('.isInstance(') 
    36413851        _left.writeJavaDef(sw) 
    3642         sw.write(' instanceof ') 
    3643         _right.writeJavaDef(sw, false) 
     3852        sw.write(' )') 
    36443853 
    36453854 
    36463855class ToExpr is partial 
  • Source/TestifyRunner.cobra

     
    254254        options['debugging-tips'] = false 
    255255        options['embed-run-time'] = false 
    256256        options['verbosity'] = 2 
    257         # trace options 
     257        options['back-end'] = .options['back-end'] 
     258        #trace options 
    258259        return options to ! 
    259260 
    260261    def testifyFinish(message as String) 
     
    385386 
    386387        _statusWriter.writeLine('([_statusCount]) [baseName]') 
    387388        _statusCount += 1 
     389         
    388390        assert File.exists(baseName) 
    389  
    390391        source = File.readAllText(baseName) 
    391392 
    392393        print 
     
    470471                continue 
    471472 
    472473            if firstLineInsensitive.startsWith('#.require.') 
    473                 rtPlatform  = CobraCore.runtimePlatform 
     474                rtPlatform  = options['back-end'] # wrongly wuz CobraCore.runtimePlatform 
    474475                what = firstLineInsensitive[10:] 
    475476                branch what 
    476477                    on 'mono' 
     
    738739        return 1 
    739740 
    740741    def _testifyRun(c as Compiler) as int 
    741         if not c.fullExeFileName.endsWith('.exe') 
     742        if not c.backEnd.isRunnableFile(c.fullExeFileName) 
     743            # below assumes created file placed in cwd 
    742744            if File.exists(c.fullExeFileName) 
    743745                print 'Produced file "[c.fullExeFileName]" as expected.' 
    744746                return 1 
     
    748750                return 0 
    749751        else 
    750752            print 'Run:' 
    751             if .verbosity >= 1 
    752                 print 'c.fullExeFileName = "[c.fullExeFileName]"' 
     753            if .verbosity >= 1, print 'c.fullExeFileName = "[c.fullExeFileName]"' 
    753754            p = c.runProcess 
    754             if .verbosity >= 2 
    755                 print '[p.startInfo.fileName] [p.startInfo.arguments]' 
     755            if .verbosity >= 2, print '[p.startInfo.fileName] [p.startInfo.arguments]' 
    756756            output = CobraCore.runAndCaptureAllOutput(p).trim 
    757757 
    758758            print 'Output:' 
  • Tests/100-basics/034j-set-property.cobra

     
    1 # .require. jvm 
     1#.require. jvm 
    22namespace Test 
    33    class Test 
    44        def main is shared 
  • Tests/100-basics/052-float.cobra

     
    1 # .require. clr 
     1#.require. clr 
    22# This is clr specific re inheritance of literals and floats  
    33namespace Test 
    44     
  • Tests/100-basics/110j-while.cobra

     
     1#.require. jvm 
     2@platform jvm 
     3namespace Test 
     4 
     5    class Test 
     6 
     7        def main 
     8 
     9            # Note: You wouldn't actually use while loops for counting, 
     10            # but counting makes a good basic test. 
     11 
     12            i as int = 0 
     13            while i < 100 
     14                i += 1 
     15            assert i == 100 
     16 
     17            i = 0 
     18            while i > 0 
     19                i = -1 
     20            assert i == 0 
     21 
     22            i = 0 
     23            post while i > 0 
     24                i = -1 
     25            assert i == -1 
     26 
     27            i = 100 
     28            while i 
     29                i -= 1 
     30            assert i == 0 
     31 
     32            # 2006-12-16: there was a bug where post while generates both a while loop and a do-while loop 
     33            count = 0 
     34            i = 10 
     35            post while i > 0 
     36                i -= 1 
     37                count += 1 
     38            assert count == 10 
     39 
     40            random = Random() 
     41            a = 1 
     42            while a <= 3 
     43                post while .check(a, b)  # using local var `b` which is first assigned below 
     44                    b = random.nextInt(3) + 1 
     45                a += 1 
     46     
     47        def check(a as int, b as int) as bool 
     48            assert b <> 0  # verifies that the while condition is not checked immediately 
     49            return a <> b 
  • Tests/100-basics/030-hello-world.cobra

     
    1 # .require. clr 
     1#.require. clr 
    22namespace Test 
    33    class Test 
    44        def main 
  • Tests/100-basics/080-inherits.cobra

     
     1#.require. clr 
    12namespace Test 
    23     
    34    class Test 
  • Tests/100-basics/030j-hello-world1.cobra

     
    1 # .require. jvm 
     1#.require. jvm 
    22namespace Test 
    33    class Test 
    44        def main is shared 
  • Tests/100-basics/032-get-property-static.cobra

     
    1 # .require. clr 
     1#.require. clr 
    22namespace Test 
    33    class Test 
    44        def main 
  • Tests/100-basics/042-int.cobra

     
    4444            assert 2*3 + 4*5 == 26 
    4545            assert (2*3 + 4*5) == 26 
    4646 
    47             # minValue and maxValue 
    48             x = 2_147_483_647 
    49             x = -2_147_483_647  # to-do: should end in 8 
    50             assert int.minValue <= -2_147_483_647  # to-do: should end in 8 
    51             assert int.maxValue >= 2_147_483_647 
  • Tests/100-basics/080j-inherits.cobra

     
     1#.require. jvm 
     2namespace Test 
     3     
     4    class Test 
     5         
     6        def main 
     7            is shared 
     8             
     9            # string lits make for good tests 
     10            assert 'aoeu' inherits String  # .warning. always 
     11# Another Mono bug. New 1.2.6 (or maybe 1.2.5):   https://bugzilla.novell.com/show_bug.cgi?id=350977 
     12            assert 'aeou' inherits Object   # .warning. always   
     13            assert not ('aoeu' inherits Void)  # .warning. never 
     14            assert not ('aoeu' inherits Integer)  # .warning. never 
     15 
     16            # primitives 
     17            assert 5 inherits int  # .warning. always 
     18            assert 5 inherits Object  # .warning. always 
     19            assert not (5 inherits String)  # .warning. never 
     20            assert 5 inherits Integer  # .warning. always 
     21             
     22            assert true inherits bool  # .warning. always 
     23            assert true inherits Object  # .warning. always 
     24            assert not (true inherits String)  # .warning. never 
     25            assert true inherits Boolean  # .warning. never 
     26 
     27            # try a method                       
     28            assert System.getenv('PATH') inherits Object  # .warning. can just check for not nil 
     29            assert System.getenv('PATH') inherits String  # .warning. can just check for not nil 
     30            assert not (System.getenv('PATH') inherits Thread)  # .warning. never 
     31 
  • Tests/100-basics/130-for-enumerable.cobra

     
    11namespace Test 
    22 
    33    class Test 
     4        shared 
     5            var fakeCommandLineArgs as List<of String> = ['130-for-enumerable' ] 
    46 
    57        def main 
    68            is shared 
    79 
    810            count as int = 0 
    911 
    10             for arg as String in Environment.getCommandLineArgs 
     12            for arg as String in .fakeCommandLineArgs 
    1113                # Console.WriteLine(arg) 
    1214                count += 1 
    1315 
    1416            assert count>0 
    1517 
    16             for arg in Environment.getCommandLineArgs 
     18            for arg in .fakeCommandLineArgs 
    1719                count += 1 
    1820 
    1921            CobraCore.noOp(arg) 
     
    2224        def more 
    2325            s = 'aoeu' 
    2426            # reuse a local 
    25             for s in Environment.getCommandLineArgs 
     27            for s in .fakeCommandLineArgs 
    2628                assert s  # .warning. always 
    2729 
    2830            .foo('aoeu') 
     
    3133        def foo(s as String) 
    3234            assert s == 'aoeu' 
    3335            # reuse an arg: 
    34             for s in Environment.getCommandLineArgs 
     36            for s in .fakeCommandLineArgs 
    3537                assert s  # .warning. always 
    3638 
    3739        var _b as String = 'aoeu' 
     
    3941        def bar 
    4042            assert _b == 'aoeu' 
    4143            # reuse a class var: 
    42             for _b in Environment.getCommandLineArgs 
     44            for _b in .fakeCommandLineArgs 
    4345                assert _b  # .warning. always 
  • Tests/100-basics/042-int-minValue.cobra

     
     1#.require. clr 
     2@platform clr 
     3namespace Test 
     4 
     5    class Test 
     6 
     7        def main 
     8            is shared 
     9 
     10            # minValue and maxValue 
     11            x = 2_147_483_647 
     12            x = -2_147_483_647  # to-do: should end in 8 
     13            assert int.minValue <= -2_147_483_647  # to-do: should end in 8 
     14            assert int.maxValue >= 2_147_483_647 
  • Tests/100-basics/033j-get-property-instance.cobra

     
    1 # .require. jvm  
     1#.require. jvm  
    22namespace Test 
    33    class Test 
    44        def main 
  • Tests/100-basics/052j-float.cobra

     
    1 # .require. jvm 
     1#.require. jvm 
    22namespace Test 
    33     
    44    class Test 
     
    1818            ff = Float(1.0f) 
    1919            assert ff inherits Float  # .warning. is always 
    2020            ii = Integer(1) 
    21             #assert not (ii inherits Float)  # .warning. is never 
     21            #assert not (ii inherits Float)  # . warning. is never 
    2222                # above also throws compiler error 
    2323            o as Object = ii 
    2424            assert not (o inherits Float)   
  • Tests/100-basics/030j-hello-world.cobra

     
    1 # .require. jvm 
     1#.require. jvm 
    22namespace Test 
    33    class Test 
    44        def main is shared 
  • Tests/100-basics/110-while.cobra

     
     1#.require. clr 
     2@platform clr 
    13namespace Test 
    24 
    35    class Test 
  • Tests/100-basics/065-indexing.cobra

     
     1#.require. clr 
    12namespace Test 
    23     
    34    class Test 
  • Tests/100-basics/034-set-property.cobra

     
    1 # .require. clr 
     1#.require. clr 
    22namespace Test 
    33    class Test 
    44        def main 
  • Tests/100-basics/120-for-numeric.cobra

     
     1#.require. clr 
     2@platform clr 
    13# numeric for loops follow the half-open interval 0 .. N-1 which lines up with the zero indexing used in .NET for arrays, lists and strings. 
    24# see also Dijkstra's comments at http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF 
    35namespace Test 
  • Tests/100-basics/065j-indexing.cobra

     
     1#.require. jvm 
     2namespace Test 
     3     
     4    class Test 
     5         
     6        def main 
     7            is shared 
     8 
     9            assert CobraCore.commandLineArgs[0].length 
     10            assert CobraCore.commandLineArgs[0]<>'roembrjkxte,.nune,.ntokmbk' 
     11            s as String = CobraCore.commandLineArgs[0] 
     12            t as String = CobraCore.commandLineArgs[0] 
     13            s = t 
     14            assert s==t 
     15            assert CobraCore.commandLineArgs.get(0) == s 
  • Tests/100-basics/122-for-numeric.cobra

     
    5555            count = 0 
    5656            for x in 1 : 10 
    5757                r = x 
    58                 continue 
     58                if x, continue # need conditional, some platforms err on dead code 
    5959                count += 1 
    6060            assert r == 9 
    6161            assert count == 0