public void InitializeController() { // assign methods which are run durning interaction with GUI view.GetButtonLoadFile().Click += LoadOrdersFromFiles; view.GetButtonGenerateReport().Click += GenerateReport; view.GetButtonClearOrdersInDatabase().Click += ClearDataBase; // Initialize parsers ParserFactory parserFactory = new ParserFactory(); parsers.Add(parserFactory.CreateParser(ParserFactory.ParserSort.CSVParser)); parsers.Add(parserFactory.CreateParser(ParserFactory.ParserSort.JSONParser)); parsers.Add(parserFactory.CreateParser(ParserFactory.ParserSort.XMLParser)); }
internal void CanParseAllowScriptsOption(string command, AllowRunScripts?result) { var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") .WithPostActions(ProcessStartPostActionProcessor.ActionProcessorId); TemplateGroup templateGroup = TemplateGroup.FromTemplateList( CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>())) .Single(); ITemplateEngineHost host = TestHost.GetVirtualHost(); IEngineEnvironmentSettings settings = new EngineEnvironmentSettings(host, virtualizeSettings: true); TemplatePackageManager packageManager = A.Fake <TemplatePackageManager>(); NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks()); var parseResult = myCommand.Parse(command); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); TemplateCommand templateCommand = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single()); Parser parser = ParserFactory.CreateParser(templateCommand); ParseResult templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty <string>()); TemplateCommandArgs templateArgs = new TemplateCommandArgs(templateCommand, myCommand, templateParseResult); Assert.Equal(result, templateArgs.AllowScripts); }
public override void Run() { IViewContent content = WorkbenchSingleton.Workbench.ActiveViewContent; if (content != null && content.PrimaryFileName != null && content is IEditable) { IParser p = ParserFactory.CreateParser(SupportedLanguage.VBNet, new StringReader(((IEditable)content).Text)); p.Parse(); if (p.Errors.Count > 0) { MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Commands.Convert.CorrectSourceCodeErrors}\n" + p.Errors.ErrorOutput); return; } ICSharpCode.NRefactory.PrettyPrinter.CSharpOutputVisitor output = new ICSharpCode.NRefactory.PrettyPrinter.CSharpOutputVisitor(); List <ISpecial> specials = p.Lexer.SpecialTracker.CurrentSpecials; PreprocessingDirective.VBToCSharp(specials); IAstVisitor v = new VBNetToCSharpConvertVisitor(ParserService.CurrentProjectContent, ParserService.GetParseInformation(content.PrimaryFileName)); v.VisitCompilationUnit(p.CompilationUnit, null); using (SpecialNodesInserter.Install(specials, output)) { output.VisitCompilationUnit(p.CompilationUnit, null); } FileService.NewFile("Generated.cs", output.Text); } }
public void CreateParser_SingleReportFileWithSingleReport_CorrectParserIsReturned() { string filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "Partcover2.3.xml"); string parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("PartCover23Parser", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "Partcover2.2.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("PartCover22Parser", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "NCover1.5.8.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("NCoverParser", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "OpenCover.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("OpenCoverParser", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "dotCover.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("DotCoverParser", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "VisualStudio2010.coveragexml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("VisualStudioParser", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "DynamicCodeCoverage.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("DynamicCodeCoverageParser", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetJavaReportDirectory(), "Cobertura2.1.1.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("CoberturaParser", parserName, "Wrong parser"); }
void AddCsFiles(DoWorkEventArgs e, string projectBasePath, string directory) { var csFiles = Directory.GetFiles(directory, "*.cs"); foreach (var csFile in csFiles) { if (e.Cancel) { return; } using (var parser = ParserFactory.CreateParser(csFile)) { parser.ParseMethodBodies = false; parser.Parse(); if (Settings.Default.ShowMethods) { var methodsInsideCsFile = ExtractMethods(projectBasePath, csFile, parser.CompilationUnit.Children); Repository.AppendRange(methodsInsideCsFile); } if (Settings.Default.ShowProperties) { var propertiesInsideCsFile = ExtractProperties(projectBasePath, csFile, parser.CompilationUnit.Children); Repository.AppendRange(propertiesInsideCsFile); } } } }
private void ParseStep() { try { string code = null; Invoke(new MethodInvoker(delegate { code = _control.Text; })); TextReader textReader = new StringReader(code); ICompilationUnit newCompilationUnit; var supportedLanguage = SupportedLanguage == SupportedLanguage.CSharp ? ICSharpCode.NRefactory.SupportedLanguage.CSharp : ICSharpCode.NRefactory.SupportedLanguage.VBNet; using (var p = 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. ProjectContent.UpdateCompilationUnit(LastCompilationUnit, newCompilationUnit, DummyFileName); LastCompilationUnit = newCompilationUnit; ParseInformation = new ParseInformation(newCompilationUnit); } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } }
public string GetNamespaceOldRuntime(string filePath, string definedSymbols, string[] defines) { var definedSymbolSplit = definedSymbols.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var uniqueSymbols = defines.Union(definedSymbolSplit).Distinct().ToArray(); using (var parser = ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.CSharp, ReadAndConverteNewLines(filePath))) { foreach (var symbol in uniqueSymbols) { parser.Lexer.ConditionalCompilationSymbols.Add(symbol, string.Empty); } parser.Lexer.EvaluateConditionalCompilation = true; parser.Parse(); try { var visitor = new NamespaceVisitor(); var data = new VisitorData { TargetClassName = Path.GetFileNameWithoutExtension(filePath) }; parser.CompilationUnit.AcceptVisitor(visitor, data); return(string.IsNullOrEmpty(data.DiscoveredNamespace) ? string.Empty : data.DiscoveredNamespace); } catch { // Don't care; all we want is the namespace } } return(string.Empty); }
public override void Run() { IWorkbenchWindow window = WorkbenchSingleton.Workbench.ActiveWorkbenchWindow; if (window != null && window.ViewContent is IEditable) { IParser p = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(((IEditable)window.ViewContent).Text)); p.Parse(); if (p.Errors.Count > 0) { MessageService.ShowError("${res:ICSharpCode.SharpDevelop.Commands.Convert.CorrectSourceCodeErrors}\n" + p.Errors.ErrorOutput); return; } VBNetOutputVisitor vbv = new VBNetOutputVisitor(); List <ISpecial> specials = p.Lexer.SpecialTracker.CurrentSpecials; PreprocessingDirective.CSharpToVB(specials); new CSharpToVBNetConvertVisitor().VisitCompilationUnit(p.CompilationUnit, null); using (SpecialNodesInserter.Install(specials, vbv)) { vbv.VisitCompilationUnit(p.CompilationUnit, null); } FileService.NewFile("Generated.VB", "VBNET", vbv.Text); } }
private Expression GetMapExpression(string mapKey) { string program = "namespace Test { public class A { public void Method() { result = " + mapKey + "; } }}"; IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(program)); parser.ParseMethodBodies = true; parser.Parse(); CompilationUnit cu = parser.CompilationUnit; ParentVisitor parentVisitor = new ParentVisitor(); parentVisitor.VisitCompilationUnit(cu, null); TypeReferenceCorrector typeReferenceCorrector = new TypeReferenceCorrector(); typeReferenceCorrector.VisitCompilationUnit(cu, null); MappingIdentifierMarker mappingIdentifierMarker = new MappingIdentifierMarker(); mappingIdentifierMarker.MarkIdentifiers(cu); NamespaceDeclaration ns = (NamespaceDeclaration)cu.Children[0]; TypeDeclaration ty = (TypeDeclaration)ns.Children[0]; MethodDeclaration md = (MethodDeclaration)ty.Children[0]; ExpressionStatement st = (ExpressionStatement)md.Body.Children[0]; AssignmentExpression ase = (AssignmentExpression)st.Expression; return(ase); }
public void PerformanceTest() { const string codeFile = @"D:\Projects\AgentRalph.hg\Ralph.Test.Project\Ralph.Test.Project\Menus.cs"; string codeText = File.ReadAllText(codeFile); IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(codeText)); parser.Parse(); if (parser.Errors.Count > 0) { throw new ApplicationException(string.Format("Expected no errors in the input code. Code was: {0} ErrorOutput: {1}", codeText, parser.Errors.ErrorOutput)); } MethodsOnASingleClassCloneFinder cloneFinder = new MethodsOnASingleClassCloneFinder(new OscillatingExtractMethodExpansionFactory()); cloneFinder.AddRefactoring(new LiteralToParameterExpansion()); var replacements = cloneFinder.GetCloneReplacements(parser.CompilationUnit); TestLog.EmbedPlainText(replacements.Clones.Count + " clones found."); foreach (var clone in replacements.Clones) { TestLog.EmbedPlainText(string.Format("{0}-{1}: {2}", clone.ReplacementSectionStartLine, clone.ReplacementSectionEndLine, clone.TextForACallToJanga)); } }
public JsFile GetJsFileFromCodeFile(string path, SupportedLanguage language) { TextReader textReader = File.OpenText(path); var file = new JsFile(); using (var parser = ParserFactory.CreateParser(language, textReader)) { var jsFile = new JsFile { FullPath = path }; parser.Parse(); if (parser.Errors.Count <= 0) { var visitor = new AstVisitor { Model = jsFile }; parser.CompilationUnit.AcceptVisitor(visitor, null); file = visitor.Model; return(file); } } return(null); }
static void Main(string[] args) { string code = @"using System; using System.Collections.Generic; using System.Linq; namespace MyCode { static class MyProg { static void Run() { int i = 0; i++; Log(i); } } } "; IParser p = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(code)); p.Parse(); //Output Original CSharpOutputVisitor output = new CSharpOutputVisitor(); output.VisitCompilationUnit(p.CompilationUnit, null); Console.Write(output.Text); //Add custom method calls AddMethodVisitor v = new AddMethodVisitor(); v.VisitCompilationUnit(p.CompilationUnit, null); v.AddMethodCalls(); output.VisitCompilationUnit(p.CompilationUnit, null); //Output result Console.Write(output.Text); }
T ParseMember <T>(string ext, string code) where T : INode { IParser parser = null; try { if (ext.Equals(".cs", StringComparison.OrdinalIgnoreCase)) { parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(code)); } if (ext.Equals(".vb", StringComparison.OrdinalIgnoreCase)) { parser = ParserFactory.CreateParser(SupportedLanguage.VBNet, new StringReader(code)); } if (parser == null) { return(default(T)); } var nodes = parser.ParseTypeMembers(); if (parser.Errors.Count > 0) { return(default(T)); } return((T)nodes.FirstOrDefault()); } finally { if (parser != null) { parser.Dispose(); } } }
/// <summary> /// 获得所有的regions区域信息,textspan都是基于(0,0)开始的 /// </summary> /// <param name="content"></param> /// <returns></returns> public static List <TextSpan> GetAllRegions(string content) { List <TextSpan> allRegions = new List <TextSpan>(); using (IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(content))) { parser.ParseMethodBodies = false; parser.Parse(); List <ISpecial> currentSpecials = parser.Lexer.SpecialTracker.CurrentSpecials; TextSpan textSpan = new TextSpan(); //使用栈来寻找可能嵌套的region Stack <int> stack = new Stack <int>(); foreach (ISpecial currentSpecial in currentSpecials) { if (currentSpecial is PreprocessingDirective) { PreprocessingDirective region = currentSpecial as PreprocessingDirective; if (region.Cmd == "#region") { stack.Push(region.StartPosition.Line - 1); //textSpan.iStartLine = region.StartPosition.Line - 1; } if (region.Cmd == "#endregion") { textSpan.iStartLine = stack.Pop(); textSpan.iEndLine = region.StartPosition.Line - 1; allRegions.Add(textSpan); } } } } return(allRegions); }
internal void Create_CanDetectParseErrorsChoiceTemplateOptions( string command, string parameterName, string parameterValues, bool isRequired, string?defaultValue, string?defaultIfNoOptionValue, string expectedError) { var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") .WithChoiceParameter(parameterName, parameterValues.Split("|"), isRequired, defaultValue, defaultIfNoOptionValue); TemplateGroup templateGroup = TemplateGroup.FromTemplateList( CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>())) .Single(); ITemplateEngineHost host = TestHost.GetVirtualHost(); IEngineEnvironmentSettings settings = new EngineEnvironmentSettings(host, virtualizeSettings: true); TemplatePackageManager packageManager = A.Fake <TemplatePackageManager>(); NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks()); var parseResult = myCommand.Parse($" new create {command}"); var instantiateCommand = (InstantiateCommand)parseResult.CommandResult.Command; var args = new InstantiateCommandArgs(instantiateCommand, parseResult); TemplateCommand templateCommand = new TemplateCommand(instantiateCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single()); Parser parser = ParserFactory.CreateParser(templateCommand); ParseResult templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty <string>()); Assert.True(templateParseResult.Errors.Any()); Assert.Equal(expectedError, templateParseResult.Errors.Single().Message); }
private bool CheckSyntax() { string command = console.CommandText.Trim(); // FIXME workaround the NRefactory issue that needs a ; at the end if (language == "C#") { if (!command.EndsWith(";")) { command += ";"; } // FIXME only one string should be available; highlighting expects C#, supproted language, CSharp language = "CSharp"; } SupportedLanguage supportedLanguage = (SupportedLanguage)Enum.Parse(typeof(SupportedLanguage), language.ToString(), true); using (var parser = ParserFactory.CreateParser(supportedLanguage, new StringReader(command))) { parser.ParseExpression(); if (parser.Errors.Count > 0) { MessageService.ShowError(parser.Errors.ErrorOutput); return(false); } } return(true); }
// could depend just on IDocument CompilationUnit ParseDocument(ITextEditor editor, out IList <ISpecial> parsedSpecials) { parsedSpecials = null; var editorLang = EditorContext.GetEditorLanguage(editor); if (editorLang == null) { return(null); } var parser = ParserFactory.CreateParser(editorLang.Value, editor.Document.CreateReader()); if (parser == null) { return(null); } parser.ParseMethodBodies = true; parser.Lexer.SkipAllComments = false; parser.Parse(); var parsedCU = parser.CompilationUnit; if (parsedCU == null) { return(null); } foreach (var node in parsedCU.Children) { // fix StartLocation / EndLocation node.AcceptVisitor(new ICSharpCode.NRefactory.Visitors.SetRegionInclusionVisitor(), null); } parsedSpecials = parser.Lexer.SpecialTracker.CurrentSpecials; return(parsedCU); }
public static T ParseGlobal <T>(string program, bool expectError, bool skipMethodBodies) where T : INode { IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(program)); parser.ParseMethodBodies = !skipMethodBodies; parser.Parse(); Assert.IsNotNull(parser.Errors); if (expectError) { Assert.IsTrue(parser.Errors.ErrorOutput.Length > 0, "There were errors expected, but parser finished without errors."); } else { Assert.AreEqual("", parser.Errors.ErrorOutput); } Assert.IsNotNull(parser.CompilationUnit); Assert.IsNotNull(parser.CompilationUnit.Children); Assert.IsNotNull(parser.CompilationUnit.Children[0]); Assert.IsTrue(parser.CompilationUnit.Children.Count > 0); Type type = typeof(T); Assert.IsTrue(type.IsAssignableFrom(parser.CompilationUnit.Children[0].GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", parser.CompilationUnit.Children[0].GetType(), type, parser.CompilationUnit.Children[0])); parser.CompilationUnit.AcceptVisitor(new CheckParentVisitor(), null); return((T)parser.CompilationUnit.Children[0]); }
/// <summary> /// Get data from cache or add it if key doesn't present /// </summary> /// <param name="cacheKey">key</param> /// <returns>Loaded data</returns> public async Task <IDataStructure> GetOrAddAsync(string cacheKey) { if (!_memoryCache.TryGetValue(cacheKey, out IDataStructure dataStructure)) { SemaphoreSlim certLock = _locks.GetOrAdd(cacheKey, k => new SemaphoreSlim(1, 1)); await certLock.WaitAsync(); try { if (!_memoryCache.TryGetValue(cacheKey, out dataStructure)) { using (var parserFactory = new ParserFactory(_datasourceOptions.Indexes[cacheKey])) { var parser = parserFactory.CreateParser(cacheKey); var dataLoader = new DataLoader(parser); dataStructure = dataLoader.Load(); } if (_dataStorageOptions.DataRefreshTime != 0) { _memoryCache.Set(cacheKey, dataStructure, GetMemoryCacheEntryOptions(_dataStorageOptions.DataRefreshTime)); } else { _memoryCache.Set(cacheKey, dataStructure); } } } finally { certLock.Release(); } } return(dataStructure); }
private static Type FindTypeMatchingMovedTypeBasedOnNamespaceFromError(IEnumerable <string> lines) { string valueFromNormalizedMessage = APIUpdaterHelper.GetValueFromNormalizedMessage(lines, "Line="); int num = (valueFromNormalizedMessage == null) ? -1 : int.Parse(valueFromNormalizedMessage); valueFromNormalizedMessage = APIUpdaterHelper.GetValueFromNormalizedMessage(lines, "Column="); int num2 = (valueFromNormalizedMessage == null) ? -1 : int.Parse(valueFromNormalizedMessage); string valueFromNormalizedMessage2 = APIUpdaterHelper.GetValueFromNormalizedMessage(lines, "Script="); Type result; if (num == -1 || num2 == -1 || valueFromNormalizedMessage2 == null) { result = null; } else { using (FileStream fileStream = File.Open(valueFromNormalizedMessage2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { IParser parser = ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.CSharp, new StreamReader(fileStream)); parser.Lexer.EvaluateConditionalCompilation = false; parser.Parse(); string text = InvalidTypeOrNamespaceErrorTypeMapper.IsTypeMovedToNamespaceError(parser.CompilationUnit, num, num2); if (text == null) { result = null; } else { result = APIUpdaterHelper.FindExactTypeMatchingMovedType(text); } } } return(result); }
static void LoadTypes(string fileName) { using (var parser = ParserFactory.CreateParser(fileName)) { // @TODO any standard preprocessor symbols we need? /*var uniqueSymbols = new HashSet<string>(definedSymbols.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); * foreach (var symbol in uniqueSymbols) * { * parser.Lexer.ConditionalCompilationSymbols.Add(symbol, string.Empty); * }*/ parser.Lexer.EvaluateConditionalCompilation = true; parser.Parse(); try { var visitor = new NamespaceVisitor(); var data = new VisitorData { typeName = s_TypeName }; parser.CompilationUnit.AcceptVisitor(visitor, data); if (data.generators.Count > 0) { s_SourceGenerators[fileName] = data.generators; } } catch { // does NRefactory throw anything we can handle here? throw; } } }
public override string GetNamespace(string fileName, string definedSymbols) { string result; using (IParser parser = ParserFactory.CreateParser(fileName)) { HashSet <string> hashSet = new HashSet <string>(definedSymbols.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); foreach (string current in hashSet) { parser.get_Lexer().get_ConditionalCompilationSymbols().Add(current, string.Empty); } parser.get_Lexer().set_EvaluateConditionalCompilation(true); parser.Parse(); try { CSharpLanguage.NamespaceVisitor namespaceVisitor = new CSharpLanguage.NamespaceVisitor(); CSharpLanguage.VisitorData visitorData = new CSharpLanguage.VisitorData { TargetClassName = Path.GetFileNameWithoutExtension(fileName) }; parser.get_CompilationUnit().AcceptVisitor(namespaceVisitor, visitorData); result = ((!string.IsNullOrEmpty(visitorData.DiscoveredNamespace)) ? visitorData.DiscoveredNamespace : string.Empty); return(result); } catch { } } result = string.Empty; return(result); }
private static Measurement GetMeasurement(Product product) { ParserFactory factory = new ParserFactory(); var parser = factory.CreateParser(product.Link); return(parser.ParseSource(product)); }
public static T ParseGlobal <T>(string program, bool expectErrors) where T : INode { IParser parser = ParserFactory.CreateParser(SupportedLanguage.VBNet, new StringReader(program)); parser.Parse(); if (expectErrors) { Assert.IsFalse(parser.Errors.ErrorOutput.Length == 0, "Expected errors, but operation completed successfully"); } else { Assert.AreEqual("", parser.Errors.ErrorOutput); } Assert.IsNotNull(parser.CompilationUnit); Assert.IsNotNull(parser.CompilationUnit.Children); Assert.IsNotNull(parser.CompilationUnit.Children[0]); Assert.AreEqual(1, parser.CompilationUnit.Children.Count); Type type = typeof(T); Assert.IsTrue(type.IsAssignableFrom(parser.CompilationUnit.Children[0].GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", parser.CompilationUnit.Children[0].GetType(), type, parser.CompilationUnit.Children[0])); parser.CompilationUnit.AcceptVisitor(new CheckParentVisitor(), null); return((T)parser.CompilationUnit.Children[0]); }
private static List <Xaml.Run> GetInlines(string line, bool isThumbnail = false) { var tokens = ParserFactory.CreateParser().Parse(line); var dict = new Dictionary <TokenType, string> { { TokenType.Keyword, "#FF569CD6" }, { TokenType.Comment, "#FF82C65B" }, { TokenType.String, "#FFD69D85" }, { TokenType.Number, "#FF00C68B" }, { TokenType.Operator, "#FF000000" }, { TokenType.Symbol, "#FF1E1E1E" }, { TokenType.Regular, "#FF1E1E1E" } }; var list = new List <Xaml.Run>(); foreach (var token in tokens) { var run = new Xaml.Run { Text = token.Value, //Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Helpers.GetColor(dict[token.Type])) }; if (isThumbnail) { run.FontSize = ThumbnailFontSize; } list.Add(run); } return(list); }
private void ParseStep() { string code = null; Invoke(new MethodInvoker(delegate { code = textEditorControl1.Text; })); TextReader textReader = new StringReader(code); ICompilationUnit newCompilationUnit; SupportedLanguage supportedLanguage; if (IsVisualBasic) { supportedLanguage = SupportedLanguage.VBNet; } else { supportedLanguage = SupportedLanguage.CSharp; } using (IParser p = 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); }
public void CreateParser_SingleReportFileWithSeveralReports_CorrectParserIsReturned() { string filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultiPartcover2.3.xml"); string parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("MultiReportParser (2x PartCover23Parser)", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultiPartcover2.2.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("MultiReportParser (2x PartCover22Parser)", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultiNCover1.5.8.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("MultiReportParser (2x NCoverParser)", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultiOpenCover.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("MultiReportParser (2x OpenCoverParser)", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultidotCover.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("MultiReportParser (2x DotCoverParser)", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultiVisualStudio2010.coveragexml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("MultiReportParser (2x VisualStudioParser)", parserName, "Wrong parser"); filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultiDynamicCodeCoverage.xml"); parserName = ParserFactory.CreateParser(new string[] { filePath }, new string[] { }).ToString(); Assert.AreEqual("MultiReportParser (2x DynamicCodeCoverageParser)", parserName, "Wrong parser"); }
public string Convert() { TextReader Reader = this.GetReader(); IParser Parser = ParserFactory.CreateParser(this.From, Reader); Parser.Parse(); if (Parser.Errors.Count > 0) { Log(Level.Error, Parser.Errors.ErrorOutput); throw new BuildException("Errors parsing code.", this.Location); } CompilationUnit Tree = Parser.CompilationUnit; IOutputAstVisitor OutputVisitor = null; switch (this.To) { case SupportedLanguage.CSharp: OutputVisitor = new CSharpOutputVisitor(); break; case SupportedLanguage.VBNet: OutputVisitor = new VBNetOutputVisitor(); break; } Tree.AcceptVisitor(OutputVisitor, null); return(OutputVisitor.Text); }
public void CSharpUsingWithAliasing() { string program = "using global::System;\n" + "using myAlias=global::My.Name.Space;\n" + "using a::b.c;\n"; IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(program)); parser.Parse(); Assert.AreEqual("", parser.Errors.ErrorOutput); CompilationUnit u = parser.CompilationUnit; Assert.AreEqual(3, u.Children.Count); Assert.IsTrue(u.Children[0] is UsingDeclaration); UsingDeclaration ud = (UsingDeclaration)u.Children[0]; Assert.AreEqual(1, ud.Usings.Count); Assert.IsFalse(((Using)ud.Usings[0]).IsAlias); Assert.AreEqual("System", ud.Usings[0].Name); Assert.IsTrue(u.Children[1] is UsingDeclaration); ud = (UsingDeclaration)u.Children[1]; Assert.AreEqual(1, ud.Usings.Count); Assert.IsTrue(((Using)ud.Usings[0]).IsAlias); Assert.AreEqual("myAlias", ud.Usings[0].Name); Assert.AreEqual("My.Name.Space", ud.Usings[0].Alias.Type); Assert.IsTrue(u.Children[2] is UsingDeclaration); ud = (UsingDeclaration)u.Children[2]; Assert.AreEqual(1, ud.Usings.Count); Assert.IsFalse(((Using)ud.Usings[0]).IsAlias); Assert.AreEqual("a.b.c", ud.Usings[0].Name); }
internal void CanParseMultiChoiceTemplateOptions(string command, string parameterName, string parameterValues, string?defaultIfNoOptionValue, string?expectedValue) { var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group") .WithChoiceParameter(parameterName, parameterValues.Split("|"), defaultIfNoOptionValue: defaultIfNoOptionValue, allowMultipleValues: true); TemplateGroup templateGroup = TemplateGroup.FromTemplateList( CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>())) .Single(); ITemplateEngineHost host = TestHost.GetVirtualHost(); IEngineEnvironmentSettings settings = new EngineEnvironmentSettings(host, virtualizeSettings: true); TemplatePackageManager packageManager = A.Fake <TemplatePackageManager>(); NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks()); var parseResult = myCommand.Parse($" new {command}"); InstantiateCommandArgs args = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult)); TemplateCommand templateCommand = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single()); Parser parser = ParserFactory.CreateParser(templateCommand); ParseResult templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty <string>()); var templateArgs = new TemplateCommandArgs(templateCommand, myCommand, templateParseResult); if (string.IsNullOrWhiteSpace(expectedValue)) { Assert.False(templateArgs.TemplateParameters.ContainsKey(parameterName)); } else { Assert.True(templateArgs.TemplateParameters.ContainsKey(parameterName)); Assert.Equal(expectedValue, templateArgs.TemplateParameters[parameterName]); } }