Expression ParseExpression(ExpressionResult expressionResult) { if (expressionResult == null || String.IsNullOrEmpty(expressionResult.Expression)) { return(null); } string expr = expressionResult.Expression.Trim(); if (!expr.EndsWith(";")) { expr += ";"; } using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(this.lang, new StringReader(expr))) { Expression result = parser.ParseExpression(); if (result is BinaryOperatorExpression) { TypeReference typeRef = ParseTypeReference(expressionResult); if (typeRef != null) { return(new TypeReferenceExpression(typeRef)); } } return(result); } }
protected override CodeDomLocalizationModel GetCurrentLocalizationModelFromDesignedFile() { ParseInformation parseInfo = ParserService.ParseFile(this.Generator.ViewContent.DesignerCodeFile.FileName, new StringTextBuffer(this.Generator.ViewContent.DesignerCodeFileContent)); IClass formClass; bool isFirstClassInFile; IList <IClass> parts = FindFormClassParts(parseInfo, out formClass, out isFirstClassInFile); foreach (string fileName in parts.Select(p => p.CompilationUnit.FileName) .Where(n => n != null) .Distinct(StringComparer.OrdinalIgnoreCase)) { ICSharpCode.NRefactory.IParser p = ICSharpCode.NRefactory.ParserFactory.CreateParser(language, ParserService.GetParseableFileContent(fileName).CreateReader()); p.Parse(); if (p.Errors.Count > 0) { throw new FormsDesignerLoadException("Syntax errors in " + fileName + ":\r\n" + p.Errors.ErrorOutput); } FindLocalizationModelVisitor visitor = new FindLocalizationModelVisitor(); p.CompilationUnit.AcceptVisitor(visitor, null); if (visitor.Model != CodeDomLocalizationModel.None) { return(visitor.Model); } } return(CodeDomLocalizationModel.None); }
public override string AddBaseTypeToClass(string existingCode, IClass targetClass, IClass newBaseType) { NR.IParser parser = ParseFile(null, existingCode); if (parser == null) { return(null); } AddTypeToBaseTypesVisitor addTypeToBaseTypesVisitor = new AddTypeToBaseTypesVisitor(targetClass, newBaseType); parser.CompilationUnit.AcceptVisitor(addTypeToBaseTypesVisitor, null); // now use an output visitor for the appropriate language (based on // extension of the existing code file) to format the new interface. IOutputAstVisitor output = GetOutputVisitor(); // run the output visitor with the specials inserter to insert comments using (SpecialNodesInserter.Install(parser.Lexer.SpecialTracker.RetrieveSpecials(), output)) { parser.CompilationUnit.AcceptVisitor(output, null); } parser.Dispose(); if (output.Errors.Count > 0) { ShowSourceCodeErrors(null, output.Errors.ErrorOutput); return(null); } return(output.Text); }
void ParseStep() { string code = null; Invoke(new MethodInvoker(delegate { code = textEditorControl1.Text; })); TextReader textReader = new StringReader(code); Dom.ICompilationUnit newCompilationUnit; if (Language == "C#") { using (NRefactory.IParser p = NRefactory.ParserFactory.CreateParser(NRefactory.SupportedLanguage.CSharp, textReader)) { p.Parse(); newCompilationUnit = ConvertCompilationUnit(p.CompilationUnit); } } else { using (NRefactory.IParser p = NRefactory.ParserFactory.CreateParser(NRefactory.SupportedLanguage.VBNet, textReader)) { p.Parse(); newCompilationUnit = ConvertCompilationUnit(p.CompilationUnit); } } // Remove information from lastCompilationUnit and add information from newCompilationUnit. myProjectContent.UpdateCompilationUnit(lastCompilationUnit, newCompilationUnit, DummyFileName); lastCompilationUnit = newCompilationUnit; }
public override ParsedDocument Parse (ProjectDom dom, string fileName, string content) { using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser (ICSharpCode.NRefactory.SupportedLanguage.CSharp, new StringReader (content))) { ParsedDocument result = new ParsedDocument (fileName); result.CompilationUnit = new MonoDevelop.Projects.Dom.CompilationUnit (fileName); parser.Errors.Error += delegate(int line, int col, string message) { result.Add (new Error (ErrorType.Error, line, col, message)); }; parser.Lexer.SpecialCommentTags = LexerTags; parser.Lexer.EvaluateConditionalCompilation = true; if (dom != null && dom.Project != null) { DotNetProjectConfiguration conf = dom.Project.DefaultConfiguration as DotNetProjectConfiguration; CSharpCompilerParameters par = conf != null ? conf.CompilationParameters as CSharpCompilerParameters : null; if (par != null) parser.Lexer.SetConditionalCompilationSymbols (par.DefineSymbols); } parser.Parse (); SpecialTracker tracker = new SpecialTracker (result); foreach (ICSharpCode.NRefactory.ISpecial special in parser.Lexer.SpecialTracker.CurrentSpecials) { special.AcceptVisitor (tracker, null); } foreach (ICSharpCode.NRefactory.Parser.TagComment tagComment in parser.Lexer.TagComments) { result.Add (new Tag (tagComment.Tag, tagComment.CommentText, new DomRegion (tagComment.StartPosition.Y, tagComment.StartPosition.X, tagComment.EndPosition.Y, tagComment.EndPosition.X))); } ConversionVisitior visitor = new ConversionVisitior (result, parser.Lexer.SpecialTracker.CurrentSpecials); visitor.VisitCompilationUnit (parser.CompilationUnit, null); result.CompilationUnit.Tag = parser.CompilationUnit; LastUnit = parser.CompilationUnit; return result; } }
void ParseStep() { string code = null; Invoke(new MethodInvoker(delegate { code = textEditorControl1.Text; })); TextReader textReader = new StringReader(code); Dom.ICompilationUnit newCompilationUnit; NRefactory.SupportedLanguage supportedLanguage; if (IsVisualBasic) { supportedLanguage = NRefactory.SupportedLanguage.VBNet; } else { supportedLanguage = NRefactory.SupportedLanguage.CSharp; } using (NRefactory.IParser p = NRefactory.ParserFactory.CreateParser(supportedLanguage, textReader)) { // we only need to parse types and method definitions, no method bodies // so speed up the parser and make it more resistent to syntax // errors in methods p.ParseMethodBodies = false; p.Parse(); newCompilationUnit = ConvertCompilationUnit(p.CompilationUnit); } // Remove information from lastCompilationUnit and add information from newCompilationUnit. myProjectContent.UpdateCompilationUnit(lastCompilationUnit, newCompilationUnit, DummyFileName); lastCompilationUnit = newCompilationUnit; parseInformation.SetCompilationUnit(newCompilationUnit); }
void TestProgram(SupportedLanguage sourceLanguage, string sourceCode, string expectedOutput) { DefaultProjectContent pc = new DefaultProjectContent(); pc.ReferencedContents.Add(projectContentRegistry.Mscorlib); pc.ReferencedContents.Add(projectContentRegistry.GetProjectContentForReference("System.Windows.Forms", "System.Windows.Forms")); if (sourceLanguage == SupportedLanguage.VBNet) { pc.ReferencedContents.Add(projectContentRegistry.GetProjectContentForReference("Microsoft.VisualBasic", "Microsoft.VisualBasic")); pc.DefaultImports = new DefaultUsing(pc); pc.DefaultImports.Usings.Add("System"); pc.DefaultImports.Usings.Add("Microsoft.VisualBasic"); } pc.Language = sourceLanguage == SupportedLanguage.CSharp ? LanguageProperties.CSharp : LanguageProperties.VBNet; HostCallback.GetCurrentProjectContent = delegate { return(pc); }; ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(sourceLanguage, new StringReader(sourceCode)); parser.Parse(); Assert.AreEqual("", parser.Errors.ErrorOutput); NRefactoryASTConvertVisitor visitor = new NRefactoryASTConvertVisitor(pc); visitor.VisitCompilationUnit(parser.CompilationUnit, null); visitor.Cu.FileName = sourceLanguage == SupportedLanguage.CSharp ? "a.cs" : "a.vb"; foreach (IClass c in visitor.Cu.Classes) { pc.AddClassToNamespaceList(c); } ParseInformation parseInfo = new ParseInformation(); parseInfo.SetCompilationUnit(visitor.Cu); if (sourceLanguage == SupportedLanguage.CSharp) { CSharpToVBNetConvertVisitor convertVisitor = new CSharpToVBNetConvertVisitor(pc, parseInfo); convertVisitor.RootNamespaceToRemove = "RootNamespace"; parser.CompilationUnit.AcceptVisitor(convertVisitor, null); } else { VBNetToCSharpConvertVisitor convertVisitor = new VBNetToCSharpConvertVisitor(pc, parseInfo); parser.CompilationUnit.AcceptVisitor(convertVisitor, null); } IOutputAstVisitor outputVisitor = sourceLanguage == SupportedLanguage.CSharp ? (IOutputAstVisitor) new VBNetOutputVisitor() : new CSharpOutputVisitor(); outputVisitor.Options.IndentationChar = ' '; outputVisitor.Options.IndentSize = 2; using (SpecialNodesInserter.Install(parser.Lexer.SpecialTracker.RetrieveSpecials(), outputVisitor)) { outputVisitor.VisitCompilationUnit(parser.CompilationUnit, null); } Assert.AreEqual("", outputVisitor.Errors.ErrorOutput); Assert.AreEqual(expectedOutput.Replace("\r", ""), outputVisitor.Text.Trim().Replace("\r", "")); }
protected override CodeCompileUnit Parse() { ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(_designerFile); parser.Parse(); CodeDomVisitor visitor = new CodeDomVisitor(); visitor.VisitCompilationUnit(parser.CompilationUnit, null); return(visitor.codeCompileUnit); }
public CompilationUnit ParseFile(string content) { using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(content))) { try { parser.Parse(); LastErrors = parser.Errors; } catch (Exception) { } return(parser.CompilationUnit); } }
Expression ParseExpression(string expression) { Expression expr = SpecialConstructs(expression); if (expr == null) { using (NR.IParser p = NR.ParserFactory.CreateParser(language, new System.IO.StringReader(expression))) { expr = p.ParseExpression(); } } return(expr); }
public static void EvaluateComplexityMetrics(MetricsContext ctx, ProjectProperties project) { mctx = ctx; PrefixName = new Stack <string>(0); lock (mctx) { foreach (var file in project.Project.Files) { /*if(file.BuildAction != BuildAction.Compile) * continue;*/ // Files not set to compile are sometimes not accessible if (file.Name.Contains("svn-base")) { continue; } string text = ""; try { text = System.IO.File.ReadAllText(file.FilePath); } catch (System.UnauthorizedAccessException uae) { continue; } catch (System.IO.FileNotFoundException fnf) { // This exception arises in Nrefactory...WTF? 0_0 continue; } ProjProp = project; File = file; Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = text; FileDoc = doc; FileText = new List <LineSegment>(); foreach (LineSegment segment in doc.Lines) { FileText.Add(segment); } using (ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(text))) { parser.Parse(); if (parser.Errors.Count > 0) { //Error handling TODO } else { foreach (var it in parser.CompilationUnit.Children) { ProcessNode(ctx, it); } } } } } }
public TypeReference ParseTypeReference(string content) { content = content.Trim(); using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(content))) { try { var result = parser.ParseTypeReference(); LastErrors = parser.Errors; return(result); } catch (Exception) { } } return(null); }
public Expression ParseExpression(string expressionText) { expressionText = expressionText.Trim(); using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(expressionText))) { Expression result = null; try { result = parser.ParseExpression(); LastErrors = parser.Errors; } catch (Exception) { } return(result); } }
public CompilationUnit ParseCurrentMemberAsCompilationUnit(string fileContent) { System.IO.TextReader content = ExtractCurrentMethod(fileContent); if (content != null) { NR.IParser p = NR.ParserFactory.CreateParser(language, content); p.Parse(); return(p.CompilationUnit); } else { return(null); } }
void RunCSharpNRefactoryVisitorClick(object sender, EventArgs e) { try { Clear(); using (NRefactory.IParser parser = NRefactory.ParserFactory.CreateParser(NRefactory.SupportedLanguage.CSharp, new StringReader(codeTextBox.Text))) { parser.ParseMethodBodies = false; parser.Parse(); NRefactoryAstVisitor visitor = new NRefactoryAstVisitor(this); visitor.VisitCompilationUnit(parser.CompilationUnit, null); } } catch (Exception ex) { walkerOutputTextBox.Text = ex.ToString(); } }
NR.IParser ParseFile(string fileContent) { NR.IParser parser = NR.ParserFactory.CreateParser(language, new StringReader(fileContent)); parser.Parse(); if (parser.Errors.Count > 0) { ShowSourceCodeErrors(parser.Errors.ErrorOutput); parser.Dispose(); return(null); } else { return(parser); } }
protected virtual Dictionary <PossibleTypeReference, object> FindPossibleTypeReferences(string fileContent) { NR.IParser parser = ParseFile(fileContent); if (parser == null) { return(null); } else { FindPossibleTypeReferencesVisitor visitor = new FindPossibleTypeReferencesVisitor(); parser.CompilationUnit.AcceptVisitor(visitor, null); parser.Dispose(); return(visitor.list); } }
protected virtual HashSet <PossibleTypeReference> FindPossibleTypeReferences(IDomProgressMonitor progressMonitor, string fileContent, ParseInformation parseInfo) { NR.IParser parser = ParseFile(progressMonitor, fileContent); if (parser == null) { return(null); } else { FindPossibleTypeReferencesVisitor visitor = new FindPossibleTypeReferencesVisitor(parseInfo); parser.CompilationUnit.AcceptVisitor(visitor, null); parser.Dispose(); return(visitor.list); } }
static CompilationUnit Parse(SupportedLanguage language, string fileName, string fileContent) { using (ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(language, new StringReader(fileContent))) { if (parser != null) { #if DEBUG LoggingService.Debug("ResourceToolkit: NRefactoryAstCacheService: Parsing file '" + fileName + "'"); #endif parser.ParseMethodBodies = true; parser.Parse(); return(parser.CompilationUnit); } } return(null); }
static TypeReference ParseTypeReference(ExpressionResult expressionResult) { if (expressionResult == null || String.IsNullOrEmpty(expressionResult.Expression)) { return(null); } string expr = expressionResult.Expression.Trim(); using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader("typeof(" + expr + ");"))) { TypeOfExpression typeOfExpression = parser.ParseExpression() as TypeOfExpression; if (typeOfExpression != null) { return(typeOfExpression.TypeReference); } } return(null); }
internal void SetupResolver(DomLocation resolvePosition) { this.resolvePosition = resolvePosition; this.resultTable.Clear(); callingType = GetTypeAtCursor(unit, fileName, resolvePosition); if (callingType != null) { callingMember = GetMemberAt(callingType, fileName, resolvePosition); callingType = dom.ResolveType(callingType); if (callingMember == null) { DomLocation posAbove = resolvePosition; posAbove.Line--; callingMember = GetMemberAt(callingType, fileName, posAbove); } } if (memberCompilationUnit != null) { return; } if (callingMember != null && !setupLookupTableVisitor) { string wrapper = CreateWrapperClassForMember(callingMember, fileName, editor); using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(lang, new StringReader(wrapper))) { parser.Parse(); memberCompilationUnit = parser.CompilationUnit; lookupTableVisitor.VisitCompilationUnit(parser.CompilationUnit, null); lookupVariableLine = CallingMember.Location.Line - 2; setupLookupTableVisitor = true; } } else if (editor != null) { string wrapper = editor.Text; using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(lang, new StringReader(wrapper))) { parser.Parse(); memberCompilationUnit = parser.CompilationUnit; lookupTableVisitor.VisitCompilationUnit(parser.CompilationUnit, null); lookupVariableLine = 0; setupLookupTableVisitor = true; } } }
// ******************************************************************************************************************************** /// <summary> /// Parses an expression with NRefactory. /// </summary> /// <param name="fileName">The file name of the source code file that contains the expression.</param> /// <param name="expression">The expression to parse.</param> /// <param name="caretLine">The 1-based line number of the expression.</param> /// <param name="caretColumn">The 1-based column number of the expression.</param> /// <returns>The parsed expression or <c>null</c> if the expression cannot be parsed or the language of the source code file is not supported.</returns> public static Expression ParseExpression(string fileName, string expression, int caretLine, int caretColumn) { SupportedLanguage?l = NRefactoryResourceResolver.GetFileLanguage(fileName); if (l == null) { return(null); } using (ICSharpCode.NRefactory.IParser p = ICSharpCode.NRefactory.ParserFactory.CreateParser(l.Value, new System.IO.StringReader(expression))) { Expression expr = p.ParseExpression(); if (expr != null) { expr.AcceptVisitor(new SetAllNodePointsAstVisitor(new Location(caretColumn, caretLine), new Location(caretColumn + 1, caretLine)), null); } return(expr); } }
public SourceUnit(String content) { using (ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(content))) { parser.Parse(); if (parser.Errors.Count > 0) { throw new Exception(parser.Errors.ErrorOutput); } specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); unit = parser.CompilationUnit; NRefactoryUtil.InsertSpecials(unit, specials); //List<ISpecial> rightSpecials = new List<ISpecial>(); //rightSpecials.AddRange(specials); //MapSpecials(unit.Children, rightSpecials); // //if (rightSpecials.Count > 0) { // System.Diagnostics.Debug.WriteLine("There are specials that did not get mapped to members."); //} } foreach (INode child in unit.Children) { if (child is UsingDeclaration) { imports.Add(child as UsingDeclaration); } else if (child is NamespaceDeclaration) { namespaces.Add(new NamespaceUnit(child as NamespaceDeclaration)); } else if (child is TypeDeclaration) { if (namespaces.Count == 0) { namespaces.Add(new NamespaceUnit()); } namespaces[0].AddType(new TypeUnit(child as TypeDeclaration)); } else { throw new Exception("Unknown node type: " + child.GetType() + " - " + child.ToString()); } } }
public INode ParseText(string text) { text = text.Trim(); using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(text))) { if (text.EndsWith(";") || text.EndsWith("}")) { BlockStatement block = null; try { block = parser.ParseBlock(); LastErrors = parser.Errors; } catch (Exception) { } if (block != null) { return(block); } } return(parser.ParseExpression()); } }
static List <HashSet <string> > GetUsedDefineCombinations(ICSharpCode.NRefactory.IParser parser) { List <HashSet <string> > result = new List <HashSet <string> > (); foreach (ISpecial special in parser.Lexer.SpecialTracker.CurrentSpecials) { PreprocessingDirective directive = special as PreprocessingDirective; if (directive == null || (directive.Cmd != "#if" && directive.Cmd != "#elif")) { continue; } ExpressionVisitor visitor = new ExpressionVisitor(); directive.Expression.AcceptVisitor(visitor, null); ICSharpCode.NRefactory.Parser.CSharp.ConditionalCompilation cond = new ICSharpCode.NRefactory.Parser.CSharp.ConditionalCompilation(); bool nothingDefined = cond.Evaluate(directive.Expression); foreach (var combination in GetAllCombinations(visitor.Identifiers)) { cond = new ICSharpCode.NRefactory.Parser.CSharp.ConditionalCompilation(); HashSet <string> defines = new HashSet <string> (); foreach (string usedIdentifier in combination) { cond.Define(usedIdentifier); defines.Add(usedIdentifier); bool curDefineStatus = cond.Evaluate(directive.Expression); if (curDefineStatus != nothingDefined) { result.Add(defines); goto next; } } } next: ; } return(result); }
public CodeCompileUnit ConvertToCodeComlieUnit(String strText) { TextReader inputstream = new StringReader(strText); #region New //CSharpParser parser=new CSharpParser(); //CompilationUnit compilationUnit=parser.Parse( inputstream , @"D:\bbb.cs" ); //IProjectContent project=new CSharpProjectContent(); //var parsedFile=compilationUnit.ToTypeSystem(); //project=project.UpdateProjectContent( null , parsedFile ); //project=project.AddAssemblyReferences( builtInLibs.Value ); //ICompilation compilation=project.CreateCompilation(); //CodeCompileUnit cUnit=new CodeDomConvertVisitor().Convert( compilation , compilationUnit , parsedFile ); ////// Remove Unsed Namespaces //for ( int i=cUnit.Namespaces.Count-1; i>=0; i-- ) //{ // if ( cUnit.Namespaces[i].Types.Count==0 ) // cUnit.Namespaces.RemoveAt( i ); //} //return cUnit; #endregion #region Old ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, inputstream); parser.ParseMethodBodies = true; parser.Lexer.SkipAllComments = false; parser.Parse(); if (parser.Errors.Count > 0) { return(null); } //foreach ( var node in parser.CompilationUnit.Children ) //{ // // fix StartLocation / EndLocation // node.AcceptVisitor( new ICSharpCode.NRefactory.Visitors.SetRegionInclusionVisitor() , null ); //} CodeDomProvider codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider(); CodeDomVisitor visit = new CodeDomVisitor(); visit.VisitCompilationUnit(parser.CompilationUnit, null); // Remove Unsed Namespaces for (int i = visit.codeCompileUnit.Namespaces.Count - 1; i >= 0; i--) { if (visit.codeCompileUnit.Namespaces[i].Types.Count == 0) { visit.codeCompileUnit.Namespaces.RemoveAt(i); } } return(visit.codeCompileUnit); #endregion }
public override string CreateNewFileLikeExisting(string existingFileContent, string codeForNewType) { NR.IParser parser = ParseFile(existingFileContent); if (parser == null) { return(null); } RemoveTypesVisitor visitor = new RemoveTypesVisitor(); parser.CompilationUnit.AcceptVisitor(visitor, null); List <NR.ISpecial> comments = new List <NR.ISpecial>(); foreach (NR.ISpecial c in parser.Lexer.SpecialTracker.CurrentSpecials) { if (c.StartPosition.Y <= visitor.includeCommentsUpToLine || c.StartPosition.Y > visitor.includeCommentsAfterLine) { comments.Add(c); } } IOutputAstVisitor outputVisitor = (language == NR.SupportedLanguage.CSharp) ? new CSharpOutputVisitor() : (IOutputAstVisitor) new VBNetOutputVisitor(); using (SpecialNodesInserter.Install(comments, outputVisitor)) { parser.CompilationUnit.AcceptVisitor(outputVisitor, null); } string expectedText; if (language == NR.SupportedLanguage.CSharp) { expectedText = "using " + RemoveTypesVisitor.DummyIdentifier + ";"; } else { expectedText = "Imports " + RemoveTypesVisitor.DummyIdentifier; } using (StringWriter w = new StringWriter()) { using (StringReader r1 = new StringReader(outputVisitor.Text)) { string line; while ((line = r1.ReadLine()) != null) { string trimLine = line.TrimStart(); if (trimLine == expectedText) { string indentation = line.Substring(0, line.Length - trimLine.Length); using (StringReader r2 = new StringReader(codeForNewType)) { while ((line = r2.ReadLine()) != null) { w.Write(indentation); w.WriteLine(line); } } } else { w.WriteLine(line); } } } if (visitor.firstType) { w.WriteLine(codeForNewType); } return(w.ToString()); } }
// Steps to load the designer: // - Parse main file // - Find other files containing parts of the form // - Parse all files and look for fields (for controls) and InitializeComponents method // - Create CodeDom objects for fields and InitializeComponents statements // - If debug build and Ctrl pressed, output CodeDom to console // - Return CodeDom objects to the .NET designer protected override CodeCompileUnit Parse() { LoggingService.Debug("NRefactoryDesignerLoader.Parse()"); lastTextContent = this.Generator.ViewContent.DesignerCodeFileContent; ParseInformation parseInfo = ParserService.GetParseInformation(this.Generator.ViewContent.DesignerCodeFile.FileName); IClass formClass; bool isFirstClassInFile; IList <IClass> parts = FindFormClassParts(parseInfo, out formClass, out isFirstClassInFile); const string missingReferenceMessage = "Your project is missing a reference to '${Name}' - please add it using 'Project > Add Reference'."; if (formClass.ProjectContent.GetClass("System.Drawing.Point", 0) == null) { throw new FormsDesignerLoadException( StringParser.Parse( missingReferenceMessage, new string[, ] { { "Name", "System.Drawing" } } )); } if (formClass.ProjectContent.GetClass("System.Windows.Forms.Form", 0) == null) { throw new FormsDesignerLoadException( StringParser.Parse( missingReferenceMessage, new string[, ] { { "Name", "System.Windows.Forms" } } )); } List <KeyValuePair <string, CompilationUnit> > compilationUnits = new List <KeyValuePair <string, CompilationUnit> >(); bool foundInitMethod = false; foreach (IClass part in parts) { string fileName = part.CompilationUnit.FileName; if (fileName == null) { continue; } bool found = false; foreach (KeyValuePair <string, CompilationUnit> entry in compilationUnits) { if (FileUtility.IsEqualFileName(fileName, entry.Key)) { found = true; break; } } if (found) { continue; } ITextBuffer fileContent; if (FileUtility.IsEqualFileName(fileName, this.Generator.ViewContent.PrimaryFileName)) { fileContent = this.Generator.ViewContent.PrimaryFileContent; } else if (FileUtility.IsEqualFileName(fileName, this.Generator.ViewContent.DesignerCodeFile.FileName)) { fileContent = new StringTextBuffer(this.Generator.ViewContent.DesignerCodeFileContent); } else { fileContent = ParserService.GetParseableFileContent(fileName); } ICSharpCode.NRefactory.IParser p = ICSharpCode.NRefactory.ParserFactory.CreateParser(language, fileContent.CreateReader()); p.Parse(); if (p.Errors.Count > 0) { throw new FormsDesignerLoadException("Syntax errors in " + fileName + ":\r\n" + p.Errors.ErrorOutput); } // Try to fix the type names to fully qualified ones FixTypeNames(p.CompilationUnit, part.CompilationUnit, ref foundInitMethod); compilationUnits.Add(new KeyValuePair <string, CompilationUnit>(fileName, p.CompilationUnit)); } if (!foundInitMethod) { throw new FormsDesignerLoadException("The InitializeComponent method was not found. Designer cannot be loaded."); } CompilationUnit combinedCu = new CompilationUnit(); NamespaceDeclaration nsDecl = new NamespaceDeclaration(formClass.Namespace); combinedCu.AddChild(nsDecl); TypeDeclaration formDecl = new TypeDeclaration(Modifiers.Public, null); nsDecl.AddChild(formDecl); formDecl.Name = formClass.Name; foreach (KeyValuePair <string, CompilationUnit> entry in compilationUnits) { foreach (object o in entry.Value.Children) { TypeDeclaration td = o as TypeDeclaration; if (td != null && td.Name == formDecl.Name) { foreach (INode node in td.Children) { formDecl.AddChild(node); } formDecl.BaseTypes.AddRange(td.BaseTypes); } if (o is NamespaceDeclaration) { foreach (object o2 in ((NamespaceDeclaration)o).Children) { td = o2 as TypeDeclaration; if (td != null && td.Name == formDecl.Name) { foreach (INode node in td.Children) { formDecl.AddChild(node); } formDecl.BaseTypes.AddRange(td.BaseTypes); } } } } } CodeDomVisitor visitor = new CodeDomVisitor(); visitor.EnvironmentInformationProvider = new ICSharpCode.SharpDevelop.Dom.NRefactoryResolver.NRefactoryInformationProvider(formClass.ProjectContent); visitor.VisitCompilationUnit(combinedCu, null); // output generated CodeDOM to the console : #if DEBUG if ((Control.ModifierKeys & Keys.Control) == Keys.Control) { CodeDomVerboseOutputGenerator outputGenerator = new CodeDomVerboseOutputGenerator(); outputGenerator.GenerateCodeFromMember(visitor.codeCompileUnit.Namespaces[0].Types[0], Console.Out, null); this.CodeDomProvider.GenerateCodeFromCompileUnit(visitor.codeCompileUnit, Console.Out, null); } #endif LoggingService.Debug("NRefactoryDesignerLoader.Parse() finished"); if (!isFirstClassInFile) { MessageService.ShowWarning("The form must be the first class in the file in order for form resources be compiled correctly.\n" + "Please move other classes below the form class definition or move them to other files."); } return(visitor.codeCompileUnit); }
public void RunVisitor() { if (searchedMember == null) { return; } // search if the member name exists in the file (otherwise it doesn't make sense to search it) FindReplace findReplace = new FindReplace(); FilterOptions filterOptions = new FilterOptions { CaseSensitive = true, WholeWordsOnly = true }; findReplace.CompilePattern(searchedMemberName, filterOptions); IEnumerable <SearchResult> result = findReplace.Search(new FileProvider(null), text.Text, searchedMemberName, null, filterOptions); if (result == null || !result.Any()) { return; } string parseText = text.Text; ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.CSharp, new StringReader(parseText)); parser.Lexer.EvaluateConditionalCompilation = true; parser.Parse(); resolver.SetupParsedCompilationUnit(parser.CompilationUnit); VisitCompilationUnit(parser.CompilationUnit, null); List <HashSet <string> > usedIdentifiers = GetUsedDefineCombinations(parser); for (int i = 0; i < usedIdentifiers.Count; i++) { parser.Lexer.ConditionalCompilationSymbols.Clear(); foreach (string define in usedIdentifiers[i]) { parser.Lexer.ConditionalCompilationSymbols.Add(define, true); } parser.Dispose(); parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.CSharp, new StringReader(parseText)); parser.Parse(); VisitCompilationUnit(parser.CompilationUnit, null); } if (IncludeXmlDocumentation) { if (searchedMember is IParameter) { IParameter parameter = (IParameter)searchedMember; var docComments = from ICSharpCode.NRefactory.Comment cmt in (from ISpecial s in parser.Lexer.SpecialTracker.CurrentSpecials where s is ICSharpCode.NRefactory.Comment && s.StartPosition.Line <= parameter.DeclaringMember.Location.Line select s) select cmt; ICSharpCode.NRefactory.Comment lastComment = null; foreach (ICSharpCode.NRefactory.Comment curComment in docComments.Reverse()) { if (lastComment != null && Math.Abs(lastComment.StartPosition.Line - curComment.StartPosition.Line) > 1) { break; } // Concat doesn't work on MatchCollections foreach (var matchCol in new [] { paramRegex.Matches(curComment.CommentText), paramRefRegex.Matches(curComment.CommentText) }) { foreach (Match match in matchCol) { if (match.Groups[1].Value == searchedMemberName) { AddUniqueReference(curComment.StartPosition.Line, curComment.StartPosition.Column + match.Groups[1].Index, searchedMemberName); } } } lastComment = curComment; } } else if (searchedMember is IMember) { IMember member = (IMember)searchedMember; var docComments = from ICSharpCode.NRefactory.Comment cmt in (from ISpecial s in parser.Lexer.SpecialTracker.CurrentSpecials where s is ICSharpCode.NRefactory.Comment select s) select cmt; string fullName = member.FullName; foreach (ICSharpCode.NRefactory.Comment curComment in docComments) { // Concat doesn't work on MatchCollections foreach (var matchCol in new [] { seeRegex.Matches(curComment.CommentText), seeAlsoRegRegex.Matches(curComment.CommentText) }) { foreach (Match match in matchCol) { if (match.Groups[1].Value.StartsWith(fullName)) { AddUniqueReference(curComment.StartPosition.Line, curComment.StartPosition.Column + match.Groups[1].Index + fullName.Length - searchedMemberName.Length, searchedMemberName); } } } } } } parser.Dispose(); }
string GetFormattedText(PolicyContainer policyParent, string input) { hasErrors = false; if (string.IsNullOrEmpty(input)) { return(input); } CSharpOutputVisitor outputVisitor = new CSharpOutputVisitor(); SetFormatOptions(outputVisitor, policyParent); outputVisitor.OutputFormatter.IndentationLevel = startIndentLevel; using (ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(input))) { parser.Parse(); hasErrors = parser.Errors.Count != 0; // if (hasErrors) // Console.WriteLine (parser.Errors.ErrorOutput); IList <ISpecial> specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); if (parser.Errors.Count == 0) { using (SpecialNodesInserter.Install(specials, outputVisitor)) { parser.CompilationUnit.AcceptVisitor(outputVisitor, null); } return(outputVisitor.Text); } } // Console.WriteLine ("trying to parse block."); using (ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(input))) { BlockStatement blockStatement = parser.ParseBlock(); hasErrors = parser.Errors.Count != 0; // if (hasErrors) // Console.WriteLine (parser.Errors.ErrorOutput); IList <ISpecial> specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); if (parser.Errors.Count == 0) { StringBuilder result = new StringBuilder(); using (var inserter = SpecialNodesInserter.Install(specials, outputVisitor)) { foreach (ICSharpCode.NRefactory.Ast.INode node in blockStatement.Children) { node.AcceptVisitor(outputVisitor, null); // result.AppendLine (outputVisitor.Text); } if (!outputVisitor.OutputFormatter.LastCharacterIsNewLine) { outputVisitor.OutputFormatter.NewLine(); } inserter.Finish(); result.AppendLine(outputVisitor.Text); } return(result.ToString()); } } // Console.WriteLine ("trying to parse expression."); using (ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(input))) { Expression expression = parser.ParseExpression(); hasErrors = parser.Errors.Count != 0; // if (hasErrors) // Console.WriteLine (parser.Errors.ErrorOutput); IList <ISpecial> specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); if (parser.Errors.Count == 0) { using (SpecialNodesInserter.Install(specials, outputVisitor)) { expression.AcceptVisitor(outputVisitor, null); } return(outputVisitor.Text); } } return(input); }