Exemplo n.º 1
0
		public override void EndNode(AstNode node)
		{
			base.EndNode(node);
			if (node is EntityDeclaration && node.Annotation<MemberReference>() != null) {
				MemberLocations[XmlDocKeyProvider.GetKey(node.Annotation<MemberReference>())] = node.StartLocation;
			}
			
			// code mappings
			var ranges = node.Annotation<List<ILRange>>();
			if (symbolsStack.Count > 0 && ranges != null && ranges.Count > 0) {
				symbolsStack.Peek().SequencePoints.Add(
					new SequencePoint() {
						ILRanges = ILRange.OrderAndJoin(ranges).ToArray(),
						StartLocation = node.StartLocation,
						EndLocation = node.EndLocation
					});
			}
			
			if (node.Annotation<MethodDebugSymbols>() != null) {
				var symbols = symbolsStack.Pop();
				symbols.SequencePoints = symbols.SequencePoints.OrderBy(s => s.ILOffset).ToList();
				symbols.StartLocation = node.StartLocation;
				symbols.EndLocation = node.EndLocation;
				DebugSymbols[XmlDocKeyProvider.GetKey(symbols.CecilMethod)] = symbols;
			}
		}
Exemplo n.º 2
0
		public virtual void VisitNullNode(AstNode nullNode)
		{
			// Should we call VisitChildren here?
			// We usually want to ignore null nodes.
			// Older NR versions (before VisitNullNode was introduced) didn't call VisitChildren() with null nodes;
			// so changing this might break VisitChildren() overrides that expect the node to be part of the AST.
		}
        public virtual void AddLocals(IEnumerable<ParameterDeclaration> declarations, AstNode statement)
        {
            declarations.ToList().ForEach(item =>
            {
                var name = this.Emitter.GetEntityName(item);
                var vName = this.AddLocal(item.Name, item.Type);

                if (item.ParameterModifier == ParameterModifier.Out || item.ParameterModifier == ParameterModifier.Ref)
                {
                    this.Emitter.LocalsMap[item.Name] = name + ".v";
                }
                else
                {
                    this.Emitter.LocalsMap[item.Name] = name;
                }
            });

            var visitor = new ReferenceArgumentVisitor();
            statement.AcceptVisitor(visitor);

            foreach (var expr in visitor.DirectionExpression)
            {
                var rr = this.Emitter.Resolver.ResolveNode(expr, this.Emitter);

                if (rr is LocalResolveResult && expr is IdentifierExpression)
                {
                    var ie = (IdentifierExpression)expr;
                    this.Emitter.LocalsMap[ie.Identifier] = ie.Identifier + ".v";
                }
                else
                {
                    throw new EmitterException(expr, "Only local variables can be passed by reference");
                }
            }
        }
Exemplo n.º 4
0
        private static Phrase FindPhrase(AstNode node)
        {
            var text = node.GetText();

            if (node.Role == Roles.Comment)
                return Phrase.Comment;

            if (node.Role == Roles.Type)
            {
                var type = (node as PrimitiveType);
                if (type != null)
                    return (type.Keyword != null) ? Phrase.Keyword : Phrase.Type;

                // some keywords can be type like "var" which our parser does not recognise
                return text.IsKeyword() ? Phrase.Keyword : Phrase.Type;
            }

            if (node is PrimitiveExpression)
            {
                if (text.IsString())
                    return Phrase.String;
            }

            if (node is CSharpTokenNode)
            {
                if (text.IsKeyword())
                    return Phrase.Keyword;
            }

            return Phrase.Unknwon;
        }
Exemplo n.º 5
0
		TextLocation GetEndOfPrev(AstNode node)
		{
			do {
				node = node.GetPrevNode();
			} while (node.NodeType == NodeType.Whitespace);
			return node.EndLocation;
		}
Exemplo n.º 6
0
 public void Run(AstNode compilationUnit)
 {
     if (!context.Settings.QueryExpressions)
         return;
     DecompileQueries(compilationUnit);
     // After all queries were decompiled, detect degenerate queries (queries not property terminated with 'select' or 'group')
     // and fix them, either by adding a degenerate select, or by combining them with another query.
     foreach (QueryExpression query in compilationUnit.Descendants.OfType<QueryExpression>()) {
         QueryFromClause fromClause = (QueryFromClause)query.Clauses.First();
         if (IsDegenerateQuery(query)) {
             // introduce select for degenerate query
             query.Clauses.Add(new QuerySelectClause { Expression = new IdentifierExpression(fromClause.Identifier) });
         }
         // See if the data source of this query is a degenerate query,
         // and combine the queries if possible.
         QueryExpression innerQuery = fromClause.Expression as QueryExpression;
         while (IsDegenerateQuery(innerQuery)) {
             QueryFromClause innerFromClause = (QueryFromClause)innerQuery.Clauses.First();
             if (fromClause.Identifier != innerFromClause.Identifier)
                 break;
             // Replace the fromClause with all clauses from the inner query
             fromClause.Remove();
             QueryClause insertionPos = null;
             foreach (var clause in innerQuery.Clauses) {
                 query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach());
             }
             fromClause = innerFromClause;
             innerQuery = fromClause.Expression as QueryExpression;
         }
     }
 }
Exemplo n.º 7
0
 public override bool IsEquivalentTo(AstNode otherNode)
 {
     var otherRegExp = otherNode as RegExpLiteral;
     return otherRegExp != null
         && string.CompareOrdinal(Pattern, otherRegExp.Pattern) == 0
         && string.CompareOrdinal(PatternSwitches, otherRegExp.PatternSwitches) == 0;
 }
 public CodeObject Compile(AstNode syntaxNode, CodeProgram prog)
 {
   var syntax = (ScriptFunctionCall)syntaxNode;
   var parameters = syntax.Parameters.Select(expr => AstDomCompiler.Compile<CodeExpression>(expr, prog)).ToList();
   var code = new CodeObjectFunctionCall(parameters);
   return code;
 }
Exemplo n.º 9
0
        /// <summary>
        /// Sets a value on a member of a basic type.
        /// </summary>
        /// <param name="ctx">The context of the runtime</param>
        /// <param name="varExp">The expression representing the index of the instance to set</param>
        /// <param name="valExp">The expression representing the value to set</param>
        /// <param name="node">The assignment ast node</param>
        public static void SetIndexValue(Context ctx, IAstVisitor visitor, AstNode node, Expr varExp, Expr valExp)
        {
            // 1. Get the value that is being assigned.
            var val = valExp.Evaluate(visitor) as LObject;

            // 2. Check the limit if string.
            ctx.Limits.CheckStringLength(node, val);

            // 3. Evaluate expression to get index info.
            var indexExp = varExp.Evaluate(visitor) as IndexAccess;
            if (indexExp == null)
                throw ComLib.Lang.Helpers.ExceptionHelper.BuildRunTimeException(node, "Value to assign is null");

            // 4. Get the target of the index access and the name / number to set.
            var target = indexExp.Instance;
            var memberNameOrIndex = indexExp.MemberName;

            // Get methods associated with type.
            var methods = ctx.Methods.Get(target.Type);

            // Case 1: users[0] = 'kishore'
            if (target.Type == LTypes.Array)
            {
                var index = Convert.ToInt32(((LNumber)memberNameOrIndex).Value);
                methods.SetByNumericIndex(target, index, val);
            }
            // Case 2: users['total'] = 20
            else if (target.Type == LTypes.Map)
            {
                var name = ((LString)memberNameOrIndex).Value;
                methods.SetByStringMember(target, name, val);
            }
        }
Exemplo n.º 10
0
        public ObjectLiteral(Context context, JSParser parser, ObjectLiteralField[] keys, AstNode[] values)
            : base(context, parser)
        {
            // the length of keys and values should be identical.
            // if either is null, or if the lengths don't match, we ignore both!
            if (keys == null || values == null || keys.Length != values.Length)
            {
                // allocate EMPTY arrays so we don't have to keep checking for nulls
                m_keys = new ObjectLiteralField[0];
                m_values = new AstNode[0];
            }
            else
            {
                // copy the arrays
                m_keys = keys;
                m_values = values;

                // make sure the parents are set properly
                foreach (AstNode astNode in keys)
                {
                    astNode.Parent = this;
                }
                foreach (AstNode astNode in values)
                {
                    astNode.Parent = this;
                }
                // because we don't ensure that the arrays are the same length, we'll need to
                // check for the minimum length every time we iterate over them
            }
        }
		public override void StartNode(AstNode node)
		{
			currentList.Add(node);
			nodes.Push(currentList);
			currentList = new List<AstNode>();
			base.StartNode(node);
		}
Exemplo n.º 12
0
		public void Run(AstNode node)
		{
			Run(node, null);
			// Declare all the variables at the end, after all the logic has run.
			// This is done so that definite assignment analysis can work on a single representation and doesn't have to be updated
			// when we change the AST.
			foreach (var v in variablesToDeclare) {
				if (v.ReplacedAssignment == null) {
					BlockStatement block = (BlockStatement)v.InsertionPoint.Parent;
					block.Statements.InsertBefore(
						v.InsertionPoint,
						new VariableDeclarationStatement((AstType)v.Type.Clone(), v.Name));
				}
			}
			// First do all the insertions, then do all the replacements. This is necessary because a replacement might remove our reference point from the AST.
			foreach (var v in variablesToDeclare) {
				if (v.ReplacedAssignment != null) {
					// We clone the right expression so that it doesn't get removed from the old ExpressionStatement,
					// which might be still in use by the definite assignment graph.
					VariableDeclarationStatement varDecl = new VariableDeclarationStatement {
						Type = (AstType)v.Type.Clone(),
						Variables = { new VariableInitializer(v.Name, v.ReplacedAssignment.Right.Detach()).CopyAnnotationsFrom(v.ReplacedAssignment) }
					};
					ExpressionStatement es = v.ReplacedAssignment.Parent as ExpressionStatement;
					if (es != null) {
						// Note: if this crashes with 'Cannot replace the root node', check whether two variables were assigned the same name
						es.ReplaceWith(varDecl.CopyAnnotationsFrom(es));
					} else {
						v.ReplacedAssignment.ReplaceWith(varDecl);
					}
				}
			}
			variablesToDeclare = null;
		}
Exemplo n.º 13
0
		void Run(AstNode node, DefiniteAssignmentAnalysis daa)
		{
			BlockStatement block = node as BlockStatement;
			if (block != null) {
				var variables = block.Statements.TakeWhile(stmt => stmt is VariableDeclarationStatement)
					.Cast<VariableDeclarationStatement>().ToList();
				if (variables.Count > 0) {
					// remove old variable declarations:
					foreach (VariableDeclarationStatement varDecl in variables) {
						Debug.Assert(varDecl.Variables.Single().Initializer.IsNull);
						varDecl.Remove();
					}
					if (daa == null) {
						// If possible, reuse the DefiniteAssignmentAnalysis that was created for the parent block
						daa = new DefiniteAssignmentAnalysis(block, cancellationToken);
					}
					foreach (VariableDeclarationStatement varDecl in variables) {
						string variableName = varDecl.Variables.Single().Name;
						bool allowPassIntoLoops = varDecl.Variables.Single().Annotation<DelegateConstruction.CapturedVariableAnnotation>() == null;
						DeclareVariableInBlock(daa, block, varDecl.Type, variableName, allowPassIntoLoops);
					}
				}
			}
			for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
				Run(child, daa);
			}
		}
Exemplo n.º 14
0
		string GetNodeTitle(AstNode node)
		{
			StringBuilder b = new StringBuilder();
			b.Append(node.Role.ToString());
			b.Append(": ");
			b.Append(node.GetType().Name);
			bool hasProperties = false;
			foreach (PropertyInfo p in node.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
				if (p.Name == "NodeType" || p.Name == "IsNull")
					continue;
				if (p.PropertyType == typeof(string) || p.PropertyType.IsEnum || p.PropertyType == typeof(bool)) {
					if (!hasProperties) {
						hasProperties = true;
						b.Append(" (");
					} else {
						b.Append(", ");
					}
					b.Append(p.Name);
					b.Append(" = ");
					try {
						object val = p.GetValue(node, null);
						b.Append(val != null ? val.ToString() : "**null**");
					} catch (TargetInvocationException ex) {
						b.Append("**" + ex.InnerException.GetType().Name + "**");
					}
				}
			}
			if (hasProperties)
				b.Append(")");
			return b.ToString();
		}
Exemplo n.º 15
0
        protected override void EmitMethodParameters(IEnumerable<ParameterDeclaration> declarations, AstNode context, bool skipClose)
        {
            this.WriteOpenParentheses();
            bool needComma = false;

            foreach (var p in declarations)
            {
                var name = this.Emitter.GetEntityName(p);

                if (needComma)
                {
                    this.WriteComma();
                }

                needComma = true;
                this.Write(name);
                this.WriteColon();
                name = BridgeTypes.ToTypeScriptName(p.Type, this.Emitter);
                this.Write(name);
            }

            if (!skipClose)
            {
                this.WriteCloseParentheses();
            }
        }
Exemplo n.º 16
0
		static IEnumerable<IType> GetAllValidTypesFromInvocation(CSharpAstResolver resolver, InvocationExpression invoke, AstNode parameter)
		{
			int index = GetArgumentIndex(invoke.Arguments, parameter);
			if (index < 0)
				yield break;

			var targetResult = resolver.Resolve(invoke.Target) as MethodGroupResolveResult;
			if (targetResult != null) {
				foreach (var method in targetResult.Methods) {
					if (index < method.Parameters.Count) {
						if (method.Parameters [index].IsParams) {
							var arrayType = method.Parameters [index].Type as ArrayType;
							if (arrayType != null)
								yield return arrayType.ElementType;
						}

						yield return method.Parameters [index].Type;
					}
				}
				foreach (var extMethods in targetResult.GetExtensionMethods ()) {
					foreach (var extMethod in extMethods) {
						if (index + 1 < extMethod.Parameters.Count) {
							if (extMethod.Parameters [index + 1].IsParams) {
								var arrayType = extMethod.Parameters [index + 1].Type as ArrayType;
								if (arrayType != null)
									yield return arrayType.ElementType;
							}

							yield return extMethod.Parameters [index + 1].Type;
						}
					}
				}
			}
		}
			public ToolTipData (ICSharpCode.NRefactory.CSharp.SyntaxTree unit, ICSharpCode.NRefactory.Semantics.ResolveResult result, ICSharpCode.NRefactory.CSharp.AstNode node, CSharpAstResolver file)
			{
				this.Unit = unit;
				this.Result = result;
				this.Node = node;
				this.Resolver = file;
			}
Exemplo n.º 18
0
        public string MethodName; //either BindingInfo.Name, or name of the variable storing lambda expression

        #endregion Fields

        #region Constructors

        public Closure(Frame parentFrame, AstNode node, FunctionBindingInfo bindingInfo)
        {
            MethodName = bindingInfo.Name;
              ParentFrame = parentFrame;
              Node = node;
              BindingInfo = bindingInfo;
        }
Exemplo n.º 19
0
        public void Run(AstNode node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            var initializer = node as VariableInitializer;
            if (initializer != null)
            {
                var newName = "_loc" + _ctr++;
                _locals[initializer.Name] = newName;
                initializer.ReplaceWith(new VariableInitializer(newName, initializer.Initializer));
            }
            else
            {
                var identifier = node as IdentifierExpression;
                if (identifier != null)
                {
                    string newName;
                    if (_locals.TryGetValue(identifier.Identifier, out newName))
                        identifier.ReplaceWith(new IdentifierExpression(newName));
                }
            }

            foreach (var c in node.Children)
                Run(c);
        }
		public OverrideEqualsGetHashCodeMethodsDialog(InsertionContext context, ITextEditor editor, ITextAnchor endAnchor,
		                                              ITextAnchor insertionPosition, ITypeDefinition selectedClass, IMethod selectedMethod, AstNode baseCallNode)
			: base(context, editor, insertionPosition)
		{
			if (selectedClass == null)
				throw new ArgumentNullException("selectedClass");
			
			InitializeComponent();
			
			this.selectedClass = selectedClass;
			this.insertionEndAnchor = endAnchor;
			this.selectedMethod = selectedMethod;
			this.baseCallNode = baseCallNode;
			
			addIEquatable.Content = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddInterface}"),
			                                      "IEquatable<" + selectedClass.Name + ">");
			
			string otherMethod = selectedMethod.Name == "Equals" ? "GetHashCode" : "Equals";
			
			addOtherMethod.Content = StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddOtherMethod}", new StringTagPair("otherMethod", otherMethod));
			
			addIEquatable.IsEnabled = !selectedClass.GetAllBaseTypes().Any(
				type => {
					if (!type.IsParameterized || (type.TypeParameterCount != 1))
						return false;
					if (type.FullName != "System.IEquatable")
						return false;
					return type.TypeArguments.First().FullName == selectedClass.FullName;
				}
			);
		}
Exemplo n.º 21
0
		public void Run(AstNode compilationUnit) {
			foreach (var en in compilationUnit.Descendants.OfType<EntityDeclaration>()) {
				var def = en.Annotation<IMemberDef>();
				Debug.Assert(def != null);
				if (def == null)
					continue;
				if (def == type) {
					if (addPartialKeyword) {
						var tdecl = en as TypeDeclaration;
						Debug.Assert(tdecl != null);
						if (tdecl != null) {
							tdecl.Modifiers |= Modifiers.Partial;
							foreach (var iface in tdecl.BaseTypes) {
								var tdr = iface.Annotation<ITypeDefOrRef>();
								if (tdr != null && ifacesToRemove.Contains(tdr))
									iface.Remove();
							}
						}
					}
				}
				else {
					if (showDefinitions) {
						if (!definitions.Contains(def))
							en.Remove();
					}
					else {
						if (definitions.Contains(def))
							en.Remove();
					}
				}
			}
		}
Exemplo n.º 22
0
        public AstNode GetParentFinallyBlock(AstNode node, bool stopOnLoops)
        {
            var insideTryFinally = false;
            var target = node.GetParent(n =>
            {
                if (n is LambdaExpression || n is AnonymousMethodExpression || n is MethodDeclaration)
                {
                    return true;
                }

                if (stopOnLoops && (n is WhileStatement || n is ForeachStatement || n is ForStatement || n is DoWhileStatement))
                {
                    return true;
                }

                if (n is TryCatchStatement && !((TryCatchStatement)n).FinallyBlock.IsNull)
                {
                    insideTryFinally = true;
                    return true;
                }

                return false;
            });

            return insideTryFinally ? ((TryCatchStatement)target).FinallyBlock : null;
        }
Exemplo n.º 23
0
        public override void EndNode(AstNode node)
        {
            if (nodeStack.Pop() != node)
                throw new InvalidOperationException();

            var startLocation = startLocations.Pop();

            // code mappings
            var ranges = node.Annotation<List<ILRange>>();
            if (symbolsStack.Count > 0 && ranges != null && ranges.Count > 0) {
                // Ignore the newline which was printed at the end of the statement
                TextLocation endLocation = (node is Statement) ? (lastEndOfLine ?? output.Location) : output.Location;
                symbolsStack.Peek().SequencePoints.Add(
                    new SequencePoint() {
                        ILRanges = ILRange.OrderAndJoin(ranges).ToArray(),
                        StartLocation = startLocation,
                        EndLocation = endLocation
                    });
            }

            if (node.Annotation<MethodDebugSymbols>() != null) {
                symbolsStack.Peek().EndLocation = output.Location;
                output.AddDebugSymbols(symbolsStack.Pop());
            }
        }
		public static bool RequiresParens(AstNode replaceNode, AstNode replaceWithNode)
		{
			if (!(replaceWithNode is BinaryOperatorExpression) &&
			    !(replaceWithNode is AssignmentExpression) &&
			    !(replaceWithNode is AsExpression) &&
			    !(replaceWithNode is IsExpression) &&
			    !(replaceWithNode is CastExpression) &&
			    !(replaceWithNode is LambdaExpression) &&
				!(replaceWithNode is ConditionalExpression)) {
				return false;
			}

			var cond = replaceNode.Parent as ConditionalExpression;
			if (cond != null && cond.Condition == replaceNode)
				return true;

			var indexer = replaceNode.Parent as IndexerExpression;
			if (indexer != null && indexer.Target == replaceNode)
				return true;

			return replaceNode.Parent is BinaryOperatorExpression || 
				replaceNode.Parent is UnaryOperatorExpression || 
				replaceNode.Parent is AssignmentExpression || 
				replaceNode.Parent is MemberReferenceExpression ||
				replaceNode.Parent is AsExpression || 
				replaceNode.Parent is IsExpression || 
				replaceNode.Parent is CastExpression ||
				replaceNode.Parent is LambdaExpression ||
				replaceNode.Parent is PointerReferenceExpression;
		}
		public void Run(AstNode compilationUnit)
		{
			foreach (InvocationExpression invocation in compilationUnit.Descendants.OfType<InvocationExpression>()) {
				MemberReferenceExpression mre = invocation.Target as MemberReferenceExpression;
				MethodReference methodReference = invocation.Annotation<MethodReference>();
				if (mre != null && mre.Target is TypeReferenceExpression && methodReference != null && invocation.Arguments.Any()) {
					MethodDefinition d = methodReference.Resolve();
					if (d != null) {
						foreach (var ca in d.CustomAttributes) {
							if (ca.AttributeType.Name == "ExtensionAttribute" && ca.AttributeType.Namespace == "System.Runtime.CompilerServices") {
								var firstArgument = invocation.Arguments.First();
								if (firstArgument is NullReferenceExpression)
									firstArgument = firstArgument.ReplaceWith(expr => expr.CastTo(AstBuilder.ConvertType(d.Parameters.First().ParameterType)));
								else
									mre.Target = firstArgument.Detach();
								if (invocation.Arguments.Any()) {
									// HACK: removing type arguments should be done indepently from whether a method is an extension method,
									// just by testing whether the arguments can be inferred
									mre.TypeArguments.Clear();
								}
								break;
							}
						}
					}
				}
			}
		}
Exemplo n.º 26
0
 public override void Init(ParsingContext context, ParseTreeNode treeNode) {
   base.Init(context, treeNode);
   Test = AddChild("Test", treeNode.ChildNodes[0]);
   IfTrue = AddChild("IfTrue", treeNode.ChildNodes[1]);
   if (treeNode.ChildNodes.Count > 2)
     IfFalse = AddChild("IfFalse", treeNode.ChildNodes[2]);
 } 
Exemplo n.º 27
0
			public override void StartNode(AstNode node)
			{
				if (parameterIndex == highlightedParameterIndex && node is ParameterDeclaration) {
					parameterStartOffset = b.Length;
				}
				base.StartNode(node);
			}
Exemplo n.º 28
0
 public override void Init(ParsingContext context, ParseTreeNode treeNode) {
   base.Init(context, treeNode);
   TargetRef = AddChild("Target", treeNode.ChildNodes[0]);
   _targetName = treeNode.ChildNodes[0].FindTokenAndGetText(); 
   Arguments = AddChild("Args", treeNode.ChildNodes[1]);
   AsString = "Call " + _targetName;
 }
Exemplo n.º 29
0
 private void InitImpl(AstContext context, ParseTreeNode parseNode, ParseTreeNode parametersNode, ParseTreeNode bodyNode) {
   base.Init(context, parseNode);
   Parameters = AddChild("Parameters", parametersNode);
   Body = AddChild("Body", bodyNode);
   AsString = "Lambda[" + Parameters.ChildNodes.Count + "]";
   Body.SetIsTail(); //this will be propagated to the last statement
 }
Exemplo n.º 30
0
        IEnumerable<CodeAction> GetActionsForAddNamespaceUsing(RefactoringContext context, AstNode node)
        {
            var nrr = context.Resolve(node) as NamespaceResolveResult;
            if (nrr == null)
                return EmptyList<CodeAction>.Instance;

            var trr = context.Resolve(node.Parent) as TypeResolveResult;
            if (trr == null)
                return EmptyList<CodeAction>.Instance;
            ITypeDefinition typeDef = trr.Type.GetDefinition();
            if (typeDef == null)
                return EmptyList<CodeAction>.Instance;

            IList<IType> typeArguments;
            ParameterizedType parameterizedType = trr.Type as ParameterizedType;
            if (parameterizedType != null)
                typeArguments = parameterizedType.TypeArguments;
            else
                typeArguments = EmptyList<IType>.Instance;

            var resolver = context.GetResolverStateBefore(node.Parent);
            if (resolver.ResolveSimpleName(typeDef.Name, typeArguments) is UnknownIdentifierResolveResult) {
                // It's possible to remove the explicit namespace usage and introduce a using instead
                return new[] { NewUsingAction(context, node, typeDef.Namespace) };
            }
            return EmptyList<CodeAction>.Instance;
        }
Exemplo n.º 31
0
        /// <summary>
        /// 各种表达式
        /// </summary>
        /// <param name="expr"></param>
        string ParseObjectCreateExpression(AstNode expr)
        {
            string newtype = "";

            foreach (var v in expr.Children)
            {
                if (v is Comment)
                {
                    Append(v.ToString().Replace("\r\n", ""));
                }
                else if (v is PrimitiveType)
                {
                    newtype = Tools.getPrimitiveTypeName(v.ToString());
                    Append(newtype);
                }
                else if (v is MemberType)
                {
                    newtype = getMemberTypeName(v.ToString());
                    Append(newtype);
                }
                else if (v is SimpleType)
                {
                    newtype = getSimpleTypeName((v as SimpleType).Identifier);
                    Append(newtype);
                }
                else if (v is CSharpTokenNode)
                {
                    if (v.ToString() == "(")//param begin;
                    {
                        Append("(");
                    }
                    else if (v.ToString() == ")")//paramend;
                    {
                        Append(")");
                    }

                    else if (v.ToString() == "new")
                    {
                        Append("new ");
                    }
                    else
                    {
                        Append(v.ToString());
                    }
                }
                else if (v is NewLineNode)
                {
                    AppendLine();
                }
                else if (v is BlockStatement)
                {
                    ParseBlockStatement(v, null);
                }
                else if (v is IdentifierExpression)
                {//add param
                    ParseIdentifierExpression(v as IdentifierExpression, null);
                }


                else
                {
                    logger.LogError("not support ParseObjectCreateExpression element:" + v.GetType().Name + "|" + v.NodeType + "|" + v.StartLocation.Line);
                }

            }
            return newtype;
        }
Exemplo n.º 32
0
        public override object VisitBlockStatement(BlockStatement blockStatement, object data)
        {
            base.VisitBlockStatement(blockStatement, data);
            foreach (ExpressionStatement stmt in blockStatement.Statements.OfType <ExpressionStatement>().ToArray())
            {
                Match displayClassAssignmentMatch = displayClassAssignmentPattern.Match(stmt);
                if (displayClassAssignmentMatch == null)
                {
                    continue;
                }

                ILVariable variable = displayClassAssignmentMatch.Get("variable").Single().Annotation <ILVariable>();
                if (variable == null)
                {
                    continue;
                }
                TypeDefinition type = variable.Type.ResolveWithinSameModule();
                if (!IsPotentialClosure(context, type))
                {
                    continue;
                }
                if (displayClassAssignmentMatch.Get("type").Single().Annotation <TypeReference>().ResolveWithinSameModule() != type)
                {
                    continue;
                }

                // Looks like we found a display class creation. Now let's verify that the variable is used only for field accesses:
                bool ok = true;
                foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>())
                {
                    if (identExpr.Identifier == variable.Name && identExpr != displayClassAssignmentMatch.Get("variable").Single())
                    {
                        if (!(identExpr.Parent is MemberReferenceExpression && identExpr.Parent.Annotation <FieldReference>() != null))
                        {
                            ok = false;
                        }
                    }
                }
                if (!ok)
                {
                    continue;
                }
                Dictionary <FieldReference, AstNode> dict = new Dictionary <FieldReference, AstNode>();
                // Delete the variable declaration statement:
                AstNode cur = stmt.NextSibling;
                stmt.Remove();
                if (blockStatement.Parent.NodeType == NodeType.Member || blockStatement.Parent is Accessor)
                {
                    // Delete any following statements as long as they assign parameters to the display class
                    // Do parameter handling only for closures created in the top scope (direct child of method/accessor)
                    List <ILVariable> parameterOccurrances = blockStatement.Descendants.OfType <IdentifierExpression>()
                                                             .Select(n => n.Annotation <ILVariable>()).Where(p => p != null && p.IsParameter).ToList();
                    AstNode next;
                    for (; cur != null; cur = next)
                    {
                        next = cur.NextSibling;

                        // Test for the pattern:
                        // "variableName.MemberName = right;"
                        ExpressionStatement closureFieldAssignmentPattern = new ExpressionStatement(
                            new AssignmentExpression(
                                new NamedNode("left", new MemberReferenceExpression {
                            Target = new IdentifierExpression(variable.Name)
                        }),
                                new AnyNode("right")
                                )
                            );
                        Match m = closureFieldAssignmentPattern.Match(cur);
                        if (m != null)
                        {
                            AstNode right       = m.Get("right").Single();
                            bool    isParameter = false;
                            if (right is ThisReferenceExpression)
                            {
                                isParameter = true;
                            }
                            else if (right is IdentifierExpression)
                            {
                                // handle parameters only if the whole method contains no other occurrance except for 'right'
                                ILVariable param = right.Annotation <ILVariable>();
                                isParameter = param.IsParameter && parameterOccurrances.Count(c => c == param) == 1;
                            }
                            if (isParameter)
                            {
                                dict[m.Get <MemberReferenceExpression>("left").Single().Annotation <FieldReference>().ResolveWithinSameModule()] = right;
                                cur.Remove();
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                // Now create variables for all fields of the display class (except for those that we already handled as parameters)
                List <Tuple <AstType, string> > variablesToDeclare = new List <Tuple <AstType, string> >();
                foreach (FieldDefinition field in type.Fields)
                {
                    if (dict.ContainsKey(field))
                    {
                        continue;
                    }
                    variablesToDeclare.Add(Tuple.Create(AstBuilder.ConvertType(field.FieldType, field), field.Name));
                    dict[field] = new IdentifierExpression(field.Name);
                }

                // Now figure out where the closure was accessed and use the simpler replacement expression there:
                foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>())
                {
                    if (identExpr.Identifier == variable.Name)
                    {
                        MemberReferenceExpression mre = (MemberReferenceExpression)identExpr.Parent;
                        AstNode replacement;
                        if (dict.TryGetValue(mre.Annotation <FieldReference>().ResolveWithinSameModule(), out replacement))
                        {
                            mre.ReplaceWith(replacement.Clone());
                        }
                    }
                }
                // Now insert the variable declarations (we can do this after the replacements only so that the scope detection works):
                Statement insertionPoint = blockStatement.Statements.FirstOrDefault();
                foreach (var tuple in variablesToDeclare)
                {
                    var newVarDecl = new VariableDeclarationStatement(tuple.Item1, tuple.Item2);
                    newVarDecl.Variables.Single().AddAnnotation(new CapturedVariableAnnotation());
                    blockStatement.Statements.InsertBefore(insertionPoint, newVarDecl);
                }
            }
            return(null);
        }
Exemplo n.º 33
0
 protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
 {
     return(child.DoMatch(other, match));
 }
Exemplo n.º 34
0
 protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
 {
     return(other == null || other.IsNull);
 }
Exemplo n.º 35
0
        protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
        {
            VariableInitializer o = other as VariableInitializer;

            return(o != null && MatchString(this.Name, o.Name) && this.Initializer.DoMatch(o.Initializer, match));
        }
Exemplo n.º 36
0
        string ParseInvocationExpression(AstNode expr)//处理函数调用
        {
            string returntype = null;
            ExpressOption option = new ExpressOption();
            option.paramType = null;
            option.memberCall = true;
            StringBuilder old = null;
            foreach (var v in expr.Children)
            {
                if (v is IdentifierExpression)
                {
                    if (option.paramType == null)
                    {
                        Append("");
                        continue;//delaycall
                    }
                    else
                    {
                        option.paramType.Add(ParseIdentifierExpression(v as IdentifierExpression, null));
                    }
                }
                else if (v is MemberReferenceExpression)
                {
                    if (option.paramType == null)
                    {
                        Append("");
                        continue;//delaycall
                    }
                    else
                    {
                        option.paramType.Add(ParseMemberReferenceExpression(v as MemberReferenceExpression, null));
                    }
                }
                if (v is CSharpTokenNode)
                {
                    if (v.ToString() == "(")
                    {//将参数处理到自定义的地方
                        old = this.builder;
                        this.builder = new StringBuilder();
                        option.paramType = new List<string>();
                    }
                    Append(v.ToString());
                    if (v.ToString() == ")")
                    {
                        string callbody = this.builder.ToString();
                        this.builder = old;


                        //此时再去处理
                        foreach (var vv in expr.Children)
                        {
                            if (vv is IdentifierExpression)
                            {


                                ParseIdentifierExpression(vv as IdentifierExpression, option);
                                break;
                            }
                            else if (vv is MemberReferenceExpression)
                            {


                                ParseMemberReferenceExpression(vv as MemberReferenceExpression, option);
                                break;
                            }
                        }
                        Append(callbody);
                    }
                }
                else if (v is PrimitiveExpression)
                {
                    option.paramType.Add(ParsePrimitiveExpression(v));
                }
                else
                {
                    logger.LogError("not support ParseInvocationExpression element:" + v.GetType().Name + "|" + expr.NodeType + "|" + expr.StartLocation.Line);

                }
            }


            return returntype;
        }
Exemplo n.º 37
0
 string ParseThisReferenceExpression(AstNode expr)//this
 {
     Append("this");
     return getCurClassName();
 }
Exemplo n.º 38
0
 public abstract void EndNode(AstNode node);
Exemplo n.º 39
0
 public override void EndNode(AstNode node)
 {
     decoratedWriter.EndNode(node);
 }
Exemplo n.º 40
0
        public void Run(AstNode compilationUnit)
        {
            // First determine all the namespaces that need to be imported:
            compilationUnit.AcceptVisitor(new FindRequiredImports(this), null);

            importedNamespaces.Add("System");             // always import System, even when not necessary

            if (context.Settings.UsingDeclarations)
            {
                // Now add using declarations for those namespaces:
                foreach (string ns in importedNamespaces.OrderByDescending(n => n))
                {
                    // we go backwards (OrderByDescending) through the list of namespaces because we insert them backwards
                    // (always inserting at the start of the list)
                    string[] parts  = ns.Split('.');
                    AstType  nsType = new SimpleType(parts[0]).WithAnnotation(TextTokenType.NamespacePart);
                    for (int i = 1; i < parts.Length; i++)
                    {
                        nsType = new MemberType {
                            Target = nsType, MemberNameToken = Identifier.Create(parts[i]).WithAnnotation(TextTokenType.NamespacePart)
                        }.WithAnnotation(TextTokenType.NamespacePart);
                    }
                    compilationUnit.InsertChildAfter(null, new UsingDeclaration {
                        Import = nsType
                    }, SyntaxTree.MemberRole);
                }
            }

            if (!context.Settings.FullyQualifyAmbiguousTypeNames)
            {
                return;
            }

            if (context.CurrentModule != null)
            {
                FindAmbiguousTypeNames(context.CurrentModule.Types, internalsVisible: true);
                if (context.CurrentModule is ModuleDefMD)
                {
                    var asmDict = new Dictionary <AssemblyDef, List <AssemblyDef> >(AssemblyEqualityComparer.Instance);
                    foreach (var r in ((ModuleDefMD)context.CurrentModule).GetAssemblyRefs())
                    {
                        AssemblyDef d = context.CurrentModule.Context.AssemblyResolver.Resolve(r, context.CurrentModule);
                        if (d == null)
                        {
                            continue;
                        }
                        List <AssemblyDef> list;
                        if (!asmDict.TryGetValue(d, out list))
                        {
                            asmDict.Add(d, list = new List <AssemblyDef>());
                        }
                        list.Add(d);
                    }
                    foreach (var list in asmDict.Values)
                    {
                        FindAmbiguousTypeNames(GetTypes(list), internalsVisible: false);
                    }
                }
            }

            // verify that the SimpleTypes refer to the correct type (no ambiguities)
            compilationUnit.AcceptVisitor(new FullyQualifyAmbiguousTypeNamesVisitor(this), null);
        }
Exemplo n.º 41
0
 /// <summary>
 /// Gets whether the expression acts like a parenthesized expression,
 /// i.e. whether information about the expected type (for lambda type inference) flows
 /// into the inner expression.
 /// </summary>
 /// <returns>Returns true for ParenthesizedExpression, CheckedExpression or UncheckedExpression; false otherwise.</returns>
 public static bool ActsAsParenthesizedExpression(AstNode expression)
 {
     return(expression is ParenthesizedExpression || expression is CheckedExpression || expression is UncheckedExpression);
 }
Exemplo n.º 42
0
 public abstract void StartNode(AstNode node);
Exemplo n.º 43
0
        public static void AddAllRecursiveILRangesTo(this IEnumerable <AstNode> nodes, AstNode target)
        {
            if (nodes == null)
            {
                return;
            }
            var ilRanges = nodes.GetAllRecursiveILRanges();

            if (ilRanges.Count > 0)
            {
                target.AddAnnotation(ilRanges);
            }
        }
Exemplo n.º 44
0
 public override void StartNode(AstNode node)
 {
     decoratedWriter.StartNode(node);
 }
 public IParameterDataProvider CreateConstructorProvider(int startOffset, ICSharpCode.NRefactory.TypeSystem.IType type, AstNode skipNode)
 {
     Assert.IsTrue(type.Kind != TypeKind.Unknown);
     return(new Provider()
     {
         Data = type.GetConstructors(m => m.Accessibility == Accessibility.Public)
     });
 }
Exemplo n.º 46
0
        protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
        {
            ParenthesizedExpression o = other as ParenthesizedExpression;

            return(o != null && this.Expression.DoMatch(o.Expression, match));
        }
        public static bool TypeChangeResolvesCorrectly(BaseRefactoringContext ctx, ParameterDeclaration parameter, AstNode rootNode, IType type)
        {
            var resolver = ctx.GetResolverStateBefore(rootNode);

            resolver = resolver.AddVariable(new DefaultParameter(type, parameter.Name));
            var astResolver = new CSharpAstResolver(resolver, rootNode, ctx.UnresolvedFile);
            var validator   = new TypeChangeValidationNavigator();

            astResolver.ApplyNavigator(validator, ctx.CancellationToken);
            return(!validator.FoundErrors);
        }
 public IParameterDataProvider CreateIndexerParameterDataProvider(int startOffset, IType type, AstNode resolvedNode)
 {
     Assert.IsTrue(type.Kind != TypeKind.Unknown);
     if (type.Kind == TypeKind.Array)
     {
         return(new ArrayProvider());
     }
     return(new IndexerProvider()
     {
         Data = type.GetProperties(p => p.IsIndexer)
     });
 }
Exemplo n.º 49
0
 public void Run(AstNode node)
 {
     node.AcceptVisitor(this, null);
 }
            public void Resolved(AstNode node, ResolveResult result)
            {
//				bool errors = result.IsError;
                FoundErrors |= result.IsError;
            }
Exemplo n.º 51
0
 public MapItemExpression(AstNode parent, Expression left, Expression right) : base(parent)
 {
     Left  = left;
     Right = right;
 }
Exemplo n.º 52
0
        protected virtual void EmitMethodParameters(IEnumerable <ParameterDeclaration> declarations, AstNode context)
        {
            this.WriteOpenParentheses();
            bool needComma = false;

            foreach (var p in declarations)
            {
                var name = this.Emitter.GetParameterName(p);

                if (needComma)
                {
                    this.WriteComma();
                }

                needComma = true;
                this.Write(name);
                this.WriteColon();
                name = BridgeTypes.ToTypeScriptName(p.Type, this.Emitter);
                this.Write(name);

                var resolveResult = this.Emitter.Resolver.ResolveNode(p.Type, this.Emitter);
                if (resolveResult != null && (resolveResult.Type.IsReferenceType.HasValue && resolveResult.Type.IsReferenceType.Value || resolveResult.Type.IsKnownType(KnownTypeCode.NullableOfT)))
                {
                    this.Write(" | null");
                }
            }

            this.WriteCloseParentheses();
        }
Exemplo n.º 53
0
 public Scope(AstNode node, Scope parent)
 {
     Node   = node;
     Parent = parent;
     Level  = (short)(parent == null ? 0 : parent.Level + 1);
 }
Exemplo n.º 54
0
        internal BraceCollectionExpression(
            AstNode parent,
            BraceCollectionType type = BraceCollectionType.Unknown
            ) : base(parent)
        {
            Expressions = new NodeList <Expression>(this);
            Type        = type;
            MarkStartAndEat(OpenBrace);

            if (!Peek.Is(CloseBrace))
            {
                var comprehension = false;
                while (true)
                {
                    Expression item = ParseInfixExpr(this);
                    if (comprehension)
                    {
                        Unit.Blame(
                            BlameType.CollectionInitializerCannotContainItemsAfterComprehension,
                            item
                            );
                    }

                    // map item (expr ':' expr)
                    if (MaybeEat(Colon))
                    {
                        if (Type == BraceCollectionType.Set)
                        {
                            Unit.ReportError("Single expression expected", Token);
                        }

                        Type = BraceCollectionType.Map;
                        item = new MapItemExpression(
                            this,
                            item,
                            ParseInfixExpr(this)
                            );
                    }
                    // set item (expr)
                    else
                    {
                        if (Type == BraceCollectionType.Map)
                        {
                            Unit.ReportError("'Key : Value' expression expected", Token);
                        }

                        Type = BraceCollectionType.Set;
                    }

                    if (Peek.Is(KeywordFor))
                    {
                        item          = new ForComprehension(this, item);
                        comprehension = true;
                    }

                    Expressions.Add(item);

                    if (Peek.Is(CloseBrace))
                    {
                        break;
                    }

                    Eat(Comma);
                }
            }

            MarkEndAndEat(CloseBrace);

            if (Expressions.Count == 0)
            {
                Unit.Blame(BlameType.EmptyCollectionLiteralNotSupported, this);
            }
        }
Exemplo n.º 55
0
 public TableIndexingNode(VariableNode variable, AstNode keyExpression)
 {
     Variable      = variable;
     KeyExpression = keyExpression;
 }
 void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result)
 {
 }
Exemplo n.º 57
0
 public override void VisitNullNode(AstNode nullNode)
 {
     new NullReferenceBlock(this, nullNode).Emit();
 }
Exemplo n.º 58
0
        protected internal override bool DoMatch(AstNode other, Match match)
        {
            CommentStatement o = other as CommentStatement;

            return(o != null && MatchString(comment, o.comment));
        }
Exemplo n.º 59
0
 public LambdaBlock(IEmitter emitter, IEnumerable <ParameterDeclaration> parameters, AstNode body, AstNode context, bool isAsync)
     : base(emitter, context)
 {
     this.Emitter    = emitter;
     this.Parameters = parameters;
     this.Body       = body;
     this.Context    = context;
     this.IsAsync    = isAsync;
 }
Exemplo n.º 60
0
        protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
        {
            CastExpression o = other as CastExpression;

            return(o != null && this.Type.DoMatch(o.Type, match) && this.Expression.DoMatch(o.Expression, match));
        }