Skip to content

Commit c71b377

Browse files
sfaqerclaude
andcommitted
Кэш Вычислить и Выполнить не зависит от числа глобальных контекстов
Скомпилированное выражение связывало области по номеру в списке кадра, где сначала идут глобальные контексты, а за ними область модуля. После ПодключитьВнешнююКомпоненту с глобальным контекстом номера сдвигались, и выражение из кэша читало компоненту вместо модуля или падало с ArgumentOutOfRangeException. Глобальные контексты теперь связываются напрямую, область модуля и вложенных вычислений - по номеру с конца. В тестовую компоненту добавлен глобальный контекст, а в tests - сценарии из #344 и #911 и подключение компоненты во время работы. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 36e2ca9 commit c71b377

16 files changed

Lines changed: 375 additions & 49 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*----------------------------------------------------------
2+
This Source Code Form is subject to the terms of the
3+
Mozilla Public License, v.2.0. If a copy of the MPL
4+
was not distributed with this file, You can obtain one
5+
at http://mozilla.org/MPL/2.0/.
6+
----------------------------------------------------------*/
7+
8+
using OneScript.Contexts;
9+
using ScriptEngine.Machine.Contexts;
10+
11+
namespace Component
12+
{
13+
// Компонента добавляет свой глобальный контекст, как в #344 и #911
14+
[GlobalContext(Category = "Тестовая компонента")]
15+
public class SimpleGlobalContext : GlobalContextBase<SimpleGlobalContext>
16+
{
17+
[ContextMethod("ГлобальныйМетодКомпоненты")]
18+
public string GlobalMethod() => "метод компоненты";
19+
20+
[ContextProperty("ГлобальноеСвойствоКомпоненты")]
21+
public string GlobalProperty => "свойство компоненты";
22+
23+
public static IAttachableContext CreateInstance() => new SimpleGlobalContext();
24+
}
25+
}

‎src/OneScript.Core/Compilation/Binding/ScopeBindingDescriptor.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ private ScopeBindingDescriptor(ScopeBindingKind kind, IAttachableContext target,
3434
public IAttachableContext Target { get; }
3535

3636
/// <summary>
37-
/// Индекс области видимости в списке ExecutionFrame.Scopes. Используется для ScopeBindingKind.FrameScope.
37+
/// Номер области видимости с конца списка ExecutionFrame.Scopes (0 - самая внутренняя). Используется для ScopeBindingKind.FrameScope.
3838
/// </summary>
3939
public int ScopeIndex { get; }
4040

‎src/ScriptEngine/Compiler/ModuleDumpWriter.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ private void WriteSymbolMap(TextWriter output, IList<ModuleSymbolBinding> map)
165165
{
166166
ScopeBindingKind.Static => item.Target?.GetType().Name ?? "null",
167167
ScopeBindingKind.ThisScope => "this",
168-
ScopeBindingKind.FrameScope => $"frame[{item.ScopeIndex}]",
168+
ScopeBindingKind.FrameScope => $"frame[^{item.ScopeIndex + 1}]",
169169
_ => "unknown"
170170
};
171171
output.Write(string.Format("{0,-3}:({1},{2},{3})\n", i, item.Kind, targetInfo, item.MemberNumber));

‎src/ScriptEngine/Machine/JoinedScopes.cs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,53 @@ public class JoinedScopes : IReadOnlyList<IAttachableContext>
1919
{
2020
private readonly IReadOnlyList<IAttachableContext> _outerScopes;
2121
private readonly IAttachableContext _innerScope;
22+
private readonly IReadOnlyList<IAttachableContext> _rootScopes;
23+
private readonly int _innerScopesCount;
2224

2325
public JoinedScopes(IReadOnlyList<IAttachableContext> outerScopes, IAttachableContext innerScope)
2426
{
2527
_outerScopes = outerScopes ?? throw new ArgumentNullException(nameof(outerScopes));
2628
_innerScope = innerScope ?? throw new ArgumentNullException(nameof(innerScope));
29+
30+
if (_outerScopes is JoinedScopes outer)
31+
{
32+
_rootScopes = outer._rootScopes;
33+
_innerScopesCount = outer._innerScopesCount + 1;
34+
}
35+
else
36+
{
37+
_rootScopes = _outerScopes;
38+
_innerScopesCount = 1;
39+
}
40+
}
41+
42+
/// <summary>
43+
/// Исходный список, к которому добавлены внутренние области (глобальные контексты окружения).
44+
/// Может расти, пока выполняется код.
45+
/// </summary>
46+
public IReadOnlyList<IAttachableContext> RootScopes => _rootScopes;
47+
48+
/// <summary>
49+
/// Число внутренних областей, добавленных к исходному списку.
50+
/// </summary>
51+
public int InnerScopesCount => _innerScopesCount;
52+
53+
/// <summary>
54+
/// Внутренняя область по номеру с конца: 0 - самая внутренняя.
55+
/// В отличие от индексатора не зависит от размера исходного списка.
56+
/// </summary>
57+
public IAttachableContext FromEnd(int index)
58+
{
59+
if (index < 0 || index >= _innerScopesCount)
60+
throw new IndexOutOfRangeException();
61+
62+
var scopes = this;
63+
for (; index > 0; index--)
64+
{
65+
scopes = (JoinedScopes)scopes._outerScopes;
66+
}
67+
68+
return scopes._innerScope;
2769
}
2870

2971
public IEnumerator<IAttachableContext> GetEnumerator()

‎src/ScriptEngine/Machine/MachineInstance.cs‎

Lines changed: 58 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2443,53 +2443,24 @@ private SymbolTable ExtractCompilerContext()
24432443
{
24442444
var ctx = new SymbolTable();
24452445
var scopes = _currentFrame.Scopes ?? Array.Empty<IAttachableContext>();
2446-
var scopeCount = scopes.Count;
2447-
var thisScope = _currentFrame.ThisScope;
24482446

2449-
// Добавляем все контексты из scopes (глобальные + локальные из предыдущих кадров)
2450-
for (int index = 0; index < scopeCount; index++)
2447+
// В начале scopes - глобальные контексты окружения, дальше области модуля и вложенных вычислений.
2448+
// Выражение кэшируется, а глобальных контекстов может стать больше (ПодключитьВнешнююКомпоненту),
2449+
// поэтому глобальные связываются напрямую, а остальные области - по номеру с конца списка
2450+
var joinedScopes = scopes as JoinedScopes;
2451+
var globals = joinedScopes?.RootScopes ?? scopes;
2452+
var globalsCount = globals.Count;
2453+
for (int index = 0; index < globalsCount; index++)
24512454
{
2452-
var scope = scopes[index];
2453-
2454-
var symbolScope = new SymbolScope();
2455-
2456-
// Добавляем методы
2457-
for (int i = 0; i < scope.MethodsCount; i++)
2458-
{
2459-
var methodInfo = scope.GetMethod(i);
2460-
symbolScope.DefineMethod(methodInfo.ToSymbol());
2461-
}
2462-
2463-
// Добавляем переменные
2464-
for (int i = 0; i < scope.VariablesCount; i++)
2465-
{
2466-
var variable = scope.GetVariable(i);
2467-
2468-
string alias = null;
2469-
if (scope is IRuntimeContextInstance runtimeContext)
2470-
{
2471-
try
2472-
{
2473-
var propInfo = runtimeContext.GetPropertyInfo(i);
2474-
alias = propInfo.Alias;
2475-
}
2476-
catch
2477-
{
2478-
// Алиас остается пустым
2479-
}
2480-
}
2481-
2482-
if (alias != null)
2483-
{
2484-
symbolScope.DefineVariable(new AliasedVariableSymbol(variable.Name, alias));
2485-
}
2486-
else
2487-
{
2488-
symbolScope.DefineVariable(new LocalVariableSymbol(variable.Name));
2489-
}
2490-
}
2455+
var scope = globals[index];
2456+
ctx.PushScope(CreateSymbolScope(scope), ScopeBindingDescriptor.Static(scope));
2457+
}
24912458

2492-
ctx.PushScope(symbolScope, ScopeBindingDescriptor.FrameScope(index));
2459+
var innerScopesCount = joinedScopes?.InnerScopesCount ?? 0;
2460+
for (int index = innerScopesCount - 1; index >= 0; index--)
2461+
{
2462+
// В кадре выражения самой внутренней будет его собственная локальная область
2463+
ctx.PushScope(CreateSymbolScope(joinedScopes.FromEnd(index)), ScopeBindingDescriptor.FrameScope(index + 1));
24932464
}
24942465

24952466
// Локальные переменные текущего фрейма
@@ -2503,6 +2474,49 @@ private SymbolTable ExtractCompilerContext()
25032474
return ctx;
25042475
}
25052476

2477+
private static SymbolScope CreateSymbolScope(IAttachableContext scope)
2478+
{
2479+
var symbolScope = new SymbolScope();
2480+
2481+
// Добавляем методы
2482+
for (int i = 0; i < scope.MethodsCount; i++)
2483+
{
2484+
var methodInfo = scope.GetMethod(i);
2485+
symbolScope.DefineMethod(methodInfo.ToSymbol());
2486+
}
2487+
2488+
// Добавляем переменные
2489+
for (int i = 0; i < scope.VariablesCount; i++)
2490+
{
2491+
var variable = scope.GetVariable(i);
2492+
2493+
string alias = null;
2494+
if (scope is IRuntimeContextInstance runtimeContext)
2495+
{
2496+
try
2497+
{
2498+
var propInfo = runtimeContext.GetPropertyInfo(i);
2499+
alias = propInfo.Alias;
2500+
}
2501+
catch
2502+
{
2503+
// Алиас остается пустым
2504+
}
2505+
}
2506+
2507+
if (alias != null)
2508+
{
2509+
symbolScope.DefineVariable(new AliasedVariableSymbol(variable.Name, alias));
2510+
}
2511+
else
2512+
{
2513+
symbolScope.DefineVariable(new LocalVariableSymbol(variable.Name));
2514+
}
2515+
}
2516+
2517+
return symbolScope;
2518+
}
2519+
25062520
[MethodImpl(MethodImplOptions.AggressiveInlining)]
25072521
private IAttachableContext ResolveBindingTarget(ModuleSymbolBinding binding)
25082522
{

‎src/ScriptEngine/Machine/ModuleSymbolBinding.cs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,13 @@ internal IAttachableContext ResolveTarget(ExecutionFrame frame)
3333

3434
private IAttachableContext ResolveFrameScope(ExecutionFrame frame)
3535
{
36-
if (frame?.Scopes == null)
36+
if (frame?.Scopes is not JoinedScopes scopes)
3737
throw new InvalidOperationException("Frame scopes are not available");
38-
if (ScopeIndex < 0 || ScopeIndex >= frame.Scopes.Count)
38+
if (ScopeIndex < 0 || ScopeIndex >= scopes.InnerScopesCount)
3939
throw new InvalidOperationException($"Invalid scope index {ScopeIndex}");
4040

41-
return frame.Scopes[ScopeIndex];
41+
// Номер с конца: глобальных контекстов в начале списка может стать больше
42+
return scopes.FromEnd(ScopeIndex);
4243
}
4344

4445
public bool Equals(ModuleSymbolBinding other)
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*----------------------------------------------------------
2+
This Source Code Form is subject to the terms of the
3+
Mozilla Public License, v.2.0. If a copy of the MPL
4+
was not distributed with this file, You can obtain one
5+
at http://mozilla.org/MPL/2.0/.
6+
----------------------------------------------------------*/
7+
8+
using FluentAssertions;
9+
using OneScript.Contexts;
10+
using ScriptEngine.Hosting;
11+
using ScriptEngine.Machine.Contexts;
12+
using Xunit;
13+
14+
namespace OneScript.Core.Tests
15+
{
16+
[GlobalContext(ManualRegistration = true)]
17+
public class EvalScopesTestGlobals : GlobalContextBase<EvalScopesTestGlobals>
18+
{
19+
[ContextProperty("СвойствоТестовогоКонтекста")]
20+
public string Property => "свойство контекста";
21+
22+
[ContextMethod("МетодТестовогоКонтекста")]
23+
public string Method() => "метод контекста";
24+
}
25+
26+
[GlobalContext(ManualRegistration = true)]
27+
public class EvalScopesTestHost : GlobalContextBase<EvalScopesTestHost>
28+
{
29+
private readonly IRuntimeEnvironment _environment;
30+
31+
public EvalScopesTestHost(IRuntimeEnvironment environment)
32+
{
33+
_environment = environment;
34+
}
35+
36+
// Как ПодключитьВнешнююКомпоненту со своим глобальным контекстом
37+
[ContextMethod("ПодключитьТестовыйКонтекст")]
38+
public void Attach() => _environment.InjectObject(new EvalScopesTestGlobals());
39+
}
40+
41+
public class EvalScopesTests
42+
{
43+
private const string Script =
44+
"Перем МояПеременная;\n" +
45+
"Перем Итог Экспорт;\n" +
46+
"\n" +
47+
"Функция МояФункция()\n" +
48+
" Возврат \"функция модуля\";\n" +
49+
"КонецФункции\n" +
50+
"\n" +
51+
"МояПеременная = \"переменная модуля\";\n" +
52+
"Итог = \"\";\n" +
53+
"Значение = Неопределено;\n" +
54+
"Для Номер = 1 По 2 Цикл\n" +
55+
" Итог = Итог + Вычислить(\"МояПеременная\") + \"; \" + Вычислить(\"МояФункция()\") + \"; \";\n" +
56+
" Выполнить(\"Значение = МояПеременная\");\n" +
57+
" Итог = Итог + Значение + \"; \";\n" +
58+
" Если Номер = 1 Тогда\n" +
59+
" ПодключитьТестовыйКонтекст();\n" +
60+
" КонецЕсли;\n" +
61+
"КонецЦикла;\n";
62+
63+
[Fact]
64+
public void CachedExpressionsSeeModuleAfterGlobalContextIsAttached()
65+
{
66+
var engine = DefaultEngineBuilder.Create().SetDefaultOptions().Build();
67+
engine.Initialize();
68+
engine.Environment.InjectObject(new EvalScopesTestHost(engine.Environment));
69+
70+
// Вычислить и Выполнить кэшируют выражения у машины процесса, поэтому все в одном запуске
71+
var instance = engine.AttachedScriptsFactory.LoadFromString(engine.GetCompilerService(), Script, engine.NewProcess());
72+
73+
instance.GetPropValue(instance.GetPropertyNumber("Итог")).ToString().Should().Be(
74+
"переменная модуля; функция модуля; переменная модуля; " +
75+
"переменная модуля; функция модуля; переменная модуля; ");
76+
}
77+
}
78+
}

0 commit comments

Comments
 (0)