public static void RunTransformationsUntil(AstNode node, Predicate<IAstTransform> abortCondition, DecompilerContext context) { if (node == null) return; for (int i = 0; i < 4; i++) { context.CancellationToken.ThrowIfCancellationRequested(); if (Options.ReduceAstJumps) { node.AcceptVisitor(new Transforms.Ast.RemoveGotos(), null); node.AcceptVisitor(new Transforms.Ast.RemoveDeadLabels(), null); } if (Options.ReduceAstLoops) { node.AcceptVisitor(new Transforms.Ast.RestoreLoop(), null); } if (Options.ReduceAstOther) { node.AcceptVisitor(new Transforms.Ast.RemoveEmptyElseBody(), null); } } foreach (var transform in CreatePipeline(context)) { context.CancellationToken.ThrowIfCancellationRequested(); if (abortCondition != null && abortCondition(transform)) return; transform.Run(node); } }
public void Run(AstNode compilationUnit) { // First determine all the namespaces that need to be imported: compilationUnit.AcceptVisitor(new FindRequiredImports(this), null); importedNamespaces.Add("System"); // always import System, even when not necessary if (context.Settings.UsingDeclarations) { // Now add using declarations for those namespaces: foreach (string ns in GetNamespacesInReverseOrder()) { // we go backwards (OrderByDescending) through the list of namespaces because we insert them backwards // (always inserting at the start of the list) string[] parts = ns.Split('.'); AstType nsType = new SimpleType(parts[0]).WithAnnotation(TextTokenType.NamespacePart); for (int i = 1; i < parts.Length; i++) { nsType = new MemberType { Target = nsType, MemberNameToken = Identifier.Create(parts[i]).WithAnnotation(TextTokenType.NamespacePart) }.WithAnnotation(TextTokenType.NamespacePart); } compilationUnit.InsertChildAfter(null, new UsingDeclaration { Import = nsType }, SyntaxTree.MemberRole); } } if (!context.Settings.FullyQualifyAmbiguousTypeNames) { return; } if (context.CurrentModule != null) { FindAmbiguousTypeNames(context.CurrentModule.Types, internalsVisible: true); var asmDict = new Dictionary <AssemblyDef, List <AssemblyDef> >(AssemblyEqualityComparer.Instance); foreach (var r in context.CurrentModule.GetAssemblyRefs()) { AssemblyDef d = context.CurrentModule.Context.AssemblyResolver.Resolve(r, context.CurrentModule); if (d == null) { continue; } List <AssemblyDef> list; if (!asmDict.TryGetValue(d, out list)) { asmDict.Add(d, list = new List <AssemblyDef>()); } list.Add(d); } foreach (var list in asmDict.Values) { FindAmbiguousTypeNames(GetTypes(list), internalsVisible: false); } } // verify that the SimpleTypes refer to the correct type (no ambiguities) compilationUnit.AcceptVisitor(new FullyQualifyAmbiguousTypeNamesVisitor(this), null); }
public void Run(AstNode rootNode, TransformContext context) { // First determine all the namespaces that need to be imported: var requiredImports = new FindRequiredImports(context); rootNode.AcceptVisitor(requiredImports); var usingScope = new UsingScope(); rootNode.AddAnnotation(usingScope); if (context.Settings.UsingDeclarations) { var insertionPoint = rootNode.Children.LastOrDefault(n => n is PreProcessorDirective p && p.Type == PreProcessorDirectiveType.Define); // Now add using declarations for those namespaces: foreach (string ns in requiredImports.ImportedNamespaces.OrderByDescending(n => n)) { Debug.Assert(context.RequiredNamespacesSuperset.Contains(ns), $"Should not insert using declaration for namespace that is missing from the superset: {ns}"); // we go backwards (OrderByDescending) through the list of namespaces because we insert them backwards // (always inserting at the start of the list) string[] parts = ns.Split('.'); AstType nsType = new SimpleType(parts[0]); for (int i = 1; i < parts.Length; i++) { nsType = new MemberType { Target = nsType, MemberName = parts[i] }; } if (context.Settings.FullyQualifyAmbiguousTypeNames) { var reference = nsType.ToTypeReference(NameLookupMode.TypeInUsingDeclaration) as TypeOrNamespaceReference; if (reference != null) { usingScope.Usings.Add(reference); } } rootNode.InsertChildAfter(insertionPoint, new UsingDeclaration { Import = nsType }, SyntaxTree.MemberRole); } } if (!context.Settings.FullyQualifyAmbiguousTypeNames) { return; } // verify that the SimpleTypes refer to the correct type (no ambiguities) rootNode.AcceptVisitor(new FullyQualifyAmbiguousTypeNamesVisitor(context, usingScope)); }
public void Run(AstNode compilationUnit) { // First determine all the namespaces that need to be imported: compilationUnit.AcceptVisitor(new FindRequiredImports(this), null); importedNamespaces.Add("System"); // always import System, even when not necessary if (context.Settings.UsingDeclarations) { // Now add using declarations for those namespaces: foreach (string ns in importedNamespaces.OrderByDescending(n => n)) { // we go backwards (OrderByDescending) through the list of namespaces because we insert them backwards // (always inserting at the start of the list) string[] parts = ns.Split('.'); AstType nsType = new SimpleType(parts[0]); for (int i = 1; i < parts.Length; i++) { nsType = new MemberType { Target = nsType, MemberName = parts[i] }; } compilationUnit.InsertChildAfter(null, new UsingDeclaration { Import = nsType }, SyntaxTree.MemberRole); } } if (!context.Settings.FullyQualifyAmbiguousTypeNames) { return; } FindAmbiguousTypeNames(context.CurrentModule, internalsVisible: true); if (context.CurrentModule is ModuleDefMD) { foreach (var r in ((ModuleDefMD)context.CurrentModule).GetAssemblyRefs()) { var d = context.CurrentModule.Context.AssemblyResolver.Resolve(r, context.CurrentModule); if (d != null) { FindAmbiguousTypeNames(d.ManifestModule, internalsVisible: false); } } } // verify that the SimpleTypes refer to the correct type (no ambiguities) compilationUnit.AcceptVisitor(new FullyQualifyAmbiguousTypeNamesVisitor(this), null); }
public override async void Execute(EditorRefactoringContext context) { SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false); ICompilation compilation = await context.GetCompilationAsync().ConfigureAwait(false); CSharpFullParseInformation info = await context.GetParseInformationAsync().ConfigureAwait(false) as CSharpFullParseInformation; EntityDeclaration node = (EntityDeclaration)st.GetNodeAt(context.CaretLocation, n => n is TypeDeclaration || n is DelegateDeclaration); IDocument document = context.Editor.Document; FileName newFileName = FileName.Create(Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(node.Name))); string header = CopyFileHeader(document, info); string footer = CopyFileEnd(document, info); AstNode newNode = node.Clone(); foreach (var ns in node.Ancestors.OfType <NamespaceDeclaration>()) { var newNS = new NamespaceDeclaration(ns.Name); newNS.Members.AddRange(ns.Children.Where(ch => ch is UsingDeclaration || ch is UsingAliasDeclaration || ch is ExternAliasDeclaration).Select(usingDecl => usingDecl.Clone())); newNS.AddMember(newNode); newNode = newNS; } var topLevelUsings = st.Children.Where(ch => ch is UsingDeclaration || ch is UsingAliasDeclaration || ch is ExternAliasDeclaration); StringBuilder newCode = new StringBuilder(header); CSharpOutputVisitor visitor = new CSharpOutputVisitor(new StringWriter(newCode), FormattingOptionsFactory.CreateSharpDevelop()); foreach (var topLevelUsing in topLevelUsings) { topLevelUsing.AcceptVisitor(visitor); } newNode.AcceptVisitor(visitor); newCode.AppendLine(footer); IViewContent viewContent = FileService.NewFile(newFileName, newCode.ToString()); viewContent.PrimaryFile.SaveToDisk(newFileName); // now that the code is saved in the other file, remove it from the original document RemoveExtractedNode(context, node); IProject project = (IProject)compilation.GetProject(); if (project != null) { FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile); projectItem.FileName = newFileName; ProjectService.AddProjectItem(project, projectItem); FileService.FireFileCreated(newFileName, false); project.Save(); ProjectBrowserPad.RefreshViewAsync(); } }
private int GetConditionComplexity(AstNode condition) { var conditionsVisitor = CreateConditionsVisitor(); condition.AcceptVisitor(conditionsVisitor); return(conditionsVisitor.Count); }
public virtual void AddLocals(IEnumerable <ParameterDeclaration> declarations, AstNode statement) { declarations.ToList().ForEach(item => { var vName = this.AddLocal(item.Name, item.Type); if (item.ParameterModifier == ParameterModifier.Out || item.ParameterModifier == ParameterModifier.Ref) { this.Emitter.LocalsMap[item.Name] = vName + ".v"; } else { this.Emitter.LocalsMap[item.Name] = vName; } }); 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 Exception("Only local variables can be passed by reference"); } } }
public InvocationExpression VisitAndCompare(AstNode expression, Func <InvocationExpression, bool> predicate) { _assignmentExpression = null; expression.AcceptVisitor(this, predicate); return(_assignmentExpression); }
protected IAsyncStep WriteAwaiter(AstNode node) { var index = System.Array.IndexOf(this.Emitter.AsyncBlock.AwaitExpressions, node) + 1; this.Write("$task" + index + " = "); var oldValue = this.Emitter.ReplaceAwaiterByVar; this.Emitter.ReplaceAwaiterByVar = true; node.AcceptVisitor(this.Emitter); this.Emitter.ReplaceAwaiterByVar = oldValue; this.WriteSemiColon(); this.WriteNewLine(); this.Write("$step = " + this.Emitter.AsyncBlock.Step + ";"); this.WriteNewLine(); this.Write("$task" + index + ".continueWith($asyncBody);"); this.WriteNewLine(); this.Write("return;"); var asyncStep = this.Emitter.AsyncBlock.AddAsyncStep(index); if (this.Emitter.AsyncBlock.EmittedAsyncSteps != null) { this.Emitter.AsyncBlock.EmittedAsyncSteps.Add(asyncStep); } return(asyncStep); }
JNode _Visit(AstNode node) { if (CompilerConfig.Current.EnableLogging) { var region = node.GetRegion(); if (region != null && !region.IsEmpty) { Log.Debug(String.Format("JsCodeImporter: Visit AstNode: {0}", ToDebug(node))); } } if (BeforeConvertCsToJsAstNode != null) { BeforeConvertCsToJsAstNode(node); } var node2 = node.AcceptVisitor(this); if (node2 != null) { var ex = node2.Ex(true); if (ex.AstNode == null) { ex.AstNode = node; } } if (AfterConvertCsToJsAstNode != null) { AfterConvertCsToJsAstNode(node, node2); } return(node2); }
public static bool Analyze(AstNode node) { var obj = new IsIteratorBlockVisitor(); node.AcceptVisitor(obj); return(obj._result); }
private void WriteGetType(bool needName, IType type, AstNode node, string modifier) { if (needName) { this.Write(BridgeTypes.ToJsName(type, this.Emitter)); } else { string s; if (node != null) { var writer = this.SaveWriter(); this.NewWriter(); node.AcceptVisitor(this.Emitter); s = this.Emitter.Output.ToString(); this.RestoreWriter(writer); if (modifier == "raw") { s = s.Trim('"'); } } else { s = "null"; } this.Write(this.WriteIndentToString("Bridge.getType(" + s + ")")); } }
public void Run(AstNode compilationUnit) { if (!context.Settings.UsingDeclarations) { return; } // First determine all the namespaces that need to be imported: compilationUnit.AcceptVisitor(this, null); importedNamespaces.Add("System"); // always import System, even when not necessary // Now add using declarations for those namespaces: foreach (string ns in importedNamespaces.OrderByDescending(n => n)) { // we go backwards (OrderByDescending) through the list of namespaces because we insert them backwards // (always inserting at the start of the list) string[] parts = ns.Split('.'); AstType nsType = new SimpleType(parts[0]); for (int i = 1; i < parts.Length; i++) { nsType = new MemberType { Target = nsType, MemberName = parts[i] }; } compilationUnit.InsertChildAfter(null, new UsingDeclaration { Import = nsType }, CompilationUnit.MemberRole); } // TODO: verify that the SimpleTypes refer to the correct type (no ambiguities) }
JsNode _Visit(AstNode node) { if (CompilerConfiguration.Current.EnableLogging) { var region = node.GetRegion(); if (!region.IsEmpty) { Log.Debug(String.Format("JsCodeImporter: Visit AstNode: {0}", ToDebug(node))); } } if (BeforeConvertCsToJsAstNode != null) { BeforeConvertCsToJsAstNode(node); } var node2 = node.AcceptVisitor(this); if (node2 != null) { if (node2.Annotation <AstNode>() == null) { node2.AddAnnotation(node); } } if (AfterConvertCsToJsAstNode != null) { AfterConvertCsToJsAstNode(node, node2); } return(node2); }
static bool ContainsLocalReferences(RefactoringContext context, AstNode expr, AstNode body) { var visitor = new ExtractMethod.VariableLookupVisitor(context); body.AcceptVisitor(visitor); return(visitor.UsedVariables.Any(variable => !expr.Contains(variable.Region.Begin))); }
public static PreProcessorDirective GetEndRegion(AstNode rootNode, PreProcessorDirective regionDirective) { var visitor = new DirectiveSearcher(regionDirective); rootNode.AcceptVisitor(visitor); return(visitor.endregion); }
public void Analyze(AstNode node, IEnumerable <string> parameters = null) { _usesThis = false; _usedVariables.Clear(); _variables.Clear(); var methodDeclaration = node.GetParent <MethodDeclaration>(); if (methodDeclaration != null) { foreach (var attrSection in methodDeclaration.Attributes) { foreach (var attr in attrSection.Attributes) { var rr = this.resolver.Resolve(attr.Type); if (rr.Type.FullName == "Bridge.InitAttribute") { this._usedVariables.Add(null); return; } } } } if (parameters != null) { foreach (var parameter in parameters) { _variables.Add(parameter); } } node.AcceptVisitor(this); }
public virtual void EmitBlockOrIndentedLine(AstNode node) { bool block = node is BlockStatement; if (!block && node is IfElseStatement && node.Parent is IfElseStatement ifStatement && ifStatement.FalseStatement == node) { block = true; } if (!block) { WriteNewLine(); Indent(); } else { WriteSpace(); } node.AcceptVisitor(Emitter); if (!block) { Outdent(); } }
public static bool HasYield(AstNode node) { var visitor = new YieldSearchVisitor(); node.AcceptVisitor(visitor); return(visitor.Found); }
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"); } } }
public MemberReferenceExpression VisitAndCompare(AstNode expression, Func <MemberReferenceExpression, bool> predicate) { _memberReferenceExpression = null; expression.AcceptVisitor(this, predicate); return(_memberReferenceExpression); }
static string ToCSharp(AstNode node) { StringWriter w = new StringWriter(); node.AcceptVisitor(new OutputVisitor(w, new CSharpFormattingOptions()), null); return(w.ToString()); }
public static bool UsesNotStaticMember(BaseRefactoringContext context, AstNode node) { var visitor = new StaticVisitor(context); node.AcceptVisitor(visitor); return(visitor.UsesNonStaticMember); }
public void Run(AstNode rootNode, TransformContext context) { this.context = context; this.conversions = CSharpConversions.Get(context.TypeSystem); InitializeContext(rootNode.Annotation <UsingScope>()); rootNode.AcceptVisitor(this); }
protected NodeOutput OutputNode(int indentLevel, AstNode node, bool startWithNewLine = false) { var result = new NodeOutput(); var stringWriter = new System.IO.StringWriter(); var formatter = new TextWriterOutputFormatter(stringWriter); formatter.Indentation = indentLevel; stringWriter.NewLine = Context.EolMarker; if (startWithNewLine) { formatter.NewLine(); } var visitor = new CSharpOutputVisitor(formatter, Context.FormattingOptions); visitor.OutputStarted += (sender, e) => { result.NodeSegments [e.AstNode] = new NodeOutput.Segment(stringWriter.GetStringBuilder().Length); }; visitor.OutputFinished += (sender, e) => { result.NodeSegments [e.AstNode].EndOffset = stringWriter.GetStringBuilder().Length; }; node.AcceptVisitor(visitor, null); result.Text = stringWriter.ToString().TrimEnd(); if (node is FieldDeclaration) { result.Text += Context.EolMarker; } return(result); }
public virtual void EmitBlockOrIndentedLine(AstNode node) { bool block = node is BlockStatement; var ifStatement = node.Parent as IfElseStatement; if (!block && node is IfElseStatement && ifStatement != null && ifStatement.FalseStatement == node) { block = true; } if (!block) { this.WriteNewLine(); this.Indent(); } else { this.WriteSpace(); } node.AcceptVisitor(this.Emitter); if (!block) { this.Outdent(); } }
private void WriteGetType(bool needName, IType type, AstNode node, string modifier) { if (needName) { this.Write(BridgeTypes.ToJsName(type, this.Emitter)); } else { string s; if (node != null) { var writer = this.SaveWriter(); this.NewWriter(); node.AcceptVisitor(this.Emitter); s = this.Emitter.Output.ToString(); this.RestoreWriter(writer); if (modifier == "raw") { s = s.Trim('"'); } } else { s = "null"; } if (type.Kind == TypeKind.TypeParameter && !Helpers.IsIgnoreGeneric(((ITypeParameter)type).Owner, this.Emitter)) { s = s + ", " + type.Name; } this.Write(this.WriteIndentToString(JS.Funcs.BRIDGE_GET_TYPE + "(" + s + ")")); } }
private void WriteCustomAwaiter(AstNode node, InvocationResolveResult awaiterMethod) { var method = awaiterMethod.Member; var inline = this.Emitter.GetInline(method); if (!string.IsNullOrWhiteSpace(inline)) { var argsInfo = new ArgumentsInfo(this.Emitter, node as Expression, awaiterMethod); new InlineArgumentsBlock(this.Emitter, argsInfo, inline).Emit(); } else { if (method.IsStatic) { this.Write(BridgeTypes.ToJsName(method.DeclaringType, this.Emitter)); this.WriteDot(); this.Write(OverloadsCollection.Create(this.Emitter, method).GetOverloadName()); this.WriteOpenParentheses(); new ExpressionListBlock(this.Emitter, new Expression[] { (Expression)node }, null).Emit(); this.WriteCloseParentheses(); } else { node.AcceptVisitor(this.Emitter); this.WriteDot(); var name = OverloadsCollection.Create(this.Emitter, method).GetOverloadName(); this.Write(name); this.WriteOpenParentheses(); this.WriteCloseParentheses(); } } }
public void Run(AstNode rootNode, TransformContext context) { if (!context.Settings.DecimalConstants) { return; } rootNode.AcceptVisitor(this); }
public void Run(AstNode rootNode, TransformContext context) { this.context = context; this.usingScope = this.rootUsingScope = rootNode.Annotation <UsingScope>(); currentMember = context.DecompiledMember; SetContext(); rootNode.AcceptVisitor(this); }
public static string ToText(AstNode node) { var stringWriter = new StringWriter(); var output = new CSharpOutputVisitor(stringWriter, FormattingOptionsFactory.CreateSharpDevelop()); node.AcceptVisitor(output); return stringWriter.GetStringBuilder().ToString(); }
public static IDictionary<AstNode, ISegment> WriteNode(StringWriter writer, AstNode node, CSharpFormattingOptions policy, ICSharpCode.AvalonEdit.TextEditorOptions options) { var formatter = new SegmentTrackingOutputFormatter(writer); formatter.IndentationString = options.IndentationString; var visitor = new CSharpOutputVisitor(formatter, policy); node.AcceptVisitor(visitor); return formatter.Segments; }
protected Expression[] GetAwaiters(AstNode node) { var awaitSearch = new AwaitSearchVisitor(); node.AcceptVisitor(awaitSearch); return(awaitSearch.GetAwaitExpressions().ToArray()); }
private void VisitNestedFunction(AstNode node, AstNode body) { var parentFunction = currentFunction; currentFunction = new NestedFunctionData(parentFunction) { DefinitionNode = node, BodyNode = body, ResolveResult = (LambdaResolveResult)_resolver.Resolve(node) }; body.AcceptVisitor(this); parentFunction.NestedFunctions.Add(currentFunction); currentFunction = parentFunction; }
void AssertOutput(string expected, AstNode node, CSharpFormattingOptions policy = null) { if (policy == null) policy = FormattingOptionsFactory.CreateMono(); StringWriter w = new StringWriter(); w.NewLine = "\n"; node.AcceptVisitor(new CSharpOutputVisitor(new TextWriterOutputFormatter(w) { IndentationString = "$" }, policy)); Assert.AreEqual(expected.Replace("\r", ""), w.ToString()); }
public static bool HasContinue(AbstractEmitterBlock block, AstNode node) { var visitor = new ContinueSearchVisitor(); node.AcceptVisitor(visitor); bool has = visitor.Found; if(has) { EmitBeginContinue(block); } return has; }
public static string ToText(AstNode node) { var stringWriter = new StringWriter(); var output = new CSharpOutputVisitor(stringWriter, FormattingOptionsFactory.CreateSharpDevelop()); node.AcceptVisitor(output); return(stringWriter.GetStringBuilder().ToString()); }
void AssertOutput(AstNode node) { RemoveTokens(node); StringWriter w = new StringWriter(); w.NewLine = "\n"; node.AcceptVisitor(new CSharpOutputVisitor(TokenWriter.CreateWriterThatSetsLocationsInAST(w), FormattingOptionsFactory.CreateSharpDevelop())); var doc = new ReadOnlyDocument(w.ToString()); ConsistencyChecker.CheckMissingTokens(node, "test.cs", doc); ConsistencyChecker.CheckPositionConsistency(node, "test.cs", doc); }
public string OutputNode (ProjectDom dom, AstNode node, string indent) { StringWriter w = new StringWriter(); var policyParent = dom != null && dom.Project != null ? dom.Project.Policies : null; IEnumerable<string> types = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); CSharpFormattingPolicy codePolicy = policyParent != null ? policyParent.Get<CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types); var formatter = new TextWriterOutputFormatter(w); int col = GetColumn (indent, 0, 4); formatter.Indentation = System.Math.Max (0, col / 4); OutputVisitor visitor = new OutputVisitor (formatter, codePolicy.CreateOptions ()); node.AcceptVisitor (visitor, null); return w.ToString(); }
public Tuple<IDictionary<IVariable, VariableData>, ISet<string>> GatherVariables(AstNode node, IMethod method, ISet<string> usedNames) { _result = new Dictionary<IVariable, VariableData>(); _usedNames = new HashSet<string>(usedNames); _currentMethod = node; _variablesDeclaredInsideLoop = new HashSet<IVariable>(); if (method != null) { foreach (var p in method.Parameters) { AddVariable(p, p.IsRef || p.IsOut); } } node.AcceptVisitor(this); return Tuple.Create((IDictionary<IVariable, VariableData>)_result, (ISet<string>)_usedNames); }
public virtual void EmitBlockOrIndentedLine(AstNode node) { bool block = node is BlockStatement; if (!block) { this.WriteNewLine(); this.Indent(); } else { this.WriteSpace(); } node.AcceptVisitor(this.Emitter); if (!block) { this.Outdent(); } }
public static void RunTransformationsUntil(AstNode node, Predicate<IAstVisitor<object, object>> abortCondition) { if (node == null) return; for (int i = 0; i < 4; i++) { if (Options.ReduceAstJumps) { node.AcceptVisitor(new Transforms.Ast.RemoveGotos(), null); node.AcceptVisitor(new Transforms.Ast.RemoveDeadLabels(), null); } if (Options.ReduceAstLoops) { node.AcceptVisitor(new Transforms.Ast.RestoreLoop(), null); } if (Options.ReduceAstOther) { node.AcceptVisitor(new Transforms.Ast.RemoveEmptyElseBody(), null); node.AcceptVisitor(new Transforms.Ast.PushNegation(), null); } } foreach (var visitor in CreatePipeline()) { if (abortCondition != null && abortCondition(visitor)) return; node.AcceptVisitor(visitor, null); } }
public void Analyze(AstNode node) { _usesThis = false; _usedVariables.Clear(); node.AcceptVisitor(this); }
public static bool HasYield(AstNode node) { var visitor = new YieldSearchVisitor(); node.AcceptVisitor(visitor); return visitor.Found; }
public ISet<string> Collect (AstNode node) { variableNames.Clear (); node.AcceptVisitor (this); return variableNames; }
protected static void Print (AstNode node) { var v = new CppOutputVisitor (Console.Out, new CppFormattingOptions ()); node.AcceptVisitor (v, null); }
protected virtual void EmitUsing(AstNode expression, IEnumerable<AstNode> inner) { string temp = null; string name = null; var varInit = expression as VariableInitializer; if (varInit != null) { name = varInit.Name; this.WriteVar(); this.Write(varInit.Name); this.Write(" = "); varInit.Initializer.AcceptVisitor(this.Emitter); this.WriteSemiColon(); this.WriteNewLine(); } else if (expression is IdentifierExpression) { name = ((IdentifierExpression)expression).Identifier; } else { temp = this.GetTempVarName(); name = temp; this.Write(temp); this.Write(" = "); expression.AcceptVisitor(this.Emitter); this.WriteSemiColon(); this.WriteNewLine(); } this.WriteTry(); if (inner != null && inner.Any()) { this.BeginBlock(); this.EmitUsing(inner.First(), inner.Skip(1)); this.EndBlock(); this.WriteNewLine(); } else { bool block = this.UsingStatement.EmbeddedStatement is BlockStatement; if (!block) { this.BeginBlock(); } this.UsingStatement.EmbeddedStatement.AcceptVisitor(this.Emitter); if (!block) { this.EndBlock(); this.WriteNewLine(); } } this.WriteFinally(); this.BeginBlock(); this.Write("if (Bridge.hasValue(" + name + ")) "); this.BeginBlock(); this.Write(name); this.Write(".dispose();"); this.WriteNewLine(); this.EndBlock(); this.WriteNewLine(); this.EndBlock(); this.WriteNewLine(); if (temp != null) { this.RemoveTempVar(temp); } }
protected virtual void EmitLambda(IEnumerable<ParameterDeclaration> parameters, AstNode body, AstNode context) { AsyncBlock asyncBlock = null; this.PushLocals(); if (this.IsAsync) { if (context is LambdaExpression) { asyncBlock = new AsyncBlock(this.Emitter, (LambdaExpression)context); } else { asyncBlock = new AsyncBlock(this.Emitter, (AnonymousMethodExpression)context); } asyncBlock.InitAsyncBlock(); } var prevMap = this.BuildLocalsMap(); var prevNamesMap = this.BuildLocalsNamesMap(); this.AddLocals(parameters, body); bool block = body is BlockStatement; this.Write(""); var savedPos = this.Emitter.Output.Length; var savedThisCount = this.Emitter.ThisRefCounter; this.WriteFunction(); this.EmitMethodParameters(parameters, context); this.WriteSpace(); if (!block && !this.IsAsync) { this.BeginBlock(); } bool isSimpleLambda = body.Parent is LambdaExpression && !block && !this.IsAsync; if (isSimpleLambda) { this.ConvertParamsToReferences(parameters); this.WriteReturn(true); } if (this.IsAsync) { asyncBlock.Emit(true); } else { body.AcceptVisitor(this.Emitter); } if (isSimpleLambda) { this.WriteSemiColon(); } if (!block && !this.IsAsync) { this.WriteNewLine(); this.EndBlock(); } if (this.Emitter.ThisRefCounter > savedThisCount) { this.Emitter.Output.Insert(savedPos, Bridge.Translator.Emitter.ROOT + "." + Bridge.Translator.Emitter.DELEGATE_BIND + "(this, "); this.WriteCloseParentheses(); } this.PopLocals(); this.ClearLocalsMap(prevMap); this.ClearLocalsNamesMap(prevNamesMap); }
protected Expression[] GetAwaiters(AstNode node) { var awaitSearch = new AwaitSearchVisitor(); node.AcceptVisitor(awaitSearch); return awaitSearch.GetAwaitExpressions().ToArray(); }
protected IAsyncStep WriteAwaiter(AstNode node) { var index = System.Array.IndexOf(this.Emitter.AsyncBlock.AwaitExpressions, node) + 1; this.Write("$task" + index + " = "); var oldValue = this.Emitter.ReplaceAwaiterByVar; this.Emitter.ReplaceAwaiterByVar = true; node.AcceptVisitor(this.Emitter); this.Emitter.ReplaceAwaiterByVar = oldValue; this.WriteSemiColon(); this.WriteNewLine(); this.Write("$step = " + this.Emitter.AsyncBlock.Step + ";"); this.WriteNewLine(); if (this.Emitter.AsyncBlock.IsTaskReturn) { this.Write("$task" + index + ".continueWith($asyncBody);"); } else { this.Write("$task" + index + ".continueWith($asyncBody, true);"); } this.WriteNewLine(); this.Write("return;"); var asyncStep = this.Emitter.AsyncBlock.AddAsyncStep(index); if (this.Emitter.AsyncBlock.EmittedAsyncSteps != null) { this.Emitter.AsyncBlock.EmittedAsyncSteps.Add(asyncStep); } return asyncStep; }
public string OutputNode (AstNode node) { using (var stringWriter = new System.IO.StringWriter ()) { var formatter = new TextWriterTokenWriter (stringWriter); // formatter.Indentation = indentLevel; stringWriter.NewLine = Document.Editor.EolMarker; var visitor = new CSharpOutputVisitor (formatter, FormattingOptionsFactory.CreateMono ()); node.AcceptVisitor (visitor); return stringWriter.ToString (); } }
internal static void Print(AstNode node) { var v = new CSharpOutputVisitor (Console.Out, new CSharpFormattingOptions ()); node.AcceptVisitor (v, null); }
void FixEmbeddedStatment(BraceStyle braceStyle, BraceForcement braceForcement, CSharpTokenNode token, bool allowInLine, AstNode node, bool statementAlreadyIndented = false) { if (node == null) { return; } bool isBlock = node is BlockStatement; TextReplaceAction beginBraceAction = null; TextReplaceAction endBraceAction = null; switch (braceForcement) { case BraceForcement.DoNotChange: //nothing break; case BraceForcement.AddBraces: if (!isBlock) { AstNode n = node.Parent.GetCSharpNodeBefore(node); int start = document.GetOffset(n.EndLocation); string startBrace = ""; switch (braceStyle) { case BraceStyle.EndOfLineWithoutSpace: startBrace = "{"; break; case BraceStyle.BannerStyle: case BraceStyle.EndOfLine: startBrace = " {"; break; case BraceStyle.NextLine: startBrace = this.options.EolMarker + curIndent.IndentString + "{"; break; case BraceStyle.NextLineShifted2: case BraceStyle.NextLineShifted: curIndent.Push(IndentType.Block); startBrace = this.options.EolMarker + curIndent.IndentString + "{"; curIndent.Pop(); break; } beginBraceAction = AddChange(start, 0, startBrace); } break; case BraceForcement.RemoveBraces: if (isBlock) { BlockStatement block = node as BlockStatement; if (block.Statements.Count() == 1) { int offset1 = document.GetOffset(node.StartLocation); int start = SearchWhitespaceStart(offset1); int offset2 = document.GetOffset(node.EndLocation); int end = SearchWhitespaceStart(offset2 - 1); beginBraceAction = AddChange(start, offset1 - start + 1, null); endBraceAction = AddChange(end + 1, offset2 - end, null); node = block.FirstChild; isBlock = false; } } break; } if (isBlock) { BlockStatement block = node as BlockStatement; if (allowInLine && block.StartLocation.Line == block.EndLocation.Line && block.Statements.Count() <= 1) { if (block.Statements.Count() == 1) { nextStatementIndent = " "; } } else { if (!statementAlreadyIndented) { EnforceBraceStyle(braceStyle, block.LBraceToken, block.RBraceToken); } } if (braceStyle == BraceStyle.NextLineShifted2) { curIndent.Push(IndentType.Block); } } else { if (allowInLine && token.StartLocation.Line == node.EndLocation.Line) { nextStatementIndent = " "; } } if (policy.IndentBlocks && !(policy.AlignEmbeddedIfStatements && node is IfElseStatement && node.Parent is IfElseStatement || policy.AlignEmbeddedUsingStatements && node is UsingStatement && node.Parent is UsingStatement)) { curIndent.Push(IndentType.Block); } if (isBlock) { VisitBlockWithoutFixingBraces((BlockStatement)node, false); } else { if (!statementAlreadyIndented) { FixStatementIndentation(node.StartLocation); } node.AcceptVisitor(this); } if (policy.IndentBlocks && !(policy.AlignEmbeddedIfStatements && node is IfElseStatement && node.Parent is IfElseStatement || policy.AlignEmbeddedUsingStatements && node is UsingStatement && node.Parent is UsingStatement)) { curIndent.Pop(); } switch (braceForcement) { case BraceForcement.DoNotChange: break; case BraceForcement.AddBraces: if (!isBlock) { int offset = document.GetOffset(node.EndLocation); if (!char.IsWhiteSpace(document.GetCharAt(offset))) { offset++; } string startBrace = ""; switch (braceStyle) { case BraceStyle.DoNotChange: startBrace = null; break; case BraceStyle.EndOfLineWithoutSpace: startBrace = this.options.EolMarker + curIndent.IndentString + "}"; break; case BraceStyle.EndOfLine: startBrace = this.options.EolMarker + curIndent.IndentString + "}"; break; case BraceStyle.NextLine: startBrace = this.options.EolMarker + curIndent.IndentString + "}"; break; case BraceStyle.BannerStyle: case BraceStyle.NextLineShifted2: case BraceStyle.NextLineShifted: curIndent.Push(IndentType.Block); startBrace = this.options.EolMarker + curIndent.IndentString + "}"; curIndent.Pop (); break; } if (startBrace != null) { endBraceAction = AddChange(offset, 0, startBrace); } } break; } if (beginBraceAction != null && endBraceAction != null) { beginBraceAction.DependsOn = endBraceAction; endBraceAction.DependsOn = beginBraceAction; } }
protected NodeOutput OutputNode(int indentLevel, AstNode node, bool startWithNewLine = false) { var stringWriter = new StringWriter (); var formatter = new SegmentTrackingTokenWriter(stringWriter); formatter.Indentation = indentLevel; formatter.IndentationString = Options.TabsToSpaces ? new string (' ', Options.IndentSize) : "\t"; stringWriter.NewLine = Options.EolMarker; if (startWithNewLine) formatter.NewLine (); var visitor = new CSharpOutputVisitor (formatter, formattingOptions); node.AcceptVisitor (visitor); string text = stringWriter.ToString().TrimEnd(); return new NodeOutput(text, formatter.NewSegments); }
static string OutputNode (MonoDevelop.Ide.Gui.Document doc, AstNode node) { using (var stringWriter = new System.IO.StringWriter ()) { // formatter.Indentation = indentLevel; var formatter = new TextWriterOutputFormatter (stringWriter); stringWriter.NewLine = doc.Editor.EolMarker; var visitor = new CSharpOutputVisitor (formatter, doc.GetFormattingOptions ()); node.AcceptVisitor (visitor); return stringWriter.ToString (); } }
static bool ContainsLocalReferences (RefactoringContext context, AstNode expr, AstNode body) { var visitor = new ExtractMethod.VariableLookupVisitor (context); body.AcceptVisitor (visitor); return visitor.UsedVariables.Any (variable => !expr.Contains (variable.Region.Begin)); }
void FixEmbeddedStatment(BraceStyle braceStyle, CSharpTokenNode token, bool allowInLine, AstNode node, bool statementAlreadyIndented = false) { if (node == null) return; bool isBlock = node is BlockStatement; FormattingChanges.TextReplaceAction beginBraceAction = null; FormattingChanges.TextReplaceAction endBraceAction = null; BlockStatement closeBlockToBeFixed = null; if (isBlock) { BlockStatement block = node as BlockStatement; if (allowInLine && block.StartLocation.Line == block.EndLocation.Line && block.Statements.Count() <= 1) { if (block.Statements.Count() == 1) nextStatementIndent = " "; } else { if (!statementAlreadyIndented) FixOpenBrace(braceStyle, block.LBraceToken); closeBlockToBeFixed = block; } if (braceStyle == BraceStyle.NextLineShifted2) curIndent.Push(IndentType.Block); } else { if (allowInLine && token.StartLocation.Line == node.EndLocation.Line) { nextStatementIndent = " "; } } bool pushed = false; if (policy.IndentBlocks && !(policy.AlignEmbeddedIfStatements && node is IfElseStatement && node.Parent is IfElseStatement || policy.AlignEmbeddedUsingStatements && node is UsingStatement && node.Parent is UsingStatement)) { curIndent.Push(IndentType.Block); pushed = true; } if (isBlock) { VisitBlockWithoutFixingBraces((BlockStatement)node, false); } else { if (!statementAlreadyIndented) FixStatementIndentation(node.StartLocation); node.AcceptVisitor(this); } if (pushed) curIndent.Pop(); if (beginBraceAction != null && endBraceAction != null) { beginBraceAction.DependsOn = endBraceAction; endBraceAction.DependsOn = beginBraceAction; } if (isBlock && braceStyle == BraceStyle.NextLineShifted2) curIndent.Pop(); if (closeBlockToBeFixed != null) { FixClosingBrace(braceStyle, closeBlockToBeFixed.RBraceToken); } }
public void Apply (AstNode rootNode) { if (rootNode == null) throw new ArgumentNullException ("rootNode"); rootNode.AcceptVisitor (new GenerateCodeVisitior (this)); }
internal static void Print(AstNode node) { var v = new CSharpOutputVisitor (Console.Out, FormattingOptionsFactory.CreateMono ()); node.AcceptVisitor (v); }
public static bool UsesNotStaticMember(RefactoringContext context, AstNode node) { var visitor = new StaticVisitor(context); node.AcceptVisitor(visitor); return visitor.UsesNonStaticMember; }