Skip to content
This repository was archived by the owner on Apr 14, 2022. It is now read-only.

When a class inherits from something that is not a class, give a diagnostic error #1277

Merged
merged 7 commits into from
Jul 11, 2019
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
71 changes: 58 additions & 13 deletions src/Analysis/Ast/Impl/Analyzer/Symbols/ClassEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Python.Analysis.Analyzer.Evaluation;
using Microsoft.Python.Analysis.Diagnostics;
using Microsoft.Python.Analysis.Types;
using Microsoft.Python.Analysis.Values;
using Microsoft.Python.Core;
using Microsoft.Python.Parsing;
using Microsoft.Python.Parsing.Ast;

namespace Microsoft.Python.Analysis.Analyzer.Symbols {
Expand Down Expand Up @@ -50,22 +53,12 @@ public void EvaluateClass() {
EvaluateInnerClasses(_classDef);

_class = classInfo;
// Set bases to the class.
var bases = new List<IPythonType>();
foreach (var a in _classDef.Bases.Where(a => string.IsNullOrEmpty(a.Name))) {
// We cheat slightly and treat base classes as annotations.
var b = Eval.GetTypeFromAnnotation(a.Expression);
if (b != null) {
var t = b.GetPythonType();
bases.Add(t);
t.AddReference(Eval.GetLocationOfName(a.Expression));
}
}
_class.SetBases(bases);

var bases = ProcessBases(outerScope);

_class.SetBases(bases);
// Declare __class__ variable in the scope.
Eval.DeclareVariable("__class__", _class, VariableSource.Declaration);

ProcessClassBody();
}
}
Expand Down Expand Up @@ -118,6 +111,47 @@ private void ProcessClassBody() {
UpdateClassMembers();
}

private IEnumerable<IPythonType> ProcessBases(Scope outerScope) {
var bases = new List<IPythonType>();
foreach (var a in _classDef.Bases.Where(a => string.IsNullOrEmpty(a.Name))) {
var expr = a.Expression;

switch (expr) {
// class declared in the current module
case NameExpression nameExpression:
var name = Eval.GetInScope(nameExpression.Name, outerScope);
switch (name) {
case PythonClassType classType:
bases.Add(classType);
break;
case IPythonConstant constant:
ReportInvalidBase(constant.Value);
break;
default:
TryAddBase(bases, a);
break;
}
break;
default:
TryAddBase(bases, a);
break;
}
}
return bases;
}

private void TryAddBase(List<IPythonType> bases, Arg arg) {
// We cheat slightly and treat base classes as annotations.
var b = Eval.GetTypeFromAnnotation(arg.Expression);
if (b != null) {
var t = b.GetPythonType();
bases.Add(t);
t.AddReference(Eval.GetLocationOfName(arg.Expression));
} else {
ReportInvalidBase(arg.ToCodeString(Eval.Ast, CodeFormattingOptions.Traditional));
}
}

private void EvaluateConstructors(ClassDefinition cd) {
// Do not use foreach since walker list is dynamically modified and walkers are removed
// after processing. Handle __init__ and __new__ first so class variables are initialized.
Expand Down Expand Up @@ -152,6 +186,17 @@ private void UpdateClassMembers() {
_class.AddMembers(members, false);
}

private void ReportInvalidBase(object argVal) {
Eval.ReportDiagnostics(Eval.Module.Uri,
new DiagnosticsEntry(
Resources.InheritNonClass.FormatInvariant(argVal),
_classDef.NameExpression.GetLocation(Eval)?.Span ?? default,
Diagnostics.ErrorCodes.InheritNonClass,
Severity.Error,
DiagnosticSource.Analysis
));
}

// Classes and functions are walked by their respective evaluators
public override bool Walk(ClassDefinition node) => false;
public override bool Walk(FunctionDefinition node) => false;
Expand Down
1 change: 1 addition & 0 deletions src/Analysis/Ast/Impl/Diagnostics/ErrorCodes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,6 @@ public static class ErrorCodes {
public const string ReturnInInit = "return-in-init";
public const string TypingNewTypeArguments = "typing-newtype-arguments";
public const string TypingGenericArguments = "typing-generic-arguments";
public const string InheritNonClass = "inherit-non-class";
}
}
9 changes: 9 additions & 0 deletions src/Analysis/Ast/Impl/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion src/Analysis/Ast/Impl/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -204,4 +204,7 @@
<data name="GenericNotAllUnique" xml:space="preserve">
<value>Arguments to Generic must all be unique.</value>
</data>
</root>
<data name="InheritNonClass" xml:space="preserve">
<value>Inheriting '{0}', which is not a class.</value>
</data>
</root>
3 changes: 3 additions & 0 deletions src/Analysis/Ast/Impl/Types/PythonClassType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Python.Analysis.Analyzer;
using Microsoft.Python.Analysis.Diagnostics;
using Microsoft.Python.Analysis.Modules;
using Microsoft.Python.Analysis.Specializations.Typing;
using Microsoft.Python.Analysis.Types.Collections;
Expand Down Expand Up @@ -190,6 +192,7 @@ internal void SetBases(IEnumerable<IPythonType> bases) {
}

bases = bases != null ? bases.Where(b => !b.GetPythonType().IsUnknown()).ToArray() : Array.Empty<IPythonType>();

// For Python 3+ attach object as a base class by default except for the object class itself.
if (DeclaringModule.Interpreter.LanguageVersion.Is3x() && DeclaringModule.ModuleType != ModuleType.Builtins) {
var objectType = DeclaringModule.Interpreter.GetBuiltinType(BuiltinTypeId.Object);
Expand Down
173 changes: 173 additions & 0 deletions src/Analysis/Ast/Test/InheritNonClassTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Python.Analysis.Diagnostics;
using Microsoft.Python.Analysis.Tests.FluentAssertions;
using Microsoft.Python.Core;
using Microsoft.Python.Parsing.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;

namespace Microsoft.Python.Analysis.Tests {
[TestClass]
public class InheritNonClassTests : AnalysisTestBase {
public TestContext TestContext { get; set; }

[TestInitialize]
public void TestInitialize()
=> TestEnvironmentImpl.TestInitialize($"{TestContext.FullyQualifiedTestClassName}.{TestContext.TestName}");

[TestCleanup]
public void Cleanup() => TestEnvironmentImpl.TestCleanup();

[TestMethod, Priority(0)]
public async Task InheritFromRenamedBuiltin() {
const string code = @"
tmp = str

class C(tmp):
def method(self):
return 'test'
";
var analysis = await GetAnalysisAsync(code);
analysis.Diagnostics.Should().BeEmpty();
}


[TestMethod, Priority(0)]
public async Task InheritFromBuiltin() {
const string code = @"
class C(str):
def method(self):
return 'test'
";
var analysis = await GetAnalysisAsync(code);
analysis.Diagnostics.Should().BeEmpty();
}


[TestMethod, Priority(0)]
public async Task InheritFromUserClass() {
const string code = @"
class D:
def hello(self):
pass

class C(D):
def method(self):
return 'test'
";
var analysis = await GetAnalysisAsync(code);
analysis.Diagnostics.Should().BeEmpty();
}


[TestMethod, Priority(0)]
public async Task InheritFromConstant() {
const string code = @"
class C(5):
def method(self):
return 'test'
";
var analysis = await GetAnalysisAsync(code);
analysis.Diagnostics.Should().HaveCount(1);

var diagnostic = analysis.Diagnostics.ElementAt(0);
diagnostic.SourceSpan.Should().Be(2, 7, 2, 8);
diagnostic.Message.Should().Be(Resources.InheritNonClass.FormatInvariant("5"));
diagnostic.ErrorCode.Should().Be(ErrorCodes.InheritNonClass);
}


[TestMethod, Priority(0)]
public async Task InheritFromConstantVar() {
const string code = @"
x = 'str'

class C(x):
def method(self):
return 'test'

x = 5

class D(x):
def method(self):
return 'test'
";
var analysis = await GetAnalysisAsync(code);
analysis.Diagnostics.Should().HaveCount(2);

var diagnostic = analysis.Diagnostics.ElementAt(0);
diagnostic.SourceSpan.Should().Be(4, 7, 4, 8);
diagnostic.Message.Should().Be(Resources.InheritNonClass.FormatInvariant("str"));
diagnostic.ErrorCode.Should().Be(ErrorCodes.InheritNonClass);

diagnostic = analysis.Diagnostics.ElementAt(1);
diagnostic.SourceSpan.Should().Be(10, 7, 10, 8);
diagnostic.Message.Should().Be(Resources.InheritNonClass.FormatInvariant("5"));
diagnostic.ErrorCode.Should().Be(ErrorCodes.InheritNonClass);
}

[Ignore]
[TestMethod, Priority(0)]
public async Task InheritFromBinaryOp() {
const string code = @"
x = 5

class C(x + 2):
def method(self):
return 'test'
";
var analysis = await GetAnalysisAsync(code);
analysis.Diagnostics.Should().HaveCount(1);

var diagnostic = analysis.Diagnostics.ElementAt(0);
diagnostic.SourceSpan.Should().Be(4, 7, 4, 8);
diagnostic.Message.Should().Be(Resources.InheritNonClass.FormatInvariant("x + 2"));
diagnostic.ErrorCode.Should().Be(ErrorCodes.InheritNonClass);
}


[TestMethod, Priority(0)]
public async Task InheritFromOtherModule() {
const string code = @"
import typing

class C(typing.TypeVar):
def method(self):
return 'test'
";
var analysis = await GetAnalysisAsync(code);
analysis.Diagnostics.Should().BeEmpty();
}

[TestMethod, Priority(0)]
public async Task InheritFromRenamedOtherModule() {
const string code = @"
import typing

tmp = typing.TypeVar
class C(tmp):
def method(self):
return 'test'
";
var analysis = await GetAnalysisAsync(code);
analysis.Diagnostics.Should().BeEmpty();
}
}
}