Ejemplo n.º 1
0
 public void TheSignatureOfACodeFileShouldContain_TheLinesOfCodeCount()
 {
     var codefile = new CodeFile(CodeFileName, Code);
     var linesOfCodeSignature = string.Format("(5)");
     string signature = Signature.For(codefile);
     signature.Should().Contain(linesOfCodeSignature);
 }
Ejemplo n.º 2
0
 public void ShouldFindInterestingCharacters()
 {
     var codeFile = new CodeFile(SampleCodeFile.CodeFileName, SampleCodeFile.Code);
     codeFile.InterestingCharacters.Should().Contain.One(';');
     codeFile.InterestingCharacters.Should().Contain.One('{');
     codeFile.InterestingCharacters.Should().Contain.One('}');
 }
Ejemplo n.º 3
0
        public void read_and_write_with_a_link()
        {
            var project = CsProjFile.CreateAtSolutionDirectory("Foo", Guid.NewGuid().ToString());

            var file = new CodeFile("..\\CommonAssemblyInfo.cs") {Link = "CommonAssemblyInfo.cs"};

            project.Add(file);

            project.Save();

            var project2 = CsProjFile.LoadFrom(project.FileName);
            project2.Find<CodeFile>("..\\CommonAssemblyInfo.cs")
                    .Link.ShouldEqual("CommonAssemblyInfo.cs");
        }
Ejemplo n.º 4
0
        public CodeModel(string source, string fileName)
        {
            _fileName = fileName;
            _file = new CodeFile(this);

            if (!string.IsNullOrEmpty(fileName))
            {
                switch (Path.GetFileName(fileName).ToLower())
                {
                    case "stdlib.i":
                    case "stdlib.i&":
                        // Don't include this file if the user happens to have stdlib.i open right now.
                        break;
                    default:
                        AddIncludeFile(_fileName, "stdlib.i", false);
                        break;
                }
            }

            _tracker = new Tracker(source);
            _file.Parse(source, fileName);
        }
Ejemplo n.º 5
0
 public static Diagnostic IncompleteDeclaration(CodeFile file, TextSpan span)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.CompilationError, DiagnosticPhase.Parsing, 3001, "Incomplete declaration"));
 }
Ejemplo n.º 6
0
 public static Diagnostic SelfOutsideMethod(CodeFile file, TextSpan span)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6008,
                           "Can't use `self` outside of a method or constructor"));
 }
Ejemplo n.º 7
0
 public static Diagnostic VariableMayNotHaveBeenAssigned(CodeFile file, TextSpan span, Name name)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6005,
                           $"Variable `{name}` may not have been assigned before use"));
 }
Ejemplo n.º 8
0
 public Scope(CodeFile file, int depth, ScopeHint hint)
 {
     _file = file;
     _depth = depth;
     _hint = ScopeHint.None;
 }
Ejemplo n.º 9
0
 public void ShouldReturnTheCompleteSignature()
 {
     var codefile = new CodeFile(CodeFileName, Code);
     string signature = Signature.For(codefile);
     signature.Should().Equal("code.cs (5): {;}");
 }
Ejemplo n.º 10
0
		private static void writeFileToFileSystem(CodeFile file, string text)
		{
			IoNic.WriteFile(text, file.FullPath); IoNic.WriteFile(text, file.FullPath);
			Vs.Helper.Log.Add(LogEntry.Info("generated {0}", file.PathToProject));
		}
Ejemplo n.º 11
0
 public void ShouldGetTheLinesOfCode()
 {
     var codeFile = new CodeFile(SampleCodeFile.CodeFileName, SampleCodeFile.Code);
     codeFile.LinesOfCode.Should().Equal(5);
 }
Ejemplo n.º 12
0
 public static Diagnostic CannotMoveBorrowedValue(CodeFile file, MoveExpressionSyntax expression)
 {
     return(new Diagnostic(file, expression.Span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 3009,
                           $"Cannot move borrowed value `{file.Code[expression.Expression.Span]}`"));
 }
Ejemplo n.º 13
0
 public static Diagnostic MustBeCallable(CodeFile file, ExpressionSyntax expression)
 {
     return(new Diagnostic(file, expression.Span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 3008,
                           $"Expression must be of callable type to be invoked `{file.Code[expression.Span]}`"));
 }
Ejemplo n.º 14
0
 public static Diagnostic CannotConvert(CodeFile file, ExpressionSyntax expression, DataType ofType, DataType toType)
 {
     return(new Diagnostic(file, expression.Span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 3007,
                           $"Cannot convert expression `{file.Code[expression.Span]}` of type `{ofType}` to type `{toType}`"));
 }
Ejemplo n.º 15
0
 public static Diagnostic CircularDefinition(CodeFile file, TextSpan span, Name typeDeclarationName)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 3006,
                           $"Declaration of type `{typeDeclarationName}` is part of a circular definition"));
 }
Ejemplo n.º 16
0
 public static Diagnostic MustBeABoolExpression(CodeFile file, TextSpan span)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 3005,
                           "Expression must be of type `bool`"));
 }
Ejemplo n.º 17
0
        private static void assertCodeFileIsCorrect(CodeFile codeFile, string expectedFullPath, string expectedContents)
        {
            Assert.That(codeFile.Id, Is.Not.EqualTo(Guid.Empty));
            Assert.That(codeFile.Filename, Is.EqualTo(Path.GetFileName(expectedFullPath)));
            Assert.That(codeFile.FullPath, Is.EqualTo(expectedFullPath));
            Assert.That(codeFile.Content, Is.EqualTo(expectedContents));
            Assert.That(codeFile.VcsRoot, Is.Not.Null);

            var expectedRepoName = Path.GetDirectoryName(expectedFullPath).Split(Path.DirectorySeparatorChar).Last();
            Assert.That(codeFile.VcsRoot.Name, Is.EqualTo(expectedRepoName));
        }
Ejemplo n.º 18
0
 public void ACodeFileShouldContainAName()
 {
     var codefile = new CodeFile("Name", SampleCodeFile.Code);
     codefile.Name.Should().Equal("Name");
 }
Ejemplo n.º 19
0
        public override void Execute(Action <DaemonStageResult> committer)
        {
            var localIdentifierNames = new HashSet <string>(StringComparer.CurrentCultureIgnoreCase);
            var highlightings        = new List <HighlightingInfo>();

            CodeFile.ProcessChildren <IIdentifier>(
                node => {
                localIdentifierNames.Add(node.Name);
                localIdentifierNames.Add(RemovePrefixAndSuffix(node));
                if (IsValidSpellCheckIdentifierNode(node))
                {
                    highlightings.AddRange(FindHighlightings(node));
                }
            }
                );

#if (RSHARP6 || RESHARP7)
            var declarationsCache = CodeFile.GetPsiServices().CacheManager.GetDeclarationsCache(CodeFile.GetPsiModule(), true, true);
#else
            var declarationsCache = CodeFile.GetPsiServices().Symbols;
#endif

            CodeFile.ProcessChildren <ITreeNode>(
                node => {
#if RSHARP6
                if (node is JavaScriptGenericToken && (node as JavaScriptGenericToken).NodeType == JavaScriptTokenType.STRING_LITERAL)
                {
                    highlightings.AddRange(FindStringHighlightings(node, localIdentifierNames, declarationsCache));
                }
#else
                if (node is IJavaScriptLiteralExpression && (node as IJavaScriptLiteralExpression).ConstantValueType == ConstantValueTypes.String)
                {
                    highlightings.AddRange(FindStringHighlightings(node, localIdentifierNames, declarationsCache));
                }
#endif
                else if (node is IComment)
                {
                    highlightings.AddRange(FindHighlightings(node as IComment, localIdentifierNames, declarationsCache));
                }
            }
                );

            committer(new DaemonStageResult(highlightings));
        }
Ejemplo n.º 20
0
		private void writeFile(CodeFile file)
		{
			if (shouldSkipFile(file))
				return;

			var text = CodeFormatter.Format(file.GetFileContents());
			var writeFile = true;
			if (File.Exists(file.FullPath))
			{
				var existingText = File.ReadAllText(file.FullPath);
				if (text == existingText)
				{
					Vs.Helper.Log.Add(LogEntry.Info("no changes {0}", file.PathToProject));
					writeFile = false;
				}
				else
				{
					checkOutFiles(file.FullPath);
				}
			}

			if (!writeFile)
				return;

			ProjectFacade.writeFileToFileSystem(file, text);

			if (Contains(file.PathToProject))
				return;
			Project.AddItem(file.VisualStudioItemTypeNode, file.PathToProject);
			filesToAddToSourceControl.Add(file.FullPath);
		}
Ejemplo n.º 21
0
        /// <summary>
        /// Processes the file.
        /// </summary>
        /// <param name="trackedMethods">The tracked methods.</param>
        /// <param name="fileIds">The file ids of the class.</param>
        /// <param name="filePath">The file path.</param>
        /// <param name="methods">The methods.</param>
        /// <returns>The <see cref="CodeFile"/>.</returns>
        private static CodeFile ProcessFile(IDictionary <string, string> trackedMethods, HashSet <string> fileIds, string filePath, XElement[] methods)
        {
            var seqpntsOfFile = methods
                                .Elements("SequencePoints")
                                .Elements("SequencePoint")
                                .Where(seqpnt => (seqpnt.Attribute("fileid") != null &&
                                                  fileIds.Contains(seqpnt.Attribute("fileid").Value)) ||
                                       (seqpnt.Attribute("fileid") == null && seqpnt.Parent.Parent.Element("FileRef") != null &&
                                        fileIds.Contains(seqpnt.Parent.Parent.Element("FileRef").Attribute("uid").Value)))
                                .Select(seqpnt => new
            {
                LineNumberStart   = int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture),
                LineNumberEnd     = seqpnt.Attribute("el") != null ? int.Parse(seqpnt.Attribute("el").Value, CultureInfo.InvariantCulture) : int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture),
                Visits            = seqpnt.Attribute("vc").Value.ParseLargeInteger(),
                TrackedMethodRefs = seqpnt.Elements("TrackedMethodRefs")
                                    .Elements("TrackedMethodRef")
                                    .Select(t => new
                {
                    Visits          = t.Attribute("vc").Value.ParseLargeInteger(),
                    TrackedMethodId = t.Attribute("uid").Value
                })
            })
                                .OrderBy(seqpnt => seqpnt.LineNumberEnd)
                                .ToArray();

            var branches = GetBranches(methods, fileIds);

            var coverageByTrackedMethod = seqpntsOfFile
                                          .SelectMany(s => s.TrackedMethodRefs)
                                          .Select(t => t.TrackedMethodId)
                                          .Distinct()
                                          .ToDictionary(id => id, id => new CoverageByTrackedMethod {
                Coverage = new int[] { }, LineVisitStatus = new LineVisitStatus[] { }
            });

            int[]             coverage        = new int[] { };
            LineVisitStatus[] lineVisitStatus = new LineVisitStatus[] { };

            if (seqpntsOfFile.Length > 0)
            {
                coverage        = new int[seqpntsOfFile[seqpntsOfFile.LongLength - 1].LineNumberEnd + 1];
                lineVisitStatus = new LineVisitStatus[seqpntsOfFile[seqpntsOfFile.LongLength - 1].LineNumberEnd + 1];

                for (int i = 0; i < coverage.Length; i++)
                {
                    coverage[i] = -1;
                }

                foreach (var trackedMethodCoverage in coverageByTrackedMethod)
                {
                    trackedMethodCoverage.Value.Coverage        = (int[])coverage.Clone();
                    trackedMethodCoverage.Value.LineVisitStatus = new LineVisitStatus[seqpntsOfFile[seqpntsOfFile.LongLength - 1].LineNumberEnd + 1];
                }

                foreach (var seqpnt in seqpntsOfFile)
                {
                    for (int lineNumber = seqpnt.LineNumberStart; lineNumber <= seqpnt.LineNumberEnd; lineNumber++)
                    {
                        int visits = coverage[lineNumber] == -1 ? seqpnt.Visits : coverage[lineNumber] + seqpnt.Visits;
                        coverage[lineNumber] = visits;

                        if (lineVisitStatus[lineNumber] != LineVisitStatus.Covered)
                        {
                            bool partiallyCovered = false;

                            ICollection <Branch> branchesOfLine = null;

                            // Use 'LineNumberStart' instead of 'lineNumber' here. Branches have line number of first line of seqpnt
                            if (branches.TryGetValue(seqpnt.LineNumberStart, out branchesOfLine))
                            {
                                partiallyCovered = branchesOfLine.Any(b => b.BranchVisits == 0);
                            }

                            LineVisitStatus statusOfLine = visits > 0 ? (partiallyCovered ? LineVisitStatus.PartiallyCovered : LineVisitStatus.Covered) : LineVisitStatus.NotCovered;
                            lineVisitStatus[lineNumber] = (LineVisitStatus)Math.Max((int)lineVisitStatus[lineNumber], (int)statusOfLine);
                        }

                        if (visits > -1)
                        {
                            foreach (var trackedMethodCoverage in coverageByTrackedMethod)
                            {
                                if (trackedMethodCoverage.Value.Coverage[lineNumber] == -1)
                                {
                                    trackedMethodCoverage.Value.Coverage[lineNumber]        = 0;
                                    trackedMethodCoverage.Value.LineVisitStatus[lineNumber] = LineVisitStatus.NotCovered;
                                }
                            }
                        }

                        foreach (var trackedMethod in seqpnt.TrackedMethodRefs)
                        {
                            var trackedMethodCoverage = coverageByTrackedMethod[trackedMethod.TrackedMethodId];

                            int             trackeMethodVisits = trackedMethodCoverage.Coverage[lineNumber] == -1 ? trackedMethod.Visits : trackedMethodCoverage.Coverage[lineNumber] + trackedMethod.Visits;
                            LineVisitStatus statusOfLine       = trackeMethodVisits > 0 ? (LineVisitStatus)Math.Min((int)LineVisitStatus.Covered, (int)lineVisitStatus[lineNumber]) : LineVisitStatus.NotCovered;

                            trackedMethodCoverage.Coverage[lineNumber]        = trackeMethodVisits;
                            trackedMethodCoverage.LineVisitStatus[lineNumber] = statusOfLine;
                        }
                    }
                }
            }

            var codeFile = new CodeFile(filePath, coverage, lineVisitStatus, branches);

            foreach (var trackedMethodCoverage in coverageByTrackedMethod)
            {
                string name = null;

                // Sometimes no corresponding MethodRef element exists
                if (trackedMethods.TryGetValue(trackedMethodCoverage.Key, out name))
                {
                    string     shortName  = name.Substring(name.Substring(0, name.IndexOf(':') + 1).LastIndexOf('.') + 1);
                    TestMethod testMethod = new TestMethod(name, shortName);
                    codeFile.AddCoverageByTestMethod(testMethod, trackedMethodCoverage.Value);
                }
            }

            var methodsOfFile = methods
                                .Where(m => m.Element("FileRef") != null && fileIds.Contains(m.Element("FileRef").Attribute("uid").Value))
                                .ToArray();

            SetMethodMetrics(codeFile, methodsOfFile);
            SetCodeElements(codeFile, methodsOfFile);

            return(codeFile);
        }
Ejemplo n.º 22
0
 public static string For(CodeFile codeFile)
 {
     var signature = CodeSignature(codeFile);
     return string.Format("{0} ({1}): {2}", codeFile.Name, codeFile.LinesOfCode, signature);
 }
Ejemplo n.º 23
0
        private CodeFile ProcessIncludeFile(string fullPathName)
        {
            try
            {
                Trace.WriteLine(string.Concat("Processing include file: ", fullPathName));

                var merger = new FileMerger();
                merger.MergeFile(fullPathName, true);

                var content = merger.MergedContent;
                if (string.IsNullOrEmpty(content)) return null;

                var file = new CodeFile(this);
                file.Parse(content, fullPathName);
                return file;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception when merging file '{0}': {1}", fullPathName, ex));
                return null;
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Extracts the metrics from the given <see cref="XElement">XElements</see>.
        /// </summary>
        /// <param name="codeFile">The code file.</param>
        /// <param name="methodsOfFile">The methods of the file.</param>
        private static void SetMethodMetrics(CodeFile codeFile, IEnumerable <XElement> methodsOfFile)
        {
            foreach (var methodGroup in methodsOfFile.GroupBy(m => m.Element("Name").Value))
            {
                var method = methodGroup.First();

                // Exclude properties and lambda expressions
                if (method.Attribute("skippedDueTo") != null ||
                    method.HasAttributeWithValue("isGetter", "true") ||
                    method.HasAttributeWithValue("isSetter", "true") ||
                    lambdaMethodNameRegex.IsMatch(methodGroup.Key))
                {
                    continue;
                }

                var metrics = new List <Metric>()
                {
                    new Metric(
                        ReportResources.CyclomaticComplexity,
                        ParserBase.CyclomaticComplexityUri,
                        MetricType.CodeQuality,
                        methodGroup.Max(m => int.Parse(m.Attribute("cyclomaticComplexity").Value, CultureInfo.InvariantCulture)),
                        MetricMergeOrder.LowerIsBetter),
                    new Metric(
                        ReportResources.SequenceCoverage,
                        ParserBase.CodeCoverageUri,
                        MetricType.CoveragePercentual,
                        methodGroup.Max(m => decimal.Parse(m.Attribute("sequenceCoverage").Value, CultureInfo.InvariantCulture))),
                    new Metric(
                        ReportResources.BranchCoverage,
                        ParserBase.CodeCoverageUri,
                        MetricType.CoveragePercentual,
                        methodGroup.Max(m => decimal.Parse(m.Attribute("branchCoverage").Value, CultureInfo.InvariantCulture)))
                };

                var npathComplexityAttributes = methodGroup.Select(m => m.Attribute("nPathComplexity")).Where(a => a != null).ToArray();

                if (npathComplexityAttributes.Length > 0)
                {
                    metrics.Insert(
                        1,
                        new Metric(
                            ReportResources.NPathComplexity,
                            ParserBase.NPathComplexityUri,
                            MetricType.CodeQuality,
                            npathComplexityAttributes
                            .Select(a => int.Parse(a.Value, CultureInfo.InvariantCulture))
                            .Max(a => a < 0 ? int.MaxValue : a),
                            MetricMergeOrder.LowerIsBetter));
                }

                var crapScoreAttributes = methodGroup.Select(m => m.Attribute("crapScore")).Where(a => a != null).ToArray();
                if (crapScoreAttributes.Length > 0)
                {
                    metrics.Add(new Metric(
                                    ReportResources.CrapScore,
                                    ParserBase.CrapScoreUri,
                                    MetricType.CodeQuality,
                                    crapScoreAttributes.Max(a => decimal.Parse(a.Value, CultureInfo.InvariantCulture)),
                                    MetricMergeOrder.LowerIsBetter));
                }

                string fullName  = ExtractMethodName(methodGroup.Key);
                string shortName = methodRegex.Replace(fullName, m => string.Format(CultureInfo.InvariantCulture, "{0}({1})", m.Groups["MethodName"].Value, m.Groups["Arguments"].Value.Length > 0 ? "..." : string.Empty));

                var methodMetric = new MethodMetric(fullName, shortName, metrics);

                var seqpnt = method
                             .Elements("SequencePoints")
                             .Elements("SequencePoint")
                             .FirstOrDefault();

                if (seqpnt != null)
                {
                    methodMetric.Line = int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture);
                }

                codeFile.AddMethodMetric(methodMetric);
            }
        }
Ejemplo n.º 25
0
 public static Diagnostic CantShadow(CodeFile file, TextSpan bindingSpan, TextSpan useSpan)
 {
     // TODO that use span needs converted to a line and column
     return(new Diagnostic(file, bindingSpan, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6003,
                           $"Variable binding can't shadow. Shadowed binding used at {useSpan}"));
 }
Ejemplo n.º 26
0
 public static Diagnostic CantRebindAsMutableBinding(CodeFile file, TextSpan span)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6002,
                           $"Mutable variable binding can't rebind previous variable binding"));
 }
Ejemplo n.º 27
0
 public FrmFileCoverage(CodeFile codeFile)
 {
     InitializeComponent();
     _codeFile = codeFile;
 }
Ejemplo n.º 28
0
 public static Diagnostic VariableMayAlreadyBeAssigned(CodeFile file, TextSpan span, Name name)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6004,
                           $"Variable `{name}` declared with `let` may already be assigned"));
 }
Ejemplo n.º 29
0
        public async Task <CodeFile> GetCodeFileAsync(string revisionId, string codeFileId)
        {
            var info = await GetBlobClient(revisionId, codeFileId).DownloadAsync();

            return(await CodeFile.DeserializeAsync(info.Value.Content));
        }
Ejemplo n.º 30
0
 public static Diagnostic UseOfPossiblyMovedValue(CodeFile file, TextSpan span)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6006,
                           "Use of possibly moved value."));
 }
Ejemplo n.º 31
0
 public UserDefinedType(string text, FileSpan fileSpan, ISyntaxEntity parent, CodeFile currentCodeFile)
     : base(text, fileSpan, parent, currentCodeFile)
 {
 }
Ejemplo n.º 32
0
 public static Diagnostic NoStringTypeDefined(CodeFile file)
 {
     return(new Diagnostic(file, new TextSpan(0, 0), DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6009,
                           "Could not find a `String` type. A `String` type must be defined in the global namespace."));
 }
Ejemplo n.º 33
0
 public override async Task <CodeFile> GetCodeFileAsync(string originalName, Stream stream, bool runAnalysis)
 {
     return(await CodeFile.DeserializeAsync(stream));
 }
Ejemplo n.º 34
0
 public static Diagnostic UnexpectedToken(CodeFile file, TextSpan span)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.CompilationError, DiagnosticPhase.Parsing, 3002, $"Unexpected token `{file.Code[span]}`"));
 }
Ejemplo n.º 35
0
        internal CodeFile CompileTest([PexAssumeUnderTest] CSharp target, string programText)
        {
            CodeFile result = target.Parse(programText, "");

            return(result);
        }
Ejemplo n.º 36
0
        private CodeFile createCodeFileInDatabase(string codeFilePath, string fileContents)
        {
            var newCodeFile = new CodeFile
            {
                Filename = Path.GetFileName(codeFilePath),
                FullPath = codeFilePath,
                Content = fileContents
            };

            using(var session = _documentStore.OpenSession())
            {
                session.Store(newCodeFile);
                session.SaveChanges();
            }

            return newCodeFile;
        }
Ejemplo n.º 37
0
 public static Diagnostic CantMove(CodeFile file, ExpressionSyntax expression)
 {
     return(new Diagnostic(file, expression.Span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6004,
                           $"Can't move out of expression"));
 }
Ejemplo n.º 38
0
 public static Diagnostic CantAssignToImmutable(CodeFile file, TextSpan span)
 {
     return(new Diagnostic(file, span, DiagnosticLevel.FatalCompilationError, DiagnosticPhase.Analysis, 6005,
                           $"Can't assign to immutable variable"));
 }
Ejemplo n.º 39
0
 public ConversionException(CodeFile codeFile, Exception ex = null, string message = "")
     : base(ex, message)
 {
     CodeFile = codeFile ?? CodeFile.Empty;
 }
Ejemplo n.º 40
0
		public void AddFile(CodeFile file)
		{
			Files.Add(file);
		}
Ejemplo n.º 41
0
 /// <summary>
 /// Eexecute this code generator against a code file
 /// </summary>
 public CompilerResult Compile(CodeFile file) => Compile(new[] { file });
Ejemplo n.º 42
0
		private bool shouldSkipFile(CodeFile file)
		{
			var response = Contains(file.PathToProject) && !file.OverwriteExistingFile;
			if (response)
			{
				Vs.Helper.Log.Add(LogEntry.Trace(
					   "SKIPPED {0} already exists",
					   file.PathToProject));
			}
			return response;
		}
Ejemplo n.º 43
0
 public StructDefinition(string text, FileSpan fileSpan, ISyntaxEntity parent, CodeFile currentCodeFile) : base(text, fileSpan, parent, currentCodeFile)
 {
 }
Ejemplo n.º 44
0
 private static string CodeSignature(CodeFile codeFile)
 {
     return string.Join(string.Empty, codeFile.InterestingCharacters);
 }
Ejemplo n.º 45
0
 protected Variable(string name, FileSpan location, ISyntaxEntity parent, CodeFile currentCodeFile)
     : base(name, location, parent, currentCodeFile)
 {
 }
Ejemplo n.º 46
0
        /// <summary>
        /// Generates an <see cref="XmlElement" /> that represent a this resource.
        /// </summary>
        /// <param name="ownerDocument">The owner document to use to create the element.</param>
        /// <param name="context">The context under which this method is executed, used to resolve the paths and load resources with.</param>
        /// <returns>
        /// An <see cref="XmlElement" /> that represent this resource.
        /// </returns>
        public virtual XmlNode ToXml(XmlDocument ownerDocument, SageContext context)
        {
            Contract.Requires<ArgumentNullException>(ownerDocument != null);
            Contract.Requires<ArgumentNullException>(context != null);

            XmlDocumentFragment result = ownerDocument.CreateDocumentFragment();
            List<string> webPaths = new List<string>();

            if (this.Unmerge)
            {
                if (codeFile == null)
                {
                    codeFile = CodeFile.Create(
                        this.GetResolvedPhysicalPath(context),
                        this.GetResolvedWebPath(context));
                }

                foreach (string dependency in codeFile.Dependencies)
                {
                    string webPath = context.Path.GetRelativeWebPath(dependency, true);
                    webPaths.Add(webPath);
                }
            }
            else
            {
                webPaths.Add(this.GetResolvedWebPath(context));
            }

            if (this.Type == ResourceType.CSS)
            {
                foreach (string webPath in webPaths)
                {
                    XmlElement link = ownerDocument.CreateElement("xhtml:link", XmlNamespaces.XHtmlNamespace);
                    link.SetAttribute("type", "text/css");
                    link.SetAttribute("rel", "stylesheet");
                    link.SetAttribute("href", webPath);
                    result.AppendChild(link);
                }
            }
            else if (this.Type == ResourceType.JavaScript)
            {
                foreach (string webPath in webPaths)
                {
                    XmlElement script = ownerDocument.CreateElement("xhtml:script", XmlNamespaces.XHtmlNamespace);
                    script.SetAttribute("type", "text/javascript");
                    script.SetAttribute("src", webPath);
                    result.AppendChild(script);
                }
            }
            else if (this.Type == ResourceType.Icon)
            {
                XmlElement icon = ownerDocument.CreateElement("xhtml:link", XmlNamespaces.XHtmlNamespace);
                icon.SetAttribute("rel", "icon");
                icon.SetAttribute("href", webPaths[0]);
                result.AppendChild(icon);
            }
            else
            {
                string documentPath = context.Path.Resolve(this.Path);
                XmlDocument document = context.Resources.LoadXml(documentPath);
                XmlElement importedElement = (XmlElement) ownerDocument.ImportNode(document.DocumentElement, true);
                if (!string.IsNullOrWhiteSpace(this.Name))
                {
                    var nameAttribute = ownerDocument.CreateAttribute("sage", "name", XmlNamespaces.SageNamespace);
                    nameAttribute.InnerText = this.Name;
                    importedElement.SetAttributeNode(nameAttribute);
                }

                result.AppendChild(importedElement);
            }

            return result;
        }
Ejemplo n.º 47
0
        static void Main(string[] args)
        {
            //var list1 = new List<HtmlElementTypes>();
            //list1.AddRange(new [] { HtmlElementTypes.Html, HtmlElementTypes.A, HtmlElementTypes.Abbr, });


            var pageSource = string.Empty;
            var list       = new List <string>
            {
                //// "file:///C:/1/bootstrap.html",
                //"http://*****:*****@"\" + (300 + fileNumber)))
                {
                    writer.WriteLine(@"// {0}", url);
                    entries.ToList().ForEach(elementDefinition =>
                    {
                        var codeEntryString = elementDefinition.GenerateCode(SupportedTargetLanguages.Java);
                        Console.WriteLine(codeEntryString);
                        writer.WriteLine(codeEntryString);
                    });
                    writer.Flush();
                    writer.Close();
                }

                /*
                 * // driver.findElement(By.xpath())
                 * // driver.findElement(By.className())
                 * // driver.findElement(By.cssSelector())
                 * // driver.findElement(By.id())
                 * // driver.findElement(By.linkText())
                 * // driver.findElement(By.name())
                 * // driver.findElement(By.partialLinkText())
                 * // driver.findElement(By.tagName())
                 */

                // 20160715
                var onlyPageMembers = entries
                                      .Where(entry => PageObjectParts.CodeOfMember == entry.CodeClass)
                                      .Cast <IPageMemberCodeEntry>()
                                      .ToList();

                using (var tempWriter = new StreamWriter(folderForExportFiles + @"\" + (400 + fileNumber)))
                {
                    // this worked
                    // entries.ToList().ForEach(eltDef => tempWriter.WriteLine("try {{ elementFound = \"0\"; elementDisplayed = \"0\"; allElementsNumber++; WebElement element = driver.findElement(By.{0}(\"{1}\")); foundElementsNumber++; elementFound = \"1\"; if (element.isDisplayed()) {{ displayedElementsNumber++; elementDisplayed = \"1\"; }} }} catch (Exception e) {{ System.out.println(\"failed: {1}\"); }} writeData(fileWriter, \"{0}\", \"{1}\", elementFound, elementDisplayed);",
                    // 20160715
                    // TODO: work only with code entries
                    // entries.ToList().ForEach(eltDef => tempWriter.WriteLine("testLocator(By.{0}(\"{1}\"), \"{0}\", \"{1}\");",
                    onlyPageMembers
                    .ForEach(eltDef => tempWriter.WriteLine("testLocator(By.{0}(\"{1}\"), \"{0}\", \"{1}\");",
                                                            // static void testLocator(org.openqa.selenium.By by, String locatorName, String locatorPath) {
                                                            eltDef.Locators.Any() ? eltDef.Locators.First(loc => loc.IsBestChoice).ElementSearchTypePreference.ToString() : "_",
                                                            eltDef.Locators.Any() ? eltDef.Locators.First(loc => loc.IsBestChoice).SearchString : "_"
                                                            ));
                    tempWriter.Flush();
                    tempWriter.Close();
                }

                // 20160715
                // exporter.WriteToFile(entries, folderForExportFiles + @"\" + (100 + ++fileNumber));
                exporter.WriteToFile(onlyPageMembers, folderForExportFiles + @"\" + (100 + ++fileNumber));
                var importedEntries = importer.LoadFromFile <HtmlElementTypes>(folderForExportFiles + @"\" + (100 + fileNumber));
                exporter.WriteToFile(importedEntries, folderForExportFiles + @"\" + (200 + fileNumber));
            });

            Console.WriteLine("Completed!");
            Console.ReadKey();
        }
Ejemplo n.º 48
0
 public void TheSignatureOfACodefileShouldContain_InterestingCharacters()
 {
     var codefile = new CodeFile(CodeFileName, Code);
     string signature = Signature.For(codefile);
     signature.Should().Contain("{;}");
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Extracts the metrics from the given <see cref="XElement">XElements</see>.
        /// </summary>
        /// <param name="codeFile">The code file.</param>
        /// <param name="methodsOfFile">The methods of the file.</param>
        private static void SetMethodMetrics(CodeFile codeFile, IEnumerable <XElement> methodsOfFile)
        {
            foreach (var method in methodsOfFile)
            {
                string fullName = method.Attribute("name").Value + method.Attribute("desc").Value;

                if (fullName.StartsWith("lambda$"))
                {
                    continue;
                }

                string shortName = methodRegex.Replace(fullName, m => string.Format(CultureInfo.InvariantCulture, "{0}({1})", m.Groups["MethodName"].Value, m.Groups["Arguments"].Value.Length > 0 ? "..." : string.Empty));

                var metrics = new List <Metric>();

                var lineRate = method.Elements("counter")
                               .Where(e => e.Attribute("type") != null && e.Attribute("type").Value == "LINE")
                               .FirstOrDefault();

                if (lineRate != null)
                {
                    decimal missed  = decimal.Parse(lineRate.Attribute("missed").Value, CultureInfo.InvariantCulture);
                    decimal covered = decimal.Parse(lineRate.Attribute("covered").Value, CultureInfo.InvariantCulture);
                    decimal total   = missed + covered;

                    metrics.Add(new Metric(
                                    ReportResources.Coverage,
                                    ParserBase.CodeCoverageUri,
                                    MetricType.CoveragePercentual,
                                    total == 0 ? (decimal?)null : Math.Round((100 * covered) / total, 2, MidpointRounding.AwayFromZero)));
                }
                else
                {
                    // If no line rate available, do not add branch coverage too
                    continue;
                }

                var branchRate = method.Elements("counter")
                                 .Where(e => e.Attribute("type") != null && e.Attribute("type").Value == "BRANCH")
                                 .FirstOrDefault();

                if (branchRate != null)
                {
                    decimal missed  = decimal.Parse(branchRate.Attribute("missed").Value, CultureInfo.InvariantCulture);
                    decimal covered = decimal.Parse(branchRate.Attribute("covered").Value, CultureInfo.InvariantCulture);
                    decimal total   = missed + covered;

                    metrics.Add(new Metric(
                                    ReportResources.BranchCoverage,
                                    ParserBase.CodeCoverageUri,
                                    MetricType.CoveragePercentual,
                                    total == 0 ? (decimal?)null : Math.Round((100 * covered) / total, 2, MidpointRounding.AwayFromZero)));
                }
                else
                {
                    // If no branch coverage is available, add default to avoid empty columns
                    metrics.Add(new Metric(
                                    ReportResources.BranchCoverage,
                                    ParserBase.CodeCoverageUri,
                                    MetricType.CoveragePercentual,
                                    null));
                }

                var methodMetric = new MethodMetric(fullName, shortName, metrics);
                methodMetric.Line = method.Attribute("line") != null?int.Parse(method.Attribute("line").Value, CultureInfo.InvariantCulture) : default(int?);

                codeFile.AddMethodMetric(methodMetric);
            }
        }
Ejemplo n.º 50
0
 public void TheSignatureOfACodefileShouldContain_TheNameOfTheFile()
 {
     var codefile = new CodeFile(CodeFileName, Code);
     string signature = Signature.For(codefile);
     signature.Should().Contain("{;}");
 }
Ejemplo n.º 51
0
 private void GetCachedNestedIncludeFiles(CodeFile file)
 {
     foreach (var incl in file.IncludeFiles)
     {
         AddIncludeFile(incl.SourceFileName, incl.FileName, incl.SearchFileDir);
     }
 }