public void UsingAliasDeclarationTest()
		{
			string program = "using TESTME=System;\n" +
				"using myAlias=My.Name.Space;\n" +
				"using StringCollection = System.Collections.Generic.List<string>;\n";
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree = parser.Parse(program);
			Assert.IsFalse(parser.HasErrors);
			
			Assert.IsTrue(3 <= syntaxTree.Children.Count());
			
			Assert.IsTrue(syntaxTree.Children.ElementAt(0) is UsingAliasDeclaration);
			UsingAliasDeclaration ud = (UsingAliasDeclaration)syntaxTree.Children.ElementAt(0);
			Assert.AreEqual("TESTME", ud.Alias);
			Assert.AreEqual("System", ud.Import.ToString());
			
			Assert.IsTrue(syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(1) is UsingAliasDeclaration);
			ud = (UsingAliasDeclaration)syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(1);
			Assert.AreEqual("myAlias", ud.Alias);
			Assert.AreEqual("My.Name.Space", ud.Import.ToString());
			
			Assert.IsTrue(syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(2) is UsingAliasDeclaration);
			ud = (UsingAliasDeclaration)syntaxTree.Children.Where (c => c.Role != Roles.NewLine).ElementAt(2);
			Assert.AreEqual("StringCollection", ud.Alias);
			Assert.AreEqual("System.Collections.Generic.List<string>", ud.Import.ToString());
		}
		public void UsingWithAliasing()
		{
			string program = "using global::System;\n" +
				"using myAlias=global::My.Name.Space;\n" +
				"using a::b.c;\n";
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu = parser.Parse(new StringReader(program));
			Assert.IsFalse(parser.HasErrors);
			
			Assert.AreEqual(3, cu.Children.Count());
			
			Assert.IsTrue(cu.Children.ElementAt(0) is UsingDeclaration);
			Assert.IsFalse(cu.Children.ElementAt(0) is UsingAliasDeclaration);
			UsingDeclaration ud = (UsingDeclaration)cu.Children.ElementAt(0);
			Assert.AreEqual("global::System", ud.Namespace);
			
			Assert.IsTrue(cu.Children.ElementAt(1) is UsingAliasDeclaration);
			UsingAliasDeclaration uad = (UsingAliasDeclaration)cu.Children.ElementAt(1);
			Assert.AreEqual("myAlias", uad.Alias);
			Assert.AreEqual("global::My.Name.Space", uad.Import.ToString());
			
			Assert.IsTrue(cu.Children.ElementAt(2) is UsingDeclaration);
			Assert.IsFalse(cu.Children.ElementAt(2) is UsingAliasDeclaration);
			ud = (UsingDeclaration)cu.Children.ElementAt(2);
			Assert.AreEqual("a::b.c", ud.Namespace);
		}
		public void UsingAliasDeclarationTest()
		{
			string program = "using TESTME=System;\n" +
				"using myAlias=My.Name.Space;\n" +
				"using StringCollection = System.Collections.Generic.List<string>;\n";
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu = parser.Parse(new StringReader(program));
			Assert.IsFalse(parser.HasErrors);
			
			Assert.AreEqual(3, cu.Children.Count());
			
			Assert.IsTrue(cu.Children.ElementAt(0) is UsingAliasDeclaration);
			UsingAliasDeclaration ud = (UsingAliasDeclaration)cu.Children.ElementAt(0);
			Assert.AreEqual("TESTME", ud.Alias);
			Assert.AreEqual("System", ud.Import.ToString());
			
			Assert.IsTrue(cu.Children.ElementAt(1) is UsingAliasDeclaration);
			ud = (UsingAliasDeclaration)cu.Children.ElementAt(1);
			Assert.AreEqual("myAlias", ud.Alias);
			Assert.AreEqual("My.Name.Space", ud.Import.ToString());
			
			Assert.IsTrue(cu.Children.ElementAt(2) is UsingAliasDeclaration);
			ud = (UsingAliasDeclaration)cu.Children.ElementAt(2);
			Assert.AreEqual("StringCollection", ud.Alias);
			Assert.AreEqual("System.Collections.Generic.List<string>", ud.Import.ToString());
		}
		public override IEntity ResolveCref(string cref)
		{
			if (cref.Length > 2 && cref[1] == ':') {
				// resolve ID string
				return base.ResolveCref(cref);
			}
			var documentationReference = new CSharpParser().ParseDocumentationReference(cref);
			var csharpContext = context as CSharpTypeResolveContext;
			CSharpResolver resolver;
			if (csharpContext != null) {
				resolver = new CSharpResolver(csharpContext);
			} else {
				resolver = new CSharpResolver(context.Compilation);
			}
			var astResolver = new CSharpAstResolver(resolver, documentationReference);
			var rr = astResolver.Resolve(documentationReference);
			
			MemberResolveResult mrr = rr as MemberResolveResult;
			if (mrr != null)
				return mrr.Member;
			TypeResolveResult trr = rr as TypeResolveResult;
			if (trr != null)
				return trr.Type.GetDefinition();
			return null;
		}
 public void GlobalReferenceExpressionTest()
 {
     CSharpParser parser = new CSharpParser();
     parser.ParseTypeReference(new StringReader("global::System"));
     //Assert.IsTrue(tre.TypeReference.IsGlobal);
     //Assert.AreEqual("System", tre.TypeReference.Type);
     throw new NotImplementedException();
 }
		CSharpParsedFile Parse(string program)
		{
			CompilationUnit cu = new CSharpParser().Parse(new StringReader(program), "test.cs");
			CSharpParsedFile parsedFile = cu.ToTypeSystem();
			project = project.UpdateProjectContent(null, parsedFile);
			compilation = project.CreateCompilation();
			return parsedFile;
		}
		public void WrongUsingTest()
		{
			string program = "using\n";
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu = parser.Parse(new StringReader(program));
			Assert.AreEqual(0, cu.Children.Count());
			Assert.IsTrue(parser.HasErrors);
		}
		public void WrongUsingTest()
		{
			string program = "using\n";
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree = parser.Parse (program);
			Assert.AreEqual(0, syntaxTree.Children.Count());
			Assert.IsTrue(parser.HasErrors);
		}
        public CodeRoot GetCodeRoot(string path)
        {
            if (File.Exists(path) == false)
                return null;

            CSharpParser formatter = new CSharpParser();
            formatter.ParseCode(File.ReadAllText(path));
            return (CodeRoot)formatter.CreatedCodeRoot;
        }
        public void IfIsIdentifiedAsKeyword()
        {
            var expression = "if (System.Console.ReadLine() == \"a\") { System.Console.WriteLine(\"Oh!\"); }";
            var result = new CSharpParser().Parse(expression);

            var ifChunk = result.TextChunks.First(ch => ch.TextValue == "if");

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(Common.CodeType.Keyword, ifChunk.CodeType);
        }
        public void SingleLineCommentsAreDiscovered()
        {
            var expression = "var a = 1 + 3; // comment";
            var result = new CSharpParser().Parse(expression);
            
            var aChunk = result.TextChunks.First(ch => ch.TextValue == "// comment");

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(CodeType.Comment, aChunk.CodeType);
        }
        public void InitializationTypeType()
        {
            var expression = "var a = new System.Int32();";
            var result = new CSharpParser().Parse(expression);

            var intChunk = result.TextChunks.First(ch => ch.TextValue == "Int32");

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(CodeType.Type, intChunk.CodeType);
            Assert.AreEqual("struct System.Int32", intChunk.TooltipValue);
        }
        public void DeclarationGenericTypeType()
        {
            var expression = "System.Tuple<int, int> a = System.Tuple.Create(1, 1);";
            var result = new CSharpParser().Parse(expression);
            
            var intChunk = result.TextChunks.First(ch => ch.TextValue == "Tuple");

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(CodeType.Type, intChunk.CodeType);
            Assert.AreEqual("class System.Tuple", intChunk.TooltipValue);
        }
        public void DeclarationPredefinedTypeType()
        {
            var expression = "int a = 1 + 3;";
            var result = new CSharpParser().Parse(expression);

            var intChunk = result.TextChunks.First(ch => ch.TextValue == "int");

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(CodeType.Keyword, intChunk.CodeType);
            Assert.AreEqual("struct System.Int32", intChunk.TooltipValue);
        }
        public void VarType()
        {
            var expression = "var a = 1 + 3;";
            var result = new CSharpParser().Parse(expression);

            var varChunk = result.TextChunks.First(ch => ch.TextValue == "var");

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(CodeType.Keyword, varChunk.CodeType);
            Assert.AreEqual("struct System.Int32", varChunk.TooltipValue);
        }
        public void SimpleMethodIsMarkedAsMethod()
        {
            var expression = "string.Join(\",\", new[]{\"a\", \"b\"})";
            var result = new CSharpParser().Parse(expression);

            var intChunk = result.TextChunks.First(ch => ch.TextValue == "Join");
            
            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(Common.CodeType.Method, intChunk.CodeType);
            Assert.AreEqual("string string.Join(string separator, params string[] value)", intChunk.TooltipValue);
        }
        public void ItemPropertyOfTupleIsDiscovered()
        {
            var expression = "var t = System.Tuple.Create(1, 2, 3); System.Console.WriteLine(t.Item2);";
            var result = new CSharpParser().Parse(expression);

            var propertyChunk = result.TextChunks.First(ch => ch.TextValue == "Item2");
            
            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(Common.CodeType.Property, propertyChunk.CodeType);
            Assert.AreEqual("System.Tuple<int, int, int>.Item2", propertyChunk.TooltipValue);
        }
        public void OverloadResolutionWorks()
        {
            var expression = "string.Join(\",\", new[]{2, 5})";
            var result = new CSharpParser().Parse(expression);

            var intChunk = result.TextChunks.First(ch => ch.TextValue == "Join");

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(Common.CodeType.Method, intChunk.CodeType);
            Assert.AreEqual("string string.Join<int>(string separator, System.Collections.Generic.IEnumerable<int> values)", intChunk.TooltipValue);
        }
        public void VariableMentionType()
        {
            var expression = "var a = 1 + 3; var b = a;";
            var result = new CSharpParser().Parse(expression);

            var aMention = result.TextChunks.Where(ch => ch.TextValue == "a").Skip(1).First();

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(CodeType.Variable, aMention.CodeType);
            Assert.AreEqual("struct System.Int32", aMention.TooltipValue);
        }
        public void NamespaceInUsingIsRecognized()
        {
            var expression = "using System.Collections.Generic;";
            var result = new CSharpParser().Parse(expression);

            var namespaceChunk = result.TextChunks.First(ch => ch.TextValue == "Generic");
            
            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(Common.CodeType.Namespace, namespaceChunk.CodeType);
            Assert.AreEqual("System.Collections.Generic", namespaceChunk.TooltipValue);
        }
		public void GlobalReferenceExpressionTest()
		{
			CSharpParser parser = new CSharpParser();
			AstType type = parser.ParseTypeReference(new StringReader("global::System"));
			Assert.IsNotNull(
				new MemberType {
					Target = new SimpleType("global"),
					IsDoubleColon = true,
					MemberName = "System"
				}.Match(type)
			);
		}
        public void ClassIsIdentifiedAsKeyword()
        {
            var expression = "public class Implementation {  }";
            var result = new CSharpParser().Parse(expression);

            var publicChunk = result.TextChunks.First(ch => ch.TextValue == "public");
            var classChunk = result.TextChunks.First(ch => ch.TextValue == "class");

            ExpressionHelper.Check(expression, result);
            Assert.AreEqual(Common.CodeType.Keyword, classChunk.CodeType);
            Assert.AreEqual(Common.CodeType.Keyword, publicChunk.CodeType);
        }
Exemple #23
0
		public void ParseAndCheckPositions()
		{
			CSharpParser parser = new CSharpParser();
			foreach (string fileName in fileNames) {
				var currentDocument = new ReadOnlyDocument(File.ReadAllText(fileName));
				SyntaxTree syntaxTree = parser.Parse(currentDocument, fileName);
				if (parser.HasErrors)
					continue;
				ConsistencyChecker.CheckPositionConsistency(syntaxTree, fileName, currentDocument);
				ConsistencyChecker.CheckMissingTokens(syntaxTree, fileName, currentDocument);
			}
		}
		internal static IProjectContent ParseTestCase()
		{
			const string fileName = "TypeSystemTests.TestCase.cs";
			
			CSharpParser parser = new CSharpParser();
			SyntaxTree syntaxTree;
			using (Stream s = typeof(TypeSystemTests).Assembly.GetManifestResourceStream(typeof(TypeSystemTests), fileName)) {
				syntaxTree = parser.Parse(s, fileName);
			}
			
			return CreateContent(syntaxTree.ToTypeSystem());
		}
Exemple #25
0
		public void ParseAndCheckPositions()
		{
			CSharpParser parser = new CSharpParser();
			foreach (string fileName in fileNames) {
				this.currentDocument = new ReadOnlyDocument(File.ReadAllText(fileName));
				CompilationUnit cu = parser.Parse(currentDocument.CreateReader(), fileName);
				if (parser.HasErrors)
					continue;
				this.currentFileName = fileName;
				CheckPositionConsistency(cu);
				CheckMissingTokens(cu);
			}
		}
        public void AssemblyAndModuleAttributesDoNotAppearOnTypes()
        {
            var parser = new CSharpParser();
            var cu = parser.Parse("[assembly: My1][module: My2][My3]class C {} public class My1Attribute : System.Attribute {} public class My2Attribute : System.Attribute {} public class My3Attribute : System.Attribute {}", "File.cs");

            var ts = cu.ToTypeSystem();
            var compilation = new CSharpProjectContent()
                .UpdateProjectContent(null, ts)
                .AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib })
                .CreateCompilation();
            var type = ReflectionHelper.ParseReflectionName("C").Resolve(compilation).GetDefinition();
            Assert.That(type.Attributes.Select(a => a.AttributeType.FullName).ToList(), Is.EqualTo(new[] { "My3Attribute" }));
        }
		public void SetUp()
		{
			pc = new SimpleProjectContent();
			var cu = new CSharpParser().Parse(new StringReader(program));
			parsedFile = new TypeSystemConvertVisitor(pc, "program.cs").Convert(cu);
			pc.UpdateProjectContent(null, parsedFile);
			
			ctx = new CompositeTypeResolveContext(new[] { pc, CecilLoaderTests.Mscorlib });
			
			baseClass = pc.GetTypeDefinition(string.Empty, "Base", 1, StringComparer.Ordinal);
			nestedClass = baseClass.NestedTypes.Single();
			derivedClass = pc.GetTypeDefinition(string.Empty, "Derived", 2, StringComparer.Ordinal);
			systemClass = pc.GetTypeDefinition("NS", "System", 0, StringComparer.Ordinal);
		}
Exemple #28
0
		public void GenerateTypeSystem()
		{
			SimpleProjectContent pc = new SimpleProjectContent();
			CSharpParser parser = new CSharpParser();
			parser.GenerateTypeSystemMode = true;
			foreach (string fileName in fileNames) {
				CompilationUnit cu;
				using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
					cu = parser.Parse(fs);
				}
				TypeSystemConvertVisitor cv = new TypeSystemConvertVisitor(pc, fileName);
				pc.UpdateProjectContent(null, cv.Convert(cu));
			}
		}
		internal static IProjectContent ParseTestCase()
		{
			const string fileName = "TypeSystemTests.TestCase.cs";
			
			CSharpParser parser = new CSharpParser();
			CompilationUnit cu;
			using (Stream s = typeof(TypeSystemTests).Assembly.GetManifestResourceStream(typeof(TypeSystemTests), fileName)) {
				cu = parser.Parse(s, fileName);
			}
			
			var parsedFile = cu.ToTypeSystem();
			return new CSharpProjectContent()
				.UpdateProjectContent(null, parsedFile)
				.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib })
				.SetAssemblyName(typeof(TypeSystemTests).Assembly.GetName().Name);
		}
		public void TestV2 ()
		{
			var input = @"class Foo
{
	void Bar (object o)
	{
		Foo foo = (Foo)o;
	}
}";

			TestRefactoringContext context;
			CSharpParser parser = new CSharpParser();
			parser.CompilerSettings.LanguageVersion = new Version(2, 0, 0);
			var issues = GetIssues (new SuggestUseVarKeywordEvidentIssue (), input, out context, false, parser);
			Assert.AreEqual (0, issues.Count);
		}
Exemple #31
0
 /// <summary>
 /// Tries to parses specified data string into syntactic item.
 /// </summary>
 protected override bool Parse(SyntacticItem item, string data)
 {
     return(CSharpParser.TryParse(item, data));
 }
 public static TestRefactoringContext Create(string content, bool expectErrors = false, CSharpParser parser = null)
 {
     return(Create(new List <string>()
     {
         content
     }, 0, expectErrors, parser));
 }
Exemple #33
0
        //
        // Processes "see" or "seealso" elements from cref attribute.
        //
        void HandleXrefCommon(MemberCore mc, DeclSpace ds, XmlElement xref)
        {
            string cref = xref.GetAttribute("cref");

            // when, XmlReader, "if (cref == null)"
            if (!xref.HasAttribute("cref"))
            {
                return;
            }

            // Nothing to be resolved the reference is marked explicitly
            if (cref.Length > 2 && cref [1] == ':')
            {
                return;
            }

            // Additional symbols for < and > are allowed for easier XML typing
            cref = cref.Replace('{', '<').Replace('}', '>');

            var encoding = module.Compiler.Settings.Encoding;
            var s        = new MemoryStream(encoding.GetBytes(cref));
            SeekableStreamReader seekable = new SeekableStreamReader(s, encoding);

            var source_file = new CompilationSourceFile("{documentation}", "", 1);
            var doc_module  = new ModuleContainer(module.Compiler);

            doc_module.DocumentationBuilder = this;
            source_file.NamespaceContainer  = new NamespaceContainer(null, doc_module, null, source_file);

            Report parse_report = new Report(new NullReportPrinter());
            var    parser       = new CSharpParser(seekable, source_file, parse_report);

            ParsedParameters          = null;
            ParsedName                = null;
            ParsedBuiltinType         = null;
            ParsedOperator            = null;
            parser.Lexer.putback_char = Tokenizer.DocumentationXref;
            parser.Lexer.parsing_generic_declaration_doc = true;
            parser.parse();
            if (parse_report.Errors > 0)
            {
                Report.Warning(1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
                               mc.GetSignatureForError(), cref);

                xref.SetAttribute("cref", "!:" + cref);
                return;
            }

            MemberSpec          member;
            string              prefix = null;
            FullNamedExpression fne    = null;

            //
            // Try built-in type first because we are using ParsedName as identifier of
            // member names on built-in types
            //
            if (ParsedBuiltinType != null && (ParsedParameters == null || ParsedName != null))
            {
                member = ParsedBuiltinType.Type;
            }
            else
            {
                member = null;
            }

            if (ParsedName != null || ParsedOperator.HasValue)
            {
                TypeSpec type        = null;
                string   member_name = null;

                if (member == null)
                {
                    if (ParsedOperator.HasValue)
                    {
                        type = mc.CurrentType;
                    }
                    else if (ParsedName.Left != null)
                    {
                        fne = ResolveMemberName(mc, ParsedName.Left);
                        if (fne != null)
                        {
                            var ns = fne as Namespace;
                            if (ns != null)
                            {
                                fne = ns.Lookup(mc, ParsedName.Name, ParsedName.Arity, Location.Null);
                                if (fne != null)
                                {
                                    member = fne.Type;
                                }
                            }
                            else
                            {
                                type = fne.Type;
                            }
                        }
                    }
                    else
                    {
                        fne = ResolveMemberName(mc, ParsedName);
                        if (fne == null)
                        {
                            type = mc.CurrentType;
                        }
                        else if (ParsedParameters == null)
                        {
                            member = fne.Type;
                        }
                        else if (fne.Type.MemberDefinition == mc.CurrentType.MemberDefinition)
                        {
                            member_name = Constructor.ConstructorName;
                            type        = fne.Type;
                        }
                    }
                }
                else
                {
                    type   = (TypeSpec)member;
                    member = null;
                }

                if (ParsedParameters != null)
                {
                    foreach (var pp in ParsedParameters)
                    {
                        pp.Resolve(mc);
                    }
                }

                if (type != null)
                {
                    if (member_name == null)
                    {
                        member_name = ParsedOperator.HasValue ?
                                      Operator.GetMetadataName(ParsedOperator.Value) : ParsedName.Name;
                    }

                    int parsed_param_count;
                    if (ParsedOperator == Operator.OpType.Explicit || ParsedOperator == Operator.OpType.Implicit)
                    {
                        parsed_param_count = ParsedParameters.Count - 1;
                    }
                    else if (ParsedParameters != null)
                    {
                        parsed_param_count = ParsedParameters.Count;
                    }
                    else
                    {
                        parsed_param_count = 0;
                    }

                    int parameters_match = -1;
                    do
                    {
                        var members = MemberCache.FindMembers(type, member_name, true);
                        if (members != null)
                        {
                            foreach (var m in members)
                            {
                                if (ParsedName != null && m.Arity != ParsedName.Arity)
                                {
                                    continue;
                                }

                                if (ParsedParameters != null)
                                {
                                    IParametersMember pm = m as IParametersMember;
                                    if (pm == null)
                                    {
                                        continue;
                                    }

                                    if (m.Kind == MemberKind.Operator && !ParsedOperator.HasValue)
                                    {
                                        continue;
                                    }

                                    int i;
                                    for (i = 0; i < parsed_param_count; ++i)
                                    {
                                        var pparam = ParsedParameters[i];

                                        if (i >= pm.Parameters.Count || pparam == null ||
                                            pparam.TypeSpec != pm.Parameters.Types[i] ||
                                            (pparam.Modifier & Parameter.Modifier.SignatureMask) != (pm.Parameters.FixedParameters[i].ModFlags & Parameter.Modifier.SignatureMask))
                                        {
                                            if (i > parameters_match)
                                            {
                                                parameters_match = i;
                                            }

                                            i = -1;
                                            break;
                                        }
                                    }

                                    if (i < 0)
                                    {
                                        continue;
                                    }

                                    if (ParsedOperator == Operator.OpType.Explicit || ParsedOperator == Operator.OpType.Implicit)
                                    {
                                        if (pm.MemberType != ParsedParameters[parsed_param_count].TypeSpec)
                                        {
                                            parameters_match = parsed_param_count + 1;
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        if (parsed_param_count != pm.Parameters.Count)
                                        {
                                            continue;
                                        }
                                    }
                                }

                                if (member != null)
                                {
                                    Report.Warning(419, 3, mc.Location,
                                                   "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
                                                   cref, member.GetSignatureForError(), m.GetSignatureForError());

                                    break;
                                }

                                member = m;
                            }
                        }

                        // Continue with parent type for nested types
                        if (member == null)
                        {
                            type = type.DeclaringType;
                        }
                        else
                        {
                            type = null;
                        }
                    } while (type != null);

                    if (member == null && parameters_match >= 0)
                    {
                        for (int i = parameters_match; i < parsed_param_count; ++i)
                        {
                            Report.Warning(1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
                                           (i + 1).ToString(), cref);
                        }

                        if (parameters_match == parsed_param_count + 1)
                        {
                            Report.Warning(1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
                        }
                    }
                }
            }

            if (member == null)
            {
                Report.Warning(1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved",
                               mc.GetSignatureForError(), cref);
                cref = "!:" + cref;
            }
            else if (member == InternalType.Namespace)
            {
                cref = "N:" + fne.GetSignatureForError();
            }
            else
            {
                prefix = GetMemberDocHead(member);
                cref   = prefix + member.GetSignatureForDocumentation();
            }

            xref.SetAttribute("cref", cref);
        }
Exemple #34
0
        public void TestMaxInstances2()
        {
            var test = @"
using System;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class E1 : Event {
        public E1() : base(1, -1) { }
    }

    class E2 : Event {
        public E2() : base(1, -1) { }
    }

    class E3 : Event {
        public E3() : base(-1, -1) { }
    }

    class E4 : Event { }

    class Unit : Event {
        public Unit() : base(1, -1) { }
    }

    class RealMachine : Machine
    {
        MachineId GhostMachine;

        [Start]
        [OnEntry(nameof(EntryInit))]
        [OnEventPushState(typeof(Unit), typeof(S1))]
        [OnEventGotoState(typeof(E4), typeof(S2))]
        [OnEventDoAction(typeof(E2), nameof(Action1))]
        class Init : MachineState { }

        void EntryInit()
        {
            GhostMachine = this.CreateMachine(typeof(GhostMachine), this.Id);
            this.Raise(new Unit());
        }

        [OnEntry(nameof(EntryS1))]
        class S1 : MachineState { }

        void EntryS1()
        {
            this.Send(GhostMachine, new E1());
        }

        [OnEntry(nameof(EntryS2))]
        [OnEventGotoState(typeof(Unit), typeof(S3))]
        class S2 : MachineState { }

        void EntryS2()
        {
            this.Raise(new Unit());
        }

        [OnEventGotoState(typeof(E4), typeof(S3))]
        class S3 : MachineState { }

        void Action1()
        {
            this.Assert((int)this.Payload == 100);
            this.Send(GhostMachine, new E3());
            this.Send(GhostMachine, new E3());
        }
    }

    class GhostMachine : Machine
    {
        MachineId RealMachine;

        [Start]
        [OnEntry(nameof(EntryInit))]
        [OnEventGotoState(typeof(Unit), typeof(GhostInit))]
        class Init : MachineState { }

        void EntryInit()
        {
            RealMachine = this.Payload as MachineId;
            this.Raise(new Unit());
        }

        [OnEventGotoState(typeof(E1), typeof(S1))]
        class GhostInit : MachineState { }

        [OnEntry(nameof(EntryS1))]
        [OnEventGotoState(typeof(E3), typeof(S2))]
        [IgnoreEvents(typeof(E1))]
        class S1 : MachineState { }

        void EntryS1()
        {
            this.Send(RealMachine, new E2(), 100);
        }

        [OnEntry(nameof(EntryS2))]
        [OnEventGotoState(typeof(E3), typeof(GhostInit))]
        class S2 : MachineState { }

        void EntryS2()
        {
            this.Send(RealMachine, new E4());
            this.Send(RealMachine, new E4());
            this.Send(RealMachine, new E4());
        }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(RealMachine));
        }
    }
}";

            var parser = new CSharpParser(new PSharpProject(),
                                          SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            var sctConfig = new DynamicAnalysisConfiguration();

            sctConfig.SuppressTrace      = true;
            sctConfig.Verbose            = 2;
            sctConfig.SchedulingStrategy = SchedulingStrategy.DFS;

            var assembly  = base.GetAssembly(program.GetSyntaxTree());
            var context   = AnalysisContext.Create(sctConfig, assembly);
            var sctEngine = SCTEngine.Create(context).Run();

            Assert.AreEqual(0, sctEngine.NumOfFoundBugs);
        }
Exemple #35
0
        public void TestSimpleAsyncAwaitFail()
        {
            var test = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class Unit : Event { }

    internal class TaskCreator : Machine
    {
        int Value;

		[Start]
        [OnEntry(nameof(InitOnEntry))]
        [OnEventGotoState(typeof(Unit), typeof(Active))]
        class Init : MachineState { }

		void InitOnEntry()
        {
            this.Value = 0;
            this.Raise(new Unit());
        }

        [OnEntry(nameof(ActiveOnEntry))]
        class Active : MachineState { }

        void ActiveOnEntry()
        {
            Process();
            this.Assert(this.Value < 3, ""Value is '{0}' (expected less than '3')."", this.Value);
        }

        async void Process()
        {
            Task t = Increment();
            this.Value++;
            await t;
            this.Value++;
        }

        Task Increment()
        {
            Task t = new Task(() => {
                this.Value++;
            });

            t.Start();
            return t;
        }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(TaskCreator));
        }
    }
}";

            var parser = new CSharpParser(new PSharpProject(),
                                          SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            var sctConfig = new DynamicAnalysisConfiguration();

            sctConfig.SuppressTrace                   = true;
            sctConfig.Verbose                         = 2;
            sctConfig.SchedulingIterations            = 2;
            sctConfig.SchedulingStrategy              = SchedulingStrategy.DFS;
            sctConfig.ScheduleIntraMachineConcurrency = true;

            var assembly  = base.GetAssembly(program.GetSyntaxTree());
            var context   = AnalysisContext.Create(sctConfig, assembly);
            var sctEngine = SCTEngine.Create(context).Run();

            var bugReport = "Value is '3' (expected less than '3').";

            Assert.AreEqual(bugReport, sctEngine.BugReport);
        }
Exemple #36
0
        public static VariableInitializer GetVariableDeclarationForLinqQuery(string query, bool requiresSelectNewAnonymousType)
        {
            try
            {
                var parser = new CSharpParser();
                var block  = parser.ParseStatements(ToQueryStatement(query)).ToList();

                if (block.Count == 0 || parser.HasErrors)
                {
                    var errs = string.Join(Environment.NewLine, parser.Errors.Select(x => x.Region + ": " + x.ErrorType + " - " + x.Message));
                    throw new InvalidOperationException("Could not understand query: \r\n" + errs);
                }

                var declaration = block[0] as VariableDeclarationStatement;
                if (declaration == null)
                {
                    throw new InvalidOperationException("Only local variable declaration are allowed");
                }

                if (declaration.Variables.Count != 1)
                {
                    throw new InvalidOperationException("Only one variable declaration is allowed");
                }

                var variable = declaration.Variables.First();

                if (variable.Initializer == null)
                {
                    throw new InvalidOperationException("Variable declaration must have an initializer");
                }

                var queryExpression = (variable.Initializer as QueryExpression);
                if (queryExpression == null)
                {
                    throw new InvalidOperationException("Variable initializer must be a query expression");
                }

                var selectClause = queryExpression.Clauses.OfType <QuerySelectClause>().FirstOrDefault();
                if (selectClause == null)
                {
                    throw new InvalidOperationException("Variable initializer must be a select query expression");
                }

                var createExpression = GetAnonymousCreateExpression(selectClause.Expression) as AnonymousTypeCreateExpression;
                if ((createExpression == null) && requiresSelectNewAnonymousType)
                {
                    throw new InvalidOperationException(
                              "Variable initializer must be a select query expression returning an anonymous object");
                }

                variable.AcceptVisitor(new TransformNullCoalescingOperatorTransformer(), null);
                variable.AcceptVisitor(new DynamicExtensionMethodsTranslator(), null);
                variable.AcceptVisitor(new TransformDynamicLambdaExpressions(), null);
                variable.AcceptVisitor(new TransformDynamicInvocationExpressions(), null);
                variable.AcceptVisitor(new TransformObsoleteMethods(), null);
                return(variable);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Could not understand query: " + e.Message, e);
            }
        }
        public void TestExitAtExplicitPop()
        {
            var test = @"
using System;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class E : Event { }

    class Real1 : Machine
    {
        bool test = false;

        [Start]
        [OnEntry(nameof(EntryInit))]
        [OnExit(nameof(ExitInit))]
        [OnEventPushState(typeof(E), typeof(Call))]
        class Init : MachineState { }

        void EntryInit()
        {
            this.Raise(new E());
        }

        void ExitInit() { }

        [OnEntry(nameof(EntryCall))]
        [OnExit(nameof(ExitCall))]
        class Call : MachineState { }

        void EntryCall()
        {
            this.Pop();
        }

        void ExitCall()
        {
            this.Assert(false);
        }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(Real1));
        }
    }
}";

            var parser = new CSharpParser(new PSharpProject(),
                                          SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            var sctConfig = new DynamicAnalysisConfiguration();

            sctConfig.SuppressTrace = true;
            sctConfig.Verbose       = 2;

            var assembly  = base.GetAssembly(program.GetSyntaxTree());
            var context   = AnalysisContext.Create(sctConfig, assembly);
            var sctEngine = SCTEngine.Create(context).Run();

            Assert.AreEqual(1, sctEngine.NumOfFoundBugs);
        }
        public static TestRefactoringContext Create(List <string> contents, int mainIndex, bool expectErrors = false, CSharpParser parser = null)
        {
            List <int>                  indexes         = new List <int>();
            List <int>                  selectionStarts = new List <int>();
            List <int>                  selectionEnds   = new List <int>();
            List <IDocument>            documents       = new List <IDocument>();
            List <CSharpUnresolvedFile> unresolvedFiles = new List <CSharpUnresolvedFile>();
            List <SyntaxTree>           units           = new List <SyntaxTree>();

            for (int i = 0; i < contents.Count; i++)
            {
                string content = contents[i];
                int    idx     = content.IndexOf("$");
                if (idx >= 0)
                {
                    content = content.Substring(0, idx) + content.Substring(idx + 1);
                }
                int idx1           = content.IndexOf("<-");
                int idx2           = content.IndexOf("->");
                int selectionStart = 0;
                int selectionEnd   = 0;
                if (0 <= idx1 && idx1 < idx2)
                {
                    content        = content.Substring(0, idx2) + content.Substring(idx2 + 2);
                    content        = content.Substring(0, idx1) + content.Substring(idx1 + 2);
                    selectionStart = idx1;
                    selectionEnd   = idx2 - 2;
                    idx            = selectionEnd;
                }
                indexes.Add(idx);
                selectionStarts.Add(selectionStart);
                selectionEnds.Add(selectionEnd);
                var doc = new StringBuilderDocument(content);
                if (parser == null)
                {
                    parser = new CSharpParser();
                }
                var unit = parser.Parse(content, "program_" + i + ".cs");
                if (!expectErrors)
                {
                    if (parser.HasErrors)
                    {
                        Console.WriteLine(content);
                        Console.WriteLine("----");
                    }
                    foreach (var error in parser.ErrorsAndWarnings)
                    {
                        Console.WriteLine(error.Message);
                    }
                    Assert.IsFalse(parser.HasErrors, "The file " + i + " contains unexpected parsing errors.");
                }
                else
                {
                    Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file " + i + "doesn't contain any.");
                }
                unit.Freeze();
                CSharpUnresolvedFile unresolvedFile = unit.ToTypeSystem();
                units.Add(unit);
                documents.Add(doc);
                unresolvedFiles.Add(unresolvedFile);
            }

            IProjectContent pc = new CSharpProjectContent();

            pc = pc.AddOrUpdateFiles(unresolvedFiles);
            pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

            var compilation = pc.CreateCompilation();
            List <TestRefactoringContext> contexts = new List <TestRefactoringContext>();

            for (int documentIndex = 0; documentIndex < documents.Count; ++documentIndex)
            {
                var          doc      = documents [documentIndex];
                var          resolver = new CSharpAstResolver(compilation, units[documentIndex], unresolvedFiles[documentIndex]);
                TextLocation location = TextLocation.Empty;
                if (indexes[documentIndex] >= 0)
                {
                    location = doc.GetLocation(indexes[documentIndex]);
                }
                var context = new TestRefactoringContext(doc, location, resolver)
                {
                    selectionStart   = selectionStarts[documentIndex],
                    selectionEnd     = selectionEnds[documentIndex],
                    projectContexts  = contexts,
                    version          = parser.CompilerSettings.LanguageVersion,
                    defaultNamespace = "Test"
                };

                contexts.Add(context);
            }

            return(contexts [mainIndex]);
        }
Exemple #39
0
        // ========================================================================
        // Properties

        #region === Properties


        #endregion

        #endregion

        // ========================================================================
        // Methods

        #region === Methods

        /// <summary>
        /// The main entry point of this class. Imports the C# file which is given
        /// as the parameter.
        /// </summary>
        /// <param name="fileName">The file path of C# source code to import.</param>
        /// <returns><c>True</c>, if the import was successful.</returns>
        public bool ImportSourceCode(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                MessageBox.Show(Strings.Error_NoCSharpFile, Strings.Error_MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            try
            {
                diagram.Name            = Path.GetFileName(fileName);
                diagram.RedrawSuspended = true;

                CSharpParser parser = new CSharpParser();

                // Open the C# source file to read
                using (StreamReader sr = new StreamReader(fileName))
                {
                    // Parse the C# file
                    SyntaxTree syntaxTree = parser.Parse(sr, fileName);

                    if (parser.HasErrors == false)
                    {
                        foreach (TypeDeclaration tp in syntaxTree.Descendants.OfType <TypeDeclaration>())
                        {
                            switch (tp.ClassType)
                            {
                            case ICSharpCode.NRefactory.CSharp.ClassType.Class:
                                AddClass(tp);
                                continue;

                            case ICSharpCode.NRefactory.CSharp.ClassType.Struct:
                                AddStrct(tp);
                                continue;

                            case ICSharpCode.NRefactory.CSharp.ClassType.Interface:
                                AddInterface(tp);
                                continue;

                            case ICSharpCode.NRefactory.CSharp.ClassType.Enum:
                                AddEnum(tp);
                                continue;

                            default:
                                continue;
                            }
                        }

                        foreach (DelegateDeclaration dd in syntaxTree.Descendants.OfType <DelegateDeclaration>())
                        {
                            AddDelegate(dd);
                        }

                        Common.ArrangeTypes(diagram);

                        /*
                         * RelationshipCreator relationshipCreator = new RelationshipCreator();
                         *
                         * NRRelationships nrRelationships = relationshipCreator.CreateRelationships(nrAssembly, settings.CreateNestings,
                         *                                                                          settings.CreateGeneralizations,
                         *                                                                          settings.CreateRealizations,
                         *                                                                          settings.CreateAssociations);
                         * AddRelationships();
                         */
                    }
                    else
                    {
                        MessageBox.Show(String.Format(Strings.Error_CSharpParsing, fileName, parser.Errors.Select(err => err.Message)), Strings.Error_MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format(Strings.Error_GeneralException, ex), Strings.Error_MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            finally
            {
                diagram.RedrawSuspended = false;
            }

            return(true);
        }
Exemple #40
0
    public static void Main(string[] args)
    {
        try {
            string[] files = Directory.GetFiles(".", "*.cs");
            foreach (string file in files)
            {
                Console.WriteLine(file + "---------------------------------------");

                //Read the file
                string text = File.ReadAllText(file);

                //Create the lexer
                CSharpLexer lexer = new CSharpLexer(new AntlrInputStream(text));

                var           tokens        = lexer.GetAllTokens();
                List <IToken> codeTokens    = new List <IToken>();
                List <IToken> commentTokens = new List <IToken>();

                var directiveTokens      = new List <IToken>();
                var directiveTokenSource = new ListTokenSource(directiveTokens);
                var directiveTokenStream = new CommonTokenStream(directiveTokenSource, CSharpLexer.DIRECTIVE);
                CSharpPreprocessorParser preprocessorParser = new CSharpPreprocessorParser(directiveTokenStream);

                int  index           = 0;
                bool compiliedTokens = true;
                while (index < tokens.Count)
                {
                    var token = tokens[index];
                    if (token.Type == CSharpLexer.SHARP)
                    {
                        directiveTokens.Clear();
                        int directiveTokenIndex = index + 1;
                        // Collect all preprocessor directive tokens.
                        while (directiveTokenIndex < tokens.Count &&
                               tokens[directiveTokenIndex].Type != CSharpLexer.Eof &&
                               tokens[directiveTokenIndex].Type != CSharpLexer.DIRECTIVE_NEW_LINE &&
                               tokens[directiveTokenIndex].Type != CSharpLexer.SHARP)
                        {
                            if (tokens[directiveTokenIndex].Channel == CSharpLexer.COMMENTS_CHANNEL)
                            {
                                commentTokens.Add(tokens[directiveTokenIndex]);
                            }
                            else if (tokens[directiveTokenIndex].Channel != Lexer.Hidden)
                            {
                                //Console.WriteLine(allTokens[directiveTokenIndex] + "  HOLA");
                                directiveTokens.Add(tokens[directiveTokenIndex]);
                            }
                            directiveTokenIndex++;
                        }

                        directiveTokenSource           = new ListTokenSource(directiveTokens);
                        directiveTokenStream           = new CommonTokenStream(directiveTokenSource, CSharpLexer.DIRECTIVE);
                        preprocessorParser.TokenStream = directiveTokenStream;
                        //preprocessorParser.SetInputStream(directiveTokenStream);
                        preprocessorParser.Reset();
                        // Parse condition in preprocessor directive (based on CSharpPreprocessorParser.g4 grammar).
                        CSharpPreprocessorParser.Preprocessor_directiveContext directive = preprocessorParser.preprocessor_directive();
                        // if true than next code is valid and not ignored.
                        compiliedTokens = directive.value;

                        String directiveStr = tokens[index + 1].Text.Trim();
                        if ("line".Equals(directiveStr) || "error".Equals(directiveStr) || "warning".Equals(directiveStr) || "define".Equals(directiveStr) || "endregion".Equals(directiveStr) || "endif".Equals(directiveStr) || "pragma".Equals(directiveStr))
                        {
                            //Console.WriteLine(directiveStr);
                            compiliedTokens = true;
                        }
                        String conditionalSymbol = null;
                        if ("define".Equals(tokens[index + 1].Text))
                        {
                            // add to the conditional symbols
                            conditionalSymbol = tokens[index + 2].Text;
                            preprocessorParser.ConditionalSymbols.Add(conditionalSymbol);
                        }
                        if ("undef".Equals(tokens[index + 1].Text))
                        {
                            conditionalSymbol = tokens[index + 2].Text;
                            preprocessorParser.ConditionalSymbols.Remove(conditionalSymbol);
                        }

                        //This code deletes the directive tokens from the input so that they don't interfere with the parsing process
                        // In all of the cases, we have to remove at least two positions of the tokens array
                        tokens.RemoveAt(directiveTokenIndex - 1);
                        tokens.RemoveAt(directiveTokenIndex - 2);

                        if ("pragma".Equals(directiveStr) || "warning".Equals(directiveStr) || "region".Equals(directiveStr) || "error".Equals(directiveStr))
                        {
                            // Remove three positions before
                            tokens.RemoveAt(directiveTokenIndex - 3);
                            directiveTokenIndex--;
                        }
                        else if ("define".Equals(directiveStr) || "undef".Equals(directiveStr) || "if".Equals(directiveStr) || "elif".Equals(directiveStr) || "line".Equals(directiveStr))
                        {
                            // Remove four positions before
                            tokens.RemoveAt(directiveTokenIndex - 3);
                            tokens.RemoveAt(directiveTokenIndex - 4);
                            directiveTokenIndex -= 2;
                        }
                        directiveTokenIndex -= 2;
                        index = directiveTokenIndex - 1;
                    }
                    else if (token.Channel == CSharpLexer.COMMENTS_CHANNEL)
                    {
                        commentTokens.Add(token); // Colect comment tokens (if required).
                    }
                    else if (token.Channel != Lexer.Hidden && token.Type != CSharpLexer.DIRECTIVE_NEW_LINE && compiliedTokens)
                    {
                        codeTokens.Add(token); // Collect code tokens.
                    }
                    index++;
                }

                // At second stage tokens parsed in usual way.
                var          codeTokenSource = new ListTokenSource(tokens);
                var          codeTokenStream = new CommonTokenStream(codeTokenSource);
                CSharpParser parser          = new CSharpParser(codeTokenStream);

                ////Create the token stream
                //CommonTokenStream tokens = new CommonTokenStream(lexer);
                //CSharpParser parser = new CSharpParser(tokens);
                IParseTree tree = parser.compilation_unit();

                ////Walk the tree
                ParseTreeWalker walker = new ParseTreeWalker();
                walker.Walk(new ProgressPrinter(), tree);
            }
        }
        catch (Exception e) {
            Console.WriteLine("Error (Program.cs): " + e);
        }
    }
Exemple #41
0
        public void TestPushItself()
        {
            var test = @"
using System;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class E1 : Event {
        public E1() : base(1, -1) { }
    }

    class E2 : Event {
        public E2() : base(1, -1) { }
    }

    class Real1 : Machine
    {
        [Start]
        [OnEntry(nameof(EntryInit))]
        [OnExit(nameof(ExitInit))]
        [OnEventGotoState(typeof(E1), typeof(Init))]
        [OnEventPushState(typeof(E2), typeof(Init))]
        class Init : MachineState { }

        void EntryInit()
        {
            this.Send(this.Id, new E1());
        }

        void ExitInit()
        {
            this.Send(this.Id, new E2());
        }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(Real1));
        }
    }
}";

            var parser = new CSharpParser(new PSharpProject(),
                                          SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            var sctConfig = new DynamicAnalysisConfiguration();

            sctConfig.SuppressTrace = true;
            sctConfig.Verbose       = 2;

            var assembly  = base.GetAssembly(program.GetSyntaxTree());
            var context   = AnalysisContext.Create(sctConfig, assembly);
            var sctEngine = SCTEngine.Create(context).Run();

            Assert.AreEqual(1, sctEngine.NumOfFoundBugs);
        }
        public void TestNewMonitor2()
        {
            var test = @"
using System;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class E2 : Event {
        public E2() : base(1, -1) { }
    }

    class Real1 : Machine
    {
        bool test = false;

        [Start]
        [OnEntry(nameof(EntryInit))]
        class Init : MachineState { }

        void EntryInit()
        {
            this.CreateMonitor(typeof(M), true);
            this.Monitor<M>(null, test);
        }
    }

    class M : Monitor
    {
        [Start]
        [OnEntry(nameof(EntryX))]
        class X : MonitorState { }

        void EntryX()
        {
            //this.Assert((bool)this.Payload == true); // passes
        }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(Real1));
        }
    }
}";

            var parser  = new CSharpParser(new PSharpProject(), SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            Configuration.SuppressTrace      = true;
            Configuration.Verbose            = 2;
            Configuration.SchedulingStrategy = "dfs";

            var assembly = base.GetAssembly(program.GetSyntaxTree());

            AnalysisContext.Create(assembly);

            SCTEngine.Setup();
            SCTEngine.Run();

            Assert.AreEqual(1, SCTEngine.NumOfFoundBugs);
        }
Exemple #43
0
        public void Parse(SeekableStreamReader reader, CompilationUnit file, ModuleContainer module)
        {
            CSharpParser parser = new CSharpParser(reader, file, module);

            parser.parse();
        }
Exemple #44
0
        public static void Main(string[] args)
        {
            /*
             *          if (args.Length == 0) {
             *                  Console.WriteLine("Please specify the path to a .sln file on the command line");
             *
             *                  Console.Write("Press any key to continue . . . ");
             *                  Console.ReadKey(true);
             *                  return;
             *          }
             *
             */



            List <string> list = new List <string>();

            Solution solution = new Solution("/Users/luozhuocheng/IOS/HotFixForUnity/AddMethodToolMac/Console/AddMethod/AddMethod.sln");

            //Solution solution = new Solution(args[0]);


//          foreach (var file in solution.AllFiles) {
//              var astResolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile);
//              foreach (var invocation in file.SyntaxTree.Descendants.OfType<InvocationExpression>()) {
//                  // Retrieve semantics for the invocation
//                  var rr = astResolver.Resolve(invocation) as InvocationResolveResult;
//                  if (rr == null) {
//                      // Not an invocation resolve result - e.g. could be a UnknownMemberResolveResult instead
//                      continue;
//                  }
//                  if (rr.Member.FullName != "System.String.IndexOf") {
//                      // Invocation isn't a string.IndexOf call
//                      continue;
//                  }
//                  if (rr.Member.Parameters.First().Type.FullName != "System.String") {
//                      // Ignore the overload that accepts a char, as that doesn't take a StringComparison.
//                      // (looking for a char always performs the expected ordinal comparison)
//                      continue;
//                  }
//                  if (rr.Member.Parameters.Last().Type.FullName == "System.StringComparison") {
//                      // Already using the overload that specifies a StringComparison
//                      continue;
//                  }
//                  Console.WriteLine(invocation.GetRegion() + ": " + invocation.GetText());
//                  file.IndexOfInvocations.Add(invocation);
//              }
//          }
//          Console.WriteLine("Found {0} places to refactor in {1} files.",
//                            solution.AllFiles.Sum(f => f.IndexOfInvocations.Count),
//                            solution.AllFiles.Count(f => f.IndexOfInvocations.Count > 0));


            Console.Write("Apply refactorings? ");
            //string answer = Console.ReadLine();
            //if ("yes".Equals(answer, StringComparison.OrdinalIgnoreCase) || "y".Equals(answer, StringComparison.OrdinalIgnoreCase))
            {
                foreach (var file in solution.AllFiles)
                {
//                  if (file.IndexOfInvocations.Count == 0)
//                      continue;
                    // DocumentScript expects the the AST to stay unmodified (so that it fits
                    // to the document state at the time of the DocumentScript constructor call),
                    // so we call Freeze() to prevent accidental modifications (e.g. forgetting a Clone() call).
                    file.SyntaxTree.Freeze();
                    // AST resolver used to find context for System.StringComparison generation
                    var compilation = file.Project.Compilation;
                    var astResolver = new CSharpAstResolver(compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile);

                    // Create a document containing the file content:
                    var document          = new StringBuilderDocument(file.OriginalText);
                    var formattingOptions = FormattingOptionsFactory.CreateAllman();
                    var options           = new TextEditorOptions();
//                  using (var script = new DocumentScript(document, formattingOptions, options)) {
//                      foreach (InvocationExpression expr in file.IndexOfInvocations) {
//                          // Generate a reference to System.StringComparison in this context:
//                          var astBuilder = new TypeSystemAstBuilder(astResolver.GetResolverStateBefore(expr));
//                          IType stringComparison = compilation.FindType(typeof(StringComparison));
//                          AstType stringComparisonAst = astBuilder.ConvertType(stringComparison);
//
//                          // Alternative 1: clone a portion of the AST and modify it
//                          var copy = (InvocationExpression)expr.Clone();
//                          copy.Arguments.Add(stringComparisonAst.Member("Ordinal"));
//                          script.Replace(expr, copy);
//
// //							// Alternative 2: perform direct text insertion
// //							int offset = script.GetCurrentOffset(expr.RParToken.StartLocation);
// //							script.InsertText(offset, ", " + stringComparisonAst.GetText() +  ".Ordinal");
//                      }
//                  }
                    using (var script = new DocumentScript(document, formattingOptions, options))
                    {
                        CSharpParser parser = new CSharpParser();
                        //SyntaxTree syntaxTree = parser.Parse(code, srcFilePath);
                        SyntaxTree syntaxTree = file.SyntaxTree;
                        foreach (var classDec in syntaxTree.Descendants.OfType <TypeDeclaration>())
                        {
                            if (classDec.ClassType == ClassType.Class || classDec.ClassType == ClassType.Struct)
                            {
                                var className = classDec.Name;
                                foreach (var method in classDec.Children.OfType <MethodDeclaration>())
                                {
                                    var returnType = method.ReturnType.ToString();
                                    if (returnType.Contains("IEnumerator") || returnType.Contains("IEnumerable"))  // 暂不支持yield!
                                    {
                                        continue;
                                    }

                                    Console.WriteLine("className:" + className + "   method:" + method.Name);
                                    AstNodeCollection <ParameterDeclaration> paramlist = method.Parameters;



                                    //
                                    //                                     if (FixUtil.Instance.NeedFix("test001.SetName"))
                                    //                                     {
                                    //                                         FixUtil.Instance.Fix("test001.SetName", this, name);
                                    //                                         return;
                                    //                                     }

                                    //list.Clear();
                                    //list.Add(",this");
                                    string str = ", this";
                                    foreach (ParameterDeclaration param in paramlist)
                                    {
                                        Console.WriteLine("param    " + param.Name);
                                        str += string.Format(", {0}", param.Name);
                                    }


                                    // 。。。。这里找到了方法体! 开始进行插入!
                                    // int offset = script.GetCurrentOffset(expr.RParToken.StartLocation);
                                    int offset = script.GetCurrentOffset(method.Body.LBraceToken.StartLocation);
                                    script.InsertText(offset + 1, "\n" +
                                                      "\n" +
                                                      string.Format("if (FixUtil.Instance.NeedFix(\"{0}.{1}\"))\n", className, method.Name) +
                                                      "{\n" +
                                                      string.Format("    FixUtil.Instance.Fix(\"{0}.{1}\"{2});\n", className, method.Name, str) +
                                                      "    return;\n" +
                                                      "}\n");
                                }
                            }
                        }
                    }
                    File.WriteAllText(Path.ChangeExtension(file.FileName, ".output.cs"), document.Text);
                }


                string text = Console.ReadLine();
            }
        }
Exemple #45
0
        public void TestActions6Fail()
        {
            var test = @"
using System;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class E1 : Event {
        public E1() : base(1, -1) { }
    }

    class E2 : Event {
        public E2() : base(1, -1) { }
    }

    class E3 : Event {
        public E3() : base(1, -1) { }
    }

    class E4 : Event {
        public E4() : base(1, -1) { }
    }

    class Unit : Event {
        public Unit() : base(1, -1) { }
    }

    class Real : Machine
    {
        MachineId GhostMachine;

        [Start]
        [OnEntry(nameof(EntryInit))]
        [OnEventGotoState(typeof(E4), typeof(S2))]
        [OnEventPushState(typeof(Unit), typeof(S1))]
        [OnEventDoAction(typeof(E2), nameof(Action1))]
        class Init : MachineState { }

        void EntryInit()
        {
            GhostMachine = this.CreateMachine(typeof(Ghost), this.Id);
            this.Raise(new Unit());
        }

        [OnEntry(nameof(EntryS1))]
        class S1 : MachineState { }

        void EntryS1()
        {
            this.Send(GhostMachine, new E1());
        }

        [OnEntry(nameof(EntryS2))]
        class S2 : MachineState { }

        void EntryS2()
        {
            // this assert is reachable
            this.Assert(false);
        }

        void Action1()
        {
            this.Assert((int)this.Payload == 100); // this assert passes
            this.Send(GhostMachine, new E3());
        }
    }

    class Ghost : Machine
    {
        MachineId RealMachine;

        [Start]
        [OnEntry(nameof(EntryInit))]
        [OnEventGotoState(typeof(E1), typeof(S1))]
        class Init : MachineState { }

        void EntryInit()
        {
            RealMachine = this.Payload as MachineId;
        }

        [OnEntry(nameof(EntryS1))]
        [OnEventGotoState(typeof(E3), typeof(S2))]
        class S1 : MachineState { }

        void EntryS1()
        {
            this.Send(RealMachine, new E2(), 100);
        }

        [OnEntry(nameof(EntryS2))]
        class S2 : MachineState { }

        void EntryS2()
        {
            this.Send(RealMachine, new E4());
        }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(Real));
        }
    }
}";

            var parser  = new CSharpParser(new PSharpProject(), SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            Configuration.SuppressTrace      = true;
            Configuration.Verbose            = 2;
            Configuration.SchedulingStrategy = "dfs";

            var assembly = base.GetAssembly(program.GetSyntaxTree());

            AnalysisContext.Create(assembly);

            SCTEngine.Setup();
            SCTEngine.Run();

            Assert.AreEqual(1, SCTEngine.NumOfFoundBugs);
            Assert.AreEqual(5, SCTEngine.ExploredDepth);
        }
Exemple #46
0
        bool IsClasslessCode(string rawCode)
        {
            if (ProcessIfMarkedAsClassless(rawCode))
            {
                return(true);
            }

            //ensure "one statement - one line" rule
            string code = new CSharpParser(rawCode).PureCode.Replace("\n", " ").Replace("\r", " ").Replace(";", ";\n");

            string       line;
            StringReader sr = new StringReader(code);

            CodeArea area = CodeArea.unknown;

            while ((line = sr.ReadLine()) != null)
            {
                string clearLine = line.Trim();

                if (clearLine.Length == 0)
                {
                    continue;
                }
                while (true)
                {
                    switch (area)
                    {
                    case CodeArea.unknown:
                    {
                        if (IsUsingDirective(clearLine))
                        {
                            area = CodeArea.header;
                            continue;
                        }
                        else if (!IsDeclaration(clearLine))
                        {
                            area = CodeArea.body;
                            continue;
                        }
                        else
                        {
                            area = CodeArea.footer;
                            continue;
                        }
                    }

                    case CodeArea.header:
                    {
                        if (IsUsingDirective(clearLine))
                        {
                            header.Append(line);
                            header.Append(Environment.NewLine);
                        }
                        else
                        {
                            area = CodeArea.body;
                            continue;
                        }
                        break;
                    }

                    case CodeArea.body:
                    {
                        if (!IsDeclaration(clearLine))
                        {
                            body.Append(line);
                            body.Append(Environment.NewLine);
                        }
                        else
                        {
                            area = CodeArea.footer;
                            continue;
                        }
                        break;
                    }

                    case CodeArea.footer:
                    {
                        footer.Append(line);
                        footer.Append(Environment.NewLine);
                        break;
                    }
                    }
                    break;
                }
            }
            if (body.Length != 0)
            {
                return(true);
            }
            else
            {
                if (footer.Length == 0)
                {
                    return(false);
                }
                else
                {
                    //it is either C# or CC# without body
                    string fotterStr = footer.ToString().TrimStart();
                    if (fotterStr.StartsWith("namespace") && IsToken(fotterStr, 0, "namespace".Length))
                    {
                        return(false);
                    }
                    else
                    {
                        foreach (string classToken in new string[] { "class", "enum", "struct" })
                        {
                            int classStart = -1;
                            while ((classStart = fotterStr.IndexOf(classToken, classStart + 1)) != -1)
                            {
                                if (IsToken(fotterStr, classStart, classToken.Length))
                                {
                                    string decorations = fotterStr.Substring(0, classStart);
                                    if (decorations.IndexOfAny(";{}()".ToCharArray()) != -1)
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        return(false);
                                    }
                                }
                            }
                        }
                        return(true);
                    }
                }
            }
        }
Exemple #47
0
            void ScanPreProcessorIf(int textOffset, ref int i)
            {
                var end = CurText.Length;
                int idx = 0;

                while ((idx = CurText.IndexOf('/', idx)) >= 0 && idx + 1 < CurText.Length)
                {
                    var next = CurText [idx + 1];
                    if (next == '/')
                    {
                        end = idx - 1;
                        break;
                    }
                    idx++;
                }

                int     length    = end - textOffset;
                string  parameter = CurText.Substring(textOffset + 3, length - 3);
                AstNode expr      = new CSharpParser().ParseExpression(parameter);
                bool    result    = false;

                if (expr != null && !expr.IsNull)
                {
                    object o = expr.AcceptVisitor(new ConditinalExpressionEvaluator(doc, Defines), null);
                    if (o is bool)
                    {
                        result = (bool)o;
                    }
                }

                foreach (Span span in spanStack)
                {
                    if (span is ElseBlockSpan)
                    {
                        result &= ((ElseBlockSpan)span).IsValid;
                        break;
                    }
                    if (span is IfBlockSpan)
                    {
                        result &= ((IfBlockSpan)span).IsValid;
                        break;
                    }
                    if (span is ElseIfBlockSpan)
                    {
                        result &= ((ElseIfBlockSpan)span).IsValid;
                        break;
                    }
                }

                var ifBlockSpan = new IfBlockSpan(result);

                foreach (Span span in spanStack)
                {
                    if (span is AbstractBlockSpan)
                    {
                        var parentBlock = (AbstractBlockSpan)span;
                        ifBlockSpan.Disabled = parentBlock.Disabled || !parentBlock.IsValid;
                        break;
                    }
                }

                FoundSpanBegin(ifBlockSpan, i, length);
                i += length - 1;
            }
Exemple #48
0
        public void TestNondet1()
        {
            var test = @"
using System;
using System.Collections.Generic;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class Unit : Event { }
    class UserEvent : Event { }
    class Done : Event { }
    class Loop : Event { }
    class Waiting : Event { }
    class Computing : Event { }

    class EventHandler : Machine
    {
        List<MachineId> Workers;

        [Start]
        [OnEntry(nameof(InitOnEntry))]
        [OnEventGotoState(typeof(Unit), typeof(WaitForUser))]
        class Init : MachineState { }

		void InitOnEntry()
        {
            this.CreateMonitor(typeof(WatchDog));
            this.Raise(new Unit());
        }

        [OnEntry(nameof(WaitForUserOnEntry))]
        [OnEventGotoState(typeof(UserEvent), typeof(HandleEvent))]
        class WaitForUser : MachineState { }

		void WaitForUserOnEntry()
        {
            this.Monitor<WatchDog>(new Waiting());
            this.Send(this.Id, new UserEvent());
        }

        [OnEntry(nameof(HandleEventOnEntry))]
        [OnEventGotoState(typeof(Done), typeof(WaitForUser))]
        [OnEventGotoState(typeof(Loop), typeof(HandleEvent))]
        class HandleEvent : MachineState { }

        void HandleEventOnEntry()
        {
            this.Monitor<WatchDog>(new Computing());
            if (this.Nondet())
            {
                this.Send(this.Id, new Done());
            }
            else
            {
                this.Send(this.Id, new Loop());
            }
        }
    }

    class WatchDog : Monitor
    {
        List<MachineId> Workers;

        [Start]
        [Cold]
        [OnEventGotoState(typeof(Waiting), typeof(CanGetUserInput))]
        [OnEventGotoState(typeof(Computing), typeof(CannotGetUserInput))]
        class CanGetUserInput : MonitorState { }
        
        [Hot]
        [OnEventGotoState(typeof(Waiting), typeof(CanGetUserInput))]
        [OnEventGotoState(typeof(Computing), typeof(CannotGetUserInput))]
        class CannotGetUserInput : MonitorState { }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(EventHandler));
        }
    }
}";

            var parser = new CSharpParser(new PSharpProject(),
                                          SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            var sctConfig = new DynamicAnalysisConfiguration();

            sctConfig.SuppressTrace     = true;
            sctConfig.Verbose           = 3;
            sctConfig.CheckLiveness     = true;
            sctConfig.CacheProgramState = true;

            Output.Debugging = true;

            var assembly  = base.GetAssembly(program.GetSyntaxTree());
            var context   = AnalysisContext.Create(sctConfig, assembly);
            var sctEngine = SCTEngine.Create(context).Run();

            var bugReport = "Monitor 'WatchDog' detected infinite execution that violates a liveness property.";

            Assert.AreEqual(bugReport, sctEngine.BugReport);
        }
Exemple #49
0
 public FindFormalInputOfMethod(CSharpParser parser)
 {
     this.parser = parser;
 }
        public void TestSEMOneMachine34()
        {
            var test = @"
using System;
using System.Collections.Generic;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class E1 : Event { }
    class E2 : Event { }
    class E3 : Event { }
    class E4 : Event { }

    class MachOS : Machine
    {
        int Int;
        bool Bool;
        MachineId mach;
        Dictionary<int, int> m;
        List<bool> s;

        [Start]
        [OnEntry(nameof(EntryInit))]
        [OnEventDoAction(typeof(E1), nameof(Foo1))]
        [OnEventDoAction(typeof(E2), nameof(Foo2))]
        [OnEventDoAction(typeof(E3), nameof(Foo3))]
        [OnEventDoAction(typeof(E4), nameof(Foo4))]
        class Init : MachineState { }

        void EntryInit()
        {
            m = new Dictionary<int, int>();
            s = new List<bool>();
            m.Add(0, 1);
            m.Add(1, 2);
			s.Add(true);
			s.Add(false);
			s.Add(true);
			this.Send(this.Id, new E1(), Tuple.Create(1, true));
			this.Send(this.Id, new E2(), 0, false);
            this.Send(this.Id, new E3(), 1);
			this.Send(this.Id, new E4(), Tuple.Create(m, s));

        }

        void Foo1()
        {
            Int = (int)(this.Payload as Tuple<int, bool>).Item1;
            this.Assert(Int == 1);
            Bool = (bool)(this.Payload as Tuple<int, bool>).Item2;
            this.Assert(Bool == true);
        }

        void Foo2()
        {
            Int = (int)(this.Payload as object[])[0];
            this.Assert(Int == 0);
            Bool = (bool)(this.Payload as object[])[1];
            this.Assert(Bool == false);
        }

        void Foo3()
        {
            Int = (int)this.Payload;
            this.Assert(Int == 1);
        }

        void Foo4()
        {
            Int = ((this.Payload as Tuple<Dictionary<int, int>, List<bool>>).Item1 as Dictionary<int, int>)[0];
            this.Assert(Int == 1);
            Bool = ((this.Payload as Tuple<Dictionary<int, int>, List<bool>>).Item2 as List<bool>)[2];
            this.Assert(Bool == true);
        }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(MachOS));
        }
    }
}";

            var parser = new CSharpParser(new PSharpProject(),
                                          SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            var sctConfig = new DynamicAnalysisConfiguration();

            sctConfig.SuppressTrace        = true;
            sctConfig.Verbose              = 2;
            sctConfig.SchedulingStrategy   = SchedulingStrategy.DFS;
            sctConfig.SchedulingIterations = 100;

            var assembly  = base.GetAssembly(program.GetSyntaxTree());
            var context   = AnalysisContext.Create(sctConfig, assembly);
            var sctEngine = SCTEngine.Create(context).Run();

            Assert.AreEqual(0, sctEngine.NumOfFoundBugs);
        }
Exemple #51
0
 public FindLiteralofMethod(CSharpParser parser, List <string> listVal)
 {
     this.parser  = parser;
     this.listVal = listVal;
     this.isConst = false;
 }
Exemple #52
0
        //
        // Parses the string @input and returns a CSharpParser if succeeful.
        //
        // if @silent is set to true then no errors are
        // reported to the user.  This is used to do various calls to the
        // parser and check if the expression is parsable.
        //
        // @partial_input: if @silent is true, then it returns whether the
        // parsed expression was partial, and more data is needed
        //
        CSharpParser ParseString(ParseMode mode, string input, out bool partial_input)
        {
            partial_input = false;
            Reset();

            var enc = ctx.Settings.Encoding;
            var s   = new MemoryStream(enc.GetBytes(input));
            SeekableStreamReader seekable = new SeekableStreamReader(s, enc);

            InputKind kind = ToplevelOrStatement(seekable);

            if (kind == InputKind.Error)
            {
                if (mode == ParseMode.ReportErrors)
                {
                    ctx.Report.Error(-25, "Detection Parsing Error");
                }
                partial_input = false;
                return(null);
            }

            if (kind == InputKind.EOF)
            {
                if (mode == ParseMode.ReportErrors)
                {
                    Console.Error.WriteLine("Internal error: EOF condition should have been detected in a previous call with silent=true");
                }
                partial_input = true;
                return(null);
            }
            seekable.Position = 0;

            source_file.DeclarationFound = false;
            CSharpParser parser = new CSharpParser(seekable, source_file, new ParserSession());

            if (kind == InputKind.StatementOrExpression)
            {
                parser.Lexer.putback_char  = Tokenizer.EvalStatementParserCharacter;
                ctx.Settings.StatementMode = true;
            }
            else
            {
                parser.Lexer.putback_char  = Tokenizer.EvalCompilationUnitParserCharacter;
                ctx.Settings.StatementMode = false;
            }

            if (mode == ParseMode.GetCompletions)
            {
                parser.Lexer.CompleteOnEOF = true;
            }

            ReportPrinter old_printer = null;

            if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions))
            {
                old_printer = ctx.Report.SetPrinter(new StreamReportPrinter(TextWriter.Null));
            }

            try {
                parser.parse();
            } finally {
                if (ctx.Report.Errors != 0)
                {
                    if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
                    {
                        partial_input = true;
                    }

                    if (parser.undo != null)
                    {
                        parser.undo.ExecuteUndo();
                    }

                    parser = null;
                }

                if (old_printer != null)
                {
                    ctx.Report.SetPrinter(old_printer);
                }
            }
            return(parser);
        }
Exemple #53
0
 public FindGlobalVariable(CSharpParser parser)
 {
     this.parser = parser;
 }
        public void SetUp()
        {
            var unresolvedFile = new CSharpParser().Parse(corlib, "corlib.cs").ToTypeSystem();

            compilation = new CSharpProjectContent().SetAssemblyName("mscorlib").AddOrUpdateFiles(unresolvedFile).CreateCompilation();
        }
        public override IEnumerable <MemberReference> FindReferences(Project project, IProjectContent content, IEnumerable <FilePath> possibleFiles, IEnumerable <object> members)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project", "Project not set.");
            }
            if (content == null)
            {
                throw new ArgumentNullException("content", "Project content not set.");
            }
            SetPossibleFiles(possibleFiles);
            SetSearchedMembers(members);

            var scopes                  = searchedMembers.Select(e => refFinder.GetSearchScopes(e as IEntity));
            var compilation             = TypeSystemService.GetCompilation(project);
            List <MemberReference> refs = new List <MemberReference> ();

            foreach (var opendoc in openDocuments)
            {
                foreach (var newRef in FindInDocument(opendoc.Item2))
                {
                    if (newRef == null || refs.Any(r => r.FileName == newRef.FileName && r.Region == newRef.Region))
                    {
                        continue;
                    }
                    refs.Add(newRef);
                }
            }

            foreach (var file in files)
            {
                string text = Mono.TextEditor.Utils.TextFileUtility.ReadAllText(file);
                if (memberName != null && text.IndexOf(memberName, StringComparison.Ordinal) < 0 &&
                    (keywordName == null || text.IndexOf(keywordName, StringComparison.Ordinal) < 0))
                {
                    continue;
                }
                using (var editor = TextEditorData.CreateImmutable(text))
                {
                    editor.Document.FileName = file;
                    var unit = new CSharpParser().Parse(editor);
                    if (unit == null)
                    {
                        continue;
                    }

                    var storedFile = content.GetFile(file);
                    var parsedFile = storedFile as CSharpParsedFile;

                    if (parsedFile == null && storedFile is ParsedDocumentDecorator)
                    {
                        parsedFile = ((ParsedDocumentDecorator)storedFile).ParsedFile as CSharpParsedFile;
                    }

                    if (parsedFile == null)
                    {
                        // for fallback purposes - should never happen.
                        parsedFile  = unit.ToTypeSystem();
                        content     = content.UpdateProjectContent(content.GetFile(file), parsedFile);
                        compilation = content.CreateCompilation();
                    }
                    foreach (var scope in scopes)
                    {
                        refFinder.FindReferencesInFile(
                            scope,
                            parsedFile,
                            unit,
                            compilation,
                            (astNode, result) =>
                        {
                            var newRef = GetReference(result, astNode, file, editor);
                            if (newRef == null || refs.Any(r => r.FileName == newRef.FileName && r.Region == newRef.Region))
                            {
                                return;
                            }
                            refs.Add(newRef);
                        },
                            CancellationToken.None
                            );
                    }
                }
            }
            return(refs);
        }
        /// <summary>
        /// Parses the specified file
        /// </summary>
        /// <param name="f">File information.</param>
        /// <param name="s">Stream with the file code.</param>
        /// <param name="dynamic">Using "dynamic" to refer to a "dynamic var"</param>
        private void parseFile(FileInfo f, Stream s, bool dynamic)
        {
            ICSharpLexer  antlrLexer;
            ICSharpParser parser;
            TokenStreamHiddenTokenFilter filter;

            try {
                TokenStream lexer;

                // Create a scanner that reads from the input stream passed to us
                if (dynamic)
                {
                    antlrLexer = new CSharpLexerDynamic(new StreamReader(s));
                }
                else
                {
                    antlrLexer = new CSharpLexer(new StreamReader(s));
                }

                // Define a selector that can switch from the C# codelexer to the C# preprocessor lexer
                TokenStreamSelector selector = new TokenStreamSelector();
                antlrLexer.Selector = selector;
                antlrLexer.setFilename(f.Name);

                CSharpPreprocessorLexer preproLexer = new CSharpPreprocessorLexer(antlrLexer.getInputState());
                preproLexer.Selector = selector;
                CSharpPreprocessorHooverLexer hooverLexer = new CSharpPreprocessorHooverLexer(antlrLexer.getInputState());
                hooverLexer.Selector = selector;

                // use the special token object class
                antlrLexer.setTokenCreator(new CustomHiddenStreamToken.CustomHiddenStreamTokenCreator());
                antlrLexer.setTabSize(1);
                preproLexer.setTokenCreator(new CustomHiddenStreamToken.CustomHiddenStreamTokenCreator());
                preproLexer.setTabSize(1);
                hooverLexer.setTokenCreator(new CustomHiddenStreamToken.CustomHiddenStreamTokenCreator());
                hooverLexer.setTabSize(1);

                // notify selector about various lexers; name them for convenient reference later
                selector.addInputStream(antlrLexer, "codeLexer");
                selector.addInputStream(preproLexer, "directivesLexer");
                selector.addInputStream(hooverLexer, "hooverLexer");
                selector.select("codeLexer"); // start with main the CSharp code lexer
                lexer = selector;

                // create the stream filter; hide WS and SL_COMMENT
                filter = new TokenStreamHiddenTokenFilter(lexer);
                filter.hide(CSharpTokenTypes.WHITESPACE);
                filter.hide(CSharpTokenTypes.NEWLINE);
                filter.hide(CSharpTokenTypes.ML_COMMENT);
                filter.hide(CSharpTokenTypes.SL_COMMENT);

                //------------------------------------------------------------------

                // Create a parser that reads from the scanner
                if (dynamic)
                {
                    parser = new CSharpParserDynamic(filter);
                    DynVarManager.DynamicOption = true;
                }
                else
                {
                    parser = new CSharpParser(filter);
                }
                parser.setFilename(f.FullName);
                //parser.setFilename(f.Name);

                // Start parsing at the compilationUnit rule
                long startTime = DateTime.Now.Ticks;

                this.astList.Add(parser.compilationUnit());

    #if DEBUG
                double       elapsedTime   = ((DateTime.Now.Ticks - startTime) / TimeSpan.TicksPerMillisecond) / 1000.0;
                ConsoleColor previousColor = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.DarkGray;
                System.Console.Out.WriteLine("Parsed {0} in: {1} seconds.", f.Name, elapsedTime);
                Console.ForegroundColor = previousColor;
    #endif
            }
            catch (RecognitionException e)
            {
                ErrorManager.Instance.NotifyError(new ParserError(new Location(e.fileName, e.line, e.column), e.Message));
            }
        }
Exemple #57
0
        public IEnumerable <AstNode> FindUsageNodes(Request request)
        {
            var res = _parser.ParsedContent(request.Buffer, request.FileName);
            var loc = new TextLocation(request.Line, request.Column);

            _result = new ConcurrentBag <AstNode>();
            var findReferences = new FindReferences
            {
                FindCallsThroughInterface         = true,
                FindCallsThroughVirtualBaseMethod = true,
                FindTypeReferencesEvenIfAliased   = false,
            };

            ResolveResult resolveResult = ResolveAtLocation.Resolve(res.Compilation, res.UnresolvedFile, res.SyntaxTree, loc);

            if (resolveResult is LocalResolveResult)
            {
                var variable = (resolveResult as LocalResolveResult).Variable;
                findReferences.FindLocalReferences(variable, res.UnresolvedFile, res.SyntaxTree, res.Compilation,
                                                   (node, rr) => _result.Add(node.GetDefinition()), CancellationToken.None);
            }
            else
            {
                IEntity entity = null;
                IEnumerable <IList <IFindReferenceSearchScope> > searchScopes = null;
                if (resolveResult is TypeResolveResult)
                {
                    var type = (resolveResult as TypeResolveResult).Type;
                    entity = type.GetDefinition();
                    ProcessTypeResults(type);
                    searchScopes = new[] { findReferences.GetSearchScopes(entity) };
                }

                if (resolveResult is MemberResolveResult)
                {
                    entity = (resolveResult as MemberResolveResult).Member;
                    if (entity.SymbolKind == SymbolKind.Constructor)
                    {
                        // process type instead
                        var type = entity.DeclaringType;
                        entity = entity.DeclaringTypeDefinition;
                        ProcessTypeResults(type);
                        searchScopes = new[] { findReferences.GetSearchScopes(entity) };
                    }
                    else
                    {
                        ProcessMemberResults(resolveResult);
                        var member  = (resolveResult as MemberResolveResult).Member;
                        var members = MemberCollector.CollectMembers(_solution,
                                                                     member, false);
                        searchScopes = members.Select(findReferences.GetSearchScopes);
                    }
                }

                if (entity == null)
                {
                    return(_result);
                }

                var projectsThatReferenceUsage = _projectFinder.FindProjectsReferencing(entity.Compilation.TypeResolveContext);

                foreach (var project in projectsThatReferenceUsage)
                {
                    var pctx        = project.ProjectContent.CreateCompilation();
                    var interesting = (from file in project.Files
                                       select(file.ParsedFile as CSharpUnresolvedFile)).ToList();

                    Parallel.ForEach(interesting.Distinct(), file =>
                    {
                        string text = _solution.GetFile(file.FileName.LowerCaseDriveLetter()).Content.Text;
                        SyntaxTree unit;
                        if (project.CompilerSettings != null)
                        {
                            unit = new CSharpParser(project.CompilerSettings).Parse(text, file.FileName);
                        }
                        else
                        {
                            unit = new CSharpParser().Parse(text, file.FileName);
                        }

                        foreach (var scope in searchScopes)
                        {
                            findReferences.FindReferencesInFile(scope, file, unit,
                                                                pctx,
                                                                (node, rr) => _result.Add(node.GetIdentifier()),
                                                                CancellationToken.None);
                        }
                    });
                }
            }
            return(_result);
        }
        public void TestPushImplicitPopWithRaise()
        {
            var test = @"
using System;
using Microsoft.PSharp;

namespace SystematicTesting
{
    class E1 : Event {
        public E1() : base(1, -1) { }
    }

    class E2 : Event {
        public E2() : base(1, -1) { }
    }

    class E3 : Event {
        public E3() : base(1, -1) { }
    }

    class Real1 : Machine
    {
        bool test = false;

        [Start]
        [OnEntry(nameof(EntryInit))]
        [OnExit(nameof(ExitInit))]
        [OnEventGotoState(typeof(E1), typeof(Init))]
        [OnEventPushState(typeof(E2), typeof(S1))]
        [OnEventDoAction(typeof(E3), nameof(Action1))]
        class Init : MachineState { }

        void EntryInit()
        {
            this.Send(this.Id, new E1());
        }

        void ExitInit()
        {
            this.Send(this.Id, new E2());
        }

        [OnEntry(nameof(EntryS1))]
        class S1 : MachineState { }

        void EntryS1()
        {
            test = true;
            this.Raise(new E1());
        }

        void Action1() { }
    }

    public static class TestProgram
    {
        public static void Main(string[] args)
        {
            TestProgram.Execute();
            Console.ReadLine();
        }

        [Test]
        public static void Execute()
        {
            PSharpRuntime.CreateMachine(typeof(Real1));
        }
    }
}";

            var parser  = new CSharpParser(new PSharpProject(), SyntaxFactory.ParseSyntaxTree(test), true);
            var program = parser.Parse();

            program.Rewrite();

            Configuration.SuppressTrace = true;
            Configuration.Verbose       = 2;

            var assembly = base.GetAssembly(program.GetSyntaxTree());

            AnalysisContext.Create(assembly);

            SCTEngine.Setup();
            SCTEngine.Run();

            Assert.AreEqual(1, SCTEngine.NumOfFoundBugs);
        }
Exemple #59
0
        public static VariableInitializer GetVariableDeclarationForLinqMethods(string query, bool requiresSelectNewAnonymousType)
        {
            try
            {
                var parser = new CSharpParser();

                var block = parser.ParseStatements(ToQueryStatement(query)).ToList();

                if (block.Count == 0 || parser.HasErrors)
                {
                    var errs = string.Join(Environment.NewLine, parser.Errors.Select(x => x.Region + ": " + x.ErrorType + " - " + x.Message));
                    throw new InvalidOperationException("Could not understand query: \r\n" + errs);
                }

                var declaration = block[0] as VariableDeclarationStatement;
                if (declaration == null)
                {
                    throw new InvalidOperationException("Only local variable declaration are allowed");
                }

                if (declaration.Variables.Count != 1)
                {
                    throw new InvalidOperationException("Only one variable declaration is allowed");
                }

                var variable = declaration.Variables.First();

                if (variable.Initializer as InvocationExpression == null)
                {
                    throw new InvalidOperationException("Variable declaration must have an initializer which is a method invocation expression");
                }

                var targetObject = ((InvocationExpression)variable.Initializer).Target as MemberReferenceExpression;
                if (targetObject == null)
                {
                    throw new InvalidOperationException("Variable initializer must be invoked on a method reference expression");
                }

                if (targetObject.MemberName != "Select" && targetObject.MemberName != "SelectMany")
                {
                    throw new InvalidOperationException("Variable initializer must end with a select call");
                }

                var lambdaExpression = AsLambdaExpression(((InvocationExpression)variable.Initializer).Arguments.Last());
                if (lambdaExpression == null)
                {
                    throw new InvalidOperationException("Variable initializer select must have a lambda expression");
                }

                variable.AcceptVisitor(new TransformNullCoalescingOperatorTransformer(), null);
                variable.AcceptVisitor(new DynamicExtensionMethodsTranslator(), null);
                variable.AcceptVisitor(new TransformDynamicLambdaExpressions(), null);
                variable.AcceptVisitor(new TransformDynamicInvocationExpressions(), null);
                variable.AcceptVisitor(new TransformObsoleteMethods(), null);

                var expressionBody = GetAnonymousCreateExpression(lambdaExpression.Body);

                var anonymousTypeCreateExpression = expressionBody as AnonymousTypeCreateExpression;
                if (anonymousTypeCreateExpression == null && requiresSelectNewAnonymousType)
                {
                    throw new InvalidOperationException("Variable initializer select must have a lambda expression with an object create expression");
                }

                var objectCreateExpression = expressionBody as ObjectCreateExpression;
                if (objectCreateExpression != null && requiresSelectNewAnonymousType)
                {
                    throw new InvalidOperationException("Variable initializer select must have a lambda expression creating an anonymous type but returning " + objectCreateExpression.Type);
                }

                return(variable);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Could not understand query: " + e.Message, e);
            }
        }
 public CustomCSharpListener(CSharpParser parser)
 {
     _parser = parser;
     _interfaceExtractRule = new InterfaceExtractorRule(_parser.InputStream as ITokenStream);
     //_interfacePreProcTemplate = new StringBuilder();
 }