content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Newtonsoft.Json; using System; namespace EthereumChain { [Serializable] public sealed class EtherAddressTransactions { [JsonProperty] private readonly string status; [JsonProperty] private readonly string message; [JsonProperty] private readonly EtherTransaction[] result; public string Status => status; public string Message => message; public EtherTransaction[] Result => result; } }
20.291667
51
0.650924
[ "MIT" ]
Mathias-Hedelund-Larsen/Crypto_Transaction_Assistant
Assets/Scripts/Other/JsonModels/EthereumChain/EtherAddressTransactions.cs
489
C#
using System; using System.Threading.Tasks; using OrchardCore.ContentManagement.Display.Models; using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; namespace OrchardCore.ContentManagement.Display.ContentDisplay { public abstract class ContentFieldDisplayDriver<TField> : DisplayDriverBase, IContentFieldDisplayDriver where TField : ContentField, new() { private const string DisplayToken = "_Display"; private const string DisplaySeparator = "_Display__"; private ContentTypePartDefinition _typePartDefinition; private ContentPartFieldDefinition _partFieldDefinition; public override ShapeResult Factory(string shapeType, Func<IBuildShapeContext, ValueTask<IShape>> shapeBuilder, Func<IShape, Task> initializeAsync) { // e.g., HtmlBodyPart.Summary, HtmlBodyPart-BlogPost, BagPart-LandingPage-Services // context.Shape is the ContentItem shape, we need to alter the part shape var result = base.Factory(shapeType, shapeBuilder, initializeAsync).Prefix(Prefix); if (_typePartDefinition != null && _partFieldDefinition != null) { var partType = _typePartDefinition.PartDefinition.Name; var partName = _typePartDefinition.Name; var fieldType = _partFieldDefinition.FieldDefinition.Name; var fieldName = _partFieldDefinition.Name; var contentType = _typePartDefinition.ContentTypeDefinition.Name; var displayMode = _partFieldDefinition.DisplayMode(); var hasDisplayMode = !String.IsNullOrEmpty(displayMode); if (GetEditorShapeType(_partFieldDefinition) == shapeType) { // HtmlBodyPart-Description, Services-Description result.Differentiator($"{partName}-{fieldName}"); // We do not need to add alternates on edit as they are handled with field editor types so return before adding alternates return result; } // If the shape type and the field type only differ by the display mode if (hasDisplayMode && shapeType == fieldType + DisplaySeparator + displayMode) { // Preserve the shape name regardless its differentiator result.Name($"{partName}-{fieldName}"); } if (fieldType == shapeType) { // HtmlBodyPart-Description, Services-Description result.Differentiator($"{partName}-{fieldName}"); } else { // HtmlBodyPart-Description-TextField, Services-Description-TextField result.Differentiator($"{partName}-{fieldName}-{shapeType}"); } result.Displaying(ctx => { var displayTypes = new[] { "", "_" + ctx.Shape.Metadata.DisplayType }; // [ShapeType]_[DisplayType], e.g. TextField.Summary ctx.Shape.Metadata.Alternates.Add($"{shapeType}_{ctx.Shape.Metadata.DisplayType}"); // When the shape type is the same as the field, we can ignore one of them in the alternate name // For instance TextField returns a unique TextField shape type. if (shapeType == fieldType) { foreach (var displayType in displayTypes) { // [PartType]__[FieldName], e.g. HtmlBodyPart-Description ctx.Shape.Metadata.Alternates.Add($"{partType}{displayType}__{fieldName}"); // [ContentType]__[PartName]__[FieldName], e.g. Blog-HtmlBodyPart-Description, LandingPage-Services-Description ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partType}__{fieldName}"); // [ContentType]__[FieldType], e.g. Blog-TextField, LandingPage-TextField ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{fieldType}"); } } else { if (hasDisplayMode) { // [FieldType]_[DisplayType]__[DisplayMode]_Display, e.g. TextField-Header.Display.Summary ctx.Shape.Metadata.Alternates.Add($"{fieldType}_{ctx.Shape.Metadata.DisplayType}__{displayMode}{DisplayToken}"); } for (var i = 0; i < displayTypes.Length; i++) { var displayType = displayTypes[i]; if (hasDisplayMode) { shapeType = $"{fieldType}__{displayMode}"; if (displayType == "") { displayType = DisplayToken; } else { shapeType += DisplayToken; } } // [FieldType]__[ShapeType], e.g. TextField-TextFieldSummary ctx.Shape.Metadata.Alternates.Add($"{fieldType}{displayType}__{shapeType}"); // [PartType]__[FieldName]__[ShapeType], e.g. HtmlBodyPart-Description-TextFieldSummary ctx.Shape.Metadata.Alternates.Add($"{partType}{displayType}__{fieldName}__{shapeType}"); // [ContentType]__[PartName]__[FieldName]__[ShapeType], e.g. Blog-HtmlBodyPart-Description-TextFieldSummary, LandingPage-Services-Description-TextFieldSummary ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partName}__{fieldName}__{shapeType}"); // [ContentType]__[FieldType]__[ShapeType], e.g. Blog-TextField-TextFieldSummary, LandingPage-TextField-TextFieldSummary ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{fieldType}__{shapeType}"); } } }); } return result; } Task<IDisplayResult> IContentFieldDisplayDriver.BuildDisplayAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, BuildDisplayContext context) { if (!String.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !String.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return Task.FromResult(default(IDisplayResult)); } var field = contentPart.Get<TField>(partFieldDefinition.Name); if (field != null) { BuildPrefix(typePartDefinition, partFieldDefinition, context.HtmlFieldPrefix); var fieldDisplayContext = new BuildFieldDisplayContext(contentPart, typePartDefinition, partFieldDefinition, context); _typePartDefinition = typePartDefinition; _partFieldDefinition = partFieldDefinition; var result = DisplayAsync(field, fieldDisplayContext); _typePartDefinition = null; _partFieldDefinition = null; return result; } return Task.FromResult(default(IDisplayResult)); } Task<IDisplayResult> IContentFieldDisplayDriver.BuildEditorAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, BuildEditorContext context) { if (!String.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !String.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return Task.FromResult(default(IDisplayResult)); } var field = contentPart.GetOrCreate<TField>(partFieldDefinition.Name); if (field != null) { BuildPrefix(typePartDefinition, partFieldDefinition, context.HtmlFieldPrefix); var fieldEditorContext = new BuildFieldEditorContext(contentPart, typePartDefinition, partFieldDefinition, context); _typePartDefinition = typePartDefinition; _partFieldDefinition = partFieldDefinition; var result = EditAsync(field, fieldEditorContext); _typePartDefinition = null; _partFieldDefinition = null; return result; } return Task.FromResult(default(IDisplayResult)); } async Task<IDisplayResult> IContentFieldDisplayDriver.UpdateEditorAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, UpdateEditorContext context) { if (!String.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !String.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return null; } var field = contentPart.GetOrCreate<TField>(partFieldDefinition.Name); BuildPrefix(typePartDefinition, partFieldDefinition, context.HtmlFieldPrefix); var updateFieldEditorContext = new UpdateFieldEditorContext(contentPart, typePartDefinition, partFieldDefinition, context); var result = await UpdateAsync(field, context.Updater, updateFieldEditorContext); if (result == null) { return null; } contentPart.Apply(partFieldDefinition.Name, field); return result; } public virtual Task<IDisplayResult> DisplayAsync(TField field, BuildFieldDisplayContext fieldDisplayContext) { return Task.FromResult(Display(field, fieldDisplayContext)); } public virtual Task<IDisplayResult> EditAsync(TField field, BuildFieldEditorContext context) { return Task.FromResult(Edit(field, context)); } public virtual Task<IDisplayResult> UpdateAsync(TField field, IUpdateModel updater, UpdateFieldEditorContext context) { return Task.FromResult(Update(field, updater, context)); } public virtual IDisplayResult Display(TField field, BuildFieldDisplayContext fieldDisplayContext) { return null; } public virtual IDisplayResult Edit(TField field, BuildFieldEditorContext context) { return null; } public virtual IDisplayResult Update(TField field, IUpdateModel updater, UpdateFieldEditorContext context) { return null; } protected string GetEditorShapeType(string shapeType, ContentPartFieldDefinition partFieldDefinition) { var editor = partFieldDefinition.Editor(); return !String.IsNullOrEmpty(editor) ? shapeType + "__" + editor : shapeType; } protected string GetEditorShapeType(string shapeType, BuildFieldEditorContext context) { return GetEditorShapeType(shapeType, context.PartFieldDefinition); } protected string GetEditorShapeType(ContentPartFieldDefinition partFieldDefinition) { return GetEditorShapeType(typeof(TField).Name + "_Edit", partFieldDefinition); } protected string GetEditorShapeType(BuildFieldEditorContext context) { return GetEditorShapeType(context.PartFieldDefinition); } protected string GetDisplayShapeType(string shapeType, BuildFieldDisplayContext context) { var displayMode = context.PartFieldDefinition.DisplayMode(); return !String.IsNullOrEmpty(displayMode) ? shapeType + DisplaySeparator + displayMode : shapeType; } protected string GetDisplayShapeType(BuildFieldDisplayContext context) { return GetDisplayShapeType(typeof(TField).Name, context); } private void BuildPrefix(ContentTypePartDefinition typePartDefinition, ContentPartFieldDefinition partFieldDefinition, string htmlFieldPrefix) { Prefix = typePartDefinition.Name + "." + partFieldDefinition.Name; if (!String.IsNullOrEmpty(htmlFieldPrefix)) { Prefix = htmlFieldPrefix + "." + Prefix; } } } }
44.761905
227
0.603419
[ "BSD-3-Clause" ]
Ermesx/OrchardCore
src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/ContentFieldDisplayDriver.cs
13,160
C#
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("de375180-0f6f-40c5-9dd4-3a27e2559d5d")] [assembly: InternalsVisibleTo("Akka.Remote.TestKit.Tests")]
45.16
87
0.661647
[ "Apache-2.0" ]
Aaronontheweb/akka.net
src/core/Akka.Remote.TestKit/Properties/AssemblyInfo.cs
1,131
C#
namespace Library.Data.Models { using Library.Data.Common.Models; public class Favorite : BaseDeletableModel<int> { public string UserId { get; set; } public ApplicationUser User { get; set; } public int BookId { get; set; } public Book Book { get; set; } } }
19.5625
51
0.607029
[ "MIT" ]
maria-tananska/Library
Data/Library.Data.Models/Favorite.cs
315
C#
#define TI_DEBUG_PRINT //----------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All Rights Reserved. // Copyright by the contributors to the Dafny Project // SPDX-License-Identifier: MIT // //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Diagnostics.Contracts; using Microsoft.Boogie; namespace Microsoft.Dafny { public class Resolver { readonly BuiltIns builtIns; ErrorReporter reporter; ModuleSignature moduleInfo = null; private bool RevealedInScope(Declaration d) { Contract.Requires(d != null); Contract.Requires(moduleInfo != null); Contract.Requires(moduleInfo.VisibilityScope != null); return useCompileSignatures || d.IsRevealedInScope(moduleInfo.VisibilityScope); } private bool VisibleInScope(Declaration d) { Contract.Requires(d != null); Contract.Requires(moduleInfo != null); Contract.Requires(moduleInfo.VisibilityScope != null); return useCompileSignatures || d.IsVisibleInScope(moduleInfo.VisibilityScope); } FreshIdGenerator defaultTempVarIdGenerator; string FreshTempVarName(string prefix, ICodeContext context) { var decl = context as Declaration; if (decl != null) { return decl.IdGenerator.FreshId(prefix); } // TODO(wuestholz): Is the following code ever needed? if (defaultTempVarIdGenerator == null) { defaultTempVarIdGenerator = new FreshIdGenerator(); } return defaultTempVarIdGenerator.FreshId(prefix); } interface IAmbiguousThing<Thing> { /// <summary> /// Returns a plural number of non-null Thing's /// </summary> ISet<Thing> Pool { get; } } class AmbiguousThingHelper<Thing> where Thing : class { public static Thing Create(ModuleDefinition m, Thing a, Thing b, IEqualityComparer<Thing> eq, out ISet<Thing> s) { Contract.Requires(a != null); Contract.Requires(b != null); Contract.Requires(eq != null); Contract.Ensures(Contract.Result<Thing>() != null || (Contract.ValueAtReturn(out s) != null || 2 <= Contract.ValueAtReturn(out s).Count)); s = null; if (eq.Equals(a, b)) { return a; } ISet<Thing> sa = a is IAmbiguousThing<Thing> ? ((IAmbiguousThing<Thing>)a).Pool : new HashSet<Thing>() {a}; ISet<Thing> sb = b is IAmbiguousThing<Thing> ? ((IAmbiguousThing<Thing>)b).Pool : new HashSet<Thing>() {b}; var union = new HashSet<Thing>(sa.Union(sb, eq)); if (sa.Count == union.Count) { // sb is a subset of sa return a; } else if (sb.Count == union.Count) { // sa is a subset of sb return b; } else { s = union; Contract.Assert(2 <= s.Count); return null; } } public static string Name(ISet<Thing> s, Func<Thing, string> name) { Contract.Requires(s != null); Contract.Requires(s.Count != 0); string nm = null; foreach (var thing in s) { string n = name(thing); if (nm == null) { nm = n; } else { nm += "/" + n; } } return nm; } public static string ModuleNames(IAmbiguousThing<Thing> amb, Func<Thing, string> moduleName) { Contract.Requires(amb != null); Contract.Ensures(Contract.Result<string>() != null); string nm = null; foreach (var d in amb.Pool) { if (nm == null) { nm = moduleName(d); } else { nm += ", " + moduleName(d); } } return nm; } } public class AmbiguousTopLevelDecl : TopLevelDecl, IAmbiguousThing<TopLevelDecl> // only used with "classes" { public static TopLevelDecl Create(ModuleDefinition m, TopLevelDecl a, TopLevelDecl b) { ISet<TopLevelDecl> s; var t = AmbiguousThingHelper<TopLevelDecl>.Create(m, a, b, new Eq(), out s); return t ?? new AmbiguousTopLevelDecl(m, AmbiguousThingHelper<TopLevelDecl>.Name(s, tld => tld.Name), s); } class Eq : IEqualityComparer<TopLevelDecl> { public bool Equals(TopLevelDecl d0, TopLevelDecl d1) { // We'd like to resolve any AliasModuleDecl to whatever module they refer to. // It seems that the only way to do that is to look at alias.Signature.ModuleDef, // but that is a ModuleDefinition, which is not a TopLevelDecl. Therefore, we // convert to a ModuleDefinition anything that might refer to something that an // AliasModuleDecl can refer to; this is AliasModuleDecl and LiteralModuleDecl. object a = d0 is ModuleDecl ? ((ModuleDecl)d0).Dereference() : d0; object b = d1 is ModuleDecl ? ((ModuleDecl)d1).Dereference() : d1; return a == b; } public int GetHashCode(TopLevelDecl d) { object a = d is ModuleDecl ? ((ModuleDecl)d).Dereference() : d; return a.GetHashCode(); } } public override string WhatKind { get { return Pool.First().WhatKind; } } readonly ISet<TopLevelDecl> Pool = new HashSet<TopLevelDecl>(); ISet<TopLevelDecl> IAmbiguousThing<TopLevelDecl>.Pool { get { return Pool; } } private AmbiguousTopLevelDecl(ModuleDefinition m, string name, ISet<TopLevelDecl> pool) : base(pool.First().tok, name, m, new List<TypeParameter>(), null, false) { Contract.Requires(name != null); Contract.Requires(pool != null && 2 <= pool.Count); Pool = pool; } public string ModuleNames() { return AmbiguousThingHelper<TopLevelDecl>.ModuleNames(this, d => d.EnclosingModuleDefinition.Name); } } class AmbiguousMemberDecl : MemberDecl, IAmbiguousThing<MemberDecl> // only used with "classes" { public static MemberDecl Create(ModuleDefinition m, MemberDecl a, MemberDecl b) { ISet<MemberDecl> s; var t = AmbiguousThingHelper<MemberDecl>.Create(m, a, b, new Eq(), out s); return t ?? new AmbiguousMemberDecl(m, AmbiguousThingHelper<MemberDecl>.Name(s, member => member.Name), s); } class Eq : IEqualityComparer<MemberDecl> { public bool Equals(MemberDecl d0, MemberDecl d1) { return d0 == d1; } public int GetHashCode(MemberDecl d) { return d.GetHashCode(); } } public override string WhatKind { get { return Pool.First().WhatKind; } } readonly ISet<MemberDecl> Pool = new HashSet<MemberDecl>(); ISet<MemberDecl> IAmbiguousThing<MemberDecl>.Pool { get { return Pool; } } private AmbiguousMemberDecl(ModuleDefinition m, string name, ISet<MemberDecl> pool) : base(pool.First().tok, name, true, pool.First().IsGhost, null, false) { Contract.Requires(name != null); Contract.Requires(pool != null && 2 <= pool.Count); Pool = pool; } public string ModuleNames() { return AmbiguousThingHelper<MemberDecl>.ModuleNames(this, d => d.EnclosingClass.EnclosingModuleDefinition.Name); } } readonly HashSet<RevealableTypeDecl> revealableTypes = new HashSet<RevealableTypeDecl>(); //types that have been seen by the resolver - used for constraining type inference during exports readonly Dictionary<TopLevelDeclWithMembers, Dictionary<string, MemberDecl>> classMembers = new Dictionary<TopLevelDeclWithMembers, Dictionary<string, MemberDecl>>(); readonly Dictionary<DatatypeDecl, Dictionary<string, DatatypeCtor>> datatypeCtors = new Dictionary<DatatypeDecl, Dictionary<string, DatatypeCtor>>(); enum ValuetypeVariety { Bool = 0, Int, Real, BigOrdinal, Bitvector, Map, IMap, None } // note, these are ordered, so they can be used as indices into valuetypeDecls readonly ValuetypeDecl[] valuetypeDecls; private Dictionary<TypeParameter, Type> SelfTypeSubstitution; readonly Graph<ModuleDecl> dependencies = new Graph<ModuleDecl>(); private ModuleSignature systemNameInfo = null; private bool useCompileSignatures = false; private List<IRewriter> rewriters; private RefinementTransformer refinementTransformer; public Resolver(Program prog) { Contract.Requires(prog != null); builtIns = prog.BuiltIns; reporter = prog.reporter; // Map#Items relies on the two destructors for 2-tuples builtIns.TupleType(Token.NoToken, 2, true); // Several methods and fields rely on 1-argument arrow types builtIns.CreateArrowTypeDecl(1); valuetypeDecls = new ValuetypeDecl[] { new ValuetypeDecl("bool", builtIns.SystemModule, 0, t => t.IsBoolType, typeArgs => Type.Bool), new ValuetypeDecl("int", builtIns.SystemModule, 0, t => t.IsNumericBased(Type.NumericPersuasion.Int), typeArgs => Type.Int), new ValuetypeDecl("real", builtIns.SystemModule, 0, t => t.IsNumericBased(Type.NumericPersuasion.Real), typeArgs => Type.Real), new ValuetypeDecl("ORDINAL", builtIns.SystemModule, 0, t => t.IsBigOrdinalType, typeArgs => Type.BigOrdinal), new ValuetypeDecl("_bv", builtIns.SystemModule, 0, t => t.IsBitVectorType, null), // "_bv" represents a family of classes, so no typeTester or type creator is supplied new ValuetypeDecl("map", builtIns.SystemModule, 2, t => t.IsMapType, typeArgs => new MapType(true, typeArgs[0], typeArgs[1])), new ValuetypeDecl("imap", builtIns.SystemModule, 2, t => t.IsIMapType, typeArgs => new MapType(false, typeArgs[0], typeArgs[1])) }; builtIns.SystemModule.TopLevelDecls.AddRange(valuetypeDecls); // Resolution error handling relies on being able to get to the 0-tuple declaration builtIns.TupleType(Token.NoToken, 0, true); // Populate the members of the basic types var floor = new SpecialField(Token.NoToken, "Floor", SpecialField.ID.Floor, null, false, false, false, Type.Int, null); floor.AddVisibilityScope(prog.BuiltIns.SystemModule.VisibilityScope, false); valuetypeDecls[(int)ValuetypeVariety.Real].Members.Add(floor.Name, floor); var isLimit = new SpecialField(Token.NoToken, "IsLimit", SpecialField.ID.IsLimit, null, false, false, false, Type.Bool, null); isLimit.AddVisibilityScope(prog.BuiltIns.SystemModule.VisibilityScope, false); valuetypeDecls[(int)ValuetypeVariety.BigOrdinal].Members.Add(isLimit.Name, isLimit); var isSucc = new SpecialField(Token.NoToken, "IsSucc", SpecialField.ID.IsSucc, null, false, false, false, Type.Bool, null); isSucc.AddVisibilityScope(prog.BuiltIns.SystemModule.VisibilityScope, false); valuetypeDecls[(int)ValuetypeVariety.BigOrdinal].Members.Add(isSucc.Name, isSucc); var limitOffset = new SpecialField(Token.NoToken, "Offset", SpecialField.ID.Offset, null, false, false, false, Type.Int, null); limitOffset.AddVisibilityScope(prog.BuiltIns.SystemModule.VisibilityScope, false); valuetypeDecls[(int)ValuetypeVariety.BigOrdinal].Members.Add(limitOffset.Name, limitOffset); builtIns.ORDINAL_Offset = limitOffset; var isNat = new SpecialField(Token.NoToken, "IsNat", SpecialField.ID.IsNat, null, false, false, false, Type.Bool, null); isNat.AddVisibilityScope(prog.BuiltIns.SystemModule.VisibilityScope, false); valuetypeDecls[(int)ValuetypeVariety.BigOrdinal].Members.Add(isNat.Name, isNat); // Add "Keys", "Values", and "Items" to map, imap foreach (var typeVariety in new[] {ValuetypeVariety.Map, ValuetypeVariety.IMap}) { var vtd = valuetypeDecls[(int)typeVariety]; var isFinite = typeVariety == ValuetypeVariety.Map; var r = new SetType(isFinite, new UserDefinedType(vtd.TypeArgs[0])); var keys = new SpecialField(Token.NoToken, "Keys", SpecialField.ID.Keys, null, false, false, false, r, null); r = new SetType(isFinite, new UserDefinedType(vtd.TypeArgs[1])); var values = new SpecialField(Token.NoToken, "Values", SpecialField.ID.Values, null, false, false, false, r, null); var gt = vtd.TypeArgs.ConvertAll(tp => (Type)new UserDefinedType(tp)); var dt = builtIns.TupleType(Token.NoToken, 2, true); var tupleType = new UserDefinedType(Token.NoToken, dt.Name, dt, gt); r = new SetType(isFinite, tupleType); var items = new SpecialField(Token.NoToken, "Items", SpecialField.ID.Items, null, false, false, false, r, null); foreach (var memb in new[] {keys, values, items}) { memb.EnclosingClass = vtd; memb.AddVisibilityScope(prog.BuiltIns.SystemModule.VisibilityScope, false); vtd.Members.Add(memb.Name, memb); } } // The result type of the following bitvector methods is the type of the bitvector itself. However, we're representing all bitvector types as // a family of types rolled up in one ValuetypeDecl. Therefore, we use the special SelfType as the result type. List<Formal> formals = new List<Formal> {new Formal(Token.NoToken, "w", Type.Nat(), true, false, false)}; var rotateLeft = new SpecialFunction(Token.NoToken, "RotateLeft", prog.BuiltIns.SystemModule, false, false, new List<TypeParameter>(), formals, new SelfType(), new List<AttributedExpression>(), new List<FrameExpression>(), new List<AttributedExpression>(), new Specification<Expression>(new List<Expression>(), null), null, null, null); rotateLeft.EnclosingClass = valuetypeDecls[(int)ValuetypeVariety.Bitvector]; rotateLeft.AddVisibilityScope(prog.BuiltIns.SystemModule.VisibilityScope, false); valuetypeDecls[(int)ValuetypeVariety.Bitvector].Members.Add(rotateLeft.Name, rotateLeft); formals = new List<Formal> {new Formal(Token.NoToken, "w", Type.Nat(), true, false, false)}; var rotateRight = new SpecialFunction(Token.NoToken, "RotateRight", prog.BuiltIns.SystemModule, false, false, new List<TypeParameter>(), formals, new SelfType(), new List<AttributedExpression>(), new List<FrameExpression>(), new List<AttributedExpression>(), new Specification<Expression>(new List<Expression>(), null), null, null, null); rotateRight.EnclosingClass = valuetypeDecls[(int)ValuetypeVariety.Bitvector]; rotateRight.AddVisibilityScope(prog.BuiltIns.SystemModule.VisibilityScope, false); valuetypeDecls[(int)ValuetypeVariety.Bitvector].Members.Add(rotateRight.Name, rotateRight); } [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(builtIns != null); Contract.Invariant(cce.NonNullElements(dependencies.GetVertices())); Contract.Invariant(cce.NonNullDictionaryAndValues(classMembers) && Contract.ForAll(classMembers.Values, v => cce.NonNullDictionaryAndValues(v))); Contract.Invariant(cce.NonNullDictionaryAndValues(datatypeCtors) && Contract.ForAll(datatypeCtors.Values, v => cce.NonNullDictionaryAndValues(v))); Contract.Invariant(!inBodyInitContext || currentMethod is Constructor); } public ValuetypeDecl AsValuetypeDecl(Type t) { Contract.Requires(t != null); foreach (var vtd in valuetypeDecls) { if (vtd.IsThisType(t)) { return vtd; } } return null; } /// <summary> /// Check that now two modules that are being compiled have the same CompileName. /// /// This could happen if they are given the same name using the 'extern' declaration modifier. /// </summary> /// <param name="prog">The Dafny program being compiled.</param> void CheckDupModuleNames(Program prog) { // Check that none of the modules have the same CompileName. Dictionary<string, ModuleDefinition> compileNameMap = new Dictionary<string, ModuleDefinition>(); foreach (ModuleDefinition m in prog.CompileModules) { if (m.IsAbstract) { // the purpose of an abstract module is to skip compilation continue; } string compileName = m.CompileName; ModuleDefinition priorModDef; if (compileNameMap.TryGetValue(compileName, out priorModDef)) { reporter.Error(MessageSource.Resolver, m.tok, "Modules '{0}' and '{1}' both have CompileName '{2}'.", priorModDef.tok.val, m.tok.val, compileName); } else { compileNameMap.Add(compileName, m); } } } public void ResolveProgram(Program prog) { Contract.Requires(prog != null); Type.ResetScopes(); Type.EnableScopes(); var origErrorCount = reporter.Count(ErrorLevel.Error); //TODO: This is used further below, but not in the >0 comparisons in the next few lines. Is that right? var bindings = new ModuleBindings(null); var b = BindModuleNames(prog.DefaultModuleDef, bindings); bindings.BindName(prog.DefaultModule.Name, prog.DefaultModule, b); if (reporter.Count(ErrorLevel.Error) > 0) { return; } // if there were errors, then the implict ModuleBindings data structure invariant // is violated, so Processing dependencies will not succeed. ProcessDependencies(prog.DefaultModule, b, dependencies); // check for cycles in the import graph foreach (var cycle in dependencies.AllCycles()) { var cy = Util.Comma(" -> ", cycle, m => m.Name); reporter.Error(MessageSource.Resolver, cycle[0], "module definition contains a cycle (note: parent modules implicitly depend on submodules): {0}", cy); } if (reporter.Count(ErrorLevel.Error) > 0) { return; } // give up on trying to resolve anything else // fill in module heights List<ModuleDecl> sortedDecls = dependencies.TopologicallySortedComponents(); int h = 0; foreach (ModuleDecl md in sortedDecls) { md.Height = h; if (md is LiteralModuleDecl) { var mdef = ((LiteralModuleDecl)md).ModuleDef; mdef.Height = h; prog.ModuleSigs.Add(mdef, null); } h++; } rewriters = new List<IRewriter>(); refinementTransformer = new RefinementTransformer(prog); rewriters.Add(refinementTransformer); rewriters.Add(new AutoContractsRewriter(reporter, builtIns)); rewriters.Add(new OpaqueFunctionRewriter(this.reporter)); rewriters.Add(new AutoReqFunctionRewriter(this.reporter)); rewriters.Add(new TimeLimitRewriter(reporter)); rewriters.Add(new ForallStmtRewriter(reporter)); rewriters.Add(new ProvideRevealAllRewriter(this.reporter)); if (DafnyOptions.O.AutoTriggers) { rewriters.Add(new QuantifierSplittingRewriter(reporter)); rewriters.Add(new TriggerGeneratingRewriter(reporter)); } rewriters.Add(new InductionRewriter(reporter)); systemNameInfo = RegisterTopLevelDecls(prog.BuiltIns.SystemModule, false); prog.CompileModules.Add(prog.BuiltIns.SystemModule); RevealAllInScope(prog.BuiltIns.SystemModule.TopLevelDecls, systemNameInfo.VisibilityScope); ResolveValuetypeDecls(); // The SystemModule is constructed with all its members already being resolved. Except for // the non-null type corresponding to class types. They are resolved here: var systemModuleClassesWithNonNullTypes = new List<TopLevelDecl>( prog.BuiltIns.SystemModule.TopLevelDecls.Where(d => d is ClassDecl && ((ClassDecl)d).NonNullTypeDecl != null)); foreach (var cl in systemModuleClassesWithNonNullTypes) { var d = ((ClassDecl)cl).NonNullTypeDecl; allTypeParameters.PushMarker(); ResolveTypeParameters(d.TypeArgs, true, d); ResolveType(d.tok, d.Rhs, d, ResolveTypeOptionEnum.AllowPrefix, d.TypeArgs); allTypeParameters.PopMarker(); } ResolveTopLevelDecls_Core(systemModuleClassesWithNonNullTypes, new Graph<IndDatatypeDecl>(), new Graph<CoDatatypeDecl>()); var compilationModuleClones = new Dictionary<ModuleDefinition, ModuleDefinition>(); foreach (var decl in sortedDecls) { if (decl is LiteralModuleDecl) { // The declaration is a literal module, so it has members and such that we need // to resolve. First we do refinement transformation. Then we construct the signature // of the module. This is the public, externally visible signature. Then we add in // everything that the system defines, as well as any "import" (i.e. "opened" modules) // directives (currently not supported, but this is where we would do it.) This signature, // which is only used while resolving the members of the module is stored in the (basically) // global variable moduleInfo. Then the signatures of the module members are resolved, followed // by the bodies. var literalDecl = (LiteralModuleDecl)decl; var m = literalDecl.ModuleDef; var errorCount = reporter.Count(ErrorLevel.Error); if (m.RefinementQId != null) { ModuleDecl md = ResolveModuleQualifiedId(m.RefinementQId.Root, m.RefinementQId, reporter); m.RefinementQId.Set(md); // If module is not found, md is null and an error message has been emitted } foreach (var r in rewriters) { r.PreResolve(m); } literalDecl.Signature = RegisterTopLevelDecls(m, true); literalDecl.Signature.Refines = refinementTransformer.RefinedSig; var sig = literalDecl.Signature; // set up environment var preResolveErrorCount = reporter.Count(ErrorLevel.Error); ResolveModuleExport(literalDecl, sig); var good = ResolveModuleDefinition(m, sig); if (good && reporter.Count(ErrorLevel.Error) == preResolveErrorCount) { // Check that the module export gives a self-contained view of the module. CheckModuleExportConsistency(m); } var tempVis = new VisibilityScope(); tempVis.Augment(sig.VisibilityScope); tempVis.Augment(systemNameInfo.VisibilityScope); Type.PushScope(tempVis); prog.ModuleSigs[m] = sig; foreach (var r in rewriters) { if (!good || reporter.Count(ErrorLevel.Error) != preResolveErrorCount) { break; } r.PostResolve(m); } if (good && reporter.Count(ErrorLevel.Error) == errorCount) { m.SuccessfullyResolved = true; } Type.PopScope(tempVis); if (reporter.Count(ErrorLevel.Error) == errorCount && !m.IsAbstract) { // compilation should only proceed if everything is good, including the signature (which preResolveErrorCount does not include); CompilationCloner cloner = new CompilationCloner(compilationModuleClones); var nw = cloner.CloneModuleDefinition(m, m.CompileName + "_Compile"); compilationModuleClones.Add(m, nw); var oldErrorsOnly = reporter.ErrorsOnly; reporter.ErrorsOnly = true; // turn off warning reporting for the clone // Next, compute the compile signature Contract.Assert(!useCompileSignatures); useCompileSignatures = true; // set Resolver-global flag to indicate that Signatures should be followed to their CompiledSignature Type.DisableScopes(); var compileSig = RegisterTopLevelDecls(nw, true); compileSig.Refines = refinementTransformer.RefinedSig; sig.CompileSignature = compileSig; foreach (var exportDecl in sig.ExportSets.Values) { exportDecl.Signature.CompileSignature = cloner.CloneModuleSignature(exportDecl.Signature, compileSig); } // Now we're ready to resolve the cloned module definition, using the compile signature ResolveModuleDefinition(nw, compileSig); prog.CompileModules.Add(nw); useCompileSignatures = false; // reset the flag Type.EnableScopes(); reporter.ErrorsOnly = oldErrorsOnly; } } else if (decl is AliasModuleDecl alias) { // resolve the path ModuleSignature p; if (ResolveExport(alias, alias.EnclosingModuleDefinition, alias.TargetQId, alias.Exports, out p, reporter)) { if (alias.Signature == null) { alias.Signature = p; } } else { alias.Signature = new ModuleSignature(); // there was an error, give it a valid but empty signature } } else if (decl is AbstractModuleDecl abs) { ModuleSignature p; if (ResolveExport(abs, abs.EnclosingModuleDefinition, abs.QId, abs.Exports, out p, reporter)) { abs.OriginalSignature = p; abs.Signature = MakeAbstractSignature(p, abs.FullCompileName, abs.Height, prog.ModuleSigs, compilationModuleClones); } else { abs.Signature = new ModuleSignature(); // there was an error, give it a valid but empty signature } } else if (decl is ModuleExportDecl) { ((ModuleExportDecl)decl).SetupDefaultSignature(); Contract.Assert(decl.Signature != null); Contract.Assert(decl.Signature.VisibilityScope != null); } else { Contract.Assert(false); // Unknown kind of ModuleDecl } Contract.Assert(decl.Signature != null); } if (reporter.Count(ErrorLevel.Error) != origErrorCount) { // do nothing else return; } // compute IsRecursive bit for mutually recursive functions and methods foreach (var module in prog.Modules()) { foreach (var clbl in ModuleDefinition.AllCallables(module.TopLevelDecls)) { if (clbl is Function) { var fn = (Function)clbl; if (!fn.IsRecursive) { // note, self-recursion has already been determined int n = module.CallGraph.GetSCCSize(fn); if (2 <= n) { // the function is mutually recursive (note, the SCC does not determine self recursion) fn.IsRecursive = true; } } if (fn.IsRecursive && fn is ExtremePredicate) { // this means the corresponding prefix predicate is also recursive var prefixPred = ((ExtremePredicate)fn).PrefixPredicate; if (prefixPred != null) { prefixPred.IsRecursive = true; } } } else { var m = (Method)clbl; if (!m.IsRecursive) { // note, self-recursion has already been determined int n = module.CallGraph.GetSCCSize(m); if (2 <= n) { // the function is mutually recursive (note, the SCC does not determine self recursion) m.IsRecursive = true; } } } } foreach (var r in rewriters) { r.PostCyclicityResolve(module); } } // fill in default decreases clauses: for functions and methods, and for loops FillInDefaultDecreasesClauses(prog); foreach (var module in prog.Modules()) { foreach (var clbl in ModuleDefinition.AllItersAndCallables(module.TopLevelDecls)) { Statement body = null; if (clbl is Method) { body = ((Method)clbl).Body; } else if (clbl is IteratorDecl) { body = ((IteratorDecl)clbl).Body; } if (body != null) { var c = new FillInDefaultLoopDecreases_Visitor(this, clbl); c.Visit(body); } } } foreach (var module in prog.Modules()) { foreach (var iter in ModuleDefinition.AllIteratorDecls(module.TopLevelDecls)) { reporter.Info(MessageSource.Resolver, iter.tok, Printer.IteratorClassToString(iter)); } } foreach (var module in prog.Modules()) { foreach (var r in rewriters) { r.PostDecreasesResolve(module); } } // fill in other additional information foreach (var module in prog.Modules()) { foreach (var clbl in ModuleDefinition.AllItersAndCallables(module.TopLevelDecls)) { Statement body = null; if (clbl is ExtremeLemma) { body = ((ExtremeLemma)clbl).PrefixLemma.Body; } else if (clbl is Method) { body = ((Method)clbl).Body; } else if (clbl is IteratorDecl) { body = ((IteratorDecl)clbl).Body; } if (body != null) { var c = new ReportOtherAdditionalInformation_Visitor(this); c.Visit(body); } } } // Determine, for each function, whether someone tries to adjust its fuel parameter foreach (var module in prog.Modules()) { CheckForFuelAdjustments(module.tok, module.Attributes, module); foreach (var clbl in ModuleDefinition.AllItersAndCallables(module.TopLevelDecls)) { Statement body = null; if (clbl is Method) { body = ((Method)clbl).Body; CheckForFuelAdjustments(clbl.Tok, ((Method)clbl).Attributes, module); } else if (clbl is IteratorDecl) { body = ((IteratorDecl)clbl).Body; CheckForFuelAdjustments(clbl.Tok, ((IteratorDecl)clbl).Attributes, module); } else if (clbl is Function) { CheckForFuelAdjustments(clbl.Tok, ((Function)clbl).Attributes, module); var c = new FuelAdjustment_Visitor(this); var bodyExpr = ((Function)clbl).Body; if (bodyExpr != null) { c.Visit(bodyExpr, new FuelAdjustment_Context(module)); } } if (body != null) { var c = new FuelAdjustment_Visitor(this); c.Visit(body, new FuelAdjustment_Context(module)); } } } Type.DisableScopes(); CheckDupModuleNames(prog); } void FillInDefaultDecreasesClauses(Program prog) { Contract.Requires(prog != null); foreach (var module in prog.Modules()) { Contract.Assert(Type.GetScope() != null); foreach (var clbl in ModuleDefinition.AllCallables(module.TopLevelDecls)) { ICallable m; string s; if (clbl is ExtremeLemma) { var prefixLemma = ((ExtremeLemma)clbl).PrefixLemma; m = prefixLemma; s = prefixLemma.Name + " "; } else { m = clbl; s = ""; } var anyChangeToDecreases = FillInDefaultDecreases(m, true); if (anyChangeToDecreases || m.InferredDecreases || m is PrefixLemma) { bool showIt = false; if (m is Function) { // show the inferred decreases clause only if it will ever matter, i.e., if the function is recursive showIt = ((Function)m).IsRecursive; } else if (m is PrefixLemma) { // always show the decrease clause, since at the very least it will start with "_k", which the programmer did not write explicitly showIt = true; } else { showIt = ((Method)m).IsRecursive; } if (showIt) { s += "decreases " + Util.Comma(m.Decreases.Expressions, Printer.ExprToString); // Note, in the following line, we use the location information for "clbl", not "m". These // are the same, except in the case where "clbl" is a GreatestLemma and "m" is a prefix lemma. reporter.Info(MessageSource.Resolver, clbl.Tok, s); } } } } } /// <summary> /// Return "true" if this routine makes any change to the decreases clause. If the decreases clause /// starts off essentially empty and a default is provided, then clbl.InferredDecreases is also set /// to true. /// </summary> bool FillInDefaultDecreases(ICallable clbl, bool addPrefixInCoClusters) { Contract.Requires(clbl != null); if (clbl is ExtremePredicate) { // extreme predicates don't have decreases clauses return false; } var anyChangeToDecreases = false; var decr = clbl.Decreases.Expressions; if (decr.Count == 0 || (clbl is PrefixLemma && decr.Count == 1)) { // The default for a function starts with the function's reads clause, if any if (clbl is Function) { var fn = (Function)clbl; if (fn.Reads.Count != 0) { // start the default lexicographic tuple with the reads clause var r = FrameToObjectSet(fn.Reads); decr.Add(AutoGeneratedExpression.Create(r)); anyChangeToDecreases = true; } } // Add one component for each parameter, unless the parameter's type is one that // doesn't appear useful to orderings. if (clbl is Function || clbl is Method) { TopLevelDeclWithMembers enclosingType; if (clbl is Function fc && !fc.IsStatic) { enclosingType = (TopLevelDeclWithMembers)fc.EnclosingClass; } else if (clbl is Method mc && !mc.IsStatic) { enclosingType = (TopLevelDeclWithMembers)mc.EnclosingClass; } else { enclosingType = null; } if (enclosingType != null) { var receiverType = GetThisType(clbl.Tok, enclosingType); if (receiverType.IsOrdered && !receiverType.IsRefType) { var th = new ThisExpr(clbl.Tok) {Type = receiverType}; // resolve here decr.Add(AutoGeneratedExpression.Create(th)); anyChangeToDecreases = true; } } } foreach (var p in clbl.Ins) { if (!(p is ImplicitFormal) && p.Type.IsOrdered) { var ie = new IdentifierExpr(p.tok, p.Name); ie.Var = p; ie.Type = p.Type; // resolve it here decr.Add(AutoGeneratedExpression.Create(ie)); anyChangeToDecreases = true; } } clbl.InferredDecreases = true; // this indicates that finding a default decreases clause was attempted } if (addPrefixInCoClusters && clbl is Function) { var fn = (Function)clbl; switch (fn.CoClusterTarget) { case Function.CoCallClusterInvolvement.None: break; case Function.CoCallClusterInvolvement.IsMutuallyRecursiveTarget: // prefix: decreases 0, clbl.Decreases.Expressions.Insert(0, Expression.CreateIntLiteral(fn.tok, 0)); anyChangeToDecreases = true; break; case Function.CoCallClusterInvolvement.CoRecursiveTargetAllTheWay: // prefix: decreases 1, clbl.Decreases.Expressions.Insert(0, Expression.CreateIntLiteral(fn.tok, 1)); anyChangeToDecreases = true; break; default: Contract.Assume(false); // unexpected case break; } } return anyChangeToDecreases; } public Expression FrameArrowToObjectSet(Expression e, FreshIdGenerator idGen) { Contract.Requires(e != null); Contract.Requires(idGen != null); return FrameArrowToObjectSet(e, idGen, builtIns); } public static Expression FrameArrowToObjectSet(Expression e, FreshIdGenerator idGen, BuiltIns builtIns) { Contract.Requires(e != null); Contract.Requires(idGen != null); Contract.Requires(builtIns != null); var arrTy = e.Type.AsArrowType; if (arrTy != null) { var bvars = new List<BoundVar>(); var bexprs = new List<Expression>(); foreach (var t in arrTy.Args) { var bv = new BoundVar(e.tok, idGen.FreshId("_x"), t); bvars.Add(bv); bexprs.Add(new IdentifierExpr(e.tok, bv.Name) {Type = bv.Type, Var = bv}); } var oVar = new BoundVar(e.tok, idGen.FreshId("_o"), builtIns.ObjectQ()); var obj = new IdentifierExpr(e.tok, oVar.Name) {Type = oVar.Type, Var = oVar}; bvars.Add(oVar); return new SetComprehension(e.tok, true, bvars, new BinaryExpr(e.tok, BinaryExpr.Opcode.In, obj, new ApplyExpr(e.tok, e, bexprs) { Type = new SetType(true, builtIns.ObjectQ()) }) { ResolvedOp = BinaryExpr.ResolvedOpcode.InSet, Type = Type.Bool }, obj, null) { Type = new SetType(true, builtIns.ObjectQ()) }; } else { return e; } } public Expression FrameToObjectSet(List<FrameExpression> fexprs) { Contract.Requires(fexprs != null); Contract.Ensures(Contract.Result<Expression>() != null); List<Expression> sets = new List<Expression>(); List<Expression> singletons = null; var idGen = new FreshIdGenerator(); foreach (FrameExpression fe in fexprs) { Contract.Assert(fe != null); if (fe.E is WildcardExpr) { // drop wildcards altogether } else { Expression e = FrameArrowToObjectSet(fe.E, idGen); // keep only fe.E, drop any fe.Field designation Contract.Assert(e.Type != null); // should have been resolved already var eType = e.Type.NormalizeExpand(); if (eType.IsRefType) { // e represents a singleton set if (singletons == null) { singletons = new List<Expression>(); } singletons.Add(e); } else if (eType is SeqType || eType is MultiSetType) { // e represents a sequence or multiset // Add: set x :: x in e var bv = new BoundVar(e.tok, idGen.FreshId("_s2s_"), ((CollectionType)eType).Arg); var bvIE = new IdentifierExpr(e.tok, bv.Name); bvIE.Var = bv; // resolve here bvIE.Type = bv.Type; // resolve here var sInE = new BinaryExpr(e.tok, BinaryExpr.Opcode.In, bvIE, e); if (eType is SeqType) { sInE.ResolvedOp = BinaryExpr.ResolvedOpcode.InSeq; // resolve here } else { sInE.ResolvedOp = BinaryExpr.ResolvedOpcode.InMultiSet; // resolve here } sInE.Type = Type.Bool; // resolve here var s = new SetComprehension(e.tok, true, new List<BoundVar>() {bv}, sInE, bvIE, null); s.Type = new SetType(true, builtIns.ObjectQ()); // resolve here sets.Add(s); } else { // e is already a set Contract.Assert(eType is SetType); sets.Add(e); } } } if (singletons != null) { Expression display = new SetDisplayExpr(singletons[0].tok, true, singletons); display.Type = new SetType(true, builtIns.ObjectQ()); // resolve here sets.Add(display); } if (sets.Count == 0) { Expression emptyset = new SetDisplayExpr(Token.NoToken, true, new List<Expression>()); emptyset.Type = new SetType(true, builtIns.ObjectQ()); // resolve here return emptyset; } else { Expression s = sets[0]; for (int i = 1; i < sets.Count; i++) { BinaryExpr union = new BinaryExpr(s.tok, BinaryExpr.Opcode.Add, s, sets[i]); union.ResolvedOp = BinaryExpr.ResolvedOpcode.Union; // resolve here union.Type = new SetType(true, builtIns.ObjectQ()); // resolve here s = union; } return s; } } private void ResolveValuetypeDecls() { moduleInfo = systemNameInfo; foreach (var valueTypeDecl in valuetypeDecls) { foreach (var kv in valueTypeDecl.Members) { if (kv.Value is Function) { ResolveFunctionSignature((Function)kv.Value); } else if (kv.Value is Method) { ResolveMethodSignature((Method)kv.Value); } } } } /// <summary> /// Resolves the module definition. /// A return code of "false" is an indication of an error that may or may not have /// been reported in an error message. So, in order to figure out if m was successfully /// resolved, a caller has to check for both a change in error count and a "false" /// return value. /// </summary> private bool ResolveModuleDefinition(ModuleDefinition m, ModuleSignature sig, bool isAnExport = false) { Contract.Requires(AllTypeConstraints.Count == 0); Contract.Ensures(AllTypeConstraints.Count == 0); sig.VisibilityScope.Augment(systemNameInfo.VisibilityScope); // make sure all imported modules were successfully resolved foreach (var d in m.TopLevelDecls) { if (d is AliasModuleDecl || d is AbstractModuleDecl) { ModuleSignature importSig; if (d is AliasModuleDecl) { var alias = (AliasModuleDecl)d; importSig = alias.TargetQId.Root != null ? alias.TargetQId.Root.Signature : alias.Signature; } else { importSig = ((AbstractModuleDecl)d).OriginalSignature; } if (importSig.ModuleDef == null || !importSig.ModuleDef.SuccessfullyResolved) { if (!m.IsEssentiallyEmptyModuleBody()) { // say something only if this will cause any testing to be omitted reporter.Error(MessageSource.Resolver, d, "not resolving module '{0}' because there were errors in resolving its import '{1}'", m.Name, d.Name); } return false; } } else if (d is LiteralModuleDecl) { var nested = (LiteralModuleDecl)d; if (!nested.ModuleDef.SuccessfullyResolved) { if (!m.IsEssentiallyEmptyModuleBody()) { // say something only if this will cause any testing to be omitted reporter.Error(MessageSource.Resolver, nested, "not resolving module '{0}' because there were errors in resolving its nested module '{1}'", m.Name, nested.Name); } return false; } } } // resolve var oldModuleInfo = moduleInfo; moduleInfo = MergeSignature(sig, systemNameInfo); Type.PushScope(moduleInfo.VisibilityScope); ResolveOpenedImports(moduleInfo, m, useCompileSignatures, this); // opened imports do not persist var datatypeDependencies = new Graph<IndDatatypeDecl>(); var codatatypeDependencies = new Graph<CoDatatypeDecl>(); int prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveTopLevelDecls_Signatures(m, sig, m.TopLevelDecls, datatypeDependencies, codatatypeDependencies); Contract.Assert(AllTypeConstraints.Count == 0); // signature resolution does not add any type constraints ResolveAttributes(m.Attributes, m, new ResolveOpts(new NoContext(m.EnclosingModule), false)); // Must follow ResolveTopLevelDecls_Signatures, in case attributes refer to members SolveAllTypeConstraints(); // solve any type constraints entailed by the attributes if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { ResolveTopLevelDecls_Core(m.TopLevelDecls, datatypeDependencies, codatatypeDependencies, isAnExport); } Type.PopScope(moduleInfo.VisibilityScope); moduleInfo = oldModuleInfo; return true; } // Resolve the exports and detect cycles. private void ResolveModuleExport(LiteralModuleDecl literalDecl, ModuleSignature sig) { ModuleDefinition m = literalDecl.ModuleDef; literalDecl.DefaultExport = sig; Graph<ModuleExportDecl> exportDependencies = new Graph<ModuleExportDecl>(); foreach (TopLevelDecl toplevel in m.TopLevelDecls) { if (toplevel is ModuleExportDecl) { ModuleExportDecl d = (ModuleExportDecl)toplevel; exportDependencies.AddVertex(d); foreach (IToken s in d.Extends) { ModuleExportDecl extend; if (sig.ExportSets.TryGetValue(s.val, out extend)) { d.ExtendDecls.Add(extend); exportDependencies.AddEdge(d, extend); } else { reporter.Error(MessageSource.Resolver, s, s.val + " must be an export of " + m.Name + " to be extended"); } } } } // detect cycles in the extend var cycleError = false; foreach (var cycle in exportDependencies.AllCycles()) { var cy = Util.Comma(" -> ", cycle, c => c.Name); reporter.Error(MessageSource.Resolver, cycle[0], "module export contains a cycle: {0}", cy); cycleError = true; } if (cycleError) { return; } // give up on trying to resolve anything else // fill in the exports for the extends. List<ModuleExportDecl> sortedExportDecls = exportDependencies.TopologicallySortedComponents(); ModuleExportDecl defaultExport = null; TopLevelDecl defaultClass; sig.TopLevels.TryGetValue("_default", out defaultClass); Contract.Assert(defaultClass is ClassDecl); Contract.Assert(((ClassDecl)defaultClass).IsDefaultClass); defaultClass.AddVisibilityScope(m.VisibilityScope, true); foreach (var d in sortedExportDecls) { defaultClass.AddVisibilityScope(d.ThisScope, true); foreach (var eexports in d.ExtendDecls.Select(e => e.Exports)) { d.Exports.AddRange(eexports); } if (d.ExtendDecls.Count == 0 && d.Exports.Count == 0) { // This is an empty export. This is allowed, but unusual. It could pop up, for example, if // someone temporary comments out everything that the export set provides/reveals. However, // if the name of the export set coincides with something else that's declared at the top // level of the module, then this export declaration is more likely an error--the user probably // forgot the "provides" or "reveals" keyword. Dictionary<string, MemberDecl> members; MemberDecl member; // Top-level functions and methods are actually recorded as members of the _default class. We look up the // export-set name there. If the export-set name happens to coincide with some other top-level declaration, // then an error will already have been produced ("duplicate name of top-level declaration"). if (classMembers.TryGetValue((ClassDecl)defaultClass, out members) && members.TryGetValue(d.Name, out member)) { reporter.Warning(MessageSource.Resolver, d.tok, "note, this export set is empty (did you perhaps forget the 'provides' or 'reveals' keyword?)"); } } foreach (ExportSignature export in d.Exports) { // check to see if it is a datatype or a member or // static function or method in the enclosing module or its imports TopLevelDecl tdecl; MemberDecl member; TopLevelDecl cldecl; Declaration decl = null; string name = export.Id; if (export.ClassId != null) { if (!sig.TopLevels.TryGetValue(export.ClassId, out cldecl)) { reporter.Error(MessageSource.Resolver, export.ClassIdTok, "'{0}' is not a top-level type declaration", export.ClassId); continue; } if (cldecl is ClassDecl && ((ClassDecl)cldecl).NonNullTypeDecl != null) { // cldecl is a possibly-null type (syntactically given with a question mark at the end) reporter.Error(MessageSource.Resolver, export.ClassIdTok, "'{0}' is not a type that can declare members", export.ClassId); continue; } if (cldecl is NonNullTypeDecl) { // cldecl was given syntactically like the name of a class, but here it's referring to the corresponding non-null subset type cldecl = cldecl.ViewAsClass; } var mt = cldecl as TopLevelDeclWithMembers; if (mt == null) { reporter.Error(MessageSource.Resolver, export.ClassIdTok, "'{0}' is not a type that can declare members", export.ClassId); continue; } var lmem = mt.Members.FirstOrDefault(l => l.Name == export.Id); if (lmem == null) { reporter.Error(MessageSource.Resolver, export.Tok, "No member '{0}' found in type '{1}'", export.Id, export.ClassId); continue; } decl = lmem; } else if (sig.TopLevels.TryGetValue(name, out tdecl)) { if (tdecl is ClassDecl && ((ClassDecl)tdecl).NonNullTypeDecl != null) { // cldecl is a possibly-null type (syntactically given with a question mark at the end) var nn = ((ClassDecl)tdecl).NonNullTypeDecl; Contract.Assert(nn != null); reporter.Error(MessageSource.Resolver, export.Tok, export.Opaque ? "Type '{1}' can only be revealed, not provided" : "Types '{0}' and '{1}' are exported together, which is accomplished by revealing the name '{0}'", nn.Name, name); continue; } // Member of the enclosing module decl = tdecl; } else if (sig.StaticMembers.TryGetValue(name, out member)) { decl = member; } else if (sig.ExportSets.ContainsKey(name)) { reporter.Error(MessageSource.Resolver, export.Tok, "'{0}' is an export set and cannot be provided/revealed by another export set (did you intend to list it in an \"extends\"?)", name); continue; } else { reporter.Error(MessageSource.Resolver, export.Tok, "'{0}' must be a member of '{1}' to be exported", name, m.Name); continue; } if (!decl.CanBeExported()) { reporter.Error(MessageSource.Resolver, export.Tok, "'{0}' is not a valid export of '{1}'", name, m.Name); continue; } if (!export.Opaque && !decl.CanBeRevealed()) { reporter.Error(MessageSource.Resolver, export.Tok, "'{0}' cannot be revealed in an export. Use \"provides\" instead.", name); continue; } export.Decl = decl; if (decl is NonNullTypeDecl nntd) { nntd.AddVisibilityScope(d.ThisScope, export.Opaque); if (!export.Opaque) { nntd.Class.AddVisibilityScope(d.ThisScope, export.Opaque); // add the anonymous constructor, if any var anonymousConstructor = nntd.Class.Members.Find(mdecl => mdecl.Name == "_ctor"); if (anonymousConstructor != null) { anonymousConstructor.AddVisibilityScope(d.ThisScope, false); } } } else { decl.AddVisibilityScope(d.ThisScope, export.Opaque); } } } foreach (ModuleExportDecl decl in sortedExportDecls) { if (decl.IsDefault) { if (defaultExport == null) { defaultExport = decl; } else { reporter.Error(MessageSource.Resolver, m.tok, "more than one default export set declared in module {0}", m.Name); } } // fill in export signature ModuleSignature signature = decl.Signature; if (signature != null) signature.ModuleDef = m; foreach (var top in sig.TopLevels) { if (!top.Value.CanBeExported() || !top.Value.IsVisibleInScope(signature.VisibilityScope)) { continue; } if (!signature.TopLevels.ContainsKey(top.Key)) { signature.TopLevels.Add(top.Key, top.Value); } if (top.Value is DatatypeDecl && top.Value.IsRevealedInScope(signature.VisibilityScope)) { foreach (var ctor in ((DatatypeDecl)top.Value).Ctors) { if (!signature.Ctors.ContainsKey(ctor.Name)) { signature.Ctors.Add(ctor.Name, new Tuple<DatatypeCtor, bool>(ctor, false)); } } } } foreach (var mem in sig.StaticMembers.Where(t => t.Value.IsVisibleInScope(signature.VisibilityScope) && t.Value.CanBeExported())) { if (!signature.StaticMembers.ContainsKey(mem.Key)) { signature.StaticMembers.Add(mem.Key, (MemberDecl)mem.Value); } } } // set the default export set, if it exists if (defaultExport != null) { literalDecl.DefaultExport = defaultExport.Signature; } else if (sortedExportDecls.Count > 0) { literalDecl.DefaultExport = null; } // final pass to propagate visibility of exported imports var sigs = sortedExportDecls.Select(d => d.Signature).Concat1(sig); foreach (var s in sigs) { foreach (var decl in s.TopLevels) { if (decl.Value is ModuleDecl && !(decl.Value is ModuleExportDecl)) { var modDecl = (ModuleDecl)decl.Value; s.VisibilityScope.Augment(modDecl.AccessibleSignature().VisibilityScope); } } } var exported = new HashSet<Tuple<Declaration, bool>>(); //some decls may not be set due to resolution errors foreach (var e in sortedExportDecls.SelectMany(e => e.Exports).Where(e => e.Decl != null)) { var decl = e.Decl; exported.Add(new Tuple<Declaration, bool>(decl, e.Opaque)); if (!e.Opaque && decl.CanBeRevealed()) { exported.Add(new Tuple<Declaration, bool>(decl, true)); if (decl is NonNullTypeDecl nntd) { exported.Add(new Tuple<Declaration, bool>(nntd.Class, true)); } } if (e.Opaque && (decl is DatatypeDecl || decl is TypeSynonymDecl)) { // Datatypes and type synonyms are marked as _provided when they appear in any provided export. If a // declaration is never provided, then either it isn't visible outside the module at all or its whole // definition is. Datatype and type-synonym declarations undergo some inference from their definitions. // Such inference should not be done for provided declarations, since different views of the module // would then get different inferred properties. decl.Attributes = new Attributes("_provided", new List<Expression>(), decl.Attributes); reporter.Info(MessageSource.Resolver, decl.tok, "{:_provided}"); } } Dictionary<RevealableTypeDecl, bool?> declScopes = new Dictionary<RevealableTypeDecl, bool?>(); Dictionary<RevealableTypeDecl, bool?> modifies = new Dictionary<RevealableTypeDecl, bool?>(); //of all existing types, compute the minimum visibility of them for each exported declaration's //body and signature foreach (var e in exported) { declScopes.Clear(); modifies.Clear(); foreach (var typ in revealableTypes) { declScopes.Add(typ, null); } foreach (var decl in sortedExportDecls) { if (decl.Exports.Exists(ex => ex.Decl == e.Item1 && (e.Item2 || !ex.Opaque))) { //if we are revealed, consider those exports where we are provided as well var scope = decl.Signature.VisibilityScope; foreach (var kv in declScopes) { bool? isOpaque = kv.Value; var typ = kv.Key; if (!typ.AsTopLevelDecl.IsVisibleInScope(scope)) { modifies[typ] = null; continue; } if (isOpaque.HasValue && isOpaque.Value) { //type is visible here, but known-opaque, so do nothing continue; } modifies[typ] = !typ.AsTopLevelDecl.IsRevealedInScope(scope); } foreach (var kv in modifies) { if (!kv.Value.HasValue) { declScopes.Remove(kv.Key); } else { var exvis = declScopes[kv.Key]; if (exvis.HasValue) { declScopes[kv.Key] = exvis.Value || kv.Value.Value; } else { declScopes[kv.Key] = kv.Value; } } } modifies.Clear(); } } VisibilityScope newscope = new VisibilityScope(e.Item1.Name); foreach (var rt in declScopes) { if (!rt.Value.HasValue) continue; rt.Key.AsTopLevelDecl.AddVisibilityScope(newscope, rt.Value.Value); } } } //check for export consistency by resolving internal modules //this should be effect-free, as it only operates on clones private void CheckModuleExportConsistency(ModuleDefinition m) { var oldModuleInfo = moduleInfo; foreach (var top in m.TopLevelDecls) { if (!(top is ModuleExportDecl)) continue; ModuleExportDecl decl = (ModuleExportDecl)top; var prevErrors = reporter.Count(ErrorLevel.Error); foreach (var export in decl.Exports) { if (export.Decl is MemberDecl member) { // For classes and traits, the visibility test is performed on the corresponding non-null type var enclosingType = member.EnclosingClass is ClassDecl cl && cl.NonNullTypeDecl != null ? cl.NonNullTypeDecl : member.EnclosingClass; if (!enclosingType.IsVisibleInScope(decl.Signature.VisibilityScope)) { reporter.Error(MessageSource.Resolver, export.Tok, "Cannot export type member '{0}' without providing its enclosing {1} '{2}'", member.Name, member.EnclosingClass.WhatKind, member.EnclosingClass.Name); } else if (member is Constructor && !member.EnclosingClass.IsRevealedInScope(decl.Signature.VisibilityScope)) { reporter.Error(MessageSource.Resolver, export.Tok, "Cannot export constructor '{0}' without revealing its enclosing {1} '{2}'", member.Name, member.EnclosingClass.WhatKind, member.EnclosingClass.Name); } else if (member is Field && !(member is ConstantField) && !member.EnclosingClass.IsRevealedInScope(decl.Signature.VisibilityScope)) { reporter.Error(MessageSource.Resolver, export.Tok, "Cannot export mutable field '{0}' without revealing its enclosing {1} '{2}'", member.Name, member.EnclosingClass.WhatKind, member.EnclosingClass.Name); } } } var scope = decl.Signature.VisibilityScope; Cloner cloner = new ScopeCloner(scope); var exportView = cloner.CloneModuleDefinition(m, m.Name); if (DafnyOptions.O.DafnyPrintExportedViews.Contains(decl.FullName)) { var wr = Console.Out; wr.WriteLine("/* ===== export set {0}", decl.FullName); var pr = new Printer(wr); pr.PrintTopLevelDecls(exportView.TopLevelDecls, 0, null, null); wr.WriteLine("*/"); } if (reporter.Count(ErrorLevel.Error) != prevErrors) { continue; } reporter = new ErrorReporterWrapper(reporter, String.Format("Raised while checking export set {0}: ", decl.Name)); var testSig = RegisterTopLevelDecls(exportView, true); //testSig.Refines = refinementTransformer.RefinedSig; ResolveModuleDefinition(exportView, testSig, true); var wasError = reporter.Count(ErrorLevel.Error) > 0; reporter = ((ErrorReporterWrapper)reporter).WrappedReporter; if (wasError) { reporter.Error(MessageSource.Resolver, decl.tok, "This export set is not consistent: {0}", decl.Name); } } moduleInfo = oldModuleInfo; } public class ModuleBindings { private ModuleBindings parent; private Dictionary<string, ModuleDecl> modules; private Dictionary<string, ModuleBindings> bindings; public ModuleBindings(ModuleBindings p) { parent = p; modules = new Dictionary<string, ModuleDecl>(); bindings = new Dictionary<string, ModuleBindings>(); } public bool BindName(string name, ModuleDecl subModule, ModuleBindings b) { if (modules.ContainsKey(name)) { return false; } else { modules.Add(name, subModule); bindings.Add(name, b); return true; } } public bool TryLookup(IToken name, out ModuleDecl m) { Contract.Requires(name != null); return TryLookupFilter(name, out m, l => true); } public bool TryLookupFilter(IToken name, out ModuleDecl m, Func<ModuleDecl, bool> filter) { Contract.Requires(name != null); if (modules.TryGetValue(name.val, out m) && filter(m)) { return true; } else if (parent != null) { return parent.TryLookupFilter(name, out m, filter); } else return false; } public IEnumerable<ModuleDecl> ModuleList { get { return modules.Values; } } public ModuleBindings SubBindings(string name) { ModuleBindings v = null; bindings.TryGetValue(name, out v); return v; } } private ModuleBindings BindModuleNames(ModuleDefinition moduleDecl, ModuleBindings parentBindings) { var bindings = new ModuleBindings(parentBindings); // moduleDecl.PrefixNamedModules is a list of pairs like: // A.B.C , module D { ... } // We collect these according to the first component of the prefix, like so: // "A" -> (A.B.C , module D { ... }) var prefixNames = new Dictionary<string, List<Tuple<List<IToken>, LiteralModuleDecl>>>(); foreach (var tup in moduleDecl.PrefixNamedModules) { var id = tup.Item1[0].val; List<Tuple<List<IToken>, LiteralModuleDecl>> prev; if (!prefixNames.TryGetValue(id, out prev)) { prev = new List<Tuple<List<IToken>, LiteralModuleDecl>>(); } prev.Add(tup); prefixNames[id] = prev; } moduleDecl.PrefixNamedModules.Clear(); // First, register all literal modules, and transferring their prefix-named modules downwards foreach (var tld in moduleDecl.TopLevelDecls) { if (tld is LiteralModuleDecl) { var subdecl = (LiteralModuleDecl)tld; // Transfer prefix-named modules downwards into the sub-module List<Tuple<List<IToken>, LiteralModuleDecl>> prefixModules; if (prefixNames.TryGetValue(subdecl.Name, out prefixModules)) { prefixNames.Remove(subdecl.Name); prefixModules = prefixModules.ConvertAll(ShortenPrefix); } else { prefixModules = null; } BindModuleName_LiteralModuleDecl(subdecl, prefixModules, bindings); } } // Next, add new modules for any remaining entries in "prefixNames". foreach (var entry in prefixNames) { var name = entry.Key; var prefixNamedModules = entry.Value; var tok = prefixNamedModules.First().Item1[0]; var modDef = new ModuleDefinition(tok, name, new List<IToken>(), false, false, null, moduleDecl, null, false, true, true); // Every module is expected to have a default class, so we create and add one now var defaultClass = new DefaultClassDecl(modDef, new List<MemberDecl>()); modDef.TopLevelDecls.Add(defaultClass); // Add the new module to the top-level declarations of its parent and then bind its names as usual var subdecl = new LiteralModuleDecl(modDef, moduleDecl); moduleDecl.TopLevelDecls.Add(subdecl); BindModuleName_LiteralModuleDecl(subdecl, prefixNamedModules.ConvertAll(ShortenPrefix), bindings); } // Finally, go through import declarations (that is, AbstractModuleDecl's and AliasModuleDecl's). foreach (var tld in moduleDecl.TopLevelDecls) { if (tld is AbstractModuleDecl || tld is AliasModuleDecl) { var subdecl = (ModuleDecl)tld; if (bindings.BindName(subdecl.Name, subdecl, null)) { // the add was successful } else { // there's already something with this name ModuleDecl prevDecl; var yes = bindings.TryLookup(subdecl.tok, out prevDecl); Contract.Assert(yes); if (prevDecl is AbstractModuleDecl || prevDecl is AliasModuleDecl) { reporter.Error(MessageSource.Resolver, subdecl.tok, "Duplicate name of import: {0}", subdecl.Name); } else if (tld is AliasModuleDecl importDecl && importDecl.Opened && importDecl.TargetQId.Path.Count == 1 && importDecl.Name == importDecl.TargetQId.rootName()) { importDecl.ShadowsLiteralModule = true; } else { reporter.Error(MessageSource.Resolver, subdecl.tok, "Import declaration uses same name as a module in the same scope: {0}", subdecl.Name); } } } } return bindings; } private Tuple<List<IToken>, LiteralModuleDecl> ShortenPrefix(Tuple<List<IToken>, LiteralModuleDecl> tup) { Contract.Requires(tup.Item1.Count != 0); var rest = tup.Item1.GetRange(1, tup.Item1.Count - 1); return new Tuple<List<IToken>, LiteralModuleDecl>(rest, tup.Item2); } private void BindModuleName_LiteralModuleDecl(LiteralModuleDecl litmod, List<Tuple<List<IToken>, LiteralModuleDecl>> /*?*/ prefixModules, ModuleBindings parentBindings) { Contract.Requires(litmod != null); Contract.Requires(parentBindings != null); // Transfer prefix-named modules downwards into the sub-module if (prefixModules != null) { foreach (var tup in prefixModules) { if (tup.Item1.Count == 0) { tup.Item2.ModuleDef.EnclosingModule = litmod.ModuleDef; // change the parent, now that we have found the right parent module for the prefix-named module var sm = new LiteralModuleDecl(tup.Item2.ModuleDef, litmod.ModuleDef); // this will create a ModuleDecl with the right parent litmod.ModuleDef.TopLevelDecls.Add(sm); } else { litmod.ModuleDef.PrefixNamedModules.Add(tup); } } } var bindings = BindModuleNames(litmod.ModuleDef, parentBindings); if (!parentBindings.BindName(litmod.Name, litmod, bindings)) { reporter.Error(MessageSource.Resolver, litmod.tok, "Duplicate module name: {0}", litmod.Name); } } private bool ResolveQualifiedModuleIdRootRefines(ModuleDefinition context, ModuleBindings bindings, ModuleQualifiedId qid, out ModuleDecl result) { Contract.Assert(qid != null); IToken root = qid.Path[0]; result = null; bool res = bindings.TryLookupFilter(root, out result, m => m.EnclosingModuleDefinition != context); qid.Root = result; return res; } // Find a matching module for the root of the QualifiedId, ignoring // (a) the module (context) itself and (b) any local imports // The latter is so that if one writes 'import A`E import F = A`F' the second A does not // resolve to the alias produced by the first import private bool ResolveQualifiedModuleIdRootImport(AliasModuleDecl context, ModuleBindings bindings, ModuleQualifiedId qid, out ModuleDecl result) { Contract.Assert(qid != null); IToken root = qid.Path[0]; result = null; bool res = bindings.TryLookupFilter(root, out result, m => context != m && ((context.EnclosingModuleDefinition == m.EnclosingModuleDefinition && context.Exports.Count == 0) || m is LiteralModuleDecl)); qid.Root = result; return res; } private bool ResolveQualifiedModuleIdRootAbstract(AbstractModuleDecl context, ModuleBindings bindings, ModuleQualifiedId qid, out ModuleDecl result) { Contract.Assert(qid != null); IToken root = qid.Path[0]; result = null; bool res = bindings.TryLookupFilter(root, out result, m => context != m && ((context.EnclosingModuleDefinition == m.EnclosingModuleDefinition && context.Exports.Count == 0) || m is LiteralModuleDecl)); qid.Root = result; return res; } private void ProcessDependenciesDefinition(ModuleDecl decl, ModuleDefinition m, ModuleBindings bindings, Graph<ModuleDecl> dependencies) { Contract.Assert(decl is LiteralModuleDecl); if (m.RefinementQId != null) { ModuleDecl other; bool res = ResolveQualifiedModuleIdRootRefines(((LiteralModuleDecl)decl).ModuleDef, bindings, m.RefinementQId, out other); if (!res) { reporter.Error(MessageSource.Resolver, m.RefinementQId.rootToken(), $"module {m.RefinementQId.ToString()} named as refinement base does not exist"); } else if (other is LiteralModuleDecl && ((LiteralModuleDecl)other).ModuleDef == m) { reporter.Error(MessageSource.Resolver, m.RefinementQId.rootToken(), "module cannot refine itself: {0}", m.RefinementQId.ToString()); } else { Contract.Assert(other != null); // follows from postcondition of TryGetValue dependencies.AddEdge(decl, other); } } foreach (var toplevel in m.TopLevelDecls) { if (toplevel is ModuleDecl) { var d = (ModuleDecl)toplevel; dependencies.AddEdge(decl, d); var subbindings = bindings.SubBindings(d.Name); ProcessDependencies(d, subbindings ?? bindings, dependencies); if (!m.IsAbstract && d is AbstractModuleDecl && ((AbstractModuleDecl)d).QId.Root != null) { reporter.Error(MessageSource.Resolver, d.tok, "The abstract import named {0} (using :) may only be used in an abstract module declaration", d.Name); } } } } private void ProcessDependencies(ModuleDecl moduleDecl, ModuleBindings bindings, Graph<ModuleDecl> dependencies) { dependencies.AddVertex(moduleDecl); if (moduleDecl is LiteralModuleDecl) { ProcessDependenciesDefinition(moduleDecl, ((LiteralModuleDecl)moduleDecl).ModuleDef, bindings, dependencies); } else if (moduleDecl is AliasModuleDecl) { var alias = moduleDecl as AliasModuleDecl; ModuleDecl root; // TryLookupFilter works outward, looking for a match to the filter for // each enclosing module. if (!ResolveQualifiedModuleIdRootImport(alias, bindings, alias.TargetQId, out root)) { // if (!bindings.TryLookupFilter(alias.TargetQId.rootToken(), out root, m => alias != m) reporter.Error(MessageSource.Resolver, alias.tok, ModuleNotFoundErrorMessage(0, alias.TargetQId.Path)); } else { dependencies.AddEdge(moduleDecl, root); } } else if (moduleDecl is AbstractModuleDecl) { var abs = moduleDecl as AbstractModuleDecl; ModuleDecl root; if (!ResolveQualifiedModuleIdRootAbstract(abs, bindings, abs.QId, out root)) { //if (!bindings.TryLookupFilter(abs.QId.rootToken(), out root, // m => abs != m && (((abs.EnclosingModuleDefinition == m.EnclosingModuleDefinition) && (abs.Exports.Count == 0)) || m is LiteralModuleDecl))) reporter.Error(MessageSource.Resolver, abs.tok, ModuleNotFoundErrorMessage(0, abs.QId.Path)); } else { dependencies.AddEdge(moduleDecl, root); } } } private static string ModuleNotFoundErrorMessage(int i, List<IToken> path, string tail = "") { Contract.Requires(path != null); Contract.Requires(0 <= i && i < path.Count); return "module " + path[i].val + " does not exist" + (1 < path.Count ? " (position " + i.ToString() + " in path " + Util.Comma(".", path, x => x.val) + ")" + tail : ""); } [Pure] private static bool EquivIfPresent<T1, T2>(Dictionary<T1, T2> dic, T1 key, T2 val) where T2 : class { T2 val2; if (dic.TryGetValue(key, out val2)) { return val.Equals(val2); } return true; } public static ModuleSignature MergeSignature(ModuleSignature m, ModuleSignature system) { Contract.Requires(m != null); Contract.Requires(system != null); var info = new ModuleSignature(); // add the system-declared information, among which we know there are no duplicates foreach (var kv in system.TopLevels) { info.TopLevels.Add(kv.Key, kv.Value); } foreach (var kv in system.Ctors) { info.Ctors.Add(kv.Key, kv.Value); } foreach (var kv in system.StaticMembers) { info.StaticMembers.Add(kv.Key, kv.Value); } // add for the module itself foreach (var kv in m.TopLevels) { if (info.TopLevels.TryGetValue(kv.Key, out var infoValue)) { if (infoValue != kv.Value) { // This only happens if one signature contains the name C as a class C (because it // provides C) and the other signature contains the name C as a non-null type decl // (because it reveals C and C?). The merge output will contain the non-null type decl // for the key (and we expect the mapping "C? -> class C" to be placed in the // merge output as well, by the end of this loop). if (infoValue is ClassDecl) { var cd = (ClassDecl)infoValue; Contract.Assert(cd.NonNullTypeDecl == kv.Value); info.TopLevels[kv.Key] = kv.Value; } else if (kv.Value is ClassDecl) { var cd = (ClassDecl)kv.Value; Contract.Assert(cd.NonNullTypeDecl == infoValue); // info.TopLevel[kv.Key] already has the right value } else { Contract.Assert(false); // unexpected } continue; } } info.TopLevels[kv.Key] = kv.Value; } foreach (var kv in m.Ctors) { Contract.Assert(EquivIfPresent(info.Ctors, kv.Key, kv.Value)); info.Ctors[kv.Key] = kv.Value; } foreach (var kv in m.StaticMembers) { Contract.Assert(EquivIfPresent(info.StaticMembers, kv.Key, kv.Value)); info.StaticMembers[kv.Key] = kv.Value; } info.IsAbstract = m.IsAbstract; info.VisibilityScope = new VisibilityScope(); info.VisibilityScope.Augment(m.VisibilityScope); info.VisibilityScope.Augment(system.VisibilityScope); return info; } public static void ResolveOpenedImports(ModuleSignature sig, ModuleDefinition moduleDef, bool useCompileSignatures, Resolver resolver) { var declarations = sig.TopLevels.Values.ToList<TopLevelDecl>(); var importedSigs = new HashSet<ModuleSignature>() {sig}; foreach (var top in declarations) { if (top is ModuleDecl && ((ModuleDecl)top).Opened) { ResolveOpenedImportsWorker(sig, moduleDef, (ModuleDecl)top, importedSigs, useCompileSignatures); } } if (resolver != null) { //needed because ResolveOpenedImports is used statically for a refinement check if (sig.TopLevels["_default"] is AmbiguousTopLevelDecl) { Contract.Assert(sig.TopLevels["_default"].WhatKind == "class"); var cl = new DefaultClassDecl(moduleDef, sig.StaticMembers.Values.ToList()); sig.TopLevels["_default"] = cl; resolver.classMembers[cl] = cl.Members.ToDictionary(m => m.Name); } } } static TopLevelDecl ResolveAlias(TopLevelDecl dd) { while (dd is AliasModuleDecl amd) { dd = amd.TargetQId.Root; } return dd; } static void ResolveOpenedImportsWorker(ModuleSignature sig, ModuleDefinition moduleDef, ModuleDecl im, HashSet<ModuleSignature> importedSigs, bool useCompileSignatures) { bool useImports = true; var s = GetSignatureExt(im.AccessibleSignature(useCompileSignatures), useCompileSignatures); if (importedSigs.Contains(s)) { return; // we've already got these declarations } importedSigs.Add(s); if (useImports) { // classes: foreach (var kv in s.TopLevels) { if (!kv.Value.CanBeExported()) continue; if (useImports || string.Equals(kv.Key, "_default", StringComparison.InvariantCulture)) { TopLevelDecl d; if (sig.TopLevels.TryGetValue(kv.Key, out d)) { // ignore the import if the existing declaration belongs to the current module if (d.EnclosingModuleDefinition != moduleDef) { bool ok = false; // keep just one if they normalize to the same entity if (d == kv.Value) { ok = true; } else if (d is ModuleDecl || kv.Value is ModuleDecl) { var dd = ResolveAlias(d); var dk = ResolveAlias(kv.Value); ok = dd == dk; } else { var dType = UserDefinedType.FromTopLevelDecl(d.tok, d); var vType = UserDefinedType.FromTopLevelDecl(kv.Value.tok, kv.Value); ok = dType.Equals(vType, true); } if (!ok) { sig.TopLevels[kv.Key] = AmbiguousTopLevelDecl.Create(moduleDef, d, kv.Value); } } } else { sig.TopLevels.Add(kv.Key, kv.Value); } } } if (useImports) { // constructors: foreach (var kv in s.Ctors) { Tuple<DatatypeCtor, bool> pair; if (sig.Ctors.TryGetValue(kv.Key, out pair)) { // The same ctor can be imported from two different imports (e.g "diamond" imports), in which case, // they are not duplicates. if (!Object.ReferenceEquals(kv.Value.Item1, pair.Item1)) { // mark it as a duplicate sig.Ctors[kv.Key] = new Tuple<DatatypeCtor, bool>(pair.Item1, true); } } else { // add new sig.Ctors.Add(kv.Key, kv.Value); } } } if (useImports) { // static members: foreach (var kv in s.StaticMembers) { if (!kv.Value.CanBeExported()) continue; MemberDecl md; if (sig.StaticMembers.TryGetValue(kv.Key, out md)) { sig.StaticMembers[kv.Key] = AmbiguousMemberDecl.Create(moduleDef, md, kv.Value); } else { // add new sig.StaticMembers.Add(kv.Key, kv.Value); } } } } } ModuleSignature RegisterTopLevelDecls(ModuleDefinition moduleDef, bool useImports) { Contract.Requires(moduleDef != null); var sig = new ModuleSignature(); sig.ModuleDef = moduleDef; sig.IsAbstract = moduleDef.IsAbstract; sig.VisibilityScope = new VisibilityScope(); sig.VisibilityScope.Augment(moduleDef.VisibilityScope); List<TopLevelDecl> declarations = moduleDef.TopLevelDecls; // This is solely used to detect duplicates amongst the various e Dictionary<string, TopLevelDecl> toplevels = new Dictionary<string, TopLevelDecl>(); // Now add the things present var anonymousImportCount = 0; foreach (TopLevelDecl d in declarations) { Contract.Assert(d != null); if (d is RevealableTypeDecl) { revealableTypes.Add((RevealableTypeDecl)d); } // register the class/datatype/module name { TopLevelDecl registerThisDecl = null; string registerUnderThisName = null; if (d is ModuleExportDecl export) { if (sig.ExportSets.ContainsKey(d.Name)) { reporter.Error(MessageSource.Resolver, d, "duplicate name of export set: {0}", d.Name); } else { sig.ExportSets[d.Name] = export; } } else if (d is AliasModuleDecl importDecl && importDecl.ShadowsLiteralModule) { // add under an anonymous name registerThisDecl = d; registerUnderThisName = string.Format("{0}#{1}", d.Name, anonymousImportCount); anonymousImportCount++; } else if (toplevels.ContainsKey(d.Name)) { reporter.Error(MessageSource.Resolver, d, "duplicate name of top-level declaration: {0}", d.Name); } else if (d is ClassDecl cl && cl.NonNullTypeDecl != null) { registerThisDecl = cl.NonNullTypeDecl; registerUnderThisName = d.Name; } else { registerThisDecl = d; registerUnderThisName = d.Name; } if (registerThisDecl != null) { toplevels[registerUnderThisName] = registerThisDecl; sig.TopLevels[registerUnderThisName] = registerThisDecl; } } if (d is ModuleDecl) { // nothing to do } else if (d is TypeSynonymDecl) { // nothing more to register } else if (d is NewtypeDecl || d is OpaqueTypeDecl) { var cl = (TopLevelDeclWithMembers)d; // register the names of the type members var members = new Dictionary<string, MemberDecl>(); classMembers.Add(cl, members); RegisterMembers(moduleDef, cl, members); } else if (d is IteratorDecl) { var iter = (IteratorDecl)d; // register the names of the implicit members var members = new Dictionary<string, MemberDecl>(); classMembers.Add(iter, members); // First, register the iterator's in- and out-parameters as readonly fields foreach (var p in iter.Ins) { if (members.ContainsKey(p.Name)) { reporter.Error(MessageSource.Resolver, p, "Name of in-parameter is used by another member of the iterator: {0}", p.Name); } else { var field = new SpecialField(p.tok, p.Name, SpecialField.ID.UseIdParam, p.CompileName, p.IsGhost, false, false, p.Type, null); field.EnclosingClass = iter; // resolve here field.InheritVisibility(iter); members.Add(p.Name, field); iter.Members.Add(field); } } var nonDuplicateOuts = new List<Formal>(); foreach (var p in iter.Outs) { if (members.ContainsKey(p.Name)) { reporter.Error(MessageSource.Resolver, p, "Name of yield-parameter is used by another member of the iterator: {0}", p.Name); } else { nonDuplicateOuts.Add(p); var field = new SpecialField(p.tok, p.Name, SpecialField.ID.UseIdParam, p.CompileName, p.IsGhost, true, true, p.Type, null); field.EnclosingClass = iter; // resolve here field.InheritVisibility(iter); iter.OutsFields.Add(field); members.Add(p.Name, field); iter.Members.Add(field); } } foreach (var p in nonDuplicateOuts) { var nm = p.Name + "s"; if (members.ContainsKey(nm)) { reporter.Error(MessageSource.Resolver, p.tok, "Name of implicit yield-history variable '{0}' is already used by another member of the iterator", p.Name); nm = p.Name + "*"; // bogus name, but at least it'll be unique } // we add some field to OutsHistoryFields, even if there was an error; the name of the field, in case of error, is not so important var tp = new SeqType(p.Type.NormalizeExpand()); var field = new SpecialField(p.tok, nm, SpecialField.ID.UseIdParam, nm, true, true, false, tp, null); field.EnclosingClass = iter; // resolve here field.InheritVisibility(iter); iter.OutsHistoryFields .Add(field); // for now, just record this field (until all parameters have been added as members) } Contract.Assert(iter.OutsFields.Count == iter.OutsHistoryFields .Count); // the code above makes sure this holds, even in the face of errors // now that already-used 'ys' names have been checked for, add these yield-history variables iter.OutsHistoryFields.ForEach(f => { members.Add(f.Name, f); iter.Members.Add(f); }); // add the additional special variables as fields iter.Member_Reads = new SpecialField(iter.tok, "_reads", SpecialField.ID.Reads, null, true, false, false, new SetType(true, builtIns.ObjectQ()), null); iter.Member_Modifies = new SpecialField(iter.tok, "_modifies", SpecialField.ID.Modifies, null, true, false, false, new SetType(true, builtIns.ObjectQ()), null); iter.Member_New = new SpecialField(iter.tok, "_new", SpecialField.ID.New, null, true, true, true, new SetType(true, builtIns.ObjectQ()), null); foreach (var field in new List<Field>() {iter.Member_Reads, iter.Member_Modifies, iter.Member_New}) { field.EnclosingClass = iter; // resolve here field.InheritVisibility(iter); members.Add(field.Name, field); iter.Members.Add(field); } // finally, add special variables to hold the components of the (explicit or implicit) decreases clause FillInDefaultDecreases(iter, false); // create the fields; unfortunately, we don't know their types yet, so we'll just insert type proxies for now var i = 0; foreach (var p in iter.Decreases.Expressions) { var nm = "_decreases" + i; var field = new SpecialField(p.tok, nm, SpecialField.ID.UseIdParam, nm, true, false, false, new InferredTypeProxy(), null); field.EnclosingClass = iter; // resolve here field.InheritVisibility(iter); iter.DecreasesFields.Add(field); members.Add(field.Name, field); iter.Members.Add(field); i++; } // Note, the typeArgs parameter to the following Method/Predicate constructors is passed in as the empty list. What that is // saying is that the Method/Predicate does not take any type parameters over and beyond what the enclosing type (namely, the // iterator type) does. // --- here comes the constructor var init = new Constructor(iter.tok, "_ctor", new List<TypeParameter>(), iter.Ins, new List<AttributedExpression>(), new Specification<FrameExpression>(new List<FrameExpression>(), null), new List<AttributedExpression>(), new Specification<Expression>(new List<Expression>(), null), null, null, null); // --- here comes predicate Valid() var valid = new Predicate(iter.tok, "Valid", false, true, new List<TypeParameter>(), new List<Formal>(), new List<AttributedExpression>(), new List<FrameExpression>(), new List<AttributedExpression>(), new Specification<Expression>(new List<Expression>(), null), null, Predicate.BodyOriginKind.OriginalOrInherited, null, null); // --- here comes method MoveNext var moveNext = new Method(iter.tok, "MoveNext", false, false, new List<TypeParameter>(), new List<Formal>(), new List<Formal>() {new Formal(iter.tok, "more", Type.Bool, false, false)}, new List<AttributedExpression>(), new Specification<FrameExpression>(new List<FrameExpression>(), null), new List<AttributedExpression>(), new Specification<Expression>(new List<Expression>(), null), null, null, null); // add these implicit members to the class init.EnclosingClass = iter; init.InheritVisibility(iter); valid.EnclosingClass = iter; valid.InheritVisibility(iter); moveNext.EnclosingClass = iter; moveNext.InheritVisibility(iter); iter.HasConstructor = true; iter.Member_Init = init; iter.Member_Valid = valid; iter.Member_MoveNext = moveNext; MemberDecl member; if (members.TryGetValue(init.Name, out member)) { reporter.Error(MessageSource.Resolver, member.tok, "member name '{0}' is already predefined for this iterator", init.Name); } else { members.Add(init.Name, init); iter.Members.Add(init); } // If the name of the iterator is "Valid" or "MoveNext", one of the following will produce an error message. That // error message may not be as clear as it could be, but the situation also seems unlikely to ever occur in practice. if (members.TryGetValue("Valid", out member)) { reporter.Error(MessageSource.Resolver, member.tok, "member name 'Valid' is already predefined for iterators"); } else { members.Add(valid.Name, valid); iter.Members.Add(valid); } if (members.TryGetValue("MoveNext", out member)) { reporter.Error(MessageSource.Resolver, member.tok, "member name 'MoveNext' is already predefined for iterators"); } else { members.Add(moveNext.Name, moveNext); iter.Members.Add(moveNext); } } else if (d is ClassDecl) { var cl = (ClassDecl)d; var preMemberErrs = reporter.Count(ErrorLevel.Error); // register the names of the class members var members = new Dictionary<string, MemberDecl>(); classMembers.Add(cl, members); RegisterMembers(moduleDef, cl, members); Contract.Assert(preMemberErrs != reporter.Count(ErrorLevel.Error) || !cl.Members.Except(members.Values).Any()); if (cl.IsDefaultClass) { foreach (MemberDecl m in members.Values) { Contract.Assert(!m.HasStaticKeyword || m is ConstantField || DafnyOptions.O .AllowGlobals); // note, the IsStatic value isn't available yet; when it becomes available, we expect it will have the value 'true' if (m is Function || m is Method || m is ConstantField) { sig.StaticMembers[m.Name] = m; } if (toplevels.ContainsKey(m.Name)) { reporter.Error(MessageSource.Resolver, m.tok, $"duplicate declaration for name {m.Name}"); } } } } else if (d is DatatypeDecl) { var dt = (DatatypeDecl)d; // register the names of the constructors var ctors = new Dictionary<string, DatatypeCtor>(); datatypeCtors.Add(dt, ctors); // ... and of the other members var members = new Dictionary<string, MemberDecl>(); classMembers.Add(dt, members); foreach (DatatypeCtor ctor in dt.Ctors) { if (ctor.Name.EndsWith("?")) { reporter.Error(MessageSource.Resolver, ctor, "a datatype constructor name is not allowed to end with '?'"); } else if (ctors.ContainsKey(ctor.Name)) { reporter.Error(MessageSource.Resolver, ctor, "Duplicate datatype constructor name: {0}", ctor.Name); } else { ctors.Add(ctor.Name, ctor); ctor.InheritVisibility(dt); // create and add the query "method" (field, really) string queryName = ctor.Name + "?"; var query = new SpecialField(ctor.tok, queryName, SpecialField.ID.UseIdParam, "is_" + ctor.CompileName, false, false, false, Type.Bool, null); query.InheritVisibility(dt); query.EnclosingClass = dt; // resolve here members.Add(queryName, query); ctor.QueryField = query; // also register the constructor name globally Tuple<DatatypeCtor, bool> pair; if (sig.Ctors.TryGetValue(ctor.Name, out pair)) { // mark it as a duplicate sig.Ctors[ctor.Name] = new Tuple<DatatypeCtor, bool>(pair.Item1, true); } else { // add new sig.Ctors.Add(ctor.Name, new Tuple<DatatypeCtor, bool>(ctor, false)); } } } // add deconstructors now (that is, after the query methods have been added) foreach (DatatypeCtor ctor in dt.Ctors) { var formalsUsedInThisCtor = new HashSet<string>(); foreach (var formal in ctor.Formals) { MemberDecl previousMember = null; var localDuplicate = false; if (formal.HasName) { if (members.TryGetValue(formal.Name, out previousMember)) { localDuplicate = formalsUsedInThisCtor.Contains(formal.Name); if (localDuplicate) { reporter.Error(MessageSource.Resolver, ctor, "Duplicate use of deconstructor name in the same constructor: {0}", formal.Name); } else if (previousMember is DatatypeDestructor) { // this is okay, if the destructor has the appropriate type; this will be checked later, after type checking } else { reporter.Error(MessageSource.Resolver, ctor, "Name of deconstructor is used by another member of the datatype: {0}", formal.Name); } } formalsUsedInThisCtor.Add(formal.Name); } DatatypeDestructor dtor; if (!localDuplicate && previousMember is DatatypeDestructor) { // a destructor with this name already existed in (a different constructor in) the datatype dtor = (DatatypeDestructor)previousMember; dtor.AddAnotherEnclosingCtor(ctor, formal); } else { // either the destructor has no explicit name, or this constructor declared another destructor with this name, or no previous destructor had this name dtor = new DatatypeDestructor(formal.tok, ctor, formal, formal.Name, "dtor_" + formal.CompileName, formal.IsGhost, formal.Type, null); dtor.InheritVisibility(dt); dtor.EnclosingClass = dt; // resolve here if (formal.HasName && !localDuplicate && previousMember == null) { // the destructor has an explict name and there was no member at all with this name before members.Add(formal.Name, dtor); } } ctor.Destructors.Add(dtor); } } // finally, add any additional user-defined members RegisterMembers(moduleDef, dt, members); } else { Contract.Assert(d is ValuetypeDecl); } } // Now, for each class, register its possibly-null type foreach (TopLevelDecl d in declarations) { if ((d as ClassDecl)?.NonNullTypeDecl != null) { var name = d.Name + "?"; TopLevelDecl prev; if (toplevels.TryGetValue(name, out prev)) { reporter.Error(MessageSource.Resolver, d, "a module that already contains a top-level declaration '{0}' is not allowed to declare a {1} '{2}'", name, d.WhatKind, d.Name); } else { toplevels[name] = d; sig.TopLevels[name] = d; } } } return sig; } void RegisterMembers(ModuleDefinition moduleDef, TopLevelDeclWithMembers cl, Dictionary<string, MemberDecl> members) { Contract.Requires(moduleDef != null); Contract.Requires(cl != null); Contract.Requires(members != null); foreach (MemberDecl m in cl.Members) { if (!members.ContainsKey(m.Name)) { members.Add(m.Name, m); if (m is Constructor) { Contract.Assert(cl is ClassDecl); // the parser ensures this condition if (cl is TraitDecl) { reporter.Error(MessageSource.Resolver, m.tok, "a trait is not allowed to declare a constructor"); } else { ((ClassDecl)cl).HasConstructor = true; } } else if (m is ExtremePredicate || m is ExtremeLemma) { var extraName = m.Name + "#"; MemberDecl extraMember; var cloner = new Cloner(); var formals = new List<Formal>(); Type typeOfK; if ((m is ExtremePredicate && ((ExtremePredicate)m).KNat) || (m is ExtremeLemma && ((ExtremeLemma)m).KNat)) { typeOfK = new UserDefinedType(m.tok, "nat", (List<Type>)null); } else { typeOfK = new BigOrdinalType(); } var k = new ImplicitFormal(m.tok, "_k", typeOfK, true, false); reporter.Info(MessageSource.Resolver, m.tok, string.Format("_k: {0}", k.Type)); formals.Add(k); if (m is ExtremePredicate) { var cop = (ExtremePredicate)m; formals.AddRange(cop.Formals.ConvertAll(cloner.CloneFormal)); List<TypeParameter> tyvars = cop.TypeArgs.ConvertAll(cloner.CloneTypeParam); // create prefix predicate cop.PrefixPredicate = new PrefixPredicate(cop.tok, extraName, cop.HasStaticKeyword, tyvars, k, formals, cop.Req.ConvertAll(cloner.CloneAttributedExpr), cop.Reads.ConvertAll(cloner.CloneFrameExpr), cop.Ens.ConvertAll(cloner.CloneAttributedExpr), new Specification<Expression>(new List<Expression>() {new IdentifierExpr(cop.tok, k.Name)}, null), cop.Body, null, cop); extraMember = cop.PrefixPredicate; // In the call graph, add an edge from P# to P, since this will have the desired effect of detecting unwanted cycles. moduleDef.CallGraph.AddEdge(cop.PrefixPredicate, cop); } else { var com = (ExtremeLemma)m; // _k has already been added to 'formals', so append the original formals formals.AddRange(com.Ins.ConvertAll(cloner.CloneFormal)); // prepend _k to the given decreases clause var decr = new List<Expression>(); decr.Add(new IdentifierExpr(com.tok, k.Name)); decr.AddRange(com.Decreases.Expressions.ConvertAll(cloner.CloneExpr)); // Create prefix lemma. Note that the body is not cloned, but simply shared. // For a greatest lemma, the postconditions are filled in after the greatest lemma's postconditions have been resolved. // For a least lemma, the preconditions are filled in after the least lemma's preconditions have been resolved. var req = com is GreatestLemma ? com.Req.ConvertAll(cloner.CloneAttributedExpr) : new List<AttributedExpression>(); var ens = com is GreatestLemma ? new List<AttributedExpression>() : com.Ens.ConvertAll(cloner.CloneAttributedExpr); com.PrefixLemma = new PrefixLemma(com.tok, extraName, com.HasStaticKeyword, com.TypeArgs.ConvertAll(cloner.CloneTypeParam), k, formals, com.Outs.ConvertAll(cloner.CloneFormal), req, cloner.CloneSpecFrameExpr(com.Mod), ens, new Specification<Expression>(decr, null), null, // Note, the body for the prefix method will be created once the call graph has been computed and the SCC for the greatest lemma is known cloner.CloneAttributes(com.Attributes), com); extraMember = com.PrefixLemma; // In the call graph, add an edge from M# to M, since this will have the desired effect of detecting unwanted cycles. moduleDef.CallGraph.AddEdge(com.PrefixLemma, com); } extraMember.InheritVisibility(m, false); members.Add(extraName, extraMember); } } else if (m is Constructor && !((Constructor)m).HasName) { reporter.Error(MessageSource.Resolver, m, "More than one anonymous constructor"); } else { reporter.Error(MessageSource.Resolver, m, "Duplicate member name: {0}", m.Name); } } } private ModuleSignature MakeAbstractSignature(ModuleSignature p, string Name, int Height, Dictionary<ModuleDefinition, ModuleSignature> mods, Dictionary<ModuleDefinition, ModuleDefinition> compilationModuleClones) { Contract.Requires(p != null); Contract.Requires(Name != null); Contract.Requires(mods != null); Contract.Requires(compilationModuleClones != null); var errCount = reporter.Count(ErrorLevel.Error); var mod = new ModuleDefinition(Token.NoToken, Name + ".Abs", new List<IToken>(), true, true, null, null, null, false, p.ModuleDef.IsToBeVerified, p.ModuleDef.IsToBeCompiled); mod.Height = Height; bool hasDefaultClass = false; foreach (var kv in p.TopLevels) { hasDefaultClass = kv.Value is DefaultClassDecl || hasDefaultClass; if (!(kv.Value is NonNullTypeDecl)) { var clone = CloneDeclaration(p.VisibilityScope, kv.Value, mod, mods, Name, compilationModuleClones); mod.TopLevelDecls.Add(clone); } } if (!hasDefaultClass) { DefaultClassDecl cl = new DefaultClassDecl(mod, p.StaticMembers.Values.ToList()); mod.TopLevelDecls.Add(CloneDeclaration(p.VisibilityScope, cl, mod, mods, Name, compilationModuleClones)); } var sig = RegisterTopLevelDecls(mod, true); sig.Refines = p.Refines; sig.CompileSignature = p; sig.IsAbstract = p.IsAbstract; mods.Add(mod, sig); var good = ResolveModuleDefinition(mod, sig); if (good && reporter.Count(ErrorLevel.Error) == errCount) { mod.SuccessfullyResolved = true; } return sig; } TopLevelDecl CloneDeclaration(VisibilityScope scope, TopLevelDecl d, ModuleDefinition m, Dictionary<ModuleDefinition, ModuleSignature> mods, string Name, Dictionary<ModuleDefinition, ModuleDefinition> compilationModuleClones) { Contract.Requires(d != null); Contract.Requires(m != null); Contract.Requires(mods != null); Contract.Requires(Name != null); Contract.Requires(compilationModuleClones != null); if (d is AbstractModuleDecl) { var abs = (AbstractModuleDecl)d; var sig = MakeAbstractSignature(abs.OriginalSignature, Name + "." + abs.Name, abs.Height, mods, compilationModuleClones); var a = new AbstractModuleDecl(abs.QId, abs.tok, m, abs.Opened, abs.Exports); a.Signature = sig; a.OriginalSignature = abs.OriginalSignature; return a; } else { return new AbstractSignatureCloner(scope).CloneDeclaration(d, m); } } // Returns the resolved Module declaration corresponding to the qualified module id // Requires the root to have been resolved // Issues an error and returns null if the path is not valid public ModuleDecl ResolveModuleQualifiedId(ModuleDecl root, ModuleQualifiedId qid, ErrorReporter reporter) { Contract.Requires(qid != null); Contract.Requires(qid.Path.Count > 0); List<IToken> Path = qid.Path; ModuleDecl decl = root; ModuleSignature p; for (int k = 1; k < Path.Count; k++) { if (decl is LiteralModuleDecl) { p = ((LiteralModuleDecl)decl).DefaultExport; if (p == null) { reporter.Error(MessageSource.Resolver, Path[k], ModuleNotFoundErrorMessage(k, Path, $" because {decl.Name} does not have a default export")); return null; } } else { p = decl.Signature; } var tld = p.TopLevels.GetValueOrDefault(Path[k].val, null); if (!(tld is ModuleDecl dd)) { if (decl.Signature.ModuleDef == null) { reporter.Error(MessageSource.Resolver, Path[k], ModuleNotFoundErrorMessage(k, Path, " because of previous error")); } else { reporter.Error(MessageSource.Resolver, Path[k], ModuleNotFoundErrorMessage(k, Path)); } return null; } // Any aliases along the qualified path ought to be already resolved, // else the modules are not being resolved in the right order if (dd is AliasModuleDecl amd) { Contract.Assert(amd.Signature != null); } decl = dd; } return decl; } public bool ResolveExport(ModuleDecl alias, ModuleDefinition parent, ModuleQualifiedId qid, List<IToken> Exports, out ModuleSignature p, ErrorReporter reporter) { Contract.Requires(qid != null); Contract.Requires(qid.Path.Count > 0); Contract.Requires(Exports != null); ModuleDecl root = qid.Root; ModuleDecl decl = ResolveModuleQualifiedId(root, qid, reporter); if (decl == null) { p = null; return false; } p = decl.Signature; if (Exports.Count == 0) { if (p.ExportSets.Count == 0) { if (decl is LiteralModuleDecl) { p = ((LiteralModuleDecl)decl).DefaultExport; } else { // p is OK } } else { var m = p.ExportSets.GetValueOrDefault(decl.Name, null); if (m == null) { // no default view is specified. reporter.Error(MessageSource.Resolver, qid.rootToken(), "no default export set declared in module: {0}", decl.Name); return false; } p = m.AccessibleSignature(); } } else { ModuleExportDecl pp; if (decl.Signature.ExportSets.TryGetValue(Exports[0].val, out pp)) { p = pp.AccessibleSignature(); } else { reporter.Error(MessageSource.Resolver, Exports[0], "no export set '{0}' in module '{1}'", Exports[0].val, decl.Name); p = null; return false; } foreach (IToken export in Exports.Skip(1)) { if (decl.Signature.ExportSets.TryGetValue(export.val, out pp)) { Contract.Assert(Object.ReferenceEquals(p.ModuleDef, pp.Signature.ModuleDef)); ModuleSignature merged = MergeSignature(p, pp.Signature); merged.ModuleDef = pp.Signature.ModuleDef; if (p.CompileSignature != null) { Contract.Assert(pp.Signature.CompileSignature != null); merged.CompileSignature = MergeSignature(p.CompileSignature, pp.Signature.CompileSignature); } else { Contract.Assert(pp.Signature.CompileSignature == null); } p = merged; } else { reporter.Error(MessageSource.Resolver, export, "no export set {0} in module {1}", export.val, decl.Name); p = null; return false; } } } return true; } public void RevealAllInScope(List<TopLevelDecl> declarations, VisibilityScope scope) { foreach (TopLevelDecl d in declarations) { d.AddVisibilityScope(scope, false); if (d is TopLevelDeclWithMembers) { var cl = (TopLevelDeclWithMembers)d; foreach (var mem in cl.Members) { if (!mem.ScopeIsInherited) { mem.AddVisibilityScope(scope, false); } } var nnd = (cl as ClassDecl)?.NonNullTypeDecl; if (nnd != null) { nnd.AddVisibilityScope(scope, false); } } } } public void ResolveTopLevelDecls_Signatures(ModuleDefinition def, ModuleSignature sig, List<TopLevelDecl/*!*/>/*!*/ declarations, Graph<IndDatatypeDecl/*!*/>/*!*/ datatypeDependencies, Graph<CoDatatypeDecl/*!*/>/*!*/ codatatypeDependencies) { Contract.Requires(declarations != null); Contract.Requires(datatypeDependencies != null); Contract.Requires(codatatypeDependencies != null); RevealAllInScope(declarations, def.VisibilityScope); /* Augment the scoping environment for the current module*/ foreach (TopLevelDecl d in declarations) { if (d is ModuleDecl && !(d is ModuleExportDecl)) { var decl = (ModuleDecl)d; moduleInfo.VisibilityScope.Augment(decl.AccessibleSignature().VisibilityScope); sig.VisibilityScope.Augment(decl.AccessibleSignature().VisibilityScope); } } /*if (sig.Refines != null) { moduleInfo.VisibilityScope.Augment(sig.Refines.VisibilityScope); sig.VisibilityScope.Augment(sig.Refines.VisibilityScope); }*/ var typeRedirectionDependencies = new Graph<RedirectingTypeDecl>(); // this concerns the type directions, not their constraints (which are checked for cyclic dependencies later) foreach (TopLevelDecl d in ModuleDefinition.AllDeclarationsAndNonNullTypeDecls(declarations)) { Contract.Assert(d != null); allTypeParameters.PushMarker(); ResolveTypeParameters(d.TypeArgs, true, d); if (d is TypeSynonymDecl) { var dd = (TypeSynonymDecl)d; ResolveType(dd.tok, dd.Rhs, dd, ResolveTypeOptionEnum.AllowPrefix, dd.TypeArgs); dd.Rhs.ForeachTypeComponent(ty => { var s = ty.AsRedirectingType; if (s != null) { typeRedirectionDependencies.AddEdge(dd, s); } }); } else if (d is NewtypeDecl) { var dd = (NewtypeDecl)d; ResolveType(dd.tok, dd.BaseType, dd, ResolveTypeOptionEnum.DontInfer, null); dd.BaseType.ForeachTypeComponent(ty => { var s = ty.AsRedirectingType; if (s != null) { typeRedirectionDependencies.AddEdge(dd, s); } }); ResolveClassMemberTypes(dd); } else if (d is IteratorDecl) { ResolveIteratorSignature((IteratorDecl)d); } else if (d is ModuleDecl) { var decl = (ModuleDecl)d; if (!def.IsAbstract && decl is AliasModuleDecl am && decl.Signature.IsAbstract) { reporter.Error(MessageSource.Resolver, am.TargetQId.rootToken(), "a compiled module ({0}) is not allowed to import an abstract module ({1})", def.Name, am.TargetQId.ToString()); } } else if (d is DatatypeDecl) { var dd = (DatatypeDecl)d; ResolveCtorTypes(dd, datatypeDependencies, codatatypeDependencies); ResolveClassMemberTypes(dd); } else { ResolveClassMemberTypes((TopLevelDeclWithMembers)d); } allTypeParameters.PopMarker(); } // Resolve the parent-trait types and fill in .ParentTraitHeads var prevErrorCount = reporter.Count(ErrorLevel.Error); var parentRelation = new Graph<TopLevelDeclWithMembers>(); foreach (TopLevelDecl d in declarations) { if (d is TopLevelDeclWithMembers cl) { ResolveParentTraitTypes(cl, parentRelation); } } // Check for cycles among parent traits foreach (var cycle in parentRelation.AllCycles()) { var cy = Util.Comma(" -> ", cycle, m => m.Name); reporter.Error(MessageSource.Resolver, cycle[0], "trait definitions contain a cycle: {0}", cy); } if (prevErrorCount == reporter.Count(ErrorLevel.Error)) { // Register the trait members in the classes that inherit them foreach (TopLevelDecl d in declarations) { if (d is TopLevelDeclWithMembers cl) { RegisterInheritedMembers(cl); } } } if (prevErrorCount == reporter.Count(ErrorLevel.Error)) { // Now that all traits have been resolved, let classes inherit the trait members foreach (var d in declarations) { if (d is TopLevelDeclWithMembers cl) { InheritedTraitMembers(cl); } } } // perform acyclicity test on type synonyms foreach (var cycle in typeRedirectionDependencies.AllCycles()) { Contract.Assert(cycle.Count != 0); var erste = cycle[0]; reporter.Error(MessageSource.Resolver, erste.Tok, "Cycle among redirecting types (newtypes, subset types, type synonyms): {0} -> {1}", Util.Comma(" -> ", cycle, syn => syn.Name), erste.Name); } } public static readonly List<NativeType> NativeTypes = new List<NativeType>() { new NativeType("byte", 0, 0x100, 8,NativeType.Selection.Byte, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java | DafnyOptions.CompilationTarget.Cpp), new NativeType("sbyte", -0x80, 0x80, 0, NativeType.Selection.SByte, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java | DafnyOptions.CompilationTarget.Cpp), new NativeType("ushort", 0, 0x1_0000, 16, NativeType.Selection.UShort, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java | DafnyOptions.CompilationTarget.Cpp), new NativeType("short", -0x8000, 0x8000, 0, NativeType.Selection.Short, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java | DafnyOptions.CompilationTarget.Cpp), new NativeType("uint", 0, 0x1_0000_0000, 32, NativeType.Selection.UInt, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java | DafnyOptions.CompilationTarget.Cpp), new NativeType("int", -0x8000_0000, 0x8000_0000, 0, NativeType.Selection.Int, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java | DafnyOptions.CompilationTarget.Cpp), new NativeType("number", -0x1f_ffff_ffff_ffff, 0x20_0000_0000_0000, 0, NativeType.Selection.Number, DafnyOptions.CompilationTarget.JavaScript), // JavaScript integers new NativeType("ulong", 0, new BigInteger(0x1_0000_0000) * new BigInteger(0x1_0000_0000), 64, NativeType.Selection.ULong, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java | DafnyOptions.CompilationTarget.Cpp), new NativeType("long", Int64.MinValue, 0x8000_0000_0000_0000, 0, NativeType.Selection.Long, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java | DafnyOptions.CompilationTarget.Cpp), }; public void ResolveTopLevelDecls_Core(List<TopLevelDecl/*!*/>/*!*/ declarations, Graph<IndDatatypeDecl/*!*/>/*!*/ datatypeDependencies, Graph<CoDatatypeDecl/*!*/>/*!*/ codatatypeDependencies, bool isAnExport = false) { Contract.Requires(declarations != null); Contract.Requires(cce.NonNullElements(datatypeDependencies.GetVertices())); Contract.Requires(cce.NonNullElements(codatatypeDependencies.GetVertices())); Contract.Requires(AllTypeConstraints.Count == 0); Contract.Ensures(AllTypeConstraints.Count == 0); int prevErrorCount = reporter.Count(ErrorLevel.Error); // ---------------------------------- Pass 0 ---------------------------------- // This pass resolves names, introduces (and may solve) type constraints, and // builds the module's call graph. // For 'newtype' and subset-type declarations, it also checks that all types were fully // determined. // ---------------------------------------------------------------------------- // Resolve the meat of classes and iterators, the definitions of type synonyms, and the type parameters of all top-level type declarations // In the first two loops below, resolve the newtype/subset-type declarations and their constraint clauses and const definitions, including // filling in .ResolvedOp fields. This is needed for the resolution of the other declarations, because those other declarations may invoke // DiscoverBounds, which looks at the .Constraint or .Rhs field of any such types involved. // The third loop resolves the other declarations. It also resolves any witness expressions of newtype/subset-type declarations. foreach (TopLevelDecl topd in declarations) { Contract.Assert(topd != null); Contract.Assert(VisibleInScope(topd)); TopLevelDecl d = topd is ClassDecl ? ((ClassDecl)topd).NonNullTypeDecl : topd; if (d is NewtypeDecl) { var dd = (NewtypeDecl)d; ResolveAttributes(d.Attributes, d, new ResolveOpts(new NoContext(d.EnclosingModuleDefinition), false)); // this check can be done only after it has been determined that the redirected types do not involve cycles AddXConstraint(dd.tok, "NumericType", dd.BaseType, "newtypes must be based on some numeric type (got {0})"); // type check the constraint, if any if (dd.Var == null) { SolveAllTypeConstraints(); } else { Contract.Assert(object.ReferenceEquals(dd.Var.Type, dd.BaseType)); // follows from NewtypeDecl invariant Contract.Assert(dd.Constraint != null); // follows from NewtypeDecl invariant scope.PushMarker(); var added = scope.Push(dd.Var.Name, dd.Var); Contract.Assert(added == Scope<IVariable>.PushResult.Success); ResolveExpression(dd.Constraint, new ResolveOpts(dd, false)); Contract.Assert(dd.Constraint.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(dd.Constraint, "newtype constraint must be of type bool (instead got {0})"); SolveAllTypeConstraints(); if (!CheckTypeInference_Visitor.IsDetermined(dd.BaseType.NormalizeExpand())) { reporter.Error(MessageSource.Resolver, dd.tok, "newtype's base type is not fully determined; add an explicit type for '{0}'", dd.Var.Name); } scope.PopMarker(); } } else if (d is SubsetTypeDecl) { var dd = (SubsetTypeDecl)d; allTypeParameters.PushMarker(); ResolveTypeParameters(d.TypeArgs, false, d); ResolveAttributes(d.Attributes, d, new ResolveOpts(new NoContext(d.EnclosingModuleDefinition), false)); // type check the constraint Contract.Assert(object.ReferenceEquals(dd.Var.Type, dd.Rhs)); // follows from SubsetTypeDecl invariant Contract.Assert(dd.Constraint != null); // follows from SubsetTypeDecl invariant scope.PushMarker(); var added = scope.Push(dd.Var.Name, dd.Var); Contract.Assert(added == Scope<IVariable>.PushResult.Success); ResolveExpression(dd.Constraint, new ResolveOpts(dd, false)); Contract.Assert(dd.Constraint.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(dd.Constraint, "subset-type constraint must be of type bool (instead got {0})"); SolveAllTypeConstraints(); if (!CheckTypeInference_Visitor.IsDetermined(dd.Rhs.NormalizeExpand())) { reporter.Error(MessageSource.Resolver, dd.tok, "subset type's base type is not fully determined; add an explicit type for '{0}'", dd.Var.Name); } scope.PopMarker(); allTypeParameters.PopMarker(); } if (topd is TopLevelDeclWithMembers) { var cl = (TopLevelDeclWithMembers)topd; currentClass = cl; foreach (var member in cl.Members) { Contract.Assert(VisibleInScope(member)); if (member is ConstantField) { var field = (ConstantField)member; var opts = new ResolveOpts(field, false); ResolveAttributes(field.Attributes, field, opts); // Resolve the value expression if (field.Rhs != null) { var ec = reporter.Count(ErrorLevel.Error); ResolveExpression(field.Rhs, opts); if (reporter.Count(ErrorLevel.Error) == ec) { // make sure initialization only refers to constant field or literal expression if (CheckIsConstantExpr(field, field.Rhs)) { AddAssignableConstraint(field.tok, field.Type, field.Rhs.Type, "type for constant '" + field.Name + "' is '{0}', but its initialization value type is '{1}'"); } } } SolveAllTypeConstraints(); if (!CheckTypeInference_Visitor.IsDetermined(field.Type.NormalizeExpand())) { reporter.Error(MessageSource.Resolver, field.tok, "const field's type is not fully determined"); } } } currentClass = null; } } Contract.Assert(AllTypeConstraints.Count == 0); if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { // Check type inference, which also discovers bounds, in newtype/subset-type constraints and const declarations foreach (TopLevelDecl topd in declarations) { TopLevelDecl d = topd is ClassDecl ? ((ClassDecl)topd).NonNullTypeDecl : topd; if (d is RedirectingTypeDecl dd && dd.Constraint != null) { CheckTypeInference(dd.Constraint, dd); } if (topd is TopLevelDeclWithMembers cl) { foreach (var member in cl.Members) { if (member is ConstantField field && field.Rhs != null) { CheckTypeInference(field.Rhs, field); if (!field.IsGhost) { CheckIsCompilable(field.Rhs); } } } } } } // Now, we're ready for the other declarations, along with any witness clauses of newtype/subset-type declarations. foreach (TopLevelDecl d in declarations) { Contract.Assert(AllTypeConstraints.Count == 0); allTypeParameters.PushMarker(); ResolveTypeParameters(d.TypeArgs, false, d); if (d is NewtypeDecl || d is SubsetTypeDecl) { // NewTypeDecl's and SubsetTypeDecl's were already processed in the loop above, except for any witness clauses var dd = (RedirectingTypeDecl)d; if (dd.Witness != null) { var prevErrCnt = reporter.Count(ErrorLevel.Error); ResolveExpression(dd.Witness, new ResolveOpts(dd, false)); ConstrainSubtypeRelation(dd.Var.Type, dd.Witness.Type, dd.Witness, "witness expression must have type '{0}' (got '{1}')", dd.Var.Type, dd.Witness.Type); SolveAllTypeConstraints(); if (reporter.Count(ErrorLevel.Error) == prevErrCnt) { CheckTypeInference(dd.Witness, dd); } if (reporter.Count(ErrorLevel.Error) == prevErrCnt && dd.WitnessKind == SubsetTypeDecl.WKind.Compiled) { CheckIsCompilable(dd.Witness); } } if (d is TopLevelDeclWithMembers dm) { ResolveClassMemberBodies(dm); } } else { if (!(d is IteratorDecl)) { // Note, attributes of iterators are resolved by ResolvedIterator, after registering any names in the iterator signature ResolveAttributes(d.Attributes, d, new ResolveOpts(new NoContext(d.EnclosingModuleDefinition), false)); } if (d is IteratorDecl) { var iter = (IteratorDecl)d; ResolveIterator(iter); ResolveClassMemberBodies(iter); // resolve the automatically generated members } else if (d is DatatypeDecl) { var dt = (DatatypeDecl)d; foreach (var ctor in dt.Ctors) { foreach (var formal in ctor.Formals) { AddTypeDependencyEdges((ICallable)d, formal.Type); } } ResolveClassMemberBodies(dt); } else if (d is TopLevelDeclWithMembers) { var dd = (TopLevelDeclWithMembers)d; ResolveClassMemberBodies(dd); } } allTypeParameters.PopMarker(); } // ---------------------------------- Pass 1 ---------------------------------- // This pass: // * checks that type inference was able to determine all types // * check that shared destructors in datatypes are in agreement // * fills in the .ResolvedOp field of binary expressions // * discovers bounds for: // - forall statements // - set comprehensions // - map comprehensions // - quantifier expressions // - assign-such-that statements // - compilable let-such-that expressions // - newtype constraints // - subset-type constraints // For each statement body that it successfully typed, this pass also: // * computes ghost interests // * determines/checks tail-recursion. // ---------------------------------------------------------------------------- if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { // Check that type inference went well everywhere; this will also fill in the .ResolvedOp field in binary expressions // Also, for each datatype, check that shared destructors are in agreement foreach (TopLevelDecl d in declarations) { if (d is IteratorDecl) { var iter = (IteratorDecl)d; var prevErrCnt = reporter.Count(ErrorLevel.Error); iter.Members.Iter(CheckTypeInference_Member); if (prevErrCnt == reporter.Count(ErrorLevel.Error)) { iter.SubExpressions.Iter(e => CheckExpression(e, this, iter)); } if (iter.Body != null) { CheckTypeInference(iter.Body, iter); if (prevErrCnt == reporter.Count(ErrorLevel.Error)) { ComputeGhostInterest(iter.Body, false, iter); CheckExpression(iter.Body, this, iter); } } } else if (d is ClassDecl) { var dd = (ClassDecl)d; ResolveClassMembers_Pass1(dd); } else if (d is SubsetTypeDecl) { var dd = (SubsetTypeDecl)d; Contract.Assert(dd.Constraint != null); CheckExpression(dd.Constraint, this, new CodeContextWrapper(dd, true)); if (dd.Witness != null) { CheckExpression(dd.Witness, this, new CodeContextWrapper(dd, dd.WitnessKind == SubsetTypeDecl.WKind.Ghost)); } } else if (d is NewtypeDecl) { var dd = (NewtypeDecl)d; if (dd.Var != null) { Contract.Assert(dd.Constraint != null); CheckExpression(dd.Constraint, this, new CodeContextWrapper(dd, true)); if (dd.Witness != null) { CheckExpression(dd.Witness, this, new CodeContextWrapper(dd, dd.WitnessKind == SubsetTypeDecl.WKind.Ghost)); } } FigureOutNativeType(dd); ResolveClassMembers_Pass1(dd); } else if (d is DatatypeDecl) { var dd = (DatatypeDecl)d; foreach (var member in classMembers[dd].Values) { var dtor = member as DatatypeDestructor; if (dtor != null) { var rolemodel = dtor.CorrespondingFormals[0]; for (int i = 1; i < dtor.CorrespondingFormals.Count; i++) { var other = dtor.CorrespondingFormals[i]; if (!Type.Equal_Improved(rolemodel.Type, other.Type)) { reporter.Error(MessageSource.Resolver, other, "shared destructors must have the same type, but '{0}' has type '{1}' in constructor '{2}' and type '{3}' in constructor '{4}'", rolemodel.Name, rolemodel.Type, dtor.EnclosingCtors[0].Name, other.Type, dtor.EnclosingCtors[i].Name); } else if (rolemodel.IsGhost != other.IsGhost) { reporter.Error(MessageSource.Resolver, other, "shared destructors must agree on whether or not they are ghost, but '{0}' is {1} in constructor '{2}' and {3} in constructor '{4}'", rolemodel.Name, rolemodel.IsGhost ? "ghost" : "non-ghost", dtor.EnclosingCtors[0].Name, other.IsGhost ? "ghost" : "non-ghost", dtor.EnclosingCtors[i].Name); } } } } ResolveClassMembers_Pass1(dd); } else if (d is OpaqueTypeDecl) { var dd = (OpaqueTypeDecl)d; ResolveClassMembers_Pass1(dd); } } } // ---------------------------------- Pass 2 ---------------------------------- // This pass fills in various additional information. // ---------------------------------------------------------------------------- if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { // fill in the postconditions and bodies of prefix lemmas foreach (var com in ModuleDefinition.AllExtremeLemmas(declarations)) { var prefixLemma = com.PrefixLemma; if (prefixLemma == null) { continue; // something went wrong during registration of the prefix lemma (probably a duplicated extreme lemma name) } var k = prefixLemma.Ins[0]; var focalPredicates = new HashSet<ExtremePredicate>(); if (com is GreatestLemma) { // compute the postconditions of the prefix lemma Contract.Assume(prefixLemma.Ens.Count == 0); // these are not supposed to have been filled in before foreach (var p in com.Ens) { var coConclusions = new HashSet<Expression>(); CollectFriendlyCallsInExtremeLemmaSpecification(p.E, true, coConclusions, true, com); var subst = new ExtremeLemmaSpecificationSubstituter(coConclusions, new IdentifierExpr(k.tok, k.Name), this.reporter, true); var post = subst.CloneExpr(p.E); prefixLemma.Ens.Add(new AttributedExpression(post)); foreach (var e in coConclusions) { var fce = e as FunctionCallExpr; if (fce != null) { // the other possibility is that "e" is a BinaryExpr GreatestPredicate predicate = (GreatestPredicate)fce.Function; focalPredicates.Add(predicate); // For every focal predicate P in S, add to S all co-predicates in the same strongly connected // component (in the call graph) as P foreach (var node in predicate.EnclosingClass.EnclosingModuleDefinition.CallGraph.GetSCC(predicate)) { if (node is GreatestPredicate) { focalPredicates.Add((GreatestPredicate)node); } } } } } } else { // compute the preconditions of the prefix lemma Contract.Assume(prefixLemma.Req.Count == 0); // these are not supposed to have been filled in before foreach (var p in com.Req) { var antecedents = new HashSet<Expression>(); CollectFriendlyCallsInExtremeLemmaSpecification(p.E, true, antecedents, false, com); var subst = new ExtremeLemmaSpecificationSubstituter(antecedents, new IdentifierExpr(k.tok, k.Name), this.reporter, false); var pre = subst.CloneExpr(p.E); prefixLemma.Req.Add(new AttributedExpression(pre, p.Label, null)); foreach (var e in antecedents) { var fce = (FunctionCallExpr)e; // we expect "antecedents" to contain only FunctionCallExpr's LeastPredicate predicate = (LeastPredicate)fce.Function; focalPredicates.Add(predicate); // For every focal predicate P in S, add to S all least predicates in the same strongly connected // component (in the call graph) as P foreach (var node in predicate.EnclosingClass.EnclosingModuleDefinition.CallGraph.GetSCC(predicate)) { if (node is LeastPredicate) { focalPredicates.Add((LeastPredicate)node); } } } } } reporter.Info(MessageSource.Resolver, com.tok, string.Format("{0} with focal predicate{2} {1}", com.PrefixLemma.Name, Util.Comma(focalPredicates, p => p.Name), focalPredicates.Count == 1 ? "" : "s")); // Compute the statement body of the prefix lemma Contract.Assume(prefixLemma.Body == null); // this is not supposed to have been filled in before if (com.Body != null) { var kMinusOne = new BinaryExpr(com.tok, BinaryExpr.Opcode.Sub, new IdentifierExpr(k.tok, k.Name), new LiteralExpr(com.tok, 1)); var subst = new ExtremeLemmaBodyCloner(com, kMinusOne, focalPredicates, this.reporter); var mainBody = subst.CloneBlockStmt(com.Body); Expression kk; Statement els; if (k.Type.IsBigOrdinalType) { kk = new MemberSelectExpr(k.tok, new IdentifierExpr(k.tok, k.Name), "Offset"); // As an "else" branch, we add recursive calls for the limit case. When automatic induction is on, // this get handled automatically, but we still want it in the case when automatic inductino has been // turned off. // forall k', params | k' < _k && Precondition { // pp(k', params); // } Contract.Assume(builtIns.ORDINAL_Offset != null); // should have been filled in earlier var kId = new IdentifierExpr(com.tok, k); var kprimeVar = new BoundVar(com.tok, "_k'", Type.BigOrdinal); var kprime = new IdentifierExpr(com.tok, kprimeVar); var smaller = Expression.CreateLess(kprime, kId); var bvs = new List<BoundVar>(); // TODO: populate with k', params var substMap = new Dictionary<IVariable, Expression>(); foreach (var inFormal in prefixLemma.Ins) { if (inFormal == k) { bvs.Add(kprimeVar); substMap.Add(k, kprime); } else { var bv = new BoundVar(inFormal.tok, inFormal.Name, inFormal.Type); bvs.Add(bv); substMap.Add(inFormal, new IdentifierExpr(com.tok, bv)); } } Expression recursiveCallReceiver; List<Expression> recursiveCallArgs; Translator.RecursiveCallParameters(com.tok, prefixLemma, prefixLemma.TypeArgs, prefixLemma.Ins, substMap, out recursiveCallReceiver, out recursiveCallArgs); var methodSel = new MemberSelectExpr(com.tok, recursiveCallReceiver, prefixLemma.Name); methodSel.Member = prefixLemma; // resolve here methodSel.TypeApplication_AtEnclosingClass = prefixLemma.EnclosingClass.TypeArgs.ConvertAll(tp => (Type)new UserDefinedType(tp.tok, tp)); methodSel.TypeApplication_JustMember = prefixLemma.TypeArgs.ConvertAll(tp => (Type)new UserDefinedType(tp.tok, tp)); methodSel.Type = new InferredTypeProxy(); var recursiveCall = new CallStmt(com.tok, com.tok, new List<Expression>(), methodSel, recursiveCallArgs); recursiveCall.IsGhost = prefixLemma.IsGhost; // resolve here var range = smaller; // The range will be strengthened later with the call's precondition, substituted // appropriately (which can only be done once the precondition has been resolved). var attrs = new Attributes("_autorequires", new List<Expression>(), null); #if VERIFY_CORRECTNESS_OF_TRANSLATION_FORALL_STATEMENT_RANGE // don't add the :_trustWellformed attribute #else attrs = new Attributes("_trustWellformed", new List<Expression>(), attrs); #endif attrs = new Attributes("auto_generated", new List<Expression>(), attrs); var forallBody = new BlockStmt(com.tok, com.tok, new List<Statement>() { recursiveCall }); var forallStmt = new ForallStmt(com.tok, com.tok, bvs, attrs, range, new List<AttributedExpression>(), forallBody); els = new BlockStmt(com.BodyStartTok, mainBody.EndTok, new List<Statement>() { forallStmt }); } else { kk = new IdentifierExpr(k.tok, k.Name); els = null; } var kPositive = new BinaryExpr(com.tok, BinaryExpr.Opcode.Lt, new LiteralExpr(com.tok, 0), kk); var condBody = new IfStmt(com.BodyStartTok, mainBody.EndTok, false, kPositive, mainBody, els); prefixLemma.Body = new BlockStmt(com.tok, condBody.EndTok, new List<Statement>() { condBody }); } // The prefix lemma now has all its components, so it's finally time we resolve it currentClass = (TopLevelDeclWithMembers)prefixLemma.EnclosingClass; allTypeParameters.PushMarker(); ResolveTypeParameters(currentClass.TypeArgs, false, currentClass); ResolveTypeParameters(prefixLemma.TypeArgs, false, prefixLemma); ResolveMethod(prefixLemma); allTypeParameters.PopMarker(); currentClass = null; CheckTypeInference_Member(prefixLemma); } } // Perform the stratosphere check on inductive datatypes, and compute to what extent the inductive datatypes require equality support foreach (var dtd in datatypeDependencies.TopologicallySortedComponents()) { if (datatypeDependencies.GetSCCRepresentative(dtd) == dtd) { // do the following check once per SCC, so call it on each SCC representative SccStratosphereCheck(dtd, datatypeDependencies); DetermineEqualitySupport(dtd, datatypeDependencies); } } // Set the SccRepr field of codatatypes foreach (var repr in codatatypeDependencies.TopologicallySortedComponents()) { foreach (var codt in codatatypeDependencies.GetSCC(repr)) { codt.SscRepr = repr; } } if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { // because CheckCoCalls requires the given expression to have been successfully resolved // Perform the guardedness check on co-datatypes foreach (var repr in ModuleDefinition.AllFunctionSCCs(declarations)) { var module = repr.EnclosingModule; bool dealsWithCodatatypes = false; foreach (var m in module.CallGraph.GetSCC(repr)) { var f = m as Function; if (f != null && f.ResultType.InvolvesCoDatatype) { dealsWithCodatatypes = true; break; } } var coCandidates = new List<CoCallResolution.CoCallInfo>(); var hasIntraClusterCallsInDestructiveContexts = false; foreach (var m in module.CallGraph.GetSCC(repr)) { var f = m as Function; if (f != null && f.Body != null) { var checker = new CoCallResolution(f, dealsWithCodatatypes); checker.CheckCoCalls(f.Body); coCandidates.AddRange(checker.FinalCandidates); hasIntraClusterCallsInDestructiveContexts |= checker.HasIntraClusterCallsInDestructiveContexts; } else if (f == null) { // the SCC contains a method, which we always consider to be a destructive context hasIntraClusterCallsInDestructiveContexts = true; } } if (coCandidates.Count != 0) { if (hasIntraClusterCallsInDestructiveContexts) { foreach (var c in coCandidates) { c.CandidateCall.CoCall = FunctionCallExpr.CoCallResolution.NoBecauseRecursiveCallsInDestructiveContext; } } else { foreach (var c in coCandidates) { c.CandidateCall.CoCall = FunctionCallExpr.CoCallResolution.Yes; c.EnclosingCoConstructor.IsCoCall = true; reporter.Info(MessageSource.Resolver, c.CandidateCall.tok, "co-recursive call"); } // Finally, fill in the CoClusterTarget field // Start by setting all the CoClusterTarget fields to CoRecursiveTargetAllTheWay. foreach (var m in module.CallGraph.GetSCC(repr)) { var f = (Function)m; // the cast is justified on account of that we allow co-recursive calls only in clusters that have no methods at all f.CoClusterTarget = Function.CoCallClusterInvolvement.CoRecursiveTargetAllTheWay; } // Then change the field to IsMutuallyRecursiveTarget whenever we see a non-self recursive non-co-recursive call foreach (var m in module.CallGraph.GetSCC(repr)) { var f = (Function)m; // cast is justified just like above foreach (var call in f.AllCalls) { if (call.CoCall != FunctionCallExpr.CoCallResolution.Yes && call.Function != f && ModuleDefinition.InSameSCC(f, call.Function)) { call.Function.CoClusterTarget = Function.CoCallClusterInvolvement.IsMutuallyRecursiveTarget; } } } } } } // Inferred required equality support for datatypes and type synonyms, and for Function and Method signatures. // First, do datatypes and type synonyms until a fixpoint is reached. bool inferredSomething; do { inferredSomething = false; foreach (var d in declarations) { if (Attributes.Contains(d.Attributes, "_provided")) { // Don't infer required-equality-support for the type parameters, since there are // scopes that see the name of the declaration but not its body. } else if (d is DatatypeDecl) { var dt = (DatatypeDecl)d; foreach (var tp in dt.TypeArgs) { if (tp.Characteristics.EqualitySupport == TypeParameter.EqualitySupportValue.Unspecified) { // here's our chance to infer the need for equality support foreach (var ctor in dt.Ctors) { foreach (var arg in ctor.Formals) { if (InferRequiredEqualitySupport(tp, arg.Type)) { tp.Characteristics.EqualitySupport = TypeParameter.EqualitySupportValue.InferredRequired; inferredSomething = true; goto DONE_DT; // break out of the doubly-nested loop } } } DONE_DT:; } } } else if (d is TypeSynonymDecl) { var syn = (TypeSynonymDecl)d; foreach (var tp in syn.TypeArgs) { if (tp.Characteristics.EqualitySupport == TypeParameter.EqualitySupportValue.Unspecified) { // here's our chance to infer the need for equality support if (InferRequiredEqualitySupport(tp, syn.Rhs)) { tp.Characteristics.EqualitySupport = TypeParameter.EqualitySupportValue.InferredRequired; inferredSomething = true; } } } } } } while (inferredSomething); // Now do it for Function and Method signatures. foreach (var d in declarations) { if (d is IteratorDecl) { var iter = (IteratorDecl)d; var done = false; foreach (var tp in iter.TypeArgs) { if (tp.Characteristics.EqualitySupport == TypeParameter.EqualitySupportValue.Unspecified) { // here's our chance to infer the need for equality support foreach (var p in iter.Ins) { if (InferRequiredEqualitySupport(tp, p.Type)) { tp.Characteristics.EqualitySupport = TypeParameter.EqualitySupportValue.InferredRequired; done = true; break; } } foreach (var p in iter.Outs) { if (done) break; if (InferRequiredEqualitySupport(tp, p.Type)) { tp.Characteristics.EqualitySupport = TypeParameter.EqualitySupportValue.InferredRequired; break; } } } } } else if (d is ClassDecl) { var cl = (ClassDecl)d; foreach (var member in cl.Members) { if (!member.IsGhost) { if (member is Function) { var f = (Function)member; foreach (var tp in f.TypeArgs) { if (tp.Characteristics.EqualitySupport == TypeParameter.EqualitySupportValue.Unspecified) { // here's our chance to infer the need for equality support if (InferRequiredEqualitySupport(tp, f.ResultType)) { tp.Characteristics.EqualitySupport = TypeParameter.EqualitySupportValue.InferredRequired; } else { foreach (var p in f.Formals) { if (InferRequiredEqualitySupport(tp, p.Type)) { tp.Characteristics.EqualitySupport = TypeParameter.EqualitySupportValue.InferredRequired; break; } } } } } } else if (member is Method) { var m = (Method)member; bool done = false; foreach (var tp in m.TypeArgs) { if (tp.Characteristics.EqualitySupport == TypeParameter.EqualitySupportValue.Unspecified) { // here's our chance to infer the need for equality support foreach (var p in m.Ins) { if (InferRequiredEqualitySupport(tp, p.Type)) { tp.Characteristics.EqualitySupport = TypeParameter.EqualitySupportValue.InferredRequired; done = true; break; } } foreach (var p in m.Outs) { if (done) break; if (InferRequiredEqualitySupport(tp, p.Type)) { tp.Characteristics.EqualitySupport = TypeParameter.EqualitySupportValue.InferredRequired; break; } } } } } } } } } // Check that functions claiming to be abstemious really are foreach (var fn in ModuleDefinition.AllFunctions(declarations)) { if (fn.Body != null) { var abstemious = true; if (Attributes.ContainsBool(fn.Attributes, "abstemious", ref abstemious) && abstemious) { if (CoCallResolution.GuaranteedCoCtors(fn) == 0) { reporter.Error(MessageSource.Resolver, fn, "the value returned by an abstemious function must come from invoking a co-constructor"); } else { CheckDestructsAreAbstemiousCompliant(fn.Body); } } } } // Check that all == and != operators in non-ghost contexts are applied to equality-supporting types. // Note that this check can only be done after determining which expressions are ghosts. foreach (var d in declarations) { if (d is IteratorDecl) { var iter = (IteratorDecl)d; foreach (var p in iter.Ins) { if (!p.IsGhost) { CheckEqualityTypes_Type(p.tok, p.Type); } } foreach (var p in iter.Outs) { if (!p.IsGhost) { CheckEqualityTypes_Type(p.tok, p.Type); } } if (iter.Body != null) { CheckEqualityTypes_Stmt(iter.Body); } } else if (d is ClassDecl) { var cl = (ClassDecl)d; foreach (var parentTrait in cl.ParentTraits) { CheckEqualityTypes_Type(cl.tok, parentTrait); } foreach (var member in cl.Members) { if (!member.IsGhost) { if (member is Field) { var f = (Field)member; CheckEqualityTypes_Type(f.tok, f.Type); } else if (member is Function) { var f = (Function)member; foreach (var p in f.Formals) { if (!p.IsGhost) { CheckEqualityTypes_Type(p.tok, p.Type); } } CheckEqualityTypes_Type(f.tok, f.ResultType); if (f.Body != null) { CheckEqualityTypes(f.Body); } } else if (member is Method) { var m = (Method)member; foreach (var p in m.Ins) { if (!p.IsGhost) { CheckEqualityTypes_Type(p.tok, p.Type); } } foreach (var p in m.Outs) { if (!p.IsGhost) { CheckEqualityTypes_Type(p.tok, p.Type); } } if (m.Body != null) { CheckEqualityTypes_Stmt(m.Body); } } } } } else if (d is DatatypeDecl) { var dt = (DatatypeDecl)d; foreach (var ctor in dt.Ctors) { foreach (var p in ctor.Formals) { if (!p.IsGhost) { CheckEqualityTypes_Type(p.tok, p.Type); } } } } else if (d is TypeSynonymDecl) { var syn = (TypeSynonymDecl)d; CheckEqualityTypes_Type(syn.tok, syn.Rhs); if (!isAnExport) { if (syn.SupportsEquality && !syn.Rhs.SupportsEquality) { reporter.Error(MessageSource.Resolver, syn.tok, "type '{0}' declared as supporting equality, but the RHS type ({1}) might not", syn.Name, syn.Rhs); } if (syn.Characteristics.IsNonempty && !syn.Rhs.IsNonempty) { reporter.Error(MessageSource.Resolver, syn.tok, "type '{0}' declared as being nonempty, but the RHS type ({1}) may be empty", syn.Name, syn.Rhs); } else if (syn.Characteristics.HasCompiledValue && !syn.Rhs.HasCompilableValue) { reporter.Error(MessageSource.Resolver, syn.tok, "type '{0}' declared as auto-initialization type, but the RHS type ({1}) does not support auto-initialization", syn.Name, syn.Rhs); } if (syn.Characteristics.ContainsNoReferenceTypes && !syn.Rhs.IsAllocFree) { reporter.Error(MessageSource.Resolver, syn.tok, "type '{0}' declared as containing no reference types, but the RHS type ({1}) may contain reference types", syn.Name, syn.Rhs); } } } } // Check that extreme predicates are not recursive with non-extreme-predicate functions (and only // with extreme predicates of the same polarity), and // check that greatest lemmas are not recursive with non-greatest-lemma methods. // Also, check that the constraints of newtypes/subset-types do not depend on the type itself. // And check that const initializers are not cyclic. var cycleErrorHasBeenReported = new HashSet<ICallable>(); foreach (var d in declarations) { if (d is ClassDecl) { foreach (var member in ((ClassDecl)d).Members) { if (member is ExtremePredicate) { var fn = (ExtremePredicate)member; // Check here for the presence of any 'ensures' clauses, which are not allowed (because we're not sure // of their soundness) fn.Req.ForEach(e => ExtremePredicateChecks(e.E, fn, CallingPosition.Positive)); fn.Decreases.Expressions.ForEach(e => ExtremePredicateChecks(e, fn, CallingPosition.Positive)); fn.Reads.ForEach(e => ExtremePredicateChecks(e.E, fn, CallingPosition.Positive)); if (fn.Ens.Count != 0) { reporter.Error(MessageSource.Resolver, fn.Ens[0].E.tok, "a {0} is not allowed to declare any ensures clause", member.WhatKind); } if (fn.Body != null) { ExtremePredicateChecks(fn.Body, fn, CallingPosition.Positive); } } else if (member is ExtremeLemma) { var m = (ExtremeLemma)member; m.Req.ForEach(e => ExtremeLemmaChecks(e.E, m)); m.Ens.ForEach(e => ExtremeLemmaChecks(e.E, m)); m.Decreases.Expressions.ForEach(e => ExtremeLemmaChecks(e, m)); if (m.Body != null) { ExtremeLemmaChecks(m.Body, m); } } else if (member is ConstantField) { var cf = (ConstantField)member; if (cf.EnclosingModule.CallGraph.GetSCCSize(cf) != 1) { var r = cf.EnclosingModule.CallGraph.GetSCCRepresentative(cf); if (cycleErrorHasBeenReported.Contains(r)) { // An error has already been reported for this cycle, so don't report another. // Note, the representative, "r", may itself not be a const. } else { cycleErrorHasBeenReported.Add(r); var cycle = Util.Comma(" -> ", cf.EnclosingModule.CallGraph.GetSCC(cf), clbl => clbl.NameRelativeToModule); reporter.Error(MessageSource.Resolver, cf.tok, "const definition contains a cycle: " + cycle); } } } } } else if (d is SubsetTypeDecl || d is NewtypeDecl) { var dd = (RedirectingTypeDecl)d; if (d.EnclosingModuleDefinition.CallGraph.GetSCCSize(dd) != 1) { var r = d.EnclosingModuleDefinition.CallGraph.GetSCCRepresentative(dd); if (cycleErrorHasBeenReported.Contains(r)) { // An error has already been reported for this cycle, so don't report another. // Note, the representative, "r", may itself not be a const. } else { cycleErrorHasBeenReported.Add(r); var cycle = Util.Comma(" -> ", d.EnclosingModuleDefinition.CallGraph.GetSCC(dd), clbl => clbl.NameRelativeToModule); reporter.Error(MessageSource.Resolver, d.tok, "recursive constraint dependency involving a {0}: {1}", d.WhatKind, cycle); } } } } } // ---------------------------------- Pass 3 ---------------------------------- // Further checks // ---------------------------------------------------------------------------- if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { // Check that type-parameter variance is respected in type definitions foreach (TopLevelDecl d in declarations) { if (d is IteratorDecl || d is ClassDecl) { foreach (var tp in d.TypeArgs) { if (tp.Variance != TypeParameter.TPVariance.Non) { reporter.Error(MessageSource.Resolver, tp.tok, "{0} declarations only support non-variant type parameters", d.WhatKind); } } } else if (d is TypeSynonymDecl) { var dd = (TypeSynonymDecl)d; CheckVariance(dd.Rhs, dd, TypeParameter.TPVariance.Co, false); } else if (d is NewtypeDecl) { var dd = (NewtypeDecl)d; CheckVariance(dd.BaseType, dd, TypeParameter.TPVariance.Co, false); } else if (d is DatatypeDecl) { var dd = (DatatypeDecl)d; foreach (var ctor in dd.Ctors) { ctor.Formals.Iter(formal => CheckVariance(formal.Type, dd, TypeParameter.TPVariance.Co, false)); } } } } if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { // Check that usage of "this" is restricted before "new;" in constructor bodies, // and that a class without any constructor only has fields with known initializers. // Also check that static fields (which are necessarily const) have initializers. var cdci = new CheckDividedConstructorInit_Visitor(this); foreach (var cl in ModuleDefinition.AllClasses(declarations)) { if (cl is TraitDecl) { // traits never have constructors, but check for static consts foreach (var member in cl.Members) { if (member is ConstantField && member.IsStatic && !member.IsGhost) { var f = (ConstantField)member; if (!isAnExport && !cl.EnclosingModuleDefinition.IsAbstract && f.Rhs == null && !f.Type.HasCompilableValue && !f.IsExtern(out _, out _)) { reporter.Error(MessageSource.Resolver, f.tok, "static non-ghost const field '{0}' of type '{1}' (which does not have a default compiled value) must give a defining value", f.Name, f.Type); } } } continue; } var hasConstructor = false; Field fieldWithoutKnownInitializer = null; foreach (var member in cl.Members) { if (member is Constructor) { hasConstructor = true; var constructor = (Constructor)member; if (constructor.BodyInit != null) { cdci.CheckInit(constructor.BodyInit); } } else if (member is ConstantField && member.IsStatic && !member.IsGhost) { var f = (ConstantField)member; if (!isAnExport && !cl.EnclosingModuleDefinition.IsAbstract && f.Rhs == null && !f.Type.HasCompilableValue && !f.IsExtern(out _, out _)) { reporter.Error(MessageSource.Resolver, f.tok, "static non-ghost const field '{0}' of type '{1}' (which does not have a default compiled value) must give a defining value", f.Name, f.Type); } } else if (member is Field && !member.IsGhost && fieldWithoutKnownInitializer == null) { var f = (Field)member; if (f is ConstantField && ((ConstantField)f).Rhs != null) { // fine } else if (!f.Type.HasCompilableValue) { fieldWithoutKnownInitializer = f; } } } if (!hasConstructor) { if (fieldWithoutKnownInitializer == null) { // time to check inherited members foreach (var member in cl.InheritedMembers) { if (member is Field && !member.IsGhost) { var f = (Field)member; if (f is ConstantField && ((ConstantField)f).Rhs != null) { // fine } else if (!Resolver.SubstType(f.Type, cl.ParentFormalTypeParametersToActuals).HasCompilableValue) { fieldWithoutKnownInitializer = f; break; } } } } // go through inherited members... if (fieldWithoutKnownInitializer != null) { reporter.Error(MessageSource.Resolver, cl.tok, "class '{0}' with fields without known initializers, like '{1}' of type '{2}', must declare a constructor", cl.Name, fieldWithoutKnownInitializer.Name, Resolver.SubstType(fieldWithoutKnownInitializer.Type, cl.ParentFormalTypeParametersToActuals)); } } } } } private void ResolveClassMembers_Pass1(TopLevelDeclWithMembers cl) { foreach (var member in cl.Members) { var prevErrCnt = reporter.Count(ErrorLevel.Error); CheckTypeInference_Member(member); if (prevErrCnt == reporter.Count(ErrorLevel.Error)) { if (member is Method) { var m = (Method)member; if (m.Body != null) { ComputeGhostInterest(m.Body, m.IsGhost, m); CheckExpression(m.Body, this, m); DetermineTailRecursion(m); } } else if (member is Function) { var f = (Function)member; if (!f.IsGhost && f.Body != null) { CheckIsCompilable(f.Body); } if (f.Body != null) { DetermineTailRecursion(f); } } if (prevErrCnt == reporter.Count(ErrorLevel.Error) && member is ICodeContext) { member.SubExpressions.Iter(e => CheckExpression(e, this, (ICodeContext)member)); } } } } private void CheckDestructsAreAbstemiousCompliant(Expression expr) { Contract.Assert(expr != null); expr = expr.Resolved; if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; if (e.Member.EnclosingClass is CoDatatypeDecl) { var ide = Expression.StripParens(e.Obj).Resolved as IdentifierExpr; if (ide != null && ide.Var is Formal) { // cool } else { reporter.Error(MessageSource.Resolver, expr, "an abstemious function is allowed to invoke a codatatype destructor only on its parameters"); } return; } } else if (expr is MatchExpr) { var e = (MatchExpr)expr; if (e.Source.Type.IsCoDatatype) { var ide = Expression.StripParens(e.Source).Resolved as IdentifierExpr; if (ide != null && ide.Var is Formal) { // cool; fall through to check match branches } else { reporter.Error(MessageSource.Resolver, e.Source, "an abstemious function is allowed to codatatype-match only on its parameters"); return; } } } else if (expr is BinaryExpr) { var e = (BinaryExpr)expr; if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.EqCommon || e.ResolvedOp == BinaryExpr.ResolvedOpcode.NeqCommon) { if (e.E0.Type.IsCoDatatype) { reporter.Error(MessageSource.Resolver, expr, "an abstemious function is not only allowed to check codatatype equality"); return; } } } else if (expr is StmtExpr) { var e = (StmtExpr)expr; // ignore the statement part CheckDestructsAreAbstemiousCompliant(e.E); return; } expr.SubExpressions.Iter(CheckDestructsAreAbstemiousCompliant); } /// <summary> /// Add edges to the callgraph. /// </summary> private void AddTypeDependencyEdges(ICodeContext context, Type type) { Contract.Requires(type != null); Contract.Requires(context != null); var caller = context as ICallable; if (caller != null && type is NonProxyType) { type.ForeachTypeComponent(ty => { var udt = ty as UserDefinedType; var cl = udt == null ? null : udt.ResolvedClass as ICallable; if (cl != null) { caller.EnclosingModule.CallGraph.AddEdge(caller, cl); } }); } } private BigInteger MaxBV(Type t) { Contract.Requires(t != null); Contract.Requires(t.IsBitVectorType); return MaxBV(t.AsBitVectorType.Width); } private BigInteger MaxBV(int bits) { Contract.Requires(0 <= bits); return BigInteger.Pow(new BigInteger(2), bits) - BigInteger.One; } private void FigureOutNativeType(NewtypeDecl dd) { Contract.Requires(dd != null); // Look at the :nativeType attribute, if any bool mustUseNativeType; List<NativeType> nativeTypeChoices = null; // null means "no preference" var args = Attributes.FindExpressions(dd.Attributes, "nativeType"); if (args != null && !dd.BaseType.IsNumericBased(Type.NumericPersuasion.Int)) { reporter.Error(MessageSource.Resolver, dd, ":nativeType can only be used on integral types"); return; } else if (args == null) { // There was no :nativeType attribute mustUseNativeType = false; } else if (args.Count == 0) { mustUseNativeType = true; } else { var arg0Lit = args[0] as LiteralExpr; if (arg0Lit != null && arg0Lit.Value is bool) { if (!(bool)arg0Lit.Value) { // {:nativeType false} says "don't use native type", so our work here is done return; } mustUseNativeType = true; } else { mustUseNativeType = true; nativeTypeChoices = new List<NativeType>(); foreach (var arg in args) { if (arg is LiteralExpr lit && lit.Value is string s) { // Get the NativeType for "s" foreach (var nativeT in NativeTypes) { if (nativeT.Name == s) { nativeTypeChoices.Add(nativeT); goto FoundNativeType; } } reporter.Error(MessageSource.Resolver, dd, ":nativeType '{0}' not known", s); return; FoundNativeType: ; } else { reporter.Error(MessageSource.Resolver, arg, "unexpected :nativeType argument"); return; } } } } // Figure out the variable and constraint. Usually, these would be just .Var and .Constraint, but // in the case .Var is null, these can be computed from the .BaseType recursively. var ddVar = dd.Var; var ddConstraint = dd.Constraint; for (var ddWhereConstraintsAre = dd; ddVar == null;) { ddWhereConstraintsAre = ddWhereConstraintsAre.BaseType.AsNewtype; if (ddWhereConstraintsAre == null) { break; } ddVar = ddWhereConstraintsAre.Var; ddConstraint = ddWhereConstraintsAre.Constraint; } List<ComprehensionExpr.BoundedPool> bounds; if (ddVar == null) { // There are no bounds at all bounds = new List<ComprehensionExpr.BoundedPool>(); } else { bounds = DiscoverAllBounds_SingleVar(ddVar, ddConstraint); } // Returns null if the argument is a constrained newtype (recursively) // Returns the transitive base type if the argument is recusively unconstrained Type AsUnconstrainedType(Type t) { while (true) { if (t.AsNewtype == null) return t; if (t.AsNewtype.Constraint != null) return null; t = t.AsNewtype.BaseType; } } // Find which among the allowable native types can hold "dd". Give an // error for any user-specified native type that's not big enough. var bigEnoughNativeTypes = new List<NativeType>(); // But first, define a local, recursive function GetConst/GetAnyConst: // These fold any constant computations, including symbolic constants, // returning null if folding is not possible. If an operation is undefined // (divide by zero, conversion out of range, etc.), then null is returned. Func<Expression, BigInteger?> GetConst = null; Func<Expression, Stack<ConstantField>, Object> GetAnyConst = null; GetAnyConst = (Expression e, Stack<ConstantField> consts) => { if (e is LiteralExpr l) { return l.Value; } else if (e is UnaryOpExpr un) { if (un.Op == UnaryOpExpr.Opcode.Not) { object e0 = GetAnyConst(un.E, consts); if (e0 is bool) { return !(bool)e0; } if (un.Type.IsBitVectorType) { int width = un.Type.AsBitVectorType.Width; return ((BigInteger.One << width) - 1) ^ (BigInteger)e0; } } else if (un.Op == UnaryOpExpr.Opcode.Cardinality) { object e0 = GetAnyConst(un.E, consts); if (e0 is string ss) { return (BigInteger)(ss.Length); } } } else if (e is MemberSelectExpr m) { if (m.Member is ConstantField c && c.IsStatic && c.Rhs != null) { // This aspect of type resolution happens before the check for cyclic references // so we have to do a check here as well. If cyclic, null is silently returned, // counting on the later error message to alert the user. if (consts.Contains(c)) { return null; } consts.Push(c); Object o = GetAnyConst(c.Rhs, consts); consts.Pop(); return o; } else if (m.Member is SpecialField sf) { string nm = sf.Name; if (nm == "Floor") { Object ee = GetAnyConst(m.Obj, consts); if (ee != null && m.Obj.Type.IsNumericBased(Type.NumericPersuasion.Real)) { ((BaseTypes.BigDec)ee).FloorCeiling(out var f, out _); return f; } } } } else if (e is BinaryExpr bin) { Object e0 = GetAnyConst(bin.E0, consts); Object e1 = GetAnyConst(bin.E1, consts); bool isBool = bin.E0.Type == Type.Bool && bin.E1.Type == Type.Bool; bool shortCircuit = isBool && (bin.ResolvedOp == BinaryExpr.ResolvedOpcode.And || bin.ResolvedOp == BinaryExpr.ResolvedOpcode.Or || bin.ResolvedOp == BinaryExpr.ResolvedOpcode.Imp); if (e0 == null || (!shortCircuit && e1 == null)) { return null; } bool isAnyReal = bin.E0.Type.IsNumericBased(Type.NumericPersuasion.Real) && bin.E1.Type.IsNumericBased(Type.NumericPersuasion.Real); bool isAnyInt = bin.E0.Type.IsNumericBased(Type.NumericPersuasion.Int) && bin.E1.Type.IsNumericBased(Type.NumericPersuasion.Int); bool isReal = bin.Type.IsRealType; bool isInt = bin.Type.IsIntegerType; bool isBV = bin.E0.Type.IsBitVectorType; int width = isBV ? bin.E0.Type.AsBitVectorType.Width : 0; bool isString = e0 is string && e1 is string; switch (bin.ResolvedOp) { case BinaryExpr.ResolvedOpcode.Add: if (isInt) return (BigInteger)e0 + (BigInteger)e1; if (isBV) return ((BigInteger)e0 + (BigInteger)e1) & MaxBV(bin.Type); if (isReal) return (BaseTypes.BigDec)e0 + (BaseTypes.BigDec)e1; break; case BinaryExpr.ResolvedOpcode.Concat: if (isString) return (string)e0 + (string)e1; break; case BinaryExpr.ResolvedOpcode.Sub: if (isInt) return (BigInteger)e0 - (BigInteger)e1; if (isBV) return ((BigInteger)e0 - (BigInteger)e1) & MaxBV(bin.Type); if (isReal) return (BaseTypes.BigDec)e0 - (BaseTypes.BigDec)e1; // Allow a special case: If the result type is a newtype that is integer-based (i.e., isInt && !isInteger) // then we generally do not fold the operations, because we do not determine whether the // result of the operation satisfies the new type constraint. However, on the occasion that // a newtype aliases int without a constraint, it occurs that a value of the newtype is initialized // with a negative value, which is represented as "0 - N", that is, it comes to this case. It // is a nuisance not to constant-fold the result, as not doing so can alter the determination // of the representation type. if (isAnyInt && AsUnconstrainedType(bin.Type) != null) { return ((BigInteger)e0)-((BigInteger)e1); } break; case BinaryExpr.ResolvedOpcode.Mul: if (isInt) return (BigInteger)e0 * (BigInteger)e1; if (isBV) return ((BigInteger)e0 * (BigInteger)e1) & MaxBV(bin.Type); if (isReal) return (BaseTypes.BigDec)e0 * (BaseTypes.BigDec)e1; break; case BinaryExpr.ResolvedOpcode.BitwiseAnd: Contract.Assert(isBV); return (BigInteger)e0 & (BigInteger)e1; case BinaryExpr.ResolvedOpcode.BitwiseOr: Contract.Assert(isBV); return (BigInteger)e0 | (BigInteger)e1; case BinaryExpr.ResolvedOpcode.BitwiseXor: Contract.Assert(isBV); return (BigInteger)e0 ^ (BigInteger)e1; case BinaryExpr.ResolvedOpcode.Div: if (isInt) { if ((BigInteger)e1 == 0) { return null; // Divide by zero } else { BigInteger a0 = (BigInteger)e0; BigInteger a1 = (BigInteger)e1; BigInteger d = a0/a1; return a0 >= 0 || a0 == d*a1 ? d : a1 > 0 ? d-1 : d+1; } } if (isBV) { if ((BigInteger)e1 == 0) { return null; // Divide by zero } else { return ((BigInteger)e0) / ((BigInteger)e1); } } if (isReal) { if ((BaseTypes.BigDec)e1 == BaseTypes.BigDec.ZERO) { return null; // Divide by zero } else { // BigDec does not have divide and is not a representation of rationals, so we don't do constant folding return null; } } break; case BinaryExpr.ResolvedOpcode.Mod: if (isInt) { if ((BigInteger)e1 == 0) { return null; // Mod by zero } else { BigInteger a = BigInteger.Abs((BigInteger)e1); BigInteger d = (BigInteger)e0 % a; return (BigInteger)e0 >= 0 ? d : d+a; } } if (isBV) { if ((BigInteger)e1 == 0) { return null; // Mod by zero } else { return (BigInteger)e0 % (BigInteger)e1; } } break; case BinaryExpr.ResolvedOpcode.LeftShift: { if ((BigInteger)e1 < 0) { return null; // Negative shift } if ((BigInteger)e1 > bin.Type.AsBitVectorType.Width) { return null; // Shift is too large } return ((BigInteger)e0 << (int)(BigInteger)e1) & MaxBV(bin.E0.Type); } case BinaryExpr.ResolvedOpcode.RightShift: { if ((BigInteger)e1 < 0) { return null; // Negative shift } if ((BigInteger)e1 > bin.Type.AsBitVectorType.Width) { return null; // Shift too large } return (BigInteger)e0 >> (int)(BigInteger)e1; } case BinaryExpr.ResolvedOpcode.And: { if ((bool)e0 && e1 == null) return null; return (bool)e0 && (bool)e1; } case BinaryExpr.ResolvedOpcode.Or: { if (!(bool)e0 && e1 == null) return null; return (bool)e0 || (bool)e1; } case BinaryExpr.ResolvedOpcode.Imp: { // ==> and <== if ((bool)e0 && e1 == null) return null; return !(bool)e0 || (bool)e1; } case BinaryExpr.ResolvedOpcode.Iff: return (bool)e0 == (bool)e1; // <==> case BinaryExpr.ResolvedOpcode.Gt: if (isAnyInt) return (BigInteger)e0 > (BigInteger)e1; if (isBV) return (BigInteger)e0 > (BigInteger)e1; if (isAnyReal) return (BaseTypes.BigDec)e0 > (BaseTypes.BigDec)e1; break; case BinaryExpr.ResolvedOpcode.GtChar: if (bin.E0.Type.IsCharType) return ((string)e0)[0] > ((string)e1)[0]; break; case BinaryExpr.ResolvedOpcode.Ge: if (isAnyInt) return (BigInteger)e0 >= (BigInteger)e1; if (isBV) return (BigInteger)e0 >= (BigInteger)e1; if (isAnyReal) return (BaseTypes.BigDec)e0 >= (BaseTypes.BigDec)e1; break; case BinaryExpr.ResolvedOpcode.GeChar: if (bin.E0.Type.IsCharType) return ((string)e0)[0] >= ((string)e1)[0]; break; case BinaryExpr.ResolvedOpcode.Lt: if (isAnyInt) return (BigInteger)e0 < (BigInteger)e1; if (isBV) return (BigInteger)e0 < (BigInteger)e1; if (isAnyReal) return (BaseTypes.BigDec)e0 < (BaseTypes.BigDec)e1; break; case BinaryExpr.ResolvedOpcode.LtChar: if (bin.E0.Type.IsCharType) return ((string)e0)[0] < ((string)e1)[0]; break; case BinaryExpr.ResolvedOpcode.ProperPrefix: if (isString) return ((string)e1).StartsWith((string)e0) && !((string)e1).Equals((string) e0); break; case BinaryExpr.ResolvedOpcode.Le: if (isAnyInt) return (BigInteger)e0 <= (BigInteger)e1; if (isBV) return (BigInteger)e0 <= (BigInteger)e1; if (isAnyReal) return (BaseTypes.BigDec)e0 <= (BaseTypes.BigDec)e1; break; case BinaryExpr.ResolvedOpcode.LeChar: if (bin.E0.Type.IsCharType) return ((string)e0)[0] <= ((string)e1)[0]; break; case BinaryExpr.ResolvedOpcode.Prefix: if (isString) return ((string)e1).StartsWith((string)e0); break; case BinaryExpr.ResolvedOpcode.EqCommon: { if (isBool) { return (bool)e0 == (bool)e1; } else if (isAnyInt || isBV) { return (BigInteger)e0 == (BigInteger)e1; } else if (isAnyReal) { return (BaseTypes.BigDec)e0 == (BaseTypes.BigDec)e1; } else if (bin.E0.Type.IsCharType) { return ((string)e0)[0] == ((string)e1)[0]; } break; } case BinaryExpr.ResolvedOpcode.SeqEq: if (isString) { return (string)e0 == (string)e1; } break; case BinaryExpr.ResolvedOpcode.SeqNeq: if (isString) { return (string)e0 != (string)e1; } break; case BinaryExpr.ResolvedOpcode.NeqCommon: { if (isBool) { return (bool)e0 != (bool)e1; } else if (isAnyInt || isBV) { return (BigInteger)e0 != (BigInteger)e1; } else if (isAnyReal) { return (BaseTypes.BigDec)e0 != (BaseTypes.BigDec)e1; } else if (bin.E0.Type.IsCharType) { return ((string)e0)[0] != ((string)e1)[0]; } else if (isString) { return (string)e0 != (string)e1; } break; } } } else if (e is ConversionExpr ce) { object o = GetAnyConst(ce.E, consts); if (o == null || ce.E.Type == ce.Type) return o; if (ce.E.Type.IsNumericBased(Type.NumericPersuasion.Real) && ce.Type.IsBitVectorType) { ((BaseTypes.BigDec)o).FloorCeiling(out var ff, out _); if (ff < 0 || ff > MaxBV(ce.Type)) { return null; // Out of range } if (((BaseTypes.BigDec)o) != BaseTypes.BigDec.FromBigInt(ff)) { return null; // Out of range } return ff; } if (ce.E.Type.IsNumericBased(Type.NumericPersuasion.Real) && ce.Type.IsNumericBased(Type.NumericPersuasion.Int)) { ((BaseTypes.BigDec)o).FloorCeiling(out var ff, out _); if (AsUnconstrainedType(ce.Type) == null) return null; if (((BaseTypes.BigDec)o) != BaseTypes.BigDec.FromBigInt(ff)) { return null; // Argument not an integer } return ff; } if (ce.E.Type.IsBitVectorType && ce.Type.IsNumericBased(Type.NumericPersuasion.Int)) { if (AsUnconstrainedType(ce.Type) == null) return null; return o; } if (ce.E.Type.IsBitVectorType && ce.Type.IsNumericBased(Type.NumericPersuasion.Real)) { if (AsUnconstrainedType(ce.Type) == null) return null; return BaseTypes.BigDec.FromBigInt((BigInteger)o); } if (ce.E.Type.IsNumericBased(Type.NumericPersuasion.Int) && ce.Type.IsBitVectorType) { BigInteger b = (BigInteger)o; if (b < 0 || b > MaxBV(ce.Type)) { return null; // Argument out of range } return o; } if (ce.E.Type.IsNumericBased(Type.NumericPersuasion.Int) && ce.Type.IsNumericBased(Type.NumericPersuasion.Int)) { // This case includes int-based newtypes to int-based new types if (AsUnconstrainedType(ce.Type) == null) return null; return o; } if (ce.E.Type.IsNumericBased(Type.NumericPersuasion.Real) && ce.Type.IsNumericBased(Type.NumericPersuasion.Real)) { // This case includes real-based newtypes to real-based new types if (AsUnconstrainedType(ce.Type) == null) return null; return o; } if (ce.E.Type.IsBitVectorType && ce.Type.IsBitVectorType) { BigInteger b = (BigInteger)o; if (b < 0 || b > MaxBV(ce.Type)) { return null; // Argument out of range } return o; } if (ce.E.Type.IsNumericBased(Type.NumericPersuasion.Int) && ce.Type.IsNumericBased(Type.NumericPersuasion.Real)) { if (AsUnconstrainedType(ce.Type) == null) return null; return BaseTypes.BigDec.FromBigInt((BigInteger)o); } if (ce.E.Type.IsCharType && ce.Type.IsNumericBased(Type.NumericPersuasion.Int)) { char c = ((String)o)[0]; if (AsUnconstrainedType(ce.Type) == null) return null; return new BigInteger(((string)o)[0]); } if (ce.E.Type.IsCharType && ce.Type.IsBitVectorType) { char c = ((String)o)[0]; if ((int)c > MaxBV(ce.Type)) { return null; // Argument out of range } return new BigInteger(((string)o)[0]); } if ((ce.E.Type.IsNumericBased(Type.NumericPersuasion.Int) || ce.E.Type.IsBitVectorType) && ce.Type.IsCharType) { BigInteger b = (BigInteger)o; if (b < BigInteger.Zero || b > new BigInteger(65535)) { return null; // Argument out of range } return ((char) (int)b).ToString(); } if (ce.E.Type.IsCharType && ce.Type.IsNumericBased(Type.NumericPersuasion.Real)) { if (AsUnconstrainedType(ce.Type) == null) return null; return BaseTypes.BigDec.FromInt(((string)o)[0]); } if (ce.E.Type.IsNumericBased(Type.NumericPersuasion.Real) && ce.Type.IsCharType) { ((BaseTypes.BigDec)o).FloorCeiling(out var ff, out _); if (((BaseTypes.BigDec)o) != BaseTypes.BigDec.FromBigInt(ff)) { return null; // Argument not an integer } if (ff < BigInteger.Zero || ff > new BigInteger(65535)) { return null; // Argument out of range } return ((char) (int)ff).ToString(); } } else if (e is SeqSelectExpr sse) { var b = GetAnyConst(sse.Seq, consts) as string; BigInteger index = (BigInteger)GetAnyConst(sse.E0, consts); if (b == null) return null; if (index < 0 || index >= b.Length || index > Int32.MaxValue) { return null; // Index out of range } return b[(int)index].ToString(); } else if (e is ITEExpr ite) { Object b = GetAnyConst(ite.Test, consts); if (b == null) return null; return ((bool)b) ? GetAnyConst(ite.Thn, consts) : GetAnyConst(ite.Els, consts); } else if (e is ConcreteSyntaxExpression n) { return GetAnyConst(n.ResolvedExpression, consts); } else { return null; } return null; }; GetConst = (Expression e) => { Object ee = GetAnyConst(e.Resolved ?? e, new Stack<ConstantField>()); return ee as BigInteger?; }; // Now, then, let's go through them types. // FIXME - should first go through the bounds to find the most constraining values // then check those values against the possible types. Note that also presumes the types are in order. BigInteger? lowest = null; BigInteger? highest = null; foreach (var bound in bounds) { if (bound is ComprehensionExpr.IntBoundedPool) { var bnd = (ComprehensionExpr.IntBoundedPool)bound; if (bnd.LowerBound != null) { BigInteger? lower = GetConst(bnd.LowerBound); if (lower != null && (lowest == null || lower < lowest)) { lowest = lower; } } if (bnd.UpperBound != null) { BigInteger? upper = GetConst(bnd.UpperBound); if (upper != null && (highest == null || upper > highest)) { highest = upper; } } } } foreach (var nativeT in nativeTypeChoices ?? NativeTypes) { bool lowerOk = (lowest != null && nativeT.LowerBound <= lowest); bool upperOk = (highest != null && nativeT.UpperBound >= highest); if (lowerOk && upperOk) { bigEnoughNativeTypes.Add(nativeT); } else if (nativeTypeChoices != null) { reporter.Error(MessageSource.Resolver, dd, "Dafny's heuristics failed to confirm '{0}' to be a compatible native type. " + "Hint: try writing a newtype constraint of the form 'i:int | lowerBound <= i < upperBound && (...any additional constraints...)'", nativeT.Name); return; } } // Finally, of the big-enough native types, pick the first one that is // supported by the selected target compiler. foreach (var nativeT in bigEnoughNativeTypes) { if ((nativeT.CompilationTargets & DafnyOptions.O.CompileTarget) != 0) { dd.NativeType = nativeT; break; } } if (dd.NativeType != null) { // Give an info message saying which type was selected--unless the user requested // one particular native type, in which case that must have been the one picked. if (nativeTypeChoices != null && nativeTypeChoices.Count == 1) { Contract.Assert(dd.NativeType == nativeTypeChoices[0]); } else { reporter.Info(MessageSource.Resolver, dd.tok, "newtype " + dd.Name + " resolves as {:nativeType \"" + dd.NativeType.Name + "\"} (Detected Range: " + lowest + " .. " + highest + ")"); } } else if (nativeTypeChoices != null) { reporter.Error(MessageSource.Resolver, dd, "None of the types given in :nativeType arguments is supported by the current compilation target. Try supplying others."); } else if (mustUseNativeType) { reporter.Error(MessageSource.Resolver, dd, "Dafny's heuristics cannot find a compatible native type. " + "Hint: try writing a newtype constraint of the form 'i:int | lowerBound <= i < upperBound && (...any additional constraints...)'"); } } TypeProxy NewIntegerBasedProxy(IToken tok) { Contract.Requires(tok != null); var proxy = new InferredTypeProxy(); ConstrainSubtypeRelation(new IntVarietiesSupertype(), proxy, tok, "integer literal used as if it had type {0}", proxy); return proxy; } private bool ConstrainSubtypeRelation(Type super, Type sub, Expression exprForToken, string msg, params object[] msgArgs) { Contract.Requires(sub != null); Contract.Requires(super != null); Contract.Requires(exprForToken != null); Contract.Requires(msg != null); Contract.Requires(msgArgs != null); return ConstrainSubtypeRelation(super, sub, exprForToken.tok, msg, msgArgs); } private void ConstrainTypeExprBool(Expression e, string msg) { Contract.Requires(e != null); Contract.Requires(msg != null); // expected to have a {0} part ConstrainSubtypeRelation(Type.Bool, e.Type, e, msg, e.Type); } private bool ConstrainSubtypeRelation(Type super, Type sub, IToken tok, string msg, params object[] msgArgs) { Contract.Requires(sub != null); Contract.Requires(super != null); Contract.Requires(tok != null); Contract.Requires(msg != null); Contract.Requires(msgArgs != null); return ConstrainSubtypeRelation(super, sub, new TypeConstraint.ErrorMsgWithToken(tok, msg, msgArgs)); } private void ConstrainAssignable(NonProxyType lhs, Type rhs, TypeConstraint.ErrorMsg errMsg, out bool moreXConstraints, bool allowDecisions) { Contract.Requires(lhs != null); Contract.Requires(rhs != null); Contract.Requires(errMsg != null); bool isRoot, isLeaf, headIsRoot, headIsLeaf; CheckEnds(lhs, out isRoot, out isLeaf, out headIsRoot, out headIsLeaf); if (isRoot) { ConstrainSubtypeRelation(lhs, rhs, errMsg, true, allowDecisions); moreXConstraints = false; } else { var lhsWithProxyArgs = Type.HeadWithProxyArgs(lhs); ConstrainSubtypeRelation(lhsWithProxyArgs, rhs, errMsg, false, allowDecisions); ConstrainAssignableTypeArgs(lhs, lhsWithProxyArgs.TypeArgs, lhs.TypeArgs, errMsg, out moreXConstraints); if (Type.SameHead(lhs, rhs, true) && lhs.AsCollectionType == null) { bool more2; ConstrainAssignableTypeArgs(lhs, lhs.TypeArgs, rhs.TypeArgs, errMsg, out more2); moreXConstraints = moreXConstraints || more2; } } } private void ConstrainAssignableTypeArgs(Type typeHead, List<Type> A, List<Type> B, TypeConstraint.ErrorMsg errMsg, out bool moreXConstraints) { Contract.Requires(typeHead != null); Contract.Requires(A != null); Contract.Requires(B != null); Contract.Requires(A.Count == B.Count); Contract.Requires(errMsg != null); var tok = errMsg.Tok; if (B.Count == 0) { // all done moreXConstraints = false; } else if (typeHead is MapType) { var em = new TypeConstraint.ErrorMsgWithBase(errMsg, "covariance for type parameter 0 expects {1} <: {0}", A[0], B[0]); AddAssignableConstraint(tok, A[0], B[0], em); em = new TypeConstraint.ErrorMsgWithBase(errMsg, "covariance for type parameter 1 expects {1} <: {0}", A[1], B[1]); AddAssignableConstraint(tok, A[1], B[1], em); moreXConstraints = true; } else if (typeHead is CollectionType) { var em = new TypeConstraint.ErrorMsgWithBase(errMsg, "covariance for type parameter expects {1} <: {0}", A[0], B[0]); AddAssignableConstraint(tok, A[0], B[0], em); moreXConstraints = true; } else { var udt = (UserDefinedType)typeHead; // note, collections, maps, and user-defined types are the only one with TypeArgs.Count != 0 var cl = udt.ResolvedClass; Contract.Assert(cl != null); Contract.Assert(cl.TypeArgs.Count == B.Count); moreXConstraints = false; for (int i = 0; i < B.Count; i++) { var msgFormat = "variance for type parameter" + (B.Count == 1 ? "" : "" + i) + " expects {0} {1} {2}"; if (cl.TypeArgs[i].Variance == TypeParameter.TPVariance.Co) { var em = new TypeConstraint.ErrorMsgWithBase(errMsg, "co" + msgFormat, A[i], ":>", B[i]); AddAssignableConstraint(tok, A[i], B[i], em); moreXConstraints = true; } else if (cl.TypeArgs[i].Variance == TypeParameter.TPVariance.Contra) { var em = new TypeConstraint.ErrorMsgWithBase(errMsg, "contra" + msgFormat, A[i], "<:", B[i]); AddAssignableConstraint(tok, B[i], A[i], em); moreXConstraints = true; } else { var em = new TypeConstraint.ErrorMsgWithBase(errMsg, "non" + msgFormat, A[i], "=", B[i]); ConstrainSubtypeRelation_Equal(A[i], B[i], em); } } } } /// <summary> /// Adds the subtyping constraint that "a" and "b" are the same type. /// </summary> private void ConstrainSubtypeRelation_Equal(Type a, Type b, TypeConstraint.ErrorMsg errMsg) { Contract.Requires(a != null); Contract.Requires(b != null); Contract.Requires(errMsg != null); var proxy = a.Normalize() as TypeProxy; if (proxy != null && proxy.T == null && !Reaches(b, proxy, 1, new HashSet<TypeProxy>())) { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: (invariance) assigning proxy {0}.T := {1}", proxy, b); } proxy.T = b; } proxy = b.Normalize() as TypeProxy; if (proxy != null && proxy.T == null && !Reaches(a, proxy, 1, new HashSet<TypeProxy>())) { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: (invariance) assigning proxy {0}.T := {1}", proxy, a); } proxy.T = a; } ConstrainSubtypeRelation(a, b, errMsg, true); ConstrainSubtypeRelation(b, a, errMsg, true); } /// <summary> /// Adds the subtyping constraint that "sub" is a subtype of "super". /// If this constraint seems feasible, returns "true". Otherwise, prints error message (either "errMsg" or something /// more specific) and returns "false". /// Note, if in doubt, this method can return "true", because the constraints will be checked for sure at a later stage. /// </summary> private bool ConstrainSubtypeRelation(Type super, Type sub, TypeConstraint.ErrorMsg errMsg, bool keepConstraints = false, bool allowDecisions = false) { Contract.Requires(sub != null); Contract.Requires(super != null); Contract.Requires(errMsg != null); if (!keepConstraints && super is InferredTypeProxy) { var ip = (InferredTypeProxy)super; if (ip.KeepConstraints) { keepConstraints = true; } } if (!keepConstraints && sub is InferredTypeProxy) { var ip = (InferredTypeProxy)sub; if (ip.KeepConstraints) { keepConstraints = true; } } super = super.NormalizeExpand(keepConstraints); sub = sub.NormalizeExpand(keepConstraints); var c = new TypeConstraint(super, sub, errMsg, keepConstraints); AllTypeConstraints.Add(c); return ConstrainSubtypeRelation_Aux(super, sub, c, keepConstraints, allowDecisions); } private bool ConstrainSubtypeRelation_Aux(Type super, Type sub, TypeConstraint c, bool keepConstraints, bool allowDecisions) { Contract.Requires(sub != null); Contract.Requires(!(sub is TypeProxy) || ((TypeProxy)sub).T == null); // caller is expected to have Normalized away proxies Contract.Requires(super != null); Contract.Requires(!(super is TypeProxy) || ((TypeProxy)super).T == null); // caller is expected to have Normalized away proxies Contract.Requires(c != null); if (object.ReferenceEquals(super, sub)) { return true; } else if (super is TypeProxy && sub is TypeProxy) { // both are proxies ((TypeProxy)sub).AddSupertype(c); ((TypeProxy)super).AddSubtype(c); return true; } else if (sub is TypeProxy) { var proxy = (TypeProxy)sub; proxy.AddSupertype(c); AssignKnownEnd(proxy, keepConstraints, allowDecisions); return true; } else if (super is TypeProxy) { var proxy = (TypeProxy)super; proxy.AddSubtype(c); AssignKnownEnd(proxy, keepConstraints, allowDecisions); return true; } else { // two non-proxy types // set "headSymbolsAgree" to "false" if it's clear the head symbols couldn't be the same; "true" means they may be the same bool headSymbolsAgree = Type.IsHeadSupertypeOf(super.NormalizeExpand(keepConstraints), sub); if (!headSymbolsAgree) { c.FlagAsError(); return false; } // TODO: inspect type parameters in order to produce some error messages sooner return true; } } /// <summary> /// "root" says that the type is a non-artificial type with no proper supertypes. /// "leaf" says that the only possible proper subtypes are subset types of the type. Thus, the only /// types that are not leaf types are traits and artificial types. /// The "headIs" versions speak only about the head symbols, so it is possible that the given /// type arguments would change the root/leaf status of the entire type. /// </summary> void CheckEnds(Type t, out bool isRoot, out bool isLeaf, out bool headIsRoot, out bool headIsLeaf) { Contract.Requires(t != null); Contract.Ensures(!Contract.ValueAtReturn(out isRoot) || Contract.ValueAtReturn(out headIsRoot)); // isRoot ==> headIsRoot Contract.Ensures(!Contract.ValueAtReturn(out isLeaf) || Contract.ValueAtReturn(out headIsLeaf)); // isLeaf ==> headIsLeaf t = t.NormalizeExpandKeepConstraints(); if (t.IsBoolType || t.IsCharType || t.IsIntegerType || t.IsRealType || t.AsNewtype != null || t.IsBitVectorType || t.IsBigOrdinalType) { isRoot = true; isLeaf = true; headIsRoot = true; headIsLeaf = true; } else if (t is ArtificialType) { isRoot = false; isLeaf = false; headIsRoot = false; headIsLeaf = false; } else if (t.IsObjectQ) { isRoot = true; isLeaf = false; headIsRoot = true; headIsLeaf = false; } else if (t is ArrowType) { var arr = (ArrowType)t; headIsRoot = true; headIsLeaf = true; // these are definitely true isRoot = true; isLeaf = true; // set these to true until proven otherwise Contract.Assert(arr.Arity + 1 == arr.TypeArgs.Count); for (int i = 0; i < arr.TypeArgs.Count; i++) { var arg = arr.TypeArgs[i]; bool r, l, hr, hl; CheckEnds(arg, out r, out l, out hr, out hl); if (i < arr.Arity) { isRoot &= l; isLeaf &= r; // argument types are contravariant } else { isRoot &= r; isLeaf &= l; // result type is covariant } } } else if (t is UserDefinedType) { var udt = (UserDefinedType)t; var cl = udt.ResolvedClass; if (cl != null) { if (cl is SubsetTypeDecl) { headIsRoot = false; headIsLeaf = true; } else if (cl is TraitDecl) { headIsRoot = false; headIsLeaf = false; } else if (cl is ClassDecl) { headIsRoot = false; headIsLeaf = true; } else if (cl is OpaqueTypeDecl) { headIsRoot = true; headIsLeaf = true; } else if (cl is InternalTypeSynonymDecl) { Contract.Assert(object.ReferenceEquals(t, t.NormalizeExpand())); // should be opaque in scope headIsRoot = true; headIsLeaf = true; } else { Contract.Assert(cl is DatatypeDecl); headIsRoot = true; headIsLeaf = true; } // for "isRoot" and "isLeaf", also take into consideration the root/leaf status of type arguments isRoot = headIsRoot; isLeaf = headIsLeaf; Contract.Assert(udt.TypeArgs.Count == cl.TypeArgs.Count); for (int i = 0; i < udt.TypeArgs.Count; i++) { var variance = cl.TypeArgs[i].Variance; if (variance != TypeParameter.TPVariance.Non) { bool r, l, hr, hl; CheckEnds(udt.TypeArgs[i], out r, out l, out hr, out hl); if (variance == TypeParameter.TPVariance.Co) { isRoot &= r; isLeaf &= l; } else { isRoot &= l; isLeaf &= r; } } } } else if (t.IsTypeParameter) { var tp = udt.AsTypeParameter; Contract.Assert(tp != null); isRoot = true; isLeaf = true; // all type parameters are invariant headIsRoot = true; headIsLeaf = true; } else { isRoot = false; isLeaf = false; // don't know headIsRoot = false; headIsLeaf = false; } } else if (t is MapType) { // map, imap Contract.Assert(t.TypeArgs.Count == 2); bool r0, l0, r1, l1, hr, hl; CheckEnds(t.TypeArgs[0], out r0, out l0, out hr, out hl); CheckEnds(t.TypeArgs[1], out r1, out l1, out hr, out hl); isRoot = r0 & r1; isLeaf = r0 & r1; // map types are covariant in both type arguments headIsRoot = true; headIsLeaf = true; } else if (t is CollectionType) { // set, iset, multiset, seq Contract.Assert(t.TypeArgs.Count == 1); bool hr, hl; CheckEnds(t.TypeArgs[0], out isRoot, out isLeaf, out hr, out hl); // type is covariant is type argument headIsRoot = true; headIsLeaf = true; } else { isRoot = false; isLeaf = false; // don't know headIsRoot = false; headIsLeaf = false; } } int _recursionDepth = 0; private bool AssignProxyAndHandleItsConstraints(TypeProxy proxy, Type t, bool keepConstraints = false) { Contract.Requires(proxy != null); Contract.Requires(proxy.T == null); Contract.Requires(t != null); Contract.Requires(!(t is TypeProxy)); Contract.Requires(!(t is ArtificialType)); if (_recursionDepth == 20000) { Contract.Assume(false); // possible infinite recursion } _recursionDepth++; var b = AssignProxyAndHandleItsConstraints_aux(proxy, t, keepConstraints); _recursionDepth--; return b; } /// <summary> /// This method is called if "proxy" is an unassigned proxy and "t" is a type whose head symbol is known. /// It always sets "proxy.T" to "t". /// Then, it deals with the constraints of "proxy" as follows: /// * If the constraint compares "t" with a non-proxy with a head comparable with that of "t", /// then add constraints that the type arguments satisfy the desired subtyping constraint /// * If the constraint compares "t" with a non-proxy with a head not comparable with that of "t", /// then report an error /// * If the constraint compares "t" with a proxy, then (depending on the constraint and "t") attempt /// to recursively set it /// After this process, the proxy's .Supertypes and .Subtypes lists of constraints are no longer needed. /// If anything is found to be infeasible, "false" is returned (and the propagation may be interrupted); /// otherwise, "true" is returned. /// </summary> private bool AssignProxyAndHandleItsConstraints_aux(TypeProxy proxy, Type t, bool keepConstraints = false) { Contract.Requires(proxy != null); Contract.Requires(proxy.T == null); Contract.Requires(t != null); Contract.Requires(!(t is TypeProxy)); Contract.Requires(!(t is ArtificialType)); t = keepConstraints ? t.Normalize() : t.NormalizeExpand(); // never violate the type constraint of a literal expression var followedRequestedAssignment = true; foreach (var su in proxy.Supertypes) { if (su is IntVarietiesSupertype) { var fam = TypeProxy.GetFamily(t); if (fam == TypeProxy.Family.IntLike || fam == TypeProxy.Family.BitVector || fam == TypeProxy.Family.Ordinal) { // good, let's continue with the request to equate the proxy with t // unless... if (t != t.NormalizeExpand()) { // force the type to be a base type if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: hijacking {0}.T := {1} to instead assign {2}", proxy, t, t.NormalizeExpand()); } t = t.NormalizeExpand(); followedRequestedAssignment = false; } } else { // hijack the setting of proxy; to do that, we decide on a particular int variety now if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: hijacking {0}.T := {1} to instead assign {2}", proxy, t, Type.Int); } t = Type.Int; followedRequestedAssignment = false; } break; } else if (su is RealVarietiesSupertype) { if (TypeProxy.GetFamily(t) == TypeProxy.Family.RealLike) { // good, let's continue with the request to equate the proxy with t // unless... if (t != t.NormalizeExpand()) { // force the type to be a base type if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: hijacking {0}.T := {1} to instead assign {2}", proxy, t, t.NormalizeExpand()); } t = t.NormalizeExpand(); followedRequestedAssignment = false; } } else { // hijack the setting of proxy; to do that, we decide on a particular real variety now if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: hijacking {0}.T := {1} to instead assign {2}", proxy, t, Type.Real); } t = Type.Real; followedRequestedAssignment = false; } break; } } // set proxy.T right away, so that we can freely recurse without having to worry about infinite recursion if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: setting proxy {0}.T := {1}", proxy, t); } proxy.T = t; // check feasibility bool isRoot, isLeaf, headRoot, headLeaf; CheckEnds(t, out isRoot, out isLeaf, out headRoot, out headLeaf); // propagate up foreach (var c in proxy.SupertypeConstraints) { var u = keepConstraints ? c.Super.NormalizeExpandKeepConstraints() : c.Super.NormalizeExpand(); if (!(u is TypeProxy)) { ImposeSubtypingConstraint(u, t, c.errorMsg); } else if (isRoot) { // If t is a root, we might as well constrain u now. Otherwise, we'll wait until the .Subtype constraint of u is dealt with. AssignProxyAndHandleItsConstraints((TypeProxy)u, t, keepConstraints); } } // propagate down foreach (var c in proxy.SubtypeConstraints) { var u = keepConstraints ? c.Sub.NormalizeExpandKeepConstraints() : c.Sub.NormalizeExpand(); Contract.Assert(!TypeProxy.IsSupertypeOfLiteral(u)); // these should only appear among .Supertypes if (!(u is TypeProxy)) { ImposeSubtypingConstraint(t, u, c.errorMsg); } else if (isLeaf) { // If t is a leaf (no pun intended), we might as well constrain u now. Otherwise, we'll wait until the .Supertype constraint of u is dealt with. AssignProxyAndHandleItsConstraints((TypeProxy)u, t, keepConstraints); } } return followedRequestedAssignment; } /// <summary> /// Impose constraints that "sub" is a subtype of "super", returning "false" if this leads to an overconstrained situation. /// In most cases, "sub" being a subtype of "super" means that "sub" and "super" have the same head symbol and, therefore, the /// same number of type arguments. Depending on the polarities of the type parameters, the corresponding arguments /// of "sub" and "super" must be in co-, in-, or contra-variant relationships to each other. /// There are two ways "sub" can be a subtype of "super" without the two having the same head symbol. /// One way is that "sub" is a subset type. In this case, the method starts by moving "sub" up toward "super". /// The other way is that "super" is a trait (possibly /// the trait "object"). By a current restriction in Dafny's type system, traits have no type parameters, so in this case, it /// suffices to check that the head symbol of "super" is something that derives from "sub". /// </summary> private bool ImposeSubtypingConstraint(Type super, Type sub, TypeConstraint.ErrorMsg errorMsg) { Contract.Requires(super != null && !(super is TypeProxy)); Contract.Requires(sub != null && !(sub is TypeProxy)); Contract.Requires(errorMsg != null); List<int> polarities = ConstrainTypeHead_Recursive(super, ref sub); if (polarities == null) { errorMsg.FlagAsError(); return false; } bool keepConstraints = KeepConstraints(super, sub); var p = polarities.Count; Contract.Assert(p == super.TypeArgs.Count); // postcondition of ConstrainTypeHead Contract.Assert(p == 0 || sub.TypeArgs.Count == super.TypeArgs.Count); // postcondition of ConstrainTypeHead for (int i = 0; i < p; i++) { var pol = polarities[i]; var tp = p == 1 ? "" : " " + i; var errMsg = new TypeConstraint.ErrorMsgWithBase(errorMsg, pol < 0 ? "contravariant type parameter{0} would require {1} <: {2}" : pol > 0 ? "covariant type parameter{0} would require {2} <: {1}" : "non-variant type parameter{0} would require {1} = {2}", tp, super.TypeArgs[i], sub.TypeArgs[i]); if (pol >= 0) { if (!ConstrainSubtypeRelation(super.TypeArgs[i], sub.TypeArgs[i], errMsg, keepConstraints)) { return false; } } if (pol <= 0) { if (!ConstrainSubtypeRelation(sub.TypeArgs[i], super.TypeArgs[i], errMsg, keepConstraints)) { return false; } } } return true; } /// <summary> /// This is a more liberal version of "ConstrainTypeHead" below. It is willing to move "sub" /// upward toward its parents until it finds a head that matches "super", if any. /// </summary> private static List<int> ConstrainTypeHead_Recursive(Type super, ref Type sub) { Contract.Requires(super != null); Contract.Requires(sub != null); super = super.NormalizeExpandKeepConstraints(); sub = sub.NormalizeExpandKeepConstraints(); var polarities = ConstrainTypeHead(super, sub); if (polarities != null) { return polarities; } foreach (var subParentType in sub.ParentTypes()) { sub = subParentType; polarities = ConstrainTypeHead_Recursive(super, ref sub); if (polarities != null) { return polarities; } } return null; } /// <summary> /// Determines if the head of "sub" can be a subtype of "super". /// If this is not possible, null is returned. /// If it is possible, return a list of polarities, one for each type argument of "sub". Polarities /// indicate: /// +1 co-variant /// 0 invariant /// -1 contra-variant /// "sub" is of some type that can (in general) have type parameters. /// See also note about Dafny's current type system in the description of method "ImposeSubtypingConstraint". /// </summary> private static List<int> ConstrainTypeHead(Type super, Type sub) { Contract.Requires(super != null && !(super is TypeProxy)); Contract.Requires(sub != null && !(sub is TypeProxy)); if (super is IntVarietiesSupertype) { var famSub = TypeProxy.GetFamily(sub); if (famSub == TypeProxy.Family.IntLike || famSub == TypeProxy.Family.BitVector || famSub == TypeProxy.Family.Ordinal || super.Equals(sub)) { return new List<int>(); } else { return null; } } else if (super is RealVarietiesSupertype) { if (TypeProxy.GetFamily(sub) == TypeProxy.Family.RealLike || super.Equals(sub)) { return new List<int>(); } else { return null; } } switch (TypeProxy.GetFamily(super)) { case TypeProxy.Family.Bool: case TypeProxy.Family.Char: case TypeProxy.Family.IntLike: case TypeProxy.Family.RealLike: case TypeProxy.Family.Ordinal: case TypeProxy.Family.BitVector: if (super.Equals(sub)) { return new List<int>(); } else { return null; } case TypeProxy.Family.ValueType: case TypeProxy.Family.Ref: case TypeProxy.Family.Opaque: break; // more elaborate work below case TypeProxy.Family.Unknown: default: // just in case the family is mentioned explicitly as one of the cases Contract.Assert(false); // unexpected type (the precondition of ConstrainTypeHead says "no proxies") return null; // please compiler } if (super is SetType) { var tt = (SetType)super; var uu = sub as SetType; return uu != null && tt.Finite == uu.Finite ? new List<int> { 1 } : null; } else if (super is SeqType) { return sub is SeqType ? new List<int> { 1 } : null; } else if (super is MultiSetType) { return sub is MultiSetType ? new List<int> { 1 } : null; } else if (super is MapType) { var tt = (MapType)super; var uu = sub as MapType; return uu != null && tt.Finite == uu.Finite ? new List<int> { 1, 1 } : null; } else if (super.IsObjectQ) { return sub.IsRefType ? new List<int>() : null; } else { // The only remaining cases are that "super" is a (co)datatype, opaque type, or non-object trait/class. // In each of these cases, "super" is a UserDefinedType. var udfSuper = (UserDefinedType)super; var clSuper = udfSuper.ResolvedClass; if (clSuper == null) { Contract.Assert(super.TypeArgs.Count == 0); if (super.IsTypeParameter) { // we're looking at a type parameter return super.AsTypeParameter == sub.AsTypeParameter ? new List<int>() : null; } else { Contract.Assert(super.IsInternalTypeSynonym); return super.AsInternalTypeSynonym == sub.AsInternalTypeSynonym ? new List<int>() : null; } } var udfSub = sub as UserDefinedType; var clSub = udfSub == null ? null : udfSub.ResolvedClass; if (clSub == null) { return null; } else if (clSuper == clSub) { // good var polarities = new List<int>(); Contract.Assert(clSuper.TypeArgs.Count == udfSuper.TypeArgs.Count); Contract.Assert(clSuper.TypeArgs.Count == udfSub.TypeArgs.Count); foreach (var tp in clSuper.TypeArgs) { var polarity = TypeParameter.Direction(tp.Variance); polarities.Add(polarity); } return polarities; } else if (udfSub.IsRefType && super.IsObjectQ) { return new List<int>(); } else if (udfSub.IsNonNullRefType && super.IsObject) { return new List<int>(); } else { return null; } } } private static bool KeepConstraints(Type super, Type sub) { Contract.Requires(super != null && !(super is TypeProxy)); Contract.Requires(sub != null && !(sub is TypeProxy)); if (super is IntVarietiesSupertype) { return false; } else if (super is RealVarietiesSupertype) { return false; } switch (TypeProxy.GetFamily(super)) { case TypeProxy.Family.Bool: case TypeProxy.Family.Char: case TypeProxy.Family.IntLike: case TypeProxy.Family.RealLike: case TypeProxy.Family.Ordinal: case TypeProxy.Family.BitVector: return false; case TypeProxy.Family.ValueType: case TypeProxy.Family.Ref: case TypeProxy.Family.Opaque: break; // more elaborate work below case TypeProxy.Family.Unknown: return false; } if (super is SetType || super is SeqType || super is MultiSetType || super is MapType) { return true; } else if (super is ArrowType) { return false; } else if (super.IsObjectQ) { return false; } else { // super is UserDefinedType return true; } } public List<TypeConstraint> AllTypeConstraints = new List<TypeConstraint>(); public List<XConstraint> AllXConstraints = new List<XConstraint>(); public class XConstraint { public readonly IToken tok; public readonly string ConstraintName; public readonly Type[] Types; public readonly TypeConstraint.ErrorMsg errorMsg; public XConstraint(IToken tok, string constraintName, Type[] types, TypeConstraint.ErrorMsg errMsg) { Contract.Requires(tok != null); Contract.Requires(constraintName != null); Contract.Requires(types != null); Contract.Requires(errMsg != null); this.tok = tok; ConstraintName = constraintName; Types = types; errorMsg = errMsg; } public override string ToString() { var s = ConstraintName + ":"; foreach (var t in Types) { s += " " + t; } return s; } /// <summary> /// Tries to confirm the XConstraint. /// If the XConstraint can be confirmed, or at least is plausible enough to have been converted into other type /// constraints or more XConstraints, then "true" is returned and the out-parameters "convertedIntoOtherTypeConstraints" /// and "moreXConstraints" are set to true accordingly. /// If the XConstraint can be refuted, then an error message will be produced and "true" is returned (to indicate /// that this XConstraint has finished serving its purpose). /// If there's not enough information to confirm or refute the XConstraint, then "false" is returned. /// </summary> public bool Confirm(Resolver resolver, bool fullstrength, out bool convertedIntoOtherTypeConstraints, out bool moreXConstraints) { Contract.Requires(resolver != null); convertedIntoOtherTypeConstraints = false; moreXConstraints = false; var t = Types[0].NormalizeExpand(); if (t is TypeProxy) { switch (ConstraintName) { case "Assignable": case "Equatable": case "EquatableArg": case "Indexable": case "Innable": case "MultiIndexable": case "IntOrORDINAL": // have a go downstairs break; default: return false; // there's not enough information to confirm or refute this XConstraint } } bool satisfied; Type tUp, uUp; switch (ConstraintName) { case "Assignable": { Contract.Assert(t == t.Normalize()); // it's already been normalized above var u = Types[1].NormalizeExpand(); if (CheckTypeInference_Visitor.IsDetermined(t) && (fullstrength || !ProxyWithNoSubTypeConstraint(u, resolver) || (Types[0].NormalizeExpandKeepConstraints().IsNonNullRefType && u is TypeProxy && resolver.HasApplicableNullableRefTypeConstraint(new HashSet<TypeProxy>() {(TypeProxy)u})))) { // This is the best case. We convert Assignable(t, u) to the subtype constraint base(t) :> u. if (CheckTypeInference_Visitor.IsDetermined(u) && t.IsSubtypeOf(u, false) && t.IsRefType) { // But we also allow cases where the rhs is a proper supertype of the lhs, and let the verifier // determine whether the rhs is provably an instance of the lhs. resolver.ConstrainAssignable((NonProxyType)u, (NonProxyType)t, errorMsg, out moreXConstraints, fullstrength); } else { resolver.ConstrainAssignable((NonProxyType)t, u, errorMsg, out moreXConstraints, fullstrength); } convertedIntoOtherTypeConstraints = true; return true; } else if (u.IsTypeParameter) { // we need the constraint base(t) :> u, which for a type parameter t can happen iff t :> u resolver.ConstrainSubtypeRelation(t, u, errorMsg); convertedIntoOtherTypeConstraints = true; return true; } else if (Type.FromSameHead(t, u, out tUp, out uUp)) { resolver.ConstrainAssignableTypeArgs(tUp, tUp.TypeArgs, uUp.TypeArgs, errorMsg, out moreXConstraints); return true; } else if (fullstrength && t is NonProxyType) { // We convert Assignable(t, u) to the subtype constraint base(t) :> u. resolver.ConstrainAssignable((NonProxyType)t, u, errorMsg, out moreXConstraints, fullstrength); convertedIntoOtherTypeConstraints = true; return true; } else if (fullstrength && u is NonProxyType) { // We're willing to change "base(t) :> u" to the stronger constraint "t :> u" for the sake of making progress. resolver.ConstrainSubtypeRelation(t, u, errorMsg); convertedIntoOtherTypeConstraints = true; return true; } // There's not enough information to say anything return false; } case "NumericType": satisfied = t.IsNumericBased(); break; case "IntegerType": satisfied = t.IsNumericBased(Type.NumericPersuasion.Int); break; case "IsBitvector": satisfied = t.IsBitVectorType; break; case "IsRefType": satisfied = t.IsRefType; break; case "IsNullableRefType": satisfied = t.IsRefType && !t.IsNonNullRefType; break; case "Orderable_Lt": satisfied = t.IsNumericBased() || t.IsBitVectorType || t.IsBigOrdinalType || t.IsCharType || t is SeqType || t is SetType || t is MultiSetType; break; case "Orderable_Gt": satisfied = t.IsNumericBased() || t.IsBitVectorType || t.IsBigOrdinalType || t.IsCharType || t is SetType || t is MultiSetType; break; case "RankOrderable": { var u = Types[1].NormalizeExpand(); if (u is TypeProxy) { return false; // not enough information } satisfied = (t.IsIndDatatype || t.IsTypeParameter) && u.IsIndDatatype; break; } case "Plussable": satisfied = t.IsNumericBased() || t.IsBitVectorType || t.IsBigOrdinalType || t.IsCharType || t is SeqType || t is SetType || t is MultiSetType || t is MapType; break; case "Minusable": satisfied = t.IsNumericBased() || t.IsBitVectorType || t.IsBigOrdinalType || t.IsCharType || t is SetType || t is MultiSetType || t is MapType; break; case "Mullable": satisfied = t.IsNumericBased() || t.IsBitVectorType || t is SetType || t is MultiSetType; break; case "IntOrORDINAL": if (!(t is TypeProxy)) { if (TernaryExpr.PrefixEqUsesNat) { satisfied = t.IsNumericBased(Type.NumericPersuasion.Int); } else { satisfied = t.IsNumericBased(Type.NumericPersuasion.Int) || t.IsBigOrdinalType; } } else if (fullstrength) { var proxy = (TypeProxy)t; if (TernaryExpr.PrefixEqUsesNat) { resolver.AssignProxyAndHandleItsConstraints(proxy, Type.Int); } else { // let's choose ORDINAL over int resolver.AssignProxyAndHandleItsConstraints(proxy, Type.BigOrdinal); } convertedIntoOtherTypeConstraints = true; satisfied = true; } else { return false; } break; case "NumericOrBitvector": satisfied = t.IsNumericBased() || t.IsBitVectorType; break; case "NumericOrBitvectorOrCharOrORDINAL": satisfied = t.IsNumericBased() || t.IsBitVectorType || t.IsCharType || t.IsBigOrdinalType; break; case "IntLikeOrBitvector": satisfied = t.IsNumericBased(Type.NumericPersuasion.Int) || t.IsBitVectorType; break; case "BooleanBits": satisfied = t.IsBoolType || t.IsBitVectorType; break; case "Sizeable": satisfied = (t is SetType && ((SetType)t).Finite) || t is MultiSetType || t is SeqType || (t is MapType && ((MapType)t).Finite); break; case "Disjointable": satisfied = t is SetType || t is MultiSetType; break; case "MultiSetConvertible": satisfied = (t is SetType && ((SetType)t).Finite) || t is SeqType; if (satisfied) { Type elementType = ((CollectionType)t).Arg; var u = Types[1]; // note, it's okay if "u" is a TypeProxy var em = new TypeConstraint.ErrorMsgWithBase(errorMsg, "expecting element type {0} (got {1})", u, elementType); resolver.ConstrainSubtypeRelation_Equal(elementType, u, em); convertedIntoOtherTypeConstraints = true; } break; case "IsCoDatatype": satisfied = t.IsCoDatatype; break; case "Indexable": if (!(t is TypeProxy)) { satisfied = t is SeqType || t is MultiSetType || t is MapType || (t.IsArrayType && t.AsArrayType.Dims == 1); } else { // t is a proxy, but perhaps it stands for something between "object" and "array<?>". If so, we can add a constraint // that it does have the form "array<?>", since "object" would not be Indexable. var proxy = (TypeProxy)t; Type meet = null; if (resolver.MeetOfAllSubtypes(proxy, ref meet, new HashSet<TypeProxy>()) && meet != null) { var tt = Type.HeadWithProxyArgs(meet); satisfied = tt is SeqType || tt is MultiSetType || tt is MapType || (tt.IsArrayType && tt.AsArrayType.Dims == 1); if (satisfied) { resolver.AssignProxyAndHandleItsConstraints(proxy, tt, true); convertedIntoOtherTypeConstraints = true; } } else { return false; // we can't determine the answer } } break; case "MultiIndexable": if (!(t is TypeProxy)) { satisfied = t is SeqType || (t.IsArrayType && t.AsArrayType.Dims == 1); } else { // t is a proxy, but perhaps it stands for something between "object" and "array<?>". If so, we can add a constraint // that it does have the form "array<?>", since "object" would not be Indexable. var proxy = (TypeProxy)t; Type meet = null; if (resolver.MeetOfAllSubtypes(proxy, ref meet, new HashSet<TypeProxy>()) && meet != null) { var tt = Type.HeadWithProxyArgs(meet); satisfied = tt is SeqType || (tt.IsArrayType && tt.AsArrayType.Dims == 1); if (satisfied) { resolver.AssignProxyAndHandleItsConstraints(proxy, tt, true); convertedIntoOtherTypeConstraints = true; } } else { return false; // we can't determine the answer } } break; case "Innable": { var elementType = FindCollectionType(t, true, new HashSet<TypeProxy>()) ?? FindCollectionType(t, false, new HashSet<TypeProxy>()); if (elementType != null) { var u = Types[1]; // note, it's okay if "u" is a TypeProxy resolver.AddXConstraint(this.tok, "Equatable", elementType, u, new TypeConstraint.ErrorMsgWithBase(errorMsg, "expecting element type to be assignable to {1} (got {0})", u, elementType)); moreXConstraints = true; return true; } if (t is TypeProxy) { return false; // not enough information to do anything } satisfied = false; break; } case "SeqUpdatable": { var xcWithExprs = (XConstraintWithExprs)this; var index = xcWithExprs.Exprs[0]; var value = xcWithExprs.Exprs[1]; if (t is SeqType) { var s = (SeqType)t; resolver.ConstrainToIntegerType(index, true, "sequence update requires integer- or bitvector-based index (got {0})"); resolver.ConstrainSubtypeRelation(s.Arg, value.Type, value, "sequence update requires the value to have the element type of the sequence (got {0})", value.Type); } else if (t is MapType) { var s = (MapType)t; if (s.Finite) { resolver.ConstrainSubtypeRelation(s.Domain, index.Type, index, "map update requires domain element to be of type {0} (got {1})", s.Domain, index.Type); resolver.ConstrainSubtypeRelation(s.Range, value.Type, value, "map update requires the value to have the range type {0} (got {1})", s.Range, value.Type); } else { resolver.ConstrainSubtypeRelation(s.Domain, index.Type, index, "imap update requires domain element to be of type {0} (got {1})", s.Domain, index.Type); resolver.ConstrainSubtypeRelation(s.Range, value.Type, value, "imap update requires the value to have the range type {0} (got {1})", s.Range, value.Type); } } else if (t is MultiSetType) { var s = (MultiSetType)t; resolver.ConstrainSubtypeRelation(s.Arg, index.Type, index, "multiset update requires domain element to be of type {0} (got {1})", s.Arg, index.Type); resolver.ConstrainToIntegerType(value, false, "multiset update requires integer-based numeric value (got {0})"); } else { satisfied = false; break; } convertedIntoOtherTypeConstraints = true; return true; } case "ContainerIndex": // The semantics of this XConstraint is that *if* the head is seq/array/map/multiset, then its element/domain type must a supertype of "u" Type indexType; if (t is SeqType || t.IsArrayType) { resolver.ConstrainToIntegerType(errorMsg.Tok, Types[1], true, errorMsg); convertedIntoOtherTypeConstraints = true; return true; } else if (t is MapType) { indexType = ((MapType)t).Domain; } else if (t is MultiSetType) { indexType = ((MultiSetType)t).Arg; } else { // some other head symbol; that's cool return true; } // note, it's okay if "Types[1]" is a TypeProxy resolver.ConstrainSubtypeRelation(indexType, Types[1], errorMsg); // use the same error message convertedIntoOtherTypeConstraints = true; return true; case "ContainerResult": // The semantics of this XConstraint is that *if* the head is seq/array/map/multiset, then the type of a selection must a subtype of "u" Type resultType; if (t is SeqType) { resultType = ((SeqType)t).Arg; } else if (t.IsArrayType) { resultType = UserDefinedType.ArrayElementType(t); } else if (t is MapType) { resultType = ((MapType)t).Range; } else if (t is MultiSetType) { resultType = resolver.builtIns.Nat(); } else { // some other head symbol; that's cool return true; } // note, it's okay if "Types[1]" is a TypeProxy resolver.ConstrainSubtypeRelation(Types[1], resultType, errorMsg); convertedIntoOtherTypeConstraints = true; return true; case "Equatable": { t = Types[0].NormalizeExpandKeepConstraints(); var u = Types[1].NormalizeExpandKeepConstraints(); if (object.ReferenceEquals(t, u)) { return true; } if (t is TypeProxy && u is TypeProxy) { return false; // not enough information to do anything sensible } else if (t is TypeProxy || u is TypeProxy) { TypeProxy proxy; Type other; if (t is TypeProxy) { proxy = (TypeProxy)t; other = u; } else { proxy = (TypeProxy)u; other = t; } if (other.IsNumericBased() || other.IsBitVectorType || other.IsBigOrdinalType) { resolver.ConstrainSubtypeRelation(other.NormalizeExpand(), proxy, errorMsg, true); convertedIntoOtherTypeConstraints = true; return true; } else if (fullstrength) { // the following is rather aggressive if (Resolver.TypeConstraintsIncludeProxy(other, proxy)) { return false; } else { if (other.IsRefType && resolver.HasApplicableNullableRefTypeConstraint_SubDirection(proxy)) { other = other.NormalizeExpand(); // shave off all constraints } satisfied = resolver.AssignProxyAndHandleItsConstraints(proxy, other, true); convertedIntoOtherTypeConstraints = true; break; } } else { return false; // not enough information } } Type a, b; satisfied = Type.FromSameHead_Subtype(t, u, resolver.builtIns, out a, out b); if (satisfied) { Contract.Assert(a.TypeArgs.Count == b.TypeArgs.Count); var cl = a is UserDefinedType ? ((UserDefinedType)a).ResolvedClass : null; for (int i = 0; i < a.TypeArgs.Count; i++) { resolver.AllXConstraints.Add(new XConstraint_EquatableArg(tok, a.TypeArgs[i], b.TypeArgs[i], a is CollectionType || (cl != null && cl.TypeArgs[i].Variance != TypeParameter.TPVariance.Non), a.IsRefType, errorMsg)); moreXConstraints = true; } } break; } case "EquatableArg": { t = Types[0].NormalizeExpandKeepConstraints(); var u = Types[1].NormalizeExpandKeepConstraints(); var moreExactThis = (XConstraint_EquatableArg)this; if (t is TypeProxy && u is TypeProxy) { return false; // not enough information to do anything sensible } else if (t is TypeProxy || u is TypeProxy) { TypeProxy proxy; Type other; if (t is TypeProxy) { proxy = (TypeProxy)t; other = u; } else { proxy = (TypeProxy)u; other = t; } if (other.IsNumericBased() || other.IsBitVectorType || other.IsBigOrdinalType) { resolver.ConstrainSubtypeRelation(other.NormalizeExpand(), proxy, errorMsg, true); convertedIntoOtherTypeConstraints = true; return true; } else if (fullstrength) { // the following is rather aggressive if (Resolver.TypeConstraintsIncludeProxy(other, proxy)) { return false; } else { if (other.IsRefType && resolver.HasApplicableNullableRefTypeConstraint_SubDirection(proxy)) { other = other.NormalizeExpand(); // shave off all constraints } satisfied = resolver.AssignProxyAndHandleItsConstraints(proxy, other, true); convertedIntoOtherTypeConstraints = true; break; } } else { return false; // not enough information } } if (moreExactThis.TreatTypeParamAsWild && (t.IsTypeParameter || u.IsTypeParameter)) { return true; } else if (!moreExactThis.AllowSuperSub) { resolver.ConstrainSubtypeRelation_Equal(t, u, errorMsg); convertedIntoOtherTypeConstraints = true; return true; } Type a, b; // okay if t<:u or u<:t (this makes type inference more manageable, though it is more liberal than one might wish) satisfied = Type.FromSameHead_Subtype(t, u, resolver.builtIns, out a, out b); if (satisfied) { Contract.Assert(a.TypeArgs.Count == b.TypeArgs.Count); var cl = a is UserDefinedType ? ((UserDefinedType)a).ResolvedClass : null; for (int i = 0; i < a.TypeArgs.Count; i++) { resolver.AllXConstraints.Add(new XConstraint_EquatableArg(tok, a.TypeArgs[i], b.TypeArgs[i], a is CollectionType || (cl != null && cl.TypeArgs[i].Variance != TypeParameter.TPVariance.Non), false, errorMsg)); moreXConstraints = true; } } break; } case "Freshable": { var collType = t.AsCollectionType; if (collType != null) { t = collType.Arg.NormalizeExpand(); } if (t is TypeProxy) { return false; // there is not enough information } satisfied = t.IsRefType; break; } case "ModifiesFrame": { var u = Types[1].NormalizeExpand(); // eventual ref type var collType = t is MapType ? null : t.AsCollectionType; if (collType != null) { t = collType.Arg.NormalizeExpand(); } if (t is TypeProxy) { if (collType != null) { // we know enough to convert into a subtyping constraint resolver.AddXConstraint(Token.NoToken/*bogus, but it seems this token would be used only when integers are involved*/, "IsRefType", t, errorMsg); moreXConstraints = true; resolver.ConstrainSubtypeRelation_Equal(u, t, errorMsg); moreXConstraints = true; convertedIntoOtherTypeConstraints = true; return true; } else { return false; // there is not enough information } } if (t.IsRefType) { resolver.ConstrainSubtypeRelation_Equal(u, t, errorMsg); convertedIntoOtherTypeConstraints = true; return true; } satisfied = false; break; } case "ReadsFrame": { var u = Types[1].NormalizeExpand(); // eventual ref type var arrTy = t.AsArrowType; if (arrTy != null) { t = arrTy.Result.NormalizeExpand(); } var collType = t is MapType ? null : t.AsCollectionType; if (collType != null) { t = collType.Arg.NormalizeExpand(); } if (t is TypeProxy) { if (collType != null) { // we know enough to convert into a subtyping constraint resolver.AddXConstraint(Token.NoToken/*bogus, but it seems this token would be used only when integers are involved*/, "IsRefType", t, errorMsg); resolver.ConstrainSubtypeRelation_Equal(u, t, errorMsg); moreXConstraints = true; convertedIntoOtherTypeConstraints = true; return true; } else { return false; // there is not enough information } } if (t.IsRefType) { resolver.ConstrainSubtypeRelation_Equal(u, t, errorMsg); convertedIntoOtherTypeConstraints = true; return true; } satisfied = false; break; } default: Contract.Assume(false); // unknown XConstraint return false; // to please the compiler } if (!satisfied) { errorMsg.FlagAsError(); } return true; // the XConstraint has served its purpose } public bool ProxyWithNoSubTypeConstraint(Type u, Resolver resolver) { Contract.Requires(u != null); Contract.Requires(resolver != null); var proxy = u as TypeProxy; if (proxy != null) { if (proxy.SubtypeConstraints.Any()) { return false; } foreach (var xc in resolver.AllXConstraints) { if (xc.ConstraintName == "Assignable" && xc.Types[0] == proxy) { return false; } } return true; } return false; } bool IsEqDetermined(Type t) { Contract.Requires(t != null); switch (TypeProxy.GetFamily(t)) { case TypeProxy.Family.Bool: case TypeProxy.Family.Char: case TypeProxy.Family.IntLike: case TypeProxy.Family.RealLike: case TypeProxy.Family.Ordinal: case TypeProxy.Family.BitVector: return true; case TypeProxy.Family.ValueType: case TypeProxy.Family.Ref: case TypeProxy.Family.Opaque: case TypeProxy.Family.Unknown: default: return false; // TODO: could be made more exact } } internal bool CouldBeAnything() { return Types.All(t => t.NormalizeExpand() is TypeProxy); } /// <summary> /// If "t" or any type among its transitive sub/super-types (depending on "towardsSub") /// is a collection type, then returns the element/domain type of that collection. /// Otherwise, returns null. /// </summary> static Type FindCollectionType(Type t, bool towardsSub, ISet<TypeProxy> visited) { Contract.Requires(t != null); Contract.Requires(visited != null); t = t.NormalizeExpand(); if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: FindCollectionType({0}, {1})", t, towardsSub ? "sub" : "super"); } if (t is CollectionType) { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: FindCollectionType({0}) = {1}", t, ((CollectionType)t).Arg); } return ((CollectionType)t).Arg; } var proxy = t as TypeProxy; if (proxy == null || visited.Contains(proxy)) { return null; } visited.Add(proxy); foreach (var sub in towardsSub ? proxy.Subtypes : proxy.Supertypes) { var e = FindCollectionType(sub, towardsSub, visited); if (e != null) { return e; } } return null; } } public class XConstraintWithExprs : XConstraint { public readonly Expression[] Exprs; public XConstraintWithExprs(IToken tok, string constraintName, Type[] types, Expression[] exprs, TypeConstraint.ErrorMsg errMsg) : base(tok, constraintName, types, errMsg) { Contract.Requires(tok != null); Contract.Requires(constraintName != null); Contract.Requires(types != null); Contract.Requires(exprs != null); Contract.Requires(errMsg != null); this.Exprs = exprs; } } public class XConstraint_EquatableArg : XConstraint { public bool AllowSuperSub; public bool TreatTypeParamAsWild; public XConstraint_EquatableArg(IToken tok, Type a, Type b, bool allowSuperSub, bool treatTypeParamAsWild, TypeConstraint.ErrorMsg errMsg) : base(tok, "EquatableArg", new Type[] { a, b }, errMsg) { Contract.Requires(tok != null); Contract.Requires(a != null); Contract.Requires(b != null); Contract.Requires(errMsg != null); AllowSuperSub = allowSuperSub; TreatTypeParamAsWild = treatTypeParamAsWild; } } /// <summary> /// Solves or simplifies as many type constraints as possible. /// If "allowDecisions" is "false", then no decisions, only determined inferences, are made; this mode is /// appropriate for the partial solving that's done before a member lookup. /// </summary> void PartiallySolveTypeConstraints(bool allowDecisions) { int state = 0; while (true) { if (2 <= state && !allowDecisions) { // time to say goodnight to Napoli return; } else if (AllTypeConstraints.Count == 0 && AllXConstraints.Count == 0) { // we're done return; } var anyNewConstraints = false; var fullStrength = false; // Process subtyping constraints PrintTypeConstraintState(220 + 2 * state); switch (state) { case 0: { var allTypeConstraints = AllTypeConstraints; AllTypeConstraints = new List<TypeConstraint>(); var processed = new HashSet<TypeConstraint>(); foreach (var c in allTypeConstraints) { ProcessOneSubtypingConstraintAndItsSubs(c, processed, fullStrength, ref anyNewConstraints); } allTypeConstraints = new List<TypeConstraint>(AllTypeConstraints); // copy the list foreach (var c in allTypeConstraints) { var super = c.Super.NormalizeExpand() as TypeProxy; if (AssignKnownEnd(super, true, fullStrength)) { anyNewConstraints = true; } else if (super != null && fullStrength && AssignKnownEndsFullstrength(super)) { // KRML: is this used any more? anyNewConstraints = true; } } } break; case 1: { // Process XConstraints // confirm as many XConstraints as possible, setting "anyNewConstraints" to "true" if the confirmation // of an XConstraint gives rise to new constraints to be handled in the loop above bool generatedMoreXConstraints; do { generatedMoreXConstraints = false; var allXConstraints = AllXConstraints; AllXConstraints = new List<XConstraint>(); foreach (var xc in allXConstraints) { bool convertedIntoOtherTypeConstraints, moreXConstraints; if (xc.Confirm(this, fullStrength, out convertedIntoOtherTypeConstraints, out moreXConstraints)) { if (convertedIntoOtherTypeConstraints) { anyNewConstraints = true; } else { generatedMoreXConstraints = true; } if (moreXConstraints) { generatedMoreXConstraints = true; } } else { AllXConstraints.Add(xc); } } } while (generatedMoreXConstraints); } break; case 2: { var assignables = AllXConstraints.Where(xc => xc.ConstraintName == "Assignable").ToList(); var postponeForNow = new HashSet<TypeProxy>(); foreach (var constraint in AllTypeConstraints) { var lhs = constraint.Super.NormalizeExpandKeepConstraints() as NonProxyType; if (lhs != null) { foreach (var ta in lhs.TypeArgs) { AddAllProxies(ta, postponeForNow); } } } foreach (var constraint in AllTypeConstraints) { var lhs = constraint.Super.Normalize() as TypeProxy; if (lhs != null && !postponeForNow.Contains(lhs)) { var rhss = assignables.Where(xc => xc.Types[0].Normalize() == lhs).Select(xc => xc.Types[1]).ToList(); if (ProcessAssignable(lhs, rhss)) { anyNewConstraints = true; // next time around the big loop, start with state 0 again } } } foreach (var assignable in assignables) { var lhs = assignable.Types[0].Normalize() as TypeProxy; if (lhs != null && !postponeForNow.Contains(lhs)) { var rhss = assignables.Where(xc => xc.Types[0].Normalize() == lhs).Select(xc => xc.Types[1]).ToList(); if (ProcessAssignable(lhs, rhss)) { anyNewConstraints = true; // next time around the big loop, start with state 0 again // process only one Assignable constraint in this way break; } } } } break; case 3: anyNewConstraints = ConvertAssignableToSubtypeConstraints(null); break; case 4: { var allTC = AllTypeConstraints; AllTypeConstraints = new List<TypeConstraint>(); var proxyProcessed = new HashSet<TypeProxy>(); foreach (var c in allTC) { ProcessFullStrength_SubDirection(c.Super, proxyProcessed, ref anyNewConstraints); } foreach (var xc in AllXConstraints) { if (xc.ConstraintName == "Assignable") { ProcessFullStrength_SubDirection(xc.Types[0], proxyProcessed, ref anyNewConstraints); } } if (!anyNewConstraints) { // only do super-direction if sub-direction had no effect proxyProcessed = new HashSet<TypeProxy>(); foreach (var c in allTC) { ProcessFullStrength_SuperDirection(c.Sub, proxyProcessed, ref anyNewConstraints); } foreach (var xc in AllXConstraints) { if (xc.ConstraintName == "Assignable") { ProcessFullStrength_SuperDirection(xc.Types[1], proxyProcessed, ref anyNewConstraints); } } } AllTypeConstraints.AddRange(allTC); } break; case 5: { // Process default numeric types var allTypeConstraints = AllTypeConstraints; AllTypeConstraints = new List<TypeConstraint>(); foreach (var c in allTypeConstraints) { if (c.Super is ArtificialType) { var proxy = c.Sub.NormalizeExpand() as TypeProxy; if (proxy != null) { AssignProxyAndHandleItsConstraints(proxy, c.Super is IntVarietiesSupertype ? (Type)Type.Int : Type.Real); anyNewConstraints = true; continue; } } AllTypeConstraints.Add(c); } } break; case 6: { fullStrength = true; bool generatedMoreXConstraints; do { generatedMoreXConstraints = false; var allXConstraints = AllXConstraints; AllXConstraints = new List<XConstraint>(); foreach (var xc in allXConstraints) { bool convertedIntoOtherTypeConstraints, moreXConstraints; if ((xc.ConstraintName == "Equatable" || xc.ConstraintName == "EquatableArg") && xc.Confirm(this, fullStrength, out convertedIntoOtherTypeConstraints, out moreXConstraints)) { if (convertedIntoOtherTypeConstraints) { anyNewConstraints = true; } else { generatedMoreXConstraints = true; } if (moreXConstraints) { generatedMoreXConstraints = true; } } else { AllXConstraints.Add(xc); } } } while (generatedMoreXConstraints); } break; case 7: { // Process default reference types var allXConstraints = AllXConstraints; AllXConstraints = new List<XConstraint>(); foreach (var xc in allXConstraints) { if (xc.ConstraintName == "IsRefType" || xc.ConstraintName == "IsNullableRefType") { var proxy = xc.Types[0].Normalize() as TypeProxy; // before we started processing default types, this would have been a proxy (since it's still in the A if (proxy != null) { AssignProxyAndHandleItsConstraints(proxy, builtIns.ObjectQ()); anyNewConstraints = true; continue; } } AllXConstraints.Add(xc); } } break; case 8: fullStrength = true; goto case 0; case 9: fullStrength = true; goto case 1; case 10: { // Finally, collapse constraints involving only proxies, which will have the effect of trading some type error // messages for type-underspecification messages. var allTypeConstraints = AllTypeConstraints; AllTypeConstraints = new List<TypeConstraint>(); foreach (var c in allTypeConstraints) { var super = c.Super.NormalizeExpand(); var sub = c.Sub.NormalizeExpand(); if (super == sub) { continue; } else if (super is TypeProxy && sub is TypeProxy) { var proxy = (TypeProxy)super; if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: (merge in PartiallySolve) assigning proxy {0}.T := {1}", proxy, sub); } proxy.T = sub; anyNewConstraints = true; // signal a change in the constraints continue; } AllTypeConstraints.Add(c); } } break; case 11: { // Last resort decisions. Sometimes get here even with some 'obvious' // inferences. Before this case was added, the type inference returned with // failure, so this is a conservative addition, and could be made more // capable. if (!allowDecisions) break; foreach (var c in AllXConstraints) { if (c.ConstraintName == "EquatableArg") { ConstrainSubtypeRelation_Equal(c.Types[0], c.Types[1], c.errorMsg); anyNewConstraints = true; AllXConstraints.Remove(c); break; } } if (anyNewConstraints) break; TypeConstraint oneSuper = null; TypeConstraint oneSub = null; var ss = new HashSet<Type>(); foreach (var c in AllTypeConstraints) { var super = c.Super.NormalizeExpand(); var sub = c.Sub.NormalizeExpand(); if (super is TypeProxy && !ss.Contains(super)) { ss.Add(super); } if (sub is TypeProxy && !ss.Contains(sub)) { ss.Add(sub); } } foreach (var t in ss) { var lowers = new HashSet<Type>(); var uppers = new HashSet<Type>(); foreach (var c in AllTypeConstraints) { var super = c.Super.NormalizeExpand(); var sub = c.Sub.NormalizeExpand(); if (t.Equals(super)) { lowers.Add(sub); oneSub = c; } if (t.Equals(sub)) { uppers.Add(super); oneSuper = c; } } bool done = false; foreach (var tl in lowers) { foreach (var tu in uppers) { if (tl.Equals(tu)) { if (!ContainsAsTypeParameter(tu, t)) { var errorMsg = new TypeConstraint.ErrorMsgWithBase(AllTypeConstraints[0].errorMsg, "Decision: {0} is decided to be {1} because the latter is both the upper and lower bound to the proxy", t, tu); ConstrainSubtypeRelation_Equal(t, tu, errorMsg); // The above changes t so that it is a proxy with an assigned type anyNewConstraints = true; done = true; break; } } } if (done) break; } } if (anyNewConstraints) break; foreach (var t in ss) { var lowers = new HashSet<Type>(); var uppers = new HashSet<Type>(); foreach (var c in AllTypeConstraints) { var super = c.Super.NormalizeExpand(); var sub = c.Sub.NormalizeExpand(); if (t.Equals(super)) lowers.Add(sub); if (t.Equals(sub)) uppers.Add(super); } if (uppers.Count == 0) { if (lowers.Count == 1) { var em = lowers.GetEnumerator(); em.MoveNext(); if (!ContainsAsTypeParameter(em.Current, t)) { var errorMsg = new TypeConstraint.ErrorMsgWithBase(oneSub.errorMsg, "Decision: {0} is decided to be {1} because the latter is a lower bound to the proxy and there is no constraint with an upper bound", t, em.Current); ConstrainSubtypeRelation_Equal(t, em.Current, errorMsg); anyNewConstraints = true; break; } } } if (lowers.Count == 0) { if (uppers.Count == 1) { var em = uppers.GetEnumerator(); em.MoveNext(); if (!ContainsAsTypeParameter(em.Current, t)) { var errorMsg = new TypeConstraint.ErrorMsgWithBase(oneSuper.errorMsg, "Decision: {0} is decided to be {1} because the latter is an upper bound to the proxy and there is no constraint with a lower bound", t, em.Current); ConstrainSubtypeRelation_Equal(t, em.Current, errorMsg); anyNewConstraints = true; break; } } } } break; } case 12: // we're so out of here return; } if (anyNewConstraints) { state = 0; } else { state++; } } } private bool ContainsAsTypeParameter(Type t, Type u) { if (t.Equals(u)) return true; if (t is UserDefinedType udt) { foreach (var tp in udt.TypeArgs) { if (ContainsAsTypeParameter(tp, u)) return true; } } if (t is CollectionType st) { foreach (var tp in st.TypeArgs) { if (ContainsAsTypeParameter(tp, u)) return true; } } return false; } private void AddAllProxies(Type type, HashSet<TypeProxy> proxies) { Contract.Requires(type != null); Contract.Requires(proxies != null); var proxy = type as TypeProxy; if (proxy != null) { proxies.Add(proxy); } else { foreach (var ta in type.TypeArgs) { AddAllProxies(ta, proxies); } } } /// <summary> /// Set "lhs" to the meet of "rhss" and "lhs.Subtypes, if possible. /// Returns "true' if something was done, or "false" otherwise. /// </summary> private bool ProcessAssignable(TypeProxy lhs, List<Type> rhss) { Contract.Requires(lhs != null && lhs.T == null); Contract.Requires(rhss != null); if (DafnyOptions.O.TypeInferenceDebug) { Console.Write("DEBUG: ProcessAssignable: {0} with rhss:", lhs); foreach (var rhs in rhss) { Console.Write(" {0}", rhs); } Console.Write(" subtypes:"); foreach (var sub in lhs.SubtypesKeepConstraints) { Console.Write(" {0}", sub); } Console.WriteLine(); } Type meet = null; foreach (var rhs in rhss) { if (rhs is TypeProxy) { return false; } meet = meet == null ? rhs : Type.Meet(meet, rhs, builtIns); } foreach (var sub in lhs.SubtypesKeepConstraints) { if (sub is TypeProxy) { return false; } meet = meet == null ? sub : Type.Meet(meet, sub, builtIns); } if (meet == null) { return false; } else if (Reaches(meet, lhs, 1, new HashSet<TypeProxy>())) { // would cause a cycle, so don't do it return false; } else { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: ProcessAssignable: assigning proxy {0}.T := {1}", lhs, meet); } lhs.T = meet; return true; } } /// <summary> /// Convert each Assignable(A, B) constraint into a subtyping constraint A :> B, /// provided that: /// - B is a non-proxy, and /// - either "proxySpecialization" is null or some proxy in "proxySpecializations" prominently appears in A. /// </summary> bool ConvertAssignableToSubtypeConstraints(ISet<TypeProxy>/*?*/ proxySpecializations) { var anyNewConstraints = false; // If (the head of) the RHS of an Assignable is known, convert the XConstraint into a subtyping constraint var allX = AllXConstraints; AllXConstraints = new List<XConstraint>(); foreach (var xc in allX) { if (xc.ConstraintName == "Assignable" && xc.Types[1].Normalize() is NonProxyType) { var t0 = xc.Types[0].NormalizeExpand(); if (proxySpecializations == null || proxySpecializations.Contains(t0) || t0.TypeArgs.Exists(ta => proxySpecializations.Contains(ta))) { ConstrainSubtypeRelation(t0, xc.Types[1], xc.errorMsg, true); anyNewConstraints = true; continue; } } AllXConstraints.Add(xc); } return anyNewConstraints; } bool TightenUpEquatable(ISet<TypeProxy> proxiesOfInterest) { Contract.Requires(proxiesOfInterest != null); var anyNewConstraints = false; var allX = AllXConstraints; AllXConstraints = new List<XConstraint>(); foreach (var xc in allX) { if (xc.ConstraintName == "Equatable" || xc.ConstraintName == "EquatableArg") { var t0 = xc.Types[0].NormalizeExpandKeepConstraints(); var t1 = xc.Types[1].NormalizeExpandKeepConstraints(); if (proxiesOfInterest.Contains(t0) || proxiesOfInterest.Contains(t1)) { ConstrainSubtypeRelation_Equal(t0, t1, xc.errorMsg); anyNewConstraints = true; continue; } } AllXConstraints.Add(xc); } return anyNewConstraints; } void ProcessOneSubtypingConstraintAndItsSubs(TypeConstraint c, ISet<TypeConstraint> processed, bool fullStrength, ref bool anyNewConstraints) { Contract.Requires(c != null); Contract.Requires(processed != null); if (processed.Contains(c)) { return; // our job has already been done, or is at least in progress } processed.Add(c); var super = c.Super.NormalizeExpandKeepConstraints(); var sub = c.Sub.NormalizeExpandKeepConstraints(); // Process all subtype types before going on var subProxy = sub as TypeProxy; if (subProxy != null) { foreach (var cc in subProxy.SubtypeConstraints) { ProcessOneSubtypingConstraintAndItsSubs(cc, processed, fullStrength, ref anyNewConstraints); } } // the processing may have assigned some proxies, so we'll refresh super and sub super = super.NormalizeExpandKeepConstraints(); sub = sub.NormalizeExpandKeepConstraints(); if (super.Equals(sub)) { // the constraint is satisfied, so just drop it } else if ((super is NonProxyType || super is ArtificialType) && sub is NonProxyType) { ImposeSubtypingConstraint(super, sub, c.errorMsg); anyNewConstraints = true; } else if (AssignKnownEnd(sub as TypeProxy, true, fullStrength)) { anyNewConstraints = true; } else if (sub is TypeProxy && fullStrength && AssignKnownEndsFullstrength((TypeProxy)sub)) { anyNewConstraints = true; } else { // keep the constraint for now AllTypeConstraints.Add(c); } } void ProcessFullStrength_SubDirection(Type t, ISet<TypeProxy> processed, ref bool anyNewConstraints) { Contract.Requires(t != null); Contract.Requires(processed != null); var proxy = t.NormalizeExpand() as TypeProxy; if (proxy != null) { if (processed.Contains(proxy)) { return; // our job has already been done, or is at least in progress } processed.Add(proxy); foreach (var u in proxy.SubtypesKeepConstraints_WithAssignable(AllXConstraints)) { ProcessFullStrength_SubDirection(u, processed, ref anyNewConstraints); } proxy = proxy.NormalizeExpand() as TypeProxy; if (proxy != null && AssignKnownEndsFullstrength_SubDirection(proxy)) { anyNewConstraints = true; } } } void ProcessFullStrength_SuperDirection(Type t, ISet<TypeProxy> processed, ref bool anyNewConstraints) { Contract.Requires(t != null); Contract.Requires(processed != null); var proxy = t.NormalizeExpand() as TypeProxy; if (proxy != null) { if (processed.Contains(proxy)) { return; // our job has already been done, or is at least in progress } processed.Add(proxy); foreach (var u in proxy.Supertypes) { ProcessFullStrength_SuperDirection(u, processed, ref anyNewConstraints); } proxy = proxy.NormalizeExpand() as TypeProxy; if (proxy != null && AssignKnownEndsFullstrength_SuperDirection(proxy)) { anyNewConstraints = true; } } } /// <summary> /// Returns true if anything happened. /// </summary> bool AssignKnownEnd(TypeProxy proxy, bool keepConstraints, bool fullStrength) { Contract.Requires(proxy == null || proxy.T == null); // caller is supposed to have called NormalizeExpand if (proxy == null) { // nothing to do return false; } // ----- first, go light; also, prefer subtypes over supertypes IEnumerable<Type> subTypes = keepConstraints ? proxy.SubtypesKeepConstraints : proxy.Subtypes; foreach (var su in subTypes) { bool isRoot, isLeaf, headRoot, headLeaf; CheckEnds(su, out isRoot, out isLeaf, out headRoot, out headLeaf); Contract.Assert(!isRoot || headRoot); // isRoot ==> headRoot if (isRoot) { if (Reaches(su, proxy, 1, new HashSet<TypeProxy>())) { // adding a constraint here would cause a bad cycle, so we don't } else { AssignProxyAndHandleItsConstraints(proxy, su, keepConstraints); return true; } } else if (headRoot) { if (Reaches(su, proxy, 1, new HashSet<TypeProxy>())) { // adding a constraint here would cause a bad cycle, so we don't } else { AssignProxyAndHandleItsConstraints(proxy, TypeProxy.HeadWithProxyArgs(su), keepConstraints); return true; } } } if (fullStrength) { IEnumerable<Type> superTypes = keepConstraints ? proxy.SupertypesKeepConstraints : proxy.Supertypes; foreach (var su in superTypes) { bool isRoot, isLeaf, headRoot, headLeaf; CheckEnds(su, out isRoot, out isLeaf, out headRoot, out headLeaf); Contract.Assert(!isLeaf || headLeaf); // isLeaf ==> headLeaf if (isLeaf) { if (Reaches(su, proxy, -1, new HashSet<TypeProxy>())) { // adding a constraint here would cause a bad cycle, so we don't } else { AssignProxyAndHandleItsConstraints(proxy, su, keepConstraints); return true; } } else if (headLeaf) { if (Reaches(su, proxy, -1, new HashSet<TypeProxy>())) { // adding a constraint here would cause a bad cycle, so we don't } else { AssignProxyAndHandleItsConstraints(proxy, TypeProxy.HeadWithProxyArgs(su), keepConstraints); return true; } } } } return false; } bool AssignKnownEndsFullstrength(TypeProxy proxy) { Contract.Requires(proxy != null); // ----- continue with full strength // If the meet of the subtypes exists, use it var meets = new List<Type>(); foreach (var su in proxy.Subtypes) { if (su is TypeProxy) { continue; // don't include proxies in the meet computation } int i = 0; for (; i < meets.Count; i++) { var j = Type.Meet(meets[i], su, builtIns); if (j != null) { meets[i] = j; break; } } if (i == meets.Count) { // we went to the end without finding a place to meet up meets.Add(su); } } if (meets.Count == 1 && !Reaches(meets[0], proxy, 1, new HashSet<TypeProxy>())) { // we were able to compute a meet of all the subtyping constraints, so use it AssignProxyAndHandleItsConstraints(proxy, meets[0]); return true; } // If the join of the supertypes exists, use it var joins = new List<Type>(); foreach (var su in proxy.Supertypes) { if (su is TypeProxy) { continue; // don't include proxies in the join computation } int i = 0; for (; i < joins.Count; i++) { var j = Type.Join(joins[i], su, builtIns); if (j != null) { joins[i] = j; break; } } if (i == joins.Count) { // we went to the end without finding a place to join in joins.Add(su); } } if (joins.Count == 1 && !(joins[0] is ArtificialType) && !Reaches(joins[0], proxy, -1, new HashSet<TypeProxy>())) { // we were able to compute a join of all the subtyping constraints, so use it AssignProxyAndHandleItsConstraints(proxy, joins[0]); return true; } return false; } bool AssignKnownEndsFullstrength_SubDirection(TypeProxy proxy) { Contract.Requires(proxy != null && proxy.T == null); // If the meet of the subtypes exists, use it var meets = new List<Type>(); var proxySubs = new HashSet<TypeProxy>(); proxySubs.Add(proxy); foreach (var su in proxy.SubtypesKeepConstraints_WithAssignable(AllXConstraints)) { if (su is TypeProxy) { proxySubs.Add((TypeProxy)su); } else { int i = 0; for (; i < meets.Count; i++) { var j = Type.Meet(meets[i], su, builtIns); if (j != null) { meets[i] = j; break; } } if (i == meets.Count) { // we went to the end without finding a place to meet up meets.Add(su); } } } if (meets.Count == 1 && !Reaches(meets[0], proxy, 1, new HashSet<TypeProxy>())) { // We were able to compute a meet of all the subtyping constraints, so use it. // Well, maybe. If "meets[0]" denotes a non-null type and "proxy" is something // that could be assigned "null", then set "proxy" to the nullable version of "meets[0]". // Stated differently, think of an applicable "IsNullableRefType" constraint as // being part of the meet computation, essentially throwing in a "...?". // Except: If the meet is a tight bound--meaning, it is also a join--then pick it // after all, because that seems to give rise to less confusing error messages. if (meets[0].IsNonNullRefType) { Type join = null; if (JoinOfAllSupertypes(proxy, ref join, new HashSet<TypeProxy>(), false) && join != null && Type.SameHead(meets[0], join)) { // leave it } else { CloseOverAssignableRhss(proxySubs); if (HasApplicableNullableRefTypeConstraint(proxySubs)) { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: Found meet {0} for proxy {1}, but weakening it to {2}", meets[0], proxy, meets[0].NormalizeExpand()); } AssignProxyAndHandleItsConstraints(proxy, meets[0].NormalizeExpand(), true); return true; } } } AssignProxyAndHandleItsConstraints(proxy, meets[0], true); return true; } return false; } private void CloseOverAssignableRhss(ISet<TypeProxy> proxySet) { Contract.Requires(proxySet != null); while (true) { var moreChanges = false; foreach (var xc in AllXConstraints) { if (xc.ConstraintName == "Assignable") { var source = xc.Types[0].Normalize() as TypeProxy; var sink = xc.Types[1].Normalize() as TypeProxy; if (source != null && sink != null && proxySet.Contains(source) && !proxySet.Contains(sink)) { proxySet.Add(sink); moreChanges = true; } } } if (!moreChanges) { return; } } } private bool HasApplicableNullableRefTypeConstraint(ISet<TypeProxy> proxySet) { Contract.Requires(proxySet != null); var nullableProxies = new HashSet<TypeProxy>(); foreach (var xc in AllXConstraints) { if (xc.ConstraintName == "IsNullableRefType") { var npr = xc.Types[0].Normalize() as TypeProxy; if (npr != null) { nullableProxies.Add(npr); } } } return proxySet.Any(nullableProxies.Contains); } private bool HasApplicableNullableRefTypeConstraint_SubDirection(TypeProxy proxy) { Contract.Requires(proxy != null); var nullableProxies = new HashSet<TypeProxy>(); foreach (var xc in AllXConstraints) { if (xc.ConstraintName == "IsNullableRefType") { var npr = xc.Types[0].Normalize() as TypeProxy; if (npr != null) { nullableProxies.Add(npr); } } } return HasApplicableNullableRefTypeConstraint_SubDirection_aux(proxy, nullableProxies, new HashSet<TypeProxy>()); } private bool HasApplicableNullableRefTypeConstraint_SubDirection_aux(TypeProxy proxy, ISet<TypeProxy> nullableProxies, ISet<TypeProxy> visitedProxies) { Contract.Requires(proxy != null); Contract.Requires(nullableProxies != null); Contract.Requires(visitedProxies != null); if (visitedProxies.Contains(proxy)) { return false; } visitedProxies.Add(proxy); if (nullableProxies.Contains(proxy)) { return true; } foreach (var sub in proxy.SubtypesKeepConstraints_WithAssignable(AllXConstraints)) { var psub = sub as TypeProxy; if (psub != null && HasApplicableNullableRefTypeConstraint_SubDirection_aux(psub, nullableProxies, visitedProxies)) { return true; } } return false; } bool AssignKnownEndsFullstrength_SuperDirection(TypeProxy proxy) { Contract.Requires(proxy != null && proxy.T == null); // First, compute the the meet of the Assignable LHSs. Then, compute // the join of that meet and the supertypes. var meets = new List<Type>(); foreach (var xc in AllXConstraints) { if (xc.ConstraintName == "Assignable" && xc.Types[1].Normalize() == proxy) { var su = xc.Types[0].Normalize(); if (su is TypeProxy) { continue; // don't include proxies in the meet computation } int i = 0; for (; i < meets.Count; i++) { var j = Type.Meet(meets[i], su, builtIns); if (j != null) { meets[i] = j; break; } } if (i == meets.Count) { // we went to the end without finding a place to meet in meets.Add(su); } } } // If the join of the supertypes exists, use it var joins = new List<Type>(meets); foreach (var su in proxy.SupertypesKeepConstraints) { if (su is TypeProxy) { continue; // don't include proxies in the join computation } int i = 0; for (; i < joins.Count; i++) { var j = Type.Join(joins[i], su, builtIns); if (j != null) { joins[i] = j; break; } } if (i == joins.Count) { // we went to the end without finding a place to join in joins.Add(su); } } if (joins.Count == 1 && !(joins[0] is ArtificialType) && !Reaches(joins[0], proxy, -1, new HashSet<TypeProxy>())) { // we were able to compute a join of all the subtyping constraints, so use it AssignProxyAndHandleItsConstraints(proxy, joins[0], true); return true; } return false; } int _reaches_recursion; private bool Reaches(Type t, TypeProxy proxy, int direction, HashSet<TypeProxy> visited) { if (_reaches_recursion == 20) { Contract.Assume(false); // possible infinite recursion } _reaches_recursion++; var b = Reaches_aux(t, proxy, direction, visited); _reaches_recursion--; return b; } private bool Reaches_aux(Type t, TypeProxy proxy, int direction, HashSet<TypeProxy> visited) { Contract.Requires(t != null); Contract.Requires(proxy != null); Contract.Requires(visited != null); t = t.NormalizeExpand(); var tproxy = t as TypeProxy; if (tproxy == null) { var polarities = Type.GetPolarities(t).ConvertAll(TypeParameter.Direction); Contract.Assert(polarities != null); Contract.Assert(polarities.Count <= t.TypeArgs.Count); for (int i = 0; i < polarities.Count; i++) { if (Reaches(t.TypeArgs[i], proxy, direction * polarities[i], visited)) { return true; } } return false; } else if (tproxy == proxy) { return true; } else if (visited.Contains(tproxy)) { return false; } else { visited.Add(tproxy); if (0 <= direction && tproxy.Subtypes.Any(su => Reaches(su, proxy, direction, visited))) { return true; } if (direction <= 0 && tproxy.Supertypes.Any(su => Reaches(su, proxy, direction, visited))) { return true; } return false; } } [System.Diagnostics.Conditional("TI_DEBUG_PRINT")] void PrintTypeConstraintState(int lbl) { if (!DafnyOptions.O.TypeInferenceDebug) { return; } Console.WriteLine("DEBUG: ---------- type constraints ---------- {0} {1}", lbl, lbl == 0 && currentMethod != null ? currentMethod.Name : ""); foreach (var constraint in AllTypeConstraints) { var super = constraint.Super.Normalize(); var sub = constraint.Sub.Normalize(); Console.WriteLine(" {0} :> {1}", super is IntVarietiesSupertype ? "int-like" : super is RealVarietiesSupertype ? "real-like" : super.ToString(), sub); } foreach (var xc in AllXConstraints) { Console.WriteLine(" {0}", xc); } Console.WriteLine(); if (lbl % 2 == 1) { Console.WriteLine("DEBUG: --------------------------------------"); } } /// <summary> /// Attempts to fully solve all type constraints. /// Upon failure, reports errors. /// Clears all constraints. /// </summary> void SolveAllTypeConstraints() { PrintTypeConstraintState(0); PartiallySolveTypeConstraints(true); PrintTypeConstraintState(1); foreach (var constraint in AllTypeConstraints) { if (Type.IsSupertype(constraint.Super, constraint.Sub)) { // unexpected condition -- PartiallySolveTypeConstraints is supposed to have continued until no more sub-typing constraints can be satisfied Contract.Assume(false, string.Format("DEBUG: Unexpectedly satisfied supertype relation ({0} :> {1}) |||| ", constraint.Super, constraint.Sub)); } else { constraint.FlagAsError(); } } foreach (var xc in AllXConstraints) { bool convertedIntoOtherTypeConstraints, moreXConstraints; if (xc.Confirm(this, true, out convertedIntoOtherTypeConstraints, out moreXConstraints)) { // unexpected condition -- PartiallySolveTypeConstraints is supposed to have continued until no more XConstraints were confirmable Contract.Assume(false, string.Format("DEBUG: Unexpectedly confirmed XConstraint: {0} |||| ", xc)); } else if (xc.CouldBeAnything()) { // suppress the error message; it will later be flagged as an underspecified type } else { xc.errorMsg.FlagAsError(); } } TypeConstraint.ReportErrors(reporter); AllTypeConstraints.Clear(); AllXConstraints.Clear(); } public class TypeConstraint { public readonly Type Super; public readonly Type Sub; public readonly bool KeepConstraints; private static List<ErrorMsg> ErrorsToBeReported = new List<ErrorMsg>(); public static void ReportErrors(ErrorReporter reporter) { Contract.Requires(reporter != null); foreach (var err in ErrorsToBeReported) { err.ReportAsError(reporter); } ErrorsToBeReported.Clear(); } abstract public class ErrorMsg { public abstract IToken Tok { get; } bool reported; public void FlagAsError() { TypeConstraint.ErrorsToBeReported.Add(this); } internal void ReportAsError(ErrorReporter reporter) { Contract.Requires(reporter != null); if (!reported) { // this "reported" bit is checked only for the top-level message, but this message and all nested ones get their "reported" bit set to "true" as a result Reporting(reporter, ""); } } private void Reporting(ErrorReporter reporter, string suffix) { Contract.Requires(reporter != null); Contract.Requires(suffix != null); if (this is ErrorMsgWithToken) { var err = (ErrorMsgWithToken)this; Contract.Assert(err.Tok != null); reporter.Error(MessageSource.Resolver, err.Tok, err.Msg + suffix, err.MsgArgs); } else { var err = (ErrorMsgWithBase)this; err.BaseMsg.Reporting(reporter, " (" + string.Format(err.Msg, err.MsgArgs) + ")" + suffix); } reported = true; } } public class ErrorMsgWithToken : ErrorMsg { readonly IToken tok; public override IToken Tok { get { return tok; } } public readonly string Msg; public readonly object[] MsgArgs; public ErrorMsgWithToken(IToken tok, string msg, params object[] msgArgs) { Contract.Requires(tok != null); Contract.Requires(msg != null); Contract.Requires(msgArgs != null); this.tok = tok; this.Msg = msg; this.MsgArgs = msgArgs; } } public class ErrorMsgWithBase : ErrorMsg { public override IToken Tok { get { return BaseMsg.Tok; } } public readonly ErrorMsg BaseMsg; public readonly string Msg; public readonly object[] MsgArgs; public ErrorMsgWithBase(ErrorMsg baseMsg, string msg, params object[] msgArgs) { Contract.Requires(baseMsg != null); Contract.Requires(msg != null); Contract.Requires(msgArgs != null); BaseMsg = baseMsg; Msg = msg; MsgArgs = msgArgs; } } public readonly ErrorMsg errorMsg; public TypeConstraint(Type super, Type sub, ErrorMsg errMsg, bool keepConstraints) { Contract.Requires(super != null); Contract.Requires(sub != null); Contract.Requires(errMsg != null); Super = super; Sub = sub; errorMsg = errMsg; KeepConstraints = keepConstraints; } public void FlagAsError() { errorMsg.FlagAsError(); } } // ------------------------------------------------------------------------------------------------------ // ----- Visitors --------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region Visitors class ResolverBottomUpVisitor : BottomUpVisitor { protected Resolver resolver; public ResolverBottomUpVisitor(Resolver resolver) { Contract.Requires(resolver != null); this.resolver = resolver; } } abstract class ResolverTopDownVisitor<T> : TopDownVisitor<T> { protected Resolver resolver; public ResolverTopDownVisitor(Resolver resolver) { Contract.Requires(resolver != null); this.resolver = resolver; } } #endregion Visitors // ------------------------------------------------------------------------------------------------------ // ----- CheckTypeInference ----------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region CheckTypeInference private void CheckTypeInference_Member(MemberDecl member) { if (member is ConstantField) { var field = (ConstantField)member; if (field.Rhs != null) { CheckTypeInference(field.Rhs, new NoContext(member.EnclosingClass.EnclosingModuleDefinition)); } CheckTypeInference(field.Type, new NoContext(member.EnclosingClass.EnclosingModuleDefinition), field.tok, "const"); } else if (member is Method) { var m = (Method)member; m.Req.Iter(mfe => CheckTypeInference_MaybeFreeExpression(mfe, m)); m.Ens.Iter(mfe => CheckTypeInference_MaybeFreeExpression(mfe, m)); CheckTypeInference_Specification_FrameExpr(m.Mod, m); CheckTypeInference_Specification_Expr(m.Decreases, m); if (m.Body != null) { CheckTypeInference(m.Body, m); } } else if (member is Function) { var f = (Function)member; var errorCount = reporter.Count(ErrorLevel.Error); f.Req.Iter(e => CheckTypeInference(e.E, f)); f.Ens.Iter(e => CheckTypeInference(e.E, f)); f.Reads.Iter(fe => CheckTypeInference(fe.E, f)); CheckTypeInference_Specification_Expr(f.Decreases, f); if (f.Body != null) { CheckTypeInference(f.Body, f); } if (errorCount == reporter.Count(ErrorLevel.Error) && f is ExtremePredicate) { var cop = (ExtremePredicate)f; CheckTypeInference_Member(cop.PrefixPredicate); } } } private void CheckTypeInference_MaybeFreeExpression(AttributedExpression mfe, ICodeContext codeContext) { Contract.Requires(mfe != null); Contract.Requires(codeContext != null); foreach (var e in Attributes.SubExpressions(mfe.Attributes)) { CheckTypeInference(e, codeContext); } CheckTypeInference(mfe.E, codeContext); } private void CheckTypeInference_Specification_Expr(Specification<Expression> spec, ICodeContext codeContext) { Contract.Requires(spec != null); Contract.Requires(codeContext != null); foreach (var e in Attributes.SubExpressions(spec.Attributes)) { CheckTypeInference(e, codeContext); } spec.Expressions.Iter(e => CheckTypeInference(e, codeContext)); } private void CheckTypeInference_Specification_FrameExpr(Specification<FrameExpression> spec, ICodeContext codeContext) { Contract.Requires(spec != null); Contract.Requires(codeContext != null); foreach (var e in Attributes.SubExpressions(spec.Attributes)) { CheckTypeInference(e, codeContext); } spec.Expressions.Iter(fe => CheckTypeInference(fe.E, codeContext)); } void CheckTypeInference(Expression expr, ICodeContext codeContext) { Contract.Requires(expr != null); Contract.Requires(codeContext != null); PartiallySolveTypeConstraints(true); var c = new CheckTypeInference_Visitor(this, codeContext); c.Visit(expr); } void CheckTypeInference(Type type, ICodeContext codeContext, IToken tok, string what) { Contract.Requires(type != null); Contract.Requires(codeContext != null); Contract.Requires(tok != null); Contract.Requires(what != null); PartiallySolveTypeConstraints(true); var c = new CheckTypeInference_Visitor(this, codeContext); c.CheckTypeIsDetermined(tok, type, what); } void CheckTypeInference(Statement stmt, ICodeContext codeContext) { Contract.Requires(stmt != null); Contract.Requires(codeContext != null); PartiallySolveTypeConstraints(true); var c = new CheckTypeInference_Visitor(this, codeContext); c.Visit(stmt); } class CheckTypeInference_Visitor : ResolverBottomUpVisitor { readonly ICodeContext codeContext; public CheckTypeInference_Visitor(Resolver resolver, ICodeContext codeContext) : base(resolver) { Contract.Requires(resolver != null); Contract.Requires(codeContext != null); this.codeContext = codeContext; } protected override void VisitOneStmt(Statement stmt) { if (stmt is VarDeclStmt) { var s = (VarDeclStmt)stmt; foreach (var local in s.Locals) { CheckTypeIsDetermined(local.Tok, local.Type, "local variable"); CheckTypeArgsContainNoOrdinal(local.Tok, local.type); } } else if (stmt is VarDeclPattern) { var s = (VarDeclPattern)stmt; s.LocalVars.Iter(local => CheckTypeIsDetermined(local.Tok, local.Type, "local variable")); s.LocalVars.Iter(local => CheckTypeArgsContainNoOrdinal(local.Tok, local.Type)); } else if (stmt is ForallStmt) { var s = (ForallStmt)stmt; s.BoundVars.Iter(bv => CheckTypeIsDetermined(bv.tok, bv.Type, "bound variable")); s.Bounds = DiscoverBestBounds_MultipleVars(s.BoundVars, s.Range, true, ComprehensionExpr.BoundedPool.PoolVirtues.Enumerable); s.BoundVars.Iter(bv => CheckTypeArgsContainNoOrdinal(bv.tok, bv.Type)); } else if (stmt is AssignSuchThatStmt) { var s = (AssignSuchThatStmt)stmt; if (s.AssumeToken == null) { var varLhss = new List<IVariable>(); foreach (var lhs in s.Lhss) { var ide = (IdentifierExpr)lhs.Resolved; // successful resolution implies all LHS's are IdentifierExpr's varLhss.Add(ide.Var); } s.Bounds = DiscoverBestBounds_MultipleVars(varLhss, s.Expr, true, ComprehensionExpr.BoundedPool.PoolVirtues.None); } foreach (var lhs in s.Lhss) { var what = lhs is IdentifierExpr ? string.Format("variable '{0}'", ((IdentifierExpr)lhs).Name) : "LHS"; CheckTypeArgsContainNoOrdinal(lhs.tok, lhs.Type); } } else if (stmt is CalcStmt) { var s = (CalcStmt)stmt; // The resolution of the calc statement builds up .Steps and .Result, which are of the form E0 OP E1, where // E0 and E1 are expressions from .Lines. These additional expressions still need to have their .ResolvedOp // fields filled in, so we visit them (but not their subexpressions) here. foreach (var e in s.Steps) { Visit(e); } Visit(s.Result); } } protected override void VisitOneExpr(Expression expr) { if (expr is LiteralExpr) { var e = (LiteralExpr)expr; if (e.Type.IsBitVectorType || e.Type.IsBigOrdinalType) { var n = (BigInteger)e.Value; var absN = n < 0 ? -n : n; // For bitvectors, check that the magnitude fits the width if (e.Type.IsBitVectorType && resolver.MaxBV(e.Type.AsBitVectorType.Width) < absN) { resolver.reporter.Error(MessageSource.Resolver, e.tok, "literal ({0}) is too large for the bitvector type {1}", absN, e.Type); } // For bitvectors and ORDINALs, check for a unary minus that, earlier, was mistaken for a negative literal // This can happen only in `match` patterns (see comment by LitPattern.OptimisticallyDesugaredLit). if (n < 0 || e.tok.val == "-0") { Contract.Assert(e.tok.val == "-0"); // this and the "if" above tests that "n < 0" happens only when the token is "-0" resolver.reporter.Error(MessageSource.Resolver, e.tok, "unary minus (-{0}, type {1}) not allowed in case pattern", absN, e.Type); } } if (expr is StaticReceiverExpr stexpr) { if (stexpr.OriginalResolved != null) { Visit(stexpr.OriginalResolved); } else { foreach (Type t in stexpr.Type.TypeArgs) { if (t is InferredTypeProxy && ((InferredTypeProxy)t).T == null) { resolver.reporter.Error(MessageSource.Resolver, stexpr.tok, "type of type parameter could not be determined; please specify the type explicitly"); } } } } } else if (expr is ComprehensionExpr) { var e = (ComprehensionExpr)expr; foreach (var bv in e.BoundVars) { if (!IsDetermined(bv.Type.Normalize())) { resolver.reporter.Error(MessageSource.Resolver, bv.tok, "type of bound variable '{0}' could not be determined; please specify the type explicitly", bv.Name); } else if (codeContext is ExtremePredicate) { CheckContainsNoOrdinal(bv.tok, bv.Type, string.Format("type of bound variable '{0}' ('{1}') is not allowed to use type ORDINAL", bv.Name, bv.Type)); } } // apply bounds discovery to quantifiers, finite sets, and finite maps string what = null; Expression whereToLookForBounds = null; var polarity = true; if (e is QuantifierExpr) { what = "quantifier"; whereToLookForBounds = ((QuantifierExpr)e).LogicalBody(); polarity = e is ExistsExpr; } else if (e is SetComprehension) { what = "set comprehension"; whereToLookForBounds = e.Range; } else if (e is MapComprehension) { what = "map comprehension"; whereToLookForBounds = e.Range; } else { Contract.Assume(e is LambdaExpr); // otherwise, unexpected ComprehensionExpr } if (whereToLookForBounds != null) { e.Bounds = DiscoverBestBounds_MultipleVars_AllowReordering(e.BoundVars, whereToLookForBounds, polarity, ComprehensionExpr.BoundedPool.PoolVirtues.None); if (2 <= DafnyOptions.O.Allocated && (codeContext is Function || codeContext is ConstantField || codeContext is RedirectingTypeDecl)) { // functions are not allowed to depend on the set of allocated objects foreach (var bv in ComprehensionExpr.BoundedPool.MissingBounds(e.BoundVars, e.Bounds, ComprehensionExpr.BoundedPool.PoolVirtues.IndependentOfAlloc)) { var msgFormat = "a {0} involved in a {3} definition is not allowed to depend on the set of allocated references; Dafny's heuristics can't figure out a bound for the values of '{1}'"; if (bv.Type.IsTypeParameter) { var tp = bv.Type.AsTypeParameter; msgFormat += " (perhaps declare its type, '{2}', as '{2}(!new)')"; } var declKind = codeContext is RedirectingTypeDecl ? ((RedirectingTypeDecl)codeContext).WhatKind : ((MemberDecl)codeContext).WhatKind; resolver.reporter.Error(MessageSource.Resolver, e, msgFormat, what, bv.Name, bv.Type, declKind); } } if ((e is SetComprehension && ((SetComprehension)e).Finite) || (e is MapComprehension && ((MapComprehension)e).Finite)) { // the comprehension had better produce a finite set if (e.Type.HasFinitePossibleValues) { // This means the set is finite, regardless of if the Range is bounded. So, we don't give any error here. // However, if this expression is used in a non-ghost context (which is not yet known at this stage of // resolution), the resolver will generate an error about that later. } else { // we cannot be sure that the set/map really is finite foreach (var bv in ComprehensionExpr.BoundedPool.MissingBounds(e.BoundVars, e.Bounds, ComprehensionExpr.BoundedPool.PoolVirtues.Finite)) { resolver.reporter.Error(MessageSource.Resolver, e, "the result of a {0} must be finite, but Dafny's heuristics can't figure out how to produce a bounded set of values for '{1}'", what, bv.Name); } } } } if (e is ExistsExpr && e.Range == null) { var binBody = ((ExistsExpr)e).Term as BinaryExpr; if (binBody != null && binBody.Op == BinaryExpr.Opcode.Imp) { // check Op, not ResolvedOp, in order to distinguish ==> and <== // apply the wisdom of Claude Marche: issue a warning here resolver.reporter.Warning(MessageSource.Resolver, e.tok, "the quantifier has the form 'exists x :: A ==> B', which most often is a typo for 'exists x :: A && B'; " + "if you think otherwise, rewrite as 'exists x :: (A ==> B)' or 'exists x :: !A || B' to suppress this warning"); } } } else if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; if (e.Member is Function || e.Member is Method) { var i = 0; foreach (var p in Util.Concat(e.TypeApplication_AtEnclosingClass, e.TypeApplication_JustMember)) { var tp = i < e.TypeApplication_AtEnclosingClass.Count ? e.Member.EnclosingClass.TypeArgs[i] : ((ICallable)e.Member).TypeArgs[i - e.TypeApplication_AtEnclosingClass.Count]; if (!IsDetermined(p.Normalize())) { resolver.reporter.Error(MessageSource.Resolver, e.tok, "type parameter '{0}' (inferred to be '{1}') to the {2} '{3}' could not be determined", tp.Name, p, e.Member.WhatKind, e.Member.Name); } else { CheckContainsNoOrdinal(e.tok, p, string.Format("type parameter '{0}' (passed in as '{1}') to the {2} '{3}' is not allowed to use ORDINAL", tp.Name, p, e.Member.WhatKind, e.Member.Name)); } i++; } } } else if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; var i = 0; foreach (var p in Util.Concat(e.TypeApplication_AtEnclosingClass, e.TypeApplication_JustFunction)) { var tp = i < e.TypeApplication_AtEnclosingClass.Count ? e.Function.EnclosingClass.TypeArgs[i] : e.Function.TypeArgs[i - e.TypeApplication_AtEnclosingClass.Count]; if (!IsDetermined(p.Normalize())) { resolver.reporter.Error(MessageSource.Resolver, e.tok, "type parameter '{0}' (inferred to be '{1}') in the function call to '{2}' could not be determined{3}", tp.Name, p, e.Name, (e.Name.StartsWith("reveal_")) ? ". If you are making an opaque function, make sure that the function can be called." : "" ); } else { CheckContainsNoOrdinal(e.tok, p, string.Format("type parameter '{0}' (passed in as '{1}') to function call '{2}' is not allowed to use ORDINAL", tp.Name, p, e.Name)); } i++; } } else if (expr is LetExpr) { var e = (LetExpr)expr; foreach (var p in e.LHSs) { foreach (var x in p.Vars) { if (!IsDetermined(x.Type.Normalize())) { resolver.reporter.Error(MessageSource.Resolver, x.tok, "the type of the bound variable '{0}' could not be determined", x.Name); } else { CheckTypeArgsContainNoOrdinal(x.tok, x.Type); } } } } else if (expr is IdentifierExpr) { // by specializing for IdentifierExpr, error messages will be clearer CheckTypeIsDetermined(expr.tok, expr.Type, "variable"); } else if (CheckTypeIsDetermined(expr.tok, expr.Type, "expression")) { if (expr is BinaryExpr) { var e = (BinaryExpr)expr; e.ResolvedOp = ResolveOp(e.Op, e.E0.Type, e.E1.Type); // Check for useless comparisons with "null" Expression other = null; // if "null" if one of the operands, then "other" is the other if (e.E0 is LiteralExpr && ((LiteralExpr)e.E0).Value == null) { other = e.E1; } else if (e.E1 is LiteralExpr && ((LiteralExpr)e.E1).Value == null) { other = e.E0; } if (other != null) { bool sense = true; switch (e.ResolvedOp) { case BinaryExpr.ResolvedOpcode.NeqCommon: sense = false; goto case BinaryExpr.ResolvedOpcode.EqCommon; case BinaryExpr.ResolvedOpcode.EqCommon: { var nntUdf = other.Type.AsNonNullRefType; if (nntUdf != null) { string name = null; string hint = ""; other = other.Resolved; if (other is IdentifierExpr) { name = string.Format("variable '{0}'", ((IdentifierExpr)other).Name); } else if (other is MemberSelectExpr) { var field = ((MemberSelectExpr)other).Member as Field; // The type of the field may be a formal type parameter, in which case the hint is omitted if (field.Type.IsNonNullRefType) { name = string.Format("field '{0}'", field.Name); } } if (name != null) { // The following relies on that a NonNullTypeDecl has a .Rhs that is a // UserDefinedType denoting the possibly null type declaration and that // these two types have the same number of type arguments. var nonNullTypeDecl = (NonNullTypeDecl)nntUdf.ResolvedClass; var possiblyNullUdf = (UserDefinedType)nonNullTypeDecl.Rhs; var possiblyNullTypeDecl = (ClassDecl)possiblyNullUdf.ResolvedClass; Contract.Assert(nonNullTypeDecl.TypeArgs.Count == possiblyNullTypeDecl.TypeArgs.Count); Contract.Assert(nonNullTypeDecl.TypeArgs.Count == nntUdf.TypeArgs.Count); var ty = new UserDefinedType(nntUdf.tok, possiblyNullUdf.Name, possiblyNullTypeDecl, nntUdf.TypeArgs); hint = string.Format(" (to make it possible for {0} to have the value 'null', declare its type to be '{1}')", name, ty); } resolver.reporter.Warning(MessageSource.Resolver, e.tok, string.Format("the type of the other operand is a non-null type, so this comparison with 'null' will always return '{0}'{1}", sense ? "false" : "true", hint)); } break; } case BinaryExpr.ResolvedOpcode.NotInSet: case BinaryExpr.ResolvedOpcode.NotInSeq: case BinaryExpr.ResolvedOpcode.NotInMultiSet: sense = false; goto case BinaryExpr.ResolvedOpcode.InSet; case BinaryExpr.ResolvedOpcode.InSet: case BinaryExpr.ResolvedOpcode.InSeq: case BinaryExpr.ResolvedOpcode.InMultiSet: { var ty = other.Type.NormalizeExpand(); var what = ty is SetType ? "set" : ty is SeqType ? "seq" : "multiset"; if (((CollectionType)ty).Arg.IsNonNullRefType) { resolver.reporter.Warning(MessageSource.Resolver, e.tok, string.Format("the type of the other operand is a {0} of non-null elements, so the {1}inclusion test of 'null' will always return '{2}'", what, sense ? "" : "non-", sense ? "false" : "true")); } break; } case BinaryExpr.ResolvedOpcode.NotInMap: goto case BinaryExpr.ResolvedOpcode.InMap; case BinaryExpr.ResolvedOpcode.InMap: { var ty = other.Type.NormalizeExpand(); if (((MapType)ty).Domain.IsNonNullRefType) { resolver.reporter.Warning(MessageSource.Resolver, e.tok, string.Format("the type of the other operand is a map to a non-null type, so the inclusion test of 'null' will always return '{0}'", sense ? "false" : "true")); } break; } default: break; } } } else if (expr is NegationExpression) { var e = (NegationExpression)expr; Expression resolved = null; if (e.E is LiteralExpr lit) { // note, not e.E.Resolved, since we don't want to do this for double negations // For real-based types, integer-based types, and bi (but not bitvectors), "-" followed by a literal is just a literal expression with a negative value if (e.E.Type.IsNumericBased(Type.NumericPersuasion.Real)) { var d = (BaseTypes.BigDec)lit.Value; Contract.Assert(!d.IsNegative); resolved = new LiteralExpr(e.tok, -d); } else if (e.E.Type.IsNumericBased(Type.NumericPersuasion.Int)) { var n = (BigInteger)lit.Value; Contract.Assert(0 <= n); resolved = new LiteralExpr(e.tok, -n); } } if (resolved == null) { // Treat all other expressions "-e" as "0 - e" Expression zero; if (e.E.Type.IsNumericBased(Type.NumericPersuasion.Real)) { zero = new LiteralExpr(e.tok, BaseTypes.BigDec.ZERO); } else { Contract.Assert(e.E.Type.IsNumericBased(Type.NumericPersuasion.Int) || e.E.Type.IsBitVectorType); zero = new LiteralExpr(e.tok, 0); } zero.Type = expr.Type; resolved = new BinaryExpr(e.tok, BinaryExpr.Opcode.Sub, zero, e.E) {ResolvedOp = BinaryExpr.ResolvedOpcode.Sub}; } resolved.Type = expr.Type; e.ResolvedExpression = resolved; } } } public static bool IsDetermined(Type t) { Contract.Requires(t != null); Contract.Requires(!(t is TypeProxy) || ((TypeProxy)t).T == null); // all other proxies indicate the type has not yet been determined, provided their type parameters have been return !(t is TypeProxy) && t.TypeArgs.All(tt => IsDetermined(tt.Normalize())); } ISet<TypeProxy> UnderspecifiedTypeProxies = new HashSet<TypeProxy>(); public bool CheckTypeIsDetermined(IToken tok, Type t, string what) { Contract.Requires(tok != null); Contract.Requires(t != null); Contract.Requires(what != null); t = t.NormalizeExpand(); if (t is TypeProxy) { var proxy = (TypeProxy)t; if (!UnderspecifiedTypeProxies.Contains(proxy)) { // report an error for this TypeProxy only once resolver.reporter.Error(MessageSource.Resolver, tok, "the type of this {0} is underspecified", what); UnderspecifiedTypeProxies.Add(proxy); } return false; } // Recurse on type arguments: return t.TypeArgs.All(rg => CheckTypeIsDetermined(tok, rg, what)); } public void CheckTypeArgsContainNoOrdinal(IToken tok, Type t) { Contract.Requires(tok != null); Contract.Requires(t != null); t = t.NormalizeExpand(); t.TypeArgs.Iter(rg => CheckContainsNoOrdinal(tok, rg, "an ORDINAL type is not allowed to be used as a type argument")); } public void CheckContainsNoOrdinal(IToken tok, Type t, string errMsg) { Contract.Requires(tok != null); Contract.Requires(t != null); Contract.Requires(errMsg != null); t = t.NormalizeExpand(); if (t.IsBigOrdinalType) { resolver.reporter.Error(MessageSource.Resolver, tok, errMsg); } t.TypeArgs.Iter(rg => CheckContainsNoOrdinal(tok, rg, errMsg)); } } #endregion CheckTypeInference // ------------------------------------------------------------------------------------------------------ // ----- CheckExpression -------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region CheckExpression /// <summary> /// This method computes ghost interests in the statement portion of StmtExpr's and /// checks for hint restrictions in any CalcStmt. /// </summary> void CheckExpression(Expression expr, Resolver resolver, ICodeContext codeContext) { Contract.Requires(expr != null); Contract.Requires(resolver != null); Contract.Requires(codeContext != null); var v = new CheckExpression_Visitor(resolver, codeContext); v.Visit(expr); } /// <summary> /// This method computes ghost interests in the statement portion of StmtExpr's and /// checks for hint restrictions in any CalcStmt. In any ghost context, it also /// changes the bound variables of all let- and let-such-that expressions to ghost. /// </summary> void CheckExpression(Statement stmt, Resolver resolver, ICodeContext codeContext) { Contract.Requires(stmt != null); Contract.Requires(resolver != null); Contract.Requires(codeContext != null); var v = new CheckExpression_Visitor(resolver, codeContext); v.Visit(stmt); } class CheckExpression_Visitor : ResolverBottomUpVisitor { readonly ICodeContext CodeContext; public CheckExpression_Visitor(Resolver resolver, ICodeContext codeContext) : base(resolver) { Contract.Requires(resolver != null); Contract.Requires(codeContext != null); CodeContext = codeContext; } protected override void VisitOneExpr(Expression expr) { if (expr is StmtExpr) { var e = (StmtExpr)expr; resolver.ComputeGhostInterest(e.S, true, CodeContext); } else if (expr is LetExpr) { var e = (LetExpr)expr; if (CodeContext.IsGhost) { foreach (var bv in e.BoundVars) { bv.MakeGhost(); } } } } protected override void VisitOneStmt(Statement stmt) { if (stmt is CalcStmt) { var s = (CalcStmt)stmt; foreach (var h in s.Hints) { resolver.CheckHintRestrictions(h, new HashSet<LocalVariable>(), "a hint"); } } else if (stmt is AssertStmt astmt && astmt.Proof != null) { resolver.CheckHintRestrictions(astmt.Proof, new HashSet<LocalVariable>(), "an assert-by body"); } } } #endregion // ------------------------------------------------------------------------------------------------------ // ----- CheckTailRecursive ----------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region CheckTailRecursive void DetermineTailRecursion(Method m) { Contract.Requires(m != null); Contract.Requires(m.Body != null); bool tail = true; bool hasTailRecursionPreference = Attributes.ContainsBool(m.Attributes, "tailrecursion", ref tail); if (hasTailRecursionPreference && !tail) { // the user specifically requested no tail recursion, so do nothing else } else if (hasTailRecursionPreference && tail && m.IsGhost) { reporter.Error(MessageSource.Resolver, m.tok, "tail recursion can be specified only for methods that will be compiled, not for ghost methods"); } else { var module = m.EnclosingClass.EnclosingModuleDefinition; var sccSize = module.CallGraph.GetSCCSize(m); if (hasTailRecursionPreference && 2 <= sccSize) { reporter.Error(MessageSource.Resolver, m.tok, "sorry, tail-call optimizations are not supported for mutually recursive methods"); } else if (hasTailRecursionPreference || sccSize == 1) { CallStmt tailCall = null; var status = CheckTailRecursive(m.Body.Body, m, ref tailCall, hasTailRecursionPreference); if (status != TailRecursionStatus.NotTailRecursive && tailCall != null) { // this means there was at least one recursive call m.IsTailRecursive = true; reporter.Info(MessageSource.Resolver, m.tok, "tail recursive"); } } } } enum TailRecursionStatus { NotTailRecursive, // contains code that makes the enclosing method body not tail recursive (in way that is supported) CanBeFollowedByAnything, // the code just analyzed does not do any recursive calls TailCallSpent, // the method body is tail recursive, provided that all code that follows it in the method body is ghost } /// <summary> /// Checks if "stmts" can be considered tail recursive, and (provided "reportError" is true) reports an error if not. /// Note, the current implementation is rather conservative in its analysis; upon need, the /// algorithm could be improved. /// In the current implementation, "enclosingMethod" is not allowed to be a mutually recursive method. /// /// The incoming value of "tailCall" is not used, but it's nevertheless a 'ref' parameter to allow the /// body to return the incoming value or to omit assignments to it. /// If the return value is CanBeFollowedByAnything, "tailCall" is unchanged. /// If the return value is TailCallSpent, "tailCall" shows one of the calls where the tail call was spent. (Note, /// there could be several if the statements have branches.) /// If the return value is NoTailRecursive, "tailCall" could be anything. In this case, an error /// message has been reported (provided "reportsErrors" is true). /// </summary> TailRecursionStatus CheckTailRecursive(List<Statement> stmts, Method enclosingMethod, ref CallStmt tailCall, bool reportErrors) { Contract.Requires(stmts != null); var status = TailRecursionStatus.CanBeFollowedByAnything; foreach (var s in stmts) { if (!s.IsGhost) { if (s is ReturnStmt && ((ReturnStmt)s).hiddenUpdate == null) { return status; } if (status == TailRecursionStatus.TailCallSpent) { // a tail call cannot be followed by non-ghost code if (reportErrors) { reporter.Error(MessageSource.Resolver, tailCall.Tok, "this recursive call is not recognized as being tail recursive, because it is followed by non-ghost code"); } return TailRecursionStatus.NotTailRecursive; } status = CheckTailRecursive(s, enclosingMethod, ref tailCall, reportErrors); if (status == TailRecursionStatus.NotTailRecursive) { return status; } } } return status; } /// <summary> /// See CheckTailRecursive(List Statement, ...), including its description of "tailCall". /// In the current implementation, "enclosingMethod" is not allowed to be a mutually recursive method. /// </summary> TailRecursionStatus CheckTailRecursive(Statement stmt, Method enclosingMethod, ref CallStmt tailCall, bool reportErrors) { Contract.Requires(stmt != null); if (stmt.IsGhost) { return TailRecursionStatus.CanBeFollowedByAnything; } if (stmt is PrintStmt) { } else if (stmt is RevealStmt) { } else if (stmt is BreakStmt) { } else if (stmt is ReturnStmt) { var s = (ReturnStmt)stmt; if (s.hiddenUpdate != null) { return CheckTailRecursive(s.hiddenUpdate, enclosingMethod, ref tailCall, reportErrors); } } else if (stmt is AssignStmt) { var s = (AssignStmt)stmt; var tRhs = s.Rhs as TypeRhs; if (tRhs != null && tRhs.InitCall != null && tRhs.InitCall.Method == enclosingMethod) { // It's a recursive call. However, it is not a tail call, because after the "new" allocation // and init call have taken place, the newly allocated object has yet to be assigned to // the LHS of the assignment statement. if (reportErrors) { reporter.Error(MessageSource.Resolver, tRhs.InitCall.Tok, "the recursive call to '{0}' is not tail recursive, because the assignment of the LHS happens after the call", tRhs.InitCall.Method.Name); } return TailRecursionStatus.NotTailRecursive; } } else if (stmt is ModifyStmt) { var s = (ModifyStmt)stmt; if (s.Body != null) { return CheckTailRecursive(s.Body, enclosingMethod, ref tailCall, reportErrors); } } else if (stmt is CallStmt) { var s = (CallStmt)stmt; if (s.Method == enclosingMethod) { // It's a recursive call. It can be considered a tail call only if the LHS of the call are the // formal out-parameters of the method for (int i = 0; i < s.Lhs.Count; i++) { var formal = enclosingMethod.Outs[i]; if (!formal.IsGhost) { var lhs = s.Lhs[i] as IdentifierExpr; if (lhs != null && lhs.Var == formal) { // all is good } else { if (reportErrors) { reporter.Error(MessageSource.Resolver, s.Tok, "the recursive call to '{0}' is not tail recursive because the actual out-parameter{1} is not the formal out-parameter '{2}'", s.Method.Name, s.Lhs.Count == 1 ? "" : " " + i, formal.Name); } return TailRecursionStatus.NotTailRecursive; } } } // Moreover, it can be considered a tail recursive call only if the type parameters are the same // as in the caller. var classTypeParameterCount = s.Method.EnclosingClass.TypeArgs.Count; Contract.Assert(s.MethodSelect.TypeApplication_JustMember.Count == s.Method.TypeArgs.Count); for (int i = 0; i < s.Method.TypeArgs.Count; i++) { var formal = s.Method.TypeArgs[i]; var actual = s.MethodSelect.TypeApplication_JustMember[i].AsTypeParameter; if (formal != actual) { if (reportErrors) { reporter.Error(MessageSource.Resolver, s.Tok, "the recursive call to '{0}' is not tail recursive because the actual type parameter{1} is not the formal type parameter '{2}'", s.Method.Name, s.Method.TypeArgs.Count == 1 ? "" : " " + i, formal.Name); } return TailRecursionStatus.NotTailRecursive; } } tailCall = s; return TailRecursionStatus.TailCallSpent; } } else if (stmt is BlockStmt) { var s = (BlockStmt)stmt; return CheckTailRecursive(s.Body, enclosingMethod, ref tailCall, reportErrors); } else if (stmt is IfStmt) { var s = (IfStmt)stmt; var stThen = CheckTailRecursive(s.Thn, enclosingMethod, ref tailCall, reportErrors); if (stThen == TailRecursionStatus.NotTailRecursive) { return stThen; } var stElse = s.Els == null ? TailRecursionStatus.CanBeFollowedByAnything : CheckTailRecursive(s.Els, enclosingMethod, ref tailCall, reportErrors); if (stElse == TailRecursionStatus.NotTailRecursive) { return stElse; } else if (stThen == TailRecursionStatus.TailCallSpent || stElse == TailRecursionStatus.TailCallSpent) { return TailRecursionStatus.TailCallSpent; } } else if (stmt is AlternativeStmt) { var s = (AlternativeStmt)stmt; var status = TailRecursionStatus.CanBeFollowedByAnything; foreach (var alt in s.Alternatives) { var st = CheckTailRecursive(alt.Body, enclosingMethod, ref tailCall, reportErrors); if (st == TailRecursionStatus.NotTailRecursive) { return st; } else if (st == TailRecursionStatus.TailCallSpent) { status = st; } } return status; } else if (stmt is WhileStmt) { var s = (WhileStmt)stmt; var status = TailRecursionStatus.NotTailRecursive; if (s.Body != null) { status = CheckTailRecursive(s.Body, enclosingMethod, ref tailCall, reportErrors); } if (status != TailRecursionStatus.CanBeFollowedByAnything) { if (status == TailRecursionStatus.NotTailRecursive) { // an error has already been reported } else if (reportErrors) { reporter.Error(MessageSource.Resolver, tailCall.Tok, "a recursive call inside a loop is not recognized as being a tail call"); } return TailRecursionStatus.NotTailRecursive; } } else if (stmt is AlternativeLoopStmt) { var s = (AlternativeLoopStmt)stmt; foreach (var alt in s.Alternatives) { var status = CheckTailRecursive(alt.Body, enclosingMethod, ref tailCall, reportErrors); if (status != TailRecursionStatus.CanBeFollowedByAnything) { if (status == TailRecursionStatus.NotTailRecursive) { // an error has already been reported } else if (reportErrors) { reporter.Error(MessageSource.Resolver, tailCall.Tok, "a recursive call inside a loop is not recognized as being a tail call"); } return TailRecursionStatus.NotTailRecursive; } } } else if (stmt is ForallStmt) { var s = (ForallStmt)stmt; var status = TailRecursionStatus.NotTailRecursive; if (s.Body != null) { status = CheckTailRecursive(s.Body, enclosingMethod, ref tailCall, reportErrors); } if (status != TailRecursionStatus.CanBeFollowedByAnything) { if (status == TailRecursionStatus.NotTailRecursive) { // an error has already been reported } else if (reportErrors) { reporter.Error(MessageSource.Resolver, tailCall.Tok, "a recursive call inside a forall statement is not a tail call"); } return TailRecursionStatus.NotTailRecursive; } } else if (stmt is MatchStmt) { var s = (MatchStmt)stmt; var status = TailRecursionStatus.CanBeFollowedByAnything; foreach (var kase in s.Cases) { var st = CheckTailRecursive(kase.Body, enclosingMethod, ref tailCall, reportErrors); if (st == TailRecursionStatus.NotTailRecursive) { return st; } else if (st == TailRecursionStatus.TailCallSpent) { status = st; } } return status; } else if (stmt is ConcreteSyntaxStatement) { var s = (ConcreteSyntaxStatement)stmt; return CheckTailRecursive(s.ResolvedStatement, enclosingMethod, ref tailCall, reportErrors); } else if (stmt is AssignSuchThatStmt) { } else if (stmt is AssignOrReturnStmt) { // TODO this should be the conservative choice, but probably we can consider this to be tail-recursive // under some conditions? However, how does this interact with compiling to exceptions? return TailRecursionStatus.NotTailRecursive; } else if (stmt is UpdateStmt) { var s = (UpdateStmt)stmt; return CheckTailRecursive(s.ResolvedStatements, enclosingMethod, ref tailCall, reportErrors); } else if (stmt is VarDeclStmt) { var s = (VarDeclStmt)stmt; if (s.Update != null) { return CheckTailRecursive(s.Update, enclosingMethod, ref tailCall, reportErrors); } } else if (stmt is VarDeclPattern) { } else if (stmt is ExpectStmt) { } else { Contract.Assert(false); // unexpected statement type } return TailRecursionStatus.CanBeFollowedByAnything; } #endregion CheckTailRecursive // ------------------------------------------------------------------------------------------------------ // ----- CheckTailRecursiveExpr ------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region CheckTailRecursiveExpr void DetermineTailRecursion(Function f) { Contract.Requires(f != null); Contract.Requires(f.Body != null); bool tail = true; bool hasTailRecursionPreference = Attributes.ContainsBool(f.Attributes, "tailrecursion", ref tail); if (hasTailRecursionPreference && !tail) { // the user specifically requested no tail recursion, so do nothing else } else if (hasTailRecursionPreference && tail && f.IsGhost) { reporter.Error(MessageSource.Resolver, f.tok, "tail recursion can be specified only for function that will be compiled, not for ghost functions"); } else { var module = f.EnclosingClass.EnclosingModuleDefinition; var sccSize = module.CallGraph.GetSCCSize(f); if (hasTailRecursionPreference && 2 <= sccSize) { reporter.Error(MessageSource.Resolver, f.tok, "sorry, tail-call optimizations are not supported for mutually recursive functions"); } else if (hasTailRecursionPreference || sccSize == 1) { var status = CheckTailRecursiveExpr(f.Body, f, true, hasTailRecursionPreference); if (status != Function.TailStatus.TriviallyTailRecursive && status != Function.TailStatus.NotTailRecursive) { // this means there was at least one recursive call f.TailRecursion = status; if (status == Function.TailStatus.TailRecursive) { reporter.Info(MessageSource.Resolver, f.tok, "tail recursive"); } else { reporter.Info(MessageSource.Resolver, f.tok, "auto-accumulator tail recursive"); } } } } } Function.TailStatus TRES_Or(Function.TailStatus a, Function.TailStatus b) { if (a == Function.TailStatus.NotTailRecursive || b == Function.TailStatus.NotTailRecursive) { return Function.TailStatus.NotTailRecursive; } else if (a == Function.TailStatus.TriviallyTailRecursive) { return b; } else if (b == Function.TailStatus.TriviallyTailRecursive) { return a; } else if (a == Function.TailStatus.TailRecursive) { return b; } else if (b == Function.TailStatus.TailRecursive) { return a; } else if (a == b) { return a; } else { return Function.TailStatus.NotTailRecursive; } } /// <summary> /// Checks if "expr" can be considered tail recursive, and (provided "reportError" is true) reports an error if not. /// Note, the current implementation is rather conservative in its analysis; upon need, the /// algorithm could be improved. /// In the current implementation, "enclosingFunction" is not allowed to be a mutually recursive function. /// /// If "allowAccumulator" is "true", then tail recursion also allows expressions of the form "E * F" /// and "F * E" where "F" is a tail-recursive expression without an accumulator, "E" has no occurrences /// of the enclosing function, and "*" is an associative and eager operator with a known (left or right, respectively) /// unit element. If "*" is such an operator, then "allowAccumulator" also allows expressions of /// the form "F - E', where "-" is an operator that satisfies "(A - X) - Y == A - (X * Y)". /// /// If "allowAccumulator" is "false", then this method returns one of these three values: /// TriviallyTailRecursive, TailRecursive, NotTailRecursive /// </summary> Function.TailStatus CheckTailRecursiveExpr(Expression expr, Function enclosingFunction, bool allowAccumulator, bool reportErrors) { Contract.Requires(expr != null); Contract.Requires(enclosingFunction != null); expr = expr.Resolved; if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; var status = e.Function == enclosingFunction ? Function.TailStatus.TailRecursive : Function.TailStatus.TriviallyTailRecursive; for (var i = 0; i < e.Function.Formals.Count; i++) { if (!e.Function.Formals[i].IsGhost) { var s = CheckHasNoRecursiveCall(e.Args[i], enclosingFunction, reportErrors); status = TRES_Or(status, s); } } return status; } else if (expr is LetExpr) { var e = (LetExpr)expr; var status = Function.TailStatus.TriviallyTailRecursive; for (var i = 0; i < e.LHSs.Count; i++) { var pat = e.LHSs[i]; if (pat.Vars.ToList().Exists(bv => !bv.IsGhost)) { if (e.Exact) { var s = CheckHasNoRecursiveCall(e.RHSs[i], enclosingFunction, reportErrors); status = TRES_Or(status, s); } else { // We have detected the existence of a non-ghost LHS, so check the RHS Contract.Assert(e.RHSs.Count == 1); status = CheckHasNoRecursiveCall(e.RHSs[0], enclosingFunction, reportErrors); break; } } } var st = CheckTailRecursiveExpr(e.Body, enclosingFunction, allowAccumulator, reportErrors); return TRES_Or(status, st); } else if (expr is ITEExpr) { var e = (ITEExpr)expr; var s0 = CheckHasNoRecursiveCall(e.Test, enclosingFunction, reportErrors); var s1 = CheckTailRecursiveExpr(e.Thn, enclosingFunction, allowAccumulator, reportErrors); var s2 = CheckTailRecursiveExpr(e.Els, enclosingFunction, allowAccumulator, reportErrors); var status = TRES_Or(s0, TRES_Or(s1, s2)); if (reportErrors && status == Function.TailStatus.NotTailRecursive) { // We get here for one of the following reasons: // * e.Test mentions the function (in which case an error has already been reported), // * either e.Thn or e.Els was determined to be NotTailRecursive (in which case an // error has already been reported), // * e.Thn and e.Els have different kinds of accumulator needs if (s0 != Function.TailStatus.NotTailRecursive && s1 != Function.TailStatus.NotTailRecursive && s2 != Function.TailStatus.NotTailRecursive) { reporter.Error(MessageSource.Resolver, expr, "if-then-else branches have different accumulator needs for tail recursion"); } } return status; } else if (expr is MatchExpr) { var e = (MatchExpr)expr; var status = CheckHasNoRecursiveCall(e.Source, enclosingFunction, reportErrors); var newError = reportErrors && status != Function.TailStatus.NotTailRecursive; foreach (var kase in e.Cases) { var s = CheckTailRecursiveExpr(kase.Body, enclosingFunction, allowAccumulator, reportErrors); newError = newError && s != Function.TailStatus.NotTailRecursive; status = TRES_Or(status, s); } if (status == Function.TailStatus.NotTailRecursive && newError) { // see comments above for ITEExpr // "newError" is "true" when: "reportErrors", and neither e.Source nor a kase.Body returned NotTailRecursive reporter.Error(MessageSource.Resolver, expr, "cases have different accumulator needs for tail recursion"); } return status; } else if (allowAccumulator && expr is BinaryExpr bin) { var accumulationOp = Function.TailStatus.TriviallyTailRecursive; // use TriviallyTailRecursive to mean bin.ResolvedOp does not support accumulation bool accumulatesOnlyOnRight = false; switch (bin.ResolvedOp) { case BinaryExpr.ResolvedOpcode.Add: if (enclosingFunction.ResultType.AsBitVectorType == null && !enclosingFunction.ResultType.IsCharType) { accumulationOp = Function.TailStatus.Accumulate_Add; } break; case BinaryExpr.ResolvedOpcode.Sub: if (enclosingFunction.ResultType.AsBitVectorType == null && !enclosingFunction.ResultType.IsCharType) { accumulationOp = Function.TailStatus.AccumulateRight_Sub; accumulatesOnlyOnRight = true; } break; case BinaryExpr.ResolvedOpcode.Mul: if (enclosingFunction.ResultType.AsBitVectorType == null) { accumulationOp = Function.TailStatus.Accumulate_Mul; } break; case BinaryExpr.ResolvedOpcode.Union: accumulationOp = Function.TailStatus.Accumulate_SetUnion; break; case BinaryExpr.ResolvedOpcode.SetDifference: accumulationOp = Function.TailStatus.AccumulateRight_SetDifference; accumulatesOnlyOnRight = true; break; case BinaryExpr.ResolvedOpcode.MultiSetUnion: accumulationOp = Function.TailStatus.Accumulate_MultiSetUnion; break; case BinaryExpr.ResolvedOpcode.MultiSetDifference: accumulationOp = Function.TailStatus.AccumulateRight_MultiSetDifference; accumulatesOnlyOnRight = true; break; case BinaryExpr.ResolvedOpcode.Concat: accumulationOp = Function.TailStatus.AccumulateLeft_Concat; // could also be AccumulateRight_Concat--make more precise below break; default: break; } if (accumulationOp != Function.TailStatus.TriviallyTailRecursive) { var s0 = CheckTailRecursiveExpr(bin.E0, enclosingFunction, false, reportErrors); Function.TailStatus s1; switch (s0) { case Function.TailStatus.NotTailRecursive: // Any errors have already been reported, but still descend down bin.E1 (possibly reporting // more errors) before returning with NotTailRecursive s1 = CheckTailRecursiveExpr(bin.E1, enclosingFunction, false, reportErrors); return s0; case Function.TailStatus.TriviallyTailRecursive: // We are in a state that would allow AcculumateLeftTailRecursive. See what bin.E1 is like: if (accumulatesOnlyOnRight) { s1 = CheckHasNoRecursiveCall(bin.E1, enclosingFunction, reportErrors); } else { s1 = CheckTailRecursiveExpr(bin.E1, enclosingFunction, false, reportErrors); } if (s1 == Function.TailStatus.TailRecursive) { bin.AccumulatesForTailRecursion = BinaryExpr.AccumulationOperand.Left; } else { Contract.Assert(s1 == Function.TailStatus.TriviallyTailRecursive || s1 == Function.TailStatus.NotTailRecursive); return s1; } return accumulationOp; case Function.TailStatus.TailRecursive: // We are in a state that would allow right-accumulative tail recursion. Check that the enclosing // function is not mentioned in bin.E1. s1 = CheckHasNoRecursiveCall(bin.E1, enclosingFunction, reportErrors); if (s1 == Function.TailStatus.TriviallyTailRecursive) { bin.AccumulatesForTailRecursion = BinaryExpr.AccumulationOperand.Right; if (accumulationOp == Function.TailStatus.AccumulateLeft_Concat) { // switch to AccumulateRight_Concat, since we had approximated it as AccumulateLeft_Concat above return Function.TailStatus.AccumulateRight_Concat; } else { return accumulationOp; } } else { Contract.Assert(s1 == Function.TailStatus.NotTailRecursive); return s1; } default: Contract.Assert(false); // unexpected case throw new cce.UnreachableException(); } } // not an operator that allows accumulation, so drop down below } else if (expr is StmtExpr) { var e = (StmtExpr)expr; // ignore the statement part, since it is ghost return CheckTailRecursiveExpr(e.E, enclosingFunction, allowAccumulator, reportErrors); } return CheckHasNoRecursiveCall(expr, enclosingFunction, reportErrors); } /// <summary> /// If "expr" contains a recursive call to "enclosingFunction" in some non-ghost sub-expressions, /// then returns TailStatus.NotTailRecursive (and if "reportErrors" is "true", then /// reports an error about the recursive call), else returns TailStatus.TriviallyTailRecursive. /// </summary> Function.TailStatus CheckHasNoRecursiveCall(Expression expr, Function enclosingFunction, bool reportErrors) { Contract.Requires(expr != null); Contract.Requires(enclosingFunction != null); var status = Function.TailStatus.TriviallyTailRecursive; if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; if (e.Function == enclosingFunction) { if (reportErrors) { reporter.Error(MessageSource.Resolver, expr, "to be tail recursive, every use of this function must be part of a tail call or a simple accumulating tail call"); } status = Function.TailStatus.NotTailRecursive; } // skip ghost sub-expressions for (var i = 0; i < e.Function.Formals.Count; i++) { if (!e.Function.Formals[i].IsGhost) { var s = CheckHasNoRecursiveCall(e.Args[i], enclosingFunction, reportErrors); status = TRES_Or(status, s); } } return status; } else if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; if (e.Member == enclosingFunction) { if (reportErrors) { reporter.Error(MessageSource.Resolver, expr, "to be tail recursive, every use of this function must be part of a tail call or a simple accumulating tail call"); } return Function.TailStatus.NotTailRecursive; } } else if (expr is LetExpr) { var e = (LetExpr)expr; // skip ghost sub-expressions for (var i = 0; i < e.LHSs.Count; i++) { var pat = e.LHSs[i]; if (pat.Vars.ToList().Exists(bv => !bv.IsGhost)) { if (e.Exact) { var s = CheckHasNoRecursiveCall(e.RHSs[i], enclosingFunction, reportErrors); status = TRES_Or(status, s); } else { // We have detected the existence of a non-ghost LHS, so check the RHS Contract.Assert(e.RHSs.Count == 1); status = CheckHasNoRecursiveCall(e.RHSs[0], enclosingFunction, reportErrors); break; } } } var st = CheckHasNoRecursiveCall(e.Body, enclosingFunction, reportErrors); return TRES_Or(status, st); } else if (expr is DatatypeValue) { var e = (DatatypeValue)expr; // skip ghost sub-expressions for (var i = 0; i < e.Ctor.Formals.Count; i++) { if (!e.Ctor.Formals[i].IsGhost) { var s = CheckHasNoRecursiveCall(e.Arguments[i], enclosingFunction, reportErrors); status = TRES_Or(status, s); } } return status; } foreach (var ee in expr.SubExpressions) { var s = CheckHasNoRecursiveCall(ee, enclosingFunction, reportErrors); status = TRES_Or(status, s); } return status; } #endregion CheckTailRecursiveExpr // ------------------------------------------------------------------------------------------------------ // ----- FuelAdjustmentChecks --------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region FuelAdjustmentChecks protected void CheckForFuelAdjustments(IToken tok, Attributes attrs, ModuleDefinition currentModule) { List<List<Expression>> results = Attributes.FindAllExpressions(attrs, "fuel"); if (results != null) { foreach (List<Expression> args in results) { if (args != null && args.Count >= 2) { // Try to extract the function from the first argument MemberSelectExpr selectExpr = args[0].Resolved as MemberSelectExpr; if (selectExpr != null) { Function f = selectExpr.Member as Function; if (f != null) { f.IsFueled = true; if (args.Count >= 3) { LiteralExpr literalLow = args[1] as LiteralExpr; LiteralExpr literalHigh = args[2] as LiteralExpr; if (literalLow != null && literalLow.Value is BigInteger && literalHigh != null && literalHigh.Value is BigInteger) { BigInteger low = (BigInteger)literalLow.Value; BigInteger high = (BigInteger)literalHigh.Value; if (!(high == low + 1 || (low == 0 && high == 0))) { reporter.Error(MessageSource.Resolver, tok, "fuel setting for function {0} must have high value == 1 + low value", f.Name); } } } } } } } } } public class FuelAdjustment_Context { public ModuleDefinition currentModule; public FuelAdjustment_Context(ModuleDefinition currentModule) { this.currentModule = currentModule; } } class FuelAdjustment_Visitor : ResolverTopDownVisitor<FuelAdjustment_Context> { public FuelAdjustment_Visitor(Resolver resolver) : base(resolver) { Contract.Requires(resolver != null); } protected override bool VisitOneStmt(Statement stmt, ref FuelAdjustment_Context st) { resolver.CheckForFuelAdjustments(stmt.Tok, stmt.Attributes, st.currentModule); return true; } } #endregion FuelAdjustmentChecks // ------------------------------------------------------------------------------------------------------ // ----- ExtremePredicateChecks ------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region ExtremePredicateChecks enum CallingPosition { Positive, Negative, Neither } static CallingPosition Invert(CallingPosition cp) { switch (cp) { case CallingPosition.Positive: return CallingPosition.Negative; case CallingPosition.Negative: return CallingPosition.Positive; default: return CallingPosition.Neither; } } class FindFriendlyCalls_Visitor : ResolverTopDownVisitor<CallingPosition> { public readonly bool IsCoContext; public readonly bool ContinuityIsImportant; public FindFriendlyCalls_Visitor(Resolver resolver, bool co, bool continuityIsImportant) : base(resolver) { Contract.Requires(resolver != null); this.IsCoContext = co; this.ContinuityIsImportant = continuityIsImportant; } protected override bool VisitOneExpr(Expression expr, ref CallingPosition cp) { if (expr is UnaryOpExpr) { var e = (UnaryOpExpr)expr; if (e.Op == UnaryOpExpr.Opcode.Not) { // for the sub-parts, use Invert(cp) cp = Invert(cp); return true; } } else if (expr is BinaryExpr) { var e = (BinaryExpr)expr; switch (e.ResolvedOp) { case BinaryExpr.ResolvedOpcode.And: case BinaryExpr.ResolvedOpcode.Or: return true; // do the sub-parts with the same "cp" case BinaryExpr.ResolvedOpcode.Imp: Visit(e.E0, Invert(cp)); Visit(e.E1, cp); return false; // don't recurse (again) on the sub-parts default: break; } } else if (expr is NestedMatchExpr) { var e = (NestedMatchExpr)expr; return VisitOneExpr(e.ResolvedExpression, ref cp); } else if (expr is MatchExpr) { var e = (MatchExpr)expr; Visit(e.Source, CallingPosition.Neither); var theCp = cp; e.Cases.Iter(kase => Visit(kase.Body, theCp)); return false; } else if (expr is ITEExpr) { var e = (ITEExpr)expr; Visit(e.Test, CallingPosition.Neither); Visit(e.Thn, cp); Visit(e.Els, cp); return false; } else if (expr is LetExpr) { var e = (LetExpr)expr; foreach (var rhs in e.RHSs) { Visit(rhs, CallingPosition.Neither); } var cpBody = cp; if (!e.Exact) { // a let-such-that expression introduces an existential that may depend on the _k in a least/greatest predicate, so we disallow recursive calls in the body of the let-such-that if (IsCoContext && cp == CallingPosition.Positive) { cpBody = CallingPosition.Neither; } else if (!IsCoContext && cp == CallingPosition.Negative) { cpBody = CallingPosition.Neither; } } Visit(e.Body, cpBody); return false; } else if (expr is QuantifierExpr) { var e = (QuantifierExpr)expr; Contract.Assert(e.SplitQuantifier == null); // No split quantifiers during resolution var cpos = IsCoContext ? cp : Invert(cp); if (ContinuityIsImportant) { if ((cpos == CallingPosition.Positive && e is ExistsExpr) || (cpos == CallingPosition.Negative && e is ForallExpr)) { if (e.Bounds.Exists(bnd => bnd == null || (bnd.Virtues & ComprehensionExpr.BoundedPool.PoolVirtues.Finite) == 0)) { // To ensure continuity of extreme predicates, don't allow calls under an existential (resp. universal) quantifier // for greatest (resp. least) predicates). cp = CallingPosition.Neither; } } } Visit(e.LogicalBody(), cp); return false; } else if (expr is StmtExpr) { var e = (StmtExpr)expr; Visit(e.E, cp); Visit(e.S, CallingPosition.Neither); return false; } else if (expr is ConcreteSyntaxExpression) { // do the sub-parts with the same "cp" return true; } // do the sub-parts with cp := Neither cp = CallingPosition.Neither; return true; } } void KNatMismatchError(IToken tok, string contextName, ExtremePredicate.KType contextK, ExtremePredicate.KType calleeK) { var hint = contextK == ExtremePredicate.KType.Unspecified ? string.Format(" (perhaps try declaring '{0}' as '{0}[nat]')", contextName) : ""; reporter.Error(MessageSource.Resolver, tok, "this call does not type check, because the context uses a _k parameter of type {0} whereas the callee uses a _k parameter of type {1}{2}", contextK == ExtremePredicate.KType.Nat ? "nat" : "ORDINAL", calleeK == ExtremePredicate.KType.Nat ? "nat" : "ORDINAL", hint); } class ExtremePredicateChecks_Visitor : FindFriendlyCalls_Visitor { readonly ExtremePredicate context; public ExtremePredicateChecks_Visitor(Resolver resolver, ExtremePredicate context) : base(resolver, context is GreatestPredicate, context.KNat) { Contract.Requires(resolver != null); Contract.Requires(context != null); this.context = context; } protected override bool VisitOneExpr(Expression expr, ref CallingPosition cp) { if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; if (ModuleDefinition.InSameSCC(context, e.Function)) { // we're looking at a recursive call if (!(context is LeastPredicate ? e.Function is LeastPredicate : e.Function is GreatestPredicate)) { resolver.reporter.Error(MessageSource.Resolver, e, "a recursive call from a {0} can go only to other {0}s", context.WhatKind); } else if (context.KNat != ((ExtremePredicate)e.Function).KNat) { resolver.KNatMismatchError(e.tok, context.Name, context.TypeOfK, ((ExtremePredicate)e.Function).TypeOfK); } else if (cp != CallingPosition.Positive) { var msg = string.Format("a {0} can be called recursively only in positive positions", context.WhatKind); if (ContinuityIsImportant && cp == CallingPosition.Neither) { // this may be inside an non-friendly quantifier msg += string.Format(" and cannot sit inside an unbounded {0} quantifier", context is LeastPredicate ? "universal" : "existential"); } else { // we don't care about the continuity restriction or // the extreme-call is not inside an quantifier, so don't bother mentioning the part of existentials/universals in the error message } resolver.reporter.Error(MessageSource.Resolver, e, msg); } else { e.CoCall = FunctionCallExpr.CoCallResolution.Yes; resolver.reporter.Info(MessageSource.Resolver, e.tok, e.Function.Name + "#[_k - 1]"); } } // do the sub-parts with cp := Neither cp = CallingPosition.Neither; return true; } return base.VisitOneExpr(expr, ref cp); } protected override bool VisitOneStmt(Statement stmt, ref CallingPosition st) { if (stmt is CallStmt) { var s = (CallStmt)stmt; if (ModuleDefinition.InSameSCC(context, s.Method)) { // we're looking at a recursive call resolver.reporter.Error(MessageSource.Resolver, stmt.Tok, "a recursive call from a {0} can go only to other {0}s", context.WhatKind); } // do the sub-parts with the same "cp" return true; } else { return base.VisitOneStmt(stmt, ref st); } } } void ExtremePredicateChecks(Expression expr, ExtremePredicate context, CallingPosition cp) { Contract.Requires(expr != null); Contract.Requires(context != null); var v = new ExtremePredicateChecks_Visitor(this, context); v.Visit(expr, cp); } #endregion ExtremePredicateChecks // ------------------------------------------------------------------------------------------------------ // ----- ExtremeLemmaChecks ----------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region ExtremeLemmaChecks class ExtremeLemmaChecks_Visitor : ResolverBottomUpVisitor { ExtremeLemma context; public ExtremeLemmaChecks_Visitor(Resolver resolver, ExtremeLemma context) : base(resolver) { Contract.Requires(resolver != null); Contract.Requires(context != null); this.context = context; } protected override void VisitOneStmt(Statement stmt) { if (stmt is CallStmt) { var s = (CallStmt)stmt; if (s.Method is ExtremeLemma || s.Method is PrefixLemma) { // all is cool } else { // the call goes from an extreme lemma context to a non-extreme-lemma callee if (ModuleDefinition.InSameSCC(context, s.Method)) { // we're looking at a recursive call (to a non-extreme-lemma) resolver.reporter.Error(MessageSource.Resolver, s.Tok, "a recursive call from a {0} can go only to other {0}s and prefix lemmas", context.WhatKind); } } } } protected override void VisitOneExpr(Expression expr) { if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; // the call goes from a greatest lemma context to a non-greatest-lemma callee if (ModuleDefinition.InSameSCC(context, e.Function)) { // we're looking at a recursive call (to a non-greatest-lemma) resolver.reporter.Error(MessageSource.Resolver, e.tok, "a recursive call from a greatest lemma can go only to other greatest lemmas and prefix lemmas"); } } } } void ExtremeLemmaChecks(Statement stmt, ExtremeLemma context) { Contract.Requires(stmt != null); Contract.Requires(context != null); var v = new ExtremeLemmaChecks_Visitor(this, context); v.Visit(stmt); } void ExtremeLemmaChecks(Expression expr, ExtremeLemma context) { Contract.Requires(context != null); if (expr == null) return; var v = new ExtremeLemmaChecks_Visitor(this, context); v.Visit(expr); } #endregion ExtremeLemmaChecks // ------------------------------------------------------------------------------------------------------ // ----- CheckEqualityTypes ----------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region CheckEqualityTypes class CheckEqualityTypes_Visitor : ResolverTopDownVisitor<bool> { public CheckEqualityTypes_Visitor(Resolver resolver) : base(resolver) { Contract.Requires(resolver != null); } protected override bool VisitOneStmt(Statement stmt, ref bool st) { if (stmt.IsGhost) { return false; // no need to recurse to sub-parts, since all sub-parts must be ghost as well } else if (stmt is VarDeclStmt) { var s = (VarDeclStmt)stmt; foreach (var v in s.Locals) { if (!v.IsGhost) { CheckEqualityTypes_Type(v.Tok, v.Type); } } } else if (stmt is VarDeclPattern) { var s = (VarDeclPattern)stmt; foreach (var v in s.LocalVars) { CheckEqualityTypes_Type(v.Tok, v.Type); } } else if (stmt is AssignStmt) { var s = (AssignStmt)stmt; var tRhs = s.Rhs as TypeRhs; if (tRhs != null && tRhs.Type is UserDefinedType) { var udt = (UserDefinedType)tRhs.Type; CheckTypeArgumentCharacteristics(tRhs.Tok, "type", udt.ResolvedClass.Name, udt.ResolvedClass.TypeArgs, tRhs.Type.TypeArgs); } } else if (stmt is WhileStmt) { var s = (WhileStmt)stmt; // don't recurse on the specification parts, which are ghost if (s.Guard != null) { Visit(s.Guard, st); } // don't recurse on the body, if it's a dirty loop if (s.Body != null) { Visit(s.Body, st); } return false; } else if (stmt is AlternativeLoopStmt) { var s = (AlternativeLoopStmt)stmt; // don't recurse on the specification parts, which are ghost foreach (var alt in s.Alternatives) { Visit(alt.Guard, st); foreach (var ss in alt.Body) { Visit(ss, st); } } return false; } else if (stmt is CallStmt) { var s = (CallStmt)stmt; CheckTypeArgumentCharacteristics(s.Tok, s.Method.WhatKind, s.Method.Name, s.Method.TypeArgs, s.MethodSelect.TypeApplication_JustMember); // recursively visit all subexpressions (which are all actual parameters) passed in for non-ghost formal parameters Contract.Assert(s.Lhs.Count == s.Method.Outs.Count); for (var i = 0; i < s.Method.Outs.Count; i++) { if (!s.Method.Outs[i].IsGhost) { Visit(s.Lhs[i], st); } } Visit(s.Receiver, st); Contract.Assert(s.Args.Count == s.Method.Ins.Count); for (var i = 0; i < s.Method.Ins.Count; i++) { if (!s.Method.Ins[i].IsGhost) { Visit(s.Args[i], st); } } return false; // we've done what there is to be done } else if (stmt is ForallStmt) { var s = (ForallStmt)stmt; foreach (var v in s.BoundVars) { CheckEqualityTypes_Type(v.Tok, v.Type); } // do substatements and subexpressions, except attributes and ensures clauses, since they are not compiled foreach (var ss in s.SubStatements) { Visit(ss, st); } if (s.Range != null) { Visit(s.Range, st); } return false; // we're done } return true; } void CheckTypeArgumentCharacteristics(IToken tok, string what, string className, List<TypeParameter> formalTypeArgs, List<Type> actualTypeArgs) { Contract.Requires(tok != null); Contract.Requires(what != null); Contract.Requires(className != null); Contract.Requires(formalTypeArgs != null); Contract.Requires(actualTypeArgs != null); Contract.Requires(formalTypeArgs.Count == actualTypeArgs.Count); for (var i = 0; i < formalTypeArgs.Count; i++) { var formal = formalTypeArgs[i]; var actual = actualTypeArgs[i]; string whatIsWrong, hint; if (!CheckCharacteristics(formal.Characteristics, actual, out whatIsWrong, out hint)) { resolver.reporter.Error(MessageSource.Resolver, tok, "type parameter{0} ({1}) passed to {2} {3} must support {4} (got {5}){6}", actualTypeArgs.Count == 1 ? "" : " " + i, formal.Name, what, className, whatIsWrong, actual, hint); } CheckEqualityTypes_Type(tok, actual); } } bool CheckCharacteristics(TypeParameter.TypeParameterCharacteristics formal, Type actual, out string whatIsWrong, out string hint) { Contract.Ensures(Contract.Result<bool>() || (Contract.ValueAtReturn(out whatIsWrong) != null && Contract.ValueAtReturn(out hint) != null)); if (formal.EqualitySupport != TypeParameter.EqualitySupportValue.Unspecified && !actual.SupportsEquality) { whatIsWrong = "equality"; hint = TypeEqualityErrorMessageHint(actual); return false; } if (formal.HasCompiledValue && !actual.HasCompilableValue) { whatIsWrong = "auto-initialization"; hint = ""; return false; } if (formal.IsNonempty && !actual.IsNonempty) { whatIsWrong = "nonempty"; hint = ""; return false; } if (formal.ContainsNoReferenceTypes && !actual.IsAllocFree) { whatIsWrong = "no references"; hint = ""; return false; } whatIsWrong = null; hint = null; return true; } protected override bool VisitOneExpr(Expression expr, ref bool st) { if (expr is BinaryExpr) { var e = (BinaryExpr)expr; var t0 = e.E0.Type.NormalizeExpand(); var t1 = e.E1.Type.NormalizeExpand(); switch (e.Op) { case BinaryExpr.Opcode.Eq: case BinaryExpr.Opcode.Neq: // First, check some special cases that can always be compared against--for example, a datatype value (like Nil) that takes no parameters if (CanCompareWith(e.E0)) { // that's cool } else if (CanCompareWith(e.E1)) { // oh yeah! } else if (!t0.SupportsEquality) { resolver.reporter.Error(MessageSource.Resolver, e.E0, "{0} can only be applied to expressions of types that support equality (got {1}){2}", BinaryExpr.OpcodeString(e.Op), t0, TypeEqualityErrorMessageHint(t0)); } else if (!t1.SupportsEquality) { resolver.reporter.Error(MessageSource.Resolver, e.E1, "{0} can only be applied to expressions of types that support equality (got {1}){2}", BinaryExpr.OpcodeString(e.Op), t1, TypeEqualityErrorMessageHint(t1)); } break; default: switch (e.ResolvedOp) { // Note, all operations on sets, multisets, and maps are guaranteed to work because of restrictions placed on how // these types are instantiated. (Except: This guarantee does not apply to equality on maps, because the Range type // of maps is not restricted, only the Domain type. However, the equality operator is checked above.) case BinaryExpr.ResolvedOpcode.InSeq: case BinaryExpr.ResolvedOpcode.NotInSeq: case BinaryExpr.ResolvedOpcode.Prefix: case BinaryExpr.ResolvedOpcode.ProperPrefix: if (!t1.SupportsEquality) { resolver.reporter.Error(MessageSource.Resolver, e.E1, "{0} can only be applied to expressions of sequence types that support equality (got {1}){2}", BinaryExpr.OpcodeString(e.Op), t1, TypeEqualityErrorMessageHint(t1)); } else if (!t0.SupportsEquality) { if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.InSet || e.ResolvedOp == BinaryExpr.ResolvedOpcode.NotInSeq) { resolver.reporter.Error(MessageSource.Resolver, e.E0, "{0} can only be applied to expressions of types that support equality (got {1}){2}", BinaryExpr.OpcodeString(e.Op), t0, TypeEqualityErrorMessageHint(t0)); } else { resolver.reporter.Error(MessageSource.Resolver, e.E0, "{0} can only be applied to expressions of sequence types that support equality (got {1}){2}", BinaryExpr.OpcodeString(e.Op), t0, TypeEqualityErrorMessageHint(t0)); } } break; default: break; } break; } } else if (expr is ComprehensionExpr) { var e = (ComprehensionExpr)expr; foreach (var bv in e.BoundVars) { CheckEqualityTypes_Type(bv.tok, bv.Type); } } else if (expr is LetExpr) { var e = (LetExpr)expr; foreach (var bv in e.BoundVars) { CheckEqualityTypes_Type(bv.tok, bv.Type); } } else if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; if (e.Member is Function || e.Member is Method) { CheckTypeArgumentCharacteristics(e.tok, e.Member.WhatKind, e.Member.Name, ((ICallable)e.Member).TypeArgs, e.TypeApplication_JustMember); } } else if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; CheckTypeArgumentCharacteristics(e.tok, e.Function.WhatKind, e.Function.Name, e.Function.TypeArgs, e.TypeApplication_JustFunction); // recursively visit all subexpressions (which are all actual parameters) passed in for non-ghost formal parameters Visit(e.Receiver, st); Contract.Assert(e.Args.Count == e.Function.Formals.Count); for (var i = 0; i < e.Args.Count; i++) { if (!e.Function.Formals[i].IsGhost) { Visit(e.Args[i], st); } } return false; // we've done what there is to be done } else if (expr is SetDisplayExpr || expr is MultiSetDisplayExpr || expr is MapDisplayExpr || expr is SeqConstructionExpr || expr is MultiSetFormingExpr || expr is StaticReceiverExpr) { // This catches other expressions whose type may potentially be illegal CheckEqualityTypes_Type(expr.tok, expr.Type); } return true; } private bool CanCompareWith(Expression expr) { Contract.Requires(expr != null); if (expr.Type.SupportsEquality) { return true; } expr = expr.Resolved; if (expr is DatatypeValue) { var e = (DatatypeValue)expr; for (int i = 0; i < e.Ctor.Formals.Count; i++) { if (e.Ctor.Formals[i].IsGhost) { return false; } else if (!CanCompareWith(e.Arguments[i])) { return false; } } return true; } else if (expr is DisplayExpression) { var e = (DisplayExpression)expr; return e.Elements.Count == 0; } else if (expr is MapDisplayExpr) { var e = (MapDisplayExpr)expr; return e.Elements.Count == 0; } return false; } public void CheckEqualityTypes_Type(IToken tok, Type type) { Contract.Requires(tok != null); Contract.Requires(type != null); type = type.Normalize(); // we only do a .Normalize() here, because we want to keep stop at any type synonym or subset type if (type is BasicType) { // fine } else if (type is SetType) { var st = (SetType)type; var argType = st.Arg; if (!argType.SupportsEquality) { resolver.reporter.Error(MessageSource.Resolver, tok, "{2}set argument type must support equality (got {0}){1}", argType, TypeEqualityErrorMessageHint(argType), st.Finite ? "" : "i"); } CheckEqualityTypes_Type(tok, argType); } else if (type is MultiSetType) { var argType = ((MultiSetType)type).Arg; if (!argType.SupportsEquality) { resolver.reporter.Error(MessageSource.Resolver, tok, "multiset argument type must support equality (got {0}){1}", argType, TypeEqualityErrorMessageHint(argType)); } CheckEqualityTypes_Type(tok, argType); } else if (type is MapType) { var mt = (MapType)type; if (!mt.Domain.SupportsEquality) { resolver.reporter.Error(MessageSource.Resolver, tok, "{2}map domain type must support equality (got {0}){1}", mt.Domain, TypeEqualityErrorMessageHint(mt.Domain), mt.Finite ? "" : "i"); } CheckEqualityTypes_Type(tok, mt.Domain); CheckEqualityTypes_Type(tok, mt.Range); } else if (type is SeqType) { Type argType = ((SeqType)type).Arg; CheckEqualityTypes_Type(tok, argType); } else if (type is UserDefinedType) { var udt = (UserDefinedType)type; List<TypeParameter> formalTypeArgs = null; if (udt.ResolvedClass != null) { formalTypeArgs = udt.ResolvedClass.TypeArgs; } else if (udt.ResolvedParam is OpaqueType_AsParameter) { var t = (OpaqueType_AsParameter)udt.ResolvedParam; formalTypeArgs = t.TypeArgs; } if (formalTypeArgs == null) { Contract.Assert(udt.TypeArgs.Count == 0); } else { CheckTypeArgumentCharacteristics(udt.tok, "type", udt.ResolvedClass.Name, formalTypeArgs, udt.TypeArgs); } } else if (type is TypeProxy) { // the type was underconstrained; this is checked elsewhere, but it is not in violation of the equality-type test } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type } } string TypeEqualityErrorMessageHint(Type argType) { Contract.Requires(argType != null); var tp = argType.AsTypeParameter; if (tp != null) { return string.Format(" (perhaps try declaring type parameter '{0}' on line {1} as '{0}(==)', which says it can only be instantiated with a type that supports equality)", tp.Name, tp.tok.line); } return ""; } } void CheckEqualityTypes_Stmt(Statement stmt) { Contract.Requires(stmt != null); var v = new CheckEqualityTypes_Visitor(this); v.Visit(stmt, false); } void CheckEqualityTypes(Expression expr) { Contract.Requires(expr != null); var v = new CheckEqualityTypes_Visitor(this); v.Visit(expr, false); } public void CheckEqualityTypes_Type(IToken tok, Type type) { Contract.Requires(tok != null); Contract.Requires(type != null); var v = new CheckEqualityTypes_Visitor(this); v.CheckEqualityTypes_Type(tok, type); } #endregion CheckEqualityTypes // ------------------------------------------------------------------------------------------------------ // ----- ComputeGhostInterest --------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region ComputeGhostInterest public void ComputeGhostInterest(Statement stmt, bool mustBeErasable, ICodeContext codeContext) { Contract.Requires(stmt != null); Contract.Requires(codeContext != null); var visitor = new GhostInterest_Visitor(codeContext, this); visitor.Visit(stmt, mustBeErasable); } class GhostInterest_Visitor { readonly ICodeContext codeContext; readonly Resolver resolver; public GhostInterest_Visitor(ICodeContext codeContext, Resolver resolver) { Contract.Requires(codeContext != null); Contract.Requires(resolver != null); this.codeContext = codeContext; this.resolver = resolver; } protected void Error(Statement stmt, string msg, params object[] msgArgs) { Contract.Requires(stmt != null); Contract.Requires(msg != null); Contract.Requires(msgArgs != null); resolver.reporter.Error(MessageSource.Resolver, stmt, msg, msgArgs); } protected void Error(Expression expr, string msg, params object[] msgArgs) { Contract.Requires(expr != null); Contract.Requires(msg != null); Contract.Requires(msgArgs != null); resolver.reporter.Error(MessageSource.Resolver, expr, msg, msgArgs); } protected void Error(IToken tok, string msg, params object[] msgArgs) { Contract.Requires(tok != null); Contract.Requires(msg != null); Contract.Requires(msgArgs != null); resolver.reporter.Error(MessageSource.Resolver, tok, msg, msgArgs); } /// <summary> /// This method does three things, in order: /// 0. Sets .IsGhost to "true" if the statement is ghost. This often depends on some guard of the statement /// (like the guard of an "if" statement) or the LHS of the statement (if it is an assignment). /// Note, if "mustBeErasable", then the statement is already in a ghost context. /// statement itself is ghost) or and the statement assigns to a non-ghost field /// 1. Determines if the statement and all its subparts are legal under its computed .IsGhost setting. /// 2. ``Upgrades'' .IsGhost to "true" if, after investigation of the substatements of the statement, it /// turns out that the statement can be erased during compilation. /// Notes: /// * Both step (0) and step (2) sets the .IsGhost field. What step (0) does affects only the /// rules of resolution, whereas step (2) makes a note for the later compilation phase. /// * It is important to do step (0) before step (1)--that is, it is important to set the statement's ghost /// status before descending into its sub-statements--because break statements look at the ghost status of /// its enclosing statements. /// * The method called by a StmtExpr must be ghost; however, this is checked elsewhere. For /// this reason, it is not necessary to visit all subexpressions, unless the subexpression /// matter for the ghost checking/recording of "stmt". /// </summary> public void Visit(Statement stmt, bool mustBeErasable) { Contract.Requires(stmt != null); Contract.Assume(!codeContext.IsGhost || mustBeErasable); // (this is really a precondition) codeContext.IsGhost ==> mustBeErasable if (stmt is AssertStmt || stmt is AssumeStmt) { stmt.IsGhost = true; var assertStmt = stmt as AssertStmt; if (assertStmt != null && assertStmt.Proof != null) { Visit(assertStmt.Proof, true); } } else if (stmt is ExpectStmt) { stmt.IsGhost = false; var s = (ExpectStmt)stmt; if (mustBeErasable) { Error(stmt, "expect statement is not allowed in this context (because this is a ghost method or because the statement is guarded by a specification-only expression)"); } else { resolver.CheckIsCompilable(s.Expr); // If not provided, the message is populated with a default value in resolution Contract.Assert(s.Message != null); resolver.CheckIsCompilable(s.Message); } } else if (stmt is PrintStmt) { var s = (PrintStmt)stmt; if (mustBeErasable) { Error(stmt, "print statement is not allowed in this context (because this is a ghost method or because the statement is guarded by a specification-only expression)"); } else { s.Args.Iter(resolver.CheckIsCompilable); } } else if (stmt is RevealStmt) { var s = (RevealStmt)stmt; s.ResolvedStatements.Iter(ss => Visit(ss, mustBeErasable)); s.IsGhost = s.ResolvedStatements.All(ss => ss.IsGhost); } else if (stmt is BreakStmt) { var s = (BreakStmt)stmt; s.IsGhost = mustBeErasable; if (s.IsGhost && !s.TargetStmt.IsGhost) { var targetIsLoop = s.TargetStmt is WhileStmt || s.TargetStmt is AlternativeLoopStmt; Error(stmt, "ghost-context break statement is not allowed to break out of non-ghost " + (targetIsLoop ? "loop" : "structure")); } } else if (stmt is ProduceStmt) { var s = (ProduceStmt)stmt; var kind = stmt is YieldStmt ? "yield" : "return"; if (mustBeErasable && !codeContext.IsGhost) { Error(stmt, "{0} statement is not allowed in this context (because it is guarded by a specification-only expression)", kind); } if (s.hiddenUpdate != null) { Visit(s.hiddenUpdate, mustBeErasable); } } else if (stmt is AssignSuchThatStmt) { var s = (AssignSuchThatStmt)stmt; s.IsGhost = mustBeErasable || s.AssumeToken != null || s.Lhss.Any(AssignStmt.LhsIsToGhost); if (mustBeErasable && !codeContext.IsGhost) { foreach (var lhs in s.Lhss) { var gk = AssignStmt.LhsIsToGhost_Which(lhs); if (gk != AssignStmt.NonGhostKind.IsGhost) { Error(lhs, "cannot assign to {0} in a ghost context", AssignStmt.NonGhostKind_To_String(gk)); } } } else if (!mustBeErasable && s.AssumeToken == null && resolver.UsesSpecFeatures(s.Expr)) { foreach (var lhs in s.Lhss) { var gk = AssignStmt.LhsIsToGhost_Which(lhs); if (gk != AssignStmt.NonGhostKind.IsGhost) { Error(lhs, "{0} cannot be assigned a value that depends on a ghost", AssignStmt.NonGhostKind_To_String(gk)); } } } } else if (stmt is UpdateStmt) { var s = (UpdateStmt)stmt; s.ResolvedStatements.Iter(ss => Visit(ss, mustBeErasable)); s.IsGhost = s.ResolvedStatements.All(ss => ss.IsGhost); } else if (stmt is AssignOrReturnStmt) { var s = (AssignOrReturnStmt)stmt; s.ResolvedStatements.Iter(ss => Visit(ss, mustBeErasable)); s.IsGhost = s.ResolvedStatements.All(ss => ss.IsGhost); } else if (stmt is VarDeclStmt) { var s = (VarDeclStmt)stmt; if (mustBeErasable) { foreach (var local in s.Locals) { // a local variable in a specification-only context might as well be ghost local.MakeGhost(); } } if (s.Update != null) { Visit(s.Update, mustBeErasable); } s.IsGhost = (s.Update == null || s.Update.IsGhost) && s.Locals.All(v => v.IsGhost); } else if (stmt is VarDeclPattern) { var s = (VarDeclPattern)stmt; if (mustBeErasable) { foreach (var local in s.LocalVars) { local.MakeGhost(); } } if (!s.IsAutoGhost || mustBeErasable) { s.IsGhost = s.LocalVars.All(v => v.IsGhost); } else { var spec = resolver.UsesSpecFeatures(s.RHS); if (spec) { foreach (var local in s.LocalVars) { local.MakeGhost(); } } else { resolver.CheckIsCompilable(s.RHS); } s.IsGhost = spec; } } else if (stmt is AssignStmt) { var s = (AssignStmt)stmt; var lhs = s.Lhs.Resolved; var gk = AssignStmt.LhsIsToGhost_Which(lhs); var isAutoGhost = AssignStmt.LhsIsToGhostOrAutoGhost(lhs); if (gk == AssignStmt.NonGhostKind.IsGhost) { s.IsGhost = true; if (s.Rhs is TypeRhs) { Error(s.Rhs.Tok, "'new' is not allowed in ghost contexts"); } } else if (gk == AssignStmt.NonGhostKind.Variable && codeContext.IsGhost) { // cool } else if (mustBeErasable) { Error(stmt, "Assignment to {0} is not allowed in this context (because this is a ghost method or because the statement is guarded by a specification-only expression)", AssignStmt.NonGhostKind_To_String(gk)); } else { if (gk == AssignStmt.NonGhostKind.Field) { var mse = (MemberSelectExpr)lhs; resolver.CheckIsCompilable(mse.Obj); } else if (gk == AssignStmt.NonGhostKind.ArrayElement) { resolver.CheckIsCompilable(lhs); } if (s.Rhs is ExprRhs) { var rhs = (ExprRhs)s.Rhs; if (isAutoGhost) { if (resolver.UsesSpecFeatures(rhs.Expr)) { // TODO: Is this the proper way to determine if an expression is ghost? ((lhs as AutoGhostIdentifierExpr).Var as LocalVariable).MakeGhost(); } } else { resolver.CheckIsCompilable(rhs.Expr); } } else if (s.Rhs is HavocRhs) { // cool } else { var rhs = (TypeRhs)s.Rhs; if (rhs.ArrayDimensions != null) { rhs.ArrayDimensions.ForEach(resolver.CheckIsCompilable); if (rhs.ElementInit != null) { resolver.CheckIsCompilable(rhs.ElementInit); } if (rhs.InitDisplay != null) { rhs.InitDisplay.ForEach(resolver.CheckIsCompilable); } } if (rhs.InitCall != null) { for (var i = 0; i < rhs.InitCall.Args.Count; i++) { if (!rhs.InitCall.Method.Ins[i].IsGhost) { resolver.CheckIsCompilable(rhs.InitCall.Args[i]); } } } } } } else if (stmt is CallStmt) { var s = (CallStmt)stmt; var callee = s.Method; Contract.Assert(callee != null); // follows from the invariant of CallStmt s.IsGhost = callee.IsGhost; // check in-parameters if (mustBeErasable) { if (!s.IsGhost) { Error(s, "only ghost methods can be called from this context"); } } else { int j; if (!callee.IsGhost) { resolver.CheckIsCompilable(s.Receiver); j = 0; foreach (var e in s.Args) { Contract.Assume(j < callee.Ins.Count); // this should have already been checked by the resolver if (!callee.Ins[j].IsGhost) { resolver.CheckIsCompilable(e); } j++; } } j = 0; foreach (var e in s.Lhs) { var resolvedLhs = e.Resolved; if (callee.IsGhost || callee.Outs[j].IsGhost) { // LHS must denote a ghost if (resolvedLhs is IdentifierExpr) { var ll = (IdentifierExpr)resolvedLhs; if (!ll.Var.IsGhost) { if (ll is AutoGhostIdentifierExpr && ll.Var is LocalVariable) { // the variable was actually declared in this statement, so auto-declare it as ghost ((LocalVariable)ll.Var).MakeGhost(); } else { Error(s, "actual out-parameter{0} is required to be a ghost variable", s.Lhs.Count == 1 ? "" : " " + j); } } } else if (resolvedLhs is MemberSelectExpr) { var ll = (MemberSelectExpr)resolvedLhs; if (!ll.Member.IsGhost) { Error(s, "actual out-parameter{0} is required to be a ghost field", s.Lhs.Count == 1 ? "" : " " + j); } } else { // this is an array update, and arrays are always non-ghost Error(s, "actual out-parameter{0} is required to be a ghost variable", s.Lhs.Count == 1 ? "" : " " + j); } } j++; } } } else if (stmt is BlockStmt) { var s = (BlockStmt)stmt; s.IsGhost = mustBeErasable; // set .IsGhost before descending into substatements (since substatements may do a 'break' out of this block) s.Body.Iter(ss => Visit(ss, mustBeErasable)); s.IsGhost = s.IsGhost || s.Body.All(ss => ss.IsGhost); // mark the block statement as ghost if all its substatements are ghost } else if (stmt is IfStmt) { var s = (IfStmt)stmt; s.IsGhost = mustBeErasable || (s.Guard != null && resolver.UsesSpecFeatures(s.Guard)); if (!mustBeErasable && s.IsGhost) { resolver.reporter.Info(MessageSource.Resolver, s.Tok, "ghost if"); } Visit(s.Thn, s.IsGhost); if (s.Els != null) { Visit(s.Els, s.IsGhost); } // if both branches were all ghost, then we can mark the enclosing statement as ghost as well s.IsGhost = s.IsGhost || (s.Thn.IsGhost && (s.Els == null || s.Els.IsGhost)); } else if (stmt is AlternativeStmt) { var s = (AlternativeStmt)stmt; s.IsGhost = mustBeErasable || s.Alternatives.Exists(alt => resolver.UsesSpecFeatures(alt.Guard)); if (!mustBeErasable && s.IsGhost) { resolver.reporter.Info(MessageSource.Resolver, s.Tok, "ghost if"); } s.Alternatives.Iter(alt => alt.Body.Iter(ss => Visit(ss, s.IsGhost))); s.IsGhost = s.IsGhost || s.Alternatives.All(alt => alt.Body.All(ss => ss.IsGhost)); } else if (stmt is WhileStmt) { var s = (WhileStmt)stmt; s.IsGhost = mustBeErasable || (s.Guard != null && resolver.UsesSpecFeatures(s.Guard)); if (!mustBeErasable && s.IsGhost) { resolver.reporter.Info(MessageSource.Resolver, s.Tok, "ghost while"); } if (s.IsGhost && s.Decreases.Expressions.Exists(e => e is WildcardExpr)) { Error(s, "'decreases *' is not allowed on ghost loops"); } if (s.IsGhost && s.Mod.Expressions != null) { s.Mod.Expressions.Iter(resolver.DisallowNonGhostFieldSpecifiers); } if (s.Body != null) { Visit(s.Body, s.IsGhost); if (s.Body.IsGhost && !s.Decreases.Expressions.Exists(e => e is WildcardExpr)) { s.IsGhost = true; } } } else if (stmt is AlternativeLoopStmt) { var s = (AlternativeLoopStmt)stmt; s.IsGhost = mustBeErasable || s.Alternatives.Exists(alt => resolver.UsesSpecFeatures(alt.Guard)); if (!mustBeErasable && s.IsGhost) { resolver.reporter.Info(MessageSource.Resolver, s.Tok, "ghost while"); } if (s.IsGhost && s.Decreases.Expressions.Exists(e => e is WildcardExpr)) { Error(s, "'decreases *' is not allowed on ghost loops"); } if (s.IsGhost && s.Mod.Expressions != null) { s.Mod.Expressions.Iter(resolver.DisallowNonGhostFieldSpecifiers); } s.Alternatives.Iter(alt => alt.Body.Iter(ss => Visit(ss, s.IsGhost))); s.IsGhost = s.IsGhost || (!s.Decreases.Expressions.Exists(e => e is WildcardExpr) && s.Alternatives.All(alt => alt.Body.All(ss => ss.IsGhost))); } else if (stmt is ForallStmt) { var s = (ForallStmt)stmt; s.IsGhost = mustBeErasable || s.Kind != ForallStmt.BodyKind.Assign || resolver.UsesSpecFeatures(s.Range); if (s.Body != null) { Visit(s.Body, s.IsGhost); } s.IsGhost = s.IsGhost || s.Body == null || s.Body.IsGhost; if (!s.IsGhost) { // Since we've determined this is a non-ghost forall statement, we now check that the bound variables have compilable bounds. var uncompilableBoundVars = s.UncompilableBoundVars(); if (uncompilableBoundVars.Count != 0) { foreach (var bv in uncompilableBoundVars) { Error(s, "forall statements in non-ghost contexts must be compilable, but Dafny's heuristics can't figure out how to produce or compile a bounded set of values for '{0}'", bv.Name); } } } } else if (stmt is ModifyStmt) { var s = (ModifyStmt)stmt; s.IsGhost = mustBeErasable; if (s.IsGhost) { s.Mod.Expressions.Iter(resolver.DisallowNonGhostFieldSpecifiers); } if (s.Body != null) { Visit(s.Body, mustBeErasable); } } else if (stmt is CalcStmt) { var s = (CalcStmt)stmt; s.IsGhost = true; foreach (var h in s.Hints) { Visit(h, true); } } else if (stmt is MatchStmt) { var s = (MatchStmt)stmt; s.IsGhost = mustBeErasable || resolver.UsesSpecFeatures(s.Source); if (!mustBeErasable && s.IsGhost) { resolver.reporter.Info(MessageSource.Resolver, s.Tok, "ghost match"); } s.Cases.Iter(kase => kase.Body.Iter(ss => Visit(ss, s.IsGhost))); s.IsGhost = s.IsGhost || s.Cases.All(kase => kase.Body.All(ss => ss.IsGhost)); } else if (stmt is ConcreteSyntaxStatement) { var s = (ConcreteSyntaxStatement)stmt; Visit(s.ResolvedStatement, mustBeErasable); s.IsGhost = s.IsGhost || s.ResolvedStatement.IsGhost; } else if (stmt is SkeletonStatement) { var s = (SkeletonStatement)stmt; s.IsGhost = mustBeErasable; if (s.S != null) { Visit(s.S, mustBeErasable); s.IsGhost = s.IsGhost || s.S.IsGhost; } } else { Contract.Assert(false); throw new cce.UnreachableException(); } } } #endregion // ------------------------------------------------------------------------------------------------------ // ----- FillInDefaultLoopDecreases --------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region FillInDefaultLoopDecreases class FillInDefaultLoopDecreases_Visitor : ResolverBottomUpVisitor { readonly ICallable EnclosingMethod; public FillInDefaultLoopDecreases_Visitor(Resolver resolver, ICallable enclosingMethod) : base(resolver) { Contract.Requires(resolver != null); Contract.Requires(enclosingMethod != null); EnclosingMethod = enclosingMethod; } protected override void VisitOneStmt(Statement stmt) { if (stmt is WhileStmt) { var s = (WhileStmt)stmt; resolver.FillInDefaultLoopDecreases(s, s.Guard, s.Decreases.Expressions, EnclosingMethod); } else if (stmt is AlternativeLoopStmt) { var s = (AlternativeLoopStmt)stmt; resolver.FillInDefaultLoopDecreases(s, null, s.Decreases.Expressions, EnclosingMethod); } } } #endregion FillInDefaultLoopDecreases // ------------------------------------------------------------------------------------------------------ // ----- ReportMoreAdditionalInformation ---------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region ReportOtherAdditionalInformation_Visitor class ReportOtherAdditionalInformation_Visitor : ResolverBottomUpVisitor { public ReportOtherAdditionalInformation_Visitor(Resolver resolver) : base(resolver) { Contract.Requires(resolver != null); } protected override void VisitOneStmt(Statement stmt) { if (stmt is ForallStmt) { var s = (ForallStmt)stmt; if (s.Kind == ForallStmt.BodyKind.Call) { var cs = (CallStmt)s.S0; // show the callee's postcondition as the postcondition of the 'forall' statement // TODO: The following substitutions do not correctly take into consideration variable capture; hence, what the hover text displays may be misleading var argsSubstMap = new Dictionary<IVariable, Expression>(); // maps formal arguments to actuals Contract.Assert(cs.Method.Ins.Count == cs.Args.Count); for (int i = 0; i < cs.Method.Ins.Count; i++) { argsSubstMap.Add(cs.Method.Ins[i], cs.Args[i]); } var substituter = new Translator.AlphaConverting_Substituter(cs.Receiver, argsSubstMap, new Dictionary<TypeParameter, Type>()); if (!Attributes.Contains(s.Attributes, "auto_generated")) { foreach (var ens in cs.Method.Ens) { var p = substituter.Substitute(ens.E); // substitute the call's actuals for the method's formals resolver.reporter.Info(MessageSource.Resolver, s.Tok, "ensures " + Printer.ExprToString(p)); } } } } } } #endregion ReportOtherAdditionalInformation_Visitor // ------------------------------------------------------------------------------------------------------ // ----- ReportMoreAdditionalInformation ---------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ #region CheckDividedConstructorInit class CheckDividedConstructorInit_Visitor : ResolverTopDownVisitor<int> { public CheckDividedConstructorInit_Visitor(Resolver resolver) : base(resolver) { Contract.Requires(resolver != null); } public void CheckInit(List<Statement> initStmts) { Contract.Requires(initStmts != null); initStmts.Iter(CheckInit); } /// <summary> /// This method almost does what Visit(Statement) does, except that it handles assignments to /// fields differently. /// </summary> void CheckInit(Statement stmt) { Contract.Requires(stmt != null); // Visit(stmt) would do: // stmt.SubExpressions.Iter(Visit); (*) // stmt.SubStatements.Iter(Visit); (**) // VisitOneStmt(stmt); (***) // We may do less for (*), we always use CheckInit instead of Visit in (**), and we do (***) the same. if (stmt is AssignStmt) { var s = stmt as AssignStmt; // The usual visitation of s.SubExpressions.Iter(Visit) would do the following: // Attributes.SubExpressions(s.Attributes).Iter(Visit); (+) // Visit(s.Lhs); (++) // s.Rhs.SubExpressions.Iter(Visit); (+++) // Here, we may do less; in particular, we may omit (++). Attributes.SubExpressions(s.Attributes).Iter(VisitExpr); // (+) var mse = s.Lhs as MemberSelectExpr; if (mse != null && Expression.AsThis(mse.Obj) != null) { if (s.Rhs is ExprRhs) { // This is a special case we allow. Omit s.Lhs in the recursive visits. That is, we omit (++). // Furthermore, because the assignment goes to a field of "this" and won't be available until after // the "new;", we can allow certain specific (and useful) uses of "this" in the RHS. s.Rhs.SubExpressions.Iter(LiberalRHSVisit); // (+++) } else { s.Rhs.SubExpressions.Iter(VisitExpr); // (+++) } } else { VisitExpr(s.Lhs); // (++) s.Rhs.SubExpressions.Iter(VisitExpr); // (+++) } } else { stmt.SubExpressions.Iter(VisitExpr); // (*) } stmt.SubStatements.Iter(CheckInit); // (**) int dummy = 0; VisitOneStmt(stmt, ref dummy); // (***) } void VisitExpr(Expression expr) { Contract.Requires(expr != null); Visit(expr, 0); } protected override bool VisitOneExpr(Expression expr, ref int unused) { if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; if (e.Member.IsInstanceIndependentConstant && Expression.AsThis(e.Obj) != null) { return false; // don't continue the recursion } } else if (expr is ThisExpr && !(expr is ImplicitThisExpr_ConstructorCall)) { resolver.reporter.Error(MessageSource.Resolver, expr.tok, "in the first division of the constructor body (before 'new;'), 'this' can only be used to assign to its fields"); } return base.VisitOneExpr(expr, ref unused); } void LiberalRHSVisit(Expression expr) { Contract.Requires(expr != null); // It is important not to allow "this" to flow into something that can be used (for compilation or // verification purposes) before the "new;", because, to the verifier, "this" has not yet been allocated. // The verifier is told that everything reachable from the heap is expected to be allocated and satisfy all // the usual properties, so "this" had better not become reachable from the heap until after the "new;" // that does the actual allocation of "this". // Within these restrictions, we can allow the (not yet fully available) value "this" to flow into values // stored in fields of "this". Such values are naked occurrences of "this" and "this" occurring // as part of constructing a value type. Since by this rule, "this" may be part of the value stored in // a field of "this", we must apply the same rules to uses of the values of fields of "this". if (expr is ConcreteSyntaxExpression) { } else if (expr is ThisExpr) { } else if (expr is MemberSelectExpr && IsThisDotField((MemberSelectExpr)expr)) { } else if (expr is SetDisplayExpr) { } else if (expr is MultiSetDisplayExpr) { } else if (expr is SeqDisplayExpr) { } else if (expr is MapDisplayExpr) { } else if (expr is BinaryExpr && IsCollectionOperator(((BinaryExpr)expr).ResolvedOp)) { } else if (expr is DatatypeValue) { } else if (expr is ITEExpr) { var e = (ITEExpr)expr; VisitExpr(e.Test); LiberalRHSVisit(e.Thn); LiberalRHSVisit(e.Els); return; } else { // defer to the usual Visit VisitExpr(expr); return; } expr.SubExpressions.Iter(LiberalRHSVisit); } static bool IsThisDotField(MemberSelectExpr expr) { Contract.Requires(expr != null); return Expression.AsThis(expr.Obj) != null && expr.Member is Field; } static bool IsCollectionOperator(BinaryExpr.ResolvedOpcode op) { switch (op) { // sets: +, *, - case BinaryExpr.ResolvedOpcode.Union: case BinaryExpr.ResolvedOpcode.Intersection: case BinaryExpr.ResolvedOpcode.SetDifference: // multisets: +, *, - case BinaryExpr.ResolvedOpcode.MultiSetUnion: case BinaryExpr.ResolvedOpcode.MultiSetIntersection: case BinaryExpr.ResolvedOpcode.MultiSetDifference: // sequences: + case BinaryExpr.ResolvedOpcode.Concat: // maps: +, - case BinaryExpr.ResolvedOpcode.MapMerge: case BinaryExpr.ResolvedOpcode.MapSubtraction: return true; default: return false; } } } #endregion // ------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------ bool InferRequiredEqualitySupport(TypeParameter tp, Type type) { Contract.Requires(tp != null); Contract.Requires(type != null); type = type.Normalize(); // we only do a .Normalize() here, because we want to keep stop at any type synonym or subset type if (type is BasicType) { } else if (type is SetType) { var st = (SetType)type; return st.Arg.AsTypeParameter == tp || InferRequiredEqualitySupport(tp, st.Arg); } else if (type is MultiSetType) { var ms = (MultiSetType)type; return ms.Arg.AsTypeParameter == tp || InferRequiredEqualitySupport(tp, ms.Arg); } else if (type is MapType) { var mt = (MapType)type; return mt.Domain.AsTypeParameter == tp || InferRequiredEqualitySupport(tp, mt.Domain) || InferRequiredEqualitySupport(tp, mt.Range); } else if (type is SeqType) { var sq = (SeqType)type; return InferRequiredEqualitySupport(tp, sq.Arg); } else if (type is UserDefinedType) { var udt = (UserDefinedType)type; List<TypeParameter> formalTypeArgs = null; if (udt.ResolvedClass != null) { formalTypeArgs = udt.ResolvedClass.TypeArgs; } else if (udt.ResolvedParam is OpaqueType_AsParameter) { var t = (OpaqueType_AsParameter)udt.ResolvedParam; formalTypeArgs = t.TypeArgs; } if (formalTypeArgs == null) { Contract.Assert(udt.TypeArgs.Count == 0); } else { Contract.Assert(formalTypeArgs.Count == udt.TypeArgs.Count); var i = 0; foreach (var argType in udt.TypeArgs) { var formalTypeArg = formalTypeArgs[i]; if ((formalTypeArg.SupportsEquality && argType.AsTypeParameter == tp) || InferRequiredEqualitySupport(tp, argType)) { return true; } i++; } } if (udt.ResolvedClass is TypeSynonymDecl) { var syn = (TypeSynonymDecl)udt.ResolvedClass; if (syn.IsRevealedInScope(Type.GetScope())) { return InferRequiredEqualitySupport(tp, syn.RhsWithArgument(udt.TypeArgs)); } } } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type } return false; } TopLevelDeclWithMembers currentClass; Method currentMethod; bool inBodyInitContext; // "true" only if "currentMethod is Constructor" readonly Scope<TypeParameter>/*!*/ allTypeParameters = new Scope<TypeParameter>(); readonly Scope<IVariable>/*!*/ scope = new Scope<IVariable>(); Scope<Statement>/*!*/ enclosingStatementLabels = new Scope<Statement>(); readonly Scope<Label>/*!*/ dominatingStatementLabels = new Scope<Label>(); List<Statement> loopStack = new List<Statement>(); // the enclosing loops (from which it is possible to break out) /// <summary> /// Resolves the types along .ParentTraits and fills in .ParentTraitHeads /// </summary> void ResolveParentTraitTypes(TopLevelDeclWithMembers cl, Graph<TopLevelDeclWithMembers> parentRelation) { Contract.Requires(cl != null); Contract.Requires(currentClass == null); Contract.Ensures(currentClass == null); currentClass = cl; allTypeParameters.PushMarker(); ResolveTypeParameters(cl.TypeArgs, false, cl); foreach (var tt in cl.ParentTraits) { var prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveType(cl.tok, tt, new NoContext(cl.EnclosingModuleDefinition), ResolveTypeOptionEnum.DontInfer, null); if (prevErrorCount == reporter.Count(ErrorLevel.Error)) { var udt = tt as UserDefinedType; if (udt != null && udt.ResolvedClass is NonNullTypeDecl nntd && nntd.ViewAsClass is TraitDecl trait) { // disallowing inheritance in multi module case bool termination = true; if (cl.EnclosingModuleDefinition == trait.EnclosingModuleDefinition || trait.IsObjectTrait || (Attributes.ContainsBool(trait.Attributes, "termination", ref termination) && !termination)) { // all is good (or the user takes responsibility for the lack of termination checking) if (!cl.ParentTraitHeads.Contains(trait)) { cl.ParentTraitHeads.Add(trait); parentRelation.AddEdge(cl, trait); } } else { reporter.Error(MessageSource.Resolver, udt.tok, "{0} '{1}' is in a different module than trait '{2}'. A {0} may only extend a trait in the same module, unless the parent trait is annotated with {{:termination false}}.", cl.WhatKind, cl.Name, trait.FullName); } } else { reporter.Error(MessageSource.Resolver, udt != null ? udt.tok : cl.tok, "a {0} can only extend traits (found '{1}')", cl.WhatKind, tt); } } } allTypeParameters.PopMarker(); currentClass = null; } /// <summary> /// This method idempotently fills in .InheritanceInformation, .ParentFormalTypeParametersToActuals, and the /// name->MemberDecl table for "cl" and the transitive parent traits of "cl". It also checks that every (transitive) /// parent trait is instantiated with the same type parameters /// The method assumes that all types along .ParentTraits have been successfully resolved and .ParentTraitHeads been filled in. /// </summary> void RegisterInheritedMembers(TopLevelDeclWithMembers cl) { Contract.Requires(cl != null); if (cl.ParentTypeInformation != null) { return; } cl.ParentTypeInformation = new TopLevelDeclWithMembers.InheritanceInformationClass(); // populate .ParentTypeInformation and .ParentFormalTypeParametersToActuals for the immediate parent traits foreach (var tt in cl.ParentTraits) { var udt = (UserDefinedType)tt; var nntd = (NonNullTypeDecl)udt.ResolvedClass; var trait = (TraitDecl)nntd.ViewAsClass; cl.ParentTypeInformation.Record(trait, udt); Contract.Assert(trait.TypeArgs.Count == udt.TypeArgs.Count); for (var i = 0; i < trait.TypeArgs.Count; i++) { // there may be duplciate parent traits, which haven't been checked for yet, so add mapping only for the first occurrence of each type parameter if (!cl.ParentFormalTypeParametersToActuals.ContainsKey(trait.TypeArgs[i])) { cl.ParentFormalTypeParametersToActuals.Add(trait.TypeArgs[i], udt.TypeArgs[i]); } } } // populate .ParentTypeInformation and .ParentFormalTypeParametersToActuals for the transitive parent traits foreach (var trait in cl.ParentTraitHeads) { // make sure the parent trait has been processed; then, incorporate its inheritance information RegisterInheritedMembers(trait); cl.ParentTypeInformation.Extend(trait, trait.ParentTypeInformation, cl.ParentFormalTypeParametersToActuals); foreach (var entry in trait.ParentFormalTypeParametersToActuals) { var v = Resolver.SubstType(entry.Value, cl.ParentFormalTypeParametersToActuals); if (!cl.ParentFormalTypeParametersToActuals.ContainsKey(entry.Key)) { cl.ParentFormalTypeParametersToActuals.Add(entry.Key, v); } } } // Check that every (transitive) parent trait is instantiated with the same type parameters foreach (var group in cl.ParentTypeInformation.GetTypeInstantiationGroups()) { Contract.Assert(1 <= group.Count); var ty = group[0].Item1; for (var i = 1; i < group.Count; i++) { if (!group.GetRange(0, i).Exists(pair => pair.Item1.Equals(group[i].Item1))) { var via0 = group[0].Item2.Count == 0 ? "" : " (via " + Util.Comma(group[0].Item2, traitDecl => traitDecl.Name) + ")"; var via1 = group[i].Item2.Count == 0 ? "" : " (via " + Util.Comma(group[i].Item2, traitDecl => traitDecl.Name) + ")"; reporter.Error(MessageSource.Resolver, cl.tok, "duplicate trait parents with the same head type must also have the same type arguments; got {0}{1} and {2}{3}", ty, via0, group[i].Item1, via1); } } } // Update the name->MemberDecl table for the class. Report an error if the same name refers to more than one member, // except when such duplication is purely that one member, say X, is inherited and the other is an override of X. var inheritedMembers = new Dictionary<string, MemberDecl>(); foreach (var trait in cl.ParentTraitHeads) { foreach (var traitMember in classMembers[trait].Values) { // TODO: rather than using .Values, it would be nice to use something that gave a deterministic order if (!inheritedMembers.TryGetValue(traitMember.Name, out var prevMember)) { // record "traitMember" as an inherited member inheritedMembers.Add(traitMember.Name, traitMember); } else if (traitMember == prevMember) { // same member, inherited two different ways } else if (traitMember.Overrides(prevMember)) { // we're inheriting "prevMember" and "traitMember" from different parent traits, where "traitMember" is an override of "prevMember" Contract.Assert(traitMember.EnclosingClass != cl && prevMember.EnclosingClass != cl && traitMember.EnclosingClass != prevMember.EnclosingClass); // sanity checks // re-map "traitMember.Name" to point to the overriding member inheritedMembers[traitMember.Name] = traitMember; } else if (prevMember.Overrides(traitMember)) { // we're inheriting "prevMember" and "traitMember" from different parent traits, where "prevMember" is an override of "traitMember" Contract.Assert(traitMember.EnclosingClass != cl && prevMember.EnclosingClass != cl && traitMember.EnclosingClass != prevMember.EnclosingClass); // sanity checks // keep the mapping to "prevMember" } else { // "prevMember" and "traitMember" refer to different members (with the same name) reporter.Error(MessageSource.Resolver, cl.tok, "{0} '{1}' inherits a member named '{2}' from both traits '{3}' and '{4}'", cl.WhatKind, cl.Name, traitMember.Name, prevMember.EnclosingClass.Name, traitMember.EnclosingClass.Name); } } } // Incorporate the inherited members into the name->MemberDecl mapping of "cl" var members = classMembers[cl]; foreach (var entry in inheritedMembers) { var name = entry.Key; var traitMember = entry.Value; if (!members.TryGetValue(name, out var clMember)) { members.Add(name, traitMember); } else { Contract.Assert(clMember.EnclosingClass == cl); // sanity check Contract.Assert(clMember.OverriddenMember == null); // sanity check clMember.OverriddenMember = traitMember; } } } /// <summary> /// Assumes type parameters have already been pushed /// </summary> void ResolveClassMemberTypes(TopLevelDeclWithMembers cl) { Contract.Requires(cl != null); Contract.Requires(currentClass == null); Contract.Ensures(currentClass == null); currentClass = cl; foreach (MemberDecl member in cl.Members) { member.EnclosingClass = cl; if (member is Field) { if (member is ConstantField) { var m = (ConstantField)member; ResolveType(member.tok, ((Field)member).Type, m, ResolveTypeOptionEnum.DontInfer, null); } else { // In the following, we pass in a NoContext, because any cycle formed by a redirecting-type constraints would have to // dereference the heap, and such constraints are not allowed to dereference the heap so an error will be produced // even if we don't detect this cycle. ResolveType(member.tok, ((Field)member).Type, new NoContext(cl.EnclosingModuleDefinition), ResolveTypeOptionEnum.DontInfer, null); } } else if (member is Function) { var f = (Function)member; var ec = reporter.Count(ErrorLevel.Error); allTypeParameters.PushMarker(); ResolveTypeParameters(f.TypeArgs, true, f); ResolveFunctionSignature(f); allTypeParameters.PopMarker(); if (f is ExtremePredicate && ec == reporter.Count(ErrorLevel.Error)) { var ff = ((ExtremePredicate)f).PrefixPredicate; // note, may be null if there was an error before the prefix predicate was generated if (ff != null) { ff.EnclosingClass = cl; allTypeParameters.PushMarker(); ResolveTypeParameters(ff.TypeArgs, true, ff); ResolveFunctionSignature(ff); allTypeParameters.PopMarker(); } } } else if (member is Method) { var m = (Method)member; var ec = reporter.Count(ErrorLevel.Error); allTypeParameters.PushMarker(); ResolveTypeParameters(m.TypeArgs, true, m); ResolveMethodSignature(m); allTypeParameters.PopMarker(); var com = m as ExtremeLemma; if (com != null && com.PrefixLemma != null && ec == reporter.Count(ErrorLevel.Error)) { var mm = com.PrefixLemma; // resolve signature of the prefix lemma mm.EnclosingClass = cl; allTypeParameters.PushMarker(); ResolveTypeParameters(mm.TypeArgs, true, mm); ResolveMethodSignature(mm); allTypeParameters.PopMarker(); } } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected member type } } currentClass = null; } /// <summary> /// This method checks the rules for inherited and overridden members. It also populates .InheritedMembers with the /// non-static members that are inherited from parent traits. /// </summary> void InheritedTraitMembers(TopLevelDeclWithMembers cl) { Contract.Requires(cl != null); Contract.Requires(cl.ParentTypeInformation != null); foreach (var member in classMembers[cl].Values) { if (member is PrefixPredicate || member is PrefixLemma) { // these are handled with the corresponding extreme predicate/lemma continue; } if (member.EnclosingClass != cl) { // The member is the one inherited from a trait (and the class does not itself define a member with this name). This // is fine for fields and for functions and methods with bodies. However, if "cl" is not itself a trait, then for a body-less function // or method, "cl" is required to at least redeclare the member with its signature. (It should also provide a stronger specification, // but that will be checked by the verifier. And it should also have a body, but that will be checked by the compiler.) if (member.IsStatic) { // nothing to do } else { cl.InheritedMembers.Add(member); if (member is Field || (member as Function)?.Body != null || (member as Method)?.Body != null) { // member is a field or a fully defined function or method } else if (cl is TraitDecl) { // there are no expectations that a field needs to repeat the signature of inherited body-less members } else { reporter.Error(MessageSource.Resolver, cl.tok, "{0} '{1}' does not implement trait {2} '{3}.{4}'", cl.WhatKind, cl.Name, member.WhatKind, member.EnclosingClass.Name, member.Name); } } continue; } if (member.OverriddenMember == null) { // this member has nothing to do with the parent traits continue; } var traitMember = member.OverriddenMember; var trait = traitMember.EnclosingClass; if (traitMember.IsStatic) { reporter.Error(MessageSource.Resolver, member.tok, "static {0} '{1}' is inherited from trait '{2}' and is not allowed to be re-declared", traitMember.WhatKind, traitMember.Name, trait.Name); } else if (member.IsStatic) { reporter.Error(MessageSource.Resolver, member.tok, "static member '{0}' overrides non-static member in trait '{1}'", member.Name, trait.Name); } else if (traitMember is Field) { // The class is not allowed to do anything with the field other than silently inherit it. reporter.Error(MessageSource.Resolver, member.tok, "{0} '{1}' is inherited from trait '{2}' and is not allowed to be re-declared", traitMember.WhatKind, traitMember.Name, trait.Name); } else if ((traitMember as Function)?.Body != null || (traitMember as Method)?.Body != null) { // the overridden member is a fully defined function or method, so the class is not allowed to do anything with it other than silently inherit it reporter.Error(MessageSource.Resolver, member.tok, "fully defined {0} '{1}' is inherited from trait '{2}' and is not allowed to be re-declared", traitMember.WhatKind, traitMember.Name, trait.Name); } else if (member is Lemma != traitMember is Lemma || member is TwoStateLemma != traitMember is TwoStateLemma || member is LeastLemma != traitMember is LeastLemma || member is GreatestLemma != traitMember is GreatestLemma || member is TwoStateFunction != traitMember is TwoStateFunction || member is LeastPredicate != traitMember is LeastPredicate || member is GreatestPredicate != traitMember is GreatestPredicate) { reporter.Error(MessageSource.Resolver, member.tok, "{0} '{1}' in '{2}' can only be overridden by a {0} (got {3})", traitMember.WhatKind, traitMember.Name, trait.Name, member.WhatKind); } else if (member.IsGhost != traitMember.IsGhost) { reporter.Error(MessageSource.Resolver, member.tok, "overridden {0} '{1}' in '{2}' has different ghost/compiled status than in trait '{3}'", traitMember.WhatKind, traitMember.Name, cl.Name, trait.Name); } else { // Copy trait member's extern attribute onto class member if class does not provide one if (!Attributes.Contains(member.Attributes, "extern") && Attributes.Contains(traitMember.Attributes, "extern")) { var traitExternArgs = Attributes.FindExpressions(traitMember.Attributes, "extern"); member.Attributes = new Attributes("extern", traitExternArgs, member.Attributes); } if (traitMember is Method) { var classMethod = (Method)member; var traitMethod = (Method)traitMember; classMethod.OverriddenMethod = traitMethod; //adding a call graph edge from the trait method to that of class cl.EnclosingModuleDefinition.CallGraph.AddEdge(traitMethod, classMethod); CheckOverride_MethodParameters(classMethod, traitMethod, cl.ParentFormalTypeParametersToActuals); var traitMethodAllowsNonTermination = Contract.Exists(traitMethod.Decreases.Expressions, e => e is WildcardExpr); var classMethodAllowsNonTermination = Contract.Exists(classMethod.Decreases.Expressions, e => e is WildcardExpr); if (classMethodAllowsNonTermination && !traitMethodAllowsNonTermination) { reporter.Error(MessageSource.Resolver, classMethod.tok, "not allowed to override a terminating method with a possibly non-terminating method ('{0}')", classMethod.Name); } } else if (traitMember is Function) { var classFunction = (Function)member; var traitFunction = (Function)traitMember; classFunction.OverriddenFunction = traitFunction; //adding a call graph edge from the trait function to that of class cl.EnclosingModuleDefinition.CallGraph.AddEdge(traitFunction, classFunction); CheckOverride_FunctionParameters(classFunction, traitFunction, cl.ParentFormalTypeParametersToActuals); } else { Contract.Assert(false); // unexpected member } } } } public void CheckOverride_FunctionParameters(Function nw, Function old, Dictionary<TypeParameter, Type> classTypeMap) { Contract.Requires(nw != null); Contract.Requires(old != null); Contract.Requires(classTypeMap != null); var typeMap = CheckOverride_TypeParameters(nw.tok, old.TypeArgs, nw.TypeArgs, nw.Name, "function", classTypeMap); if (nw is ExtremePredicate nwFix && old is ExtremePredicate oldFix && nwFix.KNat != oldFix.KNat) { reporter.Error(MessageSource.Resolver, nw, "the type of special parameter '_k' of {0} '{1}' ({2}) must be the same as in the overridden {0} ({3})", nw.WhatKind, nw.Name, nwFix.KNat ? "nat" : "ORDINAL", oldFix.KNat ? "nat" : "ORDINAL"); } CheckOverride_ResolvedParameters(nw.tok, old.Formals, nw.Formals, nw.Name, "function", "parameter", typeMap); var oldResultType = Resolver.SubstType(old.ResultType, typeMap); if (!nw.ResultType.Equals(oldResultType)) { reporter.Error(MessageSource.Resolver, nw, "the result type of function '{0}' ({1}) differs from that in the overridden function ({2})", nw.Name, nw.ResultType, oldResultType); } } public void CheckOverride_MethodParameters(Method nw, Method old, Dictionary<TypeParameter, Type> classTypeMap) { Contract.Requires(nw != null); Contract.Requires(old != null); Contract.Requires(classTypeMap != null); var typeMap = CheckOverride_TypeParameters(nw.tok, old.TypeArgs, nw.TypeArgs, nw.Name, "method", classTypeMap); if (nw is ExtremeLemma nwFix && old is ExtremeLemma oldFix && nwFix.KNat != oldFix.KNat) { reporter.Error(MessageSource.Resolver, nw, "the type of special parameter '_k' of {0} '{1}' ({2}) must be the same as in the overridden {0} ({3})", nw.WhatKind, nw.Name, nwFix.KNat ? "nat" : "ORDINAL", oldFix.KNat ? "nat" : "ORDINAL"); } CheckOverride_ResolvedParameters(nw.tok, old.Ins, nw.Ins, nw.Name, "method", "in-parameter", typeMap); CheckOverride_ResolvedParameters(nw.tok, old.Outs, nw.Outs, nw.Name, "method", "out-parameter", typeMap); } private Dictionary<TypeParameter, Type> CheckOverride_TypeParameters(IToken tok, List<TypeParameter> old, List<TypeParameter> nw, string name, string thing, Dictionary<TypeParameter, Type> classTypeMap) { Contract.Requires(tok != null); Contract.Requires(old != null); Contract.Requires(nw != null); Contract.Requires(name != null); Contract.Requires(thing != null); var typeMap = old.Count == 0 ? classTypeMap : new Dictionary<TypeParameter, Type>(classTypeMap); if (old.Count != nw.Count) { reporter.Error(MessageSource.Resolver, tok, "{0} '{1}' is declared with a different number of type parameters ({2} instead of {3}) than in the overridden {0}", thing, name, nw.Count, old.Count); } else { for (int i = 0; i < old.Count; i++) { var o = old[i]; var n = nw[i]; typeMap.Add(o, new UserDefinedType(tok, n)); // Check type characteristics if (o.Characteristics.EqualitySupport != TypeParameter.EqualitySupportValue.InferredRequired && o.Characteristics.EqualitySupport != n.Characteristics.EqualitySupport) { reporter.Error(MessageSource.Resolver, n.tok, "type parameter '{0}' is not allowed to change the requirement of supporting equality", n.Name); } if (o.Characteristics.HasCompiledValue != n.Characteristics.HasCompiledValue) { reporter.Error(MessageSource.Resolver, n.tok, "type parameter '{0}' is not allowed to change the requirement of supporting auto-initialization", n.Name); } else if (o.Characteristics.IsNonempty != n.Characteristics.IsNonempty) { reporter.Error(MessageSource.Resolver, n.tok, "type parameter '{0}' is not allowed to change the requirement of being nonempty", n.Name); } if (o.Characteristics.ContainsNoReferenceTypes != n.Characteristics.ContainsNoReferenceTypes) { reporter.Error(MessageSource.Resolver, n.tok, "type parameter '{0}' is not allowed to change the no-reference-type requirement", n.Name); } } } return typeMap; } private void CheckOverride_ResolvedParameters(IToken tok, List<Formal> old, List<Formal> nw, string name, string thing, string parameterKind, Dictionary<TypeParameter, Type> typeMap) { Contract.Requires(tok != null); Contract.Requires(old != null); Contract.Requires(nw != null); Contract.Requires(name != null); Contract.Requires(thing != null); Contract.Requires(parameterKind != null); Contract.Requires(typeMap != null); if (old.Count != nw.Count) { reporter.Error(MessageSource.Resolver, tok, "{0} '{1}' is declared with a different number of {2} ({3} instead of {4}) than in the overridden {0}", thing, name, parameterKind, nw.Count, old.Count); } else { for (int i = 0; i < old.Count; i++) { var o = old[i]; var n = nw[i]; if (!o.IsGhost && n.IsGhost) { reporter.Error(MessageSource.Resolver, n.tok, "{0} '{1}' of {2} {3} cannot be changed, compared to in the overridden {2}, from non-ghost to ghost", parameterKind, n.Name, thing, name); } else if (o.IsGhost && !n.IsGhost) { reporter.Error(MessageSource.Resolver, n.tok, "{0} '{1}' of {2} {3} cannot be changed, compared to in the overridden {2}, from ghost to non-ghost", parameterKind, n.Name, thing, name); } else if (!o.IsOld && n.IsOld) { reporter.Error(MessageSource.Resolver, n.tok, "{0} '{1}' of {2} {3} cannot be changed, compared to in the overridden {2}, from non-new to new", parameterKind, n.Name, thing, name); } else if (o.IsOld && !n.IsOld) { reporter.Error(MessageSource.Resolver, n.tok, "{0} '{1}' of {2} {3} cannot be changed, compared to in the overridden {2}, from new to non-new", parameterKind, n.Name, thing, name); } else { var oo = Resolver.SubstType(o.Type, typeMap); if (!n.Type.Equals(oo)) { reporter.Error(MessageSource.Resolver, n.tok, "the type of {0} '{1}' is different from the type of the corresponding {0} in trait {2} ('{3}' instead of '{4}')", parameterKind, n.Name, thing, n.Type, oo); } } } } } /// <summary> /// Assumes type parameters have already been pushed, and that all types in class members have been resolved /// </summary> void ResolveClassMemberBodies(TopLevelDeclWithMembers cl) { Contract.Requires(cl != null); Contract.Requires(currentClass == null); Contract.Requires(AllTypeConstraints.Count == 0); Contract.Ensures(currentClass == null); Contract.Ensures(AllTypeConstraints.Count == 0); currentClass = cl; foreach (MemberDecl member in cl.Members) { Contract.Assert(VisibleInScope(member)); if (member is ConstantField) { // don't do anything here, because const fields have already been resolved } else if (member is Field) { var opts = new ResolveOpts(new NoContext(currentClass.EnclosingModuleDefinition), false); ResolveAttributes(member.Attributes, member, opts); } else if (member is Function) { var f = (Function)member; var ec = reporter.Count(ErrorLevel.Error); allTypeParameters.PushMarker(); ResolveTypeParameters(f.TypeArgs, false, f); ResolveFunction(f); allTypeParameters.PopMarker(); if (f is ExtremePredicate && ec == reporter.Count(ErrorLevel.Error)) { var ff = ((ExtremePredicate)f).PrefixPredicate; if (ff != null) { allTypeParameters.PushMarker(); ResolveTypeParameters(ff.TypeArgs, false, ff); ResolveFunction(ff); allTypeParameters.PopMarker(); } } } else if (member is Method) { var m = (Method)member; var ec = reporter.Count(ErrorLevel.Error); allTypeParameters.PushMarker(); ResolveTypeParameters(m.TypeArgs, false, m); ResolveMethod(m); allTypeParameters.PopMarker(); } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected member type } Contract.Assert(AllTypeConstraints.Count == 0); } currentClass = null; } /// <summary> /// Checks if "expr" is a constant (that is, heap independent) expression that can be assigned to "field". /// If it is, return "true". Otherwise, report an error and return "false". /// This method also adds dependency edges to the module's call graph and checks for self-loops. If a self-loop /// is detected, "false" is returned. /// </summary> bool CheckIsConstantExpr(ConstantField field, Expression expr) { Contract.Requires(field != null); Contract.Requires(expr != null); if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; if (e.Member is Field && ((Field)e.Member).IsMutable) { reporter.Error(MessageSource.Resolver, field.tok, "only constants are allowed in the expression to initialize constant {0}", field.Name); return false; } if (e.Member is ICallable) { var other = (ICallable)e.Member; field.EnclosingModule.CallGraph.AddEdge(field, other); } // okay so far; now, go on checking subexpressions } return expr.SubExpressions.All(e => CheckIsConstantExpr(field, e)); } /// <summary> /// Assumes type parameters have already been pushed /// </summary> void ResolveCtorTypes(DatatypeDecl/*!*/ dt, Graph<IndDatatypeDecl/*!*/>/*!*/ dependencies, Graph<CoDatatypeDecl/*!*/>/*!*/ coDependencies) { Contract.Requires(dt != null); Contract.Requires(dependencies != null); Contract.Requires(coDependencies != null); foreach (DatatypeCtor ctor in dt.Ctors) { ctor.EnclosingDatatype = dt; allTypeParameters.PushMarker(); ResolveCtorSignature(ctor, dt.TypeArgs); allTypeParameters.PopMarker(); if (dt is IndDatatypeDecl) { // The dependencies of interest among inductive datatypes are all (inductive data)types mentioned in the parameter types var idt = (IndDatatypeDecl)dt; dependencies.AddVertex(idt); foreach (Formal p in ctor.Formals) { AddDatatypeDependencyEdge(idt, p.Type, dependencies); } } else { // The dependencies of interest among codatatypes are just the top-level types of parameters. var codt = (CoDatatypeDecl)dt; coDependencies.AddVertex(codt); foreach (var p in ctor.Formals) { var co = p.Type.AsCoDatatype; if (co != null && codt.EnclosingModuleDefinition == co.EnclosingModuleDefinition) { coDependencies.AddEdge(codt, co); } } } } } void AddDatatypeDependencyEdge(IndDatatypeDecl dt, Type tp, Graph<IndDatatypeDecl> dependencies) { Contract.Requires(dt != null); Contract.Requires(tp != null); Contract.Requires(dependencies != null); // more expensive check: Contract.Requires(cce.NonNullElements(dependencies)); tp = tp.NormalizeExpand(); var dependee = tp.AsIndDatatype; if (dependee != null && dt.EnclosingModuleDefinition == dependee.EnclosingModuleDefinition) { dependencies.AddEdge(dt, dependee); foreach (var ta in ((UserDefinedType)tp).TypeArgs) { AddDatatypeDependencyEdge(dt, ta, dependencies); } } } /// <summary> /// Check that the SCC of 'startingPoint' can be carved up into stratospheres in such a way that each /// datatype has some value that can be constructed from datatypes in lower stratospheres only. /// The algorithm used here is quadratic in the number of datatypes in the SCC. Since that number is /// deemed to be rather small, this seems okay. /// /// As a side effect of this checking, the GroundingCtor field is filled in (for every inductive datatype /// that passes the check). It may be that several constructors could be used as the default, but /// only the first one encountered as recorded. This particular choice is slightly more than an /// implementation detail, because it affects how certain cycles among inductive datatypes (having /// to do with the types used to instantiate type parameters of datatypes) are used. /// /// The role of the SCC here is simply to speed up this method. It would still be correct if the /// equivalence classes in the given SCC were unions of actual SCC's. In particular, this method /// would still work if "dependencies" consisted of one large SCC containing all the inductive /// datatypes in the module. /// </summary> void SccStratosphereCheck(IndDatatypeDecl startingPoint, Graph<IndDatatypeDecl/*!*/>/*!*/ dependencies) { Contract.Requires(startingPoint != null); Contract.Requires(dependencies != null); // more expensive check: Contract.Requires(cce.NonNullElements(dependencies)); var scc = dependencies.GetSCC(startingPoint); int totalCleared = 0; while (true) { int clearedThisRound = 0; foreach (var dt in scc) { if (dt.GroundingCtor != null) { // previously cleared } else if (ComputeGroundingCtor(dt)) { Contract.Assert(dt.GroundingCtor != null); // should have been set by the successful call to StratosphereCheck) clearedThisRound++; totalCleared++; } } if (totalCleared == scc.Count) { // all is good return; } else if (clearedThisRound != 0) { // some progress was made, so let's keep going } else { // whatever is in scc-cleared now failed to pass the test foreach (var dt in scc) { if (dt.GroundingCtor == null) { reporter.Error(MessageSource.Resolver, dt, "because of cyclic dependencies among constructor argument types, no instances of datatype '{0}' can be constructed", dt.Name); } } return; } } } /// <summary> /// Check that the datatype has some constructor all whose argument types can be constructed. /// Returns 'true' and sets dt.GroundingCtor if that is the case. /// </summary> bool ComputeGroundingCtor(IndDatatypeDecl dt) { Contract.Requires(dt != null); Contract.Requires(dt.GroundingCtor == null); // the intention is that this method be called only when GroundingCtor hasn't already been set Contract.Ensures(!Contract.Result<bool>() || dt.GroundingCtor != null); // Stated differently, check that there is some constuctor where no argument type goes to the same stratum. DatatypeCtor groundingCtor = null; List<TypeParameter> lastTypeParametersUsed = null; foreach (DatatypeCtor ctor in dt.Ctors) { List<TypeParameter> typeParametersUsed = new List<TypeParameter>(); foreach (Formal p in ctor.Formals) { if (!CheckCanBeConstructed(p.Type, typeParametersUsed)) { // the argument type (has a component which) is not yet known to be constructable goto NEXT_OUTER_ITERATION; } } // this constructor satisfies the requirements, check to see if it is a better fit than the // one found so far. By "better" it means fewer type arguments. Between the ones with // the same number of the type arguments, pick the one shows first. if (groundingCtor == null || typeParametersUsed.Count < lastTypeParametersUsed.Count) { groundingCtor = ctor; lastTypeParametersUsed = typeParametersUsed; } NEXT_OUTER_ITERATION: { } } if (groundingCtor != null) { dt.GroundingCtor = groundingCtor; dt.TypeParametersUsedInConstructionByGroundingCtor = new bool[dt.TypeArgs.Count]; for (int i = 0; i < dt.TypeArgs.Count; i++) { dt.TypeParametersUsedInConstructionByGroundingCtor[i] = lastTypeParametersUsed.Contains(dt.TypeArgs[i]); } return true; } // no constructor satisfied the requirements, so this is an illegal datatype declaration return false; } bool CheckCanBeConstructed(Type type, List<TypeParameter> typeParametersUsed) { type = type.NormalizeExpandKeepConstraints(); if (type is BasicType) { // values of primitive types can always be constructed return true; } else if (type is CollectionType) { // values of collection types can always be constructed return true; } var udt = (UserDefinedType)type; if (type.IsTypeParameter) { // a value can be constructed, if the type parameter stands for a type that can be constructed Contract.Assert(udt.ResolvedParam != null); typeParametersUsed.Add(udt.ResolvedParam); return true; } var cl = udt.ResolvedClass; Contract.Assert(cl != null); if (cl is InternalTypeSynonymDecl) { // a type exported as opaque from another module is like a ground type return true; } else if (cl is NewtypeDecl) { // values of a newtype can be constructed return true; } else if (cl is SubsetTypeDecl) { var td = (SubsetTypeDecl)cl; if (td.Witness != null) { // a witness exists, but may depend on type parameters type.AddFreeTypeParameters(typeParametersUsed); return true; } else if (td.WitnessKind == SubsetTypeDecl.WKind.Special) { // WKind.Special is only used with -->, ->, and non-null types: Contract.Assert(ArrowType.IsPartialArrowTypeName(td.Name) || ArrowType.IsTotalArrowTypeName(td.Name) || td is NonNullTypeDecl); if (ArrowType.IsTotalArrowTypeName(td.Name)) { return CheckCanBeConstructed(udt.TypeArgs.Last(), typeParametersUsed); } else { return true; } } else { return CheckCanBeConstructed(td.RhsWithArgument(udt.TypeArgs), typeParametersUsed); } } else if (cl is ClassDecl) { // null is a value for this possibly-null type return true; } else if (cl is CoDatatypeDecl) { // may depend on type parameters type.AddFreeTypeParameters(typeParametersUsed); return true; } var dependee = type.AsIndDatatype; Contract.Assert(dependee != null); if (dependee.GroundingCtor == null) { // the type is an inductive datatype that we don't yet know how to construct return false; } // also check the type arguments of the inductive datatype Contract.Assert(udt.TypeArgs.Count == dependee.TypeParametersUsedInConstructionByGroundingCtor.Length); var i = 0; foreach (var ta in udt.TypeArgs) { if (dependee.TypeParametersUsedInConstructionByGroundingCtor[i] && !CheckCanBeConstructed(ta, typeParametersUsed)) { return false; } i++; } return true; } void DetermineEqualitySupport(IndDatatypeDecl startingPoint, Graph<IndDatatypeDecl/*!*/>/*!*/ dependencies) { Contract.Requires(startingPoint != null); Contract.Requires(dependencies != null); // more expensive check: Contract.Requires(cce.NonNullElements(dependencies)); var scc = dependencies.GetSCC(startingPoint); // First, the simple case: If any parameter of any inductive datatype in the SCC is of a codatatype type, then // the whole SCC is incapable of providing the equality operation. Also, if any parameter of any inductive datatype // is a ghost, then the whole SCC is incapable of providing the equality operation. foreach (var dt in scc) { Contract.Assume(dt.EqualitySupport == IndDatatypeDecl.ES.NotYetComputed); foreach (var ctor in dt.Ctors) { foreach (var arg in ctor.Formals) { var anotherIndDt = arg.Type.AsIndDatatype; if (arg.IsGhost || (anotherIndDt != null && anotherIndDt.EqualitySupport == IndDatatypeDecl.ES.Never) || arg.Type.IsCoDatatype || arg.Type.IsArrowType) { // arg.Type is known never to support equality // So, go around the entire SCC and record what we learnt foreach (var ddtt in scc) { ddtt.EqualitySupport = IndDatatypeDecl.ES.Never; } return; // we are done } } } } // Now for the more involved case: we need to determine which type parameters determine equality support for each datatype in the SCC // We start by seeing where each datatype's type parameters are used in a place known to determine equality support. bool thingsChanged = false; foreach (var dt in scc) { if (dt.TypeArgs.Count == 0) { // if the datatype has no type parameters, we certainly won't find any type parameters being used in the arguments types to the constructors continue; } foreach (var ctor in dt.Ctors) { foreach (var arg in ctor.Formals) { var typeArg = arg.Type.AsTypeParameter; if (typeArg != null) { typeArg.NecessaryForEqualitySupportOfSurroundingInductiveDatatype = true; thingsChanged = true; } else { var otherDt = arg.Type.AsIndDatatype; if (otherDt != null && otherDt.EqualitySupport == IndDatatypeDecl.ES.ConsultTypeArguments) { // datatype is in a different SCC var otherUdt = (UserDefinedType)arg.Type.NormalizeExpand(); var i = 0; foreach (var otherTp in otherDt.TypeArgs) { if (otherTp.NecessaryForEqualitySupportOfSurroundingInductiveDatatype) { var tp = otherUdt.TypeArgs[i].AsTypeParameter; if (tp != null) { tp.NecessaryForEqualitySupportOfSurroundingInductiveDatatype = true; thingsChanged = true; } } } } } } } } // Then we propagate this information up through the SCC while (thingsChanged) { thingsChanged = false; foreach (var dt in scc) { if (dt.TypeArgs.Count == 0) { // if the datatype has no type parameters, we certainly won't find any type parameters being used in the arguments types to the constructors continue; } foreach (var ctor in dt.Ctors) { foreach (var arg in ctor.Formals) { var otherDt = arg.Type.AsIndDatatype; if (otherDt != null && otherDt.EqualitySupport == IndDatatypeDecl.ES.NotYetComputed) { // otherDt lives in the same SCC var otherUdt = (UserDefinedType)arg.Type.NormalizeExpand(); var i = 0; foreach (var otherTp in otherDt.TypeArgs) { if (otherTp.NecessaryForEqualitySupportOfSurroundingInductiveDatatype) { var tp = otherUdt.TypeArgs[i].AsTypeParameter; if (tp != null && !tp.NecessaryForEqualitySupportOfSurroundingInductiveDatatype) { tp.NecessaryForEqualitySupportOfSurroundingInductiveDatatype = true; thingsChanged = true; } } i++; } } } } } } // Now that we have computed the .NecessaryForEqualitySupportOfSurroundingInductiveDatatype values, mark the datatypes as ones // where equality support should be checked by looking at the type arguments. foreach (var dt in scc) { dt.EqualitySupport = IndDatatypeDecl.ES.ConsultTypeArguments; } } void ResolveAttributes(Attributes attrs, IAttributeBearingDeclaration attributeHost, ResolveOpts opts) { Contract.Requires(opts != null); // order does not matter much for resolution, so resolve them in reverse order foreach (var attr in attrs.AsEnumerable()) { if (attributeHost != null && attr is UserSuppliedAttributes) { var usa = (UserSuppliedAttributes)attr; usa.Recognized = IsRecognizedAttribute(usa, attributeHost); } if (attr.Args != null) { foreach (var arg in attr.Args) { Contract.Assert(arg != null); int prevErrors = reporter.Count(ErrorLevel.Error); ResolveExpression(arg, opts); if (prevErrors == reporter.Count(ErrorLevel.Error)) { CheckTypeInference(arg, opts.codeContext); } } } } } /// <summary> /// Check to see if the attribute is one that is supported by Dafny. What check performed here is, /// unfortunately, just an approximation, since the usage rules of a particular attribute is checked /// elsewhere (for example, in the compiler or verifier). It would be nice to improve this. /// </summary> bool IsRecognizedAttribute(UserSuppliedAttributes a, IAttributeBearingDeclaration host) { Contract.Requires(a != null); Contract.Requires(host != null); switch (a.Name) { case "opaque": return host is Function && !(host is ExtremePredicate); case "trigger": return host is ComprehensionExpr || host is SetComprehension || host is MapComprehension; case "timeLimit": case "timeLimitMultiplier": return host is TopLevelDecl; case "tailrecursive": return host is Method && !((Method)host).IsGhost; case "autocontracts": return host is ClassDecl; case "autoreq": return host is Function; case "abstemious": return host is Function; default: return false; } } void ResolveTypeParameters(List<TypeParameter/*!*/>/*!*/ tparams, bool emitErrors, TypeParameter.ParentType/*!*/ parent) { Contract.Requires(tparams != null); Contract.Requires(parent != null); // push non-duplicated type parameter names int index = 0; foreach (TypeParameter tp in tparams) { if (emitErrors) { // we're seeing this TypeParameter for the first time tp.Parent = parent; tp.PositionalIndex = index; } var r = allTypeParameters.Push(tp.Name, tp); if (emitErrors) { if (r == Scope<TypeParameter>.PushResult.Duplicate) { reporter.Error(MessageSource.Resolver, tp, "Duplicate type-parameter name: {0}", tp.Name); } else if (r == Scope<TypeParameter>.PushResult.Shadow) { reporter.Warning(MessageSource.Resolver, tp.tok, "Shadowed type-parameter name: {0}", tp.Name); } } } } void ScopePushAndReport(Scope<IVariable> scope, IVariable v, string kind) { Contract.Requires(scope != null); Contract.Requires(v != null); Contract.Requires(kind != null); ScopePushAndReport(scope, v.Name, v, v.Tok, kind); } void ScopePushAndReport<Thing>(Scope<Thing> scope, string name, Thing thing, IToken tok, string kind) where Thing : class { Contract.Requires(scope != null); Contract.Requires(name != null); Contract.Requires(thing != null); Contract.Requires(tok != null); Contract.Requires(kind != null); var r = scope.Push(name, thing); switch (r) { case Scope<Thing>.PushResult.Success: break; case Scope<Thing>.PushResult.Duplicate: reporter.Error(MessageSource.Resolver, tok, "Duplicate {0} name: {1}", kind, name); break; case Scope<Thing>.PushResult.Shadow: reporter.Warning(MessageSource.Resolver, tok, "Shadowed {0} name: {1}", kind, name); break; } } /// <summary> /// Assumes type parameters have already been pushed /// </summary> void ResolveFunctionSignature(Function f) { Contract.Requires(f != null); scope.PushMarker(); if (f.SignatureIsOmitted) { reporter.Error(MessageSource.Resolver, f, "function signature can be omitted only in refining functions"); } var option = f.TypeArgs.Count == 0 ? new ResolveTypeOption(f) : new ResolveTypeOption(ResolveTypeOptionEnum.AllowPrefix); foreach (Formal p in f.Formals) { ScopePushAndReport(scope, p, "parameter"); ResolveType(p.tok, p.Type, f, option, f.TypeArgs); AddTypeDependencyEdges(f, p.Type); } if (f.Result != null) { ScopePushAndReport(scope, f.Result, "parameter/return"); ResolveType(f.Result.tok, f.Result.Type, f, option, f.TypeArgs); } else { ResolveType(f.tok, f.ResultType, f, option, f.TypeArgs); } AddTypeDependencyEdges(f, f.ResultType); scope.PopMarker(); } /// <summary> /// Assumes type parameters have already been pushed /// </summary> void ResolveFunction(Function f) { Contract.Requires(f != null); Contract.Requires(AllTypeConstraints.Count == 0); Contract.Ensures(AllTypeConstraints.Count == 0); bool warnShadowingOption = DafnyOptions.O.WarnShadowing; // save the original warnShadowing value bool warnShadowing = false; scope.PushMarker(); if (f.IsStatic) { scope.AllowInstance = false; } if (f.IsGhost) { foreach (TypeParameter p in f.TypeArgs) { if (p.SupportsEquality) { reporter.Warning(MessageSource.Resolver, p.tok, $"type parameter {p.Name} of ghost {f.WhatKind} {f.Name} is declared (==), which is unnecessary because the {f.WhatKind} doesn’t contain any compiled code"); } } } foreach (Formal p in f.Formals) { scope.Push(p.Name, p); } ResolveAttributes(f.Attributes, f, new ResolveOpts(f, false)); // take care of the warnShadowing attribute if (Attributes.ContainsBool(f.Attributes, "warnShadowing", ref warnShadowing)) { DafnyOptions.O.WarnShadowing = warnShadowing; // set the value according to the attribute } foreach (AttributedExpression e in f.Req) { Expression r = e.E; ResolveExpression(r, new ResolveOpts(f, f is TwoStateFunction)); Contract.Assert(r.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(r, "Precondition must be a boolean (got {0})"); } foreach (FrameExpression fr in f.Reads) { ResolveFrameExpression(fr, FrameExpressionUse.Reads, f); } foreach (AttributedExpression e in f.Ens) { Expression r = e.E; if (f.Result != null) { scope.PushMarker(); scope.Push(f.Result.Name, f.Result); // function return only visible in post-conditions } ResolveExpression(r, new ResolveOpts(f, f is TwoStateFunction, false, true, false)); // since this is a function, the postcondition is still a one-state predicate, unless it's a two-state function Contract.Assert(r.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(r, "Postcondition must be a boolean (got {0})"); if (f.Result != null) { scope.PopMarker(); } } ResolveAttributes(f.Decreases.Attributes, null, new ResolveOpts(f, f is TwoStateFunction)); foreach (Expression r in f.Decreases.Expressions) { ResolveExpression(r, new ResolveOpts(f, f is TwoStateFunction)); // any type is fine } SolveAllTypeConstraints(); if (f.Body != null) { var prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveExpression(f.Body, new ResolveOpts(f, f is TwoStateFunction)); Contract.Assert(f.Body.Type != null); // follows from postcondition of ResolveExpression AddAssignableConstraint(f.tok, f.ResultType, f.Body.Type, "Function body type mismatch (expected {0}, got {1})"); SolveAllTypeConstraints(); } scope.PopMarker(); DafnyOptions.O.WarnShadowing = warnShadowingOption; // restore the original warnShadowing value } public enum FrameExpressionUse { Reads, Modifies, Unchanged } void ResolveFrameExpression(FrameExpression fe, FrameExpressionUse use, ICodeContext codeContext) { Contract.Requires(fe != null); Contract.Requires(codeContext != null); ResolveExpression(fe.E, new ResolveOpts(codeContext, codeContext is TwoStateLemma || use == FrameExpressionUse.Unchanged)); Type t = fe.E.Type; Contract.Assert(t != null); // follows from postcondition of ResolveExpression var eventualRefType = new InferredTypeProxy(); if (use == FrameExpressionUse.Reads) { AddXConstraint(fe.E.tok, "ReadsFrame", t, eventualRefType, "a reads-clause expression must denote an object or a collection of objects (instead got {0})"); } else { AddXConstraint(fe.E.tok, "ModifiesFrame", t, eventualRefType, use == FrameExpressionUse.Modifies ? "a modifies-clause expression must denote an object or a collection of objects (instead got {0})" : "an unchanged expression must denote an object or a collection of objects (instead got {0})"); } if (fe.FieldName != null) { NonProxyType tentativeReceiverType; var member = ResolveMember(fe.E.tok, eventualRefType, fe.FieldName, out tentativeReceiverType); var ctype = (UserDefinedType)tentativeReceiverType; // correctness of cast follows from the DenotesClass test above if (member == null) { // error has already been reported by ResolveMember } else if (!(member is Field)) { reporter.Error(MessageSource.Resolver, fe.E, "member {0} in type {1} does not refer to a field", fe.FieldName, ctype.Name); } else if (member is ConstantField) { reporter.Error(MessageSource.Resolver, fe.E, "expression is not allowed to refer to constant field {0}", fe.FieldName); } else { Contract.Assert(ctype != null && ctype.ResolvedClass != null); // follows from postcondition of ResolveMember fe.Field = (Field)member; } } } /// <summary> /// This method can be called even if the resolution of "fe" failed; in that case, this method will /// not issue any error message. /// </summary> void DisallowNonGhostFieldSpecifiers(FrameExpression fe) { Contract.Requires(fe != null); if (fe.Field != null && !fe.Field.IsGhost) { reporter.Error(MessageSource.Resolver, fe.E, "in a ghost context, only ghost fields can be mentioned as modifies frame targets ({0})", fe.FieldName); } } /// <summary> /// Assumes type parameters have already been pushed /// </summary> void ResolveMethodSignature(Method m) { Contract.Requires(m != null); scope.PushMarker(); if (m.SignatureIsOmitted) { reporter.Error(MessageSource.Resolver, m, "method signature can be omitted only in refining methods"); } var option = m.TypeArgs.Count == 0 ? new ResolveTypeOption(m) : new ResolveTypeOption(ResolveTypeOptionEnum.AllowPrefix); // resolve in-parameters foreach (Formal p in m.Ins) { ScopePushAndReport(scope, p, "parameter"); ResolveType(p.tok, p.Type, m, option, m.TypeArgs); AddTypeDependencyEdges(m, p.Type); } // resolve out-parameters foreach (Formal p in m.Outs) { ScopePushAndReport(scope, p, "parameter"); ResolveType(p.tok, p.Type, m, option, m.TypeArgs); AddTypeDependencyEdges(m, p.Type); } scope.PopMarker(); } /// <summary> /// Assumes type parameters have already been pushed /// </summary> void ResolveMethod(Method m) { Contract.Requires(m != null); Contract.Requires(AllTypeConstraints.Count == 0); Contract.Ensures(AllTypeConstraints.Count == 0); try { currentMethod = m; bool warnShadowingOption = DafnyOptions.O.WarnShadowing; // save the original warnShadowing value bool warnShadowing = false; // take care of the warnShadowing attribute if (Attributes.ContainsBool(m.Attributes, "warnShadowing", ref warnShadowing)) { DafnyOptions.O.WarnShadowing = warnShadowing; // set the value according to the attribute } if (m.IsGhost) { foreach (TypeParameter p in m.TypeArgs) { if (p.SupportsEquality) { reporter.Warning(MessageSource.Resolver, p.tok, $"type parameter {p.Name} of ghost {m.WhatKind} {m.Name} is declared (==), which is unnecessary because the {m.WhatKind} doesn’t contain any compiled code"); } } } // Add in-parameters to the scope, but don't care about any duplication errors, since they have already been reported scope.PushMarker(); if (m.IsStatic || m is Constructor) { scope.AllowInstance = false; } foreach (Formal p in m.Ins) { scope.Push(p.Name, p); } // Start resolving specification... foreach (AttributedExpression e in m.Req) { ResolveAttributes(e.Attributes, null, new ResolveOpts(m, m is TwoStateLemma)); ResolveExpression(e.E, new ResolveOpts(m, m is TwoStateLemma)); Contract.Assert(e.E.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.E, "Precondition must be a boolean (got {0})"); } ResolveAttributes(m.Mod.Attributes, null, new ResolveOpts(m, false)); foreach (FrameExpression fe in m.Mod.Expressions) { ResolveFrameExpression(fe, FrameExpressionUse.Modifies, m); if (m is Lemma || m is TwoStateLemma || m is ExtremeLemma) { reporter.Error(MessageSource.Resolver, fe.tok, "{0}s are not allowed to have modifies clauses", m.WhatKind); } else if (m.IsGhost) { DisallowNonGhostFieldSpecifiers(fe); } } ResolveAttributes(m.Decreases.Attributes, null, new ResolveOpts(m, false)); foreach (Expression e in m.Decreases.Expressions) { ResolveExpression(e, new ResolveOpts(m, m is TwoStateLemma)); // any type is fine } if (m is Constructor) { scope.PopMarker(); // start the scope again, but this time allowing instance scope.PushMarker(); foreach (Formal p in m.Ins) { scope.Push(p.Name, p); } } // Add out-parameters to a new scope that will also include the outermost-level locals of the body // Don't care about any duplication errors among the out-parameters, since they have already been reported scope.PushMarker(); if (m is ExtremeLemma && m.Outs.Count != 0) { reporter.Error(MessageSource.Resolver, m.Outs[0].tok, "{0}s are not allowed to have out-parameters", m.WhatKind); } else { foreach (Formal p in m.Outs) { scope.Push(p.Name, p); } } // ... continue resolving specification foreach (AttributedExpression e in m.Ens) { ResolveAttributes(e.Attributes, null, new ResolveOpts(m, true)); ResolveExpression(e.E, new ResolveOpts(m, true)); Contract.Assert(e.E.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.E, "Postcondition must be a boolean (got {0})"); } SolveAllTypeConstraints(); // Resolve body if (m.Body != null) { var com = m as ExtremeLemma; if (com != null && com.PrefixLemma != null) { // The body may mentioned the implicitly declared parameter _k. Throw it into the // scope before resolving the body. var k = com.PrefixLemma.Ins[0]; scope.Push(k.Name, k); // we expect no name conflict for _k } dominatingStatementLabels.PushMarker(); foreach (var req in m.Req) { if (req.Label != null) { if (dominatingStatementLabels.Find(req.Label.Name) != null) { reporter.Error(MessageSource.Resolver, req.Label.Tok, "assert label shadows a dominating label"); } else { var rr = dominatingStatementLabels.Push(req.Label.Name, req.Label); Contract.Assert(rr == Scope<Label>.PushResult.Success); // since we just checked for duplicates, we expect the Push to succeed } } } ResolveBlockStatement(m.Body, m); dominatingStatementLabels.PopMarker(); SolveAllTypeConstraints(); } // attributes are allowed to mention both in- and out-parameters (including the implicit _k, for greatest lemmas) ResolveAttributes(m.Attributes, m, new ResolveOpts(m, false)); DafnyOptions.O.WarnShadowing = warnShadowingOption; // restore the original warnShadowing value scope.PopMarker(); // for the out-parameters and outermost-level locals scope.PopMarker(); // for the in-parameters } finally { currentMethod = null; } } void ResolveCtorSignature(DatatypeCtor ctor, List<TypeParameter> dtTypeArguments) { Contract.Requires(ctor != null); Contract.Requires(ctor.EnclosingDatatype != null); Contract.Requires(dtTypeArguments != null); foreach (Formal p in ctor.Formals) { ResolveType(p.tok, p.Type, ctor.EnclosingDatatype, ResolveTypeOptionEnum.AllowPrefix, dtTypeArguments); } } /// <summary> /// Assumes type parameters have already been pushed /// </summary> void ResolveIteratorSignature(IteratorDecl iter) { Contract.Requires(iter != null); scope.PushMarker(); if (iter.SignatureIsOmitted) { reporter.Error(MessageSource.Resolver, iter, "iterator signature can be omitted only in refining methods"); } var initiallyNoTypeArguments = iter.TypeArgs.Count == 0; var option = initiallyNoTypeArguments ? new ResolveTypeOption(iter) : new ResolveTypeOption(ResolveTypeOptionEnum.AllowPrefix); // resolve the types of the parameters var prevErrorCount = reporter.Count(ErrorLevel.Error); foreach (var p in iter.Ins) { ResolveType(p.tok, p.Type, iter, option, iter.TypeArgs); } foreach (var p in iter.Outs) { ResolveType(p.tok, p.Type, iter, option, iter.TypeArgs); if (!p.Type.KnownToHaveToAValue(p.IsGhost)) { reporter.Error(MessageSource.Resolver, p.tok, "type of yield-parameter must support auto-initialization (got '{0}')", p.Type); } } // resolve the types of the added fields (in case some of these types would cause the addition of default type arguments) if (prevErrorCount == reporter.Count(ErrorLevel.Error)) { foreach (var p in iter.OutsHistoryFields) { ResolveType(p.tok, p.Type, iter, option, iter.TypeArgs); } } if (iter.TypeArgs.Count != iter.NonNullTypeDecl.TypeArgs.Count) { // Apparently, the type resolution automatically added type arguments to the iterator. We'll add these to the // corresponding non-null type as well. Contract.Assert(initiallyNoTypeArguments); Contract.Assert(iter.NonNullTypeDecl.TypeArgs.Count == 0); var nnt = iter.NonNullTypeDecl; nnt.TypeArgs.AddRange(iter.TypeArgs.ConvertAll(tp => new TypeParameter(tp.tok, tp.Name, tp.VarianceSyntax, tp.Characteristics))); var varUdt = (UserDefinedType)nnt.Var.Type; Contract.Assert(varUdt.TypeArgs.Count == 0); varUdt.TypeArgs = nnt.TypeArgs.ConvertAll(tp => (Type)new UserDefinedType(tp)); } scope.PopMarker(); } /// <summary> /// Assumes type parameters have already been pushed /// </summary> void ResolveIterator(IteratorDecl iter) { Contract.Requires(iter != null); Contract.Requires(currentClass == null); Contract.Ensures(currentClass == null); var initialErrorCount = reporter.Count(ErrorLevel.Error); // Add in-parameters to the scope, but don't care about any duplication errors, since they have already been reported scope.PushMarker(); scope.AllowInstance = false; // disallow 'this' from use, which means that the special fields and methods added are not accessible in the syntactically given spec iter.Ins.ForEach(p => scope.Push(p.Name, p)); // Start resolving specification... // we start with the decreases clause, because the _decreases<n> fields were only given type proxies before; we'll know // the types only after resolving the decreases clause (and it may be that some of resolution has already seen uses of // these fields; so, with no further ado, here we go Contract.Assert(iter.Decreases.Expressions.Count == iter.DecreasesFields.Count); for (int i = 0; i < iter.Decreases.Expressions.Count; i++) { var e = iter.Decreases.Expressions[i]; ResolveExpression(e, new ResolveOpts(iter, false)); // any type is fine, but associate this type with the corresponding _decreases<n> field var d = iter.DecreasesFields[i]; // If the following type constraint does not hold, then: Bummer, there was a use--and a bad use--of the field before, so this won't be the best of error messages ConstrainSubtypeRelation(d.Type, e.Type, e, "type of field {0} is {1}, but has been constrained elsewhere to be of type {2}", d.Name, e.Type, d.Type); } foreach (FrameExpression fe in iter.Reads.Expressions) { ResolveFrameExpression(fe, FrameExpressionUse.Reads, iter); } foreach (FrameExpression fe in iter.Modifies.Expressions) { ResolveFrameExpression(fe, FrameExpressionUse.Modifies, iter); } foreach (AttributedExpression e in iter.Requires) { ResolveExpression(e.E, new ResolveOpts(iter, false)); Contract.Assert(e.E.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.E, "Precondition must be a boolean (got {0})"); } scope.PopMarker(); // for the in-parameters // We resolve the rest of the specification in an instance context. So mentions of the in- or yield-parameters // get resolved as field dereferences (with an implicit "this") scope.PushMarker(); currentClass = iter; Contract.Assert(scope.AllowInstance); foreach (AttributedExpression e in iter.YieldRequires) { ResolveExpression(e.E, new ResolveOpts(iter, false)); Contract.Assert(e.E.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.E, "Yield precondition must be a boolean (got {0})"); } foreach (AttributedExpression e in iter.YieldEnsures) { ResolveExpression(e.E, new ResolveOpts(iter, true)); Contract.Assert(e.E.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.E, "Yield postcondition must be a boolean (got {0})"); } foreach (AttributedExpression e in iter.Ensures) { ResolveExpression(e.E, new ResolveOpts(iter, true)); Contract.Assert(e.E.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.E, "Postcondition must be a boolean (got {0})"); } SolveAllTypeConstraints(); ResolveAttributes(iter.Attributes, iter, new ResolveOpts(iter, false)); var postSpecErrorCount = reporter.Count(ErrorLevel.Error); // Resolve body if (iter.Body != null) { dominatingStatementLabels.PushMarker(); foreach (var req in iter.Requires) { if (req.Label != null) { if (dominatingStatementLabels.Find(req.Label.Name) != null) { reporter.Error(MessageSource.Resolver, req.Label.Tok, "assert label shadows a dominating label"); } else { var rr = dominatingStatementLabels.Push(req.Label.Name, req.Label); Contract.Assert(rr == Scope<Label>.PushResult.Success); // since we just checked for duplicates, we expect the Push to succeed } } } ResolveBlockStatement(iter.Body, iter); dominatingStatementLabels.PopMarker(); SolveAllTypeConstraints(); } currentClass = null; scope.PopMarker(); // pop off the AllowInstance setting if (postSpecErrorCount == initialErrorCount) { CreateIteratorMethodSpecs(iter); } } /// <summary> /// Assumes the specification of the iterator itself has been successfully resolved. /// </summary> void CreateIteratorMethodSpecs(IteratorDecl iter) { Contract.Requires(iter != null); // ---------- here comes the constructor ---------- // same requires clause as the iterator itself iter.Member_Init.Req.AddRange(iter.Requires); var ens = iter.Member_Init.Ens; foreach (var p in iter.Ins) { // ensures this.x == x; ens.Add(new AttributedExpression(new BinaryExpr(p.tok, BinaryExpr.Opcode.Eq, new MemberSelectExpr(p.tok, new ThisExpr(p.tok), p.Name), new IdentifierExpr(p.tok, p.Name)))); } foreach (var p in iter.OutsHistoryFields) { // ensures this.ys == []; ens.Add(new AttributedExpression(new BinaryExpr(p.tok, BinaryExpr.Opcode.Eq, new MemberSelectExpr(p.tok, new ThisExpr(p.tok), p.Name), new SeqDisplayExpr(p.tok, new List<Expression>())))); } // ensures this.Valid(); var valid_call = new FunctionCallExpr(iter.tok, "Valid", new ThisExpr(iter.tok), iter.tok, new List<Expression>()); ens.Add(new AttributedExpression(valid_call)); // ensures this._reads == old(ReadsClause); var modSetSingletons = new List<Expression>(); Expression frameSet = new SetDisplayExpr(iter.tok, true, modSetSingletons); foreach (var fr in iter.Reads.Expressions) { if (fr.FieldName != null) { reporter.Error(MessageSource.Resolver, fr.tok, "sorry, a reads clause for an iterator is not allowed to designate specific fields"); } else if (fr.E.Type.IsRefType) { modSetSingletons.Add(fr.E); } else { frameSet = new BinaryExpr(fr.tok, BinaryExpr.Opcode.Add, frameSet, fr.E); } } ens.Add(new AttributedExpression(new BinaryExpr(iter.tok, BinaryExpr.Opcode.Eq, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_reads"), new OldExpr(iter.tok, frameSet)))); // ensures this._modifies == old(ModifiesClause); modSetSingletons = new List<Expression>(); frameSet = new SetDisplayExpr(iter.tok, true, modSetSingletons); foreach (var fr in iter.Modifies.Expressions) { if (fr.FieldName != null) { reporter.Error(MessageSource.Resolver, fr.tok, "sorry, a modifies clause for an iterator is not allowed to designate specific fields"); } else if (fr.E.Type.IsRefType) { modSetSingletons.Add(fr.E); } else { frameSet = new BinaryExpr(fr.tok, BinaryExpr.Opcode.Add, frameSet, fr.E); } } ens.Add(new AttributedExpression(new BinaryExpr(iter.tok, BinaryExpr.Opcode.Eq, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_modifies"), new OldExpr(iter.tok, frameSet)))); // ensures this._new == {}; ens.Add(new AttributedExpression(new BinaryExpr(iter.tok, BinaryExpr.Opcode.Eq, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_new"), new SetDisplayExpr(iter.tok, true, new List<Expression>())))); // ensures this._decreases0 == old(DecreasesClause[0]) && ...; Contract.Assert(iter.Decreases.Expressions.Count == iter.DecreasesFields.Count); for (int i = 0; i < iter.Decreases.Expressions.Count; i++) { var p = iter.Decreases.Expressions[i]; ens.Add(new AttributedExpression(new BinaryExpr(iter.tok, BinaryExpr.Opcode.Eq, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), iter.DecreasesFields[i].Name), new OldExpr(iter.tok, p)))); } // ---------- here comes predicate Valid() ---------- var reads = iter.Member_Valid.Reads; reads.Add(new FrameExpression(iter.tok, new ThisExpr(iter.tok), null)); // reads this; reads.Add(new FrameExpression(iter.tok, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_reads"), null)); // reads this._reads; reads.Add(new FrameExpression(iter.tok, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_new"), null)); // reads this._new; // ---------- here comes method MoveNext() ---------- // requires this.Valid(); var req = iter.Member_MoveNext.Req; valid_call = new FunctionCallExpr(iter.tok, "Valid", new ThisExpr(iter.tok), iter.tok, new List<Expression>()); req.Add(new AttributedExpression(valid_call)); // requires YieldRequires; req.AddRange(iter.YieldRequires); // modifies this, this._modifies, this._new; var mod = iter.Member_MoveNext.Mod.Expressions; mod.Add(new FrameExpression(iter.tok, new ThisExpr(iter.tok), null)); mod.Add(new FrameExpression(iter.tok, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_modifies"), null)); mod.Add(new FrameExpression(iter.tok, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_new"), null)); // ensures fresh(_new - old(_new)); ens = iter.Member_MoveNext.Ens; ens.Add(new AttributedExpression(new UnaryOpExpr(iter.tok, UnaryOpExpr.Opcode.Fresh, new BinaryExpr(iter.tok, BinaryExpr.Opcode.Sub, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_new"), new OldExpr(iter.tok, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_new")))))); // ensures null !in _new ens.Add(new AttributedExpression(new BinaryExpr(iter.tok, BinaryExpr.Opcode.NotIn, new LiteralExpr(iter.tok), new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), "_new")))); // ensures more ==> this.Valid(); valid_call = new FunctionCallExpr(iter.tok, "Valid", new ThisExpr(iter.tok), iter.tok, new List<Expression>()); ens.Add(new AttributedExpression(new BinaryExpr(iter.tok, BinaryExpr.Opcode.Imp, new IdentifierExpr(iter.tok, "more"), valid_call))); // ensures this.ys == if more then old(this.ys) + [this.y] else old(this.ys); Contract.Assert(iter.OutsFields.Count == iter.OutsHistoryFields.Count); for (int i = 0; i < iter.OutsFields.Count; i++) { var y = iter.OutsFields[i]; var ys = iter.OutsHistoryFields[i]; var ite = new ITEExpr(iter.tok, false, new IdentifierExpr(iter.tok, "more"), new BinaryExpr(iter.tok, BinaryExpr.Opcode.Add, new OldExpr(iter.tok, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), ys.Name)), new SeqDisplayExpr(iter.tok, new List<Expression>() { new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), y.Name) })), new OldExpr(iter.tok, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), ys.Name))); var eq = new BinaryExpr(iter.tok, BinaryExpr.Opcode.Eq, new MemberSelectExpr(iter.tok, new ThisExpr(iter.tok), ys.Name), ite); ens.Add(new AttributedExpression(eq)); } // ensures more ==> YieldEnsures; foreach (var ye in iter.YieldEnsures) { ens.Add(new AttributedExpression( new BinaryExpr(iter.tok, BinaryExpr.Opcode.Imp, new IdentifierExpr(iter.tok, "more"), ye.E) )); } // ensures !more ==> Ensures; foreach (var e in iter.Ensures) { ens.Add(new AttributedExpression(new BinaryExpr(iter.tok, BinaryExpr.Opcode.Imp, new UnaryOpExpr(iter.tok, UnaryOpExpr.Opcode.Not, new IdentifierExpr(iter.tok, "more")), e.E) )); } // decreases this._decreases0, this._decreases1, ...; Contract.Assert(iter.Decreases.Expressions.Count == iter.DecreasesFields.Count); for (int i = 0; i < iter.Decreases.Expressions.Count; i++) { var p = iter.Decreases.Expressions[i]; iter.Member_MoveNext.Decreases.Expressions.Add(new MemberSelectExpr(p.tok, new ThisExpr(p.tok), iter.DecreasesFields[i].Name)); } iter.Member_MoveNext.Decreases.Attributes = iter.Decreases.Attributes; } // Like the ResolveTypeOptionEnum, but iff the case of AllowPrefixExtend, it also // contains a pointer to its Parent class, to fill in default type parameters properly. public class ResolveTypeOption { public readonly ResolveTypeOptionEnum Opt; public readonly TypeParameter.ParentType Parent; [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant((Opt == ResolveTypeOptionEnum.AllowPrefixExtend) == (Parent != null)); } public ResolveTypeOption(ResolveTypeOptionEnum opt) { Contract.Requires(opt != ResolveTypeOptionEnum.AllowPrefixExtend); Parent = null; Opt = opt; } public ResolveTypeOption(TypeParameter.ParentType parent) { Contract.Requires(parent != null); Opt = ResolveTypeOptionEnum.AllowPrefixExtend; Parent = parent; } } /// <summary> /// If ResolveType/ResolveTypeLenient encounters a (datatype or class) type "C" with no supplied arguments, then /// the ResolveTypeOption says what to do. The last three options take a List as a parameter, which (would have /// been supplied as an argument if C# had datatypes instead of just enums, but since C# doesn't) is supplied /// as another parameter (called 'defaultTypeArguments') to ResolveType/ResolveTypeLenient. /// </summary> public enum ResolveTypeOptionEnum { /// <summary> /// never infer type arguments /// </summary> DontInfer, /// <summary> /// create a new InferredTypeProxy type for each needed argument /// </summary> InferTypeProxies, /// <summary> /// if at most defaultTypeArguments.Count type arguments are needed, use a prefix of defaultTypeArguments /// </summary> AllowPrefix, /// <summary> /// same as AllowPrefix, but if more than defaultTypeArguments.Count type arguments are needed, first /// extend defaultTypeArguments to a sufficient length /// </summary> AllowPrefixExtend, } /// <summary> /// See ResolveTypeOption for a description of the option/defaultTypeArguments parameters. /// </summary> public void ResolveType(IToken tok, Type type, ICodeContext context, ResolveTypeOptionEnum eopt, List<TypeParameter> defaultTypeArguments) { Contract.Requires(tok != null); Contract.Requires(type != null); Contract.Requires(context != null); Contract.Requires(eopt != ResolveTypeOptionEnum.AllowPrefixExtend); ResolveType(tok, type, context, new ResolveTypeOption(eopt), defaultTypeArguments); } public void ResolveType(IToken tok, Type type, ICodeContext context, ResolveTypeOption option, List<TypeParameter> defaultTypeArguments) { Contract.Requires(tok != null); Contract.Requires(type != null); Contract.Requires(context != null); Contract.Requires(option != null); Contract.Requires((option.Opt == ResolveTypeOptionEnum.DontInfer || option.Opt == ResolveTypeOptionEnum.InferTypeProxies) == (defaultTypeArguments == null)); var r = ResolveTypeLenient(tok, type, context, option, defaultTypeArguments, false); Contract.Assert(r == null); } public class ResolveTypeReturn { public readonly Type ReplacementType; public readonly ExprDotName LastComponent; public ResolveTypeReturn(Type replacementType, ExprDotName lastComponent) { Contract.Requires(replacementType != null); Contract.Requires(lastComponent != null); ReplacementType = replacementType; LastComponent = lastComponent; } } /// <summary> /// See ResolveTypeOption for a description of the option/defaultTypeArguments parameters. /// One more thing: if "allowDanglingDotName" is true, then if the resolution would have produced /// an error message that could have been avoided if "type" denoted an identifier sequence one /// shorter, then return an unresolved replacement type where the identifier sequence is one /// shorter. (In all other cases, the method returns null.) /// </summary> public ResolveTypeReturn ResolveTypeLenient(IToken tok, Type type, ICodeContext context, ResolveTypeOption option, List<TypeParameter> defaultTypeArguments, bool allowDanglingDotName) { Contract.Requires(tok != null); Contract.Requires(type != null); Contract.Requires(context != null); Contract.Requires((option.Opt == ResolveTypeOptionEnum.DontInfer || option.Opt == ResolveTypeOptionEnum.InferTypeProxies) == (defaultTypeArguments == null)); if (type is BitvectorType) { var t = (BitvectorType)type; // nothing to resolve, but record the fact that this bitvector width is in use builtIns.Bitwidths.Add(t.Width); } else if (type is BasicType) { // nothing to resolve } else if (type is MapType) { var mt = (MapType)type; var errorCount = reporter.Count(ErrorLevel.Error); int typeArgumentCount; if (mt.HasTypeArg()) { ResolveType(tok, mt.Domain, context, option, defaultTypeArguments); ResolveType(tok, mt.Range, context, option, defaultTypeArguments); typeArgumentCount = 2; } else if (option.Opt == ResolveTypeOptionEnum.DontInfer) { mt.SetTypeArgs(new InferredTypeProxy(), new InferredTypeProxy()); typeArgumentCount = 0; } else { var inferredTypeArgs = new List<Type>(); FillInTypeArguments(tok, 2, inferredTypeArgs, defaultTypeArguments, option); Contract.Assert(inferredTypeArgs.Count <= 2); if (inferredTypeArgs.Count == 1) { mt.SetTypeArgs(inferredTypeArgs[0], new InferredTypeProxy()); typeArgumentCount = 1; } else if (inferredTypeArgs.Count == 2) { mt.SetTypeArgs(inferredTypeArgs[0], inferredTypeArgs[1]); typeArgumentCount = 2; } else { mt.SetTypeArgs(new InferredTypeProxy(), new InferredTypeProxy()); typeArgumentCount = 0; } } // defaults and auto have been applied; check if we now have the right number of arguments if (2 != typeArgumentCount) { reporter.Error(MessageSource.Resolver, tok, "Wrong number of type arguments ({0} instead of 2) passed to type: {1}", typeArgumentCount, mt.CollectionTypeName); } } else if (type is CollectionType) { var t = (CollectionType)type; var errorCount = reporter.Count(ErrorLevel.Error); if (t.HasTypeArg()) { ResolveType(tok, t.Arg, context, option, defaultTypeArguments); } else if (option.Opt != ResolveTypeOptionEnum.DontInfer) { var inferredTypeArgs = new List<Type>(); FillInTypeArguments(tok, 1, inferredTypeArgs, defaultTypeArguments, option); if (inferredTypeArgs.Count != 0) { Contract.Assert(inferredTypeArgs.Count == 1); t.SetTypeArg(inferredTypeArgs[0]); } } if (!t.HasTypeArg()) { // defaults and auto have been applied; check if we now have the right number of arguments reporter.Error(MessageSource.Resolver, tok, "Wrong number of type arguments (0 instead of 1) passed to type: {0}", t.CollectionTypeName); // add a proxy type, to make sure that CollectionType will have have a non-null Arg t.SetTypeArg(new InferredTypeProxy()); } } else if (type is UserDefinedType) { var t = (UserDefinedType)type; if (t.ResolvedClass != null || t.ResolvedParam != null) { // Apparently, this type has already been resolved return null; } var prevErrorCount = reporter.Count(ErrorLevel.Error); if (t.NamePath is ExprDotName) { var ret = ResolveDotSuffix_Type((ExprDotName)t.NamePath, new ResolveOpts(context, true), allowDanglingDotName, option, defaultTypeArguments); if (ret != null) { return ret; } } else { var s = (NameSegment)t.NamePath; ResolveNameSegment_Type(s, new ResolveOpts(context, true), option, defaultTypeArguments); } if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { var r = t.NamePath.Resolved as Resolver_IdentifierExpr; if (r == null || !(r.Type is Resolver_IdentifierExpr.ResolverType_Type)) { reporter.Error(MessageSource.Resolver, t.tok, "expected type"); } else if (r.Type is Resolver_IdentifierExpr.ResolverType_Type && r.TypeParamDecl != null) { t.ResolvedParam = r.TypeParamDecl; } else if (r.Type is Resolver_IdentifierExpr.ResolverType_Type) { var d = r.Decl; if (d is OpaqueTypeDecl) { var dd = (OpaqueTypeDecl)d; t.ResolvedParam = dd.TheType; // resolve like a type parameter, and it may have type parameters if it's an opaque type t.ResolvedClass = d; // Store the decl, so the compiler will generate the fully qualified name } else if (d is SubsetTypeDecl || d is NewtypeDecl) { var dd = (RedirectingTypeDecl)d; var caller = context as ICallable; if (caller != null && !(d is SubsetTypeDecl && caller is SpecialFunction)) { caller.EnclosingModule.CallGraph.AddEdge(caller, dd); if (caller == d) { // detect self-loops here, since they don't show up in the graph's SSC methods reporter.Error(MessageSource.Resolver, d.tok, "recursive constraint dependency involving a {0}: {1} -> {1}", d.WhatKind, d.Name); } } t.ResolvedClass = d; } else if (d is DatatypeDecl) { var dd = (DatatypeDecl)d; var caller = context as ICallable; if (caller != null) { caller.EnclosingModule.CallGraph.AddEdge(caller, dd); } t.ResolvedClass = d; } else { // d is a coinductive datatype or a class, and it may have type parameters t.ResolvedClass = d; } if (option.Opt == ResolveTypeOptionEnum.DontInfer) { // don't add anything } else if (d.TypeArgs.Count != t.TypeArgs.Count && t.TypeArgs.Count == 0) { FillInTypeArguments(t.tok, d.TypeArgs.Count, t.TypeArgs, defaultTypeArguments, option); } // defaults and auto have been applied; check if we now have the right number of arguments if (d.TypeArgs.Count != t.TypeArgs.Count) { reporter.Error(MessageSource.Resolver, t.tok, "Wrong number of type arguments ({0} instead of {1}) passed to {2}: {3}", t.TypeArgs.Count, d.TypeArgs.Count, d.WhatKind, t.Name); } } } if (t.ResolvedClass == null && t.ResolvedParam == null) { // There was some error. Still, we will set one of them to some value to prevent some crashes in the downstream resolution. The // 0-tuple is convenient, because it is always in scope. t.ResolvedClass = builtIns.TupleType(t.tok, 0, false); // clear out the TypeArgs since 0-tuple doesn't take TypeArg t.TypeArgs = new List<Type>(); } } else if (type is TypeProxy) { TypeProxy t = (TypeProxy)type; if (t.T != null) { ResolveType(tok, t.T, context, option, defaultTypeArguments); } } else if (type is SelfType) { // do nothing. } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type } return null; } /// <summary> /// Adds to "typeArgs" a list of "n" type arguments, possibly extending "defaultTypeArguments". /// </summary> static void FillInTypeArguments(IToken tok, int n, List<Type> typeArgs, List<TypeParameter> defaultTypeArguments, ResolveTypeOption option) { Contract.Requires(tok != null); Contract.Requires(0 <= n); Contract.Requires(typeArgs != null && typeArgs.Count == 0); if (option.Opt == ResolveTypeOptionEnum.InferTypeProxies) { // add type arguments that will be inferred for (int i = 0; i < n; i++) { typeArgs.Add(new InferredTypeProxy()); } } else if (option.Opt == ResolveTypeOptionEnum.AllowPrefix && defaultTypeArguments.Count < n) { // there aren't enough default arguments, so don't do anything } else { // we'll add arguments if (option.Opt == ResolveTypeOptionEnum.AllowPrefixExtend) { // extend defaultTypeArguments, if needed for (int i = defaultTypeArguments.Count; i < n; i++) { var tp = new TypeParameter(tok, "_T" + i, i, option.Parent); if (option.Parent is IteratorDecl) { tp.Characteristics.AutoInit = Type.AutoInitInfo.CompilableValue; } defaultTypeArguments.Add(tp); } } Contract.Assert(n <= defaultTypeArguments.Count); // automatically supply a prefix of the arguments from defaultTypeArguments for (int i = 0; i < n; i++) { typeArgs.Add(new UserDefinedType(defaultTypeArguments[i])); } } } public static bool TypeConstraintsIncludeProxy(Type t, TypeProxy proxy) { return TypeConstraintsIncludeProxy_Aux(t, proxy, new HashSet<TypeProxy>()); } static bool TypeConstraintsIncludeProxy_Aux(Type t, TypeProxy proxy, ISet<TypeProxy> visited) { Contract.Requires(t != null); Contract.Requires(!(t is TypeProxy) || ((TypeProxy)t).T == null); // t is expected to have been normalized first Contract.Requires(proxy != null && proxy.T == null); Contract.Requires(visited != null); var tproxy = t as TypeProxy; if (tproxy != null) { if (object.ReferenceEquals(tproxy, proxy)) { return true; } else if (visited.Contains(tproxy)) { return false; } visited.Add(tproxy); foreach (var su in tproxy.Subtypes) { if (TypeConstraintsIncludeProxy_Aux(su, proxy, visited)) { return true; } } foreach (var su in tproxy.Supertypes) { if (TypeConstraintsIncludeProxy_Aux(su, proxy, visited)) { return true; } } } else { // check type arguments of t foreach (var ta in t.TypeArgs) { var a = ta.Normalize(); if (TypeConstraintsIncludeProxy_Aux(a, proxy, visited)) { return true; } } } return false; } /// <summary> /// Returns a resolved type denoting an array type with dimension "dims" and element type "arg". /// Callers are expected to provide "arg" as an already resolved type. (Note, a proxy type is resolved-- /// only types that contain identifiers stand the possibility of not being resolved.) /// </summary> Type ResolvedArrayType(IToken tok, int dims, Type arg, ICodeContext context, bool useClassNameType) { Contract.Requires(tok != null); Contract.Requires(1 <= dims); Contract.Requires(arg != null); var at = builtIns.ArrayType(tok, dims, new List<Type> { arg }, false, useClassNameType); ResolveType(tok, at, context, ResolveTypeOptionEnum.DontInfer, null); return at; } public void ResolveStatement(Statement stmt, ICodeContext codeContext) { Contract.Requires(stmt != null); Contract.Requires(codeContext != null); if (!(stmt is ForallStmt)) { // forall statements do their own attribute resolution below ResolveAttributes(stmt.Attributes, stmt, new ResolveOpts(codeContext, true)); } if (stmt is PredicateStmt) { PredicateStmt s = (PredicateStmt)stmt; var assertStmt = stmt as AssertStmt; if (assertStmt != null && assertStmt.Label != null) { if (dominatingStatementLabels.Find(assertStmt.Label.Name) != null) { reporter.Error(MessageSource.Resolver, assertStmt.Label.Tok, "assert label shadows a dominating label"); } else { var rr = dominatingStatementLabels.Push(assertStmt.Label.Name, assertStmt.Label); Contract.Assert(rr == Scope<Label>.PushResult.Success); // since we just checked for duplicates, we expect the Push to succeed } } ResolveExpression(s.Expr, new ResolveOpts(codeContext, true)); Contract.Assert(s.Expr.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(s.Expr, "condition is expected to be of type bool, but is {0}"); if (assertStmt != null && assertStmt.Proof != null) { // clear the labels for the duration of checking the proof body, because break statements are not allowed to leave a the proof body var prevLblStmts = enclosingStatementLabels; var prevLoopStack = loopStack; enclosingStatementLabels = new Scope<Statement>(); loopStack = new List<Statement>(); ResolveStatement(assertStmt.Proof, codeContext); enclosingStatementLabels = prevLblStmts; loopStack = prevLoopStack; } var expectStmt = stmt as ExpectStmt; if (expectStmt != null) { if (expectStmt.Message == null) { expectStmt.Message = new StringLiteralExpr(s.Tok, "expectation violation", false); } ResolveExpression(expectStmt.Message, new ResolveOpts(codeContext, true)); Contract.Assert(expectStmt.Message.Type != null); // follows from postcondition of ResolveExpression } } else if (stmt is PrintStmt) { var s = (PrintStmt)stmt; var opts = new ResolveOpts(codeContext, false); s.Args.Iter(e => ResolveExpression(e, opts)); } else if (stmt is RevealStmt) { var s = (RevealStmt)stmt; foreach (var expr in s.Exprs) { var name = RevealStmt.SingleName(expr); var labeledAssert = name == null ? null : dominatingStatementLabels.Find(name) as AssertLabel; if (labeledAssert != null) { s.LabeledAsserts.Add(labeledAssert); } else { var opts = new ResolveOpts(codeContext, false, true, false, false); if (expr is ApplySuffix) { var e = (ApplySuffix)expr; var methodCallInfo = ResolveApplySuffix(e, opts, true); if (methodCallInfo == null) { reporter.Error(MessageSource.Resolver, expr.tok, "expression has no reveal lemma"); } else { var call = new CallStmt(methodCallInfo.Tok, s.EndTok, new List<Expression>(), methodCallInfo.Callee, methodCallInfo.Args); s.ResolvedStatements.Add(call); } } else { ResolveExpression(expr, opts); } foreach (var a in s.ResolvedStatements) { ResolveStatement(a, codeContext); } } } } else if (stmt is BreakStmt) { var s = (BreakStmt)stmt; if (s.TargetLabel != null) { Statement target = enclosingStatementLabels.Find(s.TargetLabel); if (target == null) { reporter.Error(MessageSource.Resolver, s, "break label is undefined or not in scope: {0}", s.TargetLabel); } else { s.TargetStmt = target; } } else { if (loopStack.Count < s.BreakCount) { reporter.Error(MessageSource.Resolver, s, "trying to break out of more loop levels than there are enclosing loops"); } else { Statement target = loopStack[loopStack.Count - s.BreakCount]; if (target.Labels == null) { // make sure there is a label, because the compiler and translator will want to see a unique ID target.Labels = new LList<Label>(new Label(target.Tok, null), null); } s.TargetStmt = target; } } } else if (stmt is ProduceStmt) { var kind = stmt is YieldStmt ? "yield" : "return"; if (stmt is YieldStmt && !(codeContext is IteratorDecl)) { reporter.Error(MessageSource.Resolver, stmt, "yield statement is allowed only in iterators"); } else if (stmt is ReturnStmt && !(codeContext is Method)) { reporter.Error(MessageSource.Resolver, stmt, "return statement is allowed only in method"); } else if (inBodyInitContext) { reporter.Error(MessageSource.Resolver, stmt, "return statement is not allowed before 'new;' in a constructor"); } var s = (ProduceStmt)stmt; if (s.rhss != null) { var cmc = codeContext as IMethodCodeContext; if (cmc == null) { // an error has already been reported above } else if (cmc.Outs.Count != s.rhss.Count) { reporter.Error(MessageSource.Resolver, s, "number of {2} parameters does not match declaration (found {0}, expected {1})", s.rhss.Count, cmc.Outs.Count, kind); } else { Contract.Assert(s.rhss.Count > 0); // Create a hidden update statement using the out-parameter formals, resolve the RHS, and check that the RHS is good. List<Expression> formals = new List<Expression>(); foreach (Formal f in cmc.Outs) { Expression produceLhs; if (stmt is ReturnStmt) { var ident = new IdentifierExpr(f.tok, f.Name); // resolve it here to avoid capture into more closely declared local variables ident.Var = f; ident.Type = ident.Var.Type; Contract.Assert(f.Type != null); produceLhs = ident; } else { var yieldIdent = new MemberSelectExpr(f.tok, new ImplicitThisExpr(f.tok), f.Name); ResolveExpression(yieldIdent, new ResolveOpts(codeContext, true)); produceLhs = yieldIdent; } formals.Add(produceLhs); } s.hiddenUpdate = new UpdateStmt(s.Tok, s.EndTok, formals, s.rhss, true); // resolving the update statement will check for return/yield statement specifics. ResolveStatement(s.hiddenUpdate, codeContext); } } else {// this is a regular return/yield statement. s.hiddenUpdate = null; } } else if (stmt is ConcreteUpdateStatement) { ResolveConcreteUpdateStmt((ConcreteUpdateStatement)stmt, codeContext); } else if (stmt is VarDeclStmt) { var s = (VarDeclStmt)stmt; // We have four cases. Contract.Assert(s.Update == null || s.Update is AssignSuchThatStmt || s.Update is UpdateStmt || s.Update is AssignOrReturnStmt); // 0. There is no .Update. This is easy, we will just resolve the locals. // 1. The .Update is an AssignSuchThatStmt. This is also straightforward: first // resolve the locals, which adds them to the scope, and then resolve the .Update. // 2. The .Update is an UpdateStmt, which, resolved, means either a CallStmt or a bunch // of parallel AssignStmt's. Here, the right-hand sides should be resolved before // the local variables have been added to the scope, but the left-hand sides should // resolve to the newly introduced variables. // 3. The .Update is a ":-" statement, for which resolution does two steps: // First, desugar, then run the regular resolution on the desugared AST. // To accommodate these options, we first reach into the UpdateStmt, if any, to resolve // the left-hand sides of the UpdateStmt. This will have the effect of shielding them // from a subsequent resolution (since expression resolution will do nothing if the .Type // field is already assigned. // Alright, so it is: // Resolve the types of the locals foreach (var local in s.Locals) { int prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveType(local.Tok, local.OptionalType, codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { local.type = local.OptionalType; } else { local.type = new InferredTypeProxy(); } } // Resolve the UpdateStmt, if any if (s.Update is UpdateStmt) { var upd = (UpdateStmt)s.Update; // resolve the LHS Contract.Assert(upd.Lhss.Count == s.Locals.Count); for (int i = 0; i < upd.Lhss.Count; i++) { var local = s.Locals[i]; var lhs = (IdentifierExpr)upd.Lhss[i]; // the LHS in this case will be an IdentifierExpr, because that's how the parser creates the VarDeclStmt Contract.Assert(lhs.Type == null); // not yet resolved lhs.Var = local; lhs.Type = local.Type; } // resolve the whole thing ResolveConcreteUpdateStmt(s.Update, codeContext); } if (s.Update is AssignOrReturnStmt) { var assignOrRet = (AssignOrReturnStmt)s.Update; // resolve the LHS Contract.Assert(assignOrRet.Lhss.Count == s.Locals.Count); for (int i = 0; i < s.Locals.Count; i++) { var local = s.Locals[i]; var lhs = (IdentifierExpr)assignOrRet .Lhss[i]; // the LHS in this case will be an IdentifierExpr, because that's how the parser creates the VarDeclStmt Contract.Assert(lhs.Type == null); // not yet resolved lhs.Var = local; lhs.Type = local.Type; } // resolve the whole thing ResolveAssignOrReturnStmt(assignOrRet, codeContext); } // Add the locals to the scope foreach (var local in s.Locals) { ScopePushAndReport(scope, local, "local-variable"); } // With the new locals in scope, it's now time to resolve the attributes on all the locals foreach (var local in s.Locals) { ResolveAttributes(local.Attributes, local, new ResolveOpts(codeContext, true)); } // Resolve the AssignSuchThatStmt, if any if (s.Update is AssignSuchThatStmt) { ResolveConcreteUpdateStmt(s.Update, codeContext); } // Update the VarDeclStmt's ghost status according to its components foreach (var local in s.Locals) { if (Attributes.Contains(local.Attributes, "assumption")) { if (currentMethod != null) { ConstrainSubtypeRelation(Type.Bool, local.type, local.Tok, "assumption variable must be of type 'bool'"); if (!local.IsGhost) { reporter.Error(MessageSource.Resolver, local.Tok, "assumption variable must be ghost"); } } else { reporter.Error(MessageSource.Resolver, local.Tok, "assumption variable can only be declared in a method"); } } } } else if (stmt is VarDeclPattern) { VarDeclPattern s = (VarDeclPattern)stmt; foreach (var local in s.LocalVars) { int prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveType(local.Tok, local.OptionalType, codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { local.type = local.OptionalType; } else { local.type = new InferredTypeProxy(); } } ResolveExpression(s.RHS, new ResolveOpts(codeContext, true)); ResolveCasePattern(s.LHS, s.RHS.Type, codeContext); // Check for duplicate names now, because not until after resolving the case pattern do we know if identifiers inside it refer to bound variables or nullary constructors var c = 0; foreach (var bv in s.LHS.Vars) { ScopePushAndReport(scope, bv, "local_variable"); c++; } if (c == 0) { // Every identifier-looking thing in the pattern resolved to a constructor; that is, this LHS is a constant literal reporter.Error(MessageSource.Resolver, s.LHS.tok, "LHS is a constant literal; to be legal, it must introduce at least one bound variable"); } } else if (stmt is AssignStmt) { AssignStmt s = (AssignStmt)stmt; int prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveExpression(s.Lhs, new ResolveOpts(codeContext, true)); // allow ghosts for now, tighted up below bool lhsResolvedSuccessfully = reporter.Count(ErrorLevel.Error) == prevErrorCount; Contract.Assert(s.Lhs.Type != null); // follows from postcondition of ResolveExpression // check that LHS denotes a mutable variable or a field var lhs = s.Lhs.Resolved; if (lhs is IdentifierExpr) { IVariable var = ((IdentifierExpr)lhs).Var; if (var == null) { // the LHS didn't resolve correctly; some error would already have been reported } else { CheckIsLvalue(lhs, codeContext); var localVar = var as LocalVariable; if (localVar != null && currentMethod != null && Attributes.Contains(localVar.Attributes, "assumption")) { var rhs = s.Rhs as ExprRhs; var expr = (rhs != null ? rhs.Expr : null); var binaryExpr = expr as BinaryExpr; if (binaryExpr != null && (binaryExpr.Op == BinaryExpr.Opcode.And) && (binaryExpr.E0.Resolved is IdentifierExpr) && ((IdentifierExpr)(binaryExpr.E0.Resolved)).Var == localVar && !currentMethod.AssignedAssumptionVariables.Contains(localVar)) { currentMethod.AssignedAssumptionVariables.Add(localVar); } else { reporter.Error(MessageSource.Resolver, stmt, string.Format("there may be at most one assignment to an assumption variable, the RHS of which must match the expression \"{0} && <boolean expression>\"", localVar.Name)); } } } } else if (lhs is MemberSelectExpr) { var fse = (MemberSelectExpr)lhs; if (fse.Member != null) { // otherwise, an error was reported above CheckIsLvalue(fse, codeContext); } } else if (lhs is SeqSelectExpr) { var slhs = (SeqSelectExpr)lhs; // LHS is fine, provided the "sequence" is really an array if (lhsResolvedSuccessfully) { Contract.Assert(slhs.Seq.Type != null); CheckIsLvalue(slhs, codeContext); } } else if (lhs is MultiSelectExpr) { CheckIsLvalue(lhs, codeContext); } else { CheckIsLvalue(lhs, codeContext); } Type lhsType = s.Lhs.Type; if (s.Rhs is ExprRhs) { ExprRhs rr = (ExprRhs)s.Rhs; ResolveExpression(rr.Expr, new ResolveOpts(codeContext, true)); Contract.Assert(rr.Expr.Type != null); // follows from postcondition of ResolveExpression AddAssignableConstraint(stmt.Tok, lhsType, rr.Expr.Type, "RHS (of type {1}) not assignable to LHS (of type {0})"); } else if (s.Rhs is TypeRhs) { TypeRhs rr = (TypeRhs)s.Rhs; Type t = ResolveTypeRhs(rr, stmt, codeContext); AddAssignableConstraint(stmt.Tok, lhsType, t, "type {1} is not assignable to LHS (of type {0})"); } else if (s.Rhs is HavocRhs) { // nothing else to do } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected RHS } } else if (stmt is CallStmt) { CallStmt s = (CallStmt)stmt; ResolveCallStmt(s, codeContext, null); } else if (stmt is BlockStmt) { var s = (BlockStmt)stmt; scope.PushMarker(); ResolveBlockStatement(s, codeContext); scope.PopMarker(); } else if (stmt is IfStmt) { IfStmt s = (IfStmt)stmt; if (s.Guard != null) { ResolveExpression(s.Guard, new ResolveOpts(codeContext, true)); Contract.Assert(s.Guard.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(s.Guard, "condition is expected to be of type bool, but is {0}"); } scope.PushMarker(); if (s.IsBindingGuard) { var exists = (ExistsExpr)s.Guard; foreach (var v in exists.BoundVars) { ScopePushAndReport(scope, v, "bound-variable"); } } dominatingStatementLabels.PushMarker(); ResolveBlockStatement(s.Thn, codeContext); dominatingStatementLabels.PopMarker(); scope.PopMarker(); if (s.Els != null) { dominatingStatementLabels.PushMarker(); ResolveStatement(s.Els, codeContext); dominatingStatementLabels.PopMarker(); } } else if (stmt is AlternativeStmt) { var s = (AlternativeStmt)stmt; ResolveAlternatives(s.Alternatives, null, codeContext); } else if (stmt is WhileStmt) { WhileStmt s = (WhileStmt)stmt; var fvs = new HashSet<IVariable>(); var usesHeap = false; if (s.Guard != null) { ResolveExpression(s.Guard, new ResolveOpts(codeContext, true)); Contract.Assert(s.Guard.Type != null); // follows from postcondition of ResolveExpression Translator.ComputeFreeVariables(s.Guard, fvs, ref usesHeap); ConstrainTypeExprBool(s.Guard, "condition is expected to be of type bool, but is {0}"); } ResolveLoopSpecificationComponents(s.Invariants, s.Decreases, s.Mod, codeContext, fvs, ref usesHeap); if (s.Body != null) { loopStack.Add(s); // push dominatingStatementLabels.PushMarker(); ResolveStatement(s.Body, codeContext); dominatingStatementLabels.PopMarker(); loopStack.RemoveAt(loopStack.Count - 1); // pop } else { Contract.Assert(s.BodySurrogate == null); // .BodySurrogate is set only once s.BodySurrogate = new WhileStmt.LoopBodySurrogate(new List<IVariable>(fvs.Where(fv => fv.IsMutable)), usesHeap); var text = Util.Comma(s.BodySurrogate.LocalLoopTargets, fv => fv.Name); if (s.BodySurrogate.UsesHeap) { text += text.Length == 0 ? "$Heap" : ", $Heap"; } text = string.Format("note, this loop has no body{0}", text.Length == 0 ? "" : " (loop frame: " + text + ")"); reporter.Warning(MessageSource.Resolver, s.Tok, text); } } else if (stmt is AlternativeLoopStmt) { var s = (AlternativeLoopStmt)stmt; ResolveAlternatives(s.Alternatives, s, codeContext); var usesHeapDontCare = false; ResolveLoopSpecificationComponents(s.Invariants, s.Decreases, s.Mod, codeContext, null, ref usesHeapDontCare); } else if (stmt is ForallStmt) { var s = (ForallStmt)stmt; int prevErrorCount = reporter.Count(ErrorLevel.Error); scope.PushMarker(); foreach (BoundVar v in s.BoundVars) { ScopePushAndReport(scope, v, "local-variable"); ResolveType(v.tok, v.Type, codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); } ResolveExpression(s.Range, new ResolveOpts(codeContext, true)); Contract.Assert(s.Range.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(s.Range, "range restriction in forall statement must be of type bool (instead got {0})"); foreach (var ens in s.Ens) { ResolveExpression(ens.E, new ResolveOpts(codeContext, true)); Contract.Assert(ens.E.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(ens.E, "ensures condition is expected to be of type bool, but is {0}"); } // Since the range and postconditions are more likely to infer the types of the bound variables, resolve them // first (above) and only then resolve the attributes (below). ResolveAttributes(s.Attributes, s, new ResolveOpts(codeContext, true)); if (s.Body != null) { // clear the labels for the duration of checking the body, because break statements are not allowed to leave a forall statement var prevLblStmts = enclosingStatementLabels; var prevLoopStack = loopStack; enclosingStatementLabels = new Scope<Statement>(); loopStack = new List<Statement>(); ResolveStatement(s.Body, codeContext); enclosingStatementLabels = prevLblStmts; loopStack = prevLoopStack; } else { reporter.Warning(MessageSource.Resolver, s.Tok, "note, this forall statement has no body"); } scope.PopMarker(); if (prevErrorCount == reporter.Count(ErrorLevel.Error)) { // determine the Kind and run some additional checks on the body if (s.Ens.Count != 0) { // The only supported kind with ensures clauses is Proof. s.Kind = ForallStmt.BodyKind.Proof; } else { // There are three special cases: // * Assign, which is the only kind of the forall statement that allows a heap update. // * Call, which is a single call statement with no side effects or output parameters. // * A single calc statement, which is a special case of Proof where the postcondition can be inferred. // The effect of Assign and the postcondition of Call will be seen outside the forall // statement. Statement s0 = s.S0; if (s0 is AssignStmt) { s.Kind = ForallStmt.BodyKind.Assign; } else if (s0 is CallStmt) { s.Kind = ForallStmt.BodyKind.Call; var call = (CallStmt)s.S0; var method = call.Method; // if the called method is not in the same module as the ForallCall stmt // don't convert it to ForallExpression since the inlined called method's // ensure clause might not be resolved correctly(test\dafny3\GenericSort.dfy) if (method.EnclosingClass.EnclosingModuleDefinition != codeContext.EnclosingModule) { s.CanConvert = false; } // Additional information (namely, the postcondition of the call) will be reported later. But it cannot be // done yet, because the specification of the callee may not have been resolved yet. } else if (s0 is CalcStmt) { s.Kind = ForallStmt.BodyKind.Proof; // add the conclusion of the calc as a free postcondition var result = ((CalcStmt)s0).Result; s.Ens.Add(new AttributedExpression(result)); reporter.Info(MessageSource.Resolver, s.Tok, "ensures " + Printer.ExprToString(result)); } else { s.Kind = ForallStmt.BodyKind.Proof; if (s.Body is BlockStmt && ((BlockStmt)s.Body).Body.Count == 0) { // an empty statement, so don't produce any warning } else { reporter.Warning(MessageSource.Resolver, s.Tok, "the conclusion of the body of this forall statement will not be known outside the forall statement; consider using an 'ensures' clause"); } } } if (s.Body != null) { CheckForallStatementBodyRestrictions(s.Body, s.Kind); } if (s.ForallExpressions != null) { foreach (Expression expr in s.ForallExpressions) { ResolveExpression(expr, new ResolveOpts(codeContext, true)); } } } } else if (stmt is ModifyStmt) { var s = (ModifyStmt)stmt; ResolveAttributes(s.Mod.Attributes, null, new ResolveOpts(codeContext, true)); foreach (FrameExpression fe in s.Mod.Expressions) { ResolveFrameExpression(fe, FrameExpressionUse.Modifies, codeContext); } if (s.Body != null) { ResolveBlockStatement(s.Body, codeContext); } } else if (stmt is CalcStmt) { var prevErrorCount = reporter.Count(ErrorLevel.Error); CalcStmt s = (CalcStmt)stmt; // figure out s.Op Contract.Assert(s.Op == null); // it hasn't been set yet if (s.UserSuppliedOp != null) { s.Op = s.UserSuppliedOp; } else { // Usually, we'd use == as the default main operator. However, if the calculation // begins or ends with a boolean literal, then we can do better by selecting ==> // or <==. Also, if the calculation begins or ends with an empty set, then we can // do better by selecting <= or >=. if (s.Lines.Count == 0) { s.Op = CalcStmt.DefaultOp; } else { bool b; if (Expression.IsBoolLiteral(s.Lines.First(), out b)) { s.Op = new CalcStmt.BinaryCalcOp(b ? BinaryExpr.Opcode.Imp : BinaryExpr.Opcode.Exp); } else if (Expression.IsBoolLiteral(s.Lines.Last(), out b)) { s.Op = new CalcStmt.BinaryCalcOp(b ? BinaryExpr.Opcode.Exp : BinaryExpr.Opcode.Imp); } else if (Expression.IsEmptySetOrMultiset(s.Lines.First())) { s.Op = new CalcStmt.BinaryCalcOp(BinaryExpr.Opcode.Ge); } else if (Expression.IsEmptySetOrMultiset(s.Lines.Last())) { s.Op = new CalcStmt.BinaryCalcOp(BinaryExpr.Opcode.Le); } else { s.Op = CalcStmt.DefaultOp; } } reporter.Info(MessageSource.Resolver, s.Tok, s.Op.ToString()); } if (s.Lines.Count > 0) { Type lineType = new InferredTypeProxy(); var e0 = s.Lines.First(); ResolveExpression(e0, new ResolveOpts(codeContext, true)); Contract.Assert(e0.Type != null); // follows from postcondition of ResolveExpression var err = new TypeConstraint.ErrorMsgWithToken(e0.tok, "all lines in a calculation must have the same type (got {0} after {1})", e0.Type, lineType); ConstrainSubtypeRelation(lineType, e0.Type, err); for (int i = 1; i < s.Lines.Count; i++) { var e1 = s.Lines[i]; ResolveExpression(e1, new ResolveOpts(codeContext, true)); Contract.Assert(e1.Type != null); // follows from postcondition of ResolveExpression // reuse the error object if we're on the dummy line; this prevents a duplicate error message if (i < s.Lines.Count - 1) { err = new TypeConstraint.ErrorMsgWithToken(e1.tok, "all lines in a calculation must have the same type (got {0} after {1})", e1.Type, lineType); } ConstrainSubtypeRelation(lineType, e1.Type, err); var step = (s.StepOps[i - 1] ?? s.Op).StepExpr(e0, e1); // Use custom line operator ResolveExpression(step, new ResolveOpts(codeContext, true)); s.Steps.Add(step); e0 = e1; } // clear the labels for the duration of checking the hints, because break statements are not allowed to leave a forall statement var prevLblStmts = enclosingStatementLabels; var prevLoopStack = loopStack; enclosingStatementLabels = new Scope<Statement>(); loopStack = new List<Statement>(); foreach (var h in s.Hints) { foreach (var oneHint in h.Body) { dominatingStatementLabels.PushMarker(); ResolveStatement(oneHint, codeContext); dominatingStatementLabels.PopMarker(); } } enclosingStatementLabels = prevLblStmts; loopStack = prevLoopStack; } if (prevErrorCount == reporter.Count(ErrorLevel.Error) && s.Lines.Count > 0) { // do not build Result from the lines if there were errors, as it might be ill-typed and produce unnecessary resolution errors var resultOp = s.StepOps.Aggregate(s.Op, (op0, op1) => op1 == null ? op0 : op0.ResultOp(op1)); s.Result = resultOp.StepExpr(s.Lines.First(), s.Lines.Last()); } else { s.Result = CalcStmt.DefaultOp.StepExpr(Expression.CreateIntLiteral(s.Tok, 0), Expression.CreateIntLiteral(s.Tok, 0)); } ResolveExpression(s.Result, new ResolveOpts(codeContext, true)); Contract.Assert(s.Result != null); Contract.Assert(prevErrorCount != reporter.Count(ErrorLevel.Error) || s.Steps.Count == s.Hints.Count); } else if (stmt is MatchStmt) { ResolveMatchStmt((MatchStmt)stmt, codeContext); } else if (stmt is NestedMatchStmt) { var s = (NestedMatchStmt)stmt; var opts = new ResolveOpts(codeContext, false); ResolveNestedMatchStmt(s, opts); } else if (stmt is SkeletonStatement) { var s = (SkeletonStatement)stmt; reporter.Error(MessageSource.Resolver, s.Tok, "skeleton statements are allowed only in refining methods"); // nevertheless, resolve the underlying statement; hey, why not if (s.S != null) { ResolveStatement(s.S, codeContext); } } else { Contract.Assert(false); throw new cce.UnreachableException(); } } private void ResolveLoopSpecificationComponents(List<AttributedExpression> invariants, Specification<Expression> decreases, Specification<FrameExpression> modifies, ICodeContext codeContext, HashSet<IVariable> fvs, ref bool usesHeap) { Contract.Requires(invariants != null); Contract.Requires(decreases != null); Contract.Requires(modifies != null); Contract.Requires(codeContext != null); foreach (AttributedExpression inv in invariants) { ResolveAttributes(inv.Attributes, null, new ResolveOpts(codeContext, true)); ResolveExpression(inv.E, new ResolveOpts(codeContext, true)); Contract.Assert(inv.E.Type != null); // follows from postcondition of ResolveExpression if (fvs != null) { Translator.ComputeFreeVariables(inv.E, fvs, ref usesHeap); } ConstrainTypeExprBool(inv.E, "invariant is expected to be of type bool, but is {0}"); } ResolveAttributes(decreases.Attributes, null, new ResolveOpts(codeContext, true)); foreach (Expression e in decreases.Expressions) { ResolveExpression(e, new ResolveOpts(codeContext, true)); if (e is WildcardExpr && !codeContext.AllowsNontermination) { reporter.Error(MessageSource.Resolver, e, "a possibly infinite loop is allowed only if the enclosing method is declared (with 'decreases *') to be possibly non-terminating"); } if (fvs != null) { Translator.ComputeFreeVariables(e, fvs, ref usesHeap); } // any type is fine } ResolveAttributes(modifies.Attributes, null, new ResolveOpts(codeContext, true)); if (modifies.Expressions != null) { usesHeap = true; // bearing a modifies clause counts as using the heap foreach (FrameExpression fe in modifies.Expressions) { ResolveFrameExpression(fe, FrameExpressionUse.Modifies, codeContext); } } } /// <summary> /// Resolves a NestedMatchStmt by /// 1 - checking that all of its patterns are linear /// 2 - desugaring it into a decision tree of MatchStmt and IfStmt (for constant matching) /// 3 - resolving the generated (sub)statement. /// </summary> void ResolveNestedMatchStmt(NestedMatchStmt s, ResolveOpts opts) { ICodeContext codeContext = opts.codeContext; Contract.Requires(s != null); Contract.Requires(codeContext != null); Contract.Requires(s.ResolvedStatement == null); bool debugMatch = DafnyOptions.O.MatchCompilerDebug; ResolveExpression(s.Source, new ResolveOpts(codeContext, true)); Contract.Assert(s.Source.Type != null); // follows from postcondition of ResolveExpression if (s.Source.Type is TypeProxy) { PartiallySolveTypeConstraints(true); if (debugMatch) Console.WriteLine("DEBUG: Type of {0} was still a proxy, solving type constraints results in type {1}", Printer.ExprToString(s.Source), s.Source.Type.ToString()); if (s.Source.Type is TypeProxy) { reporter.Error(MessageSource.Resolver, s.Tok, "Could not resolve the type of the source of the match expression. Please provide additional typing annotations."); return; } } var sourceType = PartiallyResolveTypeForMemberSelection(s.Source.tok, s.Source.Type).NormalizeExpand(); var errorCount = reporter.Count(ErrorLevel.Error); CheckLinearNestedMatchStmt(sourceType, s, opts); if (reporter.Count(ErrorLevel.Error) != errorCount) return; errorCount = reporter.Count(ErrorLevel.Error); CompileNestedMatchStmt(s, opts); if (reporter.Count(ErrorLevel.Error) != errorCount) return; enclosingStatementLabels.PushMarker(); ResolveStatement(s.ResolvedStatement, codeContext); enclosingStatementLabels.PopMarker(); } void ResolveMatchStmt(MatchStmt s, ICodeContext codeContext) { Contract.Requires(s != null); Contract.Requires(codeContext != null); Contract.Requires(s.OrigUnresolved == null); // first, clone the original expression s.OrigUnresolved = (MatchStmt)new Cloner().CloneStmt(s); ResolveExpression(s.Source, new ResolveOpts(codeContext, true)); Contract.Assert(s.Source.Type != null); // follows from postcondition of ResolveExpression var errorCount = reporter.Count(ErrorLevel.Error); var sourceType = PartiallyResolveTypeForMemberSelection(s.Source.tok, s.Source.Type).NormalizeExpand(); var dtd = sourceType.AsDatatype; var subst = new Dictionary<TypeParameter, Type>(); Dictionary<string, DatatypeCtor> ctors; if (dtd == null) { reporter.Error(MessageSource.Resolver, s.Source, "the type of the match source expression must be a datatype (instead found {0})", s.Source.Type); ctors = null; } else { ctors = datatypeCtors[dtd]; Contract.Assert(ctors != null); // dtd should have been inserted into datatypeCtors during a previous resolution stage subst = TypeSubstitutionMap(dtd.TypeArgs, sourceType.TypeArgs); // build the type-parameter substitution map for this use of the datatype } ISet<string> memberNamesUsed = new HashSet<string>(); foreach (MatchCaseStmt mc in s.Cases) { if (ctors != null) { Contract.Assert(dtd != null); var ctorId = mc.Ctor.Name; if (s.Source.Type.AsDatatype is TupleTypeDecl) { var tuple = (TupleTypeDecl)s.Source.Type.AsDatatype; var dims = tuple.Dims; ctorId = BuiltIns.TupleTypeCtorNamePrefix + dims; } if (!ctors.ContainsKey(ctorId)) { reporter.Error(MessageSource.Resolver, mc.tok, "member '{0}' does not exist in datatype '{1}'", ctorId, dtd.Name); } else { if (mc.Ctor.Formals.Count != mc.Arguments.Count) { if (s.Source.Type.AsDatatype is TupleTypeDecl) { reporter.Error(MessageSource.Resolver, mc.tok, "case arguments count does not match source arguments count"); } else { reporter.Error(MessageSource.Resolver, mc.tok, "member {0} has wrong number of formals (found {1}, expected {2})", ctorId, mc.Arguments.Count, mc.Ctor.Formals.Count); } } if (memberNamesUsed.Contains(ctorId)) { reporter.Error(MessageSource.Resolver, mc.tok, "member {0} appears in more than one case", mc.Ctor.Name); } else { memberNamesUsed.Add(ctorId); // add mc.Id to the set of names used } } } scope.PushMarker(); int i = 0; if (mc.Arguments != null) { foreach (BoundVar v in mc.Arguments) { scope.Push(v.Name, v); ResolveType(v.tok, v.Type, codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); if (i < mc.Ctor.Formals.Count) { Formal formal = mc.Ctor.Formals[i]; Type st = SubstType(formal.Type, subst); ConstrainSubtypeRelation(v.Type, st, s.Tok, "the declared type of the formal ({0}) does not agree with the corresponding type in the constructor's signature ({1})", v.Type, st); v.IsGhost = formal.IsGhost; // update the type of the boundvars in the MatchCaseToken if (v.tok is MatchCaseToken) { MatchCaseToken mt = (MatchCaseToken)v.tok; foreach (Tuple<IToken, BoundVar, bool> entry in mt.varList) { ConstrainSubtypeRelation(entry.Item2.Type, v.Type, entry.Item1, "incorrect type for bound match-case variable (expected {0}, got {1})", v.Type, entry.Item2.Type); } } } i++; } } dominatingStatementLabels.PushMarker(); foreach (Statement ss in mc.Body) { ResolveStatement(ss, codeContext); } dominatingStatementLabels.PopMarker(); scope.PopMarker(); } if (dtd != null && memberNamesUsed.Count != dtd.Ctors.Count) { // We could complain about the syntactic omission of constructors: // reporter.Error(MessageSource.Resolver, stmt, "match statement does not cover all constructors"); // but instead we let the verifier do a semantic check. // So, for now, record the missing constructors: foreach (var ctr in dtd.Ctors) { if (!memberNamesUsed.Contains(ctr.Name)) { s.MissingCases.Add(ctr); } } Contract.Assert(memberNamesUsed.Count + s.MissingCases.Count == dtd.Ctors.Count); } } /* Temporary information about the Match being desugared */ private class MatchTempInfo { public IToken Tok; public IToken EndTok; public IToken[] BranchTok; public int[] BranchIDCount; // Records the number of copies of each branch public bool isStmt; // true if we are desugaring a MatchStmt, false if a MatchExpr public bool Debug; public readonly ICodeContext CodeContext; public List<ExtendedPattern> MissingCases; public MatchTempInfo(IToken tok, int branchidnum, ICodeContext codeContext, bool debug = false) { int[] init = new int[branchidnum]; for (int i = 0; i < branchidnum; i++) { init[i] = 1; } this.Tok = tok; this.EndTok = tok; this.BranchTok = new IToken[branchidnum]; this.BranchIDCount = init; this.isStmt = false; this.Debug = debug; this.CodeContext = codeContext; this.MissingCases = new List<ExtendedPattern>(); } public MatchTempInfo(IToken tok, IToken endtok, int branchidnum, ICodeContext codeContext, bool debug = false) { int[] init = new int[branchidnum]; for (int i = 0; i < branchidnum; i++) { init[i] = 1; } this.Tok = tok; this.EndTok = endtok; this.BranchTok = new IToken[branchidnum]; this.BranchIDCount = init; this.isStmt = true; this.Debug = debug; this.CodeContext = codeContext; this.MissingCases = new List<ExtendedPattern>(); } public void UpdateBranchID(int branchID, int update) { BranchIDCount[branchID]+= update; } } /// <summary> /// A SyntaxContainer is a wrapper around either an Expression or a Statement /// It allows for generic functions over the two syntax spaces of Dafny /// </summary> private abstract class SyntaxContainer { public readonly IToken Tok; public SyntaxContainer(IToken tok) { this.Tok = tok; } } private class CExpr : SyntaxContainer { public readonly Expression Body; public CExpr(IToken tok, Expression body) : base(tok) { this.Body = body; } } private class CStmt : SyntaxContainer { public readonly Statement Body; public CStmt(IToken tok, Statement body) : base(tok) { this.Body = body; } } /// Unwraps a CStmt and returns its Body as a BlockStmt private BlockStmt BlockStmtOfCStmt(IToken tok, IToken endTok, CStmt con) { var stmt = con.Body; if (stmt is BlockStmt) { return (BlockStmt)stmt; } else { var stmts = new List<Statement>(); stmts.Add(stmt); return new BlockStmt(tok, endTok, stmts); } } /// <summary> /// RBranch is an intermediate data-structure representing a branch during pattern-match compilation /// </summary> private abstract class RBranch { public readonly IToken Tok; public int BranchID; public List<ExtendedPattern> Patterns; public RBranch(IToken tok, int branchid, List<ExtendedPattern> patterns) { this.Tok = tok; this.BranchID = branchid; this.Patterns = patterns; } } private class RBranchStmt : RBranch { public List<Statement> Body; public RBranchStmt(IToken tok, int branchid, List<ExtendedPattern> patterns, List<Statement> body) : base(tok, branchid, patterns) { this.Body = body; } public RBranchStmt(int branchid, NestedMatchCaseStmt x) : base(x.Tok, branchid, new List<ExtendedPattern>()) { this.Body = x.Body.ConvertAll((new Cloner()).CloneStmt); this.Patterns.Add(x.Pat); } public override string ToString() { var bodyStr = ""; foreach (var stmt in this.Body) { bodyStr += string.Format("{1}{0};\n", Printer.StatementToString(stmt), "\t"); } return string.Format("\t> id: {0}\n\t> patterns: <{1}>\n\t-> body:\n{2} \n", this.BranchID, String.Join(",", this.Patterns.ConvertAll(x => x.ToString())), bodyStr); } } private class RBranchExpr : RBranch { public Expression Body; public RBranchExpr(IToken tok, int branchid, List<ExtendedPattern> patterns, Expression body) : base(tok, branchid, patterns) { this.Body = body; } public RBranchExpr(int branchid, NestedMatchCaseExpr x) : base(x.Tok, branchid, new List<ExtendedPattern>()) { this.Body = x.Body; this.Patterns.Add(x.Pat); } public override string ToString() { return string.Format("\t> id: {0}\n\t-> patterns: <{1}>\n\t-> body: {2}", this.BranchID, String.Join(",", this.Patterns.ConvertAll(x => x.ToString())), Printer.ExprToString(this.Body)); } } // deep clone Patterns and Body private static RBranchStmt CloneRBranchStmt(RBranchStmt branch) { Cloner cloner = new Cloner(); return new RBranchStmt(branch.Tok, branch.BranchID, branch.Patterns.ConvertAll(x => cloner.CloneExtendedPattern(x)), branch.Body.ConvertAll(x=> cloner.CloneStmt(x))); } private static RBranchExpr CloneRBranchExpr(RBranchExpr branch) { Cloner cloner = new Cloner(); return new RBranchExpr(branch.Tok, branch.BranchID, branch.Patterns.ConvertAll(x => cloner.CloneExtendedPattern(x)), cloner.CloneExpr(branch.Body)); } private static RBranch CloneRBranch(RBranch branch) { if (branch is RBranchStmt) { return CloneRBranchStmt((RBranchStmt)branch); } else { return CloneRBranchExpr((RBranchExpr)branch); } } private static ExtendedPattern getPatternHead(RBranch branch) { return branch.Patterns.First(); } private static RBranch dropPatternHead(RBranch branch) { branch.Patterns.RemoveAt(0); return branch; } private SyntaxContainer PackBody(IToken tok, RBranch branch) { if (branch is RBranchStmt) { return new CStmt(tok, new BlockStmt(tok, tok, ((RBranchStmt)branch).Body)); } else if (branch is RBranchExpr) { return new CExpr(tok, ((RBranchExpr)branch).Body); } else { Contract.Assert(false); throw new cce.UnreachableException(); // RBranch has only two implementations } } private List<Statement> UnboxStmtContainer(SyntaxContainer con) { if (con is CStmt) { var r = new List<Statement> {((CStmt)con).Body}; return r; } else { throw new NotImplementedException("Bug in CompileRBranch: expected a StmtContainer"); } } // let-bind a variable of name "name" and type "type" as "expr" on the body of "branch" private void LetBind(RBranch branch, IdPattern var, Expression genExpr) { var name = var.Id; var type = var.Type; var isGhost = var.IsGhost; // if the expression is a generated IdentifierExpr, replace its token by the branch's Expression expr = genExpr; if (genExpr is IdentifierExpr idExpr) { if (idExpr.Name.StartsWith("_")) { expr = new IdentifierExpr(var.Tok, idExpr.Var); } } if (branch is RBranchStmt branchStmt) { var cLVar = new LocalVariable(var.Tok, var.Tok, name, type, isGhost); var cPat = new CasePattern<LocalVariable>(cLVar.EndTok, cLVar); var cLet = new VarDeclPattern(cLVar.Tok, cLVar.Tok, cPat, expr); branchStmt.Body.Insert(0, cLet); } else if (branch is RBranchExpr branchExpr) { var cBVar = new BoundVar(var.Tok, name, type); cBVar.IsGhost = isGhost; var cPat = new CasePattern<BoundVar>(cBVar.Tok, cBVar); var cPats = new List<CasePattern<BoundVar>>(); cPats.Add(cPat); var exprs = new List<Expression>(); exprs.Add(expr); var cLet = new LetExpr(cBVar.tok, cPats, exprs, branchExpr.Body, true); branchExpr.Body = cLet; } return; } // If cp is not a wildcard, replace branch.Body with let cp = expr in branch.Body // Otherwise do nothing private void LetBindNonWildCard(RBranch branch, IdPattern var, Expression expr) { if (!var.Id.StartsWith("_")) { LetBind(branch, var, expr); } } // Assumes that all SyntaxContainers in blocks and def are of the same subclass private SyntaxContainer MakeIfFromContainers(MatchTempInfo mti, MatchingContext context, Expression matchee, List<Tuple<LiteralExpr, SyntaxContainer>> blocks, SyntaxContainer def) { if (blocks.Count == 0) { if (def is CStmt sdef) { // Ensures the statements are wrapped in braces return new CStmt(null, BlockStmtOfCStmt(sdef.Body.Tok, sdef.Body.EndTok, sdef)); } else { return def; } } Tuple<LiteralExpr, SyntaxContainer> currBlock = blocks.First(); blocks = blocks.Skip(1).ToList(); IToken tok = matchee.tok; IToken endtok = matchee.tok; Expression guard = new BinaryExpr(tok, BinaryExpr.Opcode.Eq, matchee, currBlock.Item1); var elsC = MakeIfFromContainers(mti, context, matchee, blocks, def); if (currBlock.Item2 is CExpr) { var item2 = (CExpr)currBlock.Item2; if (elsC is null) { // handle an empty default // assert guard; item2.Body var contextStr = context.FillHole(new IdCtx(string.Format("c:{0}",matchee.Type.ToString()), new List<MatchingContext>())).AbstractAllHoles().ToString(); var errorMessage = new StringLiteralExpr(mti.Tok, string.Format("missing case in match expression: {0} (not all possibilities for constant 'c' in context have been covered)", contextStr), true); var attr = new Attributes("error", new List<Expression>(){ errorMessage }, null); var ag = new AssertStmt(mti.Tok, endtok, new AutoGeneratedExpression(mti.Tok, guard), null, null, attr); return new CExpr(null, new StmtExpr(tok, ag, item2.Body)); } else { var els = (CExpr)elsC; return new CExpr(null, new ITEExpr(tok, false, guard, item2.Body, els.Body)); } } else { var item2 = BlockStmtOfCStmt(tok, endtok, (CStmt)currBlock.Item2); if (elsC is null) { // handle an empty default // assert guard; item2.Body var contextStr = context.FillHole(new IdCtx(string.Format("c:{0}",matchee.Type.ToString()), new List<MatchingContext>())).AbstractAllHoles().ToString(); var errorMessage = new StringLiteralExpr(mti.Tok, string.Format("missing case in match statement: {0} (not all possibilities for constant 'c' have been covered)", contextStr), true); var attr = new Attributes("error", new List<Expression>(){ errorMessage }, null); var ag = new AssertStmt(mti.Tok, endtok, new AutoGeneratedExpression(mti.Tok, guard), null, null, attr); var body = new List<Statement>(); body.Add(ag); body.AddRange(item2.Body); return new CStmt(null, new BlockStmt(tok, endtok, body)); } else { var els = (CStmt)elsC; return new CStmt(null, new IfStmt(tok, endtok, false, guard, item2, els.Body)); } } } private MatchCase MakeMatchCaseFromContainer(IToken tok, KeyValuePair<string, DatatypeCtor> ctor, List<BoundVar> freshPatBV, SyntaxContainer insideContainer) { MatchCase newMatchCase; if (insideContainer is CStmt) { List<Statement> insideBranch = UnboxStmtContainer(insideContainer); newMatchCase = new MatchCaseStmt(tok, ctor.Value, freshPatBV, insideBranch); } else { var insideBranch = ((CExpr)insideContainer).Body; newMatchCase = new MatchCaseExpr(tok, ctor.Value, freshPatBV, insideBranch); } newMatchCase.Ctor = ctor.Value; return newMatchCase; } private BoundVar CreatePatBV(IToken oldtok , Type subtype, ICodeContext codeContext) { var tok = oldtok; var name = FreshTempVarName("_mcc#", codeContext); var type = new InferredTypeProxy(); var err = new TypeConstraint.ErrorMsgWithToken(oldtok, "the declared type of the formal ({0}) does not agree with the corresponding type in the constructor's signature ({1})", type, subtype, name); ConstrainSubtypeRelation(type, subtype, err); return new BoundVar(tok, name, type); } private IdPattern CreateFreshId(IToken oldtok , Type subtype, ICodeContext codeContext, bool isGhost = false) { var tok = oldtok; var name = FreshTempVarName("_mcc#", codeContext); var type = new InferredTypeProxy(); var err = new TypeConstraint.ErrorMsgWithToken(oldtok, "the declared type of the formal ({0}) does not agree with the corresponding type in the constructor's signature ({1})", type, subtype, name); ConstrainSubtypeRelation(type, subtype, err); return new IdPattern(tok, name, type, null, isGhost); } private void PrintRBranches(MatchingContext context, List<Expression> matchees, List<RBranch> branches) { Console.WriteLine("\t=-------="); Console.WriteLine("\tCurrent context:"); Console.WriteLine("\t> {0}", context.ToString()); Console.WriteLine("\tCurrent matchees:"); foreach(Expression matchee in matchees) { Console.WriteLine("\t> {0}", Printer.ExprToString(matchee)); } Console.WriteLine("\tCurrent branches:"); foreach(RBranch branch in branches) { Console.WriteLine(branch.ToString()); } Console.WriteLine("\t-=======-"); } /* * Implementation of case 3** (some of the head patterns are constants) of pattern-match compilation * PairPB contains, for each branches, its head pattern and the rest of the branch. */ private SyntaxContainer CompileRBranchConstant(MatchTempInfo mti, MatchingContext context, Expression currMatchee, List<Expression> matchees, List<Tuple<ExtendedPattern, RBranch>> pairPB) { // Decreate the count for each branch (increases back for each occurence later on) foreach (var PB in pairPB) { mti.UpdateBranchID(PB.Item2.BranchID, -1); } // Create a list of alternatives List<LiteralExpr> alternatives = new List<LiteralExpr>(); foreach (var PB in pairPB) { var pat = PB.Item1; LiteralExpr lit = null; if (pat is LitPattern lpat) { lit = lpat.OptimisticallyDesugaredLit; } else if (pat is IdPattern id && id.ResolvedLit != null) { lit = id.ResolvedLit; } if (lit != null && !alternatives.Exists(x => object.Equals(x.Value,lit.Value))) { alternatives.Add(lit); } } List<Tuple<LiteralExpr, SyntaxContainer>> currBlocks = new List<Tuple<LiteralExpr, SyntaxContainer>>(); // For each possible alternatives, filter potential cases and recur foreach (var currLit in alternatives) { List<RBranch> currBranches = new List<RBranch>(); foreach (var PB in pairPB) { var pat = PB.Item1; LiteralExpr lit = null; if (pat is LitPattern lpat) lit = lpat.OptimisticallyDesugaredLit; if (pat is IdPattern id && id.ResolvedLit != null) lit = id.ResolvedLit; if (lit != null) { // if pattern matches the current alternative, add it to the branch for this case, otherwise ignore it if (object.Equals(lit.Value, currLit.Value)) { mti.UpdateBranchID(PB.Item2.BranchID, 1); currBranches.Add(CloneRBranch(PB.Item2)); } } else if (pat is IdPattern currPattern) { // pattern is a bound variable, clone and let-bind the Lit var currBranch = CloneRBranch(PB.Item2); LetBindNonWildCard(currBranch, currPattern, (new Cloner()).CloneExpr(currLit)); mti.UpdateBranchID(PB.Item2.BranchID, 1); currBranches.Add(currBranch); } else { Contract.Assert(false); throw new cce.UnreachableException(); } } // Update the current context MatchingContext newcontext = context.FillHole(new LitCtx(currLit)); // Recur on the current alternative var currBlock = CompileRBranch(mti, newcontext, matchees.Select(x => x).ToList(), currBranches); currBlocks.Add(new Tuple<LiteralExpr, SyntaxContainer>(currLit, currBlock)); } // Create a default case List<RBranch> defaultBranches = new List<RBranch>(); for (int i = 0; i < pairPB.Count; i++) { var PB = pairPB.ElementAt(i); if (PB.Item1 is IdPattern currPattern && currPattern.ResolvedLit == null && currPattern.Arguments == null) { // Pattern is a bound variable, clone and let-bind the Lit var currBranch = CloneRBranch(PB.Item2); LetBindNonWildCard(currBranch, currPattern, currMatchee); mti.UpdateBranchID(PB.Item2.BranchID, 1); defaultBranches.Add(currBranch); } } // defaultBranches.Count check is to avoid adding "missing branches" when default is not present SyntaxContainer defaultBlock = defaultBranches.Count == 0 ? null : CompileRBranch(mti, context.AbstractHole(), matchees.Select(x => x).ToList(), defaultBranches); // Create If-construct joining the alternatives var ifcon = MakeIfFromContainers(mti, context, currMatchee, currBlocks, defaultBlock); return ifcon; } /* * Implementation of case 3 (some of the head patterns are constructors) of pattern-match compilation * Current matchee is a datatype (with type parameter substitution in subst) with constructors in ctors * PairPB contains, for each branches, its head pattern and the rest of the branch. */ private SyntaxContainer CompileRBranchConstructor(MatchTempInfo mti, MatchingContext context, Expression currMatchee, Dictionary<TypeParameter, Type> subst, Dictionary<string, DatatypeCtor> ctors, List<Expression> matchees, List<Tuple<ExtendedPattern, RBranch>> pairPB) { var newMatchCases = new List<MatchCase>(); // Update mti -> each branch generates up to |ctors| copies of itself foreach (var PB in pairPB) { mti.UpdateBranchID(PB.Item2.BranchID, ctors.Count() - 1); } foreach (var ctor in ctors) { if (mti.Debug) Console.WriteLine("DEBUG: ===[3]>>>> Ctor {0}", ctor.Key); var currBranches = new List<RBranch>(); // create a bound variable for each formal to use in the MatchCase for this constructor // using the currMatchee.tok to get a location closer to the error if something goes wrong var freshPatBV = ctor.Value.Formals.ConvertAll( x => CreatePatBV(currMatchee.tok, SubstType(x.Type, subst), mti.CodeContext)); // rhs to bind to head-patterns that are bound variables var rhsExpr = currMatchee; // -- filter branches for each constructor for (int i = 0; i < pairPB.Count; i++) { var PB = pairPB.ElementAt(i); if (PB.Item1 is IdPattern currPattern) { if (ctor.Key.Equals(currPattern.Id) && currPattern.Arguments != null) { // ==[3.1]== If pattern is same constructor, push the arguments as patterns and add that branch to new match // After making sure the constructor is applied to the right number of arguments var currBranch = CloneRBranch(PB.Item2); if (!(currPattern.Arguments.Count.Equals(ctor.Value.Formals.Count))) { reporter.Error(MessageSource.Resolver, mti.BranchTok[PB.Item2.BranchID], "constructor {0} of arity {1} is applied to {2} argument(s)", ctor.Key, ctor.Value.Formals.Count, currPattern.Arguments.Count); } for (int j = 0; j < currPattern.Arguments.Count; j++) { // mark patterns standing in for ghost field currPattern.Arguments[j].IsGhost = currPattern.Arguments[j].IsGhost || ctor.Value.Formals[j].IsGhost; } currBranch.Patterns.InsertRange(0, currPattern.Arguments); currBranches.Add(currBranch); } else if (ctors.ContainsKey(currPattern.Id) && currPattern.Arguments != null) { // ==[3.2]== If the pattern is a different constructor, drop the branch mti.UpdateBranchID(PB.Item2.BranchID, -1); } else if (currPattern.ResolvedLit != null) { // TODO } else { // ==[3.3]== If the pattern is a bound variable, create new bound variables for each of the arguments of the constructor, and let-binds the matchee as original bound variable // n.b. this may duplicate the matchee // make sure this potential bound var is not applied to anything, in which case it is likely a mispelled constructor if (currPattern.Arguments != null && currPattern.Arguments.Count != 0) { reporter.Error(MessageSource.Resolver, mti.BranchTok[PB.Item2.BranchID], "bound variable {0} applied to {1} argument(s).", currPattern.Id, currPattern.Arguments.Count); } var currBranch = CloneRBranch(PB.Item2); List<IdPattern> freshArgs = ctor.Value.Formals.ConvertAll(x => CreateFreshId(currPattern.Tok, SubstType(x.Type, subst), mti.CodeContext, x.IsGhost)); currBranch.Patterns.InsertRange(0, freshArgs); LetBindNonWildCard(currBranch, currPattern, rhsExpr); currBranches.Add(currBranch); } } else { Contract.Assert(false); throw new cce.UnreachableException(); } } // Add variables corresponding to the arguments of the current constructor (ctor) to the matchees List<IdentifierExpr> freshMatchees = freshPatBV.ConvertAll(x => new IdentifierExpr(x.tok, x)); List<Expression> cmatchees = matchees.Select(x => x).ToList(); cmatchees.InsertRange(0, freshMatchees); // Update the current context MatchingContext ctorctx = new IdCtx(ctor); MatchingContext newcontext = context.FillHole(ctorctx); var insideContainer = CompileRBranch(mti, newcontext, cmatchees, currBranches); if (insideContainer is null) { // If no branch matches this constructor, drop the case continue; } else { // Otherwise, add the case the new match created at [3] var tok = insideContainer.Tok is null ? currMatchee.tok : insideContainer.Tok; MatchCase newMatchCase = MakeMatchCaseFromContainer(tok, ctor, freshPatBV, insideContainer); newMatchCases.Add(newMatchCase); } } // Generate and pack the right kind of Match if (mti.isStmt) { var newMatchStmt = new MatchStmt(mti.Tok, mti.EndTok, currMatchee, newMatchCases.ConvertAll(x => (MatchCaseStmt)x), true, context); return new CStmt(null, newMatchStmt); } else { var newMatchExpr = new MatchExpr(mti.Tok, currMatchee, newMatchCases.ConvertAll(x => (MatchCaseExpr)x), true, context); return new CExpr(null, newMatchExpr); } } /// <summary> /// Create a decision tree with flattened MatchStmt (or MatchExpr) with disjoint cases and if-constructs /// Start with a list of n matchees and list of m branches, each with n patterns and a body /// 1 - if m = 0, then no original branch exists for the current case, return null /// 2 - if n = 0, return the body of the first branch /// 3** - if the head-matchee is a base type, but some patterns are constants, create if-else construct for one level and recur /// 3 - if some of the head-patterns are constructors (including tuples), create one level of matching at the type of the head-matchee, /// recur for each constructor of that datatype /// 4 - Otherwise, all head-patterns are variables, let-bind the head-matchee as the head-pattern in each of the bodypatterns, /// continue processing the matchees /// </summary> private SyntaxContainer CompileRBranch(MatchTempInfo mti, MatchingContext context, List<Expression> matchees, List<RBranch> branches) { if (mti.Debug) { Console.WriteLine("DEBUG: In CompileRBranch:"); PrintRBranches(context, matchees, branches); } // For each branch, number of matchees (n) is the number of patterns held by the branch if (!branches.TrueForAll(x => matchees.Count == x.Patterns.Count)) { reporter.Error(MessageSource.Resolver, mti.Tok, "Match is malformed, make sure constructors are fully applied"); } if (branches.Count == 0) { // ==[1]== If no branch, then match is not syntactically exhaustive -- return null if (mti.Debug) { Console.WriteLine("DEBUG: ===[1]=== No Branch"); Console.WriteLine("\t{0} Potential exhaustiveness failure on context: {1}", mti.Tok.line, context.AbstractAllHoles().ToString()); } // (Semantics) exhaustiveness is checked by the verifier, so no need for a warning here // reporter.Warning(MessageSource.Resolver, mti.Tok, "non-exhaustive case-statement"); return null; } if (matchees.Count == 0) { // ==[2]== No more matchee to process, return the first branch and decrement the count of dropped branches if (mti.Debug) { Console.WriteLine("DEBUG: ===[2]=== No Matchee"); Console.WriteLine("\treturn Bid:{0}", branches.First().BranchID); } for (int i = 1; i < branches.Count(); i ++) { mti.UpdateBranchID(branches.ElementAt(i).BranchID, -1); } return PackBody(mti.BranchTok[branches.First().BranchID], branches.First()); } // Otherwise, start handling the first matchee Expression currMatchee = matchees.First(); matchees = matchees.Skip(1).ToList(); // Get the datatype of the matchee var currMatcheeType = PartiallyResolveTypeForMemberSelection(currMatchee.tok, currMatchee.Type).NormalizeExpand(); if (currMatcheeType is TypeProxy) { PartiallySolveTypeConstraints(true); } var dtd = currMatcheeType.AsDatatype; // Get all constructors of type matchee var subst = new Dictionary<TypeParameter, Type>(); Dictionary<string, DatatypeCtor> ctors; if (dtd == null) { ctors = null; } else { ctors = datatypeCtors[dtd]; Contract.Assert(ctors != null); // dtd should have been inserted into datatypeCtors during a previous resolution stage subst = TypeSubstitutionMap(dtd.TypeArgs, currMatcheeType.TypeArgs); // Build the type-parameter substitution map for this use of the datatype } // Get the head of each patterns var patternHeads = branches.ConvertAll(new Converter<RBranch, ExtendedPattern>(getPatternHead)); var newBranches = branches.ConvertAll(new Converter<RBranch, RBranch>(dropPatternHead)); var pairPB = patternHeads.Zip(newBranches, (x, y) => new Tuple<ExtendedPattern, RBranch>(x, y)).ToList(); if (ctors != null && patternHeads.Exists(x => x is IdPattern && ((IdPattern)x).Arguments != null && ctors.ContainsKey(((IdPattern)x).Id))) { // ==[3]== If dtd is a datatype and at least one of the pattern is a constructor, create a match on currMatchee if (mti.Debug) Console.WriteLine("DEBUG: ===[3]=== Constructor Case"); return CompileRBranchConstructor(mti, context, currMatchee, subst, ctors, matchees, pairPB); } else if (dtd == null && patternHeads.Exists(x => (x is LitPattern || (x is IdPattern id && id.ResolvedLit != null)))) { // ==[3**]== If dtd is a base type and at least one of the pattern is a constant, create an If-then-else construct on the constant if (mti.Debug) Console.WriteLine("DEBUG: ===[3**]=== Constant Case"); return CompileRBranchConstant(mti, context, currMatchee, matchees, pairPB); } else { // ==[4]== all head patterns are bound variables: if (mti.Debug) Console.WriteLine("DEBUG: ===[4]=== Variable Case"); foreach (Tuple<ExtendedPattern, RBranch> PB in pairPB) { if (!(PB.Item1 is IdPattern)) { Contract.Assert(false); throw new cce.UnreachableException(); // in Variable case with a constant pattern } var currPattern = (IdPattern)PB.Item1; if (currPattern.Arguments != null) { if (dtd == null) { Contract.Assert(false); throw new cce.UnreachableException(); // non-nullary constructors of a non-datatype; } else { reporter.Error(MessageSource.Resolver, currPattern.Tok, "Type mismatch: expected constructor of type {0}. Got {1}.", dtd.Name, currPattern.Id); } } // Optimization: Don't let-bind if name is a wildcard, either in source or generated LetBindNonWildCard(PB.Item2, currPattern, currMatchee); } if (mti.Debug) { Console.WriteLine("DEBUG: return"); } return CompileRBranch(mti, context.AbstractHole(), matchees, pairPB.ToList().ConvertAll(new Converter<Tuple<ExtendedPattern, RBranch>, RBranch>(x => x.Item2))); } } private void CompileNestedMatchExpr(NestedMatchExpr e, ResolveOpts opts) { if (e.ResolvedExpression != null) { //post-resolve, skip return; } if (DafnyOptions.O.MatchCompilerDebug) Console.WriteLine("DEBUG: CompileNestedMatchExpr for match at line {0}", e.tok.line); MatchTempInfo mti = new MatchTempInfo(e.tok, e.Cases.Count(), opts.codeContext, DafnyOptions.O.MatchCompilerDebug); // create Rbranches from MatchCaseExpr and set the branch tokens in mti List<RBranch> branches = new List<RBranch>(); for (int id = 0; id < e.Cases.Count(); id++) { var branch = e.Cases.ElementAt(id); branches.Add(new RBranchExpr(id, branch)); mti.BranchTok[id] = branch.Tok; } List<Expression> matchees = new List<Expression>(); matchees.Add(e.Source); SyntaxContainer rb = CompileRBranch(mti, new HoleCtx(), matchees, branches); if (rb is null) { // Happens only if the match has no cases, create a Match with no cases as resolved expression and let ResolveMatchExpr handle it. e.ResolvedExpression = new MatchExpr(e.tok, (new Cloner()).CloneExpr(e.Source), new List<MatchCaseExpr>(), e.UsesOptionalBraces); } else if (rb is CExpr) { // replace e with desugared expression var newME = ((CExpr)rb).Body; e.ResolvedExpression = newME; for (int id = 0; id < mti.BranchIDCount.Length; id++) { if (mti.BranchIDCount[id] <= 0) { reporter.Warning(MessageSource.Resolver, mti.BranchTok[id], "this branch is redundant "); scope.PushMarker(); CheckLinearNestedMatchCase(e.Source.Type, e.Cases.ElementAt(id), opts); ResolveExpression(e.Cases.ElementAt(id).Body, opts); scope.PopMarker(); } } } else { Contract.Assert(false); throw new cce.UnreachableException(); // Returned container should be a CExpr } if (DafnyOptions.O.MatchCompilerDebug) Console.WriteLine("DEBUG: Done CompileNestedMatchExpr at line {0}", mti.Tok.line); } /// <summary> /// Stmt driver for CompileRBranch /// Input is an unresolved NestedMatchStmt with potentially nested, overlapping patterns /// On output, the NestedMatchStmt has field ResolvedStatement filled with semantically equivalent code /// </summary> private void CompileNestedMatchStmt(NestedMatchStmt s, ResolveOpts opts) { ICodeContext codeContext = opts.codeContext; if (s.ResolvedStatement != null) { //post-resolve, skip return; } if (DafnyOptions.O.MatchCompilerDebug) Console.WriteLine("DEBUG: CompileNestedMatchStmt for match at line {0}", s.Tok.line); // initialize the MatchTempInfo to record position and duplication information about each branch MatchTempInfo mti = new MatchTempInfo(s.Tok, s.EndTok, s.Cases.Count(), codeContext, DafnyOptions.O.MatchCompilerDebug); // create Rbranches from NestedMatchCaseStmt and set the branch tokens in mti List<RBranch> branches = new List<RBranch>(); for (int id = 0; id < s.Cases.Count(); id++) { var branch = s.Cases.ElementAt(id); branches.Add(new RBranchStmt(id, branch)); mti.BranchTok[id] = branch.Tok; } List<Expression> matchees = new List<Expression>(); matchees.Add(s.Source); SyntaxContainer rb = CompileRBranch(mti, new HoleCtx(), matchees, branches); if (rb is null) { // Happens only if the nested match has no cases, create a MatchStmt with no branches. s.ResolvedStatement = new MatchStmt(s.Tok, s.EndTok, (new Cloner()).CloneExpr(s.Source), new List<MatchCaseStmt>(), s.UsesOptionalBraces); } else if (rb is CStmt) { // Resolve s as desugared match s.ResolvedStatement = ((CStmt)rb).Body; for (int id = 0; id < mti.BranchIDCount.Length; id++) { if (mti.BranchIDCount[id] <= 0) { reporter.Warning(MessageSource.Resolver, mti.BranchTok[id], "this branch is redundant"); scope.PushMarker(); CheckLinearNestedMatchCase(s.Source.Type, s.Cases.ElementAt(id), opts); s.Cases.ElementAt(id).Body.ForEach(s => ResolveStatement(s, codeContext)); scope.PopMarker(); } } } else { Contract.Assert(false); throw new cce.UnreachableException(); // Returned container should be a StmtContainer } if (DafnyOptions.O.MatchCompilerDebug) Console.WriteLine("DEBUG: Done CompileNestedMatchStmt at line {0}.", mti.Tok.line); } private void CheckLinearVarPattern(Type type, IdPattern pat, ResolveOpts opts) { if (pat.Arguments != null) { reporter.Error(MessageSource.Resolver, pat.Tok , "member {0} does not exist in type {1}", pat.Id, type); return; } if (scope.FindInCurrentScope(pat.Id) != null) { reporter.Error(MessageSource.Resolver, pat.Tok , "Duplicate parameter name: {0}", pat.Id); } else if (pat.Id.StartsWith("_")) { // Wildcard, ignore return; } else { NameSegment e = new NameSegment(pat.Tok, pat.Id, null); ResolveNameSegment(e, true, null, opts, false, false); if (e.ResolvedExpression == null) { ScopePushAndReport(scope, new BoundVar(pat.Tok, pat.Id, type), "parameter"); } else { // finds in full scope, not just current scope if (e.Resolved is MemberSelectExpr mse) { if (mse.Member.IsStatic && mse.Member is ConstantField cf) { Expression c = cf.Rhs; if (c is LiteralExpr lit) { pat.ResolvedLit = lit; if (type.Equals(e.ResolvedExpression.Type)) { // OK - type is correct } else { // may well be a proxy so add a type constraint ConstrainSubtypeRelation(e.ResolvedExpression.Type, type, pat.Tok, "the type of the pattern ({0}) does not agree with the match expression ({1})", e.ResolvedExpression.Type, type); } } else { reporter.Error(MessageSource.Resolver, pat.Tok , "{0} is not initialized as a constant literal", pat.Id); ScopePushAndReport(scope, new BoundVar(pat.Tok, pat.Id, type), "parameter"); } } else { // Not a static const, so just a variable ScopePushAndReport(scope, new BoundVar(pat.Tok, pat.Id, type), "parameter"); } } else { ScopePushAndReport(scope, new BoundVar(pat.Tok, pat.Id, type), "parameter"); } } } } // pat could be // 1 - An IdPattern (without argument) at base type // 2 - A LitPattern at base type // 3* - An IdPattern at tuple type representing a tuple // 3 - An IdPattern at datatype type representing a constructor of type // 4 - An IdPattern at datatype type with no arguments representing a bound variable private void CheckLinearExtendedPattern(Type type, ExtendedPattern pat, ResolveOpts opts) { if (type == null) { return; } if (!type.IsDatatype) { // Neither tuple nor datatype if (pat is IdPattern id) { if (id.Arguments != null) { // pat is a tuple or constructor if (id.Id.StartsWith(BuiltIns.TupleTypeCtorNamePrefix)) { reporter.Error(MessageSource.Resolver, pat.Tok, $"tuple type does not match type {type.ToString()}"); } else { reporter.Error(MessageSource.Resolver, pat.Tok, $"member {id.Id} does not exist in type {type.ToString()}"); } } else { // pat is a simple variable or a constant /* =[1]= */ CheckLinearVarPattern(type, (IdPattern)pat, opts); } return; } else if (pat is LitPattern) { // pat is a literal /* =[2]= */ return; } else { Contract.Assert(false); throw new cce.UnreachableException(); } } else if (type.AsDatatype is TupleTypeDecl) { var udt = type.NormalizeExpand() as UserDefinedType; if (!(pat is IdPattern)) { reporter.Error(MessageSource.Resolver, pat.Tok, "pattern doesn't correspond to a tuple"); } IdPattern idpat = (IdPattern)pat; if (idpat.Arguments == null) { // simple variable CheckLinearVarPattern(udt, idpat, opts); return; } //We expect the number of arguments in the type of the matchee and the provided pattern to match, except if the pattern is a bound variable if (udt.TypeArgs.Count != idpat.Arguments.Count) { if (idpat.Id.StartsWith(BuiltIns.TupleTypeCtorNamePrefix)) { reporter.Error(MessageSource.Resolver, pat.Tok, $"the case pattern is a {idpat.Arguments.Count}-element tuple, while the match expression is a {udt.TypeArgs.Count}-element tuple"); } else { reporter.Error(MessageSource.Resolver, pat.Tok, $"case pattern {idpat.Id} has {idpat.Arguments.Count} arguments whereas the match expression has {udt.TypeArgs.Count}"); } } var pairTP = udt.TypeArgs.Zip(idpat.Arguments, (x, y) => new Tuple<Type, ExtendedPattern>(x, y)); foreach (var tp in pairTP) { var t = PartiallyResolveTypeForMemberSelection(pat.Tok, tp.Item1).NormalizeExpand(); CheckLinearExtendedPattern(t, tp.Item2, opts); } return; } else { // matching a datatype value if (!(pat is IdPattern)) { reporter.Error(MessageSource.Resolver, pat.Tok , "Constant pattern used in place of datatype"); } IdPattern idpat = (IdPattern) pat; var dtd = type.AsDatatype; Dictionary<string, DatatypeCtor> ctors = datatypeCtors[dtd]; if (ctors == null) { Contract.Assert(false); throw new cce.UnreachableException(); // Datatype not found } DatatypeCtor ctor = null; // Check if the head of the pattern is a constructor or a variable if (ctors.TryGetValue(idpat.Id, out ctor)) { /* =[3]= */ if (ctor != null && idpat.Arguments == null && ctor.Formals.Count == 0) { // nullary constructor without () -- so convert it to a constructor idpat.MakeAConstructor(); } if (idpat.Arguments == null) { // pat is a variable return; } else if (ctor.Formals != null && ctor.Formals.Count == idpat.Arguments.Count) { if (ctor.Formals.Count == 0) { // if nullary constructor return; } else { // if non-nullary constructor var subst = TypeSubstitutionMap(dtd.TypeArgs, type.TypeArgs); var argTypes = ctor.Formals.ConvertAll<Type>(x => SubstType(x.Type, subst)); var pairFA = argTypes.Zip(idpat.Arguments, (x, y) => new Tuple<Type, ExtendedPattern>(x, y)); foreach(var fa in pairFA) { // get DatatypeDecl of Formal, recursive call on argument CheckLinearExtendedPattern(fa.Item1, fa.Item2, opts); } } } else { // else applied to the wrong number of arguments reporter.Error(MessageSource.Resolver, idpat.Tok, "constructor {0} of arity {2} is applied to {1} argument(s)", idpat.Id, (idpat.Arguments == null? 0 : idpat.Arguments.Count), ctor.Formals.Count); } } else { /* =[4]= */ // pattern is a variable OR error (handled in CheckLinearVarPattern) CheckLinearVarPattern(type, idpat, opts); } } } private void CheckLinearNestedMatchCase(Type type, NestedMatchCase mc, ResolveOpts opts) { CheckLinearExtendedPattern(type, mc.Pat, opts); } /* * Ensures that all ExtendedPattern held in NestedMatchCase are linear * Uses provided type to determine if IdPatterns are datatypes (of the provided type) or variables */ private void CheckLinearNestedMatchExpr(Type dtd, NestedMatchExpr me, ResolveOpts opts) { foreach(NestedMatchCaseExpr mc in me.Cases) { scope.PushMarker(); CheckLinearNestedMatchCase(dtd, mc, opts); scope.PopMarker(); } } private void CheckLinearNestedMatchStmt(Type dtd, NestedMatchStmt ms, ResolveOpts opts) { foreach(NestedMatchCaseStmt mc in ms.Cases) { scope.PushMarker(); CheckLinearNestedMatchCase(dtd, mc, opts); scope.PopMarker(); } } void FillInDefaultLoopDecreases(LoopStmt loopStmt, Expression guard, List<Expression> theDecreases, ICallable enclosingMethod) { Contract.Requires(loopStmt != null); Contract.Requires(theDecreases != null); if (theDecreases.Count == 0 && guard != null) { loopStmt.InferredDecreases = true; Expression prefix = null; foreach (Expression guardConjunct in Expression.Conjuncts(guard)) { Expression guess = null; BinaryExpr bin = guardConjunct as BinaryExpr; if (bin != null) { switch (bin.ResolvedOp) { case BinaryExpr.ResolvedOpcode.Lt: case BinaryExpr.ResolvedOpcode.Le: // for A < B and A <= B, use the decreases B - A guess = Expression.CreateSubtract_TypeConvert(bin.E1, bin.E0); break; case BinaryExpr.ResolvedOpcode.Ge: case BinaryExpr.ResolvedOpcode.Gt: // for A >= B and A > B, use the decreases A - B guess = Expression.CreateSubtract_TypeConvert(bin.E0, bin.E1); break; case BinaryExpr.ResolvedOpcode.NeqCommon: if (bin.E0.Type.IsNumericBased()) { // for A != B where A and B are numeric, use the absolute difference between A and B (that is: if A <= B then B-A else A-B) var AminusB = Expression.CreateSubtract_TypeConvert(bin.E0, bin.E1); var BminusA = Expression.CreateSubtract_TypeConvert(bin.E1, bin.E0); var test = Expression.CreateAtMost(bin.E0, bin.E1); guess = Expression.CreateITE(test, BminusA, AminusB); } break; default: break; } } if (guess != null) { if (prefix != null) { // Make the following guess: if prefix then guess else -1 guess = Expression.CreateITE(prefix, guess, Expression.CreateIntLiteral(prefix.tok, -1)); } theDecreases.Add(AutoGeneratedExpression.Create(guess)); break; // ignore any further conjuncts } if (prefix == null) { prefix = guardConjunct; } else { prefix = Expression.CreateAnd(prefix, guardConjunct); } } } if (enclosingMethod is IteratorDecl) { var iter = (IteratorDecl)enclosingMethod; var ie = new IdentifierExpr(loopStmt.Tok, iter.YieldCountVariable.Name); ie.Var = iter.YieldCountVariable; // resolve here ie.Type = iter.YieldCountVariable.Type; // resolve here theDecreases.Insert(0, AutoGeneratedExpression.Create(ie)); loopStmt.InferredDecreases = true; } if (loopStmt.InferredDecreases) { string s = "decreases " + Util.Comma(theDecreases, Printer.ExprToString); reporter.Info(MessageSource.Resolver, loopStmt.Tok, s); } } private void ResolveConcreteUpdateStmt(ConcreteUpdateStatement s, ICodeContext codeContext) { Contract.Requires(codeContext != null); // First, resolve all LHS's and expression-looking RHS's. int errorCountBeforeCheckingLhs = reporter.Count(ErrorLevel.Error); var lhsNameSet = new HashSet<string>(); // used to check for duplicate identifiers on the left (full duplication checking for references and the like is done during verification) foreach (var lhs in s.Lhss) { var ec = reporter.Count(ErrorLevel.Error); ResolveExpression(lhs, new ResolveOpts(codeContext, true)); if (ec == reporter.Count(ErrorLevel.Error)) { if (lhs is SeqSelectExpr && !((SeqSelectExpr)lhs).SelectOne) { reporter.Error(MessageSource.Resolver, lhs, "cannot assign to a range of array elements (try the 'forall' statement)"); } } } // Resolve RHSs if (s is AssignSuchThatStmt) { ResolveAssignSuchThatStmt((AssignSuchThatStmt)s, codeContext); } else if (s is UpdateStmt) { ResolveUpdateStmt((UpdateStmt)s, codeContext, errorCountBeforeCheckingLhs); } else if (s is AssignOrReturnStmt) { ResolveAssignOrReturnStmt((AssignOrReturnStmt)s, codeContext); } else { Contract.Assert(false); throw new cce.UnreachableException(); } ResolveAttributes(s.Attributes, s, new ResolveOpts(codeContext, true)); } /// <summary> /// Resolve the RHSs and entire UpdateStmt (LHSs should already have been checked by the caller). /// errorCountBeforeCheckingLhs is passed in so that this method can determined if any resolution errors were found during /// LHS or RHS checking, because only if no errors were found is update.ResolvedStmt changed. /// </summary> private void ResolveUpdateStmt(UpdateStmt update, ICodeContext codeContext, int errorCountBeforeCheckingLhs) { Contract.Requires(update != null); Contract.Requires(codeContext != null); IToken firstEffectfulRhs = null; MethodCallInformation methodCallInfo = null; var j = 0; foreach (var rhs in update.Rhss) { bool isEffectful; if (rhs is TypeRhs) { var tr = (TypeRhs)rhs; ResolveTypeRhs(tr, update, codeContext); isEffectful = tr.InitCall != null; } else if (rhs is HavocRhs) { isEffectful = false; } else { var er = (ExprRhs)rhs; if (er.Expr is ApplySuffix) { var a = (ApplySuffix)er.Expr; var cRhs = ResolveApplySuffix(a, new ResolveOpts(codeContext, true), true); isEffectful = cRhs != null; methodCallInfo = methodCallInfo ?? cRhs; } else { ResolveExpression(er.Expr, new ResolveOpts(codeContext, true)); isEffectful = false; } } if (isEffectful && firstEffectfulRhs == null) { firstEffectfulRhs = rhs.Tok; } j++; } // figure out what kind of UpdateStmt this is if (firstEffectfulRhs == null) { if (update.Lhss.Count == 0) { Contract.Assert(update.Rhss.Count == 1); // guaranteed by the parser reporter.Error(MessageSource.Resolver, update, "expected method call, found expression"); } else if (update.Lhss.Count != update.Rhss.Count) { reporter.Error(MessageSource.Resolver, update, "the number of left-hand sides ({0}) and right-hand sides ({1}) must match for a multi-assignment", update.Lhss.Count, update.Rhss.Count); } else if (reporter.Count(ErrorLevel.Error) == errorCountBeforeCheckingLhs) { // add the statements here in a sequence, but don't use that sequence later for translation (instead, should translate properly as multi-assignment) for (int i = 0; i < update.Lhss.Count; i++) { var a = new AssignStmt(update.Tok, update.EndTok, update.Lhss[i].Resolved, update.Rhss[i]); update.ResolvedStatements.Add(a); } } } else if (update.CanMutateKnownState) { if (1 < update.Rhss.Count) { reporter.Error(MessageSource.Resolver, firstEffectfulRhs, "cannot have effectful parameter in multi-return statement."); } else { // it might be ok, if it is a TypeRhs Contract.Assert(update.Rhss.Count == 1); if (methodCallInfo != null) { reporter.Error(MessageSource.Resolver, methodCallInfo.Tok, "cannot have method call in return statement."); } else { // we have a TypeRhs Contract.Assert(update.Rhss[0] is TypeRhs); var tr = (TypeRhs)update.Rhss[0]; Contract.Assert(tr.InitCall != null); // there were effects, so this must have been a call. if (tr.CanAffectPreviouslyKnownExpressions) { reporter.Error(MessageSource.Resolver, tr.Tok, "can only have initialization methods which modify at most 'this'."); } else if (reporter.Count(ErrorLevel.Error) == errorCountBeforeCheckingLhs) { var a = new AssignStmt(update.Tok, update.EndTok, update.Lhss[0].Resolved, tr); update.ResolvedStatements.Add(a); } } } } else { // if there was an effectful RHS, that must be the only RHS if (update.Rhss.Count != 1) { reporter.Error(MessageSource.Resolver, firstEffectfulRhs, "an update statement is allowed an effectful RHS only if there is just one RHS"); } else if (methodCallInfo == null) { // must be a single TypeRhs if (update.Lhss.Count != 1) { Contract.Assert(2 <= update.Lhss.Count); // the parser allows 0 Lhss only if the whole statement looks like an expression (not a TypeRhs) reporter.Error(MessageSource.Resolver, update.Lhss[1].tok, "the number of left-hand sides ({0}) and right-hand sides ({1}) must match for a multi-assignment", update.Lhss.Count, update.Rhss.Count); } else if (reporter.Count(ErrorLevel.Error) == errorCountBeforeCheckingLhs) { var a = new AssignStmt(update.Tok, update.EndTok, update.Lhss[0].Resolved, update.Rhss[0]); update.ResolvedStatements.Add(a); } } else if (reporter.Count(ErrorLevel.Error) == errorCountBeforeCheckingLhs) { // a call statement var resolvedLhss = new List<Expression>(); foreach (var ll in update.Lhss) { resolvedLhss.Add(ll.Resolved); } CallStmt a = new CallStmt(methodCallInfo.Tok, update.EndTok, resolvedLhss, methodCallInfo.Callee, methodCallInfo.Args); a.OriginalInitialLhs = update.OriginalInitialLhs; update.ResolvedStatements.Add(a); } } foreach (var a in update.ResolvedStatements) { ResolveStatement(a, codeContext); } } private void ResolveAssignSuchThatStmt(AssignSuchThatStmt s, ICodeContext codeContext) { Contract.Requires(s != null); Contract.Requires(codeContext != null); var lhsSimpleVariables = new HashSet<IVariable>(); foreach (var lhs in s.Lhss) { CheckIsLvalue(lhs.Resolved, codeContext); if (lhs.Resolved is IdentifierExpr ide) { if (lhsSimpleVariables.Contains(ide.Var)) { // syntactically forbid duplicate simple-variables on the LHS reporter.Error(MessageSource.Resolver, lhs, $"variable '{ide.Var.Name}' occurs more than once as left-hand side of :|"); } else { lhsSimpleVariables.Add(ide.Var); } } // to ease in the verification of the existence check, only allow local variables as LHSs if (s.AssumeToken == null && !(lhs.Resolved is IdentifierExpr)) { reporter.Error(MessageSource.Resolver, lhs, "an assign-such-that statement (without an 'assume' clause) currently only supports local-variable LHSs"); } } ResolveExpression(s.Expr, new ResolveOpts(codeContext, true)); ConstrainTypeExprBool(s.Expr, "type of RHS of assign-such-that statement must be boolean (got {0})"); } private Expression VarDotMethod(IToken tok, string varname, string methodname) { return new ApplySuffix(tok, new ExprDotName(tok, new IdentifierExpr(tok, varname), methodname, null), new List<Expression>() { }); } private Expression makeTemp(String prefix, AssignOrReturnStmt s, ICodeContext codeContext, Expression ex) { var temp = FreshTempVarName(prefix, codeContext); var locvar = new LocalVariable(s.Tok, s.Tok, temp, ex.Type, false); var id = new IdentifierExpr(s.Tok, temp); var idlist = new List<Expression>() { id }; var lhss = new List<LocalVariable>() { locvar }; var rhss = new List<AssignmentRhs>() { new ExprRhs(ex) }; var up = new UpdateStmt(s.Tok, s.Tok, idlist, rhss); s.ResolvedStatements.Add(new VarDeclStmt(s.Tok, s.Tok, lhss, up)); return id; } /// <summary> /// Desugars "y, ... :- MethodOrExpression" into /// var temp; /// temp, ... := MethodOrExpression; /// if temp.IsFailure() { return temp.PropagateFailure(); } /// y := temp.Extract(); /// /// If the type of MethodExpression does not have an Extract, then the desugaring is /// var temp; /// temp, y, ... := MethodOrExpression; /// if temp.IsFailure() { return temp.PropagateFailure(); } /// /// If there are multiple RHSs then "y, ... :- Expression, ..." becomes /// var temp; /// temp, ... := Expression, ...; /// if temp.IsFailure() { return temp.PropagateFailure(); } /// y := temp.Extract(); /// OR /// var temp; /// temp, y, ... := Expression, ...; /// if temp.IsFailure() { return temp.PropagateFailure(); } /// /// and "y, ... :- expect MethodOrExpression, ..." into /// var temp, [y, ] ... := MethodOrExpression, ...; /// expect !temp.IsFailure(), temp.PropagateFailure(); /// [y := temp.Extract();] /// /// and saves the result into s.ResolvedStatements. /// </summary> private void ResolveAssignOrReturnStmt(AssignOrReturnStmt s, ICodeContext codeContext) { // TODO Do I have any responsibilities regarding the use of codeContext? Is it mutable? // We need to figure out whether we are using a status type that has Extract or not, // as that determines how the AssignOrReturnStmt is desugared. Thus if the Rhs is a // method call we need to know which one (to inspect its first output); if RHs is a // list of expressions, we need to know the type of the first one. For all of this we have // to do some partial type resolution. bool expectExtract = s.Lhss.Count != 0; // default value if we cannot determine and inspect the type Type firstType = null; Method call = null; if (s.Rhss != null && s.Rhss.Count != 0) { ResolveExpression(s.Rhs, new ResolveOpts(codeContext, true)); firstType = s.Rhs.Type; } else if (s.Rhs is ApplySuffix asx) { ResolveApplySuffix(asx, new ResolveOpts(codeContext, true), true); call = (asx.Lhs.Resolved as MemberSelectExpr)?.Member as Method; if (call != null) { // We're looking at a method call if (call.Outs.Count != 0) { firstType = call.Outs[0].Type; } else { reporter.Error(MessageSource.Resolver, s.Rhs.tok, "Expected {0} to have a Success/Failure output value", call.Name); } } else { // We're looking at a call to a function. Treat it like any other expression. firstType = asx.Type; } } else { ResolveExpression(s.Rhs, new ResolveOpts(codeContext, true)); firstType = s.Rhs.Type; } if ((codeContext as Method).Outs.Count == 0 && s.KeywordToken == null) { reporter.Error(MessageSource.Resolver, s.Tok, "A method containing a :- statement must have an out-parameter ({0})", (codeContext as Method).Name); return; } if (firstType != null) { firstType = PartiallyResolveTypeForMemberSelection(s.Rhs.tok, firstType); if (firstType.AsTopLevelTypeWithMembers != null) { if (firstType.AsTopLevelTypeWithMembers.Members.Find(x => x.Name == "IsFailure") == null) { reporter.Error(MessageSource.Resolver, s.Tok, "member IsFailure does not exist in {0}, in :- statement", firstType); return; } expectExtract = firstType.AsTopLevelTypeWithMembers.Members.Find(x => x.Name == "Extract") != null; if (expectExtract && call == null && s.Lhss.Count != 1 + s.Rhss.Count) { reporter.Error(MessageSource.Resolver, s.Tok, "number of lhs ({0}) must match number of rhs ({1}) for a rhs type ({2}) with member Extract", s.Lhss.Count, 1 + s.Rhss.Count, firstType); return; } else if (expectExtract && call != null && s.Lhss.Count != call.Outs.Count) { reporter.Error(MessageSource.Resolver, s.Tok, "wrong number of method result arguments (got {0}, expected {1}) for a rhs type ({2}) with member Extract", s.Lhss.Count, call.Outs.Count, firstType); return; } else if (!expectExtract && call == null && s.Lhss.Count != s.Rhss.Count){ reporter.Error(MessageSource.Resolver, s.Tok, "number of lhs ({0}) must be one less than number of rhs ({1}) for a rhs type ({2}) without member Extract", s.Lhss.Count, 1+s.Rhss.Count, firstType); return; } else if (!expectExtract && call != null && s.Lhss.Count != call.Outs.Count - 1){ reporter.Error(MessageSource.Resolver, s.Tok, "wrong number of method result arguments (got {0}, expected {1}) for a rhs type ({2}) without member Extract", s.Lhss.Count, call.Outs.Count-1, firstType); return; } } else { reporter.Error(MessageSource.Resolver, s.Tok, "The type of the first expression is not a failure type in :- statement"); return; } } else { reporter.Error(MessageSource.Resolver, s.Tok, "Internal Error: Unknown failure type in :- statement"); return; } Expression lhsExtract = null; if (expectExtract) { Method caller = codeContext as Method; if (caller != null && caller.Outs.Count == 0 && s.KeywordToken == null) { reporter.Error(MessageSource.Resolver, s.Rhs.tok, "Expected {0} to have a Success/Failure output value", caller.Name); return; } lhsExtract = s.Lhss[0]; var lhsResolved = s.Lhss[0].Resolved; // Make a new unresolved expression if (lhsResolved is MemberSelectExpr lexr) { Expression id = makeTemp("recv", s, codeContext, lexr.Obj); var lex = lhsExtract as ExprDotName; // might be just a NameSegment lhsExtract = new ExprDotName(lexr.tok, id, lexr.MemberName, lex == null ? null : lex.OptTypeArguments); } else if (lhsResolved is SeqSelectExpr lseq) { if (!lseq.SelectOne || lseq.E0 == null) { reporter.Error(MessageSource.Resolver, s.Tok, "Element ranges not allowed as l-values"); return; } Expression id = makeTemp("recv", s, codeContext, lseq.Seq); Expression id0 = id0 = makeTemp("idx", s, codeContext, lseq.E0); lhsExtract = new SeqSelectExpr(lseq.tok, lseq.SelectOne, id, id0, null); lhsExtract.Type = lseq.Type; } else if (lhsResolved is MultiSelectExpr lmulti) { Expression id = makeTemp("recv", s, codeContext, lmulti.Array); var idxs = new List<Expression>(); foreach (var i in lmulti.Indices) { Expression idx = makeTemp("idx", s, codeContext, i); idxs.Add(idx); } lhsExtract = new MultiSelectExpr(lmulti.tok, id, idxs); lhsExtract.Type = lmulti.Type; } else if (lhsResolved is IdentifierExpr) { // do nothing } else { Contract.Assert(false, "Internal error: unexpected option in ResolveAssignOrReturnStmt"); } } var temp = FreshTempVarName("valueOrError", codeContext); var lhss = new List<LocalVariable>() { new LocalVariable(s.Tok, s.Tok, temp, new InferredTypeProxy(), false) }; // "var temp ;" s.ResolvedStatements.Add(new VarDeclStmt(s.Tok, s.Tok, lhss, null)); var lhss2 = new List<Expression>() { new IdentifierExpr(s.Tok, temp) }; for (int k = (expectExtract?1:0); k < s.Lhss.Count; ++k) { lhss2.Add(s.Lhss[k]); } List<AssignmentRhs> rhss2 = new List<AssignmentRhs>() {new ExprRhs(s.Rhs)}; if (s.Rhss != null) { s.Rhss.ForEach(e => rhss2.Add(e)); } if (s.Rhss != null && s.Rhss.Count > 0) { if (lhss2.Count != rhss2.Count) { reporter.Error(MessageSource.Resolver, s.Tok, "Mismatch in expected number of LHSs and RHSs"); if (lhss2.Count < rhss2.Count) { rhss2.RemoveRange(lhss2.Count, rhss2.Count - lhss2.Count); } else { lhss2.RemoveRange(rhss2.Count, lhss2.Count - rhss2.Count); } } } // " temp, ... := MethodOrExpression, ...;" UpdateStmt up = new UpdateStmt(s.Tok, s.Tok, lhss2, rhss2); if (expectExtract) { up.OriginalInitialLhs = s.Lhss.Count == 0 ? null : s.Lhss[0]; } s.ResolvedStatements.Add(up); if (s.KeywordToken != null) { var notFailureExpr = new UnaryOpExpr(s.Tok, UnaryOpExpr.Opcode.Not, VarDotMethod(s.Tok, temp, "IsFailure")); Statement ss = null; if (s.KeywordToken.val == "expect") { // "expect !temp.IsFailure(), temp" ss = new ExpectStmt(s.Tok, s.Tok, notFailureExpr, new IdentifierExpr(s.Tok, temp), null); } else if (s.KeywordToken.val == "assume") { ss = new AssumeStmt(s.Tok, s.Tok, notFailureExpr, null); } else if (s.KeywordToken.val == "assert") { ss = new AssertStmt(s.Tok, s.Tok, notFailureExpr, null, null, null); } else { Contract.Assert(false,$"Invalid token in :- statement: {s.KeywordToken.val}"); } s.ResolvedStatements.Add(ss); } else { var enclosingOutParameter = ((Method)codeContext).Outs[0]; var ident = new IdentifierExpr(s.Tok, enclosingOutParameter.Name); // resolve it here to avoid capture into more closely declared local variables Contract.Assert(enclosingOutParameter.Type != null); // this confirms our belief that the out-parameter has already been resolved ident.Var = enclosingOutParameter; ident.Type = ident.Var.Type; s.ResolvedStatements.Add( // "if temp.IsFailure()" new IfStmt(s.Tok, s.Tok, false, VarDotMethod(s.Tok, temp, "IsFailure"), // THEN: { out := temp.PropagateFailure(); return; } new BlockStmt(s.Tok, s.Tok, new List<Statement>() { new UpdateStmt(s.Tok, s.Tok, new List<Expression>() { ident }, new List<AssignmentRhs>() {new ExprRhs(VarDotMethod(s.Tok, temp, "PropagateFailure"))} ), new ReturnStmt(s.Tok, s.Tok, null), }), // ELSE: no else block null )); } if (expectExtract) { // "y := temp.Extract();" var lhs = s.Lhss[0]; s.ResolvedStatements.Add( new UpdateStmt(s.Tok, s.Tok, new List<Expression>() { lhsExtract }, new List<AssignmentRhs>() { new ExprRhs(VarDotMethod(s.Tok, temp, "Extract")) } )); // The following check is not necessary, because the ghost mismatch is caught later. // However the error message here is much clearer. var m = ResolveMember(s.Tok, firstType, "Extract", out _); if (m != null && m.IsGhost && !AssignStmt.LhsIsToGhostOrAutoGhost(lhs)) { reporter.Error(MessageSource.Resolver, lhs.tok, "The Extract member may not be ghost unless the initial LHS is ghost"); } } s.ResolvedStatements.ForEach( a => ResolveStatement(a, codeContext) ); EnsureSupportsErrorHandling(s.Tok, firstType, expectExtract, s.KeywordToken != null); } private void EnsureSupportsErrorHandling(IToken tok, Type tp, bool expectExtract, bool hasKeywordToken) { // The "method not found" errors which will be generated here were already reported while // resolving the statement, so we don't want them to reappear and redirect them into a sink. var origReporter = this.reporter; this.reporter = new ErrorReporterSink(); if (hasKeywordToken) { if (ResolveMember(tok, tp, "IsFailure", out _) == null || (ResolveMember(tok, tp, "Extract", out _) != null) != expectExtract) { // more details regarding which methods are missing have already been reported by regular resolution origReporter.Error(MessageSource.Resolver, tok, "The right-hand side of ':-', which is of type '{0}', with a keyword token must have members 'IsFailure()', {1} 'Extract()'", tp, expectExtract ? "and" : "but not"); } } else { if (ResolveMember(tok, tp, "IsFailure", out _) == null || ResolveMember(tok, tp, "PropagateFailure", out _) == null || (ResolveMember(tok, tp, "Extract", out _) != null) != expectExtract) { // more details regarding which methods are missing have already been reported by regular resolution origReporter.Error(MessageSource.Resolver, tok, "The right-hand side of ':-', which is of type '{0}', must have members 'IsFailure()', 'PropagateFailure()', {1} 'Extract()'", tp, expectExtract ? "and" : "but not"); } } // The following checks are not necessary, because the ghost mismatch is caught later. // However the error messages here are much clearer. var m = ResolveMember(tok, tp, "IsFailure", out _); if (m != null && m.IsGhost) { origReporter.Error(MessageSource.Resolver, tok, $"The IsFailure member may not be ghost (type {tp} used in :- statement)"); } m = ResolveMember(tok, tp, "PropagateFailure", out _); if (!hasKeywordToken && m != null && m.IsGhost) { origReporter.Error(MessageSource.Resolver, tok, $"The PropagateFailure member may not be ghost (type {tp} used in :- statement)"); } this.reporter = origReporter; } void ResolveAlternatives(List<GuardedAlternative> alternatives, AlternativeLoopStmt loopToCatchBreaks, ICodeContext codeContext) { Contract.Requires(alternatives != null); Contract.Requires(codeContext != null); // first, resolve the guards foreach (var alternative in alternatives) { int prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveExpression(alternative.Guard, new ResolveOpts(codeContext, true)); Contract.Assert(alternative.Guard.Type != null); // follows from postcondition of ResolveExpression bool successfullyResolved = reporter.Count(ErrorLevel.Error) == prevErrorCount; ConstrainTypeExprBool(alternative.Guard, "condition is expected to be of type bool, but is {0}"); } if (loopToCatchBreaks != null) { loopStack.Add(loopToCatchBreaks); // push } foreach (var alternative in alternatives) { scope.PushMarker(); dominatingStatementLabels.PushMarker(); if (alternative.IsBindingGuard) { var exists = (ExistsExpr)alternative.Guard; foreach (var v in exists.BoundVars) { ScopePushAndReport(scope, v, "bound-variable"); } } foreach (Statement ss in alternative.Body) { ResolveStatement(ss, codeContext); } dominatingStatementLabels.PopMarker(); scope.PopMarker(); } if (loopToCatchBreaks != null) { loopStack.RemoveAt(loopStack.Count - 1); // pop } } /// <summary> /// Resolves the given call statement. /// Assumes all LHSs have already been resolved (and checked for mutability). /// </summary> void ResolveCallStmt(CallStmt s, ICodeContext codeContext, Type receiverType) { Contract.Requires(s != null); Contract.Requires(codeContext != null); bool isInitCall = receiverType != null; var callee = s.Method; Contract.Assert(callee != null); // follows from the invariant of CallStmt if (!isInitCall && callee is Constructor) { reporter.Error(MessageSource.Resolver, s, "a constructor is allowed to be called only when an object is being allocated"); } // resolve left-hand sides foreach (var lhs in s.Lhs) { Contract.Assume(lhs.Type != null); // a sanity check that LHSs have already been resolved } // resolve arguments int j = 0; foreach (Expression e in s.Args) { ResolveExpression(e, new ResolveOpts(codeContext, true)); j++; } bool tryToResolve = false; if (callee.Ins.Count != s.Args.Count) { reporter.Error(MessageSource.Resolver, s, "wrong number of method arguments (got {0}, expected {1})", s.Args.Count, callee.Ins.Count); } else if (callee.Outs.Count != s.Lhs.Count) { if (isInitCall) { reporter.Error(MessageSource.Resolver, s, "a method called as an initialization method must not have any result arguments"); } else { reporter.Error(MessageSource.Resolver, s, "wrong number of method result arguments (got {0}, expected {1})", s.Lhs.Count, callee.Outs.Count); tryToResolve = true; } } else { if (isInitCall) { if (callee.IsStatic) { reporter.Error(MessageSource.Resolver, s.Tok, "a method called as an initialization method must not be 'static'"); } else { tryToResolve = true; } } else if (!callee.IsStatic) { if (!scope.AllowInstance && s.Receiver is ThisExpr) { // The call really needs an instance, but that instance is given as 'this', which is not // available in this context. For more details, see comment in the resolution of a // FunctionCallExpr. reporter.Error(MessageSource.Resolver, s.Receiver, "'this' is not allowed in a 'static' context"); } else if (s.Receiver is StaticReceiverExpr) { reporter.Error(MessageSource.Resolver, s.Receiver, "call to instance method requires an instance"); } else { tryToResolve = true; } } else { tryToResolve = true; } } if (tryToResolve) { // type check the arguments var subst = s.MethodSelect.TypeArgumentSubstitutionsAtMemberDeclaration(); for (int i = 0; i < callee.Ins.Count; i++) { var it = callee.Ins[i].Type; Type st = SubstType(it, subst); AddAssignableConstraint(s.Tok, st, s.Args[i].Type, "incorrect type of method in-parameter" + (callee.Ins.Count == 1 ? "" : " " + i) + " (expected {0}, got {1})"); } for (int i = 0; i < callee.Outs.Count && i < s.Lhs.Count; i++) { var it = callee.Outs[i].Type; Type st = SubstType(it, subst); var lhs = s.Lhs[i]; AddAssignableConstraint(s.Tok, lhs.Type, st, "incorrect type of method out-parameter" + (callee.Outs.Count == 1 ? "" : " " + i) + " (expected {1}, got {0})"); } for (int i = 0; i < s.Lhs.Count; i++) { var lhs = s.Lhs[i]; // LHS must denote a mutable field. CheckIsLvalue(lhs.Resolved, codeContext); } // Resolution termination check ModuleDefinition callerModule = codeContext.EnclosingModule; ModuleDefinition calleeModule = ((ICodeContext)callee).EnclosingModule; if (callerModule == calleeModule) { // intra-module call; add edge in module's call graph var caller = codeContext as ICallable; if (caller == null) { // don't add anything to the call graph after all } else if (caller is IteratorDecl) { callerModule.CallGraph.AddEdge(((IteratorDecl)caller).Member_MoveNext, callee); } else { callerModule.CallGraph.AddEdge(caller, callee); if (caller == callee) { callee.IsRecursive = true; // self recursion (mutual recursion is determined elsewhere) } } } } if (Contract.Exists(callee.Decreases.Expressions, e => e is WildcardExpr) && !codeContext.AllowsNontermination) { reporter.Error(MessageSource.Resolver, s.Tok, "a call to a possibly non-terminating method is allowed only if the calling method is also declared (with 'decreases *') to be possibly non-terminating"); } } /// <summary> /// Checks if lhs, which is expected to be a successfully resolved expression, denotes something /// that can be assigned to. In particular, this means that lhs denotes a mutable variable, field, /// or array element. If a violation is detected, an error is reported. /// </summary> void CheckIsLvalue(Expression lhs, ICodeContext codeContext) { Contract.Requires(lhs != null); Contract.Requires(codeContext != null); if (lhs is IdentifierExpr) { var ll = (IdentifierExpr)lhs; if (!ll.Var.IsMutable) { reporter.Error(MessageSource.Resolver, lhs, "LHS of assignment must denote a mutable variable"); } } else if (lhs is MemberSelectExpr) { var ll = (MemberSelectExpr)lhs; var field = ll.Member as Field; if (field == null || !field.IsUserMutable) { var cf = field as ConstantField; if (inBodyInitContext && cf != null && !cf.IsStatic && cf.Rhs == null) { if (Expression.AsThis(ll.Obj) != null) { // it's cool; this field can be assigned to here } else { reporter.Error(MessageSource.Resolver, lhs, "LHS of assignment must denote a mutable field of 'this'"); } } else { reporter.Error(MessageSource.Resolver, lhs, "LHS of assignment must denote a mutable field"); } } } else if (lhs is SeqSelectExpr) { var ll = (SeqSelectExpr)lhs; ConstrainSubtypeRelation(ResolvedArrayType(ll.Seq.tok, 1, new InferredTypeProxy(), codeContext, true), ll.Seq.Type, ll.Seq, "LHS of array assignment must denote an array element (found {0})", ll.Seq.Type); if (!ll.SelectOne) { reporter.Error(MessageSource.Resolver, ll.Seq, "cannot assign to a range of array elements (try the 'forall' statement)"); } } else if (lhs is MultiSelectExpr) { // nothing to check; this can only denote an array element } else { reporter.Error(MessageSource.Resolver, lhs, "LHS of assignment must denote a mutable variable or field"); } } void ResolveBlockStatement(BlockStmt blockStmt, ICodeContext codeContext) { Contract.Requires(blockStmt != null); Contract.Requires(codeContext != null); if (blockStmt is DividedBlockStmt) { var div = (DividedBlockStmt)blockStmt; Contract.Assert(currentMethod is Constructor); // divided bodies occur only in class constructors Contract.Assert(!inBodyInitContext); // divided bodies are never nested inBodyInitContext = true; foreach (Statement ss in div.BodyInit) { ResolveStatementWithLabels(ss, codeContext); } Contract.Assert(inBodyInitContext); inBodyInitContext = false; foreach (Statement ss in div.BodyProper) { ResolveStatementWithLabels(ss, codeContext); } } else { foreach (Statement ss in blockStmt.Body) { ResolveStatementWithLabels(ss, codeContext); } } } void ResolveStatementWithLabels(Statement stmt, ICodeContext codeContext) { Contract.Requires(stmt != null); Contract.Requires(codeContext != null); enclosingStatementLabels.PushMarker(); // push labels for (var l = stmt.Labels; l != null; l = l.Next) { var lnode = l.Data; Contract.Assert(lnode.Name != null); // LabelNode's with .Label==null are added only during resolution of the break statements with 'stmt' as their target, which hasn't happened yet var prev = enclosingStatementLabels.Find(lnode.Name); if (prev == stmt) { reporter.Error(MessageSource.Resolver, lnode.Tok, "duplicate label"); } else if (prev != null) { reporter.Error(MessageSource.Resolver, lnode.Tok, "label shadows an enclosing label"); } else { var r = enclosingStatementLabels.Push(lnode.Name, stmt); Contract.Assert(r == Scope<Statement>.PushResult.Success); // since we just checked for duplicates, we expect the Push to succeed if (dominatingStatementLabels.Find(lnode.Name) != null) { reporter.Error(MessageSource.Resolver, lnode.Tok, "label shadows a dominating label"); } else { var rr = dominatingStatementLabels.Push(lnode.Name, lnode); Contract.Assert(rr == Scope<Label>.PushResult.Success); // since we just checked for duplicates, we expect the Push to succeed } } } ResolveStatement(stmt, codeContext); enclosingStatementLabels.PopMarker(); } /// <summary> /// This method performs some additional checks on the body "stmt" of a forall statement of kind "kind". /// </summary> public void CheckForallStatementBodyRestrictions(Statement stmt, ForallStmt.BodyKind kind) { Contract.Requires(stmt != null); if (stmt is PredicateStmt) { // cool } else if (stmt is RevealStmt) { var s = (RevealStmt)stmt; foreach (var ss in s.ResolvedStatements) { CheckForallStatementBodyRestrictions(ss, kind); } } else if (stmt is PrintStmt) { reporter.Error(MessageSource.Resolver, stmt, "print statement is not allowed inside a forall statement"); } else if (stmt is BreakStmt) { // this case is checked already in the first pass through the forall-statement body, by doing so from an empty set of labeled statements and resetting the loop-stack } else if (stmt is ReturnStmt) { reporter.Error(MessageSource.Resolver, stmt, "return statement is not allowed inside a forall statement"); } else if (stmt is YieldStmt) { reporter.Error(MessageSource.Resolver, stmt, "yield statement is not allowed inside a forall statement"); } else if (stmt is AssignSuchThatStmt) { var s = (AssignSuchThatStmt)stmt; foreach (var lhs in s.Lhss) { CheckForallStatementBodyLhs(lhs.tok, lhs.Resolved, kind); } } else if (stmt is UpdateStmt) { var s = (UpdateStmt)stmt; foreach (var ss in s.ResolvedStatements) { CheckForallStatementBodyRestrictions(ss, kind); } } else if (stmt is VarDeclStmt) { var s = (VarDeclStmt)stmt; if (s.Update != null) { CheckForallStatementBodyRestrictions(s.Update, kind); } } else if (stmt is VarDeclPattern) { // Are we fine? } else if (stmt is AssignStmt) { var s = (AssignStmt)stmt; CheckForallStatementBodyLhs(s.Lhs.tok, s.Lhs.Resolved, kind); var rhs = s.Rhs; // ExprRhs and HavocRhs are fine, but TypeRhs is not if (rhs is TypeRhs) { if (kind == ForallStmt.BodyKind.Assign) { reporter.Error(MessageSource.Resolver, rhs.Tok, "new allocation not supported in forall statements"); } else { reporter.Error(MessageSource.Resolver, rhs.Tok, "new allocation not allowed in ghost context"); } } } else if (stmt is CallStmt) { var s = (CallStmt)stmt; foreach (var lhs in s.Lhs) { CheckForallStatementBodyLhs(lhs.tok, lhs, kind); } if (s.Method.Mod.Expressions.Count != 0) { reporter.Error(MessageSource.Resolver, stmt, "the body of the enclosing forall statement is not allowed to update heap locations, so any call must be to a method with an empty modifies clause"); } if (!s.Method.IsGhost) { // The reason for this restriction is that the compiler is going to omit the forall statement altogether--it has // no effect. However, print effects are not documented, so to make sure that the compiler does not omit a call to // a method that prints something, all calls to non-ghost methods are disallowed. (Note, if this restriction // is somehow lifted in the future, then it is still necessary to enforce s.Method.Mod.Expressions.Count != 0 for // calls to non-ghost methods.) reporter.Error(MessageSource.Resolver, s, "the body of the enclosing forall statement is not allowed to call non-ghost methods"); } } else if (stmt is ModifyStmt) { reporter.Error(MessageSource.Resolver, stmt, "body of forall statement is not allowed to use a modify statement"); } else if (stmt is BlockStmt) { var s = (BlockStmt)stmt; scope.PushMarker(); foreach (var ss in s.Body) { CheckForallStatementBodyRestrictions(ss, kind); } scope.PopMarker(); } else if (stmt is IfStmt) { var s = (IfStmt)stmt; CheckForallStatementBodyRestrictions(s.Thn, kind); if (s.Els != null) { CheckForallStatementBodyRestrictions(s.Els, kind); } } else if (stmt is AlternativeStmt) { var s = (AlternativeStmt)stmt; foreach (var alt in s.Alternatives) { foreach (var ss in alt.Body) { CheckForallStatementBodyRestrictions(ss, kind); } } } else if (stmt is WhileStmt) { WhileStmt s = (WhileStmt)stmt; if (s.Body != null) { CheckForallStatementBodyRestrictions(s.Body, kind); } } else if (stmt is AlternativeLoopStmt) { var s = (AlternativeLoopStmt)stmt; foreach (var alt in s.Alternatives) { foreach (var ss in alt.Body) { CheckForallStatementBodyRestrictions(ss, kind); } } } else if (stmt is ForallStmt) { var s = (ForallStmt)stmt; switch (s.Kind) { case ForallStmt.BodyKind.Assign: reporter.Error(MessageSource.Resolver, stmt, "a forall statement with heap updates is not allowed inside the body of another forall statement"); break; case ForallStmt.BodyKind.Call: case ForallStmt.BodyKind.Proof: // these are fine, since they don't update any non-local state break; default: Contract.Assert(false); // unexpected kind break; } } else if (stmt is CalcStmt) { // cool } else if (stmt is ConcreteSyntaxStatement) { var s = (ConcreteSyntaxStatement)stmt; CheckForallStatementBodyRestrictions(s.ResolvedStatement, kind); } else if (stmt is MatchStmt) { var s = (MatchStmt)stmt; foreach (var kase in s.Cases) { foreach (var ss in kase.Body) { CheckForallStatementBodyRestrictions(ss, kind); } } } else { Contract.Assert(false); throw new cce.UnreachableException(); } } void CheckForallStatementBodyLhs(IToken tok, Expression lhs, ForallStmt.BodyKind kind) { var idExpr = lhs as IdentifierExpr; if (idExpr != null) { if (scope.ContainsDecl(idExpr.Var)) { reporter.Error(MessageSource.Resolver, tok, "body of forall statement is attempting to update a variable declared outside the forall statement"); } } else if (kind != ForallStmt.BodyKind.Assign) { reporter.Error(MessageSource.Resolver, tok, "the body of the enclosing forall statement is not allowed to update heap locations"); } } /// <summary> /// Check that a statment is a valid hint for a calculation. /// ToDo: generalize the part for compound statements to take a delegate? /// </summary> public void CheckHintRestrictions(Statement stmt, ISet<LocalVariable> localsAllowedInUpdates, string where) { Contract.Requires(stmt != null); Contract.Requires(localsAllowedInUpdates != null); Contract.Requires(where != null); if (stmt is PredicateStmt) { // cool } else if (stmt is PrintStmt) { // not allowed in ghost context } else if (stmt is RevealStmt) { var s = (RevealStmt)stmt; foreach (var ss in s.ResolvedStatements) { CheckHintRestrictions(ss, localsAllowedInUpdates, where); } } else if (stmt is BreakStmt) { // already checked while resolving hints } else if (stmt is ReturnStmt) { reporter.Error(MessageSource.Resolver, stmt, "return statement is not allowed inside {0}", where); } else if (stmt is YieldStmt) { reporter.Error(MessageSource.Resolver, stmt, "yield statement is not allowed inside {0}", where); } else if (stmt is AssignSuchThatStmt) { var s = (AssignSuchThatStmt)stmt; foreach (var lhs in s.Lhss) { CheckHintLhs(lhs.tok, lhs.Resolved, localsAllowedInUpdates, where); } } else if (stmt is AssignStmt) { var s = (AssignStmt)stmt; CheckHintLhs(s.Lhs.tok, s.Lhs.Resolved, localsAllowedInUpdates, where); } else if (stmt is CallStmt) { var s = (CallStmt)stmt; if (s.Method.Mod.Expressions.Count != 0) { reporter.Error(MessageSource.Resolver, stmt, "calls to methods with side-effects are not allowed inside {0}", where); } foreach (var lhs in s.Lhs) { CheckHintLhs(lhs.tok, lhs.Resolved, localsAllowedInUpdates, where); } } else if (stmt is UpdateStmt) { var s = (UpdateStmt)stmt; foreach (var ss in s.ResolvedStatements) { CheckHintRestrictions(ss, localsAllowedInUpdates, where); } } else if (stmt is VarDeclStmt) { var s = (VarDeclStmt)stmt; s.Locals.Iter(local => localsAllowedInUpdates.Add(local)); if (s.Update != null) { CheckHintRestrictions(s.Update, localsAllowedInUpdates, where); } } else if (stmt is VarDeclPattern) { // Are we fine? } else if (stmt is ModifyStmt) { reporter.Error(MessageSource.Resolver, stmt, "modify statements are not allowed inside {0}", where); } else if (stmt is BlockStmt) { var s = (BlockStmt)stmt; var newScopeForLocals = new HashSet<LocalVariable>(localsAllowedInUpdates); foreach (var ss in s.Body) { CheckHintRestrictions(ss, newScopeForLocals, where); } } else if (stmt is IfStmt) { var s = (IfStmt)stmt; CheckHintRestrictions(s.Thn, localsAllowedInUpdates, where); if (s.Els != null) { CheckHintRestrictions(s.Els, localsAllowedInUpdates, where); } } else if (stmt is AlternativeStmt) { var s = (AlternativeStmt)stmt; foreach (var alt in s.Alternatives) { foreach (var ss in alt.Body) { CheckHintRestrictions(ss, localsAllowedInUpdates, where); } } } else if (stmt is WhileStmt) { var s = (WhileStmt)stmt; if (s.Mod.Expressions != null && s.Mod.Expressions.Count != 0) { reporter.Error(MessageSource.Resolver, s.Mod.Expressions[0].tok, "a while statement used inside {0} is not allowed to have a modifies clause", where); } if (s.Body != null) { CheckHintRestrictions(s.Body, localsAllowedInUpdates, where); } } else if (stmt is AlternativeLoopStmt) { var s = (AlternativeLoopStmt)stmt; foreach (var alt in s.Alternatives) { foreach (var ss in alt.Body) { CheckHintRestrictions(ss, localsAllowedInUpdates, where); } } } else if (stmt is ForallStmt) { var s = (ForallStmt)stmt; switch (s.Kind) { case ForallStmt.BodyKind.Assign: reporter.Error(MessageSource.Resolver, stmt, "a forall statement with heap updates is not allowed inside {0}", where); break; case ForallStmt.BodyKind.Call: case ForallStmt.BodyKind.Proof: // these are fine, since they don't update any non-local state break; default: Contract.Assert(false); // unexpected kind break; } } else if (stmt is CalcStmt) { // cool } else if (stmt is MatchStmt) { var s = (MatchStmt)stmt; foreach (var kase in s.Cases) { foreach (var ss in kase.Body) { CheckHintRestrictions(ss, localsAllowedInUpdates, where); } } } else { Contract.Assert(false); throw new cce.UnreachableException(); } } void CheckHintLhs(IToken tok, Expression lhs, ISet<LocalVariable> localsAllowedInUpdates, string where) { Contract.Requires(tok != null); Contract.Requires(lhs != null); Contract.Requires(localsAllowedInUpdates != null); Contract.Requires(where != null); var idExpr = lhs as IdentifierExpr; if (idExpr == null) { reporter.Error(MessageSource.Resolver, tok, "{0} is not allowed to update heap locations", where); } else if (!localsAllowedInUpdates.Contains(idExpr.Var)) { reporter.Error(MessageSource.Resolver, tok, "{0} is not allowed to update a variable it doesn't declare", where); } } Type ResolveTypeRhs(TypeRhs rr, Statement stmt, ICodeContext codeContext) { Contract.Requires(rr != null); Contract.Requires(stmt != null); Contract.Requires(codeContext != null); Contract.Ensures(Contract.Result<Type>() != null); if (rr.Type == null) { if (rr.ArrayDimensions != null) { // ---------- new T[EE] OR new T[EE] (elementInit) Contract.Assert(rr.Arguments == null && rr.Path == null && rr.InitCall == null); ResolveType(stmt.Tok, rr.EType, codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); int i = 0; foreach (Expression dim in rr.ArrayDimensions) { Contract.Assert(dim != null); ResolveExpression(dim, new ResolveOpts(codeContext, false)); ConstrainToIntegerType(dim, false, string.Format("new must use an integer-based expression for the array size (got {{0}}{0})", rr.ArrayDimensions.Count == 1 ? "" : " for index " + i)); i++; } rr.Type = ResolvedArrayType(stmt.Tok, rr.ArrayDimensions.Count, rr.EType, codeContext, false); if (rr.ElementInit != null) { ResolveExpression(rr.ElementInit, new ResolveOpts(codeContext, false)); // Check // int^N -> rr.EType :> rr.ElementInit.Type builtIns.CreateArrowTypeDecl(rr.ArrayDimensions.Count); // TODO: should this be done already in the parser? var args = new List<Type>(); for (int ii = 0; ii < rr.ArrayDimensions.Count; ii++) { args.Add(builtIns.Nat()); } var arrowType = new ArrowType(rr.ElementInit.tok, builtIns.ArrowTypeDecls[rr.ArrayDimensions.Count], args, rr.EType); var lambdaType = rr.ElementInit.Type.AsArrowType; if (lambdaType != null && lambdaType.TypeArgs[0] is InferredTypeProxy) { (lambdaType.TypeArgs[0] as InferredTypeProxy).KeepConstraints = true; } string underscores; if (rr.ArrayDimensions.Count == 1) { underscores = "_"; } else { underscores = "(" + Util.Comma(rr.ArrayDimensions.Count, x => "_") + ")"; } var hintString = string.Format(" (perhaps write '{0} =>' in front of the expression you gave in order to make it an arrow type)", underscores); ConstrainSubtypeRelation(arrowType, rr.ElementInit.Type, rr.ElementInit, "array-allocation initialization expression expected to have type '{0}' (instead got '{1}'){2}", arrowType, rr.ElementInit.Type, new LazyString_OnTypeEquals(rr.EType, rr.ElementInit.Type, hintString)); } else if (rr.InitDisplay != null) { foreach (var v in rr.InitDisplay) { ResolveExpression(v, new ResolveOpts(codeContext, false)); AddAssignableConstraint(v.tok, rr.EType, v.Type, "initial value must be assignable to array's elements (expected '{0}', got '{1}')"); } } } else { bool callsConstructor = false; if (rr.Arguments == null) { ResolveType(stmt.Tok, rr.EType, codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); var cl = (rr.EType as UserDefinedType)?.ResolvedClass as NonNullTypeDecl; if (cl != null && !(rr.EType.IsTraitType && !rr.EType.NormalizeExpand().IsObjectQ)) { // life is good } else { reporter.Error(MessageSource.Resolver, stmt, "new can be applied only to class types (got {0})", rr.EType); } } else { string initCallName = null; IToken initCallTok = null; // Resolve rr.Path and do one of three things: // * If rr.Path denotes a type, then set EType,initCallName to rr.Path,"_ctor", which sets up a call to the anonymous constructor. // * If the all-but-last components of rr.Path denote a type, then do EType,initCallName := allButLast(EType),last(EType) // * Otherwise, report an error var ret = ResolveTypeLenient(rr.Tok, rr.Path, codeContext, new ResolveTypeOption(ResolveTypeOptionEnum.InferTypeProxies), null, true); if (ret != null) { // The all-but-last components of rr.Path denote a type (namely, ret.ReplacementType). rr.EType = ret.ReplacementType; initCallName = ret.LastComponent.SuffixName; initCallTok = ret.LastComponent.tok; } else { // Either rr.Path resolved correctly as a type or there was no way to drop a last component to make it into something that looked // like a type. In either case, set EType,initCallName to Path,"_ctor" and continue. rr.EType = rr.Path; initCallName = "_ctor"; initCallTok = rr.Tok; } var cl = (rr.EType as UserDefinedType)?.ResolvedClass as NonNullTypeDecl; if (cl == null || rr.EType.IsTraitType) { reporter.Error(MessageSource.Resolver, stmt, "new can be applied only to class types (got {0})", rr.EType); } else { // ---------- new C.Init(EE) Contract.Assert(initCallName != null); var prevErrorCount = reporter.Count(ErrorLevel.Error); // We want to create a MemberSelectExpr for the initializing method. To do that, we create a throw-away receiver of the appropriate // type, create an dot-suffix expression around this receiver, and then resolve it in the usual way for dot-suffix expressions. var lhs = new ImplicitThisExpr_ConstructorCall(initCallTok) { Type = rr.EType }; var callLhs = new ExprDotName(initCallTok, lhs, initCallName, ret == null ? null : ret.LastComponent.OptTypeArguments); ResolveDotSuffix(callLhs, true, rr.Arguments, new ResolveOpts(codeContext, true), true); if (prevErrorCount == reporter.Count(ErrorLevel.Error)) { Contract.Assert(callLhs.ResolvedExpression is MemberSelectExpr); // since ResolveApplySuffix succeeded and call.Lhs denotes an expression (not a module or a type) var methodSel = (MemberSelectExpr)callLhs.ResolvedExpression; if (methodSel.Member is Method) { rr.InitCall = new CallStmt(initCallTok, stmt.EndTok, new List<Expression>(), methodSel, rr.Arguments); ResolveCallStmt(rr.InitCall, codeContext, rr.EType); if (rr.InitCall.Method is Constructor) { callsConstructor = true; } } else { reporter.Error(MessageSource.Resolver, initCallTok, "object initialization must denote an initializing method or constructor ({0})", initCallName); } } } } if (rr.EType.IsRefType) { var udt = rr.EType.NormalizeExpand() as UserDefinedType; if (udt != null) { var cl = (ClassDecl)udt.ResolvedClass; // cast is guaranteed by the call to rr.EType.IsRefType above, together with the "rr.EType is UserDefinedType" test if (!callsConstructor && !cl.IsObjectTrait && !udt.IsArrayType && (cl.HasConstructor || cl.EnclosingModuleDefinition != currentClass.EnclosingModuleDefinition)) { reporter.Error(MessageSource.Resolver, stmt, "when allocating an object of {1}type '{0}', one of its constructor methods must be called", cl.Name, cl.HasConstructor ? "" : "imported "); } } } rr.Type = rr.EType; } } return rr.Type; } class LazyString_OnTypeEquals { Type t0; Type t1; string s; public LazyString_OnTypeEquals(Type t0, Type t1, string s) { Contract.Requires(t0 != null); Contract.Requires(t1 != null); Contract.Requires(s != null); this.t0 = t0; this.t1 = t1; this.s = s; } public override string ToString() { return t0.Equals(t1) ? s : ""; } } /// <summary> /// Resolve "memberName" in what currently is known as "receiverType". If "receiverType" is an unresolved /// proxy type, try to solve enough type constraints and use heuristics to figure out which type contains /// "memberName" and return that enclosing type as "tentativeReceiverType". However, try not to make /// type-inference decisions about "receiverType"; instead, lay down the further constraints that need to /// be satisfied in order for "tentativeReceiverType" to be where "memberName" is found. /// Consequently, if "memberName" is found and returned as a "MemberDecl", it may still be the case that /// "receiverType" is an unresolved proxy type and that, after solving more type constraints, "receiverType" /// eventually gets set to a type more specific than "tentativeReceiverType". /// </summary> MemberDecl ResolveMember(IToken tok, Type receiverType, string memberName, out NonProxyType tentativeReceiverType) { Contract.Requires(tok != null); Contract.Requires(receiverType != null); Contract.Requires(memberName != null); Contract.Ensures(Contract.Result<MemberDecl>() == null || Contract.ValueAtReturn(out tentativeReceiverType) != null); receiverType = PartiallyResolveTypeForMemberSelection(tok, receiverType, memberName); if (receiverType is TypeProxy) { reporter.Error(MessageSource.Resolver, tok, "type of the receiver is not fully determined at this program point", receiverType); tentativeReceiverType = null; return null; } Contract.Assert(receiverType is NonProxyType); // there are only two kinds of types: proxies and non-proxies foreach (var valuet in valuetypeDecls) { if (valuet.IsThisType(receiverType)) { MemberDecl member; if (valuet.Members.TryGetValue(memberName, out member)) { SelfType resultType = null; if (member is SpecialFunction) { resultType = ((SpecialFunction)member).ResultType as SelfType; } else if (member is SpecialField) { resultType = ((SpecialField)member).Type as SelfType; } if (resultType != null) { SelfTypeSubstitution = new Dictionary<TypeParameter, Type>(); SelfTypeSubstitution.Add(resultType.TypeArg, receiverType); resultType.ResolvedType = receiverType; } tentativeReceiverType = (NonProxyType)receiverType; return member; } break; } } var ctype = receiverType.NormalizeExpand() as UserDefinedType; var cd = ctype?.AsTopLevelTypeWithMembersBypassInternalSynonym; if (cd != null) { Contract.Assert(ctype.TypeArgs.Count == cd.TypeArgs.Count); // follows from the fact that ctype was resolved MemberDecl member; if (!classMembers[cd].TryGetValue(memberName, out member)) { if (memberName == "_ctor") { reporter.Error(MessageSource.Resolver, tok, "{0} {1} does not have an anonymous constructor", cd.WhatKind, cd.Name); } else { reporter.Error(MessageSource.Resolver, tok, "member '{0}' does not exist in {2} '{1}'", memberName, cd.Name, cd.WhatKind); } } else if (!VisibleInScope(member)) { reporter.Error(MessageSource.Resolver, tok, "member '{0}' has not been imported in this scope and cannot be accessed here", memberName); } else { tentativeReceiverType = ctype; return member; } tentativeReceiverType = null; return null; } reporter.Error(MessageSource.Resolver, tok, "type {0} does not have a member {1}", receiverType, memberName); tentativeReceiverType = null; return null; } /// <summary> /// Roughly speaking, tries to figure out the head of the type of "t", making as few inference decisions as possible. /// More precisely, returns a type that contains all the members of "t"; or if "memberName" is non-null, a type /// that at least contains the member "memberName" of "t". Typically, this type is the head type of "t", /// but it may also be a type in a super- or subtype relation to "t". /// In some cases, it is necessary to make some inference decisions in order to figure out the type to return. /// </summary> Type PartiallyResolveTypeForMemberSelection(IToken tok, Type t, string memberName = null, int strength = 0) { Contract.Requires(tok != null); Contract.Requires(t != null); Contract.Ensures(Contract.Result<Type>() != null); Contract.Ensures(!(Contract.Result<Type>() is TypeProxy) || ((TypeProxy)Contract.Result<Type>()).T == null); t = t.NormalizeExpand(); if (!(t is TypeProxy)) { return t; // we're good } // simplify constraints PrintTypeConstraintState(10); if (strength > 0) { var proxySpecializations = new HashSet<TypeProxy>(); GetRelatedTypeProxies(t, proxySpecializations); var anyNewConstraintsAssignable = ConvertAssignableToSubtypeConstraints(proxySpecializations); var anyNewConstraintsEquatable = TightenUpEquatable(proxySpecializations); if ((strength > 1 && !anyNewConstraintsAssignable && !anyNewConstraintsEquatable) || strength == 10) { if (t is TypeProxy) { // One more try var r = GetBaseTypeFromProxy((TypeProxy)t, new Dictionary<TypeProxy, Type>()); if (r != null) { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> found improvement through GetBaseTypeFromProxy: {0}", r); } return r; } } if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> found no improvement, giving up"); } return t; } } PartiallySolveTypeConstraints(false); PrintTypeConstraintState(11); t = t.NormalizeExpandKeepConstraints(); var proxy = t as TypeProxy; if (proxy == null) { return t; // simplification did the trick } if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: Member selection{3}: {1} :> {0} :> {2}", t, Util.Comma(proxy.SupertypesKeepConstraints, su => su.ToString()), Util.Comma(proxy.SubtypesKeepConstraints, su => su.ToString()), memberName == null ? "" : " (" + memberName + ")"); } var artificialSuper = proxy.InClusterOfArtificial(AllXConstraints); if (artificialSuper != null) { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> use artificial supertype: {0}", artificialSuper); } return artificialSuper; } // Look for a meet of head symbols among the proxy's subtypes Type meet = null; if (MeetOfAllSubtypes(proxy, ref meet, new HashSet<TypeProxy>()) && meet != null) { bool isRoot, isLeaf, headIsRoot, headIsLeaf; CheckEnds(meet, out isRoot, out isLeaf, out headIsRoot, out headIsLeaf); if (meet.IsDatatype) { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> meet is a datatype: {0}", meet); } ConstrainSubtypeRelation(t, meet, tok, "Member selection requires a supertype of {0} (got something more like {1})", t, meet); return meet; } else if (headIsRoot) { // we're good to go -- by picking "meet" (whose type parameters have been replaced by fresh proxies), we're not losing any generality if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> improved to {0} through meet", meet); } AssignProxyAndHandleItsConstraints(proxy, meet, true); return proxy.NormalizeExpand(); // we return proxy.T instead of meet, in case the assignment gets hijacked } else if (memberName == "_#apply" || memberName == "requires" || memberName == "reads") { var generalArrowType = meet.AsArrowType; // go all the way to the base type, to get to the general arrow type, if any0 if (generalArrowType != null) { // pick the supertype "generalArrowType" of "meet" if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> improved to {0} through meet and function application", generalArrowType); } ConstrainSubtypeRelation(generalArrowType, t, tok, "Function application requires a subtype of {0} (got something more like {1})", generalArrowType, t); return generalArrowType; } } else if (memberName != null) { // If "meet" has a member called "memberName" and no supertype of "meet" does, then we'll pick this meet if (meet.IsRefType) { var meetExpanded = meet.NormalizeExpand(); // go all the way to the base type, to get to the class if (!meetExpanded.IsObjectQ) { var cl = ((UserDefinedType)meetExpanded).ResolvedClass as ClassDecl; if (cl != null) { // TODO: the following could be improved by also supplying an upper bound of the search (computed as a join of the supertypes) var plausibleMembers = new HashSet<MemberDecl>(); FindAllMembers(cl, memberName, plausibleMembers); if (plausibleMembers.Count == 1) { var mbr = plausibleMembers.First(); if (mbr.EnclosingClass == cl) { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> improved to {0} through member-selection meet", meet); } var meetRoot = meet.NormalizeExpand(); // blow passed any constraints ConstrainSubtypeRelation(meetRoot, t, tok, "Member selection requires a subtype of {0} (got something more like {1})", meetRoot, t); return meet; } else { // pick the supertype "mbr.EnclosingClass" of "cl" Contract.Assert(mbr.EnclosingClass is TraitDecl); // a proper supertype of a ClassDecl must be a TraitDecl var typeMapping = cl.ParentFormalTypeParametersToActuals; TopLevelDecl td = mbr.EnclosingClass; foreach (var tt in cl.TraitAncestors()) { // If there is a match, the list of Type actuals is unique // (a class cannot inherit both Trait<T1> and Trait<T2> with T1 != T2). if (tt == (TraitDecl)mbr.EnclosingClass) { td = tt; } } List<Type> proxyTypeArgs = td.TypeArgs.ConvertAll(t0 => typeMapping.ContainsKey(t0) ? typeMapping[t0] : (Type)new InferredTypeProxy()); var meetMapping = TypeSubstitutionMap(cl.TypeArgs, meet.TypeArgs); proxyTypeArgs = proxyTypeArgs.ConvertAll(t0 => SubstType(t0, meetMapping)); proxyTypeArgs = proxyTypeArgs.ConvertAll(t0 => t0.AsTypeParameter == null ? t0 : (Type)new InferredTypeProxy()); var pickItFromHere = new UserDefinedType(tok, mbr.EnclosingClass.Name, mbr.EnclosingClass, proxyTypeArgs); if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> improved to {0} through meet and member lookup", pickItFromHere); } ConstrainSubtypeRelation(pickItFromHere, t, tok, "Member selection requires a subtype of {0} (got something more like {1})", pickItFromHere, t); return pickItFromHere; } } } } } } if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> found no improvement, because meet does not determine type enough"); } } // Compute the join of the proxy's supertypes Type join = null; if (JoinOfAllSupertypes(proxy, ref join, new HashSet<TypeProxy>(), false) && join != null) { // If the join does have the member, then this looks promising. It could be that the // type would get further constrained later to pick some subtype (in particular, a // subclass that overrides the member) of this join. But this is the best we can do // now. if (join is TypeProxy) { if (proxy == join.Normalize()) { // can this really ever happen? if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> found no improvement (other than the proxy itself)"); } return t; } else { if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> (merging, then trying to improve further) assigning proxy {0}.T := {1}", proxy, join); } Contract.Assert(proxy != join); proxy.T = join; Contract.Assert(t.NormalizeExpand() == join); return PartiallyResolveTypeForMemberSelection(tok, t, memberName, strength + 1); } } if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> improved to {0} through join", join); } if (memberName != null) { AssignProxyAndHandleItsConstraints(proxy, join, true); return proxy.NormalizeExpand(); // we return proxy.T instead of join, in case the assignment gets hijacked } else { return join; } } // we weren't able to do it if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine(" ----> found no improvement using simple things, trying harder once more"); } return PartiallyResolveTypeForMemberSelection(tok, t, memberName, strength + 1); } private Type/*?*/ GetBaseTypeFromProxy(TypeProxy proxy, Dictionary<TypeProxy, Type/*?*/> determinedProxies) { Contract.Requires(proxy != null); Contract.Requires(determinedProxies != null); Type t; if (determinedProxies.TryGetValue(proxy, out t)) { // "t" may be null (meaning search for "proxy" is underway or was unsuccessful) or non-null (search for // "proxy" has completed successfully), but we return it in either case return t; } determinedProxies.Add(proxy, null); // record that search for "proxy" is underway // First, go through subtype constraints, treating each as if it were an equality foreach (var c in AllTypeConstraints) { t = GetBaseTypeFromProxy_Eq(proxy, c.Super, c.Sub, determinedProxies); if (t != null) { determinedProxies[proxy] = t; return t; } } // Next, check XConstraints that can be seen as equality constraints foreach (var xc in AllXConstraints) { switch (xc.ConstraintName) { case "Assignable": case "Equatable": case "EquatableArg": t = GetBaseTypeFromProxy_Eq(proxy, xc.Types[0], xc.Types[1], determinedProxies); if (t != null) { determinedProxies[proxy] = t; return t; } break; case "InSet": // etc. TODO break; default: break; } } return null; } /// <summary> /// Tries to find a non-proxy type corresponding to "proxy", under the assumption that "t" equals "u" and /// "determinedProxies" assumptions. In the process, may add to "determinedProxies". /// </summary> private Type/*?*/ GetBaseTypeFromProxy_Eq(TypeProxy proxy, Type t, Type u, Dictionary<TypeProxy, Type/*?*/> determinedProxies) { Contract.Requires(proxy != null); Contract.Requires(determinedProxies != null); Contract.Requires(t != null); Contract.Requires(u != null); t = t.NormalizeExpand(); u = u.NormalizeExpand(); return GetBaseTypeFromProxy_EqAux(proxy, t, u, determinedProxies) ?? GetBaseTypeFromProxy_EqAux(proxy, u, t, determinedProxies); } private Type/*?*/ GetBaseTypeFromProxy_EqAux(TypeProxy proxy, Type t, Type u, Dictionary<TypeProxy, Type/*?*/> determinedProxies) { Contract.Requires(proxy != null); Contract.Requires(determinedProxies != null); Contract.Requires(t != null && (!(t is TypeProxy) || ((TypeProxy)t).T == null)); Contract.Requires(u != null && (!(u is TypeProxy) || ((TypeProxy)u).T == null)); if (t == proxy) { if (u is TypeProxy) { return GetBaseTypeFromProxy((TypeProxy)u, determinedProxies); } else { return u; } } else if (t.ContainsProxy(proxy)) { if (u is TypeProxy) { u = GetBaseTypeFromProxy((TypeProxy)u, determinedProxies); if (u == null) { return null; } } if (Type.SameHead(t, u)) { Contract.Assert(t.TypeArgs.Count == u.TypeArgs.Count); for (int i = 0; i < t.TypeArgs.Count; i++) { var r = GetBaseTypeFromProxy_Eq(proxy, t.TypeArgs[i], u.TypeArgs[i], determinedProxies); if (r != null) { return r; } } } } return null; } private void GetRelatedTypeProxies(Type t, ISet<TypeProxy> proxies) { Contract.Requires(t != null); Contract.Requires(proxies != null); var proxy = t.Normalize() as TypeProxy; if (proxy == null || proxies.Contains(proxy)) { return; } if (DafnyOptions.O.TypeInferenceDebug) { Console.WriteLine("DEBUG: GetRelatedTypeProxies: finding {0} interesting", proxy); } proxies.Add(proxy); // close over interesting constraints foreach (var c in AllTypeConstraints) { var super = c.Super.Normalize(); if (super.TypeArgs.Exists(ta => ta.Normalize() == proxy)) { GetRelatedTypeProxies(c.Sub, proxies); } } foreach (var xc in AllXConstraints) { var xc0 = xc.Types[0].Normalize(); if (xc.ConstraintName == "Assignable" && (xc0 == proxy || xc0.TypeArgs.Exists(ta => ta.Normalize() == proxy))) { GetRelatedTypeProxies(xc.Types[1], proxies); } else if (xc.ConstraintName == "Innable" && xc.Types[1].Normalize() == proxy) { GetRelatedTypeProxies(xc.Types[0], proxies); } else if ((xc.ConstraintName == "ModifiesFrame" || xc.ConstraintName == "ReadsFrame") && xc.Types[1].Normalize() == proxy) { GetRelatedTypeProxies(xc.Types[0], proxies); } } } void FindAllMembers(ClassDecl cl, string memberName, ISet<MemberDecl> foundSoFar) { Contract.Requires(cl != null); Contract.Requires(memberName != null); Contract.Requires(foundSoFar != null); MemberDecl member; if (classMembers[cl].TryGetValue(memberName, out member)) { foundSoFar.Add(member); } cl.ParentTraitHeads.ForEach(trait => FindAllMembers(trait, memberName, foundSoFar)); } /// <summary> /// Attempts to compute the meet of "meet", "t", and all of "t"'s known subtype( constraint)s. The meet /// ignores type parameters. It is assumed that "meet" on entry already includes the meet of all proxies /// in "visited". The empty meet is represented by "null". /// The return is "true" if the meet exists. /// </summary> bool MeetOfAllSubtypes(Type t, ref Type meet, ISet<TypeProxy> visited) { Contract.Requires(t != null); Contract.Requires(visited != null); t = t.NormalizeExpandKeepConstraints(); var proxy = t as TypeProxy; if (proxy != null) { if (visited.Contains(proxy)) { return true; } visited.Add(proxy); foreach (var c in proxy.SubtypeConstraints) { var s = c.Sub.NormalizeExpandKeepConstraints(); if (!MeetOfAllSubtypes(s, ref meet, visited)) { return false; } } if (meet == null) { // also consider "Assignable" constraints foreach (var c in AllXConstraints) { if (c.ConstraintName == "Assignable" && c.Types[0].Normalize() == proxy) { var s = c.Types[1].NormalizeExpandKeepConstraints(); if (!MeetOfAllSubtypes(s, ref meet, visited)) { return false; } } } } return true; } if (meet == null) { // stick with what we've got meet = t; return true; } else if (Type.IsHeadSupertypeOf(meet, t)) { // stick with what we've got return true; } else if (Type.IsHeadSupertypeOf(t, meet)) { meet = Type.HeadWithProxyArgs(t); return true; } else { meet = Type.Meet(meet, Type.HeadWithProxyArgs(t), builtIns); // the only way this can succeed is if we obtain a (non-null or nullable) trait Contract.Assert(meet == null || meet.IsObjectQ || meet.IsObject || (meet is UserDefinedType udt && (udt.ResolvedClass is TraitDecl || (udt.ResolvedClass is NonNullTypeDecl nntd && nntd.Class is TraitDecl)))); return meet != null; } } /// <summary> /// Attempts to compute the join of "join", all of "t"'s known supertype( constraint)s, and, if "includeT" /// and "t" has no supertype( constraint)s, "t". /// The join ignores type parameters. (Really?? --KRML) /// It is assumed that "join" on entry already includes the join of all proxies /// in "visited". The empty join is represented by "null". /// The return is "true" if the join exists. /// </summary> bool JoinOfAllSupertypes(Type t, ref Type join, ISet<TypeProxy> visited, bool includeT) { Contract.Requires(t != null); Contract.Requires(visited != null); t = t.NormalizeExpandKeepConstraints(); var proxy = t as TypeProxy; if (proxy != null) { if (visited.Contains(proxy)) { return true; } visited.Add(proxy); var delegatedToOthers = false; foreach (var c in proxy.SupertypeConstraints) { var s = c.Super.NormalizeExpandKeepConstraints(); delegatedToOthers = true; if (!JoinOfAllSupertypes(s, ref join, visited, true)) { return false; } } if (!delegatedToOthers) { // also consider "Assignable" constraints foreach (var c in AllXConstraints) { if (c.ConstraintName == "Assignable" && c.Types[1].Normalize() == proxy) { var s = c.Types[0].NormalizeExpandKeepConstraints(); delegatedToOthers = true; if (!JoinOfAllSupertypes(s, ref join, visited, true)) { return false; } } } } if (delegatedToOthers) { return true; } else if (!includeT) { return true; } else if (join == null || join.Normalize() == proxy) { join = proxy; return true; } else { return false; } } if (join == null) { join = Type.HeadWithProxyArgs(t); return true; } else if (Type.IsHeadSupertypeOf(t, join)) { // stick with what we've got return true; } else if (Type.IsHeadSupertypeOf(join, t)) { join = Type.HeadWithProxyArgs(t); return true; } else { join = Type.Join(join, Type.HeadWithProxyArgs(t), builtIns); return join != null; } } public static Dictionary<TypeParameter, Type> TypeSubstitutionMap(List<TypeParameter> formals, List<Type> actuals) { Contract.Requires(formals != null); Contract.Requires(actuals != null); Contract.Requires(formals.Count == actuals.Count); var subst = new Dictionary<TypeParameter, Type>(); for (int i = 0; i < formals.Count; i++) { subst.Add(formals[i], actuals[i]); } return subst; } /// <summary> /// If the substitution has no effect, the return value is pointer-equal to 'type' /// </summary> public static Type SubstType(Type type, Dictionary<TypeParameter, Type> subst) { Contract.Requires(type != null); Contract.Requires(cce.NonNullDictionaryAndValues(subst)); Contract.Ensures(Contract.Result<Type>() != null); if (type is BasicType) { return type; } else if (type is SelfType) { Type t; if (subst.TryGetValue(((SelfType)type).TypeArg, out t)) { return cce.NonNull(t); } else { Contract.Assert(false); throw new cce.UnreachableException(); // unresolved SelfType } } else if (type is MapType) { var t = (MapType)type; var dom = SubstType(t.Domain, subst); if (dom is InferredTypeProxy) { ((InferredTypeProxy)dom).KeepConstraints = true; } var ran = SubstType(t.Range, subst); if (ran is InferredTypeProxy) { ((InferredTypeProxy)ran).KeepConstraints = true; } if (dom == t.Domain && ran == t.Range) { return type; } else { return new MapType(t.Finite, dom, ran); } } else if (type is CollectionType) { var t = (CollectionType)type; var arg = SubstType(t.Arg, subst); if (arg is InferredTypeProxy) { ((InferredTypeProxy)arg).KeepConstraints = true; } if (arg == t.Arg) { return type; } else if (type is SetType) { var st = (SetType)type; return new SetType(st.Finite, arg); } else if (type is MultiSetType) { return new MultiSetType(arg); } else if (type is SeqType) { return new SeqType(arg); } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected collection type } } else if (type is ArrowType) { var t = (ArrowType)type; return new ArrowType(t.tok, (ArrowTypeDecl)t.ResolvedClass, t.Args.ConvertAll(u => SubstType(u, subst)), SubstType(t.Result, subst)); } else if (type is UserDefinedType) { var t = (UserDefinedType)type; if (t.ResolvedParam != null) { Type s; if (subst.TryGetValue(t.ResolvedParam, out s)) { Contract.Assert(t.TypeArgs.Count == 0); // what to do? return cce.NonNull(s); } else { if (t.TypeArgs.Count == 0) { return type; } else { // a type parameter with type arguments--must be an opaque type var otp = (OpaqueType_AsParameter)t.ResolvedParam; var ocl = (OpaqueTypeDecl)t.ResolvedClass; return new UserDefinedType(otp, ocl, t.TypeArgs.ConvertAll(u => SubstType(u, subst))); } } } else if (t.ResolvedClass != null) { List<Type> newArgs = null; // allocate it lazily var resolvedClass = t.ResolvedClass; var isArrowType = ArrowType.IsPartialArrowTypeName(resolvedClass.Name) || ArrowType.IsTotalArrowTypeName(resolvedClass.Name); #if TEST_TYPE_SYNONYM_TRANSPARENCY if (resolvedClass is TypeSynonymDecl && resolvedClass.Name == "type#synonym#transparency#test") { // Usually, all type parameters mentioned in the definition of a type synonym are also type parameters // to the type synonym itself, but in this instrumented testing, that is not so, so we also do a substitution // in the .Rhs of the synonym. var syn = (TypeSynonymDecl)resolvedClass; var r = SubstType(syn.Rhs, subst); if (r != syn.Rhs) { resolvedClass = new TypeSynonymDecl(syn.tok, syn.Name, syn.TypeArgs, syn.Module, r, null); newArgs = new List<Type>(); } } #endif for (int i = 0; i < t.TypeArgs.Count; i++) { Type p = t.TypeArgs[i]; Type s = SubstType(p, subst); if (s is InferredTypeProxy && !isArrowType) { ((InferredTypeProxy)s).KeepConstraints = true; } if (s != p && newArgs == null) { // lazily construct newArgs newArgs = new List<Type>(); for (int j = 0; j < i; j++) { newArgs.Add(t.TypeArgs[j]); } } if (newArgs != null) { newArgs.Add(s); } } if (newArgs == null) { // there were no substitutions return type; } else { // Note, even if t.NamePath is non-null, we don't care to keep that syntactic part of the expression in what we return here return new UserDefinedType(t.tok, t.Name, resolvedClass, newArgs); } } else { // there's neither a resolved param nor a resolved class, which means the UserDefinedType wasn't // properly resolved; just return it return type; } } else if (type is TypeProxy) { TypeProxy t = (TypeProxy)type; if (t.T == null) { return type; } var s = SubstType(t.T, subst); return s == t.T ? type : s; } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type } } /// <summary> /// Check that the type uses formal type parameters in a way that is agreeable with their variance specifications. /// "context == Co" says that "type" is allowed to vary in the positive direction. /// "context == Contra" says that "type" is allowed to vary in the negative direction. /// "context == Inv" says that "type" must not vary at all. /// * "leftOfArrow" says that the context is to the left of some arrow /// </summary> public void CheckVariance(Type type, ICallable enclosingTypeDefinition, TypeParameter.TPVariance context, bool leftOfArrow) { Contract.Requires(type != null); Contract.Requires(enclosingTypeDefinition != null); type = type.Normalize(); // we keep constraints, since subset types have their own type-parameter variance specifications; we also keep synonys, since that gives rise to better error messages if (type is BasicType) { // fine } else if (type is MapType) { var t = (MapType)type; CheckVariance(t.Domain, enclosingTypeDefinition, context, leftOfArrow); CheckVariance(t.Range, enclosingTypeDefinition, context, leftOfArrow); } else if (type is CollectionType) { var t = (CollectionType)type; CheckVariance(t.Arg, enclosingTypeDefinition, context, leftOfArrow); } else if (type is UserDefinedType) { var t = (UserDefinedType)type; if (t.ResolvedParam != null) { if (t.ResolvedParam.Variance != TypeParameter.TPVariance.Non && t.ResolvedParam.Variance != context) { reporter.Error(MessageSource.Resolver, t.tok, "formal type parameter '{0}' is not used according to its variance specification", t.ResolvedParam.Name); } else if (t.ResolvedParam.StrictVariance && leftOfArrow) { string hint; if (t.ResolvedParam.VarianceSyntax == TypeParameter.TPVarianceSyntax.NonVariant_Strict) { hint = string.Format(" (perhaps try declaring '{0}' as '!{0}')", t.ResolvedParam.Name); } else { Contract.Assert(t.ResolvedParam.VarianceSyntax == TypeParameter.TPVarianceSyntax.Covariant_Strict); hint = string.Format(" (perhaps try changing the declaration from '+{0}' to '*{0}')", t.ResolvedParam.Name); } reporter.Error(MessageSource.Resolver, t.tok, "formal type parameter '{0}' is not used according to its variance specification (it is used left of an arrow){1}", t.ResolvedParam.Name, hint); } } else { var resolvedClass = t.ResolvedClass; Contract.Assert(resolvedClass != null); // follows from that the given type was successfully resolved Contract.Assert(resolvedClass.TypeArgs.Count == t.TypeArgs.Count); if (leftOfArrow) { // we have to be careful about uses of the type being defined var cg = enclosingTypeDefinition.EnclosingModule.CallGraph; var t0 = resolvedClass as ICallable; if (t0 != null && cg.GetSCCRepresentative(t0) == cg.GetSCCRepresentative(enclosingTypeDefinition)) { reporter.Error(MessageSource.Resolver, t.tok, "using the type being defined ('{0}') here violates strict positivity, that is, it would cause a logical inconsistency by defining a type whose cardinality exceeds itself (like the Continuum Transfunctioner, you might say its power would then be exceeded only by its mystery)", resolvedClass.Name); } } for (int i = 0; i < t.TypeArgs.Count; i++) { Type p = t.TypeArgs[i]; var tpFormal = resolvedClass.TypeArgs[i]; CheckVariance(p, enclosingTypeDefinition, context == TypeParameter.TPVariance.Non ? context : context == TypeParameter.TPVariance.Co ? tpFormal.Variance : TypeParameter.Negate(tpFormal.Variance), leftOfArrow || !tpFormal.StrictVariance); } } } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type } } public static UserDefinedType GetThisType(IToken tok, TopLevelDeclWithMembers cl) { Contract.Requires(tok != null); Contract.Requires(cl != null); Contract.Ensures(Contract.Result<UserDefinedType>() != null); if (cl is ClassDecl cls && cls.NonNullTypeDecl != null) { return UserDefinedType.FromTopLevelDecl(tok, cls.NonNullTypeDecl, cls.TypeArgs); } else { return UserDefinedType.FromTopLevelDecl(tok, cl, cl.TypeArgs); } } public static UserDefinedType GetReceiverType(IToken tok, MemberDecl member) { Contract.Requires(tok != null); Contract.Requires(member != null); Contract.Ensures(Contract.Result<UserDefinedType>() != null); return GetThisType(tok, (TopLevelDeclWithMembers)member.EnclosingClass); } public class ResolveOpts { public readonly ICodeContext codeContext; public readonly bool twoState; public readonly bool isReveal; public readonly bool isPostCondition; public readonly bool InsideOld; public ResolveOpts(ICodeContext codeContext, bool twoState) { Contract.Requires(codeContext != null); this.codeContext = codeContext; this.twoState = twoState; this.isReveal = false; this.isPostCondition = false; } public ResolveOpts(ICodeContext codeContext, bool twoState, bool isReveal, bool isPostCondition, bool insideOld) { Contract.Requires(codeContext != null); this.codeContext = codeContext; this.twoState = twoState; this.isReveal = isReveal; this.isPostCondition = isPostCondition; this.InsideOld = insideOld; } } /// <summary> /// "twoState" implies that "old" and "fresh" expressions are allowed. /// </summary> public void ResolveExpression(Expression expr, ResolveOpts opts) { #if TEST_TYPE_SYNONYM_TRANSPARENCY ResolveExpressionX(expr, opts); // For testing purposes, change the type of "expr" to a type synonym (mwo-ha-ha-ha!) var t = expr.Type; Contract.Assert(t != null); var sd = new TypeSynonymDecl(expr.tok, "type#synonym#transparency#test", new List<TypeParameter>(), codeContext.EnclosingModule, t, null); var ts = new UserDefinedType(expr.tok, "type#synonym#transparency#test", sd, new List<Type>(), null); expr.DebugTest_ChangeType(ts); } public void ResolveExpressionX(Expression expr, ResolveOpts opts) { #endif Contract.Requires(expr != null); Contract.Requires(opts != null); Contract.Ensures(expr.Type != null); if (expr.Type != null) { // expression has already been resolved return; } // The following cases will resolve the subexpressions and will attempt to assign a type of expr. However, if errors occur // and it cannot be determined what the type of expr is, then it is fine to leave expr.Type as null. In that case, the end // of this method will assign proxy type to the expression, which reduces the number of error messages that are produced // while type checking the rest of the program. if (expr is ParensExpression) { var e = (ParensExpression)expr; ResolveExpression(e.E, opts); e.ResolvedExpression = e.E; e.Type = e.E.Type; } else if (expr is ChainingExpression) { var e = (ChainingExpression)expr; ResolveExpression(e.E, opts); e.ResolvedExpression = e.E; e.Type = e.E.Type; } else if (expr is NegationExpression) { var e = (NegationExpression)expr; ResolveExpression(e.E, opts); e.Type = e.E.Type; AddXConstraint(e.E.tok, "NumericOrBitvector", e.E.Type, "type of unary - must be of a numeric or bitvector type (instead got {0})"); // Note, e.ResolvedExpression will be filled in during CheckTypeInference, at which time e.Type has been determined } else if (expr is LiteralExpr) { LiteralExpr e = (LiteralExpr)expr; if (e is StaticReceiverExpr) { StaticReceiverExpr eStatic = (StaticReceiverExpr)e; this.ResolveType(eStatic.tok, eStatic.UnresolvedType, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); eStatic.Type = eStatic.UnresolvedType; } else { if (e.Value == null) { e.Type = new InferredTypeProxy(); AddXConstraint(e.tok, "IsNullableRefType", e.Type, "type of 'null' is a reference type, but it is used as {0}"); } else if (e.Value is BigInteger) { var proxy = new InferredTypeProxy(); e.Type = proxy; ConstrainSubtypeRelation(new IntVarietiesSupertype(), e.Type, e.tok, "integer literal used as if it had type {0}", e.Type); } else if (e.Value is BaseTypes.BigDec) { var proxy = new InferredTypeProxy(); e.Type = proxy; ConstrainSubtypeRelation(new RealVarietiesSupertype(), e.Type, e.tok, "type of real literal is used as {0}", e.Type); } else if (e.Value is bool) { e.Type = Type.Bool; } else if (e is CharLiteralExpr) { e.Type = Type.Char; } else if (e is StringLiteralExpr) { e.Type = Type.String(); ResolveType(e.tok, e.Type, opts.codeContext, ResolveTypeOptionEnum.DontInfer, null); } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected literal type } } } else if (expr is ThisExpr) { if (!scope.AllowInstance) { reporter.Error(MessageSource.Resolver, expr, "'this' is not allowed in a 'static' context"); } if (currentClass is ClassDecl cd && cd.IsDefaultClass) { // there's no type } else { expr.Type = GetThisType(expr.tok, currentClass); // do this regardless of scope.AllowInstance, for better error reporting } } else if (expr is IdentifierExpr) { var e = (IdentifierExpr)expr; e.Var = scope.Find(e.Name); if (e.Var != null) { expr.Type = e.Var.Type; } else { reporter.Error(MessageSource.Resolver, expr, "Identifier does not denote a local variable, parameter, or bound variable: {0}", e.Name); } } else if (expr is DatatypeValue) { DatatypeValue dtv = (DatatypeValue)expr; TopLevelDecl d; if (!moduleInfo.TopLevels.TryGetValue(dtv.DatatypeName, out d)) { reporter.Error(MessageSource.Resolver, expr.tok, "Undeclared datatype: {0}", dtv.DatatypeName); } else if (d is AmbiguousTopLevelDecl) { var ad = (AmbiguousTopLevelDecl)d; reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a type in one of the modules {1} (try qualifying the type name with the module name)", dtv.DatatypeName, ad.ModuleNames()); } else if (!(d is DatatypeDecl)) { reporter.Error(MessageSource.Resolver, expr.tok, "Expected datatype: {0}", dtv.DatatypeName); } else { ResolveDatatypeValue(opts, dtv, (DatatypeDecl)d, null); } } else if (expr is DisplayExpression) { DisplayExpression e = (DisplayExpression)expr; Type elementType = new InferredTypeProxy() { KeepConstraints = true }; foreach (Expression ee in e.Elements) { ResolveExpression(ee, opts); Contract.Assert(ee.Type != null); // follows from postcondition of ResolveExpression ConstrainSubtypeRelation(elementType, ee.Type, ee.tok, "All elements of display must have some common supertype (got {0}, but needed type or type of previous elements is {1})", ee.Type, elementType); } if (expr is SetDisplayExpr) { var se = (SetDisplayExpr)expr; expr.Type = new SetType(se.Finite, elementType); } else if (expr is MultiSetDisplayExpr) { expr.Type = new MultiSetType(elementType); } else { expr.Type = new SeqType(elementType); } } else if (expr is MapDisplayExpr) { MapDisplayExpr e = (MapDisplayExpr)expr; Type domainType = new InferredTypeProxy(); Type rangeType = new InferredTypeProxy(); foreach (ExpressionPair p in e.Elements) { ResolveExpression(p.A, opts); Contract.Assert(p.A.Type != null); // follows from postcondition of ResolveExpression ConstrainSubtypeRelation(domainType, p.A.Type, p.A.tok, "All elements of display must have some common supertype (got {0}, but needed type or type of previous elements is {1})", p.A.Type, domainType); ResolveExpression(p.B, opts); Contract.Assert(p.B.Type != null); // follows from postcondition of ResolveExpression ConstrainSubtypeRelation(rangeType, p.B.Type, p.B.tok, "All elements of display must have some common supertype (got {0}, but needed type or type of previous elements is {1})", p.B.Type, rangeType); } expr.Type = new MapType(e.Finite, domainType, rangeType); } else if (expr is NameSegment) { var e = (NameSegment)expr; ResolveNameSegment(e, true, null, opts, false); if (e.Type is Resolver_IdentifierExpr.ResolverType_Module) { reporter.Error(MessageSource.Resolver, e.tok, "name of module ({0}) is used as a variable", e.Name); e.ResetTypeAssignment(); // the rest of type checking assumes actual types } else if (e.Type is Resolver_IdentifierExpr.ResolverType_Type) { reporter.Error(MessageSource.Resolver, e.tok, "name of type ({0}) is used as a variable", e.Name); e.ResetTypeAssignment(); // the rest of type checking assumes actual types } } else if (expr is ExprDotName) { var e = (ExprDotName)expr; ResolveDotSuffix(e, true, null, opts, false); if (e.Type is Resolver_IdentifierExpr.ResolverType_Module) { reporter.Error(MessageSource.Resolver, e.tok, "name of module ({0}) is used as a variable", e.SuffixName); e.ResetTypeAssignment(); // the rest of type checking assumes actual types } else if (e.Type is Resolver_IdentifierExpr.ResolverType_Type) { reporter.Error(MessageSource.Resolver, e.tok, "name of type ({0}) is used as a variable", e.SuffixName); e.ResetTypeAssignment(); // the rest of type checking assumes actual types } } else if (expr is ApplySuffix) { var e = (ApplySuffix)expr; ResolveApplySuffix(e, opts, false); } else if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; ResolveExpression(e.Obj, opts); Contract.Assert(e.Obj.Type != null); // follows from postcondition of ResolveExpression NonProxyType tentativeReceiverType; var member = ResolveMember(expr.tok, e.Obj.Type, e.MemberName, out tentativeReceiverType); if (member == null) { // error has already been reported by ResolveMember } else if (member is Function) { var fn = member as Function; e.Member = fn; if (fn is TwoStateFunction && !opts.twoState) { reporter.Error(MessageSource.Resolver, e.tok, "a two-state function can be used only in a two-state context"); } // build the type substitution map e.TypeApplication_AtEnclosingClass = tentativeReceiverType.TypeArgs; e.TypeApplication_JustMember = new List<Type>(); Dictionary<TypeParameter, Type> subst; var ctype = tentativeReceiverType as UserDefinedType; if (ctype == null) { subst = new Dictionary<TypeParameter, Type>(); } else { subst = TypeSubstitutionMap(ctype.ResolvedClass.TypeArgs, ctype.TypeArgs); } foreach (var tp in fn.TypeArgs) { Type prox = new InferredTypeProxy(); subst[tp] = prox; e.TypeApplication_JustMember.Add(prox); } subst = BuildTypeArgumentSubstitute(subst); e.Type = SelectAppropriateArrowType(fn.tok, fn.Formals.ConvertAll(f => SubstType(f.Type, subst)), SubstType(fn.ResultType, subst), fn.Reads.Count != 0, fn.Req.Count != 0); AddCallGraphEdge(opts.codeContext, fn, e, false); } else if (member is Field) { var field = (Field)member; e.Member = field; e.TypeApplication_AtEnclosingClass = tentativeReceiverType.TypeArgs; e.TypeApplication_JustMember = new List<Type>(); if (e.Obj is StaticReceiverExpr && !field.IsStatic) { reporter.Error(MessageSource.Resolver, expr, "a field must be selected via an object, not just a class name"); } var ctype = tentativeReceiverType as UserDefinedType; if (ctype == null) { e.Type = field.Type; } else { Contract.Assert(ctype.ResolvedClass != null); // follows from postcondition of ResolveMember // build the type substitution map var subst = TypeSubstitutionMap(ctype.ResolvedClass.TypeArgs, ctype.TypeArgs); e.Type = SubstType(field.Type, subst); } AddCallGraphEdgeForField(opts.codeContext, field, e); } else { reporter.Error(MessageSource.Resolver, expr, "member {0} in type {1} does not refer to a field or a function", e.MemberName, tentativeReceiverType); } } else if (expr is SeqSelectExpr) { SeqSelectExpr e = (SeqSelectExpr)expr; ResolveSeqSelectExpr(e, opts); } else if (expr is MultiSelectExpr) { MultiSelectExpr e = (MultiSelectExpr)expr; ResolveExpression(e.Array, opts); Contract.Assert(e.Array.Type != null); // follows from postcondition of ResolveExpression Contract.Assert(e.Array.Type.TypeArgs != null); // if it is null, should make a 1-element list with a Proxy Type elementType = e.Array.Type.TypeArgs.Count > 0 ? e.Array.Type.TypeArgs[0] : new InferredTypeProxy(); ConstrainSubtypeRelation(ResolvedArrayType(e.Array.tok, e.Indices.Count, elementType, opts.codeContext, true), e.Array.Type, e.Array, "array selection requires an array{0} (got {1})", e.Indices.Count, e.Array.Type); int i = 0; foreach (Expression idx in e.Indices) { Contract.Assert(idx != null); ResolveExpression(idx, opts); Contract.Assert(idx.Type != null); // follows from postcondition of ResolveExpression ConstrainToIntegerType(idx, true, "array selection requires integer- or bitvector-based numeric indices (got {0} for index " + i + ")"); i++; } e.Type = elementType; } else if (expr is SeqUpdateExpr) { SeqUpdateExpr e = (SeqUpdateExpr)expr; ResolveExpression(e.Seq, opts); Contract.Assert(e.Seq.Type != null); // follows from postcondition of ResolveExpression ResolveExpression(e.Index, opts); ResolveExpression(e.Value, opts); AddXConstraint(expr.tok, "SeqUpdatable", e.Seq.Type, e.Index, e.Value, "update requires a sequence, map, or multiset (got {0})"); expr.Type = e.Seq.Type; } else if (expr is DatatypeUpdateExpr) { var e = (DatatypeUpdateExpr)expr; ResolveExpression(e.Root, opts); var ty = PartiallyResolveTypeForMemberSelection(expr.tok, e.Root.Type); if (!ty.IsDatatype) { reporter.Error(MessageSource.Resolver, expr, "datatype update expression requires a root expression of a datatype (got {0})", ty); } else { List<DatatypeCtor> legalSourceConstructors; var let = ResolveDatatypeUpdate(expr.tok, e.Root, ty.AsDatatype, e.Updates, opts, out legalSourceConstructors); if (let != null) { e.ResolvedExpression = let; e.LegalSourceConstructors = legalSourceConstructors; expr.Type = ty; } } } else if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; ResolveFunctionCallExpr(e, opts); } else if (expr is ApplyExpr) { var e = (ApplyExpr)expr; ResolveExpression(e.Function, opts); foreach (var arg in e.Args) { ResolveExpression(arg, opts); } // TODO: the following should be replaced by a type-class constraint that constrains the types of e.Function, e.Args[*], and e.Type var fnType = e.Function.Type.AsArrowType; if (fnType == null) { reporter.Error(MessageSource.Resolver, e.tok, "non-function expression (of type {0}) is called with parameters", e.Function.Type); } else if (fnType.Arity != e.Args.Count) { reporter.Error(MessageSource.Resolver, e.tok, "wrong number of arguments to function application (function type '{0}' expects {1}, got {2})", fnType, fnType.Arity, e.Args.Count); } else { for (var i = 0; i < fnType.Arity; i++) { AddAssignableConstraint(e.Args[i].tok, fnType.Args[i], e.Args[i].Type, "type mismatch for argument" + (fnType.Arity == 1 ? "" : " " + i) + " (function expects {0}, got {1})"); } } expr.Type = fnType == null ? new InferredTypeProxy() : fnType.Result; } else if (expr is SeqConstructionExpr) { var e = (SeqConstructionExpr)expr; var elementType = e.ExplicitElementType ?? new InferredTypeProxy(); ResolveType(e.tok, elementType, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); ResolveExpression(e.N, opts); ConstrainToIntegerType(e.N, false, "sequence construction must use an integer-based expression for the sequence size (got {0})"); ResolveExpression(e.Initializer, opts); UserDefinedType t = builtIns.Nat() as UserDefinedType; var arrowType = new ArrowType(e.tok, builtIns.ArrowTypeDecls[1], new List<Type>() { t }, elementType); var hintString = " (perhaps write '_ =>' in front of the expression you gave in order to make it an arrow type)"; ConstrainSubtypeRelation(arrowType, e.Initializer.Type, e.Initializer, "sequence-construction initializer expression expected to have type '{0}' (instead got '{1}'){2}", arrowType, e.Initializer.Type, new LazyString_OnTypeEquals(elementType, e.Initializer.Type, hintString)); expr.Type = new SeqType(elementType); } else if (expr is MultiSetFormingExpr) { MultiSetFormingExpr e = (MultiSetFormingExpr)expr; ResolveExpression(e.E, opts); var elementType = new InferredTypeProxy(); AddXConstraint(e.E.tok, "MultiSetConvertible", e.E.Type, elementType, "can only form a multiset from a seq or set (got {0})"); expr.Type = new MultiSetType(elementType); } else if (expr is OldExpr) { OldExpr e = (OldExpr)expr; if (!opts.twoState) { reporter.Error(MessageSource.Resolver, expr, "old expressions are not allowed in this context"); } else if (e.At != null) { e.AtLabel = dominatingStatementLabels.Find(e.At); if (e.AtLabel == null) { reporter.Error(MessageSource.Resolver, expr, "no label '{0}' in scope at this time", e.At); } } ResolveExpression(e.E, new ResolveOpts(opts.codeContext, false, opts.isReveal, opts.isPostCondition, true)); expr.Type = e.E.Type; } else if (expr is UnchangedExpr) { var e = (UnchangedExpr)expr; if (!opts.twoState) { reporter.Error(MessageSource.Resolver, expr, "unchanged expressions are not allowed in this context"); } else if (e.At != null) { e.AtLabel = dominatingStatementLabels.Find(e.At); if (e.AtLabel == null) { reporter.Error(MessageSource.Resolver, expr, "no label '{0}' in scope at this time", e.At); } } foreach (var fe in e.Frame) { ResolveFrameExpression(fe, FrameExpressionUse.Unchanged, opts.codeContext); } expr.Type = Type.Bool; } else if (expr is UnaryOpExpr) { var e = (UnaryOpExpr)expr; ResolveExpression(e.E, opts); Contract.Assert(e.E.Type != null); // follows from postcondition of ResolveExpression switch (e.Op) { case UnaryOpExpr.Opcode.Not: AddXConstraint(e.E.tok, "BooleanBits", e.E.Type, "logical/bitwise negation expects a boolean or bitvector argument (instead got {0})"); expr.Type = e.E.Type; break; case UnaryOpExpr.Opcode.Cardinality: AddXConstraint(expr.tok, "Sizeable", e.E.Type, "size operator expects a collection argument (instead got {0})"); expr.Type = Type.Int; break; case UnaryOpExpr.Opcode.Fresh: if (!opts.twoState) { reporter.Error(MessageSource.Resolver, expr, "fresh expressions are not allowed in this context"); } // the type of e.E must be either an object or a collection of objects AddXConstraint(expr.tok, "Freshable", e.E.Type, "the argument of a fresh expression must denote an object or a collection of objects (instead got {0})"); expr.Type = Type.Bool; break; case UnaryOpExpr.Opcode.Allocated: // the argument is allowed to have any type at all expr.Type = Type.Bool; if (2 <= DafnyOptions.O.Allocated && ((opts.codeContext is Function && !opts.InsideOld) || opts.codeContext is ConstantField || opts.codeContext is RedirectingTypeDecl)) { var declKind = opts.codeContext is RedirectingTypeDecl ? ((RedirectingTypeDecl)opts.codeContext).WhatKind : ((MemberDecl)opts.codeContext).WhatKind; reporter.Error(MessageSource.Resolver, expr, "a {0} definition is not allowed to depend on the set of allocated references", declKind); } break; default: Contract.Assert(false); throw new cce.UnreachableException(); // unexpected unary operator } } else if (expr is ConversionExpr) { var e = (ConversionExpr)expr; ResolveExpression(e.E, opts); var prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveType(e.tok, e.ToType, opts.codeContext, new ResolveTypeOption(ResolveTypeOptionEnum.DontInfer), null); if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { if (e.ToType.IsNumericBased(Type.NumericPersuasion.Int)) { AddXConstraint(expr.tok, "NumericOrBitvectorOrCharOrORDINAL", e.E.Type, "type conversion to an int-based type is allowed only from numeric and bitvector types, char, and ORDINAL (got {0})"); } else if (e.ToType.IsNumericBased(Type.NumericPersuasion.Real)) { AddXConstraint(expr.tok, "NumericOrBitvectorOrCharOrORDINAL", e.E.Type, "type conversion to a real-based type is allowed only from numeric and bitvector types, char, and ORDINAL (got {0})"); } else if (e.ToType.IsBitVectorType) { AddXConstraint(expr.tok, "NumericOrBitvectorOrCharOrORDINAL", e.E.Type, "type conversion to a bitvector-based type is allowed only from numeric and bitvector types, char, and ORDINAL (got {0})"); } else if (e.ToType.IsCharType) { AddXConstraint(expr.tok, "NumericOrBitvectorOrCharOrORDINAL", e.E.Type, "type conversion to a char type is allowed only from numeric and bitvector types, char, and ORDINAL (got {0})"); } else if (e.ToType.IsBigOrdinalType) { AddXConstraint(expr.tok, "NumericOrBitvectorOrCharOrORDINAL", e.E.Type, "type conversion to an ORDINAL type is allowed only from numeric and bitvector types, char, and ORDINAL (got {0})"); } else { reporter.Error(MessageSource.Resolver, expr, "type conversions are not supported to this type (got {0})", e.ToType); } e.Type = e.ToType; } else { e.Type = new InferredTypeProxy(); } } else if (expr is BinaryExpr) { BinaryExpr e = (BinaryExpr)expr; ResolveExpression(e.E0, opts); Contract.Assert(e.E0.Type != null); // follows from postcondition of ResolveExpression ResolveExpression(e.E1, opts); Contract.Assert(e.E1.Type != null); // follows from postcondition of ResolveExpression switch (e.Op) { case BinaryExpr.Opcode.Iff: case BinaryExpr.Opcode.Imp: case BinaryExpr.Opcode.Exp: case BinaryExpr.Opcode.And: case BinaryExpr.Opcode.Or: { ConstrainSubtypeRelation(Type.Bool, e.E0.Type, expr, "first argument to {0} must be of type bool (instead got {1})", BinaryExpr.OpcodeString(e.Op), e.E0.Type); ConstrainSubtypeRelation(Type.Bool, e.E1.Type, expr, "second argument to {0} must be of type bool (instead got {1})", BinaryExpr.OpcodeString(e.Op), e.E1.Type); expr.Type = Type.Bool; break; } case BinaryExpr.Opcode.Eq: case BinaryExpr.Opcode.Neq: AddXConstraint(expr.tok, "Equatable", e.E0.Type, e.E1.Type, "arguments must have comparable types (got {0} and {1})"); expr.Type = Type.Bool; break; case BinaryExpr.Opcode.Disjoint: Type disjointArgumentsType = new InferredTypeProxy(); ConstrainSubtypeRelation(disjointArgumentsType, e.E0.Type, expr, "arguments to {2} must have a common supertype (got {0} and {1})", e.E0.Type, e.E1.Type, BinaryExpr.OpcodeString(e.Op)); ConstrainSubtypeRelation(disjointArgumentsType, e.E1.Type, expr, "arguments to {2} must have a common supertype (got {0} and {1})", e.E0.Type, e.E1.Type, BinaryExpr.OpcodeString(e.Op)); AddXConstraint(expr.tok, "Disjointable", disjointArgumentsType, "arguments must be of a set or multiset type (got {0})"); expr.Type = Type.Bool; break; case BinaryExpr.Opcode.Lt: case BinaryExpr.Opcode.Le: { if (e.Op == BinaryExpr.Opcode.Lt && (PartiallyResolveTypeForMemberSelection(e.E0.tok, e.E0.Type).IsIndDatatype || e.E0.Type.IsTypeParameter || PartiallyResolveTypeForMemberSelection(e.E1.tok, e.E1.Type).IsIndDatatype)) { AddXConstraint(expr.tok, "RankOrderable", e.E0.Type, e.E1.Type, "arguments to rank comparison must be datatypes (got {0} and {1})"); e.ResolvedOp = BinaryExpr.ResolvedOpcode.RankLt; } else { var cmpType = new InferredTypeProxy(); var err = new TypeConstraint.ErrorMsgWithToken(expr.tok, "arguments to {2} must have a common supertype (got {0} and {1})", e.E0.Type, e.E1.Type, BinaryExpr.OpcodeString(e.Op)); ConstrainSubtypeRelation(cmpType, e.E0.Type, err); ConstrainSubtypeRelation(cmpType, e.E1.Type, err); AddXConstraint(expr.tok, "Orderable_Lt", e.E0.Type, e.E1.Type, "arguments to " + BinaryExpr.OpcodeString(e.Op) + " must be of a numeric type, bitvector type, ORDINAL, char, a sequence type, or a set-like type (instead got {0} and {1})"); } expr.Type = Type.Bool; } break; case BinaryExpr.Opcode.Gt: case BinaryExpr.Opcode.Ge: { if (e.Op == BinaryExpr.Opcode.Gt && (PartiallyResolveTypeForMemberSelection(e.E0.tok, e.E0.Type).IsIndDatatype || PartiallyResolveTypeForMemberSelection(e.E1.tok, e.E1.Type).IsIndDatatype || e.E1.Type.IsTypeParameter)) { AddXConstraint(expr.tok, "RankOrderable", e.E1.Type, e.E0.Type, "arguments to rank comparison must be datatypes (got {1} and {0})"); e.ResolvedOp = BinaryExpr.ResolvedOpcode.RankGt; } else { var cmpType = new InferredTypeProxy(); var err = new TypeConstraint.ErrorMsgWithToken(expr.tok, "arguments to {2} must have a common supertype (got {0} and {1})", e.E0.Type, e.E1.Type, BinaryExpr.OpcodeString(e.Op)); ConstrainSubtypeRelation(cmpType, e.E0.Type, err); ConstrainSubtypeRelation(cmpType, e.E1.Type, err); AddXConstraint(expr.tok, "Orderable_Gt", e.E0.Type, e.E1.Type, "arguments to " + BinaryExpr.OpcodeString(e.Op) + " must be of a numeric type, bitvector type, ORDINAL, char, or a set-like type (instead got {0} and {1})"); } expr.Type = Type.Bool; } break; case BinaryExpr.Opcode.LeftShift: case BinaryExpr.Opcode.RightShift: { expr.Type = new InferredTypeProxy(); AddXConstraint(e.tok, "IsBitvector", expr.Type, "type of " + BinaryExpr.OpcodeString(e.Op) + " must be a bitvector type (instead got {0})"); ConstrainSubtypeRelation(expr.Type, e.E0.Type, expr.tok, "type of left argument to " + BinaryExpr.OpcodeString(e.Op) + " ({0}) must agree with the result type ({1})", e.E0.Type, expr.Type); AddXConstraint(expr.tok, "IntLikeOrBitvector", e.E1.Type, "type of right argument to " + BinaryExpr.OpcodeString(e.Op) + " ({0}) must be an integer-numeric or bitvector type"); } break; case BinaryExpr.Opcode.Add: { expr.Type = new InferredTypeProxy(); AddXConstraint(e.tok, "Plussable", expr.Type, "type of + must be of a numeric type, a bitvector type, ORDINAL, char, a sequence type, or a set-like or map-like type (instead got {0})"); ConstrainSubtypeRelation(expr.Type, e.E0.Type, expr.tok, "type of left argument to + ({0}) must agree with the result type ({1})", e.E0.Type, expr.Type); ConstrainSubtypeRelation(expr.Type, e.E1.Type, expr.tok, "type of right argument to + ({0}) must agree with the result type ({1})", e.E1.Type, expr.Type); } break; case BinaryExpr.Opcode.Sub: { expr.Type = new InferredTypeProxy(); AddXConstraint(e.tok, "Minusable", expr.Type, "type of - must be of a numeric type, bitvector type, ORDINAL, char, or a set-like or map-like type (instead got {0})"); ConstrainSubtypeRelation(expr.Type, e.E0.Type, expr.tok, "type of left argument to - ({0}) must agree with the result type ({1})", e.E0.Type, expr.Type); // The following handles map subtraction, but does not in an unfortunately restrictive way. // First, it would be nice to delay the decision of it this is a map subtraction or not. This settles // for the simple way to decide based on what is currently known about the result type, which is also // done, for example, when deciding if "<" denotes rank ordering on datatypes. // Second, for map subtraction, it would be nice to allow the right-hand operand to be either a set or // an iset. That would also lead to further complexity in the code, so this code restricts the right-hand // operand to be a set. var eType = PartiallyResolveTypeForMemberSelection(expr.tok, expr.Type).AsMapType; if (eType != null) { // allow "map - set == map" var expected = new SetType(true, eType.Domain); ConstrainSubtypeRelation(expected, e.E1.Type, expr.tok, "map subtraction expects right-hand operand to have type {0} (instead got {1})", expected, e.E1.Type); } else { ConstrainSubtypeRelation(expr.Type, e.E1.Type, expr.tok, "type of right argument to - ({0}) must agree with the result type ({1})", e.E1.Type, expr.Type); } } break; case BinaryExpr.Opcode.Mul: { expr.Type = new InferredTypeProxy(); AddXConstraint(e.tok, "Mullable", expr.Type, "type of * must be of a numeric type, bitvector type, or a set-like type (instead got {0})"); ConstrainSubtypeRelation(expr.Type, e.E0.Type, expr.tok, "type of left argument to * ({0}) must agree with the result type ({1})", e.E0.Type, expr.Type); ConstrainSubtypeRelation(expr.Type, e.E1.Type, expr.tok, "type of right argument to * ({0}) must agree with the result type ({1})", e.E1.Type, expr.Type); } break; case BinaryExpr.Opcode.In: case BinaryExpr.Opcode.NotIn: AddXConstraint(expr.tok, "Innable", e.E1.Type, e.E0.Type, "second argument to \"" + BinaryExpr.OpcodeString(e.Op) + "\" must be a set, multiset, or sequence with elements of type {1}, or a map with domain {1} (instead got {0})"); expr.Type = Type.Bool; break; case BinaryExpr.Opcode.Div: expr.Type = new InferredTypeProxy(); AddXConstraint(expr.tok, "NumericOrBitvector", expr.Type, "arguments to " + BinaryExpr.OpcodeString(e.Op) + " must be numeric or bitvector types (got {0})"); ConstrainSubtypeRelation(expr.Type, e.E0.Type, expr, "type of left argument to " + BinaryExpr.OpcodeString(e.Op) + " ({0}) must agree with the result type ({1})", e.E0.Type, expr.Type); ConstrainSubtypeRelation(expr.Type, e.E1.Type, expr, "type of right argument to " + BinaryExpr.OpcodeString(e.Op) + " ({0}) must agree with the result type ({1})", e.E1.Type, expr.Type); break; case BinaryExpr.Opcode.Mod: expr.Type = new InferredTypeProxy(); AddXConstraint(expr.tok, "IntLikeOrBitvector", expr.Type, "arguments to " + BinaryExpr.OpcodeString(e.Op) + " must be integer-numeric or bitvector types (got {0})"); ConstrainSubtypeRelation(expr.Type, e.E0.Type, expr, "type of left argument to " + BinaryExpr.OpcodeString(e.Op) + " ({0}) must agree with the result type ({1})", e.E0.Type, expr.Type); ConstrainSubtypeRelation(expr.Type, e.E1.Type, expr, "type of right argument to " + BinaryExpr.OpcodeString(e.Op) + " ({0}) must agree with the result type ({1})", e.E1.Type, expr.Type); break; case BinaryExpr.Opcode.BitwiseAnd: case BinaryExpr.Opcode.BitwiseOr: case BinaryExpr.Opcode.BitwiseXor: expr.Type = NewIntegerBasedProxy(expr.tok); var errFormat = "first argument to " + BinaryExpr.OpcodeString(e.Op) + " must be of a bitvector type (instead got {0})"; ConstrainSubtypeRelation(expr.Type, e.E0.Type, expr, errFormat, e.E0.Type); AddXConstraint(expr.tok, "IsBitvector", e.E0.Type, errFormat); errFormat = "second argument to " + BinaryExpr.OpcodeString(e.Op) + " must be of a bitvector type (instead got {0})"; ConstrainSubtypeRelation(expr.Type, e.E1.Type, expr, errFormat, e.E1.Type); AddXConstraint(expr.tok, "IsBitvector", e.E1.Type, errFormat); break; default: Contract.Assert(false); throw new cce.UnreachableException(); // unexpected operator } // We should also fill in e.ResolvedOp, but we may not have enough information for that yet. So, instead, delay // setting e.ResolvedOp until inside CheckTypeInference. } else if (expr is TernaryExpr) { var e = (TernaryExpr)expr; ResolveExpression(e.E0, opts); ResolveExpression(e.E1, opts); ResolveExpression(e.E2, opts); switch (e.Op) { case TernaryExpr.Opcode.PrefixEqOp: case TernaryExpr.Opcode.PrefixNeqOp: AddXConstraint(expr.tok, "IntOrORDINAL", e.E0.Type, "prefix-equality limit argument must be an ORDINAL or integer expression (got {0})"); AddXConstraint(expr.tok, "Equatable", e.E1.Type, e.E2.Type, "arguments must have the same type (got {0} and {1})"); AddXConstraint(expr.tok, "IsCoDatatype", e.E1.Type, "arguments to prefix equality must be codatatypes (instead of {0})"); expr.Type = Type.Bool; break; default: Contract.Assert(false); // unexpected ternary operator break; } } else if (expr is LetExpr) { var e = (LetExpr)expr; if (e.Exact) { foreach (var rhs in e.RHSs) { ResolveExpression(rhs, opts); } scope.PushMarker(); if (e.LHSs.Count != e.RHSs.Count) { reporter.Error(MessageSource.Resolver, expr, "let expression must have same number of LHSs (found {0}) as RHSs (found {1})", e.LHSs.Count, e.RHSs.Count); } var i = 0; foreach (var lhs in e.LHSs) { var rhsType = i < e.RHSs.Count ? e.RHSs[i].Type : new InferredTypeProxy(); ResolveCasePattern(lhs, rhsType, opts.codeContext); // Check for duplicate names now, because not until after resolving the case pattern do we know if identifiers inside it refer to bound variables or nullary constructors var c = 0; foreach (var v in lhs.Vars) { ScopePushAndReport(scope, v, "let-variable"); c++; } if (c == 0) { // Every identifier-looking thing in the pattern resolved to a constructor; that is, this LHS is a constant literal reporter.Error(MessageSource.Resolver, lhs.tok, "LHS is a constant literal; to be legal, it must introduce at least one bound variable"); } i++; } } else { // let-such-that expression if (e.RHSs.Count != 1) { reporter.Error(MessageSource.Resolver, expr, "let-such-that expression must have just one RHS (found {0})", e.RHSs.Count); } // the bound variables are in scope in the RHS of a let-such-that expression scope.PushMarker(); foreach (var lhs in e.LHSs) { Contract.Assert(lhs.Var != null); // the parser already checked that every LHS is a BoundVar, not a general pattern var v = lhs.Var; ScopePushAndReport(scope, v, "let-variable"); ResolveType(v.tok, v.Type, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); AddTypeDependencyEdges(opts.codeContext, v.Type); } foreach (var rhs in e.RHSs) { ResolveExpression(rhs, opts); ConstrainTypeExprBool(rhs, "type of RHS of let-such-that expression must be boolean (got {0})"); } } ResolveExpression(e.Body, opts); ResolveAttributes(e.Attributes, e, opts); scope.PopMarker(); expr.Type = e.Body.Type; } else if (expr is LetOrFailExpr) { var e = (LetOrFailExpr)expr; ResolveLetOrFailExpr(e, opts); } else if (expr is QuantifierExpr) { var e = (QuantifierExpr)expr; if (opts.codeContext is Function) { ((Function)opts.codeContext).ContainsQuantifier = true; } Contract.Assert(e.SplitQuantifier == null); // No split quantifiers during resolution int prevErrorCount = reporter.Count(ErrorLevel.Error); bool _val = true; bool typeQuantifier = Attributes.ContainsBool(e.Attributes, "typeQuantifier", ref _val) && _val; allTypeParameters.PushMarker(); ResolveTypeParameters(e.TypeArgs, true, e); scope.PushMarker(); foreach (BoundVar v in e.BoundVars) { ScopePushAndReport(scope, v, "bound-variable"); var option = typeQuantifier ? new ResolveTypeOption(e) : new ResolveTypeOption(ResolveTypeOptionEnum.InferTypeProxies); ResolveType(v.tok, v.Type, opts.codeContext, option, typeQuantifier ? e.TypeArgs : null); } if (e.TypeArgs.Count > 0 && !typeQuantifier) { reporter.Error(MessageSource.Resolver, expr, "a quantifier cannot quantify over types. Possible fix: use the experimental attribute :typeQuantifier"); } if (e.Range != null) { ResolveExpression(e.Range, opts); Contract.Assert(e.Range.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.Range, "range of quantifier must be of type bool (instead got {0})"); } ResolveExpression(e.Term, opts); Contract.Assert(e.Term.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.Term, "body of quantifier must be of type bool (instead got {0})"); // Since the body is more likely to infer the types of the bound variables, resolve it // first (above) and only then resolve the attributes (below). ResolveAttributes(e.Attributes, e, opts); scope.PopMarker(); allTypeParameters.PopMarker(); expr.Type = Type.Bool; } else if (expr is SetComprehension) { var e = (SetComprehension)expr; int prevErrorCount = reporter.Count(ErrorLevel.Error); scope.PushMarker(); foreach (BoundVar v in e.BoundVars) { ScopePushAndReport(scope, v, "bound-variable"); ResolveType(v.tok, v.Type, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); var inferredProxy = v.Type as InferredTypeProxy; if (inferredProxy != null) { Contract.Assert(!inferredProxy.KeepConstraints); // in general, this proxy is inferred to be a base type } } ResolveExpression(e.Range, opts); Contract.Assert(e.Range.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.Range, "range of comprehension must be of type bool (instead got {0})"); ResolveExpression(e.Term, opts); Contract.Assert(e.Term.Type != null); // follows from postcondition of ResolveExpression ResolveAttributes(e.Attributes, e, opts); scope.PopMarker(); expr.Type = new SetType(e.Finite, e.Term.Type); } else if (expr is MapComprehension) { var e = (MapComprehension)expr; int prevErrorCount = reporter.Count(ErrorLevel.Error); scope.PushMarker(); Contract.Assert(e.BoundVars.Count == 1 || (1 < e.BoundVars.Count && e.TermLeft != null)); foreach (BoundVar v in e.BoundVars) { ScopePushAndReport(scope, v, "bound-variable"); ResolveType(v.tok, v.Type, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); var inferredProxy = v.Type as InferredTypeProxy; if (inferredProxy != null) { Contract.Assert(!inferredProxy.KeepConstraints); // in general, this proxy is inferred to be a base type } } ResolveExpression(e.Range, opts); Contract.Assert(e.Range.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.Range, "range of comprehension must be of type bool (instead got {0})"); if (e.TermLeft != null) { ResolveExpression(e.TermLeft, opts); Contract.Assert(e.TermLeft.Type != null); // follows from postcondition of ResolveExpression } ResolveExpression(e.Term, opts); Contract.Assert(e.Term.Type != null); // follows from postcondition of ResolveExpression ResolveAttributes(e.Attributes, e, opts); scope.PopMarker(); expr.Type = new MapType(e.Finite, e.TermLeft != null ? e.TermLeft.Type : e.BoundVars[0].Type, e.Term.Type); } else if (expr is LambdaExpr) { var e = (LambdaExpr)expr; int prevErrorCount = reporter.Count(ErrorLevel.Error); scope.PushMarker(); foreach (BoundVar v in e.BoundVars) { ScopePushAndReport(scope, v, "bound-variable"); ResolveType(v.tok, v.Type, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); } if (e.Range != null) { ResolveExpression(e.Range, opts); Contract.Assert(e.Range.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.Range, "Precondition must be boolean (got {0})"); } foreach (var read in e.Reads) { ResolveFrameExpression(read, FrameExpressionUse.Reads, opts.codeContext); } ResolveExpression(e.Term, opts); Contract.Assert(e.Term.Type != null); scope.PopMarker(); expr.Type = SelectAppropriateArrowType(e.tok, e.BoundVars.ConvertAll(v => v.Type), e.Body.Type, e.Reads.Count != 0, e.Range != null); } else if (expr is WildcardExpr) { expr.Type = new SetType(true, builtIns.ObjectQ()); } else if (expr is StmtExpr) { var e = (StmtExpr)expr; int prevErrorCount = reporter.Count(ErrorLevel.Error); ResolveStatement(e.S, opts.codeContext); if (reporter.Count(ErrorLevel.Error) == prevErrorCount) { var r = e.S as UpdateStmt; if (r != null && r.ResolvedStatements.Count == 1) { var call = r.ResolvedStatements[0] as CallStmt; if (call.Method.Mod.Expressions.Count != 0) { reporter.Error(MessageSource.Resolver, call, "calls to methods with side-effects are not allowed inside a statement expression"); } else if (call.Method is TwoStateLemma && !opts.twoState) { reporter.Error(MessageSource.Resolver, call, "two-state lemmas can only be used in two-state contexts"); } } } ResolveExpression(e.E, opts); Contract.Assert(e.E.Type != null); // follows from postcondition of ResolveExpression expr.Type = e.E.Type; } else if (expr is ITEExpr) { ITEExpr e = (ITEExpr)expr; ResolveExpression(e.Test, opts); Contract.Assert(e.Test.Type != null); // follows from postcondition of ResolveExpression ResolveExpression(e.Thn, opts); Contract.Assert(e.Thn.Type != null); // follows from postcondition of ResolveExpression ResolveExpression(e.Els, opts); Contract.Assert(e.Els.Type != null); // follows from postcondition of ResolveExpression ConstrainTypeExprBool(e.Test, "guard condition in if-then-else expression must be a boolean (instead got {0})"); expr.Type = new InferredTypeProxy(); ConstrainSubtypeRelation(expr.Type, e.Thn.Type, expr, "the two branches of an if-then-else expression must have the same type (got {0} and {1})", e.Thn.Type, e.Els.Type); ConstrainSubtypeRelation(expr.Type, e.Els.Type, expr, "the two branches of an if-then-else expression must have the same type (got {0} and {1})", e.Thn.Type, e.Els.Type); } else if (expr is MatchExpr) { ResolveMatchExpr((MatchExpr)expr, opts); } else if (expr is NestedMatchExpr) { NestedMatchExpr e = (NestedMatchExpr)expr; ResolveNestedMatchExpr(e, opts); if (e.ResolvedExpression != null && e.ResolvedExpression.Type != null) { // i.e. no error was thrown during compiling of the NextedMatchExpr or during resolution of the ResolvedExpression expr.Type = e.ResolvedExpression.Type; } } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression } if (expr.Type == null) { // some resolution error occurred expr.Type = new InferredTypeProxy(); } } private Expression VarDotFunction(IToken tok, string varname, string functionname) { return new ApplySuffix(tok, new ExprDotName(tok, new IdentifierExpr(tok, varname), functionname, null), new List<Expression>() { }); } // TODO search for occurrences of "new LetExpr" which could benefit from this helper private LetExpr LetPatIn(IToken tok, CasePattern<BoundVar> lhs, Expression rhs, Expression body) { return new LetExpr(tok, new List<CasePattern<BoundVar>>() { lhs }, new List<Expression>() { rhs }, body, true); } private LetExpr LetVarIn(IToken tok, string name, Type tp, Expression rhs, Expression body) { var lhs = new CasePattern<BoundVar>(tok, new BoundVar(tok, name, tp)); return LetPatIn(tok, lhs, rhs, body); } /// <summary> /// If expr.Lhs != null: Desugars "var x: T :- E; F" into "var temp := E; if temp.IsFailure() then temp.PropagateFailure() else var x: T := temp.Extract(); F" /// If expr.Lhs == null: Desugars " :- E; F" into "var temp := E; if temp.IsFailure() then temp.PropagateFailure() else F" /// </summary> public void ResolveLetOrFailExpr(LetOrFailExpr expr, ResolveOpts opts) { var temp = FreshTempVarName("valueOrError", opts.codeContext); var tempType = new InferredTypeProxy(); // "var temp := E;" expr.ResolvedExpression = LetVarIn(expr.tok, temp, tempType, expr.Rhs, // "if temp.IsFailure()" new ITEExpr(expr.tok, false, VarDotFunction(expr.tok, temp, "IsFailure"), // "then temp.PropagateFailure()" VarDotFunction(expr.tok, temp, "PropagateFailure"), // "else" expr.Lhs == null // "F" ? expr.Body // "var x: T := temp.Extract(); F" : LetPatIn(expr.tok, expr.Lhs, VarDotFunction(expr.tok, temp, "Extract"), expr.Body))); ResolveExpression(expr.ResolvedExpression, opts); expr.Type = expr.ResolvedExpression.Type; bool expectExtract = (expr.Lhs != null); EnsureSupportsErrorHandling(expr.tok, PartiallyResolveTypeForMemberSelection(expr.tok, tempType), expectExtract, false); } private Type SelectAppropriateArrowType(IToken tok, List<Type> typeArgs, Type resultType, bool hasReads, bool hasReq) { Contract.Requires(tok != null); Contract.Requires(typeArgs != null); Contract.Requires(resultType != null); var arity = typeArgs.Count; var typeArgsAndResult = Util.Snoc(typeArgs, resultType); if (hasReads) { // any arrow return new ArrowType(tok, builtIns.ArrowTypeDecls[arity], typeArgsAndResult); } else if (hasReq) { // partial arrow return new UserDefinedType(tok, ArrowType.PartialArrowTypeName(arity), builtIns.PartialArrowTypeDecls[arity], typeArgsAndResult); } else { // total arrow return new UserDefinedType(tok, ArrowType.TotalArrowTypeName(arity), builtIns.TotalArrowTypeDecls[arity], typeArgsAndResult); } } /// <summary> /// Adds appropriate type constraints that says "expr" evaluates to an integer or (if "allowBitVector" is true) a /// a bitvector. The "errFormat" string can contain a "{0}", referring to the name of the type of "expr". /// </summary> void ConstrainToIntegerType(Expression expr, bool allowBitVector, string errFormat) { Contract.Requires(expr != null); Contract.Requires(errFormat != null); var err = new TypeConstraint.ErrorMsgWithToken(expr.tok, errFormat, expr.Type); ConstrainToIntegerType(expr.tok, expr.Type, allowBitVector, err); } /// <summary> /// See ConstrainToIntegerType description for the overload above. /// </summary> void ConstrainToIntegerType(IToken tok, Type type, bool allowBitVector, TypeConstraint.ErrorMsg errorMsg) { Contract.Requires(tok != null); Contract.Requires(type != null); Contract.Requires(errorMsg != null); // We do two constraints: the first can aid in determining types, but allows bit-vectors; the second excludes bit-vectors. // However, we reuse the error message, so that only one error gets reported. ConstrainSubtypeRelation(new IntVarietiesSupertype(), type, errorMsg); if (!allowBitVector) { AddXConstraint(tok, "IntegerType", type, errorMsg); } } void AddAssignableConstraint(IToken tok, Type lhs, Type rhs, string errMsgFormat) { Contract.Requires(tok != null); Contract.Requires(lhs != null); Contract.Requires(rhs != null); Contract.Requires(errMsgFormat != null); AddXConstraint(tok, "Assignable", lhs, rhs, errMsgFormat); } private void AddXConstraint(IToken tok, string constraintName, Type type, string errMsgFormat) { Contract.Requires(tok != null); Contract.Requires(constraintName != null); Contract.Requires(type != null); Contract.Requires(errMsgFormat != null); var types = new Type[] { type }; AllXConstraints.Add(new XConstraint(tok, constraintName, types, new TypeConstraint.ErrorMsgWithToken(tok, errMsgFormat, types))); } void AddAssignableConstraint(IToken tok, Type lhs, Type rhs, TypeConstraint.ErrorMsg errMsg) { Contract.Requires(tok != null); Contract.Requires(lhs != null); Contract.Requires(rhs != null); Contract.Requires(errMsg != null); AddXConstraint(tok, "Assignable", lhs, rhs, errMsg); } private void AddXConstraint(IToken tok, string constraintName, Type type, TypeConstraint.ErrorMsg errMsg) { Contract.Requires(tok != null); Contract.Requires(constraintName != null); Contract.Requires(type != null); Contract.Requires(errMsg != null); var types = new Type[] { type }; AllXConstraints.Add(new XConstraint(tok, constraintName, types, errMsg)); } private void AddXConstraint(IToken tok, string constraintName, Type type0, Type type1, string errMsgFormat) { Contract.Requires(tok != null); Contract.Requires(constraintName != null); Contract.Requires(type0 != null); Contract.Requires(type1 != null); Contract.Requires(errMsgFormat != null); var types = new Type[] { type0, type1 }; AllXConstraints.Add(new XConstraint(tok, constraintName, types, new TypeConstraint.ErrorMsgWithToken(tok, errMsgFormat, types))); } private void AddXConstraint(IToken tok, string constraintName, Type type0, Type type1, TypeConstraint.ErrorMsg errMsg) { Contract.Requires(tok != null); Contract.Requires(constraintName != null); Contract.Requires(type0 != null); Contract.Requires(type1 != null); Contract.Requires(errMsg != null); var types = new Type[] { type0, type1 }; AllXConstraints.Add(new XConstraint(tok, constraintName, types, errMsg)); } private void AddXConstraint(IToken tok, string constraintName, Type type, Expression expr0, Expression expr1, string errMsgFormat) { Contract.Requires(tok != null); Contract.Requires(constraintName != null); Contract.Requires(type != null); Contract.Requires(expr0 != null); Contract.Requires(expr1 != null); Contract.Requires(errMsgFormat != null); var types = new Type[] { type }; var exprs = new Expression[] { expr0, expr1 }; AllXConstraints.Add(new XConstraintWithExprs(tok, constraintName, types, exprs, new TypeConstraint.ErrorMsgWithToken(tok, errMsgFormat, types))); } /// <summary> /// Attempts to rewrite a datatype update into more primitive operations, after doing the appropriate resolution checks. /// Upon success, returns that rewritten expression and sets "legalSourceConstructors". /// Upon some resolution error, return null. /// </summary> Expression ResolveDatatypeUpdate(IToken tok, Expression root, DatatypeDecl dt, List<Tuple<IToken, string, Expression>> memberUpdates, ResolveOpts opts, out List<DatatypeCtor> legalSourceConstructors) { Contract.Requires(tok != null); Contract.Requires(root != null); Contract.Requires(dt != null); Contract.Requires(memberUpdates != null); Contract.Requires(opts != null); legalSourceConstructors = null; // First, compute the list of candidate result constructors, that is, the constructors // that have all of the mentioned destructors. Issue errors for duplicated names and for // names that are not destructors in the datatype. var candidateResultCtors = dt.Ctors; // list of constructors that have all the so-far-mentioned destructors var memberNames = new HashSet<string>(); var rhsBindings = new Dictionary<string, Tuple<BoundVar/*let variable*/, IdentifierExpr/*id expr for let variable*/, Expression /*RHS in given syntax*/>>(); var subst = TypeSubstitutionMap(dt.TypeArgs, root.Type.NormalizeExpand().TypeArgs); foreach (var entry in memberUpdates) { var destructor_str = entry.Item2; if (memberNames.Contains(destructor_str)) { reporter.Error(MessageSource.Resolver, entry.Item1, "duplicate update member '{0}'", destructor_str); } else { memberNames.Add(destructor_str); MemberDecl member; if (!classMembers[dt].TryGetValue(destructor_str, out member)) { reporter.Error(MessageSource.Resolver, entry.Item1, "member '{0}' does not exist in datatype '{1}'", destructor_str, dt.Name); } else if (!(member is DatatypeDestructor)) { reporter.Error(MessageSource.Resolver, entry.Item1, "member '{0}' is not a destructor in datatype '{1}'", destructor_str, dt.Name); } else { var destructor = (DatatypeDestructor)member; var intersection = new List<DatatypeCtor>(candidateResultCtors.Intersect(destructor.EnclosingCtors)); if (intersection.Count == 0) { reporter.Error(MessageSource.Resolver, entry.Item1, "updated datatype members must belong to the same constructor (unlike the previously mentioned destructors, '{0}' does not belong to {1})", destructor_str, DatatypeDestructor.PrintableCtorNameList(candidateResultCtors, "or")); } else { candidateResultCtors = intersection; if (destructor.IsGhost) { rhsBindings.Add(destructor_str, new Tuple<BoundVar, IdentifierExpr, Expression>(null, null, entry.Item3)); } else { var xName = FreshTempVarName(string.Format("dt_update#{0}#", destructor_str), opts.codeContext); var xVar = new BoundVar(new AutoGeneratedToken(tok), xName, SubstType(destructor.Type, subst)); var x = new IdentifierExpr(new AutoGeneratedToken(tok), xVar); rhsBindings.Add(destructor_str, new Tuple<BoundVar, IdentifierExpr, Expression>(xVar, x, entry.Item3)); } } } } } if (candidateResultCtors.Count == 0) { return null; } // Check that every candidate result constructor has given a name to all of its parameters. var hasError = false; foreach (var ctor in candidateResultCtors) { if (ctor.Formals.Exists(f => !f.HasName)) { reporter.Error(MessageSource.Resolver, tok, "candidate result constructor '{0}' has an anonymous parameter (to use in datatype update expression, name all the parameters of the candidate result constructors)", ctor.Name); hasError = true; } } if (hasError) { return null; } // The legal source constructors are the candidate result constructors. (Yep, two names for the same thing.) legalSourceConstructors = candidateResultCtors; Contract.Assert(1 <= legalSourceConstructors.Count); // Rewrite the datatype update root.(x := X, y := Y, ...) to: // var d := root; // var x := X; // EXCEPT: don't do this for ghost fields // var y := Y; // .. // if d.CandidateResultConstructor0 then // CandidateResultConstructor0(x, y, ..., d.f0, d.f1, ...) // for a ghost field x, use the expression X directly // else if d.CandidateResultConstructor1 then // CandidateResultConstructor0(x, y, ..., d.g0, d.g1, ...) // ... // else // CandidateResultConstructorN(x, y, ..., d.k0, d.k1, ...) // Expression rewrite = null; // Create a unique name for d', the variable we introduce in the let expression var dName = FreshTempVarName("dt_update_tmp#", opts.codeContext); var dVar = new BoundVar(new AutoGeneratedToken(tok), dName, root.Type); var d = new IdentifierExpr(new AutoGeneratedToken(tok), dVar); Expression body = null; candidateResultCtors.Reverse(); foreach (var crc in candidateResultCtors) { // Build the arguments to the datatype constructor, using the updated value in the appropriate slot var ctor_args = new List<Expression>(); foreach (var f in crc.Formals) { Tuple<BoundVar/*let variable*/, IdentifierExpr/*id expr for let variable*/, Expression /*RHS in given syntax*/> info; if (rhsBindings.TryGetValue(f.Name, out info)) { ctor_args.Add(info.Item2 ?? info.Item3); } else { ctor_args.Add(new ExprDotName(tok, d, f.Name, null)); } } var ctor_call = new DatatypeValue(tok, crc.EnclosingDatatype.Name, crc.Name, ctor_args); ResolveDatatypeValue(opts, ctor_call, dt, root.Type.NormalizeExpand()); // resolve to root.Type, so that type parameters get filled in appropriately if (body == null) { body = ctor_call; } else { // body = if d.crc? then ctor_call else body var guard = new ExprDotName(tok, d, crc.QueryField.Name, null); body = new ITEExpr(tok, false, guard, ctor_call, body); } } Contract.Assert(body != null); // because there was at least one element in candidateResultCtors // Wrap the let's around body rewrite = body; foreach (var entry in rhsBindings) { if (entry.Value.Item1 != null) { var lhs = new CasePattern<BoundVar>(tok, entry.Value.Item1); rewrite = new LetExpr(tok, new List<CasePattern<BoundVar>>() { lhs }, new List<Expression>() { entry.Value.Item3 }, rewrite, true); } } var dVarPat = new CasePattern<BoundVar>(tok, dVar); rewrite = new LetExpr(tok, new List<CasePattern<BoundVar>>() { dVarPat }, new List<Expression>() { root }, rewrite, true); Contract.Assert(rewrite != null); ResolveExpression(rewrite, opts); return rewrite; } /// <summary> /// Resolves a NestedMatchExpr by /// 1 - checking that all of its patterns are linear /// 2 - desugaring it into a decision tree of MatchExpr and ITEEXpr (for constant matching) /// 3 - resolving the generated (sub)expression. /// </summary> void ResolveNestedMatchExpr(NestedMatchExpr me, ResolveOpts opts) { Contract.Requires(me != null); Contract.Requires(opts != null); Contract.Requires(me.ResolvedExpression == null); bool debug = DafnyOptions.O.MatchCompilerDebug; ResolveExpression(me.Source, opts); Contract.Assert(me.Source.Type != null); // follows from postcondition of ResolveExpression if (me.Source.Type is TypeProxy) { PartiallySolveTypeConstraints(true); if (debug) Console.WriteLine("DEBUG: Type of {0} was still a proxy, solving type constraints results in type {1}", Printer.ExprToString(me.Source), me.Source.Type.ToString()); if (me.Source.Type is TypeProxy) { reporter.Error(MessageSource.Resolver, me.tok, "Could not resolve the type of the source of the match expression. Please provide additional typing annotations."); return; } } var errorCount = reporter.Count(ErrorLevel.Error); var sourceType = PartiallyResolveTypeForMemberSelection(me.Source.tok, me.Source.Type).NormalizeExpand(); if (reporter.Count(ErrorLevel.Error) != errorCount) return; errorCount = reporter.Count(ErrorLevel.Error); if (debug) Console.WriteLine("DEBUG: {0} ResolveNestedMatchExpr 1 - Checking Linearity of patterns", me.tok.line); CheckLinearNestedMatchExpr(sourceType, me, opts); if (reporter.Count(ErrorLevel.Error) != errorCount) return; errorCount = reporter.Count(ErrorLevel.Error); if (debug) Console.WriteLine("DEBUG: {0} ResolveNestedMatchExpr 2 - Compiling Nested Match", me.tok.line); CompileNestedMatchExpr(me, opts); if (reporter.Count(ErrorLevel.Error) != errorCount) return; if (debug) Console.WriteLine("DEBUG: {0} ResolveNestedMatchExpr 3 - Resolving Expression", me.tok.line); ResolveExpression(me.ResolvedExpression, opts); if (debug) Console.WriteLine("DEBUG: {0} ResolveNestedMatchExpr DONE"); } void ResolveMatchExpr(MatchExpr me, ResolveOpts opts) { Contract.Requires(me != null); Contract.Requires(opts != null); Contract.Requires(me.OrigUnresolved == null); bool debug = DafnyOptions.O.MatchCompilerDebug; if (debug) Console.WriteLine("DEBUG: {0} In ResolvedMatchExpr" ); // first, clone the original expression me.OrigUnresolved = (MatchExpr)new Cloner().CloneExpr(me); ResolveExpression(me.Source, opts); Contract.Assert(me.Source.Type != null); // follows from postcondition of ResolveExpression var sourceType = PartiallyResolveTypeForMemberSelection(me.Source.tok, me.Source.Type).NormalizeExpand(); if (debug) Console.WriteLine("DEBUG: {0} ResolvedMatchExpr - Done Resolving Source" ); var dtd = sourceType.AsDatatype; var subst = new Dictionary<TypeParameter, Type>(); Dictionary<string, DatatypeCtor> ctors; if (dtd == null) { reporter.Error(MessageSource.Resolver, me.Source, "the type of the match source expression must be a datatype (instead found {0})", me.Source.Type); ctors = null; } else { Contract.Assert(sourceType != null); // dtd and sourceType are set together above ctors = datatypeCtors[dtd]; Contract.Assert(ctors != null); // dtd should have been inserted into datatypeCtors during a previous resolution stage // build the type-parameter substitution map for this use of the datatype subst = TypeSubstitutionMap(dtd.TypeArgs, sourceType.TypeArgs); } ISet<string> memberNamesUsed = new HashSet<string>(); me.Type = new InferredTypeProxy(); foreach (MatchCaseExpr mc in me.Cases) { if (ctors != null) { Contract.Assert(dtd != null); var ctorId = mc.Ctor.Name; if (me.Source.Type.AsDatatype is TupleTypeDecl) { var tuple = (TupleTypeDecl)me.Source.Type.AsDatatype; var dims = tuple.Dims; ctorId = BuiltIns.TupleTypeCtorNamePrefix + dims; } if (!ctors.ContainsKey(ctorId)) { reporter.Error(MessageSource.Resolver, mc.tok, "member '{0}' does not exist in datatype '{1}'", ctorId, dtd.Name); } else { if (mc.Ctor.Formals.Count != mc.Arguments.Count) { if (me.Source.Type.AsDatatype is TupleTypeDecl) { reporter.Error(MessageSource.Resolver, mc.tok, "case arguments count does not match source arguments count"); } else { reporter.Error(MessageSource.Resolver, mc.tok, "member {0} has wrong number of formals (found {1}, expected {2})", ctorId, mc.Arguments.Count, mc.Ctor.Formals.Count); } } if (memberNamesUsed.Contains(ctorId)) { reporter.Error(MessageSource.Resolver, mc.tok, "member {0} appears in more than one case", mc.Ctor.Name); } else { memberNamesUsed.Add(ctorId); // add mc.Id to the set of names used } } } scope.PushMarker(); int i = 0; if (mc.Arguments != null) { foreach (BoundVar v in mc.Arguments) { scope.Push(v.Name, v); ResolveType(v.tok, v.Type, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); if (i < mc.Ctor.Formals.Count) { Formal formal = mc.Ctor.Formals[i]; Type st = SubstType(formal.Type, subst); ConstrainSubtypeRelation(v.Type, st, me, "the declared type of the formal ({0}) does not agree with the corresponding type in the constructor's signature ({1})", v.Type, st); v.IsGhost = formal.IsGhost; // update the type of the boundvars in the MatchCaseToken if (v.tok is MatchCaseToken) { MatchCaseToken mt = (MatchCaseToken)v.tok; foreach (Tuple<IToken, BoundVar, bool> entry in mt.varList) { ConstrainSubtypeRelation(entry.Item2.Type, v.Type, entry.Item1, "incorrect type for bound match-case variable (expected {0}, got {1})", v.Type, entry.Item2.Type); } } } i++; } } if (debug) Console.WriteLine("DEBUG: {1} ResolvedMatchExpr - Resolving Body: {0}", Printer.ExprToString(mc.Body), mc.Body.tok.line); ResolveExpression(mc.Body, opts); Contract.Assert(mc.Body.Type != null); // follows from postcondition of ResolveExpression ConstrainSubtypeRelation(me.Type, mc.Body.Type, mc.Body.tok, "type of case bodies do not agree (found {0}, previous types {1})", mc.Body.Type, me.Type); scope.PopMarker(); } if (dtd != null && memberNamesUsed.Count != dtd.Ctors.Count) { // We could complain about the syntactic omission of constructors: // reporter.Error(MessageSource.Resolver, expr, "match expression does not cover all constructors"); // but instead we let the verifier do a semantic check. // So, for now, record the missing constructors: foreach (var ctr in dtd.Ctors) { if (!memberNamesUsed.Contains(ctr.Name)) { me.MissingCases.Add(ctr); } } Contract.Assert(memberNamesUsed.Count + me.MissingCases.Count == dtd.Ctors.Count); } if (debug) Console.WriteLine("DEBUG: {0} ResolvedMatchExpr - DONE", me.tok.line ); } void ResolveCasePattern<VT>(CasePattern<VT> pat, Type sourceType, ICodeContext context) where VT: IVariable { Contract.Requires(pat != null); Contract.Requires(sourceType != null); Contract.Requires(context != null); DatatypeDecl dtd = null; UserDefinedType udt = null; if (sourceType.IsDatatype) { udt = (UserDefinedType)sourceType.NormalizeExpand(); dtd = (DatatypeDecl)udt.ResolvedClass; } // Find the constructor in the given datatype // If what was parsed was just an identifier, we will interpret it as a datatype constructor, if possible DatatypeCtor ctor = null; if (dtd != null) { if (pat.Var == null || (pat.Var != null && pat.Var.Type is TypeProxy)) { if (datatypeCtors[dtd].TryGetValue(pat.Id, out ctor)) { if (pat.Arguments == null) { if (ctor.Formals.Count != 0) { // Leave this as a variable } else { // Convert to a constructor pat.MakeAConstructor(); pat.Ctor = ctor; pat.Var = default(VT); } } else { pat.Ctor = ctor; pat.Var = default(VT); } } } } if (pat.Var != null) { // this is a simple resolution var v = pat.Var; ResolveType(v.Tok, v.Type, context, ResolveTypeOptionEnum.InferTypeProxies, null); AddTypeDependencyEdges(context, v.Type); // Note, the following type constraint checks that the RHS type can be assigned to the new variable on the left. In particular, it // does not check that the entire RHS can be assigned to something of the type of the pattern on the left. For example, consider // a type declared as "datatype Atom<T> = MakeAtom(T)", where T is a non-variant type argument. Suppose the RHS has type Atom<nat> // and that the LHS is the pattern MakeAtom(x: int). This is okay, despite the fact that Atom<nat> is not assignable to Atom<int>. // The reason is that the purpose of the pattern on the left is really just to provide a skeleton to introduce bound variables in. AddAssignableConstraint(v.Tok, v.Type, sourceType, "type of corresponding source/RHS ({1}) does not match type of bound variable ({0})"); pat.AssembleExpr(null); return; } if (dtd == null) { // look up the name of the pattern's constructor Tuple<DatatypeCtor, bool> pair; if (moduleInfo.Ctors.TryGetValue(pat.Id, out pair) && !pair.Item2) { ctor = pair.Item1; pat.Ctor = ctor; dtd = ctor.EnclosingDatatype; var typeArgs = new List<Type>(); foreach (var xt in dtd.TypeArgs) { typeArgs.Add(new InferredTypeProxy()); } udt = new UserDefinedType(pat.tok, dtd.Name, dtd, typeArgs); ConstrainSubtypeRelation(udt, sourceType, pat.tok, "type of RHS ({0}) does not match type of bound variable '{1}'", sourceType, pat.Id); } } if (dtd == null && ctor == null) { reporter.Error(MessageSource.Resolver, pat.tok, "to use a pattern, the type of the source/RHS expression must be a datatype (instead found {0})", sourceType); } else if (ctor == null) { reporter.Error(MessageSource.Resolver, pat.tok, "constructor {0} does not exist in datatype {1}", pat.Id, dtd.Name); } else { if (pat.Arguments == null) { if (ctor.Formals.Count == 0) { // The Id matches a constructor of the correct type and 0 arguments, // so make it a nullary constructor, not a variable pat.MakeAConstructor(); } } else { if (ctor.Formals.Count != pat.Arguments.Count) { reporter.Error(MessageSource.Resolver, pat.tok, "pattern for constructor {0} has wrong number of formals (found {1}, expected {2})", pat.Id, pat.Arguments.Count, ctor.Formals.Count); } } // build the type-parameter substitution map for this use of the datatype Contract.Assert(dtd.TypeArgs.Count == udt.TypeArgs.Count); // follows from the type previously having been successfully resolved var subst = TypeSubstitutionMap(dtd.TypeArgs, udt.TypeArgs); // recursively call ResolveCasePattern on each of the arguments var j = 0; if (pat.Arguments != null) { foreach (var arg in pat.Arguments) { if (j < ctor.Formals.Count) { var formal = ctor.Formals[j]; Type st = SubstType(formal.Type, subst); ResolveCasePattern(arg, st, context); } j++; } } if (j == ctor.Formals.Count) { pat.AssembleExpr(udt.TypeArgs); } } } /// <summary> /// Look up expr.Name in the following order: /// 0. Local variable, parameter, or bound variable. /// (Language design note: If this clashes with something of interest, one can always rename the local variable locally.) /// 1. Member of enclosing class (an implicit "this" is inserted, if needed) /// 2. If isLastNameSegment: /// Unambiguous constructor name of a datatype in the enclosing module (if two constructors have the same name, an error message is produced here) /// (Language design note: If the constructor name is ambiguous or if one of the steps above takes priority, one can qualify the constructor name with the name of the datatype) /// 3. Member of the enclosing module (type name or the name of a module) /// 4. Static function or method in the enclosing module or its imports /// 5. If !isLastNameSegment: /// Unambiguous constructor name of a datatype in the enclosing module /// /// </summary> /// <param name="expr"></param> /// <param name="isLastNameSegment">Indicates that the NameSegment is not directly enclosed in another NameSegment or ExprDotName expression.</param> /// <param name="args">If the NameSegment is enclosed in an ApplySuffix, then these are the arguments. The method returns null to indicate /// that these arguments, if any, were not used. If args is non-null and the method does use them, the method returns the resolved expression /// that incorporates these arguments.</param> /// <param name="opts"></param> /// <param name="allowMethodCall">If false, generates an error if the name denotes a method. If true and the name denotes a method, returns /// a MemberSelectExpr whose .Member is a Method.</param> Expression ResolveNameSegment(NameSegment expr, bool isLastNameSegment, List<Expression> args, ResolveOpts opts, bool allowMethodCall, bool complain = true) { Contract.Requires(expr != null); Contract.Requires(!expr.WasResolved()); Contract.Requires(opts != null); Contract.Ensures(Contract.Result<Expression>() == null || args != null); if (expr.OptTypeArguments != null) { foreach (var ty in expr.OptTypeArguments) { ResolveType(expr.tok, ty, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); } } Expression r = null; // the resolved expression, if successful Expression rWithArgs = null; // the resolved expression after incorporating "args" // For 0: IVariable v; // For 1: Dictionary<string, MemberDecl> members; // For 1 and 4: MemberDecl member = null; // For 2 and 5: Tuple<DatatypeCtor, bool> pair; // For 3: TopLevelDecl decl; var name = opts.isReveal ? "reveal_" + expr.Name : expr.Name; v = scope.Find(name); if (v != null) { // ----- 0. local variable, parameter, or bound variable if (expr.OptTypeArguments != null) { if (complain) { reporter.Error(MessageSource.Resolver, expr.tok, "variable '{0}' does not take any type parameters", name); } else { expr.ResolvedExpression = null; return null; } } r = new IdentifierExpr(expr.tok, v); } else if (currentClass is TopLevelDeclWithMembers cl && classMembers.TryGetValue(cl, out members) && members.TryGetValue(name, out member)) { // ----- 1. member of the enclosing class Expression receiver; if (member.IsStatic) { receiver = new StaticReceiverExpr(expr.tok, UserDefinedType.FromTopLevelDecl(expr.tok, currentClass, currentClass.TypeArgs), (TopLevelDeclWithMembers)member.EnclosingClass, true); } else { if (!scope.AllowInstance) { if (complain) { reporter.Error(MessageSource.Resolver, expr.tok, "'this' is not allowed in a 'static' context"); //TODO: Rephrase this } else { expr.ResolvedExpression = null; return null; } // nevertheless, set "receiver" to a value so we can continue resolution } receiver = new ImplicitThisExpr(expr.tok); receiver.Type = GetThisType(expr.tok, currentClass); // resolve here } r = ResolveExprDotCall(expr.tok, receiver, null, member, args, expr.OptTypeArguments, opts, allowMethodCall); } else if (isLastNameSegment && moduleInfo.Ctors.TryGetValue(name, out pair)) { // ----- 2. datatype constructor if (ResolveDatatypeConstructor(expr, args, opts, complain, pair, name, ref r, ref rWithArgs)) { return null; } } else if (moduleInfo.TopLevels.TryGetValue(name, out decl)) { // ----- 3. Member of the enclosing module if (decl is AmbiguousTopLevelDecl) { var ad = (AmbiguousTopLevelDecl)decl; if (complain) { reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a type in one of the modules {1} (try qualifying the type name with the module name)", expr.Name, ad.ModuleNames()); } else { expr.ResolvedExpression = null; return null; } } else { // We have found a module name or a type name, neither of which is an expression. However, the NameSegment we're // looking at may be followed by a further suffix that makes this into an expresion. We postpone the rest of the // resolution to any such suffix. For now, we create a temporary expression that will never be seen by the compiler // or verifier, just to have a placeholder where we can recorded what we have found. if (!isLastNameSegment) { if (decl is ClassDecl cd && cd.NonNullTypeDecl != null && name != cd.NonNullTypeDecl.Name) { // A possibly-null type C? was mentioned. But it does not have any further members. The program should have used // the name of the class, C. Report an error and continue. if (complain) { reporter.Error(MessageSource.Resolver, expr.tok, "To access members of {0} '{1}', write '{1}', not '{2}'", decl.WhatKind, decl.Name, name); } else { expr.ResolvedExpression = null; return null; } } } r = CreateResolver_IdentifierExpr(expr.tok, name, expr.OptTypeArguments, decl); } } else if (moduleInfo.StaticMembers.TryGetValue(name, out member)) { // ----- 4. static member of the enclosing module Contract.Assert(member.IsStatic); // moduleInfo.StaticMembers is supposed to contain only static members of the module's implicit class _default if (member is AmbiguousMemberDecl) { var ambiguousMember = (AmbiguousMemberDecl)member; if (complain) { reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a static member in one of the modules {1} (try qualifying the member name with the module name)", expr.Name, ambiguousMember.ModuleNames()); } else { expr.ResolvedExpression = null; return null; } } else { var receiver = new StaticReceiverExpr(expr.tok, (ClassDecl)member.EnclosingClass, true); r = ResolveExprDotCall(expr.tok, receiver, null, member, args, expr.OptTypeArguments, opts, allowMethodCall); } } else if (!isLastNameSegment && moduleInfo.Ctors.TryGetValue(name, out pair)) { // ----- 5. datatype constructor if (ResolveDatatypeConstructor(expr, args, opts, complain, pair, name, ref r, ref rWithArgs)) { return null; } } else { // ----- None of the above if (complain) { reporter.Error(MessageSource.Resolver, expr.tok, "unresolved identifier: {0}", name); } else { expr.ResolvedExpression = null; return null; } } if (r == null) { // an error has been reported above; we won't fill in .ResolvedExpression, but we still must fill in .Type expr.Type = new InferredTypeProxy(); } else { expr.ResolvedExpression = r; var rt = r.Type; var nt = rt.UseInternalSynonym(); expr.Type = nt; } return rWithArgs; } private bool ResolveDatatypeConstructor(NameSegment expr, List<Expression>/*?*/ args, ResolveOpts opts, bool complain, Tuple<DatatypeCtor, bool> pair, string name, ref Expression r, ref Expression rWithArgs) { Contract.Requires(expr != null); Contract.Requires(opts != null); if (pair.Item2) { // there is more than one constructor with this name if (complain) { reporter.Error(MessageSource.Resolver, expr.tok, "the name '{0}' denotes a datatype constructor, but does not do so uniquely; add an explicit qualification (for example, '{1}.{0}')", expr.Name, pair.Item1.EnclosingDatatype.Name); } else { expr.ResolvedExpression = null; return true; } } else { if (expr.OptTypeArguments != null) { if (complain) { reporter.Error(MessageSource.Resolver, expr.tok, "datatype constructor does not take any type parameters ('{0}')", name); } else { expr.ResolvedExpression = null; return true; } } var rr = new DatatypeValue(expr.tok, pair.Item1.EnclosingDatatype.Name, name, args ?? new List<Expression>()); bool ok = ResolveDatatypeValue(opts, rr, pair.Item1.EnclosingDatatype, null, complain); if (!ok) { expr.ResolvedExpression = null; return true; } if (args == null) { r = rr; } else { r = rr; // this doesn't really matter, since we're returning an "rWithArgs" (but if would have been proper to have returned the ctor as a lambda) rWithArgs = rr; } } return false; } /// <summary> /// Look up expr.Name in the following order: /// 0. Type parameter /// 1. Member of enclosing class (an implicit "this" is inserted, if needed) /// 2. Member of the enclosing module (type name or the name of a module) /// 3. Static function or method in the enclosing module or its imports /// /// Note: 1 and 3 are not used now, but they will be of interest when async task types are supported. /// </summary> void ResolveNameSegment_Type(NameSegment expr, ResolveOpts opts, ResolveTypeOption option, List<TypeParameter> defaultTypeArguments) { Contract.Requires(expr != null); Contract.Requires(!expr.WasResolved()); Contract.Requires(opts != null); Contract.Requires((option.Opt == ResolveTypeOptionEnum.DontInfer || option.Opt == ResolveTypeOptionEnum.InferTypeProxies) == (defaultTypeArguments == null)); if (expr.OptTypeArguments != null) { foreach (var ty in expr.OptTypeArguments) { ResolveType(expr.tok, ty, opts.codeContext, option, defaultTypeArguments); } } Expression r = null; // the resolved expression, if successful // For 0: TypeParameter tp; #if ASYNC_TASK_TYPES // For 1: Dictionary<string, MemberDecl> members; // For 1 and 3: MemberDecl member = null; #endif // For 2: TopLevelDecl decl; tp = allTypeParameters.Find(expr.Name); if (tp != null) { // ----- 0. type parameter if (expr.OptTypeArguments == null) { r = new Resolver_IdentifierExpr(expr.tok, tp); } else { reporter.Error(MessageSource.Resolver, expr.tok, "Type parameter expects no type arguments: {0}", expr.Name); } #if ASYNC_TASK_TYPES // At the moment, there is no way for a class member to part of a type name, but this changes with async task types } else if (currentClass != null && classMembers.TryGetValue(currentClass, out members) && members.TryGetValue(expr.Name, out member)) { // ----- 1. member of the enclosing class Expression receiver; if (member.IsStatic) { receiver = new StaticReceiverExpr(expr.tok, (ClassDecl)member.EnclosingClass); } else { if (!scope.AllowInstance) { reporter.Error(MessageSource.Resolver, expr.tok, "'this' is not allowed in a 'static' context"); // nevertheless, set "receiver" to a value so we can continue resolution } receiver = new ImplicitThisExpr(expr.tok); receiver.Type = GetThisType(expr.tok, (ClassDecl)member.EnclosingClass); // resolve here } r = ResolveExprDotCall(expr.tok, receiver, member, expr.OptTypeArguments, opts.codeContext, allowMethodCall); #endif } else if (moduleInfo.TopLevels.TryGetValue(expr.Name, out decl)) { // ----- 2. Member of the enclosing module if (decl is AmbiguousTopLevelDecl) { var ad = (AmbiguousTopLevelDecl)decl; reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a type in one of the modules {1} (try qualifying the type name with the module name)", expr.Name, ad.ModuleNames()); } else { // We have found a module name or a type name, neither of which is a type expression. However, the NameSegment we're // looking at may be followed by a further suffix that makes this into a type expresion. We postpone the rest of the // resolution to any such suffix. For now, we create a temporary expression that will never be seen by the compiler // or verifier, just to have a placeholder where we can recorded what we have found. r = CreateResolver_IdentifierExpr(expr.tok, expr.Name, expr.OptTypeArguments, decl); } #if ASYNC_TASK_TYPES // At the moment, there is no way for a class member to part of a type name, but this changes with async task types } else if (moduleInfo.StaticMembers.TryGetValue(expr.Name, out member)) { // ----- 3. static member of the enclosing module Contract.Assert(member.IsStatic); // moduleInfo.StaticMembers is supposed to contain only static members of the module's implicit class _default if (ReallyAmbiguousThing(ref member)) { reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a static member in one of the modules {1} (try qualifying the member name with the module name)", expr.Name, ((AmbiguousMemberDecl)member).ModuleNames()); } else { var receiver = new StaticReceiverExpr(expr.tok, (ClassDecl)member.EnclosingClass); r = ResolveExprDotCall(expr.tok, receiver, member, expr.OptTypeArguments, opts.codeContext, allowMethodCall); } #endif } else { // ----- None of the above reporter.Error(MessageSource.Resolver, expr.tok, "Undeclared top-level type or type parameter: {0} (did you forget to qualify a name or declare a module import 'opened'?)", expr.Name); } if (r == null) { // an error has been reported above; we won't fill in .ResolvedExpression, but we still must fill in .Type expr.Type = new InferredTypeProxy(); } else { expr.ResolvedExpression = r; expr.Type = r.Type; } } Resolver_IdentifierExpr CreateResolver_IdentifierExpr(IToken tok, string name, List<Type> optTypeArguments, TopLevelDecl decl) { Contract.Requires(tok != null); Contract.Requires(name != null); Contract.Requires(decl != null); Contract.Ensures(Contract.Result<Resolver_IdentifierExpr>() != null); if (!moduleInfo.IsAbstract) { var md = decl as ModuleDecl; if (md != null && md.Signature.IsAbstract) { reporter.Error(MessageSource.Resolver, tok, "a compiled module is not allowed to use an abstract module ({0})", decl.Name); } } var n = optTypeArguments == null ? 0 : optTypeArguments.Count; if (optTypeArguments != null) { // type arguments were supplied; they must be equal in number to those expected if (n != decl.TypeArgs.Count) { reporter.Error(MessageSource.Resolver, tok, "Wrong number of type arguments ({0} instead of {1}) passed to {2}: {3}", n, decl.TypeArgs.Count, decl.WhatKind, name); } } List<Type> tpArgs = new List<Type>(); for (int i = 0; i < decl.TypeArgs.Count; i++) { tpArgs.Add(i < n ? optTypeArguments[i] : new InferredTypeProxy()); } return new Resolver_IdentifierExpr(tok, decl, tpArgs); } /// <summary> /// To resolve "id" in expression "E . id", do: /// * If E denotes a module name M: /// 0. If isLastNameSegment: /// Unambiguous constructor name of a datatype in module M (if two constructors have the same name, an error message is produced here) /// (Language design note: If the constructor name is ambiguous or if one of the steps above takes priority, one can qualify the constructor name with the name of the datatype) /// 1. Member of module M: sub-module (including submodules of imports), class, datatype, etc. /// (if two imported types have the same name, an error message is produced here) /// 2. Static function or method of M._default /// (Note that in contrast to ResolveNameSegment, imported modules, etc. are ignored) /// * If E denotes a type: /// 3. Look up id as a member of that type /// * If E denotes an expression: /// 4. Let T be the type of E. Look up id in T. /// </summary> /// <param name="expr"></param> /// <param name="isLastNameSegment">Indicates that the ExprDotName is not directly enclosed in another ExprDotName expression.</param> /// <param name="args">If the ExprDotName is enclosed in an ApplySuffix, then these are the arguments. The method returns null to indicate /// that these arguments, if any, were not used. If args is non-null and the method does use them, the method returns the resolved expression /// that incorporates these arguments.</param> /// <param name="opts"></param> /// <param name="allowMethodCall">If false, generates an error if the name denotes a method. If true and the name denotes a method, returns /// a Resolver_MethodCall.</param> Expression ResolveDotSuffix(ExprDotName expr, bool isLastNameSegment, List<Expression> args, ResolveOpts opts, bool allowMethodCall) { Contract.Requires(expr != null); Contract.Requires(!expr.WasResolved()); Contract.Requires(opts != null); Contract.Ensures(Contract.Result<Expression>() == null || args != null); // resolve the LHS expression // LHS should not be reveal lemma ResolveOpts nonRevealOpts = new ResolveOpts(opts.codeContext, opts.twoState, false, opts.isPostCondition, opts.InsideOld); if (expr.Lhs is NameSegment) { ResolveNameSegment((NameSegment)expr.Lhs, false, null, nonRevealOpts, false); } else if (expr.Lhs is ExprDotName) { ResolveDotSuffix((ExprDotName)expr.Lhs, false, null, nonRevealOpts, false); } else { ResolveExpression(expr.Lhs, nonRevealOpts); } if (expr.OptTypeArguments != null) { foreach (var ty in expr.OptTypeArguments) { ResolveType(expr.tok, ty, opts.codeContext, ResolveTypeOptionEnum.InferTypeProxies, null); } } Expression r = null; // the resolved expression, if successful Expression rWithArgs = null; // the resolved expression after incorporating "args" MemberDecl member = null; var name = opts.isReveal ? "reveal_" + expr.SuffixName : expr.SuffixName; var lhs = expr.Lhs.Resolved; if (lhs != null && lhs.Type is Resolver_IdentifierExpr.ResolverType_Module) { var ri = (Resolver_IdentifierExpr)lhs; var sig = ((ModuleDecl)ri.Decl).AccessibleSignature(useCompileSignatures); sig = GetSignature(sig); // For 0: Tuple<DatatypeCtor, bool> pair; // For 1: TopLevelDecl decl; if (isLastNameSegment && sig.Ctors.TryGetValue(name, out pair)) { // ----- 0. datatype constructor if (pair.Item2) { // there is more than one constructor with this name reporter.Error(MessageSource.Resolver, expr.tok, "the name '{0}' denotes a datatype constructor in module {2}, but does not do so uniquely; add an explicit qualification (for example, '{1}.{0}')", name, pair.Item1.EnclosingDatatype.Name, ((ModuleDecl)ri.Decl).Name); } else { if (expr.OptTypeArguments != null) { reporter.Error(MessageSource.Resolver, expr.tok, "datatype constructor does not take any type parameters ('{0}')", name); } var rr = new DatatypeValue(expr.tok, pair.Item1.EnclosingDatatype.Name, name, args ?? new List<Expression>()); ResolveDatatypeValue(opts, rr, pair.Item1.EnclosingDatatype, null); if (args == null) { r = rr; } else { r = rr; // this doesn't really matter, since we're returning an "rWithArgs" (but if would have been proper to have returned the ctor as a lambda) rWithArgs = rr; } } } else if (sig.TopLevels.TryGetValue(name, out decl)) { // ----- 1. Member of the specified module if (decl is AmbiguousTopLevelDecl) { var ad = (AmbiguousTopLevelDecl)decl; reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a type in one of the modules {1} (try qualifying the type name with the module name)", expr.SuffixName, ad.ModuleNames()); } else { // We have found a module name or a type name, neither of which is an expression. However, the ExprDotName we're // looking at may be followed by a further suffix that makes this into an expresion. We postpone the rest of the // resolution to any such suffix. For now, we create a temporary expression that will never be seen by the compiler // or verifier, just to have a placeholder where we can recorded what we have found. if (!isLastNameSegment) { if (decl is ClassDecl cd && cd.NonNullTypeDecl != null && name != cd.NonNullTypeDecl.Name) { // A possibly-null type C? was mentioned. But it does not have any further members. The program should have used // the name of the class, C. Report an error and continue. reporter.Error(MessageSource.Resolver, expr.tok, "To access members of {0} '{1}', write '{1}', not '{2}'", decl.WhatKind, decl.Name, name); } } r = CreateResolver_IdentifierExpr(expr.tok, name, expr.OptTypeArguments, decl); } } else if (sig.StaticMembers.TryGetValue(name, out member)) { // ----- 2. static member of the specified module Contract.Assert(member.IsStatic); // moduleInfo.StaticMembers is supposed to contain only static members of the module's implicit class _default if (member is AmbiguousMemberDecl) { var ambiguousMember = (AmbiguousMemberDecl)member; reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a static member in one of the modules {1} (try qualifying the member name with the module name)", expr.SuffixName, ambiguousMember.ModuleNames()); } else { var receiver = new StaticReceiverExpr(expr.tok, (ClassDecl)member.EnclosingClass, true); r = ResolveExprDotCall(expr.tok, receiver, null, member, args, expr.OptTypeArguments, opts, allowMethodCall); } } else { reporter.Error(MessageSource.Resolver, expr.tok, "unresolved identifier: {0}", name); } } else if (lhs != null && lhs.Type is Resolver_IdentifierExpr.ResolverType_Type) { var ri = (Resolver_IdentifierExpr)lhs; // ----- 3. Look up name in type Type ty; if (ri.TypeParamDecl != null) { ty = new UserDefinedType(ri.TypeParamDecl); } else { // expand any synonyms ty = new UserDefinedType(expr.tok, ri.Decl.Name, ri.Decl, ri.TypeArgs).NormalizeExpand(); } if (ty.IsDatatype) { // ----- LHS is a datatype var dt = ty.AsDatatype; Dictionary<string, DatatypeCtor> members; DatatypeCtor ctor; if (datatypeCtors.TryGetValue(dt, out members) && members.TryGetValue(name, out ctor)) { if (expr.OptTypeArguments != null) { reporter.Error(MessageSource.Resolver, expr.tok, "datatype constructor does not take any type parameters ('{0}')", name); } var rr = new DatatypeValue(expr.tok, ctor.EnclosingDatatype.Name, name, args ?? new List<Expression>()); ResolveDatatypeValue(opts, rr, ctor.EnclosingDatatype, ty); if (args == null) { r = rr; } else { r = rr; // this doesn't really matter, since we're returning an "rWithArgs" (but if would have been proper to have returned the ctor as a lambda) rWithArgs = rr; } } } var cd = r == null ? ty.AsTopLevelTypeWithMembersBypassInternalSynonym : null; if (cd != null) { // ----- LHS is a type with members Dictionary<string, MemberDecl> members; if (classMembers.TryGetValue(cd, out members) && members.TryGetValue(name, out member)) { if (!VisibleInScope(member)) { reporter.Error(MessageSource.Resolver, expr.tok, "member '{0}' has not been imported in this scope and cannot be accessed here", name); } if (!member.IsStatic) { reporter.Error(MessageSource.Resolver, expr.tok, "accessing member '{0}' requires an instance expression", name); //TODO Unify with similar error messages // nevertheless, continue creating an expression that approximates a correct one } var receiver = new StaticReceiverExpr(expr.tok, (UserDefinedType)ty.NormalizeExpand(), (TopLevelDeclWithMembers)member.EnclosingClass, false); r = ResolveExprDotCall(expr.tok, receiver, null, member, args, expr.OptTypeArguments, opts, allowMethodCall); } } if (r == null) { reporter.Error(MessageSource.Resolver, expr.tok, "member '{0}' does not exist in {2} '{1}'", name, ri.TypeParamDecl != null ? ri.TypeParamDecl.Name : ri.Decl.Name, ri.TypeParamDecl != null ? "type" : ri.Decl.WhatKind); } } else if (lhs != null) { // ----- 4. Look up name in the type of the Lhs NonProxyType tentativeReceiverType; member = ResolveMember(expr.tok, expr.Lhs.Type, name, out tentativeReceiverType); if (member != null) { Expression receiver; if (!member.IsStatic) { receiver = expr.Lhs; AddAssignableConstraint(expr.tok, tentativeReceiverType, receiver.Type, "receiver type ({1}) does not have a member named " + name); r = ResolveExprDotCall(expr.tok, receiver, tentativeReceiverType, member, args, expr.OptTypeArguments, opts, allowMethodCall); } else { receiver = new StaticReceiverExpr(expr.tok, (UserDefinedType)tentativeReceiverType, (TopLevelDeclWithMembers)member.EnclosingClass, false, lhs); r = ResolveExprDotCall(expr.tok, receiver, null, member, args, expr.OptTypeArguments, opts, allowMethodCall); } } } if (r == null) { // an error has been reported above; we won't fill in .ResolvedExpression, but we still must fill in .Type expr.Type = new InferredTypeProxy(); } else { expr.ResolvedExpression = r; expr.Type = r.Type; } return rWithArgs; } /// <summary> /// To resolve "id" in expression "E . id", do: /// * If E denotes a module name M: /// 0. Member of module M: sub-module (including submodules of imports), class, datatype, etc. /// (if two imported types have the same name, an error message is produced here) /// 1. Static member of M._default denoting an async task type /// (Note that in contrast to ResolveNameSegment_Type, imported modules, etc. are ignored) /// * If E denotes a type: /// 2. a. Member of that type denoting an async task type, or: /// b. If allowDanglingDotName: /// Return the type "E" and the given "expr", letting the caller try to make sense of the final dot-name. /// /// Note: 1 and 2a are not used now, but they will be of interest when async task types are supported. /// </summary> ResolveTypeReturn ResolveDotSuffix_Type(ExprDotName expr, ResolveOpts opts, bool allowDanglingDotName, ResolveTypeOption option, List<TypeParameter> defaultTypeArguments) { Contract.Requires(expr != null); Contract.Requires(!expr.WasResolved()); Contract.Requires(expr.Lhs is NameSegment || expr.Lhs is ExprDotName); Contract.Requires(opts != null); Contract.Ensures(Contract.Result<ResolveTypeReturn>() == null || allowDanglingDotName); // resolve the LHS expression if (expr.Lhs is NameSegment) { ResolveNameSegment_Type((NameSegment)expr.Lhs, opts, option, defaultTypeArguments); } else { ResolveDotSuffix_Type((ExprDotName)expr.Lhs, opts, false, option, defaultTypeArguments); } if (expr.OptTypeArguments != null) { foreach (var ty in expr.OptTypeArguments) { ResolveType(expr.tok, ty, opts.codeContext, option, defaultTypeArguments); } } Expression r = null; // the resolved expression, if successful var lhs = expr.Lhs.Resolved; if (lhs != null && lhs.Type is Resolver_IdentifierExpr.ResolverType_Module) { var ri = (Resolver_IdentifierExpr)lhs; var sig = ((ModuleDecl)ri.Decl).AccessibleSignature(useCompileSignatures); sig = GetSignature(sig); // For 0: TopLevelDecl decl; if (sig.TopLevels.TryGetValue(expr.SuffixName, out decl)) { // ----- 0. Member of the specified module if (decl is AmbiguousTopLevelDecl) { var ad = (AmbiguousTopLevelDecl)decl; reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a type in one of the modules {1} (try qualifying the type name with the module name)", expr.SuffixName, ad.ModuleNames()); } else { // We have found a module name or a type name. We create a temporary expression that will never be seen by the compiler // or verifier, just to have a placeholder where we can recorded what we have found. r = CreateResolver_IdentifierExpr(expr.tok, expr.SuffixName, expr.OptTypeArguments, decl); } #if ASYNC_TASK_TYPES } else if (sig.StaticMembers.TryGetValue(expr.SuffixName, out member)) { // ----- 1. static member of the specified module Contract.Assert(member.IsStatic); // moduleInfo.StaticMembers is supposed to contain only static members of the module's implicit class _default if (ReallyAmbiguousThing(ref member)) { reporter.Error(MessageSource.Resolver, expr.tok, "The name {0} ambiguously refers to a static member in one of the modules {1} (try qualifying the member name with the module name)", expr.SuffixName, ((AmbiguousMemberDecl)member).ModuleNames()); } else { var receiver = new StaticReceiverExpr(expr.tok, (ClassDecl)member.EnclosingClass); r = ResolveExprDotCall(expr.tok, receiver, member, expr.OptTypeArguments, opts.codeContext, allowMethodCall); } #endif } else { reporter.Error(MessageSource.Resolver, expr.tok, "module '{0}' does not declare a type '{1}'", ri.Decl.Name, expr.SuffixName); } } else if (lhs != null && lhs.Type is Resolver_IdentifierExpr.ResolverType_Type) { var ri = (Resolver_IdentifierExpr)lhs; // ----- 2. Look up name in type Type ty; if (ri.TypeParamDecl != null) { ty = new UserDefinedType(ri.TypeParamDecl); } else { ty = new UserDefinedType(expr.tok, ri.Decl.Name, ri.Decl, ri.TypeArgs); } if (allowDanglingDotName && ty.IsRefType) { return new ResolveTypeReturn(ty, expr); } if (r == null) { reporter.Error(MessageSource.Resolver, expr.tok, "member '{0}' does not exist in type '{1}' or cannot be part of type name", expr.SuffixName, ri.TypeParamDecl != null ? ri.TypeParamDecl.Name : ri.Decl.Name); } } if (r == null) { // an error has been reported above; we won't fill in .ResolvedExpression, but we still must fill in .Type expr.Type = new InferredTypeProxy(); } else { expr.ResolvedExpression = r; expr.Type = r.Type; } return null; } Expression ResolveExprDotCall(IToken tok, Expression receiver, Type receiverTypeBound/*?*/, MemberDecl member, List<Expression> args, List<Type> optTypeArguments, ResolveOpts opts, bool allowMethodCall) { Contract.Requires(tok != null); Contract.Requires(receiver != null); Contract.Requires(receiver.WasResolved()); Contract.Requires(member != null); Contract.Requires(opts != null && opts.codeContext != null); var rr = new MemberSelectExpr(tok, receiver, member.Name); rr.Member = member; // Now, fill in rr.Type. This requires taking into consideration the type parameters passed to the receiver's type as well as any type // parameters used in this NameSegment/ExprDotName. // Add to "subst" the type parameters given to the member's class/datatype rr.TypeApplication_AtEnclosingClass = new List<Type>(); rr.TypeApplication_JustMember = new List<Type>(); Dictionary<TypeParameter, Type> subst; var rType = (receiverTypeBound ?? receiver.Type).NormalizeExpand(); if (rType is UserDefinedType udt && udt.ResolvedClass != null) { subst = TypeSubstitutionMap(udt.ResolvedClass.TypeArgs, udt.TypeArgs); if (member.EnclosingClass == null) { // this can happen for some special members, like real.Floor } else { rr.TypeApplication_AtEnclosingClass.AddRange(rType.AsParentType(member.EnclosingClass).TypeArgs); } } else { var vtd = AsValuetypeDecl(rType); if (vtd != null) { Contract.Assert(vtd.TypeArgs.Count == rType.TypeArgs.Count); subst = TypeSubstitutionMap(vtd.TypeArgs, rType.TypeArgs); rr.TypeApplication_AtEnclosingClass.AddRange(rType.TypeArgs); } else { Contract.Assert(rType.TypeArgs.Count == 0); subst = new Dictionary<TypeParameter, Type>(); } } if (member is Field) { var field = (Field)member; if (optTypeArguments != null) { reporter.Error(MessageSource.Resolver, tok, "a field ({0}) does not take any type arguments (got {1})", field.Name, optTypeArguments.Count); } subst = BuildTypeArgumentSubstitute(subst, receiverTypeBound ?? receiver.Type); rr.Type = SubstType(field.Type, subst); AddCallGraphEdgeForField(opts.codeContext, field, rr); } else if (member is Function) { var fn = (Function)member; if (fn is TwoStateFunction && !opts.twoState) { reporter.Error(MessageSource.Resolver, tok, "two-state function ('{0}') can only be called in a two-state context", member.Name); } int suppliedTypeArguments = optTypeArguments == null ? 0 : optTypeArguments.Count; if (optTypeArguments != null && suppliedTypeArguments != fn.TypeArgs.Count) { reporter.Error(MessageSource.Resolver, tok, "function '{0}' expects {1} type arguments (got {2})", member.Name, fn.TypeArgs.Count, suppliedTypeArguments); } for (int i = 0; i < fn.TypeArgs.Count; i++) { var ta = i < suppliedTypeArguments ? optTypeArguments[i] : new InferredTypeProxy(); rr.TypeApplication_JustMember.Add(ta); subst.Add(fn.TypeArgs[i], ta); } subst = BuildTypeArgumentSubstitute(subst, receiverTypeBound ?? receiver.Type); rr.Type = SelectAppropriateArrowType(fn.tok, fn.Formals.ConvertAll(f => SubstType(f.Type, subst)), SubstType(fn.ResultType, subst), fn.Reads.Count != 0, fn.Req.Count != 0); AddCallGraphEdge(opts.codeContext, fn, rr, IsFunctionReturnValue(fn, args, opts)); } else { // the member is a method var m = (Method)member; if (!allowMethodCall) { // it's a method and method calls are not allowed in the given context reporter.Error(MessageSource.Resolver, tok, "expression is not allowed to invoke a {0} ({1})", member.WhatKind, member.Name); } int suppliedTypeArguments = optTypeArguments == null ? 0 : optTypeArguments.Count; if (optTypeArguments != null && suppliedTypeArguments != m.TypeArgs.Count) { reporter.Error(MessageSource.Resolver, tok, "method '{0}' expects {1} type arguments (got {2})", member.Name, m.TypeArgs.Count, suppliedTypeArguments); } for (int i = 0; i < m.TypeArgs.Count; i++) { var ta = i < suppliedTypeArguments ? optTypeArguments[i] : new InferredTypeProxy(); rr.TypeApplication_JustMember.Add(ta); } rr.Type = new InferredTypeProxy(); // fill in this field, in order to make "rr" resolved } return rr; } private bool IsFunctionReturnValue(Function fn, List<Expression> args, ResolveOpts opts) { bool isFunctionReturnValue = true; // if the call is in post-condition and it is calling itself, and the arguments matches // formal parameter, then it denotes function return value. if (args != null && opts.isPostCondition && opts.codeContext == fn) { foreach (var arg in args) { if (arg is NameSegment) { var name = ((NameSegment)arg).Name; IVariable v = scope.Find(name); if (!(v is Formal)) { isFunctionReturnValue = false; } } else { isFunctionReturnValue = false; } } } else { isFunctionReturnValue = false; } return isFunctionReturnValue; } class MethodCallInformation { public readonly IToken Tok; public readonly MemberSelectExpr Callee; public readonly List<Expression> Args; [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(Tok != null); Contract.Invariant(Callee != null); Contract.Invariant(Callee.Member is Method); Contract.Invariant(cce.NonNullElements(Args)); } public MethodCallInformation(IToken tok, MemberSelectExpr callee, List<Expression> args) { Contract.Requires(tok != null); Contract.Requires(callee != null); Contract.Requires(callee.Member is Method); Contract.Requires(cce.NonNullElements(args)); this.Tok = tok; this.Callee = callee; this.Args = args; } } MethodCallInformation ResolveApplySuffix(ApplySuffix e, ResolveOpts opts, bool allowMethodCall) { Contract.Requires(e != null); Contract.Requires(opts != null); Contract.Ensures(Contract.Result<MethodCallInformation>() == null || allowMethodCall); Expression r = null; // upon success, the expression to which the ApplySuffix resolves var errorCount = reporter.Count(ErrorLevel.Error); if (e.Lhs is NameSegment) { r = ResolveNameSegment((NameSegment)e.Lhs, true, e.Args, opts, allowMethodCall); // note, if r is non-null, then e.Args have been resolved and r is a resolved expression that incorporates e.Args } else if (e.Lhs is ExprDotName) { r = ResolveDotSuffix((ExprDotName)e.Lhs, true, e.Args, opts, allowMethodCall); // note, if r is non-null, then e.Args have been resolved and r is a resolved expression that incorporates e.Args } else { ResolveExpression(e.Lhs, opts); } if (e.Lhs.Type == null) { // some error had been detected during the attempted resolution of e.Lhs e.Lhs.Type = new InferredTypeProxy(); } if (r == null) { foreach (var arg in e.Args) { ResolveExpression(arg, opts); } var improvedType = PartiallyResolveTypeForMemberSelection(e.Lhs.tok, e.Lhs.Type, "_#apply"); var fnType = improvedType.AsArrowType; if (fnType == null) { var lhs = e.Lhs.Resolved; if (lhs != null && lhs.Type is Resolver_IdentifierExpr.ResolverType_Module) { reporter.Error(MessageSource.Resolver, e.tok, "name of module ({0}) is used as a function", ((Resolver_IdentifierExpr)lhs).Decl.Name); } else if (lhs != null && lhs.Type is Resolver_IdentifierExpr.ResolverType_Type) { // It may be a conversion expression var ri = (Resolver_IdentifierExpr)lhs; if (ri.TypeParamDecl != null) { reporter.Error(MessageSource.Resolver, e.tok, "name of type parameter ({0}) is used as a function", ri.TypeParamDecl.Name); } else { var decl = ri.Decl; var ty = new UserDefinedType(e.tok, decl.Name, decl, ri.TypeArgs); if (ty.AsNewtype != null) { reporter.Deprecated(MessageSource.Resolver, e.tok, "the syntax \"{0}(expr)\" for type conversions has been deprecated; the new syntax is \"expr as {0}\"", decl.Name); if (e.Args.Count != 1) { reporter.Error(MessageSource.Resolver, e.tok, "conversion operation to {0} got wrong number of arguments (expected 1, got {1})", decl.Name, e.Args.Count); } var conversionArg = 1 <= e.Args.Count ? e.Args[0] : ty.IsNumericBased(Type.NumericPersuasion.Int) ? LiteralExpr.CreateIntLiteral(e.tok, 0) : LiteralExpr.CreateRealLiteral(e.tok, BaseTypes.BigDec.ZERO); r = new ConversionExpr(e.tok, conversionArg, ty); ResolveExpression(r, opts); // resolve the rest of the arguments, if any for (int i = 1; i < e.Args.Count; i++) { ResolveExpression(e.Args[i], opts); } } else { reporter.Error(MessageSource.Resolver, e.tok, "name of type ({0}) is used as a function", decl.Name); } } } else { if (lhs is MemberSelectExpr && ((MemberSelectExpr)lhs).Member is Method) { var mse = (MemberSelectExpr)lhs; if (allowMethodCall) { var cRhs = new MethodCallInformation(e.tok, mse, e.Args); return cRhs; } else { reporter.Error(MessageSource.Resolver, e.tok, "{0} call is not allowed to be used in an expression context ({1})", mse.Member.WhatKind, mse.Member.Name); } } else if (lhs != null) { // if e.Lhs.Resolved is null, then e.Lhs was not successfully resolved and an error has already been reported reporter.Error(MessageSource.Resolver, e.tok, "non-function expression (of type {0}) is called with parameters", e.Lhs.Type); } } } else { var mse = e.Lhs is NameSegment || e.Lhs is ExprDotName ? e.Lhs.Resolved as MemberSelectExpr : null; var callee = mse == null ? null : mse.Member as Function; if (fnType.Arity != e.Args.Count) { var what = callee != null ? string.Format("function '{0}'", callee.Name) : string.Format("function type '{0}'", fnType); reporter.Error(MessageSource.Resolver, e.tok, "wrong number of arguments to function application ({0} expects {1}, got {2})", what, fnType.Arity, e.Args.Count); } else { for (var i = 0; i < fnType.Arity; i++) { AddAssignableConstraint(e.Args[i].tok, fnType.Args[i], e.Args[i].Type, "type mismatch for argument" + (fnType.Arity == 1 ? "" : " " + i) + " (function expects {0}, got {1})"); } if (errorCount != reporter.Count(ErrorLevel.Error)) { // do nothing else; error has been reported } else if (callee != null) { // produce a FunctionCallExpr instead of an ApplyExpr(MemberSelectExpr) var rr = new FunctionCallExpr(e.Lhs.tok, callee.Name, mse.Obj, e.tok, e.Args); // resolve it here: rr.Function = callee; Contract.Assert(!(mse.Obj is StaticReceiverExpr) || callee.IsStatic); // this should have been checked already Contract.Assert(callee.Formals.Count == rr.Args.Count); // this should have been checked already rr.TypeApplication_AtEnclosingClass = mse.TypeApplication_AtEnclosingClass; rr.TypeApplication_JustFunction = mse.TypeApplication_JustMember; var subst = BuildTypeArgumentSubstitute(mse.TypeArgumentSubstitutionsAtMemberDeclaration()); // type check the arguments #if DEBUG Contract.Assert(callee.Formals.Count == fnType.Arity); for (int i = 0; i < callee.Formals.Count; i++) { Expression farg = rr.Args[i]; Contract.Assert(farg.WasResolved()); Contract.Assert(farg.Type != null); Type s = SubstType(callee.Formals[i].Type, subst); Contract.Assert(s.Equals(fnType.Args[i])); Contract.Assert(farg.Type.Equals(e.Args[i].Type)); } #endif rr.Type = SubstType(callee.ResultType, subst); // further bookkeeping if (callee is ExtremePredicate) { ((ExtremePredicate)callee).Uses.Add(rr); } AddCallGraphEdge(opts.codeContext, callee, rr, IsFunctionReturnValue(callee, e.Args, opts)); r = rr; } else { r = new ApplyExpr(e.Lhs.tok, e.Lhs, e.Args); r.Type = fnType.Result; } } } } if (r == null) { // an error has been reported above; we won't fill in .ResolvedExpression, but we still must fill in .Type e.Type = new InferredTypeProxy(); } else { e.ResolvedExpression = r; e.Type = r.Type; } return null; } private Dictionary<TypeParameter, Type> BuildTypeArgumentSubstitute(Dictionary<TypeParameter, Type> typeArgumentSubstitutions, Type/*?*/ receiverTypeBound = null) { Contract.Requires(typeArgumentSubstitutions != null); var subst = new Dictionary<TypeParameter, Type>(); foreach (var entry in typeArgumentSubstitutions) { subst.Add(entry.Key, entry.Value); } if (SelfTypeSubstitution != null) { foreach (var entry in SelfTypeSubstitution) { subst.Add(entry.Key, entry.Value); } } if (receiverTypeBound != null) { TopLevelDeclWithMembers cl; var udt = receiverTypeBound?.AsNonNullRefType; if (udt != null) { cl = (TopLevelDeclWithMembers)((NonNullTypeDecl)udt.ResolvedClass).ViewAsClass; } else { udt = receiverTypeBound.NormalizeExpand() as UserDefinedType; cl = udt?.ResolvedClass as TopLevelDeclWithMembers; } if (cl != null) { foreach (var entry in cl.ParentFormalTypeParametersToActuals) { var v = SubstType(entry.Value, subst); subst.Add(entry.Key, v); } } } return subst; } /// <summary> /// the return value is false iff there is an error in resolving the datatype value; /// if there is an error then an error message is emitted iff complain is true /// </summary> private bool ResolveDatatypeValue(ResolveOpts opts, DatatypeValue dtv, DatatypeDecl dt, Type ty, bool complain = true) { Contract.Requires(opts != null); Contract.Requires(dtv != null); Contract.Requires(dt != null); Contract.Requires(ty == null || (ty.AsDatatype == dt && ty.TypeArgs.Count == dt.TypeArgs.Count)); var ok = true; var gt = new List<Type>(dt.TypeArgs.Count); var subst = new Dictionary<TypeParameter, Type>(); for (int i = 0; i < dt.TypeArgs.Count; i++) { Type t = ty == null ? new InferredTypeProxy() : ty.TypeArgs[i]; gt.Add(t); dtv.InferredTypeArgs.Add(t); subst.Add(dt.TypeArgs[i], t); } // Construct a resolved type directly, as we know the declaration is dt. dtv.Type = new UserDefinedType(dtv.tok, dt.Name, dt, gt); DatatypeCtor ctor; if (!datatypeCtors[dt].TryGetValue(dtv.MemberName, out ctor)) { ok = false; if (complain) { reporter.Error(MessageSource.Resolver, dtv.tok, "undeclared constructor {0} in datatype {1}", dtv.MemberName, dtv.DatatypeName); } } else { Contract.Assert(ctor != null); // follows from postcondition of TryGetValue dtv.Ctor = ctor; if (ctor.Formals.Count != dtv.Arguments.Count) { ok = false; if (complain) { reporter.Error(MessageSource.Resolver, dtv.tok, "wrong number of arguments to datatype constructor {0} (found {1}, expected {2})", ctor.Name, dtv.Arguments.Count, ctor.Formals.Count); } } } int j = 0; foreach (var arg in dtv.Arguments) { Formal formal = ctor != null && j < ctor.Formals.Count ? ctor.Formals[j] : null; ResolveExpression(arg, opts); Contract.Assert(arg.Type != null); // follows from postcondition of ResolveExpression if (formal != null) { Type st = SubstType(formal.Type, subst); AddAssignableConstraint(arg.tok, st, arg.Type, "incorrect type of datatype constructor argument (found {1}, expected {0})"); } j++; } return ok; } /// <summary> /// Generate an error for every ghost feature used in "expr". /// Requires "expr" to have been successfully resolved. /// </summary> void CheckIsCompilable(Expression expr) { Contract.Requires(expr != null); Contract.Requires(expr.WasResolved()); // this check approximates the requirement that "expr" be resolved if (expr is IdentifierExpr) { var e = (IdentifierExpr)expr; if (e.Var != null && e.Var.IsGhost) { reporter.Error(MessageSource.Resolver, expr, "ghost variables are allowed only in specification contexts"); return; } } else if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; if (e.Member != null && e.Member.IsGhost) { reporter.Error(MessageSource.Resolver, expr, "ghost fields are allowed only in specification contexts"); return; } } else if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; if (e.Function != null) { if (e.Function.IsGhost) { reporter.Error(MessageSource.Resolver, expr, "function calls are allowed only in specification contexts (consider declaring the function a 'function method')"); return; } // function is okay, so check all NON-ghost arguments CheckIsCompilable(e.Receiver); for (int i = 0; i < e.Function.Formals.Count; i++) { if (!e.Function.Formals[i].IsGhost) { CheckIsCompilable(e.Args[i]); } } } return; } else if (expr is DatatypeValue) { var e = (DatatypeValue)expr; // check all NON-ghost arguments // note that if resolution is successful, then |e.Arguments| == |e.Ctor.Formals| for (int i = 0; i < e.Arguments.Count; i++) { if (!e.Ctor.Formals[i].IsGhost) { CheckIsCompilable(e.Arguments[i]); } } return; } else if (expr is OldExpr) { reporter.Error(MessageSource.Resolver, expr, "old expressions are allowed only in specification and ghost contexts"); return; } else if (expr is UnaryOpExpr) { var e = (UnaryOpExpr)expr; if (e.Op == UnaryOpExpr.Opcode.Fresh) { reporter.Error(MessageSource.Resolver, expr, "fresh expressions are allowed only in specification and ghost contexts"); return; } } else if (expr is UnchangedExpr) { reporter.Error(MessageSource.Resolver, expr, "unchanged expressions are allowed only in specification and ghost contexts"); return; } else if (expr is StmtExpr) { var e = (StmtExpr)expr; // ignore the statement CheckIsCompilable(e.E); return; } else if (expr is BinaryExpr) { var e = (BinaryExpr)expr; switch (e.ResolvedOp_PossiblyStillUndetermined) { case BinaryExpr.ResolvedOpcode.RankGt: case BinaryExpr.ResolvedOpcode.RankLt: reporter.Error(MessageSource.Resolver, expr, "rank comparisons are allowed only in specification and ghost contexts"); return; default: break; } } else if (expr is TernaryExpr) { var e = (TernaryExpr)expr; switch (e.Op) { case TernaryExpr.Opcode.PrefixEqOp: case TernaryExpr.Opcode.PrefixNeqOp: reporter.Error(MessageSource.Resolver, expr, "prefix equalities are allowed only in specification and ghost contexts"); return; default: break; } } else if (expr is LetExpr) { var e = (LetExpr)expr; if (e.Exact) { Contract.Assert(e.LHSs.Count == e.RHSs.Count); var i = 0; foreach (var ee in e.RHSs) { if (!e.LHSs[i].Vars.All(bv => bv.IsGhost)) { CheckIsCompilable(ee); } i++; } CheckIsCompilable(e.Body); } else { Contract.Assert(e.RHSs.Count == 1); var lhsVarsAreAllGhost = e.BoundVars.All(bv => bv.IsGhost); if (!lhsVarsAreAllGhost) { CheckIsCompilable(e.RHSs[0]); } CheckIsCompilable(e.Body); // fill in bounds for this to-be-compiled let-such-that expression Contract.Assert(e.RHSs.Count == 1); // if we got this far, the resolver will have checked this condition successfully var constraint = e.RHSs[0]; e.Constraint_Bounds = DiscoverBestBounds_MultipleVars(e.BoundVars.ToList<IVariable>(), constraint, true, ComprehensionExpr.BoundedPool.PoolVirtues.None); } return; } else if (expr is LambdaExpr) { var e = expr as LambdaExpr; CheckIsCompilable(e.Body); return; } else if (expr is ComprehensionExpr) { var e = (ComprehensionExpr)expr; var uncompilableBoundVars = e.UncompilableBoundVars(); if (uncompilableBoundVars.Count != 0) { string what; if (e is SetComprehension) { what = ((SetComprehension)e).Finite ? "set comprehensions" : "iset comprehensions"; } else if (e is MapComprehension) { what = ((MapComprehension)e).Finite ? "map comprehensions" : "imap comprehensions"; } else { Contract.Assume(e is QuantifierExpr); // otherwise, unexpected ComprehensionExpr (since LambdaExpr is handled separately above) Contract.Assert(((QuantifierExpr)e).SplitQuantifier == null); // No split quantifiers during resolution what = "quantifiers"; } foreach (var bv in uncompilableBoundVars) { reporter.Error(MessageSource.Resolver, expr, "{0} in non-ghost contexts must be compilable, but Dafny's heuristics can't figure out how to produce or compile a bounded set of values for '{1}'", what, bv.Name); } return; } // don't recurse down any attributes if (e.Range != null) { CheckIsCompilable(e.Range); } CheckIsCompilable(e.Term); return; } else if (expr is ChainingExpression) { // We don't care about the different operators; we only want the operands, so let's get them directly from // the chaining expression var e = (ChainingExpression)expr; e.Operands.ForEach(CheckIsCompilable); return; } foreach (var ee in expr.SubExpressions) { CheckIsCompilable(ee); } } public void ResolveFunctionCallExpr(FunctionCallExpr e, ResolveOpts opts) { Contract.Requires(e != null); Contract.Requires(e.Type == null); // should not have been type checked before ResolveReceiver(e.Receiver, opts); Contract.Assert(e.Receiver.Type != null); // follows from postcondition of ResolveExpression NonProxyType tentativeReceiverType; var member = ResolveMember(e.tok, e.Receiver.Type, e.Name, out tentativeReceiverType); #if !NO_WORK_TO_BE_DONE var ctype = (UserDefinedType)tentativeReceiverType; #endif if (member == null) { // error has already been reported by ResolveMember } else if (member is Method) { reporter.Error(MessageSource.Resolver, e, "member {0} in type {1} refers to a method, but only functions can be used in this context", e.Name, cce.NonNull(ctype).Name); } else if (!(member is Function)) { reporter.Error(MessageSource.Resolver, e, "member {0} in type {1} does not refer to a function", e.Name, cce.NonNull(ctype).Name); } else { Function function = (Function)member; e.Function = function; if (function is ExtremePredicate) { ((ExtremePredicate)function).Uses.Add(e); } if (function is TwoStateFunction && !opts.twoState) { reporter.Error(MessageSource.Resolver, e.tok, "a two-state function can be used only in a two-state context"); } if (e.Receiver is StaticReceiverExpr && !function.IsStatic) { reporter.Error(MessageSource.Resolver, e, "an instance function must be selected via an object, not just a class name"); } if (function.Formals.Count != e.Args.Count) { reporter.Error(MessageSource.Resolver, e, "wrong number of function arguments (got {0}, expected {1})", e.Args.Count, function.Formals.Count); } else { Contract.Assert(ctype != null); // follows from postcondition of ResolveMember if (!function.IsStatic) { if (!scope.AllowInstance && e.Receiver is ThisExpr) { // The call really needs an instance, but that instance is given as 'this', which is not // available in this context. In most cases, occurrences of 'this' inside e.Receiver would // have been caught in the recursive call to resolve e.Receiver, but not the specific case // of e.Receiver being 'this' (explicitly or implicitly), for that case needs to be allowed // in the event that a static function calls another static function (and note that we need the // type of the receiver in order to find the method, so we could not have made this check // earlier). reporter.Error(MessageSource.Resolver, e.Receiver, "'this' is not allowed in a 'static' context"); } else if (e.Receiver is StaticReceiverExpr) { reporter.Error(MessageSource.Resolver, e.Receiver, "call to instance function requires an instance"); } } // build the type substitution map var typeMap = new Dictionary<TypeParameter, Type>(); for (int i = 0; i < ctype.TypeArgs.Count; i++) { typeMap.Add(ctype.ResolvedClass.TypeArgs[i], ctype.TypeArgs[i]); } var typeThatEnclosesMember = ctype.AsParentType(member.EnclosingClass); e.TypeApplication_AtEnclosingClass = new List<Type>(); for (int i = 0; i < typeThatEnclosesMember.TypeArgs.Count; i++) { e.TypeApplication_AtEnclosingClass.Add(typeThatEnclosesMember.TypeArgs[i]); } e.TypeApplication_JustFunction = new List<Type>(); foreach (TypeParameter p in function.TypeArgs) { var ty = new ParamTypeProxy(p); typeMap.Add(p, ty); e.TypeApplication_JustFunction.Add(ty); } Dictionary<TypeParameter, Type> subst = BuildTypeArgumentSubstitute(typeMap); // type check the arguments for (int i = 0; i < function.Formals.Count; i++) { Expression farg = e.Args[i]; ResolveExpression(farg, opts); Contract.Assert(farg.Type != null); // follows from postcondition of ResolveExpression Type s = SubstType(function.Formals[i].Type, subst); AddAssignableConstraint(e.tok, s, farg.Type, "incorrect type of function argument" + (function.Formals.Count == 1 ? "" : " " + i) + " (expected {0}, got {1})"); } e.Type = SubstType(function.ResultType, subst).NormalizeExpand(); } AddCallGraphEdge(opts.codeContext, function, e, IsFunctionReturnValue(function, e.Args, opts)); } } private void AddCallGraphEdgeForField(ICodeContext callingContext, Field field, Expression e) { Contract.Requires(callingContext != null); Contract.Requires(field != null); Contract.Requires(e != null); var cf = field as ConstantField; if (cf != null) { if (cf == callingContext) { // detect self-loops here, since they don't show up in the graph's SSC methods reporter.Error(MessageSource.Resolver, cf.tok, "recursive dependency involving constant initialization: {0} -> {0}", cf.Name); } else { AddCallGraphEdge(callingContext, cf, e, false); } } } private static void AddCallGraphEdge(ICodeContext callingContext, ICallable function, Expression e, bool isFunctionReturnValue) { Contract.Requires(callingContext != null); Contract.Requires(function != null); Contract.Requires(e != null); // Resolution termination check ModuleDefinition callerModule = callingContext.EnclosingModule; ModuleDefinition calleeModule = function is SpecialFunction ? null : function.EnclosingModule; if (callerModule == calleeModule) { // intra-module call; add edge in module's call graph var caller = callingContext as ICallable; if (caller == null) { // don't add anything to the call graph after all } else if (caller is IteratorDecl) { callerModule.CallGraph.AddEdge(((IteratorDecl)callingContext).Member_MoveNext, function); } else { callerModule.CallGraph.AddEdge(caller, function); if (caller is Function) { FunctionCallExpr ee = e as FunctionCallExpr; if (ee != null) { ((Function)caller).AllCalls.Add(ee); } } // if the call denotes the function return value in the function postconditions, then we don't // mark it as recursive. if (caller == function && (function is Function) && !isFunctionReturnValue) { ((Function)function).IsRecursive = true; // self recursion (mutual recursion is determined elsewhere) } } } } private static ModuleSignature GetSignatureExt(ModuleSignature sig, bool useCompileSignatures) { Contract.Requires(sig != null); Contract.Ensures(Contract.Result<ModuleSignature>() != null); if (useCompileSignatures) { while (sig.CompileSignature != null) sig = sig.CompileSignature; } return sig; } private ModuleSignature GetSignature(ModuleSignature sig) { return GetSignatureExt(sig, useCompileSignatures); } public static List<ComprehensionExpr.BoundedPool> DiscoverBestBounds_MultipleVars_AllowReordering<VT>(List<VT> bvars, Expression expr, bool polarity, ComprehensionExpr.BoundedPool.PoolVirtues requiredVirtues) where VT : IVariable { Contract.Requires(bvars != null); Contract.Requires(expr != null); Contract.Ensures(Contract.Result<List<ComprehensionExpr.BoundedPool>>() != null); var bounds = DiscoverBestBounds_MultipleVars(bvars, expr, polarity, requiredVirtues); if (bvars.Count > 1) { // It may be helpful to try all permutations (or, better yet, to use an algorithm that keeps track of the dependencies // and discovers good bounds more efficiently). However, all permutations would be expensive. Therefore, we try just one // other permutation, namely the reversal "bvars". This covers the important case where there are two bound variables // that work out in the opposite order. It also covers one more case for the (probably rare) case of there being more // than two bound variables. var bvarsMissyElliott = new List<VT>(bvars); // make a copy bvarsMissyElliott.Reverse(); // and then flip it and reverse it, Ti esrever dna ti pilf nwod gniht ym tup I var boundsMissyElliott = DiscoverBestBounds_MultipleVars(bvarsMissyElliott, expr, polarity, requiredVirtues); // Figure out which one seems best var meBetter = 0; for (int i = 0; i < bvars.Count; i++) { var orig = bounds[i]; var me = boundsMissyElliott[i]; if (orig == null && me != null) { meBetter = 1; break; // end game } else if (orig != null && me == null) { meBetter = -1; break; // end game } else if (orig != null && me != null) { if ((orig.Virtues & ComprehensionExpr.BoundedPool.PoolVirtues.Finite) != 0) { meBetter--; } if ((orig.Virtues & ComprehensionExpr.BoundedPool.PoolVirtues.Enumerable) != 0) { meBetter--; } if ((me.Virtues & ComprehensionExpr.BoundedPool.PoolVirtues.Finite) != 0) { meBetter++; } if ((me.Virtues & ComprehensionExpr.BoundedPool.PoolVirtues.Enumerable) != 0) { meBetter++; } } } if (meBetter > 0) { // yes, this reordering seems to have been better bvars.Reverse(); return boundsMissyElliott; } } return bounds; } /// <summary> /// For a list of variables "bvars", returns a list of best bounds, subject to the constraint "requiredVirtues", for each respective variable. /// If no bound matching "requiredVirtues" is found for a variable "v", then the bound for "v" in the returned list is set to "null". /// </summary> public static List<ComprehensionExpr.BoundedPool> DiscoverBestBounds_MultipleVars<VT>(List<VT> bvars, Expression expr, bool polarity, ComprehensionExpr.BoundedPool.PoolVirtues requiredVirtues) where VT : IVariable { Contract.Requires(bvars != null); Contract.Requires(expr != null); Contract.Ensures(Contract.Result<List<ComprehensionExpr.BoundedPool>>() != null); foreach (var bv in bvars) { var c = GetImpliedTypeConstraint(bv, bv.Type); expr = polarity ? Expression.CreateAnd(c, expr) : Expression.CreateImplies(c, expr); } var bests = DiscoverAllBounds_Aux_MultipleVars(bvars, expr, polarity, requiredVirtues); return bests; } public static List<ComprehensionExpr.BoundedPool> DiscoverAllBounds_SingleVar<VT>(VT v, Expression expr) where VT : IVariable { expr = Expression.CreateAnd(GetImpliedTypeConstraint(v, v.Type), expr); return DiscoverAllBounds_Aux_SingleVar(new List<VT> { v }, 0, expr, true, new List<ComprehensionExpr.BoundedPool>() { null }); } private static List<ComprehensionExpr.BoundedPool> DiscoverAllBounds_Aux_MultipleVars<VT>(List<VT> bvars, Expression expr, bool polarity, ComprehensionExpr.BoundedPool.PoolVirtues requiredVirtues) where VT : IVariable { Contract.Requires(bvars != null); Contract.Requires(expr != null); Contract.Ensures(Contract.Result<List<ComprehensionExpr.BoundedPool>>() != null); Contract.Ensures(Contract.Result<List<ComprehensionExpr.BoundedPool>>().Count == bvars.Count); var knownBounds = new List<ComprehensionExpr.BoundedPool>(); for (var j = 0; j < bvars.Count; j++) { knownBounds.Add(null); } for (var j = bvars.Count; 0 <= --j; ) { // important to go backwards, because DiscoverAllBounds_Aux_SingleVar assumes "knownBounds" has been filled in for higher-indexed variables var bounds = DiscoverAllBounds_Aux_SingleVar(bvars, j, expr, polarity, knownBounds); knownBounds[j] = ComprehensionExpr.BoundedPool.GetBest(bounds, requiredVirtues); #if DEBUG_PRINT if (knownBounds[j] is ComprehensionExpr.IntBoundedPool) { var ib = (ComprehensionExpr.IntBoundedPool)knownBounds[j]; var lo = ib.LowerBound == null ? "" : Printer.ExprToString(ib.LowerBound); var hi = ib.UpperBound == null ? "" : Printer.ExprToString(ib.UpperBound); Console.WriteLine("DEBUG: Bound for var {3}, {0}: {1} .. {2}", bvars[j].Name, lo, hi, j); } else if (knownBounds[j] is ComprehensionExpr.SetBoundedPool) { Console.WriteLine("DEBUG: Bound for var {2}, {0}: in {1}", bvars[j].Name, Printer.ExprToString(((ComprehensionExpr.SetBoundedPool)knownBounds[j]).Set), j); } else { Console.WriteLine("DEBUG: Bound for var {2}, {0}: {1}", bvars[j].Name, knownBounds[j], j); } #endif } return knownBounds; } /// <summary> /// Returns a list of (possibly partial) bounds for "bvars[j]", each of which can be written without mentioning any variable in "bvars[j..]" that is not bounded. /// </summary> private static List<ComprehensionExpr.BoundedPool> DiscoverAllBounds_Aux_SingleVar<VT>(List<VT> bvars, int j, Expression expr, bool polarity, List<ComprehensionExpr.BoundedPool> knownBounds) where VT : IVariable { Contract.Requires(bvars != null); Contract.Requires(0 <= j && j < bvars.Count); Contract.Requires(expr != null); Contract.Requires(knownBounds != null); Contract.Requires(knownBounds.Count == bvars.Count); var bv = bvars[j]; var bounds = new List<ComprehensionExpr.BoundedPool>(); // Maybe the type itself gives a bound if (bv.Type.IsBoolType) { bounds.Add(new ComprehensionExpr.BoolBoundedPool()); } else if (bv.Type.IsCharType) { bounds.Add(new ComprehensionExpr.CharBoundedPool()); } else if (bv.Type.IsDatatype && bv.Type.AsDatatype.HasFinitePossibleValues) { bounds.Add(new ComprehensionExpr.DatatypeBoundedPool(bv.Type.AsDatatype)); } else if (bv.Type.IsNumericBased(Type.NumericPersuasion.Int)) { bounds.Add(new AssignSuchThatStmt.WiggleWaggleBound()); } else if (bv.Type.IsAllocFree) { bounds.Add(new ComprehensionExpr.AllocFreeBoundedPool(bv.Type)); } // Go through the conjuncts of the range expression to look for bounds. foreach (var conjunct in NormalizedConjuncts(expr, polarity)) { if (conjunct is IdentifierExpr) { var ide = (IdentifierExpr)conjunct; if (ide.Var == (IVariable)bv) { Contract.Assert(bv.Type.IsBoolType); bounds.Add(new ComprehensionExpr.ExactBoundedPool(Expression.CreateBoolLiteral(Token.NoToken, true))); } continue; } if (conjunct is UnaryExpr || conjunct is OldExpr) { // we also consider a unary expression sitting immediately inside an old var unary = conjunct as UnaryOpExpr ?? ((OldExpr)conjunct).E.Resolved as UnaryOpExpr; if (unary != null) { var ide = unary.E.Resolved as IdentifierExpr; if (ide != null && ide.Var == (IVariable)bv) { if (unary.Op == UnaryOpExpr.Opcode.Not) { Contract.Assert(bv.Type.IsBoolType); bounds.Add(new ComprehensionExpr.ExactBoundedPool(Expression.CreateBoolLiteral(Token.NoToken, false))); } else if (unary.Op == UnaryOpExpr.Opcode.Allocated) { bounds.Add(new ComprehensionExpr.ExplicitAllocatedBoundedPool()); } } } continue; } var c = conjunct as BinaryExpr; if (c == null) { // other than what we already covered above, we only know what to do with binary expressions continue; } var e0 = c.E0; var e1 = c.E1; int whereIsBv = SanitizeForBoundDiscovery(bvars, j, c.ResolvedOp, knownBounds, ref e0, ref e1); if (whereIsBv < 0) { continue; } switch (c.ResolvedOp) { case BinaryExpr.ResolvedOpcode.InSet: if (whereIsBv == 0) { bounds.Add(new ComprehensionExpr.SetBoundedPool(e1, e0.Type, e1.Type.AsSetType.Arg, e1.Type.AsSetType.Finite)); } break; case BinaryExpr.ResolvedOpcode.Subset: if (whereIsBv == 0) { bounds.Add(new ComprehensionExpr.SubSetBoundedPool(e1, e1.Type.AsSetType.Finite)); } else { bounds.Add(new ComprehensionExpr.SuperSetBoundedPool(e0)); } break; case BinaryExpr.ResolvedOpcode.InMultiSet: if (whereIsBv == 0) { bounds.Add(new ComprehensionExpr.MultiSetBoundedPool(e1, e0.Type, e1.Type.AsMultiSetType.Arg)); } break; case BinaryExpr.ResolvedOpcode.InSeq: if (whereIsBv == 0) { bounds.Add(new ComprehensionExpr.SeqBoundedPool(e1, e0.Type, e1.Type.AsSeqType.Arg)); } break; case BinaryExpr.ResolvedOpcode.InMap: if (whereIsBv == 0) { bounds.Add(new ComprehensionExpr.MapBoundedPool(e1, e0.Type, e1.Type.AsMapType.Arg, e1.Type.AsMapType.Finite)); } break; case BinaryExpr.ResolvedOpcode.EqCommon: case BinaryExpr.ResolvedOpcode.SetEq: case BinaryExpr.ResolvedOpcode.SeqEq: case BinaryExpr.ResolvedOpcode.MultiSetEq: case BinaryExpr.ResolvedOpcode.MapEq: var otherOperand = whereIsBv == 0 ? e1 : e0; bounds.Add(new ComprehensionExpr.ExactBoundedPool(otherOperand)); break; case BinaryExpr.ResolvedOpcode.Gt: case BinaryExpr.ResolvedOpcode.Ge: Contract.Assert(false); throw new cce.UnreachableException(); // promised by postconditions of NormalizedConjunct case BinaryExpr.ResolvedOpcode.Lt: if (e0.Type.IsNumericBased(Type.NumericPersuasion.Int)) { if (whereIsBv == 0) { // bv < E bounds.Add(new ComprehensionExpr.IntBoundedPool(null, e1)); } else { // E < bv bounds.Add(new ComprehensionExpr.IntBoundedPool(Expression.CreateIncrement(e0, 1), null)); } } break; case BinaryExpr.ResolvedOpcode.Le: if (e0.Type.IsNumericBased(Type.NumericPersuasion.Int)) { if (whereIsBv == 0) { // bv <= E bounds.Add(new ComprehensionExpr.IntBoundedPool(null, Expression.CreateIncrement(e1, 1))); } else { // E <= bv bounds.Add(new ComprehensionExpr.IntBoundedPool(e0, null)); } } break; case BinaryExpr.ResolvedOpcode.RankLt: if (whereIsBv == 0) { bounds.Add(new ComprehensionExpr.DatatypeInclusionBoundedPool(e0.Type.IsIndDatatype)); } break; case BinaryExpr.ResolvedOpcode.RankGt: if (whereIsBv == 1) { bounds.Add(new ComprehensionExpr.DatatypeInclusionBoundedPool(e1.Type.IsIndDatatype)); } break; default: break; } } return bounds; } private static Translator translator = new Translator(null); public static Expression GetImpliedTypeConstraint(IVariable bv, Type ty) { return GetImpliedTypeConstraint(Expression.CreateIdentExpr(bv), ty); } public static Expression GetImpliedTypeConstraint(Expression e, Type ty) { Contract.Requires(e != null); Contract.Requires(ty != null); ty = ty.NormalizeExpandKeepConstraints(); var udt = ty as UserDefinedType; if (udt != null) { if (udt.ResolvedClass is NewtypeDecl) { var dd = (NewtypeDecl)udt.ResolvedClass; var c = GetImpliedTypeConstraint(e, dd.BaseType); if (dd.Var != null) { Dictionary<IVariable, Expression/*!*/> substMap = new Dictionary<IVariable, Expression>(); substMap.Add(dd.Var, e); Translator.Substituter sub = new Translator.Substituter(null, substMap, new Dictionary<TypeParameter, Type>()); c = Expression.CreateAnd(c, sub.Substitute(dd.Constraint)); } return c; } else if (udt.ResolvedClass is SubsetTypeDecl) { var dd = (SubsetTypeDecl)udt.ResolvedClass; var c = GetImpliedTypeConstraint(e, dd.RhsWithArgument(udt.TypeArgs)); Dictionary<IVariable, Expression/*!*/> substMap = new Dictionary<IVariable, Expression>(); substMap.Add(dd.Var, e); Translator.Substituter sub = new Translator.Substituter(null, substMap, new Dictionary<TypeParameter, Type>()); c = Expression.CreateAnd(c, sub.Substitute(dd.Constraint)); return c; } } return Expression.CreateBoolLiteral(e.tok, true); } /// <summary> /// If the return value is negative, the resulting "e0" and "e1" should not be used. /// Otherwise, the following is true on return: /// The new "e0 op e1" is equivalent to the old "e0 op e1". /// One of "e0" and "e1" is the identifier "boundVars[bvi]"; the return value is either 0 or 1, and indicates which. /// The other of "e0" and "e1" is an expression whose free variables are not among "boundVars[bvi..]". /// Ensures that the resulting "e0" and "e1" are not ConcreteSyntaxExpression's. /// </summary> static int SanitizeForBoundDiscovery<VT>(List<VT> boundVars, int bvi, BinaryExpr.ResolvedOpcode op, List<ComprehensionExpr.BoundedPool> knownBounds, ref Expression e0, ref Expression e1) where VT : IVariable { Contract.Requires(boundVars != null); Contract.Requires(0 <= bvi && bvi < boundVars.Count); Contract.Requires(knownBounds != null); Contract.Requires(knownBounds.Count == boundVars.Count); Contract.Requires(e0 != null); Contract.Requires(e1 != null); Contract.Ensures(Contract.Result<int>() < 2); Contract.Ensures(!(Contract.ValueAtReturn(out e0) is ConcreteSyntaxExpression)); Contract.Ensures(!(Contract.ValueAtReturn(out e1) is ConcreteSyntaxExpression)); IVariable bv = boundVars[bvi]; e0 = e0.Resolved; e1 = e1.Resolved; // make an initial assessment of where bv is; to continue, we need bv to appear in exactly one operand var fv0 = FreeVariables(e0); var fv1 = FreeVariables(e1); Expression thisSide; Expression thatSide; int whereIsBv; if (fv0.Contains(bv)) { if (fv1.Contains(bv)) { return -1; } whereIsBv = 0; thisSide = e0; thatSide = e1; } else if (fv1.Contains(bv)) { whereIsBv = 1; thisSide = e1; thatSide = e0; } else { return -1; } // Next, clean up the side where bv is by adjusting both sides of the expression switch (op) { case BinaryExpr.ResolvedOpcode.EqCommon: case BinaryExpr.ResolvedOpcode.NeqCommon: case BinaryExpr.ResolvedOpcode.Gt: case BinaryExpr.ResolvedOpcode.Ge: case BinaryExpr.ResolvedOpcode.Le: case BinaryExpr.ResolvedOpcode.Lt: // Repeatedly move additive or subtractive terms from thisSide to thatSide while (true) { var bin = thisSide as BinaryExpr; if (bin == null) { break; // done simplifying } else if (bin.ResolvedOp == BinaryExpr.ResolvedOpcode.Add) { // Change "A+B op C" into either "A op C-B" or "B op C-A", depending on where we find bv among A and B. if (!FreeVariables(bin.E1).Contains(bv)) { thisSide = bin.E0.Resolved; thatSide = new BinaryExpr(bin.tok, BinaryExpr.Opcode.Sub, thatSide, bin.E1); } else if (!FreeVariables(bin.E0).Contains(bv)) { thisSide = bin.E1.Resolved; thatSide = new BinaryExpr(bin.tok, BinaryExpr.Opcode.Sub, thatSide, bin.E0); } else { break; // done simplifying } ((BinaryExpr)thatSide).ResolvedOp = BinaryExpr.ResolvedOpcode.Sub; thatSide.Type = bin.Type; } else if (bin.ResolvedOp == BinaryExpr.ResolvedOpcode.Sub) { // Change "A-B op C" in a similar way. if (!FreeVariables(bin.E1).Contains(bv)) { // change to "A op C+B" thisSide = bin.E0.Resolved; thatSide = new BinaryExpr(bin.tok, BinaryExpr.Opcode.Add, thatSide, bin.E1); ((BinaryExpr)thatSide).ResolvedOp = BinaryExpr.ResolvedOpcode.Add; } else if (!FreeVariables(bin.E0).Contains(bv)) { // In principle, change to "-B op C-A" and then to "B dualOp A-C". But since we don't want // to change "op", we instead end with "A-C op B" and switch the mapping of thisSide/thatSide // to e0/e1 (by inverting "whereIsBv"). thisSide = bin.E1.Resolved; thatSide = new BinaryExpr(bin.tok, BinaryExpr.Opcode.Sub, bin.E0, thatSide); ((BinaryExpr)thatSide).ResolvedOp = BinaryExpr.ResolvedOpcode.Sub; whereIsBv = 1 - whereIsBv; } else { break; // done simplifying } thatSide.Type = bin.Type; } else { break; // done simplifying } } break; default: break; } // our transformation above maintained the following invariant: Contract.Assert(!FreeVariables(thatSide).Contains(bv)); // Now, see if the interesting side is simply bv itself if (thisSide is IdentifierExpr && ((IdentifierExpr)thisSide).Var == bv) { // we're cool } else { // no, the situation is more complicated than we care to understand return -1; } // Finally, check the bound variables of "thatSide". We allow "thatSide" to // depend on bound variables that are listed before "bv" (that is, a bound variable // "boundVars[k]" where "k < bvi"). By construction, "thatSide" does not depend // on "bv". Generally, for any bound variable "bj" that is listed after "bv" // (that is, "bj" is some "boundVars[j]" where "bvi < j"), we do not allow // "thatSide" to depend on "bv", but there is an important exception: // If // * "op" makes "thatSide" denote an integer upper bound on "bv" (or, analogously, // a integer lower bound), // * "thatSide" depends on "bj", // * "thatSide" is monotonic in "bj", // * "bj" has a known integer upper bound "u", // * "u" does not depend on "bv" or any bound variable listed after "bv" // (from the way we're constructing bounds, we already know that "u" // does not depend on "bj" or any bound variable listed after "bj") // then we can substitute "u" for "bj" in "thatSide". // By going from right to left, we can make the rule above slightly more // liberal by considering a cascade of substitutions. var fvThatSide = FreeVariables(thatSide); for (int j = boundVars.Count; bvi + 1 <= --j; ) { if (fvThatSide.Contains(boundVars[j])) { if (knownBounds[j] is ComprehensionExpr.IntBoundedPool) { var jBounds = (ComprehensionExpr.IntBoundedPool)knownBounds[j]; Expression u = null; if (op == BinaryExpr.ResolvedOpcode.Lt || op == BinaryExpr.ResolvedOpcode.Le) { u = whereIsBv == 0 ? jBounds.UpperBound : jBounds.LowerBound; } else if (op == BinaryExpr.ResolvedOpcode.Gt || op == BinaryExpr.ResolvedOpcode.Ge) { u = whereIsBv == 0 ? jBounds.LowerBound : jBounds.UpperBound; } if (u != null && !FreeVariables(u).Contains(bv) && IsMonotonic(u, boundVars[j], true)) { thatSide = Translator.Substitute(thatSide, boundVars[j], u); fvThatSide = FreeVariables(thatSide); continue; } } return -1; // forget about "bv OP thatSide" } } // As we return, also return the adjusted sides if (whereIsBv == 0) { e0 = thisSide; e1 = thatSide; } else { e0 = thatSide; e1 = thisSide; } return whereIsBv; } /// <summary> /// If "position", then returns "true" if "x" occurs only positively in "expr". /// If "!position", then returns "true" if "x" occurs only negatively in "expr". /// </summary> public static bool IsMonotonic(Expression expr, IVariable x, bool position) { Contract.Requires(expr != null && expr.Type != null); Contract.Requires(x != null); if (expr is IdentifierExpr) { var e = (IdentifierExpr)expr; return e.Var != x || position; } else if (expr is BinaryExpr) { var e = (BinaryExpr)expr; if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.Add) { return IsMonotonic(e.E0, x, position) && IsMonotonic(e.E1, x, position); } else if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.Sub) { return IsMonotonic(e.E0, x, position) && IsMonotonic(e.E1, x, !position); } } return !FreeVariables(expr).Contains(x); } /// <summary> /// Returns all conjuncts of "expr" in "polarity" positions. That is, if "polarity" is "true", then /// returns the conjuncts of "expr" in positive positions; else, returns the conjuncts of "expr" in /// negative positions. The method considers a canonical-like form of the expression that pushes /// negations inwards far enough that one can determine what the result is going to be (so, almost /// a negation normal form). /// As a convenience, arithmetic inequalities are rewritten so that the negation of an arithmetic /// inequality is never returned and the comparisons > and >= are never returned; the negation of /// a common equality or disequality is rewritten analogously. /// Requires "expr" to be successfully resolved. /// Ensures that what is returned is not a ConcreteSyntaxExpression. /// </summary> static IEnumerable<Expression> NormalizedConjuncts(Expression expr, bool polarity) { // We consider 5 cases. To describe them, define P(e)=Conjuncts(e,true) and N(e)=Conjuncts(e,false). // * X ==> Y is treated as a shorthand for !X || Y, and so is described by the remaining cases // * X && Y P(_) = P(X),P(Y) and N(_) = !(X && Y) // * X || Y P(_) = (X || Y) and N(_) = N(X),N(Y) // * !X P(_) = N(X) and N(_) = P(X) // * else P(_) = else and N(_) = !else // So for ==>, we have: // * X ==> Y P(_) = P(!X || Y) = (!X || Y) = (X ==> Y) // N(_) = N(!X || Y) = N(!X),N(Y) = P(X),N(Y) expr = expr.Resolved; // Binary expressions var b = expr as BinaryExpr; if (b != null) { bool breakDownFurther = false; bool p0 = polarity; switch (b.ResolvedOp) { case BinaryExpr.ResolvedOpcode.And: breakDownFurther = polarity; break; case BinaryExpr.ResolvedOpcode.Or: breakDownFurther = !polarity; break; case BinaryExpr.ResolvedOpcode.Imp: breakDownFurther = !polarity; p0 = !p0; break; default: break; } if (breakDownFurther) { foreach (var c in NormalizedConjuncts(b.E0, p0)) { yield return c; } foreach (var c in NormalizedConjuncts(b.E1, polarity)) { yield return c; } yield break; } } // Unary expression var u = expr as UnaryOpExpr; if (u != null && u.Op == UnaryOpExpr.Opcode.Not) { foreach (var c in NormalizedConjuncts(u.E, !polarity)) { yield return c; } yield break; } // no other case applied, so return the expression or its negation, but first clean it up a little b = expr as BinaryExpr; if (b != null) { BinaryExpr.Opcode newOp; BinaryExpr.ResolvedOpcode newROp; bool swapOperands; switch (b.ResolvedOp) { case BinaryExpr.ResolvedOpcode.Gt: // A > B yield polarity ? (B < A) : (A <= B); newOp = polarity ? BinaryExpr.Opcode.Lt : BinaryExpr.Opcode.Le; newROp = polarity ? BinaryExpr.ResolvedOpcode.Lt : BinaryExpr.ResolvedOpcode.Le; swapOperands = polarity; break; case BinaryExpr.ResolvedOpcode.Ge: // A >= B yield polarity ? (B <= A) : (A < B); newOp = polarity ? BinaryExpr.Opcode.Le : BinaryExpr.Opcode.Lt; newROp = polarity ? BinaryExpr.ResolvedOpcode.Le : BinaryExpr.ResolvedOpcode.Lt; swapOperands = polarity; break; case BinaryExpr.ResolvedOpcode.Le: // A <= B yield polarity ? (A <= B) : (B < A); newOp = polarity ? BinaryExpr.Opcode.Le : BinaryExpr.Opcode.Lt; newROp = polarity ? BinaryExpr.ResolvedOpcode.Le : BinaryExpr.ResolvedOpcode.Lt; swapOperands = !polarity; break; case BinaryExpr.ResolvedOpcode.Lt: // A < B yield polarity ? (A < B) : (B <= A); newOp = polarity ? BinaryExpr.Opcode.Lt : BinaryExpr.Opcode.Le; newROp = polarity ? BinaryExpr.ResolvedOpcode.Lt : BinaryExpr.ResolvedOpcode.Le; swapOperands = !polarity; break; case BinaryExpr.ResolvedOpcode.EqCommon: // A == B yield polarity ? (A == B) : (A != B); newOp = polarity ? BinaryExpr.Opcode.Eq : BinaryExpr.Opcode.Neq; newROp = polarity ? BinaryExpr.ResolvedOpcode.EqCommon : BinaryExpr.ResolvedOpcode.NeqCommon; swapOperands = false; break; case BinaryExpr.ResolvedOpcode.NeqCommon: // A != B yield polarity ? (A != B) : (A == B); newOp = polarity ? BinaryExpr.Opcode.Neq : BinaryExpr.Opcode.Eq; newROp = polarity ? BinaryExpr.ResolvedOpcode.NeqCommon : BinaryExpr.ResolvedOpcode.EqCommon; swapOperands = false; break; default: goto JUST_RETURN_IT; } if (newROp != b.ResolvedOp || swapOperands) { b = new BinaryExpr(b.tok, newOp, swapOperands ? b.E1 : b.E0, swapOperands ? b.E0 : b.E1); b.ResolvedOp = newROp; b.Type = Type.Bool; yield return b; yield break; } } JUST_RETURN_IT: ; if (polarity) { yield return expr; } else { expr = new UnaryOpExpr(expr.tok, UnaryOpExpr.Opcode.Not, expr); expr.Type = Type.Bool; yield return expr; } } /// <summary> /// Returns the set of free variables in "expr". /// Requires "expr" to be successfully resolved. /// Ensures that the set returned has no aliases. /// </summary> static ISet<IVariable> FreeVariables(Expression expr) { Contract.Requires(expr != null); Contract.Ensures(expr.Type != null); if (expr is IdentifierExpr) { var e = (IdentifierExpr)expr; return new HashSet<IVariable>() { e.Var }; } else if (expr is QuantifierExpr) { var e = (QuantifierExpr)expr; Contract.Assert(e.SplitQuantifier == null); // No split quantifiers during resolution var s = FreeVariables(e.LogicalBody()); foreach (var bv in e.BoundVars) { s.Remove(bv); } return s; } else if (expr is NestedMatchExpr) { return FreeVariables(((NestedMatchExpr)expr).ResolvedExpression); } else if (expr is MatchExpr) { var e = (MatchExpr)expr; var s = FreeVariables(e.Source); foreach (MatchCaseExpr mc in e.Cases) { var t = FreeVariables(mc.Body); foreach (var bv in mc.Arguments) { t.Remove(bv); } s.UnionWith(t); } return s; } else if (expr is LambdaExpr) { var e = (LambdaExpr)expr; var s = FreeVariables(e.Term); if (e.Range != null) { s.UnionWith(FreeVariables(e.Range)); } foreach (var fe in e.Reads) { s.UnionWith(FreeVariables(fe.E)); } foreach (var bv in e.BoundVars) { s.Remove(bv); } return s; } else { ISet<IVariable> s = null; foreach (var e in expr.SubExpressions) { var t = FreeVariables(e); if (s == null) { s = t; } else { s.UnionWith(t); } } return s == null ? new HashSet<IVariable>() : s; } } void ResolveReceiver(Expression expr, ResolveOpts opts) { Contract.Requires(expr != null); Contract.Ensures(expr.Type != null); if (expr is ThisExpr && !expr.WasResolved()) { // Allow 'this' here, regardless of scope.AllowInstance. The caller is responsible for // making sure 'this' does not really get used when it's not available. Contract.Assume(currentClass != null); // this is really a precondition, in this case expr.Type = GetThisType(expr.tok, currentClass); } else { ResolveExpression(expr, opts); } } void ResolveSeqSelectExpr(SeqSelectExpr e, ResolveOpts opts) { Contract.Requires(e != null); if (e.Type != null) { // already resolved return; } ResolveExpression(e.Seq, opts); Contract.Assert(e.Seq.Type != null); // follows from postcondition of ResolveExpression if (e.SelectOne) { AddXConstraint(e.tok, "Indexable", e.Seq.Type, "element selection requires a sequence, array, multiset, or map (got {0})"); ResolveExpression(e.E0, opts); AddXConstraint(e.E0.tok, "ContainerIndex", e.Seq.Type, e.E0.Type, "incorrect type for selection into {0} (got {1})"); Contract.Assert(e.E1 == null); e.Type = new InferredTypeProxy() { KeepConstraints = true }; AddXConstraint(e.tok, "ContainerResult", e.Seq.Type, e.Type, "type does not agree with element type of {0} (got {1})"); } else { AddXConstraint(e.tok, "MultiIndexable", e.Seq.Type, "multi-selection of elements requires a sequence or array (got {0})"); if (e.E0 != null) { ResolveExpression(e.E0, opts); AddXConstraint(e.E0.tok, "ContainerIndex", e.Seq.Type, e.E0.Type, "incorrect type for selection into {0} (got {1})"); ConstrainSubtypeRelation(NewIntegerBasedProxy(e.tok), e.E0.Type, e.E0, "wrong number of indices for multi-selection"); } if (e.E1 != null) { ResolveExpression(e.E1, opts); AddXConstraint(e.E1.tok, "ContainerIndex", e.Seq.Type, e.E1.Type, "incorrect type for selection into {0} (got {1})"); ConstrainSubtypeRelation(NewIntegerBasedProxy(e.tok), e.E1.Type, e.E1, "wrong number of indices for multi-selection"); } var resultType = new InferredTypeProxy() { KeepConstraints = true }; e.Type = new SeqType(resultType); AddXConstraint(e.tok, "ContainerResult", e.Seq.Type, resultType, "type does not agree with element type of {0} (got {1})"); } } /// <summary> /// Note: this method is allowed to be called even if "type" does not make sense for "op", as might be the case if /// resolution of the binary expression failed. If so, an arbitrary resolved opcode is returned. /// Usually, the type of the right-hand operand is used to determine the resolved operator (hence, the shorter /// name "operandType" instead of, say, "rightOperandType"). /// </summary> public static BinaryExpr.ResolvedOpcode ResolveOp(BinaryExpr.Opcode op, Type leftOperandType, Type operandType) { Contract.Requires(operandType != null); operandType = operandType.NormalizeExpand(); switch (op) { case BinaryExpr.Opcode.Iff: return BinaryExpr.ResolvedOpcode.Iff; case BinaryExpr.Opcode.Imp: return BinaryExpr.ResolvedOpcode.Imp; case BinaryExpr.Opcode.Exp: return BinaryExpr.ResolvedOpcode.Imp; case BinaryExpr.Opcode.And: return BinaryExpr.ResolvedOpcode.And; case BinaryExpr.Opcode.Or: return BinaryExpr.ResolvedOpcode.Or; case BinaryExpr.Opcode.Eq: if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.SetEq; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.MultiSetEq; } else if (operandType is SeqType) { return BinaryExpr.ResolvedOpcode.SeqEq; } else if (operandType is MapType) { return BinaryExpr.ResolvedOpcode.MapEq; } else { return BinaryExpr.ResolvedOpcode.EqCommon; } case BinaryExpr.Opcode.Neq: if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.SetNeq; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.MultiSetNeq; } else if (operandType is SeqType) { return BinaryExpr.ResolvedOpcode.SeqNeq; } else if (operandType is MapType) { return BinaryExpr.ResolvedOpcode.MapNeq; } else { return BinaryExpr.ResolvedOpcode.NeqCommon; } case BinaryExpr.Opcode.Disjoint: if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.MultiSetDisjoint; } else { return BinaryExpr.ResolvedOpcode.Disjoint; } case BinaryExpr.Opcode.Lt: if (operandType.IsIndDatatype) { return BinaryExpr.ResolvedOpcode.RankLt; } else if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.ProperSubset; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.ProperMultiSubset; } else if (operandType is SeqType) { return BinaryExpr.ResolvedOpcode.ProperPrefix; } else if (operandType is CharType) { return BinaryExpr.ResolvedOpcode.LtChar; } else { return BinaryExpr.ResolvedOpcode.Lt; } case BinaryExpr.Opcode.Le: if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.Subset; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.MultiSubset; } else if (operandType is SeqType) { return BinaryExpr.ResolvedOpcode.Prefix; } else if (operandType is CharType) { return BinaryExpr.ResolvedOpcode.LeChar; } else { return BinaryExpr.ResolvedOpcode.Le; } case BinaryExpr.Opcode.LeftShift: return BinaryExpr.ResolvedOpcode.LeftShift; case BinaryExpr.Opcode.RightShift: return BinaryExpr.ResolvedOpcode.RightShift; case BinaryExpr.Opcode.Add: if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.Union; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.MultiSetUnion; } else if (operandType is MapType) { return BinaryExpr.ResolvedOpcode.MapMerge; } else if (operandType is SeqType) { return BinaryExpr.ResolvedOpcode.Concat; } else { return BinaryExpr.ResolvedOpcode.Add; } case BinaryExpr.Opcode.Sub: if (leftOperandType is MapType) { return BinaryExpr.ResolvedOpcode.MapSubtraction; } else if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.SetDifference; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.MultiSetDifference; } else { return BinaryExpr.ResolvedOpcode.Sub; } case BinaryExpr.Opcode.Mul: if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.Intersection; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.MultiSetIntersection; } else { return BinaryExpr.ResolvedOpcode.Mul; } case BinaryExpr.Opcode.Gt: if (operandType.IsDatatype) { return BinaryExpr.ResolvedOpcode.RankGt; } else if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.ProperSuperset; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.ProperMultiSuperset; } else if (operandType is CharType) { return BinaryExpr.ResolvedOpcode.GtChar; } else { return BinaryExpr.ResolvedOpcode.Gt; } case BinaryExpr.Opcode.Ge: if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.Superset; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.MultiSuperset; } else if (operandType is CharType) { return BinaryExpr.ResolvedOpcode.GeChar; } else { return BinaryExpr.ResolvedOpcode.Ge; } case BinaryExpr.Opcode.In: if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.InSet; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.InMultiSet; } else if (operandType is MapType) { return BinaryExpr.ResolvedOpcode.InMap; } else { return BinaryExpr.ResolvedOpcode.InSeq; } case BinaryExpr.Opcode.NotIn: if (operandType is SetType) { return BinaryExpr.ResolvedOpcode.NotInSet; } else if (operandType is MultiSetType) { return BinaryExpr.ResolvedOpcode.NotInMultiSet; } else if (operandType is MapType) { return BinaryExpr.ResolvedOpcode.NotInMap; } else { return BinaryExpr.ResolvedOpcode.NotInSeq; } case BinaryExpr.Opcode.Div: return BinaryExpr.ResolvedOpcode.Div; case BinaryExpr.Opcode.Mod: return BinaryExpr.ResolvedOpcode.Mod; case BinaryExpr.Opcode.BitwiseAnd: return BinaryExpr.ResolvedOpcode.BitwiseAnd; case BinaryExpr.Opcode.BitwiseOr: return BinaryExpr.ResolvedOpcode.BitwiseOr; case BinaryExpr.Opcode.BitwiseXor: return BinaryExpr.ResolvedOpcode.BitwiseXor; default: Contract.Assert(false); throw new cce.UnreachableException(); // unexpected operator } } /// <summary> /// Returns whether or not 'expr' has any subexpression that uses some feature (like a ghost or quantifier) /// that is allowed only in specification contexts. /// Requires 'expr' to be a successfully resolved expression. /// </summary> bool UsesSpecFeatures(Expression expr) { Contract.Requires(expr != null); Contract.Requires(expr.WasResolved()); // this check approximates the requirement that "expr" be resolved if (expr is LiteralExpr) { return false; } else if (expr is ThisExpr) { return false; } else if (expr is IdentifierExpr) { IdentifierExpr e = (IdentifierExpr)expr; return cce.NonNull(e.Var).IsGhost; } else if (expr is DatatypeValue) { var e = (DatatypeValue)expr; // check all NON-ghost arguments // note that if resolution is successful, then |e.Arguments| == |e.Ctor.Formals| for (int i = 0; i < e.Arguments.Count; i++) { if (!e.Ctor.Formals[i].IsGhost && UsesSpecFeatures(e.Arguments[i])) { return true; } } return false; } else if (expr is DisplayExpression) { DisplayExpression e = (DisplayExpression)expr; return e.Elements.Exists(ee => UsesSpecFeatures(ee)); } else if (expr is MapDisplayExpr) { MapDisplayExpr e = (MapDisplayExpr)expr; return e.Elements.Exists(p => UsesSpecFeatures(p.A) || UsesSpecFeatures(p.B)); } else if (expr is MemberSelectExpr) { MemberSelectExpr e = (MemberSelectExpr)expr; if (e.Member != null) { return cce.NonNull(e.Member).IsGhost || UsesSpecFeatures(e.Obj); } else { return false; } } else if (expr is SeqSelectExpr) { SeqSelectExpr e = (SeqSelectExpr)expr; return UsesSpecFeatures(e.Seq) || (e.E0 != null && UsesSpecFeatures(e.E0)) || (e.E1 != null && UsesSpecFeatures(e.E1)); } else if (expr is MultiSelectExpr) { MultiSelectExpr e = (MultiSelectExpr)expr; return UsesSpecFeatures(e.Array) || e.Indices.Exists(ee => UsesSpecFeatures(ee)); } else if (expr is SeqUpdateExpr) { SeqUpdateExpr e = (SeqUpdateExpr)expr; return UsesSpecFeatures(e.Seq) || UsesSpecFeatures(e.Index) || UsesSpecFeatures(e.Value); } else if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; if (e.Function.IsGhost) { return true; } // check all NON-ghost arguments if (UsesSpecFeatures(e.Receiver)) { return true; } for (int i = 0; i < e.Function.Formals.Count; i++) { if (!e.Function.Formals[i].IsGhost && UsesSpecFeatures(e.Args[i])) { return true; } } return false; } else if (expr is ApplyExpr) { ApplyExpr e = (ApplyExpr)expr; return UsesSpecFeatures(e.Function) || e.Args.Exists(UsesSpecFeatures); } else if (expr is OldExpr || expr is UnchangedExpr) { return true; } else if (expr is UnaryExpr) { var e = (UnaryExpr)expr; var unaryOpExpr = e as UnaryOpExpr; if (unaryOpExpr != null && (unaryOpExpr.Op == UnaryOpExpr.Opcode.Fresh || unaryOpExpr.Op == UnaryOpExpr.Opcode.Allocated)) { return true; } return UsesSpecFeatures(e.E); } else if (expr is BinaryExpr) { BinaryExpr e = (BinaryExpr)expr; switch (e.ResolvedOp_PossiblyStillUndetermined) { case BinaryExpr.ResolvedOpcode.RankGt: case BinaryExpr.ResolvedOpcode.RankLt: return true; default: return UsesSpecFeatures(e.E0) || UsesSpecFeatures(e.E1); } } else if (expr is TernaryExpr) { var e = (TernaryExpr)expr; switch (e.Op) { case TernaryExpr.Opcode.PrefixEqOp: case TernaryExpr.Opcode.PrefixNeqOp: return true; default: break; } return UsesSpecFeatures(e.E0) || UsesSpecFeatures(e.E1) || UsesSpecFeatures(e.E2); } else if (expr is LetExpr) { var e = (LetExpr)expr; if (e.Exact) { MakeGhostAsNeeded(e.LHSs); return UsesSpecFeatures(e.Body); //return Contract.Exists(e.RHSs, ee => UsesSpecFeatures(ee)) || UsesSpecFeatures(e.Body); } else { return true; // let-such-that is always ghost } } else if (expr is QuantifierExpr) { var e = (QuantifierExpr)expr; Contract.Assert(e.SplitQuantifier == null); // No split quantifiers during resolution return e.UncompilableBoundVars().Count != 0 || UsesSpecFeatures(e.LogicalBody()); } else if (expr is SetComprehension) { var e = (SetComprehension)expr; return !e.Finite || e.UncompilableBoundVars().Count != 0 || (e.Range != null && UsesSpecFeatures(e.Range)) || (e.Term != null && UsesSpecFeatures(e.Term)); } else if (expr is MapComprehension) { var e = (MapComprehension)expr; return !e.Finite || e.UncompilableBoundVars().Count != 0 || UsesSpecFeatures(e.Range) || (e.TermLeft != null && UsesSpecFeatures(e.TermLeft)) || UsesSpecFeatures(e.Term); } else if (expr is LambdaExpr) { var e = (LambdaExpr)expr; return UsesSpecFeatures(e.Term); } else if (expr is WildcardExpr) { return false; } else if (expr is StmtExpr) { var e = (StmtExpr)expr; return UsesSpecFeatures(e.E); } else if (expr is ITEExpr) { ITEExpr e = (ITEExpr)expr; return UsesSpecFeatures(e.Test) || UsesSpecFeatures(e.Thn) || UsesSpecFeatures(e.Els); } else if (expr is NestedMatchExpr) { return UsesSpecFeatures(((NestedMatchExpr)expr).ResolvedExpression); } else if (expr is MatchExpr) { MatchExpr me = (MatchExpr)expr; if (UsesSpecFeatures(me.Source)) { return true; } return me.Cases.Exists(mc => UsesSpecFeatures(mc.Body)); } else if (expr is ConcreteSyntaxExpression) { var e = (ConcreteSyntaxExpression)expr; return e.ResolvedExpression != null && UsesSpecFeatures(e.ResolvedExpression); } else if (expr is SeqConstructionExpr) { var e = (SeqConstructionExpr)expr; return UsesSpecFeatures(e.N) || UsesSpecFeatures(e.Initializer); } else if (expr is MultiSetFormingExpr) { var e = (MultiSetFormingExpr)expr; return UsesSpecFeatures(e.E); } else { Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression } } void MakeGhostAsNeeded(List<CasePattern<BoundVar>> lhss) { foreach (CasePattern<BoundVar> lhs in lhss) { MakeGhostAsNeeded(lhs); } } void MakeGhostAsNeeded(CasePattern<BoundVar> lhs) { if (lhs.Ctor != null && lhs.Arguments != null) { for (int i = 0; i < lhs.Arguments.Count && i < lhs.Ctor.Destructors.Count; i++) { MakeGhostAsNeeded(lhs.Arguments[i], lhs.Ctor.Destructors[i]); } } } void MakeGhostAsNeeded(CasePattern<BoundVar> arg, DatatypeDestructor d) { if (arg.Expr is IdentifierExpr ie && ie.Var is BoundVar bv) { if (d.IsGhost) bv.MakeGhost(); } if (arg.Ctor != null) { MakeGhostAsNeeded(arg); } } /// <summary> /// This method adds to "friendlyCalls" all /// inductive calls if !co /// greatest predicate calls and codatatype equalities if co /// that occur in positive positions and not under /// universal quantification if !co /// existential quantification. if co /// If "expr" is the /// precondition of a least lemma if !co /// postcondition of a greatest lemma, if co /// then the "friendlyCalls" are the subexpressions that need to be replaced in order /// to create the /// precondition if !co /// postcondition if co /// of the corresponding prefix lemma. /// </summary> void CollectFriendlyCallsInExtremeLemmaSpecification(Expression expr, bool position, ISet<Expression> friendlyCalls, bool co, ExtremeLemma context) { Contract.Requires(expr != null); Contract.Requires(friendlyCalls != null); var visitor = new CollectFriendlyCallsInSpec_Visitor(this, friendlyCalls, co, context); visitor.Visit(expr, position ? CallingPosition.Positive : CallingPosition.Negative); } class CollectFriendlyCallsInSpec_Visitor : FindFriendlyCalls_Visitor { readonly ISet<Expression> friendlyCalls; readonly ExtremeLemma Context; public CollectFriendlyCallsInSpec_Visitor(Resolver resolver, ISet<Expression> friendlyCalls, bool co, ExtremeLemma context) : base(resolver, co, context.KNat) { Contract.Requires(resolver != null); Contract.Requires(friendlyCalls != null); Contract.Requires(context != null); this.friendlyCalls = friendlyCalls; this.Context = context; } protected override bool VisitOneExpr(Expression expr, ref CallingPosition cp) { if (cp == CallingPosition.Neither) { // no friendly calls in "expr" return false; // don't recurse into subexpressions } if (expr is FunctionCallExpr) { if (cp == CallingPosition.Positive) { var fexp = (FunctionCallExpr)expr; if (IsCoContext ? fexp.Function is GreatestPredicate : fexp.Function is LeastPredicate) { if (Context.KNat != ((ExtremePredicate)fexp.Function).KNat) { resolver.KNatMismatchError(expr.tok, Context.Name, Context.TypeOfK, ((ExtremePredicate)fexp.Function).TypeOfK); } else { friendlyCalls.Add(fexp); } } } return false; // don't explore subexpressions any further } else if (expr is BinaryExpr && IsCoContext) { var bin = (BinaryExpr)expr; if (cp == CallingPosition.Positive && bin.ResolvedOp == BinaryExpr.ResolvedOpcode.EqCommon && bin.E0.Type.IsCoDatatype) { friendlyCalls.Add(bin); return false; // don't explore subexpressions any further } else if (cp == CallingPosition.Negative && bin.ResolvedOp == BinaryExpr.ResolvedOpcode.NeqCommon && bin.E0.Type.IsCoDatatype) { friendlyCalls.Add(bin); return false; // don't explore subexpressions any further } } return base.VisitOneExpr(expr, ref cp); } } } class CoCallResolution { readonly Function currentFunction; readonly bool dealsWithCodatatypes; public bool HasIntraClusterCallsInDestructiveContexts = false; public readonly List<CoCallInfo> FinalCandidates = new List<CoCallInfo>(); public CoCallResolution(Function currentFunction, bool dealsWithCodatatypes) { Contract.Requires(currentFunction != null); this.currentFunction = currentFunction; this.dealsWithCodatatypes = dealsWithCodatatypes; } /// <summary> /// Determines which calls in "expr" can be considered to be co-calls, which co-constructor /// invocations host such co-calls, and which destructor operations are not allowed. /// Also records whether or not there are any intra-cluster calls in a destructive context. /// Assumes "expr" to have been successfully resolved. /// </summary> public void CheckCoCalls(Expression expr) { Contract.Requires(expr != null); CheckCoCalls(expr, 0, null, FinalCandidates); } public struct CoCallInfo { public readonly FunctionCallExpr CandidateCall; public readonly DatatypeValue EnclosingCoConstructor; public CoCallInfo(FunctionCallExpr candidateCall, DatatypeValue enclosingCoConstructor) { Contract.Requires(candidateCall != null); Contract.Requires(enclosingCoConstructor != null); CandidateCall = candidateCall; EnclosingCoConstructor = enclosingCoConstructor; } } /// <summary> /// Recursively goes through the entire "expr". Every call within the same recursive cluster is a potential /// co-call. If the call is determined not to be a co-recursive call, then its .CoCall field is filled in; /// if the situation deals with co-datatypes, then one of the NoBecause... values is chosen (rather /// than just No), so that any error message that may later be produced when trying to prove termination of the /// recursive call can include a note pointing out that the call was not selected to be a co-call. /// If the call looks like it is guarded, then it is added to the list "coCandicates", so that a later analysis /// can either set all of those .CoCall fields to Yes or to NoBecauseRecursiveCallsInDestructiveContext, depending /// on other intra-cluster calls. /// The "destructionLevel" indicates how many pending co-destructors the context has. It may be infinity (int.MaxValue) /// if the enclosing context has no easy way of controlling the uses of "expr" (for example, if the enclosing context /// passes "expr" to a function or binds "expr" to a variable). It is never negative -- excess co-constructors are /// not considered an asset, and any immediately enclosing co-constructor is passed in as a non-null "coContext" anyway. /// "coContext" is non-null if the immediate context is a co-constructor. /// </summary> void CheckCoCalls(Expression expr, int destructionLevel, DatatypeValue coContext, List<CoCallInfo> coCandidates, Function functionYouMayWishWereAbstemious = null) { Contract.Requires(expr != null); Contract.Requires(0 <= destructionLevel); Contract.Requires(coCandidates != null); expr = expr.Resolved; if (expr is DatatypeValue) { var e = (DatatypeValue)expr; if (e.Ctor.EnclosingDatatype is CoDatatypeDecl) { int dl = destructionLevel == int.MaxValue ? int.MaxValue : destructionLevel == 0 ? 0 : destructionLevel - 1; foreach (var arg in e.Arguments) { CheckCoCalls(arg, dl, e, coCandidates); } return; } } else if (expr is MemberSelectExpr) { var e = (MemberSelectExpr)expr; if (e.Member.EnclosingClass is CoDatatypeDecl) { int dl = destructionLevel == int.MaxValue ? int.MaxValue : destructionLevel + 1; CheckCoCalls(e.Obj, dl, coContext, coCandidates); return; } } else if (expr is BinaryExpr) { var e = (BinaryExpr)expr; if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.EqCommon || e.ResolvedOp == BinaryExpr.ResolvedOpcode.NeqCommon) { // Equality and disequality (for any type that may contain a co-datatype) are as destructive as can be--in essence, // they destruct the values indefinitely--so don't allow any co-recursive calls in the operands. CheckCoCalls(e.E0, int.MaxValue, null, coCandidates); CheckCoCalls(e.E1, int.MaxValue, null, coCandidates); return; } } else if (expr is TernaryExpr) { var e = (TernaryExpr)expr; if (e.Op == TernaryExpr.Opcode.PrefixEqOp || e.Op == TernaryExpr.Opcode.PrefixNeqOp) { // Prefix equality and disequality (for any type that may contain a co-datatype) are destructive. CheckCoCalls(e.E0, int.MaxValue, null, coCandidates); CheckCoCalls(e.E1, int.MaxValue, null, coCandidates); CheckCoCalls(e.E2, int.MaxValue, null, coCandidates); return; } } else if (expr is NestedMatchExpr) { var e = (NestedMatchExpr)expr; CheckCoCalls(e.ResolvedExpression, destructionLevel, coContext, coCandidates); } else if (expr is MatchExpr) { var e = (MatchExpr)expr; CheckCoCalls(e.Source, int.MaxValue, null, coCandidates); foreach (var kase in e.Cases) { CheckCoCalls(kase.Body, destructionLevel, coContext, coCandidates); } return; } else if (expr is ITEExpr) { var e = (ITEExpr)expr; CheckCoCalls(e.Test, int.MaxValue, null, coCandidates); CheckCoCalls(e.Thn, destructionLevel, coContext, coCandidates); CheckCoCalls(e.Els, destructionLevel, coContext, coCandidates); return; } else if (expr is FunctionCallExpr) { var e = (FunctionCallExpr)expr; // First, consider the arguments of the call, making sure that they do not include calls within the recursive cluster, // unless the callee is abstemious. var abstemious = true; if (!Attributes.ContainsBool(e.Function.Attributes, "abstemious", ref abstemious)) { abstemious = false; } Contract.Assert(e.Args.Count == e.Function.Formals.Count); for (var i = 0; i < e.Args.Count; i++) { var arg = e.Args[i]; if (!e.Function.Formals[i].Type.IsCoDatatype) { CheckCoCalls(arg, int.MaxValue, null, coCandidates); } else if (abstemious) { CheckCoCalls(arg, 0, coContext, coCandidates); } else { // don't you wish the callee were abstemious CheckCoCalls(arg, int.MaxValue, null, coCandidates, e.Function); } } // Second, investigate the possibility that this call itself may be a candidate co-call if (e.Name != "requires" && ModuleDefinition.InSameSCC(currentFunction, e.Function)) { // This call goes to another function in the same recursive cluster if (destructionLevel != 0 && GuaranteedCoCtors(e.Function) <= destructionLevel) { // a potentially destructive context HasIntraClusterCallsInDestructiveContexts = true; // this says we found an intra-cluster call unsuitable for recursion, if there were any co-recursive calls if (!dealsWithCodatatypes) { e.CoCall = FunctionCallExpr.CoCallResolution.No; } else { e.CoCall = FunctionCallExpr.CoCallResolution.NoBecauseRecursiveCallsAreNotAllowedInThisContext; if (functionYouMayWishWereAbstemious != null) { e.CoCallHint = string.Format("perhaps try declaring function '{0}' with '{{:abstemious}}'", functionYouMayWishWereAbstemious.Name); } } } else if (coContext == null) { // no immediately enclosing co-constructor if (!dealsWithCodatatypes) { e.CoCall = FunctionCallExpr.CoCallResolution.No; } else { e.CoCall = FunctionCallExpr.CoCallResolution.NoBecauseIsNotGuarded; } } else if (e.Function.Reads.Count != 0) { // this call is disqualified from being a co-call, because of side effects if (!dealsWithCodatatypes) { e.CoCall = FunctionCallExpr.CoCallResolution.No; } else { e.CoCall = FunctionCallExpr.CoCallResolution.NoBecauseFunctionHasSideEffects; } } else if (e.Function.Ens.Count != 0) { // this call is disqualified from being a co-call, because it has a postcondition // (a postcondition could be allowed, as long as it does not get to be used with // co-recursive calls, because that could be unsound; for example, consider // "ensures false") if (!dealsWithCodatatypes) { e.CoCall = FunctionCallExpr.CoCallResolution.No; } else { e.CoCall = FunctionCallExpr.CoCallResolution.NoBecauseFunctionHasPostcondition; } } else { // e.CoCall is not filled in here, but will be filled in when the list of candidates are processed coCandidates.Add(new CoCallInfo(e, coContext)); } } return; } else if (expr is LambdaExpr) { var e = (LambdaExpr)expr; CheckCoCalls(e.Body, destructionLevel, coContext, coCandidates); if (e.Range != null) { CheckCoCalls(e.Range, int.MaxValue, null, coCandidates); } foreach (var read in e.Reads) { CheckCoCalls(read.E, int.MaxValue, null, coCandidates); } return; } else if (expr is MapComprehension) { var e = (MapComprehension)expr; foreach (var ee in Attributes.SubExpressions(e.Attributes)) { CheckCoCalls(ee, int.MaxValue, null, coCandidates); } if (e.Range != null) { CheckCoCalls(e.Range, int.MaxValue, null, coCandidates); } // allow co-calls in the term if (e.TermLeft != null) { CheckCoCalls(e.TermLeft, destructionLevel, coContext, coCandidates); } CheckCoCalls(e.Term, destructionLevel, coContext, coCandidates); return; } else if (expr is OldExpr) { var e = (OldExpr)expr; // here, "coContext" is passed along (the use of "old" says this must be ghost code, so the compiler does not need to handle this case) CheckCoCalls(e.E, destructionLevel, coContext, coCandidates); return; } else if (expr is LetExpr) { var e = (LetExpr)expr; foreach (var rhs in e.RHSs) { CheckCoCalls(rhs, int.MaxValue, null, coCandidates); } CheckCoCalls(e.Body, destructionLevel, coContext, coCandidates); return; } else if (expr is ApplyExpr) { var e = (ApplyExpr)expr; CheckCoCalls(e.Function, int.MaxValue, null, coCandidates); foreach (var ee in e.Args) { CheckCoCalls(ee, destructionLevel, null, coCandidates); } return; } // Default handling: foreach (var ee in expr.SubExpressions) { CheckCoCalls(ee, destructionLevel, null, coCandidates); } } public static int GuaranteedCoCtors(Function function) { Contract.Requires(function != null); return function.Body != null ? GuaranteedCoCtorsAux(function.Body) : 0; } private static int GuaranteedCoCtorsAux(Expression expr) { Contract.Requires(expr != null); expr = expr.Resolved; if (expr is DatatypeValue) { var e = (DatatypeValue)expr; if (e.Ctor.EnclosingDatatype is CoDatatypeDecl) { var minOfArgs = int.MaxValue; // int.MaxValue means: not yet encountered a formal whose type is a co-datatype Contract.Assert(e.Arguments.Count == e.Ctor.Formals.Count); for (var i = 0; i < e.Arguments.Count; i++) { if (e.Ctor.Formals[i].Type.IsCoDatatype) { var n = GuaranteedCoCtorsAux(e.Arguments[i]); minOfArgs = Math.Min(minOfArgs, n); } } return minOfArgs == int.MaxValue ? 1 : 1 + minOfArgs; } } else if (expr is ITEExpr) { var e = (ITEExpr)expr; var thn = GuaranteedCoCtorsAux(e.Thn); var els = GuaranteedCoCtorsAux(e.Els); return thn < els ? thn : els; } else if (expr is NestedMatchExpr) { var e = (NestedMatchExpr)expr; return GuaranteedCoCtorsAux(e.ResolvedExpression); } else if (expr is MatchExpr) { var e = (MatchExpr)expr; var min = int.MaxValue; foreach (var kase in e.Cases) { var n = GuaranteedCoCtorsAux(kase.Body); min = Math.Min(min, n); } return min == int.MaxValue ? 0 : min; } else if (expr is LetExpr) { var e = (LetExpr)expr; return GuaranteedCoCtorsAux(e.Body); } else if (expr is IdentifierExpr) { var e = (IdentifierExpr)expr; if (e.Type.IsCoDatatype && e.Var is Formal) { // even though this is not a co-constructor, count this as 1, since that's what we would have done if it were, e.g., "Cons(s.head, s.tail)" instead of "s" return 1; } } return 0; } } class Scope<Thing> where Thing : class { [Rep] readonly List<string> names = new List<string>(); // a null means a marker [Rep] readonly List<Thing> things = new List<Thing>(); [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(names != null); Contract.Invariant(things != null); Contract.Invariant(names.Count == things.Count); Contract.Invariant(-1 <= scopeSizeWhereInstancesWereDisallowed && scopeSizeWhereInstancesWereDisallowed <= names.Count); } int scopeSizeWhereInstancesWereDisallowed = -1; public bool AllowInstance { get { return scopeSizeWhereInstancesWereDisallowed == -1; } set { Contract.Requires(AllowInstance && !value); // only allowed to change from true to false (that's all that's currently needed in Dafny); Pop is what can make the change in the other direction scopeSizeWhereInstancesWereDisallowed = names.Count; } } public void PushMarker() { names.Add(null); things.Add(null); } public void PopMarker() { int n = names.Count; while (true) { n--; if (names[n] == null) { break; } } names.RemoveRange(n, names.Count - n); things.RemoveRange(n, things.Count - n); if (names.Count < scopeSizeWhereInstancesWereDisallowed) { scopeSizeWhereInstancesWereDisallowed = -1; } } public enum PushResult { Duplicate, Shadow, Success } /// <summary> /// Pushes name-->thing association and returns "Success", if name has not already been pushed since the last marker. /// If name already has been pushed since the last marker, does nothing and returns "Duplicate". /// If the appropriate command-line option is supplied, then this method will also check if "name" shadows a previous /// name; if it does, then it will return "Shadow" instead of "Success". /// </summary> public PushResult Push(string name, Thing thing) { Contract.Requires(name != null); Contract.Requires(thing != null); if (Find(name, true) != null) { return PushResult.Duplicate; } else { var r = PushResult.Success; if (DafnyOptions.O.WarnShadowing && Find(name, false) != null) { r = PushResult.Shadow; } names.Add(name); things.Add(thing); return r; } } Thing Find(string name, bool topScopeOnly) { Contract.Requires(name != null); for (int n = names.Count; 0 <= --n; ) { if (names[n] == null) { if (topScopeOnly) { return null; // not present } } else if (names[n] == name) { Thing t = things[n]; Contract.Assert(t != null); return t; } } return null; // not present } public Thing Find(string name) { Contract.Requires(name != null); return Find(name, false); } public Thing FindInCurrentScope(string name) { Contract.Requires(name != null); return Find(name, true); } public bool ContainsDecl(Thing t) { return things.Exists(thing => thing == t); } } }
48.388522
358
0.607437
[ "MIT" ]
857b/dafny
Source/Dafny/Resolver.cs
872,691
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using WinForms.Common.Tests; using Xunit; using static Interop; namespace System.Windows.Forms.Tests { using Point = System.Drawing.Point; using Size = System.Drawing.Size; public class TextBoxTests : IClassFixture<ThreadExceptionFixture> { private static int s_preferredHeight = Control.DefaultFont.Height + SystemInformation.BorderSize.Height * 4 + 3; [WinFormsFact] public void TextBox_Ctor_Default() { using var control = new SubTextBox(); Assert.False(control.AcceptsReturn); Assert.False(control.AcceptsTab); Assert.Null(control.AccessibleDefaultActionDescription); Assert.Null(control.AccessibleDescription); Assert.Null(control.AccessibleName); Assert.Equal(AccessibleRole.Default, control.AccessibleRole); Assert.False(control.AllowDrop); Assert.Equal(AnchorStyles.Top | AnchorStyles.Left, control.Anchor); Assert.Empty(control.AutoCompleteCustomSource); Assert.Same(control.AutoCompleteCustomSource, control.AutoCompleteCustomSource); Assert.Equal(AutoCompleteMode.None, control.AutoCompleteMode); Assert.Equal(AutoCompleteSource.None, control.AutoCompleteSource); Assert.True(control.AutoSize); Assert.Equal(SystemColors.Window, control.BackColor); Assert.Null(control.BackgroundImage); Assert.Equal(ImageLayout.Tile, control.BackgroundImageLayout); Assert.Null(control.BindingContext); Assert.Equal(BorderStyle.Fixed3D, control.BorderStyle); Assert.Equal(control.PreferredHeight, control.Bottom); Assert.Equal(new Rectangle(0, 0, 100, control.PreferredHeight), control.Bounds); Assert.False(control.CanFocus); Assert.True(control.CanRaiseEvents); Assert.True(control.CanSelect); Assert.False(control.CanUndo); Assert.False(control.Capture); Assert.True(control.CausesValidation); Assert.Equal(CharacterCasing.Normal, control.CharacterCasing); Assert.Equal(new Size(96, control.PreferredHeight - 4), control.ClientSize); Assert.Equal(new Rectangle(0, 0, 96, control.PreferredHeight - 4), control.ClientRectangle); Assert.Null(control.Container); Assert.False(control.ContainsFocus); Assert.Null(control.ContextMenuStrip); Assert.Empty(control.Controls); Assert.Same(control.Controls, control.Controls); Assert.False(control.Created); Assert.Same(Cursors.IBeam, control.Cursor); Assert.Same(Cursors.IBeam, control.DefaultCursor); Assert.Equal(ImeMode.Inherit, control.DefaultImeMode); Assert.Equal(new Padding(3), control.DefaultMargin); Assert.Equal(Size.Empty, control.DefaultMaximumSize); Assert.Equal(Size.Empty, control.DefaultMinimumSize); Assert.Equal(Padding.Empty, control.DefaultPadding); Assert.Equal(new Size(100, control.PreferredHeight), control.DefaultSize); Assert.False(control.DesignMode); Assert.Equal(new Rectangle(0, 0, 96, control.PreferredHeight - 4), control.DisplayRectangle); Assert.Equal(DockStyle.None, control.Dock); Assert.False(control.DoubleBuffered); Assert.True(control.Enabled); Assert.NotNull(control.Events); Assert.Same(control.Events, control.Events); Assert.False(control.Focused); Assert.Equal(Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.Equal(SystemColors.WindowText, control.ForeColor); Assert.False(control.HasChildren); Assert.Equal(control.PreferredHeight, control.Height); Assert.True(control.HideSelection); Assert.False(control.IsAccessible); Assert.False(control.IsMirrored); Assert.NotNull(control.LayoutEngine); Assert.Same(control.LayoutEngine, control.LayoutEngine); Assert.Equal(0, control.Left); Assert.Empty(control.Lines); Assert.Equal(Point.Empty, control.Location); Assert.Equal(new Padding(3), control.Margin); Assert.Equal(Size.Empty, control.MaximumSize); Assert.Equal(32767, control.MaxLength); Assert.Equal(Size.Empty, control.MinimumSize); Assert.False(control.Modified); Assert.False(control.Multiline); Assert.Equal(Padding.Empty, control.Padding); Assert.Null(control.Parent); Assert.Equal("Microsoft\u00AE .NET", control.ProductName); Assert.Equal(4, control.PreferredSize.Width); Assert.True(control.PreferredSize.Height > 0); Assert.True(control.PreferredHeight > 0); Assert.False(control.ReadOnly); Assert.False(control.RecreatingHandle); Assert.Null(control.Region); Assert.False(control.ResizeRedraw); Assert.Equal(100, control.Right); Assert.Equal(RightToLeft.No, control.RightToLeft); Assert.Equal(ScrollBars.None, control.ScrollBars); Assert.Empty(control.SelectedText); Assert.Equal(0, control.SelectionLength); Assert.Equal(0, control.SelectionStart); Assert.True(control.ShortcutsEnabled); Assert.True(control.ShowFocusCues); Assert.True(control.ShowKeyboardCues); Assert.Null(control.Site); Assert.Equal(new Size(100, control.PreferredHeight), control.Size); Assert.Equal(0, control.TabIndex); Assert.True(control.TabStop); Assert.Empty(control.Text); Assert.Equal(HorizontalAlignment.Left, control.TextAlign); Assert.Equal(0, control.TextLength); Assert.Equal(0, control.Top); Assert.Null(control.TopLevelControl); Assert.False(control.UseSystemPasswordChar); Assert.False(control.UseWaitCursor); Assert.True(control.Visible); Assert.Equal(100, control.Width); Assert.True(control.WordWrap); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void TextBox_CreateParams_GetDefault_ReturnsExpected() { using var control = new SubTextBox(); CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("Edit", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0x200, createParams.ExStyle); Assert.Equal(control.PreferredHeight, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(0x560100C0, createParams.Style); Assert.Equal(100, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void TextBox_CanEnableIme_GetWithoutHandle_ReturnsExpected() { using var control = new SubTextBox(); Assert.True(control.CanEnableIme); Assert.True(control.IsHandleCreated); // Get again. Assert.True(control.CanEnableIme); Assert.True(control.IsHandleCreated); } [WinFormsFact] public void TextBox_CanEnableIme_GetWithHandle_ReturnsExpected() { using var control = new SubTextBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.True(control.CanEnableIme); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Get again. Assert.True(control.CanEnableIme); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void TextBox_ImeMode_GetWithoutHandle_ReturnsExpected() { using var control = new SubTextBox(); Assert.Equal(ImeMode.NoControl, control.ImeMode); Assert.True(control.IsHandleCreated); // Get again. Assert.Equal(ImeMode.NoControl, control.ImeMode); Assert.True(control.IsHandleCreated); } [WinFormsFact] public void TextBox_ImeMode_GetWithHandle_ReturnsExpected() { using var control = new SubTextBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.Equal(ImeMode.NoControl, control.ImeMode); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Get again. Assert.Equal(ImeMode.NoControl, control.ImeMode); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void TextBox_ImeModeBase_GetWithoutHandle_ReturnsExpected() { using var control = new SubTextBox(); Assert.Equal(ImeMode.NoControl, control.ImeModeBase); Assert.True(control.IsHandleCreated); // Get again. Assert.Equal(ImeMode.NoControl, control.ImeModeBase); Assert.True(control.IsHandleCreated); } [WinFormsFact] public void TextBox_ImeModeBase_GetWithHandle_ReturnsExpected() { using var control = new SubTextBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.Equal(ImeMode.NoControl, control.ImeModeBase); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Get again. Assert.Equal(ImeMode.NoControl, control.ImeModeBase); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void TextBox_PasswordChar_GetWithoutHandle_ReturnsExpected() { using var control = new SubTextBox(); Assert.Equal('\0', control.PasswordChar); Assert.True(control.IsHandleCreated); // Get again. Assert.Equal('\0', control.PasswordChar); Assert.True(control.IsHandleCreated); } [WinFormsFact] public void TextBox_PasswordChar_GetWithHandle_ReturnsExpected() { using var control = new SubTextBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.Equal('\0', control.PasswordChar); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Get again. Assert.Equal('\0', control.PasswordChar); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void TextBox_PlaceholderText() { using var tb = new TextBox { PlaceholderText = "Enter your name" }; Assert.False(string.IsNullOrEmpty(tb.PlaceholderText)); } [WinFormsFact] public void TextBox_PlaceholderText_DefaultValue() { using var tb = new TextBox(); Assert.Equal(string.Empty, tb.PlaceholderText); } [WinFormsFact] public void TextBox_PlaceholderText_When_InAccessibility_Doesnot_Raise_TextChanged() { using var tb = new SubTextBox(); bool eventRaised = false; EventHandler handler = (o, e) => eventRaised = true; tb.TextChanged += handler; tb.CreateAccessibilityInstance(); Assert.False(eventRaised); tb.TextChanged -= handler; } public static IEnumerable<object[]> TextBox_ShouldRenderPlaceHolderText_TestData() { // Test PlaceholderText var tb = new SubTextBox() { PlaceholderText = "", IsUserPaint = false, IsFocused = false, TextCount = 0 }; var msg = new Message() { Msg = (int)User32.WM.PAINT }; yield return new object[] { tb, msg, false }; // Test PlaceholderText tb = new SubTextBox() { PlaceholderText = null, IsUserPaint = false, IsFocused = false, TextCount = 0 }; msg = new Message() { Msg = (int)User32.WM.PAINT }; yield return new object[] { tb, msg, false }; // Test Message msg.Msg = (int)User32.WM.USER; tb = new SubTextBox() { PlaceholderText = "Text", IsUserPaint = false, IsFocused = false, TextCount = 0 }; yield return new object[] { tb, msg, false }; // Test UserPaint msg.Msg = (int)User32.WM.PAINT; tb = new SubTextBox() { PlaceholderText = "Text", IsUserPaint = true, IsFocused = false, TextCount = 0 }; yield return new object[] { tb, msg, false }; // Test Focused msg.Msg = (int)User32.WM.PAINT; tb = new SubTextBox() { PlaceholderText = "Text", IsUserPaint = false, IsFocused = true, TextCount = 0 }; yield return new object[] { tb, msg, false }; // Test TextLength msg.Msg = (int)User32.WM.PAINT; tb = new SubTextBox() { PlaceholderText = "Text", IsUserPaint = false, IsFocused = false, TextCount = 1 }; yield return new object[] { tb, msg, false }; // Test WM_PAINT tb = new SubTextBox() { PlaceholderText = "Text", IsUserPaint = false, IsFocused = false, TextCount = 0 }; msg.Msg = (int)User32.WM.PAINT; yield return new object[] { tb, msg, true }; // Test WM_KILLFOCUS tb = new SubTextBox() { PlaceholderText = "Text", IsUserPaint = false, IsFocused = false, TextCount = 0 }; msg.Msg = (int)User32.WM.KILLFOCUS; yield return new object[] { tb, msg, true }; } [WinFormsTheory] [MemberData(nameof(TextBox_ShouldRenderPlaceHolderText_TestData))] public void TextBox_ShouldRenderPlaceHolderText(TextBox textBox, Message m, bool expected) { var result = textBox.GetTestAccessor().ShouldRenderPlaceHolderText(m); Assert.Equal(expected, result); } [WinFormsFact] public void TextBox_PlaceholderText_NullValue_CoercedTo_StringEmpty() { using var tb = new TextBox() { PlaceholderText = "Text" }; tb.PlaceholderText = null; Assert.Equal(string.Empty, tb.PlaceholderText); } [WinFormsFact] public void TextBox_PlaceholderText_Overriden() { using var tb = new SubTextBox(); Assert.NotNull(tb); } [WinFormsFact] public void TextBox_PlaceholderTextAlignments() { using var tb = new TextBox { PlaceholderText = "Enter your name" }; System.Runtime.InteropServices.HandleRef refHandle = new System.Runtime.InteropServices.HandleRef(tb, tb.Handle); //Cover the Placeholder draw code path User32.SendMessageW(refHandle, User32.WM.PAINT, PARAM.FromBool(false)); tb.TextAlign = HorizontalAlignment.Center; User32.SendMessageW(refHandle, User32.WM.PAINT, PARAM.FromBool(false)); tb.TextAlign = HorizontalAlignment.Right; User32.SendMessageW(refHandle, User32.WM.PAINT, PARAM.FromBool(false)); Assert.False(string.IsNullOrEmpty(tb.PlaceholderText)); } [WinFormsFact] public void TextBox_PlaceholderTextAlignmentsInRightToLeft() { using var tb = new TextBox { PlaceholderText = "Enter your name", RightToLeft = RightToLeft.Yes }; System.Runtime.InteropServices.HandleRef refHandle = new System.Runtime.InteropServices.HandleRef(tb, tb.Handle); //Cover the Placeholder draw code path in RightToLeft scenario User32.SendMessageW(refHandle, User32.WM.PAINT, PARAM.FromBool(false)); tb.TextAlign = HorizontalAlignment.Center; User32.SendMessageW(refHandle, User32.WM.PAINT, PARAM.FromBool(false)); tb.TextAlign = HorizontalAlignment.Right; User32.SendMessageW(refHandle, User32.WM.PAINT, PARAM.FromBool(false)); Assert.False(string.IsNullOrEmpty(tb.PlaceholderText)); } [WinFormsFact] public void TextBox_CreateAccessibilityInstance_Invoke_ReturnsExpected() { using var control = new SubTextBox(); Control.ControlAccessibleObject instance = Assert.IsType<Control.ControlAccessibleObject>(control.CreateAccessibilityInstance()); Assert.NotNull(instance); Assert.Same(control, instance.Owner); Assert.Equal(AccessibleRole.Text, instance.Role); Assert.NotSame(control.CreateAccessibilityInstance(), instance); Assert.NotSame(control.AccessibilityObject, instance); } [WinFormsFact] public void TextBox_CreateAccessibilityInstance_InvokeWithCustomRole_ReturnsExpected() { using var control = new SubTextBox { AccessibleRole = AccessibleRole.HelpBalloon }; Control.ControlAccessibleObject instance = Assert.IsType<Control.ControlAccessibleObject>(control.CreateAccessibilityInstance()); Assert.NotNull(instance); Assert.Same(control, instance.Owner); Assert.Equal(AccessibleRole.HelpBalloon, instance.Role); Assert.NotSame(control.CreateAccessibilityInstance(), instance); Assert.NotSame(control.AccessibilityObject, instance); } [WinFormsFact] public void TextBox_GetAutoSizeMode_Invoke_ReturnsExpected() { using var control = new SubTextBox(); Assert.Equal(AutoSizeMode.GrowOnly, control.GetAutoSizeMode()); } [WinFormsTheory] [InlineData(ControlStyles.ContainerControl, false)] [InlineData(ControlStyles.UserPaint, false)] [InlineData(ControlStyles.Opaque, false)] [InlineData(ControlStyles.ResizeRedraw, false)] [InlineData(ControlStyles.FixedWidth, false)] [InlineData(ControlStyles.FixedHeight, true)] [InlineData(ControlStyles.StandardClick, false)] [InlineData(ControlStyles.Selectable, true)] [InlineData(ControlStyles.UserMouse, false)] [InlineData(ControlStyles.SupportsTransparentBackColor, false)] [InlineData(ControlStyles.StandardDoubleClick, false)] [InlineData(ControlStyles.AllPaintingInWmPaint, true)] [InlineData(ControlStyles.CacheText, false)] [InlineData(ControlStyles.EnableNotifyMessage, false)] [InlineData(ControlStyles.DoubleBuffer, false)] [InlineData(ControlStyles.OptimizedDoubleBuffer, false)] [InlineData(ControlStyles.UseTextForAccessibility, false)] [InlineData((ControlStyles)0, true)] [InlineData((ControlStyles)int.MaxValue, false)] [InlineData((ControlStyles)(-1), false)] public void TextBox_GetStyle_Invoke_ReturnsExpected(ControlStyles flag, bool expected) { using var control = new SubTextBox(); Assert.Equal(expected, control.GetStyle(flag)); // Call again to test caching. Assert.Equal(expected, control.GetStyle(flag)); } [WinFormsFact] public void TextBox_GetTopLevel_Invoke_ReturnsExpected() { using var control = new SubTextBox(); Assert.False(control.GetTopLevel()); } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] public void TextBox_OnHandleCreated_Invoke_CallsHandleCreated(EventArgs eventArgs) { using var control = new SubTextBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.HandleCreated += handler; control.OnHandleCreated(eventArgs); Assert.Equal(1, callCount); Assert.Equal(s_preferredHeight, control.Height); Assert.False(control.IsHandleCreated); // Remove handler. control.HandleCreated -= handler; control.OnHandleCreated(eventArgs); Assert.Equal(1, callCount); Assert.Equal(s_preferredHeight, control.Height); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] public void TextBox_OnHandleCreated_InvokeWithHandle_CallsHandleCreated(EventArgs eventArgs) { using var control = new SubTextBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.HandleCreated += handler; control.OnHandleCreated(eventArgs); Assert.Equal(1, callCount); Assert.Equal(s_preferredHeight, control.Height); Assert.True(control.IsHandleCreated); // Remove handler. control.HandleCreated -= handler; control.OnHandleCreated(eventArgs); Assert.Equal(1, callCount); Assert.Equal(s_preferredHeight, control.Height); Assert.True(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetEventArgsTheoryData))] public void TextBox_OnHandleDestroyed_Invoke_CallsHandleDestroyed(EventArgs eventArgs) { using var control = new SubTextBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.HandleDestroyed += handler; control.OnHandleDestroyed(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); // Remove handler. control.HandleDestroyed -= handler; control.OnHandleDestroyed(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> OnHandleDestroyed_TestData() { foreach (bool modified in new bool[] { true, false }) { yield return new object[] { modified, null }; yield return new object[] { modified, new EventArgs() }; } } [WinFormsTheory] [MemberData(nameof(OnHandleDestroyed_TestData))] public void TextBox_OnHandleDestroyed_InvokeWithHandle_CallsHandleDestroyed(bool modified, EventArgs eventArgs) { using var control = new SubTextBox { Text = "Text", SelectionStart = 1, SelectionLength = 2, Modified = modified }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.HandleDestroyed += handler; control.OnHandleDestroyed(eventArgs); Assert.Equal(1, callCount); Assert.Equal(s_preferredHeight, control.Height); Assert.Equal(0, control.SelectionStart); Assert.Equal(0, control.SelectionLength); Assert.Equal(modified, control.Modified); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Remove handler. control.HandleDestroyed -= handler; control.OnHandleDestroyed(eventArgs); Assert.Equal(1, callCount); Assert.Equal(s_preferredHeight, control.Height); Assert.Equal(0, control.SelectionStart); Assert.Equal(0, control.SelectionLength); Assert.Equal(modified, control.Modified); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } private class SubTextBox : TextBox { public int TextCount; public bool IsFocused; public bool TextAccessed; public new bool CanEnableIme => base.CanEnableIme; public new bool CanRaiseEvents => base.CanRaiseEvents; public new CreateParams CreateParams => base.CreateParams; public new Cursor DefaultCursor => base.DefaultCursor; public new ImeMode DefaultImeMode => base.DefaultImeMode; public new Padding DefaultMargin => base.DefaultMargin; public new Size DefaultMaximumSize => base.DefaultMaximumSize; public new Size DefaultMinimumSize => base.DefaultMinimumSize; public new Padding DefaultPadding => base.DefaultPadding; public new Size DefaultSize => base.DefaultSize; public new bool DesignMode => base.DesignMode; public new bool DoubleBuffered { get => base.DoubleBuffered; set => base.DoubleBuffered = value; } public new EventHandlerList Events => base.Events; public new int FontHeight { get => base.FontHeight; set => base.FontHeight = value; } public new ImeMode ImeModeBase { get => base.ImeModeBase; set => base.ImeModeBase = value; } public new bool ResizeRedraw { get => base.ResizeRedraw; set => base.ResizeRedraw = value; } public new bool ShowFocusCues => base.ShowFocusCues; public new bool ShowKeyboardCues => base.ShowKeyboardCues; public override string PlaceholderText { get => base.PlaceholderText; set => base.PlaceholderText = value; } public new AccessibleObject CreateAccessibilityInstance() => base.CreateAccessibilityInstance(); public new AutoSizeMode GetAutoSizeMode() => base.GetAutoSizeMode(); public new bool GetStyle(ControlStyles flag) => base.GetStyle(flag); public new bool GetTopLevel() => base.GetTopLevel(); public override bool Focused => IsFocused; public override int TextLength => TextCount; public override string Text { get { TextAccessed = true; return base.Text; } set => base.Text = value; } public bool IsUserPaint { get => GetStyle(ControlStyles.UserPaint); set => SetStyle(ControlStyles.UserPaint, value); } public new void OnHandleCreated(EventArgs e) => base.OnHandleCreated(e); public new void OnHandleDestroyed(EventArgs e) => base.OnHandleDestroyed(e); } } }
41.570292
141
0.609303
[ "MIT" ]
Logerfo/winforms
src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs
31,346
C#
using TasksEverywhere.CastleWindsor.Services.Abstract; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace TasksEverywhere.Logging.Services.Abstract { public interface ILoggingService : ISingletonService { bool Active { get; set; } void Configure(); void Debug(Type type, MethodBase method, string message); void Error(Type type, MethodBase method, string message, Exception ex); void Info(Type type, MethodBase method, string message); } }
29.7
79
0.734007
[ "MIT" ]
Crasso91/TasksEverywhere
TasksEverywhere.Logging/Services/Abstract/ILoggingService.cs
596
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Chromely.Core.RestfulService; namespace ChromelyReactCefGlue.Controllers { /// <summary> /// The demo controller. /// </summary> [ControllerProperty(Name = "DemoController", Route = "democontroller")] public class DemoController : ChromelyController { /// <summary> /// Initializes a new instance of the <see cref="DemoController"/> class. /// </summary> public DemoController() { this.RegisterGetRequest("/democontroller/movies", this.GetMovies); this.RegisterPostRequest("/democontroller/movies", this.SaveMovies); } /// <summary> /// The get movies. /// </summary> /// <param name="request"> /// The request. /// </param> /// <returns> /// The <see cref="ChromelyResponse"/>. /// </returns> private ChromelyResponse GetMovies(ChromelyRequest request) { List<MovieInfo> movieInfos = new List<MovieInfo>(); string assemblyName = typeof(MovieInfo).Assembly.GetName().Name; movieInfos.Add(new MovieInfo(id: 1, title: "The Shawshank Redemption", year: 1994, votes: 678790, rating: 9.2, assembly: assemblyName)); movieInfos.Add(new MovieInfo(id: 2, title: "The Godfather", year: 1972, votes: 511495, rating: 9.2, assembly: assemblyName)); movieInfos.Add(new MovieInfo(id: 3, title: "The Godfather: Part II", year: 1974, votes: 319352, rating: 9.0, assembly: assemblyName)); movieInfos.Add(new MovieInfo(id: 4, title: "The Good, the Bad and the Ugly", year: 1966, votes: 213030, rating: 8.9, assembly: assemblyName)); movieInfos.Add(new MovieInfo(id: 5, title: "My Fair Lady", year: 1964, votes: 533848, rating: 8.9, assembly: assemblyName)); movieInfos.Add(new MovieInfo(id: 6, title: "12 Angry Men", year: 1957, votes: 164558, rating: 8.9, assembly: assemblyName)); ChromelyResponse response = new ChromelyResponse(); response.Data = movieInfos; return response; } /// <summary> /// The save movies. /// </summary> /// <param name="request"> /// The request. /// </param> /// <returns> /// The <see cref="ChromelyResponse"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// ArgumentNullException - request is null exception. /// </exception> /// <exception cref="Exception"> /// Exception - post data is null exception. /// </exception> private ChromelyResponse SaveMovies(ChromelyRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (request.PostData == null) { throw new Exception("Post data is null or invalid."); } ChromelyResponse response = new ChromelyResponse(); var postDataJson = request.PostData.EnsureJson(); int rowsReceived = postDataJson.ArrayCount(); response.Data = $"{rowsReceived} rows of data successfully saved."; return response; } } /// <summary> /// The movie info. /// </summary> // ReSharper disable once StyleCop.SA1402 [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed. Suppression is OK here.")] [SuppressMessage("ReSharper", "StyleCop.SA1600")] public class MovieInfo { /// <summary> /// Initializes a new instance of the <see cref="MovieInfo"/> class. /// </summary> /// <param name="id"> /// The id. /// </param> /// <param name="title"> /// The title. /// </param> /// <param name="year"> /// The year. /// </param> /// <param name="votes"> /// The votes. /// </param> /// <param name="rating"> /// The rating. /// </param> /// <param name="assembly"> /// The assembly. /// </param> public MovieInfo(int id, string title, int year, int votes, double rating, string assembly) { this.Id = id; this.Title = title; this.Year = year; this.Votes = votes; this.Rating = rating; this.Date = DateTime.Now; this.RestfulAssembly = assembly; } public int Id { get; set; } public string Title { get; set; } public int Year { get; set; } public int Votes { get; set; } public double Rating { get; set; } public DateTime Date { get; set; } public string RestfulAssembly { get; set; } } }
35.371429
155
0.561995
[ "MIT", "BSD-3-Clause" ]
ScottKane/demo-projects
angular-react-vue/ChromelyReactCefGlue/Controllers/DemoController.cs
4,954
C#
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; namespace AuthorizationPolicies { public class RoomEntryAuthorizationHandler : AuthorizationHandler<BuildingEntryRequirement, Room> { IRoomAccess _repository; public RoomEntryAuthorizationHandler(IRoomAccess repository) { _repository = repository; } protected override Task HandleRequirementAsync( AuthorizationHandlerContext context, BuildingEntryRequirement requirement, Room room) { var badgeDetails = context.User.Claims.FirstOrDefault(c => c.Type == CustomClaims.BadgeId && c.Issuer == Issuer.Microsoft); if (badgeDetails != null) { if (_repository.CanEnter(requirement.Building, room.Number, badgeDetails.Value)) { context.Succeed(requirement); } } return Task.CompletedTask; } } }
28.611111
135
0.621359
[ "MIT" ]
AzureMentor/home
Security/ASP.NET Core 2.0/Demos/AuthorizationPolicies/RoomEntryAuthorizationHandler.cs
1,032
C#
using Terraria.ID; using Terraria.ModLoader; namespace Prism3.Items { public class RoughtenOre : ModItem { public override void SetStaticDefaults() { ItemID.Sets.SortingPriorityMaterials[item.type] = 58; } public override void SetDefaults() { item.useStyle = ItemUseStyleID.SwingThrow; item.useTurn = true; item.useAnimation = 15; item.useTime = 10; item.autoReuse = true; item.maxStack = 999; item.consumable = true; item.createTile = ModContent.TileType<Tiles.Roughten>(); item.width = 12; item.height = 12; item.value = 3000; } } }
21.964286
60
0.661789
[ "Apache-2.0" ]
PrismanticSummoner/PrismanticChaos
Items/RoughtenOre.cs
617
C#
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rekognition-2016-06-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Rekognition.Model { /// <summary> /// Container for the parameters to the CreateStreamProcessor operation. /// Creates an Amazon Rekognition stream processor that you can use to detect and recognize /// faces in a streaming video. /// /// /// <para> /// Amazon Rekognition Video is a consumer of live video from Amazon Kinesis Video Streams. /// Amazon Rekognition Video sends analysis results to Amazon Kinesis Data Streams. /// </para> /// /// <para> /// You provide as input a Kinesis video stream (<code>Input</code>) and a Kinesis data /// stream (<code>Output</code>) stream. You also specify the face recognition criteria /// in <code>Settings</code>. For example, the collection containing faces that you want /// to recognize. Use <code>Name</code> to assign an identifier for the stream processor. /// You use <code>Name</code> to manage the stream processor. For example, you can start /// processing the source video by calling <a>StartStreamProcessor</a> with the <code>Name</code> /// field. /// </para> /// /// <para> /// After you have finished analyzing a streaming video, use <a>StopStreamProcessor</a> /// to stop processing. You can delete the stream processor by calling <a>DeleteStreamProcessor</a>. /// </para> /// </summary> public partial class CreateStreamProcessorRequest : AmazonRekognitionRequest { private StreamProcessorInput _input; private string _name; private StreamProcessorOutput _output; private string _roleArn; private StreamProcessorSettings _settings; /// <summary> /// Gets and sets the property Input. /// <para> /// Kinesis video stream stream that provides the source streaming video. If you are using /// the AWS CLI, the parameter name is <code>StreamProcessorInput</code>. /// </para> /// </summary> [AWSProperty(Required=true)] public StreamProcessorInput Input { get { return this._input; } set { this._input = value; } } // Check to see if Input property is set internal bool IsSetInput() { return this._input != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// An identifier you assign to the stream processor. You can use <code>Name</code> to /// manage the stream processor. For example, you can get the current status of the stream /// processor by calling <a>DescribeStreamProcessor</a>. <code>Name</code> is idempotent. /// /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Output. /// <para> /// Kinesis data stream stream to which Amazon Rekognition Video puts the analysis results. /// If you are using the AWS CLI, the parameter name is <code>StreamProcessorOutput</code>. /// </para> /// </summary> [AWSProperty(Required=true)] public StreamProcessorOutput Output { get { return this._output; } set { this._output = value; } } // Check to see if Output property is set internal bool IsSetOutput() { return this._output != null; } /// <summary> /// Gets and sets the property RoleArn. /// <para> /// ARN of the IAM role that allows access to the stream processor. /// </para> /// </summary> [AWSProperty(Required=true)] public string RoleArn { get { return this._roleArn; } set { this._roleArn = value; } } // Check to see if RoleArn property is set internal bool IsSetRoleArn() { return this._roleArn != null; } /// <summary> /// Gets and sets the property Settings. /// <para> /// Face recognition input parameters to be used by the stream processor. Includes the /// collection to use for face recognition and the face attributes to detect. /// </para> /// </summary> [AWSProperty(Required=true)] public StreamProcessorSettings Settings { get { return this._settings; } set { this._settings = value; } } // Check to see if Settings property is set internal bool IsSetSettings() { return this._settings != null; } } }
34.844311
109
0.606462
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/Rekognition/Generated/Model/CreateStreamProcessorRequest.cs
5,819
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Runtime.CompilerServices; using static Unity.Mathematics.math; #pragma warning disable 0660, 0661 namespace Unity.Mathematics.FixedPoint { [System.Serializable] public partial struct fp2x2 : System.IEquatable<fp2x2>, IFormattable { public fp2 c0; public fp2 c1; /// <summary>fp2x2 identity transform.</summary> public static readonly fp2x2 identity = new fp2x2((fp)1, (fp)0, (fp)0, (fp)1); /// <summary>fp2x2 zero value.</summary> public static readonly fp2x2 zero; /// <summary>Constructs a fp2x2 matrix from two fp2 vectors.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public fp2x2(fp2 c0, fp2 c1) { this.c0 = c0; this.c1 = c1; } /// <summary>Constructs a fp2x2 matrix from 4 fp values given in row-major order.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public fp2x2(fp m00, fp m01, fp m10, fp m11) { this.c0 = new fp2(m00, m10); this.c1 = new fp2(m01, m11); } /// <summary>Constructs a fp2x2 matrix from a single fp value by assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public fp2x2(fp v) { this.c0 = v; this.c1 = v; } /// <summary>Constructs a fp2x2 matrix from a single int value by converting it to fp and assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public fp2x2(int v) { this.c0 = (fp2)v; this.c1 = (fp2)v; } /// <summary>Constructs a fp2x2 matrix from a int2x2 matrix by componentwise conversion.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public fp2x2(int2x2 v) { this.c0 = (fp2)v.c0; this.c1 = (fp2)v.c1; } /// <summary>Constructs a fp2x2 matrix from a single uint value by converting it to fp and assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public fp2x2(uint v) { this.c0 = (fp2)v; this.c1 = (fp2)v; } /// <summary>Constructs a fp2x2 matrix from a uint2x2 matrix by componentwise conversion.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public fp2x2(uint2x2 v) { this.c0 = (fp2)v.c0; this.c1 = (fp2)v.c1; } /// <summary>Implicitly converts a single fp value to a fp2x2 matrix by assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator fp2x2(fp v) { return new fp2x2(v); } /// <summary>Explicitly converts a single int value to a fp2x2 matrix by converting it to fp and assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator fp2x2(int v) { return new fp2x2(v); } /// <summary>Explicitly converts a int2x2 matrix to a fp2x2 matrix by componentwise conversion.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator fp2x2(int2x2 v) { return new fp2x2(v); } /// <summary>Explicitly converts a single uint value to a fp2x2 matrix by converting it to fp and assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator fp2x2(uint v) { return new fp2x2(v); } /// <summary>Explicitly converts a uint2x2 matrix to a fp2x2 matrix by componentwise conversion.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator fp2x2(uint2x2 v) { return new fp2x2(v); } /// <summary>Returns the result of a componentwise multiplication operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator * (fp2x2 lhs, fp2x2 rhs) { return new fp2x2 (lhs.c0 * rhs.c0, lhs.c1 * rhs.c1); } /// <summary>Returns the result of a componentwise multiplication operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator * (fp2x2 lhs, fp rhs) { return new fp2x2 (lhs.c0 * rhs, lhs.c1 * rhs); } /// <summary>Returns the result of a componentwise multiplication operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator * (fp lhs, fp2x2 rhs) { return new fp2x2 (lhs * rhs.c0, lhs * rhs.c1); } /// <summary>Returns the result of a componentwise addition operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator + (fp2x2 lhs, fp2x2 rhs) { return new fp2x2 (lhs.c0 + rhs.c0, lhs.c1 + rhs.c1); } /// <summary>Returns the result of a componentwise addition operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator + (fp2x2 lhs, fp rhs) { return new fp2x2 (lhs.c0 + rhs, lhs.c1 + rhs); } /// <summary>Returns the result of a componentwise addition operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator + (fp lhs, fp2x2 rhs) { return new fp2x2 (lhs + rhs.c0, lhs + rhs.c1); } /// <summary>Returns the result of a componentwise subtraction operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator - (fp2x2 lhs, fp2x2 rhs) { return new fp2x2 (lhs.c0 - rhs.c0, lhs.c1 - rhs.c1); } /// <summary>Returns the result of a componentwise subtraction operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator - (fp2x2 lhs, fp rhs) { return new fp2x2 (lhs.c0 - rhs, lhs.c1 - rhs); } /// <summary>Returns the result of a componentwise subtraction operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator - (fp lhs, fp2x2 rhs) { return new fp2x2 (lhs - rhs.c0, lhs - rhs.c1); } /// <summary>Returns the result of a componentwise division operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator / (fp2x2 lhs, fp2x2 rhs) { return new fp2x2 (lhs.c0 / rhs.c0, lhs.c1 / rhs.c1); } /// <summary>Returns the result of a componentwise division operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator / (fp2x2 lhs, fp rhs) { return new fp2x2 (lhs.c0 / rhs, lhs.c1 / rhs); } /// <summary>Returns the result of a componentwise division operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator / (fp lhs, fp2x2 rhs) { return new fp2x2 (lhs / rhs.c0, lhs / rhs.c1); } /// <summary>Returns the result of a componentwise modulus operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator % (fp2x2 lhs, fp2x2 rhs) { return new fp2x2 (lhs.c0 % rhs.c0, lhs.c1 % rhs.c1); } /// <summary>Returns the result of a componentwise modulus operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator % (fp2x2 lhs, fp rhs) { return new fp2x2 (lhs.c0 % rhs, lhs.c1 % rhs); } /// <summary>Returns the result of a componentwise modulus operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator % (fp lhs, fp2x2 rhs) { return new fp2x2 (lhs % rhs.c0, lhs % rhs.c1); } /// <summary>Returns the result of a componentwise increment operation on a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator ++ (fp2x2 val) { return new fp2x2 (++val.c0, ++val.c1); } /// <summary>Returns the result of a componentwise decrement operation on a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator -- (fp2x2 val) { return new fp2x2 (--val.c0, --val.c1); } /// <summary>Returns the result of a componentwise less than operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator < (fp2x2 lhs, fp2x2 rhs) { return new bool2x2 (lhs.c0 < rhs.c0, lhs.c1 < rhs.c1); } /// <summary>Returns the result of a componentwise less than operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator < (fp2x2 lhs, fp rhs) { return new bool2x2 (lhs.c0 < rhs, lhs.c1 < rhs); } /// <summary>Returns the result of a componentwise less than operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator < (fp lhs, fp2x2 rhs) { return new bool2x2 (lhs < rhs.c0, lhs < rhs.c1); } /// <summary>Returns the result of a componentwise less or equal operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator <= (fp2x2 lhs, fp2x2 rhs) { return new bool2x2 (lhs.c0 <= rhs.c0, lhs.c1 <= rhs.c1); } /// <summary>Returns the result of a componentwise less or equal operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator <= (fp2x2 lhs, fp rhs) { return new bool2x2 (lhs.c0 <= rhs, lhs.c1 <= rhs); } /// <summary>Returns the result of a componentwise less or equal operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator <= (fp lhs, fp2x2 rhs) { return new bool2x2 (lhs <= rhs.c0, lhs <= rhs.c1); } /// <summary>Returns the result of a componentwise greater than operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator > (fp2x2 lhs, fp2x2 rhs) { return new bool2x2 (lhs.c0 > rhs.c0, lhs.c1 > rhs.c1); } /// <summary>Returns the result of a componentwise greater than operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator > (fp2x2 lhs, fp rhs) { return new bool2x2 (lhs.c0 > rhs, lhs.c1 > rhs); } /// <summary>Returns the result of a componentwise greater than operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator > (fp lhs, fp2x2 rhs) { return new bool2x2 (lhs > rhs.c0, lhs > rhs.c1); } /// <summary>Returns the result of a componentwise greater or equal operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator >= (fp2x2 lhs, fp2x2 rhs) { return new bool2x2 (lhs.c0 >= rhs.c0, lhs.c1 >= rhs.c1); } /// <summary>Returns the result of a componentwise greater or equal operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator >= (fp2x2 lhs, fp rhs) { return new bool2x2 (lhs.c0 >= rhs, lhs.c1 >= rhs); } /// <summary>Returns the result of a componentwise greater or equal operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator >= (fp lhs, fp2x2 rhs) { return new bool2x2 (lhs >= rhs.c0, lhs >= rhs.c1); } /// <summary>Returns the result of a componentwise unary minus operation on a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator - (fp2x2 val) { return new fp2x2 (-val.c0, -val.c1); } /// <summary>Returns the result of a componentwise unary plus operation on a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 operator + (fp2x2 val) { return new fp2x2 (+val.c0, +val.c1); } /// <summary>Returns the result of a componentwise equality operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator == (fp2x2 lhs, fp2x2 rhs) { return new bool2x2 (lhs.c0 == rhs.c0, lhs.c1 == rhs.c1); } /// <summary>Returns the result of a componentwise equality operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator == (fp2x2 lhs, fp rhs) { return new bool2x2 (lhs.c0 == rhs, lhs.c1 == rhs); } /// <summary>Returns the result of a componentwise equality operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator == (fp lhs, fp2x2 rhs) { return new bool2x2 (lhs == rhs.c0, lhs == rhs.c1); } /// <summary>Returns the result of a componentwise not equal operation on two fp2x2 matrices.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator != (fp2x2 lhs, fp2x2 rhs) { return new bool2x2 (lhs.c0 != rhs.c0, lhs.c1 != rhs.c1); } /// <summary>Returns the result of a componentwise not equal operation on a fp2x2 matrix and a fp value.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator != (fp2x2 lhs, fp rhs) { return new bool2x2 (lhs.c0 != rhs, lhs.c1 != rhs); } /// <summary>Returns the result of a componentwise not equal operation on a fp value and a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2x2 operator != (fp lhs, fp2x2 rhs) { return new bool2x2 (lhs != rhs.c0, lhs != rhs.c1); } /// <summary>Returns the fp2 element at a specified index.</summary> unsafe public ref fp2 this[int index] { get { #if ENABLE_UNITY_COLLECTIONS_CHECKS if ((uint)index >= 2) throw new System.ArgumentException("index must be between[0...1]"); #endif fixed (fp2x2* array = &this) { return ref ((fp2*)array)[index]; } } } /// <summary>Returns true if the fp2x2 is equal to a given fp2x2, false otherwise.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(fp2x2 rhs) { return c0.Equals(rhs.c0) && c1.Equals(rhs.c1); } /// <summary>Returns true if the fp2x2 is equal to a given fp2x2, false otherwise.</summary> public override bool Equals(object o) { return Equals((fp2x2)o); } /// <summary>Returns a hash code for the fp2x2.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return (int)fpmath.hash(this); } /// <summary>Returns a string representation of the fp2x2.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override string ToString() { return string.Format("fp2x2({0}, {1}, {2}, {3})", c0.x, c1.x, c0.y, c1.y); } /// <summary>Returns a string representation of the fp2x2 using a specified format and culture-specific format information.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ToString(string format, IFormatProvider formatProvider) { return string.Format("fp2x2({0}, {1}, {2}, {3})", c0.x.ToString(format, formatProvider), c1.x.ToString(format, formatProvider), c0.y.ToString(format, formatProvider), c1.y.ToString(format, formatProvider)); } } public static partial class fpmath { /// <summary>Returns a fp2x2 matrix constructed from two fp2 vectors.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 fp2x2(fp2 c0, fp2 c1) { return new fp2x2(c0, c1); } /// <summary>Returns a fp2x2 matrix constructed from from 4 fp values given in row-major order.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 fp2x2(fp m00, fp m01, fp m10, fp m11) { return new fp2x2(m00, m01, m10, m11); } /// <summary>Returns a fp2x2 matrix constructed from a single fp value by assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 fp2x2(fp v) { return new fp2x2(v); } /// <summary>Returns a fp2x2 matrix constructed from a single int value by converting it to fp and assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 fp2x2(int v) { return new fp2x2(v); } /// <summary>Return a fp2x2 matrix constructed from a int2x2 matrix by componentwise conversion.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 fp2x2(int2x2 v) { return new fp2x2(v); } /// <summary>Returns a fp2x2 matrix constructed from a single uint value by converting it to fp and assigning it to every component.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 fp2x2(uint v) { return new fp2x2(v); } /// <summary>Return a fp2x2 matrix constructed from a uint2x2 matrix by componentwise conversion.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 fp2x2(uint2x2 v) { return new fp2x2(v); } /// <summary>Return the fp2x2 transpose of a fp2x2 matrix.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static fp2x2 transpose(fp2x2 v) { return fp2x2( v.c0.x, v.c0.y, v.c1.x, v.c1.y); } /// <summary>Returns a uint hash code of a fp2x2 vector.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint hash(fp2x2 v) { return math.csum(fpmath.asuint(v.c0) * uint2(0x90A285BBu, 0x5D19E1D5u) + fpmath.asuint(v.c1) * uint2(0xFAAF07DDu, 0x625C45BDu)) + 0xC9F27FCBu; } /// <summary> /// Returns a uint2 vector hash code of a fp2x2 vector. /// When multiple elements are to be hashes together, it can more efficient to calculate and combine wide hash /// that are only reduced to a narrow uint hash at the very end instead of at every step. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint2 hashwide(fp2x2 v) { return (fpmath.asuint(v.c0) * uint2(0x6D2523B1u, 0x6E2BF6A9u) + fpmath.asuint(v.c1) * uint2(0xCC74B3B7u, 0x83B58237u)) + 0x833E3E29u; } } }
53.434211
219
0.659493
[ "MIT" ]
MagicLizi/Unity.Mathematics.FixedPoint
Unity.Mathematics.FixedPoint/fp2x2.gen.cs
20,305
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MobileCan.Models { using System; using System.Collections.Generic; public partial class Review { public int Id { get; set; } public Nullable<int> ProductId { get; set; } public string UserName { get; set; } public string Review1 { get; set; } public virtual Product Product { get; set; } } }
31.84
85
0.512563
[ "MIT" ]
robaElshazly/MobileCan
MobileCan/Models/Review.cs
796
C#
using System; using System.Text.RegularExpressions; namespace RingtoneComposer.Core.Converter { public abstract class TuneConverter : IConverter<Tune> { protected readonly DurationConverter DurationConverter; protected readonly ScaleConverter ScaleConverter; protected readonly PitchConverter PitchConverter; protected const string Dot = "."; public abstract string PartitionValidatorPattern { get; } public abstract string TuneElementPattern { get; } public abstract string TuneElementDelimiter { get; } public abstract string Pause { get; } public abstract int DefaultBpm { get; } protected TuneConverter() { DurationConverter = new DurationConverter(); ScaleConverter = new ScaleConverter(); PitchConverter = new PitchConverter(); } public bool CheckPartition(string s) { var regex = new Regex(PartitionValidatorPattern); return regex.IsMatch(s); } public string ToString(Tune t) { if (t == null) throw new ArgumentNullException("t"); return InternalToString(t); } protected abstract string InternalToString(Tune t); public Tune Parse(string s) { if (s == null) throw new ArgumentNullException("s"); if (string.IsNullOrWhiteSpace(s)) throw new ArgumentException("s is empty"); return InternalParse(s); } protected abstract Tune InternalParse(string s); } }
28.77193
65
0.611585
[ "MIT" ]
skacofonix/RingtoneComposer
RingtoneComposer.Core/Business/Converter/TuneConverter.cs
1,642
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Newtonsoft.Json.Serialization; namespace Microsoft.AspNetCore.SignalR.Tests { public class MethodHub : TestHub { public Task GroupRemoveMethod(string groupName) { return Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName); } public Task ClientSendMethod(string userId, string message) { return Clients.User(userId).SendAsync("Send", message); } public Task SendToMultipleUsers(IReadOnlyList<string> userIds, string message) { return Clients.Users(userIds).SendAsync("Send", message); } public Task ConnectionSendMethod(string connectionId, string message) { return Clients.Client(connectionId).SendAsync("Send", message); } public Task SendToMultipleClients(string message, IReadOnlyList<string> connectionIds) { return Clients.Clients(connectionIds).SendAsync("Send", message); } public Task GroupAddMethod(string groupName) { return Groups.AddToGroupAsync(Context.ConnectionId, groupName); } public Task GroupSendMethod(string groupName, string message) { return Clients.Group(groupName).SendAsync("Send", message); } public Task GroupExceptSendMethod(string groupName, string message, IReadOnlyList<string> excludedConnectionIds) { return Clients.GroupExcept(groupName, excludedConnectionIds).SendAsync("Send", message); } public Task SendToMultipleGroups(string message, IReadOnlyList<string> groupNames) { return Clients.Groups(groupNames).SendAsync("Send", message); } public Task SendToOthersInGroup(string groupName, string message) { return Clients.OthersInGroup(groupName).SendAsync("Send", message); } public Task BroadcastMethod(string message) { return Clients.All.SendAsync("Broadcast", message); } public Task BroadcastItem() { return Clients.All.SendAsync("Broadcast", new Result { Message = "test", paramName = "param" }); } public Task SendArray() { return Clients.All.SendAsync("Array", new[] { 1, 2, 3 }); } public Task<int> TaskValueMethod() { return Task.FromResult(42); } public int ValueMethod() { return 43; } public ValueTask ValueTaskMethod() { return new ValueTask(Task.CompletedTask); } public ValueTask<int> ValueTaskValueMethod() { return new ValueTask<int>(43); } [HubMethodName("RenamedMethod")] public int ATestMethodThatIsRenamedByTheAttribute() { return 43; } public string Echo(string data) { return data; } public void VoidMethod() { } public string ConcatString(byte b, int i, char c, string s) { return $"{b}, {i}, {c}, {s}"; } public Task SendAnonymousObject() { return Clients.Client(Context.ConnectionId).SendAsync("Send", new { }); } public override Task OnDisconnectedAsync(Exception e) { return Task.CompletedTask; } public void MethodThatThrows() { throw new InvalidOperationException("BOOM!"); } public void ThrowHubException() { throw new HubException("This is a hub exception"); } public Task MethodThatYieldsFailedTask() { return Task.FromException(new InvalidOperationException("BOOM!")); } public static void StaticMethod() { } [Authorize("test")] public void AuthMethod() { } [Authorize("test")] public void MultiParamAuthMethod(string s1, string s2) { } public Task SendToAllExcept(string message, IReadOnlyList<string> excludedConnectionIds) { return Clients.AllExcept(excludedConnectionIds).SendAsync("Send", message); } public bool HasHttpContext() { return Context.GetHttpContext() != null; } public Task SendToOthers(string message) { return Clients.Others.SendAsync("Send", message); } public Task SendToCaller(string message) { return Clients.Caller.SendAsync("Send", message); } public Task ProtocolError() { return Clients.Caller.SendAsync("Send", new SelfRef()); } public void InvalidArgument(CancellationToken token) { } public async Task<string> StreamingConcat(ChannelReader<string> source) { var sb = new StringBuilder(); while (await source.WaitToReadAsync()) { while (source.TryRead(out var item)) { sb.Append(item); } } return sb.ToString(); } public async Task StreamDontRead(ChannelReader<string> source) { while (await source.WaitToReadAsync()) { } } public async Task<int> StreamingSum(ChannelReader<int> source) { var total = 0; while (await source.WaitToReadAsync()) { while (source.TryRead(out var item)) { total += item; } } return total; } public async Task<List<object>> UploadArray(ChannelReader<object> source) { var results = new List<object>(); while (await source.WaitToReadAsync()) { while (source.TryRead(out var item)) { results.Add(item); } } return results; } [Authorize("test")] public async Task<List<object>> UploadArrayAuth(ChannelReader<object> source) { var results = new List<object>(); while (await source.WaitToReadAsync()) { while (source.TryRead(out var item)) { results.Add(item); } } return results; } public async Task<string> TestTypeCastingErrors(ChannelReader<int> source) { try { await source.WaitToReadAsync(); } catch (Exception) { return "error identified and caught"; } return "wrong type accepted, this is bad"; } public async Task<bool> TestCustomErrorPassing(ChannelReader<int> source) { try { await source.WaitToReadAsync(); } catch (Exception ex) { return ex.Message == HubConnectionHandlerTests.CustomErrorMessage; } return false; } public Task UploadIgnoreItems(ChannelReader<string> source) { // Wait for an item to appear first then return from the hub method to end the invocation return source.WaitToReadAsync().AsTask(); } public ChannelReader<string> StreamAndUploadIgnoreItems(ChannelReader<string> source) { var channel = Channel.CreateUnbounded<string>(); _ = ChannelFunc(channel.Writer, source); return channel.Reader; async Task ChannelFunc(ChannelWriter<string> output, ChannelReader<string> input) { // Wait for an item to appear first then return from the hub method to end the invocation await input.WaitToReadAsync(); output.Complete(); } } public async Task UploadDoesWorkOnComplete(ChannelReader<string> source) { var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); Context.Items[nameof(UploadDoesWorkOnComplete)] = tcs.Task; try { while (await source.WaitToReadAsync()) { while (source.TryRead(out var item)) { } } } catch (Exception ex) { tcs.SetException(ex); } finally { tcs.TrySetResult(42); } } public async Task BlockingMethod() { var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); Context.ConnectionAborted.Register(state => ((TaskCompletionSource<object>)state).SetResult(null), tcs); await tcs.Task; } } internal class SelfRef { public SelfRef() { Self = this; } public SelfRef Self { get; set; } } public abstract class TestHub : Hub { public override Task OnConnectedAsync() { var tcs = (TaskCompletionSource<bool>)Context.Items["ConnectedTask"]; tcs?.TrySetResult(true); return base.OnConnectedAsync(); } } public class DynamicTestHub : DynamicHub { public override Task OnConnectedAsync() { var tcs = (TaskCompletionSource<bool>)Context.Items["ConnectedTask"]; tcs?.TrySetResult(true); return base.OnConnectedAsync(); } public string Echo(string data) { return data; } public Task ClientSendMethod(string userId, string message) { return Clients.User(userId).Send(message); } public Task SendToMultipleUsers(List<string> userIds, string message) { return Clients.Users(userIds).Send(message); } public Task ConnectionSendMethod(string connectionId, string message) { return Clients.Client(connectionId).Send(message); } public Task SendToMultipleClients(string message, IReadOnlyList<string> connectionIds) { return Clients.Clients(connectionIds).Send(message); } public Task GroupAddMethod(string groupName) { return Groups.AddToGroupAsync(Context.ConnectionId, groupName); } public Task GroupSendMethod(string groupName, string message) { return Clients.Group(groupName).Send(message); } public Task GroupExceptSendMethod(string groupName, string message, IReadOnlyList<string> excludedConnectionIds) { return Clients.GroupExcept(groupName, excludedConnectionIds).Send(message); } public Task SendToOthersInGroup(string groupName, string message) { return Clients.OthersInGroup(groupName).Send(message); } public Task SendToMultipleGroups(string message, IReadOnlyList<string> groupNames) { return Clients.Groups(groupNames).Send(message); } public Task BroadcastMethod(string message) { return Clients.All.Broadcast(message); } public Task SendToAllExcept(string message, IReadOnlyList<string> excludedConnectionIds) { return Clients.AllExcept(excludedConnectionIds).Send(message); } public Task SendToOthers(string message) { return Clients.Others.Send(message); } public Task SendToCaller(string message) { return Clients.Caller.Send(message); } } public class HubT : Hub<Test> { public override Task OnConnectedAsync() { var tcs = (TaskCompletionSource<bool>)Context.Items["ConnectedTask"]; tcs?.TrySetResult(true); return base.OnConnectedAsync(); } public string Echo(string data) { return data; } public Task ClientSendMethod(string userId, string message) { return Clients.User(userId).Send(message); } public Task SendToMultipleUsers(List<string> userIds, string message) { return Clients.Users(userIds).Send(message); } public Task ConnectionSendMethod(string connectionId, string message) { return Clients.Client(connectionId).Send(message); } public Task SendToMultipleClients(string message, IReadOnlyList<string> connectionIds) { return Clients.Clients(connectionIds).Send(message); } public async Task DelayedSend(string connectionId, string message) { await Task.Delay(100); await Clients.Client(connectionId).Send(message); } public Task GroupAddMethod(string groupName) { return Groups.AddToGroupAsync(Context.ConnectionId, groupName); } public Task GroupSendMethod(string groupName, string message) { return Clients.Group(groupName).Send(message); } public Task GroupExceptSendMethod(string groupName, string message, IReadOnlyList<string> excludedConnectionIds) { return Clients.GroupExcept(groupName, excludedConnectionIds).Send(message); } public Task SendToMultipleGroups(string message, IReadOnlyList<string> groupNames) { return Clients.Groups(groupNames).Send(message); } public Task SendToOthersInGroup(string groupName, string message) { return Clients.OthersInGroup(groupName).Send(message); } public Task BroadcastMethod(string message) { return Clients.All.Broadcast(message); } public Task SendToAllExcept(string message, IReadOnlyList<string> excludedConnectionIds) { return Clients.AllExcept(excludedConnectionIds).Send(message); } public Task SendToOthers(string message) { return Clients.Others.Send(message); } public Task SendToCaller(string message) { return Clients.Caller.Send(message); } } public interface Test { Task Send(string message); Task Broadcast(string message); } public class OnConnectedThrowsHub : Hub { public override Task OnConnectedAsync() { var tcs = new TaskCompletionSource(); tcs.SetException(new InvalidOperationException("Hub OnConnected failed.")); return tcs.Task; } } public class OnDisconnectedThrowsHub : TestHub { public override Task OnDisconnectedAsync(Exception exception) { var tcs = new TaskCompletionSource(); tcs.SetException(new InvalidOperationException("Hub OnDisconnected failed.")); return tcs.Task; } } public class InheritedHub : BaseHub { public override int VirtualMethod(int num) { return num - 10; } public override int VirtualMethodRenamed() { return 34; } } public class BaseHub : TestHub { public string BaseMethod(string message) { return message; } public virtual int VirtualMethod(int num) { return num; } [HubMethodName("RenamedVirtualMethod")] public virtual int VirtualMethodRenamed() { return 43; } } public class InvalidHub : TestHub { public void OverloadedMethod(int num) { } public void OverloadedMethod(string message) { } } public class GenericMethodHub : Hub { public void GenericMethod<T>() { } } public class DisposeTrackingHub : TestHub { private readonly TrackDispose _trackDispose; public DisposeTrackingHub(TrackDispose trackDispose) { _trackDispose = trackDispose; } protected override void Dispose(bool dispose) { if (dispose) { _trackDispose.DisposeCount++; } } } public class HubWithAsyncDisposable : TestHub { private AsyncDisposable _disposable; public HubWithAsyncDisposable(AsyncDisposable disposable) { _disposable = disposable; } public void Test() { } } public class AbortHub : Hub { public void Kill() { Context.Abort(); } } public class StreamingHub : TestHub { public ChannelReader<string> CounterChannel(int count) { var channel = Channel.CreateUnbounded<string>(); _ = Task.Run(async () => { for (int i = 0; i < count; i++) { await channel.Writer.WriteAsync(i.ToString()); } channel.Writer.Complete(); }); return channel.Reader; } public async Task<ChannelReader<string>> CounterChannelAsync(int count) { await Task.Yield(); return CounterChannel(count); } public async ValueTask<ChannelReader<string>> CounterChannelValueTaskAsync(int count) { await Task.Yield(); return CounterChannel(count); } public async IAsyncEnumerable<string> CounterAsyncEnumerable(int count) { for (int i = 0; i < count; i++) { await Task.Yield(); yield return i.ToString(); } } public async Task<IAsyncEnumerable<string>> CounterAsyncEnumerableAsync(int count) { await Task.Yield(); return CounterAsyncEnumerable(count); } public AsyncEnumerableImpl<string> CounterAsyncEnumerableImpl(int count) { return new AsyncEnumerableImpl<string>(CounterAsyncEnumerable(count)); } public AsyncEnumerableImplChannelThrows<string> AsyncEnumerableIsPreferredOverChannelReader(int count) { return new AsyncEnumerableImplChannelThrows<string>(CounterChannel(count)); } public ChannelReader<string> BlockingStream() { return Channel.CreateUnbounded<string>().Reader; } public ChannelReader<int> ExceptionStream() { var channel = Channel.CreateUnbounded<int>(); channel.Writer.TryComplete(new Exception("Exception from channel")); return channel.Reader; } public ChannelReader<int> ThrowStream() { throw new Exception("Throw from hub method"); } public ChannelReader<int> NullStream() { return null; } public int NonStream() { return 42; } public ChannelReader<string> StreamEcho(ChannelReader<string> source) { Channel<string> output = Channel.CreateUnbounded<string>(); _ = Task.Run(async () => { while (await source.WaitToReadAsync()) { while (source.TryRead(out string item)) { await output.Writer.WriteAsync("echo:" + item); } } output.Writer.TryComplete(); }); return output.Reader; } public async IAsyncEnumerable<string> DerivedParameterInterfaceAsyncEnumerable(IDerivedParameterTestObject param) { await Task.Yield(); yield return param.Value; } public async IAsyncEnumerable<string> DerivedParameterBaseClassAsyncEnumerable(DerivedParameterTestObjectBase param) { await Task.Yield(); yield return param.Value; } public async IAsyncEnumerable<string> DerivedParameterInterfaceAsyncEnumerableWithCancellation(IDerivedParameterTestObject param, [EnumeratorCancellation] CancellationToken token) { await Task.Yield(); yield return param.Value; } public async IAsyncEnumerable<string> DerivedParameterBaseClassAsyncEnumerableWithCancellation(DerivedParameterTestObjectBase param, [EnumeratorCancellation] CancellationToken token) { await Task.Yield(); yield return param.Value; } public class AsyncEnumerableImpl<T> : IAsyncEnumerable<T> { private readonly IAsyncEnumerable<T> _inner; public AsyncEnumerableImpl(IAsyncEnumerable<T> inner) { _inner = inner; } public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return _inner.GetAsyncEnumerator(cancellationToken); } } public class AsyncEnumerableImplChannelThrows<T> : ChannelReader<T>, IAsyncEnumerable<T> { private ChannelReader<T> _inner; public AsyncEnumerableImplChannelThrows(ChannelReader<T> inner) { _inner = inner; } public override bool TryRead(out T item) { // Not implemented to verify this is consumed as an IAsyncEnumerable<T> instead of a ChannelReader<T>. throw new NotImplementedException(); } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default) { // Not implemented to verify this is consumed as an IAsyncEnumerable<T> instead of a ChannelReader<T>. throw new NotImplementedException(); } public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return new ChannelAsyncEnumerator(_inner, cancellationToken); } // Copied from AsyncEnumeratorAdapters private class ChannelAsyncEnumerator : IAsyncEnumerator<T> { /// <summary>The channel being enumerated.</summary> private readonly ChannelReader<T> _channel; /// <summary>Cancellation token used to cancel the enumeration.</summary> private readonly CancellationToken _cancellationToken; /// <summary>The current element of the enumeration.</summary> private T _current; public ChannelAsyncEnumerator(ChannelReader<T> channel, CancellationToken cancellationToken) { _channel = channel; _cancellationToken = cancellationToken; } public T Current => _current; public ValueTask<bool> MoveNextAsync() { var result = _channel.ReadAsync(_cancellationToken); if (result.IsCompletedSuccessfully) { _current = result.Result; return new ValueTask<bool>(true); } return new ValueTask<bool>(MoveNextAsyncAwaited(result)); } private async Task<bool> MoveNextAsyncAwaited(ValueTask<T> channelReadTask) { try { _current = await channelReadTask; } catch (ChannelClosedException ex) when (ex.InnerException == null) { return false; } return true; } public ValueTask DisposeAsync() { return default; } } } public interface IDerivedParameterTestObject { public string Value { get; set; } } public abstract class DerivedParameterTestObjectBase : IDerivedParameterTestObject { public string Value { get; set; } } public class DerivedParameterTestObject : DerivedParameterTestObjectBase { } public class DerivedParameterKnownTypesBinder : ISerializationBinder { private static readonly IEnumerable<Type> _knownTypes = new List<Type>() { typeof(DerivedParameterTestObject) }; public static ISerializationBinder Instance { get; } = new DerivedParameterKnownTypesBinder(); public void BindToName(Type serializedType, out string assemblyName, out string typeName) { assemblyName = null; typeName = serializedType.Name; } public Type BindToType(string assemblyName, string typeName) => _knownTypes.Single(type => type.Name == typeName); } } public class SimpleHub : Hub { public override async Task OnConnectedAsync() { await Clients.All.SendAsync("Send", $"{Context.ConnectionId} joined"); await base.OnConnectedAsync(); } } public class SimpleVoidReturningTypedHub : Hub<IVoidReturningTypedHubClient> { public override Task OnConnectedAsync() { // Derefernce Clients, to force initialization of the TypedHubClient Clients.All.Send("herp"); return Task.CompletedTask; } } public class SimpleTypedHub : Hub<ITypedHubClient> { public override async Task OnConnectedAsync() { await Clients.All.Send($"{Context.ConnectionId} joined"); await base.OnConnectedAsync(); } } public class LongRunningHub : Hub { private TcsService _tcsService; public LongRunningHub(TcsService tcsService) { _tcsService = tcsService; } public async Task<int> LongRunningMethod() { _tcsService.StartedMethod.TrySetResult(null); await _tcsService.EndMethod.Task; return 12; } public async Task<ChannelReader<string>> LongRunningStream() { _tcsService.StartedMethod.TrySetResult(null); await _tcsService.EndMethod.Task; // Never ending stream return Channel.CreateUnbounded<string>().Reader; } public ChannelReader<int> CancelableStreamSingleParameter(CancellationToken token) { var channel = Channel.CreateBounded<int>(10); Task.Run(async () => { _tcsService.StartedMethod.SetResult(null); await token.WaitForCancellationAsync(); channel.Writer.TryComplete(); _tcsService.EndMethod.SetResult(null); }); return channel.Reader; } public ChannelReader<int> CancelableStreamMultiParameter(int ignore, int ignore2, CancellationToken token) { var channel = Channel.CreateBounded<int>(10); Task.Run(async () => { _tcsService.StartedMethod.SetResult(null); await token.WaitForCancellationAsync(); channel.Writer.TryComplete(); _tcsService.EndMethod.SetResult(null); }); return channel.Reader; } public ChannelReader<int> CancelableStreamNullableParameter(int x, string y, CancellationToken token) { var channel = Channel.CreateBounded<int>(10); Task.Run(async () => { _tcsService.StartedMethod.SetResult(x); await token.WaitForCancellationAsync(); channel.Writer.TryComplete(); _tcsService.EndMethod.SetResult(y); }); return channel.Reader; } public ChannelReader<int> StreamNullableParameter(int x, int? input) { var channel = Channel.CreateBounded<int>(10); Task.Run(() => { _tcsService.StartedMethod.SetResult(x); channel.Writer.TryComplete(); _tcsService.EndMethod.SetResult(input); return Task.CompletedTask; }); return channel.Reader; } public ChannelReader<int> CancelableStreamMiddleParameter(int ignore, CancellationToken token, int ignore2) { var channel = Channel.CreateBounded<int>(10); Task.Run(async () => { _tcsService.StartedMethod.SetResult(null); await token.WaitForCancellationAsync(); channel.Writer.TryComplete(); _tcsService.EndMethod.SetResult(null); }); return channel.Reader; } public async IAsyncEnumerable<int> CancelableStreamGeneratedAsyncEnumerable([EnumeratorCancellation] CancellationToken token) { _tcsService.StartedMethod.SetResult(null); await token.WaitForCancellationAsync(); _tcsService.EndMethod.SetResult(null); yield break; } public IAsyncEnumerable<int> CancelableStreamCustomAsyncEnumerable() { return new CustomAsyncEnumerable(_tcsService); } public int SimpleMethod() { return 21; } public async Task Upload(ChannelReader<string> stream) { _tcsService.StartedMethod.SetResult(null); _ = await stream.ReadAndCollectAllAsync(); _tcsService.EndMethod.SetResult(null); } private class CustomAsyncEnumerable : IAsyncEnumerable<int> { private readonly TcsService _tcsService; public CustomAsyncEnumerable(TcsService tcsService) { _tcsService = tcsService; } public IAsyncEnumerator<int> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return new CustomAsyncEnumerator(_tcsService, cancellationToken); } private class CustomAsyncEnumerator : IAsyncEnumerator<int> { private readonly TcsService _tcsService; private readonly CancellationToken _cancellationToken; public CustomAsyncEnumerator(TcsService tcsService, CancellationToken cancellationToken) { _tcsService = tcsService; _cancellationToken = cancellationToken; } public int Current => throw new NotImplementedException(); public ValueTask DisposeAsync() { return default; } public async ValueTask<bool> MoveNextAsync() { _tcsService.StartedMethod.SetResult(null); await _cancellationToken.WaitForCancellationAsync(); _tcsService.EndMethod.SetResult(null); return false; } } } } public class TcsService { public TaskCompletionSource<object> StartedMethod; public TaskCompletionSource<object> EndMethod; public TcsService() { Reset(); } public void Reset() { StartedMethod = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); EndMethod = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); } } public interface ITypedHubClient { Task Send(string message); } public interface IVoidReturningTypedHubClient { void Send(string message); } public class ErrorInAbortedTokenHub : Hub { public override Task OnConnectedAsync() { Context.Items[nameof(OnConnectedAsync)] = true; Context.ConnectionAborted.Register(() => { throw new InvalidOperationException("BOOM"); }); return base.OnConnectedAsync(); } public override Task OnDisconnectedAsync(Exception exception) { Context.Items[nameof(OnDisconnectedAsync)] = true; return base.OnDisconnectedAsync(exception); } } public class ConnectionLifetimeHub : Hub { private readonly ConnectionLifetimeState _state; public ConnectionLifetimeHub(ConnectionLifetimeState state) { _state = state; } public override Task OnConnectedAsync() { _state.TokenStateInConnected = Context.ConnectionAborted.IsCancellationRequested; Context.ConnectionAborted.Register(() => { _state.TokenCallbackTriggered = true; }); return base.OnConnectedAsync(); } public Task ProtocolErrorSelf() { return Clients.Caller.SendAsync("Send", new SelfRef()); } public Task ProtocolErrorAll() { return Clients.All.SendAsync("Send", new SelfRef()); } public override Task OnDisconnectedAsync(Exception exception) { _state.TokenStateInDisconnected = Context.ConnectionAborted.IsCancellationRequested; _state.DisconnectedException = exception; return base.OnDisconnectedAsync(exception); } } public class ConnectionLifetimeState { public bool TokenCallbackTriggered { get; set; } public bool TokenStateInConnected { get; set; } public bool TokenStateInDisconnected { get; set; } public Exception DisconnectedException { get; set; } } public class CallerServiceHub : Hub { private readonly CallerService _service; public CallerServiceHub(CallerService service) { _service = service; } public override Task OnConnectedAsync() { _service.SetCaller(Clients.Caller); var tcs = (TaskCompletionSource<bool>)Context.Items["ConnectedTask"]; tcs?.TrySetResult(true); return base.OnConnectedAsync(); } } public class CallerService { public IClientProxy Caller { get; private set; } public void SetCaller(IClientProxy caller) { Caller = caller; } } }
29.336894
190
0.569392
[ "Apache-2.0" ]
4samitim/aspnetcore
src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/Hubs.cs
35,703
C#
#region Apache License /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion namespace Apache.Commons.Cli { using System; /// <summary> /// Thrown when an option requiring an argument is not provided with an argument. /// </summary> [Serializable] public class MissingArgumentException : ParseException { /// <summary> /// The option requiring additional arguments /// </summary> public Option MissingArgumentOption { get; init; } /// <summary> /// Construct a new <code>MissingArgumentException</code> with the specified detail message. /// </summary> /// <param name="message">The message that describes the error.</param> public MissingArgumentException(string message) : base(message) { } /// <summary> /// Construct a new <code>MissingArgumentException</code> with the specified detail message. /// </summary> /// <param name="option">The option requiring an argument.</param> /// <since>1.2</since> public MissingArgumentException(Option option) : base("Missing argument for option: " + option.GetKey()) { this.MissingArgumentOption = option; } } }
35.210526
100
0.675635
[ "Apache-2.0" ]
EverythingDotNet/Apache-Commons-CLI
Apache.Commons.Cli/Exceptions/MissingArgumentException.cs
2,007
C#
using System; using Newtonsoft.Json.Linq; namespace OrchardCore.OpenId.YesSql.Models { /// <summary> /// Represents an OpenId token. /// </summary> public class OpenIdToken { /// <summary> /// Gets or sets the unique identifier associated with the current token. /// </summary> public string TokenId { get; set; } /// <summary> /// Gets or sets the identifier of the application associated with the current token. /// </summary> public string ApplicationId { get; set; } /// <summary> /// Gets or sets the identifier of the authorization associated with the current token. /// </summary> public string AuthorizationId { get; set; } /// <summary> /// Gets or sets the creation date of the current token. /// </summary> public DateTimeOffset? CreationDate { get; set; } /// <summary> /// Gets or sets the expiration date of the current token. /// </summary> public DateTimeOffset? ExpirationDate { get; set; } /// <summary> /// Gets or sets the physical identifier associated with the current token. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the payload of the current token, if applicable. /// Note: this property is only used for reference tokens /// and may be encrypted for security reasons. /// </summary> public string Payload { get; set; } /// <summary> /// Gets or sets the additional properties associated with the current token. /// </summary> public JObject Properties { get; set; } /// <summary> /// Gets or sets the redemption date of the current token. /// </summary> public DateTimeOffset? RedemptionDate { get; set; } /// <summary> /// Gets or sets the reference identifier associated /// with the current token, if applicable. /// Note: this property is only used for reference tokens /// and may be hashed or encrypted for security reasons. /// </summary> public string ReferenceId { get; set; } /// <summary> /// Gets or sets the status of the current token. /// </summary> public string Status { get; set; } /// <summary> /// Gets or sets the subject associated with the current token. /// </summary> public string Subject { get; set; } /// <summary> /// Gets or sets the type of the current token. /// </summary> public string Type { get; set; } } }
32.853659
95
0.573868
[ "BSD-3-Clause" ]
ArieGato/OrchardCore
src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdToken.cs
2,694
C#
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Angular { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; /// <summary> /// Program class. /// </summary> public class Program { /// <summary> /// Entry point of the application. /// </summary> /// <param name="args">Method arguments.</param> public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } /// <summary> /// Method to create a host to run the application. /// </summary> /// <param name="args">Method arguments.</param> /// <returns>Builder object.</returns> public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) // Configure logging .ConfigureLogging((hostingContext, loggingBuilder) => { // Pass logging configuration from appsettings.json loggingBuilder.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); if (hostingContext.HostingEnvironment.IsDevelopment()) { // In case of development environment, adds console and debug logging loggingBuilder.AddConsole(); loggingBuilder.AddDebug(); loggingBuilder.AddProvider(new LoggerProvider(hostingContext.Configuration)); } else { // In case of production environment, adds custom logging which uses SQL Server Database loggingBuilder.AddProvider(new LoggerProvider(hostingContext.Configuration)); } }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
37.66129
112
0.520343
[ "MIT" ]
aatishagarwal55/dotnetrepo
Angular/Program.cs
2,335
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.Extensions.DependencyInjection; using Wilson.Accounting.Data; using Wilson.Companies.Core.Entities; using Wilson.Projects.Data; using Wilson.Scheduler.Data; using Wilson.Web.Events.Interfaces; namespace Wilson.Web.Events.Handlers { public class EmployeeCreatedHandler : Handler { public EmployeeCreatedHandler(IServiceProvider serviceProvider) : base(serviceProvider) { } public async override Task Handle(IDomainEvent args) { var eventArgs = args as EmployeeCreated; if (eventArgs == null) { throw new InvalidCastException(); } var accountingDbContext = this.ServiceProvider.GetService<AccountingDbContext>(); var projectDbContext = this.ServiceProvider.GetService<ProjectsDbContext>(); var schedulerDbContext = this.ServiceProvider.GetService<SchedulerDbContext>(); var payRate = schedulerDbContext.PayRates.FirstOrDefault(); Mapper.Initialize(cfg => { cfg.CreateMap<Employee, Accounting.Core.Entities.Employee>() .ForMember(x => x.Paycheks, opt => opt.Ignore()) .ForMember(x => x.Company, opt => opt.Ignore()) .ForSourceMember(x => x.Company, opt => opt.Ignore()) .ForSourceMember(x => x.InfoRequests, opt => opt.Ignore()); cfg.CreateMap<Employee, Projects.Core.Entities.Employee>() .ForMember(x => x.Projects, opt => opt.Ignore()) .ForSourceMember(x => x.Company, opt => opt.Ignore()) .ForSourceMember(x => x.InfoRequests, opt => opt.Ignore()); cfg.CreateMap<Employee, Scheduler.Core.Entities.Employee>() .ForMember(x => x.Schedules, opt => opt.Ignore()) .ForMember(x => x.Paychecks, opt => opt.Ignore()) .ForMember(x => x.PayRate, opt => opt.Ignore()) .ForSourceMember(x => x.Company, opt => opt.Ignore()) .ForSourceMember(x => x.InfoRequests, opt => opt.Ignore()); }); if (eventArgs.Employees != null) { var accountingEmployees = Mapper.Map<IEnumerable<Employee>, IEnumerable<Accounting.Core.Entities.Employee>>(eventArgs.Employees); var projectsEmployees = Mapper.Map<IEnumerable<Employee>, IEnumerable<Projects.Core.Entities.Employee>>(eventArgs.Employees); var schedulerEmployees = Mapper.Map<IEnumerable<Employee>, IEnumerable<Scheduler.Core.Entities.Employee>>(eventArgs.Employees); foreach (var employee in schedulerEmployees) { employee.ApplayPayRate(payRate); } await accountingDbContext.Set<Accounting.Core.Entities.Employee>().AddRangeAsync(accountingEmployees); await projectDbContext.Set<Projects.Core.Entities.Employee>().AddRangeAsync(projectsEmployees); await schedulerDbContext.Set<Scheduler.Core.Entities.Employee>().AddRangeAsync(schedulerEmployees); } if (eventArgs.Employee != null) { var accountingEmployee = Mapper.Map<Employee, Accounting.Core.Entities.Employee>(eventArgs.Employee); var projectsEmployee = Mapper.Map<Employee, Projects.Core.Entities.Employee>(eventArgs.Employee); var schedulerEmployee = Mapper.Map<Employee, Scheduler.Core.Entities.Employee>(eventArgs.Employee); schedulerEmployee.ApplayPayRate(payRate); await accountingDbContext.Set<Accounting.Core.Entities.Employee>().AddAsync(accountingEmployee); await projectDbContext.Set<Projects.Core.Entities.Employee>().AddAsync(projectsEmployee); await schedulerDbContext.Set<Scheduler.Core.Entities.Employee>().AddAsync(schedulerEmployee); } await accountingDbContext.SaveChangesAsync(); await projectDbContext.SaveChangesAsync(); await schedulerDbContext.SaveChangesAsync(); } } }
48.438202
145
0.628856
[ "BSD-2-Clause" ]
AsimKhan2019/ERP-Construction
Web/Wilson.Web/Events/Handlers/EmployeeCreatedHandler.cs
4,313
C#
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion namespace Google.Protobuf.Reflection { /// <summary> /// Interface implemented by all descriptor types. /// </summary> public interface IDescriptor { /// <summary> /// Returns the name of the entity (message, field etc) being described. /// </summary> string Name { get; } /// <summary> /// Returns the fully-qualified name of the entity being described. /// </summary> string FullName { get; } /// <summary> /// Returns the descriptor for the .proto file that this entity is part of. /// </summary> FileDescriptor File { get; } } }
41.754386
87
0.709244
[ "Apache-2.0" ]
skyknight233/ProtobufGUIForUnity3d
Assets/Google.Protobuf/Reflection/IDescriptor.cs
2,380
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.EntityFrameworkCore.Specification.Tests.TestUtilities.Xunit { [Flags] public enum TestPlatform { None = 0, Windows = 1 << 0, Linux = 1 << 1, Mac = 1 << 2 } }
24.058824
111
0.647922
[ "Apache-2.0" ]
Mattlk13/EntityFramework
src/Microsoft.EntityFrameworkCore.Specification.Tests/TestUtilities/Xunit/TestPlatform.cs
409
C#
using System; class BinaryShort { static void Main() { Console.Write("Enter a number in interval [{0}; {1}]: ", short.MinValue, short.MaxValue); short number = short.Parse(Console.ReadLine()); Console.WriteLine("{0} to binary = {1}", number, ToBinary(number)); } static string ToBinary(int number) { string binNumber = ""; for (int i = 15; i >= 0; i--) { binNumber = ((number % 2) & 1) + binNumber; number >>= 1; } return binNumber; } }
24
97
0.523551
[ "MIT" ]
EmilMitev/Telerik-Academy
CSharp - part 2/4.NumeralSystems/08.BinaryShort/BinaryShort.cs
554
C#
using Newtonsoft.Json; using System.Collections.Generic; namespace BookShop.DataProcessor.ExportDto { public class AuthorExportDTO { [JsonProperty("AuthorName")] public string AuthorName { get; set; } [JsonProperty("Books")] public AuthorExportBookDTO[] Books { get; set; } } }
21.666667
56
0.664615
[ "MIT" ]
Paulina-Dyulgerska/EF_Core_CSharp_Lectures_Exercises
Exam_Preparation_1/BookShop/DataProcessor/ExportDto/AuthorExportDTO.cs
327
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CompanySales.MVC { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
25.291667
100
0.566722
[ "Apache-2.0" ]
imwyw/.net
Src/CompanySalesDemo/CompanySales.MVC/App_Start/RouteConfig.cs
609
C#
using EddiDataDefinitions; using EddiEvents; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EddiShipMonitor { public class ShipPurchasedEvent : Event { public const string NAME = "Ship purchased"; public const string DESCRIPTION = "Triggered when you purchase a ship"; public const string SAMPLE = "{ \"timestamp\":\"2016-09-20T18:14:26Z\", \"event\":\"ShipyardBuy\", \"ShipType\":\"federation_corvette\", \"ShipPrice\":18796945, \"SellOldShip\":\"CobraMkIII\", \"SellShipID\":42, \"SellPrice\":950787 }"; public static Dictionary<string, string> VARIABLES = new Dictionary<string, string>(); static ShipPurchasedEvent() { VARIABLES.Add("ship", "The ship that was purchased"); VARIABLES.Add("price", "The price of the ship that was purchased"); VARIABLES.Add("soldship", "The ship that was sold as part of the purchase"); VARIABLES.Add("soldshipid", "The ID of the ship that was sold as part of the purchase"); VARIABLES.Add("soldprice", "The credits obtained by selling the ship"); VARIABLES.Add("storedship", "The ship that was stored as part of the purchase"); VARIABLES.Add("storedid", "The ID of the ship that was stored as part of the purchase"); } [JsonProperty("ship")] public string ship { get; private set; } [JsonProperty("price")] public long price { get; private set; } [JsonProperty("soldship")] public string soldship { get; private set; } [JsonProperty("soldshipid")] public int? soldshipid { get; private set; } [JsonProperty("soldprice")] public long? soldprice { get; private set; } [JsonProperty("storedship")] public string storedship { get; private set; } [JsonProperty("storedshipid")] public int? storedshipid { get; private set; } public ShipPurchasedEvent(DateTime timestamp, string ship, long price, string soldShip, int? soldShipId, long? soldPrice, string storedShip, int? storedShipId) : base(timestamp, NAME) { this.ship = ship; this.price = price; this.soldship = soldShip; this.soldshipid = soldShipId; this.soldprice = soldPrice; this.storedship = storedShip; this.storedshipid = storedShipId; } } }
40
244
0.635317
[ "Apache-2.0" ]
cmdrmcdonald/EliteDangerousDataProvider
ShipMonitor/ShipPurchasedEvent.cs
2,522
C#
namespace NewPlatform.Flexberry.ServiceBus.Components { using System; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using ClientTools; /// <summary> /// Base implementation of component for providing access by WCF. /// </summary> internal sealed class WcfService : BaseServiceBusComponent, IWcfService { /// <summary> /// The subscriptions manager. /// </summary> private readonly ISubscriptionsManager _subscriptionsManager; /// <summary> /// The sending manager. /// </summary> private readonly ISendingManager _sendingManager; /// <summary> /// The receiving manager. /// </summary> private readonly IReceivingManager _receivingManager; /// <summary> /// Statistics service. /// </summary> private readonly IStatisticsService _statisticsService; private readonly ILogger _logger; /// <summary> /// The WCF service host. /// </summary> private ServiceHost _wcfServiceHost; /// <summary> /// Load WCF settings from .NET configuration file ("app.config" / "web.config"). /// Enabled by default. /// </summary> public bool UseWcfSettingsFromConfig { get; set; } = true; /// <summary> /// Address of WCF service. /// </summary> /// <remarks> /// Used only when <see cref="UseWcfSettingsFromConfig"/> is <c>false</c>. Cannot be <c>null</c> in that case. /// </remarks> public Uri Address { get; set; } /// <summary> /// Binding of WCF service. /// </summary> /// <remarks> /// Used only when <see cref="UseWcfSettingsFromConfig"/> is <c>false</c>. Cannot be <c>null</c> in that case. /// </remarks> public Binding Binding { get; set; } /// <summary> /// Publish WSDL. /// </summary> /// <remarks> /// Used only when <see cref="UseWcfSettingsFromConfig"/> is <c>false</c>. /// </remarks> public bool PublishWSDL { get; set; } = false; /// <summary> /// Initializes a new instance of the <see cref="WcfService"/> class. /// </summary> /// <param name="subscriptionsManager">The subscriptions manager.</param> /// <param name="sendingManager">The sending manager.</param> /// <param name="receivingManager">The receiving manager.</param> /// <param name="logger">The logger.</param> public WcfService(ISubscriptionsManager subscriptionsManager, ISendingManager sendingManager, IReceivingManager receivingManager, ILogger logger, IStatisticsService statisticsService) { if (subscriptionsManager == null) throw new ArgumentNullException(nameof(subscriptionsManager)); if (sendingManager == null) throw new ArgumentNullException(nameof(sendingManager)); if (statisticsService == null) throw new ArgumentNullException(nameof(statisticsService)); if (receivingManager == null) throw new ArgumentNullException(nameof(receivingManager)); if (logger == null) throw new ArgumentNullException(nameof(logger)); _subscriptionsManager = subscriptionsManager; _sendingManager = sendingManager; _receivingManager = receivingManager; _logger = logger; _statisticsService = statisticsService; } /// <summary> /// Starts this component. /// Starts WCF service if it is enabled. /// </summary> public override void Start() { var service = new SBService(_subscriptionsManager, _sendingManager, _receivingManager, _statisticsService); if (UseWcfSettingsFromConfig) { _logger.LogDebugMessage(nameof(WcfService), "Creating WCF host using configuration"); _wcfServiceHost = new ServiceHost(service); } else { _logger.LogDebugMessage(nameof(WcfService), "Creating WCF host using specified binding and address"); _wcfServiceHost = new ServiceHostWithoutConfiguration(service); _wcfServiceHost.AddServiceEndpoint(typeof(IServiceBusService), Binding, Address); _wcfServiceHost.AddServiceEndpoint(typeof(IServiceBusInterop), Binding, Address); _wcfServiceHost.AddServiceEndpoint(typeof(ICallbackSubscriber), Binding, Address); if (PublishWSDL) { _wcfServiceHost.Description.Behaviors.Remove<ServiceMetadataBehavior>(); _wcfServiceHost.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetUrl = Address, HttpGetEnabled = true, }); } } _logger.LogDebugMessage(nameof(WcfService), "Opening WCF host"); _wcfServiceHost.Open(); _logger.LogDebugMessage(nameof(WcfService), "WCF host opened"); base.Start(); } /// <summary> /// Stops this component. /// Stops WCF service if it is enabled. /// </summary> public override void Stop() { if (_wcfServiceHost != null) { _logger.LogDebugMessage(nameof(WcfService), "Stopping WCF host"); _wcfServiceHost.Abort(); _wcfServiceHost = null; } base.Stop(); } /// <summary> /// Special implementation of <see cref="ServiceHost"/> without data from configuration file. /// Used for configuring host from code for testing purposes of for flexible configuring Flexberry Service Bus. /// </summary> private class ServiceHostWithoutConfiguration : ServiceHost { /// <summary> /// Initializes new instance of <see cref="ServiceHostWithoutConfiguration"/> class /// with specified service instance. /// </summary> /// <param name="service">The WCF service instance for hosting.</param> public ServiceHostWithoutConfiguration(SBService service) : base(service) { } /// <summary> /// Overload implementation of loading configuration. /// Does nothing. /// </summary> protected override void ApplyConfiguration() { } } } }
35.920635
191
0.578141
[ "MIT" ]
BatNiy/NewPlatform.Flexberry.ServiceBus
NewPlatform.Flexberry.ServiceBus/Components/WcfService/WcfService.cs
6,791
C#
// // AssemblyInfo.cs // // Author: // Marek Habersack <grendel@twistedcode.net> // // Copyright (c) 2011 Novell, Inc (http://novell.com/) // // 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.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; [assembly: AssemblyProduct ("ASP.Net WebPages")] [assembly: AssemblyCompany ("Novell, Inc")] [assembly: AssemblyCopyright ("© Novell, Inc. All rights reserved.")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyTrademark ("")] [assembly: NeutralResourcesLanguage ("en-US")] [assembly: CLSCompliant (true)] [assembly: ComVisible (false)] [assembly: AssemblyFileVersion ("1.0.20105.407")] [assembly: AssemblyVersion ("1.0.0.0")] [assembly: TargetFramework (".NETFramework,Version=v4.0", FrameworkDisplayName=".NET Framework 4")] [assembly: AllowPartiallyTrustedCallers] [assembly: CompilationRelaxations (8)] [assembly: AssemblyTitle ("Microsoft.Web.Infrastructure")] [assembly: AssemblyDescription ("")] [assembly: AssemblyDelaySign (true)] [assembly: AssemblyKeyFile("../winfx.pub")]
42.377358
99
0.759127
[ "Apache-2.0" ]
121468615/mono
mcs/class/Microsoft.Web.Infrastructure/Assembly/AssemblyInfo.cs
2,249
C#
// (c) Copyright HutongGames, LLC 2010-2016. All rights reserved. #if (UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0) #define UNITY_PRE_5_1 #endif //#define DEV_MODE using UnityEngine; using System.Collections.Generic; using System.IO; using UnityEditor; namespace HutongGames.PlayMakerEditor { public class PreUpdateChecker : EditorWindow { // Categories used to report results private readonly string[] checkCategories = { "Mecanim Animator Add-on", "Physics2D Add-on", "Trigonometry Actions", "Vector2 Actions", "Quaternion Actions" }; // Where official actions are installed private readonly string[] officialPaths = { "PlayMaker/Actions/Animator", "PlayMaker/Actions/Physics2D", "PlayMaker/Actions/Trigonometry", "PlayMaker/Actions/Vector2", "PlayMaker/Actions/Quaternion" }; // Files to check for in each category private readonly string[] checkFiles = { "AnimatorCrossFade.cs,AnimatorInterruptMatchTarget.cs,AnimatorMatchTarget.cs,AnimatorPlay.cs,AnimatorStartPlayback.cs,AnimatorStartRecording.cs,AnimatorStopPlayback.cs,AnimatorStopRecording.cs,GetAnimatorApplyRootMotion.cs,GetAnimatorBody.cs,GetAnimatorBoneGameObject.cs,GetAnimatorBool.cs,GetAnimatorCullingMode.cs,GetAnimatorCurrentStateInfo.cs,GetAnimatorCurrentStateInfoIsName.cs,GetAnimatorCurrentStateInfoIsTag.cs,GetAnimatorCurrentTransitionInfo.cs,GetAnimatorCurrentTransitionInfoIsName.cs,GetAnimatorCurrentTransitionInfoIsUserName.cs,GetAnimatorDelta.cs,GetAnimatorFeetPivotActive.cs,GetAnimatorFloat.cs,GetAnimatorGravityWeight.cs,GetAnimatorHumanScale.cs,GetAnimatorIKGoal.cs,GetAnimatorInt.cs,GetAnimatorIsHuman.cs,GetAnimatorIsLayerInTransition.cs,GetAnimatorIsMatchingTarget.cs,GetAnimatorIsParameterControlledByCurve.cs,GetAnimatorLayerCount.cs,GetAnimatorLayerName.cs,GetAnimatorLayersAffectMassCenter.cs,GetAnimatorLayerWeight.cs,GetAnimatorLeftFootBottomHeight.cs,GetAnimatorNextStateInfo.cs,GetAnimatorPivot.cs,GetAnimatorPlayBackSpeed.cs,GetAnimatorPlaybackTime.cs,GetAnimatorRightFootBottomHeight.cs,GetAnimatorRoot.cs,GetAnimatorSpeed.cs,GetAnimatorTarget.cs,NavMeshAgentAnimatorSynchronizer.cs,SetAnimatorApplyRootMotion.cs,SetAnimatorBody.cs,SetAnimatorBool.cs,SetAnimatorCullingMode.cs,SetAnimatorFeetPivotActive.cs,SetAnimatorFloat.cs,SetAnimatorIKGoal.cs,SetAnimatorInt.cs,SetAnimatorLayersAffectMassCenter.cs,SetAnimatorLayerWeight.cs,SetAnimatorLookAt.cs,SetAnimatorPlayBackSpeed.cs,SetAnimatorPlaybackTime.cs,SetAnimatorSpeed.cs,SetAnimatorStabilizeFeet.cs,SetAnimatorTarget.cs,SetAnimatorTrigger.cs,AnimatorFrameUpdateSelector.cs,GetAnimatorAnimatorRootActionEditor.cs,GetAnimatorBoneGameObjectActionEditor.cs,GetAnimatorBoolActionEditor.cs,GetAnimatorCurrentStateInfoActionEditor.cs,GetAnimatorCurrentStateInfoIsNameActionEditor.cs,GetAnimatorCurrentStateInfoIsTagActionEditor.cs,GetAnimatorCurrentTransitionInfoActionEditor.cs,GetAnimatorCurrentTransitionInfoIsNameActionEditor.cs,GetAnimatorCurrentTransitionInfoIsUserNameActionEditor.cs,GetAnimatorDeltaActionEditor.cs,GetAnimatorFloatActionEditor.cs,GetAnimatorGravityWeightActionEditor.cs,GetAnimatorIKGoalActionEditor.cs,GetAnimatorIntActionEditor.cs,GetAnimatorIsLayerInTransitionActionEditor.cs,GetAnimatorIsMatchingTargetActionEditor.cs,GetAnimatorLayerWeightActionEditor.cs,GetAnimatorNextStateInfoActionEditor.cs,GetAnimatorPivotActionEditor.cs,GetAnimatorSpeedActionEditor.cs,GetAnimatorTargetActionEditor.cs,SetAnimatorBoolActionEditor.cs,SetAnimatorFloatActionEditor.cs,SetAnimatorIntActionEditor.cs,OnAnimatorUpdateActionEditorBase.cs" ,"SetCollider2dIsTrigger.cs,AddForce2d.cs,AddTorque2d.cs,Collision2dEvent.cs,GetCollision2dInfo.cs,GetMass2d.cs,GetNextLineCast2d.cs,GetNextOverlapArea2d.cs,GetNextOverlapCircle2d.cs,GetNextOverlapPoint2d.cs,GetNextRayCast2d.cs,GetRayCastHit2dInfo.cs,GetSpeed2d.cs,GetTrigger2dInfo.cs,GetVelocity2d.cs,IsFixedAngle2d.cs,IsKinematic2d.cs,IsSleeping2d.cs,LineCast2d.cs,LookAt2d.cs,LookAt2dGameObject.cs,MousePick2d.cs,MousePick2dEvent.cs,RayCast2d.cs,ScreenPick2d.cs,SetGravity2d.cs,SetGravity2dScale.cs,SetHingeJoint2dProperties.cs,SetIsFixedAngle2d.cs,SetIsKinematic2d.cs,SetMass2d.cs,SetVelocity2d.cs,SetWheelJoint2dProperties.cs,Sleep2d.cs,SmoothLookAt2d.cs,Touch Object 2d Event.cs,Trigger2dEvent.cs,WakeAllRigidBodies2d.cs,WakeUp2d.cs" ,"GetACosine.cs,GetASine.cs,GetAtan.cs,GetAtan2.cs,GetAtan2FromVector2.cs,GetAtan2FromVector3.cs,GetCosine.cs,GetSine.cs,GetTan.cs" ,"DebugVector2.cs,GetVector2Length.cs,GetVector2XY.cs,SelectRandomVector2.cs,SetVector2Value.cs,SetVector2XY.cs,Vector2Add.cs,Vector2AddXY.cs,Vector2ClampMagnitude.cs,Vector2HighPassFilter.cs,Vector2Interpolate.cs,Vector2Invert.cs,Vector2Lerp.cs,Vector2LowPassFilter.cs,Vector2MoveTowards.cs,Vector2Multiply.cs,Vector2Normalize.cs,Vector2Operator.cs,Vector2PerSecond.cs,Vector2RotateTowards.cs,Vector2Substract.cs" ,"QuaternionCompare.cs,GetQuaternionEulerAngles.cs,GetQuaternionFromRotation.cs,GetQuaternionMultipliedByQuaternion.cs,GetQuaternionMultipliedByVector.cs,QuaternionAngleAxis.cs,QuaternionBaseAction.cs,QuaternionEuler.cs,QuaternionInverse.cs,QuaternionLerp.cs,QuaternionLookRotation.cs,QuaternionLowPassFilter.cs,QuaternionRotateTowards.cs,QuaternionSlerp.cs,GetQuaternionEulerAnglesCustomEditor.cs,GetQuaternionFromRotationCustomEditor.cs,GetQuaternionMultipliedByQuaternionCustomEditor.cs,GetQuaternionMultipliedByVectorCustomEditor.cs,QuaternionAngleAxisCustomEditor.cs,QuaternionCustomEditorBase.cs,QuaternionEulerCustomEditor.cs,QuaternionInverseCustomEditor.cs,QuaternionLerpCustomEditor.cs,QuaternionLookRotationCustomEditor.cs,QuaternionLowPassFilterCustomEditor.cs,QuaternionRotateTowardsCustomEditor.cs,QuaternionSlerpCustomEditor.cs" }; /* TODO use these // official GUIDs for each file (generated by LogOfficialGUIDs) private readonly string[] fileGUIDs = { "c3264db07da4c49ffb5fe199371b98bb,18376cdddd26341f7b809912db503610,03cf67d8b733d4b37952890811925998,b66532287fa3a4997ae5dcfb967ff46c,57b6a2622136741beb45f95f75cf1433,a042efdd5fb4944abb7edadab645941a,ba34314c2df504f919e13699c71aafaf,199b0066830504bb88c7de83af154bda,7fa0f84fa8d7d48309bb7731893655b9,c22054fd1dd374c9a9c987d5cc6221f7,7666d8beb51fe44558679a70236fe940,6167f16993b5f498fbaa142e60ac1b8b,ca51ebe2658064289907fa675fcd5b5e,581a9005f2e8f49fb991e3b721ecc35a,3b6569490c2174e38b25f4763b428a89,07687adfe28594b449945d9abc9c3c29,0fe9a3bd420ec47b2bc6bdae6cdaa4ab,c30469b50b14848858f52b7fe7107982,df0ac08a28fbe4862874b2aaa02851ab,59828d3af79b24d328e2f0dfa5b4a3a7,e13fdcd155d24432ea5ddb9a289ddaef,7de2cc8e8be55430bb4b2c9a08001b9b,e3c384ee62d14458d8c070bbd88b0232,3e4e2701c656149199f7b424b0725b7d,3c5d635656f584a028aeaaa9cea3e773,b1565390c702f46aaa5cf4fa60f9e509,10472a7cdeeae4ec1b7a0a2958ad14ca,e5040ac0bba964af88c58865c193d634,1bdecd480242c4aca8287c38279d2fef,cb08474726d4c46db9951e90042f7e9a,acf2623f6aced45c9b16e208719d85cb,cdbcdbe70991c4b9f979da57c134c086,855199c246a444b1f9e5869cfd91d3c8,b217fe31f1ae848f9914c4fdbfbfdd01,9330353483e924d69b2fa7703fa61ca7,b38c867aa06344cb1a93127e55fd5dff,9f881f5e879b242e9bc5b7f5da438aec,252f9f13fe96d4f5b8ee1a309ee2e5db,7d22254eb077f4acba9bf302e62ef769,d19d957c781f6493fbbaed91c968c8ec,f6a5f9d7ea5f64549b2fc34b6b0cd5c7,cfa38da0ff4864b20be3fb1ec58d58bc,dc36092a0e28842d4bd974422ff9b206,e7921319b56514e1594bc135e632c4ea,533022f83905747cb8e71215824cadd4,0f372e08801dc40c890e1599595eaad9,84fa9e58ece094db8afb9d4f089d064a,b9d6946d83b0341ad8d4da88ed1f94f2,7e73917538b3a4e038a4970124142a06,8c086636265c24eb685a7a38abf3f843,331b242ab74d74798b8018c088452631,dd4e8c6c3305a4c848416eaf9f6dfbff,7f5b24930e6a94b16adf1f4b1f1d968d,1da53ccd0ab244a78be13e014adc7604,337fd0519278b4a4abfa114d7da5f03c,12ce8d3e805754f859045452539301b1,d08de24228e9d48f6966aef92918c88a,f883c091fa768400c9c82bbedff68386,5ca00c3f794764e0884a2e7e8bcb99fb,2d24ab33144b5435fbc2d271727badf4,e6766ded0ae1f47bdbb920e2e0a11be4,18313b45aff604fdfae21005cba51867,c01181456b38a445a9d46b1adb204fef,7016201662a0f43ef90cdc27ef28d2f3,c319a624316ec43e58ce312e218643d7,f46514705a56a44b18a3aaefe044562a,cb96adea5998a47ad856307f387542b2,20ecab07b14f24a31ad6aa95afe7b5f8,b88f6ceb1c984410fbd5b41563b9d2a1,a6ad0469f3b65455585bd6a67ace5231,b82f868d8d79e4446963165d7b7fe368,ca44151bd6a0241aa9306e42e12e4412,f2a733af2f8c941318e512d00865682f,97c1adb99041345a2b706883a0aa29f2,747e6c1106178455a98bb07727307e54,a3ce5496c052a4d51a21cd2d7a6b4ff6,dc486d0004d9c4ff0b33b013672e2819,b7b668bf47f0d4026a9a939be6dc69ec,1f0565b694e32469c9c06d051c31a156,f4d701619cd324b4f909bff1810e1aad,da454073bf02d49d48a28cb6ce4c0fc1,ad0e5154a3a6c46edafdfbec49bbb27d,e6467d12fbec648acbfe19a0ba022a0c,6927c99ea76df47c2b10e89e8b1e3f6a,d509be4bb6b01482f8d036452d23b539,3346f4d545f7340a4936b72e2e4c528d,ac8ba452b0457403caa4c60b0713a991,", "ea55526fdaa943b4bba87169f67a12f7,eaf0f3ed6b5d242d9af3ee4525911244,b6dd6adf8d6ac4bb6ad3d0021c9b8aa0,3fe37d4f2887249fbacdb30745b10d5f,63a94df6a55a542188e33a6ea28a9bde,dbc5681b28fff4b5782c9d86facecc4a,a70b105d5eff843e49ed438d206f1c1c,c018c087b7b4a4ef3a62da064be8c749,53e4c920ba9794755b18dd5cca83846b,a5fdbda89cf314991b58ea3e6b4eee19,58c2549eaa2174377a282d8c32fc1a35,b2e6f1fa5f4be42e58970f5beda35efc,75c2e65656a6142e19b0a37ad0ed8611,4720828ffbc044f9aad6b1b164bc38eb,c6c7f18245c1945cd87f8f62e48df25f,13aca478d9cc64a5998d7c7f459f5016,3326f7bf3c61f489ba5b2a7a817bd9bd,9ad0f181793d744abbfb5f25ef0cf183,a70b105d5eff843e49ed438d206f1c1c,d4400294ba87f4057a2bc118f8ec8ca2,15bd8590a698546aab33e8cd4ec9006b,da62defbd3fe34f0d979fbf900a1a9ba,19bec85c3f4fe43bd9365e5ee05b1cb8,58c2549eaa2174377a282d8c32fc1a35,b5c41daa984094cecbcfd973cad60d26,2e993b15a1ec247ca83fa651a184812a,8813d3367d00848619fb51a65822460b,0f35a67104d8a4d4aa91cf73117249f9,163a4c6c323834651b53b6165c36392e,203a12a4280db43fb9cb2650b4c470dd,6b165ecceb37e450e82a58ba6bd21853,58252178b9646486b9dda57c812ce9e1,369d94b9cb1275c41a665a7f3171689d,0660988017b964055a4f2c8f4ea48a2c,d6a02eab34e764d49930524cabac32c6,a6627f26893aa4ef2a2e9b51d93efbda,195f05ad3f0fd4ccb9fa0e9e2607aefe,3173d61ebbbc544d3964fd6488da8c4d,0599ede9318874bb8806f153794ea3db,", "6fda114c8a66e4296aed4e2a26a0611b,a8937798f5f704e5fa51b286a972dbe2,688a06197f3c54d278275cf084d6768e,2bf63cc97e56e4dcc8d616ebe3a04768,689ca023c18264a8eb07e17d24e4d3de,ed68244e96b0a47d7a0f089398480ef7,8ca5ca87ca84c4a94a2112392a257755,8e28a11b97806405eac27c765a5e86cd,858ac03f63eae483e95d68159febdf6b,", "a3dc9b6acbb9b463c894f6c5ee606989,a82ba85a9bb434407a8665e3affe57f8,60c8dd0dc3fd745a5841ca1d02a74726,285043e5e312a42df9ca1edcaa9c7c47,67463002770f84436ab893f31706f1ef,a42688746f7b64ebab25853041141133,e024d98d40a79474a954ede4f742f8b8,5755e237ef15847b1b87b8857345d126,78f25a93b238b4689a94fc24a8a3a596,eea0562bc1a9a4c11a0f5ad88c520337,4fd6cc0501d42495ca65aca36d58c666,955756b52dd7b425dbaaf0a3ab82d5ef,dde1f65f330694b05892a2430c3f0617,928126332a67546beb573aeaa2151c81,9d8d5cde65adb4dc7bf3f1f966af402a,e21c897c65f2b43da815643505c5445b,8a628084b2b4f4d19a367cedaa12154e,5c24d9da34967454482cc211b5f63d3a,c6a98fe858b7744a99c35a29a9fbc937,6174d235c04e64c728c5ea669181ef44,a3f7aef663ddf402a8e4843206f8368b,", "109faef134f274d3c8f0073c027ec212,04df43e98caae47479af52af6f7382aa,1a4862db90df44585aea2b190369fecb,4b09c7437bf4b46f7a7b0a2e0784df2b,b934f16194b9842e29683059db082a5a,e7b252bc184b64a9daacfb682ba75c3f,1ec09b8a624db4d78b78fa83e6ba57b2,1dfae9aec90344b698eb3a1bb52c7e7a,d981ac06313624fb3a1002f6e2b6af5f,c8fb9a75de503405bafbc360167a41f3,1ad91f05541104be0b4db97046df4dff,43aeb9060224147eda2dede205adf166,2eb0ae435013f4b73a5eade1acd952c7,4f3507d7651cd4beab8dfd4bf8a35aa8,3be6a1c071c024b41ba9f6177d1fe2c0,389626e75a012491dafdc591f89663ec,a15bb934be2514486aaba8aab6bad343,253be90cf8caf4bc2bd90962a721c804,e5cf62fd8a18e40bf98c7088582e1118,f90ab0e4f75b040fb805a1dfa7e4e070,9cfe22725f30c4b0795eab8d9abad7cf,273e324b1102f47538c3229d5d630b8f,f03cae33101aa45ffa317a40a938c8ab,648f82c14055f4d71936cfb3c0306ee5,b3c7d1bd8c46a45e387e06ee5ecedba7,6059b292f53004a1ab91e6f1bacc9df0,fc3d3cdb1536b4608b848887535f5b8e,", };*/ private readonly List<string> allFilesInProject = new List<string>(); private readonly List<string> allFilenames = new List<string>(); private readonly List<string> failedCategories = new List<string>(); private bool logCheckFindingToggle; private Vector2 scrollPosition; [MenuItem("PlayMaker/Tools/Pre-Update Check", false, 66)] public static void Open() { GetWindow<PreUpdateChecker>(true); } private void OnEnable() { #if UNITY_PRE_5_1 title = "PlayMaker 1.8.2 Update Check"; #else titleContent = new GUIContent("PlayMaker 1.8.2 Update Check"); #endif minSize = new Vector2(400,400); DoCheck(); } private void OnGUI() { #if DEV_MODE if (GUILayout.Button("Log GUIDs")) { LogOfficialGUIDs(); } #endif scrollPosition = GUILayout.BeginScrollView(scrollPosition); GUILayout.Label("Project Scan", EditorStyles.boldLabel); if (failedCategories.Count > 0) { var output = "The scan found these addons in your project:\n"; foreach (var category in failedCategories) { output += "\n- " + category; } output += "\n\nThese addons are now included in the main install. See Update Notes below for more info.\n"; ConsoleTextArea(output); } else { ConsoleTextArea("The scan did not find any known conflicts in your project.\n"); } GUILayout.Label("Update Notes", EditorStyles.boldLabel); EditorGUILayout.HelpBox("\nPlayMaker 1.8.2 added the following system events:\n" + "\nMOUSE UP AS BUTTON, JOINT BREAK, JOINT BREAK 2D, PARTICLE COLLISION." + "\n\nPlease remove any custom proxy components you used before to send these events.\n", MessageType.Info); EditorGUILayout.HelpBox("\nPlayMaker 1.8.1 integrated the following add-ons and actions:\n" + "\n- Physics2D Add-on" + "\n- Mecanim Animator Add-on" + "\n- Vector2 Actions\n- Quaternion Actions\n- Trigonometry Actions\n", MessageType.Info); if (failedCategories.Count > 0) { EditorGUILayout.HelpBox( "\nIf you imported these actions from official unitypackages the update should replace them automatically." + "\n\nIf you downloaded these actions from the Ecosystem or Forums you might get errors from duplicate files after updating." + "\n\nYou can either remove these files before updating, or remove duplicate files to fix any errors after updating.\n", MessageType.Warning); } else { EditorGUILayout.HelpBox("\nThe Update Check did not find any of these files in your project. " + "\n\nHowever, if you think you have some of these actions in your project, " + "you can either remove them before updating, " + "or remove duplicate files to fix any errors after updating.\n", MessageType.Info); } EditorGUILayout.HelpBox("\nThe updated files will be located under:\nAssets/PlayMaker/Actions" + "\n\nOlder files are most likely under:\nAssets/PlayMaker Custom Actions\n", MessageType.Info); GUILayout.FlexibleSpace(); GUILayout.EndScrollView(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Run Update Check Again")) { DoCheck(); } logCheckFindingToggle = GUILayout.Toggle(logCheckFindingToggle,"Log Check Findings",GUILayout.Width(130)); GUILayout.EndHorizontal(); } private static GUIStyle consoleStyle; private static void InitConsoleStyle() { if (consoleStyle == null) { consoleStyle = new GUIStyle(EditorStyles.textArea) { normal = {textColor = Color.green} }; } } private static void ConsoleTextArea(string text) { InitConsoleStyle(); text = "Scanning project...\n\n" + text; var bgColor = GUI.backgroundColor; GUI.backgroundColor = new Color(0.3f,0.5f,0.3f); GUILayout.Label(text, consoleStyle); GUI.backgroundColor = bgColor; } public void DoCheck() { ScanProject(); // check each category for (var i = 0; i < checkCategories.Length; i++) { if (ProjectHasAnyOfTheseFiles(checkFiles[i].Split(','), officialPaths[i])) { failedCategories.Add(checkCategories[i]); } } } private void ResetCheck() { allFilesInProject.Clear(); allFilenames.Clear(); failedCategories.Clear(); } private void ScanProject() { ResetCheck(); //var playmakerActionsPath = Application.dataPath + "/PlayMaker/Actions/"; // get all script files in project allFilesInProject.AddRange(Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories)); for (var i = 0; i < allFilesInProject.Count; i++) { allFilesInProject[i] = allFilesInProject[i].Replace('\\','/'); } /* // remove files under PlayMaker/Actions folder foreach (var file in allFilesInProject.ToArray()) { //Debug.Log(file); if (file.Contains(playmakerActionsPath)) { Debug.Log("Remove: " + file); allFilesInProject.Remove(file); } }*/ // process paths allFilenames.AddRange(allFilesInProject); for (var i = 0; i < allFilesInProject.Count; i++) { // get filename for easy comparison allFilenames[i] = Path.GetFileName(allFilesInProject[i]); // make paths relative to project allFilesInProject[i] = allFilesInProject[i].Remove(0, Application.dataPath.Length - 6); } } private bool ProjectHasAnyOfTheseFiles(IEnumerable<string> files, string excludePath) { var foundFile = false; foreach (var file in files) { foreach (var checkFile in allFilesInProject) { if (checkFile.Contains(excludePath)) continue; if (checkFile.Contains(file)) { if (logCheckFindingToggle) { Debug.Log( "PlayMaker Pre-UpdateCheck Found the following file (click to Ping):\n" + checkFile, AssetDatabase.LoadAssetAtPath(checkFile, typeof(Object)) ); } foundFile = true; } } /* if (allFilenames.Contains(file)) { if (logCheckFindingToggle) { var _filePath = allFilesInProject[allFilenames.IndexOf(file)]; Debug.Log( "PlayMaker Pre-UpdateCheck Found the following file (click to Ping):\n"+_filePath, AssetDatabase.LoadAssetAtPath(_filePath,typeof(Object)) ); } _foundFile = true; }*/ } return foundFile; } #if DEV_MODE private string FindFile(string filename) { Debug.Log("FindFile: " + filename); foreach (var path in allFilesInProject) { //Debug.Log(path); if (path.Contains(filename)) return path; } return string.Empty; } // used to generate fileGUIDs // the official GUIDs for updated files private void LogOfficialGUIDs() { ScanProject(); var output = " private readonly string[] fileGUIDs =\n {"; for (var i = 0; i < checkCategories.Length; i++) { output += "\n \""; var files = checkFiles[i].Split(','); for (var j = 0; j < files.Length; j++) { var assetPath = FindFile(files[j]); if (!string.IsNullOrEmpty(assetPath)) { if (assetPath.Contains("Assets/PlayMaker/Actions/")) { output += AssetDatabase.AssetPathToGUID(assetPath) + ","; } } } output += "\","; } output += "\n };\n\n"; Debug.Log(output); } #endif } }
65.787611
2,887
0.708457
[ "Apache-2.0" ]
Drestat/ARfun
ARfun/Assets/PlayMaker/Editor/PreUpdateChecker.cs
22,304
C#
#if NETFRAMEWORK using System; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Abstractions; public class AcceptanceTestV2 : IDisposable { protected Xunit2 Xunit2 { get; private set; } public void Dispose() { if (Xunit2 != null) Xunit2.Dispose(); } public List<IMessageSinkMessage> Run(Type type) { return Run(new[] { type }); } public List<IMessageSinkMessage> Run(Type[] types) { Xunit2 = new Xunit2(AppDomainSupport.Required, new NullSourceInformationProvider(), types[0].Assembly.GetLocalCodeBase(), configFileName: null, shadowCopy: true); var discoverySink = new SpyMessageSink<IDiscoveryCompleteMessage>(); foreach (var type in types) { Xunit2.Find(type.FullName, includeSourceInformation: false, messageSink: discoverySink, discoveryOptions: TestFrameworkOptions.ForDiscovery()); discoverySink.Finished.WaitOne(); discoverySink.Finished.Reset(); } var testCases = discoverySink.Messages.OfType<ITestCaseDiscoveryMessage>().Select(msg => msg.TestCase).ToArray(); var runSink = new SpyMessageSink<ITestAssemblyFinished>(); Xunit2.RunTests(testCases, runSink, TestFrameworkOptions.ForExecution()); runSink.Finished.WaitOne(); return runSink.Messages.ToList(); } public List<TMessageType> Run<TMessageType>(Type type) where TMessageType : IMessageSinkMessage { return Run(type).OfType<TMessageType>().ToList(); } public List<TMessageType> Run<TMessageType>(Type[] types) where TMessageType : IMessageSinkMessage { return Run(types).OfType<TMessageType>().ToList(); } } #endif
26.830508
164
0.754264
[ "Apache-2.0" ]
0xced/xunit
src/xunit.v2.tests/TestUtility/AcceptanceTestV2.cs
1,585
C#
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Testing.Snippets.Snippets { // [START snippets_generated_Snippets_MethodResourceSignature_sync_flattened2] using Testing.Snippets; public sealed partial class GeneratedSnippetsClientSnippets { /// <summary>Snippet for MethodResourceSignature</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void MethodResourceSignature2() { // Create client SnippetsClient snippetsClient = SnippetsClient.Create(); // Initialize request argument(s) string firstName = "items/[ITEM_ID]"; // Make the request Response response = snippetsClient.MethodResourceSignature(firstName); } } // [END snippets_generated_Snippets_MethodResourceSignature_sync_flattened2] }
38.536585
89
0.701899
[ "Apache-2.0" ]
LaudateCorpus1/gapic-generator-csharp
Google.Api.Generator.Tests/ProtoTests/Snippets/Testing.Snippets.GeneratedSnippets/SnippetsClient.MethodResourceSignature2Snippet.g.cs
1,582
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace NET.Tools { public partial class MainWin : MainForm { public MainWin() { InitializeComponent(); } public override void Initialize(SplashForm splash) { for (int i = 0; i < 100; i++) { (splash as SplashWin).Info = i + "%"; Thread.Sleep(25); } } private void btnOK_Click(object sender, EventArgs e) { Close(); } } }
20.75
61
0.527443
[ "Apache-2.0" ]
CHiiLD/net-toolkit
NET.Tools.Demo/Needed/Forms/MainWin.cs
749
C#
using System.Collections.ObjectModel; using System.Linq; using System.Windows; using System.Windows.Controls; using Fluent; using Microsoft.Xaml.Behaviors; using Param_RootNamespace.Contracts.Services; using Param_RootNamespace.Models; namespace Param_RootNamespace.Behaviors { // See how to add new Tabs and new groups in Home Tab from your pages https://github.com/microsoft/WindowsTemplateStudio/blob/master/docs/WPF/projectTypes/ribbon.md public class RibbonTabsBehavior : Behavior<Ribbon> { public static readonly DependencyProperty IsHomeTabProperty = DependencyProperty.RegisterAttached( "IsHomeTab", typeof(bool), typeof(RibbonTabsBehavior), new PropertyMetadata(default(bool))); public static void SetIsHomeTab(DependencyObject element, bool value) => element.SetValue(IsHomeTabProperty, value); public static bool GetIsHomeTab(DependencyObject element) => (bool)element.GetValue(IsHomeTabProperty); public static bool GetIsTabFromPage(RibbonTabItem item) => (bool)item.GetValue(IsTabFromPageProperty); public static void SetIsTabFromPage(RibbonTabItem item, bool value) => item.SetValue(IsTabFromPageProperty, value); public static readonly DependencyProperty IsTabFromPageProperty = DependencyProperty.RegisterAttached("IsTabFromPage", typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(false)); public static bool GetIsGroupFromPage(RibbonGroupBox item) => (bool)item.GetValue(IsGroupFromPageProperty); public static void SetIsGroupFromPage(RibbonGroupBox item, bool value) => item.SetValue(IsGroupFromPageProperty, value); public static readonly DependencyProperty IsGroupFromPageProperty = DependencyProperty.RegisterAttached("IsGroupFromPage", typeof(bool), typeof(RibbonGroupBox), new PropertyMetadata(false)); public static RibbonPageConfiguration GetPageConfiguration(Page item) => (RibbonPageConfiguration)item.GetValue(PageConfigurationProperty); public static void SetPageConfiguration(Page item, RibbonPageConfiguration value) => item.SetValue(PageConfigurationProperty, value); public static readonly DependencyProperty PageConfigurationProperty = DependencyProperty.Register("PageConfiguration", typeof(RibbonPageConfiguration), typeof(Page), new PropertyMetadata(new RibbonPageConfiguration())); public void Initialize(INavigationService navigationService) { navigationService.Navigated += OnNavigated; } private void OnNavigated(object sender, string e) { var frame = sender as Frame; if (frame != null && frame.Content is Page page) { UpdateTabs(page); } } private void UpdateTabs(Page page) { if (page != null) { var config = GetPageConfiguration(page); SetupHomeGroups(config.HomeGroups); SetupTabs(config.Tabs); } } private void SetupHomeGroups(Collection<RibbonGroupBox> homeGroups) { var homeTab = AssociatedObject.Tabs.FirstOrDefault(GetIsHomeTab); if (homeTab == null) { return; } for (int i = homeTab.Groups.Count - 1; i >= 0; i--) { if (GetIsGroupFromPage(homeTab.Groups[i])) { homeTab.Groups.RemoveAt(i); } } foreach (var group in homeGroups) { if (GetIsGroupFromPage(group)) { homeTab.Groups.Add(group); } } } private void SetupTabs(Collection<RibbonTabItem> tabs) { for (int i = AssociatedObject.Tabs.Count - 1; i >= 0; i--) { if (GetIsTabFromPage(AssociatedObject.Tabs[i])) { AssociatedObject.Tabs.RemoveAt(i); } } foreach (var tab in tabs) { if (GetIsTabFromPage(tab)) { AssociatedObject.Tabs.Add(tab); } } } } }
37.641667
169
0.601505
[ "MIT" ]
Snippets-and-Devs/WindowsTemplateStudio
templates/Wpf/_comp/_shared/Project.Ribbon/Behaviors/RibbonTabsBehavior.cs
4,400
C#
/* * LeagueClient * * 7.23.209.3517 * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace LeagueClientApi.Model { /// <summary> /// LolPurchaseWidgetValidationRequest /// </summary> [DataContract] public partial class LolPurchaseWidgetValidationRequest : IEquatable<LolPurchaseWidgetValidationRequest>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="LolPurchaseWidgetValidationRequest" /> class. /// </summary> /// <param name="Items">Items.</param> public LolPurchaseWidgetValidationRequest(List<LolPurchaseWidgetValidationRequestItem> Items = default(List<LolPurchaseWidgetValidationRequestItem>)) { this.Items = Items; } /// <summary> /// Gets or Sets Items /// </summary> [DataMember(Name="items", EmitDefaultValue=false)] public List<LolPurchaseWidgetValidationRequestItem> Items { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LolPurchaseWidgetValidationRequest {\n"); sb.Append(" Items: ").Append(Items).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LolPurchaseWidgetValidationRequest); } /// <summary> /// Returns true if LolPurchaseWidgetValidationRequest instances are equal /// </summary> /// <param name="other">Instance of LolPurchaseWidgetValidationRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(LolPurchaseWidgetValidationRequest other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Items == other.Items || this.Items != null && this.Items.SequenceEqual(other.Items) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Items != null) hash = hash * 59 + this.Items.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
32.895161
157
0.580289
[ "MIT" ]
wildbook/LeagueClientApi
Model/LolPurchaseWidgetValidationRequest.cs
4,079
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace EndpointRouter.Contracts { /// <summary> /// Interface for an endpoint result. /// </summary> public interface IEndpointResult { /// <summary> /// Executes the endpoint result. /// </summary> /// <param name="httpContext">The <see cref="HttpContext"/>.</param> /// <returns><see cref="Task"/>.</returns> Task ExecuteAsync(HttpContext httpContext); } }
27.611111
76
0.613682
[ "MIT" ]
AdamRiddick/endpoint-router
src/Contracts/IEndpointResult.cs
497
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using AutoMapper; using IdentityServer.Admin.Core.Entities.Clients; using IdentityServer.Admin.Models.Client; namespace IdentityServer.Admin.Infrastructure.Mappers { /// <summary> /// Extension methods to map to/from entity/model for clients. /// </summary> public static class ClientMappers { static ClientMappers() { Mapper = new MapperConfiguration(cfg => cfg.AddProfile<ClientMapperProfile>()) .CreateMapper(); } internal static IMapper Mapper { get; } /// <summary> /// Maps an entity to a model. /// </summary> /// <param name="entity">The entity.</param> /// <returns></returns> public static ClientModel ToModel(this Client entity) { return Mapper.Map<ClientModel>(entity); } /// <summary> /// Maps a model to an entity. /// </summary> /// <param name="model">The model.</param> /// <returns></returns> public static Client ToEntity(this ClientModel model) { return Mapper.Map<Client>(model); } } }
30.113636
107
0.600755
[ "MIT" ]
Olek-HZQ/IdentityServerManagement
src/IdentityServer.Admin/Infrastructure/Mappers/ClientMappers.cs
1,327
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using FluentAssertions; using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions; using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums; using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Extensions; using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Visitors; using Microsoft.OpenApi.Any; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Serialization; namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Tests.Visitors { [TestClass] public class UInt16TypeVisitorTests { private VisitorCollection _visitorCollection; private IVisitor _visitor; private NamingStrategy _strategy; [TestInitialize] public void Init() { this._visitorCollection = new VisitorCollection(); this._visitor = new UInt16TypeVisitor(this._visitorCollection); this._strategy = new CamelCaseNamingStrategy(); } [DataTestMethod] [DataRow(typeof(ushort), false)] public void Given_Type_When_IsNavigatable_Invoked_Then_It_Should_Return_Result(Type type, bool expected) { var result = this._visitor.IsNavigatable(type); result.Should().Be(expected); } [DataTestMethod] [DataRow(typeof(ushort), true)] [DataRow(typeof(short), false)] [DataRow(typeof(string), false)] public void Given_Type_When_IsVisitable_Invoked_Then_It_Should_Return_Result(Type type, bool expected) { var result = this._visitor.IsVisitable(type); result.Should().Be(expected); } [DataTestMethod] [DataRow(typeof(ushort), true)] [DataRow(typeof(short), false)] [DataRow(typeof(string), false)] public void Given_Type_When_IsParameterVisitable_Invoked_Then_It_Should_Return_Result(Type type, bool expected) { var result = this._visitor.IsParameterVisitable(type); result.Should().Be(expected); } [DataTestMethod] [DataRow(typeof(ushort), true)] [DataRow(typeof(short), false)] [DataRow(typeof(string), false)] public void Given_Type_When_IsPayloadVisitable_Invoked_Then_It_Should_Return_Result(Type type, bool expected) { var result = this._visitor.IsPayloadVisitable(type); result.Should().Be(expected); } [DataTestMethod] [DataRow("integer", "int32")] public void Given_Type_When_Visit_Invoked_Then_It_Should_Return_Result(string dataType, string dataFormat) { var name = "hello"; var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair<string, Type>(name, typeof(ushort)); this._visitor.Visit(acceptor, type, this._strategy); acceptor.Schemas.Should().ContainKey(name); acceptor.Schemas[name].Type.Should().Be(dataType); acceptor.Schemas[name].Format.Should().Be(dataFormat); } [DataTestMethod] [DataRow(1)] public void Given_MinLengthAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(int length) { var name = "hello"; var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair<string, Type>(name, typeof(ushort)); var attribute = new MinLengthAttribute(length); this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas.Should().ContainKey(name); acceptor.Schemas[name].Type.Should().Be("integer"); acceptor.Schemas[name].MinLength.Should().Be(length); } [DataTestMethod] [DataRow(10)] public void Given_MaxLengthAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(int length) { var name = "hello"; var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair<string, Type>(name, typeof(ushort)); var attribute = new MaxLengthAttribute(length); this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas.Should().ContainKey(name); acceptor.Schemas[name].Type.Should().Be("integer"); acceptor.Schemas[name].MaxLength.Should().Be(length); } [DataTestMethod] [DataRow(1, 10)] public void Given_RangeAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(int min, int max) { var name = "hello"; var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair<string, Type>(name, typeof(ushort)); var attribute = new RangeAttribute(min, max); this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas.Should().ContainKey(name); acceptor.Schemas[name].Type.Should().Be("integer"); acceptor.Schemas[name].Minimum.Should().Be(min); acceptor.Schemas[name].Maximum.Should().Be(max); } [DataTestMethod] [DataRow("hello", "lorem ipsum")] public void Given_OpenApiPropertyAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(string name, string description) { var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair<string, Type>(name, typeof(ushort)); var attribute = new OpenApiPropertyAttribute() { Description = description }; this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas[name].Nullable.Should().Be(false); acceptor.Schemas[name].Default.Should().BeNull(); acceptor.Schemas[name].Description.Should().Be(description); } [DataTestMethod] [DataRow("hello", true, "lorem ipsum")] [DataRow("hello", false, "lorem ipsum")] public void Given_OpenApiPropertyAttribute_With_Default_When_Visit_Invoked_Then_It_Should_Return_Result(string name, bool nullable, string description) { var @default = (ushort)1; var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair<string, Type>(name, typeof(ushort)); var attribute = new OpenApiPropertyAttribute() { Nullable = nullable, Default = @default, Description = description }; this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas[name].Nullable.Should().Be(nullable); acceptor.Schemas[name].Default.Should().NotBeNull(); (acceptor.Schemas[name].Default as OpenApiInteger).Value.Should().Be((ushort)@default); acceptor.Schemas[name].Description.Should().Be(description); } [DataTestMethod] [DataRow("hello", true, "lorem ipsum")] [DataRow("hello", false, "lorem ipsum")] public void Given_OpenApiPropertyAttribute_Without_Default_When_Visit_Invoked_Then_It_Should_Return_Result(string name, bool nullable, string description) { var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair<string, Type>(name, typeof(ushort)); var attribute = new OpenApiPropertyAttribute() { Nullable = nullable, Description = description }; this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas[name].Nullable.Should().Be(nullable); acceptor.Schemas[name].Default.Should().BeNull(); acceptor.Schemas[name].Description.Should().Be(description); } [DataTestMethod] [DataRow("hello", OpenApiVisibilityType.Advanced)] [DataRow("hello", OpenApiVisibilityType.Important)] [DataRow("hello", OpenApiVisibilityType.Internal)] public void Given_OpenApiSchemaVisibilityAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(string name, OpenApiVisibilityType visibility) { var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair<string, Type>(name, typeof(ushort)); var attribute = new OpenApiSchemaVisibilityAttribute(visibility); this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas[name].Extensions.Should().ContainKey("x-ms-visibility"); acceptor.Schemas[name].Extensions["x-ms-visibility"].Should().BeOfType<OpenApiString>(); (acceptor.Schemas[name].Extensions["x-ms-visibility"] as OpenApiString).Value.Should().Be(visibility.ToDisplayName(this._strategy)); } [DataTestMethod] [DataRow("integer", "int32")] public void Given_Type_When_ParameterVisit_Invoked_Then_It_Should_Return_Result(string dataType, string dataFormat) { var result = this._visitor.ParameterVisit(typeof(ushort), this._strategy); result.Type.Should().Be(dataType); result.Format.Should().Be(dataFormat); } [DataTestMethod] [DataRow("integer", "int32")] public void Given_Type_When_PayloadVisit_Invoked_Then_It_Should_Return_Result(string dataType, string dataFormat) { var result = this._visitor.PayloadVisit(typeof(ushort), this._strategy); result.Type.Should().Be(dataType); result.Format.Should().Be(dataFormat); } } }
42.140969
162
0.660255
[ "MIT" ]
AieatAssam/azure-functions-openapi-extension
test/Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Tests/Visitors/UInt16TypeVisitorTests.cs
9,566
C#
using GameLovers.Services; using NSubstitute; using NUnit.Framework; // ReSharper disable once CheckNamespace namespace GameLoversEditor.Services.Tests { public class MessageBrokerServiceTest { public interface IMockSubscriber { void MockMessageCall(MessageType1 message); void MockMessageCall2(MessageType1 message); void MockMessageAlternativeCall(MessageType2 message); void MockMessageAlternativeCall2(MessageType2 message); } public struct MessageType1 : IMessage {} public struct MessageType2 : IMessage {} private MessageType1 _messageType1; private MessageType2 _messageType2; private IMockSubscriber _subscriber; private MessageBrokerService _messageBroker; [SetUp] public void Init() { _messageBroker = new MessageBrokerService(); _subscriber = Substitute.For<IMockSubscriber>(); _messageType1 = new MessageType1(); _messageType2 = new MessageType2(); } [Test] public void Subscribe_Publish_Successfully() { _messageBroker.Subscribe<MessageType1>(_subscriber.MockMessageCall); _messageBroker.Publish(_messageType1); _subscriber.Received().MockMessageCall(_messageType1); } [Test] public void Publish_WithoutSubscription_DoesNothing() { _messageBroker.Publish(_messageType1); _subscriber.DidNotReceive().MockMessageCall(_messageType1); } [Test] public void Unsubscribe_Successfully() { _messageBroker.Subscribe<MessageType1>(_subscriber.MockMessageCall); _messageBroker.Unsubscribe<MessageType1>(_subscriber.MockMessageCall); _messageBroker.Publish(_messageType1); _subscriber.DidNotReceive().MockMessageCall(_messageType1); } [Test] public void UnsubscribeWithAction_KeepsSubscriptionSameType_Successfully() { _messageBroker.Subscribe<MessageType1>(_subscriber.MockMessageCall); _messageBroker.Subscribe<MessageType1>(_subscriber.MockMessageCall2); _messageBroker.Unsubscribe<MessageType1>(_subscriber.MockMessageCall); _messageBroker.Publish(_messageType1); _subscriber.DidNotReceive().MockMessageCall(_messageType1); _subscriber.Received().MockMessageCall2(_messageType1); } [Test] public void UnsubscribeWithoutAction_KeepsSubscriptionDifferentType_Successfully() { _messageBroker.Subscribe<MessageType1>(_subscriber.MockMessageCall); _messageBroker.Subscribe<MessageType2>(_subscriber.MockMessageAlternativeCall); _messageBroker.Unsubscribe<MessageType1>(); _messageBroker.Publish(_messageType2); _subscriber.DidNotReceive().MockMessageCall(_messageType1); _subscriber.Received().MockMessageAlternativeCall(_messageType2); } [Test] public void UnsubscribeAll_Successfully() { _messageBroker.Subscribe<MessageType1>(_subscriber.MockMessageCall); _messageBroker.Subscribe<MessageType1>(_subscriber.MockMessageCall2); _messageBroker.Subscribe<MessageType2>(_subscriber.MockMessageAlternativeCall); _messageBroker.Subscribe<MessageType2>(_subscriber.MockMessageAlternativeCall2); _messageBroker.UnsubscribeAll(); _messageBroker.Publish(_messageType2); _messageBroker.Publish(_messageType2); _subscriber.DidNotReceive().MockMessageCall(_messageType1); _subscriber.DidNotReceive().MockMessageCall2(_messageType1); _subscriber.DidNotReceive().MockMessageAlternativeCall(_messageType2); _subscriber.DidNotReceive().MockMessageAlternativeCall2(_messageType2); } [Test] public void Unsubscribe_WithoutSubscription_DoesNothing() { Assert.DoesNotThrow(() => _messageBroker.Unsubscribe<MessageType1>(_subscriber.MockMessageCall)); Assert.DoesNotThrow(() => _messageBroker.Unsubscribe<MessageType1>()); Assert.DoesNotThrow(() => _messageBroker.UnsubscribeAll()); } } }
32.778761
100
0.799946
[ "MIT" ]
CoderGamester/com.gamelovers.services
Tests/Editor/MessageBrokerServiceTest.cs
3,706
C#
 using System; using System.Runtime.CompilerServices; namespace Chronologic { public readonly partial struct Flag8 : IEquatable<Flag8> { private readonly byte _value; private Flag8(byte value) => _value = value; private void TransposeUnsafe(Span<Flag8> data) { // Half the maximum value of byte var m = (byte)0x0F; for (int j = 4; j != 0; j >>= 1, m ^= (byte)(m << j)) { for (int k = 0; k < 8; k = ((k | j) + 1) & ~j) { var t = (byte)((data[k] ^ (data[k | j] >> j)) & m); data[k] ^= t; data[k | j] ^= (byte)(t << j); } } } // THIS PARTICULAR implementation demands only the (^) operator public Flag8[] DoubleDeltaXor(Flag8[] data) { var result = new Flag8[data.Length]; data.CopyTo(result, 0); if (result.Length == 0 || result.Length == 1) { return result; } else if (result.Length == 2) { result[1] ^= result[0]; return result; } var prev2 = result[0] ^ result[1]; var prev1 = result[1]; for (int i = 2; i < result.Length; i++) { var prev0 = result[i]; // Required explicit conversion due to bytes var next1 = (Flag8)(prev0 ^ prev1); result[i] = (Flag8)(next1 ^ prev2); prev2 = next1; prev1 = prev0; } return result; } public Flag8[] TransposeEncode(Flag8[] data) { const int bitsize = 8; // The new array size is made of 8-byte chunks: var result = new Flag8[(data.Length + bitsize - 1) & ~0x7]; data.CopyTo(result, 0); for (int i = 0; i < result.Length; i += bitsize) { TransposeUnsafe(result.AsSpan(i, bitsize)); } return result; } public Span<Flag8> TransposeDecode(Flag8[] data, int count) { const int bitsize = 8; var result = (Flag8[])data.Clone(); for (int i = 0; i < result.Length; i += bitsize) { TransposeUnsafe(result.AsSpan(i, bitsize)); } return result.AsSpan(0, count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Flag8(byte value) => new Flag8(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator byte(Flag8 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Flag8 first, Flag8 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Flag8 first, byte second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(byte first, Flag8 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Flag8 first, Flag8 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Flag8 first, byte second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(byte first, Flag8 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Flag8 other) => _value.Equals(other._value); public override bool Equals(object other) => other is Flag8 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString("X2"); } public readonly partial struct U8 : IEquatable<U8> { private readonly byte _value; private U8(byte value) => _value = value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator U8(byte value) => new U8(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator byte(U8 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(U8 first, U8 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(U8 first, byte second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(byte first, U8 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(U8 first, U8 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(U8 first, byte second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(byte first, U8 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(U8 other) => _value.Equals(other._value); public override bool Equals(object other) => other is U8 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString(); } public readonly partial struct I8 : IEquatable<I8> { private readonly sbyte _value; private I8(sbyte value) => _value = value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator I8(sbyte value) => new I8(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator sbyte(I8 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(I8 first, I8 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(I8 first, sbyte second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(sbyte first, I8 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(I8 first, I8 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(I8 first, sbyte second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(sbyte first, I8 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(I8 other) => _value.Equals(other._value); public override bool Equals(object other) => other is I8 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString(); } public readonly partial struct Flag16 : IEquatable<Flag16> { private readonly ushort _value; private Flag16(ushort value) => _value = value; private void TransposeUnsafe(Span<Flag16> data) { // Half the maximum value of ushort var m = (ushort)0x00FF; for (int j = 8; j != 0; j >>= 1, m ^= (ushort)(m << j)) { for (int k = 0; k < 16; k = ((k | j) + 1) & ~j) { var t = (ushort)((data[k] ^ (data[k | j] >> j)) & m); data[k] ^= t; data[k | j] ^= (ushort)(t << j); } } } // THIS PARTICULAR implementation demands only the (^) operator public Flag16[] DoubleDeltaXor(Flag16[] data) { var result = new Flag16[data.Length]; data.CopyTo(result, 0); if (result.Length == 0 || result.Length == 1) { return result; } else if (result.Length == 2) { result[1] ^= result[0]; return result; } var prev2 = result[0] ^ result[1]; var prev1 = result[1]; for (int i = 2; i < result.Length; i++) { var prev0 = result[i]; // Required explicit conversion due to bytes var next1 = (Flag16)(prev0 ^ prev1); result[i] = (Flag16)(next1 ^ prev2); prev2 = next1; prev1 = prev0; } return result; } public Flag16[] TransposeEncode(Flag16[] data) { const int bitsize = 16; // The new array size is made of 16-byte chunks: var result = new Flag16[(data.Length + bitsize - 1) & ~0xF]; data.CopyTo(result, 0); for (int i = 0; i < result.Length; i += bitsize) { TransposeUnsafe(result.AsSpan(i, bitsize)); } return result; } public Span<Flag16> TransposeDecode(Flag16[] data, int count) { const int bitsize = 16; var result = (Flag16[])data.Clone(); for (int i = 0; i < result.Length; i += bitsize) { TransposeUnsafe(result.AsSpan(i, bitsize)); } return result.AsSpan(0, count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Flag16(ushort value) => new Flag16(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ushort(Flag16 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Flag16 first, Flag16 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Flag16 first, ushort second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ushort first, Flag16 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Flag16 first, Flag16 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Flag16 first, ushort second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(ushort first, Flag16 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Flag16 other) => _value.Equals(other._value); public override bool Equals(object other) => other is Flag16 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString("X4"); } public readonly partial struct U16 : IEquatable<U16> { private readonly ushort _value; private U16(ushort value) => _value = value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator U16(ushort value) => new U16(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ushort(U16 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(U16 first, U16 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(U16 first, ushort second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ushort first, U16 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(U16 first, U16 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(U16 first, ushort second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(ushort first, U16 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(U16 other) => _value.Equals(other._value); public override bool Equals(object other) => other is U16 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString(); } public readonly partial struct I16 : IEquatable<I16> { private readonly short _value; private I16(short value) => _value = value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator I16(short value) => new I16(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator short(I16 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(I16 first, I16 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(I16 first, short second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(short first, I16 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(I16 first, I16 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(I16 first, short second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(short first, I16 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(I16 other) => _value.Equals(other._value); public override bool Equals(object other) => other is I16 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString(); } public readonly partial struct Flag32 : IEquatable<Flag32> { private readonly uint _value; private Flag32(uint value) => _value = value; private void TransposeUnsafe(Span<Flag32> data) { // Half the maximum value of uint var m = (uint)0x0000FFFF; for (int j = 16; j != 0; j >>= 1, m ^= (uint)(m << j)) { for (int k = 0; k < 32; k = ((k | j) + 1) & ~j) { var t = (uint)((data[k] ^ (data[k | j] >> j)) & m); data[k] ^= t; data[k | j] ^= (uint)(t << j); } } } // THIS PARTICULAR implementation demands only the (^) operator public Flag32[] DoubleDeltaXor(Flag32[] data) { var result = new Flag32[data.Length]; data.CopyTo(result, 0); if (result.Length == 0 || result.Length == 1) { return result; } else if (result.Length == 2) { result[1] ^= result[0]; return result; } var prev2 = result[0] ^ result[1]; var prev1 = result[1]; for (int i = 2; i < result.Length; i++) { var prev0 = result[i]; // Required explicit conversion due to bytes var next1 = (Flag32)(prev0 ^ prev1); result[i] = (Flag32)(next1 ^ prev2); prev2 = next1; prev1 = prev0; } return result; } public Flag32[] TransposeEncode(Flag32[] data) { const int bitsize = 32; // The new array size is made of 32-byte chunks: var result = new Flag32[(data.Length + bitsize - 1) & ~0x1F]; data.CopyTo(result, 0); for (int i = 0; i < result.Length; i += bitsize) { TransposeUnsafe(result.AsSpan(i, bitsize)); } return result; } public Span<Flag32> TransposeDecode(Flag32[] data, int count) { const int bitsize = 32; var result = (Flag32[])data.Clone(); for (int i = 0; i < result.Length; i += bitsize) { TransposeUnsafe(result.AsSpan(i, bitsize)); } return result.AsSpan(0, count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Flag32(uint value) => new Flag32(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator uint(Flag32 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Flag32 first, Flag32 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Flag32 first, uint second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(uint first, Flag32 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Flag32 first, Flag32 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Flag32 first, uint second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(uint first, Flag32 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Flag32 other) => _value.Equals(other._value); public override bool Equals(object other) => other is Flag32 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString("X8"); } public readonly partial struct U32 : IEquatable<U32> { private readonly uint _value; private U32(uint value) => _value = value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator U32(uint value) => new U32(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator uint(U32 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(U32 first, U32 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(U32 first, uint second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(uint first, U32 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(U32 first, U32 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(U32 first, uint second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(uint first, U32 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(U32 other) => _value.Equals(other._value); public override bool Equals(object other) => other is U32 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString(); } public readonly partial struct I32 : IEquatable<I32> { private readonly int _value; private I32(int value) => _value = value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator I32(int value) => new I32(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator int(I32 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(I32 first, I32 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(I32 first, int second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(int first, I32 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(I32 first, I32 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(I32 first, int second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(int first, I32 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(I32 other) => _value.Equals(other._value); public override bool Equals(object other) => other is I32 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString(); } public readonly partial struct Flag64 : IEquatable<Flag64> { private readonly ulong _value; private Flag64(ulong value) => _value = value; private void TransposeUnsafe(Span<Flag64> data) { // Half the maximum value of ulong var m = (ulong)0x00000000FFFFFFFF; for (int j = 32; j != 0; j >>= 1, m ^= (ulong)(m << j)) { for (int k = 0; k < 64; k = ((k | j) + 1) & ~j) { var t = (ulong)((data[k] ^ (data[k | j] >> j)) & m); data[k] ^= t; data[k | j] ^= (ulong)(t << j); } } } // THIS PARTICULAR implementation demands only the (^) operator public Flag64[] DoubleDeltaXor(Flag64[] data) { var result = new Flag64[data.Length]; data.CopyTo(result, 0); if (result.Length == 0 || result.Length == 1) { return result; } else if (result.Length == 2) { result[1] ^= result[0]; return result; } var prev2 = result[0] ^ result[1]; var prev1 = result[1]; for (int i = 2; i < result.Length; i++) { var prev0 = result[i]; // Required explicit conversion due to bytes var next1 = (Flag64)(prev0 ^ prev1); result[i] = (Flag64)(next1 ^ prev2); prev2 = next1; prev1 = prev0; } return result; } public Flag64[] TransposeEncode(Flag64[] data) { const int bitsize = 64; // The new array size is made of 64-byte chunks: var result = new Flag64[(data.Length + bitsize - 1) & ~0x3F]; data.CopyTo(result, 0); for (int i = 0; i < result.Length; i += bitsize) { TransposeUnsafe(result.AsSpan(i, bitsize)); } return result; } public Span<Flag64> TransposeDecode(Flag64[] data, int count) { const int bitsize = 64; var result = (Flag64[])data.Clone(); for (int i = 0; i < result.Length; i += bitsize) { TransposeUnsafe(result.AsSpan(i, bitsize)); } return result.AsSpan(0, count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Flag64(ulong value) => new Flag64(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ulong(Flag64 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Flag64 first, Flag64 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Flag64 first, ulong second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ulong first, Flag64 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Flag64 first, Flag64 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Flag64 first, ulong second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(ulong first, Flag64 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Flag64 other) => _value.Equals(other._value); public override bool Equals(object other) => other is Flag64 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString("X16"); } public readonly partial struct U64 : IEquatable<U64> { private readonly ulong _value; private U64(ulong value) => _value = value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator U64(ulong value) => new U64(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ulong(U64 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(U64 first, U64 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(U64 first, ulong second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ulong first, U64 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(U64 first, U64 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(U64 first, ulong second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(ulong first, U64 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(U64 other) => _value.Equals(other._value); public override bool Equals(object other) => other is U64 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString(); } public readonly partial struct I64 : IEquatable<I64> { private readonly long _value; private I64(long value) => _value = value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator I64(long value) => new I64(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator long(I64 value) => value._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(I64 first, I64 second) => first._value == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(I64 first, long second) => first._value == second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(long first, I64 second) => first == second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(I64 first, I64 second) => first._value != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(I64 first, long second) => first._value != second; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(long first, I64 second) => first != second._value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(I64 other) => _value.Equals(other._value); public override bool Equals(object other) => other is I64 x && Equals(x); public override int GetHashCode() => _value.GetHashCode(); public override string ToString() => _value.ToString(); } }
35.71954
73
0.578936
[ "MIT" ]
kainous/Chronologic
src/NET/Chronologic/Flags.cs
31,078
C#
using Microsoft.Azure.RemoteRendering; using Microsoft.Azure.RemoteRendering.Unity; using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RemoteFrameStats : MonoBehaviour { public Text FrameStats = null; ARRServiceStats arrServiceStats = null; #if UNITY_EDITOR private void OnEnable() { arrServiceStats = new ARRServiceStats(); } void Update() { if (!RemoteManagerUnity.IsConnected) { FrameStats.text = string.Empty; return; } arrServiceStats.Update(RemoteManagerUnity.CurrentSession); if (FrameStats != null) { FrameStats.text = arrServiceStats.GetStatsString(); } } #endif }
21.621622
67
0.625
[ "MIT" ]
objecttheory/azure-remote-rendering
Unity/Tutorial1-CreateUnityProject/Assets/Scripts/RemoteFrameStats.cs
802
C#
using System; using System.Linq.Expressions; using Newtonsoft.Json; namespace Nest { /// <summary> /// Expands a field with dots into an object field. /// This processor allows fields with dots in the name to be accessible by other processors in the pipeline. /// Otherwise these fields can’t be accessed by any processor. /// </summary> [JsonObject(MemberSerialization.OptIn)] [JsonConverter(typeof(ProcessorJsonConverter<DotExpanderProcessor>))] public interface IDotExpanderProcessor : IProcessor { /// <summary> /// The field to expand into an object field /// </summary> [JsonProperty("field")] Field Field { get; set; } /// <summary> /// The field that contains the field to expand. /// Only required if the field to expand is part another object field, /// because the field option can only understand leaf fields. /// </summary> [JsonProperty("path")] string Path { get; set; } } /// <summary> /// Expands a field with dots into an object field. /// This processor allows fields with dots in the name to be accessible by other processors in the pipeline. /// Otherwise these fields can’t be accessed by any processor. /// </summary> public class DotExpanderProcessor : ProcessorBase, IDotExpanderProcessor { /// <summary> /// The field to expand into an object field /// </summary> [JsonProperty("field")] public Field Field { get; set; } /// <summary> /// The field that contains the field to expand. /// Only required if the field to expand is part another object field, /// because the field option can only understand leaf fields. /// </summary> [JsonProperty("path")] public string Path { get; set; } protected override string Name => "dot_expander"; } /// <summary> /// Expands a field with dots into an object field. /// This processor allows fields with dots in the name to be accessible by other processors in the pipeline. /// Otherwise these fields can’t be accessed by any processor. /// </summary> public class DotExpanderProcessorDescriptor<T> : ProcessorDescriptorBase<DotExpanderProcessorDescriptor<T>, IDotExpanderProcessor>, IDotExpanderProcessor where T : class { protected override string Name => "dot_expander"; Field IDotExpanderProcessor.Field { get; set; } string IDotExpanderProcessor.Path { get; set; } /// <summary> /// The field to expand into an object field /// </summary> public DotExpanderProcessorDescriptor<T> Field(Field field) => Assign(a => a.Field = field); /// <summary> /// The field to expand into an object field /// </summary> public DotExpanderProcessorDescriptor<T> Field(Expression<Func<T, object>> objectPath) => Assign(a => a.Field = objectPath); /// <summary> /// The field that contains the field to expand. /// Only required if the field to expand is part another object field, /// because the field option can only understand leaf fields. /// </summary> public DotExpanderProcessorDescriptor<T> Path(string path) => Assign(a => a.Path = path); } }
34.5
109
0.709157
[ "Apache-2.0" ]
Henr1k80/elasticsearch-net
src/Nest/Ingest/Processors/DotExpanderProcessor.cs
3,044
C#
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reactive.Linq; using System.Text; namespace Rxx.Parsers.Reactive.Linq { /// <summary> /// Provides <see langword="static" /> methods for defining <see cref="IObservableParser{TSource,TResult}"/> grammars. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Since it primarily provides cohesive monadic extension methods, maintainability and discoverability are not degraded.")] public static partial class ObservableParser { /// <summary> /// Applies an <paramref name="accumulator"/> function over each result sequence from the /// specified <paramref name="parser"/> and yields a sequence of accumulated results. /// </summary> /// <typeparam name="TSource">The type of the source elements.</typeparam> /// <typeparam name="TIntermediate">The type of the elements that are generated from parsing the source elements.</typeparam> /// <typeparam name="TAccumulate">The type of the accumulation.</typeparam> /// <typeparam name="TResult">The type of the elements that are generated from projecting the accumulation.</typeparam> /// <param name="parser">The parser that produces a sequence of result sequences to be aggregated.</param> /// <param name="seed">A function that returns the initial value of the accumulation for each parse result.</param> /// <param name="accumulator">A function to be invoked on each element of each parse result.</param> /// <param name="selector">A function that projects the final aggregation of each parse result.</param> /// <returns>A parser that returns the aggregated results.</returns> public static IObservableParser<TSource, TResult> Aggregate<TSource, TIntermediate, TAccumulate, TResult>( this IObservableParser<TSource, IObservable<TIntermediate>> parser, Func<TAccumulate> seed, Func<TAccumulate, TIntermediate, TAccumulate> accumulator, Func<TAccumulate, TResult> selector) { Contract.Requires(parser != null); Contract.Requires(accumulator != null); Contract.Requires(selector != null); Contract.Ensures(Contract.Result<IObservableParser<TSource, TResult>>() != null); return parser.Yield( "Aggregate", source => from result in parser.Parse(source) from acc in result.Value.Aggregate(seed(), accumulator) select result.Yield(selector(acc))); } /// <summary> /// Appends each element in each result sequence from the specified <paramref name="parser"/> /// to an accumulated <see cref="string"/>, yielding a single <see cref="string"/> per result /// sequence. /// </summary> /// <typeparam name="TSource">The type of the source elements.</typeparam> /// <typeparam name="TIntermediate">The type of the elements that are generated from parsing the source elements.</typeparam> /// <param name="parser">The parser that produces a sequence of result sequences to be joined into strings.</param> /// <returns>A parser that returns the aggregated <see cref="string"/> results.</returns> public static IObservableParser<TSource, string> Join<TSource, TIntermediate>( this IObservableParser<TSource, IObservable<TIntermediate>> parser) { Contract.Requires(parser != null); Contract.Ensures(Contract.Result<IObservableParser<TSource, string>>() != null); return Join(parser, v => v, v => v); } /// <summary> /// Appends each element in each result from the specified <paramref name="parser"/> /// to an accumulated <see cref="string"/> and projects the strings for each result. /// </summary> /// <typeparam name="TSource">The type of the source elements.</typeparam> /// <typeparam name="TIntermediate">The type of the elements that are generated from parsing the source elements.</typeparam> /// <typeparam name="TResult">The type of the elements that are generated from projecting the accumulated <see cref="string"/>.</typeparam> /// <param name="parser">The parser that produces a sequence of result sequences to be joined.</param> /// <param name="selector">A function that projects the aggregated <see cref="string"/> of each parse result.</param> /// <returns>A parser that returns the joined results.</returns> public static IObservableParser<TSource, TResult> Join<TSource, TIntermediate, TResult>( this IObservableParser<TSource, IObservable<TIntermediate>> parser, Func<string, TResult> selector) { Contract.Requires(parser != null); Contract.Requires(selector != null); Contract.Ensures(Contract.Result<IObservableParser<TSource, TResult>>() != null); return Join(parser, v => v, selector); } /// <summary> /// Applies a <paramref name="joiner"/> function over each result from the specified /// <paramref name="parser"/> to create an accumulated <see cref="string"/> and projects /// the strings for each result. /// </summary> /// <typeparam name="TSource">The type of the source elements.</typeparam> /// <typeparam name="TIntermediate">The type of the elements that are generated from parsing the source elements.</typeparam> /// <typeparam name="TJoin">The type of the accumulation on which <see cref="object.ToString"/> is called.</typeparam> /// <typeparam name="TResult">The type of the elements that are generated from projecting the accumulated <see cref="string"/>.</typeparam> /// <param name="parser">The parser that produces a sequence of result sequences to be joined.</param> /// <param name="joiner">A function to be invoked on each element of each parse result to produce a value /// on which <see cref="object.ToString"/> is called and appended to the accumulation.</param> /// <param name="selector">A function that projects the aggregated <see cref="string"/> of each parse result.</param> /// <returns>A parser that returns the joined results.</returns> public static IObservableParser<TSource, TResult> Join<TSource, TIntermediate, TJoin, TResult>( this IObservableParser<TSource, IObservable<TIntermediate>> parser, Func<TIntermediate, TJoin> joiner, Func<string, TResult> selector) { Contract.Requires(parser != null); Contract.Requires(joiner != null); Contract.Requires(selector != null); Contract.Ensures(Contract.Result<IObservableParser<TSource, TResult>>() != null); return Aggregate( parser, () => new StringBuilder(), (builder, value) => builder.Append(joiner(value)), builder => selector(builder.ToString())); } /// <summary> /// Appends the results of each result sequence from the specified <paramref name="parser"/> into an <see cref="IList{TResult}"/>. /// </summary> /// <typeparam name="TSource">The type of the source elements.</typeparam> /// <typeparam name="TResult">The type of the elements that are generated by the parser.</typeparam> /// <param name="parser">The parser that produces a sequence of result sequences to be aggregated.</param> /// <returns>A parser that returns the results aggregated into an <see cref="IList{TResult}"/>.</returns> public static IObservableParser<TSource, IList<TResult>> ToList<TSource, TResult>( this IObservableParser<TSource, IObservable<TResult>> parser) { Contract.Requires(parser != null); Contract.Ensures(Contract.Result<IObservableParser<TSource, IList<TResult>>>() != null); return parser.Aggregate( () => new List<TResult>(), (list, result) => { list.Add(result); return list; }, list => (IList<TResult>)list.AsReadOnly()); } } }
56
143
0.694909
[ "MIT" ]
slorion/multiagent-system-example
DLC.Multiagent/Rxx/Parsers/Reactive/Linq/Aggregation.cs
7,898
C#
namespace MassTransit.Configuration { using System; using System.Collections.Generic; using AzureTable; using AzureTable.Saga; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.DependencyInjection.Extensions; using Saga; public class AzureTableSagaRepositoryConfigurator<TSaga> : IAzureTableSagaRepositoryConfigurator<TSaga>, ISpecification where TSaga : class, ISaga { Func<IServiceProvider, CloudTable> _connectionFactory; Func<IServiceProvider, ISagaKeyFormatter<TSaga>> _formatterFactory = provider => new ConstPartitionSagaKeyFormatter<TSaga>(typeof(TSaga).Name); /// <summary> /// Supply factory for retrieving the Cloud Table. /// </summary> /// <param name="connectionFactory"></param> public void ConnectionFactory(Func<CloudTable> connectionFactory) { _connectionFactory = provider => connectionFactory(); } /// <summary> /// Supply factory for retrieving the Cloud Table. /// </summary> /// <param name="connectionFactory"></param> public void ConnectionFactory(Func<IServiceProvider, CloudTable> connectionFactory) { _connectionFactory = connectionFactory; } /// <summary> /// Supply factory for retrieving the key formatter. /// </summary> /// <param name="formatterFactory"></param> public void KeyFormatter(Func<ISagaKeyFormatter<TSaga>> formatterFactory) { _formatterFactory = provider => formatterFactory(); } public IEnumerable<ValidationResult> Validate() { if (_connectionFactory == null) yield return this.Failure("ConnectionFactory", "must be specified"); } public void Register<T>(ISagaRepositoryRegistrationConfigurator<T> configurator) where T : class, ISaga { configurator.TryAddSingleton<ICloudTableProvider<TSaga>>(provider => new ConstCloudTableProvider<TSaga>(_connectionFactory(provider))); configurator.TryAddSingleton(_formatterFactory); configurator.RegisterSagaRepository<T, DatabaseContext<T>, SagaConsumeContextFactory<DatabaseContext<T>, T>, AzureTableSagaRepositoryContextFactory<T>>(); } } }
36.753846
147
0.653411
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
src/Persistence/MassTransit.Azure.Table/Configuration/Configuration/AzureTableSagaRepositoryConfigurator.cs
2,389
C#
namespace UserRegistration.Test.Services { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Linq; using Moq; using NUnit.Framework; using UserRegistration.Core.Entities; using UserRegistration.Core.Persistence; using UserRegistration.Core.Services; /// <summary> /// Tests for user registration service. /// </summary> [TestFixture] public class UserRegistrationServiceTests { #region Fields /// <summary> /// The user registration service. /// </summary> private IUserRegistrationService _userRegistrationService; #endregion #region Public Methods and Operators /// <summary> /// Sets up the test. /// </summary> [SetUp] public void SetupTest() { IList<User> users = new List<User>(); IQueryable<User> queryable = users.AsQueryable(); Mock<IDbSet<User>> mockUsers = new Mock<IDbSet<User>>(); mockUsers.Setup(x => x.Provider) .Returns(queryable.Provider); mockUsers.Setup(x => x.Expression) .Returns(queryable.Expression); mockUsers.Setup(x => x.ElementType) .Returns(queryable.ElementType); mockUsers.Setup(x => x.GetEnumerator()) .Returns(queryable.GetEnumerator()); mockUsers.Setup(x => x.Add(It.IsAny<User>())) .Callback<User>(users.Add); Mock<DatabaseContext> mockContext = new Mock<DatabaseContext>(); mockContext.Setup(x => x.Users) .Returns(mockUsers.Object); this._userRegistrationService = new UserRegistrationService(mockContext.Object); } /// <summary> /// Tears down the test. /// </summary> [TearDown] public void TearDownTest() { this._userRegistrationService.Dispose(); } /// <summary> /// Tests registering a duplicate user. /// </summary> [Test] public void TestRegisterDuplicateUser() { User user = new User { UserName = "abcde", Password = "Ab123456" }; Assert.DoesNotThrow(() => this._userRegistrationService.RegisterUser(user), "Should register successfully"); Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register with same user name"); } /// <summary> /// Tests registering with invalid passwords. /// </summary> [Test] public void TestRegisterUserWithInvalidPassword() { User user = new User { UserName = "abcde" }; Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register without password"); user.Password = "Ab12345"; Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register with password that is too short"); user.Password = "ab123456"; Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register with password that has no uppercase character"); user.Password = "AB123456"; Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register with password that has no lowercase character"); user.Password = "Abcdefgh"; Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register with password that has no numbers"); } /// <summary> /// Tests registering with invalid user names. /// </summary> [Test] public void TestRegisterUserWithInvalidUserName() { User user = new User { Password = "Abcd1234" }; Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register without user name"); user.UserName = "abcd"; Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register with user name that is too short"); user.UserName = "!@#$%"; Assert.Throws<ValidationException>(() => this._userRegistrationService.RegisterUser(user), "Should fail to register with user name with non-alpha numeric characters"); } /// <summary> /// Tests registering with a null user. /// </summary> [Test] public void TestRegisterUserWithNull() { Assert.Throws<ArgumentNullException>(() => this._userRegistrationService.RegisterUser(null), "Should fail to register without a user"); } #endregion } }
37.542254
179
0.578128
[ "MIT" ]
prototypev/coding-tests
UserRegistration/UserRegistration.Test/Services/UserRegistrationServiceTests.cs
5,333
C#
using DemoSite.Infrastructure.Initilization; using EPiServer.Cms.UI.AspNetIdentity; using EPiServer.Web; using EPiServer.Web.Routing; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Jhoose.Security.DependencyInjection; using Microsoft.Extensions.Configuration; using Jhoose.Security.Core.Models; using Jhoose.Security; namespace DemoSite { public class Startup { private readonly IWebHostEnvironment _webHostingEnvironment; private readonly IConfiguration _configuration; public Startup(IWebHostEnvironment webHostingEnvironment, IConfiguration configuration) { _webHostingEnvironment = webHostingEnvironment; _configuration = configuration; } public void ConfigureServices(IServiceCollection services) { if (_webHostingEnvironment.IsDevelopment()) { //Add development configuration } services.AddMvc(); services.AddCms() .AddCmsAspNetIdentity<ApplicationUser>(); services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IFirstRequestInitializer), typeof(BootstrapAdminUser))); services.AddJhooseSecurity(_configuration); services.ConfigureApplicationCookie(options => { options.LoginPath = "/util/Login"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseJhooseSecurity(); app.UseEndpoints(endpoints => { endpoints.MapContent(); }); } } }
30.291667
129
0.65016
[ "Apache-2.0" ]
andrewmarkham/contentsecuritypolicy
src/Sample/DemoSite/Startup.cs
2,183
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Cargo.Controllers { public class ServiceController : Controller { // // GET: /Service/ public ActionResult Index() { return View(); } public ActionResult Process() { return PartialView("_Process"); } public ActionResult TransportLines() { Cargo.App_DataClass.TransportLines m = Cargo.App_DataClass.TransportLines.GetData(); return View("TransportLines",m); } public ActionResult ContactUs() { return View("ContactUs"); } } }
21.470588
96
0.571233
[ "Apache-2.0" ]
suochensheng/EnterpriseCMS
Cargo/Cargo/Controllers/ServiceController.cs
732
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; namespace WebAddressbookTests { public class GroupHelper : HelperBase { public GroupHelper(ApplicationManager manager) : base(manager) { } public GroupHelper Create(GroupData group) { manager.Navigator.GoToGroupsPage(); InitGroupCreation(); FillGroupForm(group); SubmitGroupCreation(); ReturnToGroupsPage(); return this; } public GroupHelper Modify(int v, GroupData newData) { manager.Navigator.GoToGroupsPage(); SelectGroup(v); InitGroupModification(); FillGroupForm(newData); SubmitGroupModification(); ReturnToGroupsPage(); return this; } public GroupHelper Remove(int v) { manager.Navigator.GoToGroupsPage(); SelectGroup(v); DeleteGroup(); ReturnToGroupsPage(); return this; } public GroupHelper SubmitGroupCreation() { driver.FindElement(By.Name("submit")).Click(); groupCache = null; return this; } public int GetGroupsCount() { return driver.FindElements(By.CssSelector("span.group")).Count; } public GroupHelper FillGroupForm(GroupData group) { driver.FindElement(By.Name("group_name")).Click(); Type(By.Name("group_name"), group.Name); Type(By.Name("group_header"), group.Header); Type(By.Name("group_footer"), group.Footer); return this; } public GroupHelper InitGroupCreation() { driver.FindElement(By.Name("new")).Click(); return this; } public GroupHelper DeleteGroup() { driver.FindElement(By.XPath("(//input[@name='delete'])[2]")).Click(); groupCache = null; return this; } public GroupHelper SelectGroup(int index) { driver.FindElement(By.XPath("(//input[@name='selected[]'])[" + (index+1) + "]")).Click(); return this; } public GroupHelper ReturnToGroupsPage() { driver.FindElement(By.LinkText("group page")).Click(); return this; } public GroupHelper InitGroupModification() { driver.FindElement(By.Name("edit")).Click(); return this; } public GroupHelper SubmitGroupModification() { driver.FindElement(By.Name("update")).Click(); groupCache = null; return this; } public bool IsGroupPresent() { manager.Navigator.GoToGroupsPage(); return IsElementPresent(By.ClassName("group")); } private List<GroupData> groupCache = null; public List<GroupData> GetGroupList() { if (groupCache == null) { groupCache = new List<GroupData>(); manager.Navigator.GoToGroupsPage(); ICollection<IWebElement> elements = driver.FindElements(By.CssSelector("span.group")); foreach (IWebElement element in elements) { groupCache.Add(new GroupData(element.Text)); } } return groupCache; } } }
27.414815
102
0.537693
[ "Apache-2.0" ]
pavel7pace/csharp_training
addressbook-web-tests/addressbook-web-tests/appmanager/GroupHelper.cs
3,703
C#
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Acrux.Html { internal class HtmlNodeStack : Stack<HtmlNode> { private HtmlParser m_Parser; private HtmlParserSettings m_ParserSettings; private HtmlDocument m_Document; internal HtmlNodeStack(HtmlParser parser, HtmlDocument document, HtmlParserSettings parserSettings) { m_Parser = parser; m_ParserSettings = parserSettings; m_Document = document; } public new HtmlNode Pop() { HtmlNode node = base.Pop(); ApplyParseTimeStructureFixups(node as HtmlElement); return node; } private void ApplyParseTimeStructureFixups(HtmlElement popedUpNode) { if (popedUpNode == null) return; // If this is a HEAD element outside the HEAD then make sure to add it in the HEAD if (popedUpNode.IsHeadLevelElement && popedUpNode.ParentNode != null && popedUpNode.ParentNode.Name != "head") { // Add it to the HEAD and make it current, in case it has text node associated // Make sure we get the head with XPath. The m_Document.HeadElement may be null // if the head is not found yet HtmlElement headElement = (HtmlElement)m_Document.SelectSingleNode("/html/head"); if (headElement != null) { HtmlNode lastHeadNode = headElement.ChildNodes.Count > 0 ? headElement.ChildNodes[headElement.ChildNodes.Count - 1] : null; headElement.InsertBefore(popedUpNode, lastHeadNode); return; } } if (m_ParserSettings.NoScriptsBeforeBodyAddedToHtml && m_Document.BodyElement == null && popedUpNode.Name == "noscript") { // All noscripts found before the BODY is parsed go to the HTML element HtmlNode htmlNode = m_Document.SelectSingleNode("/html"); HtmlNode fakeBodyNode = m_Document.SelectSingleNode("/html/body"); if (htmlNode != null && fakeBodyNode != null) { htmlNode.InsertBefore(popedUpNode, fakeBodyNode); return; } } } public new void Push(HtmlNode item) { base.Push(item); } } }
32.871795
143
0.568253
[ "MIT" ]
AcruxSoftware/Acrux.Html
Acrux.Html/HtmlNodeStack.cs
2,564
C#
namespace algorithms.Algorithms.Sorting.QuickSort { public class QuickSortImpl { private readonly IPartitioner _partitionImpl; public QuickSortImpl(IPartitioner partitionImpl) { _partitionImpl = partitionImpl; } public void QuickSort(int[] arr, int low, int high) { /* Partitioning schemes * Always pick first element as pivot. * Always pick last element as pivot * Pick a random element as pivot. * Pick median as pivot. */ // pick the first element as pivot if (low < high) { var index = _partitionImpl.Partition(arr, low, high); QuickSort(arr, low, index); QuickSort(arr, index + 1, high); } } } }
28.9
69
0.524798
[ "MIT" ]
jmeline/dotnet-examples
algorithms/Algorithms/Sorting/QuickSort/QuickSortImpl.cs
867
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using CoreLogging; namespace sample { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc() .Services .AddCoreLogging(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
27.574074
106
0.590329
[ "Apache-2.0" ]
alanstevens/CoreLogging
src/Sample/Startup.cs
1,491
C#
/******************************************************************************************** Author: Sergey Stoyan sergey.stoyan@gmail.com sergey.stoyan@hotmail.com stoyan@cliversoft.com http://www.cliversoft.com ********************************************************************************************/ using System; using System.Net; namespace Cliver { class WebClient : System.Net.WebClient { protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult asyncResult) { WebResponse response = null; try { response = base.GetWebResponse(request, asyncResult); } catch (WebException e) { response = e.Response; } Response = response as HttpWebResponse; return response; } protected override WebResponse GetWebResponse(WebRequest request) { WebResponse response = null; try { response = base.GetWebResponse(request); } catch (WebException e) { response = e.Response; } Response = response as HttpWebResponse; return response; } public HttpWebResponse Response { get; private set; } = null; protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); Request = request as HttpWebRequest; Request.CookieContainer = cookieContainer; return request; } private readonly CookieContainer cookieContainer = new CookieContainer(); public HttpWebRequest Request { get; private set; } = null; } }
33.345455
99
0.506543
[ "MIT" ]
aTiKhan/CliverRoutines
WebClient.cs
1,836
C#
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2020-05-31.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.CloudFront { /// <summary> /// Configuration for accessing Amazon CloudFront service /// </summary> public partial class AmazonCloudFrontConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.5.6.3"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonCloudFrontConfig() { this.AuthenticationServiceName = "cloudfront"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "cloudfront"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2020-05-31"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.1375
108
0.588235
[ "Apache-2.0" ]
rczwojdrak/aws-sdk-net
sdk/src/Services/CloudFront/Generated/AmazonCloudFrontConfig.cs
2,091
C#
using System; namespace Mirror.Cloud.Example { /// <summary> /// Network Manager with events that are used by the list server /// </summary> public class NetworkManagerListServer : NetworkManager { /// <summary> /// Called when Server Starts /// </summary> public event Action onServerStarted; /// <summary> /// Called when Server Stops /// </summary> public event Action onServerStopped; /// <summary> /// Called when players leaves or joins the room /// </summary> public event OnPlayerListChanged onPlayerListChanged; public delegate void OnPlayerListChanged(int playerCount); int connectionCount => NetworkServer.connections.Count; public override void OnServerConnect(NetworkConnection conn) { int count = connectionCount; if (count > maxConnections) { conn.Disconnect(); return; } onPlayerListChanged?.Invoke(count); } public override void OnServerDisconnect(NetworkConnection conn) { base.OnServerDisconnect(conn); onPlayerListChanged?.Invoke(connectionCount); } public override void OnStartServer() { onServerStarted?.Invoke(); } public override void OnStopServer() { onServerStopped?.Invoke(); } } }
25.288136
71
0.575067
[ "MIT" ]
28raining/Mirror
Assets/Mirror/Examples/Cloud/GUI/Scripts/NetworkManagerListServer.cs
1,492
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using PruebaGestionVentas.Server.Helpers; using PruebaGestionVentas.Server.Models; using PruebaGestionVentas.Shared.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PruebaGestionVentas.Server.Controllers { [ApiController] [Route("api/[controller]")] public class ClientesController : ControllerBase { private readonly ApplicationDbContext context; public ClientesController(ApplicationDbContext context) { this.context = context; } [HttpPost] public async Task<ActionResult<int>> Post(ClientDTO clientedto) { Cliente cliente= new Cliente(); cliente.nombre = clientedto.name; cliente.apellido = clientedto.lastname; cliente.telefono = clientedto.phone; cliente.fecha_creacion = DateTime.Now; cliente.cedula = clientedto.DocumentId; context.Add(cliente); await context.SaveChangesAsync(); return cliente.Id; } [HttpPut] public async Task<ActionResult> Put(ClientDTO client) { Cliente cliente = context.Cliente.Where(x => x.Id == client.Id).FirstOrDefault(); if (cliente == null) { return NotFound(); } else { cliente.nombre = client.name; cliente.apellido = client.lastname; cliente.cedula = client.DocumentId; cliente.telefono = client.phone; context.Attach(cliente).State = EntityState.Modified; await context.SaveChangesAsync(); return NoContent(); } context.Attach(cliente).State = EntityState.Modified; await context.SaveChangesAsync(); return NoContent(); } [HttpDelete("{id}")] public async Task<ActionResult> Delete(int id) { var exists = await context.Cliente.AnyAsync(x => x.Id == id); if (!exists) { return NotFound(); } else { context.Remove(new Producto { Id = id }); await context.SaveChangesAsync(); return NoContent(); } } [HttpGet] public async Task<ActionResult<List<ClientDTO>>> Get([FromQuery] Pagin pagin) { var queryable = context.Cliente.AsQueryable(); var queryabledto = queryable.Select(x => new ClientDTO { DocumentId = x.cedula, name = x.nombre, lastname = x.apellido, phone = x.telefono, creation_date = x.fecha_creacion, Id = x.Id }); await HttpContext.InsertParametersPaginResponse(queryabledto, pagin.NRecords); return await queryabledto.Pagionation(pagin).ToListAsync(); } [HttpGet("search/{name}")] public async Task<ActionResult<int>> Get(string name) { return await context.Cliente.Where(x => x.nombre == name).CountAsync(); } } }
32.01
199
0.581693
[ "MIT" ]
edgaralvarezrengifo/gestionventas_blazor
PruebaGestionVentas/Server/Controllers/ClientesController.cs
3,203
C#
namespace DomainServices.Test { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using AutoFixture.Xunit2; using Repositories; using Xunit; public class FakeGroupedJsonRepositoryTest { private readonly FakeGroupedJsonRepository<FakeGroupedEntity> _repository; public FakeGroupedJsonRepositoryTest() { _repository = new FakeGroupedJsonRepository<FakeGroupedEntity>(); } [Theory, AutoData] public void AddExistingThrows(FakeGroupedEntity entity) { _repository.Add(entity); Assert.Throws<ArgumentException>(() => _repository.Add(entity)); } [Theory, AutoData] public void UpdateNonExistingThrows(FakeGroupedEntity entity) { Assert.Throws<KeyNotFoundException>(() => _repository.Update(entity)); } [Fact] public void AddWithNoGroupThrows() { var entity = new FakeGroupedEntity("My Entity", null); Assert.Throws<ArgumentException>(() => _repository.Add(entity)); } [Fact] public void ContainsWithInvalidGroupedIdThrows() { Assert.Throws<ArgumentException>(() => _repository.Contains("InvalidGroupedEntityId")); } [Fact] public void GetWithInvalidGroupedIdThrows() { Assert.Throws<ArgumentException>(() => _repository.Get("InvalidGroupedEntityId")); } [Fact] public void RemoveWithInvalidGroupedIdThrows() { Assert.Throws<ArgumentException>(() => _repository.Remove("InvalidGroupedEntityId")); } [Theory, AutoData] public void GetNonExistingReturnsEmpty(FakeGroupedEntity entity) { _repository.Add(entity); Assert.False(_repository.Get("NonExistingGroup/NonExistingName").HasValue); } [Theory, AutoData] public void GetNonExistingFromExistingGroupReturnsEmpty(FakeGroupedEntity entity) { _repository.Add(entity); var id = $"{entity.Group}/NonExistingName"; Assert.False(_repository.Get(id).HasValue); } [Theory, AutoData] public void AddAndGetIsOk(FakeGroupedEntity entity) { _repository.Add(entity); var actual = _repository.Get(entity.FullName).Value; Assert.Equal(entity.Id, actual.Id); } [Theory, AutoData] public void ContainsIsOk(FakeGroupedEntity entity) { _repository.Add(entity); Assert.True(_repository.Contains(entity.FullName)); } [Theory, AutoData] public void DoesNotContainIsOk(FakeGroupedEntity entity) { Assert.False(_repository.Contains(entity.FullName)); } [Theory, AutoData] public void ContainsGroupIsOk(FakeGroupedEntity entity) { _repository.Add(entity); Assert.NotNull(entity.Group); Assert.True(_repository.ContainsGroup(entity.Group)); } [Theory, AutoData] public void DoesNotContainGroupIsOk(FakeGroupedEntity entity) { Assert.NotNull(entity.Group); Assert.False(_repository.ContainsGroup(entity.Group)); } [Theory, AutoData] public void CountIsOk(FakeGroupedEntity entity) { _repository.Add(entity); Assert.Equal(1, _repository.Count()); } [Theory, AutoData] public void GetAllIsOk(FakeGroupedEntity entity1, FakeGroupedEntity entity2) { _repository.Add(entity1); _repository.Add(entity2); var entity3 = new FakeGroupedEntity("My Entity", entity1.Group); _repository.Add(entity3); Assert.Equal(3, _repository.GetAll().Count()); } [Theory, AutoData] public void GetByGroupIsOk(FakeGroupedEntity entity1, FakeGroupedEntity entity2) { _repository.Add(entity1); _repository.Add(entity2); var entity3 = new FakeGroupedEntity("My Entity", entity1.Group); _repository.Add(entity3); Assert.NotNull(entity1.Group); Assert.NotNull(entity2.Group); Assert.Equal(2, _repository.GetByGroup(entity1.Group).Count()); Assert.Single((IEnumerable) _repository.GetByGroup(entity2.Group)); } [Theory, AutoData] public void GetFullNamesByGroupIsOk(FakeGroupedEntity entity1, FakeGroupedEntity entity2) { _repository.Add(entity1); _repository.Add(entity2); var entity3 = new FakeGroupedEntity("My Entity", entity1.Group); _repository.Add(entity3); Assert.NotNull(entity1.Group); Assert.NotNull(entity2.Group); Assert.Equal(2, _repository.GetFullNames(entity1.Group).Count()); Assert.Single((IEnumerable) _repository.GetFullNames(entity2.Group)); Assert.Equal(entity2.FullName, _repository.GetFullNames(entity2.Group).First()); } [Theory, AutoData] public void GetFullNamesIsOk(FakeGroupedEntity entity1, FakeGroupedEntity entity2) { _repository.Add(entity1); _repository.Add(entity2); var entity3 = new FakeGroupedEntity("My Entity", entity1.Group); _repository.Add(entity3); Assert.Equal(3, _repository.GetFullNames().Count()); } [Theory, AutoData] public void GetIdsIsOk(FakeGroupedEntity entity) { _repository.Add(entity); Assert.Equal(entity.Id, _repository.GetIds().First()); } [Theory, AutoData] public void RemoveIsOk(FakeGroupedEntity entity1, FakeGroupedEntity entity2) { _repository.Add(entity1); _repository.Add(entity2); _repository.Remove(entity1.FullName); Assert.False(_repository.Contains(entity1.FullName)); Assert.True(_repository.Contains(entity2.FullName)); Assert.Equal(1, _repository.Count()); } [Theory, AutoData] public void RemoveUsingPredicateIsOk(FakeGroupedEntity entity1, FakeGroupedEntity entity2) { _repository.Add(entity1); _repository.Add(entity2); _repository.Remove(e => e.Id == entity1.Id); Assert.False(_repository.Contains(entity1.FullName)); Assert.Equal(1, _repository.Count()); } [Theory, AutoData] public void UpdateIsOk(FakeGroupedEntity entity) { _repository.Add(entity); entity.Metadata.Add("Description", "New description"); _repository.Update(entity); Assert.Equal("New description", _repository.Get(entity.FullName).Value.Metadata["Description"]); } [Theory, AutoData] public void GetAllReturnsClones(FakeGroupedEntity entity) { _repository.Add(entity); foreach (var e in _repository.GetAll()) { e.Metadata.Add("Description", "A description"); } Assert.DoesNotContain("Description", _repository.Get(entity.FullName).Value.Metadata.Keys); } [Fact] public void GetAllForEmptyRepositoryIsOk() { Assert.Empty(_repository.GetAll()); } [Theory, AutoData] public void GetReturnsClone(FakeGroupedEntity entity) { _repository.Add(entity); var e = _repository.Get(entity.FullName).Value; e.Metadata.Add("Description", "A description"); Assert.DoesNotContain("Description", _repository.Get(entity.FullName).Value.Metadata.Keys); } [Theory, AutoData] public void GetByPredicateReturnsClones(FakeGroupedEntity entity) { _repository.Add(entity); var e = _repository.Get(ent => ent.Id == entity.Id).First(); e.Metadata.Add("Description", "A description"); Assert.DoesNotContain("Description", _repository.Get(entity.FullName).Value.Metadata.Keys); } [Theory, AutoData] public void GetByGroupReturnsClones(FakeGroupedEntity entity) { _repository.Add(entity); Assert.NotNull(entity.Group); var e = _repository.GetByGroup(entity.Group).First(); e.Metadata.Add("Description", "A description"); Assert.DoesNotContain("Description", _repository.Get(entity.FullName).Value.Metadata.Keys); } } }
35.052209
108
0.610793
[ "MIT" ]
larsmichael/DomainServices
Source/DomainServices.Test/FakeGroupedJsonRepositoryTest.cs
8,730
C#
using Unity.LEGO.Behaviours; using UnityEditor; using UnityEngine; namespace Unity.LEGO.EditorExt { [CustomEditor(typeof(ControlAction), true)] public class ControlActionEditor : MovementActionEditor { ControlAction m_ControlAction; SerializedProperty m_ControlTypeProp; SerializedProperty m_InputTypeProp; SerializedProperty m_MinSpeedProp; SerializedProperty m_MaxSpeedProp; SerializedProperty m_IdleSpeedProp; SerializedProperty m_RotationSpeedProp; SerializedProperty m_JumpSpeedProp; SerializedProperty m_MaxJumpsInAirProp; SerializedProperty m_IsPlayerProp; SerializedProperty m_GravityProp; static readonly Color s_BackwardsColour = Color.red; protected override void OnEnable() { base.OnEnable(); m_ControlAction = (ControlAction)m_Action; m_ControlTypeProp = serializedObject.FindProperty("m_ControlType"); m_InputTypeProp = serializedObject.FindProperty("m_InputType"); m_MinSpeedProp = serializedObject.FindProperty("m_MinSpeed"); m_MaxSpeedProp = serializedObject.FindProperty("m_MaxSpeed"); m_IdleSpeedProp = serializedObject.FindProperty("m_IdleSpeed"); m_RotationSpeedProp = serializedObject.FindProperty("m_RotationSpeed"); m_JumpSpeedProp = serializedObject.FindProperty("m_JumpSpeed"); m_MaxJumpsInAirProp = serializedObject.FindProperty("m_MaxJumpsInAir"); m_IsPlayerProp = serializedObject.FindProperty("m_IsPlayer"); m_GravityProp = serializedObject.FindProperty("m_Gravity"); } protected override void CreateGUI() { EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); EditorGUILayout.PropertyField(m_ControlTypeProp); EditorGUILayout.PropertyField(m_InputTypeProp); EditorGUI.EndDisabledGroup(); if ((ControlAction.InputType)m_InputTypeProp.enumValueIndex != ControlAction.InputType.Direct) { var minSpeedValue = (float)m_MinSpeedProp.intValue; var maxSpeedValue = (float)m_MaxSpeedProp.intValue; EditorGUILayout.MinMaxSlider(new GUIContent("Speed Range\t(" + m_MinSpeedProp.intValue + " to " + m_MaxSpeedProp.intValue + ")", "The speed in LEGO modules per second."), ref minSpeedValue, ref maxSpeedValue, -50.0f, 50.0f); m_MinSpeedProp.intValue = Mathf.RoundToInt(minSpeedValue); m_MaxSpeedProp.intValue = Mathf.RoundToInt(maxSpeedValue); if (m_MinSpeedProp.intValue != m_MaxSpeedProp.intValue) { EditorGUILayout.IntSlider(m_IdleSpeedProp, m_MinSpeedProp.intValue, m_MaxSpeedProp.intValue); } } else { EditorGUILayout.IntSlider(m_MaxSpeedProp, 0, 50, new GUIContent("Speed", "The speed in LEGO modules per second.")); if (m_MaxSpeedProp.intValue > 0) { EditorGUILayout.IntSlider(m_IdleSpeedProp, 0, m_MaxSpeedProp.intValue); } } EditorGUILayout.PropertyField(m_RotationSpeedProp); EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); EditorGUILayout.PropertyField(m_IsPlayerProp); EditorGUILayout.PropertyField(m_CollideProp); if ((ControlAction.ControlType)m_ControlTypeProp.enumValueIndex == ControlAction.ControlType.Character) { EditorGUILayout.PropertyField(m_GravityProp); EditorGUILayout.PropertyField(m_JumpSpeedProp); EditorGUILayout.PropertyField(m_MaxJumpsInAirProp); } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(!m_ControlAction.IsPlacedOnBrick()); if (GUILayout.Button("Focus Camera")) { EditorUtilities.FocusCamera(m_ControlAction); } EditorGUI.EndDisabledGroup(); } public override void OnSceneGUI() { base.OnSceneGUI(); if (Event.current.type == EventType.Repaint) { if (m_ControlAction && m_ControlAction.IsPlacedOnBrick()) { var center = m_ControlAction.GetBrickCenter(); var direction = m_ControlAction.GetBrickRotation() * Vector3.forward; var start = center + direction * m_MinSpeedProp.intValue * LEGOBehaviour.LEGOHorizontalModule; var middle = center + direction * m_IdleSpeedProp.intValue * LEGOBehaviour.LEGOHorizontalModule; var end = center + direction * m_MaxSpeedProp.intValue * LEGOBehaviour.LEGOHorizontalModule; if ((ControlAction.InputType)m_InputTypeProp.enumValueIndex == ControlAction.InputType.Direct) { Handles.color = Color.green; Handles.DrawLine(center, end); Handles.DrawSolidDisc(middle, Camera.current.transform.forward, 0.16f); Handles.DrawSolidDisc(end, Camera.current.transform.forward, 0.16f); } else { if (m_MaxSpeedProp.intValue < 0) { Handles.color = s_BackwardsColour; Handles.DrawLine(start, center); Handles.DrawSolidDisc(start, Camera.current.transform.forward, 0.16f); Handles.DrawSolidDisc(middle, Camera.current.transform.forward, 0.16f); Handles.DrawSolidDisc(end, Camera.current.transform.forward, 0.16f); } else if (m_MinSpeedProp.intValue >= 0) { Handles.color = Color.green; Handles.DrawLine(center, end); Handles.DrawSolidDisc(start, Camera.current.transform.forward, 0.16f); Handles.DrawSolidDisc(middle, Camera.current.transform.forward, 0.16f); Handles.DrawSolidDisc(end, Camera.current.transform.forward, 0.16f); } else if (m_IdleSpeedProp.intValue < 0) { Handles.color = s_BackwardsColour; Handles.DrawLine(start, center); Handles.DrawSolidDisc(start, Camera.current.transform.forward, 0.16f); Handles.DrawSolidDisc(middle, Camera.current.transform.forward, 0.16f); Handles.color = Color.green; Handles.DrawLine(center, end); Handles.DrawSolidDisc(end, Camera.current.transform.forward, 0.16f); } else { Handles.color = s_BackwardsColour; Handles.DrawLine(start, center); Handles.DrawSolidDisc(start, Camera.current.transform.forward, 0.16f); Handles.color = Color.green; Handles.DrawLine(center, end); Handles.DrawSolidDisc(middle, Camera.current.transform.forward, 0.16f); Handles.DrawSolidDisc(end, Camera.current.transform.forward, 0.16f); } } } } } } }
46.864706
187
0.565081
[ "MIT" ]
TermiSenpai/MicroLego
Assets/LEGO/Scripts/Editor/ControlActionEditor.cs
7,967
C#
using System; using System.ComponentModel; namespace lexMD5.WPFApp { internal class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private string _errorMessage; public string ErrorMessage { get => _errorMessage; set { _errorMessage = value; RaisePropertyChanged(nameof(ErrorMessage)); } } protected void ResetError() { ErrorMessage = String.Empty; } } }
18.6875
77
0.742475
[ "MIT" ]
lexakogut/DataSafetyApps
Lab2/lexMD5.WPFApp/ViewModelBase.cs
600
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; using Microsoft.Azure.SignalR.Controllers.Common; using Microsoft.Azure.SignalR.Emulator.HubEmulator; using Microsoft.Extensions.Logging; namespace Microsoft.Azure.SignalR.Emulator.Controllers { internal class SignalRServiceEmulatorWebApi : SignalRServiceWebApiDefinition { private readonly DynamicHubContextStore _store; private readonly ILogger<SignalRServiceEmulatorWebApi> _logger; public SignalRServiceEmulatorWebApi(DynamicHubContextStore store, ILogger<SignalRServiceEmulatorWebApi> _logger) : base() { _store = store; this._logger = _logger; } public override async Task<IActionResult> Broadcast(string hub, [FromBody] PayloadMessage message, [FromQuery(Name = "excluded")] IReadOnlyList<string> excluded) { if (_store.TryGetLifetimeContext(hub, out var c)) { var clients = c.ClientManager; var arguments = SafeConvertToObjectArray(message); await SendAsync(clients.AllExcept(excluded), message.Target, arguments); return Accepted(); } else { return NotFound(); } } public override async Task<IActionResult> SendToUser(string hub, string user, [FromBody] PayloadMessage message) { if (_store.TryGetLifetimeContext(hub, out var c)) { var clients = c.ClientManager; var arguments = SafeConvertToObjectArray(message); await SendAsync(clients.User(user), message.Target, arguments); return Accepted(); } else { return NotFound(); } } public override Task<IActionResult> CheckConnectionExistence(string hub, string connectionId) { if (_store.TryGetLifetimeContext(hub, out var c)) { var lifetime = c.LifetimeManager; var connection = lifetime.Connections[connectionId]; if (connection != null) { return Task.FromResult(Ok() as IActionResult); } } return Task.FromResult(NotFound() as IActionResult); } public override Task<IActionResult> CheckGroupExistence(string hub, string group) { if (_store.TryGetLifetimeContext(hub, out var c)) { if (c.UserGroupManager.GroupContainsConnections(group)) { return Task.FromResult(Ok() as IActionResult); } } return Task.FromResult(NotFound() as IActionResult); } public override Task<IActionResult> CheckUserExistence(string hub, string user) { if (_store.TryGetLifetimeContext(hub, out var c)) { foreach (var conn in c.LifetimeManager.Connections) { if (string.Equals(conn.UserIdentifier, user, StringComparison.Ordinal)) { return Task.FromResult(Ok() as IActionResult); } } } return Task.FromResult(NotFound() as IActionResult); } public override Task<IActionResult> CloseClientConnection(string hub, string connectionId, [FromQuery] string reason) { if (_store.TryGetLifetimeContext(hub, out var c)) { var lifetime = c.LifetimeManager; var connection = lifetime.Connections[connectionId]; if (connection != null) { connection.Abort(); } } return Task.FromResult(Accepted() as IActionResult); } public override Task<IActionResult> RemoveConnectionFromGroup(string hub, string group, string connectionId) { if (_store.TryGetLifetimeContext(hub, out var c)) { c.UserGroupManager.RemoveConnectionFromGroup(connectionId, group); return Task.FromResult(Ok() as IActionResult); } else { return Task.FromResult(NotFound() as IActionResult); } } public override Task<IActionResult> AddConnectionToGroup(string hub, string group, string connectionId) { if (_store.TryGetLifetimeContext(hub, out var c)) { c.UserGroupManager.AddConnectionIntoGroup(connectionId, group); return Task.FromResult(Ok() as IActionResult); } else { return Task.FromResult(NotFound() as IActionResult); } } public override async Task<IActionResult> GroupBroadcast(string hub, string group, [FromBody] PayloadMessage message, [FromQuery(Name = "excluded")] IReadOnlyList<string> excluded) { if (_store.TryGetLifetimeContext(hub, out var c)) { var clients = c.ClientManager; var arguments = SafeConvertToObjectArray(message); using (var lease = c.UserGroupManager.GetConnectionsForGroup(group)) { if (lease.Value.Count > 0) { await SendAsync(clients.Clients(lease.Value.Except(excluded).ToArray()), message.Target, arguments); } } return Accepted(); } return NotFound(); } public override async Task<IActionResult> SendToConnection(string hub, string connectionId, [FromBody] PayloadMessage message) { if (_store.TryGetLifetimeContext(hub, out var c)) { var clients = c.ClientManager; var arguments = SafeConvertToObjectArray(message); await SendAsync(clients.Client(connectionId), message.Target, arguments); return Accepted(); } else { return NotFound(); } } public override Task<IActionResult> CheckUserExistenceInGroup(string hub, string group, string user) { if (_store.TryGetLifetimeContext(hub, out var c)) { if (c.UserGroupManager.GroupContainsUser(user, group)) { return Task.FromResult(Ok() as IActionResult); } } return Task.FromResult(NotFound() as IActionResult); } public override Task<IActionResult> AddUserToGroup(string hub, string group, string user, int? ttl = null) { if (_store.TryGetLifetimeContext(hub, out var c)) { c.UserGroupManager.AddUserToGroup(user, group, ttl == null ? DateTimeOffset.MaxValue : DateTimeOffset.Now.AddSeconds(ttl.Value)); return Task.FromResult(Ok() as IActionResult); } else { return Task.FromResult(NotFound() as IActionResult); } } public override Task<IActionResult> RemoveUserFromAllGroups(string hub, string user) { if (_store.TryGetLifetimeContext(hub, out var c)) { c.UserGroupManager.RemoveUserFromAllGroups(user); return Task.FromResult(Ok() as IActionResult); } else { return Task.FromResult(NotFound() as IActionResult); } } public override Task<IActionResult> RemoveUserFromGroup(string hub, string group, string user) { if (_store.TryGetLifetimeContext(hub, out var c)) { c.UserGroupManager.RemoveUserFromGroup(user, group); return Task.FromResult(Ok() as IActionResult); } else { return Task.FromResult(NotFound() as IActionResult); } } public override Task<IActionResult> GetHealthStatus() { return Task.FromResult(Ok() as IActionResult); } private Task SendAsync(IClientProxy client, string method, object[] arguments, CancellationToken cancellationToken = default) { switch (arguments.Length) { case 0: return client.SendAsync(method, cancellationToken); case 1: return client.SendAsync( method, arguments[0], cancellationToken); case 2: return client.SendAsync( method, arguments[0], arguments[1], cancellationToken); case 3: return client.SendAsync( method, arguments[0], arguments[1], arguments[2], cancellationToken); case 4: return client.SendAsync( method, arguments[0], arguments[1], arguments[2], arguments[3], cancellationToken); case 5: return client.SendAsync( method, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], cancellationToken); case 6: return client.SendAsync( method, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], cancellationToken); case 7: return client.SendAsync( method, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], cancellationToken); case 8: return client.SendAsync( method, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], cancellationToken); case 9: return client.SendAsync( method, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8], cancellationToken); case 10: return client.SendAsync( method, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8], arguments[9], cancellationToken); default: throw new NotSupportedException(); } } private object[] SafeConvertToObjectArray(PayloadMessage payload) { try { return JsonObjectConverter.ConvertToObjectArray(payload.Arguments); } catch (Exception ex) { _logger.LogError("Failed to parse argument", ex); return null; } } } }
36.153631
188
0.488295
[ "MIT" ]
Y-Sindo/azure-signalr
src/Microsoft.Azure.SignalR.Emulator/Controllers/SignalRServiceEmulatorWebApi.cs
12,945
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>A class which implements IEnumerable by creating an optionally-deep copy of the backing collection.</summary> //----------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using Microsoft.Build.Shared; namespace Microsoft.Build.Collections { /// <summary> /// A class which implements IEnumerable by creating an optionally-deep copy of the backing collection. /// </summary> /// <remarks> /// If the type contained in the collection implements IDeepCloneable then the copies will be deep clones instead /// of mere reference copies. /// <see cref="GetEnumerator()"/> is thread safe for concurrent access. /// </remarks> /// <typeparam name="T">The type contained in the backing collection.</typeparam> internal class CopyOnReadEnumerable<T> : IEnumerable<T> { /// <summary> /// The backing collection. /// </summary> private IEnumerable<T> _backingEnumerable; /// <summary> /// The object used to synchronize access for copying. /// </summary> private object _syncRoot; /// <summary> /// Constructor. /// </summary> /// <param name="backingEnumerable">The collection which serves as a source for enumeration.</param> /// <param name="syncRoot">The object used to synchronize access for copying.</param> public CopyOnReadEnumerable(IEnumerable<T> backingEnumerable, object syncRoot) { ErrorUtilities.VerifyThrowArgumentNull(backingEnumerable, "backingCollection"); ErrorUtilities.VerifyThrowArgumentNull(syncRoot, "syncRoot"); _backingEnumerable = backingEnumerable; _syncRoot = syncRoot; } #region IEnumerable<T> Members /// <summary> /// Returns an enumerator over the collection. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<T> GetEnumerator() { List<T> list; ICollection backingCollection = _backingEnumerable as ICollection; if (backingCollection != null) { list = new List<T>(backingCollection.Count); } else { list = new List<T>(); } bool isCloneable = false; bool checkForCloneable = true; lock (_syncRoot) { foreach (T item in _backingEnumerable) { if (checkForCloneable) { if (item is IDeepCloneable<T>) { isCloneable = true; } checkForCloneable = false; } T copiedItem = isCloneable ? (item as IDeepCloneable<T>).DeepClone() : item; list.Add(copiedItem); } } return list.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an numerator over the collection. /// </summary> /// <returns>The enumerator.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } #endregion } }
34.425926
121
0.548682
[ "MIT" ]
0n1zz/main
src/Build/Collections/CopyOnReadEnumerable.cs
3,720
C#
// Copyright (c) 2017 Trevor Redfern // // This software is released under the MIT License. // https://opensource.org/licenses/MIT namespace Tests.Characters { using Xunit; using SilverNeedle.Characters; using SilverNeedle.Serialization; using SilverNeedle.Utility; public class FavoredClassOptionTests { [Fact] public void LoadsAndGeneratorsAModifierBasedOnOption() { var yaml = @"--- type: SilverNeedle.ValueStatModifier name: Hit Points modifier: 1 modifier-type: favored-class "; var option = new FavoredClassOption(yaml.ParseYaml()); var mod = option.CreateModifier(); Assert.Equal("Hit Points", mod.StatisticName); Assert.Equal(1, mod.Modifier); Assert.Equal("favored-class", mod.ModifierType); } } }
27.129032
66
0.655172
[ "MIT" ]
shortlegstudio/silverneedle-web
silverneedle-tests/Characters/FavoredClassOptionTests.cs
841
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _12.Decimal_to_Binary { class Program { public static string Reverse(string s) { char[] arr = s.ToCharArray(); Array.Reverse(arr); return new string(arr); } static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string binary = ""; while (n != 0) { int bit = n%2; binary = binary + bit; n /= 2; } binary = Reverse(binary); Console.WriteLine(binary); } } }
22.8125
50
0.487671
[ "MIT" ]
matir8/TelerikAcademy-2016-2017
Homework/C-Sharp-Fundamentals/06. Loops/06. Loops/12. Decimal to Binary/Program.cs
732
C#
#pragma checksum "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "c25d16dd49781f420c6f098fdc2b0eea93b5d2cc" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_POProvinces_Details), @"mvc.1.0.view", @"/Views/POProvinces/Details.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\_ViewImports.cshtml" using POClubs; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\_ViewImports.cshtml" using POClubs.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c25d16dd49781f420c6f098fdc2b0eea93b5d2cc", @"/Views/POProvinces/Details.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"42de478c9e9a11227ed5c85a9ff21ba4cab00116", @"/Views/_ViewImports.cshtml")] public class Views_POProvinces_Details : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<POClubs.Models.Province> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 3 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" ViewData["Title"] = "Details"; #line default #line hidden #nullable disable WriteLiteral("\r\n<h1>Details</h1>\r\n\r\n<div>\r\n <h4>Province</h4>\r\n <hr />\r\n <dl class=\"row\">\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 14 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayNameFor(model => model.Name)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 17 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayFor(model => model.Name)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 20 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayNameFor(model => model.SalesTaxCode)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 23 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayFor(model => model.SalesTaxCode)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 26 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayNameFor(model => model.SalesTax)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 29 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayFor(model => model.SalesTax)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 32 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayNameFor(model => model.IncludesFederalTax)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 35 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayFor(model => model.IncludesFederalTax)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 38 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayNameFor(model => model.FirstPostalLetter)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 41 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayFor(model => model.FirstPostalLetter)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 44 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayNameFor(model => model.CountryCodeNavigation)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 47 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" Write(Html.DisplayFor(model => model.CountryCodeNavigation.CountryCode)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n </dl>\r\n</div>\r\n<div>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c25d16dd49781f420c6f098fdc2b0eea93b5d2cc8717", async() => { WriteLiteral("Edit"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #nullable restore #line 52 "C:\Users\shittuola\Documents\Training\Prisca Olumoya\Assignment\Club\PriscaClub\PriscaClubs\Views\POProvinces\Details.cshtml" WriteLiteral(Model.ProvinceCode); #line default #line hidden #nullable disable __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(" |\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c25d16dd49781f420c6f098fdc2b0eea93b5d2cc10914", async() => { WriteLiteral("Back to List"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</div>\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<POClubs.Models.Province> Html { get; private set; } } } #pragma warning restore 1591
56.471366
298
0.721117
[ "MIT" ]
larshittu/Club
POClubs/obj/Debug/netcoreapp3.1/Razor/Views/POProvinces/Details.cshtml.g.cs
12,819
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; namespace Instrumental { [CreateAssetMenu(fileName = "UICommon", menuName = "Instrumental/UICommonElements", order = 1)] public class UICommonElements : ScriptableObject { [SerializeField] AudioClip grabClip; [SerializeField] AudioClip itemPlaceClip; [SerializeField] AudioClip errorClip; [SerializeField] AudioClip alertClip; [SerializeField] AudioMixerGroup masterGroup; // control accessors [SerializeField] Dictionary<Controls.ControlType, GameObject> controlPrefabs; public AudioClip GrabClip { get { return grabClip; } } public AudioClip ItemPlaceClip { get { return itemPlaceClip; } } public AudioClip ErrorClip { get { return errorClip; } } public AudioClip AlertClip { get { return alertClip; } } public AudioMixerGroup MasterGroup { get { return masterGroup; } } } }
35.928571
99
0.700795
[ "MIT" ]
jcorvinus/InstrumentalXR
Assets/Instrumental/Scripts/UICommonElements.cs
1,008
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; namespace BookLibrary.Models { public class IndexViewModel { public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } public class ManageLoginsViewModel { public IList<UserLoginInfo> CurrentLogins { get; set; } public IList<AuthenticationDescription> OtherLogins { get; set; } } public class FactorViewModel { public string Purpose { get; set; } } public class SetPasswordViewModel { [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class ChangePasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class AddPhoneNumberViewModel { [Required] [Phone] [Display(Name = "Phone Number")] public string Number { get; set; } } public class VerifyPhoneNumberViewModel { [Required] [Display(Name = "Code")] public string Code { get; set; } [Required] [Phone] [Display(Name = "Phone Number")] public string PhoneNumber { get; set; } } public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } } }
30.872093
110
0.625989
[ "MIT" ]
lyubohd/Software-Technologies
16. ASP.NET - Exercise/BookLibrary/BookLibrary/Models/ManageViewModels.cs
2,657
C#
using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using HttpMultipartParser; using Memorandum.Core; using Memorandum.Core.Domain; using Memorandum.Web.Framework.Utilities; using Memorandum.Web.Middleware; namespace Memorandum.Web.Framework.Backend.FastCGI { internal class FastCGIRequest : IRequest { private NameValueCollection _cookies; private NameValueCollection _postArgs; private NameValueCollection _querySet; private MultipartFormDataParser _parser; public FastCGIRequest(global::FastCGI.Request rawRequest) { RawRequest = rawRequest; } public string Method => RawRequest.GetParameterASCII("REQUEST_METHOD"); public string Path => RawRequest.GetParameterUTF8("DOCUMENT_URI"); public string ContentType => RawRequest.GetParameterASCII("CONTENT_TYPE"); public SessionContext Session { get; set; } public UnitOfWork UnitOfWork { get; set; } /// <summary> /// Current User identifier, stored in session /// </summary> public int? UserId { get { return Session.Get<int>("userId"); } set { Session.Set("userId", value); } } private User _user; /// <summary> /// Lazy loaded User /// </summary> public User User => _user ?? (_user = UnitOfWork.Users.FindById(UserId.GetValueOrDefault())); /// <summary> /// Lazy loaded cookies from request /// </summary> public NameValueCollection Cookies { get { if (_cookies == null && RawRequest.Parameters.ContainsKey("HTTP_COOKIE")) { _cookies = HttpUtilities.ParseQueryString(RawRequest.GetParameterUTF8("HTTP_COOKIE")); } return _cookies; } } /// <summary> /// Lazy loaded query arguments from QUERY_STRING /// </summary> public NameValueCollection QuerySet { get { if (_querySet == null && RawRequest.Parameters.ContainsKey("QUERY_STRING")) { _querySet = HttpUtilities.ParseQueryString(RawRequest.GetParameterASCII("QUERY_STRING")); } return _querySet; } } private MultipartFormDataParser MultipartParser => _parser ?? (_parser = new MultipartFormDataParser(RawRequest.RequestBodyStream)); /// <summary> /// Lazy loaded post arguments /// </summary> public NameValueCollection PostArgs { get { if (_postArgs == null && (Method.Equals("POST") || Method.Equals("PUT")) && RawRequest.RequestBodyStream.Length > 0) { if (ContentType.Contains("multipart")) { _postArgs = new NameValueCollection(); foreach (var par in MultipartParser.Parameters) { _postArgs.Add(par.Name, par.Data); } } else { _postArgs = HttpUtilities.ParseQueryString(Encoding.UTF8.GetString(RawRequest.GetBody())); } } return _postArgs; } } public IEnumerable<FilePart> Files => MultipartParser.Files; private global::FastCGI.Request RawRequest { get; } } }
33.172727
140
0.550562
[ "MIT" ]
bshishov/Memorandum.Net
Memorandum.Web/Framework/Backend/FastCGI/FastCGIRequest.cs
3,651
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PlotMyFace { class Linearization { public static List<Location> GetLocationsFromDither(byte[] pixels, int width, int height) { var locations = new List<Location>(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { var index = y * width + x; byte value = pixels[index]; if (value < 96) { locations.Add(new Location(x, y)); } } } return locations; } } }
24.0625
97
0.450649
[ "MIT" ]
ms-iot/plotmyface
PlotMyFace/PlotMyFace/Linearization.cs
772
C#
 namespace Chloe.DbExpressions { [System.Diagnostics.DebuggerDisplay("Name = {Name}")] public class DbTable { string _name; string _schema; public DbTable(string name) : this(name, null) { } public DbTable(string name, string schema) { this._name = name; this._schema = schema; } public string Name { get { return this._name; } } public string Schema { get { return this._schema; } } } }
22.695652
61
0.538314
[ "MIT" ]
1059444127/QueueSystem
Chloe-master/src/DotNet/Chloe/DbExpressions/DbTable.cs
524
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using UnityEngine; public static class TaskExtensions { public static IEnumerator AsIEnumerator(this Task task) { while (!task.IsCompleted) { yield return null; } if (task.IsFaulted) ExceptionDispatchInfo.Capture(task.Exception).Throw(); } public static IEnumerator<T> AsIEnumerator<T>(this Task<T> task) where T : class { while (!task.IsCompleted) { yield return null; } if (task.IsFaulted) ExceptionDispatchInfo.Capture(task.Exception).Throw(); yield return task.Result; } }
23.194444
84
0.656287
[ "MIT" ]
Baydas/unity-async
Plugins/Async/TaskExtensions.cs
835
C#
using EfCore5InLibraryProject.Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestEfCore5.Data.Mapping { public class CustomerMapping : IEntityTypeConfiguration<Customer> { public void Configure(EntityTypeBuilder<Customer> builder) { builder.HasKey(x => x.Id); builder.HasIndex(x => x.Id).IsUnique(); builder.Property(x => x.Id) .HasColumnType("uuid") .HasDefaultValueSql("uuid_generate_v4()") .IsRequired(); builder.Property(x => x.Name).HasColumnType("varchar(60)"); builder.Property(x => x.RegisterNumber); builder.Property(x => x.Phone).HasColumnType("varchar(15)"); builder.ToTable("Customers"); } } }
31.16129
72
0.645963
[ "MIT" ]
danieljoris/EfCore5InLibraryProject
src/EfCore5InLibraryProject.Data/Mapping/CustomerMapping.cs
968
C#
using System; using System.Collections.Generic; namespace UniLife.Shared.Dto.Admin { public class RoleDto { public string Name { get; set; } public List<string> Permissions { get; set; } public string FormattedPermissions { get { return String.Join(", ", Permissions.ToArray()); } } } }
18.809524
64
0.536709
[ "MIT" ]
ahmetsekmen/UniLife
src/UniLife.Shared/Dto/Admin/RoleDto.cs
397
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore.TestModels.Northwind; using Microsoft.EntityFrameworkCore.TestUtilities.Xunit; using Xunit; // ReSharper disable PossibleMultipleEnumeration // ReSharper disable ReplaceWithSingleCallToCount // ReSharper disable ReplaceWithSingleCallToFirstOrDefault // ReSharper disable ReplaceWithSingleCallToFirst // ReSharper disable AccessToModifiedClosure // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Query { public abstract partial class SimpleQueryTestBase<TFixture> { [ConditionalFact] public virtual void Select_All() { using (var context = CreateContext()) { Assert.False( context .Set<Order>() .Select( o => new ProjectedType { Order = o.OrderID, Customer = o.CustomerID }) .All(p => p.Customer == "ALFKI") ); } } private class ProjectedType { public int Order { get; set; } public string Customer { get; set; } private bool Equals(ProjectedType other) => Equals(Order, other.Order); public override bool Equals(object obj) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() && Equals((ProjectedType)obj); } public override int GetHashCode() => Order.GetHashCode(); } [ConditionalFact] public virtual void GroupBy_tracking_after_dispose() { List<IGrouping<string, Order>> groups; using (var context = CreateContext()) { groups = context.Orders.GroupBy(o => o.CustomerID).ToList(); } groups[0].First(); } [ConditionalFact] public virtual void Sum_with_no_arg() { AssertSingleResult<Order>(os => os.Select(o => o.OrderID).Sum()); } [ConditionalFact] public virtual void Sum_with_no_data_nullable() { AssertSingleResult<Order>(os => os.Where(o => o.OrderID < 0).Select(o => (int?)o.OrderID).Sum()); } [ConditionalFact] public virtual void Sum_with_binary_expression() { AssertSingleResult<Order>(os => os.Select(o => o.OrderID * 2).Sum()); } [ConditionalFact] public virtual void Sum_with_no_arg_empty() { AssertSingleResult<Order>(os => os.Where(o => o.OrderID == 42).Select(o => o.OrderID).Sum()); } [ConditionalFact] public virtual void Sum_with_arg() { AssertSingleResult<Order>(os => os.Sum(o => o.OrderID)); } [ConditionalFact] public virtual void Sum_with_arg_expression() { AssertSingleResult<Order>(os => os.Sum(o => o.OrderID + o.OrderID)); } [ConditionalFact] public virtual void Sum_with_division_on_decimal() { AssertSingleResult<OrderDetail>( ods => ods.Sum(od => od.Quantity / 2.09m), asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); } [ConditionalFact] public virtual void Sum_with_division_on_decimal_no_significant_digits() { AssertSingleResult<OrderDetail>( ods => ods.Sum(od => od.Quantity / 2m), asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); } [ConditionalFact] public virtual void Sum_with_coalesce() { AssertSingleResult<Product>(ps => ps.Where(p => p.ProductID < 40).Sum(p => p.UnitPrice ?? 0)); } [ConditionalFact] public virtual void Sum_over_subquery_is_client_eval() { AssertSingleResult<Customer>(cs => cs.Sum(c => c.Orders.Sum(o => o.OrderID))); } [ConditionalFact] public virtual void Sum_on_float_column() { AssertSingleResult<OrderDetail>(ods => ods.Where(od => od.ProductID == 1).Sum(od => od.Discount)); } [ConditionalFact] public virtual void Sum_on_float_column_in_subquery() { AssertQuery<Order>( os => os.Where(o => o.OrderID < 10300).Select(o => new { o.OrderID, Sum = o.OrderDetails.Sum(od => od.Discount) }), e => e.OrderID); } [ConditionalFact] public virtual void Average_with_no_arg() { AssertSingleResult<Order>(os => os.Select(o => o.OrderID).Average()); } [ConditionalFact] public virtual void Average_with_binary_expression() { AssertSingleResult<Order>(os => os.Select(o => o.OrderID * 2).Average()); } [ConditionalFact] public virtual void Average_with_arg() { AssertSingleResult<Order>(os => os.Average(o => o.OrderID)); } [ConditionalFact] public virtual void Average_with_arg_expression() { AssertSingleResult<Order>(os => os.Average(o => o.OrderID + o.OrderID)); } [ConditionalFact] public virtual void Average_with_division_on_decimal() { AssertSingleResult<OrderDetail>( ods => ods.Average(od => od.Quantity / 2.09m), asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); } [ConditionalFact] public virtual void Average_with_division_on_decimal_no_significant_digits() { AssertSingleResult<OrderDetail>( ods => ods.Average(od => od.Quantity / 2m), asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); } [ConditionalFact] public virtual void Average_with_coalesce() { AssertSingleResult<Product>( ps => ps.Where(p => p.ProductID < 40).Average(p => p.UnitPrice ?? 0), asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); } [ConditionalFact] public virtual void Average_over_subquery_is_client_eval() { AssertSingleResult<Customer>(cs => cs.Average(c => c.Orders.Sum(o => o.OrderID))); } [ConditionalFact] public virtual void Average_on_float_column() { AssertSingleResult<OrderDetail>(ods => ods.Where(od => od.ProductID == 1).Average(od => od.Discount)); } [ConditionalFact] public virtual void Average_on_float_column_in_subquery() { AssertQuery<Order>( os => os.Where(o => o.OrderID < 10300).Select(o => new { o.OrderID, Sum = o.OrderDetails.Average(od => od.Discount) }), e => e.OrderID); } [ConditionalFact] public virtual void Average_on_float_column_in_subquery_with_cast() { AssertQuery<Order>( os => os.Where(o => o.OrderID < 10300) .Select(o => new { o.OrderID, Sum = o.OrderDetails.Average(od => (float?)od.Discount) }), e => e.OrderID); } [ConditionalFact] public virtual void Min_with_no_arg() { AssertSingleResult<Order>(os => os.Select(o => o.OrderID).Min()); } [ConditionalFact] public virtual void Min_with_arg() { AssertSingleResult<Order>(os => os.Min(o => o.OrderID)); } [ConditionalFact] public virtual void Min_no_data() { using (var context = CreateContext()) { Assert.Throws<InvalidOperationException>(() => context.Orders.Where(o => o.OrderID == -1).Min(o => o.OrderID)); } } [ConditionalFact] public virtual void Min_no_data_subquery() { using (var context = CreateContext()) { Assert.Throws<InvalidOperationException>( () => context.Customers.Select(c => c.Orders.Where(o => o.OrderID == -1).Min(o => o.OrderID)).ToList()); } } [ConditionalFact] public virtual void Max_no_data() { using (var context = CreateContext()) { Assert.Throws<InvalidOperationException>(() => context.Orders.Where(o => o.OrderID == -1).Max(o => o.OrderID)); } } [ConditionalFact] public virtual void Max_no_data_subquery() { using (var context = CreateContext()) { Assert.Throws<InvalidOperationException>( () => context.Customers.Select(c => c.Orders.Where(o => o.OrderID == -1).Max(o => o.OrderID)).ToList()); } } [ConditionalFact] public virtual void Average_no_data() { using (var context = CreateContext()) { Assert.Throws<InvalidOperationException>(() => context.Orders.Where(o => o.OrderID == -1).Average(o => o.OrderID)); } } [ConditionalFact] public virtual void Average_no_data_subquery() { using (var context = CreateContext()) { Assert.Throws<InvalidOperationException>( () => context.Customers.Select(c => c.Orders.Where(o => o.OrderID == -1).Average(o => o.OrderID)).ToList()); } } [ConditionalFact] public virtual void Min_with_coalesce() { AssertSingleResult<Product>(ps => ps.Where(p => p.ProductID < 40).Min(p => p.UnitPrice ?? 0)); } [ConditionalFact] public virtual void Min_over_subquery_is_client_eval() { AssertSingleResult<Customer>(cs => cs.Min(c => c.Orders.Sum(o => o.OrderID))); } [ConditionalFact] public virtual void Max_with_no_arg() { AssertSingleResult<Order>(os => os.Select(o => o.OrderID).Max()); } [ConditionalFact] public virtual void Max_with_arg() { AssertSingleResult<Order>(os => os.Max(o => o.OrderID)); } [ConditionalFact] public virtual void Max_with_coalesce() { AssertSingleResult<Product>(ps => ps.Where(p => p.ProductID < 40).Max(p => p.UnitPrice ?? 0)); } [ConditionalFact] public virtual void Max_over_subquery_is_client_eval() { AssertSingleResult<Customer>(cs => cs.Max(c => c.Orders.Sum(o => o.OrderID))); } [ConditionalFact] public virtual void Count_with_no_predicate() { AssertSingleResult<Order>(os => os.Count()); } [ConditionalFact] public virtual void Count_with_predicate() { AssertSingleResult<Order>(os => os.Count(o => o.CustomerID == "ALFKI")); } [ConditionalFact] public virtual void Count_with_order_by() { AssertSingleResult<Order>(os => os.OrderBy(o => o.CustomerID).Count()); } [ConditionalFact] public virtual void Where_OrderBy_Count() { AssertSingleResult<Order>(os => os.Where(o => o.CustomerID == "ALFKI").OrderBy(o => o.OrderID).Count()); } [ConditionalFact] public virtual void OrderBy_Where_Count() { AssertSingleResult<Order>(os => os.OrderBy(o => o.OrderID).Where(o => o.CustomerID == "ALFKI").Count()); } [ConditionalFact] public virtual void OrderBy_Count_with_predicate() { AssertSingleResult<Order>(os => os.OrderBy(o => o.OrderID).Count(o => o.CustomerID == "ALFKI")); } [ConditionalFact] public virtual void OrderBy_Where_Count_with_predicate() { AssertSingleResult<Order>(os => os.OrderBy(o => o.OrderID).Where(o => o.OrderID > 10).Count(o => o.CustomerID != "ALFKI")); } [ConditionalFact] public virtual void Where_OrderBy_Count_client_eval() { AssertSingleResult<Order>(os => os.Where(o => ClientEvalPredicate(o)).OrderBy(o => ClientEvalSelectorStateless()).Count()); } [ConditionalFact] public virtual void Where_OrderBy_Count_client_eval_mixed() { AssertSingleResult<Order>(os => os.Where(o => o.OrderID > 10).OrderBy(o => ClientEvalPredicate(o)).Count()); } [ConditionalFact] public virtual void OrderBy_Where_Count_client_eval() { AssertSingleResult<Order>(os => os.OrderBy(o => ClientEvalSelectorStateless()).Where(o => ClientEvalPredicate(o)).Count()); } [ConditionalFact] public virtual void OrderBy_Where_Count_client_eval_mixed() { AssertSingleResult<Order>(os => os.OrderBy(o => o.OrderID).Where(o => ClientEvalPredicate(o)).Count()); } [ConditionalFact] public virtual void OrderBy_Count_with_predicate_client_eval() { AssertSingleResult<Order>(os => os.OrderBy(o => ClientEvalSelectorStateless()).Count(o => ClientEvalPredicate(o))); } [ConditionalFact] public virtual void OrderBy_Count_with_predicate_client_eval_mixed() { AssertSingleResult<Order>(os => os.OrderBy(o => o.OrderID).Count(o => ClientEvalPredicate(o))); } [ConditionalFact] public virtual void OrderBy_Where_Count_with_predicate_client_eval() { AssertSingleResult<Order>(os => os.OrderBy(o => ClientEvalSelectorStateless()).Where(o => ClientEvalPredicate(o)).Count(o => ClientEvalPredicate(o))); } [ConditionalFact] public virtual void OrderBy_Where_Count_with_predicate_client_eval_mixed() { AssertSingleResult<Order>(os => os.OrderBy(o => o.OrderID).Where(o => ClientEvalPredicate(o)).Count(o => o.CustomerID != "ALFKI")); } [ConditionalFact] public virtual void OrderBy_client_Take() { AssertQuery<Employee>(es => es.OrderBy(o => ClientEvalSelectorStateless()).Take(10), entryCount: 9); } public static bool ClientEvalPredicateStateless() => true; protected static bool ClientEvalPredicate(Order order) => order.OrderID > 10000; private static int ClientEvalSelectorStateless() => 42; #if Test20 protected internal int ClientEvalSelector(Order order) => order.EmployeeID % 10 ?? 0; #else protected internal uint ClientEvalSelector(Order order) => order.EmployeeID % 10 ?? 0; #endif [ConditionalFact] public virtual void Distinct() { AssertQuery<Customer>( cs => cs.Distinct(), entryCount: 91); } [ConditionalFact] public virtual void Distinct_Scalar() { AssertQuery<Customer>( cs => cs.Select(c => c.City).Distinct()); } [ConditionalFact] public virtual void OrderBy_Distinct() { AssertQuery<Customer>( cs => cs.OrderBy(c => c.CustomerID).Select(c => c.City).Distinct()); } [ConditionalFact] public virtual void Distinct_OrderBy() { AssertQuery<Customer>( cs => cs.Select(c => c.Country).Distinct().OrderBy(c => c), assertOrder: true); } [ConditionalFact] public virtual void Distinct_OrderBy2() { AssertQuery<Customer>( cs => cs.Distinct().OrderBy(c => c.CustomerID), cs => cs.Distinct().OrderBy(c => c.CustomerID, StringComparer.Ordinal), assertOrder: true, entryCount: 91); } [ConditionalFact] public virtual void Distinct_OrderBy3() { AssertQuery<Customer>( cs => cs.Select(c => new { c.CustomerID }).Distinct().OrderBy(a => a.CustomerID), cs => cs.Select(c => new { c.CustomerID }).Distinct().OrderBy(a => a.CustomerID, StringComparer.Ordinal), assertOrder: true); } [ConditionalFact] public virtual void Distinct_Count() { AssertSingleResult<Customer>( cs => cs.Distinct().Count()); } [ConditionalFact] public virtual void Select_Select_Distinct_Count() { AssertSingleResult<Customer>( cs => cs.Select(c => c.City).Select(c => c).Distinct().Count()); } [ConditionalFact] public virtual void Single_Throws() { Assert.Throws<InvalidOperationException>( () => AssertSingleResult<Customer>(cs => cs.Single())); } [ConditionalFact] public virtual void Single_Predicate() { AssertSingleResult<Customer>( cs => cs.Single(c => c.CustomerID == "ALFKI"), entryCount: 1); } [ConditionalFact] public virtual void Where_Single() { AssertSingleResult<Customer>( // ReSharper disable once ReplaceWithSingleCallToSingle cs => cs.Where(c => c.CustomerID == "ALFKI").Single(), entryCount: 1); } [ConditionalFact] public virtual void SingleOrDefault_Throws() { Assert.Throws<InvalidOperationException>( () => AssertSingleResult<Customer>( cs => cs.SingleOrDefault())); } [ConditionalFact] public virtual void SingleOrDefault_Predicate() { AssertSingleResult<Customer>( cs => cs.SingleOrDefault(c => c.CustomerID == "ALFKI"), entryCount: 1); } [ConditionalFact] public virtual void Where_SingleOrDefault() { AssertSingleResult<Customer>( // ReSharper disable once ReplaceWithSingleCallToSingleOrDefault cs => cs.Where(c => c.CustomerID == "ALFKI").SingleOrDefault(), entryCount: 1); } [ConditionalFact] public virtual void First() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).First(), entryCount: 1); } [ConditionalFact] public virtual void First_Predicate() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).First(c => c.City == "London"), entryCount: 1); } [ConditionalFact] public virtual void Where_First() { AssertSingleResult<Customer>( // ReSharper disable once ReplaceWithSingleCallToFirst cs => cs.OrderBy(c => c.ContactName).Where(c => c.City == "London").First(), entryCount: 1); } [ConditionalFact] public virtual void FirstOrDefault() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).FirstOrDefault(), entryCount: 1); } [ConditionalFact] public virtual void FirstOrDefault_Predicate() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).FirstOrDefault(c => c.City == "London"), entryCount: 1); } [ConditionalFact] public virtual void Where_FirstOrDefault() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).Where(c => c.City == "London").FirstOrDefault(), entryCount: 1); } [ConditionalFact] public virtual void FirstOrDefault_inside_subquery_gets_server_evaluated() { AssertQuery<Customer>( cs => cs.Where(c => c.CustomerID == "ALFKI" && c.Orders.Where(o => o.CustomerID == "ALFKI").FirstOrDefault().CustomerID == "ALFKI"), entryCount: 1); } [ConditionalFact] public virtual void First_inside_subquery_gets_client_evaluated() { AssertQuery<Customer>( cs => cs.Where(c => c.CustomerID == "ALFKI" && c.Orders.Where(o => o.CustomerID == "ALFKI").First().CustomerID == "ALFKI"), entryCount: 1); } [ConditionalFact] public virtual void Last() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).Last(), entryCount: 1); } [ConditionalFact] public virtual void Last_when_no_order_by() { AssertSingleResult<Customer>( // ReSharper disable once ReplaceWithSingleCallToLast cs => cs.Where(c => c.CustomerID == "ALFKI").Last(), entryCount: 1); } [ConditionalFact] public virtual void Last_Predicate() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).Last(c => c.City == "London"), entryCount: 1); } [ConditionalFact] public virtual void Where_Last() { AssertSingleResult<Customer>( // ReSharper disable once ReplaceWithSingleCallToLast cs => cs.OrderBy(c => c.ContactName).Where(c => c.City == "London").Last(), entryCount: 1); } [ConditionalFact] public virtual void LastOrDefault() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).LastOrDefault(), entryCount: 1); } [ConditionalFact] public virtual void LastOrDefault_Predicate() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.ContactName).LastOrDefault(c => c.City == "London"), entryCount: 1); } [ConditionalFact] public virtual void Where_LastOrDefault() { AssertSingleResult<Customer>( // ReSharper disable once ReplaceWithSingleCallToLastOrDefault cs => cs.OrderBy(c => c.ContactName).Where(c => c.City == "London").LastOrDefault(), entryCount: 1); } [ConditionalFact] public virtual void Contains_with_subquery() { AssertQuery<Customer, Order>( (cs, os) => cs.Where(c => os.Select(o => o.CustomerID).Contains(c.CustomerID)), entryCount: 89); } [ConditionalFact] public virtual void Contains_with_local_array_closure() { var ids = new[] { "ABCDE", "ALFKI" }; AssertQuery<Customer>( cs => cs.Where(c => ids.Contains(c.CustomerID)), entryCount: 1); ids = new[] { "ABCDE" }; AssertQuery<Customer>( cs => cs.Where(c => ids.Contains(c.CustomerID))); } [ConditionalFact] public virtual void Contains_with_subquery_and_local_array_closure() { var ids = new[] { "London", "Buenos Aires" }; AssertQuery<Customer>( cs => cs.Where( c => cs.Where(c1 => ids.Contains(c1.City)).Any(e => e.CustomerID == c.CustomerID)), entryCount: 9); ids = new[] { "London" }; AssertQuery<Customer>( cs => cs.Where( c => cs.Where(c1 => ids.Contains(c1.City)).Any(e => e.CustomerID == c.CustomerID)), entryCount: 6); } [ConditionalFact] public virtual void Contains_with_local_int_array_closure() { #if Test20 var ids = new int[] { 0, 1 }; #else var ids = new uint[] { 0, 1 }; #endif AssertQuery<Employee>( es => es.Where(e => ids.Contains(e.EmployeeID)), entryCount: 1); #if Test20 ids = new int[] { 0 }; #else ids = new uint[] { 0 }; #endif AssertQuery<Employee>( es => es.Where(e => ids.Contains(e.EmployeeID))); } [ConditionalFact] public virtual void Contains_with_local_nullable_int_array_closure() { #if Test20 var ids = new int?[] { 0, 1 }; #else var ids = new uint?[] { 0, 1 }; #endif AssertQuery<Employee>( es => es.Where(e => ids.Contains(e.EmployeeID)), entryCount: 1); #if Test20 ids = new int?[] { 0 }; #else ids = new uint?[] { 0 }; #endif AssertQuery<Employee>( es => es.Where(e => ids.Contains(e.EmployeeID))); } [ConditionalFact] public virtual void Contains_with_local_array_inline() { AssertQuery<Customer>( cs => cs.Where(c => new[] { "ABCDE", "ALFKI" }.Contains(c.CustomerID)), entryCount: 1); } [ConditionalFact] public virtual void Contains_with_local_list_closure() { var ids = new List<string> { "ABCDE", "ALFKI" }; AssertQuery<Customer>( cs => cs.Where(c => ids.Contains(c.CustomerID)), entryCount: 1); } [ConditionalFact] public virtual void Contains_with_local_list_inline() { AssertQuery<Customer>( cs => cs.Where(c => new List<string> { "ABCDE", "ALFKI" }.Contains(c.CustomerID)), entryCount: 1); } [ConditionalFact] public virtual void Contains_with_local_list_inline_closure_mix() { var id = "ALFKI"; AssertQuery<Customer>( cs => cs.Where(c => new List<string> { "ABCDE", id }.Contains(c.CustomerID)), entryCount: 1); id = "ANATR"; AssertQuery<Customer>( cs => cs.Where(c => new List<string> { "ABCDE", id }.Contains(c.CustomerID)), entryCount: 1); } [ConditionalFact] public virtual void Contains_with_local_collection_false() { string[] ids = { "ABCDE", "ALFKI" }; AssertQuery<Customer>( cs => cs.Where(c => !ids.Contains(c.CustomerID)), entryCount: 90); } [ConditionalFact] public virtual void Contains_with_local_collection_complex_predicate_and() { string[] ids = { "ABCDE", "ALFKI" }; AssertQuery<Customer>( cs => cs.Where(c => (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE") && ids.Contains(c.CustomerID)), entryCount: 1); } [ConditionalFact] public virtual void Contains_with_local_collection_complex_predicate_or() { string[] ids = { "ABCDE", "ALFKI" }; AssertQuery<Customer>( cs => cs.Where(c => ids.Contains(c.CustomerID) || (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE")), entryCount: 1); } [ConditionalFact] public virtual void Contains_with_local_collection_complex_predicate_not_matching_ins1() { string[] ids = { "ABCDE", "ALFKI" }; AssertQuery<Customer>( cs => cs.Where(c => (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE") || !ids.Contains(c.CustomerID)), entryCount: 91); } [ConditionalFact] public virtual void Contains_with_local_collection_complex_predicate_not_matching_ins2() { string[] ids = { "ABCDE", "ALFKI" }; AssertQuery<Customer>( cs => cs.Where(c => ids.Contains(c.CustomerID) && (c.CustomerID != "ALFKI" && c.CustomerID != "ABCDE"))); } [ConditionalFact] public virtual void Contains_with_local_collection_sql_injection() { string[] ids = { "ALFKI", "ABC')); GO; DROP TABLE Orders; GO; --" }; AssertQuery<Customer>( cs => cs.Where(c => ids.Contains(c.CustomerID) || (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE")), entryCount: 1); } [ConditionalFact] public virtual void Contains_with_local_collection_empty_closure() { var ids = new string[0]; AssertQuery<Customer>( cs => cs.Where(c => ids.Contains(c.CustomerID))); } [ConditionalFact] public virtual void Contains_with_local_collection_empty_inline() { AssertQuery<Customer>( cs => cs.Where(c => !(new List<string>().Contains(c.CustomerID))), entryCount: 91); } [ConditionalFact] public virtual void Contains_top_level() { AssertSingleResult<Customer>(cs => cs.Select(c => c.CustomerID).Contains("ALFKI")); } [ConditionalFact] public virtual void Contains_with_local_tuple_array_closure() { var ids = new[] { Tuple.Create(1, 2), Tuple.Create(10248, 11) }; AssertQuery<OrderDetail>( od => od.Where(o => ids.Contains(new Tuple<int, int>(o.OrderID, o.ProductID))), entryCount: 1); ids = new[] { Tuple.Create(1, 2) }; AssertQuery<OrderDetail>( od => od.Where(o => ids.Contains(new Tuple<int, int>(o.OrderID, o.ProductID)))); } [ConditionalFact] public virtual void Contains_with_local_anonymous_type_array_closure() { var ids = new[] { new { Id1 = 1, Id2 = 2 }, new { Id1 = 10248, Id2 = 11 } }; AssertQuery<OrderDetail>( od => od.Where(o => ids.Contains(new { Id1 = o.OrderID, Id2 = o.ProductID })), entryCount: 1); ids = new[] { new { Id1 = 1, Id2 = 2 } }; AssertQuery<OrderDetail>( od => od.Where(o => ids.Contains(new { Id1 = o.OrderID, Id2 = o.ProductID }))); } [ConditionalFact] public virtual void OfType_Select() { using (var context = CreateContext()) { Assert.Equal( "Reims", context.Set<Order>() .OfType<Order>() .OrderBy(o => o.OrderID) .Select(o => o.Customer.City) .First()); } } [ConditionalFact] public virtual void OfType_Select_OfType_Select() { using (var context = CreateContext()) { Assert.Equal( "Reims", context.Set<Order>() .OfType<Order>() .Select(o => o) .OfType<Order>() .OrderBy(o => o.OrderID) .Select(o => o.Customer.City) .First()); } } [ConditionalFact] public virtual void Concat_dbset() { using (var context = CreateContext()) { var query = context.Set<Customer>() .Where(c => c.City == "México D.F.") .Concat(context.Set<Customer>()) .ToList(); Assert.Equal(96, query.Count); } } [ConditionalFact] public virtual void Concat_simple() { using (var context = CreateContext()) { var query = context.Set<Customer>() .Where(c => c.City == "México D.F.") .Concat( context.Set<Customer>() .Where(s => s.ContactTitle == "Owner")) .ToList(); Assert.Equal(22, query.Count); } } [ConditionalFact] public virtual void Concat_nested() { AssertQuery<Customer>( cs => cs.Where(c => c.City == "México D.F.") .Concat(cs.Where(s => s.City == "Berlin")) .Concat(cs.Where(e => e.City == "London")), entryCount: 12); } [ConditionalFact] public virtual void Concat_non_entity() { using (var context = CreateContext()) { var query = context.Set<Customer>() .Where(c => c.City == "México D.F.") .Select(c => c.CustomerID) .Concat( context.Set<Customer>() .Where(s => s.ContactTitle == "Owner") .Select(c => c.CustomerID)) .ToList(); Assert.Equal(22, query.Count); } } [ConditionalFact] public virtual void Except_dbset() { AssertQuery<Customer>( cs => cs.Where(s => s.ContactTitle == "Owner").Except(cs)); } [ConditionalFact] public virtual void Except_simple() { AssertQuery<Customer>( cs => cs.Where(s => s.ContactTitle == "Owner") .Except(cs.Where(c => c.City == "México D.F.")), entryCount: 14); } [ConditionalFact] public virtual void Except_nested() { AssertQuery<Customer>( cs => cs.Where(s => s.ContactTitle == "Owner") .Except(cs.Where(s => s.City == "México D.F.")) .Except(cs.Where(e => e.City == "Seattle")), entryCount: 13); } [ConditionalFact] public virtual void Except_non_entity() { using (var context = CreateContext()) { var query = context.Set<Customer>() .Where(s => s.ContactTitle == "Owner") .Select(c => c.CustomerID) .Except( context.Set<Customer>() .Where(c => c.City == "México D.F.") .Select(c => c.CustomerID)) .ToList(); Assert.Equal(14, query.Count); } } [ConditionalFact] public virtual void Intersect_dbset() { AssertQuery<Customer>( cs => cs.Where(c => c.City == "México D.F.").Intersect(cs), entryCount: 5); } [ConditionalFact] public virtual void Intersect_simple() { AssertQuery<Customer>( cs => cs.Where(c => c.City == "México D.F.") .Intersect(cs.Where(s => s.ContactTitle == "Owner")), entryCount: 3); } [ConditionalFact] public virtual void Intersect_nested() { AssertQuery<Customer>( cs => cs.Where(c => c.City == "México D.F.") .Intersect(cs.Where(s => s.ContactTitle == "Owner")) .Intersect(cs.Where(e => e.Fax != null)), entryCount: 1); } [ConditionalFact] public virtual void Intersect_non_entity() { using (var context = CreateContext()) { var query = context.Set<Customer>() .Where(c => c.City == "México D.F.") .Select(c => c.CustomerID) .Intersect( context.Set<Customer>() .Where(s => s.ContactTitle == "Owner") .Select(c => c.CustomerID)) .ToList(); Assert.Equal(3, query.Count); } } [ConditionalFact] public virtual void Union_dbset() { AssertQuery<Customer>( cs => cs.Where(s => s.ContactTitle == "Owner").Union(cs), entryCount: 91); } [ConditionalFact] public virtual void Union_simple() { AssertQuery<Customer>( cs => cs.Where(s => s.ContactTitle == "Owner") .Union(cs.Where(c => c.City == "México D.F.")), entryCount: 19); } [ConditionalFact] public virtual void Union_nested() { AssertQuery<Customer>( cs => cs.Where(s => s.ContactTitle == "Owner") .Union(cs.Where(s => s.City == "México D.F.")) .Union(cs.Where(e => e.City == "London")), entryCount: 25); } [ConditionalFact] public virtual void Union_non_entity() { using (var context = CreateContext()) { var query = context.Set<Customer>() .Where(s => s.ContactTitle == "Owner") .Select(c => c.CustomerID) .Union( context.Set<Customer>() .Where(c => c.City == "México D.F.") .Select(c => c.CustomerID)) .ToList(); Assert.Equal(19, query.Count); } } [ConditionalFact] public virtual void Average_with_non_matching_types_in_projection_doesnt_produce_second_explicit_cast() { AssertSingleResult<Order>( os => os .Where(o => o.CustomerID.StartsWith("A")) .OrderBy(o => o.OrderID) .Select(o => (long)o.OrderID).Average()); } [ConditionalFact] public virtual void Max_with_non_matching_types_in_projection_introduces_explicit_cast() { AssertSingleResult<Order>( os => os .Where(o => o.CustomerID.StartsWith("A")) .OrderBy(o => o.OrderID) .Select(o => (long)o.OrderID).Max()); } [ConditionalFact] public virtual void Min_with_non_matching_types_in_projection_introduces_explicit_cast() { AssertSingleResult<Order>( os => os .Where(o => o.CustomerID.StartsWith("A")) .Select(o => (long)o.OrderID).Min()); } [ConditionalFact] public virtual void OrderBy_Take_Last_gives_correct_result() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.CustomerID) .Take(20) .Last(), entryCount: 1); } [ConditionalFact] public virtual void OrderBy_Skip_Last_gives_correct_result() { AssertSingleResult<Customer>( cs => cs.OrderBy(c => c.CustomerID) .Skip(20) .Last(), entryCount: 1); } [ConditionalFact] public virtual void Contains_over_entityType_should_rewrite_to_identity_equality() { using (var context = CreateContext()) { var query = context.Orders.Where(o => o.CustomerID == "VINET") .Contains(context.Orders.Single(o => o.OrderID == 10248)); Assert.True(query); } } [ConditionalFact] public virtual void Contains_over_entityType_should_materialize_when_composite() { using (var context = CreateContext()) { var query = context.OrderDetails.Where(o => o.ProductID == 42) .Contains(context.OrderDetails.First(o => o.OrderID == 10248 && o.ProductID == 42)); Assert.True(query); } } [ConditionalFact] public virtual void Paging_operation_on_string_doesnt_issue_warning() { using (var context = CreateContext()) { var query = context.Customers.Select(c => c.CustomerID.FirstOrDefault()).ToList(); Assert.Equal(91, query.Count); } } [ConditionalFact] public virtual void Project_constant_Sum() { AssertSingleResult<Employee>(es => es.Sum(e => 1)); } } }
33.334133
162
0.509772
[ "Apache-2.0" ]
rahulghildiyal/core
src/EFCore.Specification.Tests/Query/SimpleQueryTestBase.ResultOperators.cs
41,717
C#
using OpenQA.Selenium.Appium.Interfaces; using OpenQA.Selenium.Appium.iOS; using OpenQA.Selenium.Appium.PageObjects.Attributes; using SeleniumExtras.PageObjects; using System.Collections.Generic; namespace Appium.Integration.Tests.PageObjects { public class IOSPageObjectChecksAttributeMixOnNativeApp { ///////////////////////////////////////////////////////////////// [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]")] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/text1\")")] private IMobileElement<IOSElement> testMobileElement; [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]")] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/text1\")")] private IList<IOSElement> testMobileElements; [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]")] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/text1\")")] private IMobileElement<IOSElement> TestMobileElement { set; get; } [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]")] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/text1\")")] private IList<IOSElement> TestMobileElements { set; get; } [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(ClassName = "UIAUAIFakeClass", Priority = 1)] [FindsByIOSUIAutomation(ID = "FakeID", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/fakeId\")", Priority = 1)] [FindsByAndroidUIAutomator(ID = "FakeId", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IMobileElement<IOSElement> testMultipleElement; [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(ClassName = "UIAUAIFakeClass", Priority = 1)] [FindsByIOSUIAutomation(ID = "FakeID", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/fakeId\")", Priority = 1)] [FindsByAndroidUIAutomator(ID = "FakeId", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IList<IOSElement> testMultipleElements; ///////////////////////////////////////////////////////////////// [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(ClassName = "UIAUAIFakeClass", Priority = 1)] [FindsByIOSUIAutomation(ID = "FakeID", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/fakeId\")", Priority = 1)] [FindsByAndroidUIAutomator(ID = "FakeId", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IMobileElement<IOSElement> TestMultipleFindByElementProperty { set; get; } [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(ClassName = "UIAUAIFakeClass", Priority = 1)] [FindsByIOSUIAutomation(ID = "FakeID", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/fakeId\")", Priority = 1)] [FindsByAndroidUIAutomator(ID = "FakeId", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IList<IOSElement> MultipleFindByElementsProperty { set; get; } [FindsByAll] [MobileFindsByAll(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(ClassName = "UIAButton", Priority = 1)] //Equals method of RemoteWebElement is not consistent for mobile apps //The second selector won't be added till the problem is worked out [FindsByAndroidUIAutomator(ID = "android:id/text1", Priority = 1)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 1)] private IMobileElement<IOSElement> matchedToAllLocatorsElement; [FindsByAll] [MobileFindsByAll(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(ClassName = "UIAButton", Priority = 1)] //Equals method of RemoteWebElement is not consistent for mobile apps //The second selector won't be added till the problem is worked out [FindsByAndroidUIAutomator(ID = "android:id/text1", Priority = 1)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 1)] private IList<IOSElement> matchedToAllLocatorsElements; ///////////////////////////////////////////////////////////////// [FindsByAll] [MobileFindsByAll(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(ClassName = "UIAButton", Priority = 1)] //Equals method of RemoteWebElement is not consistent for mobile apps //The second selector won't be added till the problem is worked out [FindsByAndroidUIAutomator(ID = "android:id/text1", Priority = 1)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 1)] private IMobileElement<IOSElement> TestMatchedToAllLocatorsElementProperty { set; get; } [FindsByAll] [MobileFindsByAll(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(ClassName = "UIAButton", Priority = 1)] //Equals method of RemoteWebElement is not consistent for mobile apps //The second selector won't be added till the problem is worked out [FindsByAndroidUIAutomator(ID = "android:id/text1", Priority = 1)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 1)] private IList<IOSElement> TestMatchedToAllLocatorsElementsProperty { set; get; } ////////////////////////////////////////////////////////////////////////// public string GetMobileElementText() { return testMobileElement.Text; } public int GetMobileElementSize() { return testMobileElements.Count; } public string GetMobileElementPropertyText() { return TestMobileElement.Text; } public int GetMobileElementPropertySize() { return TestMobileElements.Count; } ////////////////////////////////////////////////////////////////////////// public string GetMultipleFindByElementText() { return testMultipleElement.Text; } public int GetMultipleFindByElementSize() { return testMultipleElements.Count; } public string GetMultipleFindByElementPropertyText() { return TestMultipleFindByElementProperty.Text; } public int GetMultipleFindByElementPropertySize() { return MultipleFindByElementsProperty.Count; } ////////////////////////////////////////////////////////////////////////// public string GetMatchedToAllLocatorsElementText() { return matchedToAllLocatorsElement.Text; } public int GetMatchedToAllLocatorsElementSize() { return matchedToAllLocatorsElements.Count; } public string GetMatchedToAllLocatorsElementPropertyText() { return TestMatchedToAllLocatorsElementProperty.Text; } public int GetMatchedToAllLocatorsElementPropertySize() { return TestMatchedToAllLocatorsElementsProperty.Count; } } }
51.413613
109
0.629837
[ "Apache-2.0" ]
ArmyMedalMei/appium-dotnet-driver
integration_tests/PageObjects/IOSPageObjectChecksAttributeMixOnNativeApp.cs
9,822
C#
using UnityEngine; namespace HG.DeferredDecals { [System.Flags] public enum DecalFeature { Diffuse = 1, Normal = 2, Smoothness = 4, Emission = 8 } [ExecuteAlways] [AddComponentMenu("Effects/Decal")] public class Decal : MonoBehaviour { private Bounds bounds; private Vector3[] boundPositions = new Vector3[8]; public Bounds DecalBounds { get { return bounds; } } public Material DecalMaterial { get => m_Material; } public int Layer { get => m_Layer; } [Range(0, 49)] [SerializeField] int m_Layer = 20; [SerializeField] DecalFeature m_FeatureSet = (DecalFeature)~0; //TODO: Make this matter [SerializeField] Material m_Material = null; public void OnEnable() { if (!m_Material) return; DeferredDecalSystem.Instance?.AddDecal(this); RecalculateBounds(); } private void Start() { if (!m_Material) return; DeferredDecalSystem.Instance?.AddDecal(this); } public void RecalculateBounds() { Vector3 scale = transform.lossyScale; Vector3 position = transform.position; Quaternion quat = Quaternion.identity; quat.SetLookRotation(transform.forward, Vector3.Cross(transform.forward, transform.right)); boundPositions[0] = position + quat * new Vector3( scale.x * 0.5f, scale.y * 0.5f, scale.z * 0.5f); boundPositions[1] = position + quat * new Vector3(-scale.x * 0.5f, scale.y * 0.5f, scale.z * 0.5f); boundPositions[2] = position + quat * new Vector3( scale.x * 0.5f, -scale.y * 0.5f, scale.z * 0.5f); boundPositions[3] = position + quat * new Vector3( scale.x * 0.5f, scale.y * 0.5f, -scale.z * 0.5f); boundPositions[4] = position + quat * new Vector3(-scale.x * 0.5f, -scale.y * 0.5f, scale.z * 0.5f); boundPositions[5] = position + quat * new Vector3( scale.x * 0.5f, -scale.y * 0.5f, -scale.z * 0.5f); boundPositions[6] = position + quat * new Vector3(-scale.x * 0.5f, scale.y * 0.5f, -scale.z * 0.5f); boundPositions[7] = position + quat * new Vector3(-scale.x * 0.5f, -scale.y * 0.5f, -scale.z * 0.5f); bounds = GeometryUtility.CalculateBounds(boundPositions, Matrix4x4.identity); } public void OnDisable() { DeferredDecalSystem.Instance?.RemoveDecal(this); } #if UNITY_EDITOR private void DrawGizmo(bool selected) { var col = new Color(0.0f, 0.7f, 1f, 1.0f); col.a = selected ? 0.1f : 0.05f; Gizmos.color = col; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(Vector3.zero, Vector3.one); col.a = selected ? 0.5f : 0.2f; Gizmos.color = col; Gizmos.DrawWireCube(Vector3.zero, Vector3.one); } public void OnDrawGizmos() { DrawGizmo(false); } public void OnDrawGizmosSelected() { DrawGizmo(true); } private void OnValidate() { DeferredDecalSystem.Instance?.RemoveDecal(this, false); OnEnable(); } [UnityEditor.MenuItem("GameObject/Effects/Deferred Decal")] static void CreateDecal() { var gameObj = new GameObject(); gameObj.name = "Deferred Decal"; gameObj.AddComponent<Decal>(); Camera cam = UnityEditor.SceneView.lastActiveSceneView.camera; Transform sceneCam = cam.transform; gameObj.transform.position = sceneCam.position + sceneCam.forward * /*(cam.nearClipPlane */ 6/*)*/; UnityEditor.Selection.activeObject = gameObj; } #endif } }
33.922414
113
0.565693
[ "MIT" ]
SanielX/DeferredDecals
Assets/DeferredDecals/Scripts/Decal.cs
3,937
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; namespace IdentityServer { [SecurityHeaders] [AllowAnonymous] public class HomeController : Controller { private readonly IIdentityServerInteractionService _interaction; private readonly IWebHostEnvironment _environment; private readonly ILogger _logger; public HomeController(IIdentityServerInteractionService interaction, IWebHostEnvironment environment, ILogger<HomeController> logger) { _interaction = interaction; _environment = environment; _logger = logger; } public IActionResult Index() { if (_environment.IsDevelopment()) { // only show in development return View(); } _logger.LogInformation("Homepage is disabled in production. Returning 404."); return NotFound(); } /// <summary> /// Shows the error page /// </summary> public async Task<IActionResult> Error(string errorId) { var vm = new ErrorViewModel(); // retrieve error details from identityserver var message = await _interaction.GetErrorContextAsync(errorId); if (message != null) { vm.Error = message; if (!_environment.IsDevelopment()) { // only show in development message.ErrorDescription = null; } } return View("Error", vm); } } }
30.646154
141
0.610442
[ "Apache-2.0" ]
springcomp/IdentityServer4.TableStorage
src/Host/Quickstart/Home/HomeController.cs
1,992
C#
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Drawing; using System.Drawing.Drawing2D; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// Pattern that uses a gradient. /// </summary> public class GradientPattern : Pattern, IGradientPattern { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GradientPattern"/> class. /// </summary> public GradientPattern() { GradientType = GradientType.Linear; Colors = new Color[2]; Colors[0] = SymbologyGlobal.RandomLightColor(1F); Colors[1] = Colors[0].Darker(.3F); Positions = new[] { 0F, 1F }; Angle = -45; } /// <summary> /// Initializes a new instance of the <see cref="GradientPattern"/> class using the specified colors. /// </summary> /// <param name="startColor">The start color.</param> /// <param name="endColor">The end color.</param> public GradientPattern(Color startColor, Color endColor) : this(startColor, endColor, -45) { } /// <summary> /// Initializes a new instance of the <see cref="GradientPattern"/> class using the specified colors and angle. /// </summary> /// <param name="startColor">The start color.</param> /// <param name="endColor">The end color.</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis.</param> public GradientPattern(Color startColor, Color endColor, double angle) : this(startColor, endColor, angle, GradientType.Linear) { } /// <summary> /// Initializes a new instance of the <see cref="GradientPattern"/> class using the specified colors, angle and style. /// </summary> /// <param name="startColor">The start color.</param> /// <param name="endColor">The end color.</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis.</param> /// <param name="style">Controls how the gradient is drawn.</param> public GradientPattern(Color startColor, Color endColor, double angle, GradientType style) { Colors = new Color[2]; Colors[0] = startColor; Colors[1] = endColor; Positions = new[] { 0F, 1F }; Angle = angle; GradientType = style; } #endregion #region Properties /// <summary> /// Gets or sets the angle for the gradient pattern. /// </summary> [Serialize("Angle")] public double Angle { get; set; } /// <summary> /// Gets or sets the colors (0 = start color, 1 = end color). /// </summary> [Serialize("Colors")] public Color[] Colors { get; set; } /// <summary> /// Gets or sets the gradient type. /// </summary> [Serialize("GradientTypes")] public GradientType GradientType { get; set; } /// <summary> /// Gets or sets the start positions (0 = start color, 1 = end color). /// </summary> [Serialize("Positions")] public float[] Positions { get; set; } #endregion #region Methods /// <summary> /// Handles the drawing code for linear gradient paths. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="gp">Path that gets drawn.</param> public override void FillPath(Graphics g, GraphicsPath gp) { RectangleF bounds = Bounds; if (bounds.IsEmpty) bounds = gp.GetBounds(); if (bounds.Width == 0 || bounds.Height == 0) return; // also don't draw gradient for very small polygons if (bounds.Width < 0.01 || bounds.Height < 0.01) return; if (GradientType == GradientType.Linear) { using (LinearGradientBrush b = new LinearGradientBrush(bounds, Colors[0], Colors[Colors.Length - 1], (float)-Angle)) { ColorBlend cb = new ColorBlend { Positions = Positions, Colors = Colors }; b.InterpolationColors = cb; g.FillPath(b, gp); } } else if (GradientType == GradientType.Circular) { PointF center = new PointF(bounds.X + (bounds.Width / 2), bounds.Y + (bounds.Height / 2)); float x = (float)(center.X - (Math.Sqrt(2) * bounds.Width / 2)); float y = (float)(center.Y - (Math.Sqrt(2) * bounds.Height / 2)); float w = (float)(bounds.Width * Math.Sqrt(2)); float h = (float)(bounds.Height * Math.Sqrt(2)); RectangleF circum = new RectangleF(x, y, w, h); GraphicsPath round = new GraphicsPath(); round.AddEllipse(circum); using (PathGradientBrush pgb = new PathGradientBrush(round)) { ColorBlend cb = new ColorBlend { Colors = Colors, Positions = Positions }; pgb.InterpolationColors = cb; g.FillPath(pgb, gp); } } else if (GradientType == GradientType.Rectangular) { double a = bounds.Width / 2; double b = bounds.Height / 2; double angle = Angle; if (angle < 0) angle = 360 + angle; angle = angle % 90; angle = 2 * (Math.PI * angle / 180); double x = a * Math.Cos(angle); double y = -b - (a * Math.Sin(angle)); PointF center = new PointF(bounds.X + (bounds.Width / 2), bounds.Y + (bounds.Height / 2)); PointF[] points = new PointF[5]; points[0] = new PointF((float)x + center.X, (float)y + center.Y); x = a + (b * Math.Sin(angle)); y = b * Math.Cos(angle); points[1] = new PointF((float)x + center.X, (float)y + center.Y); x = -a * Math.Cos(angle); y = b + (a * Math.Sin(angle)); points[2] = new PointF((float)x + center.X, (float)y + center.Y); x = -a - (b * Math.Sin(angle)); y = -b * Math.Cos(angle); points[3] = new PointF((float)x + center.X, (float)y + center.Y); points[4] = points[0]; GraphicsPath rect = new GraphicsPath(); rect.AddPolygon(points); using (PathGradientBrush pgb = new PathGradientBrush(rect)) { ColorBlend cb = new ColorBlend { Colors = Colors, Positions = Positions }; pgb.InterpolationColors = cb; g.FillPath(pgb, gp); } } } /// <summary> /// Gets a color that can be used to represent this pattern. In some cases, a color is not /// possible, in which case, this returns Gray. /// </summary> /// <returns>A single System.Color that can be used to represent this pattern.</returns> public override Color GetFillColor() { Color l = Colors[0]; Color h = Colors[Colors.Length - 1]; int a = (l.A + h.A) / 2; int r = (l.R + h.R) / 2; int g = (l.G + h.G) / 2; int b = (l.B + h.B) / 2; return Color.FromArgb(a, r, g, b); } /// <summary> /// Sets the fill color, keeping the approximate gradiant RGB changes the same, but adjusting /// the mean color to the specifeid color. /// </summary> /// <param name="color">The mean color to apply.</param> public override void SetFillColor(Color color) { if (Colors == null || Colors.Length == 0) return; if (Colors.Length == 1) { Colors[0] = color; return; } Color l = Colors[0]; Color h = Colors[Colors.Length - 1]; int da = (h.A - l.A) / 2; int dr = (h.R - l.R) / 2; int dg = (h.G - l.G) / 2; int db = (h.B - l.B) / 2; Colors[0] = Color.FromArgb(ByteSize(color.A - da), ByteSize(color.R - dr), ByteSize(color.G - dg), ByteSize(color.B - db)); Colors[Colors.Length - 1] = Color.FromArgb(ByteSize(color.A + da), ByteSize(color.R + dr), ByteSize(color.G + dg), ByteSize(color.B + db)); } private static int ByteSize(int value) { if (value > 255) return 255; return value < 0 ? 0 : value; } #endregion } }
39.738589
152
0.493056
[ "MIT" ]
eapbokma/DotSpatial
Source/DotSpatial.Symbology/GradientPattern.cs
9,577
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionPage.cs.tt namespace Microsoft.Graph { using System; /// <summary> /// The type CustodianUserSourcesCollectionPage. /// </summary> public partial class CustodianUserSourcesCollectionPage : CollectionPage<UserSource>, ICustodianUserSourcesCollectionPage { /// <summary> /// Gets the next page <see cref="ICustodianUserSourcesCollectionRequest"/> instance. /// </summary> public ICustodianUserSourcesCollectionRequest NextPageRequest { get; private set; } /// <summary> /// Initializes the NextPageRequest property. /// </summary> public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString) { if (!string.IsNullOrEmpty(nextPageLinkString)) { this.NextPageRequest = new CustodianUserSourcesCollectionRequest( nextPageLinkString, client, null); } } } }
37.358974
153
0.575841
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/CustodianUserSourcesCollectionPage.cs
1,457
C#
using UnityEngine; using UnityEngine.Rendering.PostProcessing; namespace UnityEditor.Rendering.PostProcessing { [CanEditMultipleObjects, CustomEditor(typeof(PostProcessVolume))] public sealed class PostProcessVolumeEditor : BaseEditor<PostProcessVolume> { SerializedProperty m_Profile; SerializedProperty m_IsGlobal; SerializedProperty m_BlendRadius; SerializedProperty m_Weight; SerializedProperty m_Priority; EffectListEditor m_EffectList; void OnEnable() { m_Profile = FindProperty(x => x.sharedProfile); m_IsGlobal = FindProperty(x => x.isGlobal); m_BlendRadius = FindProperty(x => x.blendDistance); m_Weight = FindProperty(x => x.weight); m_Priority = FindProperty(x => x.priority); m_EffectList = new EffectListEditor(this); RefreshEffectListEditor(m_Target.sharedProfile); } void OnDisable() { if (m_EffectList != null) m_EffectList.Clear(); } void RefreshEffectListEditor(PostProcessProfile asset) { m_EffectList.Clear(); if (asset != null) m_EffectList.Init(asset, new SerializedObject(asset)); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(m_IsGlobal); if (!m_IsGlobal.boolValue) // Blend radius is not needed for global volumes EditorGUILayout.PropertyField(m_BlendRadius); EditorGUILayout.PropertyField(m_Weight); EditorGUILayout.PropertyField(m_Priority); bool assetHasChanged = false; bool showCopy = m_Profile.objectReferenceValue != null; bool multiEdit = m_Profile.hasMultipleDifferentValues; // The layout system sort of break alignement when mixing inspector fields with custom // layouted fields, do the layout manually instead int buttonWidth = showCopy ? 45 : 60; float indentOffset = EditorGUI.indentLevel * 15f; var lineRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight); var labelRect = new Rect(lineRect.x, lineRect.y, EditorGUIUtility.labelWidth - indentOffset, lineRect.height); var fieldRect = new Rect(labelRect.xMax, lineRect.y, lineRect.width - labelRect.width - buttonWidth * (showCopy ? 2 : 1), lineRect.height); var buttonNewRect = new Rect(fieldRect.xMax, lineRect.y, buttonWidth, lineRect.height); var buttonCopyRect = new Rect(buttonNewRect.xMax, lineRect.y, buttonWidth, lineRect.height); EditorGUI.PrefixLabel(labelRect, EditorUtilities.GetContent("Profile|A reference to a profile asset.")); using (var scope = new EditorGUI.ChangeCheckScope()) { EditorGUI.BeginProperty(fieldRect, GUIContent.none, m_Profile); var profile = (PostProcessProfile)EditorGUI.ObjectField(fieldRect, m_Profile.objectReferenceValue, typeof(PostProcessProfile), false); if (scope.changed) { assetHasChanged = true; m_Profile.objectReferenceValue = profile; } EditorGUI.EndProperty(); } using (new EditorGUI.DisabledScope(multiEdit)) { if (GUI.Button(buttonNewRect, EditorUtilities.GetContent("New|Create a new profile."), showCopy ? EditorStyles.miniButtonLeft : EditorStyles.miniButton)) { // By default, try to put assets in a folder next to the currently active // scene file. If the user isn't a scene, put them in root instead. var targetName = m_Target.name; var scene = m_Target.gameObject.scene; var asset = ProfileFactory.CreatePostProcessProfile(scene, targetName); m_Profile.objectReferenceValue = asset; assetHasChanged = true; } if (showCopy && GUI.Button(buttonCopyRect, EditorUtilities.GetContent("Clone|Create a new profile and copy the content of the currently assigned profile."), EditorStyles.miniButtonRight)) { // Duplicate the currently assigned profile and save it as a new profile var origin = (PostProcessProfile)m_Profile.objectReferenceValue; var path = AssetDatabase.GetAssetPath(origin); path = AssetDatabase.GenerateUniqueAssetPath(path); var asset = Instantiate(origin); asset.settings.Clear(); AssetDatabase.CreateAsset(asset, path); foreach (var item in origin.settings) { var itemCopy = Instantiate(item); itemCopy.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy; itemCopy.name = item.name; asset.settings.Add(itemCopy); AssetDatabase.AddObjectToAsset(itemCopy, asset); } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); m_Profile.objectReferenceValue = asset; assetHasChanged = true; } } EditorGUILayout.Space(); if (m_Profile.objectReferenceValue == null) { if (assetHasChanged) m_EffectList.Clear(); // Asset wasn't null before, do some cleanup EditorGUILayout.HelpBox("Assign a Post-process Profile to this volume using the \"Asset\" field or create one automatically by clicking the \"New\" button.\nAssets are automatically put in a folder next to your scene file. If you scene hasn't been saved yet they will be created at the root of the Assets folder.", MessageType.Info); } else { if (assetHasChanged) RefreshEffectListEditor((PostProcessProfile)m_Profile.objectReferenceValue); if (!multiEdit) m_EffectList.OnGUI(); } serializedObject.ApplyModifiedProperties(); } } }
42.966887
349
0.597565
[ "MIT" ]
Aa22041100/Unity-Music-Visualizer
Assets/PostProcessing-2/PostProcessing/Editor/PostProcessVolumeEditor.cs
6,488
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; using MetricsDbProvider.Models; namespace SenderService { public class SenderService { public static void SendData(IEnumerable<Mark> transmissionDataList) { var serializer = new XmlSerializer(typeof(IEnumerable<Mark>)); using (Stream ms = new MemoryStream()) { serializer.Serialize(ms, transmissionDataList); } var service = new WebServiceReference.EmissionsWebServiceSoapClient(); var transmitionDataMapper = new MapperConfiguration(cfg => { cfg.CreateMap<TransferData, WebServiceReference.TransferData>(); }).CreateMapper(); var transmissionDataArray = new WebServiceReference.TransferData[transmissionDataList.Count()]; for (int i = 0; i < transmissionDataList.Count(); i++) { transmissionDataArray[i] = transmitionDataMapper.Map<WebServiceReference.TransferData>(transmissionDataList[i]); } try { service.UploadData(transmissionDataArray); Console.WriteLine("Данные отправлены"); } catch (Exception ex) { Console.WriteLine("Ошибка отправки данных: {0}", ex.Message); } } } }
27
116
0.736532
[ "MIT" ]
sbannikov/csharpbmstu
2019/Homework/Teams/03/Monitoring/SenderService/SenderService.asmx.cs
1,226
C#
using System; using System.Collections.Generic; using System.Linq; namespace AscheLib.UniMonad { public static partial class Identity { public static void Execute<T>(this IIdentityMonad<T> self) { self.RunIdentity(); } public static void Execute<T>(this IIdentityMonad<T> self, Action<T> onValue) { T result = self.RunIdentity(); onValue(result); } } }
24.866667
81
0.723861
[ "MIT" ]
AscheLab/AscheLib.UniMonad
Assets/AscheLib/UniMonad/Monad/Identity/Identity.Execute.cs
375
C#
using System; using System.Collections.Generic; using System.Text; namespace EchoDotNetLite.Models { /// <summary> /// バイト配列-16進数ユーティリティ /// </summary> public static class BytesConvert { /// <summary> /// バイト配列から16進数の文字列を生成します。 /// </summary> /// <param name="bytes">バイト配列</param> /// <returns>16進数文字列</returns> public static string ToHexString(byte[] bytes) { if (bytes == null) { return string.Empty; } StringBuilder sb = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) { if (b < 16) sb.Append('0'); // 二桁になるよう0を追加 sb.Append(Convert.ToString(b, 16)); } return sb.ToString().ToUpper(); } /// <summary> /// 16進数の文字列からバイト配列を生成します。 /// </summary> /// <param name="str">16進数文字列</param> /// <returns>バイト配列</returns> public static byte[] FromHexString(string str) { int length = str.Length / 2; byte[] bytes = new byte[length]; int j = 0; for (int i = 0; i < length; i++) { bytes[i] = Convert.ToByte(str.Substring(j, 2), 16); j += 2; } return bytes; } } }
27.078431
67
0.471398
[ "MIT" ]
HiroyukiSakoh/EchoDotNetLite
EchoDotNetLite/Models/BytesConvert.cs
1,551
C#
/* * Copyright (c) 2010-2021 Achim Friedland <achim.friedland@graphdefined.com> * This file is part of Styx <https://www.github.com/Vanaheimr/Styx> * * 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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Usings using System; using System.Collections.Generic; #endregion namespace org.GraphDefined.Vanaheimr.Styx { /// <summary> /// The IdentityPipe is the most basic pipe. /// It simply maps the input to the output without any processing. /// This Pipe is useful in various test case situations. /// </summary> /// <typeparam name="S">The type of the elements within the pipe.</typeparam> public class IdentityPipe<S> : AbstractPipe<S, S> { #region MoveNext() /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// True if the enumerator was successfully advanced to the next /// element; false if the enumerator has passed the end of the /// collection. /// </returns> public override Boolean MoveNext() { if (SourcePipe == null) return false; if (SourcePipe.MoveNext()) { _CurrentElement = SourcePipe.Current; return true; } return false; } #endregion } }
27.897059
81
0.632578
[ "Apache-2.0" ]
Vanaheimr/Styx
Styx/Styx/Pipes/SimplePipes/IdentityPipe.cs
1,899
C#
using System; using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OAuth; using Owin; using ReactMusicStore.WebApi.Framework.Providers; namespace ReactMusicStore.WebApi { public partial class Startup { public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static string PublicClientId { get; private set; } // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request //app.CreatePerOwinContext(KiksAppDbContext.Create); //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure the application for OAuth based flow PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); } } }
38.984848
125
0.636611
[ "MIT" ]
BeshoyHindy/React-Redux-MusicStore
src/server/React-MusicStore/Presentation/React-MusicStore.WebApi/App_Start/Startup.Auth.cs
2,575
C#
using System; using SpurRoguelike.Core; using SpurRoguelike.Core.Entities; using SpurRoguelike.Core.Primitives; namespace SpurRoguelike.ConsoleGUI { internal class ConsoleEventReporter : IEventReporter { public ConsoleEventReporter(ConsoleGui gui) { this.gui = gui; } public void ReportMessage(string message) { ReportMessage(null, message); } public void ReportMessage(Entity instigator, string message) { if (gui.IsOnScreen(instigator)) gui.DisplayMessage(new ConsoleMessage(message, ConsoleColor.Gray)); } public void ReportLevelEnd() { gui.DisplayMessage(new ConsoleMessage("You have completed the level!", ConsoleColor.Green)); } public void ReportGameEnd() { gui.DisplayMessage(new ConsoleMessage("The game is over.", ConsoleColor.White)); } public void ReportNewEntity(Location location, Entity entity) { gui.DisplayMessage(new ConsoleMessage($"A new {entity.Name} appears!", ConsoleColor.White)); } public void ReportAttack(Pawn attacker, Pawn victim) { if (gui.IsOnScreen(attacker) || gui.IsOnScreen(victim)) gui.DisplayMessage(new ConsoleMessage($"{attacker.Name} attacks {victim.Name}!", ConsoleColor.Gray)); } public void ReportDamage(Pawn pawn, int damage, Entity instigator) { if (gui.IsOnScreen(pawn)) gui.DisplayMessage(new ConsoleMessage(instigator == null ? $"{pawn.Name} takes {damage} damage." : $"{pawn.Name} takes {damage} damage from {instigator.Name}.", ConsoleColor.Gray)); } public void ReportTrap(Pawn pawn) { if (gui.IsOnScreen(pawn)) gui.DisplayMessage(new ConsoleMessage($"{pawn.Name} joins the Mickey Mouse Club!", ConsoleColor.Gray)); } public void ReportPickup(Pawn pawn, Pickup item) { if (gui.IsOnScreen(pawn)) gui.DisplayMessage(new ConsoleMessage($"{pawn.Name} picks up {item.Name}.", ConsoleColor.Gray)); } public void ReportDestroyed(Pawn pawn) { if (gui.IsOnScreen(pawn)) gui.DisplayMessage(new ConsoleMessage($"{pawn.Name} ceases to exist.", ConsoleColor.DarkRed)); } public void ReportUpgrade(Pawn pawn, int attackBonus, int defenceBonus) { gui.DisplayMessage(new ConsoleMessage($"{pawn.Name}'s skills grow: attack +{attackBonus}, defence +{defenceBonus}.", ConsoleColor.White)); } private readonly ConsoleGui gui; } }
34.5125
150
0.608113
[ "MIT" ]
wingrime/SpurBot
SpurRoguelike/ConsoleGUI/ConsoleEventReporter.cs
2,761
C#
using System; public class CypherRoulette { public static void Main() //100/100 { uint inputRows = uint.Parse(Console.ReadLine()); string cypherString = "", currString, prevString = ""; string concatMode = "NormalMode"; while (inputRows > 0) { currString = Console.ReadLine(); if (prevString == currString) { cypherString = string.Empty; if (prevString != "spin") inputRows--; continue; } if (currString != "spin") { inputRows--; } else { if (concatMode == "SpinMode") concatMode = "NormalMode"; else concatMode = "SpinMode"; prevString = currString; continue; } switch (concatMode) { case ("NormalMode"): cypherString = cypherString + currString; break; case ("SpinMode"): cypherString = currString + cypherString; break; } prevString = currString; } Console.WriteLine(cypherString); } }
23.857143
62
0.42515
[ "MIT" ]
GabrielRezendi/Programming-Fundamentals-2017
02.Extented Fundamentals/09.DATA TYPES - EXERCISES/17.01 Cypher Roulette/Program.cs
1,338
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace IcmWeather.src.Localizations { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Messages { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Messages() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("IcmWeather.src.Localizations.Messages", typeof(Messages).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to downloading meteogram. /// </summary> internal static string downloading { get { return ResourceManager.GetString("downloading", resourceCulture); } } /// <summary> /// Looks up a localized string similar to can&apos;t download meteogram. /// </summary> internal static string error_download { get { return ResourceManager.GetString("error_download", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Exit. /// </summary> internal static string exit { get { return ResourceManager.GetString("exit", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Refresh. /// </summary> internal static string refresh { get { return ResourceManager.GetString("refresh", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Settings. /// </summary> internal static string settings { get { return ResourceManager.GetString("settings", resourceCulture); } } } }
39.807339
182
0.56165
[ "Apache-2.0" ]
andre-wojtowicz/icm-weather
IcmWeather/src/Localizations/Messages.Designer.cs
4,341
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UniRx.Tests.Operators { [Microsoft.VisualStudio.TestTools.UnitTesting.TestClass] public class RangeTest { [TestMethod] public void Range() { AssertEx.Throws<ArgumentOutOfRangeException>(() => Observable.Range(1, -1).ToArray().Wait()); Observable.Range(1, 0).ToArray().Wait().Length.Is(0); Observable.Range(1, 10).ToArray().Wait().IsCollection(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Observable.Range(1, 0, Scheduler.Immediate).ToArray().Wait().Length.Is(0); Observable.Range(1, 10, Scheduler.Immediate).ToArray().Wait().IsCollection(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } } }
34.136364
118
0.616511
[ "MIT" ]
ADIX7/UniRx
Tests/UniRx.Tests/RangeTest.cs
753
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace Prototype { [Serializable] class Transform : Component { public Vector3 Position; } }
18.176471
53
0.7411
[ "MIT" ]
isbdnt/csharp-design-patterns
Prototype/Transform.cs
311
C#
//-------------------------------------- // Dom Framework // // For documentation or // if you have any issues, visit // wrench.kulestar.com // // Copyright © 2013 Kulestar Ltd // www.kulestar.com //-------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace Dom{ /// <summary> /// A Html5 capable lexer. /// </summary> public class HtmlLexer : StringReader{ /// <summary>Cached reference for the XHTML namespace.</summary> private static MLNamespace _XHTMLNamespace; /// <summary>The XML namespace for XHTML.</summary> public static MLNamespace XHTMLNamespace{ get{ if(_XHTMLNamespace==null){ // Get the namespace (Doesn't request the URL; see XML namespaces for more info): _XHTMLNamespace=Dom.MLNamespaces.Get("http://www.w3.org/1999/xhtml","xhtml","text/html"); } return _XHTMLNamespace; } } /// <summary> /// Gets or sets the current parse mode. /// </summary> public HtmlParseMode State; /// <summary>Current namespace. Defaults to XHTML (for all our HTML tags).</summary> public MLNamespace Namespace; /// <summary>Document we're adding to.</summary> public Document Document; public readonly List<Element> OpenElements; public readonly Stack<int> TemplateModes; public readonly List<Element> FormattingElements; /// <summary>The current tree mode.</summary> public int PreviousMode = HtmlTreeMode.Initial; /// <summary>The current tree mode.</summary> public int CurrentMode = HtmlTreeMode.Initial; /// <summary>The length of the current text buffer.</summary> public int TextBlockLength; /// <summary>A string builder used for constructing tokens.</summary> public System.Text.StringBuilder Builder=new System.Text.StringBuilder(); /// <summary>The head pointer.</summary> public Element head; /// <summary>The form pointer.</summary> public Element form; /// <summary>The pending table chars 'list' (we only ever add one to it).</summary> public TextNode PendingTableCharacters; /// <summary>The last created start tag name (lowercase).</summary> public string LastStartTag; /// <summary>Frameset-ok flag</summary> public bool FramesetOk=true; /// <summary>Table foster parenting. Occurs when tables are mis-nested and affects how elements are added.</summary> public bool _foster=false; /// <summary>The latest added text node. Gets cleared whenever Process is called.</summary> private TextNode text_; public HtmlLexer(string str,Node context):base(str){ // First, check for the UTF8 BOM (rather awkwardly encoded in UTF16 here): if(str!=null && str.Length>=1 && (int)str[0]==0xFEFF){ // We're UTF-8. Skip the BOM: Position++; } // Create sets: OpenElements = new List<Element>(); TemplateModes = new Stack<int>(); FormattingElements = new List<Element>(); Document=context as Document; if(Document==null){ // We're in some other context. Note that we'll always append into this context. Document=context.document; // Push it to the open element set, if it's an element: Element el=context as Element; if(el!=null){ OpenElements.Add(el); Reset(); } } // Setup namespace: Namespace=Document.Namespace; } /// <summary>Checks if all elements on the stack are ok to be open in the AfterBody mode.</summary> public void CheckAfterBodyStack(){ for(int i=OpenElements.Count-1;i>=0;i--){ // Can it still be open? if(!OpenElements[i].OkToBeOpenAfterBody){ // Fatal error - mangled DOM. throw new DOMException(DOMException.SYNTAX_ERR,(ushort)HtmlParseError.BodyClosedWrong); } } } /// <summary>Resets the insertion mode. /// http://www.w3.org/html/wg/drafts/html/master/syntax.html#the-insertion-mode /// </summary> public void Reset(){ for (int i = OpenElements.Count - 1; i >= 0; i--){ Element element = OpenElements[i]; bool last = (i == 0); int mode = element.SetLexerMode(last, this); if(mode!=HtmlTreeMode.Current){ CurrentMode=mode; break; } } } /// <summary>Parses the whole string.</summary> public void Parse(){ char peek=Peek(); // While we have more.. while(peek!=StringReader.NULL){ switch (State){ case HtmlParseMode.PCData: if(peek=='<'){ // Tag! Read(); OpenPCTag(); }else{ // Handle text nodes: HandleText(true,true); } break; case HtmlParseMode.RCData: if(peek=='<'){ // Tag! Read(); OpenRCTag(); }else{ // Handle text nodes: HandleText(true,true); } break; case HtmlParseMode.Rawtext: case HtmlParseMode.Script: // Keep going until we reach </lastTagName> // Note that these two cases are only identical here because we hand over // the special parsing of comments in the script mode to the JS parser. int start=Position; bool close; int end=GetAppropriateEnd(out close); // Add substring as a text node: string script=Input.Substring(start,end-start); // Create the text element: TextNode el=Namespace.CreateTextNode(Document); el.textContent=script; // Add it now. Process(el,null,CurrentMode); if(close){ // Add the close tag: Process(null,LastStartTag); } break; case HtmlParseMode.Plaintext: // Plaintext to end - optimized case here: int textStart=Position-TextBlockLength; int textEnd=Input.Length; // From Position to Input.Length: Position=textEnd; TextBlockLength=textEnd-textStart; // Close text: FlushTextNode(); // Just in case: Finish(); return; } // Next peek char: peek=Peek(); } // Ok: Finish(); } /// <summary>Keeps reading until </lastStartTag> is seen.</summary> private int GetAppropriateEnd(out bool closing){ int end=-1; char peek=Peek(); while (peek!='\0'){ if(peek=='<'){ end=Position; Position++; peek = Peek(); if (peek == '/'){ Position++; // Keep peeking until we hit a non-letter: int x=0; while(IsAsciiLetter(Peek(x))){ x++; } // x is the length of the tag name. // It needs to be equal to lastStartTag (case insensitive) // in order for it to successfully close. string tag=ReadString(x); if(tag.ToLower()==LastStartTag){ // We're closing the tag. // Clear until we hit > char c=Read(); while(c!='>' && c!='\0'){c=Read();} closing=true; return end; } // Not actually closing it if we fall down here. } } Position++; peek=Peek(); } if(end==-1){ // Terminated early. end=Position; } closing=false; return end; } /// <summary>Reads the contents of an open/close tag.</summary> private string ReadRawTag(bool open,bool withName){ bool first=withName; char peek=Peek(); bool selfClosing=false; if(peek=='<'){ Read(); peek=Peek(); } string tagName=null; Element result=null; while(peek!=StringReader.NULL && peek!='>' && peek!='<'){ string property; string value; PropertyTextReader.Read(this,Builder,first||selfClosing,out property,out value); property=property.ToLower(); // xmlns? if(property=="xmlns"){ // Obtain the namespace by name: MLNamespace targetNS=MLNamespaces.Get(value); if(targetNS!=null){ Namespace=targetNS; } }else if(property.StartsWith("xmlns:")){ // Declaring a namespace string[] pieces=property.Split(':'); // Create it if needed: MLNamespaces.Get(value,pieces[1],""); } if(first){ first=false; tagName=property; }else if(property=="/"){ selfClosing=true; }else if(open){ if(tagName!=null){ // Create the tag now: result=CreateTag(tagName,false); // Clear: tagName=null; } // Apply the property: result.Properties[property]=value; // Inform the change: result.OnAttributeChange(property); } peek=Peek(); } if(peek=='>'){ Read(); } if(!open){ return tagName; } if(tagName!=null){ // Set the tag now: result=CreateTag(tagName,true); }else{ // Call tag loaded: result.OnTagLoaded(); } result.SelfClosing=selfClosing; // Add it: Process(result,null,CurrentMode); return null; } /// <summary> /// Determines if the given character is an upper/lowercase character. /// </summary> /// <param name="c">The character to examine.</param> public static bool IsAsciiLetter(char c){ return (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a); } /// <summary>True if the given char is any of the HTML5 space characters (includes newlines etc).</summary> public static bool IsSpaceCharacter(char c){ return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f'; } private void EndTag(){ char c=Peek(); if (IsAsciiLetter(c)){ string tagName=ReadRawTag(false,true); // Closed tagName Process(null,tagName,CurrentMode); }else if (c == '>'){ Read(); State = HtmlParseMode.PCData; HandleText(true,true); }else if (c == '\0'){ TextBlockLength+=2; FlushTextNode(); }else{ BogusComment(); } } private void OpenPCTag(){ char c=Peek(); if(c == '/'){ Read(); EndTag(); return; } if (IsAsciiLetter(c)){ ReadRawTag(true,true); }else if(c == '!'){ Position++; if (Peek(0)=='-' && Peek(1)=='-'){ Position+=2; TextBlockLength=0; c=Read(); if(c=='-'){ // 8.2.4.47 Comment start dash state c=Read(); if(c=='-'){ if(CommentEnd()){ return; } }else if(c=='>'){ State = HtmlParseMode.PCData; }else if(c=='\0'){ // Empty comment: FlushCommentNode(0); }else{ TextBlockLength++; LoadComment(); } }else if(c=='>'){ State = HtmlParseMode.PCData; return; }else if(c=='\0'){ // Do nothing. return; }else{ TextBlockLength++; LoadComment(); } }else if(PeekLower("doctype")){ Position+=7; // Skip spaces: PropertyTextReader.SkipSpaces(this); c=Read(); DocumentType docType=new DocumentType(""); if (c == '>'){ docType.quirksMode=true; State = HtmlParseMode.PCData; }else if (c == '\0'){ docType.quirksMode=true; }else{ // Started reading the name. int nameIndex=Position-1; int length=1; while (true){ c = Read(); if(IsSpaceCharacter(c)){ docType.name_ = Input.Substring(nameIndex,length); PropertyTextReader.SkipSpaces(this); c=Read(); if (c == '>'){ State = HtmlParseMode.PCData; }else if(c == '\0'){ docType.quirksMode = true; }else if((c=='p' || c=='P') && PeekLower("ublic")){ Position+=5; // Public doctype. docType.ParsePublic(this); }else if((c=='s' || c=='S') && PeekLower("ystem")){ Position+=5; // System doctype. docType.ParseSystem(this); }else{ docType.quirksMode = true; // Broken doctype. docType.ParseBroken(this); } break; }else if (c == '>'){ State = HtmlParseMode.PCData; docType.name_ = Input.Substring(nameIndex,length); break; }else if (c == '\0'){ docType.quirksMode = true; docType.name_ = Input.Substring(nameIndex,length); break; }else{ length++; } } } Process(docType,null); return; }else if(Peek("[CDATA[")){ Position+=7; TextBlockLength=0; c=Peek(); while(c!='\0'){ if(c == ']' && Peek("]]>")){ // Close comment if there is any: FlushCommentNode(0); Position+=3; return; }else{ Position++; TextBlockLength++; c = Peek(); } } // Close comment if there is any: FlushCommentNode(0); }else{ BogusComment(); } }else if(c != '?'){ State = HtmlParseMode.PCData; HandleText(true,true); }else{ BogusComment(); } } private Comment FlushCommentNode(int positionDelta){ if(TextBlockLength==0){ return null; } // Get and clear the text: string text=Input.Substring(Position+positionDelta-TextBlockLength,TextBlockLength); TextBlockLength=0; // Create the node: Comment el=Namespace.CreateCommentNode(Document); el.textContent=text; // Add it now. Process(el,null,CurrentMode); return el; } /// <summary> /// Reads a comments body. /// </summary> private void LoadComment(){ while (true){ char c=Read(); if(c=='-'){ if(CommentDashEnd()){ return; } }else if(c=='\0'){ FlushCommentNode(0); return; }else{ TextBlockLength++; } } } /// <summary> /// See 8.2.4.49 Comment end dash state /// </summary> private bool CommentDashEnd(){ char c=Read(); if(c=='-'){ return CommentEnd(); }else if(c=='\0'){ FlushCommentNode(0); return true; }else{ TextBlockLength+=2; } // Didn't actually terminate. return false; } /// <summary>Checks if the comment has ended.</summary> private bool CommentEnd(){ while (true){ char c=Read(); if(c=='>'){ State = HtmlParseMode.PCData; FlushCommentNode(-3); return true; }else if(c=='!'){ // 8.2.4.51 Comment end bang state c=Read(); if(c=='-'){ TextBlockLength+=3; if(CommentDashEnd()){ return true; } }else if(c=='>'){ State = HtmlParseMode.PCData; return true; }else if(c=='\0'){ return true; }else{ TextBlockLength+=4; } break; }else if(c=='-'){ // (Syntax error) TextBlockLength++; break; }else if(c=='\0'){ FlushCommentNode(0); return true; }else{ TextBlockLength+=3; break; } } return false; } private void OpenRCTag(){ char peek=Peek(); if(peek == '/'){ Position++; // Keep peeking until we hit a non-letter: int x=0; while(IsAsciiLetter(Peek(x))){ x++; } // x is the length of the tag name. // It needs to be equal to lastStartTag (case insensitive) // in order for it to successfully close. string tag=ReadString(x); if(tag.ToLower()==LastStartTag){ // Clear until we hit > char c=Read(); while(c!='>' && c!='\0'){c=Read();} // Process it: Process(null,LastStartTag); return; } // Include the </ as text: TextBlockLength+=2; }else{ // Include the < as text: TextBlockLength++; } HandleText(true,true); } /// <summary>Creates a close tag if one is appropriate.</summary> private bool CreateIfAppropriate(char c){ if(Builder.Length!=LastStartTag.Length){ return false; } if((c=='>' || c=='/' || IsSpaceCharacter(c)) && Builder.ToString()==LastStartTag){ // Read it off: Read(); // Clear builder: Builder.Length=0; // Close tag: if(c!='/' && c!='>'){ // Read attribs only (and just dump them): ReadRawTag(false,false); } Process(null,LastStartTag,CurrentMode); return true; } return false; } /// <summary> /// See 8.2.4.44 Bogus comment state /// </summary> /// <param name="c">The current character.</param> private void BogusComment(){ char c=Peek(0); TextBlockLength=0; while (c!='\0' && c!='>'){ TextBlockLength++; c=Peek(TextBlockLength); } State = HtmlParseMode.PCData; FlushComment(); } /// <summary>Creates a text content block.</summary> private void HandleText(bool stopAtTag,bool allowVars){ // While we don't have a <, read text. // Look out for &, EOF and <. char peek=Peek(); while(peek!=StringReader.NULL){ if(stopAtTag && peek=='<'){ break; } if(allowVars && peek=='&'){ // Variable. AddVariable(); }else{ // Advance: TextBlockLength++; Position++; } // Next peek char: peek=Peek(); } // Close text if there is any: FlushTextNode(); } /// <summary>The current tag on the top of the stack.</summary> public string CurrentTag{ get{ Element current=CurrentElement; if(current==null){ return null; } return current.Tag; } } /// <summary>The current open node.</summary> public Node CurrentNode{ get{ int count=OpenElements.Count; if(count==0){ return Document; } return OpenElements[count-1]; } } /// <summary>The current open element.</summary> public Element CurrentElement{ get{ int count=OpenElements.Count; if(count==0){ return null; } return OpenElements[count-1]; } } /// <summary>Pushes a new open element.</summary> public void Push(Element el,bool stack){ if(_foster && CurrentElement.IsTableStructure){ AddElementWithFoster(el); }else{ Node current=CurrentElement; if(current==null){ current=Document; } current.appendChild(el); } if(stack){ OpenElements.Add(el); }else{ // Kids loaded already: el.OnChildrenLoaded(); } } private void AddElementWithFoster(Element element){ bool table = false; int index = OpenElements.Count; while (--index != 0){ if (OpenElements[index].Tag=="template"){ OpenElements[index].appendChild(element); return; }else if (OpenElements[index].Tag=="table"){ table = true; break; } } Node foster = OpenElements[index].parentNode_; if(foster==null){ foster=OpenElements[index + 1]; } if(table && OpenElements[index].parentNode_ != null){ for(int i=0;i<foster.childCount;i++){ if (foster.childNodes_[i] == OpenElements[index]){ foster.insertChild(i,element); break; } } }else{ foster.appendChild(element); } } public void Process(Node node,string close){ Process(node,close,CurrentMode); } public void Process(Node node,string close,int mode){ text_=null; Element el=node as Element; string open=null; if(el!=null){ open=el.Tag; } // If it's a close or open tag: if(el!=null){ // Change state back to PCData: State = HtmlParseMode.PCData; // Note open tag: LastStartTag=open; }else if(close!=null){ // Change state back to PCData: State = HtmlParseMode.PCData; } // OnLexerAddNode checks CurrentMode and handles itself accordingly. // The most common case should be checked first (depends on node implementations). // Essentially the more broken your HTML is, the slower it goes! if(node!=null && node.OnLexerAddNode(this,mode)){ // It handled itself. return; }else if(close!=null && CallCloseMethod(close,mode)){ // It handled itself. return; } // Default state for the current mode: switch(mode){ case HtmlTreeMode.Initial: // Reprocess it as BeforeHtml: CurrentMode = HtmlTreeMode.BeforeHtml; Process(node,close,CurrentMode); break; case HtmlTreeMode.BeforeHtml: if(close==null){ // Otherwise it's an end tag which didn't match any of the acceptable ones; Ignore it. BeforeHtmlElse(node,close); } break; case HtmlTreeMode.BeforeHead: // Create a head node: el=CreateTag("head",true); Push(el,true); head=el; // Switch to in head and reprocess: CurrentMode=HtmlTreeMode.InHead; Process(node,close,CurrentMode); break; case HtmlTreeMode.InHead: if(close==null){ // Ignore other close tags. InHeadElse(node,null); } break; case HtmlTreeMode.InHeadNoScript: // Ignore any other close tags: if(close==null){ // Reprocess as in head: // Switch mode: CurrentMode = HtmlTreeMode.InHead; Process(node,null,CurrentMode); } break; case HtmlTreeMode.AfterHead: if(close==null){ // Ignore other close tags. AfterHeadElse(node,close); } break; case HtmlTreeMode.InCaption: case HtmlTreeMode.InCell: // Reprocess as 'in body' Process(node,close,HtmlTreeMode.InBody); break; case HtmlTreeMode.InBody: // In body mode. if(el!=null){ // Any other open tag. ReconstructFormatting(); // Push it, accounting for its self closing state: Push(el,!(el.SelfClosing || el.IsSelfClosing)); }else if(close!=null){ // Any other close tag. InBodyEndTagElse(close); } break; case HtmlTreeMode.Text: // Text mode: CloseCurrentNode(); CurrentMode = PreviousMode; break; case HtmlTreeMode.InRow: case HtmlTreeMode.InTableBody: case HtmlTreeMode.InTable: InTableElse(node,close); break; case HtmlTreeMode.InTemplate: if(open!=null){ TemplateStep(node,close,HtmlTreeMode.InBody); } break; case HtmlTreeMode.InColumnGroup: if(CurrentElement.Tag=="colgroup"){ // Ignore otherwise CloseCurrentNode(); // Change mode: CurrentMode=HtmlTreeMode.InTable; Process(node,close,CurrentMode); } break; case HtmlTreeMode.AfterBody: // Switch: CurrentMode=HtmlTreeMode.InBody; Process(node,close,CurrentMode); break; case HtmlTreeMode.AfterAfterBody: // Switch and reproc: CurrentMode=HtmlTreeMode.InBody; Process(node,close); break; } } /// <summary>used by e.g. pre; skips a newline if there is one.</summary> public void SkipNewline(){ // Read off the first newline: char peek=Peek(); if(peek=='\n'){ Read(); }else if(peek=='\r'){ Read(); if(Peek(1)=='\n'){ Read(); } } } public void CloseParagraph(){ // Close a 'p' element. // http://w3c.github.io/html/syntax.html#close-a-p-element GenerateImpliedEndTagsExceptFor("p"); // Close inclusive: CloseInclusive("p"); } /// <summary>Closes a paragraph in button scope then pushes the given element.</summary> public void CloseParagraphThenAdd(Element el){ if(IsInButtonScope("p")){ CloseParagraph(); } Push(el,true); } public void CloseParagraphButtonScope(){ if(IsInButtonScope("p")){ CloseParagraph(); } } /// <summary>The all other nodes route when in the 'in table' mode.</summary> public void InTableElse(Node node,string close){ _foster = true; Process(node,close,HtmlTreeMode.InBody); _foster = false; } /// <summary>Closes the cell if the given close tag is in scope, then reprocesses it.</summary> public void CloseTableZoneInCell(string close){ if(IsInTableScope(close)){ CloseCell(); // Reproc: Process(null,close,CurrentMode); return; } } /// <summary>Handles head-favouring tags when in the 'after head' mode. /// Base, link, meta etc are examples of favouring tags; they prefer to be in the head.</summary> public void AfterHeadHeadTag(Node node){ // Push head onto the stack only: OpenElements.Add(head); // process in head: Process(node,null,HtmlTreeMode.InHead); // Pop: CloseCurrentNode(); } /// <summary>Closes to table body context if tbody, head or foot are in scope.</summary> public void CloseToTableBodyIfBody(Node node,string close){ if(IsInTableScope("tbody") || IsInTableScope("thead") || IsInTableScope("tfoot")){ // Ignore otherwise. CloseToTableBodyContext(); CloseCurrentNode(); // Reprocess: CurrentMode=HtmlTreeMode.InTable; Process(node,close,CurrentMode); } } /// <summary>Closes a caption (if it's in scope) and reprocesses the node in table mode.</summary> public void CloseCaption(Node node,string close){ if(IsInTableScope("caption")){ // Ignore the token otherwise. // Generate implied: GenerateImpliedEndTags(); // Close upto and incl. caption: CloseInclusive("caption"); // Clear to last marker: ClearFormatting(); // Table mode: CurrentMode=HtmlTreeMode.InTable; Process(node,close,CurrentMode); } } /// <summary>Triggers CloseCell if th or td are in scope.</summary> public void CloseIfThOrTr(Node node,string close){ if(IsInTableScope("th") || IsInTableScope("td")){ // Ignore otherwise. CloseCell(); // Reprocess: Process(node,close,CurrentMode); } } /// <summary>Closes to a table context and switches to table body if a tr is in scope.</summary> public void TableBodyIfTrInScope(Node node,string close){ if(IsInTableScope("tr")){ // Ignore otherwise. CloseToTableBodyContext(); CloseCurrentNode(); CurrentMode=HtmlTreeMode.InTableBody; // Reproc: Process(node,close,CurrentMode); } } public void CloseSelect(bool skipScopeCheck,Node node,string close){ if(skipScopeCheck || IsInSelectScope(close)){ CloseInclusive("select"); Reset(); // Reproc: Process(node,close,CurrentMode); } } /// <summary>Closes a table cell.</summary> public void CloseCell(){ // Generate implied: GenerateImpliedEndTags(); // Pop up to and incl 'td' or 'th': Element el=CurrentElement; while(el.Tag!="td" && el.Tag!="th"){ CloseCurrentNode(); el=CurrentElement; } if(el.Tag=="td" || el.Tag=="th"){ CloseCurrentNode(); } ClearFormatting(); CurrentMode=HtmlTreeMode.InRow; } public void BeforeHtmlElse(Node node,string close){ // Create a html node: Element el=CreateTag("html",true); Push(el,true); // Switch to before head and reprocess: CurrentMode=HtmlTreeMode.BeforeHead; Process(node,close,CurrentMode); } /// <summary>Any other end tag has been found in the InBody state.</summary> /// <param name="tag">The actual tag found.</param> private void InBodyEndTagElse(string close){ int index = OpenElements.Count - 1; Element node = CurrentElement; while (node != null){ if (node.Tag==close){ GenerateImpliedEndTagsExceptFor(close); CloseNodesFrom(index); break; }else if(node.IsSpecial){ break; } node = OpenElements[--index]; } } /// <summary>This attempts to recover mis-nested tags. For example <b><i>Hi!</b></i> is relatively common. /// This is aka the Heisenburg algorithm, but it's named 'adoption agency' in HTML5.</summary> /// <param name="tag">The actual tag given.</param> public void AdoptionAgencyAlgorithm(string tag){ int outer = 0; int inner = 0; int bookmark = 0; int index = 0; while (outer < 8){ Element formattingElement = null; Element furthestBlock = null; outer++; index = 0; inner = 0; for (int j = FormattingElements.Count - 1; j >= 0 && FormattingElements[j] != null; j--){ if (FormattingElements[j].Tag==tag){ index = j; formattingElement = FormattingElements[j]; break; } } if (formattingElement == null){ // Note that tag is always a close node. InBodyEndTagElse(tag); break; } int openIndex = OpenElements.IndexOf(formattingElement); if (openIndex == -1){ // HtmlParseError.FormattingElementNotFound FormattingElements.Remove(formattingElement); break; } if (!IsInScope(formattingElement.Tag)){ // HtmlParseError.ElementNotInScope break; } if (openIndex != OpenElements.Count - 1){ // HtmlParseError.TagClosedWrong } bookmark = index; for (int j = openIndex + 1; j < OpenElements.Count; j++){ if (OpenElements[j].IsSpecial){ index = j; furthestBlock = OpenElements[j]; break; } } if (furthestBlock == null){ do{ furthestBlock = CurrentElement; CloseCurrentNode(); }while (furthestBlock != formattingElement); FormattingElements.Remove(formattingElement); break; } Element commonAncestor = OpenElements[openIndex - 1]; Element node = furthestBlock; Element lastNode = furthestBlock; while (true){ inner++; node = OpenElements[--index]; if (node == formattingElement){ break; } if (inner > 3 && FormattingElements.Contains(node)){ FormattingElements.Remove(node); } if (!FormattingElements.Contains(node)){ CloseNode(node); continue; } Element newElement = node.cloneNode(false) as Element; commonAncestor.appendChild(newElement); OpenElements[index] = newElement; for (int l = 0; l != FormattingElements.Count; l++){ if (FormattingElements[l] == node){ FormattingElements[l] = newElement; break; } } node = newElement; if (lastNode == furthestBlock){ bookmark++; } if(lastNode.parentNode_!=null){ lastNode.parentNode_.removeChild(lastNode); } node.appendChild(lastNode); lastNode = node; } if(lastNode.parentNode_!=null){ lastNode.parentNode_.removeChild(lastNode); } if (!commonAncestor.IsTableStructure){ commonAncestor.appendChild(lastNode); }else{ AddElementWithFoster(lastNode); } Element element = formattingElement.cloneNode(false) as Element; while (furthestBlock.childNodes_.length > 0){ Node childNode = furthestBlock.childNodes_[0]; furthestBlock.removeChildAt(0); element.appendChild(childNode); } furthestBlock.appendChild(element); FormattingElements.Remove(formattingElement); FormattingElements.Insert(bookmark, element); CloseNode(formattingElement); OpenElements.Insert(OpenElements.IndexOf(furthestBlock) + 1, element); } } /// <summary>Checks if the named tag is currently open on the formatting stack.</summary> public Element FormattingCurrentlyOpen(string tagName){ // Start from the top of the stack because that's most likely where we'll find it. for(int i = FormattingElements.Count-1; i >=0; i--){ Element fmt=FormattingElements[i]; if(fmt==null){ // Marker - stop there. break; } if(fmt.Tag==tagName){ return fmt; } } return null; } /// <summary>Adds a formatting element.</summary> public void AddFormatting(Element element){ int count = 0; for (int i = FormattingElements.Count - 1; i >= 0; i--){ Element format = FormattingElements[i]; if (format == null){ break; } if (format.Tag==element.Tag && format.Namespace==element.Namespace && Node.PropertiesEqual(format.Properties,element.Properties) && ++count == 3) { FormattingElements.RemoveAt(i); break; } } FormattingElements.Add(element); } /// <summary> /// Clears formatting info to the last marker. /// </summary> public void ClearFormatting(){ while (FormattingElements.Count != 0){ int index = FormattingElements.Count - 1; Element entry = FormattingElements[index]; FormattingElements.RemoveAt(index); if (entry == null){ break; } } } /// <summary> /// Adds a formatting scope marker. /// </summary> public void AddScopeMarker(){ FormattingElements.Add(null); } /// <summary> /// Reconstruct the list of active formatting elements, if any. /// </summary> public void ReconstructFormatting(){ if (FormattingElements.Count == 0){ return; } int index = FormattingElements.Count - 1; Element entry = FormattingElements[index]; if (entry == null || OpenElements.Contains(entry)){ return; } while (index > 0){ entry = FormattingElements[--index]; if (entry == null || OpenElements.Contains(entry)){ index++; break; } } for (; index < FormattingElements.Count; index++) { // Clone it: Element element = FormattingElements[index].cloneNode(false) as Element; // Add: Push(element,true); FormattingElements[index] = element; } } /// <summary>Closes a marked formatting element like object or applet.</summary> public void CloseMarkedFormattingElement(string close){ if(IsInScope(close)){ GenerateImpliedEndTags(); CloseInclusive(close); // Clear to marker: ClearFormatting(); } } /// <summary>Adds a marked formatting element like object or applet.</summary> public void AddMarkedFormattingElement(Element el){ ReconstructFormatting(); Push(el,true); AddScopeMarker(); FramesetOk=false; } public void AddFormattingElement(Element el){ // 'in body', A start tag whose tag name is one of: "b", "big", "code", "em", .. ReconstructFormatting(); Push(el,true); AddFormatting(el); } /// <summary>True if the given tag is in list item scope.</summary> public bool IsInListItemScope(string tagName){ for (int i = OpenElements.Count - 1; i >= 0; i--){ Element node = OpenElements[i]; string tag=node.Tag; if(tag==tagName){ return true; }else if(node.IsParserScope || tag=="ol" || tag=="ul"){ return false; } } return false; } /// <summary>True if the given tag is in element scope.</summary> public bool IsInScope(string tagName){ for (int i = OpenElements.Count - 1; i >= 0; i--){ Element node = OpenElements[i]; if(node.Tag==tagName){ return true; }else if(node.IsParserScope){ return false; } } return false; } /// <summary>True if the given tag is in button scope.</summary> public bool IsInButtonScope(string tagName){ for (int i = OpenElements.Count - 1; i >= 0; i--){ Element node = OpenElements[i]; if(node.Tag==tagName){ return true; }else if(node.Tag=="button" || node.IsParserScope){ return false; } } return false; } /// <summary>True if the given tag is in table scope.</summary> public bool IsInTableScope(string tagName){ for (int i = OpenElements.Count - 1; i >= 0; i--){ Element node = OpenElements[i]; if(node.Tag==tagName){ return true; }else if(node.IsTableContext){ return false; } } return false; } /// <summary>True if the given tag is in select scope.</summary> public bool IsInSelectScope(string tagName){ for (int i = OpenElements.Count - 1; i >= 0; i--){ Element node = OpenElements[i]; if(node.Tag==tagName){ return true; }else if(node.Tag!="option" && node.Tag!="optgroup"){ return false; } } return false; } public void CloseInclusive(string tag){ // Pop up to and incl: while(CurrentElement.Tag!=tag){ CloseCurrentNode(); } if(CurrentElement.Tag==tag){ CloseCurrentNode(); } } /// <summary>Closes all nodes from the given open element stack index. Inclusive.</summary> public void CloseNodesFrom(int index){ for (int i = OpenElements.Count - 1; i >= index; i--){ CloseCurrentNode(); } } /// <summary>Close to a table body context. thead, tfoot, tbody, html and template.</summary> public void CloseToTableRowContext(){ while(!CurrentElement.IsTableRowContext){ CloseCurrentNode(); } } /// <summary>Close to a table body context. thead, tfoot, tbody, html and template.</summary> public void CloseToTableBodyContext(){ while(!CurrentElement.IsTableBodyContext){ CloseCurrentNode(); } } /// <summary>Close to a table context.</summary> public void CloseToTableContext(){ while(!CurrentElement.IsTableContext){ CloseCurrentNode(); } } /// <summary>Input or textarea in select mode.</summary> public void InputOrTextareaInSelect(Element el){ if(IsInSelectScope("select")){ CloseInclusive("select"); Reset(); // Reproc: Process(el,null); } } /// <summary>'Generic raw text element parsing algorithm'. Adds the current node then switches to the given state, whilst also changing the mode to Text.</summary> public void RawTextOrRcDataAlgorithm(Element el,HtmlParseMode stateAfter){ // Append it: Push(el,true); // Switch to RawText: PreviousMode = CurrentMode; CurrentMode = HtmlTreeMode.Text; State = stateAfter; } /// <summary>Anything else in the 'after head' mode.</summary> public void AfterHeadElse(Node node,string close){ // Create a body element: Element el=CreateTag("body",true); Push(el,true); // Switch: CurrentMode=HtmlTreeMode.InBody; Process(node,close,CurrentMode); } /// <summary>Anything else in the 'in head' mode.</summary> public void InHeadElse(Node node,string close){ // Anything else. // Close the head tag. CloseCurrentNode(); // Switch mode: CurrentMode = HtmlTreeMode.AfterHead; Process(node,close,CurrentMode); } /// <summary>Combines the attribs of the given element into target. /// Adds the attributes to target if they don't exist (doesn't overwrite).</summary> public void CombineInto(Element el,Element target){ foreach(KeyValuePair<string,string> kvp in el.Properties){ // Add the attrib if it doesn't exist: if(!target.Properties.ContainsKey(kvp.Key)){ target.setAttribute(kvp.Key, kvp.Value); } } } /// <summary>Attempts to close a block element.</summary> public void BlockClose(string close){ if(IsInScope(close)){ GenerateImpliedEndTags(); CloseInclusive(close); } } /// <summary>Checks if the named tag is currently open.</summary> public bool TagCurrentlyOpen(string tagName){ // Start from the top of the stack because that's most likely where we'll find it. for(int i = OpenElements.Count-1; i >=0; i--){ if(OpenElements[i].Tag==tagName){ return true; } } return false; } /// <summary> /// Inserting something in the template. /// </summary> /// <param name="token">The token to insert.</param> /// <param name="mode">The mode to push.</param> public void TemplateStep(Node node,string close,int mode){ TemplateModes.Pop(); TemplateModes.Push(mode); CurrentMode = mode; Process(node,close,mode); } /// <summary> /// Closes the template element. /// </summary> public void CloseTemplate(){ Element node = CurrentElement; while (node!=null && node.ImplicitEndAllowed==ImplicitEndMode.Normal && node.Tag!="template"){ CloseCurrentNode(); node = CurrentElement; } ClearFormatting(); TemplateModes.Pop(); Reset(); } /// <summary>Generate implicit end tags.</summary> public void Finish(){ /* // The only other side effects of this involve tidying the lexer up. // Not necessary because we're terminating anyway. if(TemplateModes.Count>0){ // Close the template first: if (TagCurrentlyOpen("template")){ CloseTemplate(); } } */ Element node = CurrentElement; while(node!=null){ CloseCurrentNode(); node = CurrentElement; } } /// <summary>Generate implicit end tags.</summary> public void GenerateImpliedEndTags(){ Element node = CurrentElement; // Normal only: while(node!=null && node.ImplicitEndAllowed==ImplicitEndMode.Normal){ CloseCurrentNode(); node = CurrentElement; } } /// <summary>Generate implicit end tags.</summary> public void GenerateImpliedEndTagsThorough(){ Element node = CurrentElement; // Normal and thorough: while(node!=null && ( (node.ImplicitEndAllowed & ImplicitEndMode.Thorough)!=0 )){ CloseCurrentNode(); node = CurrentElement; } } /// <summary>Generate implicit end tags.</summary> public void GenerateImpliedEndTagsExceptFor(string tagName){ Element node = CurrentElement; // Applies to normal only: while (node!=null && node.ImplicitEndAllowed==ImplicitEndMode.Normal && node.Tag!=tagName){ CloseCurrentNode(); node = CurrentElement; } } public void CloseNode(Element el){ // Kids are now ready: el.OnChildrenLoaded(); // Remove it: OpenElements.Remove(el); // Update namespace: int index=OpenElements.Count-1; if(index!=0){ Namespace=OpenElements[index-1].Namespace; } } /// <summary> /// Pops the last node from the stack of open nodes. /// </summary> public void CloseCurrentNode(){ int index=OpenElements.Count-1; if(index<0){ return; } // Kids are now ready: OpenElements[index].OnChildrenLoaded(); // Pop: OpenElements.RemoveAt(index); // Update namespace: if(index!=0){ Namespace=OpenElements[index-1].Namespace; } } /// <summary>Writes out any pending text as a comment node.</summary> private void FlushComment(){ if(TextBlockLength==0){ return; } // Get and clear the text: string text=Input.Substring(Position-TextBlockLength,TextBlockLength); TextBlockLength=0; // Create the text element: Comment el=Namespace.CreateCommentNode(Document); el.textContent=text; // Add comment node Process(el,null,CurrentMode); } /// <summary>Writes out any pending text to a text element.</summary> private TextNode FlushTextNode(){ if(TextBlockLength==0){ return null; } // Get and clear the text: string text=Input.Substring(Position-TextBlockLength,TextBlockLength); TextBlockLength=0; TextNode el=text_; if(el==null){ // Create the text element: el=Namespace.CreateTextNode(Document); el.textContent=text; // Add it now. Process(el,null,CurrentMode); // Set as latest text node: text_=el; }else{ // Great - append to an existing node. This happens after &these; are seen. el.appendData(text); } return el; } /// <summary>Appends text to the given node or creates a new node if it's null.</summary> private TextNode AppendText(TextNode node,string text){ if(node==null){ // Create the text element: node=Namespace.CreateTextNode(Document); node.textContent=text; // Add it now. Process(node,null,CurrentMode); }else{ // Append: node.appendData(text); } return node; } /// <summary>Reads out a &variable; (as used by PowerUI for localization purposes).</summary> private void AddVariable(){ // Flush textElement if we're working on one (likely): TextNode textNode=FlushTextNode(); // Read off the &: Read(); int nameLength=0; char peek=Peek(); string variableString=""; List<string> variableArguments=null; while(peek!='\0' && peek!='>'){ if(peek==';'){ if(nameLength!=0){ // The name is in the builder: variableString=Input.Substring(Position-nameLength,nameLength); } // Read off the ; Read(); // Check if this string (e.g. &WelcomeMessage;) is provided by the standard variable set: string stdEntity=CharacterEntities.GetByValueOrName(variableString); if(stdEntity==null){ // Not a standard entity; we have e.g. &Welcome; // Generate a new variable element: Node varElement=Namespace.CreateLangNode(Document); if(varElement==null){ // This namespace doesn't support this kind of variable. // Add it as a literal string instead. // Append: textNode=AppendText(textNode,"&"+variableString+";"); }else{ // Can no longer append to the previous text node: textNode=null; text_=null; ILangNode langInterface=varElement as ILangNode; langInterface.SetVariableName(variableString); if(variableArguments!=null){ langInterface.SetArguments(variableArguments.ToArray()); variableArguments=null; } langInterface.LoadNow(); // Append it: CurrentNode.appendChild(varElement); } }else{ // Got a standard entity! Append stdEntity to text node, or create a new one if it needs it. textNode=AppendText(textNode,stdEntity); } return; }else if(peek=='('){ // Read runtime argument set. &WelcomeMessage('heya!'); variableString=Input.Substring(Position-nameLength,nameLength); nameLength=0; // Read off the bracket: Read(); peek=Peek(); variableArguments=new List<string>(); while(peek!=StringReader.NULL){ if(peek==')'){ // Add it: variableArguments.Add(Input.Substring(Position-nameLength,nameLength)); nameLength=0; // Read it off: Read(); break; }else if(peek==','){ // Done one parameter - onto the next. variableArguments.Add(Input.Substring(Position-nameLength,nameLength)); nameLength=0; }else if(peek=='"' || peek=='\''){ // One of our args is a "string". // Use the string reader of the PropertyTextReader to read it. PropertyTextReader.ReadString(this,Builder); // We don't want to read a char off, so continue here. // Peek the next one: peek=Peek(); continue; }else if(peek!=' '){ // General numeric args will fall down here. // Disallowing spaces means the set can be spaced out like so: (14, 21) nameLength++; } // Read off the char: Read(); // Peek the next one: peek=Peek(); } }else if(IsSpaceCharacter(peek) || peek=='<'){ // Halt! Add it as a string literal. variableString=Input.Substring(Position-nameLength,nameLength); AppendText(textNode,"&"+variableString); return; }else{ // Read off the char: Read(); nameLength++; } peek=Peek(); } } /// <summary>Calls Element.OnLexerCloseNode. Note that it's an instance method /// but it can be called without an instance when the DOM isn't balanced. /// For example, a balanced DOM will have a 'div' on the open element stack, and we want to handle its /div /// tag when it shows up. This would directly invoke close on that open element. /// If we're not balanced, it obtains SupportedTagMeta.CloseMethod and invokes it with a null instance. /// See SupportedTagMeta.CloseMethod for more.</summary> public bool CallCloseMethod(string tag,int mode){ // Balanced? for(int i=OpenElements.Count-1;i>=0;i--){ // Get it: Element stacked=OpenElements[i]; if(stacked.Tag==tag){ // Great - call it on that instance: return stacked.OnLexerCloseNode(this,mode); } } // Unexpected close tag. // Ideally this is rare // but who knows what kind of crazy syntax is out there on the interwebs.. MLNamespace ns=Namespace; if(tag!=null && tag.IndexOf(':')!=-1){ // We have a namespace declaration in the tag. // e.g. svg:svg string[] pieces=tag.Split(':'); // Get the namespace from a (global only) prefix: ns=MLNamespaces.GetPrefix(pieces[0]); // Update the tag: tag=pieces[1]; } // Get the tag handler: SupportedTagMeta globalHandler=TagHandlers.Get(ns,tag); MethodInfo mInfo=globalHandler.CloseMethod; if(mInfo==null){ return false; } // We'll need to instance a tag: object tagInstance=Activator.CreateInstance(globalHandler.TagType); // Run it now: return (bool)mInfo.Invoke(tagInstance,new object[]{this,mode}); } /// <summary>Creates an element from the given namespace/ tag name.</summary> public Element CreateTag(string tag,bool callLoad){ MLNamespace ns=Namespace; if(tag!=null && tag.IndexOf(':')!=-1){ // We have a namespace declaration in the tag. // e.g. svg:svg string[] pieces=tag.Split(':'); // Get the namespace from a (global only) prefix: var tagNamespace=MLNamespaces.GetPrefix(pieces[0]); if(tagNamespace != null){ ns = tagNamespace; } // Update the tag: tag=pieces[1]; } // Ok: Element el=TagHandlers.Create(ns,tag); el.document_=Document; // Change namespace if needed: Namespace=el.Namespace; if(callLoad){ // Call the loaded method: el.OnTagLoaded(); } return el; } } }
21.261621
165
0.580939
[ "MIT" ]
HeasHeartfire/Mega-Test
Assets/PowerUI/Source/Dom/Html/HtmlLexer.cs
51,688
C#
using System; using System.Net.Sockets; using System.Timers; using nylium.Core.Networking.Packet; using nylium.Core.Networking.Packet.Server.Play; namespace nylium.Core.Networking { public class KeepAlive { private readonly Random random = new(); private Action<NetworkPacket> Send { get; } private Action TimeoutAction { get; } private Timer KeepAliveTimer { get; } private Timer TimeoutTimer { get; } public bool HasResponded; public KeepAlive(Action<NetworkPacket> send, Action timeoutAction, double delayInMilliseconds) { Send = send; TimeoutAction = timeoutAction; KeepAliveTimer = new Timer(delayInMilliseconds); KeepAliveTimer.Elapsed += KeepAliveTimer_Elapsed; KeepAliveTimer.AutoReset = true; TimeoutTimer = new Timer(30000); // 30 seconds TimeoutTimer.Elapsed += TimeoutTimer_Elapsed; TimeoutTimer.AutoReset = true; } private void TimeoutTimer_Elapsed(object sender, ElapsedEventArgs e) { if(!HasResponded) { KeepAliveTimer.Stop(); TimeoutTimer.Stop(); TimeoutAction(); } else { TimeoutTimer.Interval = TimeoutTimer.Interval; TimeoutTimer.Stop(); } } private void KeepAliveTimer_Elapsed(object sender, ElapsedEventArgs e) { TimeoutTimer.Stop(); SP1FKeepAlive keepAlive = new(LongRandom(random)); Send(keepAlive); HasResponded = false; TimeoutTimer.Start(); TimeoutTimer.Interval = TimeoutTimer.Interval; } private long LongRandom(Random rand) { byte[] buf = new byte[8]; rand.NextBytes(buf); return BitConverter.ToInt64(buf, 0); } public void Start() { KeepAliveTimer.Start(); TimeoutTimer.Start(); } public void Stop() { KeepAliveTimer.Stop(); TimeoutTimer.Stop(); } } }
29.027397
104
0.586126
[ "MIT" ]
zCri/nylium
nylium.Core/Networking/KeepAlive.cs
2,121
C#
using Xunit; using APIServer.Aplication.Shared; using System.Text.RegularExpressions; namespace APIServer.Application.UnitTests.Behaviours { public class CommonTests { public CommonTests() { } [Theory] [InlineData("")] [InlineData("someprefix/test")] [InlineData("some_random_text")] [InlineData("192.168.0.1")] [InlineData("192.168.0.1:9000/test")] public void UrlRegex_Fail(string url) { var result = Regex.Match(url, Common.URI_REGEX); Assert.False(result.Success); } [Theory] [InlineData("www.test.com")] [InlineData("http://test/test")] [InlineData("http://test.com/test")] [InlineData("https://test.com/test")] [InlineData("https://test.com:9000/test")] [InlineData("https://192.168.0.1/test")] [InlineData("http://192.168.0.1/test")] [InlineData("http://192.168.0.1:9000/test")] public void UrlRegex_Ok(string url) { var result = Regex.Match(url, Common.URI_REGEX); Assert.True(result.Success); } } }
28.725
60
0.578764
[ "MIT" ]
BuiTanLan/trouble-training
Src/Tests/APIServer.Aplication.Unit/Common/CommonTests.cs
1,151
C#
// ***************************************************************************** // // © Component Factory Pty Ltd, 2006 - 2016. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 5.461.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using ComponentFactory.Krypton.Toolkit; namespace MDIApplication { public partial class Form2 : KryptonForm { public Form2() { InitializeComponent(); } protected override void Dispose(bool disposing) { if (disposing) { // Remember to unhook from static event, otherwise // this object cannot be garbage collected later on KryptonManager.GlobalPaletteChanged -= new EventHandler(OnPaletteChanged); if (components != null) { components.Dispose(); } } base.Dispose(disposing); } private void Form2_Load(object sender, EventArgs e) { // Set correct initial radio button setting UpdateRadioButtons(); // Hook into changes in the global palette KryptonManager.GlobalPaletteChanged += new EventHandler(OnPaletteChanged); } private void radio2010Blue_CheckedChanged(object sender, EventArgs e) { if (radio2010Blue.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Blue; } } private void radio2010Silver_CheckedChanged(object sender, EventArgs e) { if (radio2010Silver.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Silver; } } private void radio2010Black_CheckedChanged(object sender, EventArgs e) { if (radio2010Black.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Black; } } private void radio2007Blue_CheckedChanged(object sender, EventArgs e) { if (radio2007Blue.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Blue; } } private void radio2007Silver_CheckedChanged(object sender, EventArgs e) { if (radio2007Silver.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Silver; } } private void radio2007Black_CheckedChanged(object sender, EventArgs e) { if (radio2007Black.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Black; } } private void radioSparkleBlue_CheckedChanged(object sender, EventArgs e) { if (radioSparkleBlue.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleBlue; } } private void radioSparkleOrange_CheckedChanged(object sender, EventArgs e) { if (radioSparkleOrange.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleOrange; } } private void radioSparklePurple_CheckedChanged(object sender, EventArgs e) { if (radioSparklePurple.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.SparklePurple; } } private void radioOffice2003_CheckedChanged(object sender, EventArgs e) { if (radioOffice2003.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalOffice2003; } } private void radioSystem_CheckedChanged(object sender, EventArgs e) { if (radioSystem.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalSystem; } } private void OnPaletteChanged(object sender, EventArgs e) { // Update buttons to reflect the new palette setting UpdateRadioButtons(); } private void UpdateRadioButtons() { switch (kryptonManager.GlobalPaletteMode) { case PaletteModeManager.Office2010Blue: radio2010Blue.Checked = true; break; case PaletteModeManager.Office2010Silver: radio2010Silver.Checked = true; break; case PaletteModeManager.Office2010Black: radio2010Black.Checked = true; break; case PaletteModeManager.Office2007Blue: radio2007Blue.Checked = true; break; case PaletteModeManager.Office2007Silver: radio2007Silver.Checked = true; break; case PaletteModeManager.Office2007Black: radio2007Black.Checked = true; break; case PaletteModeManager.SparkleBlue: radioSparkleBlue.Checked = true; break; case PaletteModeManager.SparkleOrange: radioSparkleOrange.Checked = true; break; case PaletteModeManager.SparklePurple: radioSparklePurple.Checked = true; break; case PaletteModeManager.ProfessionalOffice2003: radioOffice2003.Checked = true; break; case PaletteModeManager.ProfessionalSystem: radioSystem.Checked = true; break; } } } }
33.939891
93
0.550153
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.461
Source/Demos/Non-NuGet/Krypton Toolkit Examples/MDI Application/Form2.cs
6,214
C#
// Copyright (c) 2020 Sergio Aquilini // This code is licensed under MIT license (see LICENSE file for details) using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using Silverback.Messaging; using Silverback.Messaging.Configuration; using Silverback.Messaging.Publishing; using Silverback.Tests.Integration.E2E.TestHost; using Silverback.Tests.Integration.E2E.TestTypes; using Silverback.Tests.Integration.E2E.TestTypes.Messages; using Xunit; using Xunit.Abstractions; namespace Silverback.Tests.Integration.E2E.Old.Broker { public class OutboundRoutingTests : E2ETestFixture { public OutboundRoutingTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } [Fact(Skip = "Deprecated")] public async Task StaticSingleEndpoint_RoutedCorrectly() { Host.ConfigureServices( services => services .AddLogging() .AddSilverback() .UseModel() .WithConnectionToMessageBroker(options => options.AddMockedKafka()) .AddEndpoints( endpoints => endpoints .AddOutbound<TestEventOne>(new KafkaProducerEndpoint("test-e2e-one")) .AddOutbound<TestEventTwo>(new KafkaProducerEndpoint("test-e2e-two")) .AddOutbound<TestEventThree>(new KafkaProducerEndpoint("test-e2e-three"))) .AddSingletonOutboundRouter<TestPrioritizedOutboundRouter>() .AddSingletonBrokerBehavior<SpyBrokerBehavior>()) .Run(); var publisher = Host.ScopedServiceProvider.GetRequiredService<IEventPublisher>(); await publisher.PublishAsync(new TestEventOne()); await publisher.PublishAsync(new TestEventTwo()); await publisher.PublishAsync(new TestEventThree()); await publisher.PublishAsync(new TestEventFour()); SpyBehavior.OutboundEnvelopes.Should().HaveCount(3); SpyBehavior.OutboundEnvelopes[0].Endpoint.Name.Should().Be("test-e2e-one"); SpyBehavior.OutboundEnvelopes[1].Endpoint.Name.Should().Be("test-e2e-two"); SpyBehavior.OutboundEnvelopes[2].Endpoint.Name.Should().Be("test-e2e-three"); } [Fact(Skip = "Deprecated")] public async Task StaticBroadcast_RoutedCorrectly() { Host.ConfigureServices( services => services .AddLogging() .AddSilverback() .UseModel() .WithConnectionToMessageBroker(options => options.AddMockedKafka()) .AddEndpoints( endpoints => endpoints .AddOutbound<TestEventOne>( new KafkaProducerEndpoint("test-e2e-one"), new KafkaProducerEndpoint("test-e2e-two"), new KafkaProducerEndpoint("test-e2e-three"))) .AddSingletonBrokerBehavior<SpyBrokerBehavior>()) .Run(); var publisher = Host.ScopedServiceProvider.GetRequiredService<IEventPublisher>(); await publisher.PublishAsync(new TestEventOne()); await publisher.PublishAsync(new TestEventTwo()); await publisher.PublishAsync(new TestEventThree()); SpyBehavior.OutboundEnvelopes.Should().HaveCount(3); SpyBehavior.OutboundEnvelopes[0].Endpoint.Name.Should().Be("test-e2e-one"); SpyBehavior.OutboundEnvelopes[1].Endpoint.Name.Should().Be("test-e2e-two"); SpyBehavior.OutboundEnvelopes[2].Endpoint.Name.Should().Be("test-e2e-three"); } [Fact(Skip = "Deprecated")] public async Task DynamicCustomRouting_RoutedCorrectly() { Host.ConfigureServices( services => services .AddLogging() .AddSilverback() .UseModel() .WithConnectionToMessageBroker(options => options.AddMockedKafka()) .AddEndpoints( endpoints => endpoints .AddOutbound<TestPrioritizedCommand, TestPrioritizedOutboundRouter>()) .AddSingletonOutboundRouter<TestPrioritizedOutboundRouter>() .AddSingletonBrokerBehavior<SpyBrokerBehavior>()) .Run(); var publisher = Host.ScopedServiceProvider.GetRequiredService<ICommandPublisher>(); await publisher.ExecuteAsync(new TestPrioritizedCommand { Priority = Priority.Low }); await publisher.ExecuteAsync(new TestPrioritizedCommand { Priority = Priority.Low }); await publisher.ExecuteAsync(new TestPrioritizedCommand { Priority = Priority.High }); SpyBehavior.OutboundEnvelopes.Should().HaveCount(6); SpyBehavior.OutboundEnvelopes.Count(envelope => envelope.Endpoint.Name == "test-e2e-all") .Should().Be(3); SpyBehavior.OutboundEnvelopes.Count(envelope => envelope.Endpoint.Name == "test-e2e-low") .Should().Be(2); SpyBehavior.OutboundEnvelopes.Count(envelope => envelope.Endpoint.Name == "test-e2e-normal") .Should().Be(0); SpyBehavior.OutboundEnvelopes.Count(envelope => envelope.Endpoint.Name == "test-e2e-high") .Should().Be(1); } } }
48.737288
106
0.596592
[ "MIT" ]
mjeanrichard/silverback
tests/Silverback.Integration.Tests.E2E/Old/Broker/OutboundRoutingTests.cs
5,751
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Linq; using System.Drawing.Imaging; using System.Runtime.Serialization; namespace Marci30 { public partial class Form1 : Form { private const string BTN_TEXT_BASE = "Dobj egy kockával! Legutóbbi dobás:"; private readonly string FIELD_TASK_DB_PATH; private readonly string FIELD_PIC_PATH; private readonly string COVER_PIC_PATH; private readonly PictureBox[] pictureBoxes; private readonly TextBox[] textBoxes; private readonly TextBox[] playerTextBoxes; private readonly Field[] fields; private readonly List<Player> players = new List<Player>(); private readonly Pen[] playerPens; private Rectangle[] playerRectangles; private Font playerLetterFont; private int picHeight, picWidth;//pix private int? selectedPlayer = null; public Form1() { InitializeComponent(); var paths = File.ReadAllLines("paths.ini"); FIELD_TASK_DB_PATH = paths[0]; FIELD_PIC_PATH = paths[1]; COVER_PIC_PATH = paths[2]; button1.Text = BTN_TEXT_BASE + '-'; button1.Focus(); KeyPress += Form1_KeyPress; BackColor = Color.Bisque; button1.BackColor = Color.White; button1.ForeColor = Color.Black; textBoxes = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9, textBox10, textBox11, textBox12, textBox13, textBox14, textBox15, textBox16, textBox17, textBox18, textBox19, textBox20, textBox21, textBox22, textBox23, textBox24, textBox25, textBox26, textBox27, textBox28, textBox29, textBox30 }; playerTextBoxes = new TextBox[] { textBoxP1, textBoxP2, textBoxP3, textBoxP4 }; pictureBoxes = new PictureBox[] { pictureBox1, pictureBox2, pictureBox3, pictureBox4, pictureBox5, pictureBox6, pictureBox7, pictureBox8, pictureBox9, pictureBox10, pictureBox11, pictureBox12, pictureBox13, pictureBox14, pictureBox15, pictureBox16, pictureBox17, pictureBox18, pictureBox19, pictureBox20, pictureBox21, pictureBox22, pictureBox23, pictureBox24, pictureBox25, pictureBox26, pictureBox27, pictureBox28, pictureBox29, pictureBox30 }; foreach (PictureBox pb in pictureBoxes) { pb.MouseClick += PictureBoxClick; pb.MouseDoubleClick += PictureBoxDoubleClick; pb.Visible = true; pb.Image = LoadPic(COVER_PIC_PATH); pb.SizeMode = PictureBoxSizeMode.Zoom; pb.Paint += PictureboxPaint; } fields = new Field[pictureBoxes.Length]; for (int i = 0; i < fields.Length; i++) fields[i] = new Field(); for (int i = 0; i < textBoxes.Length; i++) { textBoxes[i].Visible = true; textBoxes[i].Text = (i + 1).ToString(); } playerPens = new Pen[] { new Pen(Brushes.Red), new Pen(Brushes.Green), new Pen(Brushes.Blue), new Pen(Brushes.Black) }; FindFieldContent(); Load += Form1_Load; } private Bitmap LoadPic(string path) { Image i = Image.FromFile(path); PropertyItem pi = i.PropertyItems.Select(x => x) .FirstOrDefault(x => x.Id == 0x0112); if (pi == null) { pi = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem)); pi.Id = 0x0112; // orientation pi.Len = 2; pi.Type = 3; pi.Value = new byte[2] { 1, 0 }; pi.Value[0] = 1; i.SetPropertyItem(pi); } Bitmap bmp = new Bitmap(i); byte o = pi.Value[0]; if (o == 2) bmp.RotateFlip(RotateFlipType.RotateNoneFlipX); if (o == 3) bmp.RotateFlip(RotateFlipType.RotateNoneFlipXY); if (o == 4) bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); if (o == 5) bmp.RotateFlip(RotateFlipType.Rotate90FlipX); if (o == 6) bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); if (o == 7) bmp.RotateFlip(RotateFlipType.Rotate90FlipY); if (o == 8) bmp.RotateFlip(RotateFlipType.Rotate90FlipXY); return bmp; } private void Form1_Load(object sender, EventArgs e) { picHeight = pictureBox1.Height; picWidth = pictureBox1.Width; playerRectangles = new Rectangle[playerPens.Length]; for (int i = 0; i < playerRectangles.Length; i++) { playerRectangles[i].X = (i % 2) * picWidth / 2; playerRectangles[i].Y = (i / 2) * picHeight / 2; playerRectangles[i].Width = Math.Min(picWidth, picHeight) / 2; playerRectangles[i].Height = Math.Min(picWidth, picHeight) / 2; } playerLetterFont = new Font(FontFamily.GenericSansSerif, (int)(54.0 / 164 * picHeight)); } private void PictureboxPaint(object sender, PaintEventArgs e) { int position = int.Parse(((PictureBox)sender).Name.Substring("pictureBox".Length)) - 1; for (int i = 0; i < players.Count; i++) if (players[i].Position == position) DrawPlayer(e.Graphics, i); } private void DrawPlayer(Graphics g, int i) { g.FillEllipse(playerPens[i].Brush, playerRectangles[i]); g.DrawString(players[i].Letter.ToString(), playerLetterFont, (selectedPlayer != null && selectedPlayer == i) ? Brushes.Yellow : Brushes.White, playerRectangles[i]); } private void FindFieldContent() { textBoxTitle.Text = FindTaskParts(out string[] titles, out string[][] subtasks); Shell32.Shell shell = new Shell32.Shell(); Shell32.Folder folder = shell.NameSpace(FIELD_PIC_PATH); Shell32.FolderItems items = folder.Items(); for (int i = 0; i < items.Count; i++) { var fileName = folder.GetDetailsOf(items.Item(i), 0); DecompilePicName(Path.GetFileNameWithoutExtension(fileName), out var position, out var taskNumber); fields[position - 1].TaskNumbers.Add(taskNumber); fields[position - 1].Title = titles[position - 1]; if (subtasks[position - 1].Length < taskNumber) { MessageBox.Show("Nem tartozik feladat a képhez:" + fileName); fields[position - 1].Tasks.Add(""); } else { fields[position - 1].Tasks.Add(subtasks[position - 1][taskNumber - 1]); } fields[position - 1].Paths.Add(FIELD_PIC_PATH + fileName); } } private string FindTaskParts(out string[] titles, out string[][] tasks) { string gameName; var lines = File.ReadAllLines(FIELD_TASK_DB_PATH, System.Text.Encoding.GetEncoding(1252)); titles = new string[pictureBoxes.Length]; tasks = new string[pictureBoxes.Length][]; gameName = lines[0].Split(';')[0]; for (int i = 0; i < pictureBoxes.Length; i++) { DecompileLine(lines[i + 1], out string title, out List<string> subtasks); titles[i] = title; tasks[i] = subtasks.ToArray(); } return gameName; } private void DecompileLine(string line, out string title, out List<string> subtasks) { var lineparts = line.Split(';'); if (lineparts.Length < 4) { MessageBox.Show("Hibás sor:" + line); Environment.Exit(0); throw new NotImplementedException(); } else { title = lineparts[1]; subtasks = new List<string>(); for (int i = 1; i < lineparts.Length / 2; i++) { if (lineparts[i * 2] == "") break; else subtasks.Add(lineparts[i * 2]); } } } private void DecompilePicName(string fileName, out int position, out int taskNumber) { for (int i = 0; i < fileName.Length; i++) { if (fileName[i] == '_') { if (!int.TryParse(fileName.Substring(0, i), out position) || !int.TryParse(fileName.Substring(i + 1), out taskNumber) || position < 1 || position > pictureBoxes.Length || taskNumber < 0) { MessageBox.Show("Nem támogatott filenév:" + fileName); Environment.Exit(0); } else return; } } MessageBox.Show("Nem támogatott filenév:" + fileName); Environment.Exit(0); throw new NotImplementedException(); } private void PictureBoxDoubleClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { int position = int.Parse(((PictureBox)sender).Name.Substring("pictureBox".Length)) - 1; fields[position].IncrementTaskNumber(); string path = fields[position].GetCurrentPath(); pictureBoxes[position].Image = LoadPic(path); string title = position + 1 + ": " + fields[position].Title; textBoxes[position].Text = title; ShowBigPic(title, fields[position].GetCurrentTask(), path); } } private void BigPic_FormClosed(object sender, FormClosedEventArgs e) { Enabled = true; } private void PictureBoxClick(object sender, MouseEventArgs e) { int position = int.Parse(((PictureBox)sender).Name.Substring("pictureBox".Length)) - 1; if (e.Button == MouseButtons.Left) { int picQuarter = (e.Location.X / (picWidth / 2)) + (e.Location.Y / (picHeight / 2)) * 2; if (players.Count > picQuarter && players[picQuarter].Position == position) {//click on a player happened -> it gets selected (even if click on already selected) selectedPlayer = picQuarter; } else if (selectedPlayer != null && players[(int)selectedPlayer].Position != position) {//if a player is selected and the click did not occur on a player but on a field, where the player could go-> move player players[(int)selectedPlayer].MoveTo(position); selectedPlayer = null; } else { selectedPlayer = null; } TriggerRedrawPlayers(); } else {//right click -> enlarge pic, if not hidden if (!fields[position].IsHidden()) ShowBigPic((position + 1) + ": " + fields[position].Title, fields[position].GetCurrentTask(), fields[position].GetCurrentPath()); } } private void ShowBigPic(string title, string task, string path) { var bigPic = new BigPic(title, task, path); bigPic.FormClosed += BigPic_FormClosed; Enabled = false; } private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if (char.IsLetterOrDigit(e.KeyChar) && !char.IsDigit(e.KeyChar)) {//new player requested var capitalLetter = e.KeyChar.ToString().ToUpper()[0]; bool playerExists = false; //check if player exists for (int i = 0; i < players.Count; i++) { if (players[i].Letter == capitalLetter) { selectedPlayer = i; playerExists = true; TriggerRedrawPlayers(); break; } } if (!playerExists && players.Count < playerRectangles.Length) {//new player to be created players.Add(new Player(capitalLetter)); UpdateDrinkCounters(); TriggerRedrawPlayers(); } } else if (e.KeyChar == (char)Keys.Back && selectedPlayer != null) { if (MessageBox.Show("Tényleg törölni szeretnéd " + players[(int)selectedPlayer].Letter + " játékost?", "Játékos törlése", MessageBoxButtons.YesNo) == DialogResult.Yes) {//delete player (also from board) players.RemoveAt((int)selectedPlayer); UpdateDrinkCounters(); TriggerRedrawPlayers(); } } else if (e.KeyChar == '-' && selectedPlayer != null) { players[(int)selectedPlayer].Undrink(); UpdateDrinkCounters(); //playerTextBoxes[(int)selectedPlayer].Text = players[(int)selectedPlayer].Drinks.ToString(); } else if (e.KeyChar == '+' && selectedPlayer != null) { players[(int)selectedPlayer].Drink(); UpdateDrinkCounters(); //playerTextBoxes[(int)selectedPlayer].Text = players[(int)selectedPlayer].Drinks.ToString(); } } private void UpdateDrinkCounters() { for (int i = 0; i < playerTextBoxes.Length; i++) { if (players.Count > i) { playerTextBoxes[i].BackColor = playerPens[i].Color; playerTextBoxes[i].Text = players[i].Drinks.ToString(); } else { playerTextBoxes[i].BackColor = default; playerTextBoxes[i].Text = ""; } } } private void button1_Click(object sender, EventArgs e) { Random r = new Random(); button1.Text = BTN_TEXT_BASE + (r.Next(6) + 1); if (button1.BackColor == Color.White) { button1.BackColor = Color.Black; button1.ForeColor = Color.White; } else { button1.BackColor = Color.White; button1.ForeColor = Color.Black; } } private void TriggerRedrawPlayers() { foreach (PictureBox pb in pictureBoxes) pb.Invalidate(); } private class Field { private int taskNumber = -1;//means that it's hidden public readonly List<int> TaskNumbers = new List<int>(); public string Title { get; set; } public readonly List<string> Tasks = new List<string>(); public readonly List<string> Paths = new List<string>(); private int GetIDX() { int idx; for (idx = 0; idx < TaskNumbers.Count; idx++) { if (TaskNumbers[idx] - 1 == taskNumber) break; } return idx; } public string GetCurrentTask() { return Tasks[GetIDX()]; } public string GetCurrentPath() { return Paths[GetIDX()]; } public void IncrementTaskNumber() { taskNumber = Math.Min(taskNumber + 1, TaskNumbers.Count - 1); } public bool IsHidden() { return taskNumber == -1; } } private class Player { public char Letter { get; private set; } public int Position { get; private set; } = 0; public int Drinks { get; private set; } = 0; public Player(char letter) { Letter = letter; } public void MoveTo(int position) { Position = position; } public void Drink() { Drinks++; } public void Undrink() { Drinks = Math.Max(0, Drinks - 1); } } } }
34.137864
206
0.500199
[ "MIT" ]
kartonka/board_game
Form1.cs
17,602
C#
using AutoMapper; using dotnetstarter.Common; using dotnetstarter.Mapping; using dotnetstarter.Persistence; using dotnetstarter.Repositories; using dotnetstarter.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Prometheus; namespace dotnetstarter { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { string authSecret = Configuration[Constants.AuthSecretPreference]; // -- Configure Jwt Auth services.UseJwtAuth(authSecret); // -- Uses our extention method to abstract and clean up the setup. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // -- Configure a database services.AddDbContext<AppDbContext>(options => { options.UseInMemoryDatabase("Example-In-Memory"); }); // -- Configure Dependency injection services.AddScoped<IExampleRepository, ExampleRepository>(); services.AddScoped<IExampleService, ExampleService>(); services.AddAutoMapper(typeof(ModelToResourceProfile)); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMetricServer(); app.UseHttpMetrics(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); app.UseHttpsRedirection(); app.UseExceptionHandler("/error"); // -- Directs any issues that occur into the error controller. } app.UseAuthentication(); app.UseMvc(); } } }
41.448276
144
0.659318
[ "MIT" ]
tgun/dotnetstarter
Startup.cs
2,406
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; using EfsTools.Items.Data; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(628)] [Attributes(9)] public class PcsRxfFgIoffset { [ElementsCount(1)] [ElementType("uint32")] [Description("")] public uint Value { get; set; } } }
19.727273
40
0.610599
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/PcsRxfFgIoffsetI.cs
434
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace chess.View { class CustomOutlineLabel : Label { public Color OutlineColour { get; set; } public float OutlineColourWidth { get; set; } /* This is a subclass of the label which overrides the OnPaint to add a custom border to the text which is painted.This allows us to create a white font with a black outline so that it stands out against a coloured background. */ public CustomOutlineLabel() { OutlineColour = Color.Black; OutlineColourWidth = 2; } protected override void OnPaint(PaintEventArgs e) { // BackColor is the Labels backcolor, set to transparent in the calling code e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle); using (GraphicsPath gp = new GraphicsPath()) using (Pen outline = new Pen(OutlineColour, OutlineColourWidth) { LineJoin = LineJoin.Round }) using (StringFormat sf = new StringFormat()) using (Brush foreBrush = new SolidBrush(ForeColor)) { gp.AddString(Text, Font.FontFamily, (int)Font.Style, Font.Size, ClientRectangle, sf); e.Graphics.ScaleTransform(1.3f, 1.35f); e.Graphics.SmoothingMode = SmoothingMode.HighQuality; e.Graphics.DrawPath(outline, gp); e.Graphics.FillPath(foreBrush, gp); } } } }
35.395833
88
0.624485
[ "MIT" ]
pushyka/c-all
View/CustomOutlineLabel.cs
1,701
C#
namespace QuieroPizza.Win { partial class Form2 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.listadeVentasPorProductoDataGridView = new System.Windows.Forms.DataGridView(); this.button1 = new System.Windows.Forms.Button(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.listadeVentasPorProductoBindingSource = new System.Windows.Forms.BindingSource(this.components); ((System.ComponentModel.ISupportInitialize)(this.listadeVentasPorProductoDataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.listadeVentasPorProductoBindingSource)).BeginInit(); this.SuspendLayout(); // // listadeVentasPorProductoDataGridView // this.listadeVentasPorProductoDataGridView.AutoGenerateColumns = false; this.listadeVentasPorProductoDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.listadeVentasPorProductoDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn1, this.dataGridViewTextBoxColumn2, this.dataGridViewTextBoxColumn3}); this.listadeVentasPorProductoDataGridView.DataSource = this.listadeVentasPorProductoBindingSource; this.listadeVentasPorProductoDataGridView.Location = new System.Drawing.Point(0, 65); this.listadeVentasPorProductoDataGridView.Name = "listadeVentasPorProductoDataGridView"; this.listadeVentasPorProductoDataGridView.RowTemplate.Height = 24; this.listadeVentasPorProductoDataGridView.Size = new System.Drawing.Size(571, 290); this.listadeVentasPorProductoDataGridView.TabIndex = 1; // // button1 // this.button1.Location = new System.Drawing.Point(404, 13); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(156, 35); this.button1.TabIndex = 2; this.button1.Text = "Refrescar"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.DataPropertyName = "Producto"; this.dataGridViewTextBoxColumn1.HeaderText = "Producto"; this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.DataPropertyName = "Cantidad"; this.dataGridViewTextBoxColumn2.HeaderText = "Cantidad"; this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.DataPropertyName = "Total"; this.dataGridViewTextBoxColumn3.HeaderText = "Total"; this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; // // listadeVentasPorProductoBindingSource // this.listadeVentasPorProductoBindingSource.DataSource = typeof(QuieroPizza.BL.ReporteVentasPorProducto); // // Form2 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(572, 357); this.Controls.Add(this.button1); this.Controls.Add(this.listadeVentasPorProductoDataGridView); this.Name = "Form2"; this.Text = "Form2"; ((System.ComponentModel.ISupportInitialize)(this.listadeVentasPorProductoDataGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.listadeVentasPorProductoBindingSource)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.BindingSource listadeVentasPorProductoBindingSource; private System.Windows.Forms.DataGridView listadeVentasPorProductoDataGridView; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.Button button1; } }
51.964602
155
0.651226
[ "MIT" ]
diferunah/quieropizza
QuieroPizza/QuieroPizza.Win/Form2.Designer.cs
5,874
C#
namespace DesignPatterns.Creational.Singletons.MonoState { public class MonoStateSingleton { private static bool _state; public bool State { get => _state; set => _state = value; } } }
19.538462
57
0.559055
[ "MIT" ]
luizmotta01/dotnet-design-patterns
src/DesignPatterns/Creational/Singletons/MonoState/MonoStateSingleton.cs
256
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // </auto-generated> namespace Microsoft.Azure.Management.StorSimple.Fluent.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.StorSimple; using Microsoft.Azure.Management.StorSimple.Fluent; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for ScheduledBackupStatus. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ScheduledBackupStatus { [EnumMember(Value = "Disabled")] Disabled, [EnumMember(Value = "Enabled")] Enabled } internal static class ScheduledBackupStatusEnumExtension { internal static string ToSerializedValue(this ScheduledBackupStatus? value) { return value == null ? null : ((ScheduledBackupStatus)value).ToSerializedValue(); } internal static string ToSerializedValue(this ScheduledBackupStatus value) { switch( value ) { case ScheduledBackupStatus.Disabled: return "Disabled"; case ScheduledBackupStatus.Enabled: return "Enabled"; } return null; } internal static ScheduledBackupStatus? ParseScheduledBackupStatus(this string value) { switch( value ) { case "Disabled": return ScheduledBackupStatus.Disabled; case "Enabled": return ScheduledBackupStatus.Enabled; } return null; } } }
30.936508
93
0.620831
[ "MIT" ]
abharath27/azure-libraries-for-net
src/ResourceManagement/StorSimple/Generated/Models/ScheduledBackupStatus.cs
1,949
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.SpatialAwareness; using Microsoft.MixedReality.Toolkit.Utilities; using System.Collections.Generic; using Unity.Profiling; using UnityEngine; using UnityEngine.XR; #if XR_MANAGEMENT_ENABLED using UnityEngine.XR.Management; #endif // XR_MANAGEMENT_ENABLED namespace Microsoft.MixedReality.Toolkit.XRSDK { [MixedRealityDataProvider( typeof(IMixedRealitySpatialAwarenessSystem), (SupportedPlatforms)(-1) ^ SupportedPlatforms.WindowsUniversal, // All platforms supported by Unity except UWP "XR SDK Spatial Mesh Observer", "Profiles/DefaultMixedRealitySpatialAwarenessMeshObserverProfile.asset", "MixedRealityToolkit.SDK", true, SupportedUnityXRPipelines.XRSDK)] [HelpURL("https://docs.microsoft.com/windows/mixed-reality/mrtk-unity/features/spatial-awareness/spatial-awareness-getting-started")] public class GenericXRSDKSpatialMeshObserver : BaseSpatialMeshObserver, IMixedRealityCapabilityCheck { /// <summary> /// Constructor. /// </summary> /// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the service.</param> /// <param name="name">Friendly name of the service.</param> /// <param name="priority">Service priority. Used to determine order of instantiation.</param> /// <param name="profile">The service's configuration profile.</param> public GenericXRSDKSpatialMeshObserver( IMixedRealitySpatialAwarenessSystem spatialAwarenessSystem, string name = null, uint priority = DefaultPriority, BaseMixedRealityProfile profile = null) : base(spatialAwarenessSystem, name, priority, profile) { } private IReadOnlyList<GenericXRSDKSpatialMeshObserver> observersCache; protected virtual bool? IsActiveLoader { get { #if XR_MANAGEMENT_ENABLED if (XRGeneralSettings.Instance != null && XRGeneralSettings.Instance.Manager != null && XRGeneralSettings.Instance.Manager.activeLoader != null) { if ((observersCache == null || observersCache.Count == 0) && Service is IMixedRealityDataProviderAccess spatialAwarenessDataProviderAccess && Service is IMixedRealityServiceState spatialAwarenessState && spatialAwarenessState.IsInitialized) { observersCache = spatialAwarenessDataProviderAccess.GetDataProviders<GenericXRSDKSpatialMeshObserver>(); } // Don't report ourselves as active if another observer is handling this platform for (int i = 0; i < observersCache?.Count; i++) { GenericXRSDKSpatialMeshObserver observer = observersCache[i]; if (observer != this && (observer.IsActiveLoader ?? false)) { return false; } } return true; } return null; #else return false; #endif } } /// <inheritdoc /> public override void Enable() { if (!IsActiveLoader.HasValue) { IsEnabled = false; EnableIfLoaderBecomesActive(); return; } else if (!IsActiveLoader.Value) { IsEnabled = false; return; } ConfigureObserverVolume(); base.Enable(); } private async void EnableIfLoaderBecomesActive() { await new WaitUntil(() => IsActiveLoader.HasValue); if (IsActiveLoader.Value) { Enable(); } } #region BaseSpatialObserver Implementation private XRMeshSubsystem meshSubsystem; private XRMeshSubsystem MeshSubsystem => meshSubsystem != null && meshSubsystem.running ? meshSubsystem : #if XR_MANAGEMENT_ENABLED meshSubsystem = IsActiveLoader ?? false ? XRGeneralSettings.Instance.Manager.activeLoader.GetLoadedSubsystem<XRMeshSubsystem>() : null; #else meshSubsystem = XRSubsystemHelpers.MeshSubsystem; #endif // XR_MANAGEMENT_ENABLED /// <summary> /// Implements proper cleanup of the SurfaceObserver. /// </summary> protected override void CleanupObserver() { if (IsRunning) { Suspend(); } // Since we don't handle the mesh subsystem's lifecycle, we don't do anything more here. } #endregion BaseSpatialObserver Implementation #region BaseSpatialMeshObserver Implementation /// <inheritdoc /> protected override int LookupTriangleDensity(SpatialAwarenessMeshLevelOfDetail levelOfDetail) { // For non-custom levels, the enum value is the appropriate triangles per cubic meter. int level = (int)levelOfDetail; if (MeshSubsystem != null) { if (levelOfDetail == SpatialAwarenessMeshLevelOfDetail.Unlimited) { MeshSubsystem.meshDensity = 1; } else { MeshSubsystem.meshDensity = level / (float)SpatialAwarenessMeshLevelOfDetail.Fine; // For now, map Coarse to 0.0 and Fine to 1.0 } } return level; } #endregion BaseSpatialMeshObserver Implementation #region IMixedRealityCapabilityCheck Implementation /// <inheritdoc /> public bool CheckCapability(MixedRealityCapability capability) { if (capability != MixedRealityCapability.SpatialAwarenessMesh) { return false; } var descriptors = new List<XRMeshSubsystemDescriptor>(); SubsystemManager.GetSubsystemDescriptors(descriptors); return descriptors.Count > 0 && (IsActiveLoader ?? false); } #endregion IMixedRealityCapabilityCheck Implementation #region IMixedRealityDataProvider Implementation private static readonly ProfilerMarker UpdatePerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.Update"); /// <inheritdoc /> public override void Update() { using (UpdatePerfMarker.Auto()) { if (!IsEnabled) { return; } base.Update(); UpdateObserver(); } } #endregion IMixedRealityDataProvider Implementation #region IMixedRealitySpatialAwarenessObserver Implementation /// <summary> /// A queue of MeshId that need their meshes created (or updated). /// </summary> private readonly Queue<MeshId> meshWorkQueue = new Queue<MeshId>(); private readonly List<MeshInfo> meshInfos = new List<MeshInfo>(); /// <summary> /// To prevent too many meshes from being generated at the same time, we will /// only request one mesh to be created at a time. This variable will track /// if a mesh creation request is in flight. /// </summary> private SpatialAwarenessMeshObject outstandingMeshObject = null; /// <summary> /// When surfaces are replaced or removed, rather than destroying them, we'll keep /// one as a spare for use in outstanding mesh requests. That way, we'll have fewer /// game object create/destroy cycles, which should help performance. /// </summary> protected SpatialAwarenessMeshObject spareMeshObject = null; /// <summary> /// The time at which the surface observer was last asked for updated data. /// </summary> private float lastUpdated = 0; private static readonly ProfilerMarker ResumePerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.Resume"); /// <inheritdoc/> public override void Resume() { if (IsRunning) { Debug.LogWarning("The XR SDK spatial observer is currently running."); return; } using (ResumePerfMarker.Auto()) { if (MeshSubsystem != null && !MeshSubsystem.running) { MeshSubsystem.Start(); } // We want the first update immediately. lastUpdated = 0; // UpdateObserver keys off of this value to start observing. IsRunning = true; } } private static readonly ProfilerMarker SuspendPerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.Suspend"); /// <inheritdoc/> public override void Suspend() { if (!IsRunning) { Debug.LogWarning("The XR SDK spatial observer is currently stopped."); return; } using (SuspendPerfMarker.Auto()) { if (MeshSubsystem != null && MeshSubsystem.running) { MeshSubsystem.Stop(); } // UpdateObserver keys off of this value to stop observing. IsRunning = false; // Clear any pending work. meshWorkQueue.Clear(); } } private static readonly ProfilerMarker ClearObservationsPerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.ClearObservations"); /// <inheritdoc /> public override void ClearObservations() { using (ClearObservationsPerfMarker.Auto()) { bool wasRunning = false; if (IsRunning) { wasRunning = true; Suspend(); } IReadOnlyList<int> observations = new List<int>(Meshes.Keys); foreach (int meshId in observations) { RemoveMeshObject(meshId); } if (wasRunning) { Resume(); } } } #endregion IMixedRealitySpatialAwarenessObserver Implementation #region Helpers private static readonly ProfilerMarker UpdateObserverPerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.UpdateObserver"); /// <summary> /// Requests updates from the surface observer. /// </summary> private void UpdateObserver() { if (Service == null || MeshSubsystem == null) { return; } using (UpdateObserverPerfMarker.Auto()) { // Only update the observer if it is running. if (IsRunning && (outstandingMeshObject == null)) { // If we have a mesh to work on... if (meshWorkQueue.Count > 0) { // We're using a simple first-in-first-out rule for requesting meshes, but a more sophisticated algorithm could prioritize // the queue based on distance to the user or some other metric. RequestMesh(meshWorkQueue.Dequeue()); } // If enough time has passed since the previous observer update... else if (Time.time - lastUpdated >= UpdateInterval) { // Update the observer orientation if user aligned if (ObserverVolumeType == VolumeType.UserAlignedCube) { ObserverRotation = CameraCache.Main.transform.rotation; } // Update the observer location if it is not stationary if (!IsStationaryObserver) { ObserverOrigin = CameraCache.Main.transform.position; } // The application can update the observer volume at any time, make sure we are using the latest. ConfigureObserverVolume(); if (MeshSubsystem.TryGetMeshInfos(meshInfos)) { UpdateMeshes(meshInfos); } lastUpdated = Time.time; } } } } private static readonly ProfilerMarker RequestMeshPerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.RequestMesh"); /// <summary> /// Issue a request to the Surface Observer to begin baking the mesh. /// </summary> /// <param name="meshId">ID of the mesh to bake.</param> private void RequestMesh(MeshId meshId) { using (RequestMeshPerfMarker.Auto()) { string meshName = ("SpatialMesh - " + meshId); SpatialAwarenessMeshObject newMesh; if (spareMeshObject == null) { newMesh = SpatialAwarenessMeshObject.Create( null, MeshPhysicsLayer, meshName, meshId.GetHashCode()); } else { newMesh = spareMeshObject; spareMeshObject = null; newMesh.GameObject.name = meshName; newMesh.Id = meshId.GetHashCode(); newMesh.GameObject.SetActive(true); } MeshSubsystem.GenerateMeshAsync(meshId, newMesh.Filter.mesh, newMesh.Collider, MeshVertexAttributes.Normals, (MeshGenerationResult meshGenerationResult) => MeshGenerationAction(meshGenerationResult)); outstandingMeshObject = newMesh; } } private static readonly ProfilerMarker RemoveMeshObjectPerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.RemoveMeshObject"); /// <summary> /// Removes the <see cref="SpatialAwareness.SpatialAwarenessMeshObject"/> associated with the specified id. /// </summary> /// <param name="id">The id of the mesh to be removed.</param> protected void RemoveMeshObject(int id) { using (RemoveMeshObjectPerfMarker.Auto()) { if (meshes.TryGetValue(id, out SpatialAwarenessMeshObject mesh)) { // Remove the mesh object from the collection. meshes.Remove(id); // Reclaim the mesh object for future use. ReclaimMeshObject(mesh); // Send the mesh removed event meshEventData.Initialize(this, id, null); Service?.HandleEvent(meshEventData, OnMeshRemoved); } } } private static readonly ProfilerMarker ReclaimMeshObjectPerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.ReclaimMeshObject"); /// <summary> /// Reclaims the <see cref="SpatialAwareness.SpatialAwarenessMeshObject"/> to allow for later reuse. /// </summary> protected void ReclaimMeshObject(SpatialAwarenessMeshObject availableMeshObject) { using (ReclaimMeshObjectPerfMarker.Auto()) { if (spareMeshObject == null) { // Cleanup the mesh object. // Do not destroy the game object, destroy the meshes. SpatialAwarenessMeshObject.Cleanup(availableMeshObject, false); if (availableMeshObject.GameObject != null) { availableMeshObject.GameObject.name = "Unused Spatial Mesh"; availableMeshObject.GameObject.SetActive(false); } spareMeshObject = availableMeshObject; } else { // Cleanup the mesh object. // Destroy the game object, destroy the meshes. SpatialAwarenessMeshObject.Cleanup(availableMeshObject); } } } private static readonly ProfilerMarker ConfigureObserverVolumePerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.ConfigureObserverVolume"); private Vector3 oldObserverOrigin = Vector3.zero; private Vector3 oldObservationExtents = Vector3.zero; private VolumeType oldObserverVolumeType = VolumeType.None; /// <summary> /// Applies the configured observation extents. /// </summary> protected virtual void ConfigureObserverVolume() { if (MeshSubsystem == null || (oldObserverOrigin == ObserverOrigin && oldObservationExtents == ObservationExtents && oldObserverVolumeType == ObserverVolumeType)) { return; } using (ConfigureObserverVolumePerfMarker.Auto()) { Vector3 observerOriginPlayspace = MixedRealityPlayspace.InverseTransformPoint(ObserverOrigin); // Update the observer switch (ObserverVolumeType) { case VolumeType.AxisAlignedCube: MeshSubsystem.SetBoundingVolume(observerOriginPlayspace, ObservationExtents); break; default: Debug.LogError($"Unsupported ObserverVolumeType value {ObserverVolumeType}"); break; } oldObserverOrigin = ObserverOrigin; oldObservationExtents = ObservationExtents; oldObserverVolumeType = ObserverVolumeType; } } private static readonly ProfilerMarker UpdateMeshesPerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.UpdateMeshes"); /// <summary> /// Updates meshes based on the result of the MeshSubsystem.TryGetMeshInfos method. /// </summary> private void UpdateMeshes(List<MeshInfo> meshInfos) { if (!IsRunning) { return; } using (UpdateMeshesPerfMarker.Auto()) { foreach (MeshInfo meshInfo in meshInfos) { switch (meshInfo.ChangeState) { case MeshChangeState.Added: case MeshChangeState.Updated: meshWorkQueue.Enqueue(meshInfo.MeshId); break; case MeshChangeState.Removed: RemoveMeshObject(meshInfo.MeshId.GetHashCode()); break; } } } } private static readonly ProfilerMarker MeshGenerationActionPerfMarker = new ProfilerMarker("[MRTK] GenericXRSDKSpatialMeshObserver.MeshGenerationAction"); private void MeshGenerationAction(MeshGenerationResult meshGenerationResult) { if (!IsRunning) { return; } using (MeshGenerationActionPerfMarker.Auto()) { if (outstandingMeshObject == null) { Debug.LogWarning($"MeshGenerationAction called for mesh id {meshGenerationResult.MeshId} while no request was outstanding."); return; } switch (meshGenerationResult.Status) { case MeshGenerationStatus.InvalidMeshId: case MeshGenerationStatus.Canceled: case MeshGenerationStatus.UnknownError: outstandingMeshObject = null; break; case MeshGenerationStatus.Success: // Since there is only one outstanding mesh object, update the id to match // the one received after baking. SpatialAwarenessMeshObject meshObject = outstandingMeshObject; meshObject.Id = meshGenerationResult.MeshId.GetHashCode(); outstandingMeshObject = null; // Check to see if this is a new or updated mesh. bool isMeshUpdate = meshes.ContainsKey(meshObject.Id); // We presume that if the display option is not occlusion, that we should // default to the visible material. // Note: We check explicitly for a display option of none later in this method. Material material = (DisplayOption == SpatialAwarenessMeshDisplayOptions.Occlusion) ? OcclusionMaterial : VisibleMaterial; // If this is a mesh update, we want to preserve the mesh's previous material. material = isMeshUpdate ? meshes[meshObject.Id].Renderer.sharedMaterial : material; // Apply the appropriate material. meshObject.Renderer.sharedMaterial = material; // Recalculate the mesh normals if requested. if (RecalculateNormals) { meshObject.Filter.sharedMesh.RecalculateNormals(); } // Check to see if the display option is set to none. If so, we disable // the renderer. meshObject.Renderer.enabled = (DisplayOption != SpatialAwarenessMeshDisplayOptions.None); // Set the physics material if (meshObject.Renderer.enabled) { meshObject.Collider.material = PhysicsMaterial; } // Add / update the mesh to our collection if (isMeshUpdate) { // Reclaim the old mesh object for future use. ReclaimMeshObject(meshes[meshObject.Id]); meshes.Remove(meshObject.Id); } meshes.Add(meshObject.Id, meshObject); // This is important. We need to preserve the mesh's local transform here, not its global pose. // Think of it like this. If we set the camera's coordinates 3 meters to the left, the physical camera // hasn't moved, only its coordinates have changed. Likewise, the physical room hasn't moved (relative to // the physical camera), so we also want to set its coordinates 3 meters to the left. Transform meshObjectParent = (ObservedObjectParent.transform != null) ? ObservedObjectParent.transform : null; meshObject.GameObject.transform.SetParent(meshObjectParent, false); meshEventData.Initialize(this, meshObject.Id, meshObject); if (isMeshUpdate) { Service?.HandleEvent(meshEventData, OnMeshUpdated); } else { Service?.HandleEvent(meshEventData, OnMeshAdded); } break; } } } #endregion Helpers public override void Initialize() { base.Initialize(); if (Service == null || MeshSubsystem == null) { return; } if (RuntimeSpatialMeshPrefab != null) { AddRuntimeSpatialMeshPrefabToHierarchy(); } } } }
39.303175
216
0.545858
[ "MIT" ]
BillyFrcs/MixedRealityToolkit-Unity
Assets/MRTK/Providers/XRSDK/GenericXRSDKSpatialMeshObserver.cs
24,763
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using NuGetGallery.Configuration; using WebBackgrounder; namespace NuGetGallery { public interface IIndexingService { Task<DateTime?> GetLastWriteTime(); void UpdateIndex(); void UpdateIndex(bool forceRefresh); void UpdatePackage(Package package); Task<int> GetDocumentCount(); Task<long> GetIndexSizeInBytes(); void RegisterBackgroundJobs(IList<IJob> jobs, IAppConfiguration configuration); string IndexPath { get; } bool IsLocal { get; } } }
29.884615
111
0.709138
[ "Apache-2.0" ]
DevlinSchoonraad/NuGetGallery
src/NuGetGallery/Services/IIndexingService.cs
779
C#