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 System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Elide.Scintilla;
namespace Elide.EilCode.Lexer {
internal sealed partial class Parser {
public const int _EOF = 0;
public const int _ident = 1;
public const int _intTok = 2;
public const int _address = 3;
public const int _stringTok = 4;
public const int _charTok = 5;
public const int _operatorTok = 6;
public const int _NL = 7;
public const int maxT = 107;
const bool T = true;
const bool x = false;
const int minErrDist = 2;
public Scanner scanner;
public Errors errors;
public Token t; // last recognized token
public Token la; // lookahead token
int errDist = minErrDist;
public Parser(Scanner scanner) {
ErrorCount = 0;
this.scanner = scanner;
errors = new Errors(this);
}
void SynErr (int n) {
if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n);
errDist = 0;
}
public void SemErr (string msg) {
if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg);
errDist = 0;
}
void Get () {
for (;;) {
t = la;
la = scanner.Scan();
if (la.kind <= maxT) { ++errDist; break; }
la = t;
}
}
void Expect (int n) {
if (la.kind==n) Get(); else { SynErr(n); }
}
bool StartOf (int s) {
return set[s, la.kind];
}
void ExpectWeak (int n, int follow) {
if (la.kind == n) Get();
else {
SynErr(n);
while (!StartOf(follow)) Get();
}
}
bool WeakSeparator(int n, int syFol, int repFol) {
int kind = la.kind;
if (kind == n) {Get(); return true;}
else if (StartOf(repFol)) {return false;}
else {
SynErr(n);
while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) {
Get();
kind = la.kind;
}
return StartOf(syFol);
}
}
void SingleLineComment() {
Expect(8);
var pos = t.pos;
while (StartOf(1)) {
Get();
}
if (la.kind == 7) {
Get();
} else if (la.kind == 0) {
Get();
} else SynErr(108);
Add(pos, t.pos - pos + t.val.Length, TextStyle.Style4);
}
void OpNum() {
Expect(9);
Add(t.pos, t.val.Length, TextStyle.Style7);
Expect(2);
Add(t.pos, t.val.Length, TextStyle.Style7);
Expect(10);
Add(t.pos, t.val.Length, TextStyle.Style7);
}
void Keyword() {
switch (la.kind) {
case 11: {
Get();
break;
}
case 12: {
Get();
break;
}
case 13: {
Get();
break;
}
case 14: {
Get();
break;
}
case 15: {
Get();
break;
}
case 16: {
Get();
break;
}
case 17: {
Get();
break;
}
case 18: {
Get();
break;
}
case 19: {
Get();
break;
}
case 20: {
Get();
break;
}
case 21: {
Get();
break;
}
case 22: {
Get();
break;
}
case 23: {
Get();
break;
}
case 24: {
Get();
break;
}
case 25: {
Get();
break;
}
case 26: {
Get();
break;
}
case 27: {
Get();
break;
}
case 28: {
Get();
break;
}
case 29: {
Get();
break;
}
case 30: {
Get();
break;
}
case 31: {
Get();
break;
}
case 32: {
Get();
break;
}
case 33: {
Get();
break;
}
case 34: {
Get();
break;
}
case 35: {
Get();
break;
}
case 36: {
Get();
break;
}
case 37: {
Get();
break;
}
case 38: {
Get();
break;
}
case 39: {
Get();
break;
}
case 40: {
Get();
break;
}
case 41: {
Get();
break;
}
case 42: {
Get();
break;
}
case 43: {
Get();
break;
}
case 44: {
Get();
break;
}
case 45: {
Get();
break;
}
case 46: {
Get();
break;
}
case 47: {
Get();
break;
}
case 48: {
Get();
break;
}
case 49: {
Get();
break;
}
case 50: {
Get();
break;
}
case 51: {
Get();
break;
}
case 52: {
Get();
break;
}
case 53: {
Get();
break;
}
case 54: {
Get();
break;
}
case 55: {
Get();
break;
}
case 56: {
Get();
break;
}
case 57: {
Get();
break;
}
case 58: {
Get();
break;
}
case 59: {
Get();
break;
}
case 60: {
Get();
break;
}
case 61: {
Get();
break;
}
case 62: {
Get();
break;
}
case 63: {
Get();
break;
}
case 64: {
Get();
break;
}
case 65: {
Get();
break;
}
case 66: {
Get();
break;
}
case 67: {
Get();
break;
}
case 68: {
Get();
break;
}
case 69: {
Get();
break;
}
case 70: {
Get();
break;
}
case 71: {
Get();
break;
}
case 72: {
Get();
break;
}
case 73: {
Get();
break;
}
case 74: {
Get();
break;
}
case 75: {
Get();
break;
}
case 76: {
Get();
break;
}
case 77: {
Get();
break;
}
case 78: {
Get();
break;
}
case 79: {
Get();
break;
}
case 80: {
Get();
break;
}
case 81: {
Get();
break;
}
case 82: {
Get();
break;
}
case 83: {
Get();
break;
}
case 84: {
Get();
break;
}
case 85: {
Get();
break;
}
case 86: {
Get();
break;
}
case 87: {
Get();
break;
}
case 88: {
Get();
break;
}
case 89: {
Get();
break;
}
case 90: {
Get();
break;
}
case 91: {
Get();
break;
}
case 92: {
Get();
break;
}
case 93: {
Get();
break;
}
case 94: {
Get();
break;
}
case 95: {
Get();
break;
}
case 96: {
Get();
break;
}
case 97: {
Get();
break;
}
case 98: {
Get();
break;
}
case 99: {
Get();
break;
}
case 100: {
Get();
break;
}
case 101: {
Get();
break;
}
case 102: {
Get();
break;
}
case 103: {
Get();
break;
}
case 104: {
Get();
break;
}
case 105: {
Get();
break;
}
case 106: {
Get();
break;
}
default: SynErr(109); break;
}
Add(t.pos, t.val.Length, TextStyle.Style2);
}
void Value() {
if (la.kind == 1) {
Get();
Add(t.pos, t.val.Length, TextStyle.Style1);
} else if (la.kind == 6) {
Get();
Add(t.pos, t.val.Length, TextStyle.Style3);
} else if (la.kind == 2) {
Get();
Add(t.pos, t.val.Length, TextStyle.Style6);
} else if (la.kind == 4) {
Get();
Add(t.pos, t.val.Length, TextStyle.Style5);
} else if (la.kind == 3) {
Get();
Add(t.pos, t.val.Length, TextStyle.Style8);
} else SynErr(110);
}
void Code() {
if (la.kind == 9) {
OpNum();
} else if (StartOf(2)) {
Keyword();
} else if (StartOf(3)) {
Value();
} else if (la.kind == 8) {
SingleLineComment();
} else if (la.kind == 7) {
Get();
} else SynErr(111);
}
void Eil() {
Code();
while (StartOf(4)) {
Code();
}
}
public void Parse() {
la = new Token();
la.val = "";
Get();
Eil();
Expect(0);
Expect(0);
}
static readonly bool[,] set = {
{T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x},
{x,T,T,T, T,T,T,x, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, x},
{x,x,x,x, x,x,x,x, x,x,x,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,x, x},
{x,T,T,T, T,x,T,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x},
{x,T,T,T, T,x,T,T, T,T,x,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,T, T,T,T,x, x}
};
} // end Parser
internal sealed class Errors {
private Parser p;
internal Errors(Parser p)
{
this.p = p;
}
internal void SynErr (int line, int col, int n) {
string s;
switch (n) {
case 0: s = "EOF expected"; break;
case 1: s = "ident expected"; break;
case 2: s = "intTok expected"; break;
case 3: s = "address expected"; break;
case 4: s = "stringTok expected"; break;
case 5: s = "charTok expected"; break;
case 6: s = "operatorTok expected"; break;
case 7: s = "NL expected"; break;
case 8: s = "\"//\" expected"; break;
case 9: s = "\"[\" expected"; break;
case 10: s = "\"]\" expected"; break;
case 11: s = "\"Nop\" expected"; break;
case 12: s = "\"Len\" expected"; break;
case 13: s = "\"Pushunit\" expected"; break;
case 14: s = "\"Pushelem\" expected"; break;
case 15: s = "\"Pushfld\" expected"; break;
case 16: s = "\"Hasfld\" expected"; break;
case 17: s = "\"PushI4_0\" expected"; break;
case 18: s = "\"PushI1_0\" expected"; break;
case 19: s = "\"PushI1_1\" expected"; break;
case 20: s = "\"Pop\" expected"; break;
case 21: s = "\"Pushstr_0\" expected"; break;
case 22: s = "\"Genfin\" expected"; break;
case 23: s = "\"Cons\" expected"; break;
case 24: s = "\"Tail\" expected"; break;
case 25: s = "\"Head\" expected"; break;
case 26: s = "\"Ret\" expected"; break;
case 27: s = "\"Concat\" expected"; break;
case 28: s = "\"Add\" expected"; break;
case 29: s = "\"Mul\" expected"; break;
case 30: s = "\"Div\" expected"; break;
case 31: s = "\"Quot\" expected"; break;
case 32: s = "\"Rem\" expected"; break;
case 33: s = "\"Mod\" expected"; break;
case 34: s = "\"Pow\" expected"; break;
case 35: s = "\"Sub\" expected"; break;
case 36: s = "\"Shr\" expected"; break;
case 37: s = "\"Shl\" expected"; break;
case 38: s = "\"Ceq\" expected"; break;
case 39: s = "\"Cneq\" expected"; break;
case 40: s = "\"Clt\" expected"; break;
case 41: s = "\"Cgt\" expected"; break;
case 42: s = "\"Cgteq\" expected"; break;
case 43: s = "\"Clteq\" expected"; break;
case 44: s = "\"AndBw\" expected"; break;
case 45: s = "\"OrBw\" expected"; break;
case 46: s = "\"Xor\" expected"; break;
case 47: s = "\"Not\" expected"; break;
case 48: s = "\"Neg\" expected"; break;
case 49: s = "\"NotBw\" expected"; break;
case 50: s = "\"Dup\" expected"; break;
case 51: s = "\"Swap\" expected"; break;
case 52: s = "\"Newlazy\" expected"; break;
case 53: s = "\"Newlist\" expected"; break;
case 54: s = "\"Newtup_2\" expected"; break;
case 55: s = "\"Stop\" expected"; break;
case 56: s = "\"NewI8\" expected"; break;
case 57: s = "\"NewR8\" expected"; break;
case 58: s = "\"Leave\" expected"; break;
case 59: s = "\"Flip\" expected"; break;
case 60: s = "\"LazyCall\" expected"; break;
case 61: s = "\"Call\" expected"; break;
case 62: s = "\"Callt\" expected"; break;
case 63: s = "\"Ctx\" expected"; break;
case 64: s = "\"Throw\" expected"; break;
case 65: s = "\"Rethrow\" expected"; break;
case 66: s = "\"Force\" expected"; break;
case 67: s = "\"Isnil\" expected"; break;
case 68: s = "\"Show\" expected"; break;
case 69: s = "\"Addmbr\" expected"; break;
case 70: s = "\"Traitch\" expected"; break;
case 71: s = "\"Skiptag\" expected"; break;
case 72: s = "\"Newtype\" expected"; break;
case 73: s = "\"Newtype0\" expected"; break;
case 74: s = "\"Newtype1\" expected"; break;
case 75: s = "\"Newtype2\" expected"; break;
case 76: s = "\"Ctype\" expected"; break;
case 77: s = "\"Disp\" expected"; break;
case 78: s = "\"Newconst\" expected"; break;
case 79: s = "\"Api\" expected"; break;
case 80: s = "\"Api2\" expected"; break;
case 81: s = "\"Untag\" expected"; break;
case 82: s = "\"Reccons\" expected"; break;
case 83: s = "\"Tupcons\" expected"; break;
case 84: s = "\"Ctorid\" expected"; break;
case 85: s = "\"Typeid\" expected"; break;
case 86: s = "\"Classid\" expected"; break;
case 87: s = "\"Newfunc\" expected"; break;
case 88: s = "\"Newmod\" expected"; break;
case 89: s = "\"Pushext\" expected"; break;
case 90: s = "\"Newrec\" expected"; break;
case 91: s = "\"Newtup\" expected"; break;
case 92: s = "\"Failwith\" expected"; break;
case 93: s = "\"Start\" expected"; break;
case 94: s = "\"Pushstr\" expected"; break;
case 95: s = "\"PushCh\" expected"; break;
case 96: s = "\"PushI4\" expected"; break;
case 97: s = "\"PushR4\" expected"; break;
case 98: s = "\"Pushloc\" expected"; break;
case 99: s = "\"Pushvar\" expected"; break;
case 100: s = "\"Poploc\" expected"; break;
case 101: s = "\"Popvar\" expected"; break;
case 102: s = "\"Runmod\" expected"; break;
case 103: s = "\"Br\" expected"; break;
case 104: s = "\"Brtrue\" expected"; break;
case 105: s = "\"Brfalse\" expected"; break;
case 106: s = "\"Newfun\" expected"; break;
case 107: s = "??? expected"; break;
case 108: s = "invalid SingleLineComment"; break;
case 109: s = "invalid Keyword"; break;
case 110: s = "invalid Value"; break;
case 111: s = "invalid Code"; break;
default: s = "error " + n; break;
}
//Console.WriteLine(s + "; line=" + line + ";col=" + col);
p.ErrorCount++;
//ErrorList.Add(new ElaError(s, ElaErrorType.Parser_SyntaxError, new ElaLinePragma(line, col)));
}
internal void SemErr (int line, int col, string s) {
//ErrorList.Add(new ElaError(s, ElaErrorType.Parser_SemanticError, new ElaLinePragma(line, col)));
p.ErrorCount++;
}
internal void SemErr (string s) {
//ErrorList.Add(new ElaError(s, ElaErrorType.Parser_SemanticError, null));
p.ErrorCount++;
}
} // Errors
public class FatalError: Exception {
public FatalError(string m): base(m) {}
}
} | 20.298343 | 250 | 0.491222 | [
"MIT"
] | vorov2/ela | Elide/Elide.EilCode/Lexer/Parser.cs | 14,696 | 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 DesktopGUI.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.129032 | 151 | 0.568411 | [
"Apache-2.0"
] | Airylan/RehearsalScheduler | RehearsalScheduler/DesktopGUI/Properties/Settings.Designer.cs | 1,091 | C# |
using System;
namespace SGson.Test.Entity
{
public class ArrayCase
{
public int[] ArrayUndifined { get; set; }
public ulong[] ArrayNull { get; set; }
public sbyte[] ArrayEmpty { get; set; }
public double[,,] MultidimensionalArray { get; set; }
public double[,,] MultidimensionalArrayEmpty0 { get; set; }
public double[,,] MultidimensionalArrayEmpty1 { get; set; }
public double[,,] MultidimensionalArrayEmpty2 { get; set; }
public string[][] JaggedArray { get; set; }
public string[][] JaggedArrayEmpty0 { get; set; }
public string[][] JaggedArrayEmpty1 { get; set; }
}
} | 33.055556 | 61 | 0.689076 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | zaobao/SGson | test/Entity/ArrayCase.cs | 595 | C# |
namespace BashSoft.App
{
using IO;
using Core;
using BashSoft.App.Repositories;
using BashSoft.App.SimpleJudge;
public class StartUp
{
public static void Main(string[] args)
{
var commandInterpreter = new CommandInterpreter();
var inputReader = new InputReader(commandInterpreter);
inputReader.StartReadingCommands();
// TESTS:
//IOManager.ChangeCurrentDirectoryAbsolute("C:\\Windows");
//IOManager.TraverseDirectory(20);
//IOManager.CreateDirectoryInCurrentFolder("InvalidSymbol -> *");
//StudentRepository.InitializeData();
//StudentRepository.GetAllStudentsFromCourse("Unity");
//StudentRepository.GetStudentScoresFromCourse("Unity", "Ivan");
//Tester.CompareContent(@"IO\Files\test2.txt", @"IO\Files\test3.txt");
//Tester.CompareContent(@"D:\UnexsistentDirectory\UnexistentFile.txt", @"D:\AnotherUnexsistentDirectory\AnotherUnexistentFile.txt");
}
}
}
| 33.09375 | 144 | 0.641171 | [
"MIT"
] | msotiroff/Softuni-learning | C# Fundamentals Module/CSharp-Advanced/Jan 2018 instance/Bash-Soft/Solution/BashSoft/BashSoft.App/StartUp.cs | 1,061 | C# |
using System;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
namespace ew
{
public struct Head : IComponentData
{
public float theta;
public int spineId;
public int boidId;
}
public struct Tail : IComponentData
{
public float theta;
public int boidId;
public int spineId;
}
[BurstCompile]
struct HeadJob : IJobProcessComponentData<Head, Position, Rotation>
{
[NativeDisableParallelForRestriction]
public NativeArray<Vector3> positions;
[NativeDisableParallelForRestriction]
public NativeArray<Quaternion> rotations;
[NativeDisableParallelForRestriction]
public NativeArray<float> speeds;
public float amplitude;
public float frequency;
public float size;
public float dT;
public void Execute(ref Head h, ref Position p, ref Rotation r)
{
Vector3 up = Vector3.up;
Quaternion q = rotations[h.spineId] * Quaternion.AngleAxis(Mathf.Sin(h.theta) * amplitude, up);
// Calculate the center point of the head
Vector3 pos = positions[h.spineId]
+ rotations[h.spineId] * (Vector3.forward * size * 0.5f)
+ q * (Vector3.forward * size * 0.5f);
p.Value = pos;
r.Value = q;
h.theta += frequency * dT * Mathf.PI * 2.0f * speeds[h.boidId];
}
}
[BurstCompile]
struct TailJob : IJobProcessComponentData<Tail, Position, Rotation>
{
[NativeDisableParallelForRestriction]
public NativeArray<Vector3> positions;
[NativeDisableParallelForRestriction]
public NativeArray<Quaternion> rotations;
[NativeDisableParallelForRestriction]
public NativeArray<float> speeds;
public float amplitude;
public float frequency;
public float size;
public float dT;
public void Execute(ref Tail t, ref Position p, ref Rotation r)
{
Vector3 up = Vector3.up;
Quaternion q = rotations[t.spineId] * Quaternion.AngleAxis(Mathf.Sin(-t.theta) * amplitude, up);
// Calculate the center point of the tail
//Vector3 pos = positions[t.spineId] - q * (Vector3.forward * size * 0.5f);
Vector3 pos = positions[t.spineId]
- rotations[t.spineId] * (Vector3.forward * size * 0.5f)
- q * (Vector3.forward * size * 0.5f);
p.Value = pos;
r.Value = q;
t.theta += frequency * dT * Mathf.PI * 2.0f * speeds[t.boidId];
}
}
[UpdateAfter(typeof(SpineSystem))]
public class HeadsAndTailsSystem : JobComponentSystem
{
public BoidBootstrap bootstrap;
public static HeadsAndTailsSystem Instance;
protected override void OnCreateManager()
{
Instance = this;
bootstrap = GameObject.FindObjectOfType<BoidBootstrap>();
Enabled = false;
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
// Animate the head and tail
var headJob = new HeadJob()
{
positions = SpineSystem.Instance.positions,
rotations = SpineSystem.Instance.rotations,
speeds = BoidJobSystem.Instance.speeds,
dT = Time.deltaTime * bootstrap.speed,
amplitude = bootstrap.headAmplitude,
frequency = bootstrap.animationFrequency,
size = bootstrap.size
};
var headHandle = headJob.Schedule(this, inputDeps);// Animate the head and tail
var tailJob = new TailJob()
{
positions = SpineSystem.Instance.positions,
rotations = SpineSystem.Instance.rotations,
speeds = BoidJobSystem.Instance.speeds,
dT = Time.deltaTime * bootstrap.speed,
amplitude = bootstrap.tailAmplitude,
frequency = bootstrap.animationFrequency,
size = bootstrap.size
};
return tailJob.Schedule(this, headHandle);
}
}
} | 32.282609 | 109 | 0.573962 | [
"MIT"
] | skooter500/Forms | Assets/ECSBoids/HeadsAndTailsSystem.cs | 4,457 | C# |
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.
[assembly: AssemblyTitle("Data.EFProvider")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Data.EFProvider")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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("b8638736-00e8-4cbb-bfe2-f58aca687d4f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.756757 | 85 | 0.728731 | [
"MIT"
] | cestavede/TestEFMigrations | Data.EFProvider/Properties/AssemblyInfo.cs | 1,437 | C# |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Microsoft.Kinect.Face
{
//
// Microsoft.Kinect.Face.HighDefinitionFaceFrameReference
//
public sealed partial class HighDefinitionFaceFrameReference : Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal HighDefinitionFaceFrameReference(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Microsoft_Kinect_Face_HighDefinitionFaceFrameReference_AddRefObject(ref _pNative);
}
~HighDefinitionFaceFrameReference()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameReference_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameReference_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
__EventCleanup();
Helper.NativeObjectCache.RemoveObject<HighDefinitionFaceFrameReference>(_pNative);
Microsoft_Kinect_Face_HighDefinitionFaceFrameReference_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern long Microsoft_Kinect_Face_HighDefinitionFaceFrameReference_get_RelativeTime(RootSystem.IntPtr pNative);
public RootSystem.TimeSpan RelativeTime
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameReference");
}
return RootSystem.TimeSpan.FromMilliseconds(Microsoft_Kinect_Face_HighDefinitionFaceFrameReference_get_RelativeTime(_pNative));
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_HighDefinitionFaceFrameReference_AcquireFrame(RootSystem.IntPtr pNative);
public Microsoft.Kinect.Face.HighDefinitionFaceFrame AcquireFrame()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameReference");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_HighDefinitionFaceFrameReference_AcquireFrame(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.HighDefinitionFaceFrame>(objectPointer, n => new Microsoft.Kinect.Face.HighDefinitionFaceFrame(n));
}
private void __EventCleanup()
{
}
}
}
| 42.277778 | 183 | 0.704074 | [
"Apache-2.0"
] | Cheezegami/Hybrid_Space-Autumn-Blues | Assets/Plugins/Standard Assets/Microsoft/Kinect/Face/HighDefinitionFaceFrameReference.cs | 3,805 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerPawn : Pawn
{
public virtual void Start()
{
IgnoresDamage = false;
}
public virtual void Horizontal(float value)
{
}
public virtual void Vertical(float value)
{
}
public virtual void Fire1(bool value)
{
}
public virtual void Fire2(bool value)
{
}
public virtual void Fire3(bool value)
{
}
public virtual void Fire4(bool value)
{
}
public virtual void Fire5(bool value)
{
}
public virtual void Fire6(bool value)
{
}
//public virtual void P1Horizontal(float value)
//{
//}
//public virtual void P1Vertical(float value)
//{
//}
//public virtual void P1Fire1(bool value)
//{
//}
//public virtual void P1Fire2(bool value)
//{
//}
//public virtual void P1Fire3(bool value)
//{
//}
//public virtual void P1Fire4(bool value)
//{
//}
//public virtual void P2Horizontal(float value)
//{
//}
//public virtual void P2Vertical(float value)
//{
//}
//public virtual void P2Fire1(bool value)
//{
//}
//public virtual void P2Fire2(bool value)
//{
//}
//public virtual void P2Fire3(bool value)
//{
//}
//public virtual void P2Fire4(bool value)
//{
//}
//public virtual void P3Horizontal(float value)
//{
//}
//public virtual void P3Vertical(float value)
//{
//}
//public virtual void P3Fire1(bool value)
//{
//}
//public virtual void P3Fire2(bool value)
//{
//}
//public virtual void P3Fire3(bool value)
//{
//}
//public virtual void P3Fire4(bool value)
//{
//}
//public virtual void P4Horizontal(float value)
//{
//}
//public virtual void P4Vertical(float value)
//{
//}
//public virtual void P4Fire1(bool value)
//{
//}
//public virtual void P4Fire2(bool value)
//{
//}
//public virtual void P4Fire3(bool value)
//{
//}
//public virtual void P4Fire4(bool value)
//{
//}
}
| 13.011364 | 51 | 0.555022 | [
"MIT"
] | AGGP-NHTI/Empowered | Assets/Player_Scripts/PlayerPawn.cs | 2,292 | C# |
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;
namespace Netch.Utils
{
public static class TUNTAP
{
public static string TUNTAP_COMPONENT_ID_0901 = "tap0901";
public static string TUNTAP_COMPONENT_ID_0801 = "tap0801";
public static string NETWORK_KEY = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
public static string ADAPTER_KEY = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
/// <summary>
/// 获取 TUN/TAP 适配器 ID
/// </summary>
/// <returns>适配器 ID</returns>
public static string GetComponentID()
{
try
{
var adaptersRegistry = Registry.LocalMachine.OpenSubKey(ADAPTER_KEY);
foreach (var adapterRegistryName in adaptersRegistry.GetSubKeyNames())
{
if (adapterRegistryName != "Configuration" && adapterRegistryName != "Properties")
{
var adapterRegistry = adaptersRegistry.OpenSubKey(adapterRegistryName);
var adapterComponentId = adapterRegistry.GetValue("ComponentId", "").ToString();
if (adapterComponentId == TUNTAP_COMPONENT_ID_0901 || adapterComponentId == TUNTAP_COMPONENT_ID_0801)
{
return adapterRegistry.GetValue("NetCfgInstanceId", "").ToString();
}
}
}
}
catch (Exception e)
{
Logging.Warning(e.ToString());
}
return "";
}
/// <summary>
/// 获取 TUN/TAP 适配器名称
/// </summary>
/// <param name="componentId">适配器 ID</param>
/// <returns>适配器名称</returns>
public static string GetName(string componentId)
{
var registry = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}\\Connection", NETWORK_KEY, componentId));
return registry.GetValue("Name", "").ToString();
}
/// <summary>
/// 创建 TUN/TAP 适配器
/// </summary>
/// <returns></returns>
public static bool Create()
{
return false;
}
/// <summary>
/// 卸载tap网卡
/// </summary>
public static void deltapall()
{
Logging.Info("正在卸载 TUN/TAP 适配器");
var installProcess = new Process {StartInfo = {WindowStyle = ProcessWindowStyle.Hidden, FileName = Path.Combine("bin/tap-driver", "deltapall.bat")}};
installProcess.Start();
installProcess.WaitForExit();
installProcess.Close();
}
/// <summary>
/// 安装tap网卡
/// </summary>
public static void addtap()
{
Logging.Info("正在安装 TUN/TAP 适配器");
//安装Tap Driver
var installProcess = new Process {StartInfo = {WindowStyle = ProcessWindowStyle.Hidden, FileName = Path.Combine("bin/tap-driver", "addtap.bat")}};
installProcess.Start();
installProcess.WaitForExit();
installProcess.Close();
}
}
} | 35.204301 | 161 | 0.544594 | [
"MIT"
] | yakasuakanakata/Netch | Netch/Utils/TUNTAP.cs | 3,380 | C# |
using System;
using RenderingPipe.Resources;
namespace RenderingPipe.Commands
{
class RenderTargetClearCommand: IRenderCommand
{
public RenderCommandType RenderCommandType
{
get { return RenderCommandType.Clear_Color; }
}
public override string ToString()
{
return String.Format("ClearColor: {0}"
, Color);
}
public UInt32 ResourceID
{
get;
private set;
}
public Color4 Color
{
get;
private set;
}
public RenderTargetClearCommand Create(TextureResource resource, Color4 color)
{
if (resource == null)
{
return null;
}
return new RenderTargetClearCommand
{
ResourceID = resource.ID,
Color = color,
};
}
}
}
| 22.133333 | 87 | 0.473896 | [
"MIT"
] | ousttrue/ModelGenerics | RenderingPipe/Commands/RenderTargetClearCommand.cs | 998 | C# |
/*
* Copyright 2010-2014 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 iam-2010-05-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IdentityManagement.Model
{
/// <summary>
/// Container for the parameters to the ListRoleTags operation.
/// Lists the tags that are attached to the specified role. The returned list of tags
/// is sorted by tag key. For more information about tagging, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html">Tagging
/// IAM Identities</a> in the <i>IAM User Guide</i>.
/// </summary>
public partial class ListRoleTagsRequest : AmazonIdentityManagementServiceRequest
{
private string _marker;
private int? _maxItems;
private string _roleName;
/// <summary>
/// Gets and sets the property Marker.
/// <para>
/// Use this parameter only when paginating results and only after you receive a response
/// indicating that the results are truncated. Set it to the value of the <code>Marker</code>
/// element in the response that you received to indicate where the next call should start.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=320)]
public string Marker
{
get { return this._marker; }
set { this._marker = value; }
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this._marker != null;
}
/// <summary>
/// Gets and sets the property MaxItems.
/// <para>
/// (Optional) Use this only when paginating results to indicate the maximum number of
/// items that you want in the response. If additional items exist beyond the maximum
/// that you specify, the <code>IsTruncated</code> response element is <code>true</code>.
/// </para>
///
/// <para>
/// If you do not include this parameter, it defaults to 100. Note that IAM might return
/// fewer results, even when more results are available. In that case, the <code>IsTruncated</code>
/// response element returns <code>true</code>, and <code>Marker</code> contains a value
/// to include in the subsequent call that tells the service where to continue from.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1000)]
public int MaxItems
{
get { return this._maxItems.GetValueOrDefault(); }
set { this._maxItems = value; }
}
// Check to see if MaxItems property is set
internal bool IsSetMaxItems()
{
return this._maxItems.HasValue;
}
/// <summary>
/// Gets and sets the property RoleName.
/// <para>
/// The name of the IAM role for which you want to see the list of tags.
/// </para>
///
/// <para>
/// This parameter accepts (through its <a href="http://wikipedia.org/wiki/regex">regex
/// pattern</a>) a string of characters that consist of upper and lowercase alphanumeric
/// characters with no spaces. You can also include any of the following characters: _+=,.@-
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=64)]
public string RoleName
{
get { return this._roleName; }
set { this._roleName = value; }
}
// Check to see if RoleName property is set
internal bool IsSetRoleName()
{
return this._roleName != null;
}
}
} | 37.529915 | 149 | 0.618993 | [
"Apache-2.0"
] | AltairMartinez/aws-sdk-unity-net | src/Services/IdentityManagement/Generated/Model/ListRoleTagsRequest.cs | 4,391 | C# |
// Copyright (c) Microsoft. 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes.AddImport
{
internal abstract partial class AbstractAddImportCodeFixProvider : CodeFixProvider
{
protected abstract bool IgnoreCase { get; }
protected abstract bool CanAddImport(SyntaxNode node, CancellationToken cancellationToken);
protected abstract bool CanAddImportForMethod(Diagnostic diagnostic, ISyntaxFactsService syntaxFacts, ref SyntaxNode node);
protected abstract bool CanAddImportForNamespace(Diagnostic diagnostic, ref SyntaxNode node);
protected abstract bool CanAddImportForQuery(Diagnostic diagnostic, ref SyntaxNode node);
protected abstract bool CanAddImportForType(Diagnostic diagnostic, ref SyntaxNode node);
protected abstract ISet<INamespaceSymbol> GetNamespacesInScope(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
protected abstract ITypeSymbol GetQueryClauseInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
protected abstract string GetDescription(INamespaceOrTypeSymbol symbol, SemanticModel semanticModel, SyntaxNode root);
protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, INamespaceOrTypeSymbol symbol, Document documemt, bool specialCaseSystem, CancellationToken cancellationToken);
protected abstract bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken);
protected abstract IEnumerable<ITypeSymbol> GetProposedTypes(string name, List<ITypeSymbol> accessibleTypeSymbols, SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope);
internal abstract bool IsViableField(IFieldSymbol field, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken);
internal abstract bool IsViableProperty(IPropertySymbol property, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken);
[SuppressMessage("Microsoft.StyleCop.CSharp.SpacingRules", "SA1008:OpeningParenthesisMustBeSpacedCorrectly", Justification = "Working around StyleCop bug 7080")]
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var span = context.Span;
var diagnostics = context.Diagnostics;
var cancellationToken = context.CancellationToken;
var project = document.Project;
var diagnostic = diagnostics.First();
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var ancestors = root.FindToken(span.Start, findInsideTrivia: true).GetAncestors<SyntaxNode>();
if (!ancestors.Any())
{
return;
}
var node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root);
if (node == null)
{
return;
}
var placeSystemNamespaceFirst = document.Project.Solution.Workspace.Options.GetOption(Microsoft.CodeAnalysis.Shared.Options.OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language);
using (Logger.LogBlock(FunctionId.Refactoring_AddImport, cancellationToken))
{
if (!cancellationToken.IsCancellationRequested)
{
if (this.CanAddImport(node, cancellationToken))
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var containingType = semanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken);
var containingTypeOrAssembly = containingType ?? (ISymbol)semanticModel.Compilation.Assembly;
var namespacesInScope = this.GetNamespacesInScope(semanticModel, node, cancellationToken);
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var matchingTypesNamespaces = await this.GetNamespacesForMatchingTypesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
var matchingTypes = await this.GetMatchingTypesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
var matchingNamespaces = await this.GetNamespacesForMatchingNamespacesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
var matchingExtensionMethodsNamespaces = await this.GetNamespacesForMatchingExtensionMethodsAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
var matchingFieldsAndPropertiesAsync = await this.GetNamespacesForMatchingFieldsAndPropertiesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
var queryPatternsNamespaces = await this.GetNamespacesForQueryPatternsAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);
if (matchingTypesNamespaces != null || matchingNamespaces != null || matchingExtensionMethodsNamespaces != null || matchingFieldsAndPropertiesAsync != null || queryPatternsNamespaces != null || matchingTypes != null)
{
matchingTypesNamespaces = matchingTypesNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
matchingNamespaces = matchingNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
matchingExtensionMethodsNamespaces = matchingExtensionMethodsNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
matchingFieldsAndPropertiesAsync = matchingFieldsAndPropertiesAsync ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
queryPatternsNamespaces = queryPatternsNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
matchingTypes = matchingTypes ?? SpecializedCollections.EmptyList<ITypeSymbol>();
var proposedImports =
matchingTypesNamespaces.Cast<INamespaceOrTypeSymbol>()
.Concat(matchingNamespaces.Cast<INamespaceOrTypeSymbol>())
.Concat(matchingExtensionMethodsNamespaces.Cast<INamespaceOrTypeSymbol>())
.Concat(matchingFieldsAndPropertiesAsync.Cast<INamespaceOrTypeSymbol>())
.Concat(queryPatternsNamespaces.Cast<INamespaceOrTypeSymbol>())
.Concat(matchingTypes.Cast<INamespaceOrTypeSymbol>())
.Distinct()
.Where(NotNull)
.Where(NotGlobalNamespace)
.OrderBy(INamespaceOrTypeSymbolExtensions.CompareNamespaceOrTypeSymbols)
.Take(8)
.ToList();
if (proposedImports.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var import in proposedImports)
{
var action = new MyCodeAction(this.GetDescription(import, semanticModel, node), (c) =>
this.AddImportAsync(node, import, document, placeSystemNamespaceFirst, cancellationToken));
context.RegisterCodeFix(action, diagnostic);
}
}
}
}
}
}
}
private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForMatchingTypesAsync(
Project project,
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
ISet<INamespaceSymbol> namespacesInScope,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
if (!this.CanAddImportForType(diagnostic, ref node))
{
return null;
}
string name;
int arity;
bool inAttributeContext, hasIncompleteParentMember;
CalculateContext(node, syntaxFacts, out name, out arity, out inAttributeContext, out hasIncompleteParentMember);
var symbols = await GetTypeSymbols(project, node, semanticModel, name, inAttributeContext, cancellationToken).ConfigureAwait(false);
if (symbols == null)
{
return null;
}
return GetNamespacesForMatchingTypesAsync(semanticModel, namespacesInScope, arity, inAttributeContext, hasIncompleteParentMember, symbols);
}
private IEnumerable<INamespaceSymbol> GetNamespacesForMatchingTypesAsync(SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope, int arity, bool inAttributeContext, bool hasIncompleteParentMember, IEnumerable<ITypeSymbol> symbols)
{
var accessibleTypeSymbols = symbols
.Where(s => s.ContainingSymbol is INamespaceSymbol
&& ArityAccessibilityAndAttributeContextAreCorrect(
semanticModel, s, arity,
inAttributeContext, hasIncompleteParentMember))
.ToList();
return GetProposedNamespaces(
accessibleTypeSymbols.Select(s => s.ContainingNamespace),
semanticModel,
namespacesInScope);
}
private async Task<IEnumerable<ITypeSymbol>> GetMatchingTypesAsync(
Project project,
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
ISet<INamespaceSymbol> namespacesInScope,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
if (!this.CanAddImportForType(diagnostic, ref node))
{
return null;
}
string name;
int arity;
bool inAttributeContext, hasIncompleteParentMember;
CalculateContext(node, syntaxFacts, out name, out arity, out inAttributeContext, out hasIncompleteParentMember);
var symbols = await GetTypeSymbols(project, node, semanticModel, name, inAttributeContext, cancellationToken).ConfigureAwait(false);
if (symbols == null)
{
return null;
}
return GetMatchingTypes(semanticModel, namespacesInScope, name, arity, inAttributeContext, symbols, hasIncompleteParentMember);
}
private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForMatchingNamespacesAsync(
Project project,
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
ISet<INamespaceSymbol> namespacesInScope,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
if (!this.CanAddImportForNamespace(diagnostic, ref node))
{
return null;
}
string name;
int arity;
syntaxFacts.GetNameAndArityOfSimpleName(node, out name, out arity);
if (ExpressionBinds(node, semanticModel, cancellationToken))
{
return null;
}
var symbols = await SymbolFinder.FindDeclarationsAsync(
project, name, this.IgnoreCase, SymbolFilter.Namespace, cancellationToken).ConfigureAwait(false);
return GetProposedNamespaces(
symbols.OfType<INamespaceSymbol>().Select(n => n.ContainingNamespace),
semanticModel,
namespacesInScope);
}
private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForMatchingExtensionMethodsAsync(
Project project,
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
ISet<INamespaceSymbol> namespacesInScope,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
if (!this.CanAddImportForMethod(diagnostic, syntaxFacts, ref node))
{
return null;
}
var expression = node.Parent;
var symbols = await GetSymbolsAsync(project, diagnostic, node, semanticModel, syntaxFacts, cancellationToken).ConfigureAwait(false);
return FilterForExtensionMethods(semanticModel, namespacesInScope, syntaxFacts, expression, symbols, cancellationToken);
}
private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForMatchingFieldsAndPropertiesAsync(
Project project,
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
ISet<INamespaceSymbol> namespacesInScope,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
if (!this.CanAddImportForMethod(diagnostic, syntaxFacts, ref node))
{
return null;
}
var expression = node.Parent;
var symbols = await GetSymbolsAsync(project, diagnostic, node, semanticModel, syntaxFacts, cancellationToken).ConfigureAwait(false);
return FilterForFieldsAndProperties(semanticModel, namespacesInScope, syntaxFacts, expression, symbols, cancellationToken);
}
private IEnumerable<INamespaceSymbol> FilterForFieldsAndProperties(SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope, ISyntaxFactsService syntaxFacts, SyntaxNode expression, IEnumerable<ISymbol> symbols, CancellationToken cancellationToken)
{
var propertySymbols = symbols
.OfType<IPropertySymbol>()
.Where(property => property.ContainingType?.IsAccessibleWithin(semanticModel.Compilation.Assembly) == true &&
IsViableProperty(property, expression, semanticModel, syntaxFacts, cancellationToken))
.ToList();
var fieldSymbols = symbols
.OfType<IFieldSymbol>()
.Where(field => field.ContainingType?.IsAccessibleWithin(semanticModel.Compilation.Assembly) == true &&
IsViableField(field, expression, semanticModel, syntaxFacts, cancellationToken))
.ToList();
return GetProposedNamespaces(
propertySymbols.Select(s => s.ContainingNamespace).Concat(fieldSymbols.Select(s => s.ContainingNamespace)),
semanticModel,
namespacesInScope);
}
private Task<IEnumerable<ISymbol>> GetSymbolsAsync(
Project project,
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// See if the name binds. If it does, there's nothing further we need to do.
if (ExpressionBinds(node, semanticModel, cancellationToken, checkForExtensionMethods: true))
{
return null;
}
string name;
int arity;
syntaxFacts.GetNameAndArityOfSimpleName(node, out name, out arity);
return SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Member, cancellationToken);
}
private IEnumerable<INamespaceSymbol> FilterForExtensionMethods(SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope, ISyntaxFactsService syntaxFacts, SyntaxNode expression, IEnumerable<ISymbol> symbols, CancellationToken cancellationToken)
{
var extensionMethodSymbols = symbols
.OfType<IMethodSymbol>()
.Where(method => method.IsExtensionMethod &&
method.ContainingType?.IsAccessibleWithin(semanticModel.Compilation.Assembly) == true &&
IsViableExtensionMethod(method, expression, semanticModel, syntaxFacts, cancellationToken))
.ToList();
return GetProposedNamespaces(
extensionMethodSymbols.Select(s => s.ContainingNamespace),
semanticModel,
namespacesInScope);
}
private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForQueryPatternsAsync(
Project project,
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
ISet<INamespaceSymbol> namespacesInScope,
CancellationToken cancellationToken)
{
if (!this.CanAddImportForQuery(diagnostic, ref node))
{
return null;
}
ITypeSymbol type = this.GetQueryClauseInfo(semanticModel, node, cancellationToken);
if (type == null)
{
return null;
}
// find extension methods named "Select"
var symbols = await SymbolFinder.FindDeclarationsAsync(project, "Select", this.IgnoreCase, SymbolFilter.Member, cancellationToken).ConfigureAwait(false);
var extensionMethodSymbols = symbols
.OfType<IMethodSymbol>()
.Where(s => s.IsExtensionMethod && IsViableExtensionMethod(type, s))
.ToList();
return GetProposedNamespaces(
extensionMethodSymbols.Select(s => s.ContainingNamespace),
semanticModel,
namespacesInScope);
}
private bool IsViableExtensionMethod(
ITypeSymbol typeSymbol,
IMethodSymbol method)
{
return typeSymbol != null && method.ReduceExtensionMethod(typeSymbol) != null;
}
private static bool ArityAccessibilityAndAttributeContextAreCorrect(
SemanticModel semanticModel,
ITypeSymbol symbol,
int arity,
bool inAttributeContext,
bool hasIncompleteParentMember)
{
return (arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember)
&& symbol.IsAccessibleWithin(semanticModel.Compilation.Assembly)
&& (!inAttributeContext || symbol.IsAttribute());
}
private async Task<IEnumerable<ITypeSymbol>> GetTypeSymbols(
Project project,
SyntaxNode node,
SemanticModel semanticModel,
string name,
bool inAttributeContext,
CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return null;
}
if (ExpressionBinds(node, semanticModel, cancellationToken))
{
return null;
}
var symbols = await SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false);
// also lookup type symbols with the "Attribute" suffix.
if (inAttributeContext)
{
symbols = symbols.Concat(
await SymbolFinder.FindDeclarationsAsync(project, name + "Attribute", this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false));
}
return symbols.OfType<ITypeSymbol>();
}
private IEnumerable<ITypeSymbol> GetMatchingTypes(SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope, string name, int arity, bool inAttributeContext, IEnumerable<ITypeSymbol> symbols, bool hasIncompleteParentMember)
{
var accessibleTypeSymbols = symbols
.Where(s => ArityAccessibilityAndAttributeContextAreCorrect(
semanticModel, s, arity,
inAttributeContext, hasIncompleteParentMember))
.ToList();
return GetProposedTypes(
name,
accessibleTypeSymbols,
semanticModel,
namespacesInScope);
}
private static void CalculateContext(SyntaxNode node, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember)
{
// Has to be a simple identifier or generic name.
syntaxFacts.GetNameAndArityOfSimpleName(node, out name, out arity);
inAttributeContext = syntaxFacts.IsAttributeName(node);
hasIncompleteParentMember = syntaxFacts.HasIncompleteParentMember(node);
}
protected bool ExpressionBinds(SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken, bool checkForExtensionMethods = false)
{
// See if the name binds to something other then the error type. If it does, there's nothing further we need to do.
// For extension methods, however, we will continue to search if there exists any better matched method.
cancellationToken.ThrowIfCancellationRequested();
var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods)
{
return true;
}
return symbolInfo.Symbol != null;
}
protected IEnumerable<INamespaceSymbol> GetProposedNamespaces(
IEnumerable<INamespaceSymbol> namespaces,
SemanticModel semanticModel,
ISet<INamespaceSymbol> namespacesInScope)
{
// We only want to offer to add a using if we don't already have one.
return
namespaces.Where(n => !n.IsGlobalNamespace)
.Select(n => semanticModel.Compilation.GetCompilationNamespace(n) ?? n)
.Where(n => n != null && !namespacesInScope.Contains(n));
}
private static bool NotGlobalNamespace(INamespaceOrTypeSymbol symbol)
{
return symbol.IsNamespace ? !((INamespaceSymbol)symbol).IsGlobalNamespace : true;
}
private static bool NotNull(INamespaceOrTypeSymbol symbol)
{
return symbol != null;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
base(title, createChangedDocument)
{
}
public override string EquivalenceKey
{
get
{
return Title;
}
}
}
}
}
| 50.768595 | 268 | 0.638817 | [
"Apache-2.0"
] | DavidKarlas/roslyn | src/Features/Core/CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs | 24,574 | C# |
using SixLabors.Fonts;
namespace Shinobu.Services
{
public class FontService
{
private readonly FontCollection _fontCollection = new();
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
public FontFamily FontFamily { get; private set; }
public Font Bold { get; private set; }
public FontService()
{
FontFamily = _fontCollection.Install(Program.AssetsPath + "/fonts/Roboto.ttf");
Bold = FontFamily.CreateFont(34, FontStyle.Bold);
}
}
} | 30.388889 | 91 | 0.654479 | [
"MIT"
] | pkly/shinobu-bot | bot/Services/FontService.cs | 549 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Sat.Recruitment.Api.Models;
namespace Sat.Recruitment.Api.Data.Repositories.Interfaces
{
public interface IGenericRepository<T> where T : class
{
void Agregar(T entidad);
void Eliminar(string email);
void Actualizar(T entidad);
T ObtenerPorEmail(string email);
IEnumerable<T> Listar();
}
}
| 24.666667 | 58 | 0.707207 | [
"MIT"
] | adolfredo87/ParamoTech | Sat.Recruitment.Api/Data/Repositories/Interfaces/IGenericRepository.cs | 446 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.eShopWeb.ApplicationCore.Constants;
using Microsoft.eShopWeb.Web.Interfaces;
using Microsoft.eShopWeb.Web.ViewModels;
using System.Threading.Tasks;
namespace Microsoft.eShopWeb.Web.Pages.Admin
{
[Authorize(Roles = AuthorizationConstants.Roles.ADMINISTRATORS)]
public class EditCatalogItemModel : PageModel
{
private readonly ICatalogItemViewModelService _catalogItemViewModelService;
public EditCatalogItemModel(ICatalogItemViewModelService catalogItemViewModelService)
{
_catalogItemViewModelService = catalogItemViewModelService;
}
[BindProperty]
public CatalogItemViewModel CatalogModel { get; set; } = new CatalogItemViewModel();
public async Task OnGet(CatalogItemViewModel catalogModel)
{
CatalogModel = catalogModel;
}
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
await _catalogItemViewModelService.UpdateCatalogItem(CatalogModel);
}
return RedirectToPage("/Admin/Index");
}
}
}
| 31.4 | 93 | 0.707006 | [
"MIT"
] | Rumcajsbury/TestApp | src/Web/Pages/Admin/EditCatalogItem.cshtml.cs | 1,258 | C# |
//
// C++みたいにTemplateの特殊化ができれば、レコード固有の条件をQueryオブジェクトに定義できるが、、、
//
//public class Query<ColumnInfo> : Query<ColumnInfo> {
//
//}
| 19.142857 | 60 | 0.679104 | [
"MIT"
] | hiro80/SqlAccessor | Src/SqlAccessor/Query/QueryOfColumInfo.cs | 214 | 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.472.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Security;
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("5.472.5.0")]
[assembly: AssemblyFileVersion("5.472.5.0")]
[assembly: AssemblyCopyright("© Component Factory Pty Ltd, 2006 - 2016. All rights reserved.")]
[assembly: AssemblyInformationalVersion("5.472.5.0")]
[assembly: AssemblyProduct("KryptonBorderEdge Examples")]
[assembly: AssemblyDefaultAlias("KryptonBorderEdgeExamples.dll")]
[assembly: AssemblyTitle("KryptonBorderEdge Examples")]
[assembly: AssemblyCompany("Component Factory")]
[assembly: AssemblyDescription("KryptonBorderEdge Examples")]
[assembly: AssemblyConfiguration("Production")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: StringFreezing]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AllowPartiallyTrustedCallers()]
[assembly: Dependency("System", LoadHint.Always)]
[assembly: Dependency("System.Drawing", LoadHint.Always)]
[assembly: Dependency("System.Windows.Forms", LoadHint.Always)]
[assembly: Dependency("ComponentFactory.Krypton.Toolkit", LoadHint.Always)]
| 45.351351 | 95 | 0.709178 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.472 | Source/Demos/Non-NuGet/Krypton Toolkit Examples/KryptonBorderEdge Examples/Properties/AssemblyInfo.cs | 1,682 | C# |
//
// System.Web.UI.Design.WebControls.ListControlDesigner.cs
//
// Author: Duncan Mak (duncan@novell.com)
//
// Copyright (C) 2005-2009 Novell, Inc (http://www.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.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Web.UI.WebControls;
using System.Windows.Forms.Design;
namespace System.Web.UI.Design.WebControls {
public class ListControlDesigner :
#if NET_2_0
DataBoundControlDesigner
#else
ControlDesigner,
IDataSourceProvider
#endif
{
string data_key_field;
string data_member;
string data_text_field;
string data_value_field;
public ListControlDesigner ()
: base ()
{
}
#if NET_2_0
public override DesignerActionListCollection ActionLists {
get { throw new NotImplementedException (); }
}
protected override bool UseDataSourcePickerActionList {
get { throw new NotImplementedException (); }
}
public string DataSource {
get; set;
}
#endif
public string DataKeyField {
get { return data_key_field; }
set { data_key_field = value; }
}
public string DataMember {
get { return data_member; }
set { data_member = value; }
}
public string DataTextField {
get { return data_text_field; }
set { data_text_field = value; }
}
public string DataValueField {
get { return data_value_field; }
set { data_value_field = value; }
}
#if NET_2_0
protected override void DataBind (BaseDataBoundControl dataBoundControl)
{
throw new NotImplementedException ();
}
public override void Initialize (IComponent component)
{
throw new NotImplementedException ();
}
#endif
public override string GetDesignTimeHtml ()
{
throw new NotImplementedException ();
}
public virtual IEnumerable GetResolvedSelectedDataSource ()
{
throw new NotImplementedException ();
}
public virtual object GetSelectedDataSource ()
{
throw new NotImplementedException ();
}
public override void OnComponentChanged (object sender, ComponentChangedEventArgs e)
{
throw new NotImplementedException ();
}
protected internal virtual void OnDataSourceChanged ()
{
throw new NotImplementedException ();
}
protected override void PreFilterProperties (IDictionary properties)
{
throw new NotImplementedException ();
}
}
} | 26.223077 | 86 | 0.740686 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Design/System.Web.UI.Design.WebControls/ListControlDesigner.cs | 3,409 | C# |
/*
Copyright (c) 2010 Marius Klimantavičius
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
namespace Marius.Build.Tasks
{
public class Gppg: Task
{
public bool Babel { get; set; }
public bool Conflicts { get; set; }
public bool Defines { get; set; }
public bool Gplex { get; set; }
public bool Listing { get; set; }
public bool NoLines { get; set; }
public bool Report { get; set; }
public bool Verbose { get; set; }
public bool NoInfo { get; set; }
public bool NoFilename { get; private set; }
public string OutputBaseDirectory { get; set; }
public bool UseFullPath { get; set; }
[Required]
public string ToolsPath { get; set; }
[Required]
public ITaskItem IntermediateDirectory { get; set; }
[Required]
public ITaskItem[] InputFiles { get; set; }
[Output]
public ITaskItem[] OutputFiles { get; private set; }
internal class GppgTask: SimpleToolTask
{
private Gppg _parent;
private ITaskItem _inputFile;
private ITaskItem _outputFile;
public GppgTask(Gppg parent, ITaskItem inputFile, ITaskItem outputFile)
{
_parent = parent;
_inputFile = inputFile;
_outputFile = outputFile;
}
protected string GppgBinPath
{
get { return Path.Combine(ToolsPath, "gppg\\binaries"); }
}
protected override string ToolName
{
get { return "gppg.exe"; }
}
protected override string GenerateFullPathToTool()
{
return Path.Combine(GppgBinPath, ToolName);
}
protected override string GenerateCommandLineCommands()
{
CommandLineBuilder cb = new CommandLineBuilder();
cb.AppendSwitch("/noThrow");
cb.AppendBoolSwich(_parent.Babel, "/babel");
cb.AppendBoolSwich(_parent.Conflicts, "/conflicts");
cb.AppendBoolSwich(_parent.Defines, "/defines");
cb.AppendBoolSwich(_parent.Gplex, "/gplex");
cb.AppendBoolSwich(_parent.Listing, "/listing");
cb.AppendBoolSwich(_parent.NoLines, "/no-lines");
cb.AppendBoolSwich(_parent.Report, "/report");
cb.AppendBoolSwich(_parent.Verbose, "/verbose");
cb.AppendBoolSwich(_parent.NoInfo, "/no-info");
cb.AppendBoolSwich(_parent.NoFilename, "/no-filename");
cb.AppendSwitchIfNotNull("/out:", Path.GetFullPath(_outputFile.ItemSpec));
if (_parent.UseFullPath)
cb.AppendFileNameIfNotNull(Path.GetFullPath(_inputFile.ItemSpec));
else
cb.AppendFileNameIfNotNull(Extensions.MakeRelativePath(Path.GetFullPath(GetWorkingDirectory() + "\\"), Path.GetFullPath(_inputFile.ItemSpec)));
cb.AppendSwitchIfNotNull("/line-filename:", Extensions.MakeRelativePath(Path.GetFullPath(_outputFile.ItemSpec), Path.GetFullPath(_inputFile.ItemSpec)));
Log.LogMessage("{0}", cb.ToString());
return cb.ToString();
}
protected override string GetWorkingDirectory()
{
return _parent.IntermediateDirectory.ItemSpec;
}
public override bool Execute()
{
return base.Execute();
}
}
public override bool Execute()
{
bool success = true;
List<ITaskItem> output = new List<ITaskItem>();
foreach (var item in InputFiles)
{
string outputPath = Path.ChangeExtension(item.ItemSpec, ".Generated.cs");
if (OutputBaseDirectory != null)
outputPath = Path.Combine(OutputBaseDirectory, outputPath);
var outputItem = new TaskItem(outputPath);
var task = new GppgTask(this, item, outputItem)
{
BuildEngine = this.BuildEngine,
HostObject = this.HostObject,
ToolsPath = this.ToolsPath,
};
success = success && task.Execute();
output.Add(outputItem);
}
OutputFiles = output.ToArray();
return success;
}
}
public static class Extensions
{
public static void AppendBoolSwich(this CommandLineBuilder cb, bool condition, string @switch)
{
if (condition)
cb.AppendSwitch(@switch);
}
/// <summary>
/// Creates a relative path from one file or folder to another.
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <param name="dontEscape">Boolean indicating whether to add uri safe escapes to the relative path</param>
/// <returns>The relative path from the start directory to the end path.</returns>
/// <exception cref="ArgumentNullException"></exception>
public static string MakeRelativePath(string fromPath, string toPath)
{
if (string.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
if (string.IsNullOrEmpty(toPath)) throw new ArgumentNullException("toPath");
Uri fromUri = new Uri(fromPath);
Uri toUri = new Uri(toPath);
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
return relativeUri.ToString();
}
public static void CopyTo(this Stream input, Stream output)
{
byte[] buffer = new byte[4096];
while (true)
{
int read = input.Read(buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write(buffer, 0, read);
}
}
}
}
| 35.572115 | 168 | 0.596837 | [
"MIT"
] | marius-klimantavicius/pinta | Tools/Marius.Build/Marius.Build.Tasks/Gppg.cs | 7,402 | C# |
using System;
using System.Data.SQLite;
using System.Threading.Tasks;
using Wabbajack.Hashing.xxHash64;
namespace Wabbajack.Compiler.PatchCache
{
public record CacheEntry(Hash From, Hash To, long PatchSize, IBinaryPatchCache cache)
{
}
} | 22.727273 | 89 | 0.772 | [
"Unlicense"
] | wabbajack-tools/wabbajack | Wabbajack.Compiler/PatchCache/CacheEntry.cs | 250 | C# |
#define TI_DEBUG_PRINT
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Diagnostics.Contracts;
using System.Linq.Expressions;
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) {
Contract.Requires(name != null);
Contract.Requires(pool != null && 2 <= pool.Count);
Pool = pool;
}
public string ModuleNames() {
return AmbiguousThingHelper<TopLevelDecl>.ModuleNames(this, d => d.Module.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) {
Contract.Requires(name != null);
Contract.Requires(pool != null && 2 <= pool.Count);
Pool = pool;
}
public string ModuleNames() {
return AmbiguousThingHelper<MemberDecl>.ModuleNames(this, d => d.EnclosingClass.Module.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.NumericPersuation.Int), typeArgs => Type.Int),
new ValuetypeDecl("real", builtIns.SystemModule, 0, t => t.IsNumericBased(Type.NumericPersuation.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, false, new List<TypeParameter>(), formals, new SelfType(),
new List<MaybeFreeExpression>(), new List<FrameExpression>(), new List<MaybeFreeExpression>(), 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, false, new List<TypeParameter>(), formals, new SelfType(),
new List<MaybeFreeExpression>(), new List<FrameExpression>(), new List<MaybeFreeExpression>(), 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));
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);
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) {
var alias = (AliasModuleDecl)decl;
// resolve the path
ModuleSignature p;
if (ResolveExport(alias, alias.Root, alias.Module, alias.Path, 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 ModuleFacadeDecl) {
var abs = (ModuleFacadeDecl)decl;
ModuleSignature p;
if (ResolveExport(abs, abs.Root, abs.Module, abs.Path, 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); }
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 FixpointPredicate) {
// this means the corresponding prefix predicate is also recursive
var prefixPred = ((FixpointPredicate)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 FixpointLemma) {
body = ((FixpointLemma)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 FixpointLemma) {
var prefixLemma = ((FixpointLemma)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 CoLemma 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 FixpointPredicate) {
// fixpoint-predicates don't have decreases clauses
return false;
}
var anyChangeToDecreases = false;
var decr = clbl.Decreases.Expressions;
if (DafnyOptions.O.Dafnycc) {
if (decr.Count > 1) {
reporter.Error(MessageSource.Resolver, decr[1].tok, "In dafnycc mode, only one decreases expression is allowed");
}
// In dafnycc mode, only consider first argument
if (decr.Count == 0 && clbl.Ins.Count > 0) {
var p = clbl.Ins[0];
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(ie);
return true;
}
}
return false;
}
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) {
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 ModuleFacadeDecl) {
ModuleSignature importSig;
if (d is AliasModuleDecl) {
var alias = (AliasModuleDecl)d;
importSig = alias.Root != null ? alias.Root.Signature : alias.Signature;
} else {
importSig = ((ModuleFacadeDecl)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.Module), 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);
}
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 (string s in d.Extends) {
ModuleExportDecl extend;
if (sig.ExportSets.TryGetValue(s, out extend)) {
d.ExtendDecls.Add(extend);
exportDependencies.AddEdge(d, extend);
} else {
reporter.Error(MessageSource.Resolver, m.tok, s + " 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;
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);
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, 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, ModuleFacadeDecl's and AliasModuleDecl's).
foreach (var tld in moduleDecl.TopLevelDecls) {
if (tld is ModuleFacadeDecl || 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 ModuleFacadeDecl || 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.Path.Count == 1 && importDecl.Name == importDecl.Path[0].val) {
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.Module = 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 void ProcessDependenciesDefinition(ModuleDecl decl, ModuleDefinition m, ModuleBindings bindings, Graph<ModuleDecl> dependencies) {
if (m.RefinementBaseName != null) {
ModuleDecl other;
if (!bindings.TryLookup(m.RefinementBaseName, out other)) {
reporter.Error(MessageSource.Resolver, m.RefinementBaseName, "module {0} named as refinement base does not exist", m.RefinementBaseName.val);
} else if (other is LiteralModuleDecl && ((LiteralModuleDecl)other).ModuleDef == m) {
reporter.Error(MessageSource.Resolver, m.RefinementBaseName, "module cannot refine itself: {0}", m.RefinementBaseName.val);
} else {
Contract.Assert(other != null); // follows from postcondition of TryGetValue
dependencies.AddEdge(decl, other);
m.RefinementBaseRoot = 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);
}
}
}
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;
if (!bindings.TryLookupFilter(alias.Path[0], out root,
m => alias != m && (((alias.Module == m.Module) && (alias.Exports.Count == 0)) || m is LiteralModuleDecl)))
reporter.Error(MessageSource.Resolver, alias.tok, ModuleNotFoundErrorMessage(0, alias.Path));
else {
dependencies.AddEdge(moduleDecl, root);
alias.Root = root;
}
} else if (moduleDecl is ModuleFacadeDecl) {
var abs = moduleDecl as ModuleFacadeDecl;
ModuleDecl root;
if (!bindings.TryLookupFilter(abs.Path[0], out root,
m => abs != m && (((abs.Module == m.Module) && (abs.Exports.Count == 0)) || m is LiteralModuleDecl)))
reporter.Error(MessageSource.Resolver, abs.tok, ModuleNotFoundErrorMessage(0, abs.Path));
else {
dependencies.AddEdge(moduleDecl, root);
abs.Root = root;
}
}
}
private static string ModuleNotFoundErrorMessage(int i, List<IToken> path) {
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) + ")" : "");
}
[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 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 || DafnyOptions.O.IronDafny) {
// classes:
foreach (var kv in s.TopLevels) {
if (!kv.Value.CanBeExported())
continue;
if (kv.Value is ModuleDecl && ((ModuleDecl)kv.Value).Opened && DafnyOptions.O.IronDafny) {
ResolveOpenedImportsWorker(sig, moduleDef, (ModuleDecl)kv.Value, importedSigs, useCompileSignatures);
}
// IronDafny: we need to pull the members of the opened module's _default class in so that they can be merged.
if (useImports || string.Equals(kv.Key, "_default", StringComparison.InvariantCulture)) {
TopLevelDecl d;
if (sig.TopLevels.TryGetValue(kv.Key, out d)) {
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 || DafnyOptions.O.IronDafny) {
// 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<MaybeFreeExpression>(),
new Specification<FrameExpression>(new List<FrameExpression>(), null),
new List<MaybeFreeExpression>(),
new Specification<Expression>(new List<Expression>(), null),
null, null, null);
// --- here comes predicate Valid()
var valid = new Predicate(iter.tok, "Valid", false, true, true, new List<TypeParameter>(),
new List<Formal>(),
new List<MaybeFreeExpression>(),
new List<FrameExpression>(),
new List<MaybeFreeExpression>(),
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<MaybeFreeExpression>(),
new Specification<FrameExpression>(new List<FrameExpression>(), null),
new List<MaybeFreeExpression>(),
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;
}
}
}
} 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 FixpointPredicate || m is FixpointLemma) {
var extraName = m.Name + "#";
MemberDecl extraMember;
var cloner = new Cloner();
var formals = new List<Formal>();
Type typeOfK;
if ((m is FixpointPredicate && ((FixpointPredicate)m).KNat) || (m is FixpointLemma && ((FixpointLemma)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 FixpointPredicate) {
var cop = (FixpointPredicate)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, cop.IsProtected,
tyvars, k, formals,
cop.Req.ConvertAll(cloner.CloneMayBeFreeExpr),
cop.Reads.ConvertAll(cloner.CloneFrameExpr),
cop.Ens.ConvertAll(cloner.CloneMayBeFreeExpr),
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 = (FixpointLemma)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 colemma, the postconditions are filled in after the colemma's postconditions have been resolved.
// For an inductive lemma, the preconditions are filled in after the inductive lemma's preconditions have been resolved.
var req = com is CoLemma ? com.Req.ConvertAll(cloner.CloneMayBeFreeExpr) : new List<MaybeFreeExpression>();
var ens = com is CoLemma ? new List<MaybeFreeExpression>() : com.Ens.ConvertAll(cloner.CloneMayBeFreeExpr);
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 colemma 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, 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 ModuleFacadeDecl) {
var abs = (ModuleFacadeDecl)d;
var sig = MakeAbstractSignature(abs.OriginalSignature, Name + "." + abs.Name, abs.Height, mods, compilationModuleClones);
var a = new ModuleFacadeDecl(abs.Path, abs.tok, m, abs.Opened, abs.Exports);
a.Signature = sig;
a.OriginalSignature = abs.OriginalSignature;
return a;
} else {
return new AbstractSignatureCloner(scope).CloneDeclaration(d, m);
}
}
public bool ResolveExport(ModuleDecl alias, ModuleDecl root, ModuleDefinition parent, List<IToken> Path, List<IToken> Exports, out ModuleSignature p, ErrorReporter reporter) {
Contract.Requires(Path != null);
Contract.Requires(Path.Count > 0);
Contract.Requires(Exports != null);
Contract.Requires(Exports.Count == 0 || Path.Count == 1); // Path.Count > 1 ==> Exports.Count == 0
Contract.Requires(Exports.Count == 0 || root is LiteralModuleDecl); // only literal modules may have exports
if (Path.Count == 1 && root is LiteralModuleDecl) {
// use the default export set when importing the root
LiteralModuleDecl decl = (LiteralModuleDecl)root;
if (Exports.Count == 0) {
p = decl.DefaultExport;
if (p == null) {
// no default view is specified.
reporter.Error(MessageSource.Resolver, Path[0], "no default export set declared in module: {0}", decl.Name);
return false;
}
return true;
} else {
ModuleExportDecl pp;
if (root.Signature.ExportSets.TryGetValue(Exports[0].val, out pp)) {
p = pp.Signature;
} 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 (root.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;
}
}
// Although the module is known, we demand it be imported before we're willing to access it.
var thisImport = parent.TopLevelDecls.FirstOrDefault(t => t.Name == Path[0].val && t != alias);
if (thisImport == null || !(thisImport is ModuleDecl)) {
reporter.Error(MessageSource.Resolver, Path[0], ModuleNotFoundErrorMessage(0, Path));
p = null;
return false;
}
var psig = ((ModuleDecl)thisImport).AccessibleSignature();
int i = 1;
while (i < Path.Count) {
ModuleSignature pp;
if (psig.FindImport(Path[i].val, out pp)) {
psig = pp;
i++;
} else {
reporter.Error(MessageSource.Resolver, Path[i], ModuleNotFoundErrorMessage(i, Path));
break;
}
}
p = psig;
return i == Path.Count;
}
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.Path.Last(), "a compiled module ({0}) is not allowed to import an abstract module ({1})", def.Name, Util.Comma(".", am.Path, tok => tok.val));
}
} 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),
new NativeType("sbyte", -0x80, 0x80, 0, NativeType.Selection.SByte, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java),
new NativeType("ushort", 0, 0x1_0000, 16, NativeType.Selection.UShort, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java),
new NativeType("short", -0x8000, 0x8000, 0, NativeType.Selection.Short, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java),
new NativeType("uint", 0, 0x1_0000_0000, 32, NativeType.Selection.UInt, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java),
new NativeType("int", -0x8000_0000, 0x8000_0000, 0, NativeType.Selection.Int, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java),
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),
new NativeType("long", Int64.MinValue, 0x8000_0000_0000_0000, 0, NativeType.Selection.Long, DafnyOptions.CompilationTarget.Csharp | DafnyOptions.CompilationTarget.Go | DafnyOptions.CompilationTarget.Java),
};
public void ResolveTopLevelDecls_Core(List<TopLevelDecl/*!*/>/*!*/ declarations, Graph<IndDatatypeDecl/*!*/>/*!*/ datatypeDependencies, Graph<CoDatatypeDecl/*!*/>/*!*/ codatatypeDependencies) {
Contract.Requires(declarations != null);
Contract.Requires(cce.NonNullElements(datatypeDependencies));
Contract.Requires(cce.NonNullElements(codatatypeDependencies));
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.Module), 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.Module), 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.Module), 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, dd);
} else if (d is NewtypeDecl) {
var dd = (NewtypeDecl)d;
if (dd.Var != null) {
Contract.Assert(dd.Constraint != null);
CheckExpression(dd.Constraint, this, dd);
}
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);
}
}
}
// ---------------------------------- 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.AllFixpointLemmas(declarations)) {
var prefixLemma = com.PrefixLemma;
if (prefixLemma == null) {
continue; // something went wrong during registration of the prefix lemma (probably a duplicated fixpoint-lemma name)
}
var k = prefixLemma.Ins[0];
var focalPredicates = new HashSet<FixpointPredicate>();
if (com is CoLemma) {
// 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>();
CollectFriendlyCallsInFixpointLemmaSpecification(p.E, true, coConclusions, true, com);
var subst = new FixpointLemmaSpecificationSubstituter(coConclusions, new IdentifierExpr(k.tok, k.Name), this.reporter, true);
var post = subst.CloneExpr(p.E);
prefixLemma.Ens.Add(new MaybeFreeExpression(post, p.IsFree));
foreach (var e in coConclusions) {
var fce = e as FunctionCallExpr;
if (fce != null) { // the other possibility is that "e" is a BinaryExpr
CoPredicate predicate = (CoPredicate)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.Module.CallGraph.GetSCC(predicate)) {
if (node is CoPredicate) {
focalPredicates.Add((CoPredicate)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>();
CollectFriendlyCallsInFixpointLemmaSpecification(p.E, true, antecedents, false, com);
var subst = new FixpointLemmaSpecificationSubstituter(antecedents, new IdentifierExpr(k.tok, k.Name), this.reporter, false);
var pre = subst.CloneExpr(p.E);
prefixLemma.Req.Add(new MaybeFreeExpression(pre, p.IsFree));
foreach (var e in antecedents) {
var fce = (FunctionCallExpr)e; // we expect "antecedents" to contain only FunctionCallExpr's
InductivePredicate predicate = (InductivePredicate)fce.Function;
focalPredicates.Add(predicate);
// For every focal predicate P in S, add to S all inductive predicates in the same strongly connected
// component (in the call graph) as P
foreach (var node in predicate.EnclosingClass.Module.CallGraph.GetSCC(predicate)) {
if (node is InductivePredicate) {
focalPredicates.Add((InductivePredicate)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 FixpointLemmaBodyCloner(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<MaybeFreeExpression>(), 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 (syn.MustSupportEquality && !syn.Rhs.SupportsEquality) {
reporter.Error(MessageSource.Resolver, syn.tok, "type '{0}' declared as supporting equality, but the RHS type ({1}) does not", syn.Name, syn.Rhs);
}
}
}
// Check that fixpoint-predicates are not recursive with non-fixpoint-predicate functions (and only
// with fixpoint-predicates of the same polarity), and
// check that colemmas are not recursive with non-colemma 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 FixpointPredicate) {
var fn = (FixpointPredicate)member;
// Check here for the presence of any 'ensures' clauses, which are not allowed (because we're not sure
// of their soundness)
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) {
FixpointPredicateChecks(fn.Body, fn, CallingPosition.Positive);
}
} else if (member is FixpointLemma) {
var m = (FixpointLemma)member;
if (m.Body != null) {
FixpointLemmaChecks(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.Module.CallGraph.GetSCCSize(dd) != 1) {
var r = d.Module.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.Module.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 (!cl.Module.IsAbstract && f.Rhs == null && !Compiler.InitializerIsKnown(f.Type) && !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 (!cl.Module.IsAbstract && f.Rhs == null && !Compiler.InitializerIsKnown(f.Type) && !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 (!Compiler.InitializerIsKnown(f.Type)) {
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 (!Compiler.InitializerIsKnown(Resolver.SubstType(f.Type, cl.ParentFormalTypeParametersToActuals))) {
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 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.NumericPersuation.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);
}
// 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:
Func<Expression, BigInteger?> GetConst = null;
GetConst = (Expression e) => {
int m = 1;
BinaryExpr bin = e as BinaryExpr;
if (bin != null && bin.Op == BinaryExpr.Opcode.Sub && GetConst(bin.E0) == BigInteger.Zero) {
m = -1;
e = bin.E1;
}
LiteralExpr l = e as LiteralExpr;
if (l != null && l.Value is BigInteger) {
return m * (BigInteger)l.Value;
}
return null;
};
// Now, then, let's go through them types.
foreach (var nativeT in nativeTypeChoices ?? NativeTypes) {
bool lowerOk = false;
bool upperOk = false;
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 && nativeT.LowerBound <= lower) {
lowerOk = true;
}
}
if (bnd.UpperBound != null) {
BigInteger? upper = GetConst(bnd.UpperBound);
if (upper != null && upper <= nativeT.UpperBound) {
upperOk = true;
}
}
}
}
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, "{:nativeType \"" + dd.NativeType.Name + "\"}");
}
} 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);
}
}
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 {1} <: {0}";
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, B[i], A[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 == 20) {
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.NormalizeExpandKeepConstraints() : 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, Type.Real);
}
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].NormalizeExpandKeepConstraints();
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.
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.NumericPersuation.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;
break;
case "Minusable":
satisfied = t.IsNumericBased() || t.IsBitVectorType || t.IsBigOrdinalType || t.IsCharType || t is SetType || t is MultiSetType;
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.NumericPersuation.Int);
} else {
satisfied = t.IsNumericBased(Type.NumericPersuation.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.NumericPersuation.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);
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);
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.ConstrainSubtypeRelation(Type.Int, index.Type, index, "sequence update requires integer index (got {0})", index.Type);
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, "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) {
indexType = resolver.NewIntegerBasedProxy(tok);
} else if (t.IsArrayType) {
indexType = resolver.NewIntegerBasedProxy(tok);
} 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:
// we're so out of here
return;
}
if (anyNewConstraints) {
state = 0;
} else {
state++;
}
}
}
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].NormalizeExpandKeepConstraints();
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.Module));
}
CheckTypeInference(field.Type, new NoContext(member.EnclosingClass.Module), 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 FixpointPredicate) {
var cop = (FixpointPredicate)f;
CheckTypeInference_Member(cop.PrefixPredicate);
}
}
}
private void CheckTypeInference_MaybeFreeExpression(MaybeFreeExpression 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 LetStmt) {
var s = (LetStmt)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;
var t = e.Type as BitvectorType;
if (t != null) {
var n = (BigInteger)e.Value;
// check that the given literal fits into the bitvector width
if (BigInteger.Pow(2, t.Width) <= n) {
resolver.reporter.Error(MessageSource.Resolver, e.tok, "bitvector literal ({0}) is too large for the type {1}", e.Value, t);
}
}
} 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 FixpointPredicate) {
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 is SetComprehension && 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, "a {0} must produce a finite set, 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.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 zero;
if (e.E.Type.IsNumericBased(Type.NumericPersuation.Real)) {
zero = new LiteralExpr(e.tok, Basetypes.BigDec.ZERO);
} else {
Contract.Assert(e.E.Type.IsNumericBased(Type.NumericPersuation.Int) || e.E.Type.IsBitVectorType);
zero = new LiteralExpr(e.tok, 0);
}
zero.Type = expr.Type;
var subtract = new BinaryExpr(e.tok, BinaryExpr.Opcode.Sub, zero, e.E);
subtract.Type = expr.Type;
subtract.ResolvedOp = BinaryExpr.ResolvedOpcode.Sub;
e.ResolvedExpression = subtract;
}
}
}
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.
/// </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);
}
}
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.Module;
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 LetStmt) {
} 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.Module;
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 (f.IsProtected && currentModule != f.EnclosingClass.Module) {
reporter.Error(MessageSource.Resolver, tok, "cannot adjust fuel for protected function {0} from another module", f.Name);
}
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
// ------------------------------------------------------------------------------------------------------
// ----- FixpointPredicateChecks ------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------
#region FixpointPredicateChecks
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 an inductive/co 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 fixpoint predicates, don't allow calls under an existential (resp. universal) quantifier
// for co-predicates (resp. inductive 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, FixpointPredicate.KType contextK, FixpointPredicate.KType calleeK) {
var hint = contextK == FixpointPredicate.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 == FixpointPredicate.KType.Nat ? "nat" : "ORDINAL",
calleeK == FixpointPredicate.KType.Nat ? "nat" : "ORDINAL",
hint);
}
class FixpointPredicateChecks_Visitor : FindFriendlyCalls_Visitor
{
readonly FixpointPredicate context;
public FixpointPredicateChecks_Visitor(Resolver resolver, FixpointPredicate context)
: base(resolver, context is CoPredicate, 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)) {
var article = context is InductivePredicate ? "an" : "a";
// we're looking at a recursive call
if (!(context is InductivePredicate ? e.Function is InductivePredicate : e.Function is CoPredicate)) {
resolver.reporter.Error(MessageSource.Resolver, e, "a recursive call from {0} {1} can go only to other {1}s", article, context.WhatKind);
} else if (context.KNat != ((FixpointPredicate)e.Function).KNat) {
resolver.KNatMismatchError(e.tok, context.Name, context.TypeOfK, ((FixpointPredicate)e.Function).TypeOfK);
} else if (cp != CallingPosition.Positive) {
var msg = string.Format("{0} {1} can be called recursively only in positive positions", article, 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 InductivePredicate ? "universal" : "existential");
} else {
// we don't care about the continuity restriction or
// the fixpoint-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
var article = context is InductivePredicate ? "an" : "a";
resolver.reporter.Error(MessageSource.Resolver, stmt.Tok, "a recursive call from {0} {1} can go only to other {1}s", article, context.WhatKind);
}
// do the sub-parts with the same "cp"
return true;
} else {
return base.VisitOneStmt(stmt, ref st);
}
}
}
void FixpointPredicateChecks(Expression expr, FixpointPredicate context, CallingPosition cp) {
Contract.Requires(expr != null);
Contract.Requires(context != null);
var v = new FixpointPredicateChecks_Visitor(this, context);
v.Visit(expr, cp);
}
#endregion FixpointPredicateChecks
// ------------------------------------------------------------------------------------------------------
// ----- FixpointLemmaChecks ----------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------
#region FixpointLemmaChecks
class FixpointLemmaChecks_Visitor : ResolverBottomUpVisitor
{
FixpointLemma context;
public FixpointLemmaChecks_Visitor(Resolver resolver, FixpointLemma 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 FixpointLemma || s.Method is PrefixLemma) {
// all is cool
} else {
// the call goes from a fixpoint-lemma context to a non-fixpoint-lemma callee
if (ModuleDefinition.InSameSCC(context, s.Method)) {
// we're looking at a recursive call (to a non-fixpoint-lemma)
var article = context is InductiveLemma ? "an" : "a";
resolver.reporter.Error(MessageSource.Resolver, s.Tok, "a recursive call from {0} {1} can go only to other {1}s and prefix lemmas", article, context.WhatKind);
}
}
}
}
protected override void VisitOneExpr(Expression expr)
{
if (expr is FunctionCallExpr) {
var e = (FunctionCallExpr)expr;
// the call goes from a colemma context to a non-colemma callee
if (ModuleDefinition.InSameSCC(context, e.Function)) {
// we're looking at a recursive call (to a non-colemma)
resolver.reporter.Error(MessageSource.Resolver, e.tok, "a recursive call from a colemma can go only to other colemmas and prefix lemmas");
}
}
}
}
void FixpointLemmaChecks(Statement stmt, FixpointLemma context) {
Contract.Requires(stmt != null);
Contract.Requires(context != null);
var v = new FixpointLemmaChecks_Visitor(this, context);
v.Visit(stmt);
}
#endregion FixpointLemmaChecks
// ------------------------------------------------------------------------------------------------------
// ----- 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 LetStmt) {
var s = (LetStmt)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.MustSupportZeroInitialization && !Compiler.HasZeroInitializer(actual)) {
whatIsWrong = "zero initialization";
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) {
stmt.IsGhost = false; // TODO when do we want to allow this feature in ghost code? Note that return changes control flow
} 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.IsGhost = true;
}
}
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 LetStmt) {
var s = (LetStmt)stmt;
if (mustBeErasable) {
foreach (var local in s.LocalVars) {
local.IsGhost = true;
}
}
s.IsGhost = s.LocalVars.All(v => v.IsGhost);
} else if (stmt is AssignStmt) {
var s = (AssignStmt)stmt;
var lhs = s.Lhs.Resolved;
var gk = AssignStmt.LhsIsToGhost_Which(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;
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) {
rhs.InitCall.Args.ForEach(resolver.CheckIsCompilable);
}
}
}
} 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.MapUnion:
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.MustSupportEquality && 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.Module), 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.Module == trait.Module || (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 that 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.Module), 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 FixpointPredicate && ec == reporter.Count(ErrorLevel.Error)) {
var ff = ((FixpointPredicate)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 FixpointLemma;
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 extremem 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 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
cl.InheritedMembers.Add(member);
} 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 InductiveLemma != traitMember is InductiveLemma ||
member is CoLemma != traitMember is CoLemma ||
member is TwoStateFunction != traitMember is TwoStateFunction ||
member is InductivePredicate != traitMember is InductivePredicate ||
member is CoPredicate != traitMember is CoPredicate) {
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.Module.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.Module.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 FixpointPredicate nwFix && old is FixpointPredicate 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 FixpointLemma nwFix && old is FixpointLemma 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.MustSupportZeroInitialization != n.Characteristics.MustSupportZeroInitialization) {
reporter.Error(MessageSource.Resolver, n.tok, "type parameter '{0}' is not allowed to change the requirement of supporting zero initialization", n.Name);
}
if (o.Characteristics.DisallowReferenceTypes != n.Characteristics.DisallowReferenceTypes) {
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.Module), 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 FixpointPredicate && ec == reporter.Count(ErrorLevel.Error)) {
var ff = ((FixpointPredicate)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.Module == co.Module) {
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.Module == dependee.Module) {
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 DefaultCtor 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.DefaultCtor != null) {
// previously cleared
} else if (ComputeDefaultCtor(dt)) {
Contract.Assert(dt.DefaultCtor != 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.DefaultCtor == 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.DefaultCtor if that is the case.
/// </summary>
bool ComputeDefaultCtor(IndDatatypeDecl dt) {
Contract.Requires(dt != null);
Contract.Requires(dt.DefaultCtor == null); // the intention is that this method be called only when DefaultCtor hasn't already been set
Contract.Ensures(!Contract.Result<bool>() || dt.DefaultCtor != null);
// Stated differently, check that there is some constuctor where no argument type goes to the same stratum.
DatatypeCtor defaultCtor = 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 (defaultCtor == null || typeParametersUsed.Count < lastTypeParametersUsed.Count) {
defaultCtor = ctor;
lastTypeParametersUsed = typeParametersUsed;
}
NEXT_OUTER_ITERATION: { }
}
if (defaultCtor != null) {
dt.DefaultCtor = defaultCtor;
dt.TypeParametersUsedInConstructionByDefaultCtor = new bool[dt.TypeArgs.Count];
for (int i = 0; i < dt.TypeArgs.Count; i++) {
dt.TypeParametersUsedInConstructionByDefaultCtor[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 tp, List<TypeParameter> typeParametersUsed) {
tp = tp.NormalizeExpand();
var dependee = tp.AsIndDatatype;
if (dependee == null) {
// the type is not an inductive datatype, which means it is always possible to construct it
if (tp.IsTypeParameter) {
typeParametersUsed.Add(((UserDefinedType)tp).ResolvedParam);
}
return true;
} else if (dependee.DefaultCtor == 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(((UserDefinedType)tp).TypeArgs.Count == dependee.TypeParametersUsedInConstructionByDefaultCtor.Length);
var i = 0;
foreach (var ta in ((UserDefinedType)tp).TypeArgs) { // note, "tp" is known to be a UserDefinedType, because that follows from tp being an inductive datatype
if (dependee.TypeParametersUsedInConstructionByDefaultCtor[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 FixpointPredicate);
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;
}
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 (MaybeFreeExpression 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 (MaybeFreeExpression 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
}
// 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 (MaybeFreeExpression 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 FixpointLemma) {
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 FixpointLemma && 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 (MaybeFreeExpression 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 FixpointLemma;
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 colemmas)
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.Concat(iter.Outs)) {
ResolveType(p.tok, p.Type, iter, option, iter.TypeArgs);
}
// 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 (MaybeFreeExpression 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 (MaybeFreeExpression 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 (MaybeFreeExpression 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 (MaybeFreeExpression 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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(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 MaybeFreeExpression(eq));
}
// ensures more ==> YieldEnsures;
foreach (var ye in iter.YieldEnsures) {
ens.Add(new MaybeFreeExpression(
new BinaryExpr(iter.tok, BinaryExpr.Opcode.Imp, new IdentifierExpr(iter.tok, "more"), ye.E),
ye.IsFree));
}
// ensures !more ==> Ensures;
foreach (var e in iter.Ensures) {
ens.Add(new MaybeFreeExpression(new BinaryExpr(iter.tok, BinaryExpr.Opcode.Imp,
new UnaryOpExpr(iter.tok, UnaryOpExpr.Opcode.Not, new IdentifierExpr(iter.tok, "more")),
e.E),
e.IsFree));
}
// 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.MustSupportZeroInitialization = true;
}
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 == 1);
Contract.Assert(s.Locals.Count == 1);
var local = s.Locals[0];
var lhs = (IdentifierExpr)assignOrRet.Lhss[0]; // 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 LetStmt) {
LetStmt s = (LetStmt)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.Module != 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 MaybeFreeExpression(result, true));
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;
ResolveNestedMatchStmt(s, codeContext);
} 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<MaybeFreeExpression> 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 (MaybeFreeExpression 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) {
if (!codeContext.AllowsNontermination && !DafnyOptions.O.Dafnycc) {
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, ICodeContext 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 errorCount = reporter.Count(ErrorLevel.Error);
if (s.Source is DatatypeValue) {
var e = (DatatypeValue)s.Source;
if (e.Arguments.Count < 1) {
reporter.Error(MessageSource.Resolver, s.Tok, "match source tuple needs at least 1 argument");
}
foreach (var arg in e.Arguments) {
if (arg is DatatypeValue && ((DatatypeValue)arg).Arguments.Count < 1) {
reporter.Error(MessageSource.Resolver, s.Tok, "match source tuple needs at least 1 argument");
}
}
}
if (reporter.Count(ErrorLevel.Error) != errorCount) {
return;
}
var sourceType = PartiallyResolveTypeForMemberSelection(s.Source.tok, s.Source.Type).NormalizeExpand();
errorCount = reporter.Count(ErrorLevel.Error);
CheckLinearNestedMatchStmt(sourceType, s);
if (reporter.Count(ErrorLevel.Error) != errorCount) return;
errorCount = reporter.Count(ErrorLevel.Error);
CompileNestedMatchStmt(s, codeContext);
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);
if (s.Source is DatatypeValue) {
var e = (DatatypeValue)s.Source;
if (e.Arguments.Count < 1) {
reporter.Error(MessageSource.Resolver, s.Tok, "match source tuple needs at least 1 argument");
}
foreach (var arg in e.Arguments) {
if (arg is DatatypeValue && ((DatatypeValue)arg).Arguments.Count < 1) {
reporter.Error(MessageSource.Resolver, s.Tok, "match source tuple needs at least 1 argument");
}
}
}
if (reporter.Count(ErrorLevel.Error) != errorCount) {
return;
}
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) {Type = idExpr.Type};
}
}
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 LetStmt(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, new List<ExtendedPattern>(), 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;
if (pat is LitPattern lpat) {
if (!alternatives.Exists(x => x.Value.Equals(lpat.Lit.Value))) {
alternatives.Add(lpat.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>();
for (int i = 0; i < pairPB.Count; i++) {
var PB = pairPB.ElementAt(i);
switch (PB.Item1) {
case LitPattern currPattern:
// if pattern matches the current alternative, add it to the branch for this case, otherwise ignore it
if (currPattern.Lit.Value.Equals(currLit.Value)) {
mti.UpdateBranchID(PB.Item2.BranchID, 1);
currBranches.Add(CloneRBranch(PB.Item2));
}
break;
case 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);
break;
default:
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) {
// 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)) {
// ==[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 != null) {
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);
} else if (!ctor.Value.Formals.Count.Equals(0)) {
reporter.Error(MessageSource.Resolver, mti.BranchTok[PB.Item2.BranchID], "constructor {0} of arity {1} is applied to 0 argument", ctor.Key, ctor.Value.Formals.Count);
}
currBranches.Add(currBranch);
} else if (ctors.ContainsKey(currPattern.Id)) {
// ==[3.2]== If the pattern is a difference constructor, drop the branch
mti.UpdateBranchID(PB.Item2.BranchID, -1);
} 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) { Var = x, Type = x.Type });
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 decreate 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 && 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)) {
// ==[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.Count != 0) {
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, ICodeContext codeContext) {
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(), 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 ");
}
}
} 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, ICodeContext 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");
}
}
} 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) {
if (pat.Arguments.Count != 0) {
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 {
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) {
if (type == null) {
return;
}
if (!type.IsDatatype) {
if (pat is IdPattern) {
/* =[1]= */
CheckLinearVarPattern(type, (IdPattern) pat);
return;
} else if (pat is LitPattern) {
/* =[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;
//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.Arguments.Count == 0) {
CheckLinearVarPattern(udt, idpat);
} else {
reporter.Error(MessageSource.Resolver, pat.Tok, "case arguments count does not match source arguments 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);
}
return;
} else {
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.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);
}
}
} 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);
}
}
}
private void CheckLinearNestedMatchCase(Type type, NestedMatchCase mc) {
CheckLinearExtendedPattern(type, mc.Pat);
}
/*
* 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) {
foreach(NestedMatchCaseExpr mc in me.Cases) {
scope.PushMarker();
CheckLinearNestedMatchCase(dtd, mc);
scope.PopMarker();
}
}
private void CheckLinearNestedMatchStmt(Type dtd, NestedMatchStmt ms) {
foreach(NestedMatchCaseStmt mc in ms.Cases) {
scope.PushMarker();
CheckLinearNestedMatchCase(dtd, mc);
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);
}
var a = new CallStmt(methodCallInfo.Tok, update.EndTok, resolvedLhss, methodCallInfo.Callee, methodCallInfo.Args);
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);
if (s.AssumeToken == null) {
// to ease in the verification of the existence check, only allow local variables as LHSs
foreach (var lhs in s.Lhss) {
var ide = lhs.Resolved as IdentifierExpr;
if (ide == null) {
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>() { });
}
/// <summary>
/// Desugars "y :- MethodOrExpression" into
/// "var temp := MethodOrExpression; if temp.IsFailure() { return temp.PropagateFailure(); } y := temp.Extract();"
/// and "y :- expect MethodOrExpression" into
/// "var temp := 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?
var temp = FreshTempVarName("valueOrError", codeContext);
var tempType = new InferredTypeProxy();
s.ResolvedStatements.Add(
// "var temp := MethodOrExpression;"
new VarDeclStmt(s.Tok, s.Tok, new List<LocalVariable>() { new LocalVariable(s.Tok, s.Tok, temp, tempType, false) },
new UpdateStmt(s.Tok, s.Tok, new List<Expression>() { new IdentifierExpr(s.Tok, temp) }, new List<AssignmentRhs>() { new ExprRhs(s.Rhs) })));
if (s.ExpectToken != null) {
var notFailureExpr = new UnaryOpExpr(s.Tok, UnaryOpExpr.Opcode.Not, VarDotMethod(s.Tok, temp, "IsFailure"));
s.ResolvedStatements.Add(
// "expect !temp.IsFailure(), temp"
new ExpectStmt(s.Tok, s.Tok, notFailureExpr, new IdentifierExpr(s.Tok, temp), null));
} else {
s.ResolvedStatements.Add(
// "if temp.IsFailure()"
new IfStmt(s.Tok, s.Tok, false, VarDotMethod(s.Tok, temp, "IsFailure"),
// THEN: { return temp.PropagateFailure(); }
new BlockStmt(s.Tok, s.Tok, new List<Statement>() {
new ReturnStmt(s.Tok, s.Tok, new List<AssignmentRhs>() { new ExprRhs(VarDotMethod(s.Tok, temp, "PropagateFailure"))}),
}),
// ELSE: no else block
null
));
}
Contract.Assert(s.Lhss.Count <= 1);
if (s.Lhss.Count == 1)
{
// "y := temp.Extract();"
s.ResolvedStatements.Add(
new UpdateStmt(s.Tok, s.Tok, s.Lhss, new List<AssignmentRhs>() {
new ExprRhs(VarDotMethod(s.Tok, temp, "Extract"))}));
}
foreach (var a in s.ResolvedStatements) {
ResolveStatement(a, codeContext);
}
bool expectExtract = s.Lhss.Count != 0;
EnsureSupportsErrorHandling(s.Tok, PartiallyResolveTypeForMemberSelection(s.Tok, tempType), expectExtract);
}
private void EnsureSupportsErrorHandling(IToken tok, Type tp, bool expectExtract) {
// 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 (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");
}
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++;
}
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);
}
} else {
if (isInitCall) {
if (callee.IsStatic) {
reporter.Error(MessageSource.Resolver, s.Tok, "a method called as an initialization method must not be 'static'");
}
} 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");
}
}
// 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++) {
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})");
// 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 LetStmt) {
// 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 LetStmt) {
// 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, 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(Type.Int);
}
var arrowType = new ArrowType(rr.ElementInit.tok, builtIns.ArrowTypeDecls[rr.ArrayDimensions.Count], args, rr.EType);
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.Module != currentClass.Module)) {
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.Write("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 proxyTypeArgs = mbr.EnclosingClass.TypeArgs.ConvertAll(_ => (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");
return t;
}
}
// 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) {
meet = Type.HeadWithProxyArgs(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;
var errorCount = reporter.Count(ErrorLevel.Error);
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
Type elementType = 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, "array selection requires integer-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, multiset, or datatype (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, "sequence construction must use an integer-based expression for the sequence size (got {0})");
ResolveExpression(e.Initializer, opts);
var arrowType = new ArrowType(e.tok, builtIns.ArrowTypeDecls[1], new List<Type>() { Type.Int }, 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.NumericPersuation.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.NumericPersuation.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 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 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.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 NamedExpr) {
var e = (NamedExpr)expr;
ResolveExpression(e.Body, opts);
if (e.Contract != null) ResolveExpression(e.Contract, opts);
e.Type = e.Body.Type;
} 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);
bool expectExtract = (expr.Lhs != null);
EnsureSupportsErrorHandling(expr.tok, PartiallyResolveTypeForMemberSelection(expr.tok, tempType), expectExtract);
}
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 (not a bitvector, but possibly an
/// int-based newtype). The "errFormat" string can contain a "{0}", referring to the name of the type of "expr".
/// </summary>
void ConstrainToIntegerType(Expression expr, string errFormat) {
Contract.Requires(expr != null);
Contract.Requires(errFormat != 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.
var err = new TypeConstraint.ErrorMsgWithToken(expr.tok, errFormat, expr.Type);
ConstrainSubtypeRelation(new IntVarietiesSupertype(), expr.Type, err);
AddXConstraint(expr.tok, "IntegerType", expr.Type, err);
}
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);
if (me.Source is DatatypeValue) {
var e = (DatatypeValue)me.Source;
if (e.Arguments.Count < 1) {
reporter.Error(MessageSource.Resolver, me.tok, "match source tuple needs at least 1 argument");
}
foreach (var arg in e.Arguments) {
if (arg is DatatypeValue && ((DatatypeValue)arg).Arguments.Count < 1) {
reporter.Error(MessageSource.Resolver, me.tok, "match source tuple needs at least 1 argument");
}
}
}
if (reporter.Count(ErrorLevel.Error) != errorCount) {
return;
}
var sourceType = PartiallyResolveTypeForMemberSelection(me.Source.tok, me.Source.Type).NormalizeExpand();
errorCount = reporter.Count(ErrorLevel.Error);
if (debug) Console.WriteLine("DEBUG: {0} ResolveNestedMatchExpr 1 - Checking Linearity of patterns", me.tok.line);
CheckLinearNestedMatchExpr(sourceType, me);
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.codeContext);
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 errorCount = reporter.Count(ErrorLevel.Error);
if (me.Source is DatatypeValue) {
var e = (DatatypeValue)me.Source;
if (e.Arguments.Count < 1) {
reporter.Error(MessageSource.Resolver, me.tok, "match source tuple needs at least 1 argument");
}
foreach (var arg in e.Arguments) {
if (arg is DatatypeValue && ((DatatypeValue)arg).Arguments.Count < 1) {
reporter.Error(MessageSource.Resolver, me.tok, "match source tuple needs at least 1 argument");
}
}
}
if (reporter.Count(ErrorLevel.Error) != errorCount) {
return;
}
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)) {
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 {
var argCount = pat.Arguments == null ? 0 : pat.Arguments.Count;
if (ctor.Formals.Count != argCount) {
reporter.Error(MessageSource.Resolver, pat.tok, "pattern for constructor {0} has wrong number of formals (found {1}, expected {2})", pat.Id, argCount, 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
///
/// </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) {
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:
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) {
reporter.Error(MessageSource.Resolver, expr.tok, "variable '{0}' does not take any type parameters", name);
}
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) {
reporter.Error(MessageSource.Resolver, expr.tok, "'this' is not allowed in a 'static' context"); //TODO: Rephrase this
// 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 (pair.Item2) {
// there is more than one constructor with this name
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 {
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 (moduleInfo.TopLevels.TryGetValue(name, out decl)) {
// ----- 3. 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 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.
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 (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;
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 {
var receiver = new StaticReceiverExpr(expr.tok, (ClassDecl)member.EnclosingClass, true);
r = ResolveExprDotCall(expr.tok, receiver, null, member, args, expr.OptTypeArguments, opts, allowMethodCall);
}
} else {
// ----- None of the above
reporter.Error(MessageSource.Resolver, expr.tok, "unresolved identifier: {0}", 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;
var rt = r.Type;
var nt = rt.UseInternalSynonym();
expr.Type = nt;
}
return rWithArgs;
}
/// <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;
r = ResolveExprDotCall(expr.tok, receiver, tentativeReceiverType, member, args, expr.OptTypeArguments, opts, allowMethodCall);
} else {
receiver = new StaticReceiverExpr(expr.tok, (UserDefinedType)tentativeReceiverType, (TopLevelDeclWithMembers)member.EnclosingClass, false);
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 method ({0})", 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 (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.NumericPersuation.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, "method call is not allowed to be used in an expression context ({0})", 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 FixpointPredicate) {
((FixpointPredicate)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;
}
private void ResolveDatatypeValue(ResolveOpts opts, DatatypeValue dtv, DatatypeDecl dt, Type ty) {
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 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)) {
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) {
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++;
}
}
/// <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 NamedExpr) {
if (!moduleInfo.IsAbstract)
CheckIsCompilable(((NamedExpr)expr).Body);
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 FixpointPredicate) {
((FixpointPredicate)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.AsIndDatatype));
} else if (bv.Type.IsNumericBased(Type.NumericPersuation.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.Equals(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.Equals(e1.Type.AsMultiSetType.Arg)));
}
break;
case BinaryExpr.ResolvedOpcode.InSeq:
if (whereIsBv == 0) {
bounds.Add(new ComprehensionExpr.SeqBoundedPool(e1, e0.Type.Equals(e1.Type.AsSeqType.Arg)));
}
break;
case BinaryExpr.ResolvedOpcode.InMap:
if (whereIsBv == 0) {
bounds.Add(new ComprehensionExpr.MapBoundedPool(e1, e0.Type.Equals(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.NumericPersuation.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.NumericPersuation.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.
/// </summary>
public static BinaryExpr.ResolvedOpcode ResolveOp(BinaryExpr.Opcode op, 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.MapUnion;
} else if (operandType is SeqType) {
return BinaryExpr.ResolvedOpcode.Concat;
} else {
return BinaryExpr.ResolvedOpcode.Add;
}
case BinaryExpr.Opcode.Sub:
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) {
return Contract.Exists(e.RHSs, ee => UsesSpecFeatures(ee)) || UsesSpecFeatures(e.Body);
} else {
return true; // let-such-that is always ghost
}
} else if (expr is NamedExpr) {
return moduleInfo.IsAbstract ? false : UsesSpecFeatures(((NamedExpr)expr).Body);
} 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 {
Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
}
/// <summary>
/// This method adds to "friendlyCalls" all
/// inductive calls if !co
/// copredicate 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 an inductive lemma if !co
/// postcondition of a colemma, 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 CollectFriendlyCallsInFixpointLemmaSpecification(Expression expr, bool position, ISet<Expression> friendlyCalls, bool co, FixpointLemma 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 FixpointLemma Context;
public CollectFriendlyCallsInSpec_Visitor(Resolver resolver, ISet<Expression> friendlyCalls, bool co, FixpointLemma 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 CoPredicate : fexp.Function is InductivePredicate) {
if (Context.KNat != ((FixpointPredicate)fexp.Function).KNat) {
resolver.KNatMismatchError(expr.tok, Context.Name, Context.TypeOfK, ((FixpointPredicate)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);
}
}
}
| 49.041795 | 358 | 0.611694 | [
"MIT"
] | utaal/dafny | Source/Dafny/Resolver.cs | 813,162 | C# |
using System;
using Microsoft.WindowsAzure.Storage.Blob;
namespace XYZToDo.Models.AzureModels
{
public class CloudContainer
{
public string ContainerName { get; set; }
public string URI { get; set; }
public string CreatedBy { get; set; }
public DateTimeOffset? CreatedAt { get; set; }
public static CloudContainer CreateFromCloudBlobContainer(CloudBlobContainer item)
{
if (item is CloudBlobContainer)
{
var container = (CloudBlobContainer)item;
container.FetchAttributesAsync().Wait(5000);//Gets the properties & metadata
string CreatedBy;
var result = container.Metadata.TryGetValue("CreatedBy", out CreatedBy);
if (!result)
return null;
return new CloudContainer
{
ContainerName = container.Name,
URI = container.Uri.ToString(),
CreatedAt=DateTimeOffset.Now,
CreatedBy=CreatedBy
};
}
return null;
}
}
} | 32.914286 | 92 | 0.551215 | [
"MIT"
] | tadakoglu/Xyzeki | Models/AzureModels/CloudContainer.cs | 1,152 | C# |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// The main job queue class. Encapsulates all behaviour related to queueing a job. Provides access to events, and status (i.e. running, repeating).
/// </summary>
public class CM_JobQueue : CM_GlobalCoroutineManager<CM_JobQueue>, ICM_Cloneable<CM_JobQueue>
{
#region PublicProperties
/// <summary>
/// Gets a value indicating whether this <see cref="CM_JobQueue"/> is repeating.
/// </summary>
/// <value><c>true</c> if repeating; otherwise, <c>false</c>.</value>
public bool repeating {get; private set;}
/// <summary>
/// Gets the number of times this queue executed (used if repeating).
/// </summary>
/// <value>The number of times executed.</value>
public int numOfTimesExecuted {get;private set;}
/// <summary>
/// Gets a value indicating whether this <see cref="CM_JobQueue"/> is running.
/// </summary>
/// <value><c>true</c> if running; otherwise, <c>false</c>.</value>
public bool running {get {return _jobQueueRunning;}}
/// <summary>
/// Gets a value indicating whether this <see cref="CM_JobQueue"/> is running continously i.e. will not stop running until StopContinousRunning is called.
/// </summary>
/// <value><c>true</c> if continous running; otherwise, <c>false</c>.</value>
public bool continousRunning {get {return _continousRunning;}}
#endregion
#region Events
/// <summary>
/// Raised when queue started.
/// </summary>
protected event EventHandler<CM_QueueEventArgs> queueStarted;
/// <summary>
/// Raised when queue complete.
/// </summary>
protected event EventHandler<CM_QueueEventArgs> queueComplete;
/// <summary>
/// Raised when a job in the queue has finished.
/// </summary>
protected event EventHandler<CM_QueueEventArgs> jobProcessed;
#endregion
/// <summary>
/// Gets a value indicating whether this <see cref="CM_JobQueue"/> has difficulty starting.
/// THis may be because the queue is already running or that there are no jobs in the queue.
/// </summary>
/// <value><c>true</c> if error starting; otherwise, <c>false</c>.</value>
private bool errorStarting {
get {
if (_jobQueueRunning) {
CM_Logger.instance.Log (this, "Queue already processing");
return true;
}
return false;
}
}
/// <summary>
/// Used to repeat the routine a set number of times, if
/// <see cref="CM_JobQueue.repeating"/> is true.
/// </summary>
private int? _numOfTimesToRepeat;
private Queue<CM_Job> _jobQueue = new Queue<CM_Job> ();
private bool _jobQueueRunning = false;
private bool _continousRunning = false;
private List<CM_Job> _completedJobs = new List<CM_Job> ();
/// <summary>
/// Returns an initialised <see cref="CM_JobQueue"/> instance. Provides static access to class.
/// </summary>
public static CM_JobQueue Make ()
{
return new CM_JobQueue ();
}
/// <summary>
/// Clone this instance.
/// </summary>
public CM_JobQueue Clone ()
{
var clonedQueue = Make ();
var queue = _jobQueue.ToArray ();
for (int i = 0; i <= queue.Length - 1; i++) {
clonedQueue.Enqueue (queue[i].Clone ().RemoveNotifyOnJobComplete (HandlejobComplete));
}
if (queueStarted != null) {
clonedQueue.queueStarted += queueStarted;
}
if (queueComplete != null) {
clonedQueue.queueComplete += queueComplete;
}
if (jobProcessed != null) {
clonedQueue.jobProcessed += jobProcessed;
}
foreach (var job in _completedJobs) {
clonedQueue._completedJobs.Add (job);
}
clonedQueue.repeating = repeating;
clonedQueue._numOfTimesToRepeat = _numOfTimesToRepeat;
return clonedQueue;
}
/// <summary>
/// Clone this instance the specified numOfCopies.
/// </summary>
/// <param name="numOfCopies">Number of copies.</param>
public CM_JobQueue[] Clone (int numOfCopies)
{
var queue = new CM_JobQueue[numOfCopies];
for (int i = 0; i < numOfCopies; i++) {
queue[i] = Clone ();
}
return queue;
}
#region Enqueue
/// <summary>
/// Enqueues the specified other queue. Adds the jobs from one queue to this queue and also adds the other queues event subscriptions.
/// </summary>
/// <param name="other">Other.</param>
public CM_JobQueue Enqueue (CM_JobQueue other)
{
foreach (var job in other._jobQueue) {
Enqueue (job);
}
if (other.jobProcessed != null) {
this.jobProcessed += other.jobProcessed;
}
if (other.queueStarted != null) {
this.queueStarted += other.queueStarted;
}
if (other.queueComplete != null) {
this.queueComplete += other.queueComplete;
}
return this;
}
/// <summary>
/// Enqueues the specified jobs.
/// </summary>
/// <param name="jobs">Jobs.</param>
public CM_JobQueue Enqueue (params CM_Job[] jobs)
{
foreach (var job in jobs) {
Enqueue (job);
}
return this;
}
/// <summary>
/// Enqueues the specified jobs.
/// </summary>
/// <param name="jobs">Jobs.</param>
public CM_JobQueue Enqueue (IList<CM_Job> jobs)
{
foreach (var job in jobs) {
Enqueue (job);
}
return this;
}
/// <summary>
/// Creates a new job with specified id and coroutine and adds job to queue.
/// </summary>
/// <param name="id">Job Identifier.</param>
/// <param name="routine">Routine.</param>
public CM_JobQueue Enqueue (string id, IEnumerator routine)
{
return Enqueue (MakeJob (id, routine, false));
}
/// <summary>
/// Creates a new job with specified id and coroutine and adds job to queue.
/// </summary>
/// <param name="id">Job Identifier.</param>
/// <param name="routine">Routine.</param>
public CM_JobQueue Enqueue (IEnumerator routine)
{
return Enqueue (MakeJob (null, routine, false));
}
/// <summary>
/// Enqueues the specified job.
/// </summary>
/// <param name="job">Job.</param>
public CM_JobQueue Enqueue (CM_Job job)
{
job.NotifyOnJobComplete (HandlejobComplete);
AddJobToQueue(job);
if (_continousRunning && _jobQueue.Count == 1) {
_jobQueue.Peek ().Start ();
}
return this;
}
#endregion
#region PublicOperations
/// <summary>
/// Start this instance of the queue immediately.
/// </summary>
public CM_JobQueue Start ()
{
if (!errorStarting) {
OnQueueStarted (new CM_QueueEventArgs (_jobQueue.ToArray (), _completedJobs.ToArray (), this));
if (_jobQueue.Count > 0) {
_jobQueue.Peek ().Start ();
}
_jobQueueRunning = true;
}
return this;
}
/// <summary>
/// Start the specified instance after delayInSeconds.
/// </summary>
/// <param name="delayInSeconds">Delay in seconds.</param>
public CM_JobQueue Start (float delayInSeconds)
{
if (errorStarting) {
return this;
}
int delay = (int)delayInSeconds * 1000;
new System.Threading.Timer (obj => {
lock (this) {
OnQueueStarted (new CM_QueueEventArgs (_jobQueue.ToArray (), _completedJobs.ToArray (), this));
if (_jobQueue.Count > 0) {
_jobQueue.Peek ().Start (0f);
}
_jobQueueRunning = true;
}
}, null, delay, System.Threading.Timeout.Infinite);
return this;
}
/// <summary>
/// Sets this instance to repeat. The job is repeated when it has finished processing.
/// </summary>
public CM_JobQueue Repeat ()
{
repeating = true;
return this;
}
/// <summary>
/// Sets this instance to repeat a number of times. The job is repeated when it has finished processing.
/// </summary>
public CM_JobQueue Repeat (int numOfTimes)
{
repeating = true;
numOfTimesExecuted = 0;
_numOfTimesToRepeat = numOfTimes;
return this;
}
/// <summary>
/// Stops the repeat.
/// </summary>
/// <returns>The repeat.</returns>
public CM_JobQueue StopRepeat ()
{
repeating = false;
return this;
}
/// <summary>
/// Stops the repeat after a specified delay in seconds.
/// </summary>
/// <returns>The repeat.</returns>
/// <param name="delayInSeconds">Delay in seconds.</param>
public CM_JobQueue StopRepeat (float delayInSeconds)
{
int delay = (int) delayInSeconds * 1000;
new System.Threading.Timer (obj => {
lock (this) {
repeating = false;
_numOfTimesToRepeat = null;
}
}, null, delay, System.Threading.Timeout.Infinite);
return this;
}
/// <summary>
/// Pauses this instance.
/// </summary>
public CM_JobQueue Pause ()
{
if (_jobQueueRunning) {
_jobQueue.Peek ().Pause ();
}
return this;
}
/// <summary>
/// Pause this instance after the specified delayInSeconds.
/// </summary>
/// <param name="delayInSeconds">Delay in seconds.</param>
public CM_JobQueue Pause (float delayInSeconds)
{
int delay = (int)delayInSeconds * 1000;
new System.Threading.Timer (obj => {
lock (this) {
Pause ();
}
}, null, delay, System.Threading.Timeout.Infinite);
return this;
}
/// <summary>
/// Resume this instance immediately.
/// </summary>
public CM_JobQueue Resume ()
{
if (_jobQueueRunning && _jobQueue.Count > 0) {
_jobQueue.Peek ().Resume ();
}
return this;
}
/// <summary>
/// Resume the instance after the specified delayInSeconds.
/// </summary>
/// <param name="delayInSeconds">Delay in seconds.</param>
public CM_JobQueue Resume (float delayInSeconds)
{
int delay = (int)delayInSeconds * 1000;
new System.Threading.Timer (obj => {
lock (this) {
Resume ();
}
}, null, delay, System.Threading.Timeout.Infinite);
return this;
}
/// <summary>
/// Set the queue to run continously.
/// </summary>
public CM_JobQueue ContinousRunning ()
{
_continousRunning = true;
return this;
}
/// <summary>
/// Stops the continous running of this queue.
/// </summary>
public CM_JobQueue StopContinousRunning ()
{
_continousRunning = false;
return this;
}
/// <summary>
/// Kill all currently queued jobs immediately. Clears queue list.
/// </summary>
public CM_JobQueue KillAll ()
{
if (_jobQueue.Count == 0) {
return this;
}
var jobs = _jobQueue.ToArray ();
foreach (var job in jobs) {
job.Kill ();
}
return this;
}
/// <summary>
/// Kill all currently queued jobs after the specified delayInSeconds.
/// </summary>
/// <param name="delayInSeconds">Delay in seconds.</param>
public CM_JobQueue KillAll (float delayInSeconds)
{
int delay = (int)delayInSeconds * 1000;
new System.Threading.Timer (obj => {
lock (this) {
KillAll ();
}
}, null, delay, System.Threading.Timeout.Infinite);
return this;
}
/// <summary>
/// Kills the current running job immediately.
/// </summary>
/// <returns>The current.</returns>
public CM_JobQueue KillCurrent ()
{
if (_jobQueue.Count > 0) {
_jobQueue.Peek ().Kill ();
}
return this;
}
/// <summary>
/// Kills the current running job after the specified delayInSeconds.
/// </summary>
/// <returns>The current.</returns>
/// <param name="delayInSeconds">Delay in seconds.</param>
public CM_JobQueue KillCurrent (float delayInSeconds)
{
if (_jobQueue.Count > 0) {
int delay = (int)delayInSeconds * 1000;
new System.Threading.Timer (obj => {
lock (this) {
KillCurrent ();
}
}, null, delay, System.Threading.Timeout.Infinite);
}
return this;
}
#endregion
#region EventSubscription
/// <summary>
/// Subscribes to the queue started event.
/// </summary>
/// <param name="e">The event handler to be invoked on event.</param>
public CM_JobQueue NotifyOnQueueStarted (EventHandler<CM_QueueEventArgs> e)
{
queueStarted += e;
return this;
}
/// <summary>
/// Unsubscribes to the the queue started event.
/// </summary>
/// <param name="e">The event handler to be invoked on event.</param>
public CM_JobQueue RemoveNotifyOnQueueStarted (EventHandler<CM_QueueEventArgs> e)
{
queueStarted -= e;
return this;
}
/// <summary>
/// Subscribes to the queue completed event.
/// </summary>
/// <param name="e">The event handler to be invoked on event.</param>
public CM_JobQueue NotifyOnQueueComplete (EventHandler<CM_QueueEventArgs> e)
{
queueComplete += e;
return this;
}
/// <summary>
/// Unsubscribes to the queue completed event.
/// </summary>
/// <param name="e">The event handler to be invoked on event.</param>
public CM_JobQueue RemoveNotifyOnQueueComplete (EventHandler<CM_QueueEventArgs> e)
{
queueComplete -= e;
return this;
}
/// <summary>
/// Subscribes to the the job processed event.
/// </summary>
/// <param name="e">The event handler to be invoked on event.</param>
public CM_JobQueue NotifyOnJobProcessed (EventHandler<CM_QueueEventArgs> e)
{
jobProcessed += e;
return this;
}
/// <summary>
/// Unsubscribes to the the job processed event. This event is invoked every time a job in the queue has finished running.
/// </summary>
/// <param name="e">The event handler to be invoked on event.</param>
public CM_JobQueue RemoveNotifyOnJobProcessed (EventHandler<CM_QueueEventArgs> e)
{
jobProcessed -= e;
return this;
}
#endregion
#region EventHandlers
/// <summary>
/// Raises the queue started event.
/// </summary>
/// <param name="e">E.</param>
protected void OnQueueStarted (CM_QueueEventArgs e)
{
if (queueStarted != null) {
queueStarted (this, e);
}
}
/// <summary>
/// Raises the queue complete event.
/// </summary>
/// <param name="e">E.</param>
protected void OnQueueComplete (CM_QueueEventArgs e)
{
if (queueComplete != null) {
queueComplete (this, e);
}
}
/// <summary>
/// Raises the job processed event.
/// </summary>
/// <param name="e">E.</param>
protected void OnJobProcessed (CM_QueueEventArgs e)
{
if (jobProcessed != null) {
jobProcessed (this, e);
}
}
#endregion
/// <summary>
/// Invoked whenever a queued job has finished processing. Handles maintenance of queue and raising
/// OnJobProcessed and OnQueueComplete events.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
protected override void HandlejobComplete (object sender, CM_JobEventArgs e)
{
if (e.job.repeating) {
return;
}
RemoveJobFromQueue (e.job);
var jobQueue = _jobQueue.ToArray ();
var completedJobs = _completedJobs.ToArray ();
OnJobProcessed (new CM_QueueEventArgs (jobQueue, completedJobs, this));
if (_jobQueue.Count > 0 && _jobQueueRunning) {
_jobQueue.Peek ().Start ();
} else if (_jobQueue.Count == 0 && _jobQueueRunning) {
numOfTimesExecuted++;
OnQueueComplete (new CM_QueueEventArgs (jobQueue, completedJobs, this));
if (repeating) {
if (!_numOfTimesToRepeat.HasValue) {
RequeueAll ();
_jobQueue.Peek ().Start ();
} else {
if (numOfTimesExecuted < _numOfTimesToRepeat) {
RequeueAll ();
_jobQueue.Peek ().Start ();
} else {
repeating = false;
_numOfTimesToRepeat = null;
_jobQueueRunning = false;
}
}
} else if (!_continousRunning) {
_jobQueueRunning = false;
}
_completedJobs.Clear ();
}
}
private void RequeueAll ()
{
_jobQueue.Clear ();
foreach (var job in _completedJobs) {
var jobClone = job.Clone ().NotifyOnJobComplete (HandlejobComplete);
_jobQueue.Enqueue (jobClone);
}
}
private void AddJobToQueue (CM_Job job)
{
_jobQueue.Enqueue (job);
}
private void RemoveJobFromQueue (CM_Job job)
{
job.RemoveNotifyOnJobComplete (HandlejobComplete);
_completedJobs.Add (job);
_jobQueue.Dequeue ();
}
}
| 23.085973 | 155 | 0.666863 | [
"MIT"
] | GandhiGames/unity_coroutine_manager | Assets/CM/Scripts/CM Main/CM_JobQueue.cs | 15,308 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using FairyGUI.Utils;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace FairyGUI
{
/// <summary>
/// A UI Package contains a description file and some texture,sound assets.
/// </summary>
public class UIPackage
{
/// <summary>
/// Package id. It is generated by the Editor, or set by customId.
/// </summary>
public string id { get; private set; }
/// <summary>
/// Package name.
/// </summary>
public string name { get; private set; }
/// <summary>
/// The path relative to the resources folder.
/// </summary>
public string assetPath { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="extension"></param>
/// <param name="type"></param>
/// <returns></returns>
public delegate object LoadResource(string name, string extension, System.Type type, out DestroyMethod destroyMethod);
/// <summary>
///
/// </summary>
/// <param name="result"></param>
public delegate void CreateObjectCallback(GObject result);
List<PackageItem> _items;
Dictionary<string, PackageItem> _itemsById;
Dictionary<string, PackageItem> _itemsByName;
AssetBundle _resBundle;
string _customId;
bool _fromBundle;
LoadResource _loadFunc;
class AtlasSprite
{
public PackageItem atlas;
public Rect rect = new Rect();
public bool rotated;
}
Dictionary<string, AtlasSprite> _sprites;
static Dictionary<string, UIPackage> _packageInstById = new Dictionary<string, UIPackage>();
static Dictionary<string, UIPackage> _packageInstByName = new Dictionary<string, UIPackage>();
static List<UIPackage> _packageList = new List<UIPackage>();
internal static int _constructing;
public const string URL_PREFIX = "ui://";
public UIPackage()
{
_items = new List<PackageItem>();
_itemsById = new Dictionary<string, PackageItem>();
_itemsByName = new Dictionary<string, PackageItem>();
_sprites = new Dictionary<string, AtlasSprite>();
}
/// <summary>
/// Return a UIPackage with a certain id.
/// </summary>
/// <param name="id">ID of the package.</param>
/// <returns>UIPackage</returns>
public static UIPackage GetById(string id)
{
UIPackage pkg;
if (_packageInstById.TryGetValue(id, out pkg))
return pkg;
else
return null;
}
/// <summary>
/// Return a UIPackage with a certain name.
/// </summary>
/// <param name="name">Name of the package.</param>
/// <returns>UIPackage</returns>
public static UIPackage GetByName(string name)
{
UIPackage pkg;
if (_packageInstByName.TryGetValue(name, out pkg))
return pkg;
else
return null;
}
/// <summary>
/// Add a UI package from assetbundle.
/// </summary>
/// <param name="bundle">A assetbundle.</param>
/// <returns>UIPackage</returns>
public static UIPackage AddPackage(AssetBundle bundle)
{
return AddPackage(bundle, bundle, null);
}
/// <summary>
/// Add a UI package from two assetbundles. desc and res can be same.
/// </summary>
/// <param name="desc">A assetbunble contains description file.</param>
/// <param name="res">A assetbundle contains resources.</param>
/// <returns>UIPackage</returns>
public static UIPackage AddPackage(AssetBundle desc, AssetBundle res)
{
return AddPackage(desc, res, null);
}
/// <summary>
/// Add a UI package from two assetbundles with a optional main asset name.
/// </summary>
/// <param name="desc">A assetbunble contains description file.</param>
/// <param name="res">A assetbundle contains resources.</param>
/// <param name="mainAssetName">Main asset name. e.g. Basics_fui.bytes</param>
/// <returns>UIPackage</returns>
public static UIPackage AddPackage(AssetBundle desc, AssetBundle res, string mainAssetName)
{
byte[] source = null;
#if (UNITY_5 || UNITY_5_3_OR_NEWER)
if (mainAssetName != null)
{
TextAsset ta = desc.LoadAsset<TextAsset>(mainAssetName);
if (ta != null)
source = ta.bytes;
}
else
{
string[] names = desc.GetAllAssetNames();
string searchPattern = "_fui";
foreach (string n in names)
{
if (n.IndexOf(searchPattern) != -1)
{
TextAsset ta = desc.LoadAsset<TextAsset>(n);
if (ta != null)
{
source = ta.bytes;
mainAssetName = Path.GetFileNameWithoutExtension(n);
break;
}
}
}
}
#else
if (mainAssetName != null)
{
TextAsset ta = (TextAsset)desc.Load(mainAssetName, typeof(TextAsset));
if (ta != null)
source = ta.bytes;
}
else
{
source = ((TextAsset)desc.mainAsset).bytes;
mainAssetName = desc.mainAsset.name;
}
#endif
if (source == null)
throw new Exception("FairyGUI: no package found in this bundle.");
if (desc != res)
desc.Unload(true);
ByteBuffer buffer = new ByteBuffer(source);
UIPackage pkg = new UIPackage();
pkg._resBundle = res;
pkg._fromBundle = true;
int pos = mainAssetName.IndexOf("_fui");
string assetNamePrefix;
if (pos != -1)
assetNamePrefix = mainAssetName.Substring(0, pos);
else
assetNamePrefix = mainAssetName;
if (!pkg.LoadPackage(buffer, res.name, assetNamePrefix))
return null;
_packageInstById[pkg.id] = pkg;
_packageInstByName[pkg.name] = pkg;
_packageList.Add(pkg);
return pkg;
}
/// <summary>
/// Add a UI package from a path relative to Unity Resources path.
/// </summary>
/// <param name="descFilePath">Path relative to Unity Resources path.</param>
/// <returns>UIPackage</returns>
public static UIPackage AddPackage(string descFilePath)
{
if (descFilePath.StartsWith("Assets/"))
{
#if UNITY_EDITOR
return AddPackage(descFilePath, (string name, string extension, System.Type type, out DestroyMethod destroyMethod) =>
{
destroyMethod = DestroyMethod.Unload;
return AssetDatabase.LoadAssetAtPath(name + extension, type);
});
#else
Debug.LogWarning("FairyGUI: failed to load package in '" + descFilePath + "'");
return null;
#endif
}
return AddPackage(descFilePath, (string name, string extension, System.Type type, out DestroyMethod destroyMethod) =>
{
destroyMethod = DestroyMethod.Unload;
return Resources.Load(name, type);
});
}
/// <summary>
/// 使用自定义的加载方式载入一个包。
/// </summary>
/// <param name="assetPath">包资源路径。</param>
/// <param name="loadFunc">载入函数</param>
/// <returns></returns>
public static UIPackage AddPackage(string assetPath, LoadResource loadFunc)
{
if (_packageInstById.ContainsKey(assetPath))
return _packageInstById[assetPath];
DestroyMethod dm;
TextAsset asset = (TextAsset)loadFunc(assetPath + "_fui", ".bytes", typeof(TextAsset), out dm);
if (asset == null)
{
if (Application.isPlaying)
throw new Exception("FairyGUI: Cannot load ui package in '" + assetPath + "'");
else
Debug.LogWarning("FairyGUI: Cannot load ui package in '" + assetPath + "'");
}
ByteBuffer buffer = new ByteBuffer(asset.bytes);
UIPackage pkg = new UIPackage();
pkg._loadFunc = loadFunc;
pkg.assetPath = assetPath;
if (!pkg.LoadPackage(buffer, assetPath, assetPath))
return null;
_packageInstById[pkg.id] = pkg;
_packageInstByName[pkg.name] = pkg;
_packageInstById[assetPath] = pkg;
_packageList.Add(pkg);
return pkg;
}
/// <summary>
/// 使用自定义的加载方式载入一个包。
/// </summary>
/// <param name="descData">描述文件数据。</param>
/// <param name="assetNamePrefix">资源文件名前缀。如果包含,则载入资源时名称将传入assetNamePrefix@resFileName这样格式。可以为空。</param>
/// <param name="loadFunc">载入函数</param>
/// <returns></returns>
public static UIPackage AddPackage(byte[] descData, string assetNamePrefix, LoadResource loadFunc)
{
ByteBuffer buffer = new ByteBuffer(descData);
UIPackage pkg = new UIPackage();
pkg._loadFunc = loadFunc;
if (!pkg.LoadPackage(buffer, "raw data", assetNamePrefix))
return null;
_packageInstById[pkg.id] = pkg;
_packageInstByName[pkg.name] = pkg;
_packageList.Add(pkg);
return pkg;
}
/// <summary>
/// Remove a package. All resources in this package will be disposed.
/// </summary>
/// <param name="packageIdOrName"></param>
/// <param name="allowDestroyingAssets"></param>
public static void RemovePackage(string packageIdOrName)
{
UIPackage pkg = null;
if (!_packageInstById.TryGetValue(packageIdOrName, out pkg))
{
if (!_packageInstByName.TryGetValue(packageIdOrName, out pkg))
throw new Exception("FairyGUI: '" + packageIdOrName + "' is not a valid package id or name.");
}
pkg.Dispose();
_packageInstById.Remove(pkg.id);
if (pkg._customId != null)
_packageInstById.Remove(pkg._customId);
if (pkg.assetPath != null)
_packageInstById.Remove(pkg.assetPath);
_packageInstByName.Remove(pkg.name);
_packageList.Remove(pkg);
}
/// <summary>
///
/// </summary>
public static void RemoveAllPackages()
{
if (_packageInstById.Count > 0)
{
UIPackage[] pkgs = _packageList.ToArray();
foreach (UIPackage pkg in pkgs)
{
pkg.Dispose();
}
}
_packageList.Clear();
_packageInstById.Clear();
_packageInstByName.Clear();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static List<UIPackage> GetPackages()
{
return _packageList;
}
/// <summary>
/// Create a UI object.
/// </summary>
/// <param name="pkgName">Package name.</param>
/// <param name="resName">Resource name.</param>
/// <returns>A UI object.</returns>
public static GObject CreateObject(string pkgName, string resName)
{
UIPackage pkg = GetByName(pkgName);
if (pkg != null)
return pkg.CreateObject(resName);
else
return null;
}
/// <summary>
/// Create a UI object.
/// </summary>
/// <param name="pkgName">Package name.</param>
/// <param name="resName">Resource name.</param>
/// <param name="userClass">Custom implementation of this object.</param>
/// <returns>A UI object.</returns>
public static GObject CreateObject(string pkgName, string resName, System.Type userClass)
{
UIPackage pkg = GetByName(pkgName);
if (pkg != null)
return pkg.CreateObject(resName, userClass);
else
return null;
}
/// <summary>
/// Create a UI object.
/// </summary>
/// <param name="url">Resource url.</param>
/// <returns>A UI object.</returns>
public static GObject CreateObjectFromURL(string url)
{
PackageItem pi = GetItemByURL(url);
if (pi != null)
return pi.owner.CreateObject(pi, null);
else
return null;
}
/// <summary>
/// Create a UI object.
/// </summary>
/// <param name="url">Resource url.</param>
/// <param name="userClass">Custom implementation of this object.</param>
/// <returns>A UI object.</returns>
public static GObject CreateObjectFromURL(string url, System.Type userClass)
{
PackageItem pi = GetItemByURL(url);
if (pi != null)
return pi.owner.CreateObject(pi, userClass);
else
return null;
}
public static void CreateObjectAsync(string pkgName, string resName, CreateObjectCallback callback)
{
UIPackage pkg = GetByName(pkgName);
if (pkg != null)
pkg.CreateObjectAsync(resName, callback);
else
Debug.LogError("FairyGUI: package not found - " + pkgName);
}
public static void CreateObjectFromURL(string url, CreateObjectCallback callback)
{
PackageItem pi = GetItemByURL(url);
if (pi != null)
AsyncCreationHelper.CreateObject(pi, callback);
else
Debug.LogError("FairyGUI: resource not found - " + url);
}
/// <summary>
/// Get a asset with a certain name.
/// </summary>
/// <param name="pkgName">Package name.</param>
/// <param name="resName">Resource name.</param>
/// <returns>If resource is atlas, returns NTexture; If resource is sound, returns AudioClip.</returns>
public static object GetItemAsset(string pkgName, string resName)
{
UIPackage pkg = GetByName(pkgName);
if (pkg != null)
return pkg.GetItemAsset(resName);
else
return null;
}
/// <summary>
/// Get a asset with a certain name.
/// </summary>
/// <param name="url">Resource url.</param>
/// <returns>If resource is atlas, returns NTexture; If resource is sound, returns AudioClip.</returns>
public static object GetItemAssetByURL(string url)
{
PackageItem item = GetItemByURL(url);
if (item == null)
return null;
return item.owner.GetItemAsset(item);
}
/// <summary>
/// Get url of an item in package.
/// </summary>
/// <param name="pkgName">Package name.</param>
/// <param name="resName">Resource name.</param>
/// <returns>Url.</returns>
public static string GetItemURL(string pkgName, string resName)
{
UIPackage pkg = GetByName(pkgName);
if (pkg == null)
return null;
PackageItem pi;
if (!pkg._itemsByName.TryGetValue(resName, out pi))
return null;
return URL_PREFIX + pkg.id + pi.id;
}
public static PackageItem GetItemByURL(string url)
{
if (url == null)
return null;
int pos1 = url.IndexOf("//");
if (pos1 == -1)
return null;
int pos2 = url.IndexOf('/', pos1 + 2);
if (pos2 == -1)
{
if (url.Length > 13)
{
string pkgId = url.Substring(5, 8);
UIPackage pkg = GetById(pkgId);
if (pkg != null)
{
string srcId = url.Substring(13);
return pkg.GetItem(srcId);
}
}
}
else
{
string pkgName = url.Substring(pos1 + 2, pos2 - pos1 - 2);
UIPackage pkg = GetByName(pkgName);
if (pkg != null)
{
string srcName = url.Substring(pos2 + 1);
return pkg.GetItemByName(srcName);
}
}
return null;
}
/// <summary>
/// 将'ui://包名/组件名'转换为以内部id表达的url格式。如果传入的url本身就是内部id格式,则直接返回。
/// 同时这个方法还带格式检测,如果传入不正确的url,会返回null。
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string NormalizeURL(string url)
{
if (url == null)
return null;
int pos1 = url.IndexOf("//");
if (pos1 == -1)
return null;
int pos2 = url.IndexOf('/', pos1 + 2);
if (pos2 == -1)
return url;
else
{
string pkgName = url.Substring(pos1 + 2, pos2 - pos1 - 2);
string srcName = url.Substring(pos2 + 1);
return GetItemURL(pkgName, srcName);
}
}
/// <summary>
/// Set strings source.
/// </summary>
/// <param name="source"></param>
public static void SetStringsSource(XML source)
{
TranslationHelper.LoadFromXML(source);
}
/// <summary>
/// Set a custom id for package, then you can use it in GetById.
/// </summary>
public string customId
{
get { return _customId; }
set
{
if (_customId != null)
_packageInstById.Remove(_customId);
_customId = value;
if (_customId != null)
_packageInstById[_customId] = this;
}
}
/// <summary>
///
/// </summary>
public AssetBundle resBundle
{
get { return _resBundle; }
}
bool LoadPackage(ByteBuffer buffer, string packageSource, string assetNamePrefix)
{
if (buffer.ReadUint() != 0x46475549)
{
if (Application.isPlaying)
throw new Exception("FairyGUI: old package format found in '" + packageSource + "'");
else
{
Debug.LogWarning("FairyGUI: old package format found in '" + packageSource + "'");
return false;
}
}
buffer.version = buffer.ReadInt();
buffer.ReadBool(); //compressed
id = buffer.ReadString();
name = buffer.ReadString();
if (_packageInstById.ContainsKey(id) && name != _packageInstById[id].name)
{
Debug.LogWarning("FairyGUI: Package id conflicts, '" + name + "' and '" + _packageInstById[id].name + "'");
return false;
}
buffer.Skip(20);
int indexTablePos = buffer.position;
int cnt;
buffer.Seek(indexTablePos, 4);
cnt = buffer.ReadInt();
string[] stringTable = new string[cnt];
for (int i = 0; i < cnt; i++)
stringTable[i] = buffer.ReadString();
buffer.stringTable = stringTable;
buffer.Seek(indexTablePos, 1);
PackageItem pi;
if (assetNamePrefix == null)
assetNamePrefix = string.Empty;
else if (assetNamePrefix.Length > 0)
assetNamePrefix = assetNamePrefix + "_";
cnt = buffer.ReadShort();
for (int i = 0; i < cnt; i++)
{
int nextPos = buffer.ReadInt();
nextPos += buffer.position;
pi = new PackageItem();
pi.owner = this;
pi.type = (PackageItemType)buffer.ReadByte();
pi.id = buffer.ReadS();
pi.name = buffer.ReadS();
buffer.ReadS(); //path
pi.file = buffer.ReadS();
pi.exported = buffer.ReadBool();
pi.width = buffer.ReadInt();
pi.height = buffer.ReadInt();
switch (pi.type)
{
case PackageItemType.Image:
{
pi.objectType = ObjectType.Image;
int scaleOption = buffer.ReadByte();
if (scaleOption == 1)
{
Rect rect = new Rect();
rect.x = buffer.ReadInt();
rect.y = buffer.ReadInt();
rect.width = buffer.ReadInt();
rect.height = buffer.ReadInt();
pi.scale9Grid = rect;
pi.tileGridIndice = buffer.ReadInt();
}
else if (scaleOption == 2)
pi.scaleByTile = true;
buffer.ReadBool(); //smoothing
break;
}
case PackageItemType.MovieClip:
{
buffer.ReadBool(); //smoothing
pi.objectType = ObjectType.MovieClip;
pi.rawData = buffer.ReadBuffer();
break;
}
case PackageItemType.Font:
{
pi.rawData = buffer.ReadBuffer();
break;
}
case PackageItemType.Component:
{
int extension = buffer.ReadByte();
if (extension > 0)
pi.objectType = (ObjectType)extension;
else
pi.objectType = ObjectType.Component;
pi.rawData = buffer.ReadBuffer();
UIObjectFactory.ResolvePackageItemExtension(pi);
break;
}
case PackageItemType.Atlas:
case PackageItemType.Sound:
case PackageItemType.Misc:
{
pi.file = assetNamePrefix + pi.file;
break;
}
}
_items.Add(pi);
_itemsById[pi.id] = pi;
if (pi.name != null)
_itemsByName[pi.name] = pi;
buffer.position = nextPos;
}
buffer.Seek(indexTablePos, 2);
cnt = buffer.ReadShort();
for (int i = 0; i < cnt; i++)
{
int nextPos = buffer.ReadShort();
nextPos += buffer.position;
string itemId = buffer.ReadS();
pi = _itemsById[buffer.ReadS()];
AtlasSprite sprite = new AtlasSprite();
sprite.atlas = pi;
sprite.rect.x = buffer.ReadInt();
sprite.rect.y = buffer.ReadInt();
sprite.rect.width = buffer.ReadInt();
sprite.rect.height = buffer.ReadInt();
sprite.rotated = buffer.ReadBool();
_sprites[itemId] = sprite;
buffer.position = nextPos;
}
if (buffer.Seek(indexTablePos, 3))
{
cnt = buffer.ReadShort();
for (int i = 0; i < cnt; i++)
{
int nextPos = buffer.ReadInt();
nextPos += buffer.position;
if (_itemsById.TryGetValue(buffer.ReadS(), out pi))
{
if (pi.type == PackageItemType.Image)
{
pi.pixelHitTestData = new PixelHitTestData();
pi.pixelHitTestData.Load(buffer);
}
}
buffer.position = nextPos;
}
}
if (!Application.isPlaying)
_items.Sort(ComparePackageItem);
return true;
}
static int ComparePackageItem(PackageItem p1, PackageItem p2)
{
if (p1.name != null && p2.name != null)
return p1.name.CompareTo(p2.name);
else
return 0;
}
/// <summary>
///
/// </summary>
public void LoadAllAssets()
{
int cnt = _items.Count;
for (int i = 0; i < cnt; i++)
GetItemAsset(_items[i]);
}
/// <summary>
///
/// </summary>
public void UnloadAssets()
{
int cnt = _items.Count;
for (int i = 0; i < cnt; i++)
{
PackageItem pi = _items[i];
if (pi.type == PackageItemType.Atlas)
{
if (pi.texture != null)
pi.texture.Unload();
}
else if (pi.type == PackageItemType.Sound)
{
if (pi.audioClip != null)
pi.audioClip.Unload();
}
}
if (_resBundle != null)
{
_resBundle.Unload(true);
_resBundle = null;
}
}
/// <summary>
///
/// </summary>
public void ReloadAssets()
{
if (_fromBundle)
throw new Exception("FairyGUI: new bundle must be passed to this function");
ReloadAssets(null);
}
/// <summary>
///
/// </summary>
public void ReloadAssets(AssetBundle resBundle)
{
_resBundle = resBundle;
_fromBundle = _resBundle != null;
int cnt = _items.Count;
for (int i = 0; i < cnt; i++)
{
PackageItem pi = _items[i];
if (pi.type == PackageItemType.Atlas)
{
if (pi.texture != null && pi.texture.nativeTexture == null)
LoadAtlas(pi);
}
else if (pi.type == PackageItemType.Sound)
{
if (pi.audioClip != null && pi.audioClip.nativeClip == null)
LoadSound(pi);
}
}
}
void Dispose()
{
int cnt = _items.Count;
for (int i = 0; i < cnt; i++)
{
PackageItem pi = _items[i];
if (pi.type == PackageItemType.Atlas)
{
if (pi.texture != null)
{
pi.texture.Unload();
pi.texture = null;
}
}
else if (pi.type == PackageItemType.Sound)
{
if (pi.audioClip != null)
{
pi.audioClip.Unload();
pi.audioClip = null;
}
}
}
_items.Clear();
if (_resBundle != null)
{
_resBundle.Unload(true);
_resBundle = null;
}
}
/// <summary>
///
/// </summary>
/// <param name="resName"></param>
/// <returns></returns>
public GObject CreateObject(string resName)
{
PackageItem pi;
if (!_itemsByName.TryGetValue(resName, out pi))
{
Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name);
return null;
}
return CreateObject(pi, null);
}
/// <summary>
///
/// </summary>
/// <param name="resName"></param>
/// <param name="userClass"></param>
/// <returns></returns>
public GObject CreateObject(string resName, System.Type userClass)
{
PackageItem pi;
if (!_itemsByName.TryGetValue(resName, out pi))
{
Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name);
return null;
}
return CreateObject(pi, userClass);
}
public void CreateObjectAsync(string resName, CreateObjectCallback callback)
{
PackageItem pi;
if (!_itemsByName.TryGetValue(resName, out pi))
{
Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name);
return;
}
AsyncCreationHelper.CreateObject(pi, callback);
}
GObject CreateObject(PackageItem item, System.Type userClass)
{
Stats.LatestObjectCreation = 0;
Stats.LatestGraphicsCreation = 0;
GetItemAsset(item);
GObject g = null;
if (item.type == PackageItemType.Component)
{
if (userClass != null)
g = (GComponent)Activator.CreateInstance(userClass);
else
g = UIObjectFactory.NewObject(item);
}
else
g = UIObjectFactory.NewObject(item);
if (g == null)
return null;
_constructing++;
g.packageItem = item;
g.ConstructFromResource();
_constructing--;
return g;
}
/// <summary>
///
/// </summary>
/// <param name="resName"></param>
/// <returns></returns>
public object GetItemAsset(string resName)
{
PackageItem pi;
if (!_itemsByName.TryGetValue(resName, out pi))
{
Debug.LogError("FairyGUI: Resource not found - " + resName + " in " + this.name);
return null;
}
return GetItemAsset(pi);
}
public List<PackageItem> GetItems()
{
return _items;
}
public PackageItem GetItem(string itemId)
{
PackageItem pi;
if (_itemsById.TryGetValue(itemId, out pi))
return pi;
else
return null;
}
public PackageItem GetItemByName(string itemName)
{
PackageItem pi;
if (_itemsByName.TryGetValue(itemName, out pi))
return pi;
else
return null;
}
public object GetItemAsset(PackageItem item)
{
switch (item.type)
{
case PackageItemType.Image:
if (item.texture == null)
LoadImage(item);
return item.texture;
case PackageItemType.Atlas:
if (item.texture == null)
LoadAtlas(item);
return item.texture;
case PackageItemType.Sound:
if (item.audioClip == null)
LoadSound(item);
return item.audioClip;
case PackageItemType.Font:
if (item.bitmapFont == null)
LoadFont(item);
return item.bitmapFont;
case PackageItemType.MovieClip:
if (item.frames == null)
LoadMovieClip(item);
return item.frames;
case PackageItemType.Component:
return item.rawData;
case PackageItemType.Misc:
return LoadBinary(item);
default:
return null;
}
}
void LoadAtlas(PackageItem item)
{
string ext = Path.GetExtension(item.file);
string fileName = item.file.Substring(0, item.file.Length - ext.Length);
Texture tex = null;
Texture alphaTex = null;
DestroyMethod dm;
if (_fromBundle)
{
if (_resBundle != null)
{
#if (UNITY_5 || UNITY_5_3_OR_NEWER)
tex = _resBundle.LoadAsset<Texture>(fileName);
#else
tex = (Texture2D)_resBundle.Load(fileName, typeof(Texture2D));
#endif
}
else
Debug.LogWarning("FairyGUI: bundle already unloaded.");
dm = DestroyMethod.None;
}
else
tex = (Texture)_loadFunc(fileName, ext, typeof(Texture), out dm);
if (tex == null)
Debug.LogWarning("FairyGUI: texture '" + item.file + "' not found in " + this.name);
else if (!(tex is Texture2D))
{
Debug.LogWarning("FairyGUI: settings for '" + item.file + "' is wrong! Correct values are: (Texture Type=Default, Texture Shape=2D)");
tex = null;
}
else
{
if (((Texture2D)tex).mipmapCount > 1)
Debug.LogWarning("FairyGUI: settings for '" + item.file + "' is wrong! Correct values are: (Generate Mip Maps=unchecked)");
}
if (tex != null)
{
fileName = fileName + "!a";
if (_fromBundle)
{
if (_resBundle != null)
{
#if (UNITY_5 || UNITY_5_3_OR_NEWER)
alphaTex = _resBundle.LoadAsset<Texture2D>(fileName);
#else
alphaTex = (Texture2D)_resBundle.Load(fileName, typeof(Texture2D));
#endif
}
}
else
alphaTex = (Texture2D)_loadFunc(fileName, ext, typeof(Texture2D), out dm);
}
if (tex == null)
{
tex = NTexture.CreateEmptyTexture();
dm = DestroyMethod.Destroy;
}
if (item.texture == null)
{
item.texture = new NTexture(tex, alphaTex, (float)tex.width / item.width, (float)tex.height / item.height);
item.texture.destroyMethod = dm;
}
else
{
item.texture.Reload(tex, alphaTex);
item.texture.destroyMethod = dm;
}
}
void LoadImage(PackageItem item)
{
AtlasSprite sprite;
if (_sprites.TryGetValue(item.id, out sprite))
item.texture = new NTexture((NTexture)GetItemAsset(sprite.atlas), sprite.rect, sprite.rotated);
else
item.texture = NTexture.Empty;
}
void LoadSound(PackageItem item)
{
string ext = Path.GetExtension(item.file);
string fileName = item.file.Substring(0, item.file.Length - ext.Length);
AudioClip audioClip = null;
DestroyMethod dm;
if (_resBundle != null)
{
#if (UNITY_5 || UNITY_5_3_OR_NEWER)
audioClip = _resBundle.LoadAsset<AudioClip>(fileName);
#else
audioClip = (AudioClip)_resBundle.Load(fileName, typeof(AudioClip));
#endif
dm = DestroyMethod.None;
}
else
{
audioClip = (AudioClip)_loadFunc(fileName, ext, typeof(AudioClip), out dm);
}
if (item.audioClip == null)
item.audioClip = new NAudioClip(audioClip);
else
item.audioClip.Reload(audioClip);
item.audioClip.destroyMethod = dm;
}
byte[] LoadBinary(PackageItem item)
{
string ext = Path.GetExtension(item.file);
string fileName = item.file.Substring(0, item.file.Length - ext.Length);
TextAsset ta;
if (_resBundle != null)
{
#if (UNITY_5 || UNITY_5_3_OR_NEWER)
ta = _resBundle.LoadAsset<TextAsset>(fileName);
#else
ta = (TextAsset)_resBundle.Load(fileName, typeof(TextAsset));
#endif
if (ta != null)
return ta.bytes;
else
return null;
}
else
{
DestroyMethod dm;
object ret = _loadFunc(fileName, ext, typeof(TextAsset), out dm);
if (ret == null)
return null;
if (ret is byte[])
return (byte[])ret;
else
return ((TextAsset)ret).bytes;
}
}
void LoadMovieClip(PackageItem item)
{
ByteBuffer buffer = item.rawData;
buffer.Seek(0, 0);
item.interval = buffer.ReadInt() / 1000f;
item.swing = buffer.ReadBool();
item.repeatDelay = buffer.ReadInt() / 1000f;
buffer.Seek(0, 1);
int frameCount = buffer.ReadShort();
item.frames = new MovieClip.Frame[frameCount];
string spriteId;
MovieClip.Frame frame;
AtlasSprite sprite;
for (int i = 0; i < frameCount; i++)
{
int nextPos = buffer.ReadShort();
nextPos += buffer.position;
frame = new MovieClip.Frame();
frame.rect.x = buffer.ReadInt();
frame.rect.y = buffer.ReadInt();
frame.rect.width = buffer.ReadInt();
frame.rect.height = buffer.ReadInt();
frame.addDelay = buffer.ReadInt() / 1000f;
spriteId = buffer.ReadS();
if (spriteId != null && _sprites.TryGetValue(spriteId, out sprite))
{
if (item.texture == null)
item.texture = (NTexture)GetItemAsset(sprite.atlas);
frame.uvRect = new Rect(sprite.rect.x / item.texture.width * item.texture.uvRect.width,
1 - sprite.rect.yMax * item.texture.uvRect.height / item.texture.height,
sprite.rect.width * item.texture.uvRect.width / item.texture.width,
sprite.rect.height * item.texture.uvRect.height / item.texture.height);
frame.rotated = sprite.rotated;
if (frame.rotated)
{
float tmp = frame.uvRect.width;
frame.uvRect.width = frame.uvRect.height;
frame.uvRect.height = tmp;
}
}
item.frames[i] = frame;
buffer.position = nextPos;
}
}
void LoadFont(PackageItem item)
{
BitmapFont font = new BitmapFont(item);
item.bitmapFont = font;
ByteBuffer buffer = item.rawData;
buffer.Seek(0, 0);
bool ttf = buffer.ReadBool();
font.canTint = buffer.ReadBool();
font.resizable = buffer.ReadBool();
font.hasChannel = buffer.ReadBool();
int fontSize = buffer.ReadInt();
int xadvance = buffer.ReadInt();
int lineHeight = buffer.ReadInt();
float texScaleX = 1;
float texScaleY = 1;
NTexture mainTexture = null;
AtlasSprite mainSprite = null;
if (ttf && _sprites.TryGetValue(item.id, out mainSprite))
{
mainTexture = (NTexture)GetItemAsset(mainSprite.atlas);
texScaleX = mainTexture.root.uvRect.width / mainTexture.width;
texScaleY = mainTexture.root.uvRect.height / mainTexture.height;
}
buffer.Seek(0, 1);
BitmapFont.BMGlyph bg;
int cnt = buffer.ReadInt();
for (int i = 0; i < cnt; i++)
{
int nextPos = buffer.ReadShort();
nextPos += buffer.position;
bg = new BitmapFont.BMGlyph();
char ch = buffer.ReadChar();
font.AddChar(ch, bg);
string img = buffer.ReadS();
int bx = buffer.ReadInt();
int by = buffer.ReadInt();
bg.offsetX = buffer.ReadInt();
bg.offsetY = buffer.ReadInt();
bg.width = buffer.ReadInt();
bg.height = buffer.ReadInt();
bg.advance = buffer.ReadInt();
bg.channel = buffer.ReadByte();
if (bg.channel == 1)
bg.channel = 3;
else if (bg.channel == 2)
bg.channel = 2;
else if (bg.channel == 3)
bg.channel = 1;
if (ttf)
{
if (mainSprite.rotated)
{
bg.uv[0] = new Vector2((float)(by + bg.height + mainSprite.rect.x) * texScaleX,
1 - (float)(mainSprite.rect.yMax - bx) * texScaleY);
bg.uv[1] = new Vector2(bg.uv[0].x - (float)bg.height * texScaleX, bg.uv[0].y);
bg.uv[2] = new Vector2(bg.uv[1].x, bg.uv[0].y + (float)bg.width * texScaleY);
bg.uv[3] = new Vector2(bg.uv[0].x, bg.uv[2].y);
}
else
{
bg.uv[0] = new Vector2((float)(bx + mainSprite.rect.x) * texScaleX,
1 - (float)(by + bg.height + mainSprite.rect.y) * texScaleY);
bg.uv[1] = new Vector2(bg.uv[0].x, bg.uv[0].y + (float)bg.height * texScaleY);
bg.uv[2] = new Vector2(bg.uv[0].x + (float)bg.width * texScaleX, bg.uv[1].y);
bg.uv[3] = new Vector2(bg.uv[2].x, bg.uv[0].y);
}
bg.lineHeight = lineHeight;
}
else
{
PackageItem charImg;
if (_itemsById.TryGetValue(img, out charImg))
{
GetItemAsset(charImg);
Rect uvRect = charImg.texture.uvRect;
bg.uv[0] = uvRect.position;
bg.uv[1] = new Vector2(uvRect.xMin, uvRect.yMax);
bg.uv[2] = new Vector2(uvRect.xMax, uvRect.yMax);
bg.uv[3] = new Vector2(uvRect.xMax, uvRect.yMin);
if (charImg.texture.rotated)
NGraphics.RotateUV(bg.uv, ref uvRect);
bg.width = charImg.texture.width;
bg.height = charImg.texture.height;
if (mainTexture == null)
mainTexture = charImg.texture.root;
}
if (fontSize == 0)
fontSize = bg.height;
if (bg.advance == 0)
{
if (xadvance == 0)
bg.advance = bg.offsetX + bg.width;
else
bg.advance = xadvance;
}
bg.lineHeight = bg.offsetY < 0 ? bg.height : (bg.offsetY + bg.height);
if (bg.lineHeight < font.size)
bg.lineHeight = font.size;
}
buffer.position = nextPos;
}
font.size = fontSize;
font.mainTexture = mainTexture;
if (!font.hasChannel)
font.shader = ShaderConfig.imageShader;
}
}
}
| 34.764045 | 151 | 0.456669 | [
"MIT"
] | czlsy009/UnityAppMVCFramework | Framework/Assets/SilenceFramework/Libs/FairyGUI/Scripts/UI/UIPackage.cs | 46,714 | C# |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Services.Query
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Xml.Linq;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Newtonsoft.Json.Linq;
public class Fetch
{
/// <summary>
/// The maximum number of results a query can retrieve in a single request.
/// </summary>
public const int MaximumPageSize = 5000;
public string Version { get; set; }
public int? PageSize { get; set; }
public int? PageNumber { get; set; }
public string PagingCookie { get; set; }
public int? UtcOffset { get; set; }
public bool? Aggregate { get; set; }
public bool? Distinct { get; set; }
public MappingType MappingType { get; set; }
public bool? MinActiveRowVersion { get; set; }
public OutputFormatType? OutputFormat { get; set; }
public bool? ReturnTotalRecordCount { get; set; }
public bool? NoLock { get; set; }
/// <summary>
/// SkipCache means:
/// 1) we will always execute this Fetch without checking if result is already available in cache and
/// 2) We will not cache the result.
/// </summary>
public bool? SkipCache { get; set; }
public FetchEntity Entity { get; set; }
[IgnoreDataMember]
public ICollection<XAttribute> Extensions { get; set; }
/// <remarks>
/// This is for the Reports view only.
/// </remarks>
public ICollection<Order> Orders { get; set; }
public XElement ToXml()
{
return new XElement("fetch", GetContent());
}
private IEnumerable<XObject> GetContent()
{
yield return new XAttribute("mapping", Lookups.MappingTypeToText[MappingType]);
if (Version != null) yield return new XAttribute("version", Version);
if (PageSize != null) yield return new XAttribute("count", PageSize.Value);
if (PageNumber != null) yield return new XAttribute("page", PageNumber.Value);
if (PagingCookie != null) yield return new XAttribute("paging-cookie", PagingCookie);
if (UtcOffset != null) yield return new XAttribute("utc-offset", UtcOffset.Value);
if (Aggregate != null) yield return new XAttribute("aggregate", Aggregate.Value);
if (Distinct != null) yield return new XAttribute("distinct", Distinct.Value);
if (MinActiveRowVersion != null) yield return new XAttribute("min-active-row-version", MinActiveRowVersion.Value);
if (OutputFormat != null) yield return new XAttribute("output-format", Lookups.OutputFormatTypeToText[OutputFormat.Value]);
if (ReturnTotalRecordCount != null) yield return new XAttribute("returntotalrecordcount", ReturnTotalRecordCount.Value);
if (NoLock != null) yield return new XAttribute("no-lock", NoLock.Value);
if (Orders != null)
{
foreach (var order in Orders) yield return order.ToXml();
}
if (Entity != null) yield return Entity.ToXml();
if (Extensions != null)
{
foreach (var extension in Extensions) yield return extension;
}
}
public static Fetch Parse(string text)
{
return text == null ? null : Parse(XElement.Parse(text));
}
public static Fetch FromJson(string text)
{
return text == null ? null : Parse(JObject.Parse(text));
}
public static Fetch Parse(XElement element)
{
if (element == null) return null;
return new Fetch
{
MappingType = element.GetAttribute("mapping", Lookups.MappingTypeToText).GetValueOrDefault(),
Version = element.GetAttribute("version"),
PageSize = element.GetAttribute<int?>("count"),
PageNumber = element.GetAttribute<int?>("page"),
PagingCookie = element.GetAttribute("paging-cookie"),
UtcOffset = element.GetAttribute<int?>("utc-offset"),
Aggregate = element.GetAttribute<bool?>("aggregate"),
Distinct = element.GetAttribute<bool?>("distinct"),
MinActiveRowVersion = element.GetAttribute<bool?>("min-active-row-version"),
OutputFormat = element.GetAttribute("output-format", Lookups.OutputFormatTypeToText),
ReturnTotalRecordCount = element.GetAttribute<bool?>("returntotalrecordcount"),
NoLock = element.GetAttribute<bool?>("no-lock"),
Orders = Order.Parse(element.Elements("order")),
Entity = FetchEntity.Parse(element.Element("entity")),
Extensions = element.GetExtensions(),
};
}
public static Fetch Parse(JToken element, IEnumerable<XAttribute> xmlns = null)
{
if (element == null) return null;
var namespaces = element.ToNamespaces(xmlns);
return new Fetch
{
MappingType = element.GetAttribute("mapping", Lookups.MappingTypeToText).GetValueOrDefault(),
Version = element.GetAttribute("version"),
PageSize = element.GetAttribute<int?>("count"),
PageNumber = element.GetAttribute<int?>("page"),
PagingCookie = element.GetAttribute("paging-cookie"),
UtcOffset = element.GetAttribute<int?>("utc-offset"),
Aggregate = element.GetAttribute<bool?>("aggregate"),
Distinct = element.GetAttribute<bool?>("distinct"),
MinActiveRowVersion = element.GetAttribute<bool?>("min-active-row-version"),
OutputFormat = element.GetAttribute("output-format", Lookups.OutputFormatTypeToText),
ReturnTotalRecordCount = element.GetAttribute<bool?>("returntotalrecordcount"),
NoLock = element.GetAttribute<bool?>("no-lock"),
Orders = Order.Parse(element.Elements("orders"), namespaces),
Entity = FetchEntity.Parse(element.Element("entity"), namespaces),
Extensions = element.GetExtensions(namespaces),
};
}
public FetchExpression ToFetchExpression()
{
return new FetchExpression(ToXml().ToString());
}
public RetrieveMultipleRequest ToRetrieveMultipleRequest()
{
return new RetrieveMultipleRequest { Query = ToFetchExpression() };
}
internal RetrieveSingleRequest ToRetrieveSingleRequest()
{
return new RetrieveSingleRequest(ToFetchExpression());
}
public EntityCollection Execute(
IOrganizationService service,
RequestFlag flag = RequestFlag.None,
TimeSpan? expiration = null,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
return service.RetrieveMultiple(this, flag, expiration, memberName, sourceFilePath, sourceLineNumber);
}
}
}
| 35.181319 | 126 | 0.714821 | [
"MIT"
] | Adoxio/xRM-Portals-Community-Edition | Framework/Adxstudio.Xrm/Services/Query/Fetch.cs | 6,403 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Management.Network.Models;
namespace Azure.Management.Network
{
/// <summary> The LoadBalancers service client. </summary>
public partial class LoadBalancersClient
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal LoadBalancersRestClient RestClient { get; }
/// <summary> Initializes a new instance of LoadBalancersClient for mocking. </summary>
protected LoadBalancersClient()
{
}
/// <summary> Initializes a new instance of LoadBalancersClient. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="endpoint"> server parameter. </param>
internal LoadBalancersClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
RestClient = new LoadBalancersRestClient(clientDiagnostics, pipeline, subscriptionId, endpoint);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
/// <summary> Gets the specified load balancer. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="expand"> Expands referenced resources. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<LoadBalancer>> GetAsync(string resourceGroupName, string loadBalancerName, string expand = null, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.Get");
scope.Start();
try
{
return await RestClient.GetAsync(resourceGroupName, loadBalancerName, expand, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the specified load balancer. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="expand"> Expands referenced resources. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<LoadBalancer> Get(string resourceGroupName, string loadBalancerName, string expand = null, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.Get");
scope.Start();
try
{
return RestClient.Get(resourceGroupName, loadBalancerName, expand, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Updates a load balancer tags. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="parameters"> Parameters supplied to update load balancer tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<LoadBalancer>> UpdateTagsAsync(string resourceGroupName, string loadBalancerName, TagsObject parameters, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.UpdateTags");
scope.Start();
try
{
return await RestClient.UpdateTagsAsync(resourceGroupName, loadBalancerName, parameters, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Updates a load balancer tags. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="parameters"> Parameters supplied to update load balancer tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<LoadBalancer> UpdateTags(string resourceGroupName, string loadBalancerName, TagsObject parameters, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.UpdateTags");
scope.Start();
try
{
return RestClient.UpdateTags(resourceGroupName, loadBalancerName, parameters, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets all the load balancers in a subscription. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual AsyncPageable<LoadBalancer> ListAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<LoadBalancer>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.ListAll");
scope.Start();
try
{
var response = await RestClient.ListAllAsync(cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<LoadBalancer>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.ListAll");
scope.Start();
try
{
var response = await RestClient.ListAllNextPageAsync(nextLink, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Gets all the load balancers in a subscription. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Pageable<LoadBalancer> ListAll(CancellationToken cancellationToken = default)
{
Page<LoadBalancer> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.ListAll");
scope.Start();
try
{
var response = RestClient.ListAll(cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<LoadBalancer> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.ListAll");
scope.Start();
try
{
var response = RestClient.ListAllNextPage(nextLink, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Gets all the load balancers in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual AsyncPageable<LoadBalancer> ListAsync(string resourceGroupName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
async Task<Page<LoadBalancer>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.List");
scope.Start();
try
{
var response = await RestClient.ListAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<LoadBalancer>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.List");
scope.Start();
try
{
var response = await RestClient.ListNextPageAsync(nextLink, resourceGroupName, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Gets all the load balancers in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Pageable<LoadBalancer> List(string resourceGroupName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
Page<LoadBalancer> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.List");
scope.Start();
try
{
var response = RestClient.List(resourceGroupName, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<LoadBalancer> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.List");
scope.Start();
try
{
var response = RestClient.ListNextPage(nextLink, resourceGroupName, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Deletes the specified load balancer. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<LoadBalancersDeleteOperation> StartDeleteAsync(string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.StartDelete");
scope.Start();
try
{
var originalResponse = await RestClient.DeleteAsync(resourceGroupName, loadBalancerName, cancellationToken).ConfigureAwait(false);
return new LoadBalancersDeleteOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(resourceGroupName, loadBalancerName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes the specified load balancer. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual LoadBalancersDeleteOperation StartDelete(string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.StartDelete");
scope.Start();
try
{
var originalResponse = RestClient.Delete(resourceGroupName, loadBalancerName, cancellationToken);
return new LoadBalancersDeleteOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(resourceGroupName, loadBalancerName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates or updates a load balancer. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="parameters"> Parameters supplied to the create or update load balancer operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<LoadBalancersCreateOrUpdateOperation> StartCreateOrUpdateAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.StartCreateOrUpdate");
scope.Start();
try
{
var originalResponse = await RestClient.CreateOrUpdateAsync(resourceGroupName, loadBalancerName, parameters, cancellationToken).ConfigureAwait(false);
return new LoadBalancersCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, loadBalancerName, parameters).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates or updates a load balancer. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="parameters"> Parameters supplied to the create or update load balancer operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual LoadBalancersCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _clientDiagnostics.CreateScope("LoadBalancersClient.StartCreateOrUpdate");
scope.Start();
try
{
var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, loadBalancerName, parameters, cancellationToken);
return new LoadBalancersCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, loadBalancerName, parameters).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 47.461916 | 219 | 0.598799 | [
"MIT"
] | LeighS/azure-sdk-for-net | sdk/network/Azure.Management.Network/src/Generated/LoadBalancersClient.cs | 19,317 | C# |
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.
[assembly: AssemblyTitle("030.Catch the Bits")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("030.Catch the Bits")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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("d0c9267e-ee27-4811-853c-14e912c8ec22")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.74308 | [
"MIT"
] | vanncho/SoftUni-Entrance-Exam-Prepare | 030.Catch the Bits/Properties/AssemblyInfo.cs | 1,412 | C# |
using System;
using Xamarin.Forms;
namespace Ooui.Forms
{
public class PlatformRenderer : Ooui.Html.Div, IDisposable
{
readonly Platform platform;
public Platform Platform => platform;
public override bool WantsFullScreen => true;
public PlatformRenderer (Platform platform)
{
this.platform = platform;
}
protected override bool TriggerEventFromMessage (Message message)
{
if (disposedValue)
return false;
if (message.TargetId == "window" && message.Key == "resize" && message.Value is Newtonsoft.Json.Linq.JObject j) {
var width = (double)j["width"];
var height = (double)j["height"];
Platform.Element.Style.Width = width;
Platform.Element.Style.Height = height;
return true;
}
else {
return base.TriggerEventFromMessage (message);
}
}
#region IDisposable Support
private bool disposedValue = false;
protected virtual void Dispose (bool disposing)
{
if (!disposedValue) {
if (disposing) {
// Disconnect any events we started
// Inform the page it's leaving
if (Platform.Page is IPageController pc) {
pc.SendDisappearing ();
}
}
disposedValue = true;
}
}
public void Dispose ()
{
Dispose (true);
}
#endregion
}
}
| 27.271186 | 125 | 0.522063 | [
"MIT"
] | KevinGliewe/Ooui | Ooui.Forms/PlatformRenderer.cs | 1,611 | C# |
using System;
using System.Collections.Generic;
namespace LiteDB_V6
{
internal class HeaderPage : BasePage
{
private const string HEADER_INFO = "** This is a LiteDB file **";
private const byte FILE_VERSION = 6;
public override PageType PageType { get { return PageType.Header; } }
public ushort ChangeID { get; set; }
public uint FreeEmptyPageID;
public uint LastPageID { get; set; }
public ushort DbVersion = 0;
public byte[] Password = new byte[20];
public Dictionary<string, uint> CollectionPages { get; set; }
public HeaderPage()
: base(0)
{
this.FreeEmptyPageID = uint.MaxValue;
this.ChangeID = 0;
this.LastPageID = 0;
this.ItemCount = 1; // fixed for header
this.DbVersion = 0;
this.Password = new byte[20];
this.CollectionPages = new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase);
}
protected override void ReadContent(ref LiteDB.ByteReader reader)
{
var info = reader.ReadString(HEADER_INFO.Length);
var ver = reader.ReadByte();
this.ChangeID = reader.ReadUInt16();
this.FreeEmptyPageID = reader.ReadUInt32();
this.LastPageID = reader.ReadUInt32();
this.DbVersion = reader.ReadUInt16();
this.Password = reader.ReadBytes(this.Password.Length);
// read page collections references (position on end of page)
var cols = reader.ReadByte();
for (var i = 0; i < cols; i++)
{
this.CollectionPages.Add(reader.ReadString(), reader.ReadUInt32());
}
}
}
} | 35.18 | 98 | 0.583854 | [
"MIT"
] | hex11/LiteDB | LiteDB/Upgrade/V6/Pages/HeaderPage.cs | 1,759 | 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.
// DO NOT EDIT THIS FILE! It IS AUTOGENERATED
using System;
using System.Runtime.InteropServices;
namespace Internal.JitInterface
{
unsafe partial class CorInfoImpl
{
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getMethodAttribs(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __setMethodAttribs(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CorInfoMethodRuntimeFlags attribs);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getMethodSig(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_SIG_INFO* sig, CORINFO_CLASS_STRUCT_* memberParent);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __getMethodInfo(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_METHOD_INFO* info);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoInline __canInline(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, ref uint pRestrictions);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __reportInliningDecision(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd, CorInfoInline inlineResult, byte* reason);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __canTailCall(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* declaredCalleeHnd, CORINFO_METHOD_STRUCT_* exactCalleeHnd, [MarshalAs(UnmanagedType.I1)]bool fIsTailPrefix);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __reportTailCallDecision(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, [MarshalAs(UnmanagedType.I1)]bool fIsTailPrefix, CorInfoTailCall tailCallResult, byte* reason);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getEHinfo(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint EHnumber, ref CORINFO_EH_CLAUSE clause);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getMethodClass(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_MODULE_STRUCT_* __getMethodModule(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getMethodVTableOffset(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, ref uint offsetOfIndirection, ref uint offsetAfterIndirection, [MarshalAs(UnmanagedType.U1)] ref bool isRelative);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_METHOD_STRUCT_* __resolveVirtualMethod(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* virtualMethod, CORINFO_CLASS_STRUCT_* implementingClass, CORINFO_CONTEXT_STRUCT* ownerType);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_METHOD_STRUCT_* __getUnboxedEntry(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte* requiresInstMethodTableArg);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getDefaultEqualityComparerClass(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* elemType);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __expandRawHandleIntrinsic(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, ref CORINFO_GENERICHANDLE_RESULT pResult);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoIntrinsics __getIntrinsicID(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, byte* pMustExpand);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __isIntrinsicType(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* classHnd);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoUnmanagedCallConv __getUnmanagedCallConv(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __pInvokeMarshalingRequired(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_SIG_INFO* callSiteSig);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __satisfiesMethodConstraints(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* parent, CORINFO_METHOD_STRUCT_* method);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __isCompatibleDelegate(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* objCls, CORINFO_CLASS_STRUCT_* methodParentCls, CORINFO_METHOD_STRUCT_* method, CORINFO_CLASS_STRUCT_* delegateCls, [MarshalAs(UnmanagedType.Bool)] ref bool pfIsOpenDelegate);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __methodMustBeLoadedBeforeCodeIsRun(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_METHOD_STRUCT_* __mapMethodDeclToMethodImpl(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getGSCookie(IntPtr _this, IntPtr* ppException, IntPtr* pCookieVal, IntPtr** ppCookieVal);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __setPatchpointInfo(IntPtr _this, IntPtr* ppException, PatchpointInfo* patchpointInfo);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate PatchpointInfo* __getOSRInfo(IntPtr _this, IntPtr* ppException, ref uint ilOffset);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __resolveToken(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __tryResolveToken(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __findSig(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint sigTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __findCallSiteSig(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint methTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getTokenTypeAsHandle(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __isValidToken(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __isValidStringRef(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate char* __getStringLiteral(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK, ref int length);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoType __asCorInfoType(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __getClassName(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __getClassNameFromMetadata(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte** namespaceName);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getTypeInstantiationArgument(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, uint index);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate int __appendClassName(IntPtr _this, IntPtr* ppException, char** ppBuf, ref int pnBufLen, CORINFO_CLASS_STRUCT_* cls, [MarshalAs(UnmanagedType.Bool)]bool fNamespace, [MarshalAs(UnmanagedType.Bool)]bool fFullInst, [MarshalAs(UnmanagedType.Bool)]bool fAssembly);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __isValueClass(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoInlineTypeCheck __canInlineTypeCheck(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, CorInfoInlineTypeCheckSource source);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getClassAttribs(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __isStructRequiringStackAllocRetBuf(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_MODULE_STRUCT_* __getClassModule(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_ASSEMBLY_STRUCT_* __getModuleAssembly(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* mod);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __getAssemblyName(IntPtr _this, IntPtr* ppException, CORINFO_ASSEMBLY_STRUCT_* assem);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __LongLifetimeMalloc(IntPtr _this, IntPtr* ppException, UIntPtr sz);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __LongLifetimeFree(IntPtr _this, IntPtr* ppException, void* obj);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __getClassModuleIdForStatics(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, CORINFO_MODULE_STRUCT_** pModule, void** ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getClassSize(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getHeapClassSize(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __canAllocateOnStack(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getClassAlignmentRequirement(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, [MarshalAs(UnmanagedType.Bool)]bool fDoubleAlignHint);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getClassGClayout(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte* gcPtrs);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getClassNumInstanceFields(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_FIELD_STRUCT_* __getFieldInClass(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd, int num);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __checkMethodModifier(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hMethod, byte* modifier, [MarshalAs(UnmanagedType.Bool)]bool fOptional);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoHelpFunc __getNewHelper(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, byte* pHasSideEffects);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoHelpFunc __getNewArrHelper(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* arrayCls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoHelpFunc __getCastingHelper(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, [MarshalAs(UnmanagedType.I1)]bool fThrowing);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoHelpFunc __getSharedCCtorHelper(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getTypeForBox(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoHelpFunc __getBoxHelper(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoHelpFunc __getUnBoxHelper(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __getReadyToRunHelper(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, ref CORINFO_LOOKUP_KIND pGenericLookupKind, CorInfoHelpFunc id, ref CORINFO_CONST_LOOKUP pLookup);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getReadyToRunDelegateCtorHelper(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pTargetMethod, CORINFO_CLASS_STRUCT_* delegateType, ref CORINFO_LOOKUP pLookup);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __getHelperName(IntPtr _this, IntPtr* ppException, CorInfoHelpFunc helpFunc);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoInitClassResult __initClass(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, CORINFO_METHOD_STRUCT_* method, CORINFO_CONTEXT_STRUCT* context);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __classMustBeLoadedBeforeCodeIsRun(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getBuiltinClass(IntPtr _this, IntPtr* ppException, CorInfoClassId classId);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoType __getTypeForPrimitiveValueClass(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoType __getTypeForPrimitiveNumericClass(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __canCast(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* child, CORINFO_CLASS_STRUCT_* parent);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __areTypesEquivalent(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate TypeCompareState __compareTypesForCast(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* fromClass, CORINFO_CLASS_STRUCT_* toClass);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate TypeCompareState __compareTypesForEquality(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __mergeClasses(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __isMoreSpecificType(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getParentType(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoType __getChildType(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_CLASS_STRUCT_** clsRet);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __satisfiesClassConstraints(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __isSDArray(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getArrayRank(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __getArrayInitializationData(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, uint size);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoIsAccessAllowedResult __canAccessClass(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, ref CORINFO_HELPER_DESC pAccessHelper);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __getFieldName(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* ftn, byte** moduleName);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getFieldClass(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoType __getFieldType(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, CORINFO_CLASS_STRUCT_** structType, CORINFO_CLASS_STRUCT_* memberParent);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getFieldOffset(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getFieldInfo(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_ACCESS_FLAGS flags, CORINFO_FIELD_INFO* pResult);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __isFieldStatic(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* fldHnd);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getBoundaries(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref uint cILOffsets, ref uint* pILOffsets, BoundaryTypes* implictBoundaries);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __setBoundaries(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint cMap, OffsetMapping* pMap);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getVars(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref uint cVars, ILVarInfo** vars, [MarshalAs(UnmanagedType.U1)] ref bool extendOthers);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __setVars(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint cVars, NativeVarInfo* vars);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __allocateArray(IntPtr _this, IntPtr* ppException, UIntPtr cBytes);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __freeArray(IntPtr _this, IntPtr* ppException, void* array);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_ARG_LIST_STRUCT_* __getArgNext(IntPtr _this, IntPtr* ppException, CORINFO_ARG_LIST_STRUCT_* args);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoTypeWithMod __getArgType(IntPtr _this, IntPtr* ppException, CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args, CORINFO_CLASS_STRUCT_** vcTypeRet);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getArgClass(IntPtr _this, IntPtr* ppException, CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoHFAElemType __getHFAType(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* hClass);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate HRESULT __GetErrorHRESULT(IntPtr _this, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __GetErrorMessage(IntPtr _this, IntPtr* ppException, char* buffer, uint bufferLength);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate int __FilterException(IntPtr _this, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __HandleException(IntPtr _this, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __ThrowExceptionForJitResult(IntPtr _this, IntPtr* ppException, HRESULT result);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __ThrowExceptionForHelper(IntPtr _this, IntPtr* ppException, ref CORINFO_HELPER_DESC throwHelper);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __runWithErrorTrap(IntPtr _this, IntPtr* ppException, void* function, void* parameter);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getEEInfo(IntPtr _this, IntPtr* ppException, ref CORINFO_EE_INFO pEEInfoOut);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate char* __getJitTimeLogFilename(IntPtr _this, IntPtr* ppException);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate mdToken __getMethodDefFromMethod(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hMethod);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __getMethodName(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte** moduleName);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __getMethodNameFromMetadata(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte** className, byte** namespaceName, byte** enclosingClassName);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getMethodHash(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate byte* __findNameOfToken(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleHandle, mdToken token, byte* szFQName, UIntPtr FQNameCapacity);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __getSystemVAmd64PassStructInRegisterDescriptor(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* structHnd, SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getThreadTLSIndex(IntPtr _this, IntPtr* ppException, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __getInlinedCallFrameVptr(IntPtr _this, IntPtr* ppException, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate int* __getAddrOfCaptureThreadGlobal(IntPtr _this, IntPtr* ppException, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __getHelperFtn(IntPtr _this, IntPtr* ppException, CorInfoHelpFunc ftnNum, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getFunctionEntryPoint(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref CORINFO_CONST_LOOKUP pResult, CORINFO_ACCESS_FLAGS accessFlags);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getFunctionFixedEntryPoint(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref CORINFO_CONST_LOOKUP pResult);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __getMethodSync(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CorInfoHelpFunc __getLazyStringLiteralHelper(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* handle);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_MODULE_STRUCT_* __embedModuleHandle(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* handle, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __embedClassHandle(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* handle, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_METHOD_STRUCT_* __embedMethodHandle(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* handle, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_FIELD_STRUCT_* __embedFieldHandle(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* handle, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __embedGenericHandle(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, [MarshalAs(UnmanagedType.Bool)]bool fEmbedParent, ref CORINFO_GENERICHANDLE_RESULT pResult);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getLocationOfThisType(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* context, ref CORINFO_LOOKUP_KIND pLookupKind);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getAddressOfPInvokeTarget(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, ref CORINFO_CONST_LOOKUP pLookup);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __GetCookieForPInvokeCalliSig(IntPtr _this, IntPtr* ppException, CORINFO_SIG_INFO* szMetaSig, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __canGetCookieForPInvokeCalliSig(IntPtr _this, IntPtr* ppException, CORINFO_SIG_INFO* szMetaSig);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_JUST_MY_CODE_HANDLE_* __getJustMyCodeHandle(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, ref CORINFO_JUST_MY_CODE_HANDLE_* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __GetProfilingHandle(IntPtr _this, IntPtr* ppException, [MarshalAs(UnmanagedType.Bool)] ref bool pbHookFunction, ref void* pProfilerHandle, [MarshalAs(UnmanagedType.Bool)] ref bool pbIndirectedHandles);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __getCallInfo(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_CALLINFO_FLAGS flags, CORINFO_CALL_INFO* pResult);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __canAccessFamily(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hCaller, CORINFO_CLASS_STRUCT_* hInstanceType);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __isRIDClassDomainID(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getClassDomainID(IntPtr _this, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __getFieldAddress(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, void** ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_CLASS_STRUCT_* __getStaticFieldCurrentClass(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, byte* pIsSpeculative);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate IntPtr __getVarArgsHandle(IntPtr _this, IntPtr* ppException, CORINFO_SIG_INFO* pSig, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __canGetVarArgsHandle(IntPtr _this, IntPtr* ppException, CORINFO_SIG_INFO* pSig);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate InfoAccessType __constructStringLiteral(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, mdToken metaTok, ref void* ppValue);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate InfoAccessType __emptyStringLiteral(IntPtr _this, IntPtr* ppException, ref void* ppValue);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getFieldThreadLocalStoreID(IntPtr _this, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, ref void* ppIndirection);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __setOverride(IntPtr _this, IntPtr* ppException, IntPtr pOverride, CORINFO_METHOD_STRUCT_* currentMethod);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __addActiveDependency(IntPtr _this, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MODULE_STRUCT_* moduleTo);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate CORINFO_METHOD_STRUCT_* __GetDelegateCtor(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* methHnd, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_METHOD_STRUCT_* targetMethodHnd, ref DelegateCtorArgs pCtorData);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __MethodCompileComplete(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* methHnd);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __getTailCallHelpers(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN callToken, CORINFO_SIG_INFO* sig, CORINFO_GET_TAILCALL_HELPERS_FLAGS flags, ref CORINFO_TAILCALL_HELPERS pResult);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.I1)]delegate bool __convertPInvokeCalliToCall(IntPtr _this, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, [MarshalAs(UnmanagedType.I1)]bool mustConvert);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __notifyInstructionSetUsage(IntPtr _this, IntPtr* ppException, InstructionSet instructionSet, [MarshalAs(UnmanagedType.I1)]bool supportEnabled);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __allocMem(IntPtr _this, IntPtr* ppException, uint hotCodeSize, uint coldCodeSize, uint roDataSize, uint xcptnsCount, CorJitAllocMemFlag flag, ref void* hotCodeBlock, ref void* coldCodeBlock, ref void* roDataBlock);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __reserveUnwindInfo(IntPtr _this, IntPtr* ppException, [MarshalAs(UnmanagedType.Bool)]bool isFunclet, [MarshalAs(UnmanagedType.Bool)]bool isColdCode, uint unwindSize);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __allocUnwindInfo(IntPtr _this, IntPtr* ppException, byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void* __allocGCInfo(IntPtr _this, IntPtr* ppException, UIntPtr size);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __setEHcount(IntPtr _this, IntPtr* ppException, uint cEH);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __setEHinfo(IntPtr _this, IntPtr* ppException, uint EHnumber, ref CORINFO_EH_CLAUSE clause);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
[return: MarshalAs(UnmanagedType.Bool)]delegate bool __logMsg(IntPtr _this, IntPtr* ppException, uint level, byte* fmt, IntPtr args);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate int __doAssert(IntPtr _this, IntPtr* ppException, byte* szFile, int iLine, byte* szExpr);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __reportFatalError(IntPtr _this, IntPtr* ppException, CorJitResult result);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate HRESULT __allocMethodBlockCounts(IntPtr _this, IntPtr* ppException, uint count, ref BlockCounts* pBlockCounts);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate HRESULT __getMethodBlockCounts(IntPtr _this, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftnHnd, ref uint pCount, ref BlockCounts* pBlockCounts, ref uint pNumRuns);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __recordCallSite(IntPtr _this, IntPtr* ppException, uint instrOffset, CORINFO_SIG_INFO* callSig, CORINFO_METHOD_STRUCT_* methodHandle);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate void __recordRelocation(IntPtr _this, IntPtr* ppException, void* location, void* target, ushort fRelocType, ushort slotNum, int addlDelta);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate ushort __getRelocTypeHint(IntPtr _this, IntPtr* ppException, void* target);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getExpectedTargetArchitecture(IntPtr _this, IntPtr* ppException);
[UnmanagedFunctionPointerAttribute(default(CallingConvention))]
delegate uint __getJitFlags(IntPtr _this, IntPtr* ppException, ref CORJIT_FLAGS flags, uint sizeInBytes);
static uint _getMethodAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodAttribs(ftn);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static void _setMethodAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CorInfoMethodRuntimeFlags attribs)
{
var _this = GetThis(thisHandle);
try
{
_this.setMethodAttribs(ftn, attribs);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _getMethodSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_SIG_INFO* sig, CORINFO_CLASS_STRUCT_* memberParent)
{
var _this = GetThis(thisHandle);
try
{
_this.getMethodSig(ftn, sig, memberParent);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _getMethodInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_METHOD_INFO* info)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodInfo(ftn, info);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static CorInfoInline _canInline(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, ref uint pRestrictions)
{
var _this = GetThis(thisHandle);
try
{
return _this.canInline(callerHnd, calleeHnd, ref pRestrictions);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoInline);
}
}
static void _reportInliningDecision(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd, CorInfoInline inlineResult, byte* reason)
{
var _this = GetThis(thisHandle);
try
{
_this.reportInliningDecision(inlinerHnd, inlineeHnd, inlineResult, reason);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _canTailCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* declaredCalleeHnd, CORINFO_METHOD_STRUCT_* exactCalleeHnd, [MarshalAs(UnmanagedType.I1)]bool fIsTailPrefix)
{
var _this = GetThis(thisHandle);
try
{
return _this.canTailCall(callerHnd, declaredCalleeHnd, exactCalleeHnd, fIsTailPrefix);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static void _reportTailCallDecision(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, [MarshalAs(UnmanagedType.I1)]bool fIsTailPrefix, CorInfoTailCall tailCallResult, byte* reason)
{
var _this = GetThis(thisHandle);
try
{
_this.reportTailCallDecision(callerHnd, calleeHnd, fIsTailPrefix, tailCallResult, reason);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _getEHinfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint EHnumber, ref CORINFO_EH_CLAUSE clause)
{
var _this = GetThis(thisHandle);
try
{
_this.getEHinfo(ftn, EHnumber, ref clause);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static CORINFO_CLASS_STRUCT_* _getMethodClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodClass(method);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static CORINFO_MODULE_STRUCT_* _getMethodModule(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodModule(method);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_MODULE_STRUCT_*);
}
}
static void _getMethodVTableOffset(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, ref uint offsetOfIndirection, ref uint offsetAfterIndirection, [MarshalAs(UnmanagedType.U1)] ref bool isRelative)
{
var _this = GetThis(thisHandle);
try
{
_this.getMethodVTableOffset(method, ref offsetOfIndirection, ref offsetAfterIndirection, ref isRelative);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static CORINFO_METHOD_STRUCT_* _resolveVirtualMethod(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* virtualMethod, CORINFO_CLASS_STRUCT_* implementingClass, CORINFO_CONTEXT_STRUCT* ownerType)
{
var _this = GetThis(thisHandle);
try
{
return _this.resolveVirtualMethod(virtualMethod, implementingClass, ownerType);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_METHOD_STRUCT_*);
}
}
static CORINFO_METHOD_STRUCT_* _getUnboxedEntry(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte* requiresInstMethodTableArg)
{
var _this = GetThis(thisHandle);
try
{
return _this.getUnboxedEntry(ftn, requiresInstMethodTableArg);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_METHOD_STRUCT_*);
}
}
static CORINFO_CLASS_STRUCT_* _getDefaultEqualityComparerClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* elemType)
{
var _this = GetThis(thisHandle);
try
{
return _this.getDefaultEqualityComparerClass(elemType);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static void _expandRawHandleIntrinsic(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, ref CORINFO_GENERICHANDLE_RESULT pResult)
{
var _this = GetThis(thisHandle);
try
{
_this.expandRawHandleIntrinsic(ref pResolvedToken, ref pResult);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static CorInfoIntrinsics _getIntrinsicID(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, byte* pMustExpand)
{
var _this = GetThis(thisHandle);
try
{
return _this.getIntrinsicID(method, pMustExpand);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoIntrinsics);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _isIntrinsicType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* classHnd)
{
var _this = GetThis(thisHandle);
try
{
return _this.isIntrinsicType(classHnd);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static CorInfoUnmanagedCallConv _getUnmanagedCallConv(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method)
{
var _this = GetThis(thisHandle);
try
{
return _this.getUnmanagedCallConv(method);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoUnmanagedCallConv);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _pInvokeMarshalingRequired(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_SIG_INFO* callSiteSig)
{
var _this = GetThis(thisHandle);
try
{
return _this.pInvokeMarshalingRequired(method, callSiteSig);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _satisfiesMethodConstraints(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* parent, CORINFO_METHOD_STRUCT_* method)
{
var _this = GetThis(thisHandle);
try
{
return _this.satisfiesMethodConstraints(parent, method);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _isCompatibleDelegate(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* objCls, CORINFO_CLASS_STRUCT_* methodParentCls, CORINFO_METHOD_STRUCT_* method, CORINFO_CLASS_STRUCT_* delegateCls, [MarshalAs(UnmanagedType.Bool)] ref bool pfIsOpenDelegate)
{
var _this = GetThis(thisHandle);
try
{
return _this.isCompatibleDelegate(objCls, methodParentCls, method, delegateCls, ref pfIsOpenDelegate);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static void _methodMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method)
{
var _this = GetThis(thisHandle);
try
{
_this.methodMustBeLoadedBeforeCodeIsRun(method);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static CORINFO_METHOD_STRUCT_* _mapMethodDeclToMethodImpl(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method)
{
var _this = GetThis(thisHandle);
try
{
return _this.mapMethodDeclToMethodImpl(method);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_METHOD_STRUCT_*);
}
}
static void _getGSCookie(IntPtr thisHandle, IntPtr* ppException, IntPtr* pCookieVal, IntPtr** ppCookieVal)
{
var _this = GetThis(thisHandle);
try
{
_this.getGSCookie(pCookieVal, ppCookieVal);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _setPatchpointInfo(IntPtr thisHandle, IntPtr* ppException, PatchpointInfo* patchpointInfo)
{
var _this = GetThis(thisHandle);
try
{
_this.setPatchpointInfo(patchpointInfo);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static PatchpointInfo* _getOSRInfo(IntPtr thisHandle, IntPtr* ppException, ref uint ilOffset)
{
var _this = GetThis(thisHandle);
try
{
return _this.getOSRInfo(ref ilOffset);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(PatchpointInfo*);
}
}
static void _resolveToken(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken)
{
var _this = GetThis(thisHandle);
try
{
_this.resolveToken(ref pResolvedToken);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _tryResolveToken(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken)
{
var _this = GetThis(thisHandle);
try
{
_this.tryResolveToken(ref pResolvedToken);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _findSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint sigTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig)
{
var _this = GetThis(thisHandle);
try
{
_this.findSig(module, sigTOK, context, sig);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _findCallSiteSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint methTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig)
{
var _this = GetThis(thisHandle);
try
{
_this.findCallSiteSig(module, methTOK, context, sig);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static CORINFO_CLASS_STRUCT_* _getTokenTypeAsHandle(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken)
{
var _this = GetThis(thisHandle);
try
{
return _this.getTokenTypeAsHandle(ref pResolvedToken);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _isValidToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK)
{
var _this = GetThis(thisHandle);
try
{
return _this.isValidToken(module, metaTOK);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _isValidStringRef(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK)
{
var _this = GetThis(thisHandle);
try
{
return _this.isValidStringRef(module, metaTOK);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static char* _getStringLiteral(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK, ref int length)
{
var _this = GetThis(thisHandle);
try
{
return _this.getStringLiteral(module, metaTOK, ref length);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(char*);
}
}
static CorInfoType _asCorInfoType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.asCorInfoType(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoType);
}
}
static byte* _getClassName(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassName(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
static byte* _getClassNameFromMetadata(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte** namespaceName)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassNameFromMetadata(cls, namespaceName);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
static CORINFO_CLASS_STRUCT_* _getTypeInstantiationArgument(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, uint index)
{
var _this = GetThis(thisHandle);
try
{
return _this.getTypeInstantiationArgument(cls, index);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static int _appendClassName(IntPtr thisHandle, IntPtr* ppException, char** ppBuf, ref int pnBufLen, CORINFO_CLASS_STRUCT_* cls, [MarshalAs(UnmanagedType.Bool)]bool fNamespace, [MarshalAs(UnmanagedType.Bool)]bool fFullInst, [MarshalAs(UnmanagedType.Bool)]bool fAssembly)
{
var _this = GetThis(thisHandle);
try
{
return _this.appendClassName(ppBuf, ref pnBufLen, cls, fNamespace, fFullInst, fAssembly);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(int);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _isValueClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.isValueClass(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static CorInfoInlineTypeCheck _canInlineTypeCheck(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, CorInfoInlineTypeCheckSource source)
{
var _this = GetThis(thisHandle);
try
{
return _this.canInlineTypeCheck(cls, source);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoInlineTypeCheck);
}
}
static uint _getClassAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassAttribs(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _isStructRequiringStackAllocRetBuf(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.isStructRequiringStackAllocRetBuf(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static CORINFO_MODULE_STRUCT_* _getClassModule(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassModule(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_MODULE_STRUCT_*);
}
}
static CORINFO_ASSEMBLY_STRUCT_* _getModuleAssembly(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* mod)
{
var _this = GetThis(thisHandle);
try
{
return _this.getModuleAssembly(mod);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_ASSEMBLY_STRUCT_*);
}
}
static byte* _getAssemblyName(IntPtr thisHandle, IntPtr* ppException, CORINFO_ASSEMBLY_STRUCT_* assem)
{
var _this = GetThis(thisHandle);
try
{
return _this.getAssemblyName(assem);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
static void* _LongLifetimeMalloc(IntPtr thisHandle, IntPtr* ppException, UIntPtr sz)
{
var _this = GetThis(thisHandle);
try
{
return _this.LongLifetimeMalloc(sz);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
static void _LongLifetimeFree(IntPtr thisHandle, IntPtr* ppException, void* obj)
{
var _this = GetThis(thisHandle);
try
{
_this.LongLifetimeFree(obj);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static byte* _getClassModuleIdForStatics(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, CORINFO_MODULE_STRUCT_** pModule, void** ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassModuleIdForStatics(cls, pModule, ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
static uint _getClassSize(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassSize(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static uint _getHeapClassSize(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getHeapClassSize(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _canAllocateOnStack(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.canAllocateOnStack(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static uint _getClassAlignmentRequirement(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, [MarshalAs(UnmanagedType.Bool)]bool fDoubleAlignHint)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassAlignmentRequirement(cls, fDoubleAlignHint);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static uint _getClassGClayout(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte* gcPtrs)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassGClayout(cls, gcPtrs);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static uint _getClassNumInstanceFields(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassNumInstanceFields(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static CORINFO_FIELD_STRUCT_* _getFieldInClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd, int num)
{
var _this = GetThis(thisHandle);
try
{
return _this.getFieldInClass(clsHnd, num);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_FIELD_STRUCT_*);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _checkMethodModifier(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hMethod, byte* modifier, [MarshalAs(UnmanagedType.Bool)]bool fOptional)
{
var _this = GetThis(thisHandle);
try
{
return _this.checkMethodModifier(hMethod, modifier, fOptional);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static CorInfoHelpFunc _getNewHelper(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, byte* pHasSideEffects)
{
var _this = GetThis(thisHandle);
try
{
return _this.getNewHelper(ref pResolvedToken, callerHandle, pHasSideEffects);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoHelpFunc);
}
}
static CorInfoHelpFunc _getNewArrHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* arrayCls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getNewArrHelper(arrayCls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoHelpFunc);
}
}
static CorInfoHelpFunc _getCastingHelper(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, [MarshalAs(UnmanagedType.I1)]bool fThrowing)
{
var _this = GetThis(thisHandle);
try
{
return _this.getCastingHelper(ref pResolvedToken, fThrowing);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoHelpFunc);
}
}
static CorInfoHelpFunc _getSharedCCtorHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd)
{
var _this = GetThis(thisHandle);
try
{
return _this.getSharedCCtorHelper(clsHnd);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoHelpFunc);
}
}
static CORINFO_CLASS_STRUCT_* _getTypeForBox(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getTypeForBox(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static CorInfoHelpFunc _getBoxHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getBoxHelper(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoHelpFunc);
}
}
static CorInfoHelpFunc _getUnBoxHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getUnBoxHelper(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoHelpFunc);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _getReadyToRunHelper(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, ref CORINFO_LOOKUP_KIND pGenericLookupKind, CorInfoHelpFunc id, ref CORINFO_CONST_LOOKUP pLookup)
{
var _this = GetThis(thisHandle);
try
{
return _this.getReadyToRunHelper(ref pResolvedToken, ref pGenericLookupKind, id, ref pLookup);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static void _getReadyToRunDelegateCtorHelper(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pTargetMethod, CORINFO_CLASS_STRUCT_* delegateType, ref CORINFO_LOOKUP pLookup)
{
var _this = GetThis(thisHandle);
try
{
_this.getReadyToRunDelegateCtorHelper(ref pTargetMethod, delegateType, ref pLookup);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static byte* _getHelperName(IntPtr thisHandle, IntPtr* ppException, CorInfoHelpFunc helpFunc)
{
var _this = GetThis(thisHandle);
try
{
return _this.getHelperName(helpFunc);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
static CorInfoInitClassResult _initClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, CORINFO_METHOD_STRUCT_* method, CORINFO_CONTEXT_STRUCT* context)
{
var _this = GetThis(thisHandle);
try
{
return _this.initClass(field, method, context);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoInitClassResult);
}
}
static void _classMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
_this.classMustBeLoadedBeforeCodeIsRun(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static CORINFO_CLASS_STRUCT_* _getBuiltinClass(IntPtr thisHandle, IntPtr* ppException, CorInfoClassId classId)
{
var _this = GetThis(thisHandle);
try
{
return _this.getBuiltinClass(classId);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static CorInfoType _getTypeForPrimitiveValueClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getTypeForPrimitiveValueClass(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoType);
}
}
static CorInfoType _getTypeForPrimitiveNumericClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getTypeForPrimitiveNumericClass(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoType);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _canCast(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* child, CORINFO_CLASS_STRUCT_* parent)
{
var _this = GetThis(thisHandle);
try
{
return _this.canCast(child, parent);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _areTypesEquivalent(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2)
{
var _this = GetThis(thisHandle);
try
{
return _this.areTypesEquivalent(cls1, cls2);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static TypeCompareState _compareTypesForCast(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* fromClass, CORINFO_CLASS_STRUCT_* toClass)
{
var _this = GetThis(thisHandle);
try
{
return _this.compareTypesForCast(fromClass, toClass);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(TypeCompareState);
}
}
static TypeCompareState _compareTypesForEquality(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2)
{
var _this = GetThis(thisHandle);
try
{
return _this.compareTypesForEquality(cls1, cls2);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(TypeCompareState);
}
}
static CORINFO_CLASS_STRUCT_* _mergeClasses(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2)
{
var _this = GetThis(thisHandle);
try
{
return _this.mergeClasses(cls1, cls2);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _isMoreSpecificType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2)
{
var _this = GetThis(thisHandle);
try
{
return _this.isMoreSpecificType(cls1, cls2);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static CORINFO_CLASS_STRUCT_* _getParentType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getParentType(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static CorInfoType _getChildType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_CLASS_STRUCT_** clsRet)
{
var _this = GetThis(thisHandle);
try
{
return _this.getChildType(clsHnd, clsRet);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoType);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _satisfiesClassConstraints(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.satisfiesClassConstraints(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _isSDArray(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.isSDArray(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static uint _getArrayRank(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.getArrayRank(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static void* _getArrayInitializationData(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, uint size)
{
var _this = GetThis(thisHandle);
try
{
return _this.getArrayInitializationData(field, size);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
static CorInfoIsAccessAllowedResult _canAccessClass(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, ref CORINFO_HELPER_DESC pAccessHelper)
{
var _this = GetThis(thisHandle);
try
{
return _this.canAccessClass(ref pResolvedToken, callerHandle, ref pAccessHelper);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoIsAccessAllowedResult);
}
}
static byte* _getFieldName(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* ftn, byte** moduleName)
{
var _this = GetThis(thisHandle);
try
{
return _this.getFieldName(ftn, moduleName);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
static CORINFO_CLASS_STRUCT_* _getFieldClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field)
{
var _this = GetThis(thisHandle);
try
{
return _this.getFieldClass(field);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static CorInfoType _getFieldType(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, CORINFO_CLASS_STRUCT_** structType, CORINFO_CLASS_STRUCT_* memberParent)
{
var _this = GetThis(thisHandle);
try
{
return _this.getFieldType(field, structType, memberParent);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoType);
}
}
static uint _getFieldOffset(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field)
{
var _this = GetThis(thisHandle);
try
{
return _this.getFieldOffset(field);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static void _getFieldInfo(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_ACCESS_FLAGS flags, CORINFO_FIELD_INFO* pResult)
{
var _this = GetThis(thisHandle);
try
{
_this.getFieldInfo(ref pResolvedToken, callerHandle, flags, pResult);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _isFieldStatic(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* fldHnd)
{
var _this = GetThis(thisHandle);
try
{
return _this.isFieldStatic(fldHnd);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static void _getBoundaries(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref uint cILOffsets, ref uint* pILOffsets, BoundaryTypes* implictBoundaries)
{
var _this = GetThis(thisHandle);
try
{
_this.getBoundaries(ftn, ref cILOffsets, ref pILOffsets, implictBoundaries);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _setBoundaries(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint cMap, OffsetMapping* pMap)
{
var _this = GetThis(thisHandle);
try
{
_this.setBoundaries(ftn, cMap, pMap);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _getVars(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref uint cVars, ILVarInfo** vars, [MarshalAs(UnmanagedType.U1)] ref bool extendOthers)
{
var _this = GetThis(thisHandle);
try
{
_this.getVars(ftn, ref cVars, vars, ref extendOthers);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _setVars(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint cVars, NativeVarInfo* vars)
{
var _this = GetThis(thisHandle);
try
{
_this.setVars(ftn, cVars, vars);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void* _allocateArray(IntPtr thisHandle, IntPtr* ppException, UIntPtr cBytes)
{
var _this = GetThis(thisHandle);
try
{
return _this.allocateArray(cBytes);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
static void _freeArray(IntPtr thisHandle, IntPtr* ppException, void* array)
{
var _this = GetThis(thisHandle);
try
{
_this.freeArray(array);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static CORINFO_ARG_LIST_STRUCT_* _getArgNext(IntPtr thisHandle, IntPtr* ppException, CORINFO_ARG_LIST_STRUCT_* args)
{
var _this = GetThis(thisHandle);
try
{
return _this.getArgNext(args);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_ARG_LIST_STRUCT_*);
}
}
static CorInfoTypeWithMod _getArgType(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args, CORINFO_CLASS_STRUCT_** vcTypeRet)
{
var _this = GetThis(thisHandle);
try
{
return _this.getArgType(sig, args, vcTypeRet);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoTypeWithMod);
}
}
static CORINFO_CLASS_STRUCT_* _getArgClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args)
{
var _this = GetThis(thisHandle);
try
{
return _this.getArgClass(sig, args);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static CorInfoHFAElemType _getHFAType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* hClass)
{
var _this = GetThis(thisHandle);
try
{
return _this.getHFAType(hClass);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoHFAElemType);
}
}
static HRESULT _GetErrorHRESULT(IntPtr thisHandle, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers)
{
var _this = GetThis(thisHandle);
try
{
return _this.GetErrorHRESULT(pExceptionPointers);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(HRESULT);
}
}
static uint _GetErrorMessage(IntPtr thisHandle, IntPtr* ppException, char* buffer, uint bufferLength)
{
var _this = GetThis(thisHandle);
try
{
return _this.GetErrorMessage(buffer, bufferLength);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static int _FilterException(IntPtr thisHandle, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers)
{
var _this = GetThis(thisHandle);
try
{
return _this.FilterException(pExceptionPointers);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(int);
}
}
static void _HandleException(IntPtr thisHandle, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers)
{
var _this = GetThis(thisHandle);
try
{
_this.HandleException(pExceptionPointers);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _ThrowExceptionForJitResult(IntPtr thisHandle, IntPtr* ppException, HRESULT result)
{
var _this = GetThis(thisHandle);
try
{
_this.ThrowExceptionForJitResult(result);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _ThrowExceptionForHelper(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_HELPER_DESC throwHelper)
{
var _this = GetThis(thisHandle);
try
{
_this.ThrowExceptionForHelper(ref throwHelper);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _runWithErrorTrap(IntPtr thisHandle, IntPtr* ppException, void* function, void* parameter)
{
var _this = GetThis(thisHandle);
try
{
return _this.runWithErrorTrap(function, parameter);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static void _getEEInfo(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_EE_INFO pEEInfoOut)
{
var _this = GetThis(thisHandle);
try
{
_this.getEEInfo(ref pEEInfoOut);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static char* _getJitTimeLogFilename(IntPtr thisHandle, IntPtr* ppException)
{
var _this = GetThis(thisHandle);
try
{
return _this.getJitTimeLogFilename();
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(char*);
}
}
static mdToken _getMethodDefFromMethod(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hMethod)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodDefFromMethod(hMethod);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(mdToken);
}
}
static byte* _getMethodName(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte** moduleName)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodName(ftn, moduleName);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
static byte* _getMethodNameFromMetadata(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte** className, byte** namespaceName, byte** enclosingClassName)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodNameFromMetadata(ftn, className, namespaceName, enclosingClassName);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
static uint _getMethodHash(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodHash(ftn);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static byte* _findNameOfToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleHandle, mdToken token, byte* szFQName, UIntPtr FQNameCapacity)
{
var _this = GetThis(thisHandle);
try
{
return _this.findNameOfToken(moduleHandle, token, szFQName, FQNameCapacity);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(byte*);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _getSystemVAmd64PassStructInRegisterDescriptor(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* structHnd, SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr)
{
var _this = GetThis(thisHandle);
try
{
return _this.getSystemVAmd64PassStructInRegisterDescriptor(structHnd, structPassInRegDescPtr);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static uint _getThreadTLSIndex(IntPtr thisHandle, IntPtr* ppException, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getThreadTLSIndex(ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static void* _getInlinedCallFrameVptr(IntPtr thisHandle, IntPtr* ppException, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getInlinedCallFrameVptr(ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
static int* _getAddrOfCaptureThreadGlobal(IntPtr thisHandle, IntPtr* ppException, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getAddrOfCaptureThreadGlobal(ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(int*);
}
}
static void* _getHelperFtn(IntPtr thisHandle, IntPtr* ppException, CorInfoHelpFunc ftnNum, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getHelperFtn(ftnNum, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
static void _getFunctionEntryPoint(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref CORINFO_CONST_LOOKUP pResult, CORINFO_ACCESS_FLAGS accessFlags)
{
var _this = GetThis(thisHandle);
try
{
_this.getFunctionEntryPoint(ftn, ref pResult, accessFlags);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _getFunctionFixedEntryPoint(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref CORINFO_CONST_LOOKUP pResult)
{
var _this = GetThis(thisHandle);
try
{
_this.getFunctionFixedEntryPoint(ftn, ref pResult);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void* _getMethodSync(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodSync(ftn, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
static CorInfoHelpFunc _getLazyStringLiteralHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* handle)
{
var _this = GetThis(thisHandle);
try
{
return _this.getLazyStringLiteralHelper(handle);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CorInfoHelpFunc);
}
}
static CORINFO_MODULE_STRUCT_* _embedModuleHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* handle, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.embedModuleHandle(handle, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_MODULE_STRUCT_*);
}
}
static CORINFO_CLASS_STRUCT_* _embedClassHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* handle, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.embedClassHandle(handle, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static CORINFO_METHOD_STRUCT_* _embedMethodHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* handle, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.embedMethodHandle(handle, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_METHOD_STRUCT_*);
}
}
static CORINFO_FIELD_STRUCT_* _embedFieldHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* handle, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.embedFieldHandle(handle, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_FIELD_STRUCT_*);
}
}
static void _embedGenericHandle(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, [MarshalAs(UnmanagedType.Bool)]bool fEmbedParent, ref CORINFO_GENERICHANDLE_RESULT pResult)
{
var _this = GetThis(thisHandle);
try
{
_this.embedGenericHandle(ref pResolvedToken, fEmbedParent, ref pResult);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _getLocationOfThisType(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* context, ref CORINFO_LOOKUP_KIND pLookupKind)
{
var _this = GetThis(thisHandle);
try
{
_this.getLocationOfThisType(context, ref pLookupKind);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _getAddressOfPInvokeTarget(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, ref CORINFO_CONST_LOOKUP pLookup)
{
var _this = GetThis(thisHandle);
try
{
_this.getAddressOfPInvokeTarget(method, ref pLookup);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void* _GetCookieForPInvokeCalliSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* szMetaSig, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.GetCookieForPInvokeCalliSig(szMetaSig, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _canGetCookieForPInvokeCalliSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* szMetaSig)
{
var _this = GetThis(thisHandle);
try
{
return _this.canGetCookieForPInvokeCalliSig(szMetaSig);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static CORINFO_JUST_MY_CODE_HANDLE_* _getJustMyCodeHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, ref CORINFO_JUST_MY_CODE_HANDLE_* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getJustMyCodeHandle(method, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_JUST_MY_CODE_HANDLE_*);
}
}
static void _GetProfilingHandle(IntPtr thisHandle, IntPtr* ppException, [MarshalAs(UnmanagedType.Bool)] ref bool pbHookFunction, ref void* pProfilerHandle, [MarshalAs(UnmanagedType.Bool)] ref bool pbIndirectedHandles)
{
var _this = GetThis(thisHandle);
try
{
_this.GetProfilingHandle(ref pbHookFunction, ref pProfilerHandle, ref pbIndirectedHandles);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _getCallInfo(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_CALLINFO_FLAGS flags, CORINFO_CALL_INFO* pResult)
{
var _this = GetThis(thisHandle);
try
{
_this.getCallInfo(ref pResolvedToken, pConstrainedResolvedToken, callerHandle, flags, pResult);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _canAccessFamily(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hCaller, CORINFO_CLASS_STRUCT_* hInstanceType)
{
var _this = GetThis(thisHandle);
try
{
return _this.canAccessFamily(hCaller, hInstanceType);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _isRIDClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls)
{
var _this = GetThis(thisHandle);
try
{
return _this.isRIDClassDomainID(cls);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static uint _getClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getClassDomainID(cls, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static void* _getFieldAddress(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, void** ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getFieldAddress(field, ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
static CORINFO_CLASS_STRUCT_* _getStaticFieldCurrentClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, byte* pIsSpeculative)
{
var _this = GetThis(thisHandle);
try
{
return _this.getStaticFieldCurrentClass(field, pIsSpeculative);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_CLASS_STRUCT_*);
}
}
static IntPtr _getVarArgsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* pSig, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getVarArgsHandle(pSig, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(IntPtr);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _canGetVarArgsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* pSig)
{
var _this = GetThis(thisHandle);
try
{
return _this.canGetVarArgsHandle(pSig);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static InfoAccessType _constructStringLiteral(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, mdToken metaTok, ref void* ppValue)
{
var _this = GetThis(thisHandle);
try
{
return _this.constructStringLiteral(module, metaTok, ref ppValue);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(InfoAccessType);
}
}
static InfoAccessType _emptyStringLiteral(IntPtr thisHandle, IntPtr* ppException, ref void* ppValue)
{
var _this = GetThis(thisHandle);
try
{
return _this.emptyStringLiteral(ref ppValue);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(InfoAccessType);
}
}
static uint _getFieldThreadLocalStoreID(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, ref void* ppIndirection)
{
var _this = GetThis(thisHandle);
try
{
return _this.getFieldThreadLocalStoreID(field, ref ppIndirection);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static void _setOverride(IntPtr thisHandle, IntPtr* ppException, IntPtr pOverride, CORINFO_METHOD_STRUCT_* currentMethod)
{
var _this = GetThis(thisHandle);
try
{
_this.setOverride(pOverride, currentMethod);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _addActiveDependency(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MODULE_STRUCT_* moduleTo)
{
var _this = GetThis(thisHandle);
try
{
_this.addActiveDependency(moduleFrom, moduleTo);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static CORINFO_METHOD_STRUCT_* _GetDelegateCtor(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* methHnd, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_METHOD_STRUCT_* targetMethodHnd, ref DelegateCtorArgs pCtorData)
{
var _this = GetThis(thisHandle);
try
{
return _this.GetDelegateCtor(methHnd, clsHnd, targetMethodHnd, ref pCtorData);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(CORINFO_METHOD_STRUCT_*);
}
}
static void _MethodCompileComplete(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* methHnd)
{
var _this = GetThis(thisHandle);
try
{
_this.MethodCompileComplete(methHnd);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _getTailCallHelpers(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN callToken, CORINFO_SIG_INFO* sig, CORINFO_GET_TAILCALL_HELPERS_FLAGS flags, ref CORINFO_TAILCALL_HELPERS pResult)
{
var _this = GetThis(thisHandle);
try
{
return _this.getTailCallHelpers(ref callToken, sig, flags, ref pResult);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
[return: MarshalAs(UnmanagedType.I1)]static bool _convertPInvokeCalliToCall(IntPtr thisHandle, IntPtr* ppException, ref CORINFO_RESOLVED_TOKEN pResolvedToken, [MarshalAs(UnmanagedType.I1)]bool mustConvert)
{
var _this = GetThis(thisHandle);
try
{
return _this.convertPInvokeCalliToCall(ref pResolvedToken, mustConvert);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static void _notifyInstructionSetUsage(IntPtr thisHandle, IntPtr* ppException, InstructionSet instructionSet, [MarshalAs(UnmanagedType.I1)]bool supportEnabled)
{
var _this = GetThis(thisHandle);
try
{
_this.notifyInstructionSetUsage(instructionSet, supportEnabled);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _allocMem(IntPtr thisHandle, IntPtr* ppException, uint hotCodeSize, uint coldCodeSize, uint roDataSize, uint xcptnsCount, CorJitAllocMemFlag flag, ref void* hotCodeBlock, ref void* coldCodeBlock, ref void* roDataBlock)
{
var _this = GetThis(thisHandle);
try
{
_this.allocMem(hotCodeSize, coldCodeSize, roDataSize, xcptnsCount, flag, ref hotCodeBlock, ref coldCodeBlock, ref roDataBlock);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _reserveUnwindInfo(IntPtr thisHandle, IntPtr* ppException, [MarshalAs(UnmanagedType.Bool)]bool isFunclet, [MarshalAs(UnmanagedType.Bool)]bool isColdCode, uint unwindSize)
{
var _this = GetThis(thisHandle);
try
{
_this.reserveUnwindInfo(isFunclet, isColdCode, unwindSize);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _allocUnwindInfo(IntPtr thisHandle, IntPtr* ppException, byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind)
{
var _this = GetThis(thisHandle);
try
{
_this.allocUnwindInfo(pHotCode, pColdCode, startOffset, endOffset, unwindSize, pUnwindBlock, funcKind);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void* _allocGCInfo(IntPtr thisHandle, IntPtr* ppException, UIntPtr size)
{
var _this = GetThis(thisHandle);
try
{
return _this.allocGCInfo(size);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(void*);
}
}
static void _setEHcount(IntPtr thisHandle, IntPtr* ppException, uint cEH)
{
var _this = GetThis(thisHandle);
try
{
_this.setEHcount(cEH);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _setEHinfo(IntPtr thisHandle, IntPtr* ppException, uint EHnumber, ref CORINFO_EH_CLAUSE clause)
{
var _this = GetThis(thisHandle);
try
{
_this.setEHinfo(EHnumber, ref clause);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
[return: MarshalAs(UnmanagedType.Bool)]static bool _logMsg(IntPtr thisHandle, IntPtr* ppException, uint level, byte* fmt, IntPtr args)
{
var _this = GetThis(thisHandle);
try
{
return _this.logMsg(level, fmt, args);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(bool);
}
}
static int _doAssert(IntPtr thisHandle, IntPtr* ppException, byte* szFile, int iLine, byte* szExpr)
{
var _this = GetThis(thisHandle);
try
{
return _this.doAssert(szFile, iLine, szExpr);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(int);
}
}
static void _reportFatalError(IntPtr thisHandle, IntPtr* ppException, CorJitResult result)
{
var _this = GetThis(thisHandle);
try
{
_this.reportFatalError(result);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static HRESULT _allocMethodBlockCounts(IntPtr thisHandle, IntPtr* ppException, uint count, ref BlockCounts* pBlockCounts)
{
var _this = GetThis(thisHandle);
try
{
return _this.allocMethodBlockCounts(count, ref pBlockCounts);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(HRESULT);
}
}
static HRESULT _getMethodBlockCounts(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftnHnd, ref uint pCount, ref BlockCounts* pBlockCounts, ref uint pNumRuns)
{
var _this = GetThis(thisHandle);
try
{
return _this.getMethodBlockCounts(ftnHnd, ref pCount, ref pBlockCounts, ref pNumRuns);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(HRESULT);
}
}
static void _recordCallSite(IntPtr thisHandle, IntPtr* ppException, uint instrOffset, CORINFO_SIG_INFO* callSig, CORINFO_METHOD_STRUCT_* methodHandle)
{
var _this = GetThis(thisHandle);
try
{
_this.recordCallSite(instrOffset, callSig, methodHandle);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static void _recordRelocation(IntPtr thisHandle, IntPtr* ppException, void* location, void* target, ushort fRelocType, ushort slotNum, int addlDelta)
{
var _this = GetThis(thisHandle);
try
{
_this.recordRelocation(location, target, fRelocType, slotNum, addlDelta);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
}
}
static ushort _getRelocTypeHint(IntPtr thisHandle, IntPtr* ppException, void* target)
{
var _this = GetThis(thisHandle);
try
{
return _this.getRelocTypeHint(target);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(ushort);
}
}
static uint _getExpectedTargetArchitecture(IntPtr thisHandle, IntPtr* ppException)
{
var _this = GetThis(thisHandle);
try
{
return _this.getExpectedTargetArchitecture();
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static uint _getJitFlags(IntPtr thisHandle, IntPtr* ppException, ref CORJIT_FLAGS flags, uint sizeInBytes)
{
var _this = GetThis(thisHandle);
try
{
return _this.getJitFlags(ref flags, sizeInBytes);
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
return default(uint);
}
}
static IntPtr GetUnmanagedCallbacks(out Object keepAlive)
{
IntPtr * callbacks = (IntPtr *)Marshal.AllocCoTaskMem(sizeof(IntPtr) * 170);
Object[] delegates = new Object[170];
var d0 = new __getMethodAttribs(_getMethodAttribs);
callbacks[0] = Marshal.GetFunctionPointerForDelegate(d0);
delegates[0] = d0;
var d1 = new __setMethodAttribs(_setMethodAttribs);
callbacks[1] = Marshal.GetFunctionPointerForDelegate(d1);
delegates[1] = d1;
var d2 = new __getMethodSig(_getMethodSig);
callbacks[2] = Marshal.GetFunctionPointerForDelegate(d2);
delegates[2] = d2;
var d3 = new __getMethodInfo(_getMethodInfo);
callbacks[3] = Marshal.GetFunctionPointerForDelegate(d3);
delegates[3] = d3;
var d4 = new __canInline(_canInline);
callbacks[4] = Marshal.GetFunctionPointerForDelegate(d4);
delegates[4] = d4;
var d5 = new __reportInliningDecision(_reportInliningDecision);
callbacks[5] = Marshal.GetFunctionPointerForDelegate(d5);
delegates[5] = d5;
var d6 = new __canTailCall(_canTailCall);
callbacks[6] = Marshal.GetFunctionPointerForDelegate(d6);
delegates[6] = d6;
var d7 = new __reportTailCallDecision(_reportTailCallDecision);
callbacks[7] = Marshal.GetFunctionPointerForDelegate(d7);
delegates[7] = d7;
var d8 = new __getEHinfo(_getEHinfo);
callbacks[8] = Marshal.GetFunctionPointerForDelegate(d8);
delegates[8] = d8;
var d9 = new __getMethodClass(_getMethodClass);
callbacks[9] = Marshal.GetFunctionPointerForDelegate(d9);
delegates[9] = d9;
var d10 = new __getMethodModule(_getMethodModule);
callbacks[10] = Marshal.GetFunctionPointerForDelegate(d10);
delegates[10] = d10;
var d11 = new __getMethodVTableOffset(_getMethodVTableOffset);
callbacks[11] = Marshal.GetFunctionPointerForDelegate(d11);
delegates[11] = d11;
var d12 = new __resolveVirtualMethod(_resolveVirtualMethod);
callbacks[12] = Marshal.GetFunctionPointerForDelegate(d12);
delegates[12] = d12;
var d13 = new __getUnboxedEntry(_getUnboxedEntry);
callbacks[13] = Marshal.GetFunctionPointerForDelegate(d13);
delegates[13] = d13;
var d14 = new __getDefaultEqualityComparerClass(_getDefaultEqualityComparerClass);
callbacks[14] = Marshal.GetFunctionPointerForDelegate(d14);
delegates[14] = d14;
var d15 = new __expandRawHandleIntrinsic(_expandRawHandleIntrinsic);
callbacks[15] = Marshal.GetFunctionPointerForDelegate(d15);
delegates[15] = d15;
var d16 = new __getIntrinsicID(_getIntrinsicID);
callbacks[16] = Marshal.GetFunctionPointerForDelegate(d16);
delegates[16] = d16;
var d17 = new __isIntrinsicType(_isIntrinsicType);
callbacks[17] = Marshal.GetFunctionPointerForDelegate(d17);
delegates[17] = d17;
var d18 = new __getUnmanagedCallConv(_getUnmanagedCallConv);
callbacks[18] = Marshal.GetFunctionPointerForDelegate(d18);
delegates[18] = d18;
var d19 = new __pInvokeMarshalingRequired(_pInvokeMarshalingRequired);
callbacks[19] = Marshal.GetFunctionPointerForDelegate(d19);
delegates[19] = d19;
var d20 = new __satisfiesMethodConstraints(_satisfiesMethodConstraints);
callbacks[20] = Marshal.GetFunctionPointerForDelegate(d20);
delegates[20] = d20;
var d21 = new __isCompatibleDelegate(_isCompatibleDelegate);
callbacks[21] = Marshal.GetFunctionPointerForDelegate(d21);
delegates[21] = d21;
var d22 = new __methodMustBeLoadedBeforeCodeIsRun(_methodMustBeLoadedBeforeCodeIsRun);
callbacks[22] = Marshal.GetFunctionPointerForDelegate(d22);
delegates[22] = d22;
var d23 = new __mapMethodDeclToMethodImpl(_mapMethodDeclToMethodImpl);
callbacks[23] = Marshal.GetFunctionPointerForDelegate(d23);
delegates[23] = d23;
var d24 = new __getGSCookie(_getGSCookie);
callbacks[24] = Marshal.GetFunctionPointerForDelegate(d24);
delegates[24] = d24;
var d25 = new __setPatchpointInfo(_setPatchpointInfo);
callbacks[25] = Marshal.GetFunctionPointerForDelegate(d25);
delegates[25] = d25;
var d26 = new __getOSRInfo(_getOSRInfo);
callbacks[26] = Marshal.GetFunctionPointerForDelegate(d26);
delegates[26] = d26;
var d27 = new __resolveToken(_resolveToken);
callbacks[27] = Marshal.GetFunctionPointerForDelegate(d27);
delegates[27] = d27;
var d28 = new __tryResolveToken(_tryResolveToken);
callbacks[28] = Marshal.GetFunctionPointerForDelegate(d28);
delegates[28] = d28;
var d29 = new __findSig(_findSig);
callbacks[29] = Marshal.GetFunctionPointerForDelegate(d29);
delegates[29] = d29;
var d30 = new __findCallSiteSig(_findCallSiteSig);
callbacks[30] = Marshal.GetFunctionPointerForDelegate(d30);
delegates[30] = d30;
var d31 = new __getTokenTypeAsHandle(_getTokenTypeAsHandle);
callbacks[31] = Marshal.GetFunctionPointerForDelegate(d31);
delegates[31] = d31;
var d32 = new __isValidToken(_isValidToken);
callbacks[32] = Marshal.GetFunctionPointerForDelegate(d32);
delegates[32] = d32;
var d33 = new __isValidStringRef(_isValidStringRef);
callbacks[33] = Marshal.GetFunctionPointerForDelegate(d33);
delegates[33] = d33;
var d34 = new __getStringLiteral(_getStringLiteral);
callbacks[34] = Marshal.GetFunctionPointerForDelegate(d34);
delegates[34] = d34;
var d35 = new __asCorInfoType(_asCorInfoType);
callbacks[35] = Marshal.GetFunctionPointerForDelegate(d35);
delegates[35] = d35;
var d36 = new __getClassName(_getClassName);
callbacks[36] = Marshal.GetFunctionPointerForDelegate(d36);
delegates[36] = d36;
var d37 = new __getClassNameFromMetadata(_getClassNameFromMetadata);
callbacks[37] = Marshal.GetFunctionPointerForDelegate(d37);
delegates[37] = d37;
var d38 = new __getTypeInstantiationArgument(_getTypeInstantiationArgument);
callbacks[38] = Marshal.GetFunctionPointerForDelegate(d38);
delegates[38] = d38;
var d39 = new __appendClassName(_appendClassName);
callbacks[39] = Marshal.GetFunctionPointerForDelegate(d39);
delegates[39] = d39;
var d40 = new __isValueClass(_isValueClass);
callbacks[40] = Marshal.GetFunctionPointerForDelegate(d40);
delegates[40] = d40;
var d41 = new __canInlineTypeCheck(_canInlineTypeCheck);
callbacks[41] = Marshal.GetFunctionPointerForDelegate(d41);
delegates[41] = d41;
var d42 = new __getClassAttribs(_getClassAttribs);
callbacks[42] = Marshal.GetFunctionPointerForDelegate(d42);
delegates[42] = d42;
var d43 = new __isStructRequiringStackAllocRetBuf(_isStructRequiringStackAllocRetBuf);
callbacks[43] = Marshal.GetFunctionPointerForDelegate(d43);
delegates[43] = d43;
var d44 = new __getClassModule(_getClassModule);
callbacks[44] = Marshal.GetFunctionPointerForDelegate(d44);
delegates[44] = d44;
var d45 = new __getModuleAssembly(_getModuleAssembly);
callbacks[45] = Marshal.GetFunctionPointerForDelegate(d45);
delegates[45] = d45;
var d46 = new __getAssemblyName(_getAssemblyName);
callbacks[46] = Marshal.GetFunctionPointerForDelegate(d46);
delegates[46] = d46;
var d47 = new __LongLifetimeMalloc(_LongLifetimeMalloc);
callbacks[47] = Marshal.GetFunctionPointerForDelegate(d47);
delegates[47] = d47;
var d48 = new __LongLifetimeFree(_LongLifetimeFree);
callbacks[48] = Marshal.GetFunctionPointerForDelegate(d48);
delegates[48] = d48;
var d49 = new __getClassModuleIdForStatics(_getClassModuleIdForStatics);
callbacks[49] = Marshal.GetFunctionPointerForDelegate(d49);
delegates[49] = d49;
var d50 = new __getClassSize(_getClassSize);
callbacks[50] = Marshal.GetFunctionPointerForDelegate(d50);
delegates[50] = d50;
var d51 = new __getHeapClassSize(_getHeapClassSize);
callbacks[51] = Marshal.GetFunctionPointerForDelegate(d51);
delegates[51] = d51;
var d52 = new __canAllocateOnStack(_canAllocateOnStack);
callbacks[52] = Marshal.GetFunctionPointerForDelegate(d52);
delegates[52] = d52;
var d53 = new __getClassAlignmentRequirement(_getClassAlignmentRequirement);
callbacks[53] = Marshal.GetFunctionPointerForDelegate(d53);
delegates[53] = d53;
var d54 = new __getClassGClayout(_getClassGClayout);
callbacks[54] = Marshal.GetFunctionPointerForDelegate(d54);
delegates[54] = d54;
var d55 = new __getClassNumInstanceFields(_getClassNumInstanceFields);
callbacks[55] = Marshal.GetFunctionPointerForDelegate(d55);
delegates[55] = d55;
var d56 = new __getFieldInClass(_getFieldInClass);
callbacks[56] = Marshal.GetFunctionPointerForDelegate(d56);
delegates[56] = d56;
var d57 = new __checkMethodModifier(_checkMethodModifier);
callbacks[57] = Marshal.GetFunctionPointerForDelegate(d57);
delegates[57] = d57;
var d58 = new __getNewHelper(_getNewHelper);
callbacks[58] = Marshal.GetFunctionPointerForDelegate(d58);
delegates[58] = d58;
var d59 = new __getNewArrHelper(_getNewArrHelper);
callbacks[59] = Marshal.GetFunctionPointerForDelegate(d59);
delegates[59] = d59;
var d60 = new __getCastingHelper(_getCastingHelper);
callbacks[60] = Marshal.GetFunctionPointerForDelegate(d60);
delegates[60] = d60;
var d61 = new __getSharedCCtorHelper(_getSharedCCtorHelper);
callbacks[61] = Marshal.GetFunctionPointerForDelegate(d61);
delegates[61] = d61;
var d62 = new __getTypeForBox(_getTypeForBox);
callbacks[62] = Marshal.GetFunctionPointerForDelegate(d62);
delegates[62] = d62;
var d63 = new __getBoxHelper(_getBoxHelper);
callbacks[63] = Marshal.GetFunctionPointerForDelegate(d63);
delegates[63] = d63;
var d64 = new __getUnBoxHelper(_getUnBoxHelper);
callbacks[64] = Marshal.GetFunctionPointerForDelegate(d64);
delegates[64] = d64;
var d65 = new __getReadyToRunHelper(_getReadyToRunHelper);
callbacks[65] = Marshal.GetFunctionPointerForDelegate(d65);
delegates[65] = d65;
var d66 = new __getReadyToRunDelegateCtorHelper(_getReadyToRunDelegateCtorHelper);
callbacks[66] = Marshal.GetFunctionPointerForDelegate(d66);
delegates[66] = d66;
var d67 = new __getHelperName(_getHelperName);
callbacks[67] = Marshal.GetFunctionPointerForDelegate(d67);
delegates[67] = d67;
var d68 = new __initClass(_initClass);
callbacks[68] = Marshal.GetFunctionPointerForDelegate(d68);
delegates[68] = d68;
var d69 = new __classMustBeLoadedBeforeCodeIsRun(_classMustBeLoadedBeforeCodeIsRun);
callbacks[69] = Marshal.GetFunctionPointerForDelegate(d69);
delegates[69] = d69;
var d70 = new __getBuiltinClass(_getBuiltinClass);
callbacks[70] = Marshal.GetFunctionPointerForDelegate(d70);
delegates[70] = d70;
var d71 = new __getTypeForPrimitiveValueClass(_getTypeForPrimitiveValueClass);
callbacks[71] = Marshal.GetFunctionPointerForDelegate(d71);
delegates[71] = d71;
var d72 = new __getTypeForPrimitiveNumericClass(_getTypeForPrimitiveNumericClass);
callbacks[72] = Marshal.GetFunctionPointerForDelegate(d72);
delegates[72] = d72;
var d73 = new __canCast(_canCast);
callbacks[73] = Marshal.GetFunctionPointerForDelegate(d73);
delegates[73] = d73;
var d74 = new __areTypesEquivalent(_areTypesEquivalent);
callbacks[74] = Marshal.GetFunctionPointerForDelegate(d74);
delegates[74] = d74;
var d75 = new __compareTypesForCast(_compareTypesForCast);
callbacks[75] = Marshal.GetFunctionPointerForDelegate(d75);
delegates[75] = d75;
var d76 = new __compareTypesForEquality(_compareTypesForEquality);
callbacks[76] = Marshal.GetFunctionPointerForDelegate(d76);
delegates[76] = d76;
var d77 = new __mergeClasses(_mergeClasses);
callbacks[77] = Marshal.GetFunctionPointerForDelegate(d77);
delegates[77] = d77;
var d78 = new __isMoreSpecificType(_isMoreSpecificType);
callbacks[78] = Marshal.GetFunctionPointerForDelegate(d78);
delegates[78] = d78;
var d79 = new __getParentType(_getParentType);
callbacks[79] = Marshal.GetFunctionPointerForDelegate(d79);
delegates[79] = d79;
var d80 = new __getChildType(_getChildType);
callbacks[80] = Marshal.GetFunctionPointerForDelegate(d80);
delegates[80] = d80;
var d81 = new __satisfiesClassConstraints(_satisfiesClassConstraints);
callbacks[81] = Marshal.GetFunctionPointerForDelegate(d81);
delegates[81] = d81;
var d82 = new __isSDArray(_isSDArray);
callbacks[82] = Marshal.GetFunctionPointerForDelegate(d82);
delegates[82] = d82;
var d83 = new __getArrayRank(_getArrayRank);
callbacks[83] = Marshal.GetFunctionPointerForDelegate(d83);
delegates[83] = d83;
var d84 = new __getArrayInitializationData(_getArrayInitializationData);
callbacks[84] = Marshal.GetFunctionPointerForDelegate(d84);
delegates[84] = d84;
var d85 = new __canAccessClass(_canAccessClass);
callbacks[85] = Marshal.GetFunctionPointerForDelegate(d85);
delegates[85] = d85;
var d86 = new __getFieldName(_getFieldName);
callbacks[86] = Marshal.GetFunctionPointerForDelegate(d86);
delegates[86] = d86;
var d87 = new __getFieldClass(_getFieldClass);
callbacks[87] = Marshal.GetFunctionPointerForDelegate(d87);
delegates[87] = d87;
var d88 = new __getFieldType(_getFieldType);
callbacks[88] = Marshal.GetFunctionPointerForDelegate(d88);
delegates[88] = d88;
var d89 = new __getFieldOffset(_getFieldOffset);
callbacks[89] = Marshal.GetFunctionPointerForDelegate(d89);
delegates[89] = d89;
var d90 = new __getFieldInfo(_getFieldInfo);
callbacks[90] = Marshal.GetFunctionPointerForDelegate(d90);
delegates[90] = d90;
var d91 = new __isFieldStatic(_isFieldStatic);
callbacks[91] = Marshal.GetFunctionPointerForDelegate(d91);
delegates[91] = d91;
var d92 = new __getBoundaries(_getBoundaries);
callbacks[92] = Marshal.GetFunctionPointerForDelegate(d92);
delegates[92] = d92;
var d93 = new __setBoundaries(_setBoundaries);
callbacks[93] = Marshal.GetFunctionPointerForDelegate(d93);
delegates[93] = d93;
var d94 = new __getVars(_getVars);
callbacks[94] = Marshal.GetFunctionPointerForDelegate(d94);
delegates[94] = d94;
var d95 = new __setVars(_setVars);
callbacks[95] = Marshal.GetFunctionPointerForDelegate(d95);
delegates[95] = d95;
var d96 = new __allocateArray(_allocateArray);
callbacks[96] = Marshal.GetFunctionPointerForDelegate(d96);
delegates[96] = d96;
var d97 = new __freeArray(_freeArray);
callbacks[97] = Marshal.GetFunctionPointerForDelegate(d97);
delegates[97] = d97;
var d98 = new __getArgNext(_getArgNext);
callbacks[98] = Marshal.GetFunctionPointerForDelegate(d98);
delegates[98] = d98;
var d99 = new __getArgType(_getArgType);
callbacks[99] = Marshal.GetFunctionPointerForDelegate(d99);
delegates[99] = d99;
var d100 = new __getArgClass(_getArgClass);
callbacks[100] = Marshal.GetFunctionPointerForDelegate(d100);
delegates[100] = d100;
var d101 = new __getHFAType(_getHFAType);
callbacks[101] = Marshal.GetFunctionPointerForDelegate(d101);
delegates[101] = d101;
var d102 = new __GetErrorHRESULT(_GetErrorHRESULT);
callbacks[102] = Marshal.GetFunctionPointerForDelegate(d102);
delegates[102] = d102;
var d103 = new __GetErrorMessage(_GetErrorMessage);
callbacks[103] = Marshal.GetFunctionPointerForDelegate(d103);
delegates[103] = d103;
var d104 = new __FilterException(_FilterException);
callbacks[104] = Marshal.GetFunctionPointerForDelegate(d104);
delegates[104] = d104;
var d105 = new __HandleException(_HandleException);
callbacks[105] = Marshal.GetFunctionPointerForDelegate(d105);
delegates[105] = d105;
var d106 = new __ThrowExceptionForJitResult(_ThrowExceptionForJitResult);
callbacks[106] = Marshal.GetFunctionPointerForDelegate(d106);
delegates[106] = d106;
var d107 = new __ThrowExceptionForHelper(_ThrowExceptionForHelper);
callbacks[107] = Marshal.GetFunctionPointerForDelegate(d107);
delegates[107] = d107;
var d108 = new __runWithErrorTrap(_runWithErrorTrap);
callbacks[108] = Marshal.GetFunctionPointerForDelegate(d108);
delegates[108] = d108;
var d109 = new __getEEInfo(_getEEInfo);
callbacks[109] = Marshal.GetFunctionPointerForDelegate(d109);
delegates[109] = d109;
var d110 = new __getJitTimeLogFilename(_getJitTimeLogFilename);
callbacks[110] = Marshal.GetFunctionPointerForDelegate(d110);
delegates[110] = d110;
var d111 = new __getMethodDefFromMethod(_getMethodDefFromMethod);
callbacks[111] = Marshal.GetFunctionPointerForDelegate(d111);
delegates[111] = d111;
var d112 = new __getMethodName(_getMethodName);
callbacks[112] = Marshal.GetFunctionPointerForDelegate(d112);
delegates[112] = d112;
var d113 = new __getMethodNameFromMetadata(_getMethodNameFromMetadata);
callbacks[113] = Marshal.GetFunctionPointerForDelegate(d113);
delegates[113] = d113;
var d114 = new __getMethodHash(_getMethodHash);
callbacks[114] = Marshal.GetFunctionPointerForDelegate(d114);
delegates[114] = d114;
var d115 = new __findNameOfToken(_findNameOfToken);
callbacks[115] = Marshal.GetFunctionPointerForDelegate(d115);
delegates[115] = d115;
var d116 = new __getSystemVAmd64PassStructInRegisterDescriptor(_getSystemVAmd64PassStructInRegisterDescriptor);
callbacks[116] = Marshal.GetFunctionPointerForDelegate(d116);
delegates[116] = d116;
var d117 = new __getThreadTLSIndex(_getThreadTLSIndex);
callbacks[117] = Marshal.GetFunctionPointerForDelegate(d117);
delegates[117] = d117;
var d118 = new __getInlinedCallFrameVptr(_getInlinedCallFrameVptr);
callbacks[118] = Marshal.GetFunctionPointerForDelegate(d118);
delegates[118] = d118;
var d119 = new __getAddrOfCaptureThreadGlobal(_getAddrOfCaptureThreadGlobal);
callbacks[119] = Marshal.GetFunctionPointerForDelegate(d119);
delegates[119] = d119;
var d120 = new __getHelperFtn(_getHelperFtn);
callbacks[120] = Marshal.GetFunctionPointerForDelegate(d120);
delegates[120] = d120;
var d121 = new __getFunctionEntryPoint(_getFunctionEntryPoint);
callbacks[121] = Marshal.GetFunctionPointerForDelegate(d121);
delegates[121] = d121;
var d122 = new __getFunctionFixedEntryPoint(_getFunctionFixedEntryPoint);
callbacks[122] = Marshal.GetFunctionPointerForDelegate(d122);
delegates[122] = d122;
var d123 = new __getMethodSync(_getMethodSync);
callbacks[123] = Marshal.GetFunctionPointerForDelegate(d123);
delegates[123] = d123;
var d124 = new __getLazyStringLiteralHelper(_getLazyStringLiteralHelper);
callbacks[124] = Marshal.GetFunctionPointerForDelegate(d124);
delegates[124] = d124;
var d125 = new __embedModuleHandle(_embedModuleHandle);
callbacks[125] = Marshal.GetFunctionPointerForDelegate(d125);
delegates[125] = d125;
var d126 = new __embedClassHandle(_embedClassHandle);
callbacks[126] = Marshal.GetFunctionPointerForDelegate(d126);
delegates[126] = d126;
var d127 = new __embedMethodHandle(_embedMethodHandle);
callbacks[127] = Marshal.GetFunctionPointerForDelegate(d127);
delegates[127] = d127;
var d128 = new __embedFieldHandle(_embedFieldHandle);
callbacks[128] = Marshal.GetFunctionPointerForDelegate(d128);
delegates[128] = d128;
var d129 = new __embedGenericHandle(_embedGenericHandle);
callbacks[129] = Marshal.GetFunctionPointerForDelegate(d129);
delegates[129] = d129;
var d130 = new __getLocationOfThisType(_getLocationOfThisType);
callbacks[130] = Marshal.GetFunctionPointerForDelegate(d130);
delegates[130] = d130;
var d131 = new __getAddressOfPInvokeTarget(_getAddressOfPInvokeTarget);
callbacks[131] = Marshal.GetFunctionPointerForDelegate(d131);
delegates[131] = d131;
var d132 = new __GetCookieForPInvokeCalliSig(_GetCookieForPInvokeCalliSig);
callbacks[132] = Marshal.GetFunctionPointerForDelegate(d132);
delegates[132] = d132;
var d133 = new __canGetCookieForPInvokeCalliSig(_canGetCookieForPInvokeCalliSig);
callbacks[133] = Marshal.GetFunctionPointerForDelegate(d133);
delegates[133] = d133;
var d134 = new __getJustMyCodeHandle(_getJustMyCodeHandle);
callbacks[134] = Marshal.GetFunctionPointerForDelegate(d134);
delegates[134] = d134;
var d135 = new __GetProfilingHandle(_GetProfilingHandle);
callbacks[135] = Marshal.GetFunctionPointerForDelegate(d135);
delegates[135] = d135;
var d136 = new __getCallInfo(_getCallInfo);
callbacks[136] = Marshal.GetFunctionPointerForDelegate(d136);
delegates[136] = d136;
var d137 = new __canAccessFamily(_canAccessFamily);
callbacks[137] = Marshal.GetFunctionPointerForDelegate(d137);
delegates[137] = d137;
var d138 = new __isRIDClassDomainID(_isRIDClassDomainID);
callbacks[138] = Marshal.GetFunctionPointerForDelegate(d138);
delegates[138] = d138;
var d139 = new __getClassDomainID(_getClassDomainID);
callbacks[139] = Marshal.GetFunctionPointerForDelegate(d139);
delegates[139] = d139;
var d140 = new __getFieldAddress(_getFieldAddress);
callbacks[140] = Marshal.GetFunctionPointerForDelegate(d140);
delegates[140] = d140;
var d141 = new __getStaticFieldCurrentClass(_getStaticFieldCurrentClass);
callbacks[141] = Marshal.GetFunctionPointerForDelegate(d141);
delegates[141] = d141;
var d142 = new __getVarArgsHandle(_getVarArgsHandle);
callbacks[142] = Marshal.GetFunctionPointerForDelegate(d142);
delegates[142] = d142;
var d143 = new __canGetVarArgsHandle(_canGetVarArgsHandle);
callbacks[143] = Marshal.GetFunctionPointerForDelegate(d143);
delegates[143] = d143;
var d144 = new __constructStringLiteral(_constructStringLiteral);
callbacks[144] = Marshal.GetFunctionPointerForDelegate(d144);
delegates[144] = d144;
var d145 = new __emptyStringLiteral(_emptyStringLiteral);
callbacks[145] = Marshal.GetFunctionPointerForDelegate(d145);
delegates[145] = d145;
var d146 = new __getFieldThreadLocalStoreID(_getFieldThreadLocalStoreID);
callbacks[146] = Marshal.GetFunctionPointerForDelegate(d146);
delegates[146] = d146;
var d147 = new __setOverride(_setOverride);
callbacks[147] = Marshal.GetFunctionPointerForDelegate(d147);
delegates[147] = d147;
var d148 = new __addActiveDependency(_addActiveDependency);
callbacks[148] = Marshal.GetFunctionPointerForDelegate(d148);
delegates[148] = d148;
var d149 = new __GetDelegateCtor(_GetDelegateCtor);
callbacks[149] = Marshal.GetFunctionPointerForDelegate(d149);
delegates[149] = d149;
var d150 = new __MethodCompileComplete(_MethodCompileComplete);
callbacks[150] = Marshal.GetFunctionPointerForDelegate(d150);
delegates[150] = d150;
var d151 = new __getTailCallHelpers(_getTailCallHelpers);
callbacks[151] = Marshal.GetFunctionPointerForDelegate(d151);
delegates[151] = d151;
var d152 = new __convertPInvokeCalliToCall(_convertPInvokeCalliToCall);
callbacks[152] = Marshal.GetFunctionPointerForDelegate(d152);
delegates[152] = d152;
var d153 = new __notifyInstructionSetUsage(_notifyInstructionSetUsage);
callbacks[153] = Marshal.GetFunctionPointerForDelegate(d153);
delegates[153] = d153;
var d154 = new __allocMem(_allocMem);
callbacks[154] = Marshal.GetFunctionPointerForDelegate(d154);
delegates[154] = d154;
var d155 = new __reserveUnwindInfo(_reserveUnwindInfo);
callbacks[155] = Marshal.GetFunctionPointerForDelegate(d155);
delegates[155] = d155;
var d156 = new __allocUnwindInfo(_allocUnwindInfo);
callbacks[156] = Marshal.GetFunctionPointerForDelegate(d156);
delegates[156] = d156;
var d157 = new __allocGCInfo(_allocGCInfo);
callbacks[157] = Marshal.GetFunctionPointerForDelegate(d157);
delegates[157] = d157;
var d158 = new __setEHcount(_setEHcount);
callbacks[158] = Marshal.GetFunctionPointerForDelegate(d158);
delegates[158] = d158;
var d159 = new __setEHinfo(_setEHinfo);
callbacks[159] = Marshal.GetFunctionPointerForDelegate(d159);
delegates[159] = d159;
var d160 = new __logMsg(_logMsg);
callbacks[160] = Marshal.GetFunctionPointerForDelegate(d160);
delegates[160] = d160;
var d161 = new __doAssert(_doAssert);
callbacks[161] = Marshal.GetFunctionPointerForDelegate(d161);
delegates[161] = d161;
var d162 = new __reportFatalError(_reportFatalError);
callbacks[162] = Marshal.GetFunctionPointerForDelegate(d162);
delegates[162] = d162;
var d163 = new __allocMethodBlockCounts(_allocMethodBlockCounts);
callbacks[163] = Marshal.GetFunctionPointerForDelegate(d163);
delegates[163] = d163;
var d164 = new __getMethodBlockCounts(_getMethodBlockCounts);
callbacks[164] = Marshal.GetFunctionPointerForDelegate(d164);
delegates[164] = d164;
var d165 = new __recordCallSite(_recordCallSite);
callbacks[165] = Marshal.GetFunctionPointerForDelegate(d165);
delegates[165] = d165;
var d166 = new __recordRelocation(_recordRelocation);
callbacks[166] = Marshal.GetFunctionPointerForDelegate(d166);
delegates[166] = d166;
var d167 = new __getRelocTypeHint(_getRelocTypeHint);
callbacks[167] = Marshal.GetFunctionPointerForDelegate(d167);
delegates[167] = d167;
var d168 = new __getExpectedTargetArchitecture(_getExpectedTargetArchitecture);
callbacks[168] = Marshal.GetFunctionPointerForDelegate(d168);
delegates[168] = d168;
var d169 = new __getJitFlags(_getJitFlags);
callbacks[169] = Marshal.GetFunctionPointerForDelegate(d169);
delegates[169] = d169;
keepAlive = delegates;
return (IntPtr)callbacks;
}
}
}
| 46.420299 | 318 | 0.627168 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/src/tools/Common/JitInterface/CorInfoBase.cs | 149,102 | C# |
/*
* Algebratec API
*
* Learn and test our api with ease
*
* OpenAPI spec version: 1.0.0
* Contact: support@algebratec.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using IO.Swagger.Api;
using IO.Swagger.Model;
using IO.Swagger.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace IO.Swagger.Test
{
/// <summary>
/// Class for testing HotelConfirmationResponseBookingHotelPaxes
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class HotelConfirmationResponseBookingHotelPaxesTests
{
// TODO uncomment below to declare an instance variable for HotelConfirmationResponseBookingHotelPaxes
//private HotelConfirmationResponseBookingHotelPaxes instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of HotelConfirmationResponseBookingHotelPaxes
//instance = new HotelConfirmationResponseBookingHotelPaxes();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of HotelConfirmationResponseBookingHotelPaxes
/// </summary>
[Test]
public void HotelConfirmationResponseBookingHotelPaxesInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" HotelConfirmationResponseBookingHotelPaxes
//Assert.IsInstanceOfType<HotelConfirmationResponseBookingHotelPaxes> (instance, "variable 'instance' is a HotelConfirmationResponseBookingHotelPaxes");
}
/// <summary>
/// Test the property 'Type'
/// </summary>
[Test]
public void TypeTest()
{
// TODO unit test for the property 'Type'
}
/// <summary>
/// Test the property 'Age'
/// </summary>
[Test]
public void AgeTest()
{
// TODO unit test for the property 'Age'
}
/// <summary>
/// Test the property 'FirstName'
/// </summary>
[Test]
public void FirstNameTest()
{
// TODO unit test for the property 'FirstName'
}
/// <summary>
/// Test the property 'LastName'
/// </summary>
[Test]
public void LastNameTest()
{
// TODO unit test for the property 'LastName'
}
}
}
| 27.153846 | 164 | 0.601275 | [
"Apache-2.0"
] | algebratec/travel-api-sdk-csharp | src/IO.Swagger.Test/Model/HotelConfirmationResponseBookingHotelPaxesTests.cs | 2,824 | C# |
using Foundation;
using System;
using UIKit;
namespace Toggl.iOS.Views
{
public partial class SuggestionsEmptyViewCell : UITableViewCell
{
private static readonly Random Random = new Random();
private const int minTaskWidth = 74;
private const int maxTaskWidth = 84;
private const int minProjectWidth = 42;
private const int maxProjectWidth = 84;
private const int minDescriptionWidth = 74;
private const int maxDescriptionWidth = 110;
private static readonly UIColor[] Colors =
{
UIColor.FromRGB(197f / 255f, 107f / 255f, 255f / 255f),
UIColor.FromRGB(006f / 255f, 170f / 255f, 245f / 255f),
UIColor.FromRGB(241f / 255f, 195f / 255f, 063f / 255f)
};
public static readonly NSString Key = new NSString(nameof(SuggestionsEmptyViewCell));
public static readonly UINib Nib;
static SuggestionsEmptyViewCell()
{
Nib = UINib.FromName(nameof(SuggestionsEmptyViewCell), NSBundle.MainBundle);
}
protected SuggestionsEmptyViewCell(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void AwakeFromNib()
{
base.AwakeFromNib();
TaskWidth.Constant = Random.Next(minTaskWidth, maxTaskWidth);
ProjectWidth.Constant = Random.Next(minProjectWidth, maxProjectWidth);
ProjectView.BackgroundColor = Colors[Random.Next(0, Colors.Length)];
DescriptionWidth.Constant = Random.Next(minDescriptionWidth, maxDescriptionWidth);
SetNeedsLayout();
SetNeedsUpdateConstraints();
}
}
}
| 33.673077 | 94 | 0.640777 | [
"BSD-3-Clause"
] | MULXCODE/mobileapp | Toggl.iOS/Views/Suggestions/SuggestionsEmptyViewCell.cs | 1,753 | C# |
namespace Nager.Country.CountryInfo
{
/// <summary>
/// Switzerland
/// </summary>
public class SwitzerlandInfo : ICountryInfo
{
public string CommonName => "Switzerland";
public string OfficialName => "Swiss Confederation";
public Translation[] Translations => new []
{
new Translation(LanguageCode.AR, "سويسرا"),
new Translation(LanguageCode.AZ, "İsveçrə"),
new Translation(LanguageCode.BE, "Швейцарыя"),
new Translation(LanguageCode.BG, "Швейцария"),
new Translation(LanguageCode.BS, "Švicarska"),
new Translation(LanguageCode.CA, "Suïssa"),
new Translation(LanguageCode.CS, "Švýcarsko"),
new Translation(LanguageCode.DA, "Schweiz"),
new Translation(LanguageCode.DE, "Schweiz"),
new Translation(LanguageCode.EL, "Ελβετία"),
new Translation(LanguageCode.EN, "Switzerland"),
new Translation(LanguageCode.ES, "Suiza"),
new Translation(LanguageCode.ET, "Šveits"),
new Translation(LanguageCode.FA, "سوئیس"),
new Translation(LanguageCode.FI, "Sveitsi"),
new Translation(LanguageCode.FR, "Suisse"),
new Translation(LanguageCode.HE, "שווייץ"),
new Translation(LanguageCode.HR, "Švicarska"),
new Translation(LanguageCode.HU, "Svájc"),
new Translation(LanguageCode.HY, "Շվեյցարիա"),
new Translation(LanguageCode.ID, "Swiss"),
new Translation(LanguageCode.IT, "Svizzera"),
new Translation(LanguageCode.JA, "スイス"),
new Translation(LanguageCode.KA, "შვეიცარია"),
new Translation(LanguageCode.KK, "Швейцария"),
new Translation(LanguageCode.KO, "스위스"),
new Translation(LanguageCode.KY, "Швейцария"),
new Translation(LanguageCode.LT, "Šveicarija"),
new Translation(LanguageCode.LV, "Šveice"),
new Translation(LanguageCode.MK, "Швајцарија"),
new Translation(LanguageCode.MN, "Швейцари"),
new Translation(LanguageCode.NB, "Sveits"),
new Translation(LanguageCode.NL, "Zwitserland"),
new Translation(LanguageCode.NN, "Sveits"),
new Translation(LanguageCode.PL, "Szwajcaria"),
new Translation(LanguageCode.PT, "Suíça"),
new Translation(LanguageCode.RO, "Elveția"),
new Translation(LanguageCode.RU, "Швейцария"),
new Translation(LanguageCode.SK, "Švajčiarsko"),
new Translation(LanguageCode.SL, "Švica"),
new Translation(LanguageCode.SR, "Швајцарска"),
new Translation(LanguageCode.SV, "Schweiz"),
new Translation(LanguageCode.TR, "İsviçre"),
new Translation(LanguageCode.UK, "Швейцарія"),
new Translation(LanguageCode.UZ, "Shveytsariya"),
new Translation(LanguageCode.ZH, "瑞士"),
};
public Alpha2Code Alpha2Code => Alpha2Code.CH;
public Alpha3Code Alpha3Code => Alpha3Code.CHE;
public int NumericCode => 756;
public string[] TLD => new [] { ".ch" };
public Region Region => Region.Europe;
public SubRegion SubRegion => SubRegion.WesternEurope;
public Alpha2Code[] BorderCountrys => new Alpha2Code[]
{
Alpha2Code.AT,
Alpha2Code.FR,
Alpha2Code.IT,
Alpha2Code.LI,
Alpha2Code.DE,
};
public string[] Currencies => new [] { "CHF" };
public string[] CallingCodes => new [] { "41" };
}
}
| 44.802469 | 62 | 0.602921 | [
"MIT"
] | MrGrabazu/Nager.Country | src/Nager.Country/CountryInfo/SwitzerlandInfo.cs | 3,798 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LinqToDB;
using LinqToDB.Data;
namespace Reactive.Streams.Helpers
{
public class Linq2DbContextLifetime<T,TDc> :
IAsyncEnumerableContextLifetime<T>,
IEnumerableContextLifetime<T>
where TDc:DataConnection
{
private readonly Func<TDc, IQueryable<T>> _qp;
private readonly TDc _dcp;
public Linq2DbContextLifetime(
Func<TDc> dataConnectionProducer,
Func<TDc, IQueryable<T>> queryableProducer)
{
_dcp = dataConnectionProducer();
_qp = queryableProducer;
}
public ValueTask DisposeAsync()
{
_dcp?.Dispose();
return new ValueTask();
}
public IEnumerable<T> GetEnumerable()
{
return _qp(_dcp);
}
public IAsyncEnumerable<T> GetAsyncEnumerable()
{
return _qp(_dcp).AsAsyncEnumerable();
}
}
} | 25.243902 | 55 | 0.604831 | [
"Apache-2.0"
] | to11mtm/Akka.Streams.Linq2Db | src/Reactive.Streams.Helpers.Linq2Db/Linq2DbQueryable/Linq2DbContextLifetime.cs | 1,037 | C# |
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
namespace STB_Modeling_Techniques.DEISProject.ODEDataModel.ThriftContract
{
public enum TDDIAssertionUnionType
{
AUTClaim = 0,
AUTAbstractAssertedRelationship = 1,
}
}
| 20.125 | 73 | 0.729814 | [
"MIT"
] | DEIS-Project-EU/DDI-Scripting-Tools | ODE_Tooladapter/ThriftContract/ODEThriftContract/gen_Thrift_ODE/csharp/STB_Modeling_Techniques/DEISProject/ODEDataModel/ThriftContract/TDDIAssertionUnionType.cs | 322 | C# |
using System;
using System.Data;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.WebControls;
using Amns.GreyFox.Web.UI.WebControls;
namespace Amns.Tessen.Web.UI.WebControls
{
/// <summary>
/// Default web editor for DojoAccessControlGroup.
/// </summary>
[ToolboxData("<DojoAccessControlGroup:DojoAccessControlGroupView runat=server></{0}:DojoAccessControlGroupView>")]
public class DojoAccessControlGroupView : TableWindow, INamingContainer
{
private int dojoAccessControlGroupID;
private DojoAccessControlGroup dojoAccessControlGroup;
#region Private Control Fields for _system Folder
private Literal ltCreateDate = new Literal();
private Literal ltModifyDate = new Literal();
#endregion
#region Private Control Fields for General Folder
private Literal ltName = new Literal();
private Literal ltDescription = new Literal();
private Literal ltOrderNum = new Literal();
#endregion
#region Private Control Fields for Allowed Folder
private Literal ltAllowedMemberType1 = new Literal();
private Literal ltAllowedMemberType2 = new Literal();
private Literal ltAllowedMemberType3 = new Literal();
private Literal ltAllowedMemberType4 = new Literal();
private Literal ltAllowedMemberType5 = new Literal();
#endregion
#region Private Control Fields for Denied Folder
private Literal ltDeniedMemberType1 = new Literal();
private Literal ltDeniedMemberType2 = new Literal();
private Literal ltDeniedMemberType3 = new Literal();
private Literal ltDeniedMemberType4 = new Literal();
private Literal ltDeniedMemberType5 = new Literal();
#endregion
private Button btOk = new Button();
private Button btDelete = new Button();
#region Public Control Properties
[Bindable(true), Category("Data"), DefaultValue(0)]
public int DojoAccessControlGroupID
{
get
{
return dojoAccessControlGroupID;
}
set
{
dojoAccessControlGroupID = value;
}
}
#endregion
protected override void CreateChildControls()
{
Controls.Clear();
#region Child Controls for _system Folder
ltCreateDate.EnableViewState = false;
Controls.Add(ltCreateDate);
ltModifyDate.EnableViewState = false;
Controls.Add(ltModifyDate);
#endregion
#region Child Controls for General Folder
ltName.EnableViewState = false;
Controls.Add(ltName);
ltDescription.EnableViewState = false;
Controls.Add(ltDescription);
ltOrderNum.EnableViewState = false;
Controls.Add(ltOrderNum);
#endregion
#region Child Controls for Allowed Folder
ltAllowedMemberType1.EnableViewState = false;
Controls.Add(ltAllowedMemberType1);
ltAllowedMemberType2.EnableViewState = false;
Controls.Add(ltAllowedMemberType2);
ltAllowedMemberType3.EnableViewState = false;
Controls.Add(ltAllowedMemberType3);
ltAllowedMemberType4.EnableViewState = false;
Controls.Add(ltAllowedMemberType4);
ltAllowedMemberType5.EnableViewState = false;
Controls.Add(ltAllowedMemberType5);
#endregion
#region Child Controls for Denied Folder
ltDeniedMemberType1.EnableViewState = false;
Controls.Add(ltDeniedMemberType1);
ltDeniedMemberType2.EnableViewState = false;
Controls.Add(ltDeniedMemberType2);
ltDeniedMemberType3.EnableViewState = false;
Controls.Add(ltDeniedMemberType3);
ltDeniedMemberType4.EnableViewState = false;
Controls.Add(ltDeniedMemberType4);
ltDeniedMemberType5.EnableViewState = false;
Controls.Add(ltDeniedMemberType5);
#endregion
btOk.Text = "OK";
btOk.Width = Unit.Pixel(72);
btOk.EnableViewState = false;
btOk.Click += new EventHandler(ok_Click);
Controls.Add(btOk);
btDelete.Text = "Delete";
btDelete.Width = Unit.Pixel(72);
btDelete.EnableViewState = false;
btDelete.Click += new EventHandler(delete_Click);
Controls.Add(btDelete);
ChildControlsCreated = true;
}
#region ok_Click Save and Update Method
protected void ok_Click(object sender, EventArgs e)
{
OnOkClicked(EventArgs.Empty);
}
#endregion
protected void delete_Click(object sender, EventArgs e)
{
this.OnDeleteClicked(EventArgs.Empty);
}
public event EventHandler OkClicked;
protected virtual void OnOkClicked(EventArgs e)
{
if(OkClicked != null)
OkClicked(this, e);
}
public event EventHandler DeleteClicked;
protected virtual void OnDeleteClicked(EventArgs e)
{
if(DeleteClicked != null)
DeleteClicked(this, e);
}
protected override void OnInit(EventArgs e)
{
columnCount = 2;
features = TableWindowFeatures.DisableContentSeparation |
TableWindowFeatures.WindowPrinter;
}
protected override void OnPreRender(EventArgs e)
{
if(dojoAccessControlGroupID != 0)
{
dojoAccessControlGroup = new DojoAccessControlGroup(dojoAccessControlGroupID);
#region Bind _system Folder
//
// Set Field Entries
//
ltCreateDate.Text = dojoAccessControlGroup.CreateDate.ToString();
ltModifyDate.Text = dojoAccessControlGroup.ModifyDate.ToString();
//
// Set Children Selections
//
#endregion
#region Bind General Folder
//
// Set Field Entries
//
ltName.Text = dojoAccessControlGroup.Name.ToString();
ltDescription.Text = dojoAccessControlGroup.Description.ToString();
ltOrderNum.Text = dojoAccessControlGroup.OrderNum.ToString();
//
// Set Children Selections
//
#endregion
#region Bind Allowed Folder
//
// Set Field Entries
//
//
// Set Children Selections
//
// AllowedMemberType1
if(dojoAccessControlGroup.AllowedMemberType1 != null)
ltAllowedMemberType1.Text = dojoAccessControlGroup.AllowedMemberType1.ToString();
else
ltAllowedMemberType1.Text = string.Empty;
// AllowedMemberType2
if(dojoAccessControlGroup.AllowedMemberType2 != null)
ltAllowedMemberType2.Text = dojoAccessControlGroup.AllowedMemberType2.ToString();
else
ltAllowedMemberType2.Text = string.Empty;
// AllowedMemberType3
if(dojoAccessControlGroup.AllowedMemberType3 != null)
ltAllowedMemberType3.Text = dojoAccessControlGroup.AllowedMemberType3.ToString();
else
ltAllowedMemberType3.Text = string.Empty;
// AllowedMemberType4
if(dojoAccessControlGroup.AllowedMemberType4 != null)
ltAllowedMemberType4.Text = dojoAccessControlGroup.AllowedMemberType4.ToString();
else
ltAllowedMemberType4.Text = string.Empty;
// AllowedMemberType5
if(dojoAccessControlGroup.AllowedMemberType5 != null)
ltAllowedMemberType5.Text = dojoAccessControlGroup.AllowedMemberType5.ToString();
else
ltAllowedMemberType5.Text = string.Empty;
#endregion
#region Bind Denied Folder
//
// Set Field Entries
//
//
// Set Children Selections
//
// DeniedMemberType1
if(dojoAccessControlGroup.DeniedMemberType1 != null)
ltDeniedMemberType1.Text = dojoAccessControlGroup.DeniedMemberType1.ToString();
else
ltDeniedMemberType1.Text = string.Empty;
// DeniedMemberType2
if(dojoAccessControlGroup.DeniedMemberType2 != null)
ltDeniedMemberType2.Text = dojoAccessControlGroup.DeniedMemberType2.ToString();
else
ltDeniedMemberType2.Text = string.Empty;
// DeniedMemberType3
if(dojoAccessControlGroup.DeniedMemberType3 != null)
ltDeniedMemberType3.Text = dojoAccessControlGroup.DeniedMemberType3.ToString();
else
ltDeniedMemberType3.Text = string.Empty;
// DeniedMemberType4
if(dojoAccessControlGroup.DeniedMemberType4 != null)
ltDeniedMemberType4.Text = dojoAccessControlGroup.DeniedMemberType4.ToString();
else
ltDeniedMemberType4.Text = string.Empty;
// DeniedMemberType5
if(dojoAccessControlGroup.DeniedMemberType5 != null)
ltDeniedMemberType5.Text = dojoAccessControlGroup.DeniedMemberType5.ToString();
else
ltDeniedMemberType5.Text = string.Empty;
#endregion
text = "View kitTessen_AccessControlGroups - " + dojoAccessControlGroup.ToString();
}
}
protected override void RenderContent(HtmlTextWriter output)
{
output.WriteFullBeginTag("tr");
RenderRow("row1", "DojoAccessControlGroup ID", dojoAccessControlGroupID.ToString());
output.WriteEndTag("tr");
render_systemFolder(output);
renderGeneralFolder(output);
renderAllowedFolder(output);
renderDeniedFolder(output);
//
// Render OK/Cancel Buttons
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("colspan", "2");
output.WriteAttribute("align", "right");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
btOk.RenderControl(output);
if(DeleteClicked != null)
{
output.Write(" ");
btDelete.RenderControl(output);
}
output.WriteEndTag("td");
output.WriteEndTag("tr");
}
#region Render _system Folder
private void render_systemFolder(HtmlTextWriter output)
{
//
// Render _system Folder
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", SubHeaderCssClass);
output.WriteAttribute("colspan", "2");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("System Folder");
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render CreateDate
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("CreateDate");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltCreateDate.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render ModifyDate
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("ModifyDate");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltModifyDate.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
}
#endregion
#region Render General Folder
private void renderGeneralFolder(HtmlTextWriter output)
{
//
// Render General Folder
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", SubHeaderCssClass);
output.WriteAttribute("colspan", "2");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("General");
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render Name
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Name");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltName.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render Description
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Description");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltDescription.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render OrderNum
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("OrderNum");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltOrderNum.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
}
#endregion
#region Render Allowed Folder
private void renderAllowedFolder(HtmlTextWriter output)
{
//
// Render Allowed Folder
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", SubHeaderCssClass);
output.WriteAttribute("colspan", "2");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Allowed");
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render AllowedMemberType1
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("AllowedMemberType1");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltAllowedMemberType1.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render AllowedMemberType2
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("AllowedMemberType2");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltAllowedMemberType2.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render AllowedMemberType3
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("AllowedMemberType3");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltAllowedMemberType3.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render AllowedMemberType4
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("AllowedMemberType4");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltAllowedMemberType4.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render AllowedMemberType5
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("AllowedMemberType5");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltAllowedMemberType5.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
}
#endregion
#region Render Denied Folder
private void renderDeniedFolder(HtmlTextWriter output)
{
//
// Render Denied Folder
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", SubHeaderCssClass);
output.WriteAttribute("colspan", "2");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Denied");
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render DeniedMemberType1
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("DeniedMemberType1");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltDeniedMemberType1.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render DeniedMemberType2
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("DeniedMemberType2");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltDeniedMemberType2.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render DeniedMemberType3
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("DeniedMemberType3");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltDeniedMemberType3.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render DeniedMemberType4
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("DeniedMemberType4");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltDeniedMemberType4.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
//
// Render DeniedMemberType5
//
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("DeniedMemberType5");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.Write(HtmlTextWriter.TagRightChar);
ltDeniedMemberType5.RenderControl(output);
output.WriteEndTag("td");
output.WriteEndTag("tr");
}
#endregion
protected override void LoadViewState(object savedState)
{
if(savedState != null)
{
object[] myState = (object[]) savedState;
if(myState[0] != null)
base.LoadViewState(myState[0]);
if(myState[1] != null)
dojoAccessControlGroupID = (int) myState[1];
}
}
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
object[] myState = new object[2];
myState[0] = baseState;
myState[1] = dojoAccessControlGroupID;
return myState;
}
}
}
| 26.557719 | 115 | 0.713014 | [
"MIT"
] | rahodges/Tessen | Amns.Tessen/DataObjects/DojoAccessControlGroupView.cs | 19,095 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace ICSharpCode.AvalonEdit.Editing
{
/// <summary>
/// Margin for use with the text area.
/// A vertical dotted line to separate the line numbers from the text view.
/// </summary>
public static class DottedLineMargin
{
static readonly object tag = new object();
/// <summary>
/// Creates a vertical dotted line to separate the line numbers from the text view.
/// </summary>
public static UIElement Create()
{
Line line = new Line {
X1 = 0,
Y1 = 0,
X2 = 0,
Y2 = 1,
StrokeDashArray = { 0, 2 },
Stretch = Stretch.Fill,
StrokeThickness = 1,
StrokeDashCap = PenLineCap.Round,
Margin = new Thickness(2, 0, 2, 0),
Tag = tag
};
return line;
}
/// <summary>
/// Gets whether the specified UIElement is the result of a DottedLineMargin.Create call.
/// </summary>
public static bool IsDottedLineMargin(UIElement element)
{
Line l = element as Line;
return l != null && l.Tag == tag;
}
}
}
| 34.3125 | 93 | 0.712659 | [
"MIT"
] | Acorisoft/AvalonEdit | ICSharpCode.AvalonEdit/Editing/DottedLineMargin.cs | 2,198 | C# |
using Scada.Comm;
using System.Reflection;
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.
[assembly: AssemblyTitle("ScadaCommCommon")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rapid SCADA")]
[assembly: AssemblyCopyright("Copyright © 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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("4578ffdc-f2b7-47e6-8d7c-2c3a290a0f84")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(CommUtils.AppVersion)]
[assembly: AssemblyFileVersion(CommUtils.AppVersion)]
| 37.945946 | 84 | 0.752137 | [
"Apache-2.0"
] | JoygenZhang/Rapid-SCADA-sources | ScadaComm/ScadaCommCommon/Properties/AssemblyInfo.cs | 1,407 | C# |
#region 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
using Bugbear.Core.Graph;
using Gremlin.Net.Structure;
using System.Collections.Generic;
namespace Bugbear.Graph.Wrapper
{
public interface IGraphDB : IBuildGraphDB
{
#region Getters
IReadOnlyList<Vertex> Vertices(params object[] vertexIds);
IReadOnlyList<Edge> Edges(params object[] edgeIds);
IReadOnlyDictionary<object, VertexProperty> VertexProps(string propertyKey);
IReadOnlyDictionary<object, Property> EdgeProps(string propertyKey);
#endregion
}
}
| 31.627907 | 84 | 0.738235 | [
"Apache-2.0"
] | zebmason/Bugbear | Bugbear.Graph/Wrapper/IGraphDB.cs | 1,362 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CoreDemo.Controllers
{
public class DashboardController : Controller
{
[AllowAnonymous]
public IActionResult Index()
{
return View();
}
}
}
| 18.8 | 49 | 0.638298 | [
"MIT"
] | murat1347/DotNet-Core-Blog | CoreDemo/Controllers/DashboardController.cs | 284 | C# |
namespace Zinnia.Tracking.Velocity
{
using Malimbe.BehaviourStateRequirementMethod;
using Malimbe.MemberClearanceMethod;
using Malimbe.PropertySerializationAttribute;
using Malimbe.XmlDocumentationAttribute;
using System;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// Emits the velocities of a given <see cref="VelocityTracker"/>.
/// </summary>
public class VelocityEmitter : MonoBehaviour
{
/// <summary>
/// Defines the event with the <see cref="Vector3"/>.
/// </summary>
[Serializable]
public class Vector3UnityEvent : UnityEvent<Vector3>
{
}
/// <summary>
/// Defines the event with the <see cref="float"/>.
/// </summary>
[Serializable]
public class FloatUnityEvent : UnityEvent<float>
{
}
/// <summary>
/// The source <see cref="VelocityTracker"/> to receive the velocity data from.
/// </summary>
[Serialized, Cleared]
[field: DocumentedByXml]
public VelocityTracker Source { get; set; }
/// <summary>
/// Emitted when the Tracked Velocity is emitted.
/// </summary>
[DocumentedByXml]
public Vector3UnityEvent VelocityEmitted = new Vector3UnityEvent();
/// <summary>
/// Emitted when the Tracked Speed is emitted.
/// </summary>
[DocumentedByXml]
public FloatUnityEvent SpeedEmitted = new FloatUnityEvent();
/// <summary>
/// Emitted when the Tracked Angular Velocity is emitted.
/// </summary>
[DocumentedByXml]
public Vector3UnityEvent AngularVelocityEmitted = new Vector3UnityEvent();
/// <summary>
/// Emitted when the Tracked Angular Speed is emitted.
/// </summary>
[DocumentedByXml]
public FloatUnityEvent AngularSpeedEmitted = new FloatUnityEvent();
/// <summary>
/// Emits the Velocity of the Tracked Velocity.
/// </summary>
[RequiresBehaviourState]
public virtual void EmitVelocity()
{
if (Source == null)
{
return;
}
VelocityEmitted?.Invoke(Source.GetVelocity());
}
/// <summary>
/// Emits the Speed of the Tracked Velocity.
/// </summary>
[RequiresBehaviourState]
public virtual void EmitSpeed()
{
if (Source == null)
{
return;
}
SpeedEmitted?.Invoke(Source.GetVelocity().magnitude);
}
/// <summary>
/// Emits the Angular Velocity of the Tracked Velocity.
/// </summary>
[RequiresBehaviourState]
public virtual void EmitAngularVelocity()
{
if (Source == null)
{
return;
}
AngularVelocityEmitted?.Invoke(Source.GetAngularVelocity());
}
/// <summary>
/// Emits the Angular Velocity of the Tracked Velocity.
/// </summary>
[RequiresBehaviourState]
public virtual void EmitAngularSpeed()
{
if (Source == null)
{
return;
}
AngularSpeedEmitted?.Invoke(Source.GetAngularVelocity().magnitude);
}
/// <summary>
/// Emits the Velocity, Speed, Angular Velocity and Angular Speed of the Tracked Velocity.
/// </summary>
public virtual void EmitAll()
{
EmitVelocity();
EmitSpeed();
EmitAngularVelocity();
EmitAngularSpeed();
}
}
} | 30.267717 | 99 | 0.532518 | [
"MIT"
] | ChrisJoshNow/Zinnia.Unity | Runtime/Tracking/Velocity/VelocityEmitter.cs | 3,846 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace UserScriptLib
{
/// <summary>
/// Another class to see if we can debug across two scripts at the same time.
/// </summary>
internal class AnotherClassToTestTwoScriptsAtATime
{
// TODO Create a method in here. Use the new method in MyClass. Save, recompile and debug.
}
}
| 26.4 | 99 | 0.669192 | [
"MIT"
] | robdunbar/alternet-script-debugger | UserScriptLib/AnotherClassToTestTwoScriptsAtATime.cs | 398 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SimpleWeather.HERE
{
public class Nwsalerts
{
public Warning[] warning { get; set; }
public Watch[] watch { get; set; }
}
public class Warning
{
public string type { get; set; }
public string description { get; set; }
public int severity { get; set; }
public string message { get; set; }
//public County[] county { get; set; }
//public object[] location { get; set; }
public string name { get; set; }
public DateTime validFromTimeLocal { get; set; }
public DateTime validUntilTimeLocal { get; set; }
public string country { get; set; }
public string state { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
}
/*
public class County
{
public string value { get; set; }
public string country { get; set; }
public string countryName { get; set; }
public string state { get; set; }
public string stateName { get; set; }
public string name { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
}
*/
public class Watch
{
public string type { get; set; }
public string description { get; set; }
public int severity { get; set; }
public string message { get; set; }
//public Zone[] zone { get; set; }
//public object[] location { get; set; }
public string name { get; set; }
public DateTime validFromTimeLocal { get; set; }
public DateTime validUntilTimeLocal { get; set; }
public string country { get; set; }
public string state { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
}
/*
public class Zone
{
public string value { get; set; }
public string country { get; set; }
public string countryName { get; set; }
public string state { get; set; }
public string stateName { get; set; }
public string name { get; set; }
public float latitude { get; set; }
public float longitude { get; set; }
}
*/
}
| 30.866667 | 57 | 0.566307 | [
"Apache-2.0"
] | SimpleAppProjects/SimpleWeather-Windows | SimpleWeather.Shared/HERE/NWSAlerts.cs | 2,317 | C# |
//-----------------------------------------------------------------------
// <copyright file="GestureTouchesUtility.cs" company="Google LLC">
//
// Copyright 2018 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore.Examples.ObjectManipulationInternal
{
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
// Set up touch input propagation while using Instant Preview in the editor.
using Input = GoogleARCore.InstantPreviewInput;
#endif
/// <summary>
/// Singleton used by Gesture's and GestureRecognizer's to interact with touch input.
///
/// 1. Makes it easy to find touches by fingerId.
/// 2. Allows Gestures to Lock/Release fingerIds.
/// 3. Wraps Input.Touches so that it works both in editor and on device.
/// 4. Provides helper functions for converting touch coordinates
/// and performing raycasts based on touches.
/// </summary>
internal class GestureTouchesUtility
{
private const float _edgeThresholdInches = 0.1f;
private static GestureTouchesUtility _instance;
private HashSet<int> _retainedFingerIds = new HashSet<int>();
/// <summary>
/// Initializes a new instance of the GestureTouchesUtility class. Intended for private use
/// since this class is a Singleton.
/// </summary>
private GestureTouchesUtility()
{
}
/// <summary>
/// Try to find a touch for a particular finger id.
/// </summary>
/// <param name="fingerId">The finger id to find the touch.</param>
/// <param name="touch">The output touch.</param>
/// <returns>True if a touch was found.</returns>
public static bool TryFindTouch(int fingerId, out Touch touch)
{
for (int i = 0; i < Input.touches.Length; i++)
{
if (Input.touches[i].fingerId == fingerId)
{
touch = Input.touches[i];
return true;
}
}
touch = new Touch();
return false;
}
/// <summary>
/// Converts Pixels to Inches.
/// </summary>
/// <param name="pixels">The amount to convert in pixels.</param>
/// <returns>The converted amount in inches.</returns>
public static float PixelsToInches(float pixels)
{
return pixels / Screen.dpi;
}
/// <summary>
/// Converts Inches to Pixels.
/// </summary>
/// <param name="inches">The amount to convert in inches.</param>
/// <returns>The converted amount in pixels.</returns>
public static float InchesToPixels(float inches)
{
return inches * Screen.dpi;
}
/// <summary>
/// Used to determine if a touch is off the edge of the screen based on some slop.
/// Useful to prevent accidental touches from simply holding the device from causing
/// confusing behavior.
/// </summary>
/// <param name="touch">The touch to check.</param>
/// <returns>True if the touch is off screen edge.</returns>
public static bool IsTouchOffScreenEdge(Touch touch)
{
float slopPixels = InchesToPixels(_edgeThresholdInches);
bool result = touch.position.x <= slopPixels;
result |= touch.position.y <= slopPixels;
result |= touch.position.x >= Screen.width - slopPixels;
result |= touch.position.y >= Screen.height - slopPixels;
return result;
}
/// <summary>
/// Performs a Raycast from the camera.
/// </summary>
/// <param name="screenPos">The screen position to perform the raycast from.</param>
/// <param name="result">The RaycastHit result.</param>
/// <returns>True if an object was hit.</returns>
public static bool RaycastFromCamera(Vector2 screenPos, out RaycastHit result)
{
if (Camera.main == null)
{
result = new RaycastHit();
return false;
}
Ray ray = Camera.main.ScreenPointToRay(screenPos);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
result = hit;
return true;
}
result = hit;
return false;
}
/// <summary>
/// Locks a finger Id.
/// </summary>
/// <param name="fingerId">The finger id to lock.</param>
public static void LockFingerId(int fingerId)
{
if (!IsFingerIdRetained(fingerId))
{
GetInstance()._retainedFingerIds.Add(fingerId);
}
}
/// <summary>
/// Releases a finger Id.
/// </summary>
/// <param name="fingerId">The finger id to release.</param>
public static void ReleaseFingerId(int fingerId)
{
if (IsFingerIdRetained(fingerId))
{
GetInstance()._retainedFingerIds.Remove(fingerId);
}
}
/// <summary>
/// Returns true if the finger Id is retained.
/// </summary>
/// <param name="fingerId">The finger id to check.</param>
/// <returns>True if the finger is retained.</returns>
public static bool IsFingerIdRetained(int fingerId)
{
return GetInstance()._retainedFingerIds.Contains(fingerId);
}
/// <summary>
/// Initializes the GestureTouchesUtility singleton if needed and returns a valid instance.
/// </summary>
/// <returns>The instance of GestureTouchesUtility.</returns>
private static GestureTouchesUtility GetInstance()
{
if (_instance == null)
{
_instance = new GestureTouchesUtility();
}
return _instance;
}
}
}
| 35.015789 | 99 | 0.566812 | [
"Apache-2.0"
] | jiyu-park/arcore-unity-sdk | Assets/GoogleARCore/Examples/ObjectManipulation/Scripts/Gestures/GestureTouchesUtility.cs | 6,653 | C# |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TheLongRun.Common.Orchestration.Attributes;
namespace TheLongRun.Common.Orchestration
{
/// <summary>
/// A base class for any QUERY orchestrator functions
/// </summary>
public class EventStreamBackedQueryOrchestrator
: EventStreamBackedOrchestratorBase,
IEventStreamBackedOrchestrator,
IQueryRunner,
IIdentifierGroupRunner,
IProjectionRunner
{
public bool IsComplete { get; }
/// <summary>
/// Orchestrator classification type is a QUERY
/// </summary>
public string ClassificationTypeName
{
get
{
return EventStreamBackedQueryOrchestrator.ClassifierTypeName;
}
}
private readonly string _queryName;
public string Name
{
get
{
return _queryName;
}
}
private readonly Guid _uniqueIdentifier;
public Guid UniqueIdentifier
{
get
{
return _uniqueIdentifier;
}
}
public IEventStreamBackedOrchestratorContext Context { get; set; }
/// <summary>
/// The identity by which any called orchestrations can call back with the
/// results (a return address style identity)
/// </summary>
public OrchestrationCallbackIdentity CallbackIdentity
{
get
{
return OrchestrationCallbackIdentity.Create(
OrchestrationCallbackIdentity.OrchestrationClassifications.Query ,
Name ,
UniqueIdentifier);
}
}
protected internal EventStreamBackedQueryOrchestrator(Guid uniqueIdentifier,
string instanceName = null,
OrchestrationCallbackIdentity calledBy = null)
{
if (uniqueIdentifier.Equals(Guid.Empty))
{
_uniqueIdentifier = Guid.NewGuid();
}
else
{
_uniqueIdentifier = uniqueIdentifier;
}
_queryName = instanceName ;
if (null != calledBy)
{
base.CalledBy = calledBy;
}
}
public static string ClassifierTypeName
{
get
{
return @"QUERY";
}
}
public static EventStreamBackedQueryOrchestrator CreateFromAttribute(EventStreamBackedQueryOrchestrationTriggerAttribute attr)
{
if (attr.InstanceIdentity.Equals(Guid.Empty))
{
attr.InstanceIdentity = Guid.NewGuid();
}
return new EventStreamBackedQueryOrchestrator(attr.InstanceIdentity, attr.InstanceName);
}
#region Query Runner
public async Task<IQueryResponse> RunQueryAsync(string queryName,
string instanceId,
JObject queryParameters,
DateTime? asOfDate = null)
{
if (string.IsNullOrWhiteSpace(queryName))
{
throw new ArgumentException($"Query name not set");
}
if (string.IsNullOrEmpty(instanceId))
{
instanceId = Guid.NewGuid().ToString("N");
}
// TODO: Build a callout/callback definition
// TODO: Spawn the projection
return await Task.FromException<IQueryResponse>(new NotImplementedException());
}
#endregion
#region Projection Runner
public async Task<IProjectionResponse> RunProjectionAsync(string projectionName,
string instanceId,
string aggregateKey,
DateTime? asOfDate = null,
int? asOfSequence = null)
{
// Validate the inputs...
if (string.IsNullOrWhiteSpace(projectionName))
{
throw new ArgumentException($"Projection name not set");
}
if (string.IsNullOrEmpty(instanceId))
{
instanceId = Guid.NewGuid().ToString("N");
}
if (string.IsNullOrWhiteSpace(aggregateKey))
{
throw new ArgumentException($"Projection requires a valid aggregate key");
}
// TODO: Build a callout/callback definition
// TODO: Spawn the projection
return await Task.FromException<IProjectionResponse>(new NotImplementedException());
}
#endregion
#region Identifier Group Runner
public async Task<IEnumerable<IIdentifierGroupMemberResponse>> GetIdentifierGroupMembersAsync(string groupName,
string instanceId,
DateTime? asOfDate = null)
{
if (string.IsNullOrWhiteSpace(groupName))
{
throw new ArgumentException($"Group name not set");
}
if (string.IsNullOrEmpty(instanceId))
{
instanceId = Guid.NewGuid().ToString("N");
}
// TODO: Build a callout/callback definition
// TODO: Spawn the projection
return await Task.FromException<IEnumerable<IIdentifierGroupMemberResponse>>(new NotImplementedException());
}
#endregion
}
}
| 29.715054 | 134 | 0.563597 | [
"Unlicense"
] | MerrionComputing/AzureFunctions-TheLongRun-Leagues | TheLongRun.Common/Orchestration/EventStreamBackedQueryOrchestrator.cs | 5,529 | C# |
using System;
using System.ServiceModel;
using bv.common.Configuration;
using bv.common.Core;
using bv.model.BLToolkit;
using bv.model.Model.Validators;
using eidss.model.Core;
using eidss.model.Resources;
using eidss.model.Trace;
namespace eidss.model.WcfService
{
public abstract class ServiceHostKeeper : IDisposable
{
private bool m_IsInitialized;
private ServiceHost m_Host;
private bool m_bHostExists = false;
private TraceHelper m_Trace;
protected const string TraceTitle = @"WCF Service Host";
protected abstract Type ServiceType { get; }
protected abstract string DefaultServiceHostURL { get; }
protected abstract string ServiceHostURLConfigName { get; }
protected abstract string TraceCategory { get; }
protected TraceHelper Trace
{
get { return m_Trace ?? (m_Trace = new TraceHelper(TraceCategory)); }
}
public void Open()
{
Initialize();
if (m_bHostExists)
m_Host.Open();
Trace.TraceInfo(TraceTitle, @"Service Host Opened");
OpenExtender();
}
public void Close()
{
if (m_bHostExists && m_Host == null)
{
throw new ApplicationException(@"Service host already closed.");
}
if (m_bHostExists)
m_Host.Close();
m_Host = null;
Trace.TraceInfo(TraceTitle, @"Service Host Closed");
CloseExtender();
}
public void Dispose()
{
if ((m_Host != null) && (m_Host.State == CommunicationState.Opened))
{
Close();
}
}
private void Initialize()
{
if (!m_IsInitialized)
{
try
{
InitEidssCore();
Trace.Trace(TraceTitle, "EIDSS core initialized.");
DataBaseChecker.CheckDbConnection();
InitServiceHost();
}
catch (Exception ex)
{
Trace.TraceCritical(ex);
throw;
}
m_IsInitialized = true;
}
}
protected virtual void OpenExtender()
{}
protected virtual void CloseExtender()
{ }
protected virtual void InitEidssCore()
{
DbManagerFactory.SetSqlFactory(new ConnectionCredentials().ConnectionString);
EidssUserContext.Init();
Localizer.MenuMessages = EidssMenu.Instance;
BaseFieldValidator.FieldCaptions = EidssFields.Instance;
}
protected virtual void InitServiceHost()
{
string url = Config.GetSetting(ServiceHostURLConfigName, DefaultServiceHostURL);
if (string.IsNullOrEmpty(url))
{
string message = string.Format(@"'{0}' parameter not congigured in AppSettings section.", ServiceHostURLConfigName);
throw new ApplicationException(message);
}
m_Host = new ServiceHost(ServiceType, new Uri(url));
m_bHostExists = true;
Trace.TraceInfo(TraceTitle, string.Format(@"Service Host Configured at URL {0}", url));
}
}
} | 28.745902 | 133 | 0.532079 | [
"BSD-2-Clause"
] | EIDSS/EIDSS-Legacy | EIDSS v6/eidss.core/WcfService/ServiceHostKeeper.cs | 3,509 | C# |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) 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.
*
* 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
namespace XenAPI
{
public enum network_default_locking_mode
{
unlocked, disabled, unknown
}
public static class network_default_locking_mode_helper
{
public static string ToString(network_default_locking_mode x)
{
switch (x)
{
case network_default_locking_mode.unlocked:
return "unlocked";
case network_default_locking_mode.disabled:
return "disabled";
default:
return "unknown";
}
}
}
}
| 35.661017 | 71 | 0.671578 | [
"BSD-2-Clause"
] | GaborApatiNagy/xenadmin | XenModel/XenAPI/network_default_locking_mode.cs | 2,104 | C# |
#pragma checksum "E:\diploma_project_here\SoftSpace_web\cancel\View\User\YourOrders.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8e1786631bae50bfd2e366b1387c7989bb0dfcac"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.cancel_View_User_YourOrders), @"mvc.1.0.view", @"/cancel/View/User/YourOrders.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/cancel/View/User/YourOrders.cshtml", typeof(AspNetCore.cancel_View_User_YourOrders))]
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;
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"8e1786631bae50bfd2e366b1387c7989bb0dfcac", @"/cancel/View/User/YourOrders.cshtml")]
public class cancel_View_User_YourOrders : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(1, 44, false);
#line 1 "E:\diploma_project_here\SoftSpace_web\cancel\View\User\YourOrders.cshtml"
Write(await Component.InvokeAsync("Menu" , new {}));
#line default
#line hidden
EndContext();
BeginContext(45, 21, true);
WriteLiteral("\r\n<h1>YourOrders</h1>");
EndContext();
}
#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<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 55.87234 | 186 | 0.747906 | [
"MIT"
] | DonEnot/Diplom_SoftSpace | obj/Debug/netcoreapp2.2/Razor/cancel/View/User/YourOrders.g.cshtml.cs | 2,626 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Contas.Extenso.Application.Models;
using Contas.Extenso.Domain.Models;
namespace Contas.Extenso.Application.Interfaces
{
public interface IContaService
{
Task<IEnumerable<Conta>> GetContas();
Task<(int status, string description)> CreateConta(ContaTransfer transfer);
}
} | 28.538462 | 83 | 0.757412 | [
"MIT"
] | NickeManarin/Contas | Extenso/Contas.Extenso.Application/Interfaces/IContaService.cs | 373 | C# |
using System;
using System.Data.Entity;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NUnit.Framework;
using OpenEvent.Test.Factories;
namespace OpenEvent.Test.Services.AnalyticsService
{
[TestFixture]
public class CaptureSearch
{
[Test]
public async Task Should_Capture()
{
await using (var context = new DbContextFactory().CreateContext())
{
var service = new AnalyticsServiceFactory().Create(context);
await service.CaptureSearchAsync(CancellationToken.None, "UniqueSearch", "SearchParam", new Guid("046E876E-D413-45AF-AC2A-552D7AA46C5C"),DateTime.Now);
var searchEvents = context.SearchEvents.AsQueryable();
searchEvents.Should().NotContainNulls();
searchEvents.Should().ContainSingle(x => x.Search == "UniqueSearch" && x.Params == "SearchParam");
}
}
}
} | 34.344828 | 167 | 0.63253 | [
"MIT"
] | Group23Software/OpenEvent | OpenEvent.Test/Services/AnalyticsService/CaptureSearch.cs | 996 | 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 forecast-2018-06-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ForecastService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ForecastService.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListTagsForResource Request Marshaller
/// </summary>
public class ListTagsForResourceRequestMarshaller : IMarshaller<IRequest, ListTagsForResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListTagsForResourceRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListTagsForResourceRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ForecastService");
string target = "AmazonForecast.ListTagsForResource";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-06-26";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetResourceArn())
{
context.Writer.WritePropertyName("ResourceArn");
context.Writer.Write(publicRequest.ResourceArn);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static ListTagsForResourceRequestMarshaller _instance = new ListTagsForResourceRequestMarshaller();
internal static ListTagsForResourceRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListTagsForResourceRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.67619 | 154 | 0.618541 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ForecastService/Generated/Model/Internal/MarshallTransformations/ListTagsForResourceRequestMarshaller.cs | 3,851 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Dale Roberts. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Drawing;
namespace MouseUnSnag
{
public static class GeometryUtil
{
/// <summary>
/// Return the signs of X and Y. This essentially gives us the "component direction" of
/// the point (N.B. the vector length is not "normalized" to a length 1 "unit vector" if
/// both the X and Y components are non-zero).
/// </summary>
/// <param name="p"><see cref="Point"/> of which to get the sign</param>
/// <returns><see cref="Point"/> where X, Y have values corresponding to their sign</returns>
public static Point Sign(Point p) => new Point(Math.Sign(p.X), Math.Sign(p.Y));
/// <summary>
/// Return the magnitude of Point p.
/// </summary>
/// <param name="p"><see cref="Point"/> of which to get the sign</param>
/// <returns><see cref="Point"/> where X, Y have values corresponding to their sign</returns>
public static double Magnitude(Point p) => Math.Sqrt(p.X * p.X + p.Y * p.Y);
/// <summary>
/// "Direction" vector from P1 to P2. X/Y of returned point will have values
/// of -1, 0, or 1 only (vector is not normalized to length 1).
/// </summary>
/// <param name="p1"><see cref="Point"/></param>
/// <param name="p2"><see cref="Point"/></param>
/// <returns><see cref="Point"/> with X, Y having values corresponding to their sign</returns>
public static Point Direction(Point p1, Point p2) => Sign(p2 - (Size)p1);
/// <summary>
/// If P is anywhere inside R, then OutsideDistance() returns (0,0).
/// Otherwise, it returns the (x,y) delta (sign is preserved) from P to the
/// nearest edge/corner of R.
/// </summary>
/// <param name="r"><see cref="Rectangle"/></param>
/// <param name="p"><see cref="Point"/></param>
/// <returns>Distance</returns>
public static int OutsideXDistance(Rectangle r, Point p) => Math.Max(Math.Min(0, p.X - r.Left), p.X - r.Right + 1); // For Right we must correct by 1, since the Rectangle Right is one larger than the largest valid pixel
/// <summary>
/// If P is anywhere inside R, then OutsideDistance() returns (0,0).
/// Otherwise, it returns the (x,y) delta (sign is preserved) from P to the
/// nearest edge/corner of R.
/// </summary>
/// <param name="r"><see cref="Rectangle"/></param>
/// <param name="p"><see cref="Point"/></param>
/// <returns>Distance</returns>
public static int OutsideYDistance(Rectangle r, Point p) => Math.Max(Math.Min(0, p.Y - r.Top), p.Y - r.Bottom + 1); // For Bottom we must correct by 1, since the Rectangle Bottom is one larger than the largest valid pixel
/// <summary>
/// If P is anywhere inside R, then OutsideDistance() returns (0,0).
/// Otherwise, it returns the (x,y) delta (sign is preserved) from P to the
/// nearest edge/corner of R.
/// </summary>
/// <param name="r"><see cref="Rectangle"/></param>
/// <param name="p"><see cref="Point"/></param>
/// <returns><see cref="Point"/> where X and Y represents the distance from the rectangle</returns>
public static Point OutsideDistance(Rectangle r, Point p) => new Point(OutsideXDistance(r, p), OutsideYDistance(r, p));
/// <summary>
/// This is sort-of the "opposite" of OutsideDistance. In a sense it "captures" the point to the
/// boundary/inside of the rectangle, rather than "excluding" it to the exterior of the rectangle.
/// If the point is outside the rectangle, then it returns the closest location on the
/// rectangle boundary to the Point. If Point is inside Rectangle, then it just returns
/// the point.
/// </summary>
/// <param name="r"><see cref="Rectangle"/></param>
/// <param name="p"><see cref="Point"/></param>
/// <returns><see cref="Point"/></returns>
public static Point ClosestBoundaryPoint(this Rectangle r, Point p)
=> new Point(
Math.Max(Math.Min(p.X, r.Right - 1), r.Left),
Math.Max(Math.Min(p.Y, r.Bottom - 1), r.Top));
/// <summary>
/// In which direction(s) is(are) the point outside of the rectangle? If P is
/// inside R, then this returns (0,0). Else X and/or Y can be either -1 or
/// +1, depending on which direction P is outside R.
/// </summary>
/// <param name="r"><see cref="Rectangle"/></param>
/// <param name="p"><see cref="Point"/></param>
/// <returns><see cref="Point"/></returns>
public static Point OutsideDirection(Rectangle r, Point p) => Sign(OutsideDistance(r, p));
/// <summary>
/// In which direction(s) is(are) the rectangle r2 outside of the rectangle r1? If r2
/// overlaps r1, then this returns (0,0). Else X and/or Y can be either -1 or +1, depending
/// on which direction r2 is outside r1. For a rectangle to be diagonal to another rectangle,
/// it must not overlap horizontal or vertically.
/// </summary>
/// <param name="r"><see cref="Rectangle"/></param>
/// <param name="p"><see cref="Point"/></param>
/// <returns><see cref="Point"/></returns>
public static Point OutsideDirection(Rectangle r1, Rectangle r2) => (OverlapX(r1, r2), OverlapY(r1, r2)) switch {
(false, false) => new Point(Math.Sign(r2.Left - r1.Left), Math.Sign(r2.Top - r1.Top)),
(false, true) => new Point(Math.Sign(r2.Left - r1.Left), 0),
(true, false) => new Point(0, Math.Sign(r2.Top - r1.Top)),
(true, true) => new Point(0, 0),
};
/// <summary>
/// Check if both Rectangles overlap in the X Direction
/// </summary>
/// <param name="r1"><see cref="Rectangle"/></param>
/// <param name="r2"><see cref="Rectangle"/></param>
/// <returns></returns>
public static bool OverlapX(Rectangle r1, Rectangle r2) => (r1.Left < r2.Right) && (r1.Right > r2.Left);
/// <summary>
/// Check if both Rectangles overlap in the Y Direction
/// </summary>
/// <param name="r1"><see cref="Rectangle"/></param>
/// <param name="r2"><see cref="Rectangle"/></param>
/// <returns></returns>
public static bool OverlapY(Rectangle r1, Rectangle r2) => (r1.Top < r2.Bottom) && (r1.Bottom > r2.Top);
/// <summary>
/// Rescales the Y coordinate of a point from one rectangle to another. Reference: Top
/// </summary>
/// <param name="p"><see cref="Point"/> to rescale</param>
/// <param name="source">Source <see cref="Rectangle"/></param>
/// <param name="destination">Destination <see cref="Rectangle"/></param>
/// <returns></returns>
public static Point RescaleY(this Point p, Rectangle source, Rectangle destination) => new Point(p.X, ((p.Y - source.Top) * destination.Height / source.Height) + destination.Top);
/// <summary>
/// Rescales the X coordinate of a point from one rectangle to another. Reference: Left
/// </summary>
/// <param name="p"><see cref="Point"/> to rescale</param>
/// <param name="source">Source <see cref="Rectangle"/></param>
/// <param name="destination">Destination <see cref="Rectangle"/></param>
/// <returns></returns>
public static Point RescaleX(this Point p, Rectangle source, Rectangle destination) => new Point(((p.X - source.Left) * destination.Width / source.Width) + destination.Left, p.Y);
}
}
| 53.853333 | 229 | 0.575514 | [
"MIT"
] | MouseUnSnag/MouseUnSnag | MouseUnSnag/GeometryUtil.cs | 8,078 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using UnityEngine;
namespace Peace
{
public class RealTimeWorld : MonoBehaviour
{
public String configLocation = "";
public GameObject tracking;
private Collector _collector;
private World _world;
private Vector3 _position;
private FirstPersonView _view;
private bool _collecting;
private RealTimeWorldStatistics _stats = new RealTimeWorldStatistics();
private Queue<GameObject> _objectPool;
private List<GameObject> _objectsUsed;
private async void RunCollect()
{
_collecting = true;
await _collector.CollectFirstPerson(_world, _view);
UpdateFromCollector();
_collecting = false;
}
private void UpdateFromCollector()
{
_stats.removed = 0;
_stats.added = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = _objectsUsed.Count - 1; i >= 0; --i)
{
GameObject used = _objectsUsed[i];
if (!_collector.HasNode(used.name))
{
_objectsUsed.RemoveAt(i);
used.SetActive(false);
_objectPool.Enqueue(used);
}
}
foreach (var nodeKey in _collector.GetNewNodes())
{
var node = _collector.GetNode(nodeKey);
Mesh mesh = _collector.GetMesh(node.Mesh);
if (mesh != null)
{
GameObject child = AllocateObject(nodeKey);
child.transform.localPosition = new Vector3((float)node.posX, (float)node.posZ, (float)node.posY);
child.transform.localScale = new Vector3((float)node.scaleX, (float)node.scaleZ, (float)node.scaleY);
child.transform.localEulerAngles = new Vector3((float)node.rotX, (float)node.rotZ, (float)node.rotY);
MeshFilter meshFilter = child.GetComponent<MeshFilter>();
meshFilter.sharedMesh = mesh;
MeshRenderer meshRenderer = child.GetComponent<MeshRenderer>();
Material material = _collector.GetMaterial(node.Material);
if (material != null)
{
meshRenderer.material = material;
}
else
{
meshRenderer.material.shader = Shader.Find("Standard");
}
_objectsUsed.Add(child);
}
_stats.added++;
}
sw.Stop();
_stats.updateTime = (float)sw.Elapsed.TotalMilliseconds;
_stats.collectorStats = _collector.LastStats;
}
private GameObject AllocateObject(string name)
{
GameObject obj;
if (_objectPool.Count != 0)
{
obj = _objectPool.Dequeue();
obj.SetActive(true);
obj.name = name;
}
else
{
obj = new GameObject(name);
obj.transform.SetParent(transform);
obj.AddComponent<MeshFilter>();
obj.AddComponent<MeshRenderer>();
}
return obj;
}
// Start is called before the first frame update
void Start()
{
_objectPool = new Queue<GameObject>();
_objectsUsed = new List<GameObject>();
if (configLocation == "")
{
_world = World.CreateDemo("");
}
else
{
_world = new World(configLocation);
}
_collector = new Collector();
_view.eyeResolution = 700;
_view.maxDistance = 10000;
}
void UpdatePosition(Vector3 position)
{
_position = position;
_view.X = position.x;
_view.Y = position.z;
_view.Z = position.y;
}
void Update()
{
Vector3 newPos = tracking.transform.position;
if (Vector3.Distance(newPos, _position) > 10 && !_collecting)
{
UpdatePosition(newPos);
RunCollect();
}
}
}
}
| 30.245161 | 122 | 0.486561 | [
"MIT"
] | Bycob/world | projects/peace/Assets/Peace/Scripts/RealTimeWorld.cs | 4,690 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.IndicesExists1
{
public partial class IndicesExists1YamlTests
{
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TestIndicesExists1Tests : YamlTestsBase
{
[Test]
public void TestIndicesExists1Test()
{
//do indices.exists
this.Do(()=> _client.IndicesExists("test_index"));
//is_false this._status;
this.IsFalse(this._status);
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index", null));
//do indices.exists
this.Do(()=> _client.IndicesExists("test_index"));
//is_true this._status;
this.IsTrue(this._status);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TestIndicesExistsWithLocalFlag2Tests : YamlTestsBase
{
[Test]
public void TestIndicesExistsWithLocalFlag2Test()
{
//do indices.exists
this.Do(()=> _client.IndicesExists("test_index", nv=>nv
.Add("local", @"true")
));
//is_false this._status;
this.IsFalse(this._status);
}
}
}
}
| 20.688525 | 67 | 0.701268 | [
"MIT"
] | amitstefen/elasticsearch-net | src/Tests/Elasticsearch.Net.Integration.Yaml/indices.exists/10_basic.yaml.cs | 1,262 | C# |
using NBitcoin.Crypto;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin
{
public class PartialMerkleTree : IBitcoinSerializable
{
uint _TransactionCount;
public uint TransactionCount
{
get
{
return _TransactionCount;
}
set
{
_TransactionCount = value;
}
}
List<uint256> _Hashes = new List<uint256>();
public List<uint256> Hashes
{
get
{
return _Hashes;
}
}
BitArray _Flags = new BitArray(0);
public BitArray Flags
{
get
{
return _Flags;
}
set
{
_Flags = value;
}
}
// serialization implementation
#region IBitcoinSerializable Members
public void ReadWrite(BitcoinStream stream)
{
stream.ReadWrite(ref _TransactionCount);
stream.ReadWrite(ref _Hashes);
byte[] vBytes = null;
if(!stream.Serializing)
{
stream.ReadWriteAsVarString(ref vBytes);
BitWriter writer = new BitWriter();
for(int p = 0 ; p < vBytes.Length * 8 ; p++)
writer.Write((vBytes[p / 8] & (1 << (p % 8))) != 0);
}
else
{
vBytes = new byte[(_Flags.Length + 7) / 8];
for(int p = 0 ; p < _Flags.Length ; p++)
vBytes[p / 8] |= (byte)(ToByte(_Flags.Get(p)) << (p % 8));
stream.ReadWriteAsVarString(ref vBytes);
}
}
private byte ToByte(bool v)
{
return (byte)(v ? 1 : 0);
}
#endregion
public PartialMerkleTree(uint256[] vTxid, bool[] vMatch)
{
if(vMatch.Length != vTxid.Length)
throw new ArgumentException("The size of the array of txid and matches is different");
TransactionCount = (uint)vTxid.Length;
MerkleNode root = MerkleNode.GetRoot(vTxid);
BitWriter flags = new BitWriter();
MarkNodes(root, vMatch);
BuildCore(root, flags);
Flags = flags.ToBitArray();
}
private static void MarkNodes(MerkleNode root, bool[] vMatch)
{
BitReader matches = new BitReader(new BitArray(vMatch));
foreach(var leaf in root.GetLeafs())
{
if(matches.Read())
{
leaf.IsMarked = true;
foreach(var ancestor in leaf.Ancestors())
{
ancestor.IsMarked = true;
}
}
}
}
public MerkleNode GetMerkleRoot()
{
MerkleNode node = MerkleNode.GetRoot((int)TransactionCount);
BitReader flags = new BitReader(Flags);
var hashes = Hashes.GetEnumerator();
GetMatchedTransactionsCore(node, flags, hashes, true).AsEnumerable();
return node;
}
public bool Check(uint256 expectedMerkleRootHash = null)
{
try
{
var hash = GetMerkleRoot().Hash;
return expectedMerkleRootHash == null || hash == expectedMerkleRootHash;
}
catch(Exception)
{
return false;
}
}
private void BuildCore(MerkleNode node, BitWriter flags)
{
if(node == null)
return;
flags.Write(node.IsMarked);
if(node.IsLeaf || !node.IsMarked)
Hashes.Add(node.Hash);
if(node.IsMarked)
{
BuildCore(node.Left, flags);
BuildCore(node.Right, flags);
}
}
public IEnumerable<uint256> GetMatchedTransactions()
{
BitReader flags = new BitReader(Flags);
MerkleNode root = MerkleNode.GetRoot((int)TransactionCount);
var hashes = Hashes.GetEnumerator();
return GetMatchedTransactionsCore(root, flags, hashes, false);
}
private IEnumerable<uint256> GetMatchedTransactionsCore(MerkleNode node, BitReader flags, IEnumerator<uint256> hashes, bool calculateHash)
{
if(node == null)
return new uint256[0];
node.IsMarked = flags.Read();
if(node.IsLeaf || !node.IsMarked)
{
hashes.MoveNext();
node.Hash = hashes.Current;
}
if(!node.IsMarked)
return new uint256[0];
if(node.IsLeaf)
return new uint256[] { node.Hash };
var left = GetMatchedTransactionsCore(node.Left, flags, hashes, calculateHash);
var right = GetMatchedTransactionsCore(node.Right, flags, hashes, calculateHash);
if(calculateHash)
node.UpdateHash();
return left.Concat(right);
}
public MerkleNode TryGetMerkleRoot()
{
try
{
return GetMerkleRoot();
}
catch(Exception)
{
return null;
}
}
}
}
| 22.331606 | 141 | 0.628538 | [
"MIT"
] | dthorpe/NBitcoin | NBitcoin/PartialMerkleTree.cs | 4,312 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Core;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
using Windows.Storage.Search;
using Windows.Storage.Streams;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Xamarin.Forms.Internals;
#if WINDOWS_UWP
namespace Xamarin.Forms.Platform.UWP
#else
namespace Xamarin.Forms.Platform.WinRT
#endif
{
internal abstract class WindowsBasePlatformServices : IPlatformServices
{
CoreDispatcher _dispatcher;
public WindowsBasePlatformServices(CoreDispatcher dispatcher)
{
if (dispatcher == null)
throw new ArgumentNullException("dispatcher");
_dispatcher = dispatcher;
}
public void BeginInvokeOnMainThread(Action action)
{
_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action()).WatchForError();
}
public Ticker CreateTicker()
{
return new WindowsTicker();
}
public virtual Assembly[] GetAssemblies()
{
var options = new QueryOptions { FileTypeFilter = { ".exe", ".dll" } };
StorageFileQueryResult query = Package.Current.InstalledLocation.CreateFileQueryWithOptions(options);
IReadOnlyList<StorageFile> files = query.GetFilesAsync().AsTask().Result;
var assemblies = new List<Assembly>(files.Count);
for (var i = 0; i < files.Count; i++)
{
StorageFile file = files[i];
try
{
Assembly assembly = Assembly.Load(new AssemblyName { Name = Path.GetFileNameWithoutExtension(file.Name) });
assemblies.Add(assembly);
}
catch (IOException)
{
}
catch (BadImageFormatException)
{
}
}
Assembly thisAssembly = GetType().GetTypeInfo().Assembly;
// this happens with .NET Native
if (!assemblies.Contains(thisAssembly))
assemblies.Add(thisAssembly);
return assemblies.ToArray();
}
public string GetMD5Hash(string input)
{
HashAlgorithmProvider algorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
IBuffer buffer = algorithm.HashData(Encoding.Unicode.GetBytes(input).AsBuffer());
return CryptographicBuffer.EncodeToHexString(buffer);
}
public double GetNamedSize(NamedSize size, Type targetElementType, bool useOldSizes)
{
return size.GetFontSize();
}
public async Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken)
{
using (var client = new HttpClient())
{
HttpResponseMessage streamResponse = await client.GetAsync(uri.AbsoluteUri).ConfigureAwait(false);
if (!streamResponse.IsSuccessStatusCode)
{
Log.Warning("HTTP Request", $"Could not retrieve {uri}, status code {streamResponse.StatusCode}");
return null;
}
return await streamResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
}
public IIsolatedStorageFile GetUserStoreForApplication()
{
return new WindowsIsolatedStorage(ApplicationData.Current.LocalFolder);
}
public bool IsInvokeRequired => !CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess;
public void OpenUriAction(Uri uri)
{
Launcher.LaunchUriAsync(uri).WatchForError();
}
public void StartTimer(TimeSpan interval, Func<bool> callback)
{
var timer = new DispatcherTimer { Interval = interval };
timer.Start();
timer.Tick += (sender, args) =>
{
bool result = callback();
if (!result)
timer.Stop();
};
}
internal class WindowsTimer : ITimer
{
readonly Timer _timer;
public WindowsTimer(Timer timer)
{
_timer = timer;
}
public void Change(int dueTime, int period)
{
_timer.Change(dueTime, period);
}
public void Change(long dueTime, long period)
{
Change(TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period));
}
public void Change(TimeSpan dueTime, TimeSpan period)
{
_timer.Change(dueTime, period);
}
public void Change(uint dueTime, uint period)
{
Change(TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period));
}
}
}
} | 25.497006 | 112 | 0.730155 | [
"MIT"
] | akihikodaki/Xamarin.Forms | Xamarin.Forms.Platform.WinRT/WindowsBasePlatformServices.cs | 4,260 | C# |
using UnityEngine;
// Shapes © Freya Holmér - https://twitter.com/FreyaHolmer/
// Website & Documentation - https://acegikmo.com/shapes/
namespace Shapes {
[ExecuteInEditMode]
[AddComponentMenu( "Shapes/Rectangle" )]
public class Rectangle : ShapeRenderer {
public enum RectangleType {
HardSolid,
RoundedSolid,
HardHollow,
RoundedHollow
}
public enum RectangleCornerRadiusMode {
Uniform,
PerCorner
}
public bool IsHollow => type == RectangleType.HardHollow || type == RectangleType.RoundedHollow;
public bool IsRounded => type == RectangleType.RoundedSolid || type == RectangleType.RoundedHollow;
[SerializeField] RectPivot pivot = RectPivot.Center;
public RectPivot Pivot {
get => pivot;
set {
pivot = value;
UpdateRectPositioningNow();
}
}
[SerializeField] float width = 1f;
public float Width {
get => width;
set {
width = value;
UpdateRectPositioningNow();
}
}
[SerializeField] float height = 1f;
public float Height {
get => height;
set {
height = value;
UpdateRectPositioningNow();
}
}
[SerializeField] RectangleType type = RectangleType.HardSolid;
public RectangleType Type {
get => type;
set {
type = value;
UpdateMaterial();
ApplyProperties();
}
}
[SerializeField] RectangleCornerRadiusMode cornerRadiusMode = RectangleCornerRadiusMode.Uniform;
public RectangleCornerRadiusMode CornerRadiusMode {
get => cornerRadiusMode;
set => cornerRadiusMode = value;
}
[System.Obsolete( "Radius is deprecated, please use " + nameof(CornerRadius) + " instead", true )]
public float Radius {
get => CornerRadius;
set => CornerRadius = value;
}
[SerializeField] Vector4 cornerRadii = new Vector4( 0.25f, 0.25f, 0.25f, 0.25f );
/// <summary>
/// Gets or sets a radius for all 4 corners when rounded
/// </summary>
public float CornerRadius {
get => cornerRadii.x;
set {
float r = Mathf.Max( 0f, value );
SetVector4Now( ShapesMaterialUtils.propCornerRadii, cornerRadii = new Vector4( r, r, r, r ) );
}
}
/// <summary>
/// Gets or sets a specific radius for each corner when rounded. Order is clockwise from bottom left
/// </summary>
public Vector4 CornerRadiii {
get => cornerRadii;
set => SetVector4Now( ShapesMaterialUtils.propCornerRadii, cornerRadii = new Vector4( Mathf.Max( 0f, value.x ), Mathf.Max( 0f, value.y ), Mathf.Max( 0f, value.z ), Mathf.Max( 0f, value.w ) ) );
}
[SerializeField] float thickness = 0.1f;
public float Thickness {
get => thickness;
set => SetFloatNow( ShapesMaterialUtils.propThickness, thickness = Mathf.Max( 0f, value ) );
}
public override bool HasDetailLevels => false;
void UpdateRectPositioningNow() => SetVector4Now( ShapesMaterialUtils.propRect, GetPositioningRect() );
void UpdateRectPositioning() => SetVector4( ShapesMaterialUtils.propRect, GetPositioningRect() );
Vector4 GetPositioningRect() {
float xOffset = pivot == RectPivot.Corner ? 0f : -width / 2f;
float yOffset = pivot == RectPivot.Corner ? 0f : -height / 2f;
return new Vector4( xOffset, yOffset, width, height );
}
protected override void SetAllMaterialProperties() {
if( cornerRadiusMode == RectangleCornerRadiusMode.PerCorner )
SetVector4( ShapesMaterialUtils.propCornerRadii, cornerRadii );
else if( cornerRadiusMode == RectangleCornerRadiusMode.Uniform )
SetVector4( ShapesMaterialUtils.propCornerRadii, new Vector4( CornerRadius, CornerRadius, CornerRadius, CornerRadius ) );
UpdateRectPositioning();
SetFloat( ShapesMaterialUtils.propThickness, thickness );
}
#if UNITY_EDITOR
protected override void ShapeClampRanges() {
cornerRadii = ShapesMath.AtLeast0( cornerRadii );
width = Mathf.Max( 0f, width );
height = Mathf.Max( 0f, height );
}
#endif
protected override Material[] GetMaterials() => new[] { ShapesMaterialUtils.GetRectMaterial( type )[BlendMode] };
protected override Bounds GetBounds() {
Vector2 size = new Vector2( width, height );
Vector2 center = pivot == RectPivot.Center ? default : size / 2f;
return new Bounds( center, size );
}
}
} | 30.394161 | 196 | 0.700288 | [
"MIT"
] | shelhelix/NetworkTicTacToe | Assets/!ThirdParty/Shapes/Scripts/Runtime/Components/Rectangle.cs | 4,168 | 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.Collections.Generic;
using System.Linq;
using BasicWebSite.Models;
namespace BasicWebSite
{
public class ContactsRepository
{
private readonly List<Contact> _contacts = new List<Contact>();
public Contact GetContact(int id)
{
return _contacts.FirstOrDefault(f => f.ContactId == id);
}
public void Add(Contact contact)
{
contact.ContactId = _contacts.Count + 1;
_contacts.Add(contact);
}
}
} | 27.12 | 111 | 0.650442 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Mvc/test/WebSites/BasicWebSite/ContactsRepository.cs | 678 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Text;
using System.Windows.Forms;
using AvayaMoagentClient;
namespace AvayaDialerTestClient
{
/// <summary>
/// Login
/// </summary>
public partial class Login : Form
{
/// <summary>
/// Creates a Login form with the specified extension, user ID, and password pre-filled.
/// </summary>
/// <param name="extension"></param>
/// <param name="userId"></param>
/// <param name="password"></param>
public Login(string extension, string userId, string password)
{
InitializeComponent();
Extension = extension;
UserId = userId;
Password = Utilities.ToSecureString(password);
txtExtension.Text = extension;
txtUserId.Text = userId;
txtPassword.Text = password;
}
/// <summary>
/// Extension.
/// </summary>
public string Extension { get; set; }
/// <summary>
/// UserId.
/// </summary>
public string UserId { get; set; }
/// <summary>
/// Password.
/// </summary>
public SecureString Password { get; set; }
private void OK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void Cancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void Extension_TextChanged(object sender, EventArgs e)
{
_SetButtons();
}
private void UserId_TextChanged(object sender, EventArgs e)
{
_SetButtons();
}
private void Password_TextChanged(object sender, EventArgs e)
{
_SetButtons();
}
private void _SetButtons()
{
btnOK.Enabled = !string.IsNullOrEmpty(txtExtension.Text) &&
!string.IsNullOrEmpty(txtUserId.Text) && !string.IsNullOrEmpty(txtPassword.Text);
}
private void Login_Activated(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtExtension.Text))
{
txtExtension.Focus();
}
else if (string.IsNullOrEmpty(txtUserId.Text))
{
txtUserId.Focus();
}
else if (string.IsNullOrEmpty(txtPassword.Text))
{
txtPassword.Focus();
}
else
{
btnOK.Focus();
}
}
}
}
| 22.523364 | 92 | 0.617842 | [
"BSD-2-Clause"
] | advanced-call-center-tech/avaya-moagent-client | AvayaDialerTestClient/Login.cs | 2,412 | C# |
namespace CarDealer.Dtos.Export
{
using System.Xml.Serialization;
[XmlType("car")]
public class exp_carsWithDistance_dto
{
[XmlElement("make")]
public string Make { get; set; }
[XmlElement("model")]
public string Model { get; set; }
[XmlElement("travelled-distance")]
public long TravelledDistance { get; set; }
}
} | 22.764706 | 51 | 0.604651 | [
"MIT"
] | StackSmack007/Database-Course | Exercise XML Processing/2/CarDealer/Dtos/Export/exp_carsWithDistance_dto.cs | 389 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Pdd.OpenSdk.Core.Models.Response.Promotion
{
public class CouponBatchList
{
/// <summary>
/// Examples: 9251417707
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Examples: "满3减2"
/// </summary>
[JsonProperty("batch_name")]
public string BatchName { get; set; }
/// <summary>
/// Examples: "123456"
/// </summary>
[JsonProperty("batch_desc")]
public string BatchDesc { get; set; }
/// <summary>
/// Examples: null
/// </summary>
[JsonProperty("discount_type")]
public object DiscountType { get; set; }
/// <summary>
/// Examples: 200
/// </summary>
[JsonProperty("discount_param")]
public int DiscountParam { get; set; }
/// <summary>
/// Examples: 1000
/// </summary>
[JsonProperty("init_quantity")]
public int InitQuantity { get; set; }
/// <summary>
/// Examples: 998
/// </summary>
[JsonProperty("remain_quantity")]
public int RemainQuantity { get; set; }
/// <summary>
/// Examples: 0
/// </summary>
[JsonProperty("used_quantity")]
public int UsedQuantity { get; set; }
/// <summary>
/// Examples: 3
/// </summary>
[JsonProperty("user_limit")]
public int UserLimit { get; set; }
/// <summary>
/// Examples: 2147483647
/// </summary>
[JsonProperty("max_discount_amount")]
public long MaxDiscountAmount { get; set; }
/// <summary>
/// Examples: 23
/// </summary>
[JsonProperty("duration")]
public int Duration { get; set; }
/// <summary>
/// Examples: 1
/// </summary>
[JsonProperty("period_type")]
public int PeriodType { get; set; }
/// <summary>
/// Examples: 1528300800000
/// </summary>
[JsonProperty("batch_start_time")]
public long BatchStartTime { get; set; }
/// <summary>
/// Examples: 1530374399000
/// </summary>
[JsonProperty("batch_end_time")]
public long BatchEndTime { get; set; }
/// <summary>
/// Examples: 16
/// </summary>
[JsonProperty("source_type")]
public int SourceType { get; set; }
/// <summary>
/// Examples: 8
/// </summary>
[JsonProperty("type")]
public int Type { get; set; }
/// <summary>
/// Examples: 1
/// </summary>
[JsonProperty("status")]
public int Status { get; set; }
/// <summary>
/// Examples: "{\"mallId\":[1],\"priceRange\":[300,2147483647]}"
/// </summary>
[JsonProperty("rules")]
public string Rules { get; set; }
/// <summary>
/// Examples: 8
/// </summary>
[JsonProperty("display_type")]
public int DisplayType { get; set; }
/// <summary>
/// Examples: 1528362083000
/// </summary>
[JsonProperty("created_at")]
public long CreatedAt { get; set; }
}
public class MerchantCouponBatchListResponse
{
/// <summary>
/// Examples: 99
/// </summary>
[JsonProperty("total_size")]
public int TotalSize { get; set; }
/// <summary>
/// Examples: [{"id":9251417707,"batch_name":"满3减2","batch_desc":"123456","discount_type":null,"discount_param":200,"init_quantity":1000,"remain_quantity":998,"used_quantity":0,"user_limit":3,"max_discount_amount":2147483647,"duration":23,"period_type":1,"batch_start_time":1528300800000,"batch_end_time":1530374399000,"source_type":16,"type":8,"status":1,"rules":"{\"mallId\":[1],\"priceRange\":[300,2147483647]}","display_type":8,"created_at":1528362083000}]
/// </summary>
[JsonProperty("coupon_batch_list")]
public IList<CouponBatchList> CouponBatchList { get; set; }
}
public class GetPromotionMerchantCouponListResponseModel
{
/// <summary>
/// Examples: {"total_size":99,"coupon_batch_list":[{"id":9251417707,"batch_name":"满3减2","batch_desc":"123456","discount_type":null,"discount_param":200,"init_quantity":1000,"remain_quantity":998,"used_quantity":0,"user_limit":3,"max_discount_amount":2147483647,"duration":23,"period_type":1,"batch_start_time":1528300800000,"batch_end_time":1530374399000,"source_type":16,"type":8,"status":1,"rules":"{\"mallId\":[1],\"priceRange\":[300,2147483647]}","display_type":8,"created_at":1528362083000}]}
/// </summary>
[JsonProperty("merchant_coupon_batch_list_response")]
public MerchantCouponBatchListResponse MerchantCouponBatchListResponse { get; set; }
}
}
| 31.598726 | 506 | 0.557952 | [
"Apache-2.0"
] | micro-chen/FlyBirdYoYo | Pdd.OpenSdk.Core/Models/Response/Promotion/GetPromotionMerchantCouponListResponseModel.cs | 4,973 | C# |
using Reception.Model.Interface;
namespace Reception.Model.Dto
{
public class PostDto : IPost
{
public int Id { get; set; }
public string Comment { get; set; }
public string Name { get; set; }
}
} | 18.153846 | 43 | 0.597458 | [
"MIT"
] | kirichenec/ReceptionNetCore | src/Reception.Model.Dto/PostDto.cs | 238 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using NBTExplorer.Model;
namespace NBTUtil.Ops
{
abstract class ConsoleOperation
{
public virtual bool OptionsValid (ConsoleOptions options)
{
return true;
}
public abstract bool CanProcess (DataNode dataNode);
public abstract bool Process (DataNode dataNode, ConsoleOptions options);
}
}
| 22.263158 | 81 | 0.685579 | [
"MIT"
] | 3prm3/NBTExplorer-Reloaded | NBTUtil/Ops/ConsoleOperation.cs | 425 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 the OpenSimulator Project 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 DEVELOPERS ``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 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.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using log4net;
namespace OpenSim.Region.CoreModules.Framework.Library
{
public class LocalInventoryService : IInventoryService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private InventoryFolderImpl m_Library;
public LocalInventoryService(InventoryFolderImpl lib)
{
m_Library = lib;
}
/// <summary>
/// Retrieve the root inventory folder for the given user.
/// </summary>
/// <param name="userID"></param>
/// <returns>null if no root folder was found</returns>
public InventoryFolderBase GetRootFolder(UUID userID) { return m_Library; }
/// <summary>
/// Gets everything (folders and items) inside a folder
/// </summary>
/// <param name="userId"></param>
/// <param name="folderID"></param>
/// <returns></returns>
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
InventoryFolderImpl folder = null;
InventoryCollection inv = new InventoryCollection();
inv.UserID = m_Library.Owner;
if (folderID != m_Library.ID)
{
folder = m_Library.FindFolder(folderID);
if (folder == null)
{
inv.Folders = new List<InventoryFolderBase>();
inv.Items = new List<InventoryItemBase>();
return inv;
}
}
else
folder = m_Library;
inv.Folders = folder.RequestListOfFolders();
inv.Items = folder.RequestListOfItems();
m_log.DebugFormat("[LIBRARY MODULE]: Got content for folder {0}", folder.Name);
return inv;
}
/// <summary>
/// Add a new folder to the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully added</returns>
public bool AddFolder(InventoryFolderBase folder)
{
//m_log.DebugFormat("[LIBRARY MODULE]: Adding folder {0} ({1}) to {2}", folder.Name, folder.ID, folder.ParentID);
InventoryFolderImpl parent = m_Library;
if (m_Library.ID != folder.ParentID)
parent = m_Library.FindFolder(folder.ParentID);
if (parent == null)
{
m_log.DebugFormat("[LIBRARY MODULE]: could not add folder {0} because parent folder {1} not found", folder.Name, folder.ParentID);
return false;
}
parent.CreateChildFolder(folder.ID, folder.Name, (ushort)folder.Type);
return true;
}
/// <summary>
/// Add a new item to the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully added</returns>
public bool AddItem(InventoryItemBase item)
{
//m_log.DebugFormat("[LIBRARY MODULE]: Adding item {0} to {1}", item.Name, item.Folder);
InventoryFolderImpl folder = m_Library;
if (m_Library.ID != item.Folder)
folder = m_Library.FindFolder(item.Folder);
if (folder == null)
{
m_log.DebugFormat("[LIBRARY MODULE]: could not add item {0} because folder {1} not found", item.Name, item.Folder);
return false;
}
folder.Items.Add(item.ID, item);
return true;
}
public bool CreateUserInventory(UUID user) { return false; }
/// <summary>
/// Gets the skeleton of the inventory -- folders only
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId) { return null; }
/// <summary>
/// Synchronous inventory fetch.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public InventoryCollection GetUserInventory(UUID userID) { return null; }
/// <summary>
/// Request the inventory for a user. This is an asynchronous operation that will call the callback when the
/// inventory has been received
/// </summary>
/// <param name="userID"></param>
/// <param name="callback"></param>
public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) { }
/// <summary>
/// Gets the user folder for the given folder-type
/// </summary>
/// <param name="userID"></param>
/// <param name="type"></param>
/// <returns></returns>
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) { return null; }
/// <summary>
/// Gets the items inside a folder
/// </summary>
/// <param name="userID"></param>
/// <param name="folderID"></param>
/// <returns></returns>
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) { return null; }
/// <summary>
/// Update a folder in the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully updated</returns>
public bool UpdateFolder(InventoryFolderBase folder) { return false; }
/// <summary>
/// Move an inventory folder to a new location
/// </summary>
/// <param name="folder">A folder containing the details of the new location</param>
/// <returns>true if the folder was successfully moved</returns>
public bool MoveFolder(InventoryFolderBase folder) { return false; }
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
//bool DeleteItem(InventoryItemBase item);
public bool DeleteFolders(UUID userID, List<UUID> folderIDs) { return false; }
/// <summary>
/// Purge an inventory folder of all its items and subfolders.
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully purged</returns>
public bool PurgeFolder(InventoryFolderBase folder) { return false; }
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully updated</returns>
public bool UpdateItem(InventoryItemBase item) { return false; }
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items) { return false; }
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
//bool DeleteItem(InventoryItemBase item);
public bool DeleteItems(UUID userID, List<UUID> itemIDs) { return false; }
/// <summary>
/// Get an item, given by its UUID
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public InventoryItemBase GetItem(InventoryItemBase item) { return null; }
/// <summary>
/// Get a folder, given by its UUID
/// </summary>
/// <param name="folder"></param>
/// <returns></returns>
public InventoryFolderBase GetFolder(InventoryFolderBase folder) { return null; }
/// <summary>
/// Does the given user have an inventory structure?
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public bool HasInventoryForUser(UUID userID) { return false; }
/// <summary>
/// Get the active gestures of the agent.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public List<InventoryItemBase> GetActiveGestures(UUID userId) { return null; }
/// <summary>
/// Get the union of permissions of all inventory items
/// that hold the given assetID.
/// </summary>
/// <param name="userID"></param>
/// <param name="assetID"></param>
/// <returns>The permissions or 0 if no such asset is found in
/// the user's inventory</returns>
public int GetAssetPermissions(UUID userID, UUID assetID) { return 0; }
}
}
| 39.541667 | 146 | 0.604656 | [
"BSD-3-Clause"
] | N3X15/VoxelSim | OpenSim/Region/CoreModules/Framework/Library/LocalInventoryService.cs | 10,441 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Czar.IdentityServer4")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Czar.IdentityServer4")]
[assembly: System.Reflection.AssemblyTitleAttribute("Czar.IdentityServer4")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// 由 MSBuild WriteCodeFragment 类生成。
| 37.666667 | 80 | 0.638274 | [
"MIT"
] | cityjoy/NetCoreFrame.Admin | CoreFrame.IdentityServer4.DapperExtension/obj/Debug/netcoreapp2.1/Czar.IdentityServer4.AssemblyInfo.cs | 1,020 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Threading.Tasks;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// Mixed Reality Toolkit controller definition, used to manage a specific controller type
/// </summary>
public interface IMixedRealityDictationSystem : IMixedRealityInputDeviceManager
{
/// <summary>
/// Is the system currently listing for dictation input?
/// </summary>
bool IsListening { get; }
/// <summary>
/// Turns on the dictation recognizer and begins recording audio from the default microphone.
/// </summary>
/// <param name="listener">GameObject listening for the dictation input.</param>
/// <param name="initialSilenceTimeout">The time length in seconds before dictation recognizer session ends due to lack of audio input in case there was no audio heard in the current session.</param>
/// <param name="autoSilenceTimeout">The time length in seconds before dictation recognizer session ends due to lack of audio input.</param>
/// <param name="recordingTime">Length in seconds for the manager to listen.</param>
/// <param name="micDeviceName">Optional: The microphone device to listen to.</param>
void StartRecording(GameObject listener, float initialSilenceTimeout = 5f, float autoSilenceTimeout = 20f, int recordingTime = 10, string micDeviceName = "");
/// <summary>
/// Turns on the dictation recognizer and begins recording audio from the default microphone.
/// </summary>
/// <param name="listener">GameObject listening for the dictation input.</param>
/// <param name="initialSilenceTimeout">The time length in seconds before dictation recognizer session ends due to lack of audio input in case there was no audio heard in the current session.</param>
/// <param name="autoSilenceTimeout">The time length in seconds before dictation recognizer session ends due to lack of audio input.</param>
/// <param name="recordingTime">Length in seconds for the manager to listen.</param>
/// <param name="micDeviceName">Optional: The microphone device to listen to.</param>
Task StartRecordingAsync(GameObject listener, float initialSilenceTimeout = 5f, float autoSilenceTimeout = 20f, int recordingTime = 10, string micDeviceName = "");
/// <summary>
/// Ends the recording session.
/// </summary>
void StopRecording();
/// <summary>
/// Ends the recording session.
/// </summary>
/// <returns><see href="https://docs.unity3d.com/ScriptReference/AudioClip.html">AudioClip</see> of the last recording session.</returns>
Task<AudioClip> StopRecordingAsync();
}
}
| 58.294118 | 208 | 0.680457 | [
"MIT"
] | Argylebuild/aad-hololens | Assets/MRTK/Core/Interfaces/Devices/IMixedRealityDictationSystem.cs | 2,975 | C# |
/*
* Original author: Matt Chambers <matt.chambers42 .at. gmail.com >
*
* Copyright 2020 University of Washington - Seattle, WA
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using pwiz.Skyline.Properties;
namespace pwiz.Skyline.Alerts
{
public class KeyValueGridDlg
{
/// <summary>
/// Shows a simple dialog with a grid of labels (for keys) and textboxes (for values).
/// The keys are always strings and the values are typed (but must be convertible to and from string obviously).
/// If the (optional) validateValue action throws an exception, a message box will show the user
/// the exception message and the invalid textbox value will be returned to its previous value.
/// </summary>
public static void Show<TValue>(string title, IDictionary<string, TValue> gridValues, Func<TValue, string> valueToString,
Action<string, TValue> stringToValue, Action<string, TValue> validateValue = null)
{
var layout = new TableLayoutPanel {Dock = DockStyle.Fill};
layout.RowCount = gridValues.Count + 1; // empty last row
layout.ColumnCount = 2; // key and value
foreach (ColumnStyle style in layout.ColumnStyles)
{
style.Width = 50;
style.SizeType = SizeType.Percent;
}
var keyToControl = new Dictionary<string, TextBox>();
var controlToSetting = new Dictionary<object, TValue>();
int row = 0;
foreach (var kvp in gridValues)
{
var lbl = new Label
{
Text = kvp.Key,
Dock = DockStyle.Fill,
AutoSize = true,
TextAlign = ContentAlignment.MiddleCenter
};
var value = new TextBox {Text = valueToString(kvp.Value), Dock = DockStyle.Fill};
value.LostFocus += (o, args) =>
{
if (validateValue != null && o is TextBox tb)
try
{
validateValue(tb.Text, controlToSetting[tb]);
}
catch (Exception ex)
{
tb.Text = valueToString(controlToSetting[tb]);
MessageDlg.Show(tb.Parent, ex.Message);
}
};
layout.Controls.Add(lbl, 0, row);
layout.Controls.Add(value, 1, row);
keyToControl[kvp.Key] = value;
controlToSetting[value] = kvp.Value;
row++;
}
using (var dlg = new MultiButtonMsgDlg(layout, Resources.OK) {Text = title})
{
if (dlg.ShowParentlessDialog() == DialogResult.Cancel)
return;
foreach (var kvp in keyToControl)
stringToValue(keyToControl[kvp.Key].Text, gridValues[kvp.Key]);
}
}
}
}
| 40.593407 | 129 | 0.562534 | [
"Apache-2.0"
] | jeleclaire/pwiz | pwiz_tools/Skyline/Alerts/KeyValueGridDlg.cs | 3,696 | 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 robomaker-2018-06-29.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.RoboMaker.Model
{
/// <summary>
/// This is the response object from the GetWorldTemplateBody operation.
/// </summary>
public partial class GetWorldTemplateBodyResponse : AmazonWebServiceResponse
{
private string _templateBody;
/// <summary>
/// Gets and sets the property TemplateBody.
/// <para>
/// The world template body.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=262144)]
public string TemplateBody
{
get { return this._templateBody; }
set { this._templateBody = value; }
}
// Check to see if TemplateBody property is set
internal bool IsSetTemplateBody()
{
return this._templateBody != null;
}
}
} | 30.258621 | 108 | 0.640456 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/RoboMaker/Generated/Model/GetWorldTemplateBodyResponse.cs | 1,755 | C# |
#pragma checksum "C:\Users\Mehmet\Desktop\UdemyBlogFront\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5c05831fc344a09d2edcd9b7ea64465dcbd15998"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(UdemyBlogFront.Models.Views__ViewStart), @"mvc.1.0.view", @"/Views/_ViewStart.cshtml")]
namespace UdemyBlogFront.Models
{
#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;
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5c05831fc344a09d2edcd9b7ea64465dcbd15998", @"/Views/_ViewStart.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"526d03c167286a75304edc28a2ecfe82a9efb0d7", @"/Views/_ViewImports.cshtml")]
public class Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "C:\Users\Mehmet\Desktop\UdemyBlogFront\Views\_ViewStart.cshtml"
Layout = "_Layout";
#line default
#line hidden
#nullable disable
}
#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<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 53.4 | 175 | 0.761964 | [
"MIT"
] | mehmetkillar/BlogProject-FrontEnd | BlogProject/obj/Debug/net5.0/Razor/Views/_ViewStart.cshtml.g.cs | 2,403 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BAYSOFT.Presentations.WebAPI
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 26.296296 | 70 | 0.650704 | [
"MIT"
] | bs-templates/template-architecture-cqrsfapi | src/BAYSOFT.Presentations.WebAPI/Program.cs | 710 | C# |
using Handelabra;
using Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Jp.ParahumansOfTheWormverse.Slaughterhouse9
{
public class SpiderbotsCardController : CardController
{
public SpiderbotsCardController(Card card, TurnTakerController turnTakerController)
: base(card, turnTakerController)
{
}
public override void AddTriggers()
{
// At the end of the villain turn this card deals X melee damage to the hero target with the lowest HP, where X = 1 + the number of Spiderbots in play
AddDealDamageAtEndOfTurnTrigger(
TurnTaker,
Card,
c => c.IsHero && c.IsTarget,
TargetType.LowestHP,
1,
DamageType.Melee,
dynamicAmount: c => 1 + SpiderbotCount()
);
}
private int SpiderbotCount()
{
return FindCardsWhere(
new LinqCardCriteria(c => c.Identifier == "Spiderbots" && c.IsInPlayAndHasGameText),
GetCardSource()
).Count();
}
}
}
| 30.547619 | 162 | 0.604832 | [
"BSD-2-Clause"
] | kree1/potw | Mod/Villains/Slaughterhouse9/Cards/SpiderbotsCardController.cs | 1,285 | C# |
using System.ComponentModel.DataAnnotations.Schema;
namespace la_rive_admin.Models
{
public class ItemModel : Item
{
public virtual Category Category { get; set; }
public Order Order { get; set; }
}
}
| 21.727273 | 54 | 0.648536 | [
"MIT"
] | Git-Dobou/la_rive | la_rive_admin/Models/ItemModel.cs | 241 | C# |
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Quartz;
using Zirku.Server.Models;
using Zirku.Server.Services;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace Zirku.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
=> Configuration = configuration;
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
// Configure the context to use Microsoft SQL Server.
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
// Register the entity sets needed by OpenIddict.
// Note: use the generic overload if you need
// to replace the default OpenIddict entities.
options.UseOpenIddict();
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
// Configure Identity to use the same JWT claims as OpenIddict instead
// of the legacy WS-Federation claims it uses by default (ClaimTypes),
// which saves you from doing the mapping in your authorization controller.
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = Claims.Name;
options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
options.ClaimsIdentity.RoleClaimType = Claims.Role;
});
// OpenIddict offers native integration with Quartz.NET to perform scheduled tasks
// (like pruning orphaned authorizations/tokens from the database) at regular intervals.
services.AddQuartz(options =>
{
options.UseMicrosoftDependencyInjectionJobFactory();
options.UseSimpleTypeLoader();
options.UseInMemoryStore();
});
// Register the Quartz.NET service and configure it to block shutdown until jobs are complete.
services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);
services.AddOpenIddict()
// Register the OpenIddict core components.
.AddCore(options =>
{
// Configure OpenIddict to use the Entity Framework Core stores and models.
// Note: call ReplaceDefaultEntities() to replace the default OpenIddict entities.
options.UseEntityFrameworkCore()
.UseDbContext<ApplicationDbContext>();
// Enable Quartz.NET integration.
options.UseQuartz();
})
// Register the OpenIddict server components.
.AddServer(options =>
{
// Enable the authorization, logout, userinfo, and introspection endpoints.
options.SetAuthorizationEndpointUris("/connect/authorize")
.SetLogoutEndpointUris("/connect/logout")
.SetIntrospectionEndpointUris("/connect/introspect")
.SetUserinfoEndpointUris("/connect/userinfo");
// Mark the "email", "profile" and "roles" scopes as supported scopes.
options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);
// Note: the sample only uses the implicit flow but you can enable the other
// flows if you need to support code, password or client credentials.
options.AllowImplicitFlow();
// Register the encryption credentials. This sample uses a symmetric
// encryption key that is shared between the server and the Api2 sample
// (that performs local token validation instead of using introspection).
//
// Note: in a real world application, this encryption key should be
// stored in a safe place (e.g in Azure KeyVault, stored as a secret).
options.AddEncryptionKey(new SymmetricSecurityKey(
Convert.FromBase64String("DRjd/GnduI3Efzen9V9BvbNUfc/VKgXltV7Kbk9sMkY=")));
// Register the signing credentials.
options.AddDevelopmentSigningCertificate();
// Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
options.UseAspNetCore()
.EnableAuthorizationEndpointPassthrough()
.EnableLogoutEndpointPassthrough()
.EnableUserinfoEndpointPassthrough()
.EnableStatusCodePagesIntegration();
})
// Register the OpenIddict validation components.
.AddValidation(options =>
{
// Import the configuration from the local OpenIddict server instance.
options.UseLocalServer();
// Register the ASP.NET Core host.
options.UseAspNetCore();
});
services.AddCors();
services.AddControllersWithViews();
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
// Register the worker responsible of creating and seeding the SQL database.
// Note: in a real world application, this step should be part of a setup script.
services.AddHostedService<Worker>();
}
public void Configure(IApplicationBuilder app)
{
app.UseStatusCodePagesWithReExecute("/error");
app.UseRouting();
app.UseCors(builder =>
{
builder.WithOrigins("https://localhost:44398");
builder.WithMethods("GET");
builder.WithHeaders("Authorization");
});
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(options =>
{
options.MapControllers();
options.MapDefaultControllerRoute();
});
}
}
} | 43.441558 | 106 | 0.590135 | [
"Apache-2.0"
] | NewkyNet/openiddict-samples | samples/Zirku/Zirku.Server/Startup.cs | 6,690 | C# |
// -----------------------------------------------------------------------
// <copyright file="DapperSqlExecutor.cs" company="Hybrid开源团队">
// Copyright (c) 2014-2017 Hybrid. All rights reserved.
// </copyright>
// <site>https://www.lxking.cn</site>
// <last-editor>ArcherTrister</last-editor>
// <last-date>2017-08-21 1:07</last-date>
// -----------------------------------------------------------------------
using Microsoft.Data.Sqlite;
using System.Data;
namespace Hybrid.Entity.Sqlite
{
/// <summary>
/// Sqlite的Dapper-Sql功能执行
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <typeparam name="TKey">编号类型</typeparam>
public class SqliteDapperSqlExecutor<TEntity, TKey> : SqlExecutorBase<TEntity, TKey> where TEntity : IEntity<TKey>
{
/// <summary>
/// 初始化一个<see cref="SqlExecutorBase{TEntity,TKey}"/>类型的新实例
/// </summary>
public SqliteDapperSqlExecutor(IUnitOfWorkManager unitOfWorkManager)
: base(unitOfWorkManager)
{ }
/// <summary>
/// 获取 数据库类型
/// </summary>
public override DatabaseType DatabaseType => DatabaseType.Sqlite;
/// <summary>
/// 重写以获取数据连接对象
/// </summary>
/// <param name="connectionString">数据连接字符串</param>
/// <returns></returns>
protected override IDbConnection GetDbConnection(string connectionString)
{
return new SqliteConnection(connectionString);
}
}
} | 32.913043 | 118 | 0.557464 | [
"Apache-2.0"
] | ArcherTrister/ESoftor | src/Hybrid.EntityFrameworkCore.Sqlite/SqliteDapperSqlExecutor.cs | 1,622 | C# |
#if NET_2_0
/*
Used to determine Browser Capabilities by the Browsers UserAgent String and related
Browser supplied Headers.
Copyright (C) 2002-Present Owen Brady (Ocean at owenbrady dot net)
and Dean Brettle (dean at brettle dot 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.
*/
namespace System.Web.Configuration
{
using System;
using System.Collections.Generic;
using System.Text;
internal abstract class CapabilitiesBuild : ICapabilitiesProcess
{
/// <summary>
///
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
protected abstract System.Collections.ObjectModel.Collection<string> HeaderNames(System.Collections.ObjectModel.Collection<string> list);
/// <summary>
///
/// </summary>
/// <param name="userAgent"></param>
/// <param name="initialCapabilities"></param>
/// <returns></returns>
public System.Web.Configuration.CapabilitiesResult Process(string userAgent, System.Collections.IDictionary initialCapabilities)
{
System.Collections.Specialized.NameValueCollection header;
header = new System.Collections.Specialized.NameValueCollection(1);
header.Add("User-Agent", userAgent);
return Process(header, initialCapabilities);
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="initialCapabilities"></param>
/// <returns></returns>
public System.Web.Configuration.CapabilitiesResult Process(System.Web.HttpRequest request, System.Collections.IDictionary initialCapabilities)
{
if (request != null)
{
return Process(request.Headers, initialCapabilities);
}
else
{
return Process("", initialCapabilities);
}
}
/// <summary>
///
/// </summary>
/// <param name="header"></param>
/// <param name="initialCapabilities"></param>
/// <returns></returns>
public abstract System.Web.Configuration.CapabilitiesResult Process(System.Collections.Specialized.NameValueCollection header, System.Collections.IDictionary initialCapabilities);
}
}
#endif
| 37.6125 | 181 | 0.747424 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Web/System.Web.Configuration_2.0/CapabilitiesBuild.cs | 3,009 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JwRecorder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JwRecorder")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("8345486e-a02d-4e87-8e68-8c55ad511ab6")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.27027 | 56 | 0.715508 | [
"MIT"
] | wuqinchao/JwRecorder | Properties/AssemblyInfo.cs | 1,276 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StripLib
{
public interface IStripWriter
{
void Write(string command);
}
}
| 15.928571 | 35 | 0.721973 | [
"Apache-2.0"
] | jakkaj/DayBar | Playground/Playground_Test/StripLib/IStripWriter.cs | 225 | 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.GraphModel;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed partial class SearchGraphQuery : IGraphQuery
{
private readonly IThreadingContext _threadingContext;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly string _searchPattern;
public SearchGraphQuery(
string searchPattern,
IThreadingContext threadingContext,
IAsynchronousOperationListener asyncListener)
{
_threadingContext = threadingContext;
_asyncListener = asyncListener;
_searchPattern = searchPattern;
}
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)
{
var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);
var callback = new ProgressionNavigateToSearchCallback(context, graphBuilder);
var searcher = NavigateToSearcher.Create(
solution,
_asyncListener,
callback,
_searchPattern,
searchCurrentDocument: false,
NavigateToUtilities.GetKindsProvided(solution),
_threadingContext.DisposalToken);
await searcher.SearchAsync(cancellationToken).ConfigureAwait(false);
return graphBuilder;
}
}
}
| 39.66 | 146 | 0.71054 | [
"MIT"
] | AlFasGD/roslyn | src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/SearchGraphQuery.cs | 1,985 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using System;
namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Model
{
public class DatabaseCopy
{
public Guid EntityId { get; set; }
public string SourceServerName { get; set; }
public string SourceDatabaseName { get; set; }
public string DestinationServerName { get; set; }
public string DestinationDatabaseName { get; set; }
public bool IsContinuous { get; set; }
public byte ReplicationState { get; set; }
public string ReplicationStateDescription { get; set; }
public int LocalDatabaseId { get; set; }
public bool IsLocalDatabaseReplicationTarget { get; set; }
public bool IsInterlinkConnected { get; set; }
public DateTime StartDate { get; set; }
public DateTime ModifyDate { get; set; }
public float PercentComplete { get; set; }
}
}
| 33.8 | 87 | 0.601775 | [
"MIT"
] | stankovski/azure-sdk-tools | src/ServiceManagement/Sql/Commands.SqlDatabase/Model/DatabaseCopy.cs | 1,643 | 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.
//
//
// Description: DataObjectSettingData event arguments
//
using System;
namespace System.Windows
{
/// <summary>
/// Arguments for the DataObject.SettingData event.
/// The DataObject.SettingData event is raised during
/// Copy (or Drag start) command when an editor
/// is going to start data conversion for some
/// of data formats. By handling this event an application
/// can prevent from editon doing that thus making
/// Copy performance better.
/// </summary>
public sealed class DataObjectSettingDataEventArgs : DataObjectEventArgs
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Creates a DataObjectSettingDataEventArgs.
/// </summary>
/// <param name="dataObject">
/// DataObject to which a new data format is going to be added.
/// </param>
/// <param name="format">
/// Format which is going to be added to the DataObject.
/// </param>
public DataObjectSettingDataEventArgs(IDataObject dataObject, string format) //
: base(System.Windows.DataObject.SettingDataEvent, /*isDragDrop:*/false)
{
if (dataObject == null)
{
throw new ArgumentNullException("dataObject");
}
if (format == null)
{
throw new ArgumentNullException("format");
}
_dataObject = dataObject;
_format = format;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// DataObject to which a new data format is going to be added.
/// </summary>
public IDataObject DataObject
{
get { return _dataObject; }
}
/// <summary>
/// Format which is going to be added to the DataObject.
/// </summary>
public string Format
{
get { return _format; }
}
#endregion Public Properties
#region Protected Methods
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
/// <summary>
/// The mechanism used to call the type-specific handler on the target.
/// </summary>
/// <param name="genericHandler">
/// The generic handler to call in a type-specific way.
/// </param>
/// <param name="genericTarget">
/// The target to call the handler on.
/// </param>
protected override void InvokeEventHandler(Delegate genericHandler, object genericTarget)
{
DataObjectSettingDataEventHandler handler = (DataObjectSettingDataEventHandler)genericHandler;
handler(genericTarget, this);
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private IDataObject _dataObject;
private string _format;
#endregion Private Fields
}
/// <summary>
/// The delegate to use for handlers that receive the DataObject.QueryingCopy/QueryingPaste events.
/// </summary>
/// <remarks>
/// A handler for a DataObject.SettingData event.
/// Te event is fired as part of Copy (or Drag) command
/// once for each of data formats added to a DataObject.
/// The purpose of this handler is mostly copy command
/// optimization. With the help of it application
/// can filter some formats from being added to DataObject.
/// The other opportunity of doing that exists in
/// DataObject.Copying event, which could set all undesirable
/// formats to null, but in this case the work for data
/// conversion is already done, which may be too expensive.
/// By handling DataObject.SettingData event an application
/// can prevent from each particular data format conversion.
/// By calling DataObjectSettingDataEventArgs.CancelCommand
/// method the handler tells an editor to skip one particular
/// data format (identified by DataObjectSettingDataEventArgs.Format
/// property). Note that calling CancelCommand method
/// for this event does not cancel the whole Copy or Drag
/// command.
/// </remarks>
public delegate void DataObjectSettingDataEventHandler(object sender, DataObjectSettingDataEventArgs e);
}
| 33.776316 | 108 | 0.555123 | [
"MIT"
] | 00mjk/wpf | src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/DataObjectSettingDataEventArgs.cs | 5,134 | C# |
/*
* PROJECT: Aura Operating System Development
* CONTENT: Welcome Message
* PROGRAMMERS: Alexy DA CRUZ <dacruzalexy@gmail.com>
* Valentin Charbonnier <valentinbreiz@gmail.com>
*/
using System;
namespace Aura_OS.System
{
class WelcomeMessage
{
/// <summary>
/// Display the welcome message
/// </summary>
public static void Display()
{
switch (Kernel.langSelected)
{
case "fr_FR":
Logo.Print();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" * Documentation: aura-team.com");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(" ");
break;
case "en_US":
Logo.Print();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" * Documentation: aura-team.com");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(" ");
break;
case "nl_NL":
Logo.Print();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" * Documentatie: aura-team.com");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(" ");
break;
}
}
}
}
| 30.82 | 73 | 0.484101 | [
"BSD-3-Clause"
] | Project-Magenta/Aura-Operating-System | Aura Operating System/Aura OS/System/Drawable/WelcomeMessage.cs | 1,543 | C# |
using EFCore.BulkExtensions.SqlAdapters;
using Microsoft.EntityFrameworkCore;
using NetTopologySuite.Geometries;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Xunit;
namespace EFCore.BulkExtensions.Tests
{
public class EFCoreBulkTestAtypical
{
protected int EntitiesNumber => 1000;
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void DefaultValuesTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Document>();
context.Documents.BatchDelete();
bool isSqlite = dbServer == DbServer.SQLite;
var entities = new List<Document>()
{
new Document { DocumentId = Guid.Parse("15E5936C-8021-45F4-A055-2BE89B065D9E"), Content = "Info " + 1 },
new Document { DocumentId = Guid.Parse("00C69E47-A08F-49E0-97A6-56C62C9BB47E"), Content = "Info " + 2 },
new Document { DocumentId = Guid.Parse("22CF94AE-20D3-49DE-83FA-90E79DD94706"), Content = "Info " + 3 },
new Document { DocumentId = Guid.Parse("B3A2F9A5-4222-47C3-BEEA-BF50771665D3"), Content = "Info " + 4 },
new Document { DocumentId = Guid.Parse("12AF6361-95BC-44F3-A487-C91C440018D8"), Content = "Info " + 5 },
};
var firstDocumentUp = entities.FirstOrDefault();
context.BulkInsertOrUpdate(entities, bulkConfig => bulkConfig.SetOutputIdentity = true); // example of setting BulkConfig with Action argument
var firstDocument = context.Documents.AsNoTracking().OrderBy(x => x.Content).FirstOrDefault();
var countDb = context.Documents.Count();
var countEntities = entities.Count();
// TEST
Assert.Equal(countDb, countEntities);
Assert.Equal(firstDocument.DocumentId, firstDocumentUp.DocumentId);
}
[Theory]
[InlineData(DbServer.SQLServer)]
private void TemporalTableTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
//context.Truncate<Document>(); // Can not be used because table is Temporal, so BatchDelete used instead
context.Storages.BatchDelete();
var entities = new List<Storage>()
{
new Storage { StorageId = Guid.NewGuid(), Data = "Info " + 1 },
new Storage { StorageId = Guid.NewGuid(), Data = "Info " + 2 },
new Storage { StorageId = Guid.NewGuid(), Data = "Info " + 3 },
};
context.BulkInsert(entities);
var countDb = context.Storages.Count();
var countEntities = entities.Count();
// TEST
Assert.Equal(countDb, countEntities);
}
[Theory]
[InlineData(DbServer.SQLServer)]
private void RunDefaultPKInsertWithGraph(DbServer dbServer)
{
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var department = new Department
{
Name = "Software",
Divisions = new List<Division>
{
new Division{Name = "Student A"},
new Division{Name = "Student B"},
new Division{Name = "Student C"},
}
};
context.BulkInsert(new List<Department> { department }, new BulkConfig { IncludeGraph = true });
};
}
[Theory]
[InlineData(DbServer.SQLServer)]
public void UpsertOrderTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
new EFCoreBatchTest().RunDeleteAll(dbServer);
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Add(new Item { Name = "name 1", Description = "info 1" });
context.Items.Add(new Item { Name = "name 2", Description = "info 2" });
context.SaveChanges();
var entities = new List<Item>();
for (int i = 1; i <= 4; i++)
{
int j = i;
if (i == 1) j = 2;
if (i == 2) j = 1;
entities.Add(new Item
{
Name = "name " + j,
Description = "info x " + j,
});
}
context.BulkInsertOrUpdate(entities, new BulkConfig { SetOutputIdentity = true, UpdateByProperties = new List<string> { nameof(Item.Name) } });
Assert.Equal(2, entities[0].ItemId);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)] // Does NOT have Computed Columns
private void ComputedAndDefaultValuesTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Document>();
bool isSqlite = dbServer == DbServer.SQLite;
var entities = new List<Document>();
for (int i = 1; i <= EntitiesNumber; i++)
{
var entity = new Document
{
Content = "Info " + i
};
if (isSqlite)
{
entity.DocumentId = Guid.NewGuid();
entity.ContentLength = entity.Content.Length;
}
entities.Add(entity);
}
context.BulkInsert(entities, bulkAction => bulkAction.SetOutputIdentity = true); // example of setting BulkConfig with Action argument
var firstDocument = context.Documents.AsNoTracking().FirstOrDefault();
var count = context.Documents.Count();
// TEST
Assert.Equal("DefaultData", firstDocument.Tag);
firstDocument.Tag = null;
var upsertList = new List<Document> {
//firstDocument, // GetPropertiesWithDefaultValue .SelectMany(
new Document { Content = "Info " + (count + 1) }, // to test adding new with InsertOrUpdate (entity having Guid DbGenerated)
new Document { Content = "Info " + (count + 2) }
};
if (isSqlite)
{
upsertList[0].DocumentId = Guid.NewGuid(); //[1]
upsertList[1].DocumentId = Guid.NewGuid(); //[2]
}
count += 2;
context.BulkInsertOrUpdate(upsertList);
firstDocument = context.Documents.AsNoTracking().FirstOrDefault();
var entitiesCount = context.Documents.Count();
//Assert.Null(firstDocument.Tag); // OnUpdate columns with Defaults not omitted, should change even to default value, in this case to 'null'
Assert.NotEqual(Guid.Empty, firstDocument.DocumentId);
Assert.Equal(true, firstDocument.IsActive);
Assert.Equal(firstDocument.Content.Length, firstDocument.ContentLength);
Assert.Equal(entitiesCount, count);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)] // Does NOT have Computed Columns
private void ParameterlessConstructorTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Letter>();
var entities = new List<Letter>();
int counter = 10;
for (int i = 1; i <= counter; i++)
{
var entity = new Letter("Note " + i);
entities.Add(entity);
}
context.BulkInsert(entities);
var count = context.Letters.Count();
var firstDocumentNote = context.Letters.AsNoTracking().FirstOrDefault();
// TEST
Assert.Equal(counter, count);
Assert.Equal("Note 1", firstDocumentNote.Note);
}
[Theory]
[InlineData(DbServer.SQLServer)]
//[InlineData(DbServer.Sqlite)] // No TimeStamp column type but can be set with DefaultValueSql: "CURRENT_TIMESTAMP" as it is in OnModelCreating() method.
private void TimeStampTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<File>();
var entities = new List<File>();
for (int i = 1; i <= EntitiesNumber; i++)
{
var entity = new File
{
Description = "Some data " + i
};
entities.Add(entity);
}
context.BulkInsert(entities, bulkAction => bulkAction.SetOutputIdentity = true); // example of setting BulkConfig with Action argument
// Test BulkRead
var entitiesRead = new List<File>
{
new File { Description = "Some data 1" },
new File { Description = "Some data 2" }
};
context.BulkRead(entitiesRead, new BulkConfig
{
UpdateByProperties = new List<string> { nameof(File.Description) }
});
Assert.Equal(1, entitiesRead.First().FileId);
Assert.NotNull(entitiesRead.First().VersionChange);
// For testing concurrency conflict (UPDATE changes RowVersion which is TimeStamp column)
context.Database.ExecuteSqlRaw("UPDATE dbo.[File] SET Description = 'Some data 1 PRE CHANGE' WHERE [Id] = 1;");
var entitiesToUpdate = entities.Take(10).ToList();
foreach (var entityToUpdate in entitiesToUpdate)
{
entityToUpdate.Description += " UPDATED";
}
using var transaction = context.Database.BeginTransaction();
var bulkConfig = new BulkConfig { SetOutputIdentity = true, DoNotUpdateIfTimeStampChanged = true };
context.BulkUpdate(entitiesToUpdate, bulkConfig);
var list = bulkConfig.TimeStampInfo?.EntitiesOutput.Cast<File>().ToList();
Assert.Equal(9, list.Count());
Assert.Equal(1, bulkConfig.TimeStampInfo.NumberOfSkippedForUpdate);
if (bulkConfig.TimeStampInfo?.NumberOfSkippedForUpdate > 0)
{
//Options, based on needs:
// 1. rollback entire Update
transaction.Rollback(); // 1. rollback entire Update
// 2. throw Exception
//throw new DbUpdateConcurrencyException()
// 3. Update them again
// 4. Skip them and leave it unchanged
}
else
{
transaction.Commit();
}
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void CompositeKeyTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<UserRole>();
// INSERT
var entitiesToInsert = new List<UserRole>();
for (int i = 0; i < EntitiesNumber; i++)
{
entitiesToInsert.Add(new UserRole
{
UserId = i / 10,
RoleId = i % 10,
Description = "desc"
});
}
context.BulkInsert(entitiesToInsert);
// UPDATE
var entitiesToUpdate = context.UserRoles.ToList();
int entitiesCount = entitiesToUpdate.Count();
for (int i = 0; i < entitiesCount; i++)
{
entitiesToUpdate[i].Description = "desc updated " + i;
}
context.BulkUpdate(entitiesToUpdate);
var entitiesToUpsert = new List<UserRole>()
{
new UserRole { UserId = 1, RoleId = 1 },
new UserRole { UserId = 2, RoleId = 2 },
new UserRole { UserId = 100, RoleId = 10 },
};
// TEST
var entities = context.UserRoles.ToList();
Assert.Equal(EntitiesNumber, entities.Count());
context.BulkInsertOrUpdate(entitiesToUpsert, new BulkConfig { PropertiesToInclude = new List<string> { nameof(UserRole.UserId), nameof(UserRole.RoleId) } });
var entitiesFinal = context.UserRoles.ToList();
Assert.Equal(EntitiesNumber + 1, entitiesFinal.Count());
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void DiscriminatorShadowTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.BulkDelete(context.Students.ToList());
// INSERT
var entitiesToInsert = new List<Student>();
for (int i = 1; i <= EntitiesNumber; i++)
{
entitiesToInsert.Add(new Student
{
Name = "name " + i,
Subject = "Math"
});
}
context.Students.AddRange(entitiesToInsert); // adding to Context so that Shadow property 'Discriminator' gets set
context.BulkInsert(entitiesToInsert);
// UPDATE
var entitiesToInsertOrUpdate = new List<Student>();
for (int i = 1; i <= EntitiesNumber / 2; i += 2)
{
entitiesToInsertOrUpdate.Add(new Student
{
Name = "name " + i,
Subject = "Math Upd"
});
}
context.Students.AddRange(entitiesToInsertOrUpdate); // adding to Context so that Shadow property 'Discriminator' gets set
context.BulkInsertOrUpdate(entitiesToInsertOrUpdate, new BulkConfig
{
UpdateByProperties = new List<string> { nameof(Student.Name) },
PropertiesToExclude = new List<string> { nameof(Student.PersonId) },
});
// TEST
var entities = context.Students.ToList();
Assert.Equal(EntitiesNumber, entities.Count());
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void ValueConversionTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.BulkDelete(context.Infos.ToList());
var dateTime = DateTime.Today;
// INSERT
var entitiesToInsert = new List<Info>();
for (int i = 1; i <= EntitiesNumber; i++)
{
entitiesToInsert.Add(new Info
{
Message = "Msg " + i,
ConvertedTime = dateTime,
InfoType = InfoType.InfoTypeA
});
}
context.BulkInsert(entitiesToInsert);
if (dbServer == DbServer.SQLServer)
{
var entities = context.Infos.ToList();
var entity = entities.FirstOrDefault();
Assert.Equal(entity.ConvertedTime, dateTime);
Assert.Equal("logged", entity.GetLogData());
Assert.Equal(DateTime.Today, entity.GetDateCreated());
var conn = context.Database.GetDbConnection();
if (conn.State != ConnectionState.Open)
conn.Open();
using var command = conn.CreateCommand();
command.CommandText = $"SELECT TOP 1 * FROM {nameof(Info)} ORDER BY {nameof(Info.InfoId)} DESC";
var reader = command.ExecuteReader();
reader.Read();
var row = new Info()
{
ConvertedTime = reader.Field<DateTime>(nameof(Info.ConvertedTime))
};
Assert.Equal(row.ConvertedTime, dateTime.AddDays(1));
}
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void OwnedTypesTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
if (dbServer == DbServer.SQLServer)
{
context.Truncate<ChangeLog>();
context.Database.ExecuteSqlRaw("TRUNCATE TABLE [" + nameof(ChangeLog) + "]");
}
else
{
//context.ChangeLogs.BatchDelete(); // TODO
context.BulkDelete(context.ChangeLogs.ToList());
}
var entities = new List<ChangeLog>();
for (int i = 1; i <= EntitiesNumber; i++)
{
entities.Add(new ChangeLog
{
Description = "Dsc " + i,
Audit = new Audit
{
ChangedBy = "User" + 1,
ChangedTime = DateTime.Now,
InfoType = InfoType.InfoTypeA
},
AuditExtended = new AuditExtended
{
CreatedBy = "UserS" + 1,
Remark = "test",
CreatedTime = DateTime.Now
},
AuditExtendedSecond = new AuditExtended
{
CreatedBy = "UserS" + 1,
Remark = "sec",
CreatedTime = DateTime.Now
}
});
}
context.BulkInsert(entities);
if (dbServer == DbServer.SQLServer)
{
context.BulkRead(
entities,
new BulkConfig
{
UpdateByProperties = new List<string> { nameof(Item.Description) }
}
);
Assert.Equal(2, entities[1].ChangeLogId);
}
// TEST
entities[0].Description += " UPD";
entities[0].Audit.InfoType = InfoType.InfoTypeB;
context.BulkUpdate(entities);
if (dbServer == DbServer.SQLServer)
{
context.BulkRead(entities);
}
Assert.Equal("Dsc 1 UPD", entities[0].Description);
Assert.Equal(InfoType.InfoTypeB, entities[0].Audit.InfoType);
}
[Theory]
[InlineData(DbServer.SQLServer)]
//[InlineData(DbServer.Sqlite)] Not supported
private void ShadowFKPropertiesTest(DbServer dbServer) // with Foreign Key as Shadow Property
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
if (dbServer == DbServer.SQLServer)
{
context.Truncate<ItemLink>();
context.Database.ExecuteSqlRaw("TRUNCATE TABLE [" + nameof(ItemLink) + "]");
}
else
{
//context.ChangeLogs.BatchDelete(); // TODO
context.BulkDelete(context.ItemLinks.ToList());
}
//context.BulkDelete(context.Items.ToList()); // On table with FK Truncate does not work
if (context.Items.Count() == 0)
{
for (int i = 1; i <= 10; ++i)
{
var entity = new Item
{
ItemId = 0,
Name = "name " + i,
Description = "info " + Guid.NewGuid().ToString().Substring(0, 3),
Quantity = i % 10,
Price = i / (i % 5 + 1),
TimeUpdated = DateTime.Now,
ItemHistories = new List<ItemHistory>()
};
context.Items.Add(entity);
}
context.SaveChanges();
}
var items = context.Items.ToList();
var entities = new List<ItemLink>();
for (int i = 0; i < EntitiesNumber; i++)
{
entities.Add(new ItemLink
{
ItemLinkId = 0,
Item = items[i % items.Count]
});
}
context.BulkInsert(entities);
if (dbServer == DbServer.SQLServer)
{
List<ItemLink> links = context.ItemLinks.ToList();
Assert.True(links.Count() > 0, "ItemLink row count");
foreach (var link in links)
{
Assert.NotNull(link.Item);
}
}
context.Truncate<ItemLink>();
}
[Theory]
[InlineData(DbServer.SQLServer)]
private void UpsertWithOutputSortTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
new EFCoreBatchTest().RunDeleteAll(dbServer);
var entitiesInitial = new List<Item>();
for (int i = 1; i <= 10; ++i)
{
var entity = new Item { Name = "name " + i };
entitiesInitial.Add(entity);
}
context.Items.AddRange(entitiesInitial);
context.SaveChanges();
var entities = new List<Item>()
{
new Item { ItemId = 0, Name = "name " + 11 + " New" },
new Item { ItemId = 6, Name = "name " + 6 + " Updated" },
new Item { ItemId = 5, Name = "name " + 5 + " Updated" },
new Item { ItemId = 0, Name = "name " + 12 + " New" }
};
context.BulkInsertOrUpdate(entities, new BulkConfig() { SetOutputIdentity = true });
Assert.Equal(11, entities[0].ItemId);
Assert.Equal(6, entities[1].ItemId);
Assert.Equal(5, entities[2].ItemId);
Assert.Equal(12, entities[3].ItemId);
Assert.Equal("name " + 11 + " New", entities[0].Name);
Assert.Equal("name " + 6 + " Updated", entities[1].Name);
Assert.Equal("name " + 5 + " Updated", entities[2].Name);
Assert.Equal("name " + 12 + " New", entities[3].Name);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void NoPrimaryKeyTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
var list = context.Moduls.ToList();
var bulkConfig = new BulkConfig { UpdateByProperties = new List<string> { nameof(Modul.Code) } };
context.BulkDelete(list, bulkConfig);
var list1 = new List<Modul>();
var list2 = new List<Modul>();
for (int i = 1; i <= 20; i++)
{
if (i <= 10)
{
list1.Add(new Modul
{
Code = i.ToString(),
Name = "Name " + i.ToString("00"),
});
}
list2.Add(new Modul
{
Code = i.ToString(),
Name = "Name " + i.ToString("00"),
});
}
context.BulkInsert(list1);
list2[0].Name = "UPD";
context.BulkInsertOrUpdate(list2);
// TEST
Assert.Equal(20, context.Moduls.ToList().Count());
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void NonEntityChildTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
var list = context.Animals.ToList();
context.BulkDelete(list);
var mammalList = new List<Mammal>()
{
new Mammal { Name = "Cat" },
new Mammal { Name = "Dog" }
};
var bulkConfig = new BulkConfig { SetOutputIdentity = true };
context.BulkInsert(mammalList, bulkConfig, type: typeof(Animal));
// TEST
Assert.Equal(2, context.Animals.ToList().Count());
}
[Fact]
private void GeometryColumnTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.BulkDelete(context.Addresses.ToList());
var entities = new List<Address> {
new Address {
Street = "Some Street nn",
LocationGeography = new Point(52, 13),
LocationGeometry = new Point(52, 13),
}
};
context.BulkInsertOrUpdate(entities);
}
[Fact]
private void GeographyAndGeometryArePersistedCorrectlyTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.Addresses.ToList());
}
var point = new Point(52, 13);
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var entities = new List<Address> {
new Address {
Street = "Some Street nn",
LocationGeography = point,
LocationGeometry = point
}
};
context.BulkInsertOrUpdate(entities);
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var address = context.Addresses.Single();
Assert.Equal(point.X, address.LocationGeography.Coordinate.X);
Assert.Equal(point.Y, address.LocationGeography.Coordinate.Y);
Assert.Equal(point.X, address.LocationGeometry.Coordinate.X);
Assert.Equal(point.Y, address.LocationGeometry.Coordinate.Y);
}
}
[Fact]
private void HierarchyIdColumnTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.Categories.ToList());
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var nodeIdAsString = "/1/";
var entities = new List<Category> {
new Category
{
Name = "Root Element",
HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
}
};
context.BulkInsertOrUpdate(entities);
}
}
[Fact]
private void HierarchyIdIsPersistedCorrectlySimpleTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.Categories.ToList());
}
var nodeIdAsString = "/1/";
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var entities = new List<Category> {
new Category
{
Name = "Root Element",
HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
}
};
context.BulkInsertOrUpdate(entities);
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var category = context.Categories.Single();
Assert.Equal(nodeIdAsString, category.HierarchyDescription.ToString());
}
}
[Fact]
private void HierarchyIdIsPersistedCorrectlyLargerHierarchyTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.Categories.ToList());
}
var nodeIdAsString = "/1.1/-2/3/4/5/";
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var entities = new List<Category> {
new Category
{
Name = "Deep Element",
HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
}
};
context.BulkInsertOrUpdate(entities);
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var category = context.Categories.Single();
Assert.Equal(nodeIdAsString, category.HierarchyDescription.ToString());
}
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.PostgreSQL)]
private void DestinationAndSourceTableNameTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Entry>();
context.Truncate<EntryPrep>();
context.Truncate<EntryArchive>();
var entities = new List<Entry>();
for (int i = 1; i <= 10; i++)
{
var entity = new Entry
{
Name = "Name " + i,
};
entities.Add(entity);
}
// [DEST]
context.BulkInsert(entities, b => b.CustomDestinationTableName = nameof(EntryArchive)); // Insert into table 'EntryArchive'
Assert.Equal(10, context.EntryArchives.Count());
// [SOURCE] (With CustomSourceTableName list not used so can be empty)
context.BulkInsert(new List<Entry>(), b => b.CustomSourceTableName = nameof(EntryArchive)); // InsertOrMERGE from table 'EntryArchive' into table 'Entry'
Assert.Equal(10, context.Entries.Count());
var entities2 = new List<EntryPrep>();
for (int i = 1; i <= 20; i++)
{
var entity = new EntryPrep
{
NameInfo = "Name Info " + i,
};
entities2.Add(entity);
}
context.EntryPreps.AddRange(entities2);
context.SaveChanges();
var mappings = new Dictionary<string, string>();
mappings.Add(nameof(EntryPrep.EntryPrepId), nameof(Entry.EntryId)); // here used 'nameof(Prop)' since Columns have the same name as Props
mappings.Add(nameof(EntryPrep.NameInfo), nameof(Entry.Name)); // if columns they were different name then they would be set with string names, eg. "EntryPrepareId"
var bulkConfig = new BulkConfig {
CustomSourceTableName = nameof(EntryPrep),
CustomSourceDestinationMappingColumns = mappings,
//UpdateByProperties = new List<string> { "Name" } // with this all are insert since names are different
};
// [SOURCE]
context.BulkInsertOrUpdate(new List<Entry>(), bulkConfig); // InsertOrMERGE from table 'EntryPrep' into table 'Entry'
Assert.Equal(20, context.Entries.Count());
}
[Fact]
private void TablePerTypeInsertTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.LogPersonReports.Add(new LogPersonReport { }); // used for initial add so that after RESEED it starts from 1, not 0
context.SaveChanges();
context.Truncate<LogPersonReport>();
context.Database.ExecuteSqlRaw($"DELETE FROM {nameof(Log)}");
context.Database.ExecuteSqlRaw($"DBCC CHECKIDENT('{nameof(Log)}', RESEED, 0);");
int nextLogId = GetLastRowId(context, tableName: nameof(Log));
int numberOfNewToInsert = 1000;
var entities = new List<LogPersonReport>();
for (int i = 1; i <= numberOfNewToInsert; i++)
{
nextLogId++; // OPTION 1.
var entity = new LogPersonReport
{
LogId = nextLogId, // OPTION 1.
PersonId = (i % 22),
RegBy = 15,
CreatedDate = DateTime.Now,
ReportId = (i % 22) * 10,
LogPersonReportTypeId = 4,
};
entities.Add(entity);
}
var bulkConfigBase = new BulkConfig
{
SqlBulkCopyOptions = Microsoft.Data.SqlClient.SqlBulkCopyOptions.KeepIdentity, // OPTION 1. - to ensure insert order is kept the same since SqlBulkCopy does not guarantee it.
PropertiesToInclude = new List<string>
{
nameof(LogPersonReport.LogId),
nameof(LogPersonReport.PersonId),
nameof(LogPersonReport.RegBy),
nameof(LogPersonReport.CreatedDate)
}
};
var bulkConfig = new BulkConfig
{
PropertiesToInclude = new List<string> {
nameof(LogPersonReport.LogId),
nameof(LogPersonReport.ReportId),
nameof(LogPersonReport.LogPersonReportTypeId)
}
};
context.BulkInsert(entities, bulkConfigBase, type: typeof(Log)); // to base 'Log' table
//foreach(var entity in entities) { // OPTION 2. Could be set here if Id of base table Log was set by Db (when Op.2. used 'Option 1.' have to be commented out)
// entity.LogId = ++nextLogId;
//}
context.BulkInsert(entities, bulkConfig); // to 'LogPersonReport' table
Assert.Equal(nextLogId, context.LogPersonReports.OrderByDescending(a => a.LogId).FirstOrDefault().LogId);
}
[Fact]
private void TableWithSpecialRowVersion()
{
ContextUtil.DbServer = DbServer.SQLServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.AtypicalRowVersionEntities.BatchDelete();
context.AtypicalRowVersionConverterEntities.BatchDelete();
var bulk = new List<AtypicalRowVersionEntity>();
for (var i = 0; i < 100; i++)
bulk.Add(new AtypicalRowVersionEntity { Id = Guid.NewGuid(), Name = $"Row {i}", RowVersion = i, SyncDevice = "Test" });
//Assert.Throws<InvalidOperationException>(() => context.BulkInsertOrUpdate(bulk)); // commented since when running in Debug mode it pauses on Exception
context.BulkInsertOrUpdate(bulk, new BulkConfig { IgnoreRowVersion = true });
Assert.Equal(bulk.Count(), context.AtypicalRowVersionEntities.Count());
var bulk2 = new List<AtypicalRowVersionConverterEntity>();
for (var i = 0; i < 100; i++)
bulk2.Add(new AtypicalRowVersionConverterEntity { Id = Guid.NewGuid(), Name = $"Row {i}" });
context.BulkInsertOrUpdate(bulk2);
Assert.Equal(bulk2.Count(), context.AtypicalRowVersionConverterEntities.Count());
}
private int GetLastRowId(DbContext context, string tableName)
{
var sqlConnection = context.Database.GetDbConnection();
sqlConnection.Open();
using var command = sqlConnection.CreateCommand();
command.CommandText = $"SELECT IDENT_CURRENT('{tableName}')";
int lastRowIdScalar = Convert.ToInt32(command.ExecuteScalar());
return lastRowIdScalar;
}
[Fact]
private void CustomPrecisionDateTimeTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.BulkDelete(context.Events.ToList());
var entities = new List<Event>();
for (int i = 1; i <= 10; i++)
{
var entity = new Event
{
Name = "Event " + i,
TimeCreated = DateTime.Now
};
var testTime = new DateTime(2020, 1, 1, 12, 45, 20, 324);
if (i == 1)
{
entity.TimeCreated = testTime.AddTicks(6387); // Ticks will be 3256387 when rounded to 3 digits: 326 ms
}
if (i == 2)
{
entity.TimeCreated = testTime.AddTicks(5000); // Ticks will be 3255000 when rounded to 3 digits: 326 ms (middle .5zeros goes to Upper)
}
var fullDateTimeFormat = "yyyy-MM-dd HH:mm:ss.fffffff";
entity.Description = entity.TimeCreated.ToString(fullDateTimeFormat);
entities.Add(entity);
}
bool useBulk = true;
if (useBulk)
{
context.BulkInsert(entities, b => b.DateTime2PrecisionForceRound = false);
}
else
{
context.AddRange(entities);
context.SaveChanges();
}
// TEST
Assert.Equal(3240000, context.Events.SingleOrDefault(a => a.Name == "Event 1").TimeCreated.Ticks % 10000000);
Assert.Equal(3240000, context.Events.SingleOrDefault(a => a.Name == "Event 2").TimeCreated.Ticks % 10000000);
}
[Fact]
private void ByteArrayPKBulkReadTest()
{
ContextUtil.DbServer = DbServer.SQLite;
using var context = new TestContext(ContextUtil.GetOptions());
var list = context.Archives.ToList();
if (list.Count > 0)
{
context.Archives.RemoveRange(list);
context.SaveChanges();
}
var byte1 = new byte[] { 0x10, 0x10 };
var byte2 = new byte[] { 0x20, 0x20 };
var byte3 = new byte[] { 0x30, 0x30 };
context.Archives.AddRange(
new Archive { ArchiveId = byte1, Description = "Desc1" },
new Archive { ArchiveId = byte2, Description = "Desc2" },
new Archive { ArchiveId = byte3, Description = "Desc3" }
);
context.SaveChanges();
var entities = new List<Archive>();
entities.Add(new Archive { ArchiveId = byte1 });
entities.Add(new Archive { ArchiveId = byte2 });
context.BulkRead(entities);
Assert.Equal("Desc1", entities[0].Description);
Assert.Equal("Desc2", entities[1].Description);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void PrivateKeyTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.PrivateKeys.ToList());
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var entities = new List<PrivateKey> {
new()
{
Name = "foo"
}
};
context.BulkInsertOrUpdate(entities);
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var defaultValueTest = context.PrivateKeys.Single();
Assert.Equal("foo", defaultValueTest.Name);
}
}
}
}
| 38.590179 | 190 | 0.520885 | [
"MIT"
] | Hoffs/EFCore.BulkExtensions | EFCore.BulkExtensions.Tests/EFCoreBulkTestAtypical.cs | 40,867 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Node
{
public bool walkable;
public Vector3 worldPosition;
public int gridX;
public int gridY;
public int gCost; //Cost from startpoint
public int hCost; //Cost to reach the endpoint
public Node parent;
public Node(bool _walkable,Vector3 _worldPos, int _gridX, int _gridY) {
walkable = _walkable;
worldPosition = _worldPos;
gridX = _gridX;
gridY = _gridY;
}
public int fCost //gCost+hCost
{
get
{
return gCost + hCost;
}
}
} | 21.2 | 75 | 0.627358 | [
"MIT"
] | roberko44/Routenwahlverfahren | Pathfinding with grids/Assets/Node.cs | 636 | C# |
/*
* Copyright 2010-2014 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 ec2-2014-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes the instance status.
/// </summary>
public partial class InstanceStatusDetails
{
private DateTime? _impairedSince;
private StatusName _name;
private StatusType _status;
/// <summary>
/// Gets and sets the property ImpairedSince.
/// <para>
/// The time when a status check failed. For an instance that was launched and impaired,
/// this is the time when the instance was launched.
/// </para>
/// </summary>
public DateTime ImpairedSince
{
get { return this._impairedSince.GetValueOrDefault(); }
set { this._impairedSince = value; }
}
// Check to see if ImpairedSince property is set
internal bool IsSetImpairedSince()
{
return this._impairedSince.HasValue;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The type of instance status.
/// </para>
/// </summary>
public StatusName 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 Status.
/// <para>
/// The status.
/// </para>
/// </summary>
public StatusType Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
}
} | 28.168421 | 101 | 0.588191 | [
"Apache-2.0"
] | amazon-archives/aws-sdk-xamarin | AWS.XamarinSDK/AWSSDK_Android/Amazon.EC2/Model/InstanceStatusDetails.cs | 2,676 | C# |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Dolittle.Runtime.Microservices;
namespace Dolittle.Runtime.CLI.Runtime
{
/// <summary>
/// Defines a system that can locate Runtimes that are available to connect to.
/// </summary>
public interface ICanLocateRuntimes
{
/// <summary>
/// Gets the addresses of Runtimes that are available to connect to, or the address provided in the argument.
/// </summary>
/// <param name="argument">An optional address provided to the CLI as an argument.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of type <see cref="MicroserviceAddress"/> to available Runtimes.</returns>
Task<IEnumerable<MicroserviceAddress>> GetAvailableRuntimeAddresses(MicroserviceAddress argument = null);
}
}
| 42.347826 | 127 | 0.710472 | [
"MIT"
] | dolittle/Runtime | Source/CLI/Runtime/ICanLocateRuntimes.cs | 974 | C# |
/*
Copyright (c), 2011,2012 JASDev International http://www.jasdev.com
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
*/
using System.Text;
using System.Collections;
namespace JDI.NETMF.Web
{
public class HtmlDataReader : HtmlReader
{
#region Constructors / Destructors
/// <summary>
/// Constructor..
/// </summary>
/// <param name="sourceHtml">Byte array containing source Html.</param>
/// <param name="tokens">Token name-value pairs.</param>
/// <param name="tokenDelimiter">Token name delimiter.</param>
/// <param name="lineBufferSize">Line buffer size. Must be larger than longest line length including \r\n.</param>
public HtmlDataReader(byte[] sourceHtml, Hashtable tokens, char tokenDelimiter = '~', int lineBufferSize = constLineBufferSize)
: base(tokens, tokenDelimiter, lineBufferSize)
{
this.sourceHtml = sourceHtml;
this.sourceIndex = 0;
}
/// <summary>
/// Constructor..
/// </summary>
/// <param name="sourceHtml">String containing source Html.</param>
/// <param name="tokens">Token name-value pairs.</param>
/// <param name="tokenDelimiter">Token name delimiter.</param>
/// <param name="lineBufferSize">Line buffer size. Must be larger than longest line length including \r\n.</param>
public HtmlDataReader(string sourceHtml, Hashtable tokens, char tokenDelimiter = '~', int lineBufferSize = constLineBufferSize)
: base(tokens, tokenDelimiter, lineBufferSize)
{
this.sourceHtml = Encoding.UTF8.GetBytes(sourceHtml);
this.sourceIndex = 0;
}
public override void Dispose()
{
this.sourceHtml = null;
base.Dispose();
}
#endregion
#region Line Processing Methods
// Returns next byte from source Html.
protected override int GetNextByte()
{
if (this.sourceIndex < this.sourceHtml.Length)
{
return this.sourceHtml[this.sourceIndex++];
}
return -1; // eos
}
#endregion
#region Fields
protected byte[] sourceHtml;
protected int sourceIndex;
#endregion
}
}
| 27.988372 | 129 | 0.710428 | [
"MIT"
] | devdotnetdotorg/FEZ-Domino-Bell | Work_files/363_363_FEZ_Connect_Web_Server_1.4/FEZ Connect Web Server 1.4/FEZConnect WebServer/JDI/Web/HtmlDataReader.cs | 2,407 | C# |
using System;
using System.Data;
using System.Web;
using GroupDocs.Watermark.Live.Demos.UI.Config;
namespace GroupDocs.Watermark.Live.Demos.UI.Config
{
public class BasePage : BaseRootPage
{
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
if (String.IsNullOrEmpty(Page.Title))
{
if (Resources != null)
{
Page.Title = Resources["ApplicationTitle"];
}
}
}
base.OnLoad(e);
}
protected string GetAsposeUnlockProduct(string fileName)
{
string asposeProduct = null;
string ext = System.IO.Path.GetExtension(fileName).ToLower();
if (ext == ".pdf")
{
asposeProduct = "PDF";
}
else if (ext == ".one")
{
asposeProduct = "Note";
}
else if (".doc .docx .dot .dotx .odt .ott".Contains(ext))
{
asposeProduct = "Words";
}
else if (".xls .xlsx .xlsm .xlsb .ods".Contains(ext))
{
asposeProduct = "Cells";
}
else if (".ppt .pptx .odp".Contains(ext))
{
asposeProduct = "Slides";
}
return asposeProduct;
}
}
} | 22.540984 | 73 | 0.509091 | [
"MIT"
] | groupdocs-watermark/GroupDocs.Watermark-for-.NET | Demos/LiveDemos/src/GroupDocs.Watermark.Live.Demos.UI/Config/BasePage.cs | 1,377 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AntMerchantExpandActivitySignupQueryModel Data Structure.
/// </summary>
public class AntMerchantExpandActivitySignupQueryModel : AlipayObject
{
/// <summary>
/// 参数名:活动标识 应用场景:天猫小二帮某商家报名活动 如何获取:该活动code需要由活动中心新增活动后运营提供给天猫。
/// </summary>
[JsonPropertyName("activity_code")]
public string ActivityCode { get; set; }
/// <summary>
/// 报名信息扩展字段,可为空,具体传参由开发约定
/// </summary>
[JsonPropertyName("ext_info")]
public string ExtInfo { get; set; }
}
}
| 28.782609 | 73 | 0.634441 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AntMerchantExpandActivitySignupQueryModel.cs | 812 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static GeneticAlgorithm.GeneticAlgorithm;
namespace GeneticAlgorithm
{
public static class Functions
{
public static double Fitness(FitnessFunction ff, double[] values)
{
switch (ff)
{
case FitnessFunction.Rastrigin:
return Rastrigin(values);
case FitnessFunction.Custom:
return Custom(values);
default:
return 0.0;
}
}
public static double Rastrigin(double[] values)
{
//y = A*n + SUM[xi² - A*cos(2*pi*xi)]
//A = 10
const double A = 10;
double y = A * values.Length; //y = A*n
for (int i = 0; i < values.Length; i++)
{
y += Math.Pow(values[i], 2) - A * Math.Cos(2 * Math.PI * values[i]);
}
return y;
}
public static double Custom(double[] value)
{
/*
Create your own function here!
*/
return 0.0;
}
}
}
| 24.5 | 84 | 0.481633 | [
"MIT"
] | brunocharamba/ALGntc | GeneticAlgorithm/Functions.cs | 1,228 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
namespace Microsoft.Diagnostics.Tools.RuntimeClient.DiagnosticsIpc
{
public class IpcClient
{
private static string DiagnosticPortPattern { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"^dotnet-diagnostic-(\d+)$" : @"^dotnet-diagnostic-(\d+)-(\d+)-socket$";
private static string IpcRootPath { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"\\.\pipe\" : Path.GetTempPath();
private static double ConnectTimeoutMilliseconds { get; } = TimeSpan.FromSeconds(3).TotalMilliseconds;
/// <summary>
/// Get the OS Transport to be used for communicating with a dotnet process.
/// </summary>
/// <param name="processId">The PID of the dotnet process to get the transport for</param>
/// <returns>A System.IO.Stream wrapper around the transport</returns>
private static Stream GetTransport(int processId)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
string pipeName = $"dotnet-diagnostic-{processId}";
var namedPipe = new NamedPipeClientStream(
".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
namedPipe.Connect((int)ConnectTimeoutMilliseconds);
return namedPipe;
}
else
{
string ipcPort = Directory.GetFiles(IpcRootPath) // Try best match.
.Select(namedPipe => (new FileInfo(namedPipe)).Name)
.SingleOrDefault(input => Regex.IsMatch(input, $"^dotnet-diagnostic-{processId}-(\\d+)-socket$"));
if (ipcPort == null)
{
throw new PlatformNotSupportedException($"Process {processId} not running compatible .NET Core runtime");
}
string path = Path.Combine(Path.GetTempPath(), ipcPort);
var remoteEP = new UnixDomainSocketEndPoint(path);
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
socket.Connect(remoteEP);
return new NetworkStream(socket);
}
}
/// <summary>
/// Sends a single DiagnosticIpc Message to the dotnet process with PID processId.
/// </summary>
/// <param name="processId">The PID of the dotnet process</param>
/// <param name="message">The DiagnosticsIpc Message to be sent</param>
/// <returns>The response DiagnosticsIpc Message from the dotnet process</returns>
public static IpcMessage SendMessage(int processId, IpcMessage message)
{
using (var stream = GetTransport(processId))
{
Write(stream, message);
return Read(stream);
}
}
/// <summary>
/// Sends a single DiagnosticIpc Message to the dotnet process with PID processId
/// and returns the Stream for reuse in Optional Continuations.
/// </summary>
/// <param name="processId">The PID of the dotnet process</param>
/// <param name="message">The DiagnosticsIpc Message to be sent</param>
/// <param name="response">out var for response message</param>
/// <returns>The response DiagnosticsIpc Message from the dotnet process</returns>
public static Stream SendMessage(int processId, IpcMessage message, out IpcMessage response)
{
var stream = GetTransport(processId);
Write(stream, message);
response = Read(stream);
return stream;
}
private static void Write(Stream stream, byte[] buffer)
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, true))
{
writer.Write(buffer);
}
}
private static void Write(Stream stream, IpcMessage message)
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, true))
{
writer.Write(message.Serialize());
}
}
private static IpcMessage Read(Stream stream)
{
return IpcMessage.Parse(stream);
}
}
}
| 41.688073 | 190 | 0.608715 | [
"Apache-2.0"
] | brianrob/Benchmarks | src/BenchmarksServer/Microsoft.Diagnostics.Tools.RuntimeClient/DiagnosticsIpc/IpcClient.cs | 4,546 | C# |
/*
* Copyright 2010-2014 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 dms-2016-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DatabaseMigrationService.Model
{
/// <summary>
///
/// </summary>
public partial class RemoveTagsFromResourceResponse : AmazonWebServiceResponse
{
}
} | 28.702703 | 101 | 0.730697 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/DatabaseMigrationService/Generated/Model/RemoveTagsFromResourceResponse.cs | 1,062 | C# |
/*
*Copyright (c) 2011 Seth Ballantyne <seth.ballantyne@gmail.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.Collections.Generic;
using System.Text;
namespace EraserBotFrontend
{
/// <summary>
/// Represents an installed model and all its available skins. The Model class is only
/// used in conjunction with the mesh renderer.
/// </summary>
class Model
{
string modelName;
List<string> skins = new List<string>();
/// <summary>
///
/// </summary>
/// <param name="modelName"></param>
/// <param name="modelSkins"></param>
public Model(string modelName, string[] modelSkins)
{
this.modelName = modelName;
skins.AddRange(modelSkins);
}
/// <summary>
/// Filename of the model, minus the file extension.
/// </summary>
public string Name
{
get { return modelName; }
set { modelName = value; }
}
/// <summary>
/// string array containing the names of all installed skins available for the model.
/// </summary>
public string[] Skins
{
get { return skins.ToArray(); }
set { skins.AddRange(value); }
}
}
}
| 35.058824 | 95 | 0.638003 | [
"MIT"
] | sethballantyne/eraser-bot-frontend | EraserBotFrontend/Model.cs | 2,386 | C# |
using System;
using Csla;
using Invoices.DataAccess;
namespace Invoices.DataAccess.SQLite
{
public partial class ProductSupplierItemDal
{
}
}
| 15 | 48 | 0.70303 | [
"MIT"
] | CslaGenFork/CslaGenFork | trunk/CoverageTest/Invoices-CS-DAL-DTO-INT64/Invoices.DataAccess.SQLite/ProductSupplierItemDal.cs | 165 | C# |
using OpenTK.Graphics.OpenGL;
using System;
namespace Ryujinx.Graphics.Gal.OpenGL
{
class OGLConstBuffer : IGalConstBuffer
{
private OGLCachedResource<OGLStreamBuffer> Cache;
public OGLConstBuffer()
{
Cache = new OGLCachedResource<OGLStreamBuffer>(DeleteBuffer);
}
public void LockCache()
{
Cache.Lock();
}
public void UnlockCache()
{
Cache.Unlock();
}
public void Create(long Key, long Size)
{
OGLStreamBuffer Buffer = new OGLStreamBuffer(BufferTarget.UniformBuffer, Size);
Cache.AddOrUpdate(Key, Buffer, Size);
}
public bool IsCached(long Key, long Size)
{
return Cache.TryGetSize(Key, out long CachedSize) && CachedSize == Size;
}
public void SetData(long Key, long Size, IntPtr HostAddress)
{
if (Cache.TryGetValue(Key, out OGLStreamBuffer Buffer))
{
Buffer.SetData(Size, HostAddress);
}
}
public bool TryGetUbo(long Key, out int UboHandle)
{
if (Cache.TryGetValue(Key, out OGLStreamBuffer Buffer))
{
UboHandle = Buffer.Handle;
return true;
}
UboHandle = 0;
return false;
}
private static void DeleteBuffer(OGLStreamBuffer Buffer)
{
Buffer.Dispose();
}
}
} | 23.65625 | 91 | 0.540291 | [
"Unlicense"
] | 0x0ade/Ryujinx | Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs | 1,516 | C# |
namespace Xilium.Chromium.DevTools.Syntax
{
public abstract class SyntaxObject
{
}
}
| 12.375 | 42 | 0.686869 | [
"MIT"
] | CefNet/crdtp | src/Tools/Xilium.Crdtp.CSharp.Syntax/SyntaxObject.cs | 101 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Apocryph.FunctionApp.Model;
using Ipfs;
using Ipfs.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Perper.WebJobs.Extensions.Bindings;
using Perper.WebJobs.Extensions.Config;
using Perper.WebJobs.Extensions.Model;
using Perper.WebJobs.Extensions.Triggers;
namespace Apocryph.FunctionApp.Ipfs
{
public static class IpfsLoader
{
[FunctionName(nameof(IpfsLoader))]
public static async Task Run([PerperStreamTrigger] PerperStreamContext context,
[Perper("ipfsGateway")] string ipfsGateway,
[PerperStream("hashStream")] IAsyncEnumerable<Hash> hashStream,
[PerperStream("outputStream")] IAsyncCollector<IHashed<object>> outputStream,
ILogger logger)
{
var ipfs = new IpfsClient(ipfsGateway);
await hashStream.ForEachAsync(async hash =>
{
try
{
// NOTE: Currently blocks other items on the stream and does not process them
// -- we should at least timeout
var jToken = await ipfs.Dag.GetAsync(Cid.Read(hash.Bytes), CancellationToken.None);
var item = jToken.ToObject<object>(JsonSerializer.Create(IpfsJsonSettings.DefaultSettings));
await outputStream.AddAsync(Hashed.Create(item, hash));
}
catch (Exception e)
{
logger.LogError(e.ToString());
}
}, CancellationToken.None);
}
}
} | 35 | 112 | 0.633236 | [
"MIT"
] | cyppan/apocryph | src/Apocryph.FunctionApp/Ipfs/IpfsLoader.cs | 1,719 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: get.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Kronos.Core.Messages {
/// <summary>Holder for reflection information generated from get.proto</summary>
public static partial class GetReflection {
#region Descriptor
/// <summary>File descriptor for get.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GetReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CglnZXQucHJvdG8iGQoKR2V0UmVxdWVzdBILCgNrZXkYASABKAkiKwoLR2V0",
"UmVzcG9uc2USDgoGZXhpc3RzGAEgASgIEgwKBGRhdGEYAiABKAxCF6oCFEty",
"b25vcy5Db3JlLk1lc3NhZ2VzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Kronos.Core.Messages.GetRequest), global::Kronos.Core.Messages.GetRequest.Parser, new[]{ "Key" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Kronos.Core.Messages.GetResponse), global::Kronos.Core.Messages.GetResponse.Parser, new[]{ "Exists", "Data" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class GetRequest : pb::IMessage<GetRequest> {
private static readonly pb::MessageParser<GetRequest> _parser = new pb::MessageParser<GetRequest>(() => new GetRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Kronos.Core.Messages.GetReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRequest(GetRequest other) : this() {
key_ = other.key_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRequest Clone() {
return new GetRequest(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 1;
private string key_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Key {
get { return key_; }
set {
key_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Key != other.Key) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Key.Length != 0) hash ^= Key.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Key.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Key);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Key.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Key);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetRequest other) {
if (other == null) {
return;
}
if (other.Key.Length != 0) {
Key = other.Key;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Key = input.ReadString();
break;
}
}
}
}
}
public sealed partial class GetResponse : pb::IMessage<GetResponse> {
private static readonly pb::MessageParser<GetResponse> _parser = new pb::MessageParser<GetResponse>(() => new GetResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Kronos.Core.Messages.GetReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetResponse(GetResponse other) : this() {
exists_ = other.exists_;
data_ = other.data_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetResponse Clone() {
return new GetResponse(this);
}
/// <summary>Field number for the "exists" field.</summary>
public const int ExistsFieldNumber = 1;
private bool exists_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Exists {
get { return exists_; }
set {
exists_ = value;
}
}
/// <summary>Field number for the "data" field.</summary>
public const int DataFieldNumber = 2;
private pb::ByteString data_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Data {
get { return data_; }
set {
data_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Exists != other.Exists) return false;
if (Data != other.Data) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Exists != false) hash ^= Exists.GetHashCode();
if (Data.Length != 0) hash ^= Data.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Exists != false) {
output.WriteRawTag(8);
output.WriteBool(Exists);
}
if (Data.Length != 0) {
output.WriteRawTag(18);
output.WriteBytes(Data);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Exists != false) {
size += 1 + 1;
}
if (Data.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetResponse other) {
if (other == null) {
return;
}
if (other.Exists != false) {
Exists = other.Exists;
}
if (other.Data.Length != 0) {
Data = other.Data;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Exists = input.ReadBool();
break;
}
case 18: {
Data = input.ReadBytes();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| 31.990964 | 191 | 0.653422 | [
"MIT"
] | lukasz-pyrzyk/Kronos | Src/Kronos.Core/Messages/Get.cs | 10,621 | C# |
using System;
using Prism.Mvvm;
namespace PrismSample
{
/// <summary>エンティティ系モデルクラス。</summary>
public class Person : BindableBase
{
private int? id = null;
/// <summary>IDを取得・設定します。</summary>
public int? Id
{
get { return id; }
set { SetProperty(ref id, value); }
}
private string name = string.Empty;
/// <summary>名前を取得・設定します。</summary>
public string Name
{
get { return name; }
set { SetProperty(ref name, value); }
}
private DateTime? birthday = null;
/// <summary>誕生日を取得・設定します。</summary>
public DateTime? BirthDay
{
get { return birthday; }
set
{
SetProperty(ref birthday, value);
if (value.HasValue)
this.Age = DateTime.Now.Year - value.Value.Year;
}
}
private int age = 0;
/// <summary>年齢を取得します。</summary>
public int Age
{
get { return age; }
private set { SetProperty(ref age, value); }
}
public string Kana { get; set; } = string.Empty;
/// <summary>性別(男:1、女:2)を取得・設定します。</summary>
public int? Sex { get; set; } = null;
public override string ToString()
{
return @$"クラス名: {nameof(Person)}
{nameof(this.Id)}: {this.Id}
{nameof(this.Name)}: {this.Name}
{nameof(this.BirthDay)}: {this.BirthDay}";
}
}
//public class Person
//{
// public int Id { get; set; } = 0;
// public string Name { get; set; } = string.Empty;
// public string Kana { get; set; } = string.Empty;
// public DateTime? BirthDay { get; set; } = null;
// /// <summary>性別(男:1、女:2)を取得・設定します。</summary>
// public int? Sex { get; set; } = null;
//}
}
| 20.051948 | 53 | 0.611399 | [
"Apache-2.0"
] | YouseiSakusen/WpfGettingStarted2020 | 08_Step09/SampleModels/Person.cs | 1,754 | C# |
using RSDKv5;
namespace ManiacEditor.Entity_Renders
{
public class Vultron : EntityRenderer
{
public override void Draw(Structures.EntityRenderProp Properties)
{
DevicePanel d = Properties.Graphics;
Classes.Scene.EditorEntity e = Properties.EditorObject;
int x = Properties.DrawX;
int y = Properties.DrawY;
int Transparency = Properties.Transparency;
bool fliph = false;
bool flipv = false;
int type = (int)e.attributesMap["type"].ValueUInt8;
int direction = (int)e.attributesMap["direction"].ValueUInt8;
int frameID;
switch (type)
{
case 0:
frameID = 0;
break;
case 1:
frameID = 5;
break;
default:
frameID = 0;
break;
}
switch(direction)
{
case 0:
fliph = false;
break;
case 1:
fliph = true;
break;
default:
fliph = false;
break;
}
var Animation = LoadAnimation("MSZ/Vultron.bin", d, 0, frameID);
DrawTexturePivotNormal(d, Animation, Animation.RequestedAnimID, Animation.RequestedFrameID, x, y, Transparency, fliph, flipv);
}
public override string GetObjectName()
{
return "Vultron";
}
}
}
| 27.116667 | 138 | 0.4622 | [
"MIT"
] | CarJem/ManiacEditor | ManiacEditor/Entity Renders/Normal Renders/Badniks/Vultron.cs | 1,629 | C# |
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace ToDoMini
{
public class ToDoMini : EditorWindow
{
static ToDoMini window;
ToDoMiniData dataHolder;
ToDoMiniData Data
{
get
{
if (dataHolder == null || shouldRefreshData)
{
ToDoMiniData testDataHolder =
Resources.Load<ToDoMiniData>(dataPath);
dataHolder = AssetDatabase.LoadAssetAtPath(dataPath, typeof(ToDoMiniData)) as ToDoMiniData;
if (dataHolder == null)
{
dataHolder = CreateInstance(typeof(ToDoMiniData)) as ToDoMiniData;
AssetDatabase.CreateAsset(dataHolder, dataPath);
GUI.changed = true;
}
shouldRefreshData = false;
}
return dataHolder;
}
}
readonly string dataPath = "Packages/com.lone.unityextensions/Extensions/ToDo Mini/ToDoMini data.asset";
public static bool shouldRefreshData;
readonly string taskAreaName = "miniTaskArea";
Vector2 scrollPosition;
bool shouldDrawCompletedTasks;
GUIStyle taskStyle;
GUIStyle completedTaskStyle;
int lastTextArea = -1;
int ButtonsCompactFontSize
{
get
{
#if UNITY_2019_1_OR_NEWER
return 11;
#else
return 9;
#endif
}
}
string newTask = "";
readonly static string newTaskFieldName = "miniNewTask";
static bool shouldRefocusOnNewTask;
bool returnWasPressed;
bool IsPressingReturn
{
get { return Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter; }
}
bool IsPressingEsc
{
get { return Event.current.keyCode == KeyCode.Escape; }
}
public enum DisplayDensity
{
Default,
Compact
}
string currentSearch;
SearchField searchField;
public void OnGUI()
{
DrawSearchAndSettings();
#region Draw tasks and search results.
// Update styles.
taskStyle = new GUIStyle("CN CountBadge")
{
alignment = TextAnchor.MiddleLeft,
wordWrap = true
};
if (Data.displayDensity == DisplayDensity.Compact)
{
RectOffset taskPadding = taskStyle.padding;
taskPadding.top = 3;
taskPadding.bottom = 0;
taskStyle.padding = taskPadding;
RectOffset taskMargin = taskStyle.margin;
taskMargin.top = taskMargin.bottom = 0;
taskStyle.margin = taskMargin;
}
completedTaskStyle = new GUIStyle(taskStyle);
completedTaskStyle.normal.textColor = completedTaskStyle.hover.textColor = Color.grey;
// Draw search results, or tasks.
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
if (!string.IsNullOrEmpty(currentSearch))
DrawSearchResults();
else
{
DrawCurrentTasks();
if (Data.items.Count > 0 && Data.keepCompletedTasks)
DrawCompletedTasksButton();
if (Data.items.Count > 0 && Data.keepCompletedTasks && shouldDrawCompletedTasks)
DrawCompletedTasks();
}
EditorGUILayout.EndScrollView();
#endregion
DrawNewTaskPanel();
if (focusedWindow == this && GUIUtility.hotControl != 0)
{
// If a task area is selected, save when we change control or when we lose focus.
if (GUI.GetNameOfFocusedControl() == taskAreaName)
lastTextArea = GUIUtility.hotControl;
else if (lastTextArea >= 0 && lastTextArea != GUIUtility.hotControl)
{
lastTextArea = -1;
Save();
}
// Stop the search if we are into the newTask field.
if (GUI.GetNameOfFocusedControl() == newTaskFieldName)
{
EmptySearch();
shouldRefocusOnNewTask = true;
}
}
}
void OnLostFocus()
{
// Save the previous text area.
if (lastTextArea >= 0)
{
lastTextArea = -1;
Save();
}
EmptySearch();
}
void OnDestroy()
{
if (Data)
Save();
}
[MenuItem("Window/通用/ToDo Mini %t")]
public static void Open()
{
// Get existing open window or if none, make a new one.
window = GetWindow<ToDoMini>(false);
window.titleContent = new GUIContent("☑ ToDo");
window.autoRepaintOnSceneChange = false;
window.minSize = new Vector2(150, 150);
window.Focus();
//window.ShowModalUtility();
shouldRefocusOnNewTask = true;
window.EmptySearch();
}
void DrawSearchAndSettings()
{
GUILayout.BeginHorizontal(GUI.skin.FindStyle("Toolbar"));
// Searchbar.
#if UNITY_2019_1_OR_NEWER
GUILayout.Space(3);
#endif
Rect searchRect = GUILayoutUtility.GetRect(1, 1, 18, 18, GUILayout.ExpandWidth(true));
searchRect.y += 2;
if (searchField == null)
searchField = new SearchField();
currentSearch = searchField.OnToolbarGUI(searchRect, currentSearch);
// Settings cog.
#if UNITY_2019_1_OR_NEWER
GUILayout.Space(-3);
#else
GUILayout.Space(5);
#endif
if (GUI.Button(
EditorGUILayout.GetControlRect(false, 20, GUILayout.MaxWidth(20)),
EditorGUIUtility.IconContent("_Popup"),
GUI.skin.FindStyle("IconButton")))
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("设置"), false, () =>
{
// Open the inspector and select the Data object.
EditorApplication.ExecuteMenuItem(
#if UNITY_2018_1_OR_NEWER
"Window/General/Inspector"
#else
"Window/Inspector"
#endif
);
if (Selection.activeObject == Data)
EditorGUIUtility.PingObject(Data);
else
Selection.SetActiveObjectWithContext(Data, null);
});
menu.ShowAsContext();
}
#if UNITY_2019_1_OR_NEWER
GUILayout.Space(-2);
#else
GUILayout.Space(-5);
#endif
GUILayout.EndHorizontal();
}
void DrawCurrentTasks()
{
// IsSearching? Draw search results and stop.
if (!string.IsNullOrEmpty(currentSearch))
{
List<int> items = FindItems(currentSearch);
foreach (var item in items)
{
if (!Data.items[item].isComplete)
DrawTask(item);
else
DrawCompletedTask(item);
}
return;
}
// Draw tasks.
bool hasUncompletedTasks = false;
for (int i = 0; i < Data.items.Count; i++)
{
TodoItem item = Data.items[i];
if (item.isComplete)
continue;
hasUncompletedTasks = true;
DrawTask(i);
}
// Draw a message if there are no tasks.
if (!hasUncompletedTasks)
{
EditorGUILayout.HelpBox("无任务", MessageType.Info);
}
}
void DrawTask(int i)
{
EditorGUILayout.BeginHorizontal();
// Toggle.
if (EditorGUILayout.Toggle(Data.items[i].isComplete, GUILayout.Width(12)))
{
if (Data.keepCompletedTasks)
{
Data.items[i].isComplete = true;
Save();
}
else
{
DeleteTask(i);
return;
}
}
// Task content.
GUI.SetNextControlName(taskAreaName);
//绘制Task
Data.items[i].task = EditorGUILayout.TextArea(Data.items[i].task, taskStyle);
// Draw ↑↓✖.
DrawUpDown(i);
GUILayout.Space(Data.displayDensity == DisplayDensity.Default ? 1 : -2);
DrawDelete(i);
EditorGUILayout.EndHorizontal();
}
#region Right-hand side buttons.
void DrawUpDown(int i)
{
GUIStyle upDownStyle = new GUIStyle(GUI.skin.button)
{
fixedWidth = Data.displayDensity == DisplayDensity.Compact ? 13 : 15,
padding = new RectOffset(5, 3, 2, 3),
};
if (Data.displayDensity == DisplayDensity.Compact)
{
upDownStyle.fixedHeight = 16;
upDownStyle.fontSize = ButtonsCompactFontSize;
}
if (GUILayout.Button("↑", upDownStyle) && i > 0)
{
Undo.RecordObject(Data, "上移任务");
Data.items.Insert(0, Data.items[i]);
Data.items.RemoveAt(i + 1);
Save();
}
GUILayout.Space(-4);
if (GUILayout.Button("↓", upDownStyle) && i < Data.items.Count)
{
Undo.RecordObject(Data, "下移任务");
Data.items.Add(Data.items[i]);
Data.items.RemoveAt(i);
Save();
}
}
void DrawDelete(int index)
{
GUIStyle deleteButtonStyle = new GUIStyle(GUI.skin.button);
deleteButtonStyle.fixedWidth = Data.displayDensity == DisplayDensity.Compact ? 18 : 20;
if (Data.displayDensity == DisplayDensity.Compact)
{
deleteButtonStyle.fixedHeight = 16;
deleteButtonStyle.fontSize = ButtonsCompactFontSize;
}
deleteButtonStyle.padding = new RectOffset(4, 3, 2, 3);
if (GUILayout.Button("✖", deleteButtonStyle))
DeleteTask(index);
}
#endregion
void DeleteTask(int index)
{
Undo.RecordObject(Data, "删除任务");
Data.items.RemoveAt(index);
Save();
}
#region Completed tasks.
void DrawCompletedTasksButton()
{
if (!shouldDrawCompletedTasks)
{
if (GUILayout.Button("显示 已完成任务"))
shouldDrawCompletedTasks = true;
}
else if (GUILayout.Button("隐藏 已完成任务"))
shouldDrawCompletedTasks = false;
}
void DrawCompletedTasks()
{
bool hasCompletedTasks = false;
for (int i = 0; i < Data.items.Count; i++)
{
if (!Data.items[i].isComplete)
continue;
hasCompletedTasks = true;
TodoItem item = Data.items[i];
EditorGUILayout.BeginHorizontal();
if (EditorGUILayout.Toggle(item.isComplete, GUILayout.Width(12)) == false)
{
Data.items[i].isComplete = false;
Save();
}
GUI.SetNextControlName(taskAreaName);
EditorGUILayout.TextArea(item.task, completedTaskStyle);
DrawDelete(i);
EditorGUILayout.EndHorizontal();
}
if (!hasCompletedTasks)
{
EditorGUILayout.HelpBox("没有 已完成任务.", MessageType.Info);
//EditorGUILayout.LabelField("没有 已完成任务.", EditorStyles.largeLabel);
}
}
#endregion
void DrawCompletedTask(int i)
{
EditorGUILayout.BeginHorizontal();
// Toggle.
if (EditorGUILayout.Toggle(Data.items[i].isComplete, GUILayout.Width(12)) == false)
{
Data.items[i].isComplete = false;
Save();
}
// Task content.
GUI.SetNextControlName(taskAreaName);
EditorGUILayout.TextArea(Data.items[i].task, completedTaskStyle);
// Draw ✖.
DrawDelete(i);
EditorGUILayout.EndHorizontal();
}
void DrawNewTaskPanel()
{
// Text field (focus on it if needed).
GUI.SetNextControlName(newTaskFieldName);
GUIStyle fieldStyle = new GUIStyle(GUI.skin.textField);
fieldStyle.wordWrap = true;
newTask = EditorGUILayout.TextField(newTask, fieldStyle, GUILayout.Height(40));
if (shouldRefocusOnNewTask)
{
EditorGUI.FocusTextInControl(newTaskFieldName);
shouldRefocusOnNewTask = false;
}
// "Add" button.
if ((GUILayout.Button("+ 添加任务") || returnWasPressed) &&
!string.IsNullOrEmpty(newTask))
{
Data.AddTask(newTask);
newTask = "";
shouldRefocusOnNewTask = true;
Save();
}
GUILayout.Space(6);
// Detect return press.
if (returnWasPressed && !IsPressingReturn)
EditorGUI.FocusTextInControl(newTaskFieldName);
returnWasPressed = IsPressingReturn;
ExitWindowKeyboardCheck(); //按下退出
}
private void ExitWindowKeyboardCheck()
{
if (Event.current.keyCode == KeyCode.Escape)
{
var editorWindow = EditorWindow.mouseOverWindow;
#if UNITY_2020_1_OR_NEWER
if (editorWindow && !editorWindow.docked && editorWindow == this)
#else
if (editorWindow && editorWindow == this)
#endif
{
Close();
Event.current.keyCode = KeyCode.None;
}
}
}
void Save()
{
EditorUtility.SetDirty(Data);
AssetDatabase.SaveAssets();
if (Selection.activeObject == Data)
Selection.activeObject = null;
}
#region Search.
List<int> FindItems(string search)
{
List<int> items = new List<int>();
string[] searchItems = search.Split(' ');
for (int i = 0; i < Data.items.Count; i++)
{
bool correctItem = true;
// The item is correct only if it matches all the search terms.
for (int j = 0; j < searchItems.Length; j++)
if (!Regex.IsMatch(Data.items[i].task, searchItems[j], RegexOptions.IgnoreCase))
{
correctItem = false;
j = searchItems.Length;
}
if (correctItem)
items.Add(i);
}
return items;
}
void EmptySearch()
{
currentSearch = "";
}
void DrawSearchResults()
{
List<int> items = FindItems(currentSearch);
foreach (var item in items)
{
if (!Data.items[item].isComplete)
DrawTask(item);
else
DrawCompletedTask(item);
}
}
#endregion
}
} | 31.568998 | 116 | 0.478862 | [
"MIT"
] | 654306663/UnityExtensions | Extensions/ToDo Mini/Editor/ToDoMini.cs | 16,832 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.