コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
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
|
検索条件に一致するファイルはありません
+23
-24
@@ -1,43 +1,42 @@
|
||||
# v1.13.4 - Lua スクリプト for YMM4
|
||||
# v1.14.0 - Lua スクリプト for YMM4
|
||||
|
||||
環境情報を取得する obj.getinfo を追加したリリースです。
|
||||
スクリプトの設置フォルダのパスや動画の出力状態に加えて、最大画像サイズ、BPMグリッドの情報、経過時間、本体のバージョンを名前で取得できます。MoonSharp とネイティブの両エンジンで同一の関数として動作します。
|
||||
あわせて、プラグインの内部構成を依存関係の層ごとの複数アセンブリへ分割し、Lua API の登録と入力補完をソースジェネレータによる宣言的な生成へ移行しました。既存のスクリプトの書き方と実行結果に変更はありません。
|
||||
標準の Lua には無い簡易な記法をまとめて追加したリリースです。比較の is、否定の is not、論理演算子の別名、複合代入、nil 合体、範囲指定の for など、キーボードで打ちやすく入力量を減らすための糖衣構文を導入しました。これらの記法はスクリプトの実行前に等価な標準 Lua へ変換され、MoonSharp、ネイティブ、カーネルのいずれの実行経路でも同じ結果になります。変換の基盤は属性から生成するトークン規則として設計しており、記法を 1 つ増やす場合はクラスを 1 つ追加するだけで反映されます。あわせて、エラー表示が書き換え後の行を正しく扱うように改め、新しい記号を使うとパラメータの表示判定が無効になる不具合を修正しました。既存のスクリプトの書き方と実行結果に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### obj.getinfo による環境情報の取得
|
||||
### 構文拡張
|
||||
|
||||
obj.getinfo(名前) は、名前で指定した環境情報を返します。対応していない名前を指定した場合は nil を返します。取得できる情報は次のとおりです。
|
||||
標準の Lua には無い簡易な記法をいくつか追加しました。いずれも実行前に等価な標準 Lua へ変換されるため、実行結果は手書きの標準 Lua と同じになります。変換の入口は Lua に存在しない記号または語順に限っており、文字列とコメントの内側は変換しません。
|
||||
|
||||
- "script_path" は、プラグインの設置フォルダのパスを返します。末尾には区切り文字が付きます。
|
||||
- "filter" は、フィルタ効果として処理中かどうかを返します。本プラグインでは常に true を返します。
|
||||
- "saving" は、動画を出力中のときだけ true を返します。
|
||||
- "image_max" は、最大画像サイズを横幅と高さの2つの値で返します。
|
||||
- "bpm" は、BPMグリッドのテンポと拍子と基準時間の3つの値を返します。基準時間の単位は秒です。BPMグリッドを設定していない場合はテンポが 0 になります。
|
||||
- "clock" は、YMM4 の起動からの経過時間を秒で返します。
|
||||
- "script_time" は、スクリプトの実行開始からの経過時間をミリ秒で返します。
|
||||
- "version" は、本体のバージョンを major×10000+minor×100+build の数値で返します。
|
||||
- 比較では、a is b が a == b、a is not b が a ~= b、a != b が a ~= b へ変換されます。is と is not は前後が値になる位置でのみ働くため、is という名前の変数とは衝突しません。
|
||||
- 論理では、!a が not a、a && b が a and b、a || b が a or b へ変換されます。
|
||||
- 複合代入では、+= -= *= /= %= ^= ..= を使えます。x += 1 は x = x + (1) へ展開し、右辺を括弧で囲むため優先順位は保たれます。
|
||||
- nil 合体では、a ?? b は a が nil のときだけ b を返します。a は一度だけ評価し、false や 0 は a の値としてそのまま返します。x ??= b は x が nil のときだけ b を代入します。
|
||||
- 論理代入では、x ||= b が x = x or (b)、x &&= b が x = x and (b) へ変換されます。
|
||||
- インクリメントでは、x++ が x = x + 1 へ変換されます。
|
||||
- 範囲指定の for では、for i in <0..10> が for i = 0, 10 と同じく終端を含む反復になります。for i in <0..<10> は終端を含まず、for i in <0..10, 2> は増分を 2 に指定します。
|
||||
|
||||
編集中のみプレビューへ枠を描き、出力時には描かないといった分岐へ利用できます。
|
||||
各記法の説明と例は、プラグイン付属のドキュメントおよびサイトの構文拡張のページへ追記しています。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- 既存のスクリプトの書き方と実行結果に変更はありません。obj.getinfo は新規の関数であり、従来の呼び出しへは影響しません。
|
||||
- obj.getinfo は MoonSharp とネイティブの両エンジンで動作します。script_path、filter、saving、image_max、bpm、version は両エンジンで同一の値を返します。clock と script_time は経過時間の計測であり、値そのものは実行のたびに変わります。
|
||||
- v1.13.3 までの仕様に変更はありません。
|
||||
- 追加した記法はすべて、標準の Lua には無い記号または語順を入口にしています。既存のスクリプトはそのまま動作し、実行結果も変わりません。
|
||||
- 変換は文字列とコメントの内側には及びません。行数は保たれ、整形とコメントもそのまま残ります。
|
||||
- 変換はすべての実行経路へ適用されます。MoonSharp、ネイティブ、カーネルのいずれで実行しても同じ結果になります。
|
||||
- v1.13.4 までの仕様に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- プラグインを依存関係の層ごとに LuaScript.Kernel、LuaScript.Compat、LuaScript.Media、LuaScript.Runtime、および本体の 5 つのアセンブリへ分割しました。名前空間は据え置き、参照の向きを一方向へ整理しています。
|
||||
- Lua API の登録と毎フレームの変数投影を、属性から生成するソースジェネレータへ移行しました。入力補完の候補もこの宣言から生成し、手書きの一覧を廃止しました。関数を 1 つ追加すると、登録と補完へ自動的に反映されます。
|
||||
- Kernel、Compat、Runtime の各プロジェクトを 1 ファイル 1 クラスへ整理し、ドメインごとのフォルダへ再配置しました。エンジンのテーブル管理は LuaScope へ汎用化しています。
|
||||
- 映像デコーダを LuaScript.Media プロジェクトへ分離し、ツールバーを View と ViewModel へ分離しました。ViewModel はフレームワークに依存しない構成へ整理しています。
|
||||
- obj.getinfo の実装では、BPMグリッドの情報を YMM4 のシーンから取得し、script_path と version は本体からエンジンへ渡します。経過時間は両エンジンがそれぞれ高精度タイマーで計測します。
|
||||
- テストは 3113 件です。v1.13.3 の 3092 件から、obj.getinfo の両エンジンでの実行結果の検証と、補完カタログの回帰検証、およびエンジンのテーブルライフサイクルの特性化検証を追加しました。
|
||||
- 書き換えの基盤として、空白とコメントと文字列を保持する可逆のトークン字句解析器を新設しました。カーネル抽出が使う不可逆の字句解析器とは要件が異なるため、別の実装として分けています。
|
||||
- 各記法は LuaSyntaxRule 属性を付けた 1 つのクラスとして実装し、ILuaSyntaxRule インターフェースの判定処理だけを持ちます。ソースジェネレータがこれらのクラスを収集し、優先順位で並べた規則レジストリを生成します。記法の追加はクラスの追加だけで完結し、中央の分岐を書き換える必要はありません。
|
||||
- 規則レジストリの生成器は、Lua API を生成する既存のジェネレータとは責務が異なるため、独立したジェネレータとして分離しました。
|
||||
- nil 合体の a ?? b は、a を一度だけ評価するために無名関数の即時呼び出しへ展開します。nil 合体代入の x ??= b は条件文へ展開します。複合代入と論理代入は、左辺と演算子から等価な代入文を組み立てます。
|
||||
- エラー表示では、書き換えが変更した行を記録し、その行の診断は桁ではなく行全体を対象にします。これにより、変換した独自構文の上へ誤って波線が乗ることを防ぎます。変更していない行では、報告された桁の情報をそのまま使います。この記録はソースの変更時に一度だけ作り、毎フレームの処理では文字列比較もメモリ確保も増やしません。
|
||||
- パラメータの表示判定を、カーネルの字句解析器から新しい可逆の字句解析器へ移しました。従来は新しい記号でカーネルの字句解析器が例外を投げ、スライダーとチェックと色の表示判定が無効になっていました。
|
||||
- テストは 3215 件です。v1.13.4 の 3113 件から、各記法の変換結果と評価結果の検証、変換後の独自構文がネイティブでも動作することの検証、変更行の記録の検証、および新しい記法を使ってもパラメータの表示判定が働くことの検証を追加しました。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.13.4
|
||||
Luaスクリプト for YMM4 v1.14.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.14.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -15,10 +15,10 @@ namespace LuaScript.Compat
|
||||
|
||||
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))
|
||||
return (source, []);
|
||||
return (source, [], []);
|
||||
|
||||
var lines = ScriptParserHelper.SplitLines(source);
|
||||
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||
@@ -28,7 +28,10 @@ namespace LuaScript.Compat
|
||||
AppendDeclarations(lines[i], prelude);
|
||||
|
||||
if (!hasSection && prelude.Count == 0)
|
||||
return (source, []);
|
||||
{
|
||||
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||
return (code, [], changed);
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(source.Length + 64);
|
||||
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||
@@ -45,7 +48,8 @@ namespace LuaScript.Compat
|
||||
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)
|
||||
|
||||
@@ -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, []);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using LuaScript.Engine.Kernel;
|
||||
using LuaScript.Compat.Syntax;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
@@ -35,15 +35,7 @@ namespace LuaScript.Compat
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return None;
|
||||
|
||||
List<LuaToken> tokens;
|
||||
try
|
||||
{
|
||||
tokens = LuaLexer.Tokenize(script);
|
||||
}
|
||||
catch (KernelUnsupportedException)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
var tokens = LuaSyntaxLexer.Tokenize(script);
|
||||
|
||||
HashSet<string>? members = null;
|
||||
bool color = false;
|
||||
@@ -51,26 +43,52 @@ namespace LuaScript.Compat
|
||||
for (int i = 0; i < tokens.Count; i++)
|
||||
{
|
||||
var token = tokens[i];
|
||||
if (token.Kind != LuaTokenKind.Name)
|
||||
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||
continue;
|
||||
|
||||
if (token.Text == "color")
|
||||
{
|
||||
if (i == 0 || !tokens[i - 1].IsSymbol("."))
|
||||
int previous = PreviousSignificant(tokens, i);
|
||||
if (previous < 0 || !tokens[previous].IsOperator("."))
|
||||
color = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.Text == "obj" &&
|
||||
i + 2 < tokens.Count &&
|
||||
tokens[i + 1].IsSymbol(".") &&
|
||||
tokens[i + 2].Kind == LuaTokenKind.Name)
|
||||
if (token.Text == "obj")
|
||||
{
|
||||
(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);
|
||||
}
|
||||
|
||||
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,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,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,237 @@
|
||||
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 (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,13 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal enum LuaSyntaxTokenKind
|
||||
{
|
||||
Whitespace,
|
||||
Newline,
|
||||
Comment,
|
||||
String,
|
||||
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,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,127 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
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 (!TryParseRange(context.Input, open, out string replacement, out int end))
|
||||
return false;
|
||||
|
||||
context.EmitRaw(replacement);
|
||||
context.Index = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryParseRange(IReadOnlyList<LuaSyntaxToken> input, int open, out string replacement, out int end)
|
||||
{
|
||||
replacement = string.Empty;
|
||||
end = open;
|
||||
|
||||
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;
|
||||
|
||||
string stopExpression = exclusive ? $"({stop}) - 1" : stop;
|
||||
replacement = step is null ? $"= {start}, {stopExpression}" : $"= {start}, {stopExpression}, {step}";
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.14.0</Version>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.14.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.14.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.14.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -133,5 +133,42 @@ namespace LuaScript.Tests
|
||||
double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2);
|
||||
Assert.Equal(500d * expectedRand / 100d, moved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_EmptyWhenNoRewrite()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_ReportRewrittenLineInRunnableSpace()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
|
||||
Assert.Equal(new[] { 2 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_AreSortedAndCoverEveryRewrittenLine()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
|
||||
Assert.Equal(new[] { 1, 3, 4 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_DeduplicateMultipleRewritesOnOneLine()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
|
||||
Assert.Equal(new[] { 1 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_TrackRunnableLineAfterHoistedPrelude()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
|
||||
Assert.NotEmpty(changed);
|
||||
for (int i = 1; i < changed.Length; i++)
|
||||
Assert.True(changed[i] > changed[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
using LuaScript.Compat;
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class LuaSyntaxExtensionsTests
|
||||
{
|
||||
private static string Rewrite(string source) => LuaSyntaxExtensions.Rewrite(source);
|
||||
|
||||
private static DynValue Eval(string source)
|
||||
{
|
||||
var script = new Script(CoreModules.Preset_SoftSandbox);
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
return script.Globals.Get("result");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a is not b", "a ~= b")]
|
||||
[InlineData("if x is not nil then end", "if x ~= nil then end")]
|
||||
[InlineData("a is not b", "a ~= b")]
|
||||
[InlineData("a is\tnot b", "a ~= b")]
|
||||
[InlineData("a is\t not b", "a ~= b")]
|
||||
[InlineData("a is not b and c is not d", "a ~= b and c ~= d")]
|
||||
[InlineData("f() is not nil", "f() ~= nil")]
|
||||
public void IsNot_RewritesToNotEqual(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a is b", "a == b")]
|
||||
[InlineData("x = a is b", "x = a == b")]
|
||||
[InlineData("if a is b then end", "if a == b then end")]
|
||||
[InlineData("a is nothing", "a == nothing")]
|
||||
[InlineData("f() is g()", "f() == g()")]
|
||||
public void Is_RewritesToEqual(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("local is = 1\nx = is + 1")]
|
||||
[InlineData("is = 1")]
|
||||
[InlineData("obj.is = 1")]
|
||||
[InlineData("return is")]
|
||||
[InlineData("f(is)")]
|
||||
[InlineData("x = is")]
|
||||
[InlineData("print(x)\nis(y)")]
|
||||
[InlineData("island")]
|
||||
[InlineData("basis not x")]
|
||||
[InlineData("a isnot b")]
|
||||
public void Is_DoesNotClobberIdentifier(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Newline_BetweenIsAndNot_IsNotAnOperator()
|
||||
{
|
||||
const string source = "a is\nnot b";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a.is not b")]
|
||||
[InlineData("a:is not b")]
|
||||
public void MemberAccess_IsNotRewritten(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a != b", "a ~= b")]
|
||||
[InlineData("x = a != b", "x = a ~= b")]
|
||||
public void NotEqual_RewritesToTildeEqual(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x = !y", "x = not y")]
|
||||
[InlineData("!flag", "not flag")]
|
||||
[InlineData("a = !b and !c", "a = not b and not c")]
|
||||
public void Bang_RewritesToNot(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a && b", "a and b")]
|
||||
[InlineData("a&&b", "a and b")]
|
||||
[InlineData("a || b", "a or b")]
|
||||
[InlineData("a||b", "a or b")]
|
||||
[InlineData("a && b || c", "a and b or c")]
|
||||
public void LogicalAliases_Rewrite(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x += 1", "x = x + (1)")]
|
||||
[InlineData("x -= 1", "x = x - (1)")]
|
||||
[InlineData("x *= 2", "x = x * (2)")]
|
||||
[InlineData("x /= 2", "x = x / (2)")]
|
||||
[InlineData("x %= 2", "x = x % (2)")]
|
||||
[InlineData("x ^= 2", "x = x ^ (2)")]
|
||||
[InlineData("s ..= \"b\"", "s = s .. (\"b\")")]
|
||||
[InlineData("x ||= y", "x = x or (y)")]
|
||||
[InlineData("x &&= y", "x = x and (y)")]
|
||||
[InlineData("x *= a + b", "x = x * (a + b)")]
|
||||
[InlineData("t[i] += 1", "t[i] = t[i] + (1)")]
|
||||
[InlineData("obj.count += 1", "obj.count = obj.count + (1)")]
|
||||
[InlineData("x += f(a, b)", "x = x + (f(a, b))")]
|
||||
public void AugmentedAssignment_Rewrites(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x ??= y", "if x == nil then x = (y) end")]
|
||||
[InlineData("obj.field ??= 5", "if obj.field == nil then obj.field = (5) end")]
|
||||
[InlineData(" x ??= y", " if x == nil then x = (y) end")]
|
||||
public void NilCoalesceAssignment_Rewrites(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("i++", "i = i + 1")]
|
||||
[InlineData("count ++", "count = count + 1")]
|
||||
[InlineData("t[k]++", "t[k] = t[k] + 1")]
|
||||
public void Increment_Rewrites(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesce_LowersToInlineFunction()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = (function() local __lc0 = (a) if __lc0 ~= nil then return __lc0 else return (b) end end)()",
|
||||
Rewrite("x = a ?? b"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesce_CapturesFullOrOperand()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = (function() local __lc0 = (foo(a)) if __lc0 ~= nil then return __lc0 else return (b) end end)()",
|
||||
Rewrite("x = foo(a) ?? b"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("for i in <0..10> do end", "for i = 0, 10 do end")]
|
||||
[InlineData("for i in <0..<10> do end", "for i = 0, (10) - 1 do end")]
|
||||
[InlineData("for i in <0..10, 2> do end", "for i = 0, 10, 2 do end")]
|
||||
[InlineData("for i in <0..<10, 2> do end", "for i = 0, (10) - 1, 2 do end")]
|
||||
[InlineData("for i in <a..b> do end", "for i = a, b do end")]
|
||||
public void NumericRange_Rewrites(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("for k, v in pairs(t) do end")]
|
||||
[InlineData("for i, x in ipairs(list) do end")]
|
||||
[InlineData("for i in <0> do end")]
|
||||
public void NumericRange_DoesNotTouchGenericFor(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Comment_ContentIsPreserved()
|
||||
{
|
||||
const string source = "-- a is not b\nx = 1";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LongComment_ContentIsPreserved()
|
||||
{
|
||||
const string source = "--[[ a is not b ]]\nx = 1";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShortString_ContentIsPreserved()
|
||||
{
|
||||
const string source = "x = \"a is not b ?? c += 1\"";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LongString_ContentIsPreserved()
|
||||
{
|
||||
const string source = "x = [==[ a is not b ]==]";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RewrittenCode_PreservesLineCount()
|
||||
{
|
||||
const string source = "a = 1\nb = a is not 2\nc = 3";
|
||||
string rewritten = Rewrite(source);
|
||||
Assert.Equal(source.Split('\n').Length, rewritten.Split('\n').Length);
|
||||
Assert.Contains("b = a ~= 2", rewritten);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NoTrigger_ReturnsSameReference()
|
||||
{
|
||||
const string source = "obj.x = 1\nobj.y = 2";
|
||||
Assert.Same(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", "")]
|
||||
public void Empty_IsUnchanged(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Is_EvaluatesEquality()
|
||||
{
|
||||
Assert.True(Eval("result = (1 is 1)").Boolean);
|
||||
Assert.False(Eval("result = (1 is 2)").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNot_EvaluatesInequality()
|
||||
{
|
||||
Assert.True(Eval("result = (1 is not 2)").Boolean);
|
||||
Assert.False(Eval("result = (2 is not 2)").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotEqual_Evaluates()
|
||||
{
|
||||
Assert.True(Eval("result = (1 != 2)").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Bang_Evaluates()
|
||||
{
|
||||
Assert.True(Eval("result = (!false)").Boolean);
|
||||
Assert.False(Eval("result = (!true)").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LogicalAliases_Evaluate()
|
||||
{
|
||||
Assert.False(Eval("result = (true && false)").Boolean);
|
||||
Assert.Equal(4d, Eval("result = (false || 4)").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesce_FallsBackOnlyOnNil()
|
||||
{
|
||||
Assert.Equal(7d, Eval("result = nil ?? 7").Number);
|
||||
Assert.Equal(3d, Eval("result = 3 ?? 7").Number);
|
||||
var falseResult = Eval("result = false ?? 7");
|
||||
Assert.Equal(DataType.Boolean, falseResult.Type);
|
||||
Assert.False(falseResult.Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesce_EvaluatesLeftOnce()
|
||||
{
|
||||
const string source = "calls = 0\nfunction f() calls = calls + 1 return 42 end\nresult = f() ?? 0\nassert(calls == 1)";
|
||||
var script = new Script(CoreModules.Preset_SoftSandbox);
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
Assert.Equal(42d, script.Globals.Get("result").Number);
|
||||
Assert.Equal(1d, script.Globals.Get("calls").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesceAssignment_Evaluates()
|
||||
{
|
||||
Assert.Equal(9d, Eval("x = nil\nx ??= 9\nresult = x").Number);
|
||||
Assert.Equal(4d, Eval("x = 4\nx ??= 9\nresult = x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AugmentedAssignment_Evaluates()
|
||||
{
|
||||
Assert.Equal(8d, Eval("x = 5\nx += 3\nresult = x").Number);
|
||||
Assert.Equal(2d, Eval("x = 5\nx -= 3\nresult = x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AugmentedAssignment_PreservesPrecedence()
|
||||
{
|
||||
Assert.Equal(14d, Eval("a = 5\nb = 2\nx = 2\nx *= a + b\nresult = x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConcatAssignment_Evaluates()
|
||||
{
|
||||
Assert.Equal("ab", Eval("s = \"a\"\ns ..= \"b\"\nresult = s").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LogicalAssignment_Evaluates()
|
||||
{
|
||||
Assert.Equal(10d, Eval("x = false\nx ||= 10\nresult = x").Number);
|
||||
Assert.Equal(2d, Eval("x = 2\nx ||= 10\nresult = x").Number);
|
||||
Assert.Equal(5d, Eval("x = 1\nx &&= 5\nresult = x").Number);
|
||||
Assert.False(Eval("x = false\nx &&= 5\nresult = x").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Increment_Evaluates()
|
||||
{
|
||||
Assert.Equal(2d, Eval("x = 1\nx++\nresult = x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NumericRange_InclusiveEvaluates()
|
||||
{
|
||||
Assert.Equal(6d, Eval("s = 0\nfor i in <1..3> do s = s + i end\nresult = s").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NumericRange_ExclusiveEvaluates()
|
||||
{
|
||||
Assert.Equal(6d, Eval("s = 0\nfor i in <1..<4> do s = s + i end\nresult = s").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NumericRange_SteppedEvaluates()
|
||||
{
|
||||
Assert.Equal(30d, Eval("s = 0\nfor i in <0..10, 2> do s = s + i end\nresult = s").Number);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using LuaScript.Compat;
|
||||
using LuaScript.Engine;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
@@ -151,6 +152,25 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(System.Text.Encoding.UTF8.GetByteCount("C:/サンプル/画像.png"), fields[NativeProtocol.Alpha]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNotOperator_RunsAfterTransform()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var fields = Fields(2, 2, 0d);
|
||||
var pixels = new byte[16];
|
||||
|
||||
string script = AviUtlScript.Transform("obj.x = (1 is not 2) and 7 or 0\nobj.y = (2 is not 2) and 7 or 0");
|
||||
|
||||
bool ok = RunWorker(
|
||||
script,
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(7d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Y]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInfo_ExposesEnvironmentInfo()
|
||||
{
|
||||
|
||||
@@ -64,5 +64,46 @@ namespace LuaScript.Tests
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.False(usage.Check(i));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("if obj.check0 != nil then obj.alpha = 0 end", 0)]
|
||||
[InlineData("local v = obj.check1 ?? 1", 1)]
|
||||
[InlineData("obj.check2 ??= true", 2)]
|
||||
[InlineData("local v = not obj.check3 && true", 3)]
|
||||
[InlineData("for i in <0..obj.check0> do end", 0)]
|
||||
public void DetectsCheckThroughExtendedSyntax(string script, int index)
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect(script);
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.Equal(i == index, usage.Check(i));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("obj.x = obj.slider0 ?? 50", 0)]
|
||||
[InlineData("obj.zoom += obj.slider2 != 0 and 1 or 0", 2)]
|
||||
public void DetectsSliderThroughExtendedSyntax(string script, int index)
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect(script);
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.Equal(i == index, usage.Slider(i));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DetectsColorThroughExtendedSyntax()
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect("obj.rz = color != 0 and color || 1");
|
||||
Assert.True(usage.Color);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DetectsMultipleReferencesAcrossExtendedSyntax()
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect("local a = obj.check0 && obj.check3 != 0\nobj.x = obj.slider1 ?? 0");
|
||||
Assert.True(usage.Check0);
|
||||
Assert.False(usage.Check1);
|
||||
Assert.False(usage.Check2);
|
||||
Assert.True(usage.Check3);
|
||||
Assert.True(usage.Slider(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,7 @@ namespace LuaScript
|
||||
private string _sourceScript = string.Empty;
|
||||
private string _runnableScript = string.Empty;
|
||||
private int[] _runnableLineMap = [];
|
||||
private int[] _runnableChangedLines = [];
|
||||
private bool _runnableCached;
|
||||
private ID2D1Image? _cachedInput;
|
||||
private RenderKey _cachedKey;
|
||||
@@ -214,9 +215,10 @@ namespace LuaScript
|
||||
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
||||
return _runnableScript;
|
||||
|
||||
var (code, lineMap) = AviUtlScript.TransformWithMap(source);
|
||||
var (code, lineMap, changedLines) = AviUtlScript.TransformWithMap(source);
|
||||
_runnableScript = code;
|
||||
_runnableLineMap = lineMap;
|
||||
_runnableChangedLines = changedLines;
|
||||
_sourceScript = source;
|
||||
_runnableCached = true;
|
||||
return _runnableScript;
|
||||
@@ -232,11 +234,19 @@ namespace LuaScript
|
||||
private LuaScriptDiagnostic CreateDiagnostic(LuaScriptDiagnosticKind kind, string message)
|
||||
{
|
||||
var diagnostic = LuaScriptDiagnosticParser.Parse(kind, message);
|
||||
return diagnostic.Line > 0
|
||||
? diagnostic with { Line = MapRunnableLine(diagnostic.Line) }
|
||||
: diagnostic;
|
||||
if (diagnostic.Line <= 0)
|
||||
return diagnostic;
|
||||
|
||||
if (IsRunnableLineRewritten(diagnostic.Line))
|
||||
diagnostic = diagnostic with { Column = 0, Length = 0 };
|
||||
|
||||
return diagnostic with { Line = MapRunnableLine(diagnostic.Line) };
|
||||
}
|
||||
|
||||
private bool IsRunnableLineRewritten(int runnableLine)
|
||||
=> _runnableChangedLines.Length != 0
|
||||
&& Array.BinarySearch(_runnableChangedLines, runnableLine) >= 0;
|
||||
|
||||
private int MapRunnableLine(int runnableLine)
|
||||
{
|
||||
int index = runnableLine - 1;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.14.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -725,6 +725,39 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- امتدادات الصياغة -
|
||||
|
||||
تمت إضافة بعض الصيغ غير الموجودة في Lua القياسية. يجري تحويل النص البرمجي
|
||||
قبل التنفيذ، لذلك تعمل بالطريقة نفسها على جميع المحركات. لا يجري تحويل ما
|
||||
بداخل السلاسل النصية والتعليقات.
|
||||
|
||||
○ is / is not
|
||||
a is b تعني a == b، و a is not b تعني a ~= b.
|
||||
مثال: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○ != / ! / && / ||
|
||||
!= تعني ~=، و ! تعني not، و && تعني and، و || تعني or.
|
||||
|
||||
○ الإسناد المركب (+= -= *= /= %= ^= ..=)
|
||||
x += 1 يتوسع إلى x = x + (1). و ..= لدمج السلاسل النصية.
|
||||
|
||||
○ ?? (دمج القيمة الفارغة)
|
||||
a ?? b يعيد b فقط عندما تكون a فارغة (nil)، ولا يرجع إلى false.
|
||||
|
||||
○ ??= / ||= / &&=
|
||||
x ??= b يسند فقط عندما تكون x فارغة (nil).
|
||||
x ||= b هو x = x or (b)، و x &&= b هو x = x and (b).
|
||||
|
||||
○ ++
|
||||
x++ يتوسع إلى x = x + 1. استخدمه كعبارة في سطر مستقل.
|
||||
|
||||
○ حلقة النطاق (<البداية..النهاية>)
|
||||
for i in <0..10> do مثل for i = 0, 10 do ويشمل النهاية.
|
||||
<0..<10> لا يشمل النهاية. <0..10, 2> يستخدم خطوة 2.
|
||||
|
||||
|
||||
- أمثلة على النصوص البرمجية -
|
||||
|
||||
○ تلاشٍ تدريجي للظهور - fade-in (النص الافتراضي)
|
||||
|
||||
@@ -752,6 +752,39 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- Syntax Extensions -
|
||||
|
||||
A few notations that plain Lua does not have are added. The script is
|
||||
transformed before execution, so they work the same on every engine.
|
||||
The insides of strings and comments are not transformed.
|
||||
|
||||
o is / is not
|
||||
a is b means a == b, and a is not b means a ~= b.
|
||||
Example: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
o != / ! / && / ||
|
||||
!= means ~=, ! means not, && means and, and || means or.
|
||||
|
||||
o Compound assignment (+= -= *= /= %= ^= ..=)
|
||||
x += 1 expands to x = x + (1). ..= concatenates strings.
|
||||
|
||||
o ?? (nil coalescing)
|
||||
a ?? b returns b only when a is nil. It does not fall back on false.
|
||||
|
||||
o ??= / ||= / &&=
|
||||
x ??= b assigns only when x is nil.
|
||||
x ||= b is x = x or (b), and x &&= b is x = x and (b).
|
||||
|
||||
o ++
|
||||
x++ expands to x = x + 1. Use it as a statement on its own line.
|
||||
|
||||
o Range for (<start..stop>)
|
||||
for i in <0..10> do is the same as for i = 0, 10 do and includes the end.
|
||||
<0..<10> excludes the end. <0..10, 2> uses a step of 2.
|
||||
|
||||
|
||||
- Script Examples -
|
||||
|
||||
o Fade in (default script)
|
||||
|
||||
@@ -762,6 +762,39 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- Extensiones de sintaxis -
|
||||
|
||||
Se añaden algunas notaciones que Lua estándar no tiene. El script se
|
||||
transforma antes de ejecutarse, por lo que funcionan igual en todos los
|
||||
motores. El interior de las cadenas y los comentarios no se transforma.
|
||||
|
||||
o is / is not
|
||||
a is b significa a == b, y a is not b significa a ~= b.
|
||||
Ejemplo: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
o != / ! / && / ||
|
||||
!= significa ~=, ! significa not, && significa and y || significa or.
|
||||
|
||||
o Asignación compuesta (+= -= *= /= %= ^= ..=)
|
||||
x += 1 se expande a x = x + (1). ..= concatena cadenas.
|
||||
|
||||
o ?? (fusión de nil)
|
||||
a ?? b devuelve b solo cuando a es nil. No recurre a false.
|
||||
|
||||
o ??= / ||= / &&=
|
||||
x ??= b asigna solo cuando x es nil.
|
||||
x ||= b es x = x or (b), y x &&= b es x = x and (b).
|
||||
|
||||
o ++
|
||||
x++ se expande a x = x + 1. Úsalo como una sentencia en su propia línea.
|
||||
|
||||
o for de rango (<inicio..fin>)
|
||||
for i in <0..10> do es igual que for i = 0, 10 do e incluye el final.
|
||||
<0..<10> excluye el final. <0..10, 2> usa un incremento de 2.
|
||||
|
||||
|
||||
- Ejemplos de script -
|
||||
|
||||
o Fundido de entrada (script predeterminado)
|
||||
|
||||
@@ -758,6 +758,39 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- Ekstensi Sintaks -
|
||||
|
||||
Beberapa notasi yang tidak ada pada Lua standar ditambahkan. Skrip
|
||||
ditransformasikan sebelum dijalankan, sehingga bekerja sama pada semua
|
||||
mesin. Bagian dalam string dan komentar tidak ditransformasikan.
|
||||
|
||||
o is / is not
|
||||
a is b berarti a == b, dan a is not b berarti a ~= b.
|
||||
Contoh: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
o != / ! / && / ||
|
||||
!= berarti ~=, ! berarti not, && berarti and, dan || berarti or.
|
||||
|
||||
o Penugasan majemuk (+= -= *= /= %= ^= ..=)
|
||||
x += 1 diperluas menjadi x = x + (1). ..= menggabungkan string.
|
||||
|
||||
o ?? (koalesing nil)
|
||||
a ?? b mengembalikan b hanya saat a bernilai nil. Tidak beralih ke false.
|
||||
|
||||
o ??= / ||= / &&=
|
||||
x ??= b menetapkan hanya saat x bernilai nil.
|
||||
x ||= b adalah x = x or (b), dan x &&= b adalah x = x and (b).
|
||||
|
||||
o ++
|
||||
x++ diperluas menjadi x = x + 1. Gunakan sebagai pernyataan satu baris.
|
||||
|
||||
o for rentang (<awal..akhir>)
|
||||
for i in <0..10> do sama dengan for i = 0, 10 do dan menyertakan akhir.
|
||||
<0..<10> tidak menyertakan akhir. <0..10, 2> memakai langkah 2.
|
||||
|
||||
|
||||
- Contoh Skrip -
|
||||
|
||||
o Fade in (skrip default)
|
||||
|
||||
@@ -730,6 +730,38 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- 構文の拡張 -
|
||||
|
||||
標準の Lua に無い記法を追加しています。実行前にスクリプトを変換するため、
|
||||
すべての実行エンジンで同じように使えます。文字列とコメントの内側は変換しません。
|
||||
|
||||
○is / is not
|
||||
a is b は a == b、a is not b は a ~= b と同じ意味になります。
|
||||
例:if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○!= / ! / && / ||
|
||||
!= は ~=、! は not、&& は and、|| は or と同じ意味になります。
|
||||
|
||||
○複合代入(+= -= *= /= %= ^= ..=)
|
||||
x += 1 は x = x + (1) に展開します。..= は文字列の連結です。
|
||||
|
||||
○??(nil 合体)
|
||||
a ?? b は a が nil のときだけ b を返します。false は返しません。
|
||||
|
||||
○??= / ||= / &&=
|
||||
x ??= b は x が nil のときだけ代入します。
|
||||
x ||= b は x = x or (b)、x &&= b は x = x and (b) です。
|
||||
|
||||
○++
|
||||
x++ は x = x + 1 に展開します。行単位の文として使います。
|
||||
|
||||
○範囲 for(<開始..終了>)
|
||||
for i in <0..10> do は for i = 0, 10 do と同じで終端を含みます。
|
||||
<0..<10> は終端を含みません。<0..10, 2> は増分 2 です。
|
||||
|
||||
|
||||
- スクリプト例 -
|
||||
|
||||
○フェードイン(デフォルトスクリプト)
|
||||
|
||||
@@ -723,6 +723,38 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- 구문 확장 -
|
||||
|
||||
표준 Lua에 없는 표기를 추가했습니다. 스크립트는 실행 전에 변환되므로 모든
|
||||
엔진에서 동일하게 동작합니다. 문자열과 주석의 내부는 변환하지 않습니다.
|
||||
|
||||
○ is / is not
|
||||
a is b는 a == b, a is not b는 a ~= b와 같은 의미입니다.
|
||||
예: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○ != / ! / && / ||
|
||||
!=는 ~=, !는 not, &&는 and, ||는 or와 같은 의미입니다.
|
||||
|
||||
○ 복합 대입 (+= -= *= /= %= ^= ..=)
|
||||
x += 1은 x = x + (1)로 확장됩니다. ..=는 문자열 연결입니다.
|
||||
|
||||
○ ?? (nil 병합)
|
||||
a ?? b는 a가 nil일 때만 b를 반환합니다. false로는 대체하지 않습니다.
|
||||
|
||||
○ ??= / ||= / &&=
|
||||
x ??= b는 x가 nil일 때만 대입합니다.
|
||||
x ||= b는 x = x or (b), x &&= b는 x = x and (b)입니다.
|
||||
|
||||
○ ++
|
||||
x++는 x = x + 1로 확장됩니다. 한 줄짜리 문으로 사용합니다.
|
||||
|
||||
○ 범위 for (<시작..끝>)
|
||||
for i in <0..10> do는 for i = 0, 10 do와 같으며 끝을 포함합니다.
|
||||
<0..<10>는 끝을 포함하지 않습니다. <0..10, 2>는 증분이 2입니다.
|
||||
|
||||
|
||||
- 스크립트 예 -
|
||||
|
||||
○ 페이드인(기본 스크립트)
|
||||
|
||||
@@ -699,6 +699,38 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- 语法扩展 -
|
||||
|
||||
添加了标准 Lua 没有的写法。脚本在执行前会被转换,因此在所有引擎上表现一致。
|
||||
字符串和注释的内部不会被转换。
|
||||
|
||||
○ is / is not
|
||||
a is b 与 a == b 相同,a is not b 与 a ~= b 相同。
|
||||
示例:if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○ != / ! / && / ||
|
||||
!= 相当于 ~=,! 相当于 not,&& 相当于 and,|| 相当于 or。
|
||||
|
||||
○ 复合赋值(+= -= *= /= %= ^= ..=)
|
||||
x += 1 展开为 x = x + (1)。..= 用于字符串连接。
|
||||
|
||||
○ ??(nil 合并)
|
||||
a ?? b 仅当 a 为 nil 时返回 b。不会因 false 而回退。
|
||||
|
||||
○ ??= / ||= / &&=
|
||||
x ??= b 仅当 x 为 nil 时赋值。
|
||||
x ||= b 即 x = x or (b),x &&= b 即 x = x and (b)。
|
||||
|
||||
○ ++
|
||||
x++ 展开为 x = x + 1。作为独立一行的语句使用。
|
||||
|
||||
○ 范围 for(<起始..结束>)
|
||||
for i in <0..10> do 与 for i = 0, 10 do 相同,包含结束值。
|
||||
<0..<10> 不包含结束值。<0..10, 2> 的步长为 2。
|
||||
|
||||
|
||||
- 脚本示例 -
|
||||
|
||||
○ 淡入(默认脚本)
|
||||
|
||||
@@ -700,6 +700,38 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- 語法擴充 -
|
||||
|
||||
新增了標準 Lua 沒有的寫法。腳本在執行前會被轉換,因此在所有引擎上表現一致。
|
||||
字串與註解的內部不會被轉換。
|
||||
|
||||
○ is / is not
|
||||
a is b 與 a == b 相同,a is not b 與 a ~= b 相同。
|
||||
範例:if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○ != / ! / && / ||
|
||||
!= 相當於 ~=,! 相當於 not,&& 相當於 and,|| 相當於 or。
|
||||
|
||||
○ 複合指派(+= -= *= /= %= ^= ..=)
|
||||
x += 1 會展開為 x = x + (1)。..= 用於字串連接。
|
||||
|
||||
○ ??(nil 合併)
|
||||
a ?? b 僅在 a 為 nil 時回傳 b。不會因 false 而回退。
|
||||
|
||||
○ ??= / ||= / &&=
|
||||
x ??= b 僅在 x 為 nil 時指派。
|
||||
x ||= b 即 x = x or (b),x &&= b 即 x = x and (b)。
|
||||
|
||||
○ ++
|
||||
x++ 會展開為 x = x + 1。作為獨立一行的敘述使用。
|
||||
|
||||
○ 範圍 for(<起始..結束>)
|
||||
for i in <0..10> do 與 for i = 0, 10 do 相同,包含結束值。
|
||||
<0..<10> 不包含結束值。<0..10, 2> 的步長為 2。
|
||||
|
||||
|
||||
- 腳本範例 -
|
||||
|
||||
○ 淡入(預設腳本)
|
||||
|
||||
@@ -30,6 +30,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
- [7. スクリプトエディタの支援機能](#7-スクリプトエディタの支援機能)
|
||||
- [8. インポート・エクスポート・クリア](#8-インポートエクスポートクリア)
|
||||
- [9. AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)
|
||||
- [10. 構文拡張](#10-構文拡張)
|
||||
5. [実行モデル](#実行モデル)
|
||||
- [実行エンジンの自動振り分け](#実行エンジンの自動振り分け)
|
||||
- [実行スレッドとタイムアウト](#実行スレッドとタイムアウト)
|
||||
@@ -80,7 +81,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
- `table`、`string`、`math`、`bit32`
|
||||
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
|
||||
`io`、`os`、`debug`、`ffi`、`require` 等は利用できません。ファイルへのアクセス(`require` を含む)はスクリプトローダー側で明示的に禁止されており、呼び出すと例外になります。
|
||||
`io`、`os`、`debug`、`ffi`、`require` 等は利用できません。ファイルへのアクセス(`require` を含む)はスクリプトローダー側で明示的に禁止されており、呼び出すと例外になります。標準の Lua に無い記法の追加については[構文拡張](#10-構文拡張)を参照してください。
|
||||
|
||||
### 2. obj テーブルによる描画制御
|
||||
|
||||
@@ -228,6 +229,20 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
- `obj.mes` / `obj.rand1` などの未実装関数
|
||||
- `require` によるモジュール読み込み、`io` / `dofile` などの任意ファイルアクセス(`obj.load("image"/"movie")` のみ、先頭ヘッダー検証付きで対応)
|
||||
|
||||
### 10. 構文拡張
|
||||
|
||||
標準の Lua には無い簡易な記法をいくつか追加しています。キーボードで打ちやすく入力量を減らすための糖衣構文で、スクリプトは実行前に等価な標準 Lua へ変換されます。変換はすべての実行エンジン(LuaJIT・MoonSharp・CPU カーネル)に適用され、文字列とコメントの内側は変換しません。Lua に存在しない記号だけを入口にしているため、既存のスクリプトはそのまま動作します。
|
||||
|
||||
- **比較**: `a is b`(`a == b`)、`a is not b`(`a ~= b`)、`a != b`(`a ~= b`)
|
||||
- **論理**: `!a`(`not a`)、`a && b`(`a and b`)、`a || b`(`a or b`)
|
||||
- **複合代入**: `+=` `-=` `*=` `/=` `%=` `^=` `..=`(例: `x += 1` は `x = x + (1)`)
|
||||
- **nil 合体**: `a ?? b`(`a` が `nil` のときだけ `b` を返す。`false` は返しません)、`x ??= b`
|
||||
- **論理代入**: `x ||= b`(`x = x or (b)`)、`x &&= b`(`x = x and (b)`)
|
||||
- **インクリメント**: `x++`(`x = x + 1`)
|
||||
- **範囲 for**: `for i in <0..10>`(`for i = 0, 10`。終端を含む)、`<0..<10>`(終端を含まない)、`<0..10, 2>`(増分 2)
|
||||
|
||||
各記法の詳しい説明と例はドキュメント(`LuaScript/docs`)およびサイトの「構文拡張」を参照してください。
|
||||
|
||||
---
|
||||
|
||||
## 実行モデル
|
||||
|
||||
+2
-1
@@ -11,7 +11,8 @@
|
||||
group: "Lua 言語",
|
||||
items: [
|
||||
{ title: "Lua の基礎", href: "lua-basics.html" },
|
||||
{ title: "標準ライブラリ", href: "stdlib.html" }
|
||||
{ title: "標準ライブラリ", href: "stdlib.html" },
|
||||
{ title: "構文拡張", href: "syntax.html" }
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@ debug_print(string.format("x = %d", obj.x))</code></pre>
|
||||
<p>これらの中身は <a href="stdlib.html">標準ライブラリ</a> にまとめています。</p>
|
||||
|
||||
<div class="pager">
|
||||
<a href="stdlib.html">← 標準ライブラリ</a>
|
||||
<a href="syntax.html">← 構文拡張</a>
|
||||
<a href="obj.html">obj オブジェクト →</a>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -95,6 +95,11 @@ x, y = y, x</code></pre>
|
||||
local v = amp ~= 0 and amp or 50
|
||||
obj.x = obj.x + v</code></pre>
|
||||
|
||||
<p>
|
||||
このプラグインは、標準の Lua に無い記法(<code>is not</code>・<code>??</code>・複合代入・範囲 for など)も追加しています。
|
||||
詳しくは<a href="syntax.html">構文拡張</a>を参照してください。
|
||||
</p>
|
||||
|
||||
<h2>条件分岐</h2>
|
||||
|
||||
<pre><code>if obj.t < 0.5 then
|
||||
|
||||
@@ -77,6 +77,11 @@
|
||||
<priority>0.7</priority>
|
||||
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://luascript.routersys.com/syntax.html</loc>
|
||||
<priority>0.7</priority>
|
||||
<lastmod>2026-07-03T00:00:00+09:00</lastmod>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://luascript.routersys.com/reference.html</loc>
|
||||
<priority>0.7</priority>
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ extract, replace, btest, countlz, countrz</code></pre>
|
||||
|
||||
<div class="pager">
|
||||
<a href="lua-basics.html">← Lua の基礎</a>
|
||||
<a href="globals.html">グローバル変数 →</a>
|
||||
<a href="syntax.html">構文拡張 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>構文拡張 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>構文拡張</h1>
|
||||
|
||||
<p>
|
||||
このプラグインは、標準の Lua には無い簡易な記法をいくつか追加しています。キーボードで打ちやすく、
|
||||
入力量と読み替えの手間を減らすための糖衣構文です。スクリプトは実行前に等価な標準 Lua へ変換されるため、
|
||||
すべての実行エンジン(LuaJIT・MoonSharp・CPU カーネル)で同じように動きます。
|
||||
</p>
|
||||
|
||||
<div class="note">
|
||||
変換は字句単位で行い、<strong>文字列とコメントの内側は変換しません</strong>。
|
||||
また Lua に存在しない記号(<code>?</code> <code>!</code> <code>&</code> <code>|</code> や <code>in <</code> の並び)だけを入口にしているため、
|
||||
通常の Lua スクリプトはそのまま動作します。
|
||||
</div>
|
||||
|
||||
<h2>比較演算子</h2>
|
||||
|
||||
<p><code>is</code> と <code>is not</code> は、値どうしを比べる位置に書いたときだけ演算子として扱います。変数名としての <code>is</code> は変換しません。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>a is b</code></td><td><code>a == b</code></td></tr>
|
||||
<tr><td><code>a is not b</code></td><td><code>a ~= b</code></td></tr>
|
||||
<tr><td><code>a != b</code></td><td><code>a ~= b</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>if frame is not 0 then
|
||||
obj.x = 100
|
||||
end</code></pre>
|
||||
|
||||
<h2>論理演算子</h2>
|
||||
|
||||
<p>他言語でなじみのある記号を、Lua の <code>and</code> / <code>or</code> / <code>not</code> の別名として使えます。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>!a</code></td><td><code>not a</code></td></tr>
|
||||
<tr><td><code>a && b</code></td><td><code>a and b</code></td></tr>
|
||||
<tr><td><code>a || b</code></td><td><code>a or b</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>if !hidden && frame != 0 then
|
||||
obj.alpha = 255
|
||||
end</code></pre>
|
||||
|
||||
<h2>複合代入</h2>
|
||||
|
||||
<p>左辺の値を使って計算し、同じ場所へ書き戻す記法です。右辺は括弧で包んで展開するため、演算子の優先順位はそのまま保たれます。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>展開後</th></tr>
|
||||
<tr><td><code>x += 1</code></td><td><code>x = x + (1)</code></td></tr>
|
||||
<tr><td><code>x -= 1</code></td><td><code>x = x - (1)</code></td></tr>
|
||||
<tr><td><code>x *= 2</code></td><td><code>x = x * (2)</code></td></tr>
|
||||
<tr><td><code>x /= 2</code></td><td><code>x = x / (2)</code></td></tr>
|
||||
<tr><td><code>x %= 2</code></td><td><code>x = x % (2)</code></td></tr>
|
||||
<tr><td><code>x ^= 2</code></td><td><code>x = x ^ (2)</code></td></tr>
|
||||
<tr><td><code>s ..= "b"</code></td><td><code>s = s .. ("b")</code>(文字列の連結)</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>local total = 0
|
||||
total += obj.track0
|
||||
total *= 2</code></pre>
|
||||
|
||||
<h2>インクリメント</h2>
|
||||
|
||||
<p><code>++</code> は行単位の文として使い、1 を加えて書き戻します。</p>
|
||||
|
||||
<pre><code>count++</code></pre>
|
||||
|
||||
<p>上の <code>count++</code> は <code>count = count + 1</code> に展開します。</p>
|
||||
|
||||
<h2>nil 合体演算子</h2>
|
||||
|
||||
<p>
|
||||
<code>a ?? b</code> は、<code>a</code> が <code>nil</code> のときだけ <code>b</code> を返します。
|
||||
<code>a and b or c</code> と違い、<code>a</code> が <code>false</code> のときは <code>false</code> をそのまま返します。既定値を安全に書けます。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.x = obj.track0 ?? 100</code></pre>
|
||||
|
||||
<div class="note">
|
||||
<code>a ?? b</code> は左辺を 1 度だけ評価する無名関数に展開します。<code>b</code> は左辺が <code>nil</code> のときだけ評価されます。
|
||||
</div>
|
||||
|
||||
<h2>代入をともなう演算子</h2>
|
||||
|
||||
<p>変数が未設定・偽のときにまとめて代入する記法です。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>x ??= b</code></td><td><code>x</code> が <code>nil</code> のときだけ <code>b</code> を代入</td></tr>
|
||||
<tr><td><code>x ||= b</code></td><td><code>x = x or (b)</code></td></tr>
|
||||
<tr><td><code>x &&= b</code></td><td><code>x = x and (b)</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>speed ??= 90
|
||||
obj.rz = time * speed</code></pre>
|
||||
|
||||
<h2>範囲 for</h2>
|
||||
|
||||
<p>
|
||||
数値 for を、範囲を視覚的に表す <code><開始..終了></code> で書けます。<code>..</code> は終端を含み、
|
||||
<code>..<</code> は終端を含みません。<code>,</code> のあとに増分を指定できます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>for i in <0..10> do</code></td><td><code>for i = 0, 10 do</code>(10 を含む)</td></tr>
|
||||
<tr><td><code>for i in <0..<10> do</code></td><td><code>for i = 0, (10) - 1 do</code>(10 を含まない)</td></tr>
|
||||
<tr><td><code>for i in <0..10, 2> do</code></td><td><code>for i = 0, 10, 2 do</code>(増分 2)</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>local sum = 0
|
||||
for i in <1..10> do
|
||||
sum = sum + i
|
||||
end</code></pre>
|
||||
|
||||
<div class="note">
|
||||
<code>in <</code> の並びは通常の Lua には現れないため、<code>ipairs</code> や <code>pairs</code> を使う汎用 for には影響しません。
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<a href="stdlib.html">← 標準ライブラリ</a>
|
||||
<a href="globals.html">グローバル変数 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
新しいイシューから参照
ユーザーをブロックする