GithubHelp home page GithubHelp logo

nilproject / nil.js Goto Github PK

View Code? Open in Web Editor NEW
325.0 32.0 49.0 73.1 MB

JavaScript engine for .NET written in C#.

License: BSD 3-Clause "New" or "Revised" License

C# 4.72% JavaScript 95.20% HTML 0.07% CSS 0.01% PowerShell 0.01%
javascript engine nuget dotnet nil js parsing script

nil.js's People

Contributors

dotjoshjohnson avatar jsobell avatar kmvi avatar lpreiner avatar muscipular avatar nilproject avatar rmja avatar rundevelopment avatar savissimo avatar taritsyn avatar tlaster avatar tolmachev-pravo avatar v12 avatar viceice 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

nil.js's Issues

Сериализация делегатов.

Они не сериализуются и поэтому общую сериализацию прикрутить пока не представляется возможным. Возможно, если изменить значимые архитектурные решения

Issue with proxing method

Hello!
I've found an issue during integration of NiL.JS with mine project (replacing Jurassic, which is good, but too slow).
For example, I need to proxy method

void TestMethod(double testValue)

in javascript this is executed as

testobj.TestMethod(0)

but the NiL.JS TypeProxy unable to resolve this call and throws exception, because 0 in NiL.JS is int, but TestMethod need double (TypeProxy.cs:GetMember() line 348).

(the example is oversimplified, in fact I've more complex arguments list)

Arguments Pool

Need for enable pool for Arguments instances, but now something goes wrong

И снова ToDateTime

Привет.

Вот такой код по логике должен отрабатывать:

var today1 = DateTime.Today;
var today2 = new DateTime(today1.Year, today1.Month, today1.Day);
Assert.AreEqual(today1, today2);
Assert.AreEqual(today1.ToUniversalTime(), today2.ToUniversalTime());
context.DefineVariable("today1").Assign(JSValue.Marshal(today1));
context.DefineVariable("today2").Assign(JSValue.Marshal(today2));
var jsToday1 = (NiL.JS.BaseLibrary.Date)context.GetVariable("today1").Value;
var jsToday2 = (NiL.JS.BaseLibrary.Date)context.GetVariable("today2").Value;
Assert.AreEqual(today1, jsToday1.ToDateTime());
Assert.AreEqual(today2, jsToday2.ToDateTime());

Последний ассерт не отрабатывает. Я понимаю, что это происходит потому что у today1.Kind == DateTimeKind.Unspecified. Может правильнее было бы такой случай тоже воспринимать как локальное время?

DynamicObject

Планируется поддержка DynamicObject? На сколько я вижу сейчас поддержки таких объектов нет, или я ошибаюсь?

NiL.JS.BaseLibrary.Date.ToDateTime

Привет!

Похоже неверно отрабатывает ToDateTime у NiL.JS.BaseLibrary.Date

        context.DefineVariable("ddd").Assign(JSValue.Marshal(DateTime.Today));
        var jsDate = (NiL.JS.BaseLibrary.Date)context.GetVariable("ddd").Value;
        Assert.AreEqual(jsDate.ToDateTime(), DateTime.Today);

При DateTime.Today равным 25.01.2016, jsDate.ToDateTime() выдает 07.01.2017 21:00

Date parse problem

The following code doesn't work as I expect:

NiL.JS.Core.Context ctx = new NiL.JS.Core.Context();
ctx.Eval(@"ret = new Date(Date.parse(""2015-10-27T01:01:01.001Z""));");
Console.WriteLine(ctx.GetVariable("ret").ToString());

From Output Windows I receive this:

Tue Oct 27 2015 02:17:41 GMT+0100 (ora legale Europa occidentale)

If I run this code into chrome console I receive the right date.

Tue Oct 27 2015 02:01:01 GMT+0100 (ora solare Europa occidentale)

Any suggestions?

Crash

Crash on
String({ toString: Function.prototype.toString });

invoke more than 1 scripts on 1 context?

hi, is it possible to run many scripts on 1 context?

when i try with global context dont work, when i try to create a new context, and run js dont work only.

pls help

Support DLR

What do you think, should i implement support DLR or not?

Архитектура ClassProxy

Архитектура ClassProxy не верна. Класс необходимо разделить на три:
прототип - работает с реальным классом и возвращает обёртки для нестатических членов.
конструктор - создаёт экземпляр класса и возвращает статические члены класса.
экземпляр - подойдёт стандартный JSObject. Должен хранить созданный экземпляр класса и не должен предоставлять доступ к членам.

unsolvable error

hi, i use oop.js to create classes.

but when i use it i get this error: NiL.JS.Core.JSException occurred
HResult=-2146233088
Message=TypeError: undefined is not callable
Source=NiL.JS
StackTrace:
bei NiL.JS.Expressions.New.ThisSetter.Evaluate(Context context) in c:\Users\Дмитрий\Documents\Projects\NiL.JS\NiL.JS\Expressions\New.cs:Zeile 46.
InnerException:

but it works in browser

i really need your help

Массив объектов

Привет.

Вот такой код:

class TestArrayData
{
public string getName() { return "test"; }
}

class TestArray
{
public TestArrayData[] getArray() { return new[] {new TestArrayData(), new TestArrayData()}; }
}

[TestMethod]
public void ObjectArrayTest()
{
var engine = new Context();
engine.DefineVariable("obj").Assign(JSValue.Marshal(new TestArray()));
engine.Eval("obj.getArray().forEach((t) => console.log(t.getName()))");
}

выдает "TypeError: Can not get prototype of null or undefined". Этого же не должно быть?

Снова ToDateTime

Привет!

Вот такой тест не отрабатывает:

        var context = new Context();
        context.Eval("var date1 = new Date(2000, 0, 1)");
        var date1 = ((NiL.JS.BaseLibrary.Date)context.GetVariable("date1").Value);
        Assert.AreEqual(new DateTime(2000, 1, 1), date1.ToDateTime());
        context.GetVariable("date1").Assign(JSValue.Marshal(date1.ToDateTime()));
        date1 = ((NiL.JS.BaseLibrary.Date)context.GetVariable("date1").Value);
        Assert.AreEqual(new DateTime(2000, 1, 1), date1.ToDateTime());

Во втором ассерте ToDateTime возвращает дату в gmt

oop support

is it planned to implement real oop support for new ecmascript?

How to call method

Hi,
when I want to call a c#-method from JS I can use a delegate, as described in the examples. This is very fast (I get about 1 mio executions/s).
But how can I do the opposite and call a JS method from C#? For example in jurassic I can do:

i = engine.CallGlobalFunction<int>("test"); /// call the js-method test()

Is there an equvalent in NiL.JS?
Actually I do the following, which is very slow (I get about 30k executions/s):

context.Eval("result = test();");
result = (int)context.GetVariable("result").Value;

Доступен метод Clone()

Из-за того, что JSObject ICloneable, у всех объектов есть метод Clone(). Вообще, баг, но я не вижу большой проблемы в том, что этот метод останется

Params

Такой код:

class TestParams
{
public bool doParams(string test, params object[] testParams)
{
return testParams[1].ToString() == "ddd";
}
}

[TestMethod]
public void ParamsTest()
{
var engine = new Context();
engine.DefineVariable("obj").Assign(JSValue.Marshal(new TestParams()));
var result = engine.Eval("obj.doParams('asd', 2, 'ddd', 4.5)").Value;
Assert.IsTrue((bool)result);
}

должен отрабатывать?

Дата в массиве

Привет!

Какая-то мистика с массивом происходит:

var engine = new Context();

engine.Eval("var scriptDateArray = [new Date(2015, 1, 1), new Date(2013, 1, 1), new Date(2016, 1, 1), new Date(2000, 3, 1)];");
var scriptDateArray = engine.GetVariable("scriptDateArray");
var jsArray = scriptDateArray.Value as NiL.JS.BaseLibrary.Array;
Assert.IsNotNull(jsArray);
Assert.AreEqual(4, jsArray.length);

Срабатывает второй ассерт, получается что jsArray.length == 0
Воспроизводится если в массиве есть хоть одна дата

Built-In objects should not rely on native throw/catch exception mechanisms for JS try/catch

Take for instance the following sputnik test:
sputnik\ch15\15.1\15.1.3\15.1.3.1\S15.1.3.1_A1.10_T1.js

each iteration of the loop causes a .net exception to be thrown and caught. This causes the specific tests (and others like it) to take a very long time to run as it is throwing and catching ~65520 .net exceptions.

A different mechanism should be used by the engine to express JS exceptions internally that are only thrown as a .net exception if there isn't an outermost JS based catch.

This would improve performance on these types of tests and overall.

Fails in certain scenarios using UglifyJS

Obtain UglifyJS and generate a browser self-build See instructions

uglifyjs --self -c -m -o /tmp/uglifyjs.js

Execute the following code:

var myString = @"(function (fallback) {
    fallback = fallback || function () { };
})(null);";

var script = new Script("");
script.Context.Eval(Resources.uglifyjs);
script.Context.DefineVariable("code").Assign(new NiL.JS.BaseLibrary.String(myString));

var result = script.Context.Eval(@"var ast = UglifyJS.parse(code);
ast.figure_out_scope();
compressor = UglifyJS.Compressor();
ast = ast.transform(compressor);
ast.print_to_string();");


Console.WriteLine(result.ToString());

This fails, but when using UglifyJS with NodeJS/Browser this succeeds.

Function type

The Function type seems to have a .call method with an uppercase letter as well.
Which one should I use? Could you make the Arguments optional? I hate writing new Arguments() each time.

Also, is there any way I can use generic types?

Sputnik Test causes non-returning loop

The test runner never proceeds after the following sputnik tests

sputnik\ch15\15.1\15.1.3\15.1.3.1\S15.1.3.1_A1.10_T1.js
sputnik\ch15\15.1\15.1.3\15.1.3.1\S15.1.3.1_A1.11_T1.js
sputnik\ch15\15.1\15.1.3\15.1.3.1\S15.1.3.1_A1.11_T2.js

The conditional variable doesn't seem to increment after the catch.

Context.Eval() with compiling

Hello!
I can't find any way to compile code with Context.Eval().
Am I doing something wrong? I need to prepare .NET context for javascript file. First, I create a new Context, then add all dependent javascript files with Context.Eval() and then add code of the main javascript file with Context.Eval(). Then I'm able get a function from Context and invoke it. But it seems there are no optimizations/compilation done...
Is there any way for doing that using Script class (with TryCompile())?

Also I noticed that C#<->JS communitcation seems to be much slower than in Jurassic, would be like to get more advices how to improve it. The project (game) is using javascript for game logic scripts, so the fast communication is very important.

By the way, API is great, much better than Jurassic. Well done!

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.