Example #1
0
 protected InterpreterScope(AnalysisValue av, InterpreterScope cloned, bool isCloned) {
     Debug.Assert(isCloned);
     _av = av;
     Children.AddRange(cloned.Children);
     _nodeScopes = cloned._nodeScopes;
     _nodeValues = cloned._nodeValues;
     _variables = cloned._variables;
     _linkedVariables = cloned._linkedVariables;
 }
Example #2
0
        public OverviewWalker(ProjectEntry entry, AnalysisUnit topAnalysis, PythonAst tree) {
            _entry = entry;
            _curUnit = topAnalysis;

            _tree = tree;
            Debug.Assert(_tree != null);

            _scope = topAnalysis.Scope;
        }
Example #3
0
        public InterpreterScope(AnalysisValue av, Node ast, InterpreterScope outerScope) {
            _av = av;
            _node = ast;
            OuterScope = outerScope;

            _nodeScopes = new AnalysisDictionary<Node, InterpreterScope>();
            _nodeValues = new AnalysisDictionary<Node, IAnalysisSet>();
            _variables = new AnalysisDictionary<string, VariableDef>();
            _linkedVariables = new AnalysisDictionary<string, HashSet<VariableDef>>();
        }
Example #4
0
 // TODO: What about names being redefined?
 // remember classes/functions as they start new scopes
 public override bool Walk(ClassDefinition node) {
     var cls = AddClass(node, _curUnit);
     if (cls != null) {
         _analysisStack.Push(_curUnit);
         _curUnit = cls.AnalysisUnit;
         Debug.Assert(_scope.EnumerateTowardsGlobal.Contains(cls.AnalysisUnit.Scope.OuterScope));
         _scope = cls.AnalysisUnit.Scope;
         return true;
     }
     return false;
 }
Example #5
0
 public FunctionScope(
     FunctionInfo function,
     Node node,
     InterpreterScope declScope,
     IPythonProjectEntry declModule
 )
     : base(function, node, declScope) {
     ReturnValue = new VariableDef();
     if (Function.FunctionDefinition.IsCoroutine) {
         Coroutine = new CoroutineInfo(function.ProjectState, declModule);
         ReturnValue.AddTypes(function.ProjectEntry, Coroutine.SelfSet, false);
     } else if (Function.FunctionDefinition.IsGenerator) {
         Generator = new GeneratorInfo(function.ProjectState, declModule);
         ReturnValue.AddTypes(function.ProjectEntry, Generator.SelfSet, false);
     }
 }
Example #6
0
        internal FunctionAnalysisUnit(
            FunctionInfo function,
            AnalysisUnit declUnit,
            InterpreterScope declScope,
            IPythonProjectEntry declEntry
        )
            : base(function.FunctionDefinition, null) {
            _declUnit = declUnit;
            Function = function;
            _decoratorCalls = new Dictionary<Node, Expression>();

            var scope = new FunctionScope(Function, Function.FunctionDefinition, declScope, declEntry);
            scope.EnsureParameters(this);
            _scope = scope;

            AnalysisLog.NewUnit(this);
        }
        public override bool Walk(IfStatement node)
        {
            foreach (var test in node.TestsInternal)
            {
                _eval.Evaluate(test.Test);

                var prevScope = Scope;

                TryPushIsInstanceScope(test, test.Test);

                test.Body.Walk(this);

                Scope = prevScope;
            }
            if (node.ElseStatement != null)
            {
                node.ElseStatement.Walk(this);
            }
            return(false);
        }
Example #8
0
 public FunctionScope(
     FunctionInfo function,
     Node node,
     InterpreterScope declScope,
     IPythonProjectEntry declModule
     )
     : base(function, node, declScope)
 {
     ReturnValue = new VariableDef();
     if (Function.FunctionDefinition.IsCoroutine)
     {
         Coroutine = new CoroutineInfo(function.ProjectState, declModule);
         ReturnValue.AddTypes(function.ProjectEntry, Coroutine.SelfSet, false, declModule);
     }
     else if (Function.FunctionDefinition.IsGenerator)
     {
         Generator = new GeneratorInfo(function.ProjectState, declModule);
         ReturnValue.AddTypes(function.ProjectEntry, Generator.SelfSet, false, declModule);
     }
 }
Example #9
0
        protected InterpreterScope(AnalysisValue av, InterpreterScope cloned, bool isCloned)
        {
            Debug.Assert(isCloned);
            _av = av;
            Children.AddRange(cloned.Children);
            _nodeScopes = cloned._nodeScopes;
            _nodeValues = cloned._nodeValues;
            _variables  = cloned._variables;
            if (cloned._linkedVariables == null)
            {
                // linkedVariables could be created later, and we need to share them if it.
                cloned._linkedVariables = new Dictionary <string, HashSet <VariableDef> >();
            }
            _linkedVariables = cloned._linkedVariables;
#if DEBUG
            NodeScopes = new ReadOnlyDictionary <Node, InterpreterScope>(_nodeScopes);
            NodeValues = new ReadOnlyDictionary <Node, IAnalysisSet>(_nodeValues);
            Variables  = new ReadOnlyDictionary <string, VariableDef>(_variables);
#endif
        }
Example #10
0
        internal FunctionAnalysisUnit(
            FunctionInfo function,
            AnalysisUnit declUnit,
            InterpreterScope declScope,
            IPythonProjectEntry declEntry,
            bool concreteParameters
            )
            : base(function.FunctionDefinition, null)
        {
            _declUnit           = declUnit;
            Function            = function;
            _concreteParameters = concreteParameters;
            _decoratorCalls     = new Dictionary <Node, Expression>();

            var scope = new FunctionScope(Function, Function.FunctionDefinition, declScope, declEntry);

            _scope = scope;

            if (GetType() == typeof(FunctionAnalysisUnit))
            {
                AnalysisLog.NewUnit(this);
            }
        }
Example #11
0
        internal static FunctionInfo AddFunction(FunctionDefinition node, AnalysisUnit outerUnit, InterpreterScope prevScope)
        {
            InterpreterScope scope;

            if (!prevScope.TryGetNodeScope(node, out scope))
            {
                if (node.Body == null || node.Name == null)
                {
                    return(null);
                }

                var func = new FunctionInfo(node, outerUnit, prevScope);
                var unit = func.AnalysisUnit;
                scope = unit.Scope;

                prevScope.Children.Add(scope);
                prevScope.AddNodeScope(node, scope);

                if (!node.IsLambda && node.Name != "<genexpr>")
                {
                    // lambdas don't have their names published

                    var funcVar = prevScope.AddLocatedVariable(node.Name, node.NameExpression, unit);
                    // Decorated functions don't have their type set yet
                    if (node.Decorators == null)
                    {
                        funcVar.AddTypes(unit, func.SelfSet);
                    }
                }

                unit.Enqueue();
            }
            return(scope.AnalysisValue as FunctionInfo);
        }
 public ClassScope(ClassInfo classInfo, ClassDefinition ast, InterpreterScope outerScope)
     : base(classInfo, ast, outerScope)
 {
     classInfo.Scope = this;
 }
Example #13
0
 public virtual InterpreterScope AddNodeScope(Node node, InterpreterScope scope)
 {
     return(_nodeScopes[node] = scope);
 }
Example #14
0
        private static bool IsInFunctionParameter(InterpreterScope scope, PythonAst tree, SourceLocation location)
        {
            var function = scope.Node as FunctionDefinition;
            if (function == null) {
                // Not a function
                return false;
            }

            if (location.Index < function.StartIndex || location.Index >= function.Body.StartIndex) {
                // Not within the def line
                return false;
            }

            return function.Parameters != null &&
                function.Parameters.Any(p => {
                    var paramName = p.GetVerbatimImage(tree) ?? p.Name;
                    return location.Index >= p.StartIndex && location.Index <= p.StartIndex + paramName.Length;
                });
        }
Example #15
0
        private void PushIsInstanceScope(Node node, KeyValuePair<NameExpression, Expression>[] isInstanceNames, SuiteStatement effectiveSuite) {
            InterpreterScope scope;
            if (!_curUnit.Scope.TryGetNodeScope(node, out scope)) {
                // find our parent scope, it may not be just the last entry in _scopes
                // because that can be a StatementScope and we would start a new range.
                var declScope = _scope.EnumerateTowardsGlobal.FirstOrDefault(s => !(s is StatementScope));

                scope = new IsInstanceScope(node.StartIndex, effectiveSuite, declScope);

                declScope.Children.Add(scope);
                declScope.AddNodeScope(node, scope);
                _scope = scope;
            }
        }
Example #16
0
 private static string GetPrivatePrefixClassName(InterpreterScope scope)
 {
     var klass = scope.EnumerateTowardsGlobal.OfType<ClassScope>().FirstOrDefault();
     return klass == null ? null : klass.Name;
 }
Example #17
0
        private IEnumerable<IAnalysisVariable> GetVariablesInScope(NameExpression name, InterpreterScope scope)
        {
            var result = new List<IAnalysisVariable>();

            result.AddRange(scope.GetMergedVariables(name.Name).SelectMany(ToVariables));

            // if a variable is imported from another module then also yield the defs/refs for the
            // value in the defining module.
            result.AddRange(scope.GetLinkedVariables(name.Name).SelectMany(ToVariables));

            var classScope = scope as ClassScope;
            if (classScope != null) {
                // if the member is defined in a base class as well include the base class member and references
                var cls = classScope.Class;
                if (cls.Push()) {
                    try {
                        foreach (var baseNs in cls.Bases.SelectMany()) {
                            if (baseNs.Push()) {
                                try {
                                    ClassInfo baseClassNs = baseNs as ClassInfo;
                                    if (baseClassNs != null) {
                                        result.AddRange(
                                            baseClassNs.Scope.GetMergedVariables(name.Name).SelectMany(ToVariables)
                                        );
                                    }
                                } finally {
                                    baseNs.Pop();
                                }
                            }
                        }
                    } finally {
                        cls.Pop();
                    }
                }
            }

            return result;
        }
Example #18
0
        internal IEnumerable<MemberResult> GetMemberResults(
            IEnumerable<AnalysisValue> vars,
            InterpreterScope scope,
            GetMemberOptions options
            )
        {
            IList<AnalysisValue> namespaces = new List<AnalysisValue>();
            foreach (var ns in vars) {
                if (ns != null) {
                    namespaces.Add(ns);
                }
            }

            if (namespaces.Count == 1) {
                // optimize for the common case of only a single namespace
                var newMembers = namespaces[0].GetAllMembers(GlobalScope.InterpreterContext, options);
                if (newMembers == null || newMembers.Count == 0) {
                    return new MemberResult[0];
                }

                return SingleMemberResult(GetPrivatePrefix(scope), options, newMembers);
            }

            Dictionary<string, IEnumerable<AnalysisValue>> memberDict = null;
            Dictionary<string, IEnumerable<AnalysisValue>> ownerDict = null;
            HashSet<string> memberSet = null;
            int namespacesCount = namespaces.Count;
            foreach (AnalysisValue ns in namespaces) {
                if (ProjectState._noneInst == ns) {
                    namespacesCount -= 1;
                    continue;
                }

                var newMembers = ns.GetAllMembers(GlobalScope.InterpreterContext, options);
                // IntersectMembers(members, memberSet, memberDict);
                if (newMembers == null || newMembers.Count == 0) {
                    continue;
                }

                if (memberSet == null) {
                    // first namespace, add everything
                    memberSet = new HashSet<string>(newMembers.Keys);
                    memberDict = new Dictionary<string, IEnumerable<AnalysisValue>>();
                    ownerDict = new Dictionary<string, IEnumerable<AnalysisValue>>();
                    foreach (var kvp in newMembers) {
                        var tmp = new List<AnalysisValue>(kvp.Value);
                        memberDict[kvp.Key] = tmp;
                        ownerDict[kvp.Key] = new List<AnalysisValue> { ns };
                    }
                } else {
                    // 2nd or nth namespace, union or intersect
                    HashSet<string> toRemove;
                    IEnumerable<string> adding;

                    if (options.Intersect()) {
                        adding = new HashSet<string>(newMembers.Keys);
                        // Find the things only in memberSet that we need to remove from memberDict
                        // toRemove = (memberSet ^ adding) & memberSet

                        toRemove = new HashSet<string>(memberSet);
                        toRemove.SymmetricExceptWith(adding);
                        toRemove.IntersectWith(memberSet);

                        // intersect memberSet with what we're adding
                        memberSet.IntersectWith(adding);

                        // we're only adding things they both had
                        adding = memberSet;
                    } else {
                        // we're adding all of newMembers keys
                        adding = newMembers.Keys;
                        toRemove = null;
                    }

                    // update memberDict
                    foreach (var name in adding) {
                        IEnumerable<AnalysisValue> values;
                        List<AnalysisValue> valueList;
                        if (!memberDict.TryGetValue(name, out values)) {
                            memberDict[name] = values = new List<AnalysisValue>();
                        }
                        if ((valueList = values as List<AnalysisValue>) == null) {
                            memberDict[name] = valueList = new List<AnalysisValue>(values);
                        }
                        valueList.AddRange(newMembers[name]);

                        if (!ownerDict.TryGetValue(name, out values)) {
                            ownerDict[name] = values = new List<AnalysisValue>();
                        }
                        if ((valueList = values as List<AnalysisValue>) == null) {
                            ownerDict[name] = valueList = new List<AnalysisValue>(values);
                        }
                        valueList.Add(ns);
                    }

                    if (toRemove != null) {
                        foreach (var name in toRemove) {
                            memberDict.Remove(name);
                            ownerDict.Remove(name);
                        }
                    }
                }
            }

            if (memberDict == null) {
                return new MemberResult[0];
            }
            if (options.Intersect()) {
                // No need for this information if we're only showing the
                // intersection. Setting it to null saves lookups later.
                ownerDict = null;
            }
            return MemberDictToResultList(GetPrivatePrefix(scope), options, memberDict, ownerDict, namespacesCount);
        }
Example #19
0
 public ExpressionEvaluator(AnalysisUnit unit, InterpreterScope scope, bool mergeScopes = false)
 {
     _unit        = unit;
     Scope        = scope;
     _mergeScopes = mergeScopes;
 }
Example #20
0
        private IEnumerable<MemberResult> GetKeywordMembers(GetMemberOptions options, InterpreterScope scope)
        {
            IEnumerable<string> keywords = null;

            if (options.ExpressionKeywords()) {
                // keywords available in any context
                keywords = PythonKeywords.Expression(ProjectState.LanguageVersion);
            } else {
                keywords = Enumerable.Empty<string>();
            }

            if (options.StatementKeywords()) {
                keywords = keywords.Union(PythonKeywords.Statement(ProjectState.LanguageVersion));
            }

            if (!(scope is FunctionScope)) {
                keywords = keywords.Except(PythonKeywords.InvalidOutsideFunction(ProjectState.LanguageVersion));
            }

            return keywords.Select(kw => new MemberResult(kw, PythonMemberType.Keyword));
        }
Example #21
0
 public IsInstanceScope(int startIndex, SuiteStatement effectiveSuite, InterpreterScope outerScope)
     : base(null, null, outerScope)
 {
     _startIndex     = _endIndex = startIndex;
     _effectiveSuite = effectiveSuite;
 }
 public virtual InterpreterScope AddNodeScope(Node node, InterpreterScope scope) => _nodeScopes[node] = scope;
Example #23
0
 public static bool IsOriginalClosureScope(InterpreterScope scope) => (scope as FunctionScope)?.Function.IsClosure == true && scope.OriginalScope == null;
Example #24
0
 IAnalysisSet IModule.GetModuleMember(Node node, AnalysisUnit unit, string name, bool addRef, InterpreterScope linkedScope, string linkedName)
 {
     var res = AnalysisSet.Empty;
     foreach (var member in _members.OfType<IModule>()) {
         res = res.Union(member.GetModuleMember(node, unit, name, addRef, linkedScope, linkedName));
     }
     return res;
 }
Example #25
0
        private static int GetParentScopeIndent(InterpreterScope scope, PythonAst tree)
        {
            if (scope is ClassScope) {
                // Return column of "class" statement
                return tree.IndexToLocation(scope.GetStart(tree)).Column;
            }

            var function = scope as FunctionScope;
            if (function != null && !((FunctionDefinition)function.Node).IsLambda) {
                // Return column of "def" statement
                return tree.IndexToLocation(scope.GetStart(tree)).Column;
            }

            var isinstance = scope as IsInstanceScope;
            if (isinstance != null && isinstance._effectiveSuite != null) {
                int col = tree.IndexToLocation(isinstance._startIndex).Column;
                if (isinstance._effectiveSuite.StartIndex < isinstance._startIndex) {
                    // "assert isinstance", so scope is before the test
                    return col - 1;
                } else {
                    // "if isinstance", so scope is at the test
                    return col;
                }
            }

            return -1;
        }
Example #26
0
        public override bool Walk(SuiteStatement node) {
            var prevSuite = _curSuite;
            _curSuite = node;

            // recursively walk the statements in the suite
            if (node.Statements != null) {
                foreach (var innerNode in node.Statements) {
                    innerNode.Walk(this);
                }
            }

            _curSuite = prevSuite;

            // then check if we encountered an assert which added an isinstance scope.
            IsInstanceScope isInstanceScope = _scope as IsInstanceScope;
            if (isInstanceScope != null && isInstanceScope._effectiveSuite == node) {
                // pop the isinstance scope
                _scope = _scope.OuterScope;
                // transform back into a line number and start the new statement scope on the line
                // after the suite statement.
                var lineNo = _tree.IndexToLocation(node.EndIndex).Line;

                int offset;
                if (_tree._lineLocations.Length == 0) {
                    // single line input
                    offset = 0;
                } else {
                    offset = lineNo < _tree._lineLocations.Length ? _tree._lineLocations[lineNo].EndIndex : _tree._lineLocations[_tree._lineLocations.Length - 1].EndIndex;
                }
                var closingScope = new StatementScope(offset, _scope);
                _scope.Children.Add(closingScope);
                _scope = closingScope;
            }
            return false;
        }
Example #27
0
 /// <summary>
 /// Makes sure we create a scope for a comprehension (generator, set, dict, or list comprehension in 3.x) where
 /// the variables which are assigned will be stored.  
 /// </summary>
 private void EnsureComprehensionScope(Comprehension node, Func<Comprehension, ComprehensionScope> makeScope) {
     InterpreterScope scope, declScope = _scope;
     if (!declScope.TryGetNodeScope(node, out scope)) {
         scope = makeScope(node);
         
         declScope.AddNodeScope(node, scope);
         declScope.Children.Add(scope);
     }
     _scope = scope;
 }
Example #28
0
 public override InterpreterScope AddNodeScope(Node node, InterpreterScope scope) => OuterScope.AddNodeScope(node, scope);
Example #29
0
 public override void PostWalk(SuiteStatement node) {
     while (_scope is StatementScope) {
         _scope = _scope.OuterScope;
     }
     base.PostWalk(node);
 }
Example #30
0
        /// <summary>
        /// Returns a sequence of possible types associated with the name in the expression evaluators scope.
        /// </summary>
        public IAnalysisSet LookupAnalysisSetByName(Node node, string name, bool addRef = true, bool addDependency = false)
        {
            InterpreterScope createIn = null;
            VariableDef      refs     = null;

            if (_mergeScopes)
            {
                var scope = Scope.EnumerateTowardsGlobal
                            .FirstOrDefault(s => (s == Scope || s.VisibleToChildren) && s.ContainsVariable(name));
                if (scope != null)
                {
                    return(scope.GetMergedVariableTypes(name));
                }
            }
            else
            {
                foreach (var scope in Scope.EnumerateTowardsGlobal)
                {
                    if (scope == Scope || scope.VisibleToChildren)
                    {
                        refs = scope.GetVariable(node, _unit, name, addRef);
                        if (refs != null)
                        {
                            if (addRef)
                            {
                                scope.AddReferenceToLinkedVariables(node, _unit, name);
                            }
                            break;
                        }
                        else if (addRef && createIn == null && scope.ContainsImportStar)
                        {
                            // create the variable so that we can appropriately
                            // add any dependent reads to it.
                            createIn = scope;
                        }
                    }
                }
            }

            if (_unit.ForEval)
            {
                return(refs?.Types ?? ProjectState.BuiltinModule.GetMember(node, _unit, name));
            }

            bool warn = false;
            var  res  = refs?.Types;

            if (res == null)
            {
                // No variable found, so look in builtins
                res = ProjectState.BuiltinModule.GetMember(node, _unit, name);
                if (!res.Any())
                {
                    // No builtin found, so ...
                    if (createIn != null)
                    {
                        // ... create a variable in the best known scope
                        refs = createIn.CreateVariable(node, _unit, name, addRef);
                        res  = refs.Types;
                    }
                    else
                    {
                        // ... warn the user
                        warn = true;
                    }
                }
            }
            else if (!res.Any() && !refs.IsAssigned)
            {
                // Variable has no values, so if we also don't know about any
                // definitions then warn.
                warn = true;
            }

            if (addDependency && refs != null)
            {
                refs.AddDependency(_unit);
            }

            if (warn)
            {
                ProjectState.AddDiagnostic(node, _unit, ErrorMessages.UsedBeforeAssignment(name), DiagnosticSeverity.Warning, ErrorMessages.UsedBeforeAssignmentCode);
            }
            else
            {
                ProjectState.ClearDiagnostic(node, _unit, ErrorMessages.UsedBeforeAssignmentCode);
            }

            return(res);
        }
Example #31
0
 public override void PostWalk(ClassDefinition node) {
     if (node.Body != null && node.Name != null) {
         Debug.Assert(_scope.Node == node);
         Debug.Assert(_scope.OuterScope.Node != node);
         _scope = _scope.OuterScope;
         _curUnit = _analysisStack.Pop();
         Debug.Assert(_scope.EnumerateTowardsGlobal.Contains(_curUnit.Scope));
     }
 }
Example #32
0
 /// <summary>
 /// Finds the best available analysis unit for lookup. This will be the one that is provided
 /// by the nearest enclosing scope that is capable of providing one.
 /// </summary>
 private AnalysisUnit GetNearestEnclosingAnalysisUnit(InterpreterScope scopes)
 {
     var units = from scope in scopes.EnumerateTowardsGlobal
                 let ns = scope.AnalysisValue
                 where ns != null
                 let unit = ns.AnalysisUnit
                 where unit != null
                 select unit;
     return units.FirstOrDefault() ?? _unit;
 }
Example #33
0
 public override bool Walk(FunctionDefinition node) {
     var function = AddFunction(node, _curUnit);
     if (function != null) {
         _analysisStack.Push(_curUnit);
         _curUnit = function.AnalysisUnit;
         Debug.Assert(_scope.EnumerateTowardsGlobal.Contains(function.AnalysisUnit.Scope.OuterScope));
         _scope = function.AnalysisUnit.Scope;
         return true;
     }
     return false;
 }
Example #34
0
 internal ModuleAnalysis(AnalysisUnit unit, InterpreterScope scope)
 {
     _unit = unit;
     _scope = scope;
 }
Example #35
0
 internal ModuleAnalysis(AnalysisUnit unit, InterpreterScope scope, IAnalysisCookie cookie) {
     _unit = unit;
     _scope = scope;
     _cookie = cookie;
 }
Example #36
0
        private static InterpreterScope FindScope(InterpreterScope parent, PythonAst tree, SourceLocation location)
        {
            var children = parent.Children.Where(c => !(c is StatementScope)).ToList();

            InterpreterScope candidate = null;

            for (int i = 0; i < children.Count; ++i) {
                if (IsInFunctionParameter(children[i], tree, location)) {
                    // In parameter name scope, so consider the function scope.
                    candidate = children[i];
                    continue;
                }

                int start = children[i].GetBodyStart(tree);

                if (start > location.Index) {
                    // We've gone past index completely so our last candidate is
                    // the best one.
                    break;
                }

                int end = children[i].GetStop(tree);
                if (i + 1 < children.Count) {
                    int nextStart = children[i + 1].GetStart(tree);
                    if (nextStart > end) {
                        end = nextStart;
                    }
                }

                if (location.Index <= end || (candidate == null && i + 1 == children.Count)) {
                    candidate = children[i];
                }
            }

            if (candidate == null) {
                // No children, so we must belong in our parent
                return parent;
            }

            int scopeIndent = GetParentScopeIndent(candidate, tree);
            if (location.Column <= scopeIndent) {
                // Candidate is at deeper indentation than location and the
                // candidate is scoped, so return the parent instead.
                return parent;
            }

            // Recurse to check children of candidate scope
            var child = FindScope(candidate, tree, location);

            var funcChild = child as FunctionScope;
            if (funcChild != null &&
                funcChild.Function.FunctionDefinition.IsLambda &&
                child.GetStop(tree) < location.Index) {
                // Do not want to extend a lambda function's scope to the end of
                // the parent scope.
                return parent;
            }

            return child;
        }
Example #37
0
 public ComprehensionScope(AnalysisValue comprehensionResult, Comprehension comprehension, InterpreterScope outerScope)
     : base(comprehensionResult, comprehension, outerScope) {
 }
Example #38
0
 private static string GetPrivatePrefix(InterpreterScope scope)
 {
     string classScopePrefix = GetPrivatePrefixClassName(scope);
     if (classScopePrefix != null) {
         return "_" + classScopePrefix + "__";
     }
     return null;
 }
Example #39
0
 public override InterpreterScope AddNodeScope(Node node, InterpreterScope scope) {
     return OuterScope.AddNodeScope(node, scope);
 }
Example #40
0
        private static bool IsFirstLineOfFunction(InterpreterScope innerScope, InterpreterScope outerScope, SourceLocation location)
        {
            if (innerScope.OuterScope == outerScope && innerScope is FunctionScope) {
                var funcScope = (FunctionScope)innerScope;
                var def = funcScope.Function.FunctionDefinition;

                // TODO: Use indexes rather than lines to check location
                if (location.Line == def.GetStart(def.GlobalParent).Line) {
                    return true;
                }
            }
            return false;
        }
Example #41
0
 public ClassScope(ClassInfo classInfo, ClassDefinition ast, InterpreterScope outerScope)
     : base(classInfo, ast, outerScope) {
     classInfo.Scope = this;
 }
        /// <summary>
        /// Returns a sequence of possible types associated with the name in the expression evaluators scope.
        /// </summary>
        public IAnalysisSet LookupAnalysisSetByName(Node node, string name, bool addRef = true, bool addDependency = false)
        {
            InterpreterScope createIn = null;
            VariableDef      refs     = null;

            if (_mergeScopes)
            {
                var scope = Scope.EnumerateTowardsGlobal
                            .FirstOrDefault(s => (s == Scope || s.VisibleToChildren) && s.ContainsVariable(name));
                if (scope != null)
                {
                    return(scope.GetMergedVariableTypes(name));
                }
            }
            else
            {
                foreach (var scope in Scope.EnumerateTowardsGlobal)
                {
                    if (scope == Scope || scope.VisibleToChildren)
                    {
                        refs = scope.GetVariable(node, _unit, name, addRef);
                        if (refs != null)
                        {
                            if (addRef)
                            {
                                scope.AddReferenceToLinkedVariables(node, _unit, name);
                            }
                            break;
                        }
                        else if (addRef && createIn == null && scope.ContainsImportStar)
                        {
                            // create the variable so that we can appropriately
                            // add any dependent reads to it.
                            createIn = scope;
                        }
                    }
                }
            }

            if (_unit.ForEval)
            {
                return(refs?.Types ?? ProjectState.BuiltinModule.GetMember(node, _unit, name));
            }

            bool warn = false;
            var  res  = refs?.Types;

            if (res == null)
            {
                // No variable found, so look in builtins
                res = ProjectState.BuiltinModule.GetMember(node, _unit, name);
                if (!res.Any())
                {
                    // No builtin found, so ...
                    if (createIn != null)
                    {
                        // ... create a variable in the best known scope
                        refs = createIn.CreateVariable(node, _unit, name, addRef);
                        res  = refs.Types;
                    }
                    else
                    {
                        switch (name)
                        {
                        // "atom" in Python grammar.
                        case "True":
                        case "False":
                        case "None":
                        case "...":
                            Debug.Fail($"Known good name '{name}' not found in scope");
                            break;

                        default:
                            // ... warn the user
                            warn = true;
                            break;
                        }
                    }
                }
            }

            if (addDependency && refs != null)
            {
                refs.AddDependency(_unit);
            }

            if (warn)
            {
                ProjectState.AddDiagnostic(node, _unit, ErrorMessages.UseBeforeDef(name), DiagnosticSeverity.Warning, ErrorMessages.UseBeforeDefCode);
            }
            else
            {
                ProjectState.ClearDiagnostic(node, _unit, ErrorMessages.UseBeforeDefCode);
            }

            return(res);
        }
Example #43
0
        public IAnalysisSet GetModuleMember(Node node, AnalysisUnit unit, string name, bool addRef = true, InterpreterScope linkedScope = null, string linkedName = null) {
            var importedValue = Scope.CreateVariable(node, unit, name, addRef);
            ModuleDefinition.AddDependency(unit);

            if (linkedScope != null) {
                linkedScope.AddLinkedVariable(linkedName ?? name, importedValue);
            }
            return importedValue.GetTypesNoCopy(unit, DeclaringModule);
        }
Example #44
0
        internal static FunctionInfo AddFunction(FunctionDefinition node, AnalysisUnit outerUnit, InterpreterScope prevScope)
        {
            InterpreterScope scope;

            if (!prevScope.TryGetNodeScope(node, out scope))
            {
                if (node.Body == null || node.Name == null)
                {
                    return(null);
                }

                var func = new FunctionInfo(node, outerUnit, prevScope);
                var unit = func.AnalysisUnit;
                scope = unit.InterpreterScope;
                (unit as FunctionAnalysisUnit)?.EnsureParameters();

                prevScope.Children.Add(scope);
                prevScope.AddNodeScope(node, scope);

                if (!node.IsLambda && node.Name != "<genexpr>")
                {
                    // Create the variable (except for lambdas) but do not add any
                    // values yet. (This happens in FunctionAnalysisUnit.)
                    prevScope.AddLocatedVariable(node.Name, node.NameExpression, unit);
                }

                unit.Enqueue();
            }
            return(scope.AnalysisValue as FunctionInfo);
        }
Example #45
0
 public ComprehensionScope(AnalysisValue comprehensionResult, Comprehension comprehension, InterpreterScope outerScope)
     : base(comprehensionResult, comprehension, outerScope)
 {
 }
Example #46
0
 public InterpreterScope(AnalysisValue av, InterpreterScope outerScope)
     : this(av, null, outerScope)
 {
 }
Example #47
0
 public override InterpreterScope AddNodeScope(Node node, InterpreterScope scope)
 {
     return(OuterScope.AddNodeScope(node, scope));
 }
Example #48
0
 public IsInstanceScope(int startIndex, SuiteStatement effectiveSuite, InterpreterScope outerScope)
     : base(null, null, outerScope) {
     _startIndex = _endIndex = startIndex;
     _effectiveSuite = effectiveSuite;
 }
 public StatementScope(int index, InterpreterScope outerScope)
     : base(null, outerScope)
 {
     _startIndex = _endIndex = index;
 }