Example #1
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;
        }
Example #2
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;
 }
	TextLocation GetEndOfPrev(AstNode node)
	{
		do {
			node = node.GetPrevNode();
		} while (node.NodeType == NodeType.Whitespace);
		return node.EndLocation;
	}
	public override void StartNode(AstNode node)
	{
		currentList.Add(node);
		nodes.Push(currentList);
		currentList = new List<AstNode>();
		base.StartNode(node);
	}
Example #5
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);
            }
        }
Example #6
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();
            }
        }
	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);
		}
	}
Example #8
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());
            }
        }
Example #9
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;
 }
		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;
						}
					}
				}
			}
		}
	}
Example #12
0
	public override void StartNode(AstNode node)
	{
		if (parameterIndex == highlightedParameterIndex && node is ParameterDeclaration) {
			parameterStartOffset = b.Length;
		}
		base.StartNode(node);
	}
Example #13
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]);
 } 
Example #14
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
 }
	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;
	}
Example #16
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;
        }
Example #17
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();
	}
Example #18
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;
        }
Example #19
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;
	}
	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;
			}
		);
	}
Example #21
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 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();
				}
			}
		}
	}
 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;
 }
Example #24
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;
        }
 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;
         }
     }
 }
Example #26
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 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");
                }
            }
        }
Example #28
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;
						}
					}
				}
			}
		}
Example #29
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.
	}
Example #30
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;
		}
	}