コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
72aa5d7351
|
||
|
|
a68c0fedd6
|
||
|
|
c5ed30bc72
|
||
|
|
6f44e30fa1
|
||
|
|
3db40f07cb
|
||
|
|
ff8791d086
|
||
|
|
f7f445bd3d
|
||
|
|
68af14bbf8
|
||
|
|
7a23318be3
|
||
|
|
4072d9b117
|
||
|
|
bc366a0af2
|
||
|
|
0c896d44ee
|
||
|
|
9a9acc4b85
|
||
|
|
a7e2285691
|
||
|
|
093e16feec
|
||
|
|
70b1b79fc2
|
||
|
|
995e1bc1aa
|
||
|
|
1120373e67
|
||
|
|
43b3ed7077
|
||
|
|
04ab6b111b
|
||
|
|
5d6787e7d6
|
||
|
|
6960406965
|
||
|
|
9454310988
|
||
|
|
d3118d20af
|
||
|
|
78337c06dd
|
||
|
|
85fc0f8e9f
|
||
|
|
c19ae507cf
|
||
|
|
004041b342
|
||
|
|
08f69cf76d
|
||
|
|
e10bfbe406
|
||
|
|
1a46a76b59
|
||
|
|
e2f32a6722
|
||
|
|
5a23f4329e
|
||
|
|
f5fd6cebdb
|
||
|
|
48f6711f1a
|
||
|
|
859046f5aa
|
||
|
|
7c7a60807f
|
||
|
|
1b23b2937e
|
||
|
|
4135f52499
|
||
|
|
8fda0bfec5
|
||
|
|
7e353053c7
|
||
|
|
d744d218fb
|
||
|
|
772fa6b678
|
||
|
|
154bc6a5c0
|
||
|
|
593939c2d4
|
||
|
|
6730c8ce70
|
||
|
|
b6a1e6e43c
|
||
|
|
fd06fdafe7
|
||
|
|
20a119c6c8
|
||
|
|
cfa8141424
|
||
|
|
7a2a7e5593
|
||
|
|
1a61091ec2
|
||
|
|
bbb1bd3562
|
||
|
|
db8017a8ce
|
||
|
|
bc69ec5681
|
||
|
|
8f6c3105ef
|
||
|
|
de6c1b8b44
|
||
|
|
ffd57fabd0
|
||
|
|
a80d5dec88
|
||
|
|
8bccf5ed01
|
||
|
|
7c831441fc
|
||
|
|
7cd54ff3e8
|
||
|
|
3c3f5aed69
|
||
|
|
913e1a8643
|
||
|
|
f6c7dac970
|
||
|
|
95db23f253
|
||
|
|
62044a3351
|
||
|
|
694b50d375
|
||
|
|
122d85068d
|
||
|
|
620670915f
|
||
|
|
10974242aa
|
||
|
|
36b2ada16a
|
||
|
|
8428057eb4
|
||
|
|
1133daf764
|
||
|
|
b09070e8df
|
||
|
|
cde0b8f498
|
||
|
|
916dd278b2
|
||
|
|
d6d0792207
|
||
|
|
a7bae506a7
|
||
|
|
d05906de7b
|
||
|
|
a8300041e3
|
||
|
|
8bd0d2bc0e
|
||
|
|
cf5f4acf72
|
||
|
|
0d6709d518
|
||
|
|
12bd10164b
|
||
|
|
6287e74fe5
|
||
|
|
8956b7c8d5
|
||
|
|
60c6a37f89
|
||
|
|
9a9c2ec405
|
||
|
|
103b612082
|
||
|
|
9e1da1839e
|
||
|
|
c19e12aa87
|
||
|
|
ed4c38772f
|
||
|
|
d31fd77aee
|
||
|
|
eb0199131d
|
||
|
|
36935bdf1d
|
||
|
|
7d9a9f1cb8
|
||
|
|
3ce2483062
|
||
|
|
fc8a07f935
|
||
|
|
d1279c25fa
|
||
|
|
048c6d6707
|
||
|
|
3a29862423
|
||
|
|
8c69864456
|
||
|
|
8a7b328db4
|
||
|
|
8517bf5f50
|
||
|
|
b928101e3e
|
||
|
|
7fb671e8c6
|
||
|
|
20ff47edce
|
||
|
|
8f9b7c725f
|
||
|
|
499f8ba078
|
||
|
|
66f2d398b7
|
||
|
|
935bca6fbb
|
||
|
|
4c7ef12361
|
||
|
|
65e7864221
|
||
|
|
25430c4dcf
|
||
|
|
f0234d21e4
|
||
|
|
bfe23707f0
|
||
|
|
e74af227d8
|
||
|
|
2b5901379f
|
||
|
|
deb94b3f29
|
||
|
|
74a65b7a8b
|
||
|
|
a4cc0f3220
|
||
|
|
86f889cbd2
|
||
|
|
c2f48230f3
|
||
|
|
4153956b37
|
||
|
|
3763db1cfc
|
||
|
|
9bcab1ae28
|
||
|
|
6e13a4d1c2
|
||
|
|
8dc87d63be
|
||
|
|
0afb7afc21
|
||
|
|
2769a29808
|
||
|
|
1f21b4c49c
|
||
|
|
cafc6d6e48
|
||
|
|
49a2ce29b2
|
||
|
|
d728c8d056
|
||
|
|
b6eac20941
|
||
|
|
d8589007b3
|
||
|
|
85596f76f7
|
||
|
|
018999ff5e
|
||
|
|
c5da497bb3
|
||
|
|
f46cb08f85
|
||
|
|
b0a5293b89
|
||
|
|
67a1b4fa31
|
||
|
|
2d0fb2c47a
|
||
|
|
45d5164afa
|
||
|
|
ba20fc8187
|
||
|
|
669b24c2b3
|
||
|
|
91a3e3f762
|
||
|
|
722ae62326
|
||
|
|
fee1f293c7
|
||
|
|
b6764fe637
|
||
|
|
01e368207d
|
||
|
|
29ea2ea45c
|
||
|
|
1d60d8b245
|
||
|
|
8f2aafdffd
|
||
|
|
f26816343f
|
||
|
|
0cab8972e0
|
||
|
|
f2aa668cf6
|
||
|
|
ed27979f64
|
||
|
|
7b958ea171
|
||
|
|
332dab3889
|
||
|
|
75d457a7ab
|
||
|
|
50e1801878
|
||
|
|
793d010bdb
|
||
|
|
b564b0b185
|
||
|
|
6d83fe93d8
|
||
|
|
db9c3747ea
|
||
|
|
7d887afe5a
|
||
|
|
ac34830367
|
||
|
|
8ed188d0e2
|
||
|
|
9c55c08caf
|
||
|
|
42868023f3
|
||
|
|
e146b36fa0
|
||
|
|
5fac495848
|
||
|
|
4fd519249f
|
||
|
|
1b26df959f
|
||
|
|
3cd67212a1
|
||
|
|
46692dfe95
|
||
|
|
e8d9cef129
|
||
|
|
18036cd74e
|
||
|
|
c8f857d2b4
|
||
|
|
ac7f797566
|
||
|
|
8beae1a277
|
||
|
|
6eb4d7c9af
|
||
|
|
a843f460de
|
||
|
|
27f04c7560
|
||
|
|
43c0ce88b3
|
||
|
|
00f0d991c1
|
||
|
|
784d294ca6
|
||
|
|
260d427bcf
|
||
|
|
b62f4a3a7d
|
||
|
|
79a408cafd
|
||
|
|
807df7df8a
|
||
|
|
0c5e3066c1
|
||
|
|
fbaff95503
|
||
|
|
8dec38a911
|
||
|
|
902d729c19
|
||
|
|
79f8ff8839
|
||
|
|
9a630ecb5a
|
||
|
|
d9e6132a1f
|
||
|
|
e685e7aa40
|
||
|
|
bf49fe9984
|
||
|
|
c05a1479f9
|
||
|
|
80ddb663b0
|
||
|
|
2f1bbc3828
|
||
|
|
e911f6e83f
|
||
|
|
6162ce5c19
|
||
|
|
59dcb82b49
|
||
|
|
d37726cdf6
|
||
|
|
0c09cf4a51
|
||
|
|
0d4809924d
|
||
|
|
1e97e7d8fe
|
||
|
|
06cfefe1b4
|
||
|
|
37b1371f57
|
||
|
|
9db756c974
|
||
|
|
43f3161ebb
|
||
|
|
4b3b74edae
|
||
|
|
5129ece749
|
||
|
|
24ef4135cf
|
||
|
|
044fdbf1eb
|
||
|
|
9e1ad6c133
|
||
|
|
6d8def9f08
|
||
|
|
7a9f1ff6e8
|
||
|
|
82db144b86
|
||
|
|
d3fb73ed94
|
||
|
|
7dd777fbc6
|
||
|
|
aa17df08d8
|
||
|
|
e5c4485f16
|
||
|
|
9b901f91b6
|
||
|
|
2b24a407e6
|
||
|
|
150b4818d4
|
||
|
|
34b7d60ca6
|
||
|
|
7dc6083fd7
|
||
|
|
245fb9c323
|
||
|
|
42c3bc4f4b
|
||
|
|
d273f99593
|
||
|
|
e1763e0c81
|
||
|
|
7221ce3aca
|
||
|
|
5f3ad96ea2
|
||
|
|
4e0bf831c5
|
||
|
|
0fedfd5804
|
||
|
|
f11225e2a1
|
||
|
|
92e8c43160
|
||
|
|
5fb9eae7a0
|
||
|
|
f109232cae
|
||
|
|
1596a048cd
|
||
|
|
0b0c795d7a
|
||
|
|
2be3c3d28b
|
||
|
|
3f9e4ebca4
|
||
|
|
03042b17e7
|
||
|
|
5e6d74dfee
|
||
|
|
40d68416c2
|
||
|
|
de6472c34b
|
||
|
|
55c8bffb70
|
||
|
|
8ca66bceb8
|
||
|
|
865f5117ea
|
||
|
|
b30f7a818b
|
||
|
|
95786a1f0a
|
||
|
|
cc07e2a83d
|
||
|
|
08e5e432b7
|
||
|
|
1e9b039cef
|
||
|
|
bad39fe0db
|
||
|
|
a5567a804d
|
||
|
|
a9cb4a9cda
|
||
|
|
9e9b5277af
|
||
|
|
1d8705c7ee
|
||
|
|
14683c7909
|
||
|
|
42b123ebc3
|
||
|
|
b0114abdb7
|
||
|
|
c21de5b3eb
|
||
|
|
bd891d9a1e
|
||
|
|
d2bef10085
|
||
|
|
3eafcdc70e
|
||
|
|
6f26fc95fa
|
||
|
|
88ce786d05
|
||
|
|
d69ae5f06e
|
||
|
|
d42d8a6764
|
||
|
|
8f9ace2dc8
|
||
|
|
c416e955a4
|
||
|
|
7362e70ab8
|
||
|
|
c9741836a5
|
||
|
|
afd57d758d
|
||
|
|
c56432dbd6
|
||
|
|
9493aef779
|
||
|
|
5d55f2c083
|
||
|
|
09918c2858
|
||
|
|
a687bba0ff
|
||
|
|
bb591b6fef
|
||
|
|
27d7294290
|
||
|
|
8d1cf91499
|
||
|
|
b2a1900616
|
||
|
|
f786250866
|
||
|
|
20dfba6e7e
|
||
|
|
5e40f45910
|
||
|
|
ea4f096bc4
|
||
|
|
d7812f39dc
|
||
|
|
77fdf60ec9
|
||
|
|
bcb9925953
|
||
|
|
ec7d8a1da4
|
||
|
|
098d6e498b
|
||
|
|
ccf37dd1d3
|
||
|
|
2ce3068d54
|
||
|
|
c2a1990501
|
||
|
|
4ac25584b9
|
||
|
|
5e40f30124
|
||
|
|
9d541e06b9
|
||
|
|
bca7b5707e
|
||
|
|
a17289a2da
|
||
|
|
71e6b71056
|
||
|
|
13a0602adb
|
||
|
|
6a0c993755
|
||
|
|
484a26ec45
|
||
|
|
a121a598b6
|
||
|
|
6dd70413a9
|
||
|
|
ac482b6041
|
||
|
|
c2761c0796
|
||
|
|
3bbd411d86
|
||
|
|
324faabb96
|
||
|
|
32b706cb8b
|
||
|
|
aa97c52b38
|
||
|
|
a2f0231739
|
||
|
|
2905192d3a
|
||
|
|
ee6f6bd9c1
|
||
|
|
8853f5e403
|
||
|
|
867de7aa73
|
||
|
|
e384d7e490
|
||
|
|
87e060d71d
|
||
|
|
9c6167d224
|
||
|
|
a8a91103e1
|
||
|
|
4a2f4b2dbb
|
||
|
|
33fc45639b
|
||
|
|
7af803e46e
|
||
|
|
48e8287704
|
||
|
|
7eff4591f0
|
||
|
|
5b1bb4ad6e
|
||
|
|
7f3e6b0019
|
||
|
|
7519a11851
|
||
|
|
4193c40f41
|
||
|
|
cd68bf86b0
|
||
|
|
9948204265
|
||
|
|
25670bde90
|
||
|
|
ae230c0e10
|
||
|
|
7ee8f1ccf0
|
||
|
|
da88898a67
|
||
|
|
3c63ba0729
|
||
|
|
e7382ac289
|
||
|
|
ee7e4f43bc
|
||
|
|
7dc6e9fb40
|
||
|
|
803534d804
|
||
|
|
a25803fa30
|
||
|
|
e42401670f
|
||
|
|
a139326c39
|
||
|
|
496c237f50
|
||
|
|
dfbcbded98
|
||
|
|
2ebbe3ced0
|
||
|
|
9671cba5a1
|
||
|
|
947532f064
|
||
|
|
6e3594eb01
|
||
|
|
abc7b2cde2
|
||
|
|
68d862ded0
|
||
|
|
d3060fd202
|
検索条件に一致するファイルはありません
+51
-39
@@ -1,61 +1,73 @@
|
|||||||
# v1.10.0 - Lua スクリプト for YMM4
|
# v1.18.0 - Lua スクリプト for YMM4
|
||||||
|
|
||||||
エフェクトパネルへ新しいパラメータ入力欄を追加したリリースです。整数スライダー 4 本と、
|
AviUtl の音声取得関数 obj.getaudio を追加したリリースです。編集中のシーン全体の音声、エフェクトを付けたアイテム自身の音声、任意の音声ファイルから、PCM・周波数スペクトラム・フーリエ変換のデータを取得し、音に反応する演出をスクリプトで作れます。あわせて obj.getobject が返すテーブルへ他アイテムのメタデータを追加し、合成音声アイテムも参照の対象にしました。どちらも従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の両方で動作し、音声の取得とメタデータの解決はホスト側で一度だけ行うため、実行結果は両エンジンで一致します。
|
||||||
テキスト・フォント・フォルダ・ファイルの文字列入力をスクリプトから参照できるようにしました。
|
|
||||||
文字列パラメータは MoonSharp とネイティブの両エンジンで同じ名前から参照でき、ネイティブでは
|
|
||||||
共有メモリの文字列領域を必要量に応じて拡張・縮小します。あわせて毎フレームのアロケーションを
|
|
||||||
見直し、補完候補を拡充しました。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 新機能・機能改善
|
## 新機能
|
||||||
|
|
||||||
### 1. 整数スライダー obj.slider0〜3
|
### obj.getaudio(buf, file [, type, size])
|
||||||
|
|
||||||
数値スライダーを 4 本追加しました。各値は `obj.slider0`〜`obj.slider3` として参照できます。
|
音声データを取得します。
|
||||||
|
|
||||||
- 値は整数で、小数は扱いません。表示範囲は `obj.slider0` が 1〜10、`obj.slider1` が 0〜100、
|
local buf = {}
|
||||||
`obj.slider2` が 0〜1000、`obj.slider3` が -1000〜1000 です。
|
local n, rate = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||||
- 状態の切り替えなど、補間を伴わない整数値の受け渡しに使えます。
|
for i = 1, n do
|
||||||
- MoonSharp・ネイティブ・CPU/GPU カーネルのいずれのレーンからも参照できます。
|
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||||
|
end
|
||||||
|
|
||||||
### 2. 文字列パラメータ obj.text / obj.font / obj.dir / obj.file_*
|
- buf に渡したテーブルの buf[1]~buf[n] へデータを格納し、取得したデータ数とサンプリングレートを返します。buf に nil を渡すと、テーブルを 3 番目の戻り値として返します。
|
||||||
|
- file には音声ファイルのパスを指定します。特別な名前として "audiobuffer" と "itembuffer" を受け付けます。
|
||||||
|
- "audiobuffer" は編集中のシーン全体の音声で、タイムライン上の全アイテムを合成した音声を取得します。AviUtl の「編集中の音声データ」と同じ解釈です。読み取り位置はタイムラインの現在の再生位置です。
|
||||||
|
- "itembuffer" は AviUtl に存在しない YMM4 向けの独自拡張で、このエフェクトを付けたアイテム自身の音声を取得します。音量・パン・フェード・音声エフェクトを適用した後の音声で、合成音声アイテムに付ければそのセリフの音声だけに反応できます。音声を持たないアイテム(画像や図形等)ではデータ数 0 になります。
|
||||||
|
- type は取得するデータの種類で、省略すると "pcm" になります。
|
||||||
|
- "pcm" : 16bit スケール基準(-32768~32767)のモノラル PCM です。現在位置から連続したサンプルを返します。
|
||||||
|
- "spectrum" : 周波数帯ごとの音量データです。size は分割する帯域の数で、最大 512、省略時は 32 です。
|
||||||
|
- "fourier" : 離散フーリエ変換の振幅データ(0.0~1.0 目安)です。周波数範囲は 1/2048~1/2 で、省略時は 1024 個です。
|
||||||
|
- "xxxx.l" / "xxxx.r" : 上記種別の左 / 右チャンネル版です。無指定のときは左右の平均です。
|
||||||
|
- size は取得するデータ数で、取得できた数が指定より少ないことがあります。1 回で取得できるデータ数は最大 1024 個です。
|
||||||
|
- ファイルと "itembuffer" の読み取り位置はオブジェクトの現在の再生位置(obj.time)です。spectrum / fourier は読み取り位置からの区間を解析して返します。
|
||||||
|
- 取得できない場合はデータ数 0 を返し、エラーにはなりません。
|
||||||
|
|
||||||
テキスト・フォント・フォルダ・ファイルの入力欄を追加しました。
|
### obj.getobject のメタデータ
|
||||||
|
|
||||||
- `obj.text` はテキスト入力欄の文字列、`obj.font` はフォント名、`obj.dir` はフォルダのパスです。
|
obj.getobject(tag [, frame]) が返すテーブルへ、他アイテムのメタデータを追加しました。
|
||||||
- ファイル選択は種類ごとに `obj.file_video` / `obj.file_audio` / `obj.file_image` /
|
|
||||||
`obj.file_project` / `obj.file_mp4` / `obj.file_exo` / `obj.file_subtitle` /
|
|
||||||
`obj.file_shader` で参照し、選択したファイルのパスを取得します。
|
|
||||||
- 取得したパスは `obj.load` へ渡して画像・動画の読み込みに使えます。
|
|
||||||
- MoonSharp とネイティブの両エンジンで同じ名前から参照できます。
|
|
||||||
|
|
||||||
### 3. 補完候補の拡充
|
local o = obj.getobject("BGM")
|
||||||
|
if o and o.exist then
|
||||||
|
obj.load("text", o.character .. ": " .. o.text)
|
||||||
|
end
|
||||||
|
|
||||||
スクリプトエディタの補完候補へ `obj.slider0`〜`obj.slider3` と、追加した文字列パラメータの
|
- .length : アイテムのフレーム数を返します。
|
||||||
各名前を加えました。
|
- .volume : 音量設定の現在値を返します。合成音声アイテム以外は 0 です。
|
||||||
|
- .character : キャラクター名を返します。合成音声アイテム以外は空文字列です。
|
||||||
|
- .text : セリフまたは表示テキストを返します。合成音声アイテムとテキストアイテム以外は空文字列です。
|
||||||
|
- .kind : アイテムの種別名を返します。
|
||||||
|
- 合成音声アイテムが参照の対象になりました。座標・拡大率・回転・不透明度は字幕の表示情報を返します。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 互換性・後方互換
|
## 互換性・後方互換
|
||||||
|
|
||||||
- スライダーと文字列パラメータは、スクリプト本体でそれらを参照したときだけエフェクトパネルへ
|
- obj.getaudio は AviUtl 互換の関数として追加しました。"audiobuffer" の意味は AviUtl の「編集中の音声データ」に合わせています。buf の添字は 1 始まりで、AviUtl 向けの既存スクリプトの慣例と同じです。
|
||||||
表示されます。参照しない既存スクリプトの表示と挙動は変わりません。
|
- "itembuffer" は AviUtl / AviUtl2 に存在しない YMM4 向けの独自拡張です。AviUtl 向けに書かれた既存スクリプトへの影響はありません。
|
||||||
- CPU/GPU カーネルは数値計算に特化するため、文字列パラメータは扱いません。文字列を参照する
|
- obj.getaudio が 1 回で取得できるデータ数の上限は 1024 個です。AviUtl の代表的な用途(spectrum の帯域数 32 前後、fourier の 1024 個、pcm の 1000 個前後)はいずれも上限の範囲に収まります。
|
||||||
スクリプトは MoonSharp かネイティブで実行してください。
|
- obj.getobject の既存フィールドの意味と値に変更はありません。メタデータは追加のみで、従来の呼び出しはそのまま動きます。
|
||||||
- トラックバー・チェックボックス・カラー・AviUtl 互換ヘッダの既存挙動は変わりません。
|
- 未対応の type や読み取りの失敗はデータ数 0 の戻り値で表し、スクリプトを停止させません。
|
||||||
|
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.17.0 までの構文拡張と既存の API に変更はありません。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 内部実装
|
## 内部実装
|
||||||
|
|
||||||
- ネイティブの共有メモリへ文字列パラメータ領域を追加し、容量をワーカーの起動引数にしました。
|
- PCM・スペクトラム・フーリエ変換の計算は LuaScript.Compat へ追加した AviUtlAudioConverter が担います。pcm は ±32768 のスケール、spectrum は窓 1024 の FFT の帯域平均を 2/N×32768 で正規化、fourier は窓 2048 の FFT の振幅を 2/N で正規化した値です。計算はホスト側で一度だけ行い、両エンジンは同じ結果を受け取るため、エンジン間の一致は構造的に保証されます。
|
||||||
必要量が容量を超えると 2 倍へ拡張し、容量の半分以下に収まると縮小します。最小は 64KB で、
|
- 音声の取得は新設の AudioSampleProvider が担い、3 つの経路を持ちます。"audiobuffer" はシーンの公開メソッド Scene.TryCreateAudioSource で得たタイムライン音源を用います。これは公式コミュニティプラグインの音量取得系の映像エフェクトが同じ状況(映像エフェクトからの音声参照)で使っているのと同じ経路です。ファイルはプラグイン公開 API の AudioFileSourceFactory を用います。
|
||||||
容量の変化はワーカーの再生成のみで完結します。
|
- "itembuffer" は EffectedItemSourceForEditorInfo を直接生成します。これは YMM4 のエディタ向けインターフェイス IEditorInfo.CreateItemAudioSource が返す実体と同じ公開クラスで、プロジェクトのサンプリングレートと音声アップサンプリング設定を反映した、YMM4 本体の編集時再生と同じ音声を返します。ただしこのクラスはプラグイン公開 API のアセンブリ(YukkuriMovieMaker.Plugin)ではなく本体側にあり、互換性の保証がありません。そのため生成はインライン展開を禁止した専用メソッドへ隔離し、将来の本体更新で型が失われた場合に発生する TypeLoadException を捕捉して、プラグイン公開 API の IAudioItem.CreateAudioSource(音量等を適用する前の音声)へ縮退します。例外がスクリプトへ漏れることはありません。
|
||||||
- 文字列パラメータの変更検出をバージョン方式へ変更し、フレームごとの署名文字列の生成を
|
- "itembuffer" の自アイテムの特定は、シーンのアイテム一覧から自分のエフェクトを VideoEffects に含むアイテムを参照の同一性で探します。
|
||||||
やめました。値の参照が変わったときだけ版数を進めます。
|
- 音源はファイルパス・シーン・アイテムごとに 1 件ずつキャッシュし、対象が変わったときだけ作り直します。読み取り緩衝と結果配列は伸長のみの再利用で、定常状態の毎フレームの割り当てはありません。失敗はすべてデータ数 0 の戻り値で表し、例外を制御フローに使いません。
|
||||||
- ネイティブの文字列書き込みで、名前のバイト列をキャッシュし、値のエンコード先バッファを
|
- 高速ランタイムにはプロセス間手順の呼出種別 CbKindGetAudio を追加しました。要求はタグ領域へ file と type の 2 文字列、応答は同じタグ領域へ double 配列で返します。タグ領域は 8192 バイトのため、1 回の取得上限が 1024 個になります。この返却方法は obj.setanchor の座標返却と同じ手口です。
|
||||||
再利用します。
|
- 音声は描画鍵で検知できない外部状態のため、obj.getaudio でデータを取得したフレームは描画キャッシュを使わず毎回再実行します。obj.load("scene") と同じ扱いです。
|
||||||
- スライダーの値は MoonSharp の obj テーブル・ネイティブのフィールド・CPU/GPU カーネルの
|
- obj.getobject のメタデータは、SceneObjectInfo へ Length / Volume / Character / Text / Kind を追加し、シーンオブジェクトリゾルバーを IVideoItem 基準へ改めて合成音声アイテムも列挙の対象にしました。高速ランタイムの応答は、数値を既存の結果領域、3 つの文字列をタグ領域へ区切り文字付きで返します。同じタグと同じフレームへの連続した問い合わせのフレーム内キャッシュは従来のままです。
|
||||||
ユニフォームへ配線しました。スクリプトの使用検出は obj メンバを汎用的に走査する方式へ
|
- obj.effect と obj.brush が共有するパラメータ適用部品の名前を Ymm4PropertyBinder から ParameterBinder へ改めました。実装と適用結果に変更はありません。
|
||||||
再設計しました。
|
- ドキュメントは付属の 8 言語、サイトの obj の関数・リファレンス・トップ・制限事項のページ、README を更新しました。あわせて既存ドキュメントの冗長なカッコ補足と強調記法を整理しました。
|
||||||
|
- テストは 3347 件です。v1.17.0 の 3332 件から、音声変換の pcm のスケールとチャンネル選択・不足時の短縮・スペクトラムの帯域位置・フーリエの正規化・未対応種別、MoonSharp レーンの getaudio の委譲の往復・既定値・失敗時の 0 返し・データ数の切り詰め、高速ランタイムの getaudio の呼出種別の往復と失敗時の 0 返し、両エンジンの getobject のメタデータの往復の検証を追加しました。ソリューションは x64 で 0 個の警告、0 個のエラーです。
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
========================================
|
========================================
|
||||||
Luaスクリプト for YMM4 v1.10.0
|
Luaスクリプト for YMM4 v1.18.0
|
||||||
========================================
|
========================================
|
||||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||||
ピクセルを直接制御できるプラグインです。
|
ピクセルを直接制御できるプラグインです。
|
||||||
|
|||||||
@@ -73,6 +73,10 @@ jobs:
|
|||||||
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||||
|
|
||||||
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
|
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Kernel.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
|
||||||
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
|
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
|
||||||
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
||||||
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlAudioConverter
|
||||||
|
{
|
||||||
|
public const int MaxSamples = 1024;
|
||||||
|
public const int SpectrumWindow = 1024;
|
||||||
|
public const int FourierWindow = 2048;
|
||||||
|
public const int SpectrumBins = SpectrumWindow / 2;
|
||||||
|
|
||||||
|
private const double PcmScale = 32768d;
|
||||||
|
|
||||||
|
private readonly double[] _mono = new double[FourierWindow];
|
||||||
|
private readonly double[] _real = new double[FourierWindow];
|
||||||
|
private readonly double[] _imag = new double[FourierWindow];
|
||||||
|
|
||||||
|
private enum DataKind
|
||||||
|
{
|
||||||
|
Unknown,
|
||||||
|
Pcm,
|
||||||
|
Spectrum,
|
||||||
|
Fourier,
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int RequiredFrames(string type, int size)
|
||||||
|
{
|
||||||
|
var (kind, _) = Parse(type);
|
||||||
|
return kind switch
|
||||||
|
{
|
||||||
|
DataKind.Pcm => ResolveCount(kind, size),
|
||||||
|
DataKind.Spectrum => SpectrumWindow,
|
||||||
|
DataKind.Fourier => FourierWindow,
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Convert(string type, ReadOnlySpan<float> interleaved, int frames, int size, Span<double> destination)
|
||||||
|
{
|
||||||
|
var (kind, channel) = Parse(type);
|
||||||
|
if (kind == DataKind.Unknown || frames <= 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
int window = kind switch
|
||||||
|
{
|
||||||
|
DataKind.Pcm => Math.Min(frames, ResolveCount(kind, size)),
|
||||||
|
DataKind.Spectrum => SpectrumWindow,
|
||||||
|
_ => FourierWindow,
|
||||||
|
};
|
||||||
|
FillMono(interleaved, frames, channel, window);
|
||||||
|
|
||||||
|
switch (kind)
|
||||||
|
{
|
||||||
|
case DataKind.Pcm:
|
||||||
|
{
|
||||||
|
int count = Math.Min(ResolveCount(kind, size), frames);
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
destination[i] = Math.Clamp(_mono[i] * PcmScale, -32768d, 32767d);
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
case DataKind.Spectrum:
|
||||||
|
{
|
||||||
|
int bands = ResolveCount(kind, size);
|
||||||
|
Fft(SpectrumWindow);
|
||||||
|
double scale = 2d / SpectrumWindow * PcmScale;
|
||||||
|
for (int b = 0; b < bands; b++)
|
||||||
|
{
|
||||||
|
int start = b * SpectrumBins / bands;
|
||||||
|
int end = (b + 1) * SpectrumBins / bands;
|
||||||
|
if (end <= start)
|
||||||
|
end = start + 1;
|
||||||
|
double sum = 0d;
|
||||||
|
for (int bin = start; bin < end; bin++)
|
||||||
|
sum += Magnitude(bin);
|
||||||
|
destination[b] = sum / (end - start) * scale;
|
||||||
|
}
|
||||||
|
return bands;
|
||||||
|
}
|
||||||
|
case DataKind.Fourier:
|
||||||
|
{
|
||||||
|
int count = ResolveCount(kind, size);
|
||||||
|
Fft(FourierWindow);
|
||||||
|
double scale = 2d / FourierWindow;
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
destination[i] = Magnitude(i + 1) * scale;
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ResolveCount(DataKind kind, int size)
|
||||||
|
{
|
||||||
|
int fallback = kind == DataKind.Spectrum ? 32 : MaxSamples;
|
||||||
|
int max = kind == DataKind.Spectrum ? SpectrumBins : MaxSamples;
|
||||||
|
return size <= 0 ? Math.Min(fallback, max) : Math.Clamp(size, 1, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (DataKind Kind, int Channel) Parse(string type)
|
||||||
|
{
|
||||||
|
int channel = 0;
|
||||||
|
int length = type.Length;
|
||||||
|
if (length >= 2 && type[length - 2] == '.')
|
||||||
|
{
|
||||||
|
char suffix = type[length - 1];
|
||||||
|
if (suffix == 'l')
|
||||||
|
channel = 1;
|
||||||
|
else if (suffix == 'r')
|
||||||
|
channel = 2;
|
||||||
|
if (channel != 0)
|
||||||
|
length -= 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
var name = type.AsSpan(0, length);
|
||||||
|
DataKind kind = DataKind.Unknown;
|
||||||
|
if (name.SequenceEqual("pcm"))
|
||||||
|
kind = DataKind.Pcm;
|
||||||
|
else if (name.SequenceEqual("spectrum"))
|
||||||
|
kind = DataKind.Spectrum;
|
||||||
|
else if (name.SequenceEqual("fourier"))
|
||||||
|
kind = DataKind.Fourier;
|
||||||
|
return (kind, channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FillMono(ReadOnlySpan<float> interleaved, int frames, int channel, int window)
|
||||||
|
{
|
||||||
|
int available = Math.Min(frames, window);
|
||||||
|
for (int i = 0; i < available; i++)
|
||||||
|
{
|
||||||
|
float left = interleaved[i * 2];
|
||||||
|
float right = interleaved[i * 2 + 1];
|
||||||
|
_mono[i] = channel switch
|
||||||
|
{
|
||||||
|
1 => left,
|
||||||
|
2 => right,
|
||||||
|
_ => (left + right) * 0.5d,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for (int i = available; i < window; i++)
|
||||||
|
_mono[i] = 0d;
|
||||||
|
}
|
||||||
|
|
||||||
|
private double Magnitude(int bin) =>
|
||||||
|
Math.Sqrt(_real[bin] * _real[bin] + _imag[bin] * _imag[bin]);
|
||||||
|
|
||||||
|
private void Fft(int n)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
_real[i] = _mono[i];
|
||||||
|
_imag[i] = 0d;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 1, j = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
int bit = n >> 1;
|
||||||
|
for (; (j & bit) != 0; bit >>= 1)
|
||||||
|
j ^= bit;
|
||||||
|
j |= bit;
|
||||||
|
if (i < j)
|
||||||
|
{
|
||||||
|
(_real[i], _real[j]) = (_real[j], _real[i]);
|
||||||
|
(_imag[i], _imag[j]) = (_imag[j], _imag[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int len = 2; len <= n; len <<= 1)
|
||||||
|
{
|
||||||
|
double angle = -2d * Math.PI / len;
|
||||||
|
double wRe = Math.Cos(angle);
|
||||||
|
double wIm = Math.Sin(angle);
|
||||||
|
for (int i = 0; i < n; i += len)
|
||||||
|
{
|
||||||
|
double curRe = 1d;
|
||||||
|
double curIm = 0d;
|
||||||
|
for (int k = 0; k < len / 2; k++)
|
||||||
|
{
|
||||||
|
int a = i + k;
|
||||||
|
int b = i + k + len / 2;
|
||||||
|
double tRe = _real[b] * curRe - _imag[b] * curIm;
|
||||||
|
double tIm = _real[b] * curIm + _imag[b] * curRe;
|
||||||
|
_real[b] = _real[a] - tRe;
|
||||||
|
_imag[b] = _imag[a] - tIm;
|
||||||
|
_real[a] += tRe;
|
||||||
|
_imag[a] += tIm;
|
||||||
|
double nextRe = curRe * wRe - curIm * wIm;
|
||||||
|
curIm = curRe * wIm + curIm * wRe;
|
||||||
|
curRe = nextRe;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class AviUtlGlobalFunctions
|
||||||
|
{
|
||||||
|
public static int BitOr(double a, double b) => ToBitOperand(a) | ToBitOperand(b);
|
||||||
|
|
||||||
|
public static int BitAnd(double a, double b) => ToBitOperand(a) & ToBitOperand(b);
|
||||||
|
|
||||||
|
public static int BitXor(double a, double b) => ToBitOperand(a) ^ ToBitOperand(b);
|
||||||
|
|
||||||
|
public static int BitShift(double value, double shift)
|
||||||
|
{
|
||||||
|
int v = ToBitOperand(value);
|
||||||
|
int n = ToBitOperand(shift);
|
||||||
|
return n >= 0 ? v << n : v >> -n;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int ToBitOperand(double value)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(value))
|
||||||
|
return 0;
|
||||||
|
if (value <= int.MinValue)
|
||||||
|
return int.MinValue;
|
||||||
|
if (value >= int.MaxValue)
|
||||||
|
return int.MaxValue;
|
||||||
|
return (int)Math.Ceiling(value - 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int RgbCompose(double r, double g, double b) =>
|
||||||
|
(ToColorChannel(r) << 16) | (ToColorChannel(g) << 8) | ToColorChannel(b);
|
||||||
|
|
||||||
|
public static void RgbComponents(double color, out int r, out int g, out int b)
|
||||||
|
{
|
||||||
|
int c = ToColor(color);
|
||||||
|
r = (c >> 16) & 0xFF;
|
||||||
|
g = (c >> 8) & 0xFF;
|
||||||
|
b = c & 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int RgbInterpolate(double r1, double g1, double b1, double r2, double g2, double b2, double t) =>
|
||||||
|
RgbCompose(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t);
|
||||||
|
|
||||||
|
public static int HsvCompose(double h, double s, double v)
|
||||||
|
{
|
||||||
|
h = WrapHue(h);
|
||||||
|
s = ClampRatio(s);
|
||||||
|
v = ClampRatio(v);
|
||||||
|
|
||||||
|
double c = v * s;
|
||||||
|
double x = c * (1d - Math.Abs(h / 60d % 2d - 1d));
|
||||||
|
double m = v - c;
|
||||||
|
int sector = (int)Math.Floor(h / 60d);
|
||||||
|
|
||||||
|
double r, g, b;
|
||||||
|
if (sector == 0) { r = c; g = x; b = 0d; }
|
||||||
|
else if (sector == 1) { r = x; g = c; b = 0d; }
|
||||||
|
else if (sector == 2) { r = 0d; g = c; b = x; }
|
||||||
|
else if (sector == 3) { r = 0d; g = x; b = c; }
|
||||||
|
else if (sector == 4) { r = x; g = 0d; b = c; }
|
||||||
|
else { r = c; g = 0d; b = x; }
|
||||||
|
|
||||||
|
return (ToColorChannel(RoundHalfUp((r + m) * 255d)) << 16) |
|
||||||
|
(ToColorChannel(RoundHalfUp((g + m) * 255d)) << 8) |
|
||||||
|
ToColorChannel(RoundHalfUp((b + m) * 255d));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void HsvComponents(double color, out int h, out int s, out int v)
|
||||||
|
{
|
||||||
|
RgbComponents(color, out int r, out int g, out int b);
|
||||||
|
double rf = r / 255d;
|
||||||
|
double gf = g / 255d;
|
||||||
|
double bf = b / 255d;
|
||||||
|
|
||||||
|
double max = Math.Max(rf, Math.Max(gf, bf));
|
||||||
|
double min = Math.Min(rf, Math.Min(gf, bf));
|
||||||
|
double delta = max - min;
|
||||||
|
|
||||||
|
double hue = 0d;
|
||||||
|
if (delta > 0d)
|
||||||
|
{
|
||||||
|
if (max == rf)
|
||||||
|
hue = 60d * (((gf - bf) / delta % 6d + 6d) % 6d);
|
||||||
|
else if (max == gf)
|
||||||
|
hue = 60d * ((bf - rf) / delta + 2d);
|
||||||
|
else
|
||||||
|
hue = 60d * ((rf - gf) / delta + 4d);
|
||||||
|
}
|
||||||
|
|
||||||
|
h = (int)RoundHalfUp(hue);
|
||||||
|
s = (int)RoundHalfUp(max > 0d ? delta / max * 100d : 0d);
|
||||||
|
v = (int)RoundHalfUp(max * 100d);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int HsvInterpolate(double h1, double s1, double v1, double h2, double s2, double v2, double t) =>
|
||||||
|
HsvCompose(h1 + (h2 - h1) * t, s1 + (s2 - s1) * t, v1 + (v2 - v1) * t);
|
||||||
|
|
||||||
|
private static int ToColorChannel(double value)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(value) || value <= 0d)
|
||||||
|
return 0;
|
||||||
|
if (value >= 255d)
|
||||||
|
return 255;
|
||||||
|
return (int)Math.Floor(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ToColor(double value)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(value))
|
||||||
|
return 0;
|
||||||
|
if (value <= int.MinValue)
|
||||||
|
value = int.MinValue;
|
||||||
|
else if (value >= int.MaxValue)
|
||||||
|
value = int.MaxValue;
|
||||||
|
long floored = (long)Math.Floor(value);
|
||||||
|
return (int)(floored & 0xFFFFFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double WrapHue(double h)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(h) || double.IsInfinity(h))
|
||||||
|
return 0d;
|
||||||
|
double wrapped = h - Math.Floor(h / 360d) * 360d;
|
||||||
|
return wrapped >= 360d ? 0d : wrapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double ClampRatio(double value)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(value) || value <= 0d)
|
||||||
|
return 0d;
|
||||||
|
if (value >= 100d)
|
||||||
|
return 1d;
|
||||||
|
return value / 100d;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double RoundHalfUp(double value) => Math.Floor(value + 0.5);
|
||||||
|
}
|
||||||
|
}
|
||||||
差分なしでファイル名を変更。
@@ -0,0 +1,26 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Version>1.18.0</Version>
|
||||||
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="LuaScript" />
|
||||||
|
<InternalsVisibleTo Include="LuaScript.Runtime" />
|
||||||
|
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
||||||
|
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<EmbeddedResource Include="AviUtlCompatMap.xml" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -42,7 +42,7 @@ namespace LuaScript.Compat
|
|||||||
if (string.IsNullOrEmpty(script))
|
if (string.IsNullOrEmpty(script))
|
||||||
return AviUtlEngine.AviUtl;
|
return AviUtlEngine.AviUtl;
|
||||||
|
|
||||||
foreach (var raw in script.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'))
|
foreach (var raw in ScriptParserHelper.SplitLines(script))
|
||||||
{
|
{
|
||||||
var line = raw.Trim();
|
var line = raw.Trim();
|
||||||
if (!line.StartsWith("--!", System.StringComparison.Ordinal))
|
if (!line.StartsWith("--!", System.StringComparison.Ordinal))
|
||||||
-5
@@ -2,11 +2,6 @@ using System.Collections.Generic;
|
|||||||
|
|
||||||
namespace LuaScript.Compat
|
namespace LuaScript.Compat
|
||||||
{
|
{
|
||||||
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
|
|
||||||
{
|
|
||||||
public double Transform(double value) => value * Scale + Offset;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed class AviUtlEffectMapping
|
internal sealed class AviUtlEffectMapping
|
||||||
{
|
{
|
||||||
private readonly Dictionary<string, AviUtlParameterMapping> _parameters;
|
private readonly Dictionary<string, AviUtlParameterMapping> _parameters;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal enum AviUtlEngine
|
||||||
|
{
|
||||||
|
AviUtl,
|
||||||
|
AviUtl2,
|
||||||
|
Both,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,5 @@
|
|||||||
namespace LuaScript.Compat
|
namespace LuaScript.Compat
|
||||||
{
|
{
|
||||||
internal enum AviUtlEngine
|
|
||||||
{
|
|
||||||
AviUtl,
|
|
||||||
AviUtl2,
|
|
||||||
Both,
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static class AviUtlEngineExtensions
|
internal static class AviUtlEngineExtensions
|
||||||
{
|
{
|
||||||
public static bool Includes(this AviUtlEngine scope, AviUtlEngine target) =>
|
public static bool Includes(this AviUtlEngine scope, AviUtlEngine target) =>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
|
||||||
|
{
|
||||||
|
public double Transform(double value) => value * Scale + Offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
差分なしでファイル名を変更。
+3
-34
@@ -43,26 +43,8 @@ namespace LuaScript.Compat
|
|||||||
if (string.IsNullOrEmpty(source))
|
if (string.IsNullOrEmpty(source))
|
||||||
return layout;
|
return layout;
|
||||||
|
|
||||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
var lines = ScriptParserHelper.SplitLines(source);
|
||||||
|
ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||||
int sectionStart = 0;
|
|
||||||
int sectionEnd = lines.Length;
|
|
||||||
for (int i = 0; i < lines.Length; i++)
|
|
||||||
{
|
|
||||||
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
|
|
||||||
continue;
|
|
||||||
sectionStart = i + 1;
|
|
||||||
sectionEnd = lines.Length;
|
|
||||||
for (int j = sectionStart; j < lines.Length; j++)
|
|
||||||
{
|
|
||||||
if (ScriptParserHelper.IsSectionHeader(lines[j]))
|
|
||||||
{
|
|
||||||
sectionEnd = j;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = sectionStart; i < sectionEnd; i++)
|
for (int i = sectionStart; i < sectionEnd; i++)
|
||||||
layout.ParseLine(lines[i]);
|
layout.ParseLine(lines[i]);
|
||||||
@@ -72,21 +54,8 @@ namespace LuaScript.Compat
|
|||||||
|
|
||||||
private void ParseLine(string line)
|
private void ParseLine(string line)
|
||||||
{
|
{
|
||||||
int i = ScriptParserHelper.SkipSpaces(line, 0);
|
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
|
||||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
|
||||||
return;
|
return;
|
||||||
i += 2;
|
|
||||||
if (i < line.Length && line[i] == '!')
|
|
||||||
return;
|
|
||||||
|
|
||||||
int nameStart = i;
|
|
||||||
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
|
|
||||||
i++;
|
|
||||||
if (i >= line.Length || line[i] != ':')
|
|
||||||
return;
|
|
||||||
|
|
||||||
string name = line.Substring(nameStart, i - nameStart);
|
|
||||||
string content = line.Substring(i + 1);
|
|
||||||
|
|
||||||
if (name.StartsWith("track", StringComparison.OrdinalIgnoreCase) &&
|
if (name.StartsWith("track", StringComparison.OrdinalIgnoreCase) &&
|
||||||
TryGetIndex(name, 5, MaxTracks, out int trackIndex))
|
TryGetIndex(name, 5, MaxTracks, out int trackIndex))
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlPixelShaderLibrary
|
||||||
|
{
|
||||||
|
private const string SectionMarker = "--[[pixelshader@";
|
||||||
|
|
||||||
|
public static AviUtlPixelShaderLibrary Empty { get; } = new(null);
|
||||||
|
|
||||||
|
private readonly Dictionary<string, string>? _shaders;
|
||||||
|
|
||||||
|
private AviUtlPixelShaderLibrary(Dictionary<string, string>? shaders) => _shaders = shaders;
|
||||||
|
|
||||||
|
public int Count => _shaders?.Count ?? 0;
|
||||||
|
|
||||||
|
public static AviUtlPixelShaderLibrary Parse(string? source)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(source))
|
||||||
|
return Empty;
|
||||||
|
|
||||||
|
Dictionary<string, string>? shaders = null;
|
||||||
|
int index = 0;
|
||||||
|
while (index < source.Length)
|
||||||
|
{
|
||||||
|
int lineStart = index;
|
||||||
|
int lineBreak = source.IndexOf('\n', index);
|
||||||
|
index = lineBreak < 0 ? source.Length : lineBreak + 1;
|
||||||
|
|
||||||
|
int i = ScriptParserHelper.SkipSpaces(source, lineStart);
|
||||||
|
if (!MatchesMarker(source, i))
|
||||||
|
continue;
|
||||||
|
i += SectionMarker.Length;
|
||||||
|
|
||||||
|
int nameStart = i;
|
||||||
|
while (i < source.Length && IsEntryPointChar(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i == nameStart || i >= source.Length || source[i] != ':')
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string name = source[nameStart..i];
|
||||||
|
int bodyStart = i + 1;
|
||||||
|
int bodyEnd = source.IndexOf("]]", bodyStart, StringComparison.Ordinal);
|
||||||
|
if (bodyEnd < 0)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
shaders ??= new Dictionary<string, string>(StringComparer.Ordinal);
|
||||||
|
shaders.TryAdd(name, source[bodyStart..bodyEnd]);
|
||||||
|
index = bodyEnd + 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return shaders is null ? Empty : new AviUtlPixelShaderLibrary(shaders);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGet(string name, out string hlsl)
|
||||||
|
{
|
||||||
|
hlsl = string.Empty;
|
||||||
|
if (_shaders is null || string.IsNullOrEmpty(name))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int at = name.IndexOf('@');
|
||||||
|
string local = at < 0 ? name : name[..at];
|
||||||
|
if (_shaders.TryGetValue(local, out var found))
|
||||||
|
{
|
||||||
|
hlsl = found;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string EntryPointOf(string name)
|
||||||
|
{
|
||||||
|
int at = name.IndexOf('@');
|
||||||
|
return at < 0 ? name : name[..at];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool MatchesMarker(string text, int index) =>
|
||||||
|
index + SectionMarker.Length <= text.Length &&
|
||||||
|
string.CompareOrdinal(text, index, SectionMarker, 0, SectionMarker.Length) == 0;
|
||||||
|
|
||||||
|
private static bool IsEntryPointChar(char c) =>
|
||||||
|
ScriptParserHelper.IsNameChar(c) || c == '_';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,42 +15,23 @@ namespace LuaScript.Compat
|
|||||||
|
|
||||||
public static string Transform(string source) => TransformWithMap(source).Code;
|
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||||
|
|
||||||
public static (string Code, int[] LineMap) TransformWithMap(string source)
|
public static (string Code, int[] LineMap, int[] ChangedLines) TransformWithMap(string source)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(source))
|
if (string.IsNullOrEmpty(source))
|
||||||
return (source, []);
|
return (source, [], []);
|
||||||
|
|
||||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
var lines = ScriptParserHelper.SplitLines(source);
|
||||||
|
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||||
int sectionStart = 0;
|
|
||||||
int sectionEnd = lines.Length;
|
|
||||||
bool hasSection = false;
|
|
||||||
|
|
||||||
for (int i = 0; i < lines.Length; i++)
|
|
||||||
{
|
|
||||||
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
hasSection = true;
|
|
||||||
sectionStart = i + 1;
|
|
||||||
sectionEnd = lines.Length;
|
|
||||||
for (int j = sectionStart; j < lines.Length; j++)
|
|
||||||
{
|
|
||||||
if (ScriptParserHelper.IsSectionHeader(lines[j]))
|
|
||||||
{
|
|
||||||
sectionEnd = j;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
var prelude = new List<string>();
|
var prelude = new List<string>();
|
||||||
for (int i = sectionStart; i < sectionEnd; i++)
|
for (int i = sectionStart; i < sectionEnd; i++)
|
||||||
AppendDeclarations(lines[i], prelude);
|
AppendDeclarations(lines[i], prelude);
|
||||||
|
|
||||||
if (!hasSection && prelude.Count == 0)
|
if (!hasSection && prelude.Count == 0)
|
||||||
return (source, []);
|
{
|
||||||
|
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||||
|
return (code, [], changed);
|
||||||
|
}
|
||||||
|
|
||||||
var builder = new StringBuilder(source.Length + 64);
|
var builder = new StringBuilder(source.Length + 64);
|
||||||
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||||
@@ -67,26 +48,14 @@ namespace LuaScript.Compat
|
|||||||
lineMap[row++] = i;
|
lineMap[row++] = i;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (builder.ToString(), lineMap);
|
var (rewritten, changedLines) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||||
|
return (rewritten, lineMap, changedLines);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AppendDeclarations(string line, List<string> prelude)
|
private static void AppendDeclarations(string line, List<string> prelude)
|
||||||
{
|
{
|
||||||
int i = ScriptParserHelper.SkipSpaces(line, 0);
|
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
|
||||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
|
||||||
return;
|
return;
|
||||||
i += 2;
|
|
||||||
if (i < line.Length && line[i] == '!')
|
|
||||||
return;
|
|
||||||
|
|
||||||
int nameStart = i;
|
|
||||||
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
|
|
||||||
i++;
|
|
||||||
if (i >= line.Length || line[i] != ':')
|
|
||||||
return;
|
|
||||||
|
|
||||||
string name = line.Substring(nameStart, i - nameStart);
|
|
||||||
string content = line.Substring(i + 1);
|
|
||||||
|
|
||||||
switch (Classify(name))
|
switch (Classify(name))
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using LuaScript.Compat.Syntax;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxExtensions
|
||||||
|
{
|
||||||
|
public static string Rewrite(string source) => RewriteWithMap(source).Code;
|
||||||
|
|
||||||
|
public static (string Code, int[] ChangedLines) RewriteWithMap(string source)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(source))
|
||||||
|
return (source, []);
|
||||||
|
|
||||||
|
var tokens = LuaSyntaxLexer.Tokenize(source);
|
||||||
|
var context = new LuaRewriteContext(tokens);
|
||||||
|
var rules = LuaSyntaxRuleRegistry.Rules;
|
||||||
|
|
||||||
|
while (!context.AtEnd)
|
||||||
|
{
|
||||||
|
var current = context.Current;
|
||||||
|
if (current.IsTrivia || current.Kind == LuaSyntaxTokenKind.String)
|
||||||
|
{
|
||||||
|
context.Emit(current);
|
||||||
|
context.Advance();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool matched = false;
|
||||||
|
foreach (var rule in rules)
|
||||||
|
{
|
||||||
|
if (rule.TryApply(context))
|
||||||
|
{
|
||||||
|
matched = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!matched)
|
||||||
|
{
|
||||||
|
context.Emit(current);
|
||||||
|
context.Advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.Changed ? (context.Serialize(), context.ChangedLines) : (source, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
-17
@@ -1,6 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using LuaScript.Engine.Kernel;
|
using LuaScript.Compat.Syntax;
|
||||||
|
|
||||||
namespace LuaScript.Compat
|
namespace LuaScript.Compat
|
||||||
{
|
{
|
||||||
@@ -35,15 +35,7 @@ namespace LuaScript.Compat
|
|||||||
if (string.IsNullOrEmpty(script))
|
if (string.IsNullOrEmpty(script))
|
||||||
return None;
|
return None;
|
||||||
|
|
||||||
List<LuaToken> tokens;
|
var tokens = LuaSyntaxLexer.Tokenize(script);
|
||||||
try
|
|
||||||
{
|
|
||||||
tokens = LuaLexer.Tokenize(script);
|
|
||||||
}
|
|
||||||
catch (KernelUnsupportedException)
|
|
||||||
{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
HashSet<string>? members = null;
|
HashSet<string>? members = null;
|
||||||
bool color = false;
|
bool color = false;
|
||||||
@@ -51,26 +43,52 @@ namespace LuaScript.Compat
|
|||||||
for (int i = 0; i < tokens.Count; i++)
|
for (int i = 0; i < tokens.Count; i++)
|
||||||
{
|
{
|
||||||
var token = tokens[i];
|
var token = tokens[i];
|
||||||
if (token.Kind != LuaTokenKind.Name)
|
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
if (token.Text == "color")
|
if (token.Text == "color")
|
||||||
{
|
{
|
||||||
if (i == 0 || !tokens[i - 1].IsSymbol("."))
|
int previous = PreviousSignificant(tokens, i);
|
||||||
|
if (previous < 0 || !tokens[previous].IsOperator("."))
|
||||||
color = true;
|
color = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (token.Text == "obj" &&
|
if (token.Text == "obj")
|
||||||
i + 2 < tokens.Count &&
|
|
||||||
tokens[i + 1].IsSymbol(".") &&
|
|
||||||
tokens[i + 2].Kind == LuaTokenKind.Name)
|
|
||||||
{
|
{
|
||||||
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[i + 2].Text);
|
int dot = NextSignificant(tokens, i + 1);
|
||||||
|
if (dot < 0 || !tokens[dot].IsOperator("."))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
int member = NextSignificant(tokens, dot + 1);
|
||||||
|
if (member < 0 || tokens[member].Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[member].Text);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ScriptParameterUsage(members, color);
|
return new ScriptParameterUsage(members, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static int PreviousSignificant(List<LuaSyntaxToken> tokens, int from)
|
||||||
|
{
|
||||||
|
for (int i = from - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (!tokens[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int NextSignificant(List<LuaSyntaxToken> tokens, int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < tokens.Count; i++)
|
||||||
|
{
|
||||||
|
if (!tokens[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class ScriptParserHelper
|
||||||
|
{
|
||||||
|
public static bool IsSectionHeader(string line)
|
||||||
|
{
|
||||||
|
int i = SkipSpaces(line, 0);
|
||||||
|
return i < line.Length && line[i] == '@';
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int SkipSpaces(string text, int index)
|
||||||
|
{
|
||||||
|
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||||
|
index++;
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsNameChar(char c) =>
|
||||||
|
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||||
|
|
||||||
|
public static string[] SplitLines(string source) =>
|
||||||
|
source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||||
|
|
||||||
|
public static bool TryFindSection(string[] lines, out int start, out int end)
|
||||||
|
{
|
||||||
|
start = 0;
|
||||||
|
end = lines.Length;
|
||||||
|
for (int i = 0; i < lines.Length; i++)
|
||||||
|
{
|
||||||
|
if (!IsSectionHeader(lines[i]))
|
||||||
|
continue;
|
||||||
|
start = i + 1;
|
||||||
|
end = lines.Length;
|
||||||
|
for (int j = start; j < lines.Length; j++)
|
||||||
|
{
|
||||||
|
if (IsSectionHeader(lines[j]))
|
||||||
|
{
|
||||||
|
end = j;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryParseDirective(string line, out string name, out string content)
|
||||||
|
{
|
||||||
|
name = string.Empty;
|
||||||
|
content = string.Empty;
|
||||||
|
int i = SkipSpaces(line, 0);
|
||||||
|
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||||
|
return false;
|
||||||
|
i += 2;
|
||||||
|
if (i < line.Length && line[i] == '!')
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int nameStart = i;
|
||||||
|
while (i < line.Length && IsNameChar(line[i]))
|
||||||
|
i++;
|
||||||
|
if (i >= line.Length || line[i] != ':')
|
||||||
|
return false;
|
||||||
|
|
||||||
|
name = line.Substring(nameStart, i - nameStart);
|
||||||
|
content = line.Substring(i + 1);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal interface ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
bool TryApply(LuaRewriteContext context);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaKeywords
|
||||||
|
{
|
||||||
|
private static readonly HashSet<string> Reserved = new()
|
||||||
|
{
|
||||||
|
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
|
||||||
|
"goto", "if", "in", "local", "nil", "not", "or", "repeat", "return",
|
||||||
|
"then", "true", "until", "while",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly HashSet<string> ExpressionSafe = new()
|
||||||
|
{
|
||||||
|
"and", "or", "not", "nil", "true", "false",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool IsReserved(string name) => Reserved.Contains(name);
|
||||||
|
|
||||||
|
public static bool IsExpressionBoundary(string name) => Reserved.Contains(name) && !ExpressionSafe.Contains(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal readonly struct LuaRangeParts
|
||||||
|
{
|
||||||
|
public LuaRangeParts(string start, string stop, string? step, bool exclusive)
|
||||||
|
{
|
||||||
|
Start = start;
|
||||||
|
Stop = stop;
|
||||||
|
Step = step;
|
||||||
|
Exclusive = exclusive;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Start { get; }
|
||||||
|
|
||||||
|
public string Stop { get; }
|
||||||
|
|
||||||
|
public string? Step { get; }
|
||||||
|
|
||||||
|
public bool Exclusive { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class LuaRangeSyntax
|
||||||
|
{
|
||||||
|
public static bool TryParse(IReadOnlyList<LuaSyntaxToken> input, int open, out LuaRangeParts parts, out int end)
|
||||||
|
{
|
||||||
|
parts = default;
|
||||||
|
end = open;
|
||||||
|
|
||||||
|
if (open < 0 || open >= input.Count || !input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int position = open + 1;
|
||||||
|
if (!TryReadSegment(input, ref position, "..", ">", out string start, out string startTerminator) || startTerminator != "..")
|
||||||
|
return false;
|
||||||
|
|
||||||
|
bool exclusive = false;
|
||||||
|
int caret = NextSignificant(input, position);
|
||||||
|
if (caret >= 0 && input[caret].IsOperator("<"))
|
||||||
|
{
|
||||||
|
exclusive = true;
|
||||||
|
position = caret + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!TryReadSegment(input, ref position, ",", ">", out string stop, out string stopTerminator))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string? step = null;
|
||||||
|
if (stopTerminator == ",")
|
||||||
|
{
|
||||||
|
if (!TryReadSegment(input, ref position, ">", ">", out string stepText, out string stepTerminator) || stepTerminator != ">")
|
||||||
|
return false;
|
||||||
|
step = stepText;
|
||||||
|
}
|
||||||
|
else if (stopTerminator != ">")
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start.Length == 0 || stop.Length == 0 || (step is not null && step.Length == 0))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
parts = new LuaRangeParts(start, stop, step, exclusive);
|
||||||
|
end = position;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryReadSegment(IReadOnlyList<LuaSyntaxToken> input, ref int position, string primaryStop, string secondaryStop, out string text, out string terminator)
|
||||||
|
{
|
||||||
|
text = string.Empty;
|
||||||
|
terminator = string.Empty;
|
||||||
|
int start = position;
|
||||||
|
int depth = 0;
|
||||||
|
int count = input.Count;
|
||||||
|
|
||||||
|
while (position < count)
|
||||||
|
{
|
||||||
|
var token = input[position];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
return false;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return false;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && (token.Text == primaryStop || token.Text == secondaryStop))
|
||||||
|
{
|
||||||
|
terminator = token.Text;
|
||||||
|
text = Trim(input, start, position);
|
||||||
|
position++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int NextSignificant(IReadOnlyList<LuaSyntaxToken> input, int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < input.Count; i++)
|
||||||
|
{
|
||||||
|
if (!input[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Trim(IReadOnlyList<LuaSyntaxToken> input, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal sealed class LuaRewriteContext
|
||||||
|
{
|
||||||
|
private readonly List<LuaSyntaxToken> _input;
|
||||||
|
private readonly List<LuaSyntaxToken> _output;
|
||||||
|
private List<int>? _changedLines;
|
||||||
|
private int _line = 1;
|
||||||
|
private int _lastChangedLine;
|
||||||
|
private int _temporaries;
|
||||||
|
|
||||||
|
public LuaRewriteContext(List<LuaSyntaxToken> input)
|
||||||
|
{
|
||||||
|
_input = input;
|
||||||
|
_output = new List<LuaSyntaxToken>(input.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<LuaSyntaxToken> Input => _input;
|
||||||
|
|
||||||
|
public List<LuaSyntaxToken> Output => _output;
|
||||||
|
|
||||||
|
public int Index { get; set; }
|
||||||
|
|
||||||
|
public bool Changed { get; private set; }
|
||||||
|
|
||||||
|
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
|
||||||
|
|
||||||
|
public bool AtEnd => Index >= _input.Count;
|
||||||
|
|
||||||
|
public LuaSyntaxToken Current => _input[Index];
|
||||||
|
|
||||||
|
public void Advance() => Index++;
|
||||||
|
|
||||||
|
public void Emit(LuaSyntaxToken token)
|
||||||
|
{
|
||||||
|
_output.Add(token);
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
_line++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitRaw(string text)
|
||||||
|
{
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, text));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitOperator(string text)
|
||||||
|
{
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, text));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string NextTemporary() => "__lc" + _temporaries++;
|
||||||
|
|
||||||
|
public int NextSignificant(int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < _input.Count; i++)
|
||||||
|
{
|
||||||
|
if (!_input[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryPreviousOutputSignificantSameLine(out LuaSyntaxToken token)
|
||||||
|
{
|
||||||
|
for (int i = _output.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (_output[i].Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
break;
|
||||||
|
if (_output[i].IsTrivia)
|
||||||
|
continue;
|
||||||
|
token = _output[i];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
token = default;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int NextSignificantSameLine(int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < _input.Count; i++)
|
||||||
|
{
|
||||||
|
if (_input[i].Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return -1;
|
||||||
|
if (_input[i].IsTrivia)
|
||||||
|
continue;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitWord(string word)
|
||||||
|
{
|
||||||
|
if (_output.Count > 0 && !_output[_output.Count - 1].IsTrivia)
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, word));
|
||||||
|
if (Index < _input.Count && !_input[Index].IsTrivia)
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void MarkChanged()
|
||||||
|
{
|
||||||
|
Changed = true;
|
||||||
|
if (_line == _lastChangedLine)
|
||||||
|
return;
|
||||||
|
(_changedLines ??= new List<int>()).Add(_line);
|
||||||
|
_lastChangedLine = _line;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryReadTrailingLvalue(out int start, out string text)
|
||||||
|
{
|
||||||
|
start = _output.Count;
|
||||||
|
text = string.Empty;
|
||||||
|
int end = _output.Count;
|
||||||
|
while (end > 0 && _output[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
if (end == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int depth = 0;
|
||||||
|
int begin = end;
|
||||||
|
for (int i = end - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = _output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0 || token.Text == ".")
|
||||||
|
{
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name)
|
||||||
|
{
|
||||||
|
if (depth == 0 && LuaKeywords.IsReserved(token.Text))
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0)
|
||||||
|
{
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (begin < end && _output[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
if (begin >= end)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
start = begin;
|
||||||
|
text = Concat(begin, end);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryPopOrOperand(out string text)
|
||||||
|
{
|
||||||
|
text = string.Empty;
|
||||||
|
int end = _output.Count;
|
||||||
|
while (end > 0 && _output[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
if (end == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int depth = 0;
|
||||||
|
int begin = end;
|
||||||
|
for (int i = end - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = _output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth == 0 && token.Text is "=" or "," or ";")
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (begin < end && _output[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
if (begin >= end)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
text = Concat(begin, end);
|
||||||
|
_output.RemoveRange(begin, _output.Count - begin);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RemoveOutputFrom(int start) => _output.RemoveRange(start, _output.Count - start);
|
||||||
|
|
||||||
|
public bool LastOutputIsTrivia() => _output.Count == 0 || _output[_output.Count - 1].IsTrivia;
|
||||||
|
|
||||||
|
public string ReadLineExpression()
|
||||||
|
{
|
||||||
|
int start = Index;
|
||||||
|
int depth = 0;
|
||||||
|
while (Index < _input.Count)
|
||||||
|
{
|
||||||
|
var token = _input[Index];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
depth++;
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text == ";")
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Index++;
|
||||||
|
}
|
||||||
|
return TrimmedRange(start, Index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string ReadForwardOrOperand()
|
||||||
|
{
|
||||||
|
int start = Index;
|
||||||
|
int depth = 0;
|
||||||
|
while (Index < _input.Count)
|
||||||
|
{
|
||||||
|
var token = _input[Index];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
depth++;
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text is "," or ";")
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
Index++;
|
||||||
|
}
|
||||||
|
return TrimmedRange(start, Index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Serialize()
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
foreach (var token in _output)
|
||||||
|
builder.Append(token.Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Concat(int begin, int end)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(_output[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string TrimmedRange(int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && _input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && _input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(_input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxFacts
|
||||||
|
{
|
||||||
|
public static bool IsValueEnd(LuaSyntaxToken token) => token.Kind switch
|
||||||
|
{
|
||||||
|
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
|
||||||
|
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false",
|
||||||
|
LuaSyntaxTokenKind.Operator => token.Text is ")" or "]" or "}",
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool IsValueStart(LuaSyntaxToken token) => token.Kind switch
|
||||||
|
{
|
||||||
|
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
|
||||||
|
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false" or "not" or "function",
|
||||||
|
LuaSyntaxTokenKind.Operator => token.Text is "(" or "{" or "-" or "#" or "~",
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxLexer
|
||||||
|
{
|
||||||
|
private static readonly string[] Operators =
|
||||||
|
{
|
||||||
|
"...", "..=", "??=", "||=", "&&=",
|
||||||
|
"==", "~=", "<=", ">=", "..", "::", "??", "||", "&&", "!=", "++",
|
||||||
|
"=>", "|>",
|
||||||
|
"+=", "-=", "*=", "/=", "%=", "^=",
|
||||||
|
"+", "-", "*", "/", "%", "^", "#", "<", ">", "=",
|
||||||
|
"(", ")", "{", "}", "[", "]", ";", ":", ",", ".",
|
||||||
|
"!", "&", "|", "?", "~",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static List<LuaSyntaxToken> Tokenize(string source)
|
||||||
|
{
|
||||||
|
var tokens = new List<LuaSyntaxToken>();
|
||||||
|
int i = 0;
|
||||||
|
int length = source.Length;
|
||||||
|
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
|
||||||
|
if (c == '\r' || c == '\n')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
if (c == '\r' && i + 1 < length && source[i + 1] == '\n')
|
||||||
|
i += 2;
|
||||||
|
else
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Newline, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == ' ' || c == '\t' || c == '\f' || c == '\v')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
while (i < length && (source[i] == ' ' || source[i] == '\t' || source[i] == '\f' || source[i] == '\v'))
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '-' && i + 1 < length && source[i + 1] == '-')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipComment(source, i + 2);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Comment, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '[')
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipLongBracket(source, i, level);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '"' || c == '\'')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipShortString(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '`')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipShortString(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.InterpolatedString, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsDigit(c) || (c == '.' && i + 1 < length && IsDigit(source[i + 1])))
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipNumber(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Number, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsNameStart(c))
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
while (i < length && IsNamePart(source[i]))
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? op = MatchOperator(source, i);
|
||||||
|
if (op is not null)
|
||||||
|
{
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, op));
|
||||||
|
i += op.Length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, source.Substring(i, 1)));
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? MatchOperator(string source, int index)
|
||||||
|
{
|
||||||
|
int remaining = source.Length - index;
|
||||||
|
foreach (var op in Operators)
|
||||||
|
{
|
||||||
|
if (op.Length > remaining)
|
||||||
|
continue;
|
||||||
|
if (string.CompareOrdinal(source, index, op, 0, op.Length) == 0)
|
||||||
|
return op;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipNumber(string source, int i)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
|
||||||
|
{
|
||||||
|
i += 2;
|
||||||
|
while (i < length && (IsHexDigit(source[i]) || source[i] == '.'))
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == 'p' || source[i] == 'P'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i < length && source[i] == '.' && !(i + 1 < length && source[i + 1] == '.'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (i < length && (source[i] == 'e' || source[i] == 'E'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipComment(string source, int i)
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
return SkipLongBracket(source, i, level);
|
||||||
|
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length && source[i] != '\n' && source[i] != '\r')
|
||||||
|
i++;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int LongBracketLevel(string source, int i)
|
||||||
|
{
|
||||||
|
if (i >= source.Length || source[i] != '[')
|
||||||
|
return -1;
|
||||||
|
int j = i + 1;
|
||||||
|
int level = 0;
|
||||||
|
while (j < source.Length && source[j] == '=')
|
||||||
|
{
|
||||||
|
level++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
return j < source.Length && source[j] == '[' ? level : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipLongBracket(string source, int i, int level)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
i += level + 2;
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
if (source[i] == ']')
|
||||||
|
{
|
||||||
|
int j = i + 1;
|
||||||
|
int count = 0;
|
||||||
|
while (j < length && source[j] == '=')
|
||||||
|
{
|
||||||
|
count++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
if (count == level && j < length && source[j] == ']')
|
||||||
|
return j + 1;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipShortString(string source, int start)
|
||||||
|
{
|
||||||
|
char quote = source[start];
|
||||||
|
int i = start + 1;
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == quote)
|
||||||
|
return i + 1;
|
||||||
|
if (c == '\n' || c == '\r')
|
||||||
|
return i;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
|
||||||
|
|
||||||
|
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
|
||||||
|
|
||||||
|
private static bool IsDigit(char c) => c >= '0' && c <= '9';
|
||||||
|
|
||||||
|
private static bool IsHexDigit(char c) => IsDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
|
||||||
|
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
|
||||||
|
{
|
||||||
|
public int Order { get; } = order;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal readonly struct LuaSyntaxToken
|
||||||
|
{
|
||||||
|
public LuaSyntaxToken(LuaSyntaxTokenKind kind, string text)
|
||||||
|
{
|
||||||
|
Kind = kind;
|
||||||
|
Text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LuaSyntaxTokenKind Kind { get; }
|
||||||
|
|
||||||
|
public string Text { get; }
|
||||||
|
|
||||||
|
public bool IsTrivia => Kind is LuaSyntaxTokenKind.Whitespace or LuaSyntaxTokenKind.Newline or LuaSyntaxTokenKind.Comment;
|
||||||
|
|
||||||
|
public bool IsName(string value) => Kind == LuaSyntaxTokenKind.Name && Text == value;
|
||||||
|
|
||||||
|
public bool IsOperator(string value) => Kind == LuaSyntaxTokenKind.Operator && Text == value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal enum LuaSyntaxTokenKind
|
||||||
|
{
|
||||||
|
Whitespace,
|
||||||
|
Newline,
|
||||||
|
Comment,
|
||||||
|
String,
|
||||||
|
InterpolatedString,
|
||||||
|
Number,
|
||||||
|
Name,
|
||||||
|
Operator,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(70)]
|
||||||
|
internal sealed class AugmentedAssignmentRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (context.Current.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string? connective = Connective(context.Current.Text);
|
||||||
|
if (connective is null)
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out _, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string value = context.ReadLineExpression();
|
||||||
|
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
|
||||||
|
context.EmitRaw($"{separator}= {target} {connective} ({value})");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Connective(string op) => op switch
|
||||||
|
{
|
||||||
|
"+=" => "+",
|
||||||
|
"-=" => "-",
|
||||||
|
"*=" => "*",
|
||||||
|
"/=" => "/",
|
||||||
|
"%=" => "%",
|
||||||
|
"^=" => "^",
|
||||||
|
"..=" => "..",
|
||||||
|
"||=" => "or",
|
||||||
|
"&&=" => "and",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(80)]
|
||||||
|
internal sealed class NilCoalesceAssignRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("??="))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Advance();
|
||||||
|
string value = context.ReadLineExpression();
|
||||||
|
context.EmitRaw($"if {target} == nil then {target} = ({value}) end");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(90)]
|
||||||
|
internal sealed class IncrementRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("++"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out _, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
|
||||||
|
context.EmitRaw($"{separator}= {target} + 1");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(10)]
|
||||||
|
internal sealed class IsNotRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("is"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int notIndex = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (notIndex < 0 || !context.Input[notIndex].IsName("not"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int after = context.NextSignificant(notIndex + 1);
|
||||||
|
if (after < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[after]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("~=");
|
||||||
|
context.Index = notIndex + 1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(20)]
|
||||||
|
internal sealed class IsRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("is"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int next = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (next < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[next]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("==");
|
||||||
|
context.Advance();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(30)]
|
||||||
|
internal sealed class NotEqualRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("!="))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("~=");
|
||||||
|
context.Advance();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(5)]
|
||||||
|
internal sealed class LuaInterpolatedStringRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (context.Current.Kind != LuaSyntaxTokenKind.InterpolatedString)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string text = context.Current.Text;
|
||||||
|
int end = text.Length;
|
||||||
|
if (end >= 2 && text[end - 1] == '`')
|
||||||
|
end--;
|
||||||
|
string content = text.Substring(1, end - 1);
|
||||||
|
|
||||||
|
var pieces = new List<string>();
|
||||||
|
var literal = new StringBuilder();
|
||||||
|
int i = 0;
|
||||||
|
while (i < content.Length)
|
||||||
|
{
|
||||||
|
char c = content[i];
|
||||||
|
if (c == '\\' && i + 1 < content.Length)
|
||||||
|
{
|
||||||
|
literal.Append(content[i]);
|
||||||
|
literal.Append(content[i + 1]);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '{')
|
||||||
|
{
|
||||||
|
int close = FindClosingBrace(content, i + 1);
|
||||||
|
if (close < 0)
|
||||||
|
{
|
||||||
|
literal.Append(c);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
string expression = content.Substring(i + 1, close - i - 1).Trim();
|
||||||
|
if (expression.Length > 0)
|
||||||
|
{
|
||||||
|
FlushLiteral(pieces, literal);
|
||||||
|
pieces.Add($"tostring({LuaSyntaxExtensions.Rewrite(expression)})");
|
||||||
|
}
|
||||||
|
i = close + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
literal.Append(c);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
FlushLiteral(pieces, literal);
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
if (pieces.Count == 0)
|
||||||
|
{
|
||||||
|
context.EmitRaw("\"\"");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (pieces.Count == 1)
|
||||||
|
{
|
||||||
|
context.EmitRaw(pieces[0]);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
context.EmitRaw($"({string.Join(" .. ", pieces)})");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void FlushLiteral(List<string> pieces, StringBuilder literal)
|
||||||
|
{
|
||||||
|
if (literal.Length == 0)
|
||||||
|
return;
|
||||||
|
pieces.Add($"\"{literal.ToString().Replace("\"", "\\\"")}\"");
|
||||||
|
literal.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindClosingBrace(string content, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
char quote = '\0';
|
||||||
|
for (int i = from; i < content.Length; i++)
|
||||||
|
{
|
||||||
|
char c = content[i];
|
||||||
|
if (quote != '\0')
|
||||||
|
{
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == quote)
|
||||||
|
quote = '\0';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '"' || c == '\'')
|
||||||
|
{
|
||||||
|
quote = c;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '{')
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '}')
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return i;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(35)]
|
||||||
|
internal sealed class LuaLambdaRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("=>"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
if (!TryNormalizeParameters(target, out string parameters))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int body = context.NextSignificant(context.Index + 1);
|
||||||
|
if (body < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[body]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Advance();
|
||||||
|
string expression = context.ReadForwardOrOperand();
|
||||||
|
if (expression.Length == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitRaw($"(function({parameters}) return {LuaSyntaxExtensions.Rewrite(expression)} end)");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryNormalizeParameters(string text, out string parameters)
|
||||||
|
{
|
||||||
|
parameters = string.Empty;
|
||||||
|
text = text.Trim();
|
||||||
|
bool wrapped = text.StartsWith("(") && text.EndsWith(")");
|
||||||
|
if (wrapped)
|
||||||
|
text = text.Substring(1, text.Length - 2).Trim();
|
||||||
|
|
||||||
|
if (text.Length == 0)
|
||||||
|
return wrapped;
|
||||||
|
|
||||||
|
var names = text.Split(',');
|
||||||
|
for (int i = 0; i < names.Length; i++)
|
||||||
|
{
|
||||||
|
string name = names[i].Trim();
|
||||||
|
if (name == "...")
|
||||||
|
{
|
||||||
|
if (i != names.Length - 1)
|
||||||
|
return false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!IsName(name) || LuaKeywords.IsReserved(name))
|
||||||
|
return false;
|
||||||
|
if (!wrapped && names.Length > 1)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
parameters = string.Join(", ", System.Array.ConvertAll(names, static n => n.Trim()));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsName(string text)
|
||||||
|
{
|
||||||
|
if (text.Length == 0)
|
||||||
|
return false;
|
||||||
|
if (text[0] != '_' && !char.IsLetter(text[0]))
|
||||||
|
return false;
|
||||||
|
for (int i = 1; i < text.Length; i++)
|
||||||
|
{
|
||||||
|
if (text[i] != '_' && !char.IsLetterOrDigit(text[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(40)]
|
||||||
|
internal sealed class LogicalNotRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("!"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("not");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(50)]
|
||||||
|
internal sealed class AndAliasRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("&&"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("and");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(60)]
|
||||||
|
internal sealed class OrAliasRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("||"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("or");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(100)]
|
||||||
|
internal sealed class NilCoalesceRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("??"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string right = context.ReadForwardOrOperand();
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({left}) if {temporary} ~= nil then return {temporary} else return ({right}) end end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(110)]
|
||||||
|
internal sealed class LuaNumericRangeRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("in"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int open = context.NextSignificant(context.Index + 1);
|
||||||
|
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string stopExpression = parts.Exclusive ? $"({parts.Stop}) - 1" : parts.Stop;
|
||||||
|
string replacement = parts.Step is null
|
||||||
|
? $"= {parts.Start}, {stopExpression}"
|
||||||
|
: $"= {parts.Start}, {stopExpression}, {parts.Step}";
|
||||||
|
context.EmitRaw(replacement);
|
||||||
|
context.Index = end;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(98)]
|
||||||
|
internal sealed class LuaPipeRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("|>"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int targetStart = context.NextSignificant(context.Index + 1);
|
||||||
|
if (targetStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[targetStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
var segment = ReadSegment(context);
|
||||||
|
string call = BuildCall(segment, left);
|
||||||
|
context.EmitRaw(call);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<LuaSyntaxToken> ReadSegment(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
var tokens = new List<LuaSyntaxToken>();
|
||||||
|
int depth = 0;
|
||||||
|
while (!context.AtEnd)
|
||||||
|
{
|
||||||
|
var token = context.Current;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text is "," or ";" or "|>")
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokens.Add(token);
|
||||||
|
context.Advance();
|
||||||
|
}
|
||||||
|
while (tokens.Count > 0 && tokens[0].IsTrivia)
|
||||||
|
tokens.RemoveAt(0);
|
||||||
|
while (tokens.Count > 0 && tokens[tokens.Count - 1].IsTrivia)
|
||||||
|
tokens.RemoveAt(tokens.Count - 1);
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildCall(List<LuaSyntaxToken> segment, string left)
|
||||||
|
{
|
||||||
|
string argument = $"({left})";
|
||||||
|
if (segment.Count == 0)
|
||||||
|
return argument;
|
||||||
|
|
||||||
|
if (segment[segment.Count - 1].IsOperator(")"))
|
||||||
|
{
|
||||||
|
int open = FindOpeningParen(segment);
|
||||||
|
if (open > 0)
|
||||||
|
{
|
||||||
|
string callee = Concat(segment, 0, open);
|
||||||
|
string arguments = Concat(segment, open + 1, segment.Count - 1);
|
||||||
|
return arguments.Length == 0
|
||||||
|
? $"{callee}({argument})"
|
||||||
|
: $"{callee}({argument}, {arguments})";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $"{Concat(segment, 0, segment.Count)}({argument})";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindOpeningParen(List<LuaSyntaxToken> segment)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = segment.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = segment[i];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth--;
|
||||||
|
if (depth == 0)
|
||||||
|
return token.Text == "(" ? i : -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Concat(List<LuaSyntaxToken> segment, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && segment[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && segment[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(segment[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(108)]
|
||||||
|
internal sealed class LuaRangeMembershipRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("in"))
|
||||||
|
return false;
|
||||||
|
if (IsForHeader(context))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int open = context.NextSignificant(context.Index + 1);
|
||||||
|
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||||
|
return false;
|
||||||
|
if (parts.Step is not null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
string upper = parts.Exclusive ? "<" : "<=";
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({left}) return {temporary} >= ({LuaSyntaxExtensions.Rewrite(parts.Start)}) and {temporary} {upper} ({LuaSyntaxExtensions.Rewrite(parts.Stop)}) end)()");
|
||||||
|
context.Index = end;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsForHeader(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
var output = context.Output;
|
||||||
|
for (int i = output.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return false;
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "do" or "then")
|
||||||
|
return false;
|
||||||
|
if (token.Text == "for")
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(92)]
|
||||||
|
internal sealed class LuaSafeNavigationRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("?"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int accessor = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (accessor < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (context.Input[accessor].IsOperator("."))
|
||||||
|
return TryApplyMember(context, accessor);
|
||||||
|
if (context.Input[accessor].IsOperator("["))
|
||||||
|
return TryApplyIndex(context, accessor);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryApplyMember(LuaRewriteContext context, int accessor)
|
||||||
|
{
|
||||||
|
int name = context.NextSignificantSameLine(accessor + 1);
|
||||||
|
if (name < 0)
|
||||||
|
return false;
|
||||||
|
var token = context.Input[name];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Name || LuaKeywords.IsReserved(token.Text))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Index = name + 1;
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}.{token.Text} end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryApplyIndex(LuaRewriteContext context, int accessor)
|
||||||
|
{
|
||||||
|
int close = FindClosingBracket(context, accessor + 1);
|
||||||
|
if (close < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string key = Concat(context, accessor + 1, close);
|
||||||
|
if (key.Length == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Index = close + 1;
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}[{LuaSyntaxExtensions.Rewrite(key)}] end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindClosingBracket(LuaRewriteContext context, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = from; i < context.Input.Count; i++)
|
||||||
|
{
|
||||||
|
var token = context.Input[i];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is ")" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return -1;
|
||||||
|
depth--;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text == "]")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return i;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Concat(LuaRewriteContext context, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && context.Input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(context.Input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(96)]
|
||||||
|
internal sealed class LuaTernaryRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("?"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int thenStart = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (thenStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[thenStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int colon = FindColon(context, context.Index + 1);
|
||||||
|
if (colon < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int elseStart = context.NextSignificantSameLine(colon + 1);
|
||||||
|
if (elseStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[elseStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string condition))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Index++;
|
||||||
|
string thenExpression = ReadUntil(context, colon);
|
||||||
|
context.Index = colon + 1;
|
||||||
|
string elseExpression = context.ReadForwardOrOperand();
|
||||||
|
|
||||||
|
context.EmitRaw($"(function() if {condition} then return ({LuaSyntaxExtensions.Rewrite(thenExpression)}) else return ({LuaSyntaxExtensions.Rewrite(elseExpression)}) end end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindColon(LuaRewriteContext context, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = from; i < context.Input.Count; i++)
|
||||||
|
{
|
||||||
|
var token = context.Input[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return -1;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
return -1;
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return -1;
|
||||||
|
depth--;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "," or ";" or "?")
|
||||||
|
return -1;
|
||||||
|
if (token.Text == ":")
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadUntil(LuaRewriteContext context, int stop)
|
||||||
|
{
|
||||||
|
var builder = new System.Text.StringBuilder();
|
||||||
|
int begin = context.Index;
|
||||||
|
int end = stop;
|
||||||
|
while (begin < end && context.Input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(context.Input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Collections;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal readonly struct EquatableArray<T>(T[] items) : IEquatable<EquatableArray<T>>, IReadOnlyList<T>
|
||||||
|
where T : IEquatable<T>
|
||||||
|
{
|
||||||
|
private readonly T[] _items = items;
|
||||||
|
|
||||||
|
public static readonly EquatableArray<T> Empty = new([]);
|
||||||
|
|
||||||
|
public int Count => _items?.Length ?? 0;
|
||||||
|
|
||||||
|
public T this[int index] => _items[index];
|
||||||
|
|
||||||
|
public bool Equals(EquatableArray<T> other)
|
||||||
|
{
|
||||||
|
var a = _items ?? [];
|
||||||
|
var b = other._items ?? [];
|
||||||
|
if (a.Length != b.Length)
|
||||||
|
return false;
|
||||||
|
for (int i = 0; i < a.Length; i++)
|
||||||
|
{
|
||||||
|
if (!a[i].Equals(b[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Equals(object? obj) => obj is EquatableArray<T> other && Equals(other);
|
||||||
|
|
||||||
|
public override int GetHashCode()
|
||||||
|
{
|
||||||
|
var items = _items ?? [];
|
||||||
|
int hash = 17;
|
||||||
|
foreach (var item in items)
|
||||||
|
hash = hash * 31 + (item?.GetHashCode() ?? 0);
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)(_items ?? [])).GetEnumerator();
|
||||||
|
|
||||||
|
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace System.Runtime.CompilerServices
|
||||||
|
{
|
||||||
|
internal static class IsExternalInit;
|
||||||
|
}
|
||||||
@@ -0,0 +1,486 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
using Microsoft.CodeAnalysis.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaParameterKind
|
||||||
|
{
|
||||||
|
ExecutionContext,
|
||||||
|
Arguments,
|
||||||
|
DynValue,
|
||||||
|
Double,
|
||||||
|
Int,
|
||||||
|
Bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum LuaReturnKind
|
||||||
|
{
|
||||||
|
DynValue,
|
||||||
|
Double,
|
||||||
|
Void,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
|
||||||
|
|
||||||
|
internal sealed record LuaFunctionModel(
|
||||||
|
string LuaName,
|
||||||
|
string MethodName,
|
||||||
|
LuaReturnKind ReturnKind,
|
||||||
|
EquatableArray<LuaParameterModel> Parameters);
|
||||||
|
|
||||||
|
internal sealed record LuaConstantModel(string LuaName, string MemberName);
|
||||||
|
|
||||||
|
internal enum LuaUpdateKind
|
||||||
|
{
|
||||||
|
Direct,
|
||||||
|
OptionalValue,
|
||||||
|
OptionalReference,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind);
|
||||||
|
|
||||||
|
internal sealed record LuaCatalogEntry(
|
||||||
|
string Table,
|
||||||
|
string Name,
|
||||||
|
bool IsFunction,
|
||||||
|
EquatableArray<string> Parameters);
|
||||||
|
|
||||||
|
internal sealed record LuaTypePart(string Name, bool IsStatic);
|
||||||
|
|
||||||
|
internal sealed record LuaTableModel(
|
||||||
|
string Namespace,
|
||||||
|
EquatableArray<LuaTypePart> TypeChain,
|
||||||
|
string TableName,
|
||||||
|
string ContextType,
|
||||||
|
EquatableArray<LuaFunctionModel> Functions,
|
||||||
|
EquatableArray<LuaConstantModel> Constants,
|
||||||
|
EquatableArray<LuaUpdateModel> Updates,
|
||||||
|
EquatableArray<LuaCatalogEntry> Entries);
|
||||||
|
|
||||||
|
[Generator]
|
||||||
|
public sealed class LuaApiGenerator : IIncrementalGenerator
|
||||||
|
{
|
||||||
|
private const string TableAttributeName = "LuaScript.Api.LuaTableAttribute";
|
||||||
|
private const string FunctionAttributeName = "LuaScript.Api.LuaFunctionAttribute";
|
||||||
|
private const string ConstantAttributeName = "LuaScript.Api.LuaConstantAttribute";
|
||||||
|
private const string VariableAttributeName = "LuaScript.Api.LuaVariableAttribute";
|
||||||
|
private const string BuiltinAttributeName = "LuaScript.Api.LuaBuiltinAttribute";
|
||||||
|
|
||||||
|
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||||
|
{
|
||||||
|
var tables = context.SyntaxProvider
|
||||||
|
.ForAttributeWithMetadataName(
|
||||||
|
TableAttributeName,
|
||||||
|
static (node, _) => node is ClassDeclarationSyntax,
|
||||||
|
static (ctx, _) => CreateModel(ctx))
|
||||||
|
.Where(static model => model is not null)
|
||||||
|
.Select(static (model, _) => model!);
|
||||||
|
|
||||||
|
var assemblyEntries = context.CompilationProvider
|
||||||
|
.Select(static (compilation, _) => CollectAssemblyEntries(compilation));
|
||||||
|
|
||||||
|
context.RegisterSourceOutput(tables, static (ctx, model) =>
|
||||||
|
{
|
||||||
|
if (model.Functions.Count == 0 && model.Constants.Count == 0 && model.Updates.Count == 0)
|
||||||
|
return;
|
||||||
|
ctx.AddSource(RegistrationHintName(model), SourceText.From(EmitRegistration(model), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
|
||||||
|
var catalog = tables.Collect().Combine(assemblyEntries);
|
||||||
|
context.RegisterSourceOutput(catalog, static (ctx, source) =>
|
||||||
|
{
|
||||||
|
var (models, extra) = source;
|
||||||
|
var entries = models
|
||||||
|
.OrderBy(static m => m.Namespace, StringComparer.Ordinal)
|
||||||
|
.ThenBy(static m => string.Join("+", m.TypeChain.Select(static p => p.Name)), StringComparer.Ordinal)
|
||||||
|
.SelectMany(static m => m.Entries)
|
||||||
|
.Concat(extra)
|
||||||
|
.ToArray();
|
||||||
|
if (entries.Length == 0)
|
||||||
|
return;
|
||||||
|
ctx.AddSource("LuaApiCatalog.g.cs", SourceText.From(EmitCatalog(entries), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaTableModel? CreateModel(GeneratorAttributeSyntaxContext context)
|
||||||
|
{
|
||||||
|
if (context.TargetSymbol is not INamedTypeSymbol symbol)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var tableArguments = context.Attributes[0].ConstructorArguments;
|
||||||
|
string tableName = tableArguments.Length > 0 && tableArguments[0].Value is string name ? name : string.Empty;
|
||||||
|
|
||||||
|
var chain = new List<LuaTypePart>();
|
||||||
|
for (var type = symbol; type is not null; type = type.ContainingType)
|
||||||
|
chain.Insert(0, new LuaTypePart(type.Name, type.IsStatic));
|
||||||
|
|
||||||
|
var entries = new List<(int Position, LuaCatalogEntry Entry)>();
|
||||||
|
foreach (var attribute in symbol.GetAttributes())
|
||||||
|
{
|
||||||
|
string? attributeName = attribute.AttributeClass?.ToDisplayString();
|
||||||
|
if (attributeName is not (VariableAttributeName or BuiltinAttributeName or FunctionAttributeName))
|
||||||
|
continue;
|
||||||
|
var entry = CreateAttributeEntry(attribute, tableName);
|
||||||
|
if (entry is null)
|
||||||
|
continue;
|
||||||
|
int position = attribute.ApplicationSyntaxReference?.Span.Start ?? 0;
|
||||||
|
entries.Add((position, entry));
|
||||||
|
}
|
||||||
|
var classEntries = entries.OrderBy(static e => e.Position).Select(static e => e.Entry).ToList();
|
||||||
|
|
||||||
|
var functions = new List<(int Position, LuaFunctionModel Function, LuaCatalogEntry Entry)>();
|
||||||
|
var constants = new List<(int Position, LuaConstantModel Constant, LuaCatalogEntry Entry)>();
|
||||||
|
var updates = new List<(int Position, LuaUpdateModel Update, LuaCatalogEntry? Entry)>();
|
||||||
|
string contextType = string.Empty;
|
||||||
|
foreach (var member in symbol.GetMembers())
|
||||||
|
{
|
||||||
|
int position = member.DeclaringSyntaxReferences.Length > 0
|
||||||
|
? member.DeclaringSyntaxReferences[0].Span.Start
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
if (member is IMethodSymbol method)
|
||||||
|
{
|
||||||
|
var functionAttribute = FindAttribute(method, FunctionAttributeName);
|
||||||
|
if (functionAttribute is not null)
|
||||||
|
{
|
||||||
|
var function = CreateFunctionModel(method, functionAttribute, out var catalogParameters);
|
||||||
|
if (function is null)
|
||||||
|
continue;
|
||||||
|
functions.Add((position, function, new LuaCatalogEntry(tableName, function.LuaName, true, catalogParameters)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var variableAttribute = FindAttribute(method, VariableAttributeName);
|
||||||
|
if (variableAttribute is not null)
|
||||||
|
{
|
||||||
|
var update = CreateUpdateModel(method, variableAttribute, tableName, ref contextType, out var entry);
|
||||||
|
if (update is not null)
|
||||||
|
updates.Add((position, update, entry));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (member is IFieldSymbol or IPropertySymbol)
|
||||||
|
{
|
||||||
|
var attribute = FindAttribute(member, ConstantAttributeName);
|
||||||
|
if (attribute is null)
|
||||||
|
continue;
|
||||||
|
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string constantName)
|
||||||
|
continue;
|
||||||
|
constants.Add((
|
||||||
|
position,
|
||||||
|
new LuaConstantModel(constantName, member.Name),
|
||||||
|
new LuaCatalogEntry(tableName, constantName, false, EquatableArray<string>.Empty)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var orderedMembers = functions
|
||||||
|
.Select(static f => (Position: f.Position, Entry: f.Entry))
|
||||||
|
.Concat(constants.Select(static c => (Position: c.Position, Entry: c.Entry)))
|
||||||
|
.Concat(updates.Where(static u => u.Entry is not null).Select(static u => (Position: u.Position, Entry: u.Entry!)))
|
||||||
|
.OrderBy(static e => e.Position)
|
||||||
|
.Select(static e => e.Entry);
|
||||||
|
|
||||||
|
return new LuaTableModel(
|
||||||
|
symbol.ContainingNamespace.ToDisplayString(),
|
||||||
|
new EquatableArray<LuaTypePart>([.. chain]),
|
||||||
|
tableName,
|
||||||
|
contextType,
|
||||||
|
new EquatableArray<LuaFunctionModel>([.. functions.OrderBy(static f => f.Position).Select(static f => f.Function)]),
|
||||||
|
new EquatableArray<LuaConstantModel>([.. constants.OrderBy(static c => c.Position).Select(static c => c.Constant)]),
|
||||||
|
new EquatableArray<LuaUpdateModel>([.. updates.OrderBy(static u => u.Position).Select(static u => u.Update)]),
|
||||||
|
new EquatableArray<LuaCatalogEntry>([.. classEntries, .. orderedMembers]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AttributeData? FindAttribute(ISymbol symbol, string attributeName)
|
||||||
|
{
|
||||||
|
foreach (var attribute in symbol.GetAttributes())
|
||||||
|
{
|
||||||
|
if (attribute.AttributeClass?.ToDisplayString() == attributeName)
|
||||||
|
return attribute;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaCatalogEntry? CreateAttributeEntry(AttributeData attribute, string defaultTable)
|
||||||
|
{
|
||||||
|
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string name)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
string table = defaultTable;
|
||||||
|
foreach (var argument in attribute.NamedArguments)
|
||||||
|
{
|
||||||
|
if (argument.Key == "Table" && argument.Value.Value is string overridden)
|
||||||
|
table = overridden;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isFunction = attribute.AttributeClass?.ToDisplayString() is (BuiltinAttributeName or FunctionAttributeName);
|
||||||
|
var parameters = isFunction && attribute.ConstructorArguments.Length > 1
|
||||||
|
? ExtractStringArray(attribute.ConstructorArguments[1])
|
||||||
|
: EquatableArray<string>.Empty;
|
||||||
|
|
||||||
|
return new LuaCatalogEntry(table, name, isFunction, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static EquatableArray<string> ExtractStringArray(TypedConstant constant)
|
||||||
|
{
|
||||||
|
if (constant.Kind != TypedConstantKind.Array)
|
||||||
|
return EquatableArray<string>.Empty;
|
||||||
|
return new EquatableArray<string>([.. constant.Values.Select(static v => v.Value as string ?? string.Empty)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaFunctionModel? CreateFunctionModel(IMethodSymbol method, AttributeData attribute, out EquatableArray<string> catalogParameters)
|
||||||
|
{
|
||||||
|
catalogParameters = EquatableArray<string>.Empty;
|
||||||
|
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string luaName)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
LuaReturnKind returnKind;
|
||||||
|
if (method.ReturnsVoid)
|
||||||
|
returnKind = LuaReturnKind.Void;
|
||||||
|
else if (method.ReturnType.ToDisplayString() == "MoonSharp.Interpreter.DynValue")
|
||||||
|
returnKind = LuaReturnKind.DynValue;
|
||||||
|
else if (method.ReturnType.SpecialType == SpecialType.System_Double)
|
||||||
|
returnKind = LuaReturnKind.Double;
|
||||||
|
else
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var parameters = new List<LuaParameterModel>();
|
||||||
|
foreach (var parameter in method.Parameters)
|
||||||
|
{
|
||||||
|
LuaParameterKind kind;
|
||||||
|
string defaultLiteral = string.Empty;
|
||||||
|
switch (parameter.Type.ToDisplayString())
|
||||||
|
{
|
||||||
|
case "MoonSharp.Interpreter.ScriptExecutionContext":
|
||||||
|
kind = LuaParameterKind.ExecutionContext;
|
||||||
|
break;
|
||||||
|
case "MoonSharp.Interpreter.CallbackArguments":
|
||||||
|
kind = LuaParameterKind.Arguments;
|
||||||
|
break;
|
||||||
|
case "MoonSharp.Interpreter.DynValue":
|
||||||
|
kind = LuaParameterKind.DynValue;
|
||||||
|
break;
|
||||||
|
case "double":
|
||||||
|
kind = LuaParameterKind.Double;
|
||||||
|
defaultLiteral = FormatDouble(parameter.HasExplicitDefaultValue ? (double)parameter.ExplicitDefaultValue! : 0d);
|
||||||
|
break;
|
||||||
|
case "int":
|
||||||
|
kind = LuaParameterKind.Int;
|
||||||
|
defaultLiteral = FormatDouble(parameter.HasExplicitDefaultValue ? (int)parameter.ExplicitDefaultValue! : 0);
|
||||||
|
break;
|
||||||
|
case "bool":
|
||||||
|
kind = LuaParameterKind.Bool;
|
||||||
|
defaultLiteral = parameter.HasExplicitDefaultValue && (bool)parameter.ExplicitDefaultValue! ? "true" : "false";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
parameters.Add(new LuaParameterModel(parameter.Name, kind, defaultLiteral));
|
||||||
|
}
|
||||||
|
|
||||||
|
var explicitParameters = attribute.ConstructorArguments.Length > 1
|
||||||
|
? ExtractStringArray(attribute.ConstructorArguments[1])
|
||||||
|
: EquatableArray<string>.Empty;
|
||||||
|
catalogParameters = explicitParameters.Count > 0
|
||||||
|
? explicitParameters
|
||||||
|
: new EquatableArray<string>([.. parameters
|
||||||
|
.Where(static p => p.Kind is not (LuaParameterKind.ExecutionContext or LuaParameterKind.Arguments))
|
||||||
|
.Select(static p => p.Name)]);
|
||||||
|
|
||||||
|
return new LuaFunctionModel(luaName, method.Name, returnKind, new EquatableArray<LuaParameterModel>([.. parameters]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaUpdateModel? CreateUpdateModel(IMethodSymbol method, AttributeData attribute, string tableName, ref string contextType, out LuaCatalogEntry? entry)
|
||||||
|
{
|
||||||
|
entry = null;
|
||||||
|
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string luaName)
|
||||||
|
return null;
|
||||||
|
if (method.Parameters.Length != 1)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
string parameterType = method.Parameters[0].Type.ToDisplayString();
|
||||||
|
if (contextType.Length == 0)
|
||||||
|
contextType = parameterType;
|
||||||
|
else if (contextType != parameterType)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var returnType = method.ReturnType;
|
||||||
|
LuaUpdateKind kind;
|
||||||
|
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
|
||||||
|
kind = LuaUpdateKind.OptionalValue;
|
||||||
|
else if (returnType.IsReferenceType)
|
||||||
|
kind = LuaUpdateKind.OptionalReference;
|
||||||
|
else
|
||||||
|
kind = LuaUpdateKind.Direct;
|
||||||
|
|
||||||
|
bool inCatalog = true;
|
||||||
|
foreach (var argument in attribute.NamedArguments)
|
||||||
|
{
|
||||||
|
if (argument.Key == "InCatalog" && argument.Value.Value is bool value)
|
||||||
|
inCatalog = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inCatalog)
|
||||||
|
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
|
||||||
|
return new LuaUpdateModel(luaName, method.Name, kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FormatDouble(double value) =>
|
||||||
|
value.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + "d";
|
||||||
|
|
||||||
|
private static string RegistrationHintName(LuaTableModel model)
|
||||||
|
{
|
||||||
|
var chain = string.Join(".", model.TypeChain.Select(static p => p.Name));
|
||||||
|
return $"{model.Namespace}.{chain}.LuaRegistration.g.cs";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EmitRegistration(LuaTableModel model)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
builder.AppendLine($"namespace {model.Namespace}");
|
||||||
|
builder.AppendLine("{");
|
||||||
|
|
||||||
|
string indent = " ";
|
||||||
|
foreach (var part in model.TypeChain)
|
||||||
|
{
|
||||||
|
builder.AppendLine($"{indent}{(part.IsStatic ? "static partial class " : "partial class ")}{part.Name}");
|
||||||
|
builder.AppendLine($"{indent}{{");
|
||||||
|
indent += " ";
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isStatic = model.TypeChain[model.TypeChain.Count - 1].IsStatic;
|
||||||
|
string body = indent + " ";
|
||||||
|
|
||||||
|
if (model.Constants.Count > 0 || model.Functions.Count > 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine($"{indent}internal {(isStatic ? "static " : "")}void RegisterLuaMembers(global::MoonSharp.Interpreter.Table table)");
|
||||||
|
builder.AppendLine($"{indent}{{");
|
||||||
|
|
||||||
|
foreach (var constant in model.Constants)
|
||||||
|
builder.AppendLine($"{body}table[\"{constant.LuaName}\"] = {constant.MemberName};");
|
||||||
|
|
||||||
|
foreach (var function in model.Functions)
|
||||||
|
{
|
||||||
|
string call = $"{function.MethodName}({EmitArguments(function.Parameters)})";
|
||||||
|
string lambda = function.ReturnKind switch
|
||||||
|
{
|
||||||
|
LuaReturnKind.DynValue => $"(execCtx, args) => {call}",
|
||||||
|
LuaReturnKind.Double => $"(execCtx, args) => global::MoonSharp.Interpreter.DynValue.NewNumber({call})",
|
||||||
|
_ => $"(execCtx, args) => {{ {call}; return global::MoonSharp.Interpreter.DynValue.Void; }}",
|
||||||
|
};
|
||||||
|
builder.AppendLine($"{body}table[\"{function.LuaName}\"] = global::MoonSharp.Interpreter.DynValue.NewCallback({lambda});");
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.AppendLine($"{indent}}}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (model.Updates.Count > 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine($"{indent}internal {(isStatic ? "static " : "")}void UpdateLuaMembers(global::MoonSharp.Interpreter.Table table, global::{model.ContextType} context)");
|
||||||
|
builder.AppendLine($"{indent}{{");
|
||||||
|
foreach (var update in model.Updates)
|
||||||
|
{
|
||||||
|
switch (update.Kind)
|
||||||
|
{
|
||||||
|
case LuaUpdateKind.OptionalValue:
|
||||||
|
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}");
|
||||||
|
break;
|
||||||
|
case LuaUpdateKind.OptionalReference:
|
||||||
|
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
builder.AppendLine($"{indent}}}");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
indent = new string(' ', 4 * (i + 1));
|
||||||
|
builder.AppendLine($"{indent}}}");
|
||||||
|
}
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
|
||||||
|
{
|
||||||
|
var rendered = new List<string>();
|
||||||
|
int position = 0;
|
||||||
|
foreach (var parameter in parameters)
|
||||||
|
{
|
||||||
|
if (parameter.Kind == LuaParameterKind.ExecutionContext)
|
||||||
|
{
|
||||||
|
rendered.Add("execCtx");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (parameter.Kind == LuaParameterKind.Arguments)
|
||||||
|
{
|
||||||
|
rendered.Add("args");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
rendered.Add(parameter.Kind switch
|
||||||
|
{
|
||||||
|
LuaParameterKind.DynValue => $"args.Count > {position} ? args[{position}] : global::MoonSharp.Interpreter.DynValue.Nil",
|
||||||
|
LuaParameterKind.Double => $"args.Count > {position} ? args[{position}].CastToNumber() ?? {parameter.DefaultLiteral} : {parameter.DefaultLiteral}",
|
||||||
|
LuaParameterKind.Int => $"(int)(args.Count > {position} ? args[{position}].CastToNumber() ?? {parameter.DefaultLiteral} : {parameter.DefaultLiteral})",
|
||||||
|
_ => $"args.Count > {position} ? args[{position}].CastToBool() : {parameter.DefaultLiteral}",
|
||||||
|
});
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
return string.Join(", ", rendered);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EmitCatalog(LuaCatalogEntry[] entries)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
builder.AppendLine("namespace LuaScript.Generated");
|
||||||
|
builder.AppendLine("{");
|
||||||
|
builder.AppendLine(" internal static class LuaApiModuleInitializer");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" [global::System.Runtime.CompilerServices.ModuleInitializer]");
|
||||||
|
builder.AppendLine(" internal static void Initialize()");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" global::LuaScript.Api.LuaApiCatalog.Register(new global::LuaScript.Api.LuaApiMember[]");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
foreach (var entry in entries)
|
||||||
|
{
|
||||||
|
string kind = entry.IsFunction
|
||||||
|
? "global::LuaScript.Api.LuaApiMemberKind.Function"
|
||||||
|
: "global::LuaScript.Api.LuaApiMemberKind.Variable";
|
||||||
|
string parameters = entry.Parameters.Count == 0
|
||||||
|
? "global::System.Array.Empty<string>()"
|
||||||
|
: $"new string[] {{ {string.Join(", ", entry.Parameters.Select(static p => $"\"{p}\""))} }}";
|
||||||
|
builder.AppendLine($" new(\"{entry.Table}\", \"{entry.Name}\", {kind}, {parameters}),");
|
||||||
|
}
|
||||||
|
builder.AppendLine(" });");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<LuaCatalogEntry> CollectAssemblyEntries(Compilation compilation)
|
||||||
|
{
|
||||||
|
var entries = new List<(int Position, LuaCatalogEntry Entry)>();
|
||||||
|
foreach (var attribute in compilation.Assembly.GetAttributes())
|
||||||
|
{
|
||||||
|
string? attributeName = attribute.AttributeClass?.ToDisplayString();
|
||||||
|
if (attributeName is not (VariableAttributeName or BuiltinAttributeName or FunctionAttributeName))
|
||||||
|
continue;
|
||||||
|
var entry = CreateAttributeEntry(attribute, string.Empty);
|
||||||
|
if (entry is null)
|
||||||
|
continue;
|
||||||
|
entries.Add((attribute.ApplicationSyntaxReference?.Span.Start ?? 0, entry));
|
||||||
|
}
|
||||||
|
return [.. entries.OrderBy(static e => e.Position).Select(static e => e.Entry)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>netstandard2.0</TargetFramework>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Version>1.18.0</Version>
|
||||||
|
<IsRoslynComponent>true</IsRoslynComponent>
|
||||||
|
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" PrivateAssets="all" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
using Microsoft.CodeAnalysis.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order);
|
||||||
|
|
||||||
|
[Generator]
|
||||||
|
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
|
||||||
|
{
|
||||||
|
private const string RuleAttributeName = "LuaScript.Compat.Syntax.LuaSyntaxRuleAttribute";
|
||||||
|
private const string RuleInterfaceName = "LuaScript.Compat.Syntax.ILuaSyntaxRule";
|
||||||
|
|
||||||
|
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||||
|
{
|
||||||
|
var rules = context.SyntaxProvider
|
||||||
|
.ForAttributeWithMetadataName(
|
||||||
|
RuleAttributeName,
|
||||||
|
static (node, _) => node is ClassDeclarationSyntax,
|
||||||
|
static (ctx, _) => CreateModel(ctx))
|
||||||
|
.Where(static model => model is not null)
|
||||||
|
.Select(static (model, _) => model!);
|
||||||
|
|
||||||
|
context.RegisterSourceOutput(rules.Collect(), static (ctx, models) =>
|
||||||
|
{
|
||||||
|
if (models.Length == 0)
|
||||||
|
return;
|
||||||
|
ctx.AddSource("LuaSyntaxRuleRegistry.g.cs", SourceText.From(Emit(models), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaSyntaxRuleModel? CreateModel(GeneratorAttributeSyntaxContext context)
|
||||||
|
{
|
||||||
|
if (context.TargetSymbol is not INamedTypeSymbol symbol)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (!symbol.AllInterfaces.Any(static contract => contract.ToDisplayString() == RuleInterfaceName))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
int order = 0;
|
||||||
|
var arguments = context.Attributes[0].ConstructorArguments;
|
||||||
|
if (arguments.Length > 0 && arguments[0].Value is int value)
|
||||||
|
order = value;
|
||||||
|
|
||||||
|
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
|
||||||
|
{
|
||||||
|
var ordered = models
|
||||||
|
.OrderBy(static m => m.Order)
|
||||||
|
.ThenBy(static m => m.TypeName, StringComparer.Ordinal)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
builder.AppendLine("namespace LuaScript.Compat.Syntax");
|
||||||
|
builder.AppendLine("{");
|
||||||
|
builder.AppendLine(" internal static class LuaSyntaxRuleRegistry");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" internal static readonly global::LuaScript.Compat.Syntax.ILuaSyntaxRule[] Rules = new global::LuaScript.Compat.Syntax.ILuaSyntaxRule[]");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
foreach (var model in ordered)
|
||||||
|
builder.AppendLine($" new global::{model.TypeName}(),");
|
||||||
|
builder.AppendLine(" };");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.Intrinsics;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class CpuKernel(CpuKernel.RowDelegate row, CpuKernel.RowDelegate? block)
|
||||||
|
{
|
||||||
|
public delegate void RowDelegate(byte[] buffer, int rowBase, int xStart, int xEnd, double y, double[] uniforms);
|
||||||
|
|
||||||
|
private const int ParallelThreshold = 64;
|
||||||
|
private const int WarmupRunsPerPath = 1;
|
||||||
|
private const int TimedRunsPerPath = 3;
|
||||||
|
|
||||||
|
private readonly RowDelegate _row = row;
|
||||||
|
private readonly RowDelegate? _block = block;
|
||||||
|
private long _rowTicks;
|
||||||
|
private long _blockTicks;
|
||||||
|
private int _rowRuns;
|
||||||
|
private int _blockRuns;
|
||||||
|
private bool _nextIsBlock = true;
|
||||||
|
private bool _decided;
|
||||||
|
private bool _useBlock;
|
||||||
|
|
||||||
|
public bool? BlockAdopted => _decided ? _useBlock : null;
|
||||||
|
|
||||||
|
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
|
||||||
|
{
|
||||||
|
if (_block is null || !Vector256.IsHardwareAccelerated)
|
||||||
|
{
|
||||||
|
Run(buffer, width, height, uniforms, false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_decided)
|
||||||
|
{
|
||||||
|
Run(buffer, width, height, uniforms, _useBlock);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool useBlock = _nextIsBlock;
|
||||||
|
_nextIsBlock = !_nextIsBlock;
|
||||||
|
|
||||||
|
long start = Stopwatch.GetTimestamp();
|
||||||
|
Run(buffer, width, height, uniforms, useBlock);
|
||||||
|
long elapsed = Stopwatch.GetTimestamp() - start;
|
||||||
|
|
||||||
|
if (useBlock)
|
||||||
|
{
|
||||||
|
if (_blockRuns >= WarmupRunsPerPath)
|
||||||
|
_blockTicks += elapsed;
|
||||||
|
_blockRuns++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (_rowRuns >= WarmupRunsPerPath)
|
||||||
|
_rowTicks += elapsed;
|
||||||
|
_rowRuns++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_rowRuns >= WarmupRunsPerPath + TimedRunsPerPath &&
|
||||||
|
_blockRuns >= WarmupRunsPerPath + TimedRunsPerPath)
|
||||||
|
{
|
||||||
|
_useBlock = _blockTicks < _rowTicks;
|
||||||
|
_decided = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Run(byte[] buffer, int width, int height, double[] uniforms, bool useBlock)
|
||||||
|
{
|
||||||
|
var row = _row;
|
||||||
|
var block = useBlock ? _block : null;
|
||||||
|
int stride = width * 4;
|
||||||
|
int blockWidth = block is null ? 0 : width & ~3;
|
||||||
|
|
||||||
|
void RunRow(int y)
|
||||||
|
{
|
||||||
|
int rowBase = y * stride;
|
||||||
|
if (blockWidth > 0)
|
||||||
|
block!(buffer, rowBase, 0, blockWidth, y, uniforms);
|
||||||
|
if (blockWidth < width)
|
||||||
|
row(buffer, rowBase, blockWidth, width, y, uniforms);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (height < ParallelThreshold)
|
||||||
|
{
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
RunRow(y);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Parallel.For(0, height, RunRow);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
-6
@@ -31,11 +31,15 @@ namespace LuaScript.Engine.Kernel
|
|||||||
[KFunc.Max] = Binary(nameof(Math.Max)),
|
[KFunc.Max] = Binary(nameof(Math.Max)),
|
||||||
};
|
};
|
||||||
|
|
||||||
public static CpuKernel Compile(KernelProgram program)
|
public static CpuKernel Compile(KernelProgram program) =>
|
||||||
|
new(CompileRow(program), SimdKernelCompiler.TryCompile(program));
|
||||||
|
|
||||||
|
public static CpuKernel.RowDelegate CompileRow(KernelProgram program)
|
||||||
{
|
{
|
||||||
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||||
var width = Expression.Parameter(typeof(int), "width");
|
|
||||||
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||||
|
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||||
|
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||||
var y = Expression.Parameter(typeof(double), "y");
|
var y = Expression.Parameter(typeof(double), "y");
|
||||||
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||||
|
|
||||||
@@ -85,7 +89,7 @@ namespace LuaScript.Engine.Kernel
|
|||||||
var breakLabel = Expression.Label("break");
|
var breakLabel = Expression.Label("break");
|
||||||
var loop = Expression.Loop(
|
var loop = Expression.Loop(
|
||||||
Expression.IfThenElse(
|
Expression.IfThenElse(
|
||||||
Expression.LessThan(x, width),
|
Expression.LessThan(x, xEnd),
|
||||||
Expression.Block(statements),
|
Expression.Block(statements),
|
||||||
Expression.Break(breakLabel)),
|
Expression.Break(breakLabel)),
|
||||||
breakLabel);
|
breakLabel);
|
||||||
@@ -94,10 +98,10 @@ namespace LuaScript.Engine.Kernel
|
|||||||
locals.AddRange(inputs);
|
locals.AddRange(inputs);
|
||||||
locals.AddRange(slots);
|
locals.AddRange(slots);
|
||||||
|
|
||||||
var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop);
|
var body = Expression.Block(locals, Expression.Assign(x, xStart), loop);
|
||||||
|
|
||||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, width, rowBase, y, uniforms);
|
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
|
||||||
return new CpuKernel(lambda.Compile());
|
return lambda.Compile();
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record Context(
|
private sealed record Context(
|
||||||
@@ -151,6 +155,8 @@ namespace LuaScript.Engine.Kernel
|
|||||||
|
|
||||||
private static Expression BuildCall(KCall call, Context context)
|
private static Expression BuildCall(KCall call, Context context)
|
||||||
{
|
{
|
||||||
|
if (call.Func == KFunc.Fmod)
|
||||||
|
return Expression.Modulo(Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||||
var method = Functions[call.Func];
|
var method = Functions[call.Func];
|
||||||
if (call.Arguments.Count == 1)
|
if (call.Arguments.Count == 1)
|
||||||
return Expression.Call(method, Build(call.Arguments[0], context));
|
return Expression.Call(method, Build(call.Arguments[0], context));
|
||||||
+13
-19
@@ -9,12 +9,6 @@ namespace LuaScript.Engine.Kernel
|
|||||||
|
|
||||||
public const int ConstantFloatCount = ConstantVectorCount * 4;
|
public const int ConstantFloatCount = ConstantVectorCount * 4;
|
||||||
|
|
||||||
private static readonly string[] Intrinsics =
|
|
||||||
[
|
|
||||||
"abs", "floor", "ceil", "sqrt", "sin", "cos", "tan", "asin", "acos",
|
|
||||||
"atan", "atan2", "exp", "log", "pow", "min", "max", "fmod",
|
|
||||||
];
|
|
||||||
|
|
||||||
public static string Emit(KernelProgram program)
|
public static string Emit(KernelProgram program)
|
||||||
{
|
{
|
||||||
var builder = new StringBuilder(1024);
|
var builder = new StringBuilder(1024);
|
||||||
@@ -32,8 +26,8 @@ namespace LuaScript.Engine.Kernel
|
|||||||
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
|
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
|
||||||
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
|
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
|
||||||
builder.Append(" float inA = srcA * 255.0;\n");
|
builder.Append(" float inA = srcA * 255.0;\n");
|
||||||
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(";\n");
|
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(" - 0.5;\n");
|
||||||
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(";\n");
|
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(" - 0.5;\n");
|
||||||
|
|
||||||
for (int i = 0; i < program.Bindings.Count; i++)
|
for (int i = 0; i < program.Bindings.Count; i++)
|
||||||
{
|
{
|
||||||
@@ -42,21 +36,21 @@ namespace LuaScript.Engine.Kernel
|
|||||||
builder.Append(";\n");
|
builder.Append(";\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.Append(" float outA = ");
|
builder.Append(" float outA = clamp(");
|
||||||
EmitExpression(builder, program.OutputA);
|
EmitExpression(builder, program.OutputA);
|
||||||
builder.Append(";\n");
|
builder.Append(", 0.0, 255.0);\n");
|
||||||
builder.Append(" float alphaK = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
builder.Append(" float alphaK = outA / 255.0;\n");
|
||||||
|
|
||||||
builder.Append(" float oR = clamp((");
|
builder.Append(" float oR = floor(clamp((");
|
||||||
EmitExpression(builder, program.OutputR);
|
EmitExpression(builder, program.OutputR);
|
||||||
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||||
builder.Append(" float oG = clamp((");
|
builder.Append(" float oG = floor(clamp((");
|
||||||
EmitExpression(builder, program.OutputG);
|
EmitExpression(builder, program.OutputG);
|
||||||
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||||
builder.Append(" float oB = clamp((");
|
builder.Append(" float oB = floor(clamp((");
|
||||||
EmitExpression(builder, program.OutputB);
|
EmitExpression(builder, program.OutputB);
|
||||||
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||||
builder.Append(" float oA = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
builder.Append(" float oA = floor(outA) / 255.0;\n");
|
||||||
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
|
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
|
||||||
|
|
||||||
return builder.ToString();
|
return builder.ToString();
|
||||||
@@ -153,7 +147,7 @@ namespace LuaScript.Engine.Kernel
|
|||||||
|
|
||||||
private static void EmitCall(StringBuilder builder, KCall call)
|
private static void EmitCall(StringBuilder builder, KCall call)
|
||||||
{
|
{
|
||||||
builder.Append(Intrinsics[(int)call.Func]).Append('(');
|
builder.Append(KFunctions.Intrinsic(call.Func)).Append('(');
|
||||||
for (int i = 0; i < call.Arguments.Count; i++)
|
for (int i = 0; i < call.Arguments.Count; i++)
|
||||||
{
|
{
|
||||||
if (i > 0)
|
if (i > 0)
|
||||||
+291
-33
@@ -5,36 +5,16 @@ namespace LuaScript.Engine.Kernel
|
|||||||
{
|
{
|
||||||
internal sealed class KernelExtractor
|
internal sealed class KernelExtractor
|
||||||
{
|
{
|
||||||
private readonly record struct FuncSpec(KFunc Func, int MinArgs, int MaxArgs);
|
|
||||||
|
|
||||||
private static readonly Dictionary<string, FuncSpec> MathFunctions = new(StringComparer.Ordinal)
|
|
||||||
{
|
|
||||||
["abs"] = new(KFunc.Abs, 1, 1),
|
|
||||||
["floor"] = new(KFunc.Floor, 1, 1),
|
|
||||||
["ceil"] = new(KFunc.Ceil, 1, 1),
|
|
||||||
["sqrt"] = new(KFunc.Sqrt, 1, 1),
|
|
||||||
["sin"] = new(KFunc.Sin, 1, 1),
|
|
||||||
["cos"] = new(KFunc.Cos, 1, 1),
|
|
||||||
["tan"] = new(KFunc.Tan, 1, 1),
|
|
||||||
["asin"] = new(KFunc.Asin, 1, 1),
|
|
||||||
["acos"] = new(KFunc.Acos, 1, 1),
|
|
||||||
["atan"] = new(KFunc.Atan, 1, 1),
|
|
||||||
["atan2"] = new(KFunc.Atan2, 2, 2),
|
|
||||||
["exp"] = new(KFunc.Exp, 1, 1),
|
|
||||||
["log"] = new(KFunc.Log, 1, 1),
|
|
||||||
["pow"] = new(KFunc.Pow, 2, 2),
|
|
||||||
["fmod"] = new(KFunc.Fmod, 2, 2),
|
|
||||||
["min"] = new(KFunc.Min, 2, int.MaxValue),
|
|
||||||
["max"] = new(KFunc.Max, 2, int.MaxValue),
|
|
||||||
};
|
|
||||||
|
|
||||||
private readonly List<KExpr> _bindings = [];
|
private readonly List<KExpr> _bindings = [];
|
||||||
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
private Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||||
private readonly SortedSet<KernelUniform> _uniforms = [];
|
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||||
|
|
||||||
private string _widthVariable = string.Empty;
|
private string _widthVariable = string.Empty;
|
||||||
private string _heightVariable = string.Empty;
|
private string _heightVariable = string.Empty;
|
||||||
private bool _coordsEnabled;
|
private bool _coordsEnabled;
|
||||||
|
private string? _pixelDataVariable;
|
||||||
|
private string _baseIndexVariable = string.Empty;
|
||||||
|
private readonly bool[] _writtenChannels = new bool[4];
|
||||||
|
|
||||||
public static KernelProgram? TryExtract(string runnableScript)
|
public static KernelProgram? TryExtract(string runnableScript)
|
||||||
{
|
{
|
||||||
@@ -55,28 +35,187 @@ namespace LuaScript.Engine.Kernel
|
|||||||
int index = 0;
|
int index = 0;
|
||||||
while (index < block.Count && block[index] is LocalStmt prelude)
|
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||||
{
|
{
|
||||||
|
if (TryBindPixelData(prelude))
|
||||||
|
{
|
||||||
|
index++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
BindLocal(prelude);
|
BindLocal(prelude);
|
||||||
index++;
|
index++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||||
return null;
|
return null;
|
||||||
if (index + 1 != block.Count)
|
int tail = index + 1;
|
||||||
|
if (tail < block.Count && IsPutPixelData(block[tail]))
|
||||||
|
tail++;
|
||||||
|
if (tail != block.Count)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||||
return null;
|
return null;
|
||||||
|
_scope.Remove(outerVar);
|
||||||
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||||
return null;
|
return null;
|
||||||
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||||
return null;
|
return null;
|
||||||
|
_scope.Remove(innerVar);
|
||||||
if (outerAxis == innerAxis)
|
if (outerAxis == innerAxis)
|
||||||
return null;
|
return null;
|
||||||
|
if (_pixelDataVariable is not null &&
|
||||||
|
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
|
||||||
|
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
|
||||||
|
return null;
|
||||||
|
|
||||||
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||||
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||||
|
|
||||||
return BuildKernel(inner.Body);
|
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsPutPixelData(LuaStmt statement) =>
|
||||||
|
_pixelDataVariable is not null &&
|
||||||
|
statement is CallStmt { Call: CallExpr { Arguments.Count: 1 } call } &&
|
||||||
|
IsObjectMethod(call, "putpixeldata") &&
|
||||||
|
call.Arguments[0] is NameExpr { } handle &&
|
||||||
|
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
private bool TryBindPixelData(LocalStmt local)
|
||||||
|
{
|
||||||
|
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||||
|
local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 })
|
||||||
|
return false;
|
||||||
|
if (_pixelDataVariable is not null)
|
||||||
|
throw new KernelUnsupportedException("Multiple pixel-data handles are not supported.");
|
||||||
|
_pixelDataVariable = local.Names[0];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KernelProgram? BuildPixelDataKernel(IReadOnlyList<LuaStmt> body)
|
||||||
|
{
|
||||||
|
if (body.Count < 5)
|
||||||
|
return null;
|
||||||
|
if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0]))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
EnsureNotCoordinateName(baseStmt.Names[0]);
|
||||||
|
_baseIndexVariable = baseStmt.Names[0];
|
||||||
|
_coordsEnabled = true;
|
||||||
|
|
||||||
|
KExpr? outR = null, outG = null, outB = null;
|
||||||
|
for (int i = 1; i < body.Count; i++)
|
||||||
|
{
|
||||||
|
switch (body[i])
|
||||||
|
{
|
||||||
|
case LocalStmt local:
|
||||||
|
BindLocal(local);
|
||||||
|
break;
|
||||||
|
case AssignStmt assign:
|
||||||
|
BindAssign(assign);
|
||||||
|
break;
|
||||||
|
case IfStmt conditional:
|
||||||
|
LowerConditional(conditional);
|
||||||
|
break;
|
||||||
|
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||||
|
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||||
|
if (writeChannel == 0) outR = value;
|
||||||
|
else if (writeChannel == 1) outG = value;
|
||||||
|
else outB = value;
|
||||||
|
_writtenChannels[writeChannel] = true;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (outR is null || outG is null || outB is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsBaseIndex(LuaExpr expression)
|
||||||
|
{
|
||||||
|
if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled ||
|
||||||
|
scaled.Left is not BinaryExpr { Operator: "+" } sum)
|
||||||
|
return false;
|
||||||
|
if (!IsCoordinate(sum.Right, KAxis.X))
|
||||||
|
return false;
|
||||||
|
if (sum.Left is not BinaryExpr { Operator: "*" } stride)
|
||||||
|
return false;
|
||||||
|
return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsWidth(LuaExpr expression)
|
||||||
|
{
|
||||||
|
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||||
|
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||||
|
return uniform == KernelUniform.Width;
|
||||||
|
if (expression is NameExpr { } alias &&
|
||||||
|
TryUniformAlias(alias.Name, out var aliased))
|
||||||
|
return aliased == KernelUniform.Width;
|
||||||
|
return _pixelDataVariable is not null &&
|
||||||
|
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||||
|
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryUniformAlias(string name, out KernelUniform uniform)
|
||||||
|
{
|
||||||
|
if (_scope.TryGetValue(name, out int slot) && _bindings[slot] is KUniformRef reference)
|
||||||
|
{
|
||||||
|
uniform = reference.Uniform;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uniform = default;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||||
|
{
|
||||||
|
channel = 0;
|
||||||
|
if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call ||
|
||||||
|
call.Target is not NameExpr { } handle ||
|
||||||
|
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
return false;
|
||||||
|
if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel))
|
||||||
|
return false;
|
||||||
|
channel--;
|
||||||
|
return !_writtenChannels[channel];
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsPixelDataSet(MethodCallExpr call, out int channel)
|
||||||
|
{
|
||||||
|
channel = 0;
|
||||||
|
if (call.Method != "set" || call.Arguments.Count != 2 ||
|
||||||
|
call.Target is not NameExpr { } handle ||
|
||||||
|
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
return false;
|
||||||
|
if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel))
|
||||||
|
return false;
|
||||||
|
channel--;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr ClampChannel(KExpr value)
|
||||||
|
{
|
||||||
|
var bound = new KLocalRef(AddBinding(value));
|
||||||
|
return new KSelect(
|
||||||
|
new KCompare(KCompareOp.Less, bound, new KConst(0d)),
|
||||||
|
new KConst(0d),
|
||||||
|
new KSelect(
|
||||||
|
new KCompare(KCompareOp.Greater, bound, new KConst(255d)),
|
||||||
|
new KConst(255d),
|
||||||
|
bound));
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset)
|
||||||
|
{
|
||||||
|
offset = 0;
|
||||||
|
if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } ||
|
||||||
|
!string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal))
|
||||||
|
return false;
|
||||||
|
offset = (int)number.Value;
|
||||||
|
return offset == number.Value && offset >= min && offset <= max;
|
||||||
}
|
}
|
||||||
|
|
||||||
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
|
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
|
||||||
@@ -107,12 +246,15 @@ namespace LuaScript.Engine.Kernel
|
|||||||
case AssignStmt assign:
|
case AssignStmt assign:
|
||||||
BindAssign(assign);
|
BindAssign(assign);
|
||||||
break;
|
break;
|
||||||
|
case IfStmt conditional:
|
||||||
|
LowerConditional(conditional);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel"))
|
if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel"))
|
||||||
return null;
|
return null;
|
||||||
if (call.Arguments.Count is < 5 or > 6)
|
if (call.Arguments.Count is < 5 or > 6)
|
||||||
return null;
|
return null;
|
||||||
@@ -162,11 +304,85 @@ namespace LuaScript.Engine.Kernel
|
|||||||
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void LowerConditional(IfStmt statement) =>
|
||||||
|
LowerConditional(statement.Clauses, 0, statement.ElseBody);
|
||||||
|
|
||||||
|
private void LowerConditional(IReadOnlyList<IfClause> clauses, int index, IReadOnlyList<LuaStmt>? elseBody)
|
||||||
|
{
|
||||||
|
var clause = clauses[index];
|
||||||
|
var condition = LowerBool(clause.Condition);
|
||||||
|
var baseline = _scope;
|
||||||
|
|
||||||
|
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||||
|
LowerBranchBody(clause.Body);
|
||||||
|
var taken = _scope;
|
||||||
|
|
||||||
|
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||||
|
if (index + 1 < clauses.Count)
|
||||||
|
LowerConditional(clauses, index + 1, elseBody);
|
||||||
|
else if (elseBody is not null)
|
||||||
|
LowerBranchBody(elseBody);
|
||||||
|
var skipped = _scope;
|
||||||
|
|
||||||
|
var merged = new Dictionary<string, int>(baseline.Count, StringComparer.Ordinal);
|
||||||
|
foreach (var name in baseline.Keys)
|
||||||
|
{
|
||||||
|
int whenTrue = taken[name];
|
||||||
|
int whenFalse = skipped[name];
|
||||||
|
merged[name] = whenTrue == whenFalse
|
||||||
|
? whenTrue
|
||||||
|
: AddBinding(new KSelect(condition, new KLocalRef(whenTrue), new KLocalRef(whenFalse)));
|
||||||
|
}
|
||||||
|
_scope = merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LowerBranchBody(IReadOnlyList<LuaStmt> body)
|
||||||
|
{
|
||||||
|
Dictionary<string, int>? shadowed = null;
|
||||||
|
HashSet<string>? introduced = null;
|
||||||
|
foreach (var statement in body)
|
||||||
|
{
|
||||||
|
switch (statement)
|
||||||
|
{
|
||||||
|
case LocalStmt local:
|
||||||
|
foreach (var name in local.Names)
|
||||||
|
{
|
||||||
|
if (introduced?.Contains(name) == true || shadowed?.ContainsKey(name) == true)
|
||||||
|
continue;
|
||||||
|
if (_scope.TryGetValue(name, out int slot))
|
||||||
|
(shadowed ??= new(StringComparer.Ordinal))[name] = slot;
|
||||||
|
else
|
||||||
|
(introduced ??= new(StringComparer.Ordinal)).Add(name);
|
||||||
|
}
|
||||||
|
BindLocal(local);
|
||||||
|
break;
|
||||||
|
case AssignStmt assign:
|
||||||
|
BindAssign(assign);
|
||||||
|
break;
|
||||||
|
case IfStmt nested:
|
||||||
|
LowerConditional(nested);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new KernelUnsupportedException("Unsupported statement in a conditional branch.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (shadowed is not null)
|
||||||
|
foreach (var (name, slot) in shadowed)
|
||||||
|
_scope[name] = slot;
|
||||||
|
if (introduced is not null)
|
||||||
|
foreach (var name in introduced)
|
||||||
|
_scope.Remove(name);
|
||||||
|
}
|
||||||
|
|
||||||
private void EnsureNotCoordinateName(string name)
|
private void EnsureNotCoordinateName(string name)
|
||||||
{
|
{
|
||||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||||
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||||
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
|
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
|
||||||
|
if (_pixelDataVariable is not null && string.Equals(name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
throw new KernelUnsupportedException("Local variable shadows the pixel-data handle.");
|
||||||
|
if (_baseIndexVariable.Length > 0 && string.Equals(name, _baseIndexVariable, StringComparison.Ordinal))
|
||||||
|
throw new KernelUnsupportedException("Local variable shadows the base index.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private int AddBinding(KExpr expression)
|
private int AddBinding(KExpr expression)
|
||||||
@@ -187,6 +403,8 @@ namespace LuaScript.Engine.Kernel
|
|||||||
return LowerMember(member);
|
return LowerMember(member);
|
||||||
case CallExpr call:
|
case CallExpr call:
|
||||||
return LowerCall(call);
|
return LowerCall(call);
|
||||||
|
case MethodCallExpr method when TryPixelDataChannel(method, out int channel):
|
||||||
|
return new KInput((KChannel)channel);
|
||||||
case UnaryExpr { Operator: "-" } unary:
|
case UnaryExpr { Operator: "-" } unary:
|
||||||
return new KNegate(Lower(unary.Operand));
|
return new KNegate(Lower(unary.Operand));
|
||||||
case BinaryExpr binary:
|
case BinaryExpr binary:
|
||||||
@@ -223,13 +441,23 @@ namespace LuaScript.Engine.Kernel
|
|||||||
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||||
return UseUniform(uniform);
|
return UseUniform(uniform);
|
||||||
|
|
||||||
|
if (_pixelDataVariable is not null &&
|
||||||
|
member.Target is NameExpr { } handle &&
|
||||||
|
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
if (string.Equals(member.Name, "width", StringComparison.Ordinal))
|
||||||
|
return UseUniform(KernelUniform.Width);
|
||||||
|
if (string.Equals(member.Name, "height", StringComparison.Ordinal))
|
||||||
|
return UseUniform(KernelUniform.Height);
|
||||||
|
}
|
||||||
|
|
||||||
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private KExpr LowerCall(CallExpr call)
|
private KExpr LowerCall(CallExpr call)
|
||||||
{
|
{
|
||||||
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
|
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
|
||||||
!MathFunctions.TryGetValue(function, out var spec))
|
!KFunctions.TryResolve(function, out var spec))
|
||||||
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
|
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
|
||||||
|
|
||||||
int count = call.Arguments.Count;
|
int count = call.Arguments.Count;
|
||||||
@@ -323,11 +551,9 @@ namespace LuaScript.Engine.Kernel
|
|||||||
return false;
|
return false;
|
||||||
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||||
return false;
|
return false;
|
||||||
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field })
|
if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||||
return false;
|
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||||
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
{
|
||||||
return false;
|
|
||||||
|
|
||||||
if (uniform == KernelUniform.Width)
|
if (uniform == KernelUniform.Width)
|
||||||
{
|
{
|
||||||
axis = KAxis.X;
|
axis = KAxis.X;
|
||||||
@@ -341,6 +567,38 @@ namespace LuaScript.Engine.Kernel
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (_pixelDataVariable is not null &&
|
||||||
|
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
|
||||||
|
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
if (pixelField == "width")
|
||||||
|
{
|
||||||
|
axis = KAxis.X;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (pixelField == "height")
|
||||||
|
{
|
||||||
|
axis = KAxis.Y;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bound.Left is NameExpr { } alias && TryUniformAlias(alias.Name, out var aliased))
|
||||||
|
{
|
||||||
|
if (aliased == KernelUniform.Width)
|
||||||
|
{
|
||||||
|
axis = KAxis.X;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (aliased == KernelUniform.Height)
|
||||||
|
{
|
||||||
|
axis = KAxis.Y;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private bool IsGetPixel(LuaExpr expression) =>
|
private bool IsGetPixel(LuaExpr expression) =>
|
||||||
expression is CallExpr call && IsObjectMethod(call, "getpixel") &&
|
expression is CallExpr call && IsObjectMethod(call, "getpixel") &&
|
||||||
call.Arguments.Count == 2 &&
|
call.Arguments.Count == 2 &&
|
||||||
差分なしでファイル名を変更。
@@ -0,0 +1,270 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.Intrinsics;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class SimdKernelCompiler
|
||||||
|
{
|
||||||
|
private static readonly Type Vec = typeof(Vector256<double>);
|
||||||
|
|
||||||
|
private static readonly MethodInfo Broadcast = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double)])!;
|
||||||
|
private static readonly MethodInfo Create4 = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double), typeof(double), typeof(double), typeof(double)])!;
|
||||||
|
private static readonly MethodInfo GetElement = VecOp(nameof(Vector256.GetElement), 1, 1);
|
||||||
|
private static readonly MethodInfo Add = VecOp(nameof(Vector256.Add), 2);
|
||||||
|
private static readonly MethodInfo Subtract = VecOp(nameof(Vector256.Subtract), 2);
|
||||||
|
private static readonly MethodInfo Multiply = VecOp(nameof(Vector256.Multiply), 2);
|
||||||
|
private static readonly MethodInfo Divide = VecOp(nameof(Vector256.Divide), 2);
|
||||||
|
private static readonly MethodInfo Negate = VecOp(nameof(Vector256.Negate), 1);
|
||||||
|
private static readonly MethodInfo Abs = VecOp(nameof(Vector256.Abs), 1);
|
||||||
|
private static readonly MethodInfo Sqrt = VecOp(nameof(Vector256.Sqrt), 1);
|
||||||
|
private static readonly MethodInfo FloorFn = typeof(Vector256).GetMethod(nameof(Vector256.Floor), [Vec])!;
|
||||||
|
private static readonly MethodInfo CeilingFn = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), [Vec])!;
|
||||||
|
private static readonly MethodInfo ConditionalSelect = VecOp(nameof(Vector256.ConditionalSelect), 3);
|
||||||
|
private static readonly MethodInfo LessThan = VecOp(nameof(Vector256.LessThan), 2);
|
||||||
|
private static readonly MethodInfo GreaterThan = VecOp(nameof(Vector256.GreaterThan), 2);
|
||||||
|
private static readonly MethodInfo LessThanOrEqual = VecOp(nameof(Vector256.LessThanOrEqual), 2);
|
||||||
|
private static readonly MethodInfo GreaterThanOrEqual = VecOp(nameof(Vector256.GreaterThanOrEqual), 2);
|
||||||
|
private static readonly MethodInfo EqualsFn = VecOp(nameof(Vector256.Equals), 2);
|
||||||
|
private static readonly MethodInfo BitwiseAnd = VecOp(nameof(Vector256.BitwiseAnd), 2);
|
||||||
|
private static readonly MethodInfo BitwiseOr = VecOp(nameof(Vector256.BitwiseOr), 2);
|
||||||
|
private static readonly MethodInfo OnesComplement = VecOp(nameof(Vector256.OnesComplement), 1);
|
||||||
|
|
||||||
|
private static readonly Expression Zero = Expression.Constant(Vector256<double>.Zero, Vec);
|
||||||
|
private static readonly Expression AllBits = Expression.Constant(Vector256<double>.AllBitsSet, Vec);
|
||||||
|
private static readonly Expression V255 = Expression.Constant(Vector256.Create(255d), Vec);
|
||||||
|
|
||||||
|
public static CpuKernel.RowDelegate? TryCompile(KernelProgram program)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return Compile(program);
|
||||||
|
}
|
||||||
|
catch (KernelUnsupportedException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CpuKernel.RowDelegate Compile(KernelProgram program)
|
||||||
|
{
|
||||||
|
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||||
|
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||||
|
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||||
|
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||||
|
var yScalar = Expression.Parameter(typeof(double), "y");
|
||||||
|
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||||
|
|
||||||
|
var x = Expression.Variable(typeof(int), "x");
|
||||||
|
var index = Expression.Variable(typeof(int), "index");
|
||||||
|
var yVec = Expression.Variable(Vec, "yVec");
|
||||||
|
var xVec = Expression.Variable(Vec, "xVec");
|
||||||
|
var alphaRaw = Expression.Variable(Vec, "alphaRaw");
|
||||||
|
var transparent = Expression.Variable(Vec, "transparent");
|
||||||
|
var scale = Expression.Variable(Vec, "scale");
|
||||||
|
var inputs = new[]
|
||||||
|
{
|
||||||
|
Expression.Variable(Vec, "inR"),
|
||||||
|
Expression.Variable(Vec, "inG"),
|
||||||
|
Expression.Variable(Vec, "inB"),
|
||||||
|
Expression.Variable(Vec, "inA"),
|
||||||
|
};
|
||||||
|
var slots = new ParameterExpression[program.Bindings.Count];
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
slots[i] = Expression.Variable(Vec, "slot" + i);
|
||||||
|
|
||||||
|
var context = new Context(xVec, yVec, uniforms, inputs, slots);
|
||||||
|
|
||||||
|
var statements = new List<Expression>
|
||||||
|
{
|
||||||
|
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||||
|
Expression.Assign(xVec, Expression.Call(Create4,
|
||||||
|
ToDouble(x),
|
||||||
|
ToDouble(Expression.Add(x, Constant(1))),
|
||||||
|
ToDouble(Expression.Add(x, Constant(2))),
|
||||||
|
ToDouble(Expression.Add(x, Constant(3))))),
|
||||||
|
Expression.Assign(alphaRaw, LoadChannel(buffer, index, 3)),
|
||||||
|
Expression.Assign(transparent, Call(LessThanOrEqual, alphaRaw, Zero)),
|
||||||
|
Expression.Assign(scale, Select(transparent, Zero, Call(Divide, V255, alphaRaw))),
|
||||||
|
Expression.Assign(inputs[3], Select(transparent, Zero, alphaRaw)),
|
||||||
|
Expression.Assign(inputs[0], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 2), scale)))),
|
||||||
|
Expression.Assign(inputs[1], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 1), scale)))),
|
||||||
|
Expression.Assign(inputs[2], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 0), scale)))),
|
||||||
|
};
|
||||||
|
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||||
|
|
||||||
|
var outA = Expression.Variable(Vec, "outA");
|
||||||
|
var alphaScale = Expression.Variable(Vec, "alphaScale");
|
||||||
|
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||||
|
statements.Add(Expression.Assign(alphaScale, Call(Divide, ClampByte(outA), V255)));
|
||||||
|
statements.Add(StoreChannel(buffer, index, 0, ClampByte(Call(Multiply, Build(program.OutputB, context), alphaScale))));
|
||||||
|
statements.Add(StoreChannel(buffer, index, 1, ClampByte(Call(Multiply, Build(program.OutputG, context), alphaScale))));
|
||||||
|
statements.Add(StoreChannel(buffer, index, 2, ClampByte(Call(Multiply, Build(program.OutputR, context), alphaScale))));
|
||||||
|
statements.Add(StoreChannel(buffer, index, 3, ClampByte(outA)));
|
||||||
|
statements.Add(Expression.AddAssign(x, Constant(4)));
|
||||||
|
|
||||||
|
var breakLabel = Expression.Label("break");
|
||||||
|
var loop = Expression.Loop(
|
||||||
|
Expression.IfThenElse(
|
||||||
|
Expression.LessThan(x, xEnd),
|
||||||
|
Expression.Block(statements),
|
||||||
|
Expression.Break(breakLabel)),
|
||||||
|
breakLabel);
|
||||||
|
|
||||||
|
var locals = new List<ParameterExpression> { x, index, yVec, xVec, alphaRaw, transparent, scale, outA, alphaScale };
|
||||||
|
locals.AddRange(inputs);
|
||||||
|
locals.AddRange(slots);
|
||||||
|
|
||||||
|
var body = Expression.Block(
|
||||||
|
locals,
|
||||||
|
Expression.Assign(yVec, Expression.Call(Broadcast, yScalar)),
|
||||||
|
Expression.Assign(x, xStart),
|
||||||
|
loop);
|
||||||
|
|
||||||
|
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, yScalar, uniforms);
|
||||||
|
return lambda.Compile();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record Context(
|
||||||
|
Expression X,
|
||||||
|
Expression Y,
|
||||||
|
ParameterExpression Uniforms,
|
||||||
|
Expression[] Inputs,
|
||||||
|
ParameterExpression[] Slots);
|
||||||
|
|
||||||
|
private static Expression Build(KExpr expression, Context context)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case KConst value:
|
||||||
|
return Expression.Constant(Vector256.Create(value.Value), Vec);
|
||||||
|
case KInput input:
|
||||||
|
return context.Inputs[(int)input.Channel];
|
||||||
|
case KCoord coord:
|
||||||
|
return coord.Axis == KAxis.X ? context.X : context.Y;
|
||||||
|
case KUniformRef uniform:
|
||||||
|
return Expression.Call(Broadcast, Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform)));
|
||||||
|
case KLocalRef local:
|
||||||
|
return context.Slots[local.Slot];
|
||||||
|
case KNegate negate:
|
||||||
|
return Call(Negate, Build(negate.Operand, context));
|
||||||
|
case KArith arithmetic:
|
||||||
|
return BuildArithmetic(arithmetic, context);
|
||||||
|
case KCall call:
|
||||||
|
return BuildCall(call, context);
|
||||||
|
case KSelect select:
|
||||||
|
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported SIMD expression.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||||
|
{
|
||||||
|
var left = Build(arithmetic.Left, context);
|
||||||
|
var right = Build(arithmetic.Right, context);
|
||||||
|
return arithmetic.Op switch
|
||||||
|
{
|
||||||
|
KArithOp.Add => Call(Add, left, right),
|
||||||
|
KArithOp.Subtract => Call(Subtract, left, right),
|
||||||
|
KArithOp.Multiply => Call(Multiply, left, right),
|
||||||
|
KArithOp.Divide => Call(Divide, left, right),
|
||||||
|
KArithOp.Modulo => Call(Subtract, left, Call(Multiply, Call(FloorFn, Call(Divide, left, right)), right)),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported SIMD arithmetic operator."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildCall(KCall call, Context context)
|
||||||
|
{
|
||||||
|
var argument = Build(call.Arguments[0], context);
|
||||||
|
return call.Func switch
|
||||||
|
{
|
||||||
|
KFunc.Abs => Call(Abs, argument),
|
||||||
|
KFunc.Floor => Call(FloorFn, argument),
|
||||||
|
KFunc.Ceil => Call(CeilingFn, argument),
|
||||||
|
KFunc.Sqrt => Call(Sqrt, argument),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported SIMD function."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildBool(KBool condition, Context context)
|
||||||
|
{
|
||||||
|
switch (condition)
|
||||||
|
{
|
||||||
|
case KBoolConst value:
|
||||||
|
return value.Value ? AllBits : Zero;
|
||||||
|
case KNot not:
|
||||||
|
return Call(OnesComplement, BuildBool(not.Operand, context));
|
||||||
|
case KLogical logical:
|
||||||
|
return logical.IsAnd
|
||||||
|
? Call(BitwiseAnd, BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||||
|
: Call(BitwiseOr, BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||||
|
case KCompare compare:
|
||||||
|
var left = Build(compare.Left, context);
|
||||||
|
var right = Build(compare.Right, context);
|
||||||
|
return compare.Op switch
|
||||||
|
{
|
||||||
|
KCompareOp.Less => Call(LessThan, left, right),
|
||||||
|
KCompareOp.Greater => Call(GreaterThan, left, right),
|
||||||
|
KCompareOp.LessEqual => Call(LessThanOrEqual, left, right),
|
||||||
|
KCompareOp.GreaterEqual => Call(GreaterThanOrEqual, left, right),
|
||||||
|
KCompareOp.Equal => Call(EqualsFn, left, right),
|
||||||
|
KCompareOp.NotEqual => Call(OnesComplement, Call(EqualsFn, left, right)),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported SIMD comparison."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported SIMD condition.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression ClampByte(Expression value)
|
||||||
|
{
|
||||||
|
var low = Select(Call(LessThan, value, Zero), Zero, value);
|
||||||
|
return Select(Call(GreaterThan, low, V255), V255, low);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||||
|
Expression.Call(ConditionalSelect, condition, whenTrue, whenFalse);
|
||||||
|
|
||||||
|
private static Expression LoadChannel(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||||
|
Expression.Call(Create4,
|
||||||
|
ToDouble(ReadByte(buffer, index, offset)),
|
||||||
|
ToDouble(ReadByte(buffer, index, offset + 4)),
|
||||||
|
ToDouble(ReadByte(buffer, index, offset + 8)),
|
||||||
|
ToDouble(ReadByte(buffer, index, offset + 12)));
|
||||||
|
|
||||||
|
private static Expression StoreChannel(ParameterExpression buffer, ParameterExpression index, int offset, Expression value)
|
||||||
|
{
|
||||||
|
var writes = new Expression[4];
|
||||||
|
for (int lane = 0; lane < 4; lane++)
|
||||||
|
writes[lane] = Expression.Assign(
|
||||||
|
Expression.ArrayAccess(buffer, Expression.Add(index, Constant(lane * 4 + offset))),
|
||||||
|
Expression.Convert(Expression.Call(GetElement, value, Constant(lane)), typeof(byte)));
|
||||||
|
return Expression.Block(writes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||||
|
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||||
|
|
||||||
|
private static Expression Call(MethodInfo method, params Expression[] arguments) =>
|
||||||
|
Expression.Call(method, arguments);
|
||||||
|
|
||||||
|
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||||
|
|
||||||
|
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||||
|
|
||||||
|
private static MethodInfo VecOp(string name, int vectorArgs, int intArgs = 0) =>
|
||||||
|
typeof(Vector256).GetMethods()
|
||||||
|
.Single(m => m.Name == name && m.IsGenericMethodDefinition &&
|
||||||
|
m.GetParameters().Length == vectorArgs + intArgs &&
|
||||||
|
m.GetParameters().Take(vectorArgs).All(p => IsVector(p.ParameterType)) &&
|
||||||
|
m.GetParameters().Skip(vectorArgs).All(p => p.ParameterType == typeof(int)))
|
||||||
|
.MakeGenericMethod(typeof(double));
|
||||||
|
|
||||||
|
private static bool IsVector(Type type) =>
|
||||||
|
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Vector256<>);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KArithOp
|
||||||
|
{
|
||||||
|
Add,
|
||||||
|
Subtract,
|
||||||
|
Multiply,
|
||||||
|
Divide,
|
||||||
|
Modulo,
|
||||||
|
Power,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KAxis
|
||||||
|
{
|
||||||
|
X,
|
||||||
|
Y,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal abstract record KBool;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KBoolConst(bool Value) : KBool;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KChannel
|
||||||
|
{
|
||||||
|
R,
|
||||||
|
G,
|
||||||
|
B,
|
||||||
|
A,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KCompareOp
|
||||||
|
{
|
||||||
|
Less,
|
||||||
|
Greater,
|
||||||
|
LessEqual,
|
||||||
|
GreaterEqual,
|
||||||
|
Equal,
|
||||||
|
NotEqual,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KConst(double Value) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KCoord(KAxis Axis) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal abstract record KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KFunc
|
||||||
|
{
|
||||||
|
Abs,
|
||||||
|
Floor,
|
||||||
|
Ceil,
|
||||||
|
Sqrt,
|
||||||
|
Sin,
|
||||||
|
Cos,
|
||||||
|
Tan,
|
||||||
|
Asin,
|
||||||
|
Acos,
|
||||||
|
Atan,
|
||||||
|
Atan2,
|
||||||
|
Exp,
|
||||||
|
Log,
|
||||||
|
Pow,
|
||||||
|
Min,
|
||||||
|
Max,
|
||||||
|
Fmod,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal readonly record struct KFunctionInfo(KFunc Func, string Name, int MinArgs, int MaxArgs);
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class KFunctions
|
||||||
|
{
|
||||||
|
private static readonly KFunctionInfo[] Catalog =
|
||||||
|
[
|
||||||
|
new(KFunc.Abs, "abs", 1, 1),
|
||||||
|
new(KFunc.Floor, "floor", 1, 1),
|
||||||
|
new(KFunc.Ceil, "ceil", 1, 1),
|
||||||
|
new(KFunc.Sqrt, "sqrt", 1, 1),
|
||||||
|
new(KFunc.Sin, "sin", 1, 1),
|
||||||
|
new(KFunc.Cos, "cos", 1, 1),
|
||||||
|
new(KFunc.Tan, "tan", 1, 1),
|
||||||
|
new(KFunc.Asin, "asin", 1, 1),
|
||||||
|
new(KFunc.Acos, "acos", 1, 1),
|
||||||
|
new(KFunc.Atan, "atan", 1, 1),
|
||||||
|
new(KFunc.Atan2, "atan2", 2, 2),
|
||||||
|
new(KFunc.Exp, "exp", 1, 1),
|
||||||
|
new(KFunc.Log, "log", 1, 1),
|
||||||
|
new(KFunc.Pow, "pow", 2, 2),
|
||||||
|
new(KFunc.Min, "min", 2, int.MaxValue),
|
||||||
|
new(KFunc.Max, "max", 2, int.MaxValue),
|
||||||
|
new(KFunc.Fmod, "fmod", 2, 2),
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, KFunctionInfo> ByName = BuildByName();
|
||||||
|
private static readonly string[] Intrinsics = BuildIntrinsics();
|
||||||
|
|
||||||
|
public static bool TryResolve(string name, out KFunctionInfo info) => ByName.TryGetValue(name, out info);
|
||||||
|
|
||||||
|
public static string Intrinsic(KFunc func) => Intrinsics[(int)func];
|
||||||
|
|
||||||
|
private static Dictionary<string, KFunctionInfo> BuildByName()
|
||||||
|
{
|
||||||
|
var map = new Dictionary<string, KFunctionInfo>(Catalog.Length, StringComparer.Ordinal);
|
||||||
|
foreach (var info in Catalog)
|
||||||
|
map[info.Name] = info;
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string[] BuildIntrinsics()
|
||||||
|
{
|
||||||
|
var names = new string[Enum.GetValues<KFunc>().Length];
|
||||||
|
foreach (var info in Catalog)
|
||||||
|
names[(int)info.Func] = info.Name;
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KInput(KChannel Channel) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KLocalRef(int Slot) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KNegate(KExpr Operand) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KNot(KBool Operand) : KBool;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KernelProgram(
|
||||||
|
IReadOnlyList<KExpr> Bindings,
|
||||||
|
KExpr OutputR,
|
||||||
|
KExpr OutputG,
|
||||||
|
KExpr OutputB,
|
||||||
|
KExpr OutputA,
|
||||||
|
IReadOnlyList<KernelUniform> Uniforms);
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KernelUniform
|
||||||
|
{
|
||||||
|
Width,
|
||||||
|
Height,
|
||||||
|
HalfWidth,
|
||||||
|
HalfHeight,
|
||||||
|
CenterX,
|
||||||
|
CenterY,
|
||||||
|
CenterZ,
|
||||||
|
Diagonal,
|
||||||
|
X,
|
||||||
|
Y,
|
||||||
|
Z,
|
||||||
|
Ox,
|
||||||
|
Oy,
|
||||||
|
Oz,
|
||||||
|
Sx,
|
||||||
|
Sy,
|
||||||
|
Sz,
|
||||||
|
Zoom,
|
||||||
|
Aspect,
|
||||||
|
Alpha,
|
||||||
|
Rx,
|
||||||
|
Ry,
|
||||||
|
Rz,
|
||||||
|
Rxr,
|
||||||
|
Ryr,
|
||||||
|
Rzr,
|
||||||
|
Track0,
|
||||||
|
Track1,
|
||||||
|
Track2,
|
||||||
|
Track3,
|
||||||
|
Slider0,
|
||||||
|
Slider1,
|
||||||
|
Slider2,
|
||||||
|
Slider3,
|
||||||
|
Check0,
|
||||||
|
Check1,
|
||||||
|
Check2,
|
||||||
|
Check3,
|
||||||
|
Color,
|
||||||
|
Time,
|
||||||
|
Frame,
|
||||||
|
TotalFrame,
|
||||||
|
TotalTime,
|
||||||
|
T,
|
||||||
|
Framerate,
|
||||||
|
Layer,
|
||||||
|
Index,
|
||||||
|
Num,
|
||||||
|
SceneWidth,
|
||||||
|
SceneHeight,
|
||||||
|
SceneCenterX,
|
||||||
|
SceneCenterY,
|
||||||
|
TimelineFrame,
|
||||||
|
TimelineTime,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,64 +3,6 @@ using System.Collections.Generic;
|
|||||||
|
|
||||||
namespace LuaScript.Engine.Kernel
|
namespace LuaScript.Engine.Kernel
|
||||||
{
|
{
|
||||||
internal enum KernelUniform
|
|
||||||
{
|
|
||||||
Width,
|
|
||||||
Height,
|
|
||||||
HalfWidth,
|
|
||||||
HalfHeight,
|
|
||||||
CenterX,
|
|
||||||
CenterY,
|
|
||||||
CenterZ,
|
|
||||||
Diagonal,
|
|
||||||
X,
|
|
||||||
Y,
|
|
||||||
Z,
|
|
||||||
Ox,
|
|
||||||
Oy,
|
|
||||||
Oz,
|
|
||||||
Sx,
|
|
||||||
Sy,
|
|
||||||
Sz,
|
|
||||||
Zoom,
|
|
||||||
Aspect,
|
|
||||||
Alpha,
|
|
||||||
Rx,
|
|
||||||
Ry,
|
|
||||||
Rz,
|
|
||||||
Rxr,
|
|
||||||
Ryr,
|
|
||||||
Rzr,
|
|
||||||
Track0,
|
|
||||||
Track1,
|
|
||||||
Track2,
|
|
||||||
Track3,
|
|
||||||
Slider0,
|
|
||||||
Slider1,
|
|
||||||
Slider2,
|
|
||||||
Slider3,
|
|
||||||
Check0,
|
|
||||||
Check1,
|
|
||||||
Check2,
|
|
||||||
Check3,
|
|
||||||
Color,
|
|
||||||
Time,
|
|
||||||
Frame,
|
|
||||||
TotalFrame,
|
|
||||||
TotalTime,
|
|
||||||
T,
|
|
||||||
Framerate,
|
|
||||||
Layer,
|
|
||||||
Index,
|
|
||||||
Num,
|
|
||||||
SceneWidth,
|
|
||||||
SceneHeight,
|
|
||||||
SceneCenterX,
|
|
||||||
SceneCenterY,
|
|
||||||
TimelineFrame,
|
|
||||||
TimelineTime,
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static class KernelUniforms
|
internal static class KernelUniforms
|
||||||
{
|
{
|
||||||
public static int Count { get; } = Enum.GetValues<KernelUniform>().Length;
|
public static int Count { get; } = Enum.GetValues<KernelUniform>().Length;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record BoolExpr(bool Value) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal abstract record LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal abstract record LuaStmt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record NameExpr(string Name) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record NilExpr : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record NumberExpr(double Value) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record NumericForStmt(
|
||||||
|
string Variable,
|
||||||
|
LuaExpr Start,
|
||||||
|
LuaExpr Stop,
|
||||||
|
LuaExpr? Step,
|
||||||
|
IReadOnlyList<LuaStmt> Body) : LuaStmt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record StringExpr(string Value) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
|
||||||
|
}
|
||||||
@@ -149,8 +149,8 @@ namespace LuaScript.Engine.Kernel
|
|||||||
return new AssignStmt(targets, values);
|
return new AssignStmt(targets, values);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (first is CallExpr call)
|
if (first is CallExpr or MethodCallExpr)
|
||||||
return new CallStmt(call);
|
return new CallStmt(first);
|
||||||
|
|
||||||
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
||||||
}
|
}
|
||||||
@@ -275,6 +275,12 @@ namespace LuaScript.Engine.Kernel
|
|||||||
{
|
{
|
||||||
expression = new CallExpr(expression, ParseArguments());
|
expression = new CallExpr(expression, ParseArguments());
|
||||||
}
|
}
|
||||||
|
else if (t.IsSymbol(":"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
string method = ExpectName();
|
||||||
|
expression = new MethodCallExpr(expression, method, ParseArguments());
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
@@ -2,16 +2,6 @@ using System;
|
|||||||
|
|
||||||
namespace LuaScript.Engine.Kernel
|
namespace LuaScript.Engine.Kernel
|
||||||
{
|
{
|
||||||
internal enum LuaTokenKind
|
|
||||||
{
|
|
||||||
Name,
|
|
||||||
Number,
|
|
||||||
String,
|
|
||||||
Keyword,
|
|
||||||
Symbol,
|
|
||||||
Eof,
|
|
||||||
}
|
|
||||||
|
|
||||||
internal readonly struct LuaToken(LuaTokenKind kind, string text, double number)
|
internal readonly struct LuaToken(LuaTokenKind kind, string text, double number)
|
||||||
{
|
{
|
||||||
public LuaTokenKind Kind { get; } = kind;
|
public LuaTokenKind Kind { get; } = kind;
|
||||||
274ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする