2 回答

TA貢獻1786條經驗 獲得超13個贊
如果您使用通用類和擴展方法,您可以采用更通用的方法
public class PositionAware<T> : IPositionAware<PositionAware<T>>
{
public PositionAware(T value)
{
Value = value;
}
public T Value { get; }
public Position Start { get; private set; }
public int Length { get; private set; }
public PositionAware<T> SetPos(Position startPos, int length)
{
Start = startPos;
Length = length;
return this;
}
}
public static Parser<PositionAware<T>> WithPosition<T>(this Parser<T> value)
{
return value.Select(x => new PositionAware<T>(x)).Positioned();
}
使用它:
from c in Parse.Char('a').WithPosition()
select (c.Start, c.Value)
from c in Parameter.DelimitedBy(ListDelimiter).WithPosition()
select (c.Start, c.Value)

TA貢獻1744條經驗 獲得超4個贊
我已經設法回答我自己的問題。這是 Positioned() 解析器擴展調用,允許解析器跟蹤原始文本中的位置。
Parser<Expression> FunctionCall = (from namePart in Parse.Letter.Many().Text()
from lparen in Parse.Char('(')
from expr in Parameter.DelimitedBy(ListDelimiter)
from rparen in Parse.Char(')')
select new MethodPosAware(namePart, expr)).Positioned()
.Select(x => CallMethod(x.Value, Enumerable.Repeat(sourceData, 1)
.Concat(x.Params)
.ToArray(),
x.Pos.Pos, x.Length));
我必須創建一個新的MethodPosAware類來保留位置信息,該信息源自 Sprache 的IPositionAware:
class MethodPosAware : IPositionAware<MethodPosAware>
{
public MethodPosAware(string methodName, IEnumerable<Expression> parameters)
{
Value = methodName;
Params = parameters;
}
public MethodPosAware SetPos(Position startPos, int length)
{
Pos = startPos;
Length = length;
return this;
}
public Position Pos { get; set; }
public int Length { get; set; }
public string Value { get; set; }
public IEnumerable<Expression> Params { get; set; }
}
我想我將進一步擴展它以不僅僅使用方法名稱,但這足以回答我現在的問題。我希望這可以幫助某人。
- 2 回答
- 0 關注
- 135 瀏覽
添加回答
舉報