Skip to content
This repository has been archived by the owner on Jul 15, 2023. It is now read-only.

Exclude attributes from precondition visibility verification #280

Merged
merged 2 commits into from
Oct 28, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Foxtrot/Foxtrot/Checker/VisibilityHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Compiler;
using System.Diagnostics.Contracts;

Expand All @@ -23,6 +24,9 @@ namespace Microsoft.Contracts.Foxtrot
[ContractVerification(true)]
internal class VisibilityHelper : InspectorIncludingClosures
{
private static readonly Lazy<TypeNode> systemAttributeType = new Lazy<TypeNode>(() =>
HelperMethods.FindType(SystemTypes.SystemAssembly, StandardIds.System, Identifier.For("Attribute")));

private Member memberInErrorFound;

/// <summary>
Expand All @@ -37,6 +41,22 @@ private void ReInitialize(Method asThisMember)
this.AsThisMember = asThisMember;
}

private static bool IsAttribute(TypeNode declaringType)
{
var currentType = declaringType;
while (currentType != null)
{
if (currentType == systemAttributeType.Value)
{
return true;
}

currentType = currentType.BaseType;
}

return false;
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current code checks declaringType.BaseType twice on recurrence.
Loop version should be simpler:

private static bool IsAttribute(TypeNode declaringType)
{
    TypeNode currentType = declaringType;
    while (currentType != null)
    {
        if (currentType == systemAttributeType.Value)
        {
            return true;
        }

        currentType = declaringType.BaseType;
    }

    return false;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the loop version instead of

currentType = declaringType.BaseType

this should be

currentType = currentType.BaseType

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, thanks. Otherwise it might be less efficient than recursive version...

/// <summary>
/// Checks for less-than-visible member references in an expression.
/// </summary>
Expand All @@ -47,6 +67,11 @@ public override void VisitMemberBinding(MemberBinding binding)
Member mem = binding.BoundMember;
if (mem != null)
{
// Member visiting includes also all attributes for the method.
// But from Code Contracts perspective public method can have less visible attributes
// because they're not part of the precondition.
if (IsAttribute(mem.DeclaringType)) return;

Field f = mem as Field;
bool specPublic = false;

Expand Down
38 changes: 38 additions & 0 deletions Foxtrot/Tests/RewriterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,31 @@ public static IEnumerable<object> AsyncTests
}
}

public static IEnumerable<object> PreconditionVisibilityTests
{
get
{
return Enumerable.Range(0, PreconditionVisibilityTestData.Count()).Select(i => new object[] { i });
}
}

private static IEnumerable<Options> PreconditionVisibilityTestData
{
get
{
yield return new Options(
sourceFile: @"Foxtrot\Tests\Sources\AttributesAndPreconditions.cs",
foxtrotOptions: @"",
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new string[0],
libPaths: new[] {@"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug"},
compilerCode: "CS",
useBinDir: false,
useExe: true,
mustSucceed: true);
}
}

private static IEnumerable<Options> AsyncPostconditionsData
{
Expand Down Expand Up @@ -2021,6 +2046,19 @@ public void BuildRewriteRunRoslynTestCasesWithV45(int testIndex)
options.UseTestHarness = true;
TestDriver.BuildRewriteRun(_testOutputHelper, options);
}

[Theory]
[MemberData("PreconditionVisibilityTests")]
[Trait("Category", "Runtime"), Trait("Category", "CoreTest"), Trait("Category", "V4.5")]
public void PreconditionVisibilityTests45(int testIndex)
{
Options options = PreconditionVisibilityTestData.ElementAt(testIndex);
options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName));
options.BuildFramework = @".NETFramework\v4.5";
options.ContractFramework = @".NETFramework\v4.0";
options.UseTestHarness = true;
TestDriver.BuildRewriteRun(_testOutputHelper, options);
}

[Theory(Skip = "Old Roslyn bits are not compatible with CCRewrite. Test (and old binaries) should be removed in the next iteration.")]
[MemberData("TestFile")]
Expand Down
51 changes: 51 additions & 0 deletions Foxtrot/Tests/Sources/AttributesAndPreconditions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics.Contracts;
using System.Threading;

namespace Tests.Sources
{
internal class MyAttr : Attribute { }

public class Foo
{
public static void Method1([MyAttr] string s)
{
// If ccrewrite behaves properly, this method should not fail
Contract.Requires(s.StartsWith("foo"));
}
}

partial class TestMain
{
partial void Run()
{
if (behave)
{
Foo.Method1("foo");
}
else
{
throw new ArgumentNullException();
}
}

public ContractFailureKind NegativeExpectedKind = ContractFailureKind.Precondition;
public string NegativeExpectedCondition = "Value cannot be null.";
}
}