/// <summary> /// Checks the methods within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); /* // Get the autoupdate setting. string flag = null; if (document.File.Project.LocalSettings != null) { flag = document.File.Project.LocalSettings.GetProperty("ParamCheckAutomatic"); if (flag == null && document.File.Project.GlobalSettings != null) { flag = document.File.Project.GlobalSettings.GetProperty("ParamCheckAutomatic"); } } this.autoUpdate = (flag != null && flag == "1"); */ // Analyze the document. CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { this.ProcessElement(csdocument, csdocument.RootElement); } }
public void TestCode() { var codeFile = new CodeDocument { TabCharacter = " " }; codeFile.Namespace("Test") .Class("public", "TestClass", "") ._() ._("private string _value;") ._() .Function("public", "TestClass", "string value") ._("_value = value;") .End() ._() .Function("public void ", "TestMethod", "") ._("_value = 5;") .End() ._() ._() .Interface("public", "TestInterface", "") ._("void TestMethod();") .End() .End() .End(); Debug.WriteLine(codeFile.ToString()); Assert.IsTrue(true); }
public void ParserComments() { var code = "PROGRAM MyApp # comment\n" + "\n" + " MODEL MyFirstClass # comment\n" + "\n" + " FUNCTION Main() # comment\n" + " # comment\n" + " END FUNCTION # comment\n" + "\n" + " ASYNC FUNCTION MyMethod(arg1, arg2, arg3[])\n" + "\n" + " END FUNCTION\n" + "\n" + " END MODEL # comment for fun\n" + "\n" + "END PROGRAM\n"; var codeDocument = new CodeDocument(code, "MyApp"); var parser = new Parser <AlgoBASIC>(); parser.ParseAsync(codeDocument).Wait(); Assert.AreEqual(parser.AlgorithmProgram.Classes.First().Name.ToString(), "MyFirstClass"); Assert.AreEqual(parser.AlgorithmProgram.Classes.First().Members.First().Name.ToString(), "Main"); Assert.AreEqual(((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).Name.ToString(), "MyMethod"); Assert.AreEqual(((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).IsAsync, true); Assert.AreEqual(((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).Arguments[2].Name.ToString(), "arg3"); Assert.AreEqual(((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).Arguments[2].IsArray, true); }
public void ParserEnglish() { var codeDocuments = new List <CodeDocument>(); var code = "PROGRAM MyApp\n" + "\n" + " MODEL MyFirstClass\n" + "\n" + " END MODEL\n" + "\n" + "END PROGRAM\n"; var codeDocument = new CodeDocument(code, "MyFirstClass"); codeDocuments.Add(codeDocument); code = "MODEL MySecondClass\n" + "\n" + "END MODEL\n"; codeDocument = new CodeDocument(code, "MySecondClass"); codeDocuments.Add(codeDocument); var parser = new Parser <AlgoBASIC>(); parser.ParseAsync(codeDocuments, null).Wait(); Assert.AreEqual(parser.AlgorithmProgram.Name, "MyApp"); Assert.AreEqual(parser.AlgorithmProgram.Classes[0].Name.ToString(), "MyFirstClass"); Assert.AreEqual(parser.AlgorithmProgram.Classes[1].Name.ToString(), "MySecondClass"); }
public void ParserFunctionDeclaration() { var code = "PROGRAM MyApp\n" + "\n" + " MODEL MyFirstClass\n" + "\n" + " FUNCTION Main()\n" + "\n" + " END FUNCTION\n" + "\n" + " ASYNC FUNCTION MyMethod(arg1, arg2, arg3[])\n" + " VARIABLE test\n" + " END FUNCTION\n" + "\n" + " END MODEL\n" + "\n" + "END PROGRAM\n"; var codeDocument = new CodeDocument(code, "MyApp"); var parser = new Parser <AlgoBASIC>(); parser.ParseAsync(codeDocument).Wait(); Assert.AreEqual(parser.AlgorithmProgram.Classes.First().Name.ToString(), "MyFirstClass"); Assert.AreEqual(parser.AlgorithmProgram.Classes.First().Members.First().Name.ToString(), "Main"); Assert.AreEqual(((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).Name.ToString(), "MyMethod"); Assert.AreEqual(((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).IsAsync, true); Assert.AreEqual(((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).Arguments[2].Name.ToString(), "arg3"); Assert.AreEqual(((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).Arguments[2].IsArray, true); Assert.AreEqual(((AlgorithmVariableDeclaration)((AlgorithmClassMethodDeclaration)parser.AlgorithmProgram.Classes.First().Members[1]).Statements.First()).Name.ToString(), "test"); }
/// <summary> /// Checks the placement of brackets within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); XmlDocument contents = new XmlDocument(); XmlNode root = contents.CreateElement("StyleCopCsParserObjectModel"); contents.AppendChild(root); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null) { this.ProcessElement(csdocument.RootElement, root); } // Get the location where the output file should be stored. string testOutputDirectory = (string)this.Core.HostTag; if (string.IsNullOrEmpty(testOutputDirectory)) { throw new InvalidOperationException("The HostTag has not been properly set in StyleCopCore."); } // Save the output to the file. string outputFileLocation = Path.Combine(testOutputDirectory, Path.GetFileNameWithoutExtension(document.SourceCode.Path) + "ObjectModelResults.xml"); contents.Save(outputFileLocation); }
/// <summary> /// Checks the methods within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; Settings settings = new Settings(); settings.DoNotUseRegions = this.IsRuleEnabled(document, Rules.DoNotUseRegions.ToString()); settings.DoNotPlaceRegionsWithinElements = this.IsRuleEnabled(document, Rules.DoNotPlaceRegionsWithinElements.ToString()); settings.AvoidStringFormatUseStringInterpolation = this.IsRuleEnabled(document, Rules.AvoidStringFormatUseStringInterpolation.ToString()); if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { // Checks various formatting rules. csdocument.WalkDocument(this.ProcessElement, null, new CodeWalkerExpressionVisitor <object>(this.ProcessExpression), settings); // Check statement formatting rules. this.CheckStatementFormattingRulesForElement(csdocument.RootElement); // Check the class member rules. this.CheckClassMemberRulesForElements(csdocument.RootElement, null, null); // Looks for empty comments. this.CheckForEmptyComments(csdocument.RootElement); // Checks the usage of the built-in types and empty strings. this.IterateTokenList(csdocument, settings); } }
protected override void ProcessOutput(CodeDocument doc) { // Compile expression string result; try { result = doc.Name + " is ok\r\n"; var names = new List <string>(); int pad = doc.ChildNodes.Count() > 0 ? doc.ChildNodes.Max(n => n.Name.Length) + 2 : 0; IEnumerable <CodeElement> elements = doc.ChildNodes.OfType <CodeElement>(); foreach (CodeElement elem in elements) { if (!names.Contains(elem.Name)) { result += "Number of " + (elem.Name + ":").PadRight(pad) + elements.Count(e => e.Name == elem.Name) + "\r\n"; names.Add(elem.Name); } } int i = doc.ChildNodes.OfType <CommentElement>().Count(); if (i > 0) { result += "Number of " + "comment:".PadRight(pad) + i + "\r\n"; } } catch (Exception e) { result = "Output cant be read.\r\n" + e.Message + "\r\n"; } Output = result; }
private static ICodeBlock GetAllFactoryMethods(string factoryClassName, string baseClassName, int numberToPreAllocate, bool poolObjects) { string className = factoryClassName.Substring(0, factoryClassName.Length - "Factory".Length); ICodeBlock codeBlock = new CodeDocument(); codeBlock.Line("public static FlatRedBall.Math.Axis? SortAxis { get; set;}"); GetCreateNewFactoryMethod(codeBlock, factoryClassName, poolObjects, baseClassName); codeBlock._(); GetInitializeFactoryMethod(codeBlock, className, poolObjects, "mScreenListReference"); codeBlock._(); GetDestroyFactoryMethod(codeBlock, factoryClassName); codeBlock._(); GetFactoryInitializeMethod(codeBlock, factoryClassName, numberToPreAllocate); codeBlock._(); GetMakeUnusedFactory(codeBlock, factoryClassName, poolObjects); codeBlock._(); string whereClass = className; if (!string.IsNullOrEmpty(baseClassName)) { whereClass = baseClassName.Replace("\\", "."); } AddAddListMethod(codeBlock, whereClass); AddRemoveListMethod(codeBlock, whereClass); AddClearListsToAddTo(codeBlock); return(codeBlock); }
private void _CmdUser_TriggerBuild() { try { var prolog = new PrologEngine(persistentCommandHistory: false); prolog.ConsultFromString(CodeDocument.Text); prolog.GetFirstSolution(CodeDocumentQuery.Text); MyConsole.WriteLine("----------------------"); foreach (var sol in prolog.GetEnumerator()) { var errorInfo = MyPrologUtils.TryToGetErrorFromPrologSolution(sol); if (errorInfo != null) { CurErrorMessage = errorInfo.Message; var errorLine = CodeDocumentQuery.GetLineByNumber(1); CurErrorWordHighlightQuery = new WordHighlight(errorLine.Offset, errorLine.Length); break; } var stringified = sol.VarValuesIterator.Select(val => $"{val.Name}:{val.Value}").StringJoin(", "); MyConsole.WriteLine(stringified); } } catch (Exception ex) { var errorInfo = MyPrologUtils.TryToGetErrorFromException(ex); if (errorInfo.Line != null) { var errorLine = CodeDocument.GetLineByNumber(errorInfo.Line.Value); CurErrorWordHighlight = new WordHighlight(errorLine.Offset, errorLine.Length); } CurErrorMessage = errorInfo.Message; } }
public DocumentClient(TextEditor editor, string extension) { m_editor = editor; string fileType = CodeDocument.GetDocumentType(extension); m_info = new DocumentClientInfo(fileType, extension, null, null); }
private bool isNextEnd(int index) { int prevInex = index; if (prevInex < CodeDocument.Length && ( CodeDocument.GetCharAt(prevInex) == ' ' || CodeDocument.GetCharAt(prevInex) == '\t' ) ) { prevInex++; } if (prevInex >= CodeDocument.Length || CodeDocument.GetCharAt(prevInex) != 'e') { return(false); } prevInex++; if (prevInex >= CodeDocument.Length || CodeDocument.GetCharAt(prevInex) != 'n') { return(false); } prevInex++; if (CodeDocument.GetCharAt(prevInex) != 'd') { return(false); } return(true); }
private static ICodeBlock GenerateEventGeneratedCodeFile(IElement element) { ICodeBlock codeBlock = new CodeDocument(); var currentBlock = codeBlock; string elementNamespace = ProjectManager.ProjectNamespace; elementNamespace += "." + element.Name.Replace("/", ".").Replace("\\", ".").Substring( 0, element.Name.Length - (element.ClassName.Length + 1)); AddUsingStatementsToBlock(currentBlock); currentBlock = currentBlock .Namespace(elementNamespace); currentBlock = currentBlock .Class("public partial", element.ClassName, ""); foreach (EventResponseSave ers in element.Events) { currentBlock = FillWithGeneratedEventCode(currentBlock, ers, element); } return(codeBlock); }
/// <summary> /// Analyzes the document. /// </summary> /// <param name="document">The document.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref /// name="document"/> is <c>null</c>.</exception> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); this.IncludeGenerated = this.GetValue <bool>( document.Settings, Strings.IncludeGenerated); var csDocument = (CsDocument)document; if (csDocument.RootElement != null && (this.IncludeGenerated || !csDocument.RootElement.Generated)) { // check start of document this.CheckIfFileStartsWithWhitespace( csDocument.RootElement, csDocument.Tokens.First.Value); // check whole document this.IterateDocumentTokens(csDocument); // check end of document this.CheckIfDocumentEndsWithMultipleWhitespaceLines( csDocument.RootElement, csDocument.Tokens.Last); this.CheckIfFileEndsWithNewline( csDocument.RootElement, csDocument.Tokens.Last.Value); } }
// Internal for testing internal void OnDocumentStructureChanged(object state) { _dispatcher.AssertForegroundThread(); if (_disposed) { return; } var args = (DocumentStructureChangedEventArgs)state; if (_latestChangeReference == null || // extra hardening !_latestChangeReference.IsAssociatedWith(args) || args.Snapshot != TextBuffer.CurrentSnapshot) { // In the middle of parsing a newer change or about to parse a newer change. return; } _latestChangeReference = null; _codeDocument = args.CodeDocument; _snapshot = args.Snapshot; _partialParser = new RazorSyntaxTreePartialParser(CodeDocument.GetSyntaxTree()); DocumentStructureChanged?.Invoke(this, args); }
// Internal for testing internal void OnDocumentStructureChanged(object state) { _dispatcher.AssertForegroundThread(); if (_disposed) { return; } var backgroundParserArgs = (BackgroundParserResultsReadyEventArgs)state; if (_latestChangeReference == null || // extra hardening _latestChangeReference != backgroundParserArgs.ChangeReference || backgroundParserArgs.ChangeReference.Snapshot != TextBuffer.CurrentSnapshot) { // In the middle of parsing a newer change or about to parse a newer change. return; } _latestChangeReference = null; _codeDocument = backgroundParserArgs.CodeDocument; _snapshot = backgroundParserArgs.ChangeReference.Snapshot; _partialParser = new RazorSyntaxTreePartialParser(CodeDocument.GetSyntaxTree()); var documentStructureChangedArgs = new DocumentStructureChangedEventArgs( backgroundParserArgs.ChangeReference.Change, backgroundParserArgs.ChangeReference.Snapshot, backgroundParserArgs.CodeDocument); DocumentStructureChanged?.Invoke(this, documentStructureChangedArgs); }
public void ParserFrench() { var codeDocuments = new List <CodeDocument>(); var code = "PROGRAMME MyApp\n" + "\n" + " MODELE MyFirstClass\n" + "\n" + " FIN MODELE\n" + "\n" + "FIN PROGRAMME\n"; var codeDocument = new CodeDocument(code, "MyFirstClass"); codeDocuments.Add(codeDocument); code = "MODELE MySecondClass\n" + "\n" + "FIN MODELE\n"; codeDocument = new CodeDocument(code, "MySecondClass"); codeDocuments.Add(codeDocument); var parser = new Parser <AlgoBASIC>(AlgoBASIC.Culture.French); parser.ParseAsync(codeDocuments, null).Wait(); Assert.AreEqual(parser.AlgorithmProgram.Name, "MyApp"); Assert.AreEqual(parser.AlgorithmProgram.Classes[0].Name.ToString(), "MyFirstClass"); Assert.AreEqual(parser.AlgorithmProgram.Classes[1].Name.ToString(), "MySecondClass"); }
/// <summary> /// Checks the methods within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); /* * // Get the autoupdate setting. * string flag = null; * if (document.File.Project.LocalSettings != null) * { * flag = document.File.Project.LocalSettings.GetProperty("ParamCheckAutomatic"); * if (flag == null && document.File.Project.GlobalSettings != null) * { * flag = document.File.Project.GlobalSettings.GetProperty("ParamCheckAutomatic"); * } * } * * this.autoUpdate = (flag != null && flag == "1"); */ // Analyze the document. CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { this.ProcessElement(csdocument, csdocument.RootElement); } }
protected override void ProcessOutput(CodeDocument doc) { Output = "Compile\r\n"; // Compile expression Program program; Dictionary <string, Function> functions = Program.AddFunction(null, "Write", WriteLine, "str"); Dictionary <string, ValueBase> parameters = null; try { program = ProgramBuilder.CreateProgram(doc, functions, parameters); } catch (Exception e) { Output += "Program does not compile.\r\n(Compiling the parser output fails)\r\n" + e.Message; return; } // execute program try { Output = "Run\r\n"; program.RunProgram(parameters); } catch (Exception e) { Output += "Program failed: " + e.Message; return; } Output += "Program has executed!"; }
protected ITaskProvider GetTaskProvider(CodeDocument doc) { if (doc != null) return GetTaskProvider(doc.CodeEditor.Key); return null; }
/// <summary> /// Checks the placement of brackets within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); XmlDocument contents = new XmlDocument(); XmlNode root = contents.CreateElement("StyleCopCsParserObjectModel"); contents.AppendChild(root); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null) { this.ProcessElement(csdocument.RootElement, root); } // Get the location where the output file should be stored. string testOutputDirectory = (string)this.Core.HostTag; if (string.IsNullOrEmpty(testOutputDirectory)) { throw new InvalidOperationException("The HostTag has not been properly set in StyleCopCore."); } // Save the output to the file. string outputFileLocation = Path.Combine(testOutputDirectory, Path.GetFileNameWithoutExtension(document.SourceCode.Path) + "ObjectModelResults.xml"); contents.Save(outputFileLocation); }
private static ICodeBlock GetAllFactoryMethods(string factoryClassName, string baseClassName, int numberToPreAllocate, bool poolObjects) { string className = factoryClassName.Substring(0, factoryClassName.Length - "Factory".Length); ICodeBlock codeBlock = new CodeDocument(); GetCreateNewFactoryMethod(codeBlock, factoryClassName, poolObjects, baseClassName); codeBlock._(); GetInitializeFactoryMethod(codeBlock, className, poolObjects, "mScreenListReference"); codeBlock._(); if (!string.IsNullOrEmpty(baseClassName)) { GetInitializeFactoryMethod(codeBlock, FileManager.RemovePath(baseClassName), poolObjects, "mBaseScreenListReference"); codeBlock._(); } GetDestroyFactoryMethod(codeBlock, factoryClassName); codeBlock._(); GetFactoryInitializeMethod(codeBlock, factoryClassName, numberToPreAllocate); codeBlock._(); GetMakeUnusedFactory(codeBlock, factoryClassName, poolObjects); return(codeBlock); }
/// <summary> /// Checks the methods within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; Settings settings = new Settings(); settings.DoNotUseRegions = this.IsRuleEnabled(document, Rules.DoNotUseRegions.ToString()); settings.DoNotPlaceRegionsWithinElements = this.IsRuleEnabled(document, Rules.DoNotPlaceRegionsWithinElements.ToString()); if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { // Checks various formatting rules. csdocument.WalkDocument(this.ProcessElement, null, new CodeWalkerExpressionVisitor<object>(this.ProcessExpression), settings); // Check statement formatting rules. this.CheckStatementFormattingRulesForElement(csdocument.RootElement); // Check the class member rules. this.CheckClassMemberRulesForElements(csdocument.RootElement, null, null); // Looks for empty comments. this.CheckForEmptyComments(csdocument.RootElement); // Checks the usage of the built-in types and empty strings. this.IterateTokenList(csdocument, settings); } }
private void AddDocument(CodeDocument codeDoc) { if (codeDoc != null && codeDoc.Features.Set(CodeEditorFeatures.Tasks)) { var editor = app.Editor(codeDoc.GetType()); var sci = editor.Control as ScintillaControl; if (sci != null) { var node = new TreeNode(); codeDoc.FileChanged += (o, ev) => ChangeNodeText(node); node.ImageKey = node.SelectedImageKey = "Folder"; node.Tag = codeDoc; node.Nodes.Add(new TreeNode { Tag = stub }); ChangeNodeText(node); nodeMap.Add(codeDoc, node); treeView.Nodes.Add(node); if (!sciMap.ContainsKey(sci)) { sci.TextChanged += (o, ev) => ContentChanged(); } } } }
protected override void ProcessOutput(CodeDocument doc) { // Compile expression string result; int animalCount = 0; try { result = "ok\r\n"; // doc.ChildNodes.OfType<CodeElement>().FirstOrDefault(); animalCount = doc.Nodes("valueline").Count(); result += "Number of animals: " + animalCount + "\r\n"; } catch (Exception e) { Output = "Output cant be read.\r\n" + e.Message + "\r\n"; return; } try { float longlivitySum = doc.Nodes("valueline").Sum(node => int.Parse(node.Nodes("valueC").FirstOrDefault()?.Value ?? "0")); if (animalCount > 0) { result += "Average longevity: " + longlivitySum / animalCount; } } catch (Exception e) { result += "longevity cant be read.\r\n" + e.Message + "\r\n"; } Output = "Csv data: " + result; }
private static void GenerateCustomClass(CustomClassSave customClass) { if (customClass.GenerateCode) { string fileName = ""; ICodeBlock codeBlock = new CodeDocument(); List <TypedMemberBase> members; Dictionary <string, string> untypedMembers; ReferencedFileSave rfs = null; if (customClass.CsvFilesUsingThis.Count != 0) { rfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(customClass.CsvFilesUsingThis[0]); } if (rfs != null) { // let's just use the existing code flow, even though it's less efficient: GenerateAndSaveDataClass(rfs, rfs.CsvDelimiter); } else { fileName = GetClassInfo(fileName, null, customClass, out members, out untypedMembers); bool succeeded = GenerateClassFromMembers(rfs, true, customClass.Name, members, untypedMembers); } } //return fileName; }
/// <summary> /// Checks the order of the elements within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null) { // Get the value of the GeneratedCodeElementOrder property. bool checkGeneratedCode = OrderingRules.GeneratedCodeElementOrderDefaultValueProperty; if (document.Settings != null) { BooleanProperty setting = this.GetSetting(document.Settings, OrderingRules.GeneratedCodeElementOrderProperty) as BooleanProperty; if (setting != null) { checkGeneratedCode = setting.Value; } // Check the rest of the elements. this.ProcessElements(csdocument.RootElement, checkGeneratedCode); } this.CheckUsingDirectiveOrder(csdocument.RootElement); } }
/// <summary> /// Initializes settings from specified document. /// </summary> public void Initialize(SourceAnalyzer analyzer, CodeDocument document) { IndentOptions = GetOptionsData <IndentOptionsData>( analyzer, document, Rules.CheckAllowedIndentationCharacters); LastLineOptions = GetOptionsData <LastLineOptionsData>( analyzer, document, Rules.CheckWhetherLastCodeLineIsEmpty); CharLimitOptions = GetOptionsData <CharLimitOptionsData>( analyzer, document, Rules.CodeLineMustNotBeLongerThan); MethodSizeOptions = GetOptionsData <LimitOptionsData>( analyzer, document, Rules.MethodMustNotContainMoreLinesThan); PropertySizeOptions = GetOptionsData <LimitOptionsData>( analyzer, document, Rules.PropertyMustNotContainMoreLinesThan); FileSizeOptions = GetOptionsData <LimitOptionsData>( analyzer, document, Rules.FileMustNotContainMoreLinesThan); }
/// <summary> /// Initializes common settings. /// </summary> private void InitializeCommon(SourceAnalyzer analyzer, CodeDocument document) { m_names = new Dictionary <string, string>(); m_examples = new Dictionary <string, string>(); m_regulars = new Dictionary <string, Regex>(); string words = SettingsManager.GetValue <string>( analyzer, document.Settings, NamingSettings.Words); foreach (string setting in NamingSettings.GetCommon()) { string name = SettingsManager.GetFriendlyName(analyzer, setting); m_names.Add(setting, name); string value = SettingsManager.GetValue <string>(analyzer, document.Settings, setting); if (String.IsNullOrEmpty(value)) { m_examples.Add(setting, null); m_regulars.Add(setting, null); } else { string example = NamingMacro.BuildExample(value); m_examples.Add(setting, example); Regex regex = NamingMacro.BuildRegex(value, words); m_regulars.Add(setting, regex); } } }
internal void CompileAlways(CodeDocument doc) { var th = new Thread(InternalCompile); th.IsBackground = true; th.Start(doc); }
private void ParseInput() { if (_parser == null) { Markup = "Grammar is not valid"; Output = ""; return; } // Load input CodeDocument doc = null; try { doc = CodeDocument.Load(_parser, _input); } catch (ParserException e) { Output = e.Message; Markup = "Input is not valid"; return; } // Convert to markup Markup = doc.ToMarkup(); ProcessOutput(doc); }
protected override void ProcessOutput(CodeDocument doc) { // Compile expression ExpressionBase expression; try { expression = ExpressionBuilder.BuildExp(doc.ChildNodes.OfType <CodeElement>().FirstOrDefault()); } catch (Exception e) { Output = "Expression does not compile.\r\n(The processing of parser output fails)\r\n" + e.Message; return; } // execute expression float result; try { result = expression.execute(); } catch (Exception e) { Output = "Expression cant execute.\r\n" + e.Message; return; } Output = "Expression result: " + result; }
public override Task <RazorSyntaxTree> GetLatestSyntaxTreeAsync(ITextSnapshot atOrNewerSnapshot, CancellationToken cancellationToken = default) { if (atOrNewerSnapshot == null) { throw new ArgumentNullException(nameof(atOrNewerSnapshot)); } lock (UpdateStateLock) { if (_disposed || (_latestParsedSnapshot != null && atOrNewerSnapshot.Version.VersionNumber <= _latestParsedSnapshot.Version.VersionNumber)) { return(Task.FromResult(CodeDocument?.GetSyntaxTree())); } SyntaxTreeRequest request = null; for (var i = _syntaxTreeRequests.Count - 1; i >= 0; i--) { if (_syntaxTreeRequests[i].Snapshot == atOrNewerSnapshot) { request = _syntaxTreeRequests[i]; break; } } if (request == null) { request = new SyntaxTreeRequest(atOrNewerSnapshot, cancellationToken); _syntaxTreeRequests.Add(request); } return(request.Task); } }
/// <summary> /// Checks the order of the elements within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null) { // Get the value of the GeneratedCodeElementOrder property. bool checkGeneratedCode = OrderingRules.GeneratedCodeElementOrderDefaultValueProperty; if (document.Settings != null) { BooleanProperty setting = this.GetSetting(document.Settings, OrderingRules.GeneratedCodeElementOrderProperty) as BooleanProperty; if (setting != null) { checkGeneratedCode = setting.Value; } // Check the rest of the elements. this.ProcessElements(csdocument.RootElement, checkGeneratedCode); } this.CheckUsingDirectiveOrder(csdocument.RootElement); } }
public override void AnalyzeDocument(CodeDocument document) { CsDocument csDocument = (CsDocument)document; csDocument.WalkDocument( new CodeWalkerElementVisitor <object>(this.VisitElement)); }
public static void CallDisposeAfterDisposing() { CodeDocument document = null; using (document = new CodeDocument(0, 0)) { } document.Dispose(); }
public static void CallWriteTextWithCodeLineAfterDisposing() { CodeDocument document = null; using (document = new CodeDocument(0, 0)) { } Assert.Throws<ObjectDisposedException>(() => document.WriteText(null as CodeLine)); }
/// <inheritdoc /> public override bool DoAnalysis(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; return csdocument.FileHeader == null || !csdocument.FileHeader.UnStyled; }
public static void CallWriteTextWithListOfCodeLineILGeneratorISymbolDocumentWriterAfterDisposing() { CodeDocument document = null; using (document = new CodeDocument(0, 0)) { } Assert.Throws<ObjectDisposedException>(() => document.WriteText(null as List<CodeLine>, null as ILGenerator, null as ISymbolDocumentWriter)); }
internal void Compile(CodeDocument doc) { if (thread != null) return; thread = new Thread(InternalCompile); thread.IsBackground = true; thread.Start(doc); }
public override void AnalyzeDocument(CodeDocument currentCodeDocument) { var codeDocument = (CsDocument) currentCodeDocument; if (codeDocument.RootElement != null && !codeDocument.RootElement.Generated) { _numberOfClasses = 0; codeDocument.WalkDocument(CheckClasses, null, null); } }
/// <summary> /// Checks the spacing of items within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { this.CheckSpacing(csdocument.Tokens, false, null); } }
public override void AnalyzeDocument(CodeDocument document) { var csharpDocument = (CsDocument)document; if (csharpDocument.RootElement != null && !csharpDocument.RootElement.Generated) { if (IsRuleEnabled(csharpDocument, RuleName)) { CheckLineLength(csharpDocument); } } }
/// <summary> /// Checks the case of element names within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { Dictionary<string, string> validPrefixes = this.GetPrefixes(document.Settings); this.ProcessElement(csdocument.RootElement, validPrefixes, false); } }
public static void WriteMultipleLinesWithDifferentDebuggableStates() { using (var document = new CodeDocument(0, 0)) { document.WriteText(new List<CodeLine>() { new CodeLine("x", true), new CodeLine("x", false), new CodeLine("x", true) }, null, null); } }
/// <summary> /// Checks the placement of brackets within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { // Check placement of curly brackets. csdocument.WalkDocument(this.VisitElement, this.CheckStatementCurlyBracketPlacement, this.CheckExpressionCurlyBracketPlacement); // Check line spacing rules. this.CheckLineSpacing(csdocument); } }
public override bool DoAnalysis(CodeDocument document) { var doc = (CsDocument)document; // skipping wrong or auto-generated documents if (doc.RootElement == null || doc.RootElement.Generated) { return true; } if (IsRuleEnabled(document, RuleName)) { doc.WalkDocument(null, null, VisitExpression); } return true; }
private void UpdateText(string text) { // we use a RichTextBlock here instead of the SyntaxEditor because the SyntaxEditor // adds too much overhead when we don't need editing capabilities var document = new CodeDocument(); document.Language = Language; document.SetText(text); var reader = document.CurrentSnapshot.GetReader(0); var paragraph = new Paragraph(); while (!reader.IsAtSnapshotEnd) { var token = reader.PeekToken(); var tokenText = reader.ReadText(token.Length); var run = new Run() {Text = tokenText}; if (token.Key == "Field") { run.Foreground = FieldBrush; } else if (token.Key == "Operator") { run.Foreground = OperatorBrush; } else if (token.Key == "Value") { run.Foreground = ValueBrush; } paragraph.Inlines.Add(run); } TextBlock.Blocks.Clear(); TextBlock.Blocks.Add(paragraph); }
/// <summary> /// Returns a value indicating whether to delay analysis of this document until the next pass. /// </summary> /// <param name="document"> /// The document to analyze. /// </param> /// <param name="passNumber"> /// The current pass number. /// </param> /// <returns> /// Returns true if analysis should be delayed. /// </returns> public override bool DelayAnalysis(CodeDocument document, int passNumber) { Param.RequireNotNull(document, "document"); Param.Ignore(passNumber); bool delay = false; // We sometimes delay pass zero, but never pass one. if (passNumber == 0) { // Get the root element. CsDocument csdocument = document as CsDocument; if (csdocument != null && csdocument.RootElement != null) { // If the element has any partial classes, structs, or interfaces, delay. This is due // to the fact that the class members rules need knowledge about all parts of the class // in order to find all class members. delay = Utils.ContainsPartialMembers(csdocument.RootElement); } } return delay; }
/// <summary> /// Checks the methods within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { // Check the access modifier rules. TopLevelElements topLevelElements = new TopLevelElements(); csdocument.WalkDocument(this.ProcessElement, this.ProcessStatement, this.ProcessExpression, topLevelElements); // If there is more than one top-level class in the file, make sure they are all // partial classes and are all of the same type. if (topLevelElements.Classes.Count > 1) { string name = string.Empty; foreach (Class classElement in topLevelElements.Classes) { if (!classElement.Declaration.ContainsModifier(CsTokenType.Partial) || (!string.IsNullOrEmpty(name) && string.Compare(name, classElement.FullNamespaceName, StringComparison.Ordinal) != 0)) { // Set the violation line number to the second class in the file. int count = 0; foreach (Class c in topLevelElements.Classes) { if (count == 1) { this.AddViolation(c, c.LineNumber, Rules.FileMayOnlyContainASingleClass); break; } ++count; } break; } name = classElement.FullNamespaceName; } } // If there is more than one namespace in the file, this is a violation. if (topLevelElements.Namespaces.Count > 1) { // Set the violation line number to the second namespace in the file. int count = 0; foreach (Namespace n in topLevelElements.Namespaces) { if (count == 1) { this.AddViolation(n, n.LineNumber, Rules.FileMayOnlyContainASingleNamespace); break; } ++count; } } } }
/// <inheritdoc /> public override bool DoAnalysis(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; CachedCodeStrings.Culture = document.SourceCode.Project.Culture; return csdocument.FileHeader == null || !csdocument.FileHeader.UnStyled; }
/// <summary> /// Checks the element headers within the given document. /// </summary> /// <param name="document"> /// The document to check. /// </param> public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { NamingService namingService = NamingService.GetNamingService(document.SourceCode.Project.Culture); namingService.AddDeprecatedWords(document.SourceCode.Project.DeprecatedWords); foreach (string dictionaryFolder in document.SourceCode.Project.DictionaryFolders) { if (dictionaryFolder.StartsWith(".", StringComparison.Ordinal)) { // Check relative to the source file namingService.AddDictionaryFolder( StyleCop.Utils.MakeAbsolutePath( Path.GetDirectoryName(document.SourceCode.Path), dictionaryFolder)); // Check relative to the settings file string location = document.SourceCode.Settings.Location; if (location != null) { namingService.AddDictionaryFolder( StyleCop.Utils.MakeAbsolutePath(Path.GetDirectoryName(location), dictionaryFolder)); } // Check relative to the project location namingService.AddDictionaryFolder( StyleCop.Utils.MakeAbsolutePath( Path.GetDirectoryName(document.SourceCode.Project.Location), dictionaryFolder)); } else { namingService.AddDictionaryFolder(dictionaryFolder); } } namingService.AddDictionaryFolder(Path.GetDirectoryName(document.SourceCode.Path)); namingService.AddDictionaryFolder(Path.GetDirectoryName(document.SourceCode.Project.Location)); this.CheckElementDocumentation(csdocument); this.CheckFileHeader(csdocument); this.CheckSingleLineComments(csdocument.RootElement); } }
public override bool ParseFile(SourceCode sourceCode, int passNumber, ref CodeDocument document) { Param.RequireNotNull(sourceCode, "sourceCode"); Param.RequireGreaterThanOrEqualToZero(passNumber, "passNumber"); Param.Ignore(document); StyleCopTrace.In(sourceCode, passNumber, document); // The document is parsed on the first pass. On any subsequent passes, we do not do anything. if (passNumber == 0) { if (this.SkipAnalysisForDocument(sourceCode)) { return false; } try { using (TextReader reader = sourceCode.Read()) { // Create the document. if (reader == null) { this.AddViolation(sourceCode, 1, Rules.FileMustBeReadable); } else { // Create the lexer object for the code string. CodeLexer lexer = new CodeLexer(this, sourceCode, new CodeReader(reader)); // Parse the document. CodeParser parser = new CodeParser(this, lexer); parser.ParseDocument(); document = parser.Document; } } } catch (SyntaxException syntaxex) { this.AddViolation(syntaxex.SourceCode, syntaxex.LineNumber, Rules.SyntaxException, syntaxex.Message); CsDocument csdocument = new CsDocument(sourceCode, this); csdocument.FileHeader = new FileHeader(string.Empty, new CsTokenList(csdocument.Tokens), new Reference<ICodePart>(csdocument)); document = csdocument; } } return StyleCopTrace.Out(false); }
internal void CompileAlways(CodeDocument doc) { var th = new Thread(InternalCompile); th.IsBackground = true; th.Start(doc); }
/// <summary> /// Analyzes a code file. /// </summary> /// <param name="document">The document to be analyzed.</param> public override void AnalyzeDocument(CodeDocument document) { CsDocument csharpDocument = (CsDocument)document; if (csharpDocument.RootElement != null && !csharpDocument.RootElement.Generated) { bool lastTokenWasWhitespace = false; bool lastTokenWasEndOfLine = false; bool firstToken = true; string lastLineIndentation = string.Empty; int lengthOfLastLine = 0; int lengthOfCurrentLine = 0; CsToken lastNonWhitespaceToken = null; foreach (CsToken token in csharpDocument.Tokens) { bool startOfLine = lastTokenWasEndOfLine || firstToken; lengthOfCurrentLine += token.Text.Length; if (token.CsTokenType == CsTokenType.WhiteSpace) { if (token.Text.Contains(" \t")) { this.AddViolation(csharpDocument.RootElement, token.LineNumber, NerdBankRule.NoSpacesBeforeTabs); } } // WIP: Support this: (note the use of tab-space-tab to support proper character alignment and indentation) //// var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")) //// select new { //// Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, //// Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value, //// }; if (token.CsTokenType == CsTokenType.WhiteSpace && startOfLine) { // Only allow spaces after as many tabs as were on the previous line, // and no more spaces than the length of the previous line minus the tabs, // and only one more tab than the previous line had (or else they're probably trying // to do some kind of character alignment with the previous line, which should be // done with spaces. int numberOfIndentingTabsThisLine = token.Text.ToCharArray().TakeWhile(ch => ch == '\t').Count(); int numberOfIndentingTabsLastLine = lastLineIndentation.ToCharArray().TakeWhile(ch => ch == '\t').Count(); if (numberOfIndentingTabsThisLine > numberOfIndentingTabsLastLine + 1) { // Disabling until the above WIP is fixed. ////this.AddViolation(csharpDocument.RootElement, token.LineNumber, NerdBankRule.OneTabIndent); } if (token.Text.Contains(" ")) { if (numberOfIndentingTabsThisLine < numberOfIndentingTabsLastLine) { // This line has fewer tabs indenting it than the previous line did, // so there definitely should not have been any spaces in the indentation. this.AddViolation(csharpDocument.RootElement, token.LineNumber, NerdBankRule.IndentUsingTabs); } else { int lastLineContentLength = lengthOfLastLine - numberOfIndentingTabsLastLine - 1; // -1 to not include \n int numberOfIndentingSpacesThisLine = token.Text.ToCharArray().SkipWhile(ch => ch == '\t').TakeWhile(ch => ch == ' ').Count(); if (numberOfIndentingSpacesThisLine > lastLineContentLength) { // This line is indented with spaces that go further out than the last character of the last line. this.AddViolation(csharpDocument.RootElement, token.LineNumber, NerdBankRule.IndentUsingTabs); } else { if (lastNonWhitespaceToken.CsTokenType == CsTokenType.OpenCurlyBracket) { // This is the beginning of a new block. No spaces should be used in indentation. this.AddViolation(csharpDocument.RootElement, token.LineNumber, NerdBankRule.IndentUsingTabs); } } } } lastLineIndentation = token.Text; } if (token.CsTokenType == CsTokenType.EndOfLine && lastTokenWasWhitespace) { this.AddViolation(csharpDocument.RootElement, token.LineNumber, NerdBankRule.NoTrailingWhiteSpace); } lastTokenWasEndOfLine = token.CsTokenType == CsTokenType.EndOfLine; lastTokenWasWhitespace = token.CsTokenType == CsTokenType.WhiteSpace; firstToken = false; if (token.CsTokenType != CsTokenType.WhiteSpace && token.CsTokenType != CsTokenType.EndOfLine) { lastNonWhitespaceToken = token; } if (token.CsTokenType == CsTokenType.EndOfLine) { lengthOfLastLine = lengthOfCurrentLine; lengthOfCurrentLine = 0; } } } }