本文整理汇总了C#中ICSharpCode.NRefactory.CSharp.CSharpOutputVisitor类的典型用法代码示例。如果您正苦于以下问题:C# CSharpOutputVisitor类的具体用法?C# CSharpOutputVisitor怎么用?C# CSharpOutputVisitor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CSharpOutputVisitor类属于ICSharpCode.NRefactory.CSharp命名空间,在下文中一共展示了CSharpOutputVisitor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ToText
public static string ToText(AstNode node)
{
var stringWriter = new StringWriter();
var output = new CSharpOutputVisitor(stringWriter, FormattingOptionsFactory.CreateSharpDevelop());
node.AcceptVisitor(output);
return stringWriter.GetStringBuilder().ToString();
}
示例2: WriteNode
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;
}
示例3: GetBodyStatistics
public static CSharpMethodBodyStatistics GetBodyStatistics(this MethodDeclaration declaration)
{
using (var writer = new StringWriter()) {
var visitor = new CSharpOutputVisitor(writer, FormattingOptionsFactory.CreateAllman());
declaration.AcceptVisitor(visitor);
var bodyAsString = writer.ToString();
return new CSharpMethodBodyStatistics(
bodyAsString.Split(new[] {Environment.NewLine}, StringSplitOptions.None).Length,
bodyAsString.Length,
bodyAsString.GetHashCode());
}
}
示例4: GenerateText
public static string GenerateText(TypeDeclaration type,
OrderedPartCollection<AbstractDynamicCompilationExtension> extensions,
HashSet<string> namespaces = null)
{
var unit = new SyntaxTree();
if (namespaces == null)
{
namespaces = new HashSet<string>
{
typeof (SystemTime).Namespace,
typeof (AbstractViewGenerator).Namespace,
typeof (Enumerable).Namespace,
typeof (IEnumerable<>).Namespace,
typeof (IEnumerable).Namespace,
typeof (int).Namespace,
typeof (LinqOnDynamic).Namespace,
typeof (Field).Namespace,
typeof (CultureInfo).Namespace,
typeof (Regex).Namespace
};
}
foreach (var extension in extensions)
{
foreach (var ns in extension.Value.GetNamespacesToImport())
{
namespaces.Add(ns);
}
}
foreach (var ns in namespaces)
{
unit.Members.Add(new UsingDeclaration(ns));
}
unit.Members.Add(new WindowsNewLine());
unit.Members.Add(type);
var stringWriter = new StringWriter();
var output = new CSharpOutputVisitor(stringWriter, FormattingOptionsFactory.CreateSharpDevelop());
unit.AcceptVisitor(output);
return stringWriter.GetStringBuilder().ToString();
}
示例5: GetPartialMethodSignature
static string GetPartialMethodSignature(MethodDeclaration declaration)
{
if(declaration.Parameters.Count > 0) {
using (var writer = new StringWriter()) {
var visitor = new CSharpOutputVisitor(writer, FormattingOptionsFactory.CreateAllman());
var parameterIndex = 0;
foreach (var parameter in declaration.Parameters) {
if (parameterIndex > 0)
writer.Write(",");
parameter.AcceptVisitor(visitor);
parameterIndex++;
}
return string.Format("{0}({1})", GetNameWithTypeParameters(declaration), writer);
}
}
return string.Format("{0}()", GetNameWithTypeParameters(declaration));
}
示例6: BuildExpression
public string BuildExpression(Dictionary<string, Expression> selectExpressions)
{
var anonymousTypeCreateExpression = new AnonymousTypeCreateExpression();
var crrv = new ChangeRootReferenceVisitor(FromIdentifier);
foreach (var curExpr in selectExpressions.OrderBy(x => x.Key))
{
curExpr.Value.AcceptVisitor(crrv);
anonymousTypeCreateExpression.Initializers.Add(
new AssignmentExpression(new IdentifierExpression(curExpr.Key), curExpr.Value.Clone()));
}
if (FromExpression == null)
FromExpression = new IdentifierExpression();
var queryExpr = new QueryExpression
{
Clauses =
{
new QueryFromClause
{
Identifier = "doc",
Expression = FromExpression.Clone()
},
new QuerySelectClause
{
Expression = anonymousTypeCreateExpression.Clone()
}
}
};
FromIdentifier = "doc";
var printer = new StringWriter();
var printerVisitor = new CSharpOutputVisitor(printer, FormattingOptionsFactory.CreateSharpDevelop());
queryExpr.AcceptVisitor(printerVisitor);
var format = printer.GetStringBuilder().ToString();
if (format.Substring(0, 3) == "\r\n\t")
{
format = format.Remove(0, 3);
}
format = format.Replace("\r\n\t", "\n");
return format;
}
示例7: Execute
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();
}
}
示例8: WriteCommaSeparatedList
void WriteCommaSeparatedList(IEnumerable<AstNode> parameters)
{
if (parameters.Any())
{
var last = parameters.Last();
foreach (AstNode node in parameters)
{
if (_includePlaceholders)
{
_writer.WriteToken(Roles.Text, "$");
_writer.WriteToken(Roles.Text, "{");
_writer.WriteToken(Roles.Text, _counter.ToString());
_writer.WriteToken(Roles.Text, ":");
}
var outputVisitor = new CSharpOutputVisitor(_writer, _policy);
node.AcceptVisitor(outputVisitor);
if (_includePlaceholders)
{
_writer.WriteToken(Roles.Text, "}");
}
if (node != last)
{
this.Comma(node);
}
_counter++;
}
}
}
示例9: AppendReturnType
void AppendReturnType (StringBuilder result, CodeGenerationOptions options, IType type)
{
if (type == null)
throw new ArgumentNullException ("type");
var implementingType = options.Part;
var loc = implementingType.Region.End;
var pf = implementingType.UnresolvedFile;
var file = pf as CSharpUnresolvedFile;
var resolved = type;
if (resolved.Kind == TypeKind.Unknown) {
result.Append (type.FullName);
return;
}
var def = type.GetDefinition ();
if (def != null) {
using (var stringWriter = new System.IO.StringWriter ()) {
var formatter = new TextWriterOutputFormatter (stringWriter);
stringWriter.NewLine = EolMarker;
var visitor = new CSharpOutputVisitor (formatter, FormattingOptionsFactory.CreateMono ());
var shortType = CreateShortType (def.Compilation, file, loc, resolved);
shortType.AcceptVisitor (visitor);
var typeString = stringWriter.ToString ();
if (typeString.StartsWith ("global::"))
typeString = typeString.Substring ("global::".Length);
result.Append (typeString);
}
} else {
result.Append (new ICSharpCode.NRefactory.CSharp.CSharpAmbience ().ConvertType (type));
}
}
示例10: CSharpGenerateCodeButtonClick
void CSharpGenerateCodeButtonClick(object sender, EventArgs e)
{
var w = new StringWriter();
var output = new CSharpOutputVisitor (w, new CSharpFormattingOptions());
unit.AcceptVisitor (output, null);
editor.Text = w.ToString();
}
示例11: CSharpGenerateCodeButtonClick
void CSharpGenerateCodeButtonClick(object sender, EventArgs e)
{
StringWriter w = new StringWriter();
CSharpOutputVisitor output = new CSharpOutputVisitor(w, new CSharpFormattingOptions());
compilationUnit.AcceptVisitor(output, null);
csharpCodeTextBox.Text = w.ToString();
}
示例12: AddFieldsToFile
public void AddFieldsToFile(string targetProjectPath, string relativeFilePath, List<TargetField> list)
{
CompilationUnit compilationUnit;
bool anyChanges = false;
string filePath = Path.Combine(Path.GetDirectoryName(targetProjectPath), relativeFilePath);
using(StreamReader reader = new StreamReader(filePath))
{
CSharpParser parser = new CSharpParser();
compilationUnit = parser.Parse(reader, Path.GetFileName(filePath));
}
string typeName;
string typeNamespace;
DotNetParserHelper.SplitType(this.TargetClassFullName, out typeName, out typeNamespace);
var typeDeclarationList = compilationUnit.Descendants.Where(i => i is TypeDeclaration);
var classObject = (TypeDeclaration)compilationUnit.Descendants.Single(i=>i is TypeDeclaration && ((TypeDeclaration)i).Name == typeName);
foreach(var field in list)
{
switch(field.SourceClassFullName)
{
//case "System.Web.UI.WebControls.Literal":
// TargetControlGenerator.AddLiteralControl(classObject, field);
// anyChanges = true;
// break;
case "System.Web.UI.WebControls.HyperLink":
TargetControlGenerator.AddHyperLinkControl(classObject, field, field.SourceClassFullName);
anyChanges = true;
break;
}
}
if(anyChanges)
{
using(StreamWriter writer = new StreamWriter(filePath))
{
CSharpOutputVisitor visitor = new CSharpOutputVisitor(writer, new CSharpFormattingOptions());
compilationUnit.AcceptVisitor(visitor);
}
}
}
示例13: CreateDesignerWebPageFile
private void CreateDesignerWebPageFile(TargetClassComparisonResult targetClass, string designerFilePath)
{
string typeName;
string typeNamespace;
DotNetParserHelper.SplitType(targetClass.TargetClassFullName, out typeName, out typeNamespace);
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using System.Linq;");
sb.AppendLine("using System.Text;");
sb.AppendLine("using MMDB.UITest.Core;");
sb.AppendLine("using WatiN.Core;");
sb.AppendLine();
sb.AppendLine(string.Format("namespace {0}", typeNamespace));
sb.AppendLine("{");
//sb.AppendLine(string.Format("[{0}(sourceClassFullName:\"{1}\",expectedUrlList: new string[] {{\"{2}\"}})]", typeof(UIClientPageAttribute).FullName, targetClass.SourceClassFullName, targetClass.ExpectedUrl));
sb.AppendLine(string.Format("[{0}(sourceClassFullName:\"{1}\")]", typeof(UIClientPageAttribute).FullName, targetClass.SourceClassFullName));
sb.AppendLine(string.Format("partial class {0} : {1}", typeName, typeof(BasePageClient).FullName));
sb.AppendLine("{");
sb.AppendLine();
sb.AppendLine(string.Format("public {0} (Browser browser) : base(browser) {{}}", typeName));
sb.AppendLine();
sb.AppendLine(string.Format("protected override IEnumerable<string> ExpectedUrlList {{ get {{ return new string[] {{ \"{0}\" }}; }} }}", targetClass.ExpectedUrl));
sb.AppendLine("}");
sb.AppendLine("}");
CSharpParser parser = new CSharpParser();
var compilationUnit = parser.Parse(sb.ToString(), Path.GetFileName(designerFilePath));
if (!Directory.Exists(Path.GetDirectoryName(designerFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(designerFilePath));
}
using (StreamWriter writer = new StreamWriter(designerFilePath))
{
CSharpOutputVisitor outputVistor = new CSharpOutputVisitor(writer, new CSharpFormattingOptions());
compilationUnit.AcceptVisitor(outputVistor, null);
}
}
示例14: GenerateCode
protected override string GenerateCode(ITypeDefinition currentClass)
{
List<PropertyOrFieldWrapper> filtered = parameterList
.Where(p => p.IsIncluded)
.OrderBy(p => p.Index)
.ToList();
var test = refactoringContext.GetNode();
var insertedConstructor = refactoringContext.GetNode().PrevSibling as ConstructorDeclaration;
if (insertedConstructor == null)
{
// We are not inside of a constructor declaration
return null;
}
using (Script script = refactoringContext.StartScript()) {
BlockStatement originalCtorBody = insertedConstructor.Body;
foreach (PropertyOrFieldWrapper w in filtered) {
if (w.AddCheckForNull) {
// true = reference, null = generic or unknown
if (w.Type.IsReferenceType != false)
script.AddTo(originalCtorBody,
new IfElseStatement(
new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.Equality, new PrimitiveExpression(null)),
new ThrowStatement(new ObjectCreateExpression(new SimpleType("ArgumentNullException"), new List<Expression>() { new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"') }))
)
);
else
script.AddTo(originalCtorBody,
new IfElseStatement(
new UnaryOperatorExpression(UnaryOperatorType.Not, new MemberReferenceExpression(new IdentifierExpression(w.MemberName), "HasValue")),
new ThrowStatement(new ObjectCreateExpression(new SimpleType("ArgumentNullException"), new List<Expression>() { new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"') }))
)
);
}
if (w.AddRangeCheck) {
script.AddTo(originalCtorBody,
new IfElseStatement(
new BinaryOperatorExpression(
new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.LessThan, new IdentifierExpression("lower")),
BinaryOperatorType.ConditionalOr,
new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.GreaterThan, new IdentifierExpression("upper"))
),
new ThrowStatement(
new ObjectCreateExpression(
new SimpleType("ArgumentOutOfRangeException"),
new List<Expression>() { new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"'), new IdentifierExpression(w.ParameterName), new BinaryOperatorExpression(new PrimitiveExpression("Value must be between "), BinaryOperatorType.Add, new BinaryOperatorExpression(new IdentifierExpression("lower"), BinaryOperatorType.Add, new BinaryOperatorExpression(new PrimitiveExpression(" and "), BinaryOperatorType.Add, new IdentifierExpression("upper")))) }
)
)
)
);
}
}
foreach (PropertyOrFieldWrapper w in filtered) {
script.AddTo(originalCtorBody,
new ExpressionStatement(new AssignmentExpression(new MemberReferenceExpression(new ThisReferenceExpression(), w.MemberName), AssignmentOperatorType.Assign, new IdentifierExpression(w.ParameterName)))
);
}
}
AnchorElement parameterListElement = insertionContext.ActiveElements
.OfType<AnchorElement>()
.FirstOrDefault(item => item.Name.Equals("parameterList", StringComparison.OrdinalIgnoreCase));
if (parameterListElement != null) {
StringBuilder pList = new StringBuilder();
var parameters = filtered
.Select(p => new ParameterDeclaration(refactoringContext.CreateShortType(p.Type), p.ParameterName))
.ToList();
using (StringWriter textWriter = new StringWriter(pList)) {
// Output parameter list as string
var formattingOptions = FormattingOptionsFactory.CreateMono();
CSharpOutputVisitor outputVisitor = new CSharpOutputVisitor(textWriter, formattingOptions);
for (int i = 0; i < parameters.Count; i++) {
if (i > 0)
textWriter.Write(",");
outputVisitor.VisitParameterDeclaration(parameters[i]);
}
}
parameterListElement.Text = pList.ToString();
}
return null;
}
示例15: LeftBrace
public static BraceHelper LeftBrace(CSharpOutputVisitor owner, CodeBracesRangeFlags flags) {
var bh = new BraceHelper(owner, flags);
owner.WriteToken(Roles.LBrace, BoxedTextColor.Punctuation);
bh.leftEnd = owner.writer.GetLocation() ?? 0;
return bh;
}