public void GetLineEndings_Should_Return_Easy_Cases(EndOfLine endOfLine, string expected) { var code = "tester\n"; var result = CodeFormatter.GetLineEnding( code, new PrinterOptions() { EndOfLine = endOfLine } ); result.Should().Be(expected); }
public DocumentEntry(string content, Uri uri, IServiceContainer services) { _services = services; EditorBuffer = new EditorBuffer(content, "R"); Document = new REditorDocument(EditorBuffer, services, false); _completionManager = new CompletionManager(services); _signatureManager = new SignatureManager(services); _diagnosticsPublisher = new DiagnosticsPublisher(Document, uri, services); _formatter = new CodeFormatter(_services); _symbolsProvider = new DocumentSymbolsProvider(); }
static IEnumerable <ColumnCollectionItem> GetStatColumnCollectionItems(CodeFormatter formatter, StatCollectionType statCollectionType) { var columnItems = new List <ColumnCollectionItem>(); foreach (var statType in EnumHelper <StatType> .Values) { var dbField = statType.GetDatabaseField(statCollectionType); var item = ColumnCollectionItem.FromEnum(formatter, dbField, statType); columnItems.Add(item); } return(columnItems); }
/// <summary> /// Creates type info for a strongly-typed tuple, such as Tuple[T1, T2, ...]. /// </summary> public NamedTupleType(string tupleName, IReadOnlyList <string> itemNames, IReadOnlyList <IPythonType> itemTypes, IPythonModule declaringModule, IndexSpan indexSpan) : base(itemTypes, declaringModule, declaringModule.Interpreter) { Name = tupleName ?? throw new ArgumentNullException(nameof(tupleName)); ItemNames = itemNames; var typeNames = itemTypes.Select(t => t.IsUnknown() ? string.Empty : t.Name); var pairs = itemNames.Zip(typeNames, (name, typeName) => string.IsNullOrEmpty(typeName) ? name : $"{name}: {typeName}"); Documentation = CodeFormatter.FormatSequence(tupleName, '(', pairs); _locatedMember = new NamedTupleLocatedMember(new Location(declaringModule, indexSpan)); }
public void PowerShellFormattingInfoTest() { CodeFormatter target = new CodeFormatter(); target.FormattingInfo = new PowerShellFormattingInfo(); string code = File.ReadAllText("psinput.txt"); string expected = File.ReadAllText("psexpected.txt"); string actual; actual = target.FormatCode(code); Assert.IsFalse(target.UsedFallbackFormatting); Assert.AreEqual(expected, actual); }
public void FilesFormattedSolution() { var(workspacePath, workspaceType) = WorkspacePathHelper.GetWorkspaceInfo(UnformattedSolutionFilePath); var options = new FormatOptions( workspacePath, workspaceType, LogLevel.Error, saveFormattedFiles: false, changesAreErrors: false, AllFileMatcher, reportPath: string.Empty); _ = CodeFormatter.FormatWorkspaceAsync(options, EmptyLogger, default).GetAwaiter().GetResult(); }
public void CopyAll() { if (this.proc == null) { return; } var sw = new StringWriter(); var writer = new TextFormatter(sw); var fmt = new CodeFormatter(writer); fmt.Write(proc); sw.Flush(); Clipboard.SetText(sw.ToString()); }
public static void GenerateCode(IRelation relation, string outputFolderAbsolute, bool useMetamodelInterface = true) { string code = GenerateCode(relation, useMetamodelInterface); try { code = CodeFormatter.Format(code); } catch (Exception) { // TODO } File.WriteAllText(PrepareOutputFolderString(outputFolderAbsolute) + QvtCodeGeneratorStrings.GetFileName(relation), code); }
private IPythonType CreateAnyStr() { var str = Interpreter.GetBuiltinType(BuiltinTypeId.Str); var bytes = Interpreter.GetBuiltinType(BuiltinTypeId.Bytes); var unicode = Interpreter.GetBuiltinType(BuiltinTypeId.Unicode); var name = "AnyStr"; var constraints = Interpreter.LanguageVersion.Is3x() ? new IPythonType[] { str, bytes } : new IPythonType[] { str, unicode }; var docArgs = new[] { $"'{name}'" }.Concat(constraints.Select(c => c.Name)); var documentation = CodeFormatter.FormatSequence("TypeVar", '(', docArgs); return(new GenericTypeParameter(name, this, constraints, default, documentation, default));
private void GenCode(Procedure proc, StringWriter sw) { sw.WriteLine("{0}()", proc.Name); sw.WriteLine("{"); CodeFormatter cf = proc.CreateCodeFormatter(new TextFormatter(sw) { UseTabs = false }); cf.WriteStatementList(proc.Body); sw.WriteLine("}"); }
public void IncludePreElementTest() { var target = new CodeFormatter() { IncludePreElement = false }; target.FormattingInfo = new CSharpFormattingInfo(); const string code = "int i = 5;"; const string expected = "<span class=\"keyword\">int</span> i = 5;"; var actual = target.FormatCode(code); Assert.AreEqual(expected, actual); }
public void CSharpFormattingInfoTest() { CodeFormatter target = new CodeFormatter(); CSharpFormattingInfo info = new CSharpFormattingInfo(); info.Types = new string[] { "Program", "Console", "String" }; target.FormattingInfo = info; string code = File.ReadAllText("csinput.txt"); string expected = File.ReadAllText("csexpected.txt"); string actual; actual = target.FormatCode(code); Assert.AreEqual(expected, actual); }
public void CssClassNullTest() { var target = new CodeFormatter() { CssClass = null }; target.FormattingInfo = new CSharpFormattingInfo(); const string code = "int i = 5;"; const string expected = "<pre><span class=\"keyword\">int</span> i = 5;</pre>"; var actual = target.FormatCode(code); Assert.AreEqual(expected, actual); }
public void Emit(string fnName, EmitFlags f, Formatter fmt, CodeFormatter w, TypeFormatter t) { bool emitStorage = (f & EmitFlags.ArgumentKind) == EmitFlags.ArgumentKind; if (emitStorage) { if (ReturnValue != null) { w.WriteFormalArgumentType(ReturnValue, emitStorage); fmt.Write(" "); } else { fmt.Write("void "); } fmt.Write("{0}(", fnName); } else { if (ReturnValue == null) { fmt.Write("void {0}", fnName); } else { t.Write(ReturnValue.DataType, fnName); //$TODO: won't work with fn's that return pointers to functions or arrays. } fmt.Write("("); } var sep = ""; if (Parameters != null) { for (int i = 0; i < Parameters.Length; ++i) { fmt.Write(sep); sep = ", "; w.WriteFormalArgument(Parameters[i], emitStorage, t); } } fmt.Write(")"); if ((f & EmitFlags.LowLevelInfo) == EmitFlags.LowLevelInfo) { fmt.WriteLine(); fmt.Write("// stackDelta: {0}; fpuStackDelta: {1}; fpuMaxParam: {2}", StackDelta, FpuStackDelta, FpuStackArgumentMax); fmt.WriteLine(); } }
public void DisplayProcedure(Procedure proc) { if (codeView == null || proc == null) { return; } this.proc = proc; var tsf = new TextSpanFormatter(); var fmt = new CodeFormatter(tsf); fmt.InnerFormatter.UseTabs = false; fmt.Write(proc); this.TextView.Model = tsf.GetModel(); }
public void TestsyPoo() { //copy dummy file to temp location //format it //debug why the spans are being joined. //.\Content\*.html //.\kindlegen\KindleGen\Bin\Debug //..\..\..\..\content\*.html var d = Environment.CurrentDirectory; File.Delete("01_KeyTypes.html"); File.Copy(@"..\..\..\..\..\content\01_KeyTypes.html", "01_KeyTypes.html"); CodeFormatter.FormatKindleContentFiles(@".\"); }
public void Write(bool emitFrame, BlockDecorator decorator, TextWriter writer) { writer.WriteLine("// {0}", Name); if (emitFrame) { Frame.Write(writer); } var formatter = new TextFormatter(writer); Signature.Emit(Name, ProcedureSignature.EmitFlags.None, new TextFormatter(writer)); writer.WriteLine(); var codeFormatter = new CodeFormatter(formatter); new ProcedureFormatter(this, decorator, codeFormatter).WriteProcedureBlocks(); }
private IPythonType CreateAnyStr() { var str = Interpreter.GetBuiltinType(BuiltinTypeId.Str); var bytes = Interpreter.GetBuiltinType(BuiltinTypeId.Bytes); var unicode = Interpreter.GetBuiltinType(BuiltinTypeId.Unicode); var constraints = Interpreter.LanguageVersion.Is3x() ? new[] { str, bytes } : new[] { str, unicode }; var docArgs = new[] { "'AnyStr'" }.Concat(constraints.Select(c => c.Name)); var documentation = CodeFormatter.FormatSequence("TypeVar", '(', docArgs); return(new PythonTypeWrapper("AnyStr", documentation, this, Interpreter.GetBuiltinType(BuiltinTypeId.Str))); }
public void WriteStatements(TextWriter writer) { TextFormatter f = new TextFormatter(writer); f.UseTabs = true; f.TabSize = 4; CodeFormatter cf = new CodeFormatter(f); int i = 0; foreach (Statement s in Statements) { s.Instruction.Accept(cf); ++i; } }
public void WriteProcedure(Procedure proc, TextWriter writer) { var textFormatter = new TextFormatter(writer) { Indentation = 0, }; textFormatter.WriteLine(); var codeFormatter = new CodeFormatter(textFormatter); foreach (var stm in proc.Statements) { stm.Instruction.Accept(codeFormatter); } }
public Task Run() { var nativeApiInfo = _nativeApiInfoProvider.Get(MahuaPlatform.CleverQQ); var nativeApiIn = _httpApiInputModelsGenerator.Generate(new HttpApiInputModelsGeneratorInput { NativeApiInfo = nativeApiInfo, MahuaPlatform = MahuaPlatform.CleverQQ }); var code = CodeFormatter.FormatCode(nativeApiIn); File.WriteAllText("../Newbe.Mahua.InputReceivers.HttpApi/Services/Controllers/CleverQQController.cs", code, Encoding.UTF8); return(Task.CompletedTask); }
public void NoFilesFormattedProject() { var(workspacePath, workspaceType) = WorkspacePathHelper.GetWorkspaceInfo(FormattedProjectFilePath); var options = new FormatOptions( workspacePath, workspaceType, LogLevel.Error, saveFormattedFiles: false, changesAreErrors: false, ImmutableHashSet <string> .Empty, ImmutableHashSet <string> .Empty, reportPath: string.Empty); _ = CodeFormatter.FormatWorkspaceAsync(options, EmptyLogger, default).GetAwaiter().GetResult(); }
public async Task <string> TestFormatWorkspaceAsync(string solutionOrProjectPath, IEnumerable <string> files, int expectedExitCode, int expectedFilesFormatted, int expectedFileCount) { var workspacePath = Path.GetFullPath(solutionOrProjectPath); var isSolution = workspacePath.EndsWith(".sln"); var filesToFormat = files.Select(Path.GetFullPath).ToImmutableHashSet(StringComparer.OrdinalIgnoreCase); var logger = new TestLogger(); var formatResult = await CodeFormatter.FormatWorkspaceAsync(workspacePath, isSolution, logWorkspaceWarnings : false, saveFormattedFiles : false, filesToFormat, logger, CancellationToken.None); Assert.Equal(expectedExitCode, formatResult.ExitCode); Assert.Equal(expectedFilesFormatted, formatResult.FilesFormatted); Assert.Equal(expectedFileCount, formatResult.FileCount); return(logger.GetLog()); }
public void Write(bool emitFrame, bool showEdges, TextWriter writer) { writer.WriteLine("// {0}", Name); writer.WriteLine("// Return size: {0}", this.Signature.ReturnAddressOnStack); if (emitFrame) { Frame.Write(writer); } Signature.Emit(Name, ProcedureSignature.EmitFlags.None, new TextFormatter(writer)); writer.WriteLine(); var formatter = new CodeFormatter(new TextFormatter(writer)); new ProcedureFormatter(this, new BlockDecorator { ShowEdges = showEdges }, formatter).WriteProcedureBlocks(); }
public void VisualBasicFormattingInfoTest() { CodeFormatter target = new CodeFormatter(); VisualBasicFormattingInfo info = new VisualBasicFormattingInfo(); target.FormattingInfo = new VisualBasicFormattingInfo() { Types = new string[] { "Program", "Console", "String" } }; string code = File.ReadAllText("vbinput.txt"); string expected = File.ReadAllText("vbexpected.txt"); string actual; actual = target.FormatCode(code); Assert.AreEqual(expected, actual); }
public Task Run() { var nativeApiInfo = _nativeApiInfoProvider.Get(MahuaPlatform.Mpq); var apiHandler = _apiHandlerGenerator.Generate(new ApiHandlerGeneratorInput { Namespace = "Newbe.Mahua.QQLight", NativeApiInfo = nativeApiInfo, ApiOutBaseName = "QQLightApiOutput", ApiHandlerClassName = "QQLightMahuaApiHandler", }); File.WriteAllText("../Newbe.Mahua.QQLight/QQLightMahuaApiHandler.cs", CodeFormatter.FormatCode(apiHandler), Encoding.UTF8); return(Task.CompletedTask); }
public async Task FilesFormattedInUnformattedSolution() { var logger = new TestLogger(); var path = Path.GetFullPath("tests/projects/for_code_formatter/unformatted_solution/unformatted_solution.sln", SolutionPath); var exitCode = await CodeFormatter.FormatWorkspaceAsync(logger, path, isSolution : true, logAllWorkspaceWarnings : false, saveFormattedFiles : false, cancellationToken : CancellationToken.None); var log = logger.GetLog(); var pattern = string.Format(Resources.Formatted_0_of_1_files_in_2_ms, "(\\d+)", "\\d+", "\\d+"); var filesFormatted = new Regex(pattern, RegexOptions.Multiline); var match = filesFormatted.Match(log); Assert.Equal(0, exitCode); Assert.True(match.Success, log); Assert.Equal("1", match.Groups[1].Value); }
public async Task FSharpProjectsDoNotCreateException() { var logger = new TestLogger(); var path = Path.GetFullPath("tests/projects/for_code_formatter/fsharp_project/fsharp_project.fsproj", SolutionPath); var exitCode = await CodeFormatter.FormatWorkspaceAsync(logger, path, isSolution : false, logAllWorkspaceWarnings : false, saveFormattedFiles : false, cancellationToken : CancellationToken.None); var logLines = logger.GetLog().Split(Environment.NewLine); Assert.Equal(4, logLines.Length); var actualErrorMessage = logLines[2]; var expectedErrorMessage = string.Format(Resources.Could_not_format_0_Format_currently_supports_only_CSharp_and_Visual_Basic_projects, path); Assert.Equal(expectedErrorMessage, actualErrorMessage); Assert.Equal(1, exitCode); }
private void RunTest32(string expected, Program program) { var sw = new StringWriter(); foreach (var proc in program.Procedures.Values) { var cfgc = new ControlFlowGraphCleaner(proc); cfgc.Transform(); var sa = new StructureAnalysis(proc); sa.Structure(); var fmt = new CodeFormatter(new TextFormatter(sw)); fmt.Write(proc); sw.WriteLine("==="); } Console.WriteLine(sw); Assert.AreEqual(expected, sw.ToString()); }
private static void Add_Degrees_Radians(CsClass cl) { for (var i = 0; i < 2; i++) { var c = i == 0 ? "const double mul = 180.0 / Math.PI;" : "const double mul = Math.PI / 180.0;"; OneArg(cl, i == 0 ? "Degrees" : "Radians", null, q => { var cf = new CodeFormatter(); cf.Writeln(c); var map = q.Map("# * mul"); cf.Writeln("return " + map + ";"); q.Make(cf.Text); }); } }
/// <summary> /// Executes the parameters. /// </summary> /// <param name="functionDeclaration"> /// The function declaration. /// </param> private void ExecuteFunction([NotNull] ICSharpFunctionDeclaration functionDeclaration) { if (this.IsAvailableGetterFunction(functionDeclaration)) { this.ExecuteReturnValueAttribute(functionDeclaration); } var assertions = this.GetAssertions(functionDeclaration, true); if (assertions.Count == 0) { return; } var factory = CSharpElementFactory.GetInstance(functionDeclaration.GetPsiModule()); var body = functionDeclaration.Body; var codeFormatter = new CodeFormatter(); var accessRights = GetAccessRights(functionDeclaration); foreach (var assertion in assertions) { if (assertion.Nullable) { continue; } if (!assertion.NeedsStatement) { continue; } if (assertion.Statement != null) { body.RemoveStatement(assertion.Statement); assertion.Statement = factory.CreateStatement(assertion.Statement.GetText()); continue; } var code = GetCode(assertion, accessRights); if (string.IsNullOrEmpty(code)) { continue; } code = string.Format(code, assertion.Parameter.ShortName); assertion.Statement = factory.CreateStatement(code); } IStatement anchor = null; if (body != null) { anchor = GetAnchor(body); } var hasAsserts = false; foreach (var assertion in assertions) { if (assertion.Nullable) { continue; } this.MarkParameterWithAttribute(assertion); if (body == null || assertion.Statement == null) { continue; } var result = body.AddStatementBefore(assertion.Statement, anchor); var range = result.GetDocumentRange(); codeFormatter.Format(this.Solution, range); hasAsserts = true; } if (anchor != null && hasAsserts) { this.InsertBlankLine(anchor, codeFormatter); } }
/// <summary> /// Executes the internal. /// </summary> /// <param name="element"> /// The element. /// </param> protected override void Execute(IElement element) { var statement = this.Provider.GetSelectedElement<IExpressionStatement>(true, true); if (statement == null) { return; } var factory = CSharpElementFactory.GetInstance(statement.GetPsiModule()); if (factory == null) { return; } var expression = statement.Expression; if ((expression == null) || !(expression.ToTreeNode() is IUnaryExpressionNode)) { return; } var type = expression.Type(); if (!type.IsResolved) { return; } var declaredType = type as IDeclaredType; if (declaredType == null) { return; } var enumerate = declaredType.GetTypeElement() as IEnum; if (enumerate == null) { return; } var typeName = enumerate.ShortName; var code = new StringBuilder("switch("); code.Append(statement.GetText()); code.Append(") {"); foreach (var field in enumerate.EnumMembers) { code.Append("case "); code.Append(typeName); code.Append('.'); code.Append(field.ShortName); code.Append(":\r\nbreak;"); } code.Append("default:\r\n"); code.Append("throw new System.ArgumentOutOfRangeException();"); code.Append("\r\n}"); var result = factory.CreateStatement(code.ToString()); if (result == null) { return; } result = statement.ReplaceBy(result); var range = result.GetDocumentRange(); var codeFormatter = new CodeFormatter(); codeFormatter.Format(this.Solution, range); }
/// <summary> /// Inserts the assert. /// </summary> /// <param name="element">The element.</param> /// <param name="anchor">The anchor.</param> /// <param name="name">The name of the variable.</param> private void CheckStringAssignment(IElement element, IStatement anchor, string name) { var methodDeclaration = anchor.GetContainingTypeMemberDeclaration() as IMethodDeclaration; if (methodDeclaration == null) { return; } var body = methodDeclaration.Body; if (body == null) { return; } var csharpElement = element as ICSharpElement; if (csharpElement == null) { return; } var factory = CSharpElementFactory.GetInstance(element.GetPsiModule()); var statement = factory.CreateStatement(string.Format("if (string.IsNullOrEmpty({0})) {{ }}", name)); var result = body.AddStatementAfter(statement, anchor); var range = result.GetDocumentRange(); var codeFormatter = new CodeFormatter(); codeFormatter.Format(this.Solution, range); }