GithubHelp home page GithubHelp logo

saltarelle / saltarellecompiler Goto Github PK

View Code? Open in Web Editor NEW
296.0 296.0 74.0 134.85 MB

C# to JavaScript compiler – Now http://bridge.net

Home Page: http://saltarelle-compiler.com

License: Other

C# 92.84% PowerShell 1.11% Pascal 1.86% JavaScript 4.07% CSS 0.11% Batchfile 0.01%

saltarellecompiler's People

Contributors

astrorenales avatar erik-kallen avatar geoffreymcgill avatar jam40jeff avatar kenneyw avatar mattleibow avatar nippur72 avatar prodigysim avatar thecoderok avatar volkanceylan 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

saltarellecompiler's Issues

Array.Slice shoud return T[], not untyped System.Array

compare:

var sliceResult = (int[])(new [] {1,2,3}.Slice(0)); // ugly typecast
var sliceResult2 = new[] {1,2,3}.Slice2(0);
where Slice2

[Imported]
public static class ArrayExtensions
{
    [InstanceMethodOnFirstArgument]
    [ScriptName("slice")]
    public static T[] Slice2<T>(this T[] arr, int startIndex)
    {
        return null;
    }
}

Switch statements with string keys

When i write some switch statement that operates on string like:

    public override void CreateEditor(string op)
    {
        switch (op)
        {
            case FilterOp.BW:
                Container.html("<input type=\"text\"/><span class=\"sep\">-</span><input type=\"text\"/>");
                return;
            case FilterOp.GE:
                ....
        }

        base.CreateEditor(op);
    }

I get an error like below:

Error 24 System.Collections.Generic.Dictionary<string,int>.Dictionary(int)' is obsolete:This is only for use by the c# compiler, and cannot be used for generating script.'

A field or property System.Collections.Generic.Dictionary<TKey,TValue>' cannot be initialized with a collection object initializer because typeSystem.Collections.Generic.Dictionary<string,int>' does not implement `System.Collections.IEnumerable' interface

Multiple output files

This is probably the coolest library I have seen so far! It really made my weekend!

Anyway, I am trying to get a Knockout plugin working, and it seems to be going quite well. The only real challenge is that all the output goes into one file. It would be really awesome just to have one project that creates the scripts, but for each page, there would be a single script with only that particular view model.

Maybe there could be another attribute that we could apply to the types that we want in each file?

1.3.0 obsolete messages

I don't understand what has to be done, with the new obsolete messages, e.q. jQuery.Current is obsolete, jQuery.Current is fragile. Migrate your code to use methods that supply the context as a parameter:

e.q. a plugin (static class with Mixin("$.fn") attribute has a static constructor :
public static jQueryObject MyPlugin( MyPluginOptions options )
{
....
return jQuery.Current.Each(delegate(i,e) { .... } /// obsolete message on this line

and within
jQuery.Select( selector ).Each(delegate(index, element) { jQuery.This.Value("'); }
inside Each this is defined to by the jquery object

Why is jQueryAjaxOptions.Context type Element not Object?

From the jQuery documentation of the ajax method:
context Object
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so...

So, it says that its type is Object, but in Saltarelle, its type is Element.
Is there a reason for this?

Non ASCII characters in string constants are distorted

When I have non ASCII characters in my C# string literals, they appear mangled.

For example, the author name "Erik Källén" is transformed to "Erik Kأ¤llأ©n" in the JavaScript file.

Does this have anything to do with the Arabic locale of my OS?

I tried to change the encoding of the cs file to different encodings but this didn't resolve the problem.

New global javascript namespace variable

In the process of updating the mscorlib to support nodejs I need to add "global" as a variable at the same scope as "window". My intention is to add a method to globals, something like isNodeJS() and topLevel, that will return either global or window. Thoughts?

  Test Error : Saltarelle.Compiler.Tests.RuntimeLibraryTests.TypeUtilityMethodsTests.SetPropertyWorks
   com.gargoylesoftware.htmlunit.ScriptException : ReferenceError: "global" is not defined. (script in http://localhost/
test.htm from (6, 34) to (2617, 10)#13)
  ----> net.sourceforge.htmlunit.corejs.javascript.EcmaError :

This is the error I currently get.

Type.InvokeMethod(null, "osr", sid, true);

Scriptsharp compiles this to:

osr(sid, true);

Saltarelle :
null'osr';

don't know enough about javascript if Saltarelles statement will do the correct thing if anything at all.

I use it for jqGrid,
var osr = grid.getGridParam('onSelectRow');
if ($.isFunction(osr)) { Type.InvokeMethod(null, "osr',sid,true); }

Error overriding methods from a generic base class

Using Saltarelle 1.2.5 from NuGet, the following code:

public class A<T>
{
    protected virtual void M()
    {
    }
}

public class B : A<object>
{
    protected override void M()
    {
    }
}

Results in the following three compilation errors:

Error 1 INTERNAL ERROR: Error importing type B: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary2.get_Item(TKey key) at Saltarelle.Compiler.MetadataImporter.ScriptSharpMetadataImporter.ProcessMethod(IMethod method, String preferredName, Boolean nameSpecified, Dictionary2 usedNames)
at Saltarelle.Compiler.MetadataImporter.ScriptSharpMetadataImporter.ProcessTypeMembers(ITypeDefinition typeDefinition)
at Saltarelle.Compiler.MetadataImporter.ScriptSharpMetadataImporter.Prepare(IEnumerable`1 types, IAssembly mainAssembly, IErrorReporter errorReporter).

Error 2 INTERNAL ERROR: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Saltarelle.Compiler.MetadataImporter.ScriptSharpMetadataImporter.GetMethodSemantics(IMethod method)
at Saltarelle.Compiler.Compiler.Compiler.VisitMethodDeclaration(MethodDeclaration methodDeclaration)
at ICSharpCode.NRefactory.CSharp.MethodDeclaration.AcceptVisitor(IAstVisitor visitor)
at Saltarelle.Compiler.Compiler.Compiler.VisitChildren(AstNode node)
at ICSharpCode.NRefactory.CSharp.DepthFirstAstVisitor.VisitTypeDeclaration(TypeDeclaration typeDeclaration)
at Saltarelle.Compiler.Compiler.Compiler.VisitTypeDeclaration(TypeDeclaration typeDeclaration)
at ICSharpCode.NRefactory.CSharp.TypeDeclaration.AcceptVisitor(IAstVisitor visitor)
at Saltarelle.Compiler.Compiler.Compiler.VisitChildren(AstNode node)
at ICSharpCode.NRefactory.CSharp.DepthFirstAstVisitor.VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
at ICSharpCode.NRefactory.CSharp.NamespaceDeclaration.AcceptVisitor(IAstVisitor visitor)
at Saltarelle.Compiler.Compiler.Compiler.VisitChildren(AstNode node)
at ICSharpCode.NRefactory.CSharp.DepthFirstAstVisitor.VisitSyntaxTree(SyntaxTree syntaxTree)
at ICSharpCode.NRefactory.CSharp.SyntaxTree.AcceptVisitor(IAstVisitor visitor)
at Saltarelle.Compiler.Compiler.Compiler.Compile(PreparedCompilation compilation).

Error 3 INTERNAL ERROR: Error adding default constructor to type: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Saltarelle.Compiler.MetadataImporter.ScriptSharpMetadataImporter.GetConstructorSemantics(IMethod method)
at Saltarelle.Compiler.Compiler.Compiler.MaybeAddDefaultConstructorToType(JsClass jsClass, IMethod constructor)
at Saltarelle.Compiler.Compiler.Compiler.Compile(PreparedCompilation compilation).

Casting to an interface fails

I don't know if interfaces are supported yet, but casting an object to an interface fails with following error:

Uncaught TypeError: Expecting a function in instanceof check, but got undefined 
Type$isInstanceOfTypeStatic mscorlib.debug.js:1600
Type$cast

As interface has no type definition, isInstanceOfTypeStatic fails.

Option to ignore type casts and nullable conversions

Saltarelle checks type conversions, and nullable to value type conversions.

Although i think these checks might be useful to caught hidden errors, as people will be porting from S# to Saltarelle like me, and might have made assumptions that they won't fail (any cast is a no-op in S#), it might become very hard to port existing code.

Can there be a assembly level option to disable such checks, so older code lives in older assembly, while newer code written for Saltarelle with such checks lives in another assembly.

static class method difference from script#

[Imported]
[IgnoreNamespace]
public static class JSON
{
public static string Stringify(object data)
{
return null;
}
}

c# code:
return JSON.Stringify(data);

translated by Saltarelle to
return Object.stringify(data);

while Script#
return JSON.stringify(data);

Update: I can make it work using
[InlineCode("JSON.stringify({data});")]
public static string Stringify(object data)
{
return null;
}

but it feels like this is not the right way

Feature request: 'this' should work in InlineCodeAttribute for extension methods

I found that the jQueryUI tabs plugin class in the Saltarelle runtime missing a means to set the tabTemplate option. I thought this will be easy to add using a C# extension method, so I wrote the following:

namespace jQueryUIHelpers
{
    [Imported]
    public static class Tabs
    {
        [InlineCode("{this}.tabs('option' , 'tabTemplate', {template})")]
        public static TabsObject SetTabTemplate(this TabsObject instance, string template)
        {
            return null;
        }
    }
}

Which gave me a compiler error Cannot use {this} in the literal code for a static method
But this is not an ordinary static method, it's an extension method which in C# gives the flavour of instance methods, and InlineCodeAttribute should handle it as an instance method too.

ObjectLiteral is ignored on AlternateSignatures

This is my class:

[Serializable]
[IgnoreNamespace]
[Imported(IsRealType = true)]
public class Contact
{
    public string FirstName;
    public string LastName;
    public ObservableArray<Phone> Phones;

    [ObjectLiteral]
    public Contact(string firstName, string lastName, ObservableArray<Phone> phones)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Phones = phones;
    }

    [ObjectLiteral]
    [AlternateSignature]
    public Contact(string firstName, string lastName, Phone[] phones)
    {
    }
}

Init once like this:

new Contact(
    firstName: "Danny",
    lastName: "LaRusso",
    phones: new Phone[] { // using array
        new Phone(type: "Mobile", number: "(555) 121-2121"), 
        new Phone(type: "Home", number: "(555) 123-4567")
    })

and in another place like this:

new Contact(
    firstName: contact.FirstName,
    lastName: contact.LastName,
    phones: Knockout.ObservableArray(contact.Phones.Value) // using observable

this results in different code:

first (incorrect):

new Contact('Danny', 'LaRusso', [{ type: 'Mobile', number: ..........

second (correct):

{ firstName: contact.firstName, lastName: contact.lastName, phones: ko.observableArray(contact.phones()) };

As you can see, only one of constructors outputs json format. If i remove the [Imported] and [ObjectLiteral] attributes, this is some of the code it generates:

// the object
Contact = function() {
};
Contact.$ctor = function(firstName, lastName, phones) {
    var $this = {};
    ......
};

// the usages 
new Contact('Danny', 'LaRusso', ....
// and
Contact.$ctor(contact.firstName ....

what are the reason for the diferrences between the outputs from the different constructors. Why does the one use new and the other { ... }?

Should MutableDateTime type be named as Date?

AFAIK, in S#'s latest versions, DateTime is renamed to Date.

For someone coming from C# background, it is normal to expect DateTime type as a non-mutable type.

But if there was a Date type instead of MutableDateTime, one coming from Javascript background, should have no problems understanding that it is a mutable type.

So, don't you think MutableDateTime for simple javascript type like Date is a bit long name and would create problems porting code?

Generic class with multiple constructors

The below c# generates the below javascript. Im not certain its related to generic constraints, but what I do know is that ctor1 should return this or some variant. Whats happening is it cant set foo because $t1 is null, because ctor1 doesnt return (because you use ctor1 instead of new). Hope this was informative enough, if not let me know.

using System.Html;
using System.Runtime.CompilerServices;

namespace SalterelleTest
{
    public class Class1
    {
        public Class1()
        {

            var ma = MakeArea(new MainArea<MainAreaInformation>(new MainAreaInformation()) { Foo = 2, Bar = 2 });
            ma.Bar = 12;
        }

        private MainArea<T> MakeArea<T>(MainArea<T> mainArea)
        {
            return mainArea;
        }
    }
    public class MainArea<T>
    {
        private T myInfo;

        public MainArea(T info)
        {
            myInfo = info;
        }
        public MainArea()
        {
        }

        [IntrinsicProperty]public int Foo { get; set; }
        [IntrinsicProperty]public int Bar { get; set; }
    }
    public class MainAreaInformation
    {
    }
}
Type.registerNamespace('SalterelleTest');
////////////////////////////////////////////////////////////////////////////////
// SalterelleTest.Class1
SalterelleTest.Class1 = function() {
    var $t1 = new Type.makeGenericType(SalterelleTest.MainArea$1, [SalterelleTest.MainAreaInformation]).$ctor1(new SalterelleTest.MainAreaInformation());
    $t1.foo = 2;
    $t1.bar = 2;
    var ma = this.$makeArea(SalterelleTest.MainAreaInformation).call(this, $t1);
    ma.bar = 12;
};
SalterelleTest.Class1.prototype = {
    $makeArea: function(T) {
        return function(mainArea) {
            return mainArea;
        };
    }
};
////////////////////////////////////////////////////////////////////////////////
// SalterelleTest.MainArea$1
SalterelleTest.MainArea$1 = function(T) {
    var $type = function() {
        this.$myInfo = T.getDefaultValue();
        this.foo = 0;
        this.bar = 0;
    };
    $type.$ctor1 = function(info) {
        this.$myInfo = T.getDefaultValue();
        this.foo = 0;
        this.bar = 0;
        this.$myInfo = info;
    };
    $type.$ctor1.prototype = $type.prototype;
    $type.registerGenericClassInstance($type, SalterelleTest.MainArea$1, [T], function() {
        return Object;
    }, function() {
        return [];
    });
    return $type;
};
SalterelleTest.MainArea$1.registerGenericClass('SalterelleTest.MainArea$1', 1);
////////////////////////////////////////////////////////////////////////////////
// SalterelleTest.MainAreaInformation
SalterelleTest.MainAreaInformation = function() {
};
SalterelleTest.Class1.registerClass('SalterelleTest.Class1', Object);
SalterelleTest.MainAreaInformation.registerClass('SalterelleTest.MainAreaInformation', Object);

Invalid Javascript when using Actions and No Braces

This C# code:

Action test = () => self.Category.Value = "hello World"; 

produces:

var test = function() {
    self.category('hello World');
    'hello World';
};

However, when I use braces:

Action test = () => { self.Category.Value = "hello World"; };

it produces:

var test = function() {
    self.category('hello World');
};

This is the definition of the Value property:

public T Value {
    [InlineCode("{this}()")]
    // [ScriptName("")] - this also didn't work
    get { return default(T); }

    [InlineCode("{this}({value})")]
    // [ScriptName("")] - this also didn't work
    set { }
}

And, What is maybe more wrong, if I remove my attributes:

public T Value {
    get { return default(T); }
    set { }
}

it does this:

var test = function() {
    self.category.set_value('hello World');
    'hello World';
};

Add AjaxPrefilter to jQuery

This is used in the new features of jQuery 1.5:

public static jQueryObject AjaxPrefilter(Action<jQueryAjaxOptions> action) { return null; }

as can be seen here: http://bugs.jquery.com/ticket/8338

Usage:

jQuery.AjaxPrefilter(options => { options.Global = true; });

produces:

$.ajaxPrefilter(function(options) {
    options.global = true;
});

Issue with foreach over ienumerable

When foreaching over IEnumerables it wraps the code in a try finally, with dispose in the finally block. While I take issue with the speed concerns of this method (http://jsperf.com/saltarelle-foreach-test) especially since with arrays the dispose is empty, the real problem is its swallowing an exception that's going on in the block. For now i'm okay with wrapping that portion of the code in my own try catch, but can we evaluate the need to have this setup?

nuget packages problem

There is a problem with the nuget packages and package restore on build, which is commonly used, to allow not to commit the packages into the source repository.

The compiler gives an error:
error MSB4019: The imported project ....\packages\Saltarelle.Compiler.1.2.5\tools\Saltarelle.Compiler.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.

Of course, the Saltarelle packages do not exist yet on build... (they will be downloaded by nuget package restore just before build starts) but it can't start the build because it needs already something from the package...

Problem is more common even, when package is updated, anyone checking out the project will not be able to compile, because the new reference will be missing...

Non-generic Dictionary type for S# compability

In S#, we had a non-generic type with name Dictionary which was a match for javascript object type.

Now closest to it i see in Saltaralle is JsDictionary, so i changed all my non-generic dictionaries to JsDictionary type.

Also for consistency, changed generic Dictionary<k, v> types to JsDictionary<k, v>.

This might not be a big trouble, but another extra step for porting existing code.

Also, as there was no object initializer syntax, for imported objects with "params object[]" constructor, S# acted like these params are field / value pairs for object initializer. One should have to remove all those constructors, and change all such parameters to object initialization syntax again.

Could we provide a backwards-compability option, at least by means of using a helper method in mscorlib.js for such constructors of imported objects?

NamedValues Enum's dont compile right in switches

[NamedValues]
public enum SomeType
{
    [ScriptName("foo")]
    Foo,
    [ScriptName("bar")]
    Bar
}

[IntrinsicProperty]
public SomeType Type{get;set;}


switch(this.Type){
    case SomeType.Foo:
         Window.Alert("foo");
    break;
}

Compiles to indexes in the case's.

System.Html.ImageElement ScriptName

The scriptname being "Element" causes it not to instantiate correctly in javascript. It needs to be Image.

var img=new ImageElement();
img.Src="";
var img=new Element();
img.src="";

It should compile into:

var img=new Image();
img.src="";

Questions about the compiler

Hi,

I came across the Saltarelle compiler through the SharpDevelop forums, when looking for info about NRefactory. I was writing my own JS compiler, and am 2/3 way done; however, looking through your code, it seems you are quite a bit further ahead than me. It seemed like a good idea to check what your plans are for this before continuing work on mine; it may be better not to duplicate effort?

I notice that the code doesn't yet handle end-to-end conversions ('output writer' is still in your todo list.) I assume that the difficulty here is figuring out the dependencies between compiled C# files, so that the source is printed out in the correct order (I'm also assuming that only the static initializers would need to be checked for dependencies?)

The key focus of my compiler was that it should be easy for users to plug their own functionality in - e.g. if people wanted to change how C# classes are implemented in JS, they could override it easily in the compiler; or if someone wanted to implement say parts of Mscorlib in the compiler (e.g. by transforming a List to an array and converting the List methods to JS code), or implement the async keyword, or implement LINQ support, then the compiler should support that. The idea was to provide a 'compiler framework' of sorts, that would handle the basics but be extensible. Does this sound interesting?

Cheers,
Nick

Problem with visual studio intellisense

I couldnt get Saltarelle work through nuget and gave up.

So, downloaded Saltarelle compiler and runtime dlls, and extracted them into a directory.

Created an empty class library project. Changed target framework to 2.0. Checked don't reference mscorlib in build properties. Added references to santarelle runtime (mscorlib.dll, Script.Web, Script.jQuery).

Now my project builds fine without any error. And intelilsense is ok in Visual Studio.

But as soon as i change Microsoft.CSharp.targets to Saltarelle.Compiler.targets in project file, i lose intellisense for ScriptName, ScriptAlias vs. attributes. Project continues to build fine, but seems like Visual Studio uses .NET frameworks original mscorlib for intellisense.

I tried uninstalling scriptsharp, changing target framework to 3.5, 4.0 etc, putting assemblies in GAC with no luck.

What i might be doing wrong?

Iterator blocks do not compile (missing System.Threading.Thread members)

Using Saltarelle 1.2.5 from NuGet in VS2010.

The C# compiler returns the following errors when compiling any code that includes iterator blocks:

Error 1 Missing compiler required member 'System.Threading.Thread.get_CurrentThread'
Error 2 Missing compiler required member 'System.Threading.Thread.get_ManagedThreadId'

The compiler can be satisfied by adding an empty placeholder class as follows:

namespace System.Threading
{
    public class Thread
    {
        public static Thread CurrentThread { get; set; }
        public int ManagedThreadId { get; set; }
    }
}

With the placeholder class in place, the compiler is satisfied enough to produce a DLL, and the resulting Javascript after translation appears correct (and doesn't actually reference the Thread class).

Suggestion: attribute for scoped functions

In JS, it's possible to run a function in a context different to where it was declared:

var x = function() { alert(this.name); };
var y = { name: "John Doe" };
x.call(y);

This facility is used in a few libraries; for instance:

It would be great to have an attribute which we could set on method (or delegate) parameters that specifies that this parameter should be bound to 'this' when the method is called. Any access to that parameter in the C# code would then be correctly typed, and would be converted to 'this' in the resulting Javascript - perhaps something like:

[ScriptName("object")]
public class MyDelegateThisContext
{
    public string Name { get; set; }
}

delegate void MyDelegate([BindToThis]MyDelegateThisContext that);

public class MyClass
{
    public void DoSomething()
    {
         myOtherClass.MyEventHandler = delegate(MyDelegateThisContext that) {
             Window.Alert(that.Name);
        }
    }
}

Build error

I tried to build the project but keep coming up with

c:\my\directory\SaltarelleCompiler\Runtime\src\Core\CoreScript\CoreScript.csproj : error MSB4057: The target

"GetNativeManifest" does not exist in the project.

which forces the exception

7/26/2012 8:37:15 PM: An Error Occurred:
Exec: Error executing command  msbuild "$base_dir\Runtime\src\Runtime.sln" /verbosity:minimal     /p:"Configuration=$configuration" .
At B:\code\SaltarelleCompiler\SaltarelleCompiler\build\psake.psm1:134 char:14
+         throw <<<<  ("Exec: " + $errorMessage)
    + CategoryInfo          : OperationStopped: (Exec: Error exe...onfiguration" .:String) [], RuntimeException
    + FullyQualifiedErrorId : Exec: Error executing command  msbuild "$base_dir\Runtime\src\Runtime.sln"      /verbosity:minimal /p:"Configuration=$configuration" .

Can you give any insight as to why this would occur? The internet comes up mostly empty for that error, and GetNativeManifest. Im building on windows 7 64bit.

Decided to include the full log file if it helps http://pastebin.com/BqjHHWmm

I am currently very interested in this project, and plan to convert a large script# project over to it. I look forward to the progress!

Duplicate using causes odd behavior

    using foo;
    using foo;
    namespace bar
    {
        public class Bar
        {
            public Bar()
            {
                var fm = new Foo();
                Console.Log(fm);
            }
        }
    }
    namespace foo
    {
        public class Foo
        {

        }
    }
Type.registerNamespace('HeadServer.bar');
////////////////////////////////////////////////////////////////////////////////
// HeadServer.bar.Bar
HeadServer.bar.Bar = function() {
    var fm = HeadServer.foo.Foo;
    console.log(fm);
};
Type.registerNamespace('HeadServer.foo');
////////////////////////////////////////////////////////////////////////////////
// HeadServer.foo.Foo
HeadServer.foo.Foo = function() {
};
Type.registerNamespace('HeadServer.bar');
////////////////////////////////////////////////////////////////////////////////
// HeadServer.bar.Bar
HeadServer.bar.Bar = function() {
    var fm = new HeadServer.foo.Foo();
    console.log(fm);
};
Type.registerNamespace('HeadServer.foo');
////////////////////////////////////////////////////////////////////////////////
// HeadServer.foo.Foo
HeadServer.foo.Foo = function() {
};

I cant quite figure out a way to parse an entire program in a test case, Parser.ParseProgram seems to fail, but the first source will generate the next one, as opposed to the third (which is generated when only one using is used). Im not sure if this is a c# compiler issue or what, but I suppose it should be noted. Took me far too long to track it down....

Latest compiler/.targets file doesn't copy generated .js file to bin/Debug

I think latest compiler doesn't output @(IntermediateScript) information so when i build a project, sometimes there is a script in obj/Debug directory, but none in bin/Debug.

The one in obj/Debug is probably generated by Visual Studio itself for intellisense, not build process.

I also tried with my own .targets file, situtation is the same.

Tried with AlreadyCompiled = (true/false), and no change.

Also there is no .dll in bin/Debug directory too.

Maybe i'm wrong? Are scripts expected to be generated in obj/Debug?

Bug: Brackets validations

Code:

var a = 12;      
jQuery.Select("#output").Html(a.ToString);

is compiled.
But it throw javascript error:

RangeError: radix must be an integer at least 2 and no greater than 36
http://localhost:2721/Scripts/mscorlib.debug.js:1562

jquery plugin problem

I have a jquery plugin using attribute [Mixin("$.fn")]

It is a static class with a static constructor.
The static constructor calls a static function inside the same static class.

private static void foo( arg1, arg2 ) { ... }
calling foo(arg1,arg2) from within the constructor ,
Script# compiles this to:
$.fn.foo( arg1, arg2);

and saltarelle :
foo(arg1,arg2);

as a consequence, I get an error that foo is not defined.

Maybe there is a better way to write jquery plugins with Salterelle.. any idea how to solve this ?

IgnoreNamespace attribute & Type.registerNameSpace problem

I have a class which is marked with [IgnoreNamespace]

the compiler creates script :
Type.registerNameSpace("");

just before the code for the class:
MyClass = function() { ... }

Type.registerNamespace("") causes an error on mscorlib, but only in internet explorer, not in chrome (firefox not tested).

In my old project, ScriptSharp does not seem to emit to line:
Type.registerNameSpace("");

ExpandParams attribute and single parameter

I have a set of imported methods like below:

        [ScriptName("ntLinkDropDown")] public Query ntLinkDropDown(NtLinkDropDownOptions options) { return null; }
        [ScriptName("ntLinkDropDown"), ExpandParams] public Query ntLinkDropDown(string method, params object[] parameters) { return null; }
        [ScriptName("ntLinkDropDown"), ExpandParams] public object NtLinkDropDown(string method, params object[] parameters) { return null; }

When i call them like:

_element.ntLinkDropDown("val", null);

I get an error:

Error   1   The method Sinerji.Query.ntLinkDropDown must be invoked in expanded form for its its param array.   

I guess compiler thinks i'm passing an array (null) to it.

KnockoutApi.DependentObservable can be writable

Hi. Thanks for great library.

Please add setter for KnockoutApi.DependentObservable.Value, DependentObservable can be writable if we set DependentObservableOptions.SetValueFunction delegate.

    /// <summary>
    /// Gets the current computed value.
    /// </summary>
    public T Value {
        [ScriptName("")]
        get { return default(T); }
        [ScriptName("")]  //!!!!!!!!!!!!!!
        set { }  //!!!!!!!!!!!!!!
    }

Unable to inherit the Element class to extend it

I am trying to create a VideoElement for Html5 by inheriting the element class and implementing functions in it.
The following code generates this error.

Error 1 This constructor cannot be used from script.

public class VideoElement : Element
{
    public int Volume
    {
        [InlineCode("{this}.volume * 100")]
        get;
        [InlineCode("{this}.volume = {value} / 100")]
        set;
    }
}

Is this correct if so then we need a better error message explaining this and if so whats the proper way to approach it.

Add the SlideUp/Down(Action) to jQueryObject

Is is valid to use slideUp and slideDown without a time, but with a callback:

public jQueryObject SlideUp(Action callback)
{
}

public jQueryObject SlideDown(Action callback)
{
}

Suggestion: Saltarelle.Register(Class, Url)

Saltarelle be made easier to user for first timers by allowing the following pattern...

  1. Add reference to Saltarelle.dll
  2. Create a class which extends Saltarelle.CompliedScript
  3. Add 'Saltarelle.Register(class, url)' where class is the type defined above and url is the path where the compiled script should be exposed (eg. "~/scripts/myclass.js")

Help wanted: feature design: module support

I want to add support for require to the compiler. Basically, it should be possible to have a class like this (given to-be-defined attributes):

public class Http {
    public static void CreateServer(Action<Connection> handler) {
    }
}

with an invocation of which should be possible to compile to something like the following:

var $http = require('http');
... other code ...
var server = $http.createServer(function(c) {
    ... code in the delegate ...
});

This should be some kind of attribute on the assembly (or the class?). This attribute should also cause the generated code to be usable as a Node module.

Additionally, addition of this attribute (with some additional flags) should allow AMD-style code to be generated, so a generated script could look something like:

define(['mscorlib', 'lib1', 'lib2'], function($mscorlib, $lib1, $lib2) {
    ... module code goes here ...
});

Unfortunately I feel like I know too little about how these things (Node/require/AMD) are used in practice, so I would like the help of the community to design the feature. If you have any idea about which attributes you'd want for this, and how the generated code should look, please share your thoughts here.

Implicit conversion from int to decimal failing

While trying to port an existing Script# project i get following error:

int rt = 12312312;
return (Math.Floor(rt / 60) + ":" + Pi.zeroPad(rt % 60, 2));

The best overloaded method match for System.Math.Floor(System.Number) Argument#1' cannot convert int' expression to typeSystem.Number'

IEnumerable's that are arrays

When an array is set to an ienumerable, foreach will try to call dispose and fail. Should probably check if $t1.dispose exists before calling it. Thoughts?

using System.Collections.Generic;
using CommonLibraries;

namespace Client
{
    public class Class
    {
        public IEnumerable<int> fmsint { get; set; }
        public Class()
        {
            fmsint = new int[10];


            foreach (var i in fmsint)
            {
                Console.Log(i);
            }

            Console.Log("--");
        }
    }
}
Type.registerNamespace('Client');
////////////////////////////////////////////////////////////////////////////////
// Client.Class
Client.Class = function() {
    this.$1$fmsintField = null;
    this.set_fmsint(new Array(10));
    var $t1 = this.get_fmsint().getEnumerator();
    try {
        while ($t1.moveNext()) {
            var i = $t1.get_current();
            console.log(i);
        }
    }
    finally {
        $t1.dispose();
    }
    console.log('--');
};
Client.Class.prototype = {
    get_fmsint: function() {
        return this.$1$fmsintField;
    },
    set_fmsint: function(value) {
        this.$1$fmsintField = value;
    }
};
Client.Class.registerClass('Client.Class', Object);

Calling base static method from subclass fails

For a simple sample like:

using System.Runtime.CompilerServices;

namespace TestLibrary1
{
public class Class1
{
public static void Test1()
{
System.Html.Window.Alert("hello");
}
}

public class Class2 : Class1
{
    static Class2()
    {
        Test1();
    }
}

}

I get following error:

Uncaught TypeError: Object function () {
TestLibrary1.Class1.call(this);
} has no method 'test1'

?? operator translation

In ScriptSharp, when you use the ?? operator this is translated to the || operator.

e.g. function foo(string requestType) {
requestType = requestType ?? "POST";
}
translates to (in ScripSharp)
requestType = requestType || "POST";

but Saltarelle compiles to:
requestType = Object.coalesce(requestType,"POST");

is there a reason for this difference ? the || operator in javascript is common usage for default values.

ScriptName cannot be string.Empty

It seems like a feature, but there is very specific scenario where it makes my life harder.
The new specification of XMLHttpRequest allows the field responseType to be empty ("", not null).
Hence, when I try to create an enum with

public enum ResponseType {
    [ScriptName("")]
    Default = 0
}

I am out of luck. (the compiler gives me an error that it can not be string.Empty or null, it says that it can't be null for string.Empty).
Any comments, thoughts?

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.