├── .github
└── workflows
│ └── go.yml
├── .gitignore
├── LICENSE
├── README.md
├── cmd
└── gowasm2csharp
│ └── main.go
├── example
├── binding
│ ├── binding.csproj
│ ├── main.cs
│ ├── main.go
│ └── run.sh
├── goroutine
│ ├── goroutine.csproj
│ ├── main.cs
│ ├── main.go
│ └── run.sh
├── helloworld
│ ├── helloworld.csproj
│ ├── main.cs
│ ├── main.go
│ └── run.sh
└── monogame
│ ├── Content
│ └── Content.mgcb
│ ├── GoGame.cs
│ ├── Program.cs
│ ├── main.go
│ ├── monogame.csproj
│ ├── monogame.sln
│ └── run.sh
├── go.mod
├── go.sum
├── gowasm2csharp
├── bits.go
├── generate.go
├── import.go
├── inst.go
├── js.go
├── mem.go
└── ops.go
├── internal
└── stackvar
│ ├── stackvars.go
│ └── stackvars_test.go
└── test
├── binding
├── binding.csproj
├── binding_test.go
├── main.cs
└── run.sh
└── stdlib
├── main.cs
├── run.sh
└── stdlib.csproj
/.github/workflows/go.yml:
--------------------------------------------------------------------------------
1 | name: Go
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 | pull_request:
7 | branches: [ master ]
8 |
9 | jobs:
10 |
11 | test:
12 | name: Test
13 | runs-on: ubuntu-latest
14 | steps:
15 |
16 | - uses: actions/setup-go@v1
17 | with:
18 | go-version: 1.14
19 | id: go
20 | - uses: actions/checkout@v2
21 | - uses: actions/setup-dotnet@v1
22 | with:
23 | dotnet-version: '3.1.102'
24 |
25 | - name: Test stdlib
26 | working-directory: test/stdlib
27 | run: |
28 | ./run.sh fmt -test.v -test.run=^Test
29 | ./run.sh math -test.v -test.run=^Test
30 | ./run.sh math/bits -test.v -test.run=^Test
31 | ./run.sh runtime/internal/atomic -test.v -test.run=^Test
32 | ./run.sh runtime/internal/math -test.v -test.run=^Test
33 | ./run.sh runtime/internal/sys -test.v -test.run=^Test
34 | ./run.sh sort -test.v -test.run=^Test
35 | ./run.sh sync -test.v -test.run=^Test
36 | ./run.sh sync/atomic -test.v -test.run=^Test
37 |
38 | - name: Test binding
39 | working-directory: test/binding
40 | run: ./run.sh
41 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *~
2 | *.wasm
3 | .DS_Store
4 | .vs
5 | autogen/
6 | bin/
7 | obj/
8 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # go2dotnet
2 |
3 | A converter from Go to .NET (C#)
4 |
5 | ## Example
6 |
7 | ```sh
8 | cd example/helloworld
9 | ./run.sh
10 | ```
11 |
12 | ## How does this work?
13 |
14 | This tool analyses a Wasm file compiled from Go files, and generates C# files based on the Wasm file.
15 |
16 | ## Calling C# code from Go
17 |
18 | You can use `syscall/js`. You can access C# world via `js.Global().Get(".net").Get("Something.That.Can.Be.Reached.By.Reflection")`.
19 |
20 | See `example/binding` for actual usages.
21 |
22 | ## TODO
23 |
24 | * Improving compiling speed by reducing C# files
25 | * `net/http`
26 | * `os`
27 |
--------------------------------------------------------------------------------
/cmd/gowasm2csharp/main.go:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | package main
4 |
5 | import (
6 | "flag"
7 | "log"
8 | "os"
9 |
10 | "github.com/pkg/profile"
11 |
12 | "github.com/hajimehoshi/go2dotnet/gowasm2csharp"
13 | )
14 |
15 | var (
16 | flagOut = flag.String("out", ".", "Output directory")
17 | flagWasm = flag.String("wasm", "", "WebAssembly file generated by Go")
18 | flagNamespace = flag.String("namespace", "", "Namespace")
19 | flagProfile = flag.Bool("profile", false, "Take profiles")
20 | )
21 |
22 | func main() {
23 | flag.Parse()
24 | if *flagProfile {
25 | defer profile.Start().Stop()
26 | }
27 |
28 | if err := os.MkdirAll(*flagOut, 0755); err != nil {
29 | log.Fatal(err)
30 | }
31 | if err := gowasm2csharp.Generate(*flagOut, *flagWasm, *flagNamespace); err != nil {
32 | log.Fatal(err)
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/example/binding/binding.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 | true
7 |
8 |
9 |
10 |
11 | Go2DotNet.Example.Binding.AutoGen.MemInitData
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/example/binding/main.cs:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | #pragma warning disable 649
4 |
5 | using System;
6 | using Go2DotNet.Example.Binding.AutoGen;
7 |
8 | namespace Go2DotNet.Example.Binding
9 | {
10 | public class Test
11 | {
12 | internal static void CallTwice(IInvokable a)
13 | {
14 | a.Invoke(null);
15 | a.Invoke(null);
16 | }
17 | }
18 |
19 | class Program
20 | {
21 | static void Main(string[] args)
22 | {
23 | Go go = new Go();
24 | go.Run(args);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/example/binding/main.go:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | // +build example
4 |
5 | package main
6 |
7 | import (
8 | "syscall/js"
9 | )
10 |
11 | func main() {
12 | t := js.Global().Get(".net").Get("Go2DotNet.Example.Binding.Test")
13 | f := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
14 | println("Hi")
15 | return nil
16 | })
17 | defer f.Release()
18 | t.Call("CallTwice", f)
19 | }
20 |
--------------------------------------------------------------------------------
/example/binding/run.sh:
--------------------------------------------------------------------------------
1 | set -e
2 | env GOOS=js GOARCH=wasm go build -tags example -o binding.wasm -trimpath .
3 | rm -rf autogen
4 | go run ../../cmd/gowasm2csharp -out autogen -wasm binding.wasm -namespace Go2DotNet.Example.Binding.AutoGen
5 | dotnet run .
6 |
--------------------------------------------------------------------------------
/example/goroutine/goroutine.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 | true
7 |
8 |
9 |
10 |
11 | Go2DotNet.Example.Goroutine.AutoGen.MemInitData
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/example/goroutine/main.cs:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | using System;
4 | using Go2DotNet.Example.Goroutine.AutoGen;
5 |
6 | namespace Go2DotNet.Example.Goroutine
7 | {
8 | class Program
9 | {
10 | static void Main(string[] args)
11 | {
12 | Go go = new Go();
13 | go.Run(args);
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/example/goroutine/main.go:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | // +build example
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "time"
10 | )
11 |
12 | func main() {
13 | ch1 := make(chan string)
14 | ch2 := make(chan string)
15 | ch3 := make(chan struct{})
16 |
17 | go func() {
18 | for {
19 | time.Sleep(100 * time.Millisecond)
20 | ch1 <- "A"
21 | }
22 | }()
23 | go func() {
24 | for {
25 | time.Sleep(200 * time.Millisecond)
26 | ch2 <- "B"
27 | }
28 | }()
29 | go func() {
30 | for {
31 | time.Sleep(3 * time.Second)
32 | close(ch3)
33 | }
34 | }()
35 |
36 | loop:
37 | for {
38 | select {
39 | case str := <-ch1:
40 | fmt.Println(str)
41 | case str := <-ch2:
42 | fmt.Println(str)
43 | case <-ch3:
44 | fmt.Println("Done")
45 | break loop
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/example/goroutine/run.sh:
--------------------------------------------------------------------------------
1 | set -e
2 | env GOOS=js GOARCH=wasm go build -tags example -o goroutine.wasm -trimpath .
3 | rm -rf autogen
4 | go run ../../cmd/gowasm2csharp -out autogen -wasm goroutine.wasm -namespace Go2DotNet.Example.Goroutine.AutoGen
5 | dotnet run .
6 |
--------------------------------------------------------------------------------
/example/helloworld/helloworld.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 | true
7 |
8 |
9 |
10 |
11 | Go2DotNet.Example.HelloWorld.AutoGen.MemInitData
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/example/helloworld/main.cs:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | using System;
4 | using Go2DotNet.Example.HelloWorld.AutoGen;
5 |
6 | namespace Go2DotNet.Example.HelloWorld
7 | {
8 | class Program
9 | {
10 | static void Main(string[] args)
11 | {
12 | Go go = new Go();
13 | go.Run(args);
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/example/helloworld/main.go:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | // +build example
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | )
10 |
11 | func main() {
12 | fmt.Println("Hello, World!")
13 | }
14 |
--------------------------------------------------------------------------------
/example/helloworld/run.sh:
--------------------------------------------------------------------------------
1 | set -e
2 | env GOOS=js GOARCH=wasm go build -tags example -o helloworld.wasm -trimpath .
3 | rm -rf autogen
4 | go run ../../cmd/gowasm2csharp -out autogen -wasm helloworld.wasm -namespace Go2DotNet.Example.HelloWorld.AutoGen
5 | dotnet run .
6 |
--------------------------------------------------------------------------------
/example/monogame/Content/Content.mgcb:
--------------------------------------------------------------------------------
1 |
2 | #----------------------------- Global Properties ----------------------------#
3 |
4 | /outputDir:bin/$(Platform)
5 | /intermediateDir:obj/$(Platform)
6 | /platform:DesktopGL
7 | /config:
8 | /profile:Reach
9 | /compress:False
10 |
11 | #-------------------------------- References --------------------------------#
12 |
13 |
14 | #---------------------------------- Content ---------------------------------#
15 |
16 |
--------------------------------------------------------------------------------
/example/monogame/GoGame.cs:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | using Microsoft.Xna.Framework;
4 | using Microsoft.Xna.Framework.Graphics;
5 | using Microsoft.Xna.Framework.Input;
6 | using Go2DotNet.Example.MonoGame.AutoGen;
7 |
8 | namespace Go2DotNet.Example.MonoGame
9 | {
10 | static class GoGameRunner
11 | {
12 | public static void Run(IInvokable onUpdate, IInvokable onDraw)
13 | {
14 | using var g = new GoGame(onUpdate, onDraw);
15 | g.Run();
16 | }
17 | }
18 |
19 | public class GoGame : Game
20 | {
21 | GraphicsDeviceManager graphics;
22 | SpriteBatch spriteBatch;
23 | IInvokable onUpdate;
24 | IInvokable onDraw;
25 |
26 | public GoGame(IInvokable onUpdate, IInvokable onDraw)
27 | {
28 | this.onUpdate = onUpdate;
29 | this.onDraw = onDraw;
30 | graphics = new GraphicsDeviceManager(this);
31 | Content.RootDirectory = "Content";
32 | IsMouseVisible = true;
33 | }
34 |
35 | protected override void Initialize()
36 | {
37 | // TODO: Add your initialization logic here
38 |
39 | base.Initialize();
40 | }
41 |
42 | protected override void LoadContent()
43 | {
44 | spriteBatch = new SpriteBatch(GraphicsDevice);
45 |
46 | // TODO: use this.Content to load your game content here
47 | }
48 |
49 | protected override void Update(GameTime gameTime)
50 | {
51 | if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
52 | Exit();
53 |
54 | this.onUpdate.Invoke(null);
55 |
56 | base.Update(gameTime);
57 | }
58 |
59 | protected override void Draw(GameTime gameTime)
60 | {
61 | int v = (int)(double)this.onDraw.Invoke(null);
62 | GraphicsDevice.Clear(new Color(v, v, v));
63 |
64 | base.Draw(gameTime);
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/example/monogame/Program.cs:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | using System;
4 | using Go2DotNet.Example.MonoGame.AutoGen;
5 |
6 | namespace Go2DotNet.Example.MonoGame
7 | {
8 | public static class Program
9 | {
10 | [STAThread]
11 | static void Main()
12 | {
13 | Go go = new Go();
14 | go.Run();
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/example/monogame/main.go:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | // +build example
4 |
5 | package main
6 |
7 | import (
8 | "syscall/js"
9 | )
10 |
11 | type game struct {
12 | counter int
13 | }
14 |
15 | func (g *game) update() {
16 | g.counter += 2
17 | if g.counter >= 256 {
18 | g.counter = 0
19 | }
20 | }
21 |
22 | func (g *game) draw() int {
23 | return g.counter
24 | }
25 |
26 | func main() {
27 | g := &game{}
28 |
29 | updatef := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
30 | g.update()
31 | return nil
32 | })
33 | defer updatef.Release()
34 |
35 | drawf := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
36 | return g.draw()
37 | })
38 | defer drawf.Release()
39 |
40 | js.Global().Get(".net").Get("Go2DotNet.Example.MonoGame.GoGameRunner").Call("Run", updatef, drawf)
41 | }
42 |
--------------------------------------------------------------------------------
/example/monogame/monogame.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WinExe
5 | netcoreapp3.1
6 |
7 |
8 |
9 | true
10 |
11 |
12 | true
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | Go2DotNet.Example.MonoGame.AutoGen.MemInitData
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/example/monogame/monogame.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "monogame", "monogame.csproj", "{7DB9B0FE-3F26-4144-88BC-39F50E5FAD7C}"
5 | EndProject
6 | Global
7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
8 | Debug|Any CPU = Debug|Any CPU
9 | Release|Any CPU = Release|Any CPU
10 | EndGlobalSection
11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
12 | {7DB9B0FE-3F26-4144-88BC-39F50E5FAD7C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13 | {7DB9B0FE-3F26-4144-88BC-39F50E5FAD7C}.Debug|Any CPU.Build.0 = Debug|Any CPU
14 | {7DB9B0FE-3F26-4144-88BC-39F50E5FAD7C}.Release|Any CPU.ActiveCfg = Release|Any CPU
15 | {7DB9B0FE-3F26-4144-88BC-39F50E5FAD7C}.Release|Any CPU.Build.0 = Release|Any CPU
16 | EndGlobalSection
17 | EndGlobal
18 |
--------------------------------------------------------------------------------
/example/monogame/run.sh:
--------------------------------------------------------------------------------
1 | set -e
2 | env GOOS=js GOARCH=wasm go build -tags example -o monogame.wasm -trimpath .
3 | rm -rf autogen
4 | go run ../../cmd/gowasm2csharp -out autogen -wasm monogame.wasm -namespace Go2DotNet.Example.MonoGame.AutoGen
5 | dotnet run .
6 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/hajimehoshi/go2dotnet
2 |
3 | go 1.13
4 |
5 | require (
6 | github.com/go-interpreter/wagon v0.6.1-0.20200226200811-4ca95707c808
7 | github.com/pkg/profile v1.4.0
8 | golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a
9 | golang.org/x/sys v0.0.0-20190412213103-97732733099d // indirect
10 | )
11 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/edsrzf/mmap-go v1.0.0 h1:CEBF7HpRnUCSJgGUb5h1Gm7e3VkmVDrR8lvWVLtrOFw=
2 | github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
3 | github.com/go-interpreter/wagon v0.6.1-0.20200226200811-4ca95707c808 h1:DK/r87dK66orWskGaYpM/0csKs1uOtwve5tX0z/ZljI=
4 | github.com/go-interpreter/wagon v0.6.1-0.20200226200811-4ca95707c808/go.mod h1:lQUozviuTS6v7A2HXs6L0Wc72Apl9+mKsGLsJOHYiME=
5 | github.com/pkg/profile v1.4.0 h1:uCmaf4vVbWAOZz36k1hrQD7ijGRzLwaME8Am/7a4jZI=
6 | github.com/pkg/profile v1.4.0/go.mod h1:NWz/XGvpEW1FyYQ7fCx4dqYBLlfTcE+A9FLAkNKqjFE=
7 | github.com/twitchyliquid64/golang-asm v0.0.0-20190126203739-365674df15fc h1:RTUQlKzoZZVG3umWNzOYeFecQLIh+dbxXvJp1zPQJTI=
8 | github.com/twitchyliquid64/golang-asm v0.0.0-20190126203739-365674df15fc/go.mod h1:NoCfSFWosfqMqmmD7hApkirIK9ozpHjxRnRxs1l413A=
9 | golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a h1:WXEvlFVvvGxCJLG6REjsT03iWnKLEWinaScsxF2Vm2o=
10 | golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
11 | golang.org/x/sys v0.0.0-20190306220234-b354f8bf4d9e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
12 | golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
13 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
14 |
--------------------------------------------------------------------------------
/gowasm2csharp/bits.go:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | package gowasm2csharp
4 |
5 | import (
6 | "os"
7 | "path/filepath"
8 | "text/template"
9 | )
10 |
11 | func writeBitsCS(dir string, namespace string) error {
12 | f, err := os.Create(filepath.Join(dir, "Bits.cs"))
13 | if err != nil {
14 | return err
15 | }
16 | defer f.Close()
17 |
18 | if err := bitsTmpl.Execute(f, struct {
19 | Namespace string
20 | }{
21 | Namespace: namespace,
22 | }); err != nil {
23 | return err
24 | }
25 | return nil
26 | }
27 |
28 | var bitsTmpl = template.Must(template.New("Bits.cs").Parse(`// Code generated by go2dotnet. DO NOT EDIT.
29 |
30 | namespace {{.Namespace}}
31 | {
32 | // The implementation is copied from the Go standard package math/bits, which is under BSD-style license.
33 | static class Bits
34 | {
35 | public static int LeadingZeros(uint x)
36 | {
37 | return 32 - Len(x);
38 | }
39 |
40 | public static int LeadingZeros(ulong x)
41 | {
42 | return 64 - Len(x);
43 | }
44 |
45 | public static int TailingZeros(uint x)
46 | {
47 | if (x == 0)
48 | {
49 | return 32;
50 | }
51 | return (int)deBruijn32tab[(x&-x)*deBruijn32>>(32-5)];
52 | }
53 |
54 | public static int TailingZeros(ulong x)
55 | {
56 | if (x == 0)
57 | {
58 | return 64;
59 | }
60 | return (int)deBruijn64tab[(x&(ulong)(-(long)x))*deBruijn64>>(64-6)];
61 | }
62 |
63 | public static int OnesCount(uint x)
64 | {
65 | return (int)(pop8tab[x>>24] + pop8tab[x>>16&0xff] + pop8tab[x>>8&0xff] + pop8tab[x&0xff]);
66 | }
67 |
68 | public static int OnesCount(ulong x)
69 | {
70 | const ulong m0 = 0x5555555555555555ul;
71 | const ulong m1 = 0x3333333333333333ul;
72 | const ulong m2 = 0x0f0f0f0f0f0f0f0ful;
73 | const ulong m = 0xfffffffffffffffful;
74 |
75 | x = ((x>>1)&(m0&m)) + (x&(m0&m));
76 | x = ((x>>2)&(m1&m)) + (x&(m1&m));
77 | x = ((x>>4) + x) & (m2 & m);
78 | x += x >> 8;
79 | x += x >> 16;
80 | x += x >> 32;
81 | return (int)(x) & ((1<<7) - 1);
82 | }
83 |
84 | public static uint RotateLeft(uint x, int k)
85 | {
86 | const int n = 32;
87 | int s = k & (n - 1);
88 | return x<>(n-s);
89 | }
90 |
91 | public static ulong RotateLeft(ulong x, int k)
92 | {
93 | const int n = 64;
94 | int s = k & (n - 1);
95 | return x<>(n-s);
96 | }
97 |
98 | private static int Len(uint x)
99 | {
100 | int n = 0;
101 | if (x >= 1<<16)
102 | {
103 | x >>= 16;
104 | n = 16;
105 | }
106 | if (x >= 1<<8)
107 | {
108 | x >>= 8;
109 | n += 8;
110 | }
111 | return n + (int)len8tab[x];
112 | }
113 |
114 | private static int Len(ulong x)
115 | {
116 | int n = 0;
117 | if (x >= 1ul<<32)
118 | {
119 | x >>= 32;
120 | n = 32;
121 | }
122 | if (x >= 1ul<<16)
123 | {
124 | x >>= 16;
125 | n += 16;
126 | }
127 | if (x >= 1ul<<8)
128 | {
129 | x >>= 8;
130 | n += 8;
131 | }
132 | return n + (int)len8tab[x];
133 | }
134 |
135 | static byte[] pop8tab = new byte[] {
136 | 0x00, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x03, 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04,
137 | 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05,
138 | 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05,
139 | 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06,
140 | 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05,
141 | 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06,
142 | 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06,
143 | 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07,
144 | 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05,
145 | 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06,
146 | 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06,
147 | 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07,
148 | 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06,
149 | 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07,
150 | 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07,
151 | 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07, 0x05, 0x06, 0x06, 0x07, 0x06, 0x07, 0x07, 0x08,
152 | };
153 |
154 | static byte[] len8tab = new byte[] {
155 | 0x00, 0x01, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
156 | 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
157 | 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
158 | 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
159 | 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
160 | 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
161 | 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
162 | 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
163 | 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
164 | 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
165 | 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
166 | 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
167 | 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
168 | 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
169 | 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
170 | 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
171 | };
172 |
173 | const uint deBruijn32 = 0x077CB531;
174 |
175 | static byte[] deBruijn32tab = new byte[] {
176 | 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
177 | 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9,
178 | };
179 |
180 | const ulong deBruijn64 = 0x03f79d71b4ca8b09;
181 |
182 | static byte[] deBruijn64tab = new byte[] {
183 | 0, 1, 56, 2, 57, 49, 28, 3, 61, 58, 42, 50, 38, 29, 17, 4,
184 | 62, 47, 59, 36, 45, 43, 51, 22, 53, 39, 33, 30, 24, 18, 12, 5,
185 | 63, 55, 48, 27, 60, 41, 37, 16, 46, 35, 44, 21, 52, 32, 23, 11,
186 | 54, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6,
187 | };
188 | }
189 | }
190 | `))
191 |
--------------------------------------------------------------------------------
/gowasm2csharp/generate.go:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Apache-2.0
2 |
3 | package gowasm2csharp
4 |
5 | import (
6 | "bytes"
7 | "fmt"
8 | "os"
9 | "path/filepath"
10 | "strings"
11 | "text/template"
12 |
13 | "github.com/go-interpreter/wagon/wasm"
14 | "golang.org/x/sync/errgroup"
15 | )
16 |
17 | func identifierFromString(str string) string {
18 | var ident string
19 | for _, r := range []rune(str) {
20 | if r > 0xff {
21 | panic("identifiers cannot include non-Latin1 characters")
22 | }
23 | if '0' <= r && r <= '9' {
24 | ident += string(r)
25 | continue
26 | }
27 | if 'a' <= r && r <= 'z' {
28 | ident += string(r)
29 | continue
30 | }
31 | if 'A' <= r && r <= 'Z' {
32 | ident += string(r)
33 | continue
34 | }
35 | ident += fmt.Sprintf("_%02x", r)
36 | }
37 | if len(ident) > 512 {
38 | ident = ident[:511]
39 | }
40 | return ident
41 | }
42 |
43 | type wasmFunc struct {
44 | Mod *wasm.Module
45 | Funcs []*wasmFunc
46 | Types []*wasmType
47 | Type *wasmType
48 | Wasm wasm.Function
49 | Index int
50 | Import bool
51 | BodyStr string
52 | }
53 |
54 | func (f *wasmFunc) Identifier() string {
55 | return identifierFromString(f.Wasm.Name)
56 | }
57 |
58 | var funcTmpl = template.Must(template.New("func").Parse(`// OriginalName: {{.OriginalName}}
59 | // Index: {{.Index}}
60 | {{if .WithBody}}{{if .Public}}public{{else}}private{{end}} {{end}}{{.ReturnType}} {{.Name}}({{.Args}}){{if .WithBody}}
61 | {
62 | {{range .Locals}} {{.}}
63 | {{end}}{{if .Locals}}
64 | {{end}}{{range .Body}}{{.}}
65 | {{end}}}{{else}};{{end}}`))
66 |
67 | func wasmTypeToReturnType(v wasm.ValueType) returnType {
68 | switch v {
69 | case wasm.ValueTypeI32:
70 | return returnTypeI32
71 | case wasm.ValueTypeI64:
72 | return returnTypeI64
73 | case wasm.ValueTypeF32:
74 | return returnTypeF32
75 | case wasm.ValueTypeF64:
76 | return returnTypeF64
77 | default:
78 | panic("not reached")
79 | }
80 | }
81 |
82 | func (f *wasmFunc) CSharp(indent string, public bool, withBody bool) (string, error) {
83 | var retType returnType
84 | switch ts := f.Wasm.Sig.ReturnTypes; len(ts) {
85 | case 0:
86 | retType = returnTypeVoid
87 | case 1:
88 | retType = wasmTypeToReturnType(ts[0])
89 | default:
90 | return "", fmt.Errorf("the number of return values must be 0 or 1 but %d", len(ts))
91 | }
92 |
93 | var args []string
94 | for i, t := range f.Wasm.Sig.ParamTypes {
95 | args = append(args, fmt.Sprintf("%s local%d", wasmTypeToReturnType(t).CSharp(), i))
96 | }
97 |
98 | var locals []string
99 | var body []string
100 | if withBody {
101 | if f.BodyStr != "" {
102 | body = strings.Split(f.BodyStr, "\n")
103 | } else if f.Wasm.Body != nil {
104 | var idx int
105 | for _, e := range f.Wasm.Body.Locals {
106 | for i := 0; i < int(e.Count); i++ {
107 | locals = append(locals, fmt.Sprintf("%s local%d = 0;", wasmTypeToReturnType(e.Type).CSharp(), idx+len(f.Wasm.Sig.ParamTypes)))
108 | idx++
109 | }
110 | }
111 | var err error
112 | body, err = f.bodyToCSharp()
113 | if err != nil {
114 | return "", err
115 | }
116 | } else {
117 | body = []string{" throw new NotImplementedException();"}
118 | }
119 | }
120 |
121 | var buf bytes.Buffer
122 | if err := funcTmpl.Execute(&buf, struct {
123 | OriginalName string
124 | Name string
125 | Index int
126 | ReturnType string
127 | Args string
128 | Locals []string
129 | Body []string
130 | Public bool
131 | WithBody bool
132 | }{
133 | OriginalName: f.Wasm.Name,
134 | Name: identifierFromString(f.Wasm.Name),
135 | Index: f.Index,
136 | ReturnType: retType.CSharp(),
137 | Args: strings.Join(args, ", "),
138 | Locals: locals,
139 | Body: body,
140 | Public: public,
141 | WithBody: withBody,
142 | }); err != nil {
143 | return "", err
144 | }
145 |
146 | // Add indentations
147 | var lines []string
148 | for _, line := range strings.Split(buf.String(), "\n") {
149 | lines = append(lines, indent+line)
150 | }
151 | return strings.Join(lines, "\n") + "\n", nil
152 | }
153 |
154 | type wasmExport struct {
155 | Funcs []*wasmFunc
156 | Index int
157 | Name string
158 | }
159 |
160 | func (e *wasmExport) CSharp(indent string) (string, error) {
161 | f := e.Funcs[e.Index]
162 |
163 | var ret string
164 | var retType returnType
165 | switch ts := f.Wasm.Sig.ReturnTypes; len(ts) {
166 | case 0:
167 | retType = returnTypeVoid
168 | case 1:
169 | ret = "return "
170 | retType = wasmTypeToReturnType(ts[0])
171 | default:
172 | return "", fmt.Errorf("the number of return values must be 0 or 1 but %d", len(ts))
173 | }
174 |
175 | var args []string
176 | var argsToPass []string
177 | for i, t := range f.Wasm.Sig.ParamTypes {
178 | args = append(args, fmt.Sprintf("%s arg%d", wasmTypeToReturnType(t).CSharp(), i))
179 | argsToPass = append(argsToPass, fmt.Sprintf("arg%d", i))
180 | }
181 |
182 | str := fmt.Sprintf(`public %s %s(%s)
183 | {
184 | %s%s(%s);
185 | }
186 | `, retType.CSharp(), e.Name, strings.Join(args, ", "), ret, identifierFromString(f.Wasm.Name), strings.Join(argsToPass, ", "))
187 |
188 | lines := strings.Split(str, "\n")
189 | for i := range lines {
190 | lines[i] = indent + lines[i]
191 | }
192 | return strings.Join(lines, "\n"), nil
193 | }
194 |
195 | type wasmGlobal struct {
196 | Type wasm.ValueType
197 | Index int
198 | Init int
199 | }
200 |
201 | func (g *wasmGlobal) CSharp(indent string) string {
202 | return fmt.Sprintf("%sprivate %s global%d = %d;", indent, wasmTypeToReturnType(g.Type).CSharp(), g.Index, g.Init)
203 | }
204 |
205 | type wasmType struct {
206 | Sig *wasm.FunctionSig
207 | Index int
208 | }
209 |
210 | func (t *wasmType) CSharp(indent string) (string, error) {
211 | var retType returnType
212 | switch ts := t.Sig.ReturnTypes; len(ts) {
213 | case 0:
214 | retType = returnTypeVoid
215 | case 1:
216 | retType = wasmTypeToReturnType(ts[0])
217 | default:
218 | return "", fmt.Errorf("the number of return values must be 0 or 1 but %d", len(ts))
219 | }
220 |
221 | var args []string
222 | for i, t := range t.Sig.ParamTypes {
223 | args = append(args, fmt.Sprintf("%s arg%d", wasmTypeToReturnType(t).CSharp(), i))
224 | }
225 |
226 | return fmt.Sprintf("%sprivate delegate %s Type%d(%s);", indent, retType.CSharp(), t.Index, strings.Join(args, ", ")), nil
227 | }
228 |
229 | func Generate(outDir string, wasmFile string, namespace string) error {
230 | f, err := os.Open(wasmFile)
231 | if err != nil {
232 | return err
233 | }
234 | defer f.Close()
235 |
236 | mod, err := wasm.DecodeModule(f)
237 | if err != nil {
238 | return err
239 | }
240 |
241 | var types []*wasmType
242 | for i, e := range mod.Types.Entries {
243 | e := e
244 | types = append(types, &wasmType{
245 | Sig: &e,
246 | Index: i,
247 | })
248 | }
249 |
250 | var ifs []*wasmFunc
251 | for i, e := range mod.Import.Entries {
252 | name := e.FieldName
253 | ifs = append(ifs, &wasmFunc{
254 | Type: types[e.Type.(wasm.FuncImport).Type],
255 | Wasm: wasm.Function{
256 | Sig: types[e.Type.(wasm.FuncImport).Type].Sig,
257 | Name: name,
258 | },
259 | Index: i,
260 | Import: true,
261 | BodyStr: importFuncBodies[name],
262 | })
263 | }
264 |
265 | // There is a bug that signature and body are shifted (go-interpreter/wagon#190).
266 | var names wasm.NameMap
267 | if c := mod.Custom(wasm.CustomSectionName); c != nil {
268 | var nsec wasm.NameSection
269 | if err := nsec.UnmarshalWASM(bytes.NewReader(c.Data)); err != nil {
270 | return err
271 | }
272 | if len(nsec.Types[wasm.NameFunction]) > 0 {
273 | sub, err := nsec.Decode(wasm.NameFunction)
274 | if err != nil {
275 | return err
276 | }
277 | names = sub.(*wasm.FunctionNames).Names
278 | }
279 | }
280 | var fs []*wasmFunc
281 | for i, t := range mod.Function.Types {
282 | name := names[uint32(i+len(mod.Import.Entries))]
283 | body := mod.Code.Bodies[i]
284 | fs = append(fs, &wasmFunc{
285 | Type: types[t],
286 | Wasm: wasm.Function{
287 | Sig: types[t].Sig,
288 | Body: &body,
289 | Name: name,
290 | },
291 | Index: i + len(mod.Import.Entries),
292 | })
293 | }
294 |
295 | var exports []*wasmExport
296 | for _, e := range mod.Export.Entries {
297 | switch e.Kind {
298 | case wasm.ExternalFunction:
299 | exports = append(exports, &wasmExport{
300 | Index: int(e.Index),
301 | Name: e.FieldStr,
302 | })
303 | case wasm.ExternalMemory:
304 | // Ignore
305 | default:
306 | return fmt.Errorf("export type %d is not implemented", e.Kind)
307 | }
308 | }
309 |
310 | allfs := append(ifs, fs...)
311 | for _, e := range exports {
312 | e.Funcs = allfs
313 | }
314 | for _, f := range ifs {
315 | f.Mod = mod
316 | f.Funcs = allfs
317 | f.Types = types
318 | }
319 | for _, f := range fs {
320 | f.Mod = mod
321 | f.Funcs = allfs
322 | f.Types = types
323 | }
324 |
325 | var globals []*wasmGlobal
326 | for i, e := range mod.Global.Globals {
327 | // TODO: Consider mutability.
328 | // TODO: Use e.Type.Init.
329 | globals = append(globals, &wasmGlobal{
330 | Type: e.Type.Type,
331 | Index: i,
332 | Init: 0,
333 | })
334 | }
335 |
336 | if mod.Start != nil {
337 | return fmt.Errorf("start section must be nil but not")
338 | }
339 |
340 | tables := make([][]uint32, len(mod.Table.Entries))
341 | for _, e := range mod.Elements.Entries {
342 | v, err := mod.ExecInitExpr(e.Offset)
343 | if err != nil {
344 | return err
345 | }
346 | offset := v.(int32)
347 | if diff := int(offset) + int(len(e.Elems)) - int(len(tables[e.Index])); diff > 0 {
348 | tables[e.Index] = append(tables[e.Index], make([]uint32, diff)...)
349 | }
350 | copy(tables[e.Index][offset:], e.Elems)
351 | }
352 |
353 | var data []wasmData
354 | for _, e := range mod.Data.Entries {
355 | offset, err := mod.ExecInitExpr(e.Offset)
356 | if err != nil {
357 | return err
358 | }
359 | data = append(data, wasmData{
360 | Offset: int(offset.(int32)),
361 | Data: e.Data,
362 | })
363 | }
364 |
365 | var g errgroup.Group
366 | g.Go(func() error {
367 | out, err := os.Create(filepath.Join(outDir, "Go.cs"))
368 | if err != nil {
369 | return err
370 | }
371 | defer out.Close()
372 |
373 | if err := goTmpl.Execute(out, struct {
374 | Namespace string
375 | ImportFuncs []*wasmFunc
376 | }{
377 | Namespace: namespace,
378 | ImportFuncs: ifs,
379 | }); err != nil {
380 | return err
381 | }
382 | return nil
383 | })
384 | g.Go(func() error {
385 | return writeBitsCS(outDir, namespace)
386 | })
387 | g.Go(func() error {
388 | return writeJSCS(outDir, namespace)
389 | })
390 | g.Go(func() error {
391 | return writeInstCS(outDir, namespace, ifs, fs, exports, globals, types, tables)
392 | })
393 | g.Go(func() error {
394 | return writeMemInitData(outDir, data)
395 | })
396 | g.Go(func() error {
397 | return writeMemCS(outDir, namespace, int(mod.Memory.Entries[0].Limits.Initial))
398 | })
399 |
400 | if err := g.Wait(); err != nil {
401 | return err
402 | }
403 |
404 | return nil
405 | }
406 |
407 | var goTmpl = template.Must(template.New("Go.cs").Parse(`// Code generated by go2dotnet. DO NOT EDIT.
408 |
409 | using System;
410 | using System.Collections.Concurrent;
411 | using System.Collections.Generic;
412 | using System.Diagnostics;
413 | using System.Security.Cryptography;
414 | using System.Text;
415 | using System.Timers;
416 |
417 | namespace {{.Namespace}}
418 | {
419 | internal interface IImport
420 | {
421 | {{- range $value := .ImportFuncs}}
422 | {{$value.CSharp " " false false}}{{end}}
423 | }
424 |
425 | public class Go
426 | {
427 | class Import : IImport
428 | {
429 | internal Import(Go go)
430 | {
431 | this.go = go;
432 | }
433 | {{range $value := .ImportFuncs}}
434 | {{$value.CSharp " " true true}}{{end}}
435 | private Go go;
436 | }
437 |
438 | private class JSValues : JSObject.IValues
439 | {
440 | public JSValues(Go go)
441 | {
442 | this.go = go;
443 | }
444 |
445 | public object Get(string key)
446 | {
447 | switch (key)
448 | {
449 | case "_makeFuncWrapper":
450 | return new JSObject((object self, object[] args) =>
451 | {
452 | return this.go.MakeFuncWrapper((int)JSObject.ToDouble(args[0]));
453 | });
454 | case "_pendingEvent":
455 | return this.go.pendingEvent;
456 | }
457 | throw new KeyNotFoundException(key);
458 | }
459 |
460 | public void Set(string key, object value)
461 | {
462 | switch (key)
463 | {
464 | case "_pendingEvent":
465 | this.go.pendingEvent = (JSObject)value;
466 | return;
467 | }
468 | throw new KeyNotFoundException(key);
469 | }
470 |
471 | public void Remove(string key)
472 | {
473 | throw new NotImplementedException();
474 | }
475 |
476 | private Go go;
477 | }
478 |
479 | public Go()
480 | {
481 | this.import = new Import(this);
482 | this.taskQueue = new BlockingCollection(new ConcurrentQueue());
483 | }
484 |
485 | internal object LoadValue(int addr)
486 | {
487 | double f = this.mem.LoadFloat64(addr);
488 | if (f == 0)
489 | {
490 | return JSObject.Undefined;
491 | }
492 | if (!double.IsNaN(f))
493 | {
494 | return f;
495 | }
496 | int id = (int)this.mem.LoadUint32(addr);
497 | return this.values[id];
498 | }
499 |
500 | internal void StoreValue(int addr, object v)
501 | {
502 | const int NaNHead = 0x7FF80000;
503 | double? d = JSObject.ToDouble(v);
504 | if (d.HasValue)
505 | {
506 | if (double.IsNaN(d.Value))
507 | {
508 | this.mem.StoreInt32(addr + 4, NaNHead);
509 | this.mem.StoreInt32(addr, 0);
510 | return;
511 | }
512 | if (d.Value == 0)
513 | {
514 | this.mem.StoreInt32(addr + 4, NaNHead);
515 | this.mem.StoreInt32(addr, 1);
516 | return;
517 | }
518 | this.mem.StoreFloat64(addr, d.Value);
519 | return;
520 | }
521 | if (v == JSObject.Undefined)
522 | {
523 | this.mem.StoreFloat64(addr, 0);
524 | return;
525 | }
526 | switch (v)
527 | {
528 | case null:
529 | this.mem.StoreInt32(addr + 4, NaNHead);
530 | this.mem.StoreInt32(addr, 2);
531 | return;
532 | case true:
533 | this.mem.StoreInt32(addr + 4, NaNHead);
534 | this.mem.StoreInt32(addr, 3);
535 | return;
536 | case false:
537 | this.mem.StoreInt32(addr + 4, NaNHead);
538 | this.mem.StoreInt32(addr, 4);
539 | return;
540 | }
541 | int id = 0;
542 | if (this.ids.ContainsKey(v))
543 | {
544 | id = this.ids[v];
545 | }
546 | else
547 | {
548 | if (this.idPool.Count > 0)
549 | {
550 | id = this.idPool.Pop();
551 | }
552 | else
553 | {
554 | id = this.values.Count;
555 | }
556 | this.values[id] = v;
557 | this.goRefCounts[id] = 0;
558 | this.ids[v] = id;
559 | }
560 | this.goRefCounts[id]++;
561 | int typeFlag = 1;
562 | if (v is string)
563 | {
564 | typeFlag = 2;
565 | // There is no counterpart for Symbol in C#, then typeFlag = 3 is not used.
566 | }
567 | else if (v is JSObject && ((JSObject)v).IsFunction)
568 | {
569 | typeFlag = 4;
570 | }
571 | this.mem.StoreInt32(addr + 4, NaNHead | typeFlag);
572 | this.mem.StoreInt32(addr, id);
573 | }
574 |
575 | internal object[] LoadSliceOfValues(int addr)
576 | {
577 | var array = (int)this.mem.LoadInt64(addr);
578 | var len = (int)this.mem.LoadInt64(addr + 8);
579 | var a = new object[len];
580 | for (int i = 0; i < len; i++)
581 | {
582 | a[i] = this.LoadValue(array + i * 8);
583 | }
584 | return a;
585 | }
586 |
587 | public void Run()
588 | {
589 | Run(new string[0]);
590 | }
591 |
592 | public void Run(string[] args)
593 | {
594 | this.debugWriter = new Writer(Console.Error);
595 | this.stopwatch = Stopwatch.StartNew();
596 | this.mem = new Mem();
597 | this.inst = new Inst(this.mem, this.import);
598 | this.values = new Dictionary
599 | {
600 | {0, double.NaN},
601 | {1, 0.0},
602 | {2, null},
603 | {3, true},
604 | {4, false},
605 | {5, JSObject.Global},
606 | {6, JSObject.Go(new JSValues(this))},
607 | };
608 | this.goRefCounts = new Dictionary();
609 | this.ids = new Dictionary