public string GetSourceCodeForFile(string pMixinsRecipesFile, string className) { if (!pMixinsRecipesFile.StartsWith("pMixins.Mvc.Recipes/")) { pMixinsRecipesFile = "pMixins.Mvc.Recipes/" + pMixinsRecipesFile; } var fileContents = GetSourceFile(pMixinsRecipesFile); if (string.IsNullOrEmpty(fileContents)) { _log.InfoFormat("Could not read file at [{0}]", pMixinsRecipesFile); return(string.Empty); } var syntaxTree = _parser.Parse(fileContents); return (syntaxTree.Descendants.OfType <TypeDeclaration>() .Where(x => x.Name.Equals(className, StringComparison.InvariantCultureIgnoreCase)) .Select(x => x.GetText().Trim()) //I HATE REGEX //.Select(x => spaceParanthCleanupRegex.Replace(x, "(")) .Select(x => x.Replace(" (", "(").Replace("=(", "= (").Replace("\t", " ")) .FirstOrDefault()); }
public MethodResult ExtractPrototypeAndMethod(string code) { Guard.AgainstNullArgument("code", code); var @class = "class A { " + code + " } "; var visitor = new MethodVisitor(); var parser = new CSharpParser(); var syntaxTree = parser.Parse(@class); syntaxTree.AcceptVisitor(visitor); syntaxTree.Freeze(); var result = visitor.GetMethodDeclarations().FirstOrDefault(); // find newlines in method signature to maintain linenumbers var newLines = code.Substring(0, code.IndexOf("{", StringComparison.Ordinal) - 1) .Where(x => x.Equals('\n')) .Aggregate(string.Empty, (a, c) => a + c); // use code methodblock to maintain linenumbers var codeBlock = code.Substring(code.IndexOf("{", StringComparison.Ordinal), code.LastIndexOf("}", StringComparison.Ordinal) - code.IndexOf("{", StringComparison.Ordinal) + 1); var method = result.MethodExpression.ToString(); var blockStart = method.IndexOf("{", StringComparison.Ordinal); var blockEnd = method.LastIndexOf("}", StringComparison.Ordinal); method = method.Remove(blockStart, blockEnd - blockStart + 1); method = method.Insert(blockStart, codeBlock); return new MethodResult { ProtoType = result.MethodPrototype.ToString().Trim() + newLines, MethodExpression = newLines + method.Trim() }; }
protected void Prepare(string source, bool minimizeNames = true, bool expectErrors = false) { IProjectContent project = new CSharpProjectContent(); var parser = new CSharpParser(); using (var rdr = new StringReader(source)) { var pf = new CSharpUnresolvedFile { FileName = "File.cs" }; var syntaxTree = parser.Parse(rdr, pf.FileName); syntaxTree.AcceptVisitor(new TypeSystemConvertVisitor(pf)); project = project.AddOrUpdateFiles(pf); } project = project.AddAssemblyReferences(new[] { Files.Mscorlib }); _errorReporter = new MockErrorReporter(!expectErrors); var compilation = project.CreateCompilation(); var s = new AttributeStore(compilation, _errorReporter); RunAutomaticMetadataAttributeAppliers(s, compilation); s.RunAttributeCode(); Metadata = new MetadataImporter(_errorReporter, compilation, s, new CompilerOptions { MinimizeScript = minimizeNames }); Metadata.Prepare(compilation.GetAllTypeDefinitions()); AllErrors = _errorReporter.AllMessages.ToList().AsReadOnly(); AllErrorTexts = _errorReporter.AllMessages.Select(m => m.FormattedMessage).ToList().AsReadOnly(); if (expectErrors) { Assert.That(AllErrorTexts, Is.Not.Empty, "Compile should have generated errors"); } else { Assert.That(AllErrorTexts, Is.Empty, "Compile should not generate errors"); } AllTypes = compilation.MainAssembly.TopLevelTypeDefinitions.SelectMany(SelfAndNested).ToDictionary(t => t.ReflectionName); }
public virtual List<CSClass> ParseString(string data, string filePath, string projectDirectory, IEnumerable<CSClass> existingClassList) { string relativeFilePath = filePath.Replace(projectDirectory,""); if(relativeFilePath.StartsWith("\\")) { relativeFilePath = relativeFilePath.Substring(1); } List<CSClass> returnValue = new List<CSClass>(existingClassList ?? new CSClass[]{} ); var parser = new CSharpParser(); var compilationUnit = parser.Parse(data, filePath); var namespaceNodeList = compilationUnit.Children.Where(i=>i is NamespaceDeclaration); foreach(NamespaceDeclaration namespaceNode in namespaceNodeList) { var typeDeclarationNodeList = namespaceNode.Children.Where(i=>i is TypeDeclaration); foreach(TypeDeclaration typeDeclarationNode in typeDeclarationNodeList) { var classObject = returnValue.SingleOrDefault(i=>i.ClassName == typeDeclarationNode.Name && i.NamespaceName == namespaceNode.FullName); if(classObject == null) { classObject = new CSClass { NamespaceName = namespaceNode.FullName, ClassName = typeDeclarationNode.Name }; returnValue.Add(classObject); } ClassParser.BuildClass(classObject, typeDeclarationNode, relativeFilePath); } } return returnValue; }
public static void Main(string[] args) { var server = new TcpListener(IPAddress.Loopback, 5556); server.Start(); while (true) { var newClient = server.AcceptTcpClient(); Console.WriteLine("Got new client."); using (var clientStream = newClient.GetStream()) { var request = CSharpParseRequest.ParseDelimitedFrom(clientStream); Console.WriteLine("Starting collecting AST for:\n"); Console.WriteLine(request.Filename); var parser = new CSharpParser(); var csFile = new FileStream(request.Filename, FileMode.Open); var cu = parser.Parse(csFile); var resultBuilder = CSharpParseResult.CreateBuilder(); foreach (var child in cu.Children) { var builder = Landman.Rascal.CSharp.Profobuf.AstNode.CreateBuilder(); GenerateNode(child, builder); resultBuilder.AddResult(builder); } resultBuilder.Build().WriteDelimitedTo(clientStream); Console.WriteLine("\nFinished"); } } }
public ParseInformation Parse(FileName fileName, ITextSource fileContent, bool fullParseInformationRequested, IProject parentProject, CancellationToken cancellationToken) { var csharpProject = parentProject as CSharpProject; CSharpParser parser = new CSharpParser(csharpProject != null ? csharpProject.CompilerSettings : null); parser.GenerateTypeSystemMode = !fullParseInformationRequested; SyntaxTree cu = parser.Parse(fileContent, fileName); cu.Freeze(); CSharpUnresolvedFile file = cu.ToTypeSystem(); ParseInformation parseInfo; if (fullParseInformationRequested) parseInfo = new CSharpFullParseInformation(file, fileContent.Version, cu); else parseInfo = new ParseInformation(file, fileContent.Version, fullParseInformationRequested); IDocument document = fileContent as IDocument; AddCommentTags(cu, parseInfo.TagComments, fileContent, parseInfo.FileName, ref document); if (fullParseInformationRequested) { if (document == null) document = new ReadOnlyDocument(fileContent, parseInfo.FileName); ((CSharpFullParseInformation)parseInfo).newFoldings = CreateNewFoldings(cu, document); } return parseInfo; }
public void TestCapturedForeachInCSharp4() { var parser = new CSharpParser(); var tree = parser.Parse(@" using System; class TestClass { void TestMethod() { int? accum = 0; foreach (var x in new int?[] { 1, 2, 3}) { Action action = () => { x = null; }; accum += x; } } } ", "test.cs"); Assert.AreEqual(0, tree.Errors.Count); var method = tree.Descendants.OfType<MethodDeclaration>().Single(); var analysis = CreateNullValueAnalysis(tree, method, false); var foreachStatement = (ForeachStatement)method.Body.Statements.ElementAt(1); var foreachBody = (BlockStatement)foreachStatement.EmbeddedStatement; var action = foreachBody.Statements.First(); var lastStatement = method.Body.Statements.Last(); Assert.AreEqual(NullValueStatus.CapturedUnknown, analysis.GetVariableStatusBeforeStatement(action, "x")); Assert.AreEqual(NullValueStatus.CapturedUnknown, analysis.GetVariableStatusAfterStatement(action, "x")); Assert.AreEqual(NullValueStatus.Unknown, analysis.GetVariableStatusAfterStatement(lastStatement, "accum")); }
public static void ClassInitialize(TestContext context) { Token[] psTokens; ParseError[] psErrors; var ast = Parser.ParseFile(Path.Combine(context.DeploymentDirectory, ExpectationsFile), out psTokens, out psErrors); var items = ast.EndBlock.FindAll(m => m is AssignmentStatementAst, false); Expectations = new Dictionary<string, string>(); foreach (AssignmentStatementAst item in items) { var variableExpression = item.Left as VariableExpressionAst; var scriptBlockAst = item.Right.Find(m => m is ScriptBlockAst, true) as ScriptBlockAst; if (variableExpression != null && scriptBlockAst != null) { Expectations.Add(variableExpression.VariablePath.UserPath, scriptBlockAst.Extent.ToString().Trim('}', '{').Trim()); } } TestData = new Dictionary<string, string>(); var parser = new CSharpParser(); var syntaxTree = parser.Parse(File.ReadAllText(Path.Combine(context.DeploymentDirectory, TestDataFile))); foreach (NamespaceDeclaration namespaceDeclaration in syntaxTree.Members.Where(m => m is NamespaceDeclaration)) { TestData.Add(namespaceDeclaration.FullName, namespaceDeclaration.ToString()); } }
public static List<CSharpClassAst> GetCSharpClasses(this AssignmentStatementAst ast) { var result = new List<CSharpClassAst>(); var parser = new CSharpParser(); foreach (var str in ast.Right.FindAll(x => x is StringConstantExpressionAst,true)) { var value = ((StringConstantExpressionAst)str).Value; var syntaxTree = parser.Parse(value); if (!syntaxTree.Errors.Any()) foreach (var child in syntaxTree.Children) { var tree = child as TypeDeclaration; if (tree != null) { if (tree.ClassType == ClassType.Class) result.Add(new CSharpClassAst(tree, (StringConstantExpressionAst)str)); } } } return result; }
public static ICSharpCode.NRefactory.CSharp.CompilationUnit Parse(this ICSharpCode.NRefactory.CSharp.CSharpParser parser, TextEditorData data) { using (var stream = data.OpenStream()) { return(parser.Parse(stream, data.Document.FileName)); } }
protected override void Run () { MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument; CSharpParser parser = new CSharpParser (); var unit = parser.Parse (doc.Editor); if (unit == null) return; var node = unit.GetNodeAt (doc.Editor.Caret.Line, doc.Editor.Caret.Column); if (node == null) return; Stack<AstNode > nodeStack = new Stack<AstNode> (); nodeStack.Push (node); if (doc.Editor.IsSomethingSelected) { while (node != null && doc.Editor.MainSelection.IsSelected (node.StartLocation.Line, node.StartLocation.Column, node.EndLocation.Line, node.EndLocation.Column)) { node = node.Parent; if (node != null) { if (nodeStack.Count > 0 && nodeStack.Peek ().StartLocation == node.StartLocation && nodeStack.Peek ().EndLocation == node.EndLocation) nodeStack.Pop (); nodeStack.Push (node); } } } if (nodeStack.Count > 2) { nodeStack.Pop (); // parent nodeStack.Pop (); // current node node = nodeStack.Pop (); // next children in which the caret is doc.Editor.SetSelection (node.StartLocation.Line, node.StartLocation.Column, node.EndLocation.Line, node.EndLocation.Column); } else { doc.Editor.ClearSelection (); } }
protected void BuildSyntaxTree() { for (int i = 0; i < this.SourceFiles.Count; i++) { var fileName = this.SourceFiles[i]; using (var reader = new StreamReader(fileName)) { var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser(); if (!string.IsNullOrEmpty(Defines)) { string[] defs = Defines.Split(';'); foreach (string def in defs) { parser.CompilerSettings.ConditionalSymbols.Add(def); } } if (this.DefineConstants != null && this.DefineConstants.Count > 0) { foreach (var defineConstant in this.DefineConstants) { parser.CompilerSettings.ConditionalSymbols.Add(defineConstant); } } var syntaxTree = parser.Parse(reader, fileName); if (parser.HasErrors) { foreach (var error in parser.Errors) { throw new EmitterException(syntaxTree, string.Format("Parsing error in a file {0} {2}: {1}", fileName, error.Message, error.Region.Begin.ToString())); } } var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree); syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree); var emptyLambdaDetecter = new EmptyLambdaDetecter(); syntaxTree.AcceptVisitor(emptyLambdaDetecter); if (emptyLambdaDetecter.Found) { var fixer = new EmptyLambdaFixer(); var astNode = syntaxTree.AcceptVisitor(fixer); syntaxTree = (astNode != null ? (SyntaxTree)astNode : syntaxTree); } var f = new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile { FileName = fileName }); this.ParsedSourceFiles.Add(f); var tcv = new TypeSystemConvertVisitor(f.ParsedFile); f.SyntaxTree.AcceptVisitor(tcv); } } }
public static string GetMethodBody(string sourceFilePath, string methodName, int callingLine) { if (!File.Exists(sourceFilePath)) return string.Format("{0} file not found.", Path.GetFileName(sourceFilePath)); try { var parser = new CSharpParser(); var syntaxTree = parser.Parse(File.ReadAllText(sourceFilePath)); var result = syntaxTree.Descendants.OfType<MethodDeclaration>() .FirstOrDefault(y => y.NameToken.Name == methodName && y.EndLocation.Line > callingLine); if (result != null) { return result.ToString(FormattingOptionsFactory.CreateSharpDevelop()).Trim(); } result = syntaxTree.Descendants.OfType<MethodDeclaration>() .FirstOrDefault(y => y.NameToken.Name == methodName); if (result != null) { return result.ToString(FormattingOptionsFactory.CreateSharpDevelop()).Trim(); } } catch { return readLines(sourceFilePath, callingLine); } return readLines(sourceFilePath, callingLine); }
IUnresolvedFile Parse(string fileName, string code) { var parser = new CSharpParser(); var syntaxTree = parser.Parse(code, fileName); Assert.IsFalse(parser.HasErrors); return syntaxTree.ToTypeSystem(); }
public ConvertionResult ToKnockoutVm(string code, TranslateOptions options = null) { if(options == null) { options = TranslateOptions.Defaults; } _log.Debug("Converting code to Knockout VM. Options:\n{0}\nCode:\n{1}", options.ToFormattedJson(), code); Func<ConvertionResult, ConvertionResult> exit = r => { _log.Debug("Returning Convertion Result: {0}", r.ToFormattedJson()); return r; }; var result = new ConvertionResult(); if(code.IsNullOrEmpty()) { result.Success = false; result.Message = "No code provided"; return exit(result); } // do convertion code = code.AddDefaultUsings(); var visitor = new NRefactoryVisitor(options); var textReader = new StringReader(code); var parser = new CSharpParser(); var cu = parser.Parse(textReader, "dummy.cs"); if(parser.HasErrors) { var errors = cu.GetErrors(); var warnings = cu.GetErrors(ErrorType.Warning); result.Success = false; result.Message = "Error parsing code file."; result.Errors.AddRange(errors); result.Warnings.AddRange(warnings); return exit(result); } if(parser.HasWarnings) { var warnings = cu.GetErrors(ErrorType.Warning); result.Message = "Parsed code contains warnings!"; result.Warnings.AddRange(warnings); } cu.AcceptVisitor(visitor); var writter = new KnockoutWritter(); var convertedCode = writter.Write(visitor.Result, options); result.Success = true; result.Code = convertedCode; return exit(result); }
public ParseResult Parse(string code) { var result = new ParseResult(); var parser = new CSharpParser(); var syntaxTree = parser.Parse(code); var codeLines = code.Split(new[] { Environment.NewLine }, StringSplitOptions.None); var codeLinesDictionary = new Dictionary<int, Tuple<string, bool>>(); for (int i = 0; i < codeLines.Length; i++) { codeLinesDictionary.Add(i, new Tuple<string, bool>(codeLines[i], true)); } var typeMembersTree = parser.ParseTypeMembers(code); foreach (var typeMember in typeMembersTree.Where(x => x is TypeDeclaration || x is MethodDeclaration)) { var element = typeMember.GetText(); if (typeMember is TypeDeclaration) { result.Declarations += element; } //else //{ // result.Declarations += "public static partial ScriptCsMethod {"; // result.Declarations += element; // result.Declarations += "}"; //} for (var i = typeMember.StartLocation.Line - 1; i < typeMember.StartLocation.Line; i++) { var oldItem = codeLinesDictionary[i]; codeLinesDictionary[i] = new Tuple<string, bool>(oldItem.Item1, false); } } var keysToRemove = codeLinesDictionary.Where(x => x.Value.Item2 == false).Select(i => i.Key); keysToRemove.ToList().ForEach(x => codeLinesDictionary.Remove(x)); foreach (var correct in syntaxTree.Members) { var element = correct.GetText(); ; result.Declarations += element; } if (syntaxTree.Errors.Any()) { var evalLines = codeLines.Skip(syntaxTree.Errors.First().Region.BeginLine - 1).ToList(); result.Evaluations += string.Join(Environment.NewLine, evalLines); //result.Evaluations = "public void ScriptCsInvoke() {" + Environment.NewLine; //result.Evaluations = string.Join(Environment.NewLine, codeLinesDictionary.Select(i => i.Value.Item1)); //result.Evaluations += Environment.NewLine + "}"; } var evaluationTree = parser.ParseStatements(result.Evaluations); return result; }
private static IEnumerable<AstNode> ParseAsMethodBody(CSharpParser parser, ref string sourceCode) { sourceCode = ExtraCode.Add( before: "unsafe partial class MyClass { void M() { ", code: sourceCode, after: "}}"); return parser.Parse(new StringReader(sourceCode), "").Children; }
public void AddMethod(string methodCode) { var parser = new CSharpParser(); var syntaxTree = parser.Parse("public class Foo{" + methodCode + "}"); var method = syntaxTree.Children.First().Children.First(x => x is MethodDeclaration).Clone(); tree.AddChild<EntityDeclaration>((EntityDeclaration)method, Roles.TypeMemberRole); }
protected static TypeDeclaration ParseType(string code) { var cSharpParser = new CSharpParser(); var tree = cSharpParser.Parse(code); Assert.AreEqual(0, tree.Errors.Count, tree.Errors.Aggregate("", (s, e) => s + e.Message + "\r\n")); var type = tree.GetTypes().Single(); return (TypeDeclaration)type; }
private SyntaxTree ReadSyntaxTree(Stream stream) { using (var streamReader = new StreamReader(stream)) { var codeParser = new CSharpParser(); return(codeParser.Parse(streamReader)); } }
internal static int Main(string[] args) { Console.WriteLine("Empty try catch finder, version {0}.", Assembly.GetExecutingAssembly().GetName().Version); Console.WriteLine("Copyright © dmportella 2012 all right reserved."); Console.WriteLine(Environment.NewLine); int errorCount = 0; CSharpParser parser = new CSharpParser(); foreach(string fileName in Directory.GetFiles(args[0], "*.cs", SearchOption.AllDirectories)) { SyntaxTree syntaxTree = null; using (FileStream file = File.OpenRead(fileName)) { syntaxTree = parser.Parse(file); } foreach (CatchClause node in syntaxTree.Descendants.OfType<CatchClause>()) { if (node.Body.Statements.Count == 0) { FileInfo inf = new FileInfo(fileName); Console.WriteLine("Error: Found a empty catch on {0} line {1}.", inf.FullName, node.StartLocation.Line); errorCount++; } else { //TODO just scanning the first instance will change that to loop through them all at some point. ThrowStatement throwStatement = node.Descendants.OfType<ThrowStatement>().FirstOrDefault(); if (throwStatement != null && (throwStatement.Expression as IdentifierExpression) != null) { IdentifierExpression ex = throwStatement.Expression as IdentifierExpression; if (string.Compare(node.VariableName, ex.Identifier, false) == 0) { FileInfo inf = new FileInfo(fileName); Console.WriteLine("Error: Found a catch block with a bad rethrow on {0} line {1}.", inf.FullName, node.StartLocation.Line); errorCount++; } } } } } Console.WriteLine(Environment.NewLine); Console.WriteLine("Number of errors found: {0}", errorCount); return errorCount; }
public ParsedDocument Parse(bool storeAst, string fileName, System.IO.TextReader content, MonoDevelop.Projects.Project project = null) { var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser(GetCompilerArguments(project)); parser.GenerateTypeSystemMode = !storeAst; var result = new ParsedDocumentDecorator(); if (project != null) { var projectFile = project.Files.GetFile(fileName); if (projectFile != null && projectFile.BuildAction != BuildAction.Compile) { result.Flags |= ParsedDocumentFlags.NonSerializable; } } var tagComments = CommentTag.SpecialCommentTags.Select(t => t.Tag).ToArray(); parser.CompilationUnitCallback = delegate(CompilerCompilationUnit top) { foreach (var special in top.SpecialsBag.Specials) { var comment = special as SpecialsBag.Comment; if (comment != null) { VisitComment(result, comment, tagComments); } else { if (storeAst) { VisitPreprocessorDirective(result, special as SpecialsBag.PreProcessorDirective); } } } }; var unit = parser.Parse(content, fileName); unit.Freeze(); var pf = unit.ToTypeSystem(); try { pf.LastWriteTime = System.IO.File.GetLastWriteTimeUtc(fileName); } catch (Exception) { pf.LastWriteTime = DateTime.UtcNow; } result.LastWriteTimeUtc = pf.LastWriteTime.Value; result.ParsedFile = pf; result.Add(GenerateFoldings(unit, result)); if (storeAst) { result.Ast = unit; } return(result); }
public bool IsClass(string code) { var visitor = new ClassTypeVisitor(); var parser = new CSharpParser(); var syntaxTree = parser.Parse(code); syntaxTree.AcceptVisitor(visitor); syntaxTree.Freeze(); return visitor.GetClassDeclarations().Any(); }
private static IList<MethodVisitorResult> ExtractMethodDeclaration(string code) { var visitor = new MethodVisitor(); var parser = new CSharpParser(); var syntaxTree = parser.Parse(code); syntaxTree.AcceptVisitor(visitor); syntaxTree.Freeze(); return visitor.GetMethodDeclarations(); }
public override UnifiedProgram GenerateWithoutNormalizing(string code) { var parser = new CSharpParser(); var reader = new StringReader(code); // TODO: use proper value for the second argument var unit = parser.Parse(reader, "TextReader"); var visitor = new NRefactoryAstVisitor(); var uElem = unit.AcceptVisitor(visitor, null); return uElem as UnifiedProgram; }
public CSharpFile(CSharpProject project, FileName fileName) { this.Project = project; this.FileName = fileName; this.OriginalText = File.ReadAllText(fileName); CSharpParser p = new CSharpParser(project.CompilerSettings); this.SyntaxTree = p.Parse(this.OriginalText, fileName); this.UnresolvedTypeSystemForFile = SD.ParserService.GetExistingUnresolvedFile(fileName, null, project.IProject) as CSharpUnresolvedFile; if (this.UnresolvedTypeSystemForFile == null) throw new InvalidOperationException("LoadSolutionProjectsThread not yet finished?"); }
void CSharpParseButtonClick(object sender, EventArgs e) { CSharpParser parser = new CSharpParser(); compilationUnit = parser.Parse(new StringReader(csharpCodeTextBox.Text)); csharpTreeView.Nodes.Clear(); foreach (var element in compilationUnit.Children) { csharpTreeView.Nodes.Add(MakeTreeNode(element)); } SelectCurrentNode(csharpTreeView.Nodes); resolveButton.Enabled = true; }
public LocatorCSharpParser(TextReader input) { CSharpParser parser = new CSharpParser(); CompilationUnit compilationUnit = parser.Parse(input, ""); this.VisitCompilationUnit(compilationUnit); /*foreach (KeyValuePair<string, TypeDeclDict> entry in _classes) { Console.WriteLine("talking about " + entry.Key); entry.Value.debug(); }*/ }
public Fact(TextReader input) { CSharpParser parser = new CSharpParser(); CompilationUnit unit = parser.Parse(input, ""); this.VisitCompilationUnit(unit); for (int j = 0; j < comments.Count; j++) if (comments[j].StartLocation.Line< firstClassStartLine) comment += comments[j].GetText().Replace("//","").Replace("\n", "\\n"); }
private static IList<TypeDeclaration> ExtractClassDeclarations(string className, string code) { var visitor = new ClassTypeVisitor(); var parser = new CSharpParser(); var syntaxTree = parser.Parse(code); syntaxTree.AcceptVisitor(visitor); syntaxTree.Freeze(); return visitor.GetClassDeclarations() .Where(x => !x.GetText().StartsWith(string.Format("class {0}", className))) .ToList(); }
public CSharpFile(CSharpProject project, string fileName) { Project = project; FileName = fileName; OriginalText = File.ReadAllText(fileName, Encoding.Default); var p = new CSharpParser(project.CompilerSettings); SyntaxTree = p.Parse(OriginalText, fileName); UnresolvedTypeSystemForFile = SyntaxTree.ToTypeSystem(); LinesOfCode = 1 + OriginalText.Count(c => c == '\n'); }
public bool IsMethod(string code) { Guard.AgainstNullArgument("code", code); var @class = "class A { " + code + " } "; var visitor = new MethodVisitor(); var parser = new CSharpParser(); var syntaxTree = parser.Parse(@class); syntaxTree.AcceptVisitor(visitor); syntaxTree.Freeze(); return visitor.GetMethodDeclarations().Any() && code.TrimEnd().EndsWith("}"); }
private static string CSharpToPowerShell(string csharp) { CSharpParser parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(csharp); CodeDomConvertVisitor visitor = new CodeDomConvertVisitor(); var codeObject = syntaxTree.AcceptVisitor(visitor); var stringWriter = new StringWriter(); var powerShellProvider = new PowerShellCodeDomProvider(); powerShellProvider.GenerateCodeFromCompileUnit(codeObject as CodeCompileUnit, stringWriter, new CodeGeneratorOptions()); return stringWriter.ToString(); }
public File(Project project, string name) : base(project, name) { var parser = new CSharpParser(Utils.Convert.ToCompilerSettings(Project.CompilerSettings)); SyntaxTree = parser.Parse(Content, Name); if (parser.HasErrors) { var exceptionMessage = string.Format("Error parsing {0}:\n", Name); exceptionMessage = parser.ErrorsAndWarnings.Aggregate(exceptionMessage, (current, error) => current + string.Format("{0} {1} \n", error.Region, error.ErrorType)); throw new ParseException(exceptionMessage); } UnresolvedTypeSystemForFile = SyntaxTree.ToTypeSystem(); }
public LocatorCSharpParser(String filePath, bool overload) { this.overload = overload; TextReader reader = File.OpenText(filePath); CSharpParser parser = new CSharpParser(); CompilationUnit compilationUnit = parser.Parse(reader, filePath); this.VisitCompilationUnit(compilationUnit); //Console.WriteLine("iterating over"); //foreach (KeyValuePair<string, Tupel> entry in _methodRanges) // Console.WriteLine(entry.Key + ": " + entry.Value.toJSON()); }
protected virtual SyntaxTree GetSyntaxTree(string fileName) { using (var reader = new StreamReader(fileName)) { var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser(); var syntaxTree = parser.Parse(reader, fileName); if (parser.HasErrors) { foreach (var error in parser.Errors) { Bridge.Translator.Exception.Throw("Parsing error in a file {0} {2}: {1}", fileName, error.Message, error.Region.Begin.ToString()); } } return(syntaxTree); } }
public static AstNode ParseSnippet(this ICSharpCode.NRefactory.CSharp.CSharpParser parser, TextEditorData data) { using (var stream = new StreamReader(data.OpenStream())) { var result = parser.ParseExpression(stream); if (!parser.HasErrors) { return(result); } } parser.ErrorPrinter.Reset(); using (var stream = new StreamReader(data.OpenStream())) { var result = parser.ParseStatements(stream); if (!parser.HasErrors) { return(result.First()); } } parser.ErrorPrinter.Reset(); using (var stream = data.OpenStream()) { return(parser.Parse(stream)); } }
public override ParsedDocument Parse(bool storeAst, string fileName, System.IO.TextReader content, MonoDevelop.Projects.Project project = null) { var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser(GetCompilerArguments(project)); parser.GenerateTypeSystemMode = !storeAst; var result = new ParsedDocumentDecorator(); if (project != null) { var projectFile = project.Files.GetFile(fileName); if (projectFile != null && !TypeSystemParserNode.IsCompileBuildAction(projectFile.BuildAction)) { result.Flags |= ParsedDocumentFlags.NonSerializable; } } var tagComments = CommentTag.SpecialCommentTags.Select(t => t.Tag).ToArray(); parser.CompilationUnitCallback = delegate(CompilerCompilationUnit top) { foreach (var special in top.SpecialsBag.Specials) { var comment = special as SpecialsBag.Comment; if (comment != null) { VisitComment(result, comment, tagComments); } else { if (storeAst) { var ppd = special as SpecialsBag.PreProcessorDirective; if (ppd != null) { VisitPreprocessorDirective(result, ppd); } } } } }; var unit = parser.Parse(content, fileName); unit.Freeze(); var pf = unit.ToTypeSystem(); try { pf.LastWriteTime = System.IO.File.GetLastWriteTimeUtc(fileName); } catch (Exception) { pf.LastWriteTime = DateTime.UtcNow; } result.LastWriteTimeUtc = pf.LastWriteTime.Value; result.ParsedFile = pf; result.Add(GetSemanticTags(unit)); result.CreateRefactoringContext = delegate(MonoDevelop.Ide.Gui.Document doc, System.Threading.CancellationToken token) { var task = MDRefactoringContext.Create(doc, doc.Editor.Caret.Location, token); task.Wait(5000, token); if (!task.IsCompleted) { return(null); } return(task.Result); }; result.CreateRefactoringContextWithEditor = (data, resolver, token) => new MDRefactoringContext((DotNetProject)project, data, result, (CSharpAstResolver)resolver, TextLocation.Empty, token); if (storeAst) { result.Ast = unit; result.Add(GenerateFoldings(unit, result)); } return(result); }
public static void Format(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, MonoDevelop.Ide.Gui.Document data, ProjectDom dom, DomLocation location, bool correctBlankLines, bool runAferCR /* = false*/) { if (data.ParsedDocument == null || data.ParsedDocument.CompilationUnit == null) { return; } var member = data.ParsedDocument.CompilationUnit.GetMemberAt(location.Line + (runAferCR ? -1 : 0), location.Column); if (member == null || member.Location.IsEmpty || member.BodyRegion.End.IsEmpty) { return; } StringBuilder sb = new StringBuilder(); int closingBrackets = 0; DomRegion validRegion = DomRegion.Empty; foreach (var u in data.ParsedDocument.CompilationUnit.Usings.Where(us => us.IsFromNamespace)) { // the dom parser breaks A.B.C into 3 namespaces with the same region, this is filtered here if (u.ValidRegion == validRegion || !u.ValidRegion.Contains(location)) { continue; } // indicates a parser error on namespace level. if (u.Namespaces.FirstOrDefault() == "<invalid>") { continue; } validRegion = u.ValidRegion; sb.Append("namespace Stub {"); sb.Append(data.Editor.EolMarker); closingBrackets++; } var parent = member.DeclaringType; while (parent != null) { sb.Append("class Stub {"); sb.Append(data.Editor.EolMarker); closingBrackets++; parent = parent.DeclaringType; } int memberStart = data.Editor.LocationToOffset(member.Location.Line, 1); int memberEnd = data.Editor.LocationToOffset(member.BodyRegion.End.Line + (runAferCR ? 1 : 0), member.BodyRegion.End.Column); if (memberEnd < 0) { memberEnd = data.Editor.Length; } int startOffset = sb.Length; sb.Append(data.Editor.GetTextBetween(memberStart, memberEnd)); int endOffset = sb.Length; sb.Append(data.Editor.EolMarker); sb.Append(new string ('}', closingBrackets)); TextEditorData stubData = new TextEditorData() { Text = sb.ToString() }; stubData.Document.FileName = data.FileName; var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser(); var compilationUnit = parser.Parse(stubData); bool hadErrors = parser.HasErrors; var policy = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain); var adapter = new TextEditorDataAdapter(stubData); var domSpacingVisitor = new AstFormattingVisitor(policy.CreateOptions(), adapter, new FormattingActionFactory(data.Editor)) { HadErrors = hadErrors }; compilationUnit.AcceptVisitor(domSpacingVisitor, null); var changes = new List <ICSharpCode.NRefactory.CSharp.Refactoring.Action> (); changes.AddRange(domSpacingVisitor.Changes.Cast <TextReplaceAction> ().Where(c => startOffset < c.Offset && c.Offset < endOffset)); int delta = memberStart - startOffset; HashSet <int> lines = new HashSet <int> (); foreach (TextReplaceAction change in changes) { change.Offset += delta; lines.Add(data.Editor.OffsetToLineNumber(change.Offset)); } // be sensible in documents with parser errors - only correct up to the caret position. if (hadErrors || data.ParsedDocument.Errors.Any(e => e.ErrorType == ErrorType.Error)) { var lastOffset = data.Editor.Caret.Offset; changes.RemoveAll(c => ((TextReplaceAction)c).Offset > lastOffset); } using (var undo = data.Editor.OpenUndoGroup()) { MDRefactoringContext.MdScript.RunActions(changes, null); foreach (int line in lines) { data.Editor.Document.CommitLineUpdate(line); } } stubData.Dispose(); }
private void BuildSyntaxTreeForFile(int index, ref string[] rewriten) { var fileName = this.SourceFiles[index]; this.Log.Trace("Source file " + (fileName ?? string.Empty) + " ..."); var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser(); if (this.DefineConstants != null && this.DefineConstants.Count > 0) { foreach (var defineConstant in this.DefineConstants) { parser.CompilerSettings.ConditionalSymbols.Add(defineConstant); } } var syntaxTree = parser.Parse(rewriten[index], fileName); syntaxTree.FileName = fileName; this.Log.Trace("\tParsing syntax tree done"); if (parser.HasErrors) { var errors = new List <string>(); foreach (var error in parser.Errors) { errors.Add(fileName + ":" + error.Region.BeginLine + "," + error.Region.BeginColumn + ": " + error.Message); } throw new EmitterException(syntaxTree, "Error parsing code." + Environment.NewLine + String.Join(Environment.NewLine, errors)); } var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree); this.Log.Trace("\tExpanding query expressions done"); syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree); var emptyLambdaDetecter = new EmptyLambdaDetecter(); syntaxTree.AcceptVisitor(emptyLambdaDetecter); this.Log.Trace("\tAccepting lambda detector visitor done"); if (emptyLambdaDetecter.Found) { var fixer = new EmptyLambdaFixer(); var astNode = syntaxTree.AcceptVisitor(fixer); this.Log.Trace("\tAccepting lambda fixer visitor done"); syntaxTree = (astNode != null ? (SyntaxTree)astNode : syntaxTree); syntaxTree.FileName = fileName; } var f = new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile { FileName = fileName }); this.ParsedSourceFiles[index] = f; var tcv = new TypeSystemConvertVisitor(f.ParsedFile); f.SyntaxTree.AcceptVisitor(tcv); this.Log.Trace("\tAccepting type system convert visitor done"); this.Log.Trace("Source file " + (fileName ?? string.Empty) + " done"); }
protected void BuildSyntaxTree() { this.Log.Info("Building syntax tree..."); var rewriter = new SharpSixRewriter(this); for (int i = 0; i < this.SourceFiles.Count; i++) { var fileName = this.SourceFiles[i]; this.Log.Trace("Source file " + (fileName ?? string.Empty) + " ..."); var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser(); if (this.DefineConstants != null && this.DefineConstants.Count > 0) { foreach (var defineConstant in this.DefineConstants) { parser.CompilerSettings.ConditionalSymbols.Add(defineConstant); } } var syntaxTree = parser.Parse(rewriter.Rewrite(i), fileName); syntaxTree.FileName = fileName; //var syntaxTree = parser.Parse(reader, fileName); this.Log.Trace("\tParsing syntax tree done"); if (parser.HasErrors) { foreach (var error in parser.Errors) { throw new EmitterException(syntaxTree, string.Format("Parsing error in a file {0} {2}: {1}", fileName, error.Message, error.Region.Begin.ToString())); } } var expandResult = new QueryExpressionExpander().ExpandQueryExpressions(syntaxTree); this.Log.Trace("\tExpanding query expressions done"); syntaxTree = (expandResult != null ? (SyntaxTree)expandResult.AstNode : syntaxTree); var emptyLambdaDetecter = new EmptyLambdaDetecter(); syntaxTree.AcceptVisitor(emptyLambdaDetecter); this.Log.Trace("\tAccepting lambda detector visitor done"); if (emptyLambdaDetecter.Found) { var fixer = new EmptyLambdaFixer(); var astNode = syntaxTree.AcceptVisitor(fixer); this.Log.Trace("\tAccepting lambda fixer visitor done"); syntaxTree = (astNode != null ? (SyntaxTree)astNode : syntaxTree); syntaxTree.FileName = fileName; } var f = new ParsedSourceFile(syntaxTree, new CSharpUnresolvedFile { FileName = fileName }); this.ParsedSourceFiles.Add(f); var tcv = new TypeSystemConvertVisitor(f.ParsedFile); f.SyntaxTree.AcceptVisitor(tcv); this.Log.Trace("\tAccepting type system convert visitor done"); this.Log.Trace("Source file " + (fileName ?? string.Empty) + " done"); } this.Log.Info("Building syntax tree done"); }
private void LoadSytanxTree(string sourceCode) { CSharpParser csParser = new CSharpParser(); syntaxTree = csParser.Parse(sourceCode); }