Skip to content

Commit

Permalink
Переделки в PABCSystem - теперь используются yield
Browse files Browse the repository at this point in the history
Исправлена мелкая ошибка - в генерируемом коде var res исправлена на var $res
  • Loading branch information
miks1965 committed Aug 1, 2016
1 parent 381df67 commit ed30e42
Show file tree
Hide file tree
Showing 7 changed files with 141 additions and 79 deletions.
2 changes: 1 addition & 1 deletion Configuration/GlobalAssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ internal static class RevisionClass
public const string Major = "3";
public const string Minor = "1";
public const string Build = "0";
public const string Revision = "1290";
public const string Revision = "1291";

public const string MainVersion = Major + "." + Minor;
public const string FullVersion = Major + "." + Minor + "." + Build + "." + Revision;
Expand Down
4 changes: 2 additions & 2 deletions Configuration/Version.defs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
%MINOR%=1
%REVISION%=1290
%COREVERSION%=0
%REVISION%=1291
%MINOR%=1
%MAJOR%=3
2 changes: 1 addition & 1 deletion ReleaseGenerators/PascalABCNET_version.nsh
Original file line number Diff line number Diff line change
@@ -1 +1 @@
!define VERSION '3.1.0.1290'
!define VERSION '3.1.0.1291'
22 changes: 11 additions & 11 deletions SyntaxVisitors/YieldVisitors/ProcessYieldsCapturedVars.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,19 +184,19 @@ type_declarations GenClassesForYield(procedure_definition pd,


// frninja 20/04/16 - поддержка шаблонных классов
var stl = new statement_list(new var_statement("res", new new_expr(this.CreateClassReference(className), new expression_list())));
var stl = new statement_list(new var_statement("$res", new new_expr(this.CreateClassReference(className), new expression_list())));


//stl.AddMany(lid.Select(id => new assign(new dot_node("res", id), id)));
stl.AddMany(lid.Select(id => new assign(new dot_node("res", new ident(formalParamsMap[id.name])), id)));
//stl.AddMany(lid.Select(id => new assign(new dot_node("$res", id), id)));
stl.AddMany(lid.Select(id => new assign(new dot_node("$res", new ident(formalParamsMap[id.name])), id)));

// frninja 08/12/15 - захват self
if (iteratorClassName != null && !pd.proc_header.class_keyword)
{
stl.Add(new assign(new dot_node("res", YieldConsts.Self), new ident("self")));
stl.Add(new assign(new dot_node("$res", YieldConsts.Self), new ident("self")));
}

stl.Add(new assign("Result", "res"));
stl.Add(new assign("Result", "$res"));

// New body
pd.proc_body = new block(stl);
Expand Down Expand Up @@ -263,18 +263,18 @@ type_declarations GenClassesForYield(procedure_definition pd,
//SyntaxTreeBuilder.BuildClassDefinition(interfaces1, cm1));


var stl1 = new statement_list(new var_statement("res", new new_expr(this.CreateClassReference(className), new expression_list())));
var stl1 = new statement_list(new var_statement("$res", new new_expr(this.CreateClassReference(className), new expression_list())));


stl1.AddMany(lid.Select(id => new assign(new dot_node("res", new ident(formalParamsMap[id.name])), new ident(formalParamsMap[id.name]))));
stl1.AddMany(lid.Select(id => new assign(new dot_node("$res", new ident(formalParamsMap[id.name])), new ident(formalParamsMap[id.name]))));

// Переприсваивание self
if (iteratorClassName != null && !pd.proc_header.class_keyword)
{
stl1.Add(new assign(new dot_node("res", YieldConsts.Self), new ident(YieldConsts.Self)));
stl1.Add(new assign(new dot_node("$res", YieldConsts.Self), new ident(YieldConsts.Self)));
}

stl1.Add(new assign("Result", "res"));
stl1.Add(new assign("Result", "$res"));


GetEnumeratorBody.Add(new if_node(new bin_expr(new ident(YieldConsts.State), new int32_const(0), Operators.Equal),
Expand Down Expand Up @@ -928,8 +928,8 @@ public override void visit(procedure_definition pd)

// Обработка метода для корректного захвата локальных переменных и их типов
// - это уже не надо - иногда можно включать чтобы посмотреть, что собой представляет функция после Loweringа
IEnumerable<var_def_statement> localsClonesCollection;
CreateLocalVariablesTypeProxies(pd, out localsClonesCollection);
//IEnumerable<var_def_statement> localsClonesCollection;
//CreateLocalVariablesTypeProxies(pd, out localsClonesCollection);

// frninja 16/11/15: перенес ниже чтобы работал захват для lowered for

Expand Down
95 changes: 63 additions & 32 deletions TestSuite/CompilationSamples/PABCSystem.pas
Original file line number Diff line number Diff line change
Expand Up @@ -3788,9 +3788,9 @@ function Seq<T>(params a: array of T): sequence of T;
Result := res;
end;

type
{type
// Вспомогательный класс для генерации бесконечной последовательности целых, начиная с заданного значения
{ IntNumbersClass = class(SeqBaseInteger,IEnumerable<integer>,IEnumerator<integer>)
IntNumbersClass = class(SeqBaseInteger,IEnumerable<integer>,IEnumerator<integer>)
private
first,cur: integer;
public
Expand All @@ -3815,7 +3815,7 @@ { IntNumbersClass = class(SeqBaseInteger,IEnumerable<integer>,IEnumerator<integ
end;}

// Вспомогательный класс для генерации рекуррентных последовательностей
IterateClass<T> = class(SeqBase<T>,IEnumerable<T>,IEnumerator<T>)
{ IterateClass<T> = class(SeqBase<T>,IEnumerable<T>,IEnumerator<T>)
private
first: T;
cur: T;
Expand Down Expand Up @@ -3890,18 +3890,33 @@ Iterate2Class<T> = class(SeqBase<T>,IEnumerable<T>,IEnumerator<T>)
b := second;
isfirst := true;
end;
end;
end;}

/// Возвращает бесконечную рекуррентную последовательность элементов, задаваемую начальным элементом first и функцией next
function Iterate<T>(first: T; next: T->T): sequence of T;
begin
Result := IterateClass&<T>.Create(first,next).Select(x->T(x));
yield first;
while True do
begin
first := next(first);
yield first;
end;
//Result := IterateClass&<T>.Create(first,next).Select(x->T(x));
end;

/// Возвращает бесконечную рекуррентную последовательность элементов, задаваемую начальными элементами first, second и функцией next
function Iterate<T>(first,second: T; next: (T,T)->T): sequence of T;
begin
Result := Iterate2Class&<T>.Create(first,second,next).Select(x->T(x));
yield first;
yield second;
while True do
begin
var nxt := next(first,second);
yield nxt;
first := second;
second := nxt;
end;
// Result := Iterate2Class&<T>.Create(first,second,next).Select(x->T(x));
end;

function SeqGen<T>(count: integer; first: T; next: T -> T): sequence of T;
Expand Down Expand Up @@ -7911,60 +7926,49 @@ function Iterate<T>(Self,second: T; next: (T,T) -> T): sequence of T; extensionm
/// Возвращает бесконечную последовательность целых от текущего значения с шагом 1
function Step(Self: integer): sequence of integer; extensionmethod;
begin
//Result := IntNumbersClass.Create(Self);
var s := Self;
while True do
begin
yield s;
s += 1;
yield Self;
Self += 1;
end;
end;

/// Возвращает бесконечную последовательность целых от текущего значения с шагом step
function Step(Self: integer; step: integer): sequence of integer; extensionmethod;
begin
{var slf := Self;
Result := IntNumbersClass.Create().Select(x->x*step+slf);}
var s := Self;
while True do
begin
yield s;
s += step;
yield Self;
Self += step;
end;
end;

/// Возвращает бесконечную последовательность вещественных от текущего значения с шагом step
function Step(Self: real; step: real): sequence of real; extensionmethod;
begin
{var slf := Self;
Result := IntNumbersClass.Create().Select(x->x*step+slf);}
var s := Self;
while True do
begin
yield s;
s += step;
yield Self;
Self += step;
end;
end;

// Возвращает бесконечную последовательность элементов, совпадающих с данным
///--
function &Repeat<T>(Self: T): sequence of T; extensionmethod;
begin
var s := Self;
while True do
yield s;
yield Self;
end;

/// Повторяет последовательность бесконечное число раз
function Cycle<T>(Self: sequence of T): sequence of T; extensionmethod;
begin
var s := Self;
while True do
begin
foreach var x in s do
foreach var x in Self do
yield x;
end;
// Result := SeqFill(MaxInt,Self).SelectMany(x->x);
end;

//------------------------------------------------------------------------------
Expand All @@ -7986,7 +7990,10 @@ function Print<T>(Self: sequence of T; delim: string): sequence of T; extensionm
/// Выводит последовательность на экран, используя пробел в качестве разделителя
function Print<T>(Self: sequence of T): sequence of T; extensionmethod;
begin
Result := Self.Print(PrintDelimDefault);
if typeof(T)=typeof(char) then
Result := Self.Print('')
else
Result := Self.Print(PrintDelimDefault);
end;

/// Выводит последовательность на экран, используя delim в качестве разделителя, и переходит на новую строку
Expand All @@ -8000,7 +8007,10 @@ function Println<T>(Self: sequence of T; delim: string): sequence of T; extensio
/// Выводит последовательность на экран, используя пробел качестве разделителя, и переходит на новую строку
function Println<T>(Self: sequence of T): sequence of T; extensionmethod;
begin
Result := Self.Println(PrintDelimDefault);
if typeof(T)=typeof(char) then
Result := Self.Println('')
else
Result := Self.Println(PrintDelimDefault);
end;

/// Выводит последовательность строк в файл
Expand All @@ -8025,7 +8035,9 @@ function JoinIntoString<T>(Self: sequence of T; delim: string): string; extensio
/// Преобразует элементы последовательности в строковое представление, после чего объединяет их в строку, используя пробел в качестве разделителя
function JoinIntoString<T>(Self: sequence of T): string; extensionmethod;
begin
Result := Self.JoinIntoString(' ');
if typeof(T) = typeof(char) then
Result := Self.JoinIntoString('')
else Result := Self.JoinIntoString(' ');
end;

/// Применяет действие к каждому элементу последовательности
Expand Down Expand Up @@ -8144,15 +8156,25 @@ function Cartesian<T,T1>(Self: sequence of T; b: sequence of T1): sequence of (T
begin
if b=nil then
raise new System.ArgumentNullException('b');
Result := Self.Select(x->b.Select(y->(x,y))).SelectMany(x->x);

foreach var x in Self do
foreach var y in b do
yield (x,y)

//Result := Self.Select(x->b.Select(y->(x,y))).SelectMany(x->x);
end;

/// Декартово произведение последовательностей
function Cartesian<T,T1,T2>(Self: sequence of T; b: sequence of T1; func: (T,T1)->T2): sequence of T2; extensionmethod;
begin
if b=nil then
raise new System.ArgumentNullException('b');
Result := Self.Select(x->b.Select(y->(x,y))).SelectMany(x->x).Select(x->func(x[0],x[1]));

foreach var x in Self do
foreach var y in b do
yield func(x,y)

// Result := Self.Select(x->b.Select(y->(x,y))).SelectMany(x->x).Select(x->func(x[0],x[1]));
end;

/// Разбивает последовательности на две в позиции ind
Expand Down Expand Up @@ -8290,11 +8312,20 @@ function Pairwise<T>(Self: sequence of T): sequence of (T,T); extensionmethod;
end
end;


/// Превращает последовательность в последовательность пар соседних элементов, применяет func к каждой паре полученных элементов и получает новую последовательность
function Pairwise<T,Res>(Self: sequence of T; func:(T,T)->Res): sequence of Res; extensionmethod;
begin
Result := Self.ZipTuple(Self.Skip(1)).Select(x->func(x[0],x[1]));
var previous: T;
var it := Self.GetEnumerator();
if (it.MoveNext()) then
previous := it.Current;

while (it.MoveNext()) do
begin
yield func(previous,it.Current);
previous := it.Current;
end
// Result := Self.ZipTuple(Self.Skip(1)).Select(x->func(x[0],x[1]));
end;

/// Разбивает последовательность на серии длины size
Expand Down
Binary file modified bin/Lib/PABCRtl.dll
Binary file not shown.
Loading

0 comments on commit ed30e42

Please sign in to comment.