sebastienros / jint

Javascript Interpreter for .NET
BSD 2-Clause "Simplified" License
4.02k stars 556 forks source link

Implicit Namespaces & Interopt #1884

Closed robertmuehsig closed 2 months ago

robertmuehsig commented 2 months ago

Version used

3.1.2

Describe the bug

I created a small demo app (.NET 8 Console App) and played with the .NET Interopt, but encountered a strange "bug", but I'm not sure if this is "by design".

To Reproduce

Program.cs:

// See https://aka.ms/new-console-template for more information
using Jint;

Console.WriteLine(Test());

static string Test()
{
    string clrSample = """
    var JintImplicitUsings = importNamespace('JintImplicitUsings');
    var test = new JintImplicitUsings.Sample();
    test.Name = "Hello JS";

    return test.Name;
    """;

    var evaluatedResult = new Engine(options => { options.AllowClr(typeof(Sample).Assembly); })
        .Evaluate(clrSample).ToObject();

    return evaluatedResult.ToString();
}

Sample.cs:

public class Sample
{
    public string Name { get; set; }
}

image

Expected behavior

It should found the "Sample" constructor, but it fails with:

Jint.Runtime.JavaScriptException
  HResult=0x80131500
  Message=JintImplicitUsings.Sample is not a constructor
  Source=Jint
  StackTrace:
   at Jint.Engine.ScriptEvaluation(ScriptRecord scriptRecord, ParserOptions parserOptions)
   at Jint.Engine.<>c__DisplayClass96_0.<Execute>b__0()
   at Jint.Engine.ExecuteWithConstraints[T](Boolean strict, Func`1 callback)
   at Jint.Engine.Execute(Prepared`1& preparedScript)
   at Jint.Engine.Evaluate(Prepared`1& preparedScript)
   at Jint.Engine.Evaluate(String code, String source)
   at Program.<<Main>$>g__Test|0_0() in C:\_PrivateRepo\JintImplicitUsings\JintImplicitUsings\Program.cs:line 16
   at Program.<Main>$(String[] args) in C:\_PrivateRepo\JintImplicitUsings\JintImplicitUsings\Program.cs:line 4

Inner Exception 1:
JavaScriptErrorWrapperException: JintImplicitUsings.Sample is not a constructor

Additional context

If I add an explicit Namespace to "Sample.cs" it works.

Not a big deal, but it took me a few minutes to figure out why it didn't work.

Zaitonn commented 2 months ago
// net8.0
// without namespace
Console.WriteLine(typeof(Sample).Namespace);
Console.WriteLine(typeof(Sample).Namespace is null);

public class Sample
{
    public string Name { get; set; }
}

output:


True

the namespace of Sample is null so Jint can't get ctor by your namespace so Jint should not be to blame

it's net's features but not bug

sebastienros commented 2 months ago

So maybe the interop code should check for namespace-less types. Probably with an option though, if we can't register a null namespace.

lahma commented 2 months ago

It's now possible to import the empty namespace and get types from there. See #1888 and its test case.

lahma commented 2 months ago

This is part of the latest 3.1.3 release.