public static IEnumerable<IVariable> GetScopeVariables(this IScope scope, int position) {
bool globalScope = scope is GlobalScope;
if (!globalScope) {
// See if this is a function scope with arguments
var funcDef = scope.Parent as IFunctionDefinition;
if (funcDef != null && funcDef.Arguments != null) {
foreach (var arg in funcDef.Arguments) {
var na = arg as IVariable;
if (na != null) {
yield return na;
} else {
var ea = arg as ExpressionArgument;
if (ea != null && ea.ArgumentValue != null && ea.ArgumentValue.Children.Count == 1) {
var v = ea.ArgumentValue.Children[0] as IVariable;
if (v != null) {
yield return v;
}
}
}
}
}
var forStatement = scope.Parent as For;
var enumExpression = forStatement?.EnumerableExpression;
var variable = enumExpression?.Variable;
if (variable != null) {
yield return variable;
}
}
foreach (var c in scope.Children) {
var es = c as IExpressionStatement;
if (es != null) {
if (!globalScope && es.Start > position) {
// In local scope stop at the predefined location
// so we do not enumerate variables or functions
// that hasn't been declared yet in the scope flow.
yield break;
}
Variable v;
var fd = es.GetVariableOrFunctionDefinition(out v);
if (fd != null && v != null) {
v.Value = new RFunction(fd);
}
if (v != null) {
yield return v;
}
}
}
}