Code Monkey home page Code Monkey logo

cs2j's People

Contributors

twiglet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cs2j's Issues

override -> @override

@OverRide
The C# methods declared as override could be declared in Java as @OverRide. Not mandatory in Java, but helpful.

You are right, at the moment we don't support annotations on the C# or
Java side. That is on our list of things to fix.

can't write a constructor for KeyValuePair

Yeah, I have a Dictionary<KVP<T,K>,V> I'm populating, so I have to create the KVPs.

I'll make a new type in c# and change the translation file. Shouldn't hurt anything if that's just a sub-class of KVP on c# side, right?

Since you're scanning everything for context, might it be possible eventually to support different translation templates to be applied based on usage? So. if "new" is applied to this type anywhere, it's a KVPsupport, otherwise it's an entry. Naturally all references would have to agree.

This particular case isn't a big deal, but I wonder if there are other C# / java differences that could help with?

-Ben

On Thu, Feb 2, 2012 at 4:15 AM, Kevin Glynn [email protected] wrote:

The Object.Equals imp is good.

Unfortunately the KeyValuePair change is going to break stuff that I want to keep, e.g. at the moment:

static IDictionary<int, IDictionary<String, int>>
Rename(IDictionary<Set, int> renamer,
IDictionary<Set, IDictionary<String, Set>> trans) {
IDictionary<int, IDictionary<String, int>> newtrans =
new Dictionary<int, IDictionary<String, int>>();
foreach (KeyValuePair<Set, IDictionary<String, Set>> entry
in trans) {
Set k = entry.Key;
IDictionary<String, int> newktrans = new Dictionary<String, int>();
foreach (KeyValuePair<String, Set> tr in entry.Value)
newktrans.Add(tr.Key, renamer[tr.Value]);
newtrans.Add(renamer[k], newktrans);
}
return newtrans;
}

translates to

static Map<Integer,Map<String,Integer>> rename(Map<Set,Integer> renamer, Map<Set,Map<String,Set>> trans) throws Exception {
Map<Integer,Map<String,Integer>> newtrans = new HashMap<Integer,Map<String,Integer>>();
for (Entry<Set,Map<String,Set>> entry : trans.entrySet())
{
Set k = entry.getKey();
Map<String,Integer> newktrans = new HashMap<String,Integer>();
for (Entry<String,Set> tr : entry.getValue().entrySet())
newktrans.put(tr.getKey(), renamer.get(tr.getValue()));
newtrans.put(renamer.get(k), newktrans);
}
return newtrans;
}

but if we translate KVP to some new KVPSupport type then of course the built in Java types can't produce one of those.

What is the use case? I suppose you just want to create a pair? If so I think I might need you to create a pair type in your C#.

cheers

k

On 02 Feb 2012, at 00:36, Ben Clark wrote:

Please look this commit over when you get a chance, and see if you anticipate any trouble.

Or tweak to conform to your conventions.

https://github.com/RusticiSoftware/CS2JLibrary/commit/f116896fd821b08afae2696b82cd83a7f3b499f5

Ben Clark | http://scorm.com/tincan | +1 615.538.8550 | @ProjectTinCan

Exception when run mkit.bat

I am using ant 1.10.1 to run mkit.bat. I got the following error. Any hint will be appriciated

`[ant-antlr3] ANTLR Parser Generator Version 3.2 Sep 23, 2009 12:02:23
[ant-antlr3] D:\Bitbucket\cs2j-master\CSharpTranslator\src\CSharpParser\cs.g
[ant-antlr3] error(10): internal error: Can't get property indirectDelegates using method get/isIndirectDelegates from org.antlr.tool.Grammar instance : java.lang.NullPointerException
[ant-antlr3] java.util.Objects.requireNonNull(Objects.java:203)
[ant-antlr3] java.util.ArrayList.removeAll(ArrayList.java:689)
[ant-antlr3] org.antlr.tool.CompositeGrammar.getIndirectDelegates(CompositeGrammar.java:222)
[ant-antlr3] org.antlr.tool.Grammar.getIndirectDelegates(Grammar.java:2620)
[ant-antlr3] sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ant-antlr3] sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ant-antlr3] sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ant-antlr3] java.lang.reflect.Method.invoke(Method.java:498)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.invokeMethod(ASTExpr.java:564)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.rawGetObjectProperty(ASTExpr.java:515)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.getObjectProperty(ASTExpr.java:417)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.attribute(ActionEvaluator.java:351)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.expr(ActionEvaluator.java:136)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.templateApplication(ActionEvaluator.java:216)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.expr(ActionEvaluator.java:126)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:84)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
[ant-antlr3] org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.writeTemplate(ASTExpr.java:750)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:680)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.writeAttribute(ASTExpr.java:660)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:86)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
[ant-antlr3] org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.writeTemplate(ASTExpr.java:750)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:680)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.writeAttribute(ASTExpr.java:660)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:86)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
[ant-antlr3] org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.writeTemplate(ASTExpr.java:750)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:680)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.writeAttribute(ASTExpr.java:660)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:86)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
[ant-antlr3] org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.writeTemplate(ASTExpr.java:750)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:680)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.writeAttribute(ASTExpr.java:660)
[ant-antlr3] org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:86)
[ant-antlr3] org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
[ant-antlr3] org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
[ant-antlr3] org.antlr.codegen.CodeGenerator.write(CodeGenerator.java:1281)
[ant-antlr3] org.antlr.codegen.Target.genRecognizerFile(Target.java:94)
[ant-antlr3] org.antlr.codegen.CodeGenerator.genRecognizer(CodeGenerator.java:466)
[ant-antlr3] org.antlr.Tool.generateRecognizer(Tool.java:641)
[ant-antlr3] org.antlr.Tool.process(Tool.java:454)
[ant-antlr3] org.antlr.Tool.main(Tool.java:91)

BUILD FAILED
D:\Bitbucket\cs2j-master\CSharpTranslator\build\build.xml:174: ANTLR returned: 1

Total time: 4 seconds`

Doesn't support newer C#

Apparently this tool doesn't support the newer versions of C# for instance it doesnt support string interpolation ($)

Can't resolve against methods with varargs params

If you turn on option -warnings-resolve-failures=true you will see numerous failures. One case where we fail to resolve is when the method accepts variable number of arguments:

/Users/keving/svnrepos/ScormEngineNet/src/app/ScormEngine.Core/Logic/Web/Delivery/IntermediateRequest.cs(32) warning: Could not resolve method application of GetString against RusticiSoftware.ScormContentPlayer.Logic.IntegrationInterface

sort

Collections.sort
In C# we have sorted a list with
pps.Sort(new PostProfileComparer());
This was tranlated to
pps.Sort(new PostProfileComparer());
but in Java the Sort method does not exist. Needs to be translated to Collections.sort(pps, ...)

support java naming convenions

Method names
If you could propose a renaming scheme then we will add that as an option.
Well the renaming-scheme would be easy. It would only apply for C# methods (C# properties are already handled correctly by CS2J): If a (static or instance) method starts with a capital letter, then this capital letter is converted to a lower-case letter.
Examples of converted method names:
FilterJob => filterJob
CompareTo => compareTo
Check => check
Add => add
GetTextBlocks => getTextBlocks
RunAlgorithm => runAlgorithm
This would only lead to a problem if in a C# class both names are used, i.e. a name starting with capital and with lower letter:
public void RunAlgorithm() { .... }
private void runAlgorithm() { .... }
However, if C# conventions are followed, then all methods should start with capital letters anyway.

OK, we will add this too. Probably we can print a warning in this
case.

Not able to compile the code

Hi,

The source is missing the following classes:
Error 1 Source file '..\CSharpParser\csLexer.cs' could not be found \cs2j\CSharpTranslator\src\CS2JTranslator\CSC CS2JTranslator
Error 2 Source file '..\CSharpParser\csParser.cs' could not be found \cs2j\CSharpTranslator\src\CS2JTranslator\CSC CS2JTranslator
Error 3 Source file 'CS2JTransform\JavaMaker.cs' could not be found \cs2j\CSharpTranslator\src\CS2JTranslator\CSC CS2JTranslator
Error 4 Source file 'CS2JTransform\JavaPrettyPrint.cs' could not be found \cs2j\CSharpTranslator\src\CS2JTranslator\CSC CS2JTranslator
Error 5 Source file 'CS2JTransform\NetMaker.cs' could not be found \cs2j\CSharpTranslator\src\CS2JTranslator\CSC CS2JTranslator
Error 6 Source file 'CS2JTransform\TemplateExtracter.cs' could not be found \cs2j\CSharpTranslator\src\CS2JTranslator\CSC CS2JTranslator

What am I missing?

Thank you

NetMaker can't parse LINQ :(

For example:

var query =
from book in new AmazonServiceCall()
where
book.Title == "Hyperion" && book.Condition == BookCondition.All && book.Price < 15

                  select book;

cloning objects

Cloning
Cloning is not completely supported by CS2J. Method
public XxxDto Clone()
{
return ((XxxDto)MemberwiseClone());
}
Is converted to
public XxxDto Clone() throws Exception {
return ((XxxDto)MemberwiseClone());
}
I would have expected
public XxxDto clone() {
try {
return (XxxDto) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
I know, it is difficult as soon as the C# class has fields of a struct type.

Add Warnings if we generate methods with same name as existing methods

I was thinking of a case like this:

public class RenameTest {

    public string AMethod(object x) {
        return "AMethod has arg " + x.ToString();
    }

    public string aMethod(string s) {
        return "aMethod has string arg \"" + s + "\"";
    }

    public static void RNMain(string arg) {
        RenameTest rnObj = new RenameTest();
        Console.Out.WriteLine(rnObj.AMethod(arg));   // *******
    }   

}

After renaming then the starred line will call a different method because of the more specific overload.

As you say this can happen already with properties and setXXXXX methods. We will look into adding warnings if we detect this might happen.

cs2j enters an infinite loop when processing this class

Hello, The class pasted below causes the converter to enter an infinite loop. (However, 551 other classes were processed successfully, thank you for all your work!) I thought I would share the offending code so you could use it to investigate any potential bug, if desired.
Blake

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CSharpTools.Tools
{
///

   /// StringGroup
   /// This class provides utilities for manipulating a StringGroup.
   /// A StringGroup is a delimited string with a specific format, shown below. 
   /// These strings can contain a generically typed group of values.
   ///
   /// The format is designed to include delimiter characters around every value.
   /// That way, when searching for a specific value in a database, you can always include
   /// the delimiter character on both sides of the string to explicitly specify the length 
   /// of the results.
   /// 
   /// The format is enclosed in braces so that multiple string groups could be included in a 
   /// single string if desired.
   ///
   /// Values that contain the delimiter or brace characters will be escaped and unescaped as needed.
   /// 
   /// At the moment, this class does not modify new line or whitespace characters. 
   /// 
   /// String format examples:
   /// "{:1:2:3:4:}"
   /// "{:Red:Green:Blue:Yellow:}"
   /// </summary>


   static public class StringGroup
   {
       static private string delimiter = ":";
       /// <summary>


       /// leftBrace
       /// Contains the left brace character used by this class. 
       /// </summary>


       static private string leftBrace = "{";
       /// <summary>


       /// rightBrace
       /// Contains the right brace character used by this class. 
       /// </summary>


       static private string rightBrace = "}";
       /// <summary>


       /// delimiterEscape
       /// Contains the delimiter escape string used by this class.
       /// </summary>


       static private string delimiterEscape = "&#58;";
       /// <summary>


       /// leftBraceEscape
       /// Contains the left brace escape string used by this class.
       /// </summary>


       static private string leftBraceEscape = "&#123;";
       /// <summary>


       /// rightBraceEscape
       /// Contains the right brace escape string used by this class.
       /// </summary>


       static private string rightBraceEscape = "&#125;";
       const string emptyGroup = "{e}";
       /// <summary>
       /// GroupToList
       /// This accepts a string that is formatted as a group, and returns a 
       /// strongly typed list that contains the elements of the string.
       ///
       /// Example call:
       /// List{int} numbersList = StringGroupToList{int}(numbersGroup);
       /// </summary>
       static public List<T> GroupToList<T>(string stringGroup)
       {
           if (stringGroup == emptyGroup) { return new List<T>(); }
           List<T> result = new List<T>();
           stringGroup = Use.SafeSubString(stringGroup, 1, stringGroup.Length - 2);
           string[] stringArray = stringGroup.Split(delimiter[0]);
           int stop = stringArray.Length - 1;
           for (int i = 1; i < stop; ++i)
           {
               string element = stringArray[i];
               element = element.Replace(delimiterEscape, delimiter);
               element = element.Replace(leftBraceEscape, leftBrace);
               element = element.Replace(rightBraceEscape, rightBrace);
               dynamic elementDynamic;
               Type parameter = typeof(T);
               if (parameter == typeof(int))
               {
                   try { elementDynamic = Convert.ToInt32(element); }
                   catch (Exception)
                   { throw new Exception("Could not convert group element to integer in function StringGroupToList()."); }
               }
               else if (parameter == typeof(long))
               {
                   try { elementDynamic = Convert.ToInt64(element); }
                   catch (Exception)
                   { throw new Exception("Could not convert group element to long in function StringGroupToList()."); }
               }
               else
               {
                   elementDynamic = element;
               }
               result.Add(elementDynamic);
           }
           return result;
       }

       /// <summary>
       /// GroupFromList
       /// Returns a formatted string containing all of the list elements.
       /// The returned string is suitable for storing in a database record, and
       /// can also be converted back into a list through the reverse function.
       /// Any null values in the list are included as empty strings.
       /// Any values containing the pipe character will be escaped.
       /// </summary>
       static public string GroupFromList<T>(List<T> list)
       {
           if (list.Count == 0) { return emptyGroup; }
           string result = leftBrace + delimiter;
           foreach (T elementGeneric in list)
           {
               string element;
               try { element = Convert.ToString(elementGeneric); }
               catch (Exception)
               { throw new Exception("Could not convert list element to a string in function StringGroupFromList()."); }
               element = element.Replace(delimiter, delimiterEscape);
               element = element.Replace(rightBrace, rightBraceEscape);
               element = element.Replace(leftBrace, leftBraceEscape);
               result += element + delimiter;
           }
           return result + rightBrace;
       }


       static public string GroupFromParameters(params object[] values)
       {
           return GroupFromList<object>(values.ToList<object>());
       }

       static public string ClusterFromListOfGroups(List<string> listOfStringGroupsOrClusters)
       {
           string result = "";
           foreach (string group in listOfStringGroupsOrClusters)
           {
               result += group;
           }
           return result;
       }


       static public List<string> ClusterToListOfGroups(string groupCluster)
       {
           if (groupCluster == null || groupCluster.Trim().Length == 0)
               return new List<string>();
           string startSequence = leftBrace + delimiter;
           string endSequence = delimiter + rightBrace;
           groupCluster = groupCluster.Trim();
           if ((!groupCluster.StartsWith(emptyGroup)) &&
               ((!groupCluster.StartsWith(startSequence)) || (!groupCluster.EndsWith(endSequence))))
           {
               throw new Exception("ClusterToListOfStringGroups(), Invalid string input was given.");
           }
           List<string> result = new List<string>();
           int searchPosition = 0;
           while (searchPosition < groupCluster.Length)
           {
               int emptyStartIndex = groupCluster.IndexOf(emptyGroup, searchPosition);
               int startIndex = groupCluster.IndexOf(startSequence, searchPosition);
               int endIndex = groupCluster.IndexOf(endSequence, searchPosition);
               if ((emptyStartIndex != searchPosition) &&
                   (startIndex == -1 || endIndex == -1 ||
                   startIndex != searchPosition || endIndex < searchPosition + 2))
               {
                   throw new Exception("ClusterToListOfStringGroups(), Invalid string input was given.");
               }
               if (emptyStartIndex == searchPosition)
               {
                   int afterEmptyIndex = emptyStartIndex + emptyGroup.Length;
                   int length = afterEmptyIndex - emptyStartIndex;
                   result.Add(Use.SafeSubString(groupCluster, emptyStartIndex, length));
                   searchPosition = afterEmptyIndex;
               }
               else
               {
                   int afterEndIndex = endIndex + endSequence.Length;
                   int length = afterEndIndex - startIndex;
                   result.Add(Use.SafeSubString(groupCluster, startIndex, length));
                   searchPosition = afterEndIndex;
               }
           }
           return result;
       }

       static public void Test()
       {
           // Test the separating and grouping abilities.
           string currentGroup = "{:1:2:3:}";
           List<long> longList = StringGroup.GroupToList<long>(currentGroup);
           List<int> intList = StringGroup.GroupToList<int>(currentGroup);
           currentGroup = "{:abc77:3::}";
           List<string> stringList1 = StringGroup.GroupToList<string>(currentGroup);
           List<string> groupList = new List<string>();
           currentGroup = StringGroup.GroupFromList(longList);
           groupList.Add(currentGroup);
           currentGroup = StringGroup.GroupFromList(new List<int>());
           groupList.Add(currentGroup);
           currentGroup = StringGroup.GroupFromList(intList);
           groupList.Add(currentGroup);
           currentGroup = StringGroup.GroupFromList(stringList1);
           groupList.Add(currentGroup);

           // Test the clustering abilities.
           string cluster = StringGroup.ClusterFromListOfGroups(groupList);
           List<string> groupList2 = StringGroup.ClusterToListOfGroups(cluster);
           foreach (string stringGroup in groupList2)
           {
               List<string> stringList2 = StringGroup.GroupToList<string>(stringGroup);
           }
       }

   }

}

parser fails if <EOF> is on commented line

I get these, but there is no file name displayed:
line 723:6 no viable alternative at character ''
line 723:6 no viable alternative at character ''
line 723:6 required (...)+ loop did not match anything at character ''

  • The C# parser doesn't like this because the EOF is on the same line as a comment:

////}

If you had a carriage return:

////}

then the problem goes away. I'll have a look and see if that can be fixed.

ref / out params and loops

We don't properly handle ref / out params that are passed via calls in expressions in while conditions, switch scrutinees etc.

e.g.

while ( funReturnBool(ref param)) {

}

dummy enum generation code assumes that values are given in ascending order

see Generic below:

public enum CorCallingConvention
{
Default = 0x0,

    VarArg        = 0x5,
    Field         = 0x6,
    LocalSig     = 0x7,
    Property      = 0x8,
    Unmanaged         = 0x9,
    GenericInst   = 0xa,  // generic method instantiation
    NativeVarArg  = 0xb,  // used ONLY for 64bit vararg PInvoke calls

        // The high bits of the calling convention convey additional info
    Mask      = 0x0f,  // Calling convention is bottom 4 bits
    HasThis   = 0x20,  // Top bit indicates a 'this' parameter
    ExplicitThis = 0x40,  // This parameter is explicitly in the signature
    Generic   = 0x10,  // Generic method sig with explicit number of type arguments (precedes ordinary parameter count)
};

enum initializers are not in ascending order

Is this a problem? Get a whole bunch of these:
C:\rts_lib_java\rts_lib\DecoderMask.cs(998) warning: [UNSUPPORTED] enum member's value initialization ignored, value has already been assigned and enum values must be unique

Ohhh … CS2J assumes that the enum initializers are given in ascending order. We will fix this.

Support Object Initializers

In C# you can initialize an object as you create it by assigning to fields and properties:

public static void NotifyRegistryChanged (AddinRegistry reg)
{
    if (RegistryChanged != null)
        RegistryChanged (null, new RegistryEventArgs () { Registry = reg });
}

http://msdn.microsoft.com/en-us/library/bb384062(v=VS.100).aspx

==>

public static void NotifyRegistryChanged (AddinRegistry reg)
{
    if (RegistryChanged != null) {
        RegistryEventArgs __tmpVar1 = new RegistryEventArgs ();
        __tmpVar1.Registry = reg;
        RegistryChanged (null, __tmpVar1);
     }
}

Indexers in Explicit Interface Implementation declarations are throwing translation exceptions and prevent file translation

this method in C# source prevents class from being translated to Java:

string IParameterCollection.this[string name]
{
	get
	{
		IParameter parameter = this[name, 0];
		if (parameter != null)
		{
			return parameter.Value;
		}
		return null;
	}
}

this throws an Exception:

Cannot process file: C:\Users\mypath\SomeCollection.cs                                       exception: 
Antlr.Runtime.Tree.RewriteEmptyStreamException: rule method_body                                                                                                             

at Antlr.Runtime.Tree.RewriteRuleElementStream.NextTree()                                                                                                                       

at Antlr.Runtime.Tree.RewriteRuleSubtreeStream.FetchObject(ProcessHandler ph)                                                                                                         

at Antlr.Runtime.Tree.RewriteRuleSubtreeStream.NextTree()                                                                                                                              

at Twiglet.CS2J.Translator.Transform.NetMaker.class_member_declaration()                                                                                                               

at Twiglet.CS2J.Translator.Transform.NetMaker.class_member_declarations()                                                                                                              

at Twiglet.CS2J.Translator.Transform.NetMaker.class_body()                                                                                                                             

at Twiglet.CS2J.Translator.Transform.NetMaker.class_declaration()                                                                                                                      

at Twiglet.CS2J.Translator.Transform.NetMaker.type_declaration()                                                                                                                       

at Twiglet.CS2J.Translator.Transform.NetMaker.compilation_unit()                                                                                                                       

at Twiglet.CS2J.Translator.CS2J.translateFile(String fullName)                                                                                                                         

at Twiglet.CS2J.Translator.CS2J.doFile(String root, String ext, FileProcessor processFile, IList`1 excludes) 

regex

Regex
Given C# code:
Regex regex = new Regex("[.,:;]");
job.Title = regex.Replace(job.Title, "");
this was translated to
Pattern regex = Pattern.compile("[.,:;]");
job.setTitle(regex.Replace(job.getTitle(), ""));
but method Replace does not exist on class Pattern.

Implement IComparer

Comparator
Interface IComparer from C# is not translated correctly. The generated Java class looks as follows:
public class PostProfileComparer extends IComparer
{
public int Compare( PostProfile x, PostProfile y) throws Exception {
return y.getScore().Compare(x.getScore());
}

}
but interface IComparer is not defined, and also method Compare is not defined on type int (the result type of method getScore()).

We haven't yet implemented the IComparer class. I will look into that.
When we do then y.GetScore() should be automatically cast to an
Integer before we call the Compare method.

Conversion of switch to if-then-else is broken if default: is not last

        int classToken;
        switch(TokenUtils.TypeFromToken(classToken))
        {
        default:
            Debug.Assert(false);
            break;
        case CorTokenType.mdtTypeRef:
            className = GetTypeNameFromRef(classToken);
            break;
        case CorTokenType.mdtTypeDef: 
            {           
                int parentToken;
                className = GetTypeNameFromDef(classToken,out parentToken);
                break;
            }
        }

make enums option is broken

mono ~/gitrepos/rustici/cs2jBinaryCurrent/CS2JTranslator/bin/cs2j.exe -dump-xmls -dump-enums -out-enum-dir enums.xml -out-java-dir /tmp -net-templates-dir java/CS2JLibrary/ -app-dir net/src/app/ScormEngine.Core/Logic -cs-dir net/src/app/ScormEngine.Core/Logic

ArrayList (Collection) constructor translation

Collections con strucotor
The C#-constructor
public GroupConfiguration(IEnumerable groups, IEnumerable rules, Settings settings)
{
Groups = new List(groups);
was translated to
public GroupConfiguration( Iterable groups, Iterable rules, Settings settings) throws Exception {
setGroups(new ArrayList(groups));
setRules(new ArrayList(rules));
this.setSetting(settings);
}
Problem: the constructor ArrayList(Iterable does not exist in Java.

I will look into that.

Add warnings where new modifier is used.

A final comment for today (I was curious how you solved this C# feature):
Given the following C# file:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ch.fhnw.imvs
{
class B {
public virtual void foo() {
Console.WriteLine("B:foo");
}
}
class D : B {
public new void foo() {
Console.WriteLine("D:foo");
}
}

public class Test5 {
public static void Main(){
B b = new D();
b.foo();
Console.WriteLine("Done");
}
}
/*
Output:
B:foo
*/
}

Executing this program generates the output B:foo. If I run the generated Java program (the generated code is attached), then the output is D:foo. Has to do with the "new" modifier I used in class D.

I do not yet know how that problem could be solved in Java.

Yes, we naively assume all methods are virtual as in Java. I will
have a think about how we can improve this. And, in the meantime I
will add warnings where the new modifier is used.

Thanks again for your feedback.

CS2J execution error

While running cs2j.exe it states "is not a valid Win32 application" and gives an Access Denied message in command prompt.
Can anyone please help with any suggestion

Thanks in advance.

Bad character (shows up as space)

Is it some sort of wacky unicode character?

Extracting type info from file /Users/keving/gitrepos/monodevelop/main/src/core/Mono.Texteditor/Mono.TextEditor/TextEditorContainer.cs
line 72:6 no viable alternative at character ' '
line 72:23 no viable alternative at character ' '
line 73:32 no viable alternative at character ' '
line 73:41 no viable alternative at character ' '
line 74:21 no viable alternative at character ' '
line 74:50 no viable alternative at character ' '
line 74:55 no viable alternative at character ' '
line 78:32 no viable alternative at character ' '
line 78:41 no viable alternative at character ' '
line 79:21 no viable alternative at character ' '
line 79:50 no viable alternative at character ' '
line 79:55 no viable alternative at character ' '

in 'as' expansion in JavaMaker the type node is getting shared between the three expressions

With Source code:

using System.Collections;

namespace RusticiSoftware.ScormContentPlayer.Logic
{
    /// <summary>
    /// Contains default methods for integration methods which are not specific to a client integration. Most implementations can inherit from this class and only
    /// override the LMS specific methods rather than overriding all the utility methods (such as configuration, logging, etc).
    /// </summary>
    public abstract class Fred
    {
           public int[] fred()
           {
              ArrayList result = new ArrayList();
              return result.ToArray(typeof(int)) as int[];
           }
        }
}

Giving internal trees:

Java Syntax Parse Tree for Fred

package{ RusticiSoftware.ScormContentPlayer.Logic class{ public abstract Fred { METHOD{ public TYPE{ int [ ] } fred { TYPE{ ArrayList } result = new{ TYPE{ ArrayList } } ; return{ ?:{ instanceof{ APPLY{ .{ result ToArray } ARGS{ typeof{ TYPE{ int } } } } TYPE{ int [ ] } } (cast){ TYPE{ int [ ] } APPLY{ .{ result ToArray } ARGS{ typeof{ TYPE{ int } } } } } (cast){ TYPE{ int [ ] } null } } } } Exception } } } } } }

Final Java Parse Tree for Fred

package{ RusticiSoftware.ScormContentPlayer.Logic import CS2JNet.System.Collections.ArrayListSupport import java.util.ArrayList class{ public abstract Fred { METHOD{ public TYPE{ int [ ] } fred { TYPE{ JAVAWRAPPER{ ArrayList } } result = JAVAWRAPPER{ new ArrayList() } ; return{ ?:{ instanceof{ JAVAWRAPPER{ ArrayListSupport.toArray(${this}, new ${TYPEOF_expr_TYPE}[0]) this EXPRESSION{ result } TYPEOF_expr ARGUMENT{ typeof{ TYPE{ int } } } TYPEOF_expr_TYPE EXPRESSION{ int } } TYPE{ Integer [ ] } } (cast){ TYPE{ Integer [ ] } JAVAWRAPPER{ ArrayListSupport.toArray(${this}, new ${TYPEOF_expr_TYPE}[0]) this EXPRESSION{ result } TYPEOF_expr ARGUMENT{ typeof{ TYPE{ int } } } TYPEOF_expr_TYPE EXPRESSION{ int } } } (cast){ TYPE{ Integer [ ] } null } } } } Exception } } } }

The 'int' node is being changed to 'Integer' throughout, yet these type trees are dupTree'd

bad comment placement

I just realized that you already handle the problem of name clashes (with an /* ignore / comment):
If I translate the C# class
public class Test3 {
public int Value {
get { return 13; }
set { /
ignore */; }
}
public int getValue() {
return 4711;
}
}
this results in the Java class
public class Test3
{
public int getValue() throws Exception {
return 13;
}

       public   void setValue( int value) throws Exception {
               ;
       }

       /* ignore */
       public   int getValue() throws Exception {
           return 4711;
       }
   }

This will lead to a compiler error on the Java side. This case is the same as I described above with methods runAlgorithm and RunAlgorithm in a C# class in case that RunAlgorithm is converted to runAlgorithm.

The /* ignore */ comment is being erroneously put on the second
getValue() method, it should be on the setValue() method as in the C#
source (correctly placing comments in the Java is a bit of a black
art).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.