Skip to content

Implement support for properties in Emscripten generator. #1932

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ jobs:
- uses: actions/checkout@v4

- name: Setup emsdk
uses: mymindstorm/setup-emsdk@v11
uses: mymindstorm/setup-emsdk@v14
with:
version: ${{ env.EMSCRIPTEN_VERSION }}
actions-cache-folder: emsdk-cache-${{ runner.os }}
Expand Down Expand Up @@ -88,14 +88,15 @@ jobs:
- name: Test (QuickJS)
if: runner.os != 'Windows'
shell: bash
run: tests/quickjs/test.sh -dotnet_configuration $BUILD_CONFIGURATION
run: tests/quickjs/test.sh --dotnet-config $BUILD_CONFIGURATION

- name: Test (Emscripten)
if: runner.os != 'Windows'
shell: bash
run: tests/emscripten/test.sh -dotnet_configuration $BUILD_CONFIGURATION
run: tests/emscripten/test.sh --dotnet-config $BUILD_CONFIGURATION

- name: Pack
if: matrix.build-cfg == 'Release'
shell: bash
run: build/build.sh prepack -platform $PLATFORM -configuration $BUILD_CONFIGURATION

Expand Down
7 changes: 7 additions & 0 deletions src/CLI/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@ public bool ValidateOptions(List<string> messages)

options.Platform ??= Platform.Host;

if (options.Architecture is TargetArchitecture.WASM32 or TargetArchitecture.WASM64 &&
options.Platform is not TargetPlatform.Emscripten)
{
messages.Add("Please set Emscripten platform for WASM architectures.");
return false;
}

if (string.IsNullOrEmpty(options.OutputDir))
{
options.OutputDir = Path.Combine(Directory.GetCurrentDirectory(), "gen");
Expand Down
14 changes: 12 additions & 2 deletions src/Generator/Driver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,12 @@ public void SetupPasses(ILibrary library)

passes.AddPass(new CleanInvalidDeclNamesPass());
passes.AddPass(new FastDelegateToDelegatesPass());
passes.AddPass(new FieldToPropertyPass());

if (Options.GeneratorKind != GeneratorKind.Emscripten)
{
passes.AddPass(new FieldToPropertyPass());
}

passes.AddPass(new CheckIgnoredDeclsPass());
passes.AddPass(new CheckEnumsPass());
passes.AddPass(new MakeProtectedNestedTypesPublicPass());
Expand Down Expand Up @@ -283,9 +288,14 @@ public void SetupPasses(ILibrary library)

passes.AddPass(new CheckDuplicatedNamesPass());

if (Options.IsCLIGenerator || Options.IsCSharpGenerator)
if (Options.IsCLIGenerator || Options.IsCSharpGenerator
|| Options.GeneratorKind.ID is GeneratorKind.Emscripten_ID)
{
passes.RenameDeclsUpperCase(RenameTargets.Any & ~RenameTargets.Parameter);
}

if (Options.IsCLIGenerator || Options.IsCSharpGenerator)
{
passes.AddPass(new CheckKeywordNamesPass());
}

Expand Down
31 changes: 25 additions & 6 deletions src/Generator/Generators/Emscripten/EmscriptenSources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,6 @@ public override void VisitClassConstructors(IEnumerable<Method> ctors)
}
}

public override bool VisitProperty(Property property)
{
return true;
}

public override bool VisitMethodDecl(Method method)
{
Indent();
Expand All @@ -130,9 +125,33 @@ public override bool VisitMethodDecl(Method method)
return ret;
}

public override bool VisitProperty(Property property)
{
if (property.Field != null)
return property.Field.Visit(this);

if (!property.GetMethod.IsConst)
{
Console.WriteLine($"Cannot bind non-const property getter method: {property.GetMethod.QualifiedOriginalName}");
return false;
}

var @class = property.Namespace as Class;
Indent();
Write($".property(\"{property.Name}\", &{@class.QualifiedOriginalName}::{property.GetMethod.OriginalName}");

if (property.HasSetter)
Write($", &{@class.QualifiedOriginalName}::{property.SetMethod.OriginalName}");

WriteLine(")");
Unindent();

return true;
}

public override bool VisitFieldDecl(Field field)
{
WriteLineIndent($".field(\"{field.Name}\", &{field.Class.QualifiedOriginalName}::{field.OriginalName})");
WriteLineIndent($".property(\"{field.Name}\", &{field.Class.QualifiedOriginalName}::{field.OriginalName})");
return true;
}

Expand Down
2 changes: 2 additions & 0 deletions src/Generator/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,8 @@ public bool DoAllModulesHaveLibraries() =>

public bool IsCLIGenerator => GeneratorKind == GeneratorKind.CLI;

public bool IsJSGenerator => GeneratorKind == GeneratorKind.Emscripten || GeneratorKind == GeneratorKind.QuickJS;

public readonly List<string> DependentNameSpaces = new List<string>();
public bool MarshalCharAsManagedChar { get; set; }
public bool MarshalConstCharArrayAsString { get; set; } = true;
Expand Down
8 changes: 8 additions & 0 deletions src/Generator/Passes/CheckIgnoredDecls.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,14 @@ public override bool VisitFunctionDecl(Function function)
return false;
}

if (Options.IsJSGenerator && function is Method { Kind: CXXMethodKind.Normal } && ret.Type.GetFinalPointee().IsClass())
{
function.ExplicitlyIgnore();
Diagnostics.Debug("Function '{0}' was ignored due to {1} return decl not yet implemented in JS generators",
function.Name, msg);
return false;
}

foreach (var param in function.Parameters)
{
if (HasInvalidDecl(param, out msg))
Expand Down
22 changes: 18 additions & 4 deletions tests/Classes.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ class Class
{
public:
void ReturnsVoid() {}
int ReturnsInt() { return 0; }
// Class* PassAndReturnsClassPtr(Class* obj) { return obj; }
int ReturnsInt() const { return 0; }
Class* PassAndReturnsClassPtr(Class* obj) { return obj; }
};

class ClassWithField
Expand All @@ -18,7 +18,21 @@ class ClassWithField
{
}
int Field;
int ReturnsField() { return Field; }
int ReturnsField() const { return Field; }
};

class ClassWithProperty
{
public:
ClassWithProperty()
: Field(10)
{
}
int GetField() const { return Field; }
void SetField(int value) { Field = value; }

private:
int Field;
};

class ClassWithOverloads
Expand All @@ -41,4 +55,4 @@ class ClassWithExternalInheritance : public ClassFromAnotherUnit
};

// void FunctionPassClassByRef(Class* klass) { }
// Class* FunctionReturnsClassByRef() { return new Class(); }
// Class* FunctionReturnsClassByRef() { return new Class(); }
23 changes: 23 additions & 0 deletions tests/emscripten/bindings.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
generator "emscripten"
platform "emscripten"
architecture "wasm32"

includedirs
{
"..",
"../../include",
}

output "gen"

module "tests"
namespace "test"
headers
{
"Builtins.h",
"Classes.h",
"Classes2.h",
"Delegates.h",
"Enums.h",
"Overloads.h"
}
9 changes: 8 additions & 1 deletion tests/emscripten/test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,14 @@ function classes() {

var classWithField = new test.ClassWithField();
eq(classWithField.ReturnsField(), 10);
//eq(classWithField.Field, 10);
eq(classWithField.Field, 10);
classWithField.Field = 20;
eq(classWithField.ReturnsField(), 20);

var classWithProperty = new test.ClassWithProperty();
eq(classWithProperty.Field, 10);
classWithProperty.Field = 20;
eq(classWithProperty.Field, 20);
}

builtins();
Expand Down
76 changes: 48 additions & 28 deletions tests/emscripten/test.sh
Original file line number Diff line number Diff line change
@@ -1,27 +1,46 @@
#!/usr/bin/env bash
set -e

dir=$(cd "$(dirname "$0")"; pwd)
rootdir="$dir/../.."
dotnet_configuration=Release
configuration=debug
dotnet_configuration=DebugOpt
make_configuration=debug
platform=x64
jsinterp=$(which node)

for arg in "$@"; do
case $arg in
--with-node=*)
jsinterp="${arg#*=}"
shift
;;
-configuration)
configuration=$2
shift
;;
-dotnet_configuration)
dotnet_configuration=$2
shift
;;
esac
usage() {
cat <<EOF
Usage: $(basename $0) [--with-node=NODE] [--make-config CONFIG] [--dotnet-config CONFIG]
EOF
exit 1
}

while [[ $# -gt 0 ]]; do
case "$1" in
--with-node=*)
jsinterp="${1#*=}"
shift
;;
--with-node)
jsinterp="$2"
shift 2
;;
--make-config|--make-configuration)
make_configuration="$2"
shift 2
;;
--dotnet-config|--dotnet-configuration)
dotnet_configuration="$2"
shift 2
;;
-h|--help)
usage
;;
*)
echo "Unknown option: $1" >&2
usage
;;
esac
done

if [ "$CI" = "true" ]; then
Expand All @@ -34,20 +53,21 @@ else
reset=`tput sgr0`
fi

# 1) Generate
generate=true

if [ $generate = true ]; then
echo "${green}Generating bindings${reset}"
dotnet $rootdir/bin/${dotnet_configuration}/CppSharp.CLI.dll \
--gen=emscripten --platform=emscripten --arch=wasm32 \
-I$dir/.. -I$rootdir/include -o $dir/gen -m tests $dir/../*.h
echo "${green}Generating bindings with .NET configuration $dotnet_configuration${reset}"
dotnet "$rootdir/bin/${dotnet_configuration}/CppSharp.CLI.dll" --property=keywords \
"$dir/bindings.lua"
fi

echo "${green}Building generated binding files${reset}"
premake=$rootdir/build/premake.sh
config=$configuration $premake --file=$dir/premake5.lua gmake
emmake make -C $dir/gen
echo
# 2) Build
echo "${green}Building generated binding files (make config: $make_configuration)${reset}"
premake="$rootdir/build/premake.sh"
"$premake" --file=$dir/premake5.lua gmake2
config=$make_configuration emmake make -C "$dir/gen"

# 3) Test
echo
echo "${green}Executing JS tests with Node${reset}"
$jsinterp $dir/test.mjs
"$jsinterp" "$dir/test.mjs"
Loading
Loading