Code Monkey home page Code Monkey logo

jsil's People

Contributors

brainslugs83 avatar callanh avatar danielcrenna avatar desunit avatar dmirmilshteyn avatar elw00d avatar euphoria avatar hach-que avatar iskiselev avatar kg avatar markusjohnsson avatar matra774 avatar matthid avatar mdaveynis avatar mike-e-angelo avatar mwh avatar nanexcool avatar robashton avatar rohansi avatar xen2 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  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

jsil's Issues

Nothing is rendered

When I compile my Project and open the html File in my browser, i have nothing rendered. The canvas is dynamicaly created in the Program.Main function.
Maybe it helps, that when I doubleclick the Application.js file, I get an error, that the JSIL object is undefined.

Best way to deal with attributes?

I've some code that needs to look at the attributes defined on a class, as far as I can see there is nothing for this yet.

Now, it's a trivial task to add it to the AssemblyTranslator I think, and to keep it as part of the graph for writing out to JS - but what about when we reach JS land?

Now, spitting out: JSIL.AddAttribute(System.MyType, new MyCustomAttribute("bob"));

Will probably work, and they could be stored on a property on the 'type' definition

System.MyType.$CustomAttributes

Thoughts?

Better directory structure or description

Currently with all directories in root, it is hard to get what directories are for. So i would like to suggest to restructure the directories in categorizing subdirectories or to put an description file beside.

Error while redefining Array.Get

When running in browser (tested with IE9 and FF8), the following code breaks at run time

      var x = new int[,] { { 1, 2 }, { 2, 2 } };
      Console.WriteLine(x[2, 2].ToString());

Array.Get is implemented in JSIL.MultidimensionalArray which redefines the Get method to:

  this.Get = function (y, x) {
    return items[(y * width) + x];
  };

This has two problems:

  • FF complains with "this.Get is read-only"
  • IE9 allows to re-define this method, but after JSIL.Initialize() is called, the method get overwritten with a stub that reports "The external method 'Get' of type 'System.Array' has not been implemented". I guess that this is because it is defined as [JSExternal] in Proxies.csproj). If I do not call Jsil.Initialize(), then it works OK in IE9 (but other things are broken).

Probably the best option would be to use different method name 'JsilGet' or something similar.

Any pointers on how to implement the fix. I was unable to find out how to change JSILC to emit differnet method name (the only reference that I have found is in AstmethodBodyBuilder.TransformCall which checks "cecilMethod.Name == "Get"", but breakpoint that was set on this line never fired).

Any help is appreciated.

Matra

Std lib replacement support like in Script#

In Script# it is possible to replace a std lib with the one from Script#. With that it is only possible to access function in c# which are supported in Script# and also the intellisens only show classes and function which are supported not the whole thing which the clr offers.

Untranslatable goto with locals passed to [out] params

HI,

I have found another case of untranslatable gotos. Here is a minimal version to reproduce it (in real time. it uses Dictionary classe, TrygetValue etc).

public object func(object o)
{
  return null;
}

public bool func2(out object obj)
{
  obj = null;
  return false;
}

public object TestUntranslatableGotoWithOutParam()
{
  object ret;
  if (func2(out ret))
  {
  }
  return func(ret);
}

This produces the following warning/error:

// Generating JS warning : Untranslatable goto encountered: goto IL_12

UPDATE: I am not using the latest version of JSIL - I am using the one from beginning of December.

Matra

Bug in JSIL\ILBlockTranslator.cs

The Translate_EqualityComparison method does not handle the case where the node.Arguments[x].ExpectedType == null. It should be changed to:

    protected JSExpression Translate_EqualityComparison (ILExpression node, bool checkEqual) {
        if (
            (node != null) &&
            (node.Arguments.Count == 2) &&
            (node.Arguments[0] != null) &&
            (node.Arguments[1] != null) &&
            (node.Arguments[0].ExpectedType != null) &&
            (node.Arguments[0].ExpectedType.FullName != null) &&
            (node.Arguments[1].ExpectedType != null) &&
            (node.Arguments[1].ExpectedType.FullName != null) &&
            (node.Arguments[0].ExpectedType.FullName == "System.Boolean") &&
            (node.Arguments[1].ExpectedType.FullName == "System.Boolean") &&
            (node.Arguments[1].Code.ToString().Contains("Ldc_"))
        ) {
            // Comparison against boolean constant
            bool comparand = Convert.ToInt64(node.Arguments[1].Operand) != 0;

            // TODO: This produces '!(x > y)' when 'x <= y' would be preferable.
            //  This should be easy to fix once javascript output is done via AST construction.
            if (comparand != checkEqual)
                return new JSUnaryOperatorExpression(
                    JSOperator.LogicalNot, TranslateNode(node.Arguments[0])
                );
            else
                return TranslateNode(node.Arguments[0]);

        } else {
            return Translate_BinaryOp(node, checkEqual ? JSOperator.Equal : JSOperator.NotEqual);
        }
    }

This and the previous issue I reported can be seen while translating the NetJSWire.Lite.dll library found at: http://netjswire.codeplex.com/

Thanks.

Generating proxy classes for browser build in objects

Hi,

I have a question regarding interaction with build in web browser object

I would like to write code like this in C#:

var mySelect=document.getElementById("MyId");

mySelect.Add(new Option());

callSomeMethod(mySelect.Value)

Select class is provided by browser. I have defined this class in C#, similar to this:

public class Select
{

[JSExternal]
public string Value
{
  get
  {
    return null;
  }
  set
  {
  }
}

the problem is that MSIL generates

JSIL.MakeClass("System.Object", "Select", true);

Is there any way to get rid of this?

What I am trying to achive is to generate Proxy classes in JSIL; that are similar to ScriptSharp: https://github.com/nikhilk/scriptsharp/blob/master/src/Libraries/Web/Html/InputElement.cs

Bug in JSIL\Transforms\SimplifyOperators.cs for nullable types

First let me thank you for writing this thing, it really is unbelievable.

The first IF branch starting on line 46 does not handle the case for "GetUnderlyingType". It should be changed to:

        if (method != null) {
            if (
                (type != null) &&
                (type.Type.FullName.StartsWith("System.Nullable"))
            ) {
                TypeReference t = null;

                if (type.Type as GenericInstanceType != null)
                    t = (type.Type as GenericInstanceType).GenericArguments[0];

                var @null = JSLiteral.Null(t);
                var @default = new JSDefaultValueLiteral(t);

                switch (method.Method.Member.Name) {
                    case ".ctor":
                        JSExpression value;
                        if (ie.Arguments.Count == 0) {
                            value = @null;
                        } else {
                            value = ie.Arguments[0];
                        }

                        var boe = new JSBinaryOperatorExpression(
                            JSOperator.Assignment, ie.ThisReference, value, type.Type                                
                        );
                        ParentNode.ReplaceChild(ie, boe);
                        VisitReplacement(boe);

                        break;
                    case "GetValueOrDefault":
                        var isNull = new JSBinaryOperatorExpression(
                            JSOperator.Equal, ie.ThisReference, @null, TypeSystem.Boolean
                        );

                        JSTernaryOperatorExpression ternary;
                        if (ie.Arguments.Count == 0) {
                            ternary = new JSTernaryOperatorExpression(
                                isNull, @default, ie.ThisReference, type.Type
                            );
                        } else {
                            ternary = new JSTernaryOperatorExpression(
                                isNull, ie.Arguments[0], ie.ThisReference, type.Type
                            );
                        }

                        ParentNode.ReplaceChild(ie, ternary);
                        VisitReplacement(ternary);

                        break;
                    case "GetUnderlyingType":
                        break;
                    default:
                        throw new NotImplementedException(method.Method.Member.FullName);
                }

                return;
            } else if (

Thanks

The order that types are sealed in JSIL.Initialize is important

As I understand it, sealed types are initialized as part of start up because of a call to

JSIL.Initialize();

However, types which are sealed can refer to other types which are sealed in their static initializers, and if the other type has not yet been sealed/initialized, exceptions result.

I thought the reason SealType existed was that InitializeType wouldn't have to be called until the type was accessed?

Yet there is the line

JSIL.InitializeType(type);

in MakeSealedTypeGetter which results in the errors

Have I missed something?

System.Threading.Thread initialization in JSIL.Bootrstrap.js

JSIL.Bootrstrap.js contains a JS implementation of System.Threading.Thread, but it is not using the Jsil.ImplementExternals, which makes the following test case fail with "The external method 'get_CurrentThread' of type 'System.Threading.Thread' has not been implemented."

static IEnumerable<int> GiveMeSomeInts()
{
  yield return 1;
  yield return 2;
  yield return 3;
}

static void Main(string[] args)
{

  int sum = 0; 
  foreach (var anInt in GiveMeSomeInts())
  {
    sum += anInt;
  }

  Assert(6, sum, "foreach/yield");

}

The fix is something along the following:

JSIL.ImplementExternals(
  "System.Threading.Thread", false, {
_cctor2 : function () {
  // This type already has a cctor, so we add a second one.
  System.Threading.Thread._currentThread = new System.Threading.Thread();
},
get_CurrentThread : function () {
  return System.Threading.Thread._currentThread;
}
}
);

JSIL.ImplementExternals(
  "System.Threading.Thread", true, {
_ctor : function () { },
 get_ManagedThreadId : function () { return 0; } // matra774 added
}
);

Please note, that get_ManagedThreadId aslo need to be implemented (it can return 0 as long the JavaScipt is running on single thread, which is the case in today's browser).

The C# compiler generates code similar to this:

this.$initialThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

Bug: incorrect delcaration of Array's constructor proxy for MultidimensionalArray

Proxy for constructor of multidimensional array is incorrect:
https://github.com/kevingadd/JSIL/blob/order-independence/Proxies/Array.cs#L25

Current (wrong):

[JSReplacement("JSIL.MultidimensionalArray.New($elementType, $sizeX, $sizeY)")]

Correct:

[JSReplacement("JSIL.MultidimensionalArray.New($elementType, [$sizeX, $sizeY])")]

JSIL.MultidimensionalArray expect an array as second parameter (dimension).

Similar bug exists for 3d and (probably also) for more than 3 dimensional arrays (but laters are not supported by JSIL.MultidimensionalArray), so this is currently not an issue

'this' keyword cannot be used in Lambda expressions

There is a problem when compiling lambda functions which contains the "this" keyword. Take the following program:

using System;

public class Program
{
    public static void Main(string[] args)
    {
        new Program().Run();
    }

    private int x = 1;
    private string y = "y";

    public void Run()
    {
        Func<string> a = () =>
        {
            return String.Format("x={0}, y={1}", this.x, this.y);
        };

        Func<int, string> b = (z) =>
        {
            return String.Format("x={0}, y={1}, z={2}", this.x, this.y, z);
        };

        Console.WriteLine("a()={0} b()={1}", a(), b(3));
    }
}


// CLI: "a()=x=1, y=y b()=x=1, y=y, z=3"
// JSIL: "a()=x=undefined, y=undefined b()=x=undefined, y=undefined, z=3"

The JS code will have "this" keywords in the anonymous methods, but since JS is all wierd when it comes to "this" scoping, it will not point to the Program object. I've tried to track this down (using the above as unit test), and while gaining a lot of insight into the JSIL codebase, I've not managed to solve the problem yet.

I came as far as ILBlockTranslator.Translate_Newobj where some delegate & closure stuff is happening.. But not luck so far.

Provide clearer feedback from the solution builder

The solution builder needs to provide clear feedback on which projects and targets are being built, so it will be clear when the user has failed to mark individual projects for build in a given configuration or is building the wrong configuration.

This would have probably addressed issue #49.

Generate a manifest of all translation outputs that specifies the correct load order

Translation generates .js files in a mostly arbitrary order; however, for correct behavior they must be loaded in an order that ensures that all a type's dependencies are defined before that type is defined. This order can be very hard to determine for complex applications, as it requires looking at the references of each involved assembly.

JSIL should output a manifest in a human-readable format that lists the generated .js files in the order that they should be loaded for correct behavior.

Cannot clone

Hello

I failed cloning repository. I'm not familiar with git (using mercural now), and instructions on jsil.org were quite short, Google did not help me either.

I run "git clone --recursive git://github.com/kevingadd/JSIL.git" against msysgita and getting the following output

Cloning into JSIL...
remote: Counting objects: 4168, done.
remote: Compressing objects: 100% (1094/1094), done.
remote: Total 4168 (delta 3141), reused 4079 (delta 3053)
Receiving objects: 100% (4168/4168), 4.69 MiB | 408 KiB/s, done.
Resolving deltas: 100% (3141/3141), done.
Submodule 'Examples/Mannux-xna' ([email protected]:kevingadd/XnaMannux.git) registered for path 'Examples/Mannux-xna'
Submodule 'Examples/Tetris' (https://github.com/ttocs7/tetris.git) registered for path 'Examples/Tetris'
Submodule 'Upstream/ILSpy' (https://github.com/kevingadd/ILSpy.git) registered for path 'Upstream/ILSpy'
Cloning into Examples/Mannux-xna...
The authenticity of host 'github.com (207.97.227.239)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,207.97.227.239' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

Clone of '[email protected]:kevingadd/XnaMannux.git' into submodule path 'Examples/Mannux-xna' failed

So, I, probably, need more detailed instructions on how to clone repository.

JSILC generates JS, that uses uninitialized variable if it is being passed by ref to another method

Here is the minimal test case (reduced version of IEnumerable.ToArray from MOno implementation):

public class RefArrayTest
{
 public void SomeRefFunction2(ref int[] x)
 {
 }
 public int[] MyTest(bool dummy)
 {
   int[] array;
   if (dummy) // if you remove this and the following 4 lines, then the generated code is OK
   {
     array = new int[3];
     return array;
   }
   array = null;
   SomeRefFunction2(ref array); //Array.Resize(ref array, pos * 2);
   return array;
 }

}

And here is the JS code generated:

JSIL.MakeClass(new JSIL.TypeRef($asm02, "System.Object"), "TestHelloWorld.RefArrayTest", true, [], function ($) {
    $.prototype.SomeRefFunction2 = function (/* ref */ x) {
    };
    $.prototype.MyTest = function (dummy) {
        if (dummy) {
            var array = new JSIL.Variable(JSIL.Array.New($asm02.System.Int32, 3));
            var result = array.value;
        } else {
            array.value = null;  // **** UNINITIALIZED array, so array.value fails ****
            this.SomeRefFunction2(/* ref */ array);
            result = array.value;
        }
        return result;
    };
    $.prototype._ctor = function () {
        $asm02.System.Object.prototype._ctor.call(this);
    };

});

Compiler fails to convert a "Hello World" console application.

No code modified. Just compiled solution, all projects except "Proxies.XNA" (do not have XNA installed now). Run compiler against simple application given below (.Net 4.0)

using System;

namespace CSConsole
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello world!");
        }
    }
}

got NullReferenceException at "ILBlockTranslator.cs:1307"

compiler output was

// Loading D:\Visual Studio 2010\Projects\CSConsole\Bin\CSConsole.exe...
// Loading mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089...
// Could not load symbols for module mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089: Could not find file 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.pdb'.
// Translating D:\Visual Studio 2010\Projects\CSConsole\Bin\CSConsole.exe...
// Translating C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll...
Warning: Untranslatable goto encountered: goto IL_7F
Warning: unsupported reference type for ldobj: conv.u:int32*(ldloca:float32&[exp:int32*](value))

EXE and PDB are just 17Kb, however I did not find how to attach files here :-(

Don't emit finally blocks in output JavaScript

Jan de Mooji has informed me that functions using try { } finally { } are not compiled by JaegerMonkey in Firefox at present, and that try { } catch { } does not have the same problem. So, JSIL should transform try/finally blocks into equivalent try/catch blocks.

How to specify --nodeps in new configuration system

I am having troubles finding out how to correctlay specify --nodeps and other options. I was unable to correctly pass them on command line (see bellow) or provide correct: defaults.jsilconfig

jsilc JSIL\TestHelloWorld\bin\Debug\TestHelloWorld.exe --nodeps

Unhandled Exception: Mono.Options.OptionException: Could not convert string `nodeps' to type Boolean for option `--nodeps'. ---> System.FormatException: nodeps is not a valid value for Boolean. ---> System.FormatException: String was not recognized as a valid Boolean.
  at System.Boolean.Parse(String value)
  at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
  --- End of inner exception stack trace ---
  at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFromString(String text)
at Mono.Options.Option.Parse[T](String value, OptionContext c) in JSIL\Upstream\Options.cs:line 449 
--- End of inner exception stack trace ---
at Mono.Options.Option.Parse[T](String value, OptionContext c) in JSIL\Upstream\Options.cs:line 452
at Mono.Options.OptionSet.ActionOption`1.OnParseComplete(OptionContext c) in JSIL\Upstream\Options.cs:line 864
at Mono.Options.Option.Invoke(OptionContext c) in JSIL\Upstream\Options.cs:line 541
at Mono.Options.OptionSet.Parse(String argument, OptionContext c) in JSIL\Upstream\Options.cs:line 1047
at Mono.Options.OptionSet.Parse(IEnumerable`1 arguments) in JSIL\Upstream\Options.cs:line 942
at JSIL.Compiler.Program.ParseCommandLine(IEnumerable`1 arguments, List`1 buildGroups) in JSIL\Compiler\Program.cs:line 119
at JSIL.Compiler.Program.Main(String[] arguments) in JSIL\Compiler\Program.cs:line 232

Any help would be appreciated.

matra774

Static constructors in generic types

I have a collection (PresentationFrameworkCollection(Of T)

It has a static initlalizer with sets up a dependency property

.cctor = function() {
PresentationFrameworkCollection.Of(T).CountProperty = DependencyProperty.Create(... etc)

}

This of course won't work because CountProperty is declared as a field on PresentationFrameworkCollection, and the Of call will create an indirect getter to that field (resulting in a "Cannot write to read only property" exception).

What's the best way to deal with this? I don't actually know if static fields like that are closed-type-specific

Unable to run JSILc.exe on anything

Hi there --

Would just like to say I feel this is a fantastic idea for a project.

Okay, to the issue:

I was able to successfully compile all of the projects and submodules of JSIL. Now, when I try to run JSILc.exe on my XNA project (or anything, or even run it without arguments) it has the same exact output.


on the line: [LINE 63 in PdbHelper.cs, class Mono.Cecil.Pdb.PdbReaderProvider]

Upon inspection of the local variables in the debugger, fileName has the value "" (blank string).

The full exception below: [JSIL is at C:\Users\Branch\JSIL]

Unhandled Exception: System.ArgumentException: Empty path name is not legal.
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I
nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o
ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolea
n useLongPath)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access,
FileShare share)
   at Mono.Cecil.Pdb.PdbReaderProvider.GetSymbolReader(ModuleDefinition module,
String fileName) in C:\Users\Branch\JSIL\Upstream\ILSpy\Mono.Cecil\symbols\pdb\M
ono.Cecil.Pdb\PdbHelper.cs:line 63
   at Mono.Cecil.ModuleReader.ReadSymbols(ModuleDefinition module, ReaderParamet
ers parameters) in C:\Users\Branch\JSIL\Upstream\ILSpy\Mono.Cecil\Mono.Cecil\Ass
emblyReader.cs:line 99
   at Mono.Cecil.ModuleReader.CreateModuleFrom(Image image, ReaderParameters par
ameters) in C:\Users\Branch\JSIL\Upstream\ILSpy\Mono.Cecil\Mono.Cecil\AssemblyRe
ader.cs:line 83
   at Mono.Cecil.ModuleDefinition.ReadModule(Stream stream, ReaderParameters par
ameters) in C:\Users\Branch\JSIL\Upstream\ILSpy\Mono.Cecil\Mono.Cecil\ModuleDefi
nition.cs:line 913
   at Mono.Cecil.ModuleDefinition.ReadModule(String fileName, ReaderParameters p
arameters) in C:\Users\Branch\JSIL\Upstream\ILSpy\Mono.Cecil\Mono.Cecil\ModuleDe
finition.cs:line 897
   at Mono.Cecil.AssemblyDefinition.ReadAssembly(String fileName, ReaderParamete
rs parameters) in C:\Users\Branch\JSIL\Upstream\ILSpy\Mono.Cecil\Mono.Cecil\Asse
mblyDefinition.cs:line 140
   at JSIL.AssemblyTranslator.LoadAssembly(String path, Boolean useSymbols, Bool
ean includeDependencies) in C:\Users\Branch\JSIL\JSIL\AssemblyTranslator.cs:line
 227
   at JSIL.AssemblyTranslator.AddProxyAssembly(String path, Boolean includeDepen
dencies) in C:\Users\Branch\JSIL\JSIL\AssemblyTranslator.cs:line 206
   at JSIL.AssemblyTranslator.AddProxyAssembly(Assembly assembly, Boolean includ
eDependencies) in C:\Users\Branch\JSIL\JSIL\AssemblyTranslator.cs:line 214
   at JSIL.AssemblyTranslator..ctor() in C:\Users\Branch\JSIL\JSIL\AssemblyTrans
lator.cs:line 162
   at JSIL.Compiler.Program.Main(String[] arguments) in C:\Users\Branch\JSIL\Com
piler\Program.cs:line 49

If there's any more information you may have, please let me know and I will be glad to perform actions.
--spectrum

Bug: Detecting lambda expressions for nested compiler generated classes

IlBlockTranslator.Translate_Newobj algoritm for detecting compiler generated calcualtes emitInLine based on methodDef or methodDef.DeclaringType

But if the method contains multiple lambda expressions, we should not only check if DeclaringType is compiler generated, but also if DeclaringType.DeclaringType is compiler generated (and so on).

I do not quite understand what is the purpose of TypesAreEqual check in emitInLine condition and how to write it for a generic (multiple levels of nesting) types.

Currently the such lambda expressions are trieated as ignored members, but are also not emitted inline, which causes run time error such as $l$gc__DisplayClass4f is undefined*

Matra

Untraslatable goto-s

Hi Kevin

I am digging in the JSIL, and it looks really great. However when trying to translate some of the LINQ code from MONO project base, i frequentyl gets error that are related to untraslatable GOTOs. Like the following ('ve added method names to the output of JSILC.exe):

Translating System.Boolean System.Linq.QuickSort`1/<Sort>d__0::MoveNext()
Warning: Untranslatable goto encountered: goto IL_B6

Translating System.Boolean System.Linq.Enumerable/<CreateRangeIterator>d__53::MoveNext()
Warning: Untranslatable goto encountered: goto IL_74

Translating System.Boolean System.Linq.Enumerable/<CreateRepeatIterator>d__57`1::MoveNext()
Warning: Untranslatable goto encountered: goto IL_6D

Translating System.Boolean System.Linq.Enumerable/d__5b`1::MoveNext()
Warning: Untranslatable goto encountered: goto IL_90

Any ideas how to fix those? Those methods are compiler generated (IEnumerable & yield stuff), so I can not fix them manually.

Additional noe: The code for these methods looks quite basic:

static IEnumerable<TResult> CreateRepeatIterator<TResult> (TResult element, int count)
    {
        for (int i = 0; i < count; i++)
            yield return element;
    }

    static IEnumerable<int> CreateRangeIterator (int start, int count)
    {
        for (int i = 0; i < count; i++)
            yield return start + i;
    }

Matra

I am working of the a branch that does not contain the latest version
https://github.com/markusjohnsson/JSIL/tree/jsil_corlib

Thanks,
Matra

Faulty expression braces (optimisation?)

I've some code that looks like this:

 private void btnDivide_Click(object sender, RoutedEventArgs e)
    {
        Operate((x, y) => (int) (x / (y == 0 ? 0.000000001 : y)));
    }

Gets converted into

Calculator.MainPage.prototype.btnDivide_Click = function (sender, e) {
    this.Operate(function (x, y) {
            return Math.floor(x / (y === 0) ? 1E-09 : y);
        });
};

Something is going on here :-)

JSIL.Cast doesn't work well with null values

I just shoved a (if null then return null) check in JSIL.Cast to fix this - is this the best solution? Standard .NET behaviour is to return null if you're casting from null?

Issue with the latest build RE $outer_this

I have some code

    public App()
    {
        this.Startup += this.Application_Startup;
          InitializeComponent();
    }

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        this.RootVisual = new MainPage();
    }

Which turns into

Calculator.App.prototype._ctor = function () {
    var $outer_this = this;
    System.Windows.Application.prototype._ctor.call(this);
    System.Windows.Application.prototype.add_Startup.call(this, JSIL.Delegate.New("System.Windows.StartupEventHandler", $outer_this, Calculator.App.prototype.Application_Startup));
    this.InitializeComponent();
};
Calculator.App.prototype.Application_Startup = function (sender, e) {
    System.Windows.Application.prototype.set_RootVisual.call($outer_this, (new Calculator.MainPage()));

I assume you added this to fix a bug, but it appears to have propagated into code where it shouldn't be!

System libraries support level

It is not clear what libraries are supported. I've found project converted from XNA, however it is not clear if XNA is fully supported. Also, it is not clear if XNA is supported or recommended way to build GUI.

Translating "switch" with several cases produces JSIL.IgnoredMemberReference

C# compiler sometimes optimizes 'case/switch' statement by using Dictionary<> that is initialized on first run. This dictionary is stored in member that is ignored by JSIL.

int TestSwitchWithoutDefaultTransaltesOK(string input)  // translates ok
{
  switch (input)
  {
    case "One": return 1;
    case "Two": return 2;
    case "Three": return 3;
    case "Four": return 4;
    case "Five": return 5;
    case "Six": return 6;
    //default: return 0;
  }
  return 0;
}

int TestSwitchWithDefaultFails(string input)   // deos not tranlate OK
{
  switch (input)
  {
    case "One": return 1;
    case "Two": return 2;
    case "Three": return 3;
    case "Four": return 4;
    case "Five": return 5;
    case "Six": return 6;
    default: return 0;
  }
}

The second one is translated to the following block which contains a reference to a ingnroed member:

$asm01.TestHelloWorld.Program.prototype.TestSwitchWithDefaultFails = function (input) {
var num = new JSIL.Variable(0);
if (input !== null) {
    if (JSIL.IgnoredMember("$$method0x600003a-1") === null) {
        var expr_18 = JSIL.New(System.Collections.Generic.Dictionary$b2.Of(System.String, System.Int32), "_ctor$3", [6]);
        expr_18.Add("One", 0);
        expr_18.Add("Two", 1);
        expr_18.Add("Three", 2);
        expr_18.Add("Four", 3);
        expr_18.Add("Five", 4);
        expr_18.Add("Six", 5);
        JSIL.IgnoredMember("$$method0x600003a-1") = expr_18;
    }
    if (JSIL.IgnoredMember("$$method0x600003a-1").TryGetValue(input, /* ref */ num)) {
        switch (num.value) {
            case 0: 
                var result = 1;
                return result;
            case 1: 
                result = 2;
                return result;
            case 2: 
                result = 3;
                return result;
            case 3: 
                result = 4;
                return result;
            case 4: 
                result = 5;
                return result;
            case 5: 
                result = 6;
                return result;
        }
    }
}
result = 0;
return result;
}; 

If c# compilers would do something similar also for non-basic-value type keys (such as object references) then this would require a working Dictionary class (mentioned in another case). I doubt, that this is the case.

Something similar was alo reported at:
nikhilk/scriptsharp#56

NullableType, Value and HasValue and Structs and ctors

Firstly, I've added the Value and HasValue properties in my fork as that's what most code compiles to use if you do things like

Nullable(Of int) value = 0;
if(value == null)

and

(int)value

There is a more fundamental problem though, in that the code

Nullable(Of int) value = null;

compiles into

NullableType(Of int) value = new NullableType(Of int)();

This means the default ctor doesn't get called, and value is undefined

This means that the checks for value === null fail because value is undefined, not null.

I'd write a test case, but in the latest pull from you my tests don't work because a path somewhere along the line is empty, I don't know what's changed to cause that and I haven't got time to find out.

A little help

Sorry for asking such a noobish question, but how do I actually run the outputted javascript program, specifically could you provide a bare bones html page and a simple example with a hello world app.

PrintStackTrace send requests to server

In the latest version, printStackTrace() function is used when defining interfcaes, types etc. What is the purpuse of this function.

In IE; it sends a ajax requests to unexstings files. The filenames also contains line numbers together with files and for such requests IIS returns 404. Samle urls:

http://localhost/Scripts/JSIL.Bootstrap.js:971
http://localhost/Scripts/JSIL.Bootstrap.js:953
http://localhost/Scripts/JSIL.Bootstrap.js:971

This slows down the page a lot ;-)ΒΈ

The only point where CallStack is used is in JSIL.RegisterName (which is called by JSIL.MakeXXX) to notify the user where name was previously defined.

The JS call stack is:

printStackTrace.implementation.ajax() at JSIL.Core.js:242
printStackTrace.implementation.getSource() at JSIL.Core.js:299
printStackTrace.implementation.guessAnonymousFunction() at JSIL.Core.js:322
printStackTrace.implementation.guessAnonymousFunctions() at JSIL.Core.js:311
printStackTrace() at JSIL.Core.js:50
JSIL.MakeInterface() at JSIL.Core.js:1598
(anonymous function)() at JSIL.Linq,%20Version=0.0.0.0,%20Culture=neutral,%20PublicKeyToken=null.js:5

Please note, that line number are probably wrong, because I have added some new functions to JSIL.Core.

Windows Phone XNA

Hi,

When I try to convert XNA game using JSILc I'm getting this error:
// Building 'C:\prywatne\FunApp\XGame\Wp7\XGame.sln' ... done.
// Applied settings from 'defaults.jsilconfig'.
// Loaded C:\prywatne\FunApp\XGame\Wp7\Platformer\Platformer\bin\Windows Phone\Debug\XGame.dll
// Could not load module Microsoft.Devices.Sensors, Version=7.0.0.0, Culture=neutral, PublicKeyToken=24eec0d8c86cda1e: Failed to resolve assembly: 'Microsoft.Devices.Sensors, Version=7.0.0.0, Culture=neutral, PublicKeyToken=24eec0d8c86cda1e
'
// Loaded C:\Windows\Microsoft.NET\assembly\GAC_32\Microsoft.Xna.Framework.Game\v4.0_4.0.0.0__842cf8be1de50553\Microsoft.Xna.Framework.Game.dll
// Loaded C:\prywatne\FunApp\XGame\Wp7\Platformer\Platformer\bin\Windows Phone\Debug\FarseerPhysicsXNA.dll
// Loaded C:\Windows\Microsoft.NET\assembly\GAC_32\Microsoft.Xna.Framework.Graphics\v4.0_4.0.0.0__842cf8be1de50553\Microsoft.Xna.Framework.Graphics.dll
// Loaded C:\Windows\Microsoft.NET\assembly\GAC_32\Microsoft.Xna.Framework\v4.0_4.0.0.0__842cf8be1de50553\Microsoft.Xna.Framework.dll
// Loaded C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at JSIL.AssemblyTranslator.<>c__DisplayClassf.b__b(Int32 i) in E:\GitHub\JSIL\JSIL\AssemblyTranslator.cs:line 227
at System.Threading.Tasks.Parallel.<>c__DisplayClassf1.<ForWorker>b__c() at System.Threading.Tasks.Task.InnerInvoke() at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask) at System.Threading.Tasks.Task.<>c__DisplayClass7.<ExecuteSelfReplicating>b__ 6(Object ) --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceled Exceptions) at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action1 body, Action2 bodyWithState, Func4 bodyWithLocal, Func1 localInit, Action1 localFinally)
at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body)
at JSIL.AssemblyTranslator.LoadAssembly(String path, Boolean useSymbols, Boolean includeDependencies) in E:\GitHub\JSIL\JSIL\AssemblyTranslator.cs:line 0
at JSIL.AssemblyTranslator.LoadAssembly(String path) in E:\GitHub\JSIL\JSIL\AssemblyTranslator.cs:line 116
at JSIL.AssemblyTranslator.Translate(String assemblyPath, Boolean scanForProxies) in E:\GitHub\JSIL\JSIL\AssemblyTranslator.cs:line 260
at JSIL.Compiler.Program.Main(String[] arguments) in E:\GitHub\JSIL\Compiler\Program.cs:line 253

Stop using the JS new operator

The JS new operator as defined in current versions of javascript only works on Function objects. Since instances of Function cannot have custom prototypes, this makes it impossible for types to inherit static members from base types.

Supporting the new operator has other undesirable implications (like making overloaded constructors more complicated and expensive than they would be otherwise) so in practice it's probably best to stop using it entirely.

Either:

Type.$New(...)

or

JSIL.New(Type, ...)

Should probably be used as the replacement. The former is preferable since it doesn't require the use of .call or .apply to be implemented, and makes the syntax for overloaded constructors clearer ($New$0, $New$1, etc). It sure is ugly, though...

"is" operand not working

if I write simple code such as: "if (x is TypeY)", it doesn't get translated properly.

After tracking the problem little bit, I noticed that the Cgt.un which contains isinst should normally process it properly.

However, because of ICSharpCode optimizer (in SimplifyLogicNotArgument), this Cgt.un gets transformed into Cle.un. As a result, isinst is not detected anymore (by Translate_Cgt), and it results in wrong javascript code:

if (JSIL.TryCast(x, $asm01.TypeY) > null) {

I would say that Translate_Cle might need to process it as well (in which case I could probably easily do a fix), but if a different course of action is required, please let me know.

Generic Static Properties

I can't imagine this will take you long given that you support Generic Static Methods, but the following test case will not work:

using System;

public static class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine(GenericStaticClass<int>.Default);
    }
}

public static class GenericStaticClass<T>
{
    public static string Default
    {
        get { return typeof (T).FullName; }
    }
}

Visual Studio randomly adds non-x86 build configurations to JSIL, which break it

VS randomly decides to add new build configurations to the JSIL solution, like 'Any CPU' or 'Mixed Platforms', which if selected cause it to build incorrectly and fail in various ways. JSIL needs to at the very least detect when it has been built in the wrong configuration and display a clear warning so the user can fix it.

Related issue: #12.

It'd be nice to prevent VS from doing this, as well, but it may not be possible:
http://stackoverflow.com/questions/207566/prevent-visual-studio-from-automatically-creating-mixed-platforms-solution-con

Cannot build my XNA 4.0 solution with current version of JSIL.

I hadn't had a problem in the past, but this evening I have been unable to build my XNA 4.0 game with JSIL after pulling the most recent version. (commit 09c3d0b) Note that I have not pulled for a couple of months, so I made sure to delete my JSIL working directory and clone anew.

I call JSILc from the cmd prompt as follows:

JSILc.exe C:\Users\Branch\mygame\mygame\mygame.sln

The console window shows the following information:

// Building '..\mygame\mygame\mygame.sln' ... done.
// Applied settings from 'defaults.jsilconfig'.

And that's all! It returns to the cmd prompt. No javascript files are created in any folder. I attempted to debug the issue, perhaps to figure things out and maybe help with the troubleshooting here.

at JSIL.Compiler.Program.Main() (filename Program.cs) line 242, kvp does not have any values, so var filename contains nothing and therefore the foreach loop is skipped, Main is exited and so is the program.

The program seems to understand that the argument of C:\Users\Branch\mygame\mygame\mygame.sln is a solution file (which I am able to open in Visual Studios C# 2010 Express with no problem) and gives buildGroups a value (which looks like a default value) as follows:

(Copied from Locals tab in Visual Studios)


-       buildGroups Count = 1   System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<JSIL.Compiler.Configuration,System.Collections.Generic.IEnumerable<string>>>
+       [0] {[JSIL.Compiler.Configuration, System.String[]]}    System.Collections.Generic.KeyValuePair<JSIL.Compiler.Configuration,System.Collections.Generic.IEnumerable<string>>

For completeness,

-       arguments   {string[1]} string[]
        [0] "C:\\Users\\Branch\\mygame\\mygame\\mygame.sln" string

and


-       kvp {[JSIL.Compiler.Configuration, System.String[]]}    System.Collections.Generic.KeyValuePair<JSIL.Compiler.Configuration,System.Collections.Generic.IEnumerable<string>>
-       Value   {string[0]} System.Collections.Generic.IEnumerable<string> {string[]}
        [string[]]  {string[0]} string[]


I hope this is enough information, however if you require more, please let me know and I will be happy to provide as much as I can to get this working.

Thanks,
--spectrum

Generate more compessor-friendly javascript

Wrap class definitions into anonimous functions and use variables instead fully qualified

(function(){
...
  var _$$System$Drawing$Bitmap$prototype = System.Drawing.Bitmap.prototype;
  _$$System$Drawing$Bitmap$prototype._ctor$1 = function (filename, b) {
    _$$System$Drawing$Bitmap$prototype._ctor$0.call(this, filename);
  };
...
})();

Bug: JSIL version of Dictionary<K, V> not compatible with collection initializers

Hi,

The following code

 var cache = new Dictionary<string, string>()
  {
    {"key1","value1" },
  };

Generates wrong Javascript. Note that only key is initialized, but not the value. I'm guessing that the wrong initializer is called. The following code is generated:

var cache = JSIL.Cast(JSIL.New(System.Collections.Generic.Dictionary$b2.Of(System.String, System.String), "_ctor$0", [])
.__Initialize__(["key1"]), System.Collections.Generic.Dictionary$b2.Of(System.String, System.String));

Here is the version of JavaScript with all optimizations turned off:

var cache = JSIL.Cast((JSIL.New(System.Collections.Generic.Dictionary$b2.Of(System.String, System.String), "_ctor$0", [])
= new JSIL.CollectionInitializer("key1")), System.Collections.Generic.Dictionary$b2.Of(System.String, System.String));

Matra

Function call whose result is assigned to unused variable in try block is not generated

If you assigned a result of function call to a local variable inside try block and this local variable is not used, then function call is not generated.

Example:

public object SomeFunctionWithSideEffect()
{    
  return null;
}

public void TestmethodCallNotGenerated()
{

  try
  {
    var tmp = 
      SomeFunctionWithSideEffect();    
  }
  catch (Exception ex)
  {        
    SomeFunctionWithSideEffect(); // if you remove this, the result is the same
  }

}

Generated code:

    $.prototype.SomeFunctionWithSideEffect = function () {
        return null;
    };
    $.prototype.TestmethodCallNotGenerated = function () {
        try {
        } catch ($exception) {
            this.SomeFunctionWithSideEffect();
        }
    };

If you remove assignment to tmp variable or use the tmp variable alter, then correct code is generated.

Overriding interface members explicitly does not work

A class "A" which inherits from another class "A" which implements an interface "I" can re-implement that same interface explicitly. However, this fails using JSIL:

using System;

public interface I
{
    void Foo();
}

public class A : I
{
    public void Foo()
    {
        Console.WriteLine("A");
    }
}

public class B: A, I
{
    void I.Foo()
    {
        Console.WriteLine("B");
    }
}

public static class Program
{
    public static void Main(string[] args)
    {
        I i;

        var a = new A();
        i = a;
        a.Foo(); // expected: "A"
        i.Foo(); // expected: "A"

        var b = new B();
        i = b;
        b.Foo(); // expected: "A"
        i.Foo(); // expected: "B"

    }
}
  String lengths are both 7. Strings differ at index 6.
  Expected: "A\nA\nA\nB"
  But was:  "A\nA\nA\nA"
  --------------------^

"Memory Leak" in $jsilxna.imageMultipliedCache

Not really a memory leak, but the canvases are relatively expensive and tint animations (via dynamic lighting for example) can cause the multiplied cache to grow large enough to crash the browser. It might be good to keep only the 300-500 most recently used canvases in the cache.

Also, I've noticed that the multiplying algorithm is quite expensive, are there any possible ways to do this natively?

System.TimeSpan has not been implemented

Reason for System.TimeSpan: When dealing with time-synchronizing and periodic events, it is very helpful to have a class like this.

Use case: Every 60 seconds, fire an event.

MSDN Link:

http://msdn.microsoft.com/en-us/library/system.timespan.aspx

Javascript exception:

Unhandled exception: Error: The external method '_ctor$3' of type 'System.TimeSpan' has not been implemented. Error: The external method '_ctor$3' of type 'System.TimeSpan' has not been implemented. at Object._ctor$3 (file:///C:/Users/Branch/JSIL/Libraries/JSIL.Core.js:323:23) at Object.New (file:///C:/Users/Branch/JSIL/Libraries/JSIL.Core.js:443:10) at Object._cctor (file:///C:/Users/Branch/JSIL/JSIL-GearsDEBUG-0.1.2/GearsVGE,%20Version=0.1.0.0,%20Culture=neutral,%20PublicKeyToken=null.js:719:43) at Object.InitializeType (file:///C:/Users/Branch/JSIL/Libraries/JSIL.Core.js:766:12) at Object.Input (file:///C:/Users/Branch/JSIL/Libraries/JSIL.Core.js:801:10) at sealIt (file:///C:/Users/Branch/JSIL/Libraries/JSIL.Core.js:846:18) at Object.SealTypes (file:///C:/Users/Branch/JSIL/Libraries/JSIL.Core.js:876:7) at file:///C:/Users/Branch/JSIL/JSIL-GearsDEBUG-0.1.2/GearsVGE,%20Version=0.1.0.0,%20Culture=neutral,%20PublicKeyToken=null.js:1452:8 at Object.Initialize (file:///C:/Users/Branch/JSIL/Libraries/JSIL.Core.js:364:5) at file:///C:/Users/Branch/JSIL/Libraries/JSIL.Browser.js:412:12

Treating MulticastDelegate as a class

When translating corlib, public abstract class MulticastDelegate: Delegate is translated to JSIL.MakeDelegate("System.MulticastDelegate"). This causes problems during initialization because MakeDelegate assumes that MulticastDelegate is defined.

Instead, it should be translated to JSIL.MakeClass("System.Delegate", "System.MulticastDelegate", true).

ComplexSwitch.cs produces code with gotos

When translated, https://github.com/kevingadd/JSIL/blob/master/Tests/TestCases/ComplexSwitch.cs produces code with gotos even though it really shouldn't need to. The problem appears to be that the C# compiler inserts a case for '1' that jumps to the default block, resulting in two jumps to a single target. As a result, the ILSpy decompilation pipeline leaves those gotos in place.

I think this can be addressed using a variation on the solution to issue #39.

Stable binary distribution of JSIL

Could anyone provide a stable binary distribution of JSIL?
I'm trying to convert some code, so I did everything as the Wiki page suggested, but I can't run JSILc.exe because it's exiting with errors (tries to launch a debugger). Unfortunately, I don't have time to check what's wrong and it would be nice to have the out-of-the-box version functional.

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.