public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { if (!CutRegion.Contains(localVariableDeclaration.StartLocation.Line - 1, localVariableDeclaration.StartLocation.Column - 1)) { foreach (VariableDeclaration varDecl in localVariableDeclaration.Variables) { variables[varDecl.Name] = new VariableDescriptor(varDecl.Name) { IsDefined = true, ReturnType = ConvertTypeReference(localVariableDeclaration.TypeReference), Location = new DocumentLocation(MemberLocation.Line + localVariableDeclaration.StartLocation.Line - 1, localVariableDeclaration.StartLocation.Column - 1) }; } } return(base.VisitLocalVariableDeclaration(localVariableDeclaration, data)); }
public void VBNetLocalJaggedArrayDeclarationTest() { LocalVariableDeclaration lvd = ParseUtil.ParseStatement <LocalVariableDeclaration>("Dim a(10)() As Integer"); Assert.AreEqual(1, lvd.Variables.Count); Assert.AreEqual("a", lvd.Variables[0].Name); TypeReference type = lvd.GetTypeForVariable(0); Assert.AreEqual("System.Int32", type.Type); Assert.AreEqual(new int[] { 0, 0 }, type.RankSpecifier); ArrayCreateExpression ace = (ArrayCreateExpression)lvd.Variables[0].Initializer; Assert.AreEqual(new int[] { 0, 0 }, ace.CreateType.RankSpecifier); Assert.AreEqual(1, ace.Arguments.Count); Assert.AreEqual(10, ((PrimitiveExpression)ace.Arguments[0]).Value); }
public void VBNetComplexGenericLocalVariableDeclarationTest() { LocalVariableDeclaration lvd = ParseUtil.ParseStatement <LocalVariableDeclaration>("Dim where As Generic(Of Printable, G(Of Printable()))"); Assert.AreEqual(1, lvd.Variables.Count); Assert.AreEqual("where", lvd.Variables[0].Name); TypeReference type = lvd.GetTypeForVariable(0); Assert.AreEqual("Generic", type.Type); Assert.AreEqual(2, type.GenericTypes.Count); Assert.AreEqual("Printable", type.GenericTypes[0].Type); Assert.AreEqual(0, type.GenericTypes[0].GenericTypes.Count); Assert.AreEqual("G", type.GenericTypes[1].Type); Assert.AreEqual(1, type.GenericTypes[1].GenericTypes.Count); Assert.AreEqual("Printable", type.GenericTypes[1].GenericTypes[0].Type); }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { if (AddDefaultValueInitializerToLocalVariableDeclarations) { for (int i = 0; i < localVariableDeclaration.Variables.Count; i++) { VariableDeclaration decl = localVariableDeclaration.Variables[i]; if (decl.FixedArrayInitialization.IsNull && decl.Initializer.IsNull) { TypeReference type = localVariableDeclaration.GetTypeForVariable(i); decl.Initializer = ExpressionBuilder.CreateDefaultValueForType(type); } } } return(base.VisitLocalVariableDeclaration(localVariableDeclaration, data)); }
public void VBNetNestedGenericLocalVariableDeclarationTest() { LocalVariableDeclaration lvd = ParseUtilVBNet.ParseStatement <LocalVariableDeclaration>("Dim a as MyType(of string).InnerClass(of integer).InnerInnerClass"); Assert.AreEqual(1, lvd.Variables.Count); InnerClassTypeReference ic = (InnerClassTypeReference)lvd.GetTypeForVariable(0); Assert.AreEqual("InnerInnerClass", ic.Type); Assert.AreEqual(0, ic.GenericTypes.Count); ic = (InnerClassTypeReference)ic.BaseType; Assert.AreEqual("InnerClass", ic.Type); Assert.AreEqual(1, ic.GenericTypes.Count); Assert.AreEqual("System.Int32", ic.GenericTypes[0].Type); Assert.AreEqual("MyType", ic.BaseType.Type); Assert.AreEqual(1, ic.BaseType.GenericTypes.Count); Assert.AreEqual("System.String", ic.BaseType.GenericTypes[0].Type); }
public void CSharpNestedGenericLocalVariableDeclarationTest() { LocalVariableDeclaration lvd = ParseUtilCSharp.ParseStatement <LocalVariableDeclaration>("MyType<string>.InnerClass<int>.InnerInnerClass a;"); Assert.AreEqual(1, lvd.Variables.Count); InnerClassTypeReference ic = (InnerClassTypeReference)lvd.GetTypeForVariable(0); Assert.AreEqual("InnerInnerClass", ic.Type); Assert.AreEqual(0, ic.GenericTypes.Count); ic = (InnerClassTypeReference)ic.BaseType; Assert.AreEqual("InnerClass", ic.Type); Assert.AreEqual(1, ic.GenericTypes.Count); Assert.AreEqual("System.Int32", ic.GenericTypes[0].Type); Assert.AreEqual("MyType", ic.BaseType.Type); Assert.AreEqual(1, ic.BaseType.GenericTypes.Count); Assert.AreEqual("System.String", ic.BaseType.GenericTypes[0].Type); }
public void VBNetLocalArrayDeclarationWithInitializationAndLowerBoundTest() { // VB.NET allows only "0" as lower bound LocalVariableDeclaration lvd = ParseUtilVBNet.ParseStatement <LocalVariableDeclaration>("Dim a(0 To 10) As Integer"); Assert.AreEqual(1, lvd.Variables.Count); Assert.AreEqual("a", lvd.Variables[0].Name); TypeReference type = lvd.GetTypeForVariable(0); Assert.AreEqual("System.Int32", type.Type); Assert.AreEqual(new int[] { 0 }, type.RankSpecifier); ArrayCreateExpression ace = (ArrayCreateExpression)lvd.Variables[0].Initializer; Assert.AreEqual(new int[] { 0 }, ace.CreateType.RankSpecifier); Assert.AreEqual(1, ace.Arguments.Count); Assert.AreEqual(10, ((PrimitiveExpression)ace.Arguments[0]).Value); }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { // Console.WriteLine ("LocalVariableDeclaration: " + localVariableDeclaration.StartLocation.ToString () + " - " + localVariableDeclaration.EndLocation.ToString ()); localVariableDeclaration.TypeReference.AcceptVisitor(this, data); foreach (VariableDeclaration o in localVariableDeclaration.Variables) { if (o.Name == ((IntegrateTemporaryVariableVisitorOptions)data).GetName()) { IntegrateTemporaryVariableVisitorOptions options = (IntegrateTemporaryVariableVisitorOptions)data; options.Initializer = localVariableDeclaration.GetVariableDeclaration(((LocalVariable)options.Options.SelectedItem).Name).Initializer; if (localVariableDeclaration.Variables.Count == 1) { TextReplaceChange change = new TextReplaceChange(); change.Description = string.Format(GettextCatalog.GetString("Deleting local variable declaration {0}"), options.GetName()); change.FileName = options.Options.Document.FileName; change.Offset = options.Options.Document.TextEditor.GetPositionFromLineColumn(localVariableDeclaration.StartLocation.Line + ((LocalVariable)options.Options.SelectedItem).DeclaringMember.BodyRegion.Start.Line, localVariableDeclaration.StartLocation.Column); int end = options.Options.Document.TextEditor.GetPositionFromLineColumn(localVariableDeclaration.EndLocation.Line + ((LocalVariable)options.Options.SelectedItem).DeclaringMember.BodyRegion.Start.Line, localVariableDeclaration.EndLocation.Column); change.RemovedChars = end - change.Offset; change.InsertedText = ""; ((IntegrateTemporaryVariableVisitorOptions)data).Changes.Add(change); } else { TextReplaceChange change = new TextReplaceChange(); change.Description = string.Format(GettextCatalog.GetString("Deleting local variable declaration {0}"), options.GetName()); change.FileName = options.Options.Document.FileName; change.Offset = options.Options.Document.TextEditor.GetPositionFromLineColumn(localVariableDeclaration.StartLocation.Line + ((LocalVariable)options.Options.SelectedItem).DeclaringMember.BodyRegion.Start.Line, localVariableDeclaration.StartLocation.Column); int end = options.Options.Document.TextEditor.GetPositionFromLineColumn(localVariableDeclaration.EndLocation.Line + ((LocalVariable)options.Options.SelectedItem).DeclaringMember.BodyRegion.Start.Line, localVariableDeclaration.EndLocation.Column); change.RemovedChars = end - change.Offset; localVariableDeclaration.Variables.Remove(localVariableDeclaration.GetVariableDeclaration(options.GetName())); INRefactoryASTProvider provider = options.Options.GetASTProvider(); change.InsertedText = options.Options.GetWhitespaces(change.Offset) + provider.OutputNode(options.Options.Dom, localVariableDeclaration); ((IntegrateTemporaryVariableVisitorOptions)data).Changes.Add(change); } } else { o.AcceptVisitor(this, data); } } return(null); }
private bool NonLinqVersion(CatchClause catchClause) { List <INode> children = catchClause.StatementBlock.Children; if (children.Count <= 0) { return(false); } LocalVariableDeclaration lvd = children[0] as LocalVariableDeclaration; if (lvd == null || lvd.TypeReference.Type != "System.String") { return(false); } InvocationExpression initializer = lvd.Variables[0].Initializer as InvocationExpression; if (initializer == null) { return(false); } MemberReferenceExpression mre = initializer.TargetObject as MemberReferenceExpression; if (mre == null) { return(false); } if (mre.MemberName != "ToString") { return(false); } IdentifierExpression ie = mre.TargetObject as IdentifierExpression; if (ie == null || ie.Identifier != catchClause.VariableName) { return(false); } // ToString is being called on the exception return(children.Count == 1 || IsNotUsedInAnyRemainingStatements(ie, children.GetRange(1, children.Count - 1))); }
public override object VisitUsingStatement(UsingStatement usingStatement, object data) { LocalVariableDeclaration lvd = usingStatement.ResourceAcquisition as LocalVariableDeclaration; if (lvd != null && lvd.Variables.Count > 1) { usingStatement.ResourceAcquisition = new LocalVariableDeclaration(lvd.Variables[0]); for (int i = 1; i < lvd.Variables.Count; i++) { UsingStatement n = new UsingStatement(new LocalVariableDeclaration(lvd.Variables[i]), usingStatement.EmbeddedStatement); usingStatement.EmbeddedStatement = new BlockStatement(); usingStatement.EmbeddedStatement.AddChild(n); usingStatement = n; } } return(base.VisitUsingStatement(usingStatement, data)); }
public void CSharpComplexGenericLocalVariableDeclarationTest() { LocalVariableDeclaration lvd = ParseUtilCSharp.ParseStatement <LocalVariableDeclaration>("Generic<Namespace.Printable, G<Printable[]> > where = new Generic<Namespace.Printable, G<Printable[]>>();"); Assert.AreEqual(1, lvd.Variables.Count); Assert.AreEqual("where", ((VariableDeclaration)lvd.Variables[0]).Name); TypeReference type = lvd.GetTypeForVariable(0); Assert.AreEqual("Generic", type.Type); Assert.AreEqual(2, type.GenericTypes.Count); Assert.AreEqual("Namespace.Printable", type.GenericTypes[0].Type); Assert.AreEqual(0, type.GenericTypes[0].GenericTypes.Count); Assert.AreEqual("G", type.GenericTypes[1].Type); Assert.AreEqual(1, type.GenericTypes[1].GenericTypes.Count); Assert.AreEqual("Printable", type.GenericTypes[1].GenericTypes[0].Type); // TODO: Check initializer }
string GetVariableNameFromVariableDeclaration(LocalVariableDeclaration declaration) { if (declaration == null) { return(null); } if (declaration.Variables.Count != 1) { return(null); } VariableDeclaration varDecl = declaration.Variables[0]; if (!ExpressionCanBeNull(varDecl.Initializer) || ExpressionIsValueType(varDecl.Initializer)) { // don't offer action where it makes no sense return(null); } return(varDecl.Name); }
public override object TrackedVisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data) { string variableName = GetVariableName(arrayCreateExpression); List <Expression> initializerList = arrayCreateExpression.ArrayInitializer.CreateExpressions; Expression replacedExpression = arrayCreateExpression; if (initializerList.Count > 0 && initializerList[0] is CollectionInitializerExpression && data is InsertionBlockData) { ArrayCreateExpression replacedArrayCreateExpression = arrayCreateExpression; replacedArrayCreateExpression.ArrayInitializer = null; replacedArrayCreateExpression.Arguments.Add(new PrimitiveExpression(initializerList.Count, initializerList.Count.ToString())); string arrayTypeName = arrayCreateExpression.CreateType.Type + "s"; Position position = Position.After; if (variableName == null) { variableName = arrayTypeName; position = Position.Before; } List <Statement> initStatements = GetArrayInitStatements(replacedArrayCreateExpression, variableName, initializerList); InsertionBlockData insertionBlockData = (InsertionBlockData)data; insertionBlockData.Block = (BlockStatement)AstUtil.GetParentOfType(replacedArrayCreateExpression, typeof(BlockStatement)); insertionBlockData.BlockChildIndex = GetBlockChildIndex(replacedArrayCreateExpression, position); insertionBlockData.Statements = initStatements; if (variableName == arrayTypeName) { IdentifierExpression identifierExpression = new IdentifierExpression(variableName); replacedExpression = identifierExpression; VariableDeclaration variableDeclaration = new VariableDeclaration(variableName, arrayCreateExpression); LocalVariableDeclaration localVariable = new LocalVariableDeclaration(variableDeclaration); localVariable.TypeReference = arrayCreateExpression.CreateType; initStatements.Insert(0, localVariable); } ReplaceCurrentNode(replacedExpression); } return(base.TrackedVisitArrayCreateExpression(arrayCreateExpression, data)); }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { base.VisitLocalVariableDeclaration(localVariableDeclaration, data); if ((localVariableDeclaration.Modifier & Modifiers.Static) == Modifiers.Static) { INode parent = localVariableDeclaration.Parent; while (parent != null && !IsTypeLevel(parent)) { parent = parent.Parent; } if (parent != null) { string fieldPrefix = "static_" + GetTypeLevelEntityName(parent) + "_"; foreach (VariableDeclaration v in localVariableDeclaration.Variables) { if (!v.Initializer.IsNull) { string initFieldName = fieldPrefix + v.Name + "_Init"; FieldDeclaration initField = new FieldDeclaration(null); initField.TypeReference = new TypeReference("Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag"); initField.Modifier = (((AttributedNode)parent).Modifier & Modifiers.Static) | Modifiers.ReadOnly; Expression initializer = initField.TypeReference.New(); initField.Fields.Add(new VariableDeclaration(initFieldName, initializer)); InsertBeforeSibling(parent, initField); InsertAfterSibling(localVariableDeclaration, InitStaticVariable(initFieldName, v.Name, v.Initializer, parent.Parent as TypeDeclaration)); } FieldDeclaration field = new FieldDeclaration(null); field.TypeReference = localVariableDeclaration.TypeReference; field.Modifier = ((AttributedNode)parent).Modifier & Modifiers.Static; field.Fields.Add(new VariableDeclaration(fieldPrefix + v.Name) { TypeReference = v.TypeReference }); InsertBeforeSibling(parent, field); } new PrefixFieldsVisitor(localVariableDeclaration.Variables, fieldPrefix).Run(parent); RemoveCurrentNode(); } } return(null); }
private static Parameter MakeParameter(LocalVariableDeclaration <QsLocalSymbol> parameter) { var type = MapResolvedTypeToDataType(parameter.Type); var arrayType = parameter.Type.Resolution is QsTypeKind.ArrayType innerType ? (DataType?)MapResolvedTypeToDataType(innerType.Item) : null; if (arrayType == DataType.ArrayType) { throw new ArgumentException("Multi-dimensional arrays are not supported types of entry point parameters."); } return(new Parameter() { Name = parameter.VariableName is QsLocalSymbol.ValidName name ? name.Item : throw new ArgumentException("Encountered invalid name for parameter."), Type = type, ArrayType = arrayType, });
private void AddDebugInfoForAlloca(Alloca argSlot, IrFunction function, LocalVariableDeclaration localVar) { uint line = ( uint )localVar.Location.StartLine; uint col = ( uint )localVar.Location.StartColumn; DILocalVariable debugVar = Module.DIBuilder.CreateLocalVariable(scope: function.DISubProgram , name: localVar.Name , file: function.DISubProgram.File , line , type: DoubleType , alwaysPreserve: false , debugFlags: DebugInfoFlags.None ); Module.DIBuilder.InsertDeclare(storage: argSlot , varInfo: debugVar , location: new DILocation(Context, line, col, function.DISubProgram) , insertAtEnd: InstructionBuilder.InsertBlock ); }
public Statement GetStatement() { var parameterType = semanticModel.GetTypeInfo(forEachStatementSyntax.Type).GetClassType(); var parameter = new LocalVariableDeclaration { Type = parameterType, Name = forEachStatementSyntax.Identifier.ValueText }; var collection = statementInterpreterHandler.GetStatement(forEachStatementSyntax.Expression); var body = statementInterpreterHandler.GetStatement(forEachStatementSyntax.Statement); return(new ForEachStatement { Variable = parameter, Collection = collection, Body = body }); }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { if (localVariableDeclaration.TypeReference.Type.Contains(TypeToFind)) { foreach (VariableDeclaration variableDeclaration in localVariableDeclaration.Variables) { _intvariables.Add(variableDeclaration.Name); if (variableDeclaration.Initializer is MemberReferenceExpression) { MemberReferenceExpression memb = (MemberReferenceExpression)variableDeclaration.Initializer; if (IsMinValue(memb)) { UnlockWith(localVariableDeclaration); } } } } return(base.VisitLocalVariableDeclaration(localVariableDeclaration, data)); }
public TypeReference FindType(string name, Statement currentStatement) { INode node = currentStatement; while ((node = node.Parent) != null) { foreach (INode childNode in node.Children) { LocalVariableDeclaration varDecl = childNode as LocalVariableDeclaration; if (varDecl != null) { foreach (VariableDeclaration var in varDecl.Variables) { if (nameComparer.Equals(var.Name, name)) { return(var.TypeReference); } } } } } return(null); }
/** * Call back method that must be called when the given <code> * LocalVariableDeclaration</code> will become the next <i>traverse * candidate</i>. * * @param pLocalVariableDeclaration The <code>LocalVariableDeclaration * </code> object that will become the * next <i>traverse candidate</i>. */ public void performAction( LocalVariableDeclaration pLocalVariableDeclaration) { // Nothing to do. }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { // Console.WriteLine ("LocalVariableDeclaration: " + localVariableDeclaration.StartLocation.ToString () + " - " + localVariableDeclaration.EndLocation.ToString ()); localVariableDeclaration.TypeReference.AcceptVisitor(this, data); foreach (VariableDeclaration o in localVariableDeclaration.Variables) { if (o.Name == ((IntegrateTemporaryVariableVisitorOptions)data).GetName()) { IntegrateTemporaryVariableVisitorOptions options = (IntegrateTemporaryVariableVisitorOptions)data; options.Initializer = localVariableDeclaration.GetVariableDeclaration(((LocalVariable)options.Options.SelectedItem).Name).Initializer; if (localVariableDeclaration.Variables.Count == 1) { TextReplaceChange change = new TextReplaceChange(); change.Description = string.Format(GettextCatalog.GetString("Deleting local variable declaration {0}"), options.GetName()); change.FileName = options.Options.Document.FileName; int lineNumber = localVariableDeclaration.StartLocation.Line + ((LocalVariable)options.Options.SelectedItem).DeclaringMember.BodyRegion.Start.Line; change.Offset = options.Options.Document.Editor.Document.LocationToOffset(lineNumber, localVariableDeclaration.StartLocation.Column); int end = options.Options.Document.Editor.Document.LocationToOffset(localVariableDeclaration.EndLocation.Line + ((LocalVariable)options.Options.SelectedItem).DeclaringMember.BodyRegion.Start.Line, localVariableDeclaration.EndLocation.Column); change.RemovedChars = end - change.Offset; // check if whole line can be removed. var line = options.Options.Document.Editor.GetLine(lineNumber); if (line.GetIndentation(options.Options.Document.Editor.Document).Length == localVariableDeclaration.StartLocation.Column - 1) { bool isEmpty = true; for (int i = end; i < line.EndOffset; i++) { if (!char.IsWhiteSpace(options.Options.Document.Editor.GetCharAt(i))) { isEmpty = false; break; } } if (isEmpty) { change.Offset = line.Offset; change.RemovedChars = line.Length; } } change.InsertedText = ""; ((IntegrateTemporaryVariableVisitorOptions)data).Changes.Add(change); } else { TextReplaceChange change = new TextReplaceChange(); change.Description = string.Format(GettextCatalog.GetString("Deleting local variable declaration {0}"), options.GetName()); change.FileName = options.Options.Document.FileName; change.Offset = options.Options.Document.Editor.Document.LocationToOffset(localVariableDeclaration.StartLocation.Line + ((LocalVariable)options.Options.SelectedItem).DeclaringMember.BodyRegion.Start.Line, localVariableDeclaration.StartLocation.Column); int end = options.Options.Document.Editor.Document.LocationToOffset(localVariableDeclaration.EndLocation.Line + ((LocalVariable)options.Options.SelectedItem).DeclaringMember.BodyRegion.Start.Line, localVariableDeclaration.EndLocation.Column); change.RemovedChars = end - change.Offset; localVariableDeclaration.Variables.Remove(localVariableDeclaration.GetVariableDeclaration(options.GetName())); INRefactoryASTProvider provider = options.Options.GetASTProvider(); change.InsertedText = options.Options.GetWhitespaces(change.Offset) + provider.OutputNode(options.Options.Dom, localVariableDeclaration); ((IntegrateTemporaryVariableVisitorOptions)data).Changes.Add(change); } } else { o.AcceptVisitor(this, data); } } return(null); }
public virtual object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { Debug.Assert((localVariableDeclaration != null)); Debug.Assert((localVariableDeclaration.TypeReference != null)); Debug.Assert((localVariableDeclaration.Variables != null)); nodeStack.Push(localVariableDeclaration.TypeReference); localVariableDeclaration.TypeReference.AcceptVisitor(this, data); localVariableDeclaration.TypeReference = ((TypeReference)(nodeStack.Pop())); for (int i = 0; i < localVariableDeclaration.Variables.Count; i++) { VariableDeclaration o = localVariableDeclaration.Variables[i]; Debug.Assert(o != null); nodeStack.Push(o); o.AcceptVisitor(this, data); o = (VariableDeclaration)nodeStack.Pop(); if (o == null) localVariableDeclaration.Variables.RemoveAt(i--); else localVariableDeclaration.Variables[i] = o; } return null; }
public virtual object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { throw new global::System.NotImplementedException("LocalVariableDeclaration"); }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { if (AddDefaultValueInitializerToLocalVariableDeclarations) { for (int i = 0; i < localVariableDeclaration.Variables.Count; i++) { VariableDeclaration decl = localVariableDeclaration.Variables[i]; if (decl.FixedArrayInitialization.IsNull && decl.Initializer.IsNull) { TypeReference type = localVariableDeclaration.GetTypeForVariable(i); decl.Initializer = ExpressionBuilder.CreateDefaultValueForType(type); } } } return base.VisitLocalVariableDeclaration(localVariableDeclaration, data); }
private void Statement() { ICSharpCode.NRefactory.Parser.AST.Statement stmt = null; Point location = this.la.Location; if (this.IsLabel()) { base.Expect(1); base.compilationUnit.AddChild(new LabelStatement(this.t.val)); base.Expect(9); this.Statement(); } else if (this.la.kind == 0x3b) { TypeReference reference; Expression expression; base.lexer.NextToken(); this.Type(out reference); LocalVariableDeclaration childNode = new LocalVariableDeclaration(reference, Modifier.Const); string name = null; childNode.StartLocation = this.t.Location; base.Expect(1); name = this.t.val; base.Expect(3); this.Expr(out expression); childNode.Variables.Add(new VariableDeclaration(name, expression)); while (this.la.kind == 14) { base.lexer.NextToken(); base.Expect(1); name = this.t.val; base.Expect(3); this.Expr(out expression); childNode.Variables.Add(new VariableDeclaration(name, expression)); } base.Expect(11); base.compilationUnit.AddChild(childNode); } else if (this.IsLocalVarDecl()) { this.LocalVariableDecl(out stmt); base.Expect(11); base.compilationUnit.AddChild(stmt); } else if (this.StartOf(0x17)) { this.EmbeddedStatement(out stmt); base.compilationUnit.AddChild(stmt); } else { base.SynErr(0xa8); } if (stmt != null) { stmt.StartLocation = location; stmt.EndLocation = this.t.EndLocation; } }
public LocalTreeNode( LocalVariableDeclaration local ) : base( TreeViewImage.Field, local ) { this.Text = local.Type.ToString(); }
public static TypeReference type(this LocalVariableDeclaration localVariableDeclaration) { return(localVariableDeclaration.TypeReference); }
private void Process_Local_Variable_Declaration(StringBuilder sb, LocalVariableDeclaration declaration) { if (declaration.Variables == null || declaration.Variables.Count == 0) return; if (declaration.IsConst) sb.Append("const "); VariableDeclarator firstVar = ((VariableDeclarator)declaration.Variables[0]); sb.Append(FormatterUtility.FormatDataType(firstVar, document, controller)); sb.AppendFormat(" {0}", firstVar.Name.Text); if (firstVar.Initializer != null) { sb.Append(" = "); sb.Append(FormatExpression(firstVar.Initializer)); } for (int i = 1; i < declaration.Variables.Count; i++) { sb.Append(", "); VariableDeclarator varDec = declaration.Variables[i] as VariableDeclarator; if (varDec == null) throw new ParserException("Not expecting node of type " + declaration.Variables[i].GetType() + " in local variable declaration."); Process_Variable_Declarator(sb, varDec); } }
protected TypeReference GetIdentifierType(Expression ex, INode parent) { string identifier = ((IdentifierExpression)ex).Identifier; TypeReference typeReference = null; INode parentScope = parent; while (parentScope != null) { if (parentScope is CastExpression) { CastExpression castExpression = (CastExpression)parentScope; if (castExpression.Expression is IdentifierExpression && ((IdentifierExpression)castExpression.Expression).Identifier == identifier) { return(castExpression.CastTo); } } else if (parentScope is BlockStatement) { typeReference = GetTypeInLocalVariables((BlockStatement)parentScope, identifier); if (typeReference != null) { return(typeReference); } } else if (parentScope is CatchClause) { string catchVar = ((CatchClause)parentScope).VariableName; if (catchVar == identifier) { return(((CatchClause)parentScope).TypeReference); } } else if (parentScope is ForStatement) { ForStatement forStatement = (ForStatement)parentScope; if (forStatement.Initializers.Count > 0) { Statement variable = (Statement)forStatement.Initializers[0]; if (variable is LocalVariableDeclaration) { LocalVariableDeclaration localVariable = (LocalVariableDeclaration)variable; if (((VariableDeclaration)localVariable.Variables[0]).Name == identifier) { return(localVariable.TypeReference); } } } } else if (parentScope is ForeachStatement || parentScope is MethodDeclaration || parentScope is ConstructorDeclaration || parentScope is TypeDeclaration) { break; } parentScope = parentScope.Parent; } if (parentScope is ConstructorDeclaration || parentScope is MethodDeclaration) { BlockStatement body = GetBody(parentScope); List <ParameterDeclarationExpression> parameters = ((ParametrizedNode)parentScope).Parameters; TypeDeclaration typeDeclaration = AstUtil.GetParentOfType(parentScope, typeof(TypeDeclaration)) as TypeDeclaration; typeReference = GetTypeInLocalVariables(body, identifier); if (typeReference == null) { typeReference = GetTypeInArguments(parameters, identifier); } if (typeReference == null) { typeReference = GetTypeInMembers(typeDeclaration, identifier); } if (typeReference == null) { typeReference = GetStaticClassType(identifier, ex.Parent); } } else if (parentScope is TypeDeclaration) { typeReference = GetTypeInMembers((TypeDeclaration)parentScope, identifier); if (typeReference == null) { typeReference = GetStaticClassType(identifier, ex.Parent); } } else if (parentScope is ForeachStatement) { string foreachVarName = ((ForeachStatement)parentScope).VariableName; TypeReference foreachVariableType = ((ForeachStatement)parentScope).TypeReference; if (identifier == foreachVarName) { return(foreachVariableType); } else { typeReference = GetType(ex, parentScope.Parent); } } if (typeReference != null && typeReference.Parent == null) { typeReference.Parent = parent; } return(typeReference); }
/** * Returns the local variable declaration stated within the <code>for</code> * statement's initializer. * * @return The <code>for</code> statement's initializer variable * declaration or <code>null</code> if <code>getForInitType() != * ForInitType.VAR_DECL</code>. */ public LocalVariableDeclaration getInitializerVarDecl() { if (mForInitType != ForInitType.VAR_DECL) { return null; } if (mInitVarDecl == null) { mInitVarDecl = new AST2LocalVariableDeclaration((AST2JSOMTree) getTreeNode().GetChild(0).GetChild(0), getTokenRewriteStream()); } return mInitVarDecl; }
/// <summary> /// Generates code that converts an object to the target type. /// </summary> public static Expression ConvertTo(string name, Expression value, TypeReference targetType, BlockStatement blockStatement, Statement failStmt, bool allowNull, bool isOptional, int seqNum) { if (Utility.IsType(targetType, "System.Object")) { // no conversion needed return(value); } string temp_local_name = String.Format("tmp{0}", seqNum); // create the "conversion failed" block ArrayList parameters = new ArrayList(); parameters.Add(value); parameters.Add(new PrimitiveExpression(targetType.Type, targetType.Type)); parameters.Add(new PrimitiveExpression(name, name)); // the statements to execute when the cast failed BlockStatement fail_block = new BlockStatement(); fail_block.AddChild(new StatementExpression(new InvocationExpression(new FieldReferenceExpression( new TypeReferenceExpression("PhpException"), "InvalidImplicitCast"), parameters))); fail_block.AddChild(failStmt); // try to determine whether the target type is a reference or value type Type system_type = Type.GetType(targetType.SystemType); if (system_type != null && system_type.IsValueType) { // value type LocalVariableDeclaration temp_local; if (isOptional) { temp_local = new LocalVariableDeclaration(targetType); temp_local.Variables.Add(new VariableDeclaration(temp_local_name)); blockStatement.AddChild(temp_local); BlockStatement new_block_stmt = new BlockStatement(); IfElseStatement opt_stmt = new IfElseStatement(new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new FieldReferenceExpression( new IdentifierExpression("Arg"), "Default")), new_block_stmt, new StatementExpression(new AssignmentExpression(new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, new ObjectCreateExpression(targetType, new ArrayList())))); blockStatement.AddChild(opt_stmt); blockStatement = new_block_stmt; } IfElseStatement if_stmt = new IfElseStatement(new UnaryOperatorExpression( new ParenthesizedExpression(new BinaryOperatorExpression(value, BinaryOperatorType.TypeCheck, new TypeReferenceExpression(targetType))), UnaryOperatorType.Not), fail_block); blockStatement.AddChild(if_stmt); if (isOptional) { blockStatement.AddChild(new StatementExpression(new AssignmentExpression( new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, new CastExpression(targetType, value)))); return(new IdentifierExpression(temp_local_name)); } else { return(new CastExpression(targetType, value)); } } else { // probably a reference type LocalVariableDeclaration temp_local = new LocalVariableDeclaration(targetType); blockStatement.AddChild(temp_local); if (isOptional) { // first check for Arg.Default temp_local.Variables.Add( new VariableDeclaration(temp_local_name, new PrimitiveExpression(null, String.Empty))); BlockStatement new_block_stmt = new BlockStatement(); IfElseStatement opt_stmt = new IfElseStatement(new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new FieldReferenceExpression( new IdentifierExpression("Arg"), "Default")), new_block_stmt); blockStatement.AddChild(opt_stmt); blockStatement = new_block_stmt; // then perform the as-cast blockStatement.AddChild(new StatementExpression(new AssignmentExpression( new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, CreateAsCastExpression(value, targetType)))); } else { // perform the as-cast temp_local.Variables.Add( new VariableDeclaration(temp_local_name, CreateAsCastExpression(value, targetType))); } IfElseStatement if_stmt = new IfElseStatement(new BinaryOperatorExpression( new IdentifierExpression(temp_local_name), BinaryOperatorType.Equality, new PrimitiveExpression(null, String.Empty)), fail_block); if (allowNull) { // throw only if the value is not of targetType and not null if_stmt.Condition = new BinaryOperatorExpression(if_stmt.Condition, BinaryOperatorType.LogicalAnd, new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new PrimitiveExpression(null, String.Empty))); } blockStatement.AddChild(if_stmt); return(new IdentifierExpression(temp_local_name)); } }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { base.VisitLocalVariableDeclaration(localVariableDeclaration, data); if ((localVariableDeclaration.Modifier & Modifiers.Static) == Modifiers.Static) { INode parent = localVariableDeclaration.Parent; while (parent != null && !IsTypeLevel(parent)) { parent = parent.Parent; } if (parent != null) { INode type = parent.Parent; if (type != null) { int pos = type.Children.IndexOf(parent); if (pos >= 0) { FieldDeclaration field = new FieldDeclaration(null); field.TypeReference = localVariableDeclaration.TypeReference; field.Modifier = Modifiers.Static; field.Fields = localVariableDeclaration.Variables; new PrefixFieldsVisitor(field.Fields, "static_" + GetTypeLevelEntityName(parent) + "_").Run(parent); type.Children.Insert(pos + 1, field); RemoveCurrentNode(); } } } } return null; }
void LocalDeclarationStatement( #line 2724 "VBNET.ATG" out Statement statement) { #line 2726 "VBNET.ATG" ModifierList m = new ModifierList(); LocalVariableDeclaration localVariableDeclaration; bool dimfound = false; while (la.kind == 75 || la.kind == 92 || la.kind == 189) { if (la.kind == 75) { lexer.NextToken(); #line 2732 "VBNET.ATG" m.Add(Modifiers.Const, t.Location); } else if (la.kind == 189) { lexer.NextToken(); #line 2733 "VBNET.ATG" m.Add(Modifiers.Static, t.Location); } else { lexer.NextToken(); #line 2734 "VBNET.ATG" dimfound = true; } } #line 2737 "VBNET.ATG" if(dimfound && (m.Modifier & Modifiers.Const) != 0) { Error("Dim is not allowed on constants."); } if(m.isNone && dimfound == false) { Error("Const, Dim or Static expected"); } localVariableDeclaration = new LocalVariableDeclaration(m.Modifier); localVariableDeclaration.StartLocation = t.Location; VariableDeclarator( #line 2748 "VBNET.ATG" localVariableDeclaration.Variables); while (la.kind == 12) { lexer.NextToken(); VariableDeclarator( #line 2749 "VBNET.ATG" localVariableDeclaration.Variables); } #line 2751 "VBNET.ATG" statement = localVariableDeclaration; }
/// <summary> /// Generates code that converts an object to the target type. /// </summary> public static Expression ConvertTo(string name, Expression value, TypeReference targetType, BlockStatement blockStatement, Statement failStmt, bool allowNull, bool isOptional, int seqNum) { if (Utility.IsType(targetType, "System.Object")) { // no conversion needed return value; } string temp_local_name = String.Format("tmp{0}", seqNum); // create the "conversion failed" block ArrayList parameters = new ArrayList(); parameters.Add(value); parameters.Add(new PrimitiveExpression(targetType.Type, targetType.Type)); parameters.Add(new PrimitiveExpression(name, name)); // the statements to execute when the cast failed BlockStatement fail_block = new BlockStatement(); fail_block.AddChild(new StatementExpression(new InvocationExpression(new FieldReferenceExpression( new TypeReferenceExpression("PhpException"), "InvalidImplicitCast"), parameters))); fail_block.AddChild(failStmt); // try to determine whether the target type is a reference or value type Type system_type = Type.GetType(targetType.SystemType); if (system_type != null && system_type.IsValueType) { // value type LocalVariableDeclaration temp_local; if (isOptional) { temp_local = new LocalVariableDeclaration(targetType); temp_local.Variables.Add(new VariableDeclaration(temp_local_name)); blockStatement.AddChild(temp_local); BlockStatement new_block_stmt = new BlockStatement(); IfElseStatement opt_stmt = new IfElseStatement(new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new FieldReferenceExpression( new IdentifierExpression("Arg"), "Default")), new_block_stmt, new StatementExpression(new AssignmentExpression(new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, new ObjectCreateExpression(targetType, new ArrayList())))); blockStatement.AddChild(opt_stmt); blockStatement = new_block_stmt; } IfElseStatement if_stmt = new IfElseStatement(new UnaryOperatorExpression( new ParenthesizedExpression(new BinaryOperatorExpression(value, BinaryOperatorType.TypeCheck, new TypeReferenceExpression(targetType))), UnaryOperatorType.Not), fail_block); blockStatement.AddChild(if_stmt); if (isOptional) { blockStatement.AddChild(new StatementExpression(new AssignmentExpression( new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, new CastExpression(targetType, value)))); return new IdentifierExpression(temp_local_name); } else return new CastExpression(targetType, value); } else { // probably a reference type LocalVariableDeclaration temp_local = new LocalVariableDeclaration(targetType); blockStatement.AddChild(temp_local); if (isOptional) { // first check for Arg.Default temp_local.Variables.Add( new VariableDeclaration(temp_local_name, new PrimitiveExpression(null, String.Empty))); BlockStatement new_block_stmt = new BlockStatement(); IfElseStatement opt_stmt = new IfElseStatement(new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new FieldReferenceExpression( new IdentifierExpression("Arg"), "Default")), new_block_stmt); blockStatement.AddChild(opt_stmt); blockStatement = new_block_stmt; // then perform the as-cast blockStatement.AddChild(new StatementExpression(new AssignmentExpression( new IdentifierExpression(temp_local_name), AssignmentOperatorType.Assign, CreateAsCastExpression(value, targetType)))); } else { // perform the as-cast temp_local.Variables.Add( new VariableDeclaration(temp_local_name, CreateAsCastExpression(value, targetType))); } IfElseStatement if_stmt = new IfElseStatement(new BinaryOperatorExpression( new IdentifierExpression(temp_local_name), BinaryOperatorType.Equality, new PrimitiveExpression(null, String.Empty)), fail_block); if (allowNull) { // throw only if the value is not of targetType and not null if_stmt.Condition = new BinaryOperatorExpression(if_stmt.Condition, BinaryOperatorType.LogicalAnd, new BinaryOperatorExpression( value, BinaryOperatorType.InEquality, new PrimitiveExpression(null, String.Empty))); } blockStatement.AddChild(if_stmt); return new IdentifierExpression(temp_local_name); } }
/// <summary> /// Creates an argless stub for the specified implementation method. /// </summary> private MethodDeclaration CreateArgless(MethodDeclaration template) { MethodDeclaration method = new MethodDeclaration(template.Name, Modifier.Public | Modifier.Static, new TypeReference("Object"), new List<ParameterDeclarationExpression>(), new List<AttributeSection>()); method.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("Object"), "instance")); method.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("PhpStack"), "stack")); method.Body = new BlockStatement(); // stack.CalleeName = <template name> method.Body.AddChild(new StatementExpression(new AssignmentExpression(new FieldReferenceExpression( new IdentifierExpression("stack"), "CalleeName"), AssignmentOperatorType.Assign, new PrimitiveExpression(template.Name, template.Name)))); // peek arguments int arg_counter = 0, shift = 0; foreach (ParameterDeclarationExpression param in template.Parameters) { arg_counter++; LocalVariableDeclaration arg_local = new LocalVariableDeclaration(new TypeReference("Object")); Expression initializer; if (Utility.IsDecoratedByAttribute(param.Attributes, "PHP.Core.ThisAttribute")) { initializer = new IdentifierExpression("instance"); shift++; } else { ArrayList peek_params = new ArrayList(); peek_params.Add(new PrimitiveExpression(arg_counter - shift, String.Empty)); if (Utility.IsDecoratedByAttribute(param.Attributes, Utility.OptionalAttrType)) { initializer = new InvocationExpression(new FieldReferenceExpression( new IdentifierExpression("stack"), "PeekValueOptional"), peek_params); } else { initializer = new InvocationExpression(new FieldReferenceExpression( new IdentifierExpression("stack"), "PeekValue"), peek_params); } } arg_local.Variables.Add(new VariableDeclaration(String.Format("arg{0}", arg_counter), initializer)); method.Body.AddChild(arg_local); } // stack.RemoveFrame() method.Body.AddChild(new StatementExpression(new InvocationExpression(new FieldReferenceExpression( new IdentifierExpression("stack"), "RemoveFrame"), new ArrayList()))); // return [invoke argfull] ArrayList argfull_params = new ArrayList(); argfull_params.Add(new FieldReferenceExpression(new IdentifierExpression("stack"), "Context")); for (int i = 0; i < template.Parameters.Count; i++) { argfull_params.Add(new IdentifierExpression(String.Format("arg{0}", i + 1))); } if ((template.Modifier & Modifier.Static) == Modifier.Static) { method.Body.AddChild(new ReturnStatement(new InvocationExpression(new IdentifierExpression( template.Name), argfull_params))); } else { method.Body.AddChild(new ReturnStatement(new InvocationExpression( new FieldReferenceExpression(new ParenthesizedExpression( new CastExpression(new TypeReference(((TypeDeclaration)template.Parent).Name), new IdentifierExpression("instance"))), template.Name), argfull_params))); } Utility.MakeNonBrowsable(method); return method; }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { List <Change> result = new List <Change> (); ExtractMethodParameters param = (ExtractMethodParameters)prop; TextEditorData data = options.GetTextEditorData(); INRefactoryASTProvider provider = options.GetASTProvider(); IResolver resolver = options.GetResolver(); ICSharpCode.NRefactory.Ast.INode node = Analyze(options, param, false); if (param.VariablesToGenerate.Count > 0) { TextReplaceChange varGen = new TextReplaceChange(); varGen.Description = GettextCatalog.GetString("Generate some temporary variables"); varGen.FileName = options.Document.FileName; LineSegment line = data.Document.GetLine(Math.Max(0, data.Document.OffsetToLineNumber(data.SelectionRange.Offset) - 1)); varGen.Offset = line.Offset + line.EditableLength; varGen.InsertedText = Environment.NewLine + options.GetWhitespaces(line.Offset); foreach (VariableDescriptor var in param.VariablesToGenerate) { TypeReference tr = options.ShortenTypeName(var.ReturnType).ConvertToTypeReference(); varGen.InsertedText += provider.OutputNode(options.Dom, new LocalVariableDeclaration(new VariableDeclaration(var.Name, null, tr))).Trim(); } result.Add(varGen); } InvocationExpression invocation = new InvocationExpression(new IdentifierExpression(param.Name)); foreach (VariableDescriptor var in param.Parameters) { if (!param.OneChangedVariable && param.ChangedVariables.Contains(var.Name)) { FieldDirection fieldDirection = FieldDirection.Ref; VariableDescriptor outsideVar = null; if (param.VariablesOutside.TryGetValue(var.Name, out outsideVar) && (var.GetsAssigned || param.VariablesToGenerate.Where(v => v.Name == var.Name).Any())) { if (!outsideVar.GetsAssigned) { fieldDirection = FieldDirection.Out; } } invocation.Arguments.Add(new DirectionExpression(fieldDirection, new IdentifierExpression(var.Name))); } else { invocation.Arguments.Add(new IdentifierExpression(var.Name)); } } // string mimeType = DesktopService.GetMimeTypeForUri (options.Document.FileName); TypeReference returnType = new TypeReference("System.Void", true); ICSharpCode.NRefactory.Ast.INode outputNode; if (param.OneChangedVariable) { string name = param.ChangedVariables.First(); returnType = options.ShortenTypeName(param.Variables.Find(v => v.Name == name).ReturnType).ConvertToTypeReference(); if (param.OutsideVariableList.Any(v => v.Name == name && !v.IsDefined)) { LocalVariableDeclaration varDecl = new LocalVariableDeclaration(returnType); varDecl.Variables.Add(new VariableDeclaration(name, invocation)); outputNode = varDecl; } else { outputNode = new ExpressionStatement(new AssignmentExpression(new IdentifierExpression(name), ICSharpCode.NRefactory.Ast.AssignmentOperatorType.Assign, invocation)); } } else { outputNode = node is BlockStatement ? (ICSharpCode.NRefactory.Ast.INode) new ExpressionStatement(invocation) : invocation; } TextReplaceChange replacement = new TextReplaceChange(); replacement.Description = string.Format(GettextCatalog.GetString("Substitute selected statement(s) with call to {0}"), param.Name); replacement.FileName = options.Document.FileName; replacement.Offset = options.Document.TextEditor.SelectionStartPosition; replacement.RemovedChars = options.Document.TextEditor.SelectionEndPosition - options.Document.TextEditor.SelectionStartPosition; replacement.MoveCaretToReplace = true; LineSegment line1 = data.Document.GetLineByOffset(options.Document.TextEditor.SelectionEndPosition); if (options.Document.TextEditor.SelectionEndPosition == line1.Offset) { if (line1.Offset > 0) { LineSegment line2 = data.Document.GetLineByOffset(line1.Offset - 1); replacement.RemovedChars -= line2.DelimiterLength; } } replacement.InsertedText = options.GetWhitespaces(options.Document.TextEditor.SelectionStartPosition) + provider.OutputNode(options.Dom, outputNode).Trim(); result.Add(replacement); TextReplaceChange insertNewMethod = new TextReplaceChange(); insertNewMethod.FileName = options.Document.FileName; insertNewMethod.Description = string.Format(GettextCatalog.GetString("Create new method {0} from selected statement(s)"), param.Name); insertNewMethod.RemovedChars = param.InsertionPoint.LineBefore == NewLineInsertion.Eol ? 0 : param.InsertionPoint.Location.Column; insertNewMethod.Offset = data.Document.LocationToOffset(param.InsertionPoint.Location) - insertNewMethod.RemovedChars; ExtractMethodAstTransformer transformer = new ExtractMethodAstTransformer(param.VariablesToGenerate); node.AcceptVisitor(transformer, null); if (!param.OneChangedVariable && node is Expression) { ResolveResult resolveResult = resolver.Resolve(new ExpressionResult("(" + provider.OutputNode(options.Dom, node) + ")"), new DomLocation(options.Document.TextEditor.CursorLine, options.Document.TextEditor.CursorColumn)); if (resolveResult.ResolvedType != null) { returnType = options.ShortenTypeName(resolveResult.ResolvedType).ConvertToTypeReference(); } } MethodDeclaration methodDecl = new MethodDeclaration(); methodDecl.Name = param.Name; methodDecl.Modifier = param.Modifiers; methodDecl.TypeReference = returnType; if (!param.ReferencesMember) { methodDecl.Modifier |= ICSharpCode.NRefactory.Ast.Modifiers.Static; } if (node is BlockStatement) { methodDecl.Body = new BlockStatement(); methodDecl.Body.AddChild(new EmptyStatement()); if (param.OneChangedVariable) { methodDecl.Body.AddChild(new ReturnStatement(new IdentifierExpression(param.ChangedVariables.First()))); } } else if (node is Expression) { methodDecl.Body = new BlockStatement(); methodDecl.Body.AddChild(new ReturnStatement(node as Expression)); } foreach (VariableDescriptor var in param.VariablesToDefine) { BlockStatement block = methodDecl.Body; LocalVariableDeclaration varDecl = new LocalVariableDeclaration(options.ShortenTypeName(var.ReturnType).ConvertToTypeReference()); varDecl.Variables.Add(new VariableDeclaration(var.Name)); block.Children.Insert(0, varDecl); } foreach (VariableDescriptor var in param.Parameters) { TypeReference typeReference = options.ShortenTypeName(var.ReturnType).ConvertToTypeReference(); ParameterDeclarationExpression pde = new ParameterDeclarationExpression(typeReference, var.Name); if (!param.OneChangedVariable) { if (param.ChangedVariables.Contains(var.Name)) { pde.ParamModifier = ICSharpCode.NRefactory.Ast.ParameterModifiers.Ref; } if (param.VariablesToGenerate.Where(v => v.Name == var.Name).Any()) { pde.ParamModifier = ICSharpCode.NRefactory.Ast.ParameterModifiers.Out; } VariableDescriptor outsideVar = null; if (var.GetsAssigned && param.VariablesOutside.TryGetValue(var.Name, out outsideVar)) { if (!outsideVar.GetsAssigned) { pde.ParamModifier = ICSharpCode.NRefactory.Ast.ParameterModifiers.Out; } } } methodDecl.Parameters.Add(pde); } string indent = options.GetIndent(param.DeclaringMember); StringBuilder methodText = new StringBuilder(); switch (param.InsertionPoint.LineBefore) { case NewLineInsertion.Eol: methodText.AppendLine(); break; case NewLineInsertion.BlankLine: methodText.Append(indent); methodText.AppendLine(); break; } if (param.GenerateComment) { methodText.Append(indent); methodText.AppendLine("/// <summary>"); methodText.Append(indent); methodText.AppendLine("/// TODO: write a comment."); methodText.Append(indent); methodText.AppendLine("/// </summary>"); Ambience ambience = AmbienceService.GetAmbienceForFile(options.Document.FileName); foreach (ParameterDeclarationExpression pde in methodDecl.Parameters) { methodText.Append(indent); methodText.Append("/// <param name=\""); methodText.Append(pde.ParameterName); methodText.Append("\"> A "); methodText.Append(ambience.GetString(pde.TypeReference.ConvertToReturnType(), OutputFlags.IncludeGenerics | OutputFlags.UseFullName)); methodText.Append(" </param>"); methodText.AppendLine(); } if (methodDecl.TypeReference.Type != "System.Void") { methodText.Append(indent); methodText.AppendLine("/// <returns>"); methodText.Append(indent); methodText.Append("/// A "); methodText.AppendLine(ambience.GetString(methodDecl.TypeReference.ConvertToReturnType(), OutputFlags.IncludeGenerics | OutputFlags.UseFullName)); methodText.Append(indent); methodText.AppendLine("/// </returns>"); } } methodText.Append(indent); if (node is BlockStatement) { string text = provider.OutputNode(options.Dom, methodDecl, indent).Trim(); int emptyStatementMarker = text.LastIndexOf(';'); if (param.OneChangedVariable) { emptyStatementMarker = text.LastIndexOf(';', emptyStatementMarker - 1); } StringBuilder sb = new StringBuilder(); sb.Append(text.Substring(0, emptyStatementMarker)); sb.Append(AddIndent(param.Text, indent + "\t")); sb.Append(text.Substring(emptyStatementMarker + 1)); methodText.Append(sb.ToString()); } else { methodText.Append(provider.OutputNode(options.Dom, methodDecl, options.GetIndent(param.DeclaringMember)).Trim()); } switch (param.InsertionPoint.LineAfter) { case NewLineInsertion.Eol: methodText.AppendLine(); break; case NewLineInsertion.BlankLine: methodText.AppendLine(); methodText.AppendLine(); methodText.Append(indent); break; } insertNewMethod.InsertedText = methodText.ToString(); result.Add(insertNewMethod); return(result); }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { for (int i = 0; i < localVariableDeclaration.Variables.Count; ++i) { VariableDeclaration varDecl = (VariableDeclaration)localVariableDeclaration.Variables[i]; AddVariable(localVariableDeclaration.GetTypeForVariable(i), varDecl.Name, localVariableDeclaration.StartLocation, CurrentEndLocation, (localVariableDeclaration.Modifier & Modifiers.Const) == Modifiers.Const, false, varDecl.Initializer, null); } return base.VisitLocalVariableDeclaration(localVariableDeclaration, data); }
public LocalVariableDeclarationExpressionInterpreter(LocalVariableDeclaration localVariableDeclaration) { this.localVariableDeclaration = localVariableDeclaration; }
public virtual object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { throw new global::System.NotImplementedException("LocalVariableDeclaration"); }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { localVariableDeclarations.Add(localVariableDeclaration); return(base.VisitLocalVariableDeclaration(localVariableDeclaration, data)); }
private void LocalVariableDecl(out ICSharpCode.NRefactory.Parser.AST.Statement stmt) { TypeReference reference; VariableDeclaration var = null; this.Type(out reference); LocalVariableDeclaration declaration2 = new LocalVariableDeclaration(reference); declaration2.StartLocation = this.t.Location; this.LocalVariableDeclarator(out var); declaration2.Variables.Add(var); while (this.la.kind == 14) { base.lexer.NextToken(); this.LocalVariableDeclarator(out var); declaration2.Variables.Add(var); } stmt = declaration2; }
void LocalVariableDecl( #line 1456 "cs.ATG" out Statement stmt) { #line 1458 "cs.ATG" TypeReference type; VariableDeclaration var = null; LocalVariableDeclaration localVariableDeclaration; Location startPos = la.Location; Type( #line 1464 "cs.ATG" out type); #line 1464 "cs.ATG" localVariableDeclaration = new LocalVariableDeclaration(type); localVariableDeclaration.StartLocation = startPos; LocalVariableDeclarator( #line 1465 "cs.ATG" out var); #line 1465 "cs.ATG" SafeAdd(localVariableDeclaration, localVariableDeclaration.Variables, var); while (la.kind == 14) { lexer.NextToken(); LocalVariableDeclarator( #line 1466 "cs.ATG" out var); #line 1466 "cs.ATG" SafeAdd(localVariableDeclaration, localVariableDeclaration.Variables, var); } #line 1467 "cs.ATG" stmt = localVariableDeclaration; stmt.EndLocation = t.EndLocation; }
public sealed override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { BeginVisit(localVariableDeclaration); object result = TrackedVisitLocalVariableDeclaration(localVariableDeclaration, data); EndVisit(localVariableDeclaration); return result; }
void Statement() { #line 1480 "cs.ATG" TypeReference type; Expression expr; Statement stmt = null; Location startPos = la.Location; while (!(StartOf(29))) {SynErr(192); lexer.NextToken(); } if ( #line 1489 "cs.ATG" IsLabel()) { Identifier(); #line 1489 "cs.ATG" compilationUnit.AddChild(new LabelStatement(t.val)); Expect(9); Statement(); } else if (la.kind == 60) { lexer.NextToken(); Type( #line 1492 "cs.ATG" out type); #line 1492 "cs.ATG" LocalVariableDeclaration var = new LocalVariableDeclaration(type, Modifiers.Const); string ident = null; var.StartLocation = t.Location; Identifier(); #line 1493 "cs.ATG" ident = t.val; Location varStart = t.Location; Expect(3); Expr( #line 1494 "cs.ATG" out expr); #line 1496 "cs.ATG" SafeAdd(var, var.Variables, new VariableDeclaration(ident, expr) { StartLocation = varStart, EndLocation = t.EndLocation, TypeReference = type }); while (la.kind == 14) { lexer.NextToken(); Identifier(); #line 1502 "cs.ATG" ident = t.val; Expect(3); Expr( #line 1502 "cs.ATG" out expr); #line 1504 "cs.ATG" SafeAdd(var, var.Variables, new VariableDeclaration(ident, expr) { StartLocation = varStart, EndLocation = t.EndLocation, TypeReference = type }); } Expect(11); #line 1510 "cs.ATG" var.EndLocation = t.EndLocation; compilationUnit.AddChild(var); } else if ( #line 1513 "cs.ATG" IsLocalVarDecl()) { LocalVariableDecl( #line 1513 "cs.ATG" out stmt); Expect(11); #line 1513 "cs.ATG" compilationUnit.AddChild(stmt); } else if (StartOf(30)) { EmbeddedStatement( #line 1515 "cs.ATG" out stmt); #line 1515 "cs.ATG" compilationUnit.AddChild(stmt); } else SynErr(193); #line 1521 "cs.ATG" if (stmt != null) { stmt.StartLocation = startPos; stmt.EndLocation = t.EndLocation; } }
public virtual object TrackedVisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { return base.VisitLocalVariableDeclaration(localVariableDeclaration, data); }
public virtual object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { Debug.Assert((localVariableDeclaration != null)); Debug.Assert((localVariableDeclaration.TypeReference != null)); Debug.Assert((localVariableDeclaration.Variables != null)); localVariableDeclaration.TypeReference.AcceptVisitor(this, data); foreach (VariableDeclaration o in localVariableDeclaration.Variables) { Debug.Assert(o != null); o.AcceptVisitor(this, data); } return null; }
/** * Call back method that must be called as soon as the given <code> * LocalVariableDeclaration</code> object has been traversed. * * @param pLocalVariableDeclaration The <code>LocalVariableDeclaration * </code> object that has just been * traversed. */ public void actionPerformed( LocalVariableDeclaration pLocalVariableDeclaration) { // Nothing to do. }
public override List <Change> PerformChanges(RefactoringOptions options, object prop) { varCount = 0; selectionStart = selectionEnd = -1; List <Change> result = new List <Change> (); IResolver resolver = options.GetResolver(); INRefactoryASTProvider provider = options.GetASTProvider(); if (resolver == null || provider == null) { return(result); } TextEditorData data = options.GetTextEditorData(); if (data == null) { return(result); } ResolveResult resolveResult; LineSegment lineSegment; ICSharpCode.NRefactory.Ast.CompilationUnit unit = provider.ParseFile(data.Document.Text); MonoDevelop.Refactoring.ExtractMethod.VariableLookupVisitor visitor = new MonoDevelop.Refactoring.ExtractMethod.VariableLookupVisitor(resolver, new DomLocation(data.Caret.Line, data.Caret.Column)); if (options.ResolveResult == null) { LoggingService.LogError("resolve result == null:" + options.ResolveResult); return(result); } IMember callingMember = options.ResolveResult.CallingMember; if (callingMember != null) { visitor.MemberLocation = new Location(callingMember.Location.Column, callingMember.Location.Line); } unit.AcceptVisitor(visitor, null); if (data.IsSomethingSelected) { ExpressionResult expressionResult = new ExpressionResult(data.SelectedText.Trim()); if (expressionResult.Expression.Contains(" ") || expressionResult.Expression.Contains("\t")) { expressionResult.Expression = "(" + expressionResult.Expression + ")"; } resolveResult = resolver.Resolve(expressionResult, new DomLocation(data.Caret.Line, data.Caret.Column)); if (resolveResult == null) { return(result); } IReturnType resolvedType = resolveResult.ResolvedType; if (resolvedType == null || string.IsNullOrEmpty(resolvedType.Name)) { resolvedType = DomReturnType.Object; } varName = CreateVariableName(resolvedType, visitor); TypeReference returnType; if (resolveResult.ResolvedType == null || string.IsNullOrEmpty(resolveResult.ResolvedType.Name)) { returnType = new TypeReference("var"); returnType.IsKeyword = true; } else { returnType = options.ShortenTypeName(resolveResult.ResolvedType).ConvertToTypeReference(); } options.ParseMember(resolveResult.CallingMember); TextReplaceChange insert = new TextReplaceChange(); insert.FileName = options.Document.FileName; insert.Description = GettextCatalog.GetString("Insert variable declaration"); LocalVariableDeclaration varDecl = new LocalVariableDeclaration(returnType); varDecl.Variables.Add(new VariableDeclaration(varName, provider.ParseExpression(data.SelectedText))); GetContainingEmbeddedStatementVisitor blockVisitor = new GetContainingEmbeddedStatementVisitor(); blockVisitor.LookupLocation = new Location(data.Caret.Column + 1, data.Caret.Line + 1); unit.AcceptVisitor(blockVisitor, null); StatementWithEmbeddedStatement containing = blockVisitor.ContainingStatement as StatementWithEmbeddedStatement; if (containing != null && !(containing.EmbeddedStatement is BlockStatement)) { insert.Offset = data.Document.LocationToOffset(containing.StartLocation.Line - 1, containing.StartLocation.Column - 1); lineSegment = data.Document.GetLineByOffset(insert.Offset); insert.RemovedChars = data.Document.LocationToOffset(containing.EndLocation.Line - 1, containing.EndLocation.Column - 1) - insert.Offset; BlockStatement insertedBlock = new BlockStatement(); insertedBlock.AddChild(varDecl); insertedBlock.AddChild(containing.EmbeddedStatement); containing.EmbeddedStatement = insertedBlock; insert.InsertedText = provider.OutputNode(options.Dom, containing, options.GetWhitespaces(lineSegment.Offset)).TrimStart(); int offset, length; if (SearchSubExpression(insert.InsertedText, data.SelectedText, 0, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { insert.InsertedText = insert.InsertedText.Substring(0, offset) + varName + insert.InsertedText.Substring(offset + length); insertOffset = insert.Offset + offset; } } } else if (blockVisitor.ContainingStatement is IfElseStatement) { IfElseStatement ifElse = blockVisitor.ContainingStatement as IfElseStatement; insert.Offset = data.Document.LocationToOffset(blockVisitor.ContainingStatement.StartLocation.Line - 1, blockVisitor.ContainingStatement.StartLocation.Column - 1); lineSegment = data.Document.GetLineByOffset(insert.Offset); insert.RemovedChars = data.Document.LocationToOffset(blockVisitor.ContainingStatement.EndLocation.Line - 1, blockVisitor.ContainingStatement.EndLocation.Column - 1) - insert.Offset; BlockStatement insertedBlock = new BlockStatement(); insertedBlock.AddChild(varDecl); if (blockVisitor.ContainsLocation(ifElse.TrueStatement[0])) { insertedBlock.AddChild(ifElse.TrueStatement[0]); ifElse.TrueStatement[0] = insertedBlock; } else { insertedBlock.AddChild(ifElse.FalseStatement[0]); ifElse.FalseStatement[0] = insertedBlock; } insert.InsertedText = provider.OutputNode(options.Dom, blockVisitor.ContainingStatement, options.GetWhitespaces(lineSegment.Offset)); int offset, length; if (SearchSubExpression(insert.InsertedText, provider.OutputNode(options.Dom, insertedBlock), 0, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { if (SearchSubExpression(insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) { insert.InsertedText = insert.InsertedText.Substring(0, offset) + varName + insert.InsertedText.Substring(offset + length); insertOffset = insert.Offset + offset; } } } } else { lineSegment = data.Document.GetLine(data.Caret.Line); insert.Offset = lineSegment.Offset; insert.InsertedText = options.GetWhitespaces(lineSegment.Offset) + provider.OutputNode(options.Dom, varDecl) + Environment.NewLine; insertOffset = insert.Offset + options.GetWhitespaces(lineSegment.Offset).Length + provider.OutputNode(options.Dom, varDecl.TypeReference).Length + " ".Length; TextReplaceChange replace = new TextReplaceChange(); replace.FileName = options.Document.FileName; replace.Offset = data.SelectionRange.Offset; replace.RemovedChars = data.SelectionRange.Length; replace.InsertedText = varName; result.Add(replace); replaceOffset = replace.Offset; if (insert.Offset < replaceOffset) { replaceOffset += insert.InsertedText.Length - insert.RemovedChars; } varCount++; } result.Add(insert); varCount++; selectionStart = insert.Offset; return(result); } lineSegment = data.Document.GetLine(data.Caret.Line); string line = data.Document.GetTextAt(lineSegment); Expression expression = provider.ParseExpression(line); if (expression == null) { return(result); } resolveResult = resolver.Resolve(new ExpressionResult(line), new DomLocation(options.Document.TextEditor.CursorLine, options.Document.TextEditor.CursorColumn)); if (resolveResult.ResolvedType != null && !string.IsNullOrEmpty(resolveResult.ResolvedType.FullName)) { TextReplaceChange insert = new TextReplaceChange(); insert.FileName = options.Document.FileName; insert.Description = GettextCatalog.GetString("Insert variable declaration"); insert.Offset = lineSegment.Offset + options.GetWhitespaces(lineSegment.Offset).Length; varName = CreateVariableName(resolveResult.ResolvedType, visitor); LocalVariableDeclaration varDecl = new LocalVariableDeclaration(options.ShortenTypeName(resolveResult.ResolvedType).ConvertToTypeReference()); varDecl.Variables.Add(new VariableDeclaration(varName, expression)); insert.RemovedChars = expression.EndLocation.Column - 1; insert.InsertedText = provider.OutputNode(options.Dom, varDecl); insertOffset = insert.Offset + provider.OutputNode(options.Dom, varDecl.TypeReference).Length + " ".Length; result.Add(insert); varCount++; int idx = 0; while (idx < insert.InsertedText.Length - varName.Length) { if (insert.InsertedText.Substring(idx, varName.Length) == varName && (idx == 0 || insert.InsertedText[idx - 1] == ' ') && (idx == insert.InsertedText.Length - varName.Length - 1 || insert.InsertedText[idx + varName.Length] == ' ')) { selectionStart = insert.Offset + idx; selectionEnd = selectionStart + varName.Length; break; } idx++; } } return(result); }
protected override IEnumerable <string> GenerateCode(INRefactoryASTProvider astProvider, string indent, List <IBaseMember> includedMembers) { // Genereate Equals MethodDeclaration methodDeclaration = new MethodDeclaration(); methodDeclaration.Name = "Equals"; methodDeclaration.TypeReference = DomReturnType.Bool.ConvertToTypeReference(); methodDeclaration.Modifier = ICSharpCode.NRefactory.Ast.Modifiers.Public | ICSharpCode.NRefactory.Ast.Modifiers.Override; methodDeclaration.Body = new BlockStatement(); methodDeclaration.Parameters.Add(new ParameterDeclarationExpression(DomReturnType.Object.ConvertToTypeReference(), "obj")); IdentifierExpression paramId = new IdentifierExpression("obj"); IfElseStatement ifStatement = new IfElseStatement(null); ifStatement.Condition = new BinaryOperatorExpression(paramId, BinaryOperatorType.Equality, new PrimitiveExpression(null)); ifStatement.TrueStatement.Add(new ReturnStatement(new PrimitiveExpression(false))); methodDeclaration.Body.AddChild(ifStatement); ifStatement = new IfElseStatement(null); List <Expression> arguments = new List <Expression> (); arguments.Add(new ThisReferenceExpression()); arguments.Add(paramId); ifStatement.Condition = new InvocationExpression(new IdentifierExpression("ReferenceEquals"), arguments); ifStatement.TrueStatement.Add(new ReturnStatement(new PrimitiveExpression(true))); methodDeclaration.Body.AddChild(ifStatement); ifStatement = new IfElseStatement(null); ifStatement.Condition = new BinaryOperatorExpression(new InvocationExpression(new MemberReferenceExpression(paramId, "GetType")), BinaryOperatorType.InEquality, new TypeOfExpression(new TypeReference(Options.EnclosingType.Name))); ifStatement.TrueStatement.Add(new ReturnStatement(new PrimitiveExpression(false))); methodDeclaration.Body.AddChild(ifStatement); LocalVariableDeclaration varDecl = new LocalVariableDeclaration(new DomReturnType(Options.EnclosingType).ConvertToTypeReference()); varDecl.Variables.Add(new VariableDeclaration("other", new CastExpression(varDecl.TypeReference, paramId, CastType.Cast))); methodDeclaration.Body.AddChild(varDecl); IdentifierExpression otherId = new IdentifierExpression("other"); Expression binOp = null; foreach (IMember member in includedMembers) { Expression right = new BinaryOperatorExpression(new IdentifierExpression(member.Name), BinaryOperatorType.Equality, new MemberReferenceExpression(otherId, member.Name)); if (binOp == null) { binOp = right; } else { binOp = new BinaryOperatorExpression(binOp, BinaryOperatorType.LogicalAnd, right); } } methodDeclaration.Body.AddChild(new ReturnStatement(binOp)); yield return(astProvider.OutputNode(this.Options.Dom, methodDeclaration, indent)); methodDeclaration = new MethodDeclaration(); methodDeclaration.Name = "GetHashCode"; methodDeclaration.TypeReference = DomReturnType.Int32.ConvertToTypeReference(); methodDeclaration.Modifier = ICSharpCode.NRefactory.Ast.Modifiers.Public | ICSharpCode.NRefactory.Ast.Modifiers.Override; methodDeclaration.Body = new BlockStatement(); binOp = null; foreach (IMember member in includedMembers) { Expression right; right = new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression(member.Name), "GetHashCode")); IType type = Options.Dom.SearchType(member, member.ReturnType); if (type != null && type.ClassType != MonoDevelop.Projects.Dom.ClassType.Struct && type.ClassType != MonoDevelop.Projects.Dom.ClassType.Enum) { right = new ParenthesizedExpression(new ConditionalExpression(new BinaryOperatorExpression(new IdentifierExpression(member.Name), BinaryOperatorType.InEquality, new PrimitiveExpression(null)), right, new PrimitiveExpression(0))); } if (binOp == null) { binOp = right; } else { binOp = new BinaryOperatorExpression(binOp, BinaryOperatorType.ExclusiveOr, right); } } BlockStatement uncheckedBlock = new BlockStatement(); uncheckedBlock.AddChild(new ReturnStatement(binOp)); methodDeclaration.Body.AddChild(new UncheckedStatement(uncheckedBlock)); yield return(astProvider.OutputNode(this.Options.Dom, methodDeclaration, indent)); }
void EmbeddedStatement( #line 2755 "VBNET.ATG" out Statement statement) { #line 2757 "VBNET.ATG" Statement embeddedStatement = null; statement = null; Expression expr = null; string name = String.Empty; List<Expression> p = null; if (la.kind == 107) { lexer.NextToken(); #line 2763 "VBNET.ATG" ExitType exitType = ExitType.None; switch (la.kind) { case 195: { lexer.NextToken(); #line 2765 "VBNET.ATG" exitType = ExitType.Sub; break; } case 114: { lexer.NextToken(); #line 2767 "VBNET.ATG" exitType = ExitType.Function; break; } case 171: { lexer.NextToken(); #line 2769 "VBNET.ATG" exitType = ExitType.Property; break; } case 95: { lexer.NextToken(); #line 2771 "VBNET.ATG" exitType = ExitType.Do; break; } case 111: { lexer.NextToken(); #line 2773 "VBNET.ATG" exitType = ExitType.For; break; } case 203: { lexer.NextToken(); #line 2775 "VBNET.ATG" exitType = ExitType.Try; break; } case 216: { lexer.NextToken(); #line 2777 "VBNET.ATG" exitType = ExitType.While; break; } case 182: { lexer.NextToken(); #line 2779 "VBNET.ATG" exitType = ExitType.Select; break; } default: SynErr(273); break; } #line 2781 "VBNET.ATG" statement = new ExitStatement(exitType); } else if (la.kind == 203) { TryStatement( #line 2782 "VBNET.ATG" out statement); } else if (la.kind == 76) { lexer.NextToken(); #line 2783 "VBNET.ATG" ContinueType continueType = ContinueType.None; if (la.kind == 95 || la.kind == 111 || la.kind == 216) { if (la.kind == 95) { lexer.NextToken(); #line 2783 "VBNET.ATG" continueType = ContinueType.Do; } else if (la.kind == 111) { lexer.NextToken(); #line 2783 "VBNET.ATG" continueType = ContinueType.For; } else { lexer.NextToken(); #line 2783 "VBNET.ATG" continueType = ContinueType.While; } } #line 2783 "VBNET.ATG" statement = new ContinueStatement(continueType); } else if (la.kind == 200) { lexer.NextToken(); if (StartOf(29)) { Expr( #line 2785 "VBNET.ATG" out expr); } #line 2785 "VBNET.ATG" statement = new ThrowStatement(expr); } else if (la.kind == 180) { lexer.NextToken(); if (StartOf(29)) { Expr( #line 2787 "VBNET.ATG" out expr); } #line 2787 "VBNET.ATG" statement = new ReturnStatement(expr); } else if (la.kind == 196) { lexer.NextToken(); Expr( #line 2789 "VBNET.ATG" out expr); EndOfStmt(); Block( #line 2789 "VBNET.ATG" out embeddedStatement); Expect(100); Expect(196); #line 2790 "VBNET.ATG" statement = new LockStatement(expr, embeddedStatement); } else if (la.kind == 174) { lexer.NextToken(); Identifier(); #line 2792 "VBNET.ATG" name = t.val; if (la.kind == 25) { lexer.NextToken(); if (StartOf(37)) { ArgumentList( #line 2793 "VBNET.ATG" out p); } Expect(26); } #line 2795 "VBNET.ATG" statement = new RaiseEventStatement(name, p); } else if (la.kind == 218) { WithStatement( #line 2798 "VBNET.ATG" out statement); } else if (la.kind == 43) { lexer.NextToken(); #line 2800 "VBNET.ATG" Expression handlerExpr = null; Expr( #line 2801 "VBNET.ATG" out expr); Expect(12); Expr( #line 2801 "VBNET.ATG" out handlerExpr); #line 2803 "VBNET.ATG" statement = new AddHandlerStatement(expr, handlerExpr); } else if (la.kind == 178) { lexer.NextToken(); #line 2806 "VBNET.ATG" Expression handlerExpr = null; Expr( #line 2807 "VBNET.ATG" out expr); Expect(12); Expr( #line 2807 "VBNET.ATG" out handlerExpr); #line 2809 "VBNET.ATG" statement = new RemoveHandlerStatement(expr, handlerExpr); } else if (la.kind == 216) { lexer.NextToken(); Expr( #line 2812 "VBNET.ATG" out expr); EndOfStmt(); Block( #line 2813 "VBNET.ATG" out embeddedStatement); Expect(100); Expect(216); #line 2815 "VBNET.ATG" statement = new DoLoopStatement(expr, embeddedStatement, ConditionType.While, ConditionPosition.Start); } else if (la.kind == 95) { lexer.NextToken(); #line 2820 "VBNET.ATG" ConditionType conditionType = ConditionType.None; if (la.kind == 209 || la.kind == 216) { WhileOrUntil( #line 2823 "VBNET.ATG" out conditionType); Expr( #line 2823 "VBNET.ATG" out expr); EndOfStmt(); Block( #line 2824 "VBNET.ATG" out embeddedStatement); Expect(138); #line 2827 "VBNET.ATG" statement = new DoLoopStatement(expr, embeddedStatement, conditionType == ConditionType.While ? ConditionType.DoWhile : conditionType, ConditionPosition.Start); } else if (la.kind == 1 || la.kind == 11) { EndOfStmt(); Block( #line 2834 "VBNET.ATG" out embeddedStatement); Expect(138); if (la.kind == 209 || la.kind == 216) { WhileOrUntil( #line 2835 "VBNET.ATG" out conditionType); Expr( #line 2835 "VBNET.ATG" out expr); } #line 2837 "VBNET.ATG" statement = new DoLoopStatement(expr, embeddedStatement, conditionType, ConditionPosition.End); } else SynErr(274); } else if (la.kind == 111) { lexer.NextToken(); #line 2842 "VBNET.ATG" Expression group = null; TypeReference typeReference; string typeName; Location startLocation = t.Location; if (la.kind == 97) { lexer.NextToken(); LoopControlVariable( #line 2849 "VBNET.ATG" out typeReference, out typeName); Expect(125); Expr( #line 2850 "VBNET.ATG" out group); EndOfStmt(); Block( #line 2851 "VBNET.ATG" out embeddedStatement); Expect(149); if (StartOf(29)) { Expr( #line 2852 "VBNET.ATG" out expr); } #line 2854 "VBNET.ATG" statement = new ForeachStatement(typeReference, typeName, group, embeddedStatement, expr); statement.StartLocation = startLocation; statement.EndLocation = t.EndLocation; } else if (StartOf(38)) { #line 2865 "VBNET.ATG" Expression start = null; Expression end = null; Expression step = null; Expression variableExpr = null; Expression nextExpr = null; List<Expression> nextExpressions = null; if ( #line 2872 "VBNET.ATG" IsLoopVariableDeclaration()) { LoopControlVariable( #line 2873 "VBNET.ATG" out typeReference, out typeName); } else { #line 2875 "VBNET.ATG" typeReference = null; typeName = null; SimpleExpr( #line 2876 "VBNET.ATG" out variableExpr); } Expect(10); Expr( #line 2878 "VBNET.ATG" out start); Expect(201); Expr( #line 2878 "VBNET.ATG" out end); if (la.kind == 190) { lexer.NextToken(); Expr( #line 2878 "VBNET.ATG" out step); } EndOfStmt(); Block( #line 2879 "VBNET.ATG" out embeddedStatement); Expect(149); if (StartOf(29)) { Expr( #line 2882 "VBNET.ATG" out nextExpr); #line 2884 "VBNET.ATG" nextExpressions = new List<Expression>(); nextExpressions.Add(nextExpr); while (la.kind == 12) { lexer.NextToken(); Expr( #line 2887 "VBNET.ATG" out nextExpr); #line 2887 "VBNET.ATG" nextExpressions.Add(nextExpr); } } #line 2890 "VBNET.ATG" statement = new ForNextStatement { TypeReference = typeReference, VariableName = typeName, LoopVariableExpression = variableExpr, Start = start, End = end, Step = step, EmbeddedStatement = embeddedStatement, NextExpressions = nextExpressions }; } else SynErr(275); } else if (la.kind == 105) { lexer.NextToken(); Expr( #line 2903 "VBNET.ATG" out expr); #line 2903 "VBNET.ATG" statement = new ErrorStatement(expr); } else if (la.kind == 176) { lexer.NextToken(); #line 2905 "VBNET.ATG" bool isPreserve = false; if (la.kind == 169) { lexer.NextToken(); #line 2905 "VBNET.ATG" isPreserve = true; } ReDimClause( #line 2906 "VBNET.ATG" out expr); #line 2908 "VBNET.ATG" ReDimStatement reDimStatement = new ReDimStatement(isPreserve); statement = reDimStatement; SafeAdd(reDimStatement, reDimStatement.ReDimClauses, expr as InvocationExpression); while (la.kind == 12) { lexer.NextToken(); ReDimClause( #line 2912 "VBNET.ATG" out expr); #line 2913 "VBNET.ATG" SafeAdd(reDimStatement, reDimStatement.ReDimClauses, expr as InvocationExpression); } } else if (la.kind == 104) { lexer.NextToken(); Expr( #line 2917 "VBNET.ATG" out expr); #line 2919 "VBNET.ATG" EraseStatement eraseStatement = new EraseStatement(); if (expr != null) { SafeAdd(eraseStatement, eraseStatement.Expressions, expr);} while (la.kind == 12) { lexer.NextToken(); Expr( #line 2922 "VBNET.ATG" out expr); #line 2922 "VBNET.ATG" if (expr != null) { SafeAdd(eraseStatement, eraseStatement.Expressions, expr); } } #line 2923 "VBNET.ATG" statement = eraseStatement; } else if (la.kind == 191) { lexer.NextToken(); #line 2925 "VBNET.ATG" statement = new StopStatement(); } else if ( #line 2927 "VBNET.ATG" la.kind == Tokens.If) { Expect(122); #line 2928 "VBNET.ATG" Location ifStartLocation = t.Location; Expr( #line 2928 "VBNET.ATG" out expr); if (la.kind == 199) { lexer.NextToken(); } if (la.kind == 1 || la.kind == 11) { EndOfStmt(); Block( #line 2931 "VBNET.ATG" out embeddedStatement); #line 2933 "VBNET.ATG" IfElseStatement ifStatement = new IfElseStatement(expr, embeddedStatement); ifStatement.StartLocation = ifStartLocation; Location elseIfStart; while (la.kind == 99 || #line 2939 "VBNET.ATG" IsElseIf()) { if ( #line 2939 "VBNET.ATG" IsElseIf()) { Expect(98); #line 2939 "VBNET.ATG" elseIfStart = t.Location; Expect(122); } else { lexer.NextToken(); #line 2940 "VBNET.ATG" elseIfStart = t.Location; } #line 2942 "VBNET.ATG" Expression condition = null; Statement block = null; Expr( #line 2943 "VBNET.ATG" out condition); if (la.kind == 199) { lexer.NextToken(); } EndOfStmt(); Block( #line 2944 "VBNET.ATG" out block); #line 2946 "VBNET.ATG" ElseIfSection elseIfSection = new ElseIfSection(condition, block); elseIfSection.StartLocation = elseIfStart; elseIfSection.EndLocation = t.Location; elseIfSection.Parent = ifStatement; ifStatement.ElseIfSections.Add(elseIfSection); } if (la.kind == 98) { lexer.NextToken(); EndOfStmt(); Block( #line 2955 "VBNET.ATG" out embeddedStatement); #line 2957 "VBNET.ATG" ifStatement.FalseStatement.Add(embeddedStatement); } Expect(100); Expect(122); #line 2961 "VBNET.ATG" ifStatement.EndLocation = t.Location; statement = ifStatement; } else if (StartOf(39)) { #line 2966 "VBNET.ATG" IfElseStatement ifStatement = new IfElseStatement(expr); ifStatement.StartLocation = ifStartLocation; SingleLineStatementList( #line 2969 "VBNET.ATG" ifStatement.TrueStatement); if (la.kind == 98) { lexer.NextToken(); if (StartOf(39)) { SingleLineStatementList( #line 2972 "VBNET.ATG" ifStatement.FalseStatement); } } #line 2974 "VBNET.ATG" ifStatement.EndLocation = t.Location; statement = ifStatement; } else SynErr(276); } else if (la.kind == 182) { lexer.NextToken(); if (la.kind == 61) { lexer.NextToken(); } Expr( #line 2977 "VBNET.ATG" out expr); EndOfStmt(); #line 2978 "VBNET.ATG" List<SwitchSection> selectSections = new List<SwitchSection>(); Statement block = null; while (la.kind == 61) { #line 2982 "VBNET.ATG" List<CaseLabel> caseClauses = null; Location caseLocation = la.Location; lexer.NextToken(); CaseClauses( #line 2983 "VBNET.ATG" out caseClauses); if ( #line 2983 "VBNET.ATG" IsNotStatementSeparator()) { lexer.NextToken(); } EndOfStmt(); #line 2985 "VBNET.ATG" SwitchSection selectSection = new SwitchSection(caseClauses); selectSection.StartLocation = caseLocation; Block( #line 2988 "VBNET.ATG" out block); #line 2990 "VBNET.ATG" selectSection.Children = block.Children; selectSection.EndLocation = t.EndLocation; selectSections.Add(selectSection); } #line 2996 "VBNET.ATG" statement = new SwitchStatement(expr, selectSections); Expect(100); Expect(182); } else if (la.kind == 157) { #line 2999 "VBNET.ATG" OnErrorStatement onErrorStatement = null; OnErrorStatement( #line 3000 "VBNET.ATG" out onErrorStatement); #line 3000 "VBNET.ATG" statement = onErrorStatement; } else if (la.kind == 119) { #line 3001 "VBNET.ATG" GotoStatement goToStatement = null; GotoStatement( #line 3002 "VBNET.ATG" out goToStatement); #line 3002 "VBNET.ATG" statement = goToStatement; } else if (la.kind == 179) { #line 3003 "VBNET.ATG" ResumeStatement resumeStatement = null; ResumeStatement( #line 3004 "VBNET.ATG" out resumeStatement); #line 3004 "VBNET.ATG" statement = resumeStatement; } else if (StartOf(38)) { #line 3007 "VBNET.ATG" Expression val = null; AssignmentOperatorType op; bool mustBeAssignment = la.kind == Tokens.Plus || la.kind == Tokens.Minus || la.kind == Tokens.Not || la.kind == Tokens.Times; SimpleExpr( #line 3013 "VBNET.ATG" out expr); if (StartOf(40)) { AssignmentOperator( #line 3015 "VBNET.ATG" out op); Expr( #line 3015 "VBNET.ATG" out val); #line 3015 "VBNET.ATG" expr = new AssignmentExpression(expr, op, val); } else if (la.kind == 1 || la.kind == 11 || la.kind == 98) { #line 3016 "VBNET.ATG" if (mustBeAssignment) Error("error in assignment."); } else SynErr(277); #line 3019 "VBNET.ATG" // a field reference expression that stands alone is a // invocation expression without parantheses and arguments if(expr is MemberReferenceExpression || expr is IdentifierExpression) { expr = new InvocationExpression(expr); } statement = new ExpressionStatement(expr); } else if (la.kind == 60) { lexer.NextToken(); SimpleExpr( #line 3026 "VBNET.ATG" out expr); #line 3026 "VBNET.ATG" statement = new ExpressionStatement(expr); } else if (la.kind == 211) { lexer.NextToken(); #line 3028 "VBNET.ATG" Statement block; if ( #line 3029 "VBNET.ATG" Peek(1).kind == Tokens.As) { #line 3030 "VBNET.ATG" LocalVariableDeclaration resourceAquisition = new LocalVariableDeclaration(Modifiers.None); VariableDeclarator( #line 3031 "VBNET.ATG" resourceAquisition.Variables); while (la.kind == 12) { lexer.NextToken(); VariableDeclarator( #line 3033 "VBNET.ATG" resourceAquisition.Variables); } Block( #line 3035 "VBNET.ATG" out block); #line 3037 "VBNET.ATG" statement = new UsingStatement(resourceAquisition, block); } else if (StartOf(29)) { Expr( #line 3039 "VBNET.ATG" out expr); Block( #line 3040 "VBNET.ATG" out block); #line 3041 "VBNET.ATG" statement = new UsingStatement(new ExpressionStatement(expr), block); } else SynErr(278); Expect(100); Expect(211); } else if (StartOf(41)) { LocalDeclarationStatement( #line 3044 "VBNET.ATG" out statement); } else SynErr(279); }
void ConvertForStatement(ForStatement forStatement) { // ForStatement -> ForNextStatement when for-loop is simple // only the following forms of the for-statement are allowed: // for (TypeReference name = start; name < oneAfterEnd; name += step) // for (name = start; name < oneAfterEnd; name += step) // for (TypeReference name = start; name <= end; name += step) // for (name = start; name <= end; name += step) // for (TypeReference name = start; name > oneAfterEnd; name -= step) // for (name = start; name > oneAfterEnd; name -= step) // for (TypeReference name = start; name >= end; name -= step) // for (name = start; name >= end; name -= step) // check if the form is valid and collect TypeReference, name, start, end and step if (forStatement.Initializers.Count != 1) { return; } if (forStatement.Iterator.Count != 1) { return; } StatementExpression statement = forStatement.Iterator[0] as StatementExpression; if (statement == null) { return; } AssignmentExpression iterator = statement.Expression as AssignmentExpression; if (iterator == null || (iterator.Op != AssignmentOperatorType.Add && iterator.Op != AssignmentOperatorType.Subtract)) { return; } IdentifierExpression iteratorIdentifier = iterator.Left as IdentifierExpression; if (iteratorIdentifier == null) { return; } PrimitiveExpression stepExpression = iterator.Right as PrimitiveExpression; if (stepExpression == null || !(stepExpression.Value is int)) { return; } int step = (int)stepExpression.Value; if (iterator.Op == AssignmentOperatorType.Subtract) { step = -step; } BinaryOperatorExpression condition = forStatement.Condition as BinaryOperatorExpression; if (condition == null || !(condition.Left is IdentifierExpression)) { return; } if ((condition.Left as IdentifierExpression).Identifier != iteratorIdentifier.Identifier) { return; } Expression end; if (iterator.Op == AssignmentOperatorType.Subtract) { if (condition.Op == BinaryOperatorType.GreaterThanOrEqual) { end = condition.Right; } else if (condition.Op == BinaryOperatorType.GreaterThan) { end = Expression.AddInteger(condition.Right, 1); } else { return; } } else { if (condition.Op == BinaryOperatorType.LessThanOrEqual) { end = condition.Right; } else if (condition.Op == BinaryOperatorType.LessThan) { end = Expression.AddInteger(condition.Right, -1); } else { return; } } Expression start; TypeReference typeReference = null; LocalVariableDeclaration varDecl = forStatement.Initializers[0] as LocalVariableDeclaration; if (varDecl != null) { if (varDecl.Variables.Count != 1 || varDecl.Variables[0].Name != iteratorIdentifier.Identifier || varDecl.Variables[0].Initializer == null) { return; } typeReference = varDecl.GetTypeForVariable(0); start = varDecl.Variables[0].Initializer; } else { statement = forStatement.Initializers[0] as StatementExpression; if (statement == null) { return; } AssignmentExpression assign = statement.Expression as AssignmentExpression; if (assign == null || assign.Op != AssignmentOperatorType.Assign) { return; } if (!(assign.Left is IdentifierExpression)) { return; } if ((assign.Left as IdentifierExpression).Identifier != iteratorIdentifier.Identifier) { return; } start = assign.Right; } ForNextStatement forNextStatement = new ForNextStatement(typeReference, iteratorIdentifier.Identifier, start, end, (step == 1) ? null : new PrimitiveExpression(step, step.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)), forStatement.EmbeddedStatement, null); Statement.Replace(forStatement, forNextStatement); }
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) { CodeVariableDeclarationStatement declStmt = null; for (int i = 0; i < localVariableDeclaration.Variables.Count; ++i) { CodeTypeReference type = ConvType(localVariableDeclaration.GetTypeForVariable(i) ?? new TypeReference("System.Object", true)); VariableDeclaration var = (VariableDeclaration)localVariableDeclaration.Variables[i]; if (!var.Initializer.IsNull) { declStmt = new CodeVariableDeclarationStatement(type, var.Name, (CodeExpression)((INode)var.Initializer).AcceptVisitor(this, data)); } else { declStmt = new CodeVariableDeclarationStatement(type, var.Name); } variables.Add(declStmt); AddStmt(declStmt); } return declStmt; }