Here are the examples of the csharp api System.Diagnostics.Debug.Fail(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
681 Examples
19
Source : Disassembler.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
public void Disreplacedemble(Formatter formatter, TextWriter output, DisasmInfo method) {
formatterOutput.writer = output;
targets.Clear();
sortedTargets.Clear();
bool uppercaseHex = formatter.Options.UppercaseHex;
output.Write(commentPrefix);
output.WriteLine("================================================================================");
output.Write(commentPrefix);
output.WriteLine(method.MethodFullName);
uint codeSize = 0;
foreach (var info in method.Code)
codeSize += (uint)info.Code.Length;
var codeSizeHexText = codeSize.ToString(uppercaseHex ? "X" : "x");
output.WriteLine($"{commentPrefix}{codeSize} (0x{codeSizeHexText}) bytes");
var instrCount = method.Instructions.Count;
var instrCountHexText = instrCount.ToString(uppercaseHex ? "X" : "x");
output.WriteLine($"{commentPrefix}{instrCount} (0x{instrCountHexText}) instructions");
void Add(ulong address, TargetKind kind) {
if (!targets.TryGetValue(address, out var addrInfo))
targets[address] = new AddressInfo(kind);
else if (addrInfo.Kind < kind)
addrInfo.Kind = kind;
}
if (method.Instructions.Count > 0)
Add(method.Instructions[0].IP, TargetKind.Unknown);
foreach (ref var instr in method.Instructions) {
switch (instr.FlowControl) {
case FlowControl.Next:
case FlowControl.Interrupt:
break;
case FlowControl.UnconditionalBranch:
Add(instr.NextIP, TargetKind.Unknown);
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Branch);
break;
case FlowControl.ConditionalBranch:
case FlowControl.XbeginXabortXend:
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Branch);
break;
case FlowControl.Call:
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Call);
break;
case FlowControl.IndirectBranch:
Add(instr.NextIP, TargetKind.Unknown);
// Unknown target
break;
case FlowControl.IndirectCall:
// Unknown target
break;
case FlowControl.Return:
case FlowControl.Exception:
Add(instr.NextIP, TargetKind.Unknown);
break;
default:
Debug.Fail($"Unknown flow control: {instr.FlowControl}");
break;
}
var baseReg = instr.MemoryBase;
if (baseReg == Register.RIP || baseReg == Register.EIP) {
int opCount = instr.OpCount;
for (int i = 0; i < opCount; i++) {
if (instr.GetOpKind(i) == OpKind.Memory) {
if (method.Contains(instr.IPRelativeMemoryAddress))
Add(instr.IPRelativeMemoryAddress, TargetKind.Branch);
break;
}
}
}
else if (instr.MemoryDisplSize >= 2) {
ulong displ;
switch (instr.MemoryDisplSize) {
case 2:
case 4: displ = instr.MemoryDisplacement; break;
case 8: displ = (ulong)(int)instr.MemoryDisplacement; break;
default:
Debug.Fail($"Unknown mem displ size: {instr.MemoryDisplSize}");
goto case 8;
}
if (method.Contains(displ))
Add(displ, TargetKind.Branch);
}
}
foreach (var map in method.ILMap) {
if (targets.TryGetValue(map.nativeStartAddress, out var info)) {
if (info.Kind < TargetKind.BlockStart && info.Kind != TargetKind.Unknown)
info.Kind = TargetKind.BlockStart;
}
else
targets.Add(map.nativeStartAddress, info = new AddressInfo(TargetKind.Unknown));
if (info.ILOffset < 0)
info.ILOffset = map.ilOffset;
}
int labelIndex = 0, methodIndex = 0;
string GetLabel(int index) => LABEL_PREFIX + index.ToString();
string GetFunc(int index) => FUNC_PREFIX + index.ToString();
foreach (var kv in targets) {
if (method.Contains(kv.Key))
sortedTargets.Add(kv);
}
sortedTargets.Sort((a, b) => a.Key.CompareTo(b.Key));
foreach (var kv in sortedTargets) {
var address = kv.Key;
var info = kv.Value;
switch (info.Kind) {
case TargetKind.Unknown:
info.Name = null;
break;
case TargetKind.Data:
info.Name = GetLabel(labelIndex++);
break;
case TargetKind.BlockStart:
case TargetKind.Branch:
info.Name = GetLabel(labelIndex++);
break;
case TargetKind.Call:
info.Name = GetFunc(methodIndex++);
break;
default:
throw new InvalidOperationException();
}
}
foreach (ref var instr in method.Instructions) {
ulong ip = instr.IP;
if (targets.TryGetValue(ip, out var lblInfo)) {
output.WriteLine();
if (!(lblInfo.Name is null)) {
output.Write(lblInfo.Name);
output.Write(':');
output.WriteLine();
}
if (lblInfo.ILOffset >= 0) {
if (ShowSourceCode) {
foreach (var info in sourceCodeProvider.GetStatementLines(method, lblInfo.ILOffset)) {
output.Write(commentPrefix);
var line = info.Line;
int column = commentPrefix.Length;
WriteWithTabs(output, line, 0, line.Length, '\0', ref column);
output.WriteLine();
if (info.Partial) {
output.Write(commentPrefix);
column = commentPrefix.Length;
WriteWithTabs(output, line, 0, info.Span.Start, ' ', ref column);
output.WriteLine(new string('^', info.Span.Length));
}
}
}
}
}
if (ShowAddresses) {
var address = FormatAddress(bitness, ip, uppercaseHex);
output.Write(address);
output.Write(" ");
}
else
output.Write(formatter.Options.TabSize > 0 ? "\t\t" : " ");
if (ShowHexBytes) {
if (!method.TryGetCode(ip, out var nativeCode))
throw new InvalidOperationException();
var codeBytes = nativeCode.Code;
int index = (int)(ip - nativeCode.IP);
int instrLen = instr.Length;
for (int i = 0; i < instrLen; i++) {
byte b = codeBytes[index + i];
output.Write(b.ToString(uppercaseHex ? "X2" : "x2"));
}
int missingBytes = HEXBYTES_COLUMN_BYTE_LENGTH - instrLen;
for (int i = 0; i < missingBytes; i++)
output.Write(" ");
output.Write(" ");
}
formatter.Format(instr, formatterOutput);
output.WriteLine();
}
}
19
Source : XmlHighlightingDefinition.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public object VisitImport(XshdImport import)
{
HighlightingRuleSet hrs = GetRuleSet(import, import.RuleSetReference);
XshdRuleSet inputRuleSet;
if (reverseRuleSetDict.TryGetValue(hrs, out inputRuleSet)) {
// ensure the ruleset is processed before importing its members
if (VisitRuleSet(inputRuleSet) != hrs)
Debug.Fail("this shouldn't happen");
}
return hrs;
}
19
Source : Contract.cs
with MIT License
from abdullin
with MIT License
from abdullin
[DebuggerStepThrough, DebuggerHidden]
internal static void RaiseContractFailure(SDC.ContractFailureKind kind, string message, string file, int line)
{
if (message == null)
{
switch (kind)
{
case SDC.ContractFailureKind.replacedert: message = "An replacedertion was not met"; break;
case SDC.ContractFailureKind.Precondition: message = "A pre-requisite was not met"; break;
case SDC.ContractFailureKind.Postcondition: message = "A post-condition was not met"; break;
default: message = "An expectation was not met"; break;
}
}
if (file != null)
{ // add the caller infos
message = String.Format("{0} in {1}:line {2}", message, file, line);
}
//TODO: check if we are running under NUnit, and map to an replacedert.Fail() instead ?
Debug.Fail(message);
// If you break here, that means that an replacedertion failed somewhere up the stack.
// TODO: find a way to have the debugger break, but show the caller of Contract.replacedert(..) method, instead of here ?
if (Debugger.IsAttached) Debugger.Break();
throw new InvalidOperationException(message);
}
19
Source : LSBRadixSort.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public static void Sort<TValue, TKeySpan, TValueSpan>(ref TKeySpan inputKeys, ref TValueSpan inputValues, ref TKeySpan scratchKeys, ref TValueSpan scratchValues,
int startIndex, int count, int keysUpperBound, BufferPool bufferPool, out TKeySpan sortedKeys, out TValueSpan sortedValues)
where TKeySpan : ISpan<int> where TValueSpan : ISpan<TValue>
{
//Note that we require the scratch and input spans to contain the offset region. That's because the output could be either the scratch or the input spans.
Debug.replacedert(
inputKeys.Length >= startIndex + count && inputValues.Length >= startIndex + count &&
inputKeys.Length >= startIndex + count && inputValues.Length >= startIndex + count,
"The spans must be able to hold the sort region.");
#if DEBUG
for (int i = startIndex; i < startIndex + count; ++i)
{
//Technically, there are instances where someone may want to force a smaller sort... but... that's extremely rare, and there are other options available.
Debug.replacedert(inputKeys[i] <= keysUpperBound, "The given upper bound must actually bound the elements in the sort region, or else the sort won't sort.");
}
#endif
int bucketSetCount = keysUpperBound < (1 << 16) ? keysUpperBound < (1 << 8) ? 1 : 2 : keysUpperBound < (1 << 24) ? 3 : 4;
var intPool = bufferPool.SpecializeFor<int>();
intPool.Take(bucketSetCount * 256, out var bucketCounts);
unsafe
{
//The bucket counts will be added to, so they need to be zeroed.
Unsafe.InitBlockUnaligned(bucketCounts.Memory, 0, (uint)(sizeof(int) * 256 * bucketSetCount));
}
switch (bucketSetCount)
{
case 1:
{
SortU8(ref inputKeys[startIndex], ref inputValues[startIndex], ref scratchKeys[startIndex], ref scratchValues[startIndex], ref bucketCounts[0], count);
sortedKeys = scratchKeys;
sortedValues = scratchValues;
}
break;
case 2:
{
SortU16(ref inputKeys[startIndex], ref inputValues[startIndex], ref scratchKeys[startIndex], ref scratchValues[startIndex], ref bucketCounts[0], count);
sortedKeys = inputKeys;
sortedValues = inputValues;
}
break;
case 3:
{
SortU24(ref inputKeys[startIndex], ref inputValues[startIndex], ref scratchKeys[startIndex], ref scratchValues[startIndex], ref bucketCounts[0], count);
sortedKeys = scratchKeys;
sortedValues = scratchValues;
}
break;
case 4:
{
SortU32(ref inputKeys[startIndex], ref inputValues[startIndex], ref scratchKeys[startIndex], ref scratchValues[startIndex], ref bucketCounts[0], count);
sortedKeys = inputKeys;
sortedValues = inputValues;
}
break;
default:
Debug.Fail("Invalid bucket set count.");
sortedKeys = default(TKeySpan);
sortedValues = default(TValueSpan);
break;
}
intPool.Return(ref bucketCounts);
}
19
Source : DdbConverterFactory.cs
with MIT License
from AllocZero
with MIT License
from AllocZero
internal sealed override DdbPropertyInfo CreateDdbPropertyInfo(PropertyInfo propertyInfo, string attributeName, DynamoDbAttributeType attributeType, DynamoDbContextMetadata dynamoDbContextMetadata)
{
Debug.Fail("We should never get here.");
throw new InvalidOperationException();
}
19
Source : NoAllocStringBuilder.cs
with MIT License
from AllocZero
with MIT License
from AllocZero
public void Append(int value)
{
if (!value.TryFormat(_buffer.Slice(_index), out var charsWritten))
Resize(_buffer.Length + PrimitiveLengths.Int);
if (!value.TryFormat(_buffer.Slice(_index), out charsWritten))
Debug.Fail("Format should always be successful after resize");
_index += charsWritten;
}
19
Source : Marvin.cs
with MIT License
from AllocZero
with MIT License
from AllocZero
private static long ComputeHash(ReadOnlySpan<byte> data, ulong seed)
{
uint p0 = (uint)seed;
uint p1 = (uint)(seed >> 32);
if (data.Length >= sizeof(uint))
{
ReadOnlySpan<uint> uData = MemoryMarshal.Cast<byte, uint>(data);
for (int i = 0; i < uData.Length; i++)
{
p0 += uData[i];
Block(ref p0, ref p1);
}
// byteOffset = data.Length - data.Length % 4
// is equivalent to clearing last 2 bits of length
// Using it directly gives a perf hit for short strings making it at least 5% or more slower.
int byteOffset = data.Length & (~3);
data = data.Slice(byteOffset);
}
switch (data.Length)
{
case 0:
p0 += 0x80u;
break;
case 1:
p0 += 0x8000u | data[0];
break;
case 2:
p0 += 0x800000u | MemoryMarshal.Cast<byte, ushort>(data)[0];
break;
case 3:
p0 += 0x80000000u | (((uint)data[2]) << 16) | (uint)(MemoryMarshal.Cast<byte, ushort>(data)[0]);
break;
default:
Debug.Fail("Should not get here.");
break;
}
Block(ref p0, ref p1);
Block(ref p0, ref p1);
return (((long)p1) << 32) | p0;
}
19
Source : DbiScope.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public void Read(RecursionCounter counter, IImageStream stream, uint scopeEnd) {
if (!counter.Increment())
throw new PdbException("Scopes too deep");
while (stream.Position < scopeEnd) {
var size = stream.ReadUInt16();
var begin = stream.Position;
var end = begin + size;
var type = (SymbolType)stream.ReadUInt16();
DbiScope child = null;
uint? childEnd = null;
string name;
switch (type) {
case SymbolType.S_BLOCK32: {
stream.Position += 4;
childEnd = stream.ReadUInt32();
var len = stream.ReadUInt32();
var addr = PdbAddress.ReadAddress(stream);
name = PdbReader.ReadCString(stream);
child = new DbiScope(name, addr.Offset, len);
break;
}
case SymbolType.S_UNAMESPACE:
Namespaces.Add(new DbiNamespace(PdbReader.ReadCString(stream)));
break;
case SymbolType.S_MANSLOT: {
var variable = new DbiVariable();
variable.Read(stream);
Variables.Add(variable);
break;
}
case SymbolType.S_OEM:
if (stream.Position + 20 > end)
break;
if (!ReadAndCompareBytes(stream, end, dotNetOemGuid)) {
Debug.Fail("Unknown OEM record GUID, not .NET GUID");
break;
}
stream.Position += 4;// typeIndex or 0
name = ReadUnicodeString(stream, end);
Debug.replacedert(name != null);
if (name == null)
break;
var data = stream.ReadBytes((int)(end - stream.Position));
if (oemInfos == null)
oemInfos = new List<OemInfo>(1);
oemInfos.Add(new OemInfo(name, data));
break;
case SymbolType.S_MANCONSTANT:
uint signatureToken = stream.ReadUInt32();
object value;
if (!NumericReader.TryReadNumeric(stream, end, out value))
break;
name = PdbReader.ReadCString(stream);
if (constants == null)
constants = new List<ConstantInfo>();
constants.Add(new ConstantInfo(name, signatureToken, value));
break;
case SymbolType.S_END:
break;
default:
Debug.Fail("Unknown symbol type: " + type);
break;
}
stream.Position = end;
if (child != null) {
child.Read(counter, stream, childEnd.Value);
Children.Add(child);
child = null;
}
}
counter.Decrement();
if (stream.Position != scopeEnd)
Debugger.Break();
}
19
Source : DbiScope.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public PdbConstant[] GetConstants(ModuleDefMD module, GenericParamContext gpContext) {
if (constants == null)
return emptySymbolConstants;
var res = new PdbConstant[constants.Count];
for (int i = 0; i < res.Length; i++) {
var info = constants[i];
TypeSig signature;
var saSig = module.ResolveToken(info.SignatureToken, gpContext) as StandAloneSig;
var fieldSig = saSig == null ? null : saSig.Signature as FieldSig;
if (fieldSig == null) {
Debug.Fail("Constant without a signature");
signature = null;
}
else
signature = fieldSig.Type;
res[i] = new PdbConstant(info.Name, signature, info.Value);
}
return res;
}
19
Source : PdbWriter.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
void Write(MethodDef method) {
uint rid = metaData.GetRid(method);
if (rid == 0) {
Error("Method {0} ({1:X8}) is not defined in this module ({2})", method, method.MDToken.Raw, module);
return;
}
var info = new CurrentMethod(this, method, instrToOffset);
var body = method.Body;
var symbolToken = new SymbolToken((int)new MDToken(MD.Table.Method, metaData.GetRid(method)).Raw);
writer.OpenMethod(symbolToken);
seqPointsHelper.Write(this, info.Method.Body.Instructions);
var pdbMethod = body.PdbMethod;
if (pdbMethod == null)
body.PdbMethod = pdbMethod = new PdbMethod();
var scope = pdbMethod.Scope;
if (scope == null)
pdbMethod.Scope = scope = new PdbScope();
if (scope.Namespaces.Count == 0 && scope.Variables.Count == 0 && scope.Constants.Count == 0) {
if (scope.Scopes.Count == 0) {
// We must open at least one sub scope (the sym writer creates the 'method' scope
// which covers the whole method) or the native PDB reader will fail to read all
// sequence points.
writer.OpenScope(0);
writer.CloseScope((int)info.BodySize);
}
else {
foreach (var childScope in scope.Scopes)
WriteScope(ref info, childScope, 0);
}
}
else {
Debug.Fail("Root scope isn't empty");
WriteScope(ref info, scope, 0);
}
if (pdbMethod.CustomDebugInfos.Count != 0) {
customDebugInfoWriterContext.Logger = GetLogger();
var cdiData = PdbCustomDebugInfoWriter.Write(metaData, method, customDebugInfoWriterContext, pdbMethod.CustomDebugInfos);
if (cdiData != null)
writer.SetSymAttribute(symbolToken, "MD2", cdiData);
}
var asyncMethod = pdbMethod.AsyncMethod;
if (asyncMethod != null) {
if (writer3 == null || !writer3.SupportsAsyncMethods)
Error("PDB symbol writer doesn't support writing async methods");
else
WriteAsyncMethod(ref info, asyncMethod);
}
writer.CloseMethod();
}
19
Source : ModuleLoader.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
void Load(Resource obj) {
if (obj == null)
return;
Add(obj.Offset);
Add(obj.Name);
Add(obj.Attributes);
switch (obj.ResourceType) {
case ResourceType.Embedded:
var er = (EmbeddedResource)obj;
// Make sure data is cached
if (!(er.Data is MemoryImageStream))
er.Data = MemoryImageStream.Create(er.GetClonedResourceStream().ReadAllBytes());
break;
case ResourceType.replacedemblyLinked:
var ar = (replacedemblyLinkedResource)obj;
Add(ar.replacedembly);
break;
case ResourceType.Linked:
var lr = (LinkedResource)obj;
Add(lr.File);
Add(lr.Hash);
break;
default:
Debug.Fail("Unknown resource");
break;
}
}
19
Source : ModuleLoader.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
void Load(IMDTokenProvider mdt) {
if (mdt == null)
return;
switch (mdt.MDToken.Table) {
case Table.Module: Load((ModuleDef)mdt); break;
case Table.TypeRef: Load((TypeRef)mdt); break;
case Table.TypeDef: Load((TypeDef)mdt); break;
case Table.Field: Load((FieldDef)mdt); break;
case Table.Method: Load((MethodDef)mdt); break;
case Table.Param: Load((ParamDef)mdt); break;
case Table.InterfaceImpl: Load((InterfaceImpl)mdt); break;
case Table.MemberRef: Load((MemberRef)mdt); break;
case Table.Constant: Load((Constant)mdt); break;
case Table.DeclSecurity: Load((DeclSecurity)mdt); break;
case Table.ClreplacedLayout: Load((ClreplacedLayout)mdt); break;
case Table.StandAloneSig: Load((StandAloneSig)mdt); break;
case Table.Event: Load((EventDef)mdt); break;
case Table.Property: Load((PropertyDef)mdt); break;
case Table.ModuleRef: Load((ModuleRef)mdt); break;
case Table.TypeSpec: Load((TypeSpec)mdt); break;
case Table.ImplMap: Load((ImplMap)mdt); break;
case Table.replacedembly: Load((replacedemblyDef)mdt); break;
case Table.replacedemblyRef: Load((replacedemblyRef)mdt); break;
case Table.File: Load((FileDef)mdt); break;
case Table.ExportedType: Load((ExportedType)mdt); break;
case Table.GenericParam: Load((GenericParam)mdt); break;
case Table.MethodSpec: Load((MethodSpec)mdt); break;
case Table.GenericParamConstraint: Load((GenericParamConstraint)mdt); break;
case Table.ManifestResource:
var rsrc = mdt as Resource;
if (rsrc != null) {
Load(rsrc);
break;
}
var mr = mdt as ManifestResource;
if (mr != null) {
Load(mr);
break;
}
Debug.Fail("Unknown ManifestResource");
break;
case Table.FieldPtr:
case Table.MethodPtr:
case Table.ParamPtr:
case Table.CustomAttribute:
case Table.FieldMarshal:
case Table.FieldLayout:
case Table.EventMap:
case Table.EventPtr:
case Table.PropertyMap:
case Table.PropertyPtr:
case Table.MethodSemantics:
case Table.MethodImpl:
case Table.FieldRVA:
case Table.ENCLog:
case Table.ENCMap:
case Table.replacedemblyProcessor:
case Table.replacedemblyOS:
case Table.replacedemblyRefProcessor:
case Table.replacedemblyRefOS:
case Table.NestedClreplaced:
case Table.Doreplacedent:
case Table.MethodDebugInformation:
case Table.LocalScope:
case Table.LocalVariable:
case Table.LocalConstant:
case Table.ImportScope:
case Table.StateMachineMethod:
case Table.CustomDebugInformation:
break;
default:
Debug.Fail("Unknown type");
break;
}
}
19
Source : ModuleLoader.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
void LoadObj(object o) {
var ts = o as TypeSig;
if (ts != null) {
Load(ts);
return;
}
var mdt = o as IMDTokenProvider;
if (mdt != null) {
Load(mdt);
return;
}
var ca = o as CustomAttribute;
if (ca != null) {
Load(ca);
return;
}
var sa = o as SecurityAttribute;
if (sa != null) {
Load(sa);
return;
}
var na = o as CANamedArgument;
if (na != null) {
Load(na);
return;
}
var p = o as Parameter;
if (p != null) {
Load(p);
return;
}
var pdbMethod = o as PdbMethod;
if (pdbMethod != null) {
Load(pdbMethod);
return;
}
var rd = o as ResourceDirectory;
if (rd != null) {
Load(rd);
return;
}
var rdata = o as ResourceData;
if (rdata != null) {
Load(rdata);
return;
}
Debug.Fail("Unknown type");
}
19
Source : UnixChildProcessStateHelper.cs
with MIT License
from asmichi
with MIT License
from asmichi
public IChildProcessStateHolder SpawnProcess(
ref ChildProcessStartInfoInternal startInfo,
string resolvedPath,
SafeHandle stdIn,
SafeHandle stdOut,
SafeHandle stdErr)
{
var arguments = startInfo.Arguments;
var environmentVariables = startInfo.EnvironmentVariables;
var workingDirectory = startInfo.WorkingDirectory;
Span<int> fds = stackalloc int[3];
int handleCount = 0;
uint flags = 0;
if (stdIn != null)
{
fds[handleCount++] = stdIn.DangerousGetHandle().ToInt32();
flags |= RequestFlagsRedirectStdin;
}
if (stdOut != null)
{
fds[handleCount++] = stdOut.DangerousGetHandle().ToInt32();
flags |= RequestFlagsRedirectStdout;
}
if (stdErr != null)
{
fds[handleCount++] = stdErr.DangerousGetHandle().ToInt32();
flags |= RequestFlagsRedirectStderr;
}
if (startInfo.CreateNewConsole)
{
flags |= RequestFlagsCreateNewProcessGroup;
}
else
{
Debug.replacedert(!startInfo.AllowSignal);
}
// If AttachToCurrentConsole (== !startInfo.AllowSignal), leave the process running after we (the parent) exit.
// After being orphaned (and possibly reparented to the shell), it may continue running or may be terminated by SIGTTIN/SIGTTOU.
if (startInfo.AllowSignal)
{
flags |= RequestFlagsEnableAutoTermination;
}
using var bw = new MyBinaryWriter(InitialBufferCapacity);
var stateHolder = UnixChildProcessState.Create(this, startInfo.AllowSignal);
try
{
bw.Write(stateHolder.State.Token);
bw.Write(flags);
bw.Write(workingDirectory);
bw.Write(resolvedPath);
bw.Write((uint)(arguments.Count + 1));
bw.Write(resolvedPath);
foreach (var x in arguments)
{
bw.Write(x);
}
if (!startInfo.UseCustomEnvironmentVariables)
{
// Send the environment variables of this process to the helper process.
//
// NOTE: We cannot cache or detect updates to the environment block; only the runtime can.
// Concurrently invoking getenv and setenv is a racy operation; therefore the runtime
// employs a process-global lock.
//
// Fortunately, the caller can take a snapshot of environment variables theirselves.
var processEnvVars = Environment.GetEnvironmentVariables();
var envVarCount = processEnvVars.Count;
bw.Write((uint)envVarCount);
var sortedEnvVars = ArrayPool<KeyValuePair<string, string>>.Shared.Rent(envVarCount);
try
{
EnvironmentVariableListUtil.ToSortedKeyValuePairs(processEnvVars, sortedEnvVars);
foreach (var (name, value) in sortedEnvVars.replacedpan<KeyValuePair<string, string>>().Slice(0, envVarCount))
{
bw.WriteEnvironmentVariable(name, value);
}
}
finally
{
ArrayPool<KeyValuePair<string, string>>.Shared.Return(sortedEnvVars);
}
}
else
{
bw.Write((uint)environmentVariables.Length);
foreach (var (name, value) in environmentVariables.Span)
{
bw.WriteEnvironmentVariable(name, value);
}
}
// Work around https://github.com/microsoft/WSL/issues/6490
// On WSL 1, if you call recvmsg multiple times to fully receive data sent with sendmsg,
// the fds will be duplicated for each recvmsg call.
// Send only fixed length of of data with the fds and receive that much data with one recvmsg call.
// That will be safer anyway.
Span<byte> header = stackalloc byte[sizeof(uint) * 2];
if (!BitConverter.TryWriteBytes(header, (uint)UnixHelperProcessCommand.SpawnProcess)
|| !BitConverter.TryWriteBytes(header.Slice(sizeof(uint)), bw.Length))
{
Debug.Fail("Should never fail.");
}
var subchannel = _helperProcess.RentSubchannelAsync(default).AsTask().GetAwaiter().GetResult();
try
{
subchannel.SendExactBytesAndFds(header, fds.Slice(0, handleCount));
subchannel.SendExactBytes(bw.GetBuffer());
GC.KeepAlive(stdIn);
GC.KeepAlive(stdOut);
GC.KeepAlive(stdErr);
var (error, processId) = subchannel.ReceiveCommonResponse();
if (error > 0)
{
throw new Win32Exception(error);
}
else if (error < 0)
{
throw new AsmichiChildProcessInternalLogicErrorException(
string.Format(CultureInfo.InvariantCulture, "Internal logic error: Bad request {0}.", error));
}
stateHolder.State.SetProcessId(processId);
return stateHolder;
}
finally
{
_helperProcess.ReturnSubchannel(subchannel);
}
}
catch
{
stateHolder.Dispose();
throw;
}
}
19
Source : UnixChildProcessStateHelper.cs
with MIT License
from asmichi
with MIT License
from asmichi
public void SendSignal(long token, UnixHelperProcessSignalNumber signalNumber)
{
Span<byte> request = stackalloc byte[4 + 4 + 8 + 4];
if (!BitConverter.TryWriteBytes(request, (uint)UnixHelperProcessCommand.SignalProcess)
|| !BitConverter.TryWriteBytes(request.Slice(4), 8 + 4)
|| !BitConverter.TryWriteBytes(request.Slice(4 + 4), token)
|| !BitConverter.TryWriteBytes(request.Slice(4 + 4 + 8), (uint)signalNumber))
{
Debug.Fail("Should never fail.");
}
var subchannel = _helperProcess.RentSubchannelAsync(default).AsTask().GetAwaiter().GetResult();
try
{
subchannel.SendExactBytes(request);
var (error, _) = subchannel.ReceiveCommonResponse();
if (error > 0)
{
throw new Win32Exception(error);
}
else if (error < 0)
{
throw new AsmichiChildProcessInternalLogicErrorException(
string.Format(CultureInfo.InvariantCulture, "Internal logic error: Bad request {0}.", error));
}
}
finally
{
_helperProcess.ReturnSubchannel(subchannel);
}
}
19
Source : DefaultTagHelperCompletionService.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public override IReadOnlyList<CompletionItem> GetCompletionsAt(SourceSpan location, RazorCodeDoreplacedent codeDoreplacedent)
{
if (codeDoreplacedent == null)
{
throw new ArgumentNullException(nameof(codeDoreplacedent));
}
var syntaxTree = codeDoreplacedent.GetSyntaxTree();
var change = new SourceChange(location, "");
var owner = syntaxTree.Root.LocateOwner(change);
if (owner == null)
{
Debug.Fail("Owner should never be null.");
return Array.Empty<CompletionItem>();
}
var parent = owner.Parent;
if (TryGetElementInfo(parent, out var containingTagNameToken, out var attributes) &&
containingTagNameToken.Span.IntersectsWith(location.AbsoluteIndex))
{
var stringifiedAttributes = StringifyAttributes(attributes);
var elementCompletions = GetElementCompletions(parent, containingTagNameToken.Content, stringifiedAttributes, codeDoreplacedent);
return elementCompletions;
}
if (TryGetAttributeInfo(parent, out containingTagNameToken, out var selectedAttributeName, out attributes) &&
attributes.Span.IntersectsWith(location.AbsoluteIndex))
{
var stringifiedAttributes = StringifyAttributes(attributes);
var attributeCompletions = GetAttributeCompletions(parent, containingTagNameToken.Content, selectedAttributeName, stringifiedAttributes, codeDoreplacedent);
return attributeCompletions;
}
// Invalid location for TagHelper completions.
return Array.Empty<CompletionItem>();
}
19
Source : RazorDiagnosticsPublisher.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
internal async Task PublishDiagnosticsAsync(DoreplacedentSnapshot doreplacedent)
{
var result = await doreplacedent.GetGeneratedOutputAsync();
var diagnostics = result.GetCSharpDoreplacedent().Diagnostics;
lock (_publishedDiagnostics)
{
if (_publishedDiagnostics.TryGetValue(doreplacedent.FilePath, out var previousDiagnostics) &&
diagnostics.SequenceEqual(previousDiagnostics))
{
// Diagnostics are the same as last publish
return;
}
_publishedDiagnostics[doreplacedent.FilePath] = diagnostics;
}
if (!doreplacedent.TryGetText(out var sourceText))
{
Debug.Fail("Doreplacedent source text should already be available.");
}
var convertedDiagnostics = diagnostics.Select(razorDiagnostic => RazorDiagnosticConverter.Convert(razorDiagnostic, sourceText));
PublishDiagnosticsForFilePath(doreplacedent.FilePath, convertedDiagnostics);
if (_logger.IsEnabled(LogLevel.Trace))
{
var diagnosticString = string.Join(", ", diagnostics.Select(diagnostic => diagnostic.Id));
_logger.LogTrace($"Publishing diagnostics for doreplacedent '{doreplacedent.FilePath}': {diagnosticString}");
}
}
19
Source : RazorLanguageEndpoint.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public async Task<RazorLanguageQueryResponse> Handle(RazorLanguageQueryParams request, CancellationToken cancellationToken)
{
long doreplacedentVersion = -1;
DoreplacedentSnapshot doreplacedentSnapshot = null;
await Task.Factory.StartNew(() =>
{
_doreplacedentResolver.TryResolveDoreplacedent(request.Uri.AbsolutePath, out doreplacedentSnapshot);
if (!_doreplacedentVersionCache.TryGetDoreplacedentVersion(doreplacedentSnapshot, out doreplacedentVersion))
{
Debug.Fail("Doreplacedent should always be available here.");
}
return doreplacedentSnapshot;
}, CancellationToken.None, TaskCreationOptions.None, _foregroundDispatcher.ForegroundScheduler);
var codeDoreplacedent = await doreplacedentSnapshot.GetGeneratedOutputAsync();
var sourceText = await doreplacedentSnapshot.GetTextAsync();
var linePosition = new LinePosition((int)request.Position.Line, (int)request.Position.Character);
var hostDoreplacedentIndex = sourceText.Lines.GetPosition(linePosition);
var responsePosition = request.Position;
if (codeDoreplacedent.IsUnsupported())
{
// All language queries on unsupported doreplacedents return Html. This is equivalent to what pre-VSCode Razor was capable of.
return new RazorLanguageQueryResponse()
{
Kind = RazorLanguageKind.Html,
Position = responsePosition,
PositionIndex = hostDoreplacedentIndex,
HostDoreplacedentVersion = doreplacedentVersion,
};
}
var syntaxTree = codeDoreplacedent.GetSyntaxTree();
var clreplacedifiedSpans = syntaxTree.GetClreplacedifiedSpans();
var tagHelperSpans = syntaxTree.GetTagHelperSpans();
var languageKind = GetLanguageKind(clreplacedifiedSpans, tagHelperSpans, hostDoreplacedentIndex);
var responsePositionIndex = hostDoreplacedentIndex;
if (languageKind == RazorLanguageKind.CSharp)
{
if (TryGetCSharpProjectedPosition(codeDoreplacedent, hostDoreplacedentIndex, out var projectedPosition, out var projectedIndex))
{
// For C# locations, we attempt to return the corresponding position
// within the projected doreplacedent
responsePosition = projectedPosition;
responsePositionIndex = projectedIndex;
}
else
{
// It no longer makes sense to think of this location as C#, since it doesn't
// correspond to any position in the projected doreplacedent. This should not happen
// since there should be source mappings for all the C# spans.
languageKind = RazorLanguageKind.Razor;
responsePositionIndex = hostDoreplacedentIndex;
}
}
_logger.LogTrace($"Language query request for ({request.Position.Line}, {request.Position.Character}) = {languageKind} at ({responsePosition.Line}, {responsePosition.Character})");
return new RazorLanguageQueryResponse()
{
Kind = languageKind,
Position = responsePosition,
PositionIndex = responsePositionIndex,
HostDoreplacedentVersion = doreplacedentVersion
};
}
19
Source : RemoteProjectSnapshotProjectEngineFactory.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public override RazorProjectEngine Create(
RazorConfiguration configuration,
RazorProjectFileSystem fileSystem,
Action<RazorProjectEngineBuilder> configure)
{
if (!(fileSystem is DefaultRazorProjectFileSystem defaultFileSystem))
{
Debug.Fail("Unexpected file system.");
return null;
}
var remoteFileSystem = new RemoteRazorProjectFileSystem(defaultFileSystem.Root, _filePathNormalizer);
return base.Create(configuration, remoteFileSystem, configure);
}
19
Source : OmniSharpWorkspaceProjectStateChangeDetector.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected override async void InitializeSolution(Solution solution)
{
if (_foregroundDispatcher.IsForegroundThread)
{
base.InitializeSolution(solution);
return;
}
await Task.Factory.StartNew(
() =>
{
try
{
base.InitializeSolution(solution);
}
catch (Exception ex)
{
Debug.Fail("Unexpected error when initializing solution: " + ex);
}
},
CancellationToken.None,
TaskCreationOptions.None,
_foregroundDispatcher.ForegroundScheduler);
}
19
Source : OmniSharpWorkspaceProjectStateChangeDetector.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
internal override async void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
if (_foregroundDispatcher.IsForegroundThread)
{
base.Workspace_WorkspaceChanged(sender, args);
return;
}
await Task.Factory.StartNew(
() =>
{
try
{
base.Workspace_WorkspaceChanged(sender, args);
}
catch (Exception ex)
{
Debug.Fail("Unexpected error when handling a workspace changed event: " + ex);
}
},
CancellationToken.None,
TaskCreationOptions.None,
_foregroundDispatcher.ForegroundScheduler);
}
19
Source : TaskbarIcon.cs
with MIT License
from ay2015
with MIT License
from ay2015
private void SetVersion()
{
iconData.VersionOrTimeout = (uint) NotifyIconVersion.Vista;
bool status = WinApi.Shell_NotifyIcon(NotifyCommand.SetVersion, ref iconData);
if (!status)
{
iconData.VersionOrTimeout = (uint) NotifyIconVersion.Win2000;
status = Ay.Framework.WPF.NotifyIcon.Util.WriteIconData(ref iconData, NotifyCommand.SetVersion);
}
if (!status)
{
iconData.VersionOrTimeout = (uint) NotifyIconVersion.Win95;
status = Ay.Framework.WPF.NotifyIcon.Util.WriteIconData(ref iconData, NotifyCommand.SetVersion);
}
if (!status)
{
Debug.Fail("Could not set version");
}
}
19
Source : CommandManager.cs
with MIT License
from b-editor
with MIT License
from b-editor
public void Do(IRecordCommand command)
{
if (!_process)
{
Debug.WriteLine("if (!process) {...");
return;
}
try
{
_process = false;
command.Do();
UndoStack.Push(command);
CanUndo = UndoStack.Count > 0;
RedoStack.Clear();
CanRedo = RedoStack.Count > 0;
}
catch
{
Debug.Fail("Commandの実行中に例外が発生。");
CommandCancel?.Invoke(null, EventArgs.Empty);
}
_process = true;
Executed?.Invoke(command, CommandType.Do);
}
19
Source : WindowsTitlebar.axaml.cs
with MIT License
from b-editor
with MIT License
from b-editor
private void SetRecentUsedFiles()
{
static async Task ProjectOpenCommand(string name)
{
if (!File.Exists(name))
{
if (await AppModel.Current.Message.DialogAsync(
Strings.FileDoesNotExistRemoveItFromList,
IMessage.IconType.Info,
new IMessage.ButtonType[] { IMessage.ButtonType.Yes, IMessage.ButtonType.No }) == IMessage.ButtonType.Yes)
{
BEditor.Settings.Default.RecentFiles.Remove(name);
}
return;
}
ProgressDialog? dialog = null;
try
{
dialog = new ProgressDialog
{
IsIndeterminate = { Value = true }
};
dialog.Show(App.GetMainWindow());
await MainWindowViewModel.DirectOpenAsync(name);
}
catch
{
AppModel.Current.AppStatus = Status.Idle;
AppModel.Current.Project = null;
Debug.Fail(string.Empty);
AppModel.Current.Message.Snackbar(
string.Format(Strings.FailedToLoad, Strings.ProjectFile),
string.Empty,
IMessage.IconType.Error);
}
finally
{
dialog?.Close();
}
}
var items = new AvaloniaList<MenuItem>(BEditor.Settings.Default.RecentFiles.Reverse().Select(i => new MenuItem
{
Header = i
}));
_recentFiles.Items = items;
foreach (var item in items)
{
item.Click += async (s, e) => await ProjectOpenCommand(((s as MenuItem)!.Header as string)!);
}
BEditor.Settings.Default.RecentFiles.CollectionChanged += async (s, e) =>
{
await Dispatcher.UIThread.InvokeAsync(() =>
{
if (s is null) return;
if (e.Action is NotifyCollectionChangedAction.Add)
{
var menu = new MenuItem
{
Header = (s as ObservableCollection<string>)![e.NewStartingIndex]
};
menu.Click += async (s, e) => await ProjectOpenCommand(((s as MenuItem)!.Header as string)!);
((AvaloniaList<MenuItem>)_recentFiles.Items).Insert(0, menu);
}
else if (e.Action is NotifyCollectionChangedAction.Remove)
{
var file = e.OldItems![0] as string;
foreach (var item in _recentFiles.Items)
{
if (item is MenuItem menuItem && menuItem.Header is string header && header == file)
{
((AvaloniaList<MenuItem>)_recentFiles.Items).Remove(menuItem);
return;
}
}
}
}
19
Source : Shader.cs
with MIT License
from b-editor
with MIT License
from b-editor
private static void CompileShader(int shader)
{
GL.CompileShader(shader);
GL.GetShader(shader, ShaderParameter.CompileStatus, out var code);
if (code != (int)All.True)
{
// We can use `GL.GetShaderInfoLog(shader)` to get information about the error.
var infoLog = GL.GetShaderInfoLog(shader);
Debug.Fail(string.Empty);
throw new GraphicsException(string.Format(Strings.ErrorOccurredWhilistCompilingShader, shader, infoLog));
}
}
19
Source : Shader.cs
with MIT License
from b-editor
with MIT License
from b-editor
private static void LinkProgram(int program)
{
GL.LinkProgram(program);
GL.GetProgram(program, GetProgramParameterName.LinkStatus, out var code);
if (code != (int)All.True)
{
Debug.Fail(string.Empty);
throw new GraphicsException(string.Format(Strings.ErrorOccurredWhilstLinkingProgram, program));
}
}
19
Source : TaskbarIcon.cs
with Apache License 2.0
from beckzhu
with Apache License 2.0
from beckzhu
private void SetVersion()
{
iconData.VersionOrTimeout = (uint) NotifyIconVersion.Vista;
bool status = WinApi.Shell_NotifyIcon(NotifyCommand.SetVersion, ref iconData);
if (!status)
{
iconData.VersionOrTimeout = (uint) NotifyIconVersion.Win2000;
status = Util.WriteIconData(ref iconData, NotifyCommand.SetVersion);
}
if (!status)
{
iconData.VersionOrTimeout = (uint) NotifyIconVersion.Win95;
status = Util.WriteIconData(ref iconData, NotifyCommand.SetVersion);
}
if (!status)
{
Debug.Fail("Could not set version");
}
}
19
Source : Compound.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
public static bool ValidateChildIndex(TypedIndex shapeIndex, Shapes shapeBatches)
{
if (shapeIndex.Type < 0 || shapeIndex.Type >= shapeBatches.RegisteredTypeSpan)
{
Debug.Fail("Child shape type needs to fit within the shape batch registered types.");
return false;
}
var batch = shapeBatches[shapeIndex.Type];
if (shapeIndex.Index < 0 || shapeIndex.Index >= batch.Capacity)
{
Debug.Fail("Child shape index should point to a valid buffer location in the sahpe batch.");
return false;
}
if (shapeBatches[shapeIndex.Type].Compound)
{
Debug.Fail("Child shape type should be convex.");
return false;
}
//TODO: We don't have a cheap way to verify that a specific index actually contains a shape right now.
return true;
}
19
Source : ConstraintChecker.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
[Conditional("DEBUG")]
public static void replacedertUnitLength(in Vector3 v, string typeName, string propertyName)
{
var lengthSquared = v.LengthSquared();
if (lengthSquared > 1 + 1e-5f || lengthSquared < 1 - 1e-5f || !IsFiniteNumber(lengthSquared))
{
Debug.Fail($"{typeName}.{propertyName} must be unit length.");
}
}
19
Source : ConstraintChecker.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
[Conditional("DEBUG")]
public static void replacedertUnitLength(in Quaternion q, string typeName, string propertyName)
{
var lengthSquared = q.LengthSquared();
if (lengthSquared > 1 + 1e-5f || lengthSquared < 1 - 1e-5f || !IsFiniteNumber(lengthSquared))
{
Debug.Fail($"{typeName}.{propertyName} must be unit length.");
}
}
19
Source : ConstraintChecker.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
[Conditional("DEBUG")]
public static void replacedertValid(in SpringSettings settings, string typeName)
{
if (!SpringSettings.Validate(settings))
{
Debug.Fail($"{typeName}.SpringSettings must have positive frequency and nonnegative damping ratio.");
}
}
19
Source : LSBRadixSort.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
public static void Sort<TValue>(ref Buffer<int> inputKeys, ref Buffer<TValue> inputValues, ref Buffer<int> scratchKeys, ref Buffer<TValue> scratchValues,
int startIndex, int count, int keysUpperBound, BufferPool bufferPool, out Buffer<int> sortedKeys, out Buffer<TValue> sortedValues)
where TValue : unmanaged
{
//Note that we require the scratch and input spans to contain the offset region. That's because the output could be either the scratch or the input spans.
Debug.replacedert(
inputKeys.Length >= startIndex + count && inputValues.Length >= startIndex + count &&
inputKeys.Length >= startIndex + count && inputValues.Length >= startIndex + count,
"The spans must be able to hold the sort region.");
#if DEBUG
for (int i = startIndex; i < startIndex + count; ++i)
{
//Technically, there are instances where someone may want to force a smaller sort... but... that's extremely rare, and there are other options available.
Debug.replacedert(inputKeys[i] <= keysUpperBound, "The given upper bound must actually bound the elements in the sort region, or else the sort won't sort.");
}
#endif
int bucketSetCount = keysUpperBound < (1 << 16) ? keysUpperBound < (1 << 8) ? 1 : 2 : keysUpperBound < (1 << 24) ? 3 : 4;
bufferPool.Take<int>(bucketSetCount * 256, out var bucketCounts);
unsafe
{
//The bucket counts will be added to, so they need to be zeroed.
Unsafe.InitBlockUnaligned(bucketCounts.Memory, 0, (uint)(sizeof(int) * 256 * bucketSetCount));
}
switch (bucketSetCount)
{
case 1:
{
SortU8(ref inputKeys[startIndex], ref inputValues[startIndex], ref scratchKeys[startIndex], ref scratchValues[startIndex], ref bucketCounts[0], count);
sortedKeys = scratchKeys;
sortedValues = scratchValues;
}
break;
case 2:
{
SortU16(ref inputKeys[startIndex], ref inputValues[startIndex], ref scratchKeys[startIndex], ref scratchValues[startIndex], ref bucketCounts[0], count);
sortedKeys = inputKeys;
sortedValues = inputValues;
}
break;
case 3:
{
SortU24(ref inputKeys[startIndex], ref inputValues[startIndex], ref scratchKeys[startIndex], ref scratchValues[startIndex], ref bucketCounts[0], count);
sortedKeys = scratchKeys;
sortedValues = scratchValues;
}
break;
case 4:
{
SortU32(ref inputKeys[startIndex], ref inputValues[startIndex], ref scratchKeys[startIndex], ref scratchValues[startIndex], ref bucketCounts[0], count);
sortedKeys = inputKeys;
sortedValues = inputValues;
}
break;
default:
Debug.Fail("Invalid bucket set count.");
sortedKeys = default;
sortedValues = default;
break;
}
bufferPool.Return(ref bucketCounts);
}
19
Source : ConstraintChecker.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
[Conditional("DEBUG")]
public static void replacedertValid(in MotorSettings settings, string typeName)
{
if (!MotorSettings.Validate(settings))
{
Debug.Fail($"{typeName}.MotorSettings must have nonnegative maximum force and damping.");
}
}
19
Source : NarrowPhaseCCDContinuations.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
[MethodImpl(MethodImplOptions.AggressiveInlining)]
CollidablePair GetCollidablePair(int pairId)
{
var continuation = new CCDContinuationIndex(pairId);
Debug.replacedert(continuation.Exists);
var index = continuation.Index;
switch ((ConstraintGeneratorType)continuation.Type)
{
case ConstraintGeneratorType.Discrete:
return discrete.Caches[index].Pair;
case ConstraintGeneratorType.Continuous:
return continuous.Caches[index].Pair;
}
Debug.Fail("Invalid collision continuation type. Corrupted data?");
return new CollidablePair();
}
19
Source : ConstraintChecker.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
[Conditional("DEBUG")]
public static void replacedertValid(in ServoSettings settings, string typeName)
{
if (!ServoSettings.Validate(settings))
{
Debug.Fail($"{typeName}.ServoSettings must have nonnegative maximum speed, base speed, and maximum force.");
}
}
19
Source : TypeProcessor.cs
with Apache License 2.0
from bepu
with Apache License 2.0
from bepu
public virtual void IncrementallyUpdateContactData(ref TypeBatch typeBatch, Bodies bodies, float dt, float inverseDt, int startBundle, int end)
{
Debug.Fail("A contact data update was scheduled for a type batch that does not have a contact data update implementation.");
}
19
Source : MainWindow.xaml.cs
with Apache License 2.0
from bezzad
with Apache License 2.0
from bezzad
private async void RenderToMemory(object sender, RoutedEventArgs e)
{
try
{
var pageStep = Renderer.PagesDisplayMode == PdfViewerPagesDisplayMode.BookMode ? 2 : 1;
Dispatcher.Invoke(() => Renderer.GotoPage(0));
while (Renderer.PageNo < Renderer.PageCount - pageStep)
{
Dispatcher.Invoke(() => Renderer.NextPage());
await Task.Delay(1);
}
}
catch (Exception ex)
{
Cts.Cancel();
Debug.Fail(ex.Message);
MessageBox.Show(this, ex.Message, "Error!");
}
}
19
Source : MainWindow.xaml.cs
with Apache License 2.0
from bezzad
with Apache License 2.0
from bezzad
private void SaveAsImages(string path)
{
try
{
for (var i = 0; i < Renderer.PageCount; i++)
{
var size = Renderer.Doreplacedent.PageSizes[i];
var image = Renderer.Doreplacedent.Render(i, (int)size.Width * 5, (int)size.Height * 5, 300, 300, false);
image.Save(Path.Combine(path, $"img{i}.png"));
}
}
catch (Exception ex)
{
Cts.Cancel();
Debug.Fail(ex.Message);
MessageBox.Show(this, ex.Message, "Error!");
}
}
19
Source : Disposer.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public void Set(IDisposable disposable)
{
if (disposable == null)
{
throw new ArgumentNullException("disposable");
}
object originalFieldValue = Interlocked.CompareExchange(ref _disposable, disposable, null);
if (originalFieldValue == null)
{
// this is the first call to Set() and Dispose() hasn't yet been called; do nothing
}
else if (originalFieldValue == _disposedSentinel)
{
// Dispose() has already been called, so we need to dispose of the object that was just added
disposable.Dispose();
}
else
{
#if !NET35 && !SILVERLIGHT && !NETFX_CORE
// Set has been called multiple times, fail
Debug.Fail("Multiple calls to Disposer.Set(IDisposable) without calling Disposer.Dispose()");
#endif
}
}
19
Source : Palette.cs
with MIT License
from Braini01
with MIT License
from Braini01
public void Read(BinaryReaderEx input, int[] startOffsets)
{
//read Taggs
while (input.ReadAscii(4) == "GGAT")
{
var taggName = input.ReadAscii(4);
int taggSize = input.ReadInt32();
switch (taggName)
{
case "CXAM": //MAXC
Debug.replacedert(taggSize == 4);
MaxColor = new PackedColor(input.ReadUInt32());
break;
case "CGVA": //AVGC
Debug.replacedert(taggSize == 4);
AverageColor = new PackedColor(input.ReadUInt32());
break;
case "GALF": //FLAG
Debug.replacedert(taggSize == 4);
int flags = input.ReadInt32();
if ((flags & PicFlagAlpha) != 0)
IsAlpha = true;
if ((flags & PicFlagTransparent) != 0)
IsTransparent = true;
break;
case "SFFO": //OFFS
int nOffs = taggSize / sizeof(int);
for (int i = 0; i < nOffs; i++)
{
startOffsets[i] = input.ReadInt32();
}
break;
case "ZIWS": //SWIZ
Debug.replacedert(taggSize == 4);
ARGBSwizzle newSwizzle;
newSwizzle.SwizA = (TexSwizzle)input.ReadByte();
newSwizzle.SwizR = (TexSwizzle)input.ReadByte();
newSwizzle.SwizG = (TexSwizzle)input.ReadByte();
newSwizzle.SwizB = (TexSwizzle)input.ReadByte();
ChannelSwizzle = newSwizzle;
break;
default:
//just skip the data
Debug.Fail("What is that unknown PAA tagg?");
input.Position += taggSize;
break;
}
}
input.Position -= 4;
//read palette colors
var nPaletteColors = input.ReadUInt16();
Colors = new PackedColor[nPaletteColors];
for (int index = 0; index < nPaletteColors; ++index)
{
var b = input.ReadByte();
var g = input.ReadByte();
var r = input.ReadByte();
Colors[index] = new PackedColor(r, g, b);
}
}
19
Source : ThreadPoolAnalyzer.cs
with MIT License
from chrisnas
with MIT License
from chrisnas
private void DumpRunningThreadpoolThreads(ClrMDHelper helper)
{
Dictionary<string, ThreadDistributionItem> distribution = new Dictionary<string, ThreadDistributionItem>(8 * 1024);
StringBuilder sb = new StringBuilder(8 * 1024 * 1024);
_host.WriteLine("\r\n ID ThreadOBJ Locks Details");
_host.WriteLine("-----------------------------------------------------------------------------------");
foreach (var thread in _host.Session.Clr.Threads
.Where(t => t.IsThreadpoolWorker)
.OrderBy(t => (t.LockCount > 0) ? -1 : (!t.IsAlive ? t.ManagedThreadId + 10000 : t.ManagedThreadId)))
{
string details = GetCallStackInfo(helper, thread);
sb.AppendFormat("{0,4} {1} {2} {3}\r\n",
thread.ManagedThreadId.ToString(),
thread.Address.ToString("X16"),
((thread.LockCount > 0) ? thread.LockCount.ToString("D4") : " "),
details
);
// the details might have different forms
// 155 000000CC08EF5030 Thread
// + [method signature]
// => WaitHandle.WaitOneNative(0x000000CFC388EBA0 : SafeWaitHandle)
// 156 000000CC08EFD050 Task | [method signature]
// + [method signature]
// => WaitHandle.WaitOneNative(0x000000CF40B7F480 : SafeWaitHandle)
// but we just want to group by the first TWO lines (not the "=> ..." that contains pointers values that will break the grouping
// so the key is computed up to "=>"
string key = details;
int pos = details.IndexOf("=>");
if (pos == -1)
{
key = string.Intern(details);
}
else
{
int lastLineMarkerPos = details.IndexOf("\r\n");
if (lastLineMarkerPos == -1)
{
Debug.Fail("unexpected item format" + details);
lastLineMarkerPos = pos;
}
key = string.Intern(details.Substring(0, lastLineMarkerPos + "\r\n".Length));
}
ThreadDistributionItem state;
if (distribution.ContainsKey(key))
{
state = distribution[key];
}
else
{
state = new ThreadDistributionItem()
{
Key = key,
Count = 0
};
distribution[key] = state;
}
state.Count++;
}
_host.WriteLine(sb.ToString());
// build a summary
if (distribution.Values.Count > 0)
{
sb.Clear();
sb.AppendLine("\r\n____________________________________________________________________________________________________\r\nCount Details\r\n----------------------------------------------------------------------------------------------------");
int total = 0;
foreach (var item in distribution.Values.OrderBy(t => t.Count))
{
sb.AppendLine(string.Format(" {0,4} {1}", item.Count.ToString(), item.Key));
total += item.Count;
}
sb.AppendLine(" ----");
sb.AppendLine(string.Format(" {0,4}\r\n", total.ToString()));
_host.WriteLine(sb.ToString());
}
}
19
Source : HeapSnapshotFactory.cs
with MIT License
from chrisnas
with MIT License
from chrisnas
private static DumpHeapParsingState ParseAndAddTypeEntry(string line, HeapSnapshot snapshot)
{
if (line.StartsWith("Total"))
{
return DumpHeapParsingState.End;
}
// MT Count TotalSize Clreplaced Name
// 651d7ffc 1 12 System.Configuration.Internal.ConfigurationManagerInternal
//
// or in x64
//
// 0x000007ff01221408 1,448 57,920 System.Xml.XmlQualifiedName
//
TypeEntry entry = new TypeEntry();
var pos = 0;
var end = 0;
string field;
// 1. look for the MT
end = line.IndexOf(SPACE);
if (end == -1)
{
Debug.WriteLine("impossible to find the end of the MT field");
return DumpHeapParsingState.Error;
}
field = line.Substring(pos, end - pos);
entry.MethodTable = field;
if (!SkipSpaces(line, ref end))
{
Debug.WriteLine("impossible to find the start of the Count field");
return DumpHeapParsingState.Error;
}
pos = end;
// 2. look for the count
end = line.IndexOf(SPACE, pos);
if (end == -1)
{
Debug.WriteLine("impossible to find the end of the Count field");
return DumpHeapParsingState.Error;
}
field = line.Substring(pos, end - pos);
if (!long.TryParse(GetNumberFromString(field), out var count))
{
Debug.WriteLine("invalid decimal value for the Count field");
return DumpHeapParsingState.Error;
}
entry.Count = count;
if (!SkipSpaces(line, ref end))
{
Debug.WriteLine("impossible to find the start of the TotalSize field");
return DumpHeapParsingState.Error;
}
pos = end;
// 3. look for the total size
end = line.IndexOf(SPACE, pos);
if (end == -1)
{
Debug.WriteLine("impossible to find the end of the MT field");
return DumpHeapParsingState.Error;
}
field = line.Substring(pos, end - pos);
if (!long.TryParse(GetNumberFromString(field), out var totalSize))
{
Debug.WriteLine("invalid decimal value for the TotalSize field");
return DumpHeapParsingState.Error;
}
entry.TotalSize = totalSize;
if (!SkipSpaces(line, ref end))
{
Debug.WriteLine("impossible to find the start of the TotalSize field");
return DumpHeapParsingState.Error;
}
pos = end;
// 4. look for the clreplaced name
field = line.Substring(pos);
entry.Name = string.Intern(field);
snapshot.ObjectCount += entry.Count;
snapshot.Size += entry.TotalSize;
string key = HeapSnapshot.GetKey(entry);
if (!snapshot.TypeStats.ContainsKey(key))
{
snapshot.TypeStats.Add(key, entry);
}
else
{
Debug.Fail("This should never happen");
throw new InvalidOperationException($"Impossible to find {key} for the entry");
}
return DumpHeapParsingState.TypeEntries;
}
19
Source : ListViewHelpers.cs
with MIT License
from chrisnas
with MIT License
from chrisnas
private int InternalCompare(TypeEntry xEntry, TypeEntry yEntry)
{
switch (Column)
{
case columnCount:
if (xEntry.Count > yEntry.Count)
return 1;
if (xEntry.Count < yEntry.Count)
return -1;
return 0;
case columnSize:
if (xEntry.TotalSize > yEntry.TotalSize)
return 1;
if (xEntry.TotalSize < yEntry.TotalSize)
return -1;
return 0;
case columnClreplaced:
return string.Compare(xEntry.Name, yEntry.Name);
default:
Debug.Fail("Unknown column");
break;
}
return 0;
}
19
Source : Interop.GetSystemMetrics.cs
with MIT License
from chromelyapps
with MIT License
from chromelyapps
public static int GetCurrentSystemMetrics(SystemMetric nIndex, uint dpi)
{
if (IsWindows10_1607OrGreater)
{
return GetSystemMetricsForDpi(nIndex, dpi);
}
else
{
Debug.Fail("GetSystemMetricsForDpi() is not available on this OS");
return GetSystemMetrics(nIndex);
}
}
19
Source : SortedCollection.cs
with MIT License
from clovett
with MIT License
from clovett
internal bool Update(T item, int priority)
{
ItemKey oldKey = null;
if (!indexes.TryGetValue(item, out oldKey))
{
Debug.Fail("Update called but item is not in the list");
return false;
}
if (oldKey.Priority == priority)
{
return false;
}
else
{
this.sortedItems.Remove(oldKey);
// Since we are changing the priority, we also have to give it a new index since we cannot
// guarentee that the new priority + old index is not already used.
InternalAdd(item, priority);
return true;
}
}
19
Source : SortedCollection.cs
with MIT License
from clovett
with MIT License
from clovett
internal void Remove(T item)
{
if (this.sortedItems.Count > 0)
{
ItemKey oldKey = null;
if (!indexes.TryGetValue(item, out oldKey))
{
Debug.Fail("Remove called but item is not in the list");
return;
}
cachedList = null;
indexes.Remove(item);
this.sortedItems.Remove(oldKey);
}
}
19
Source : CodeTemplate.cs
with MIT License
from CoderLine
with MIT License
from CoderLine
public override string ToString()
{
return FormatArgRegex.Replace(_template, match =>
{
var variable = BuildVariable(match);
if (!Variables.TryGetValue(variable.Name, out variable))
{
Debug.Fail("All variables should have been emitted and filled by now");
variable.RawValue = "null/*missing value*/";
}
return variable.RawValue;
});
}
19
Source : MethodBlock.cs
with MIT License
from CoderLine
with MIT License
from CoderLine
protected override void DoEmit(CancellationToken cancellationToken = new CancellationToken())
{
if (Emitter.IsExternal(_method)
|| Emitter.IsCompilerExtension(_method)
|| (_method.MethodKind == MethodKind.PropertyGet && Emitter.IsExternal(_method.replacedociatedSymbol))
|| (_method.MethodKind == MethodKind.PropertySet && Emitter.IsExternal(_method.replacedociatedSymbol))
)
{
return;
}
if (!_method.ExplicitInterfaceImplementations.IsEmpty
|| (_method.MethodKind == MethodKind.PropertyGet && !((IPropertySymbol)_method.replacedociatedSymbol).ExplicitInterfaceImplementations.IsEmpty)
|| (_method.MethodKind == MethodKind.PropertySet && !((IPropertySymbol)_method.replacedociatedSymbol).ExplicitInterfaceImplementations.IsEmpty)
)
{
return;
}
switch (_method.MethodKind)
{
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
if (Emitter.IsAutoProperty((IPropertySymbol)_method.replacedociatedSymbol))
{
return;
}
break;
case MethodKind.EventRaise:
if (Emitter.IsEventField((IEventSymbol)_method.replacedociatedSymbol))
{
return;
}
break;
}
if (_method.MethodKind == MethodKind.Destructor)
{
// TODO: Warning: Destructors not supported
return;
}
if (_method.MethodKind == MethodKind.StaticConstructor && _method.DeclaringSyntaxReferences.Length == 0)
{
// implicit static constructor
return;
}
if (_method.ContainingType.TypeKind == TypeKind.Struct && Emitter.IsAbstract(_method.ContainingType) && _method.MethodKind == MethodKind.Constructor && _method.DeclaringSyntaxReferences.Length == 0)
{
// implicit constructor for structs
return;
}
WriteComments(_method, cancellationToken);
WriteMeta(_method, cancellationToken);
if (Emitter.IsFrom(_method))
{
Write("@:from ");
}
if (Emitter.IsTo(_method))
{
Write("@:to ");
}
var op = Emitter.GetOp(_method);
if (op != null)
{
Write("@:op");
WriteOpenParentheses();
Write(op);
WriteCloseParentheses();
}
if (_method.MethodKind == MethodKind.StaticConstructor || _method.ContainingType.TypeKind == TypeKind.Interface)
{
WriteAccessibility(Accessibility.Public);
}
else
{
WriteAccessibility(_method.DeclaredAccessibility);
}
if (_method.IsStatic)
{
Write("static ");
}
if (Emitter.IsInline(_method))
{
Write("inline ");
}
if (_method.OverriddenMethod != null && _method.OverriddenMethod.ContainingType.SpecialType != SpecialType.System_Object && !Emitter.IsAbstract(_method.ContainingType))
{
Write("override ");
}
Write("function ");
var methodName = Emitter.GetMethodName(_method);
Write(methodName);
var typeParameters = new List<ITypeSymbol>(_method.TypeParameters);
if (_method.IsStatic)
{
CollectTypeParameters(typeParameters, _method.ReturnType);
foreach (var parameter in _method.Parameters)
{
CollectTypeParameters(typeParameters, parameter.Type);
}
}
if (typeParameters.Count > 0)
{
Write("<");
for (int i = 0; i < typeParameters.Count; i++)
{
if (i > 0)
{
WriteComma();
}
Write(typeParameters[i].Name);
}
Write(">");
}
WriteOpenParentheses();
WriteParameterDeclarations(_method.Parameters, cancellationToken);
WriteCloseParentheses();
WriteSpace();
switch (_method.MethodKind)
{
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
WriteColon();
WriteType(((IPropertySymbol)_method.replacedociatedSymbol).Type);
break;
case MethodKind.EventAdd:
case MethodKind.EventRemove:
WriteColon();
WriteType(Emitter.GetSpecialType(SpecialType.System_Void));
break;
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
break;
default:
WriteColon();
if (Emitter.IsGetEnumeratorAsIterator(_method))
{
Write("Iterable<");
var generic = ((INamedTypeSymbol)_method.ReturnType).TypeArguments[0];
WriteType(generic);
Write(">");
}
else
{
WriteType(_method.ReturnType);
}
Write(" ");
break;
}
if (_method.ContainingType.TypeKind == TypeKind.Interface || (Emitter.IsNative(_method.ContainingType) && _method.IsExtern))
{
WriteSemiColon(true);
}
else
{
WriteNewLine();
BeginBlock();
if (_method.DeclaringSyntaxReferences.IsEmpty && _method.MethodKind == MethodKind.Constructor && !_method.IsStatic && _method.ContainingType.BaseType != null && _method.ContainingType.BaseType.SpecialType != SpecialType.System_Object)
{
// default constructor
var x = Emitter.GetMethodName(_method);
if (x == "new")
{
if (!Emitter.HasNoConstructor(_method.ContainingType.BaseType))
{
Write("super");
WriteOpenCloseParentheses();
WriteSemiColon(true);
}
}
else
{
Write(x);
WriteOpenCloseParentheses();
WriteSemiColon(true);
}
}
else if (!_method.DeclaringSyntaxReferences.IsEmpty)
{
foreach (var reference in _method.DeclaringSyntaxReferences)
{
var node = reference.GetSyntax(cancellationToken);
var methodDeclarationSyntax = node as MethodDeclarationSyntax;
var constructorDeclarationSyntax = node as ConstructorDeclarationSyntax;
var accessorDeclarationSyntax = node as AccessorDeclarationSyntax;
var operatorDeclarationSyntax = node as OperatorDeclarationSyntax;
var conversionOperatorDeclarationSyntax = node as ConversionOperatorDeclarationSyntax;
var arrowExpressionClauseSyntax = node as ArrowExpressionClauseSyntax;
if (methodDeclarationSyntax != null)
{
if (methodDeclarationSyntax.ExpressionBody != null)
{
if (!_method.ReturnsVoid)
{
WriteReturn(true);
}
EmitTree(methodDeclarationSyntax.ExpressionBody.Expression,
cancellationToken);
WriteSemiColon(true);
}
else if (methodDeclarationSyntax.Body != null)
{
foreach (var statement in methodDeclarationSyntax.Body.Statements)
{
EmitTree(statement, cancellationToken);
}
}
else if (_method.IsAbstract)
{
Write("throw \"abstract\";");
WriteNewLine();
}
}
else if (conversionOperatorDeclarationSyntax != null)
{
if (conversionOperatorDeclarationSyntax.ExpressionBody != null)
{
if (!_method.ReturnsVoid)
{
WriteReturn(true);
}
EmitTree(conversionOperatorDeclarationSyntax.ExpressionBody.Expression,
cancellationToken);
WriteSemiColon(true);
}
else if (conversionOperatorDeclarationSyntax.Body != null)
{
foreach (var statement in conversionOperatorDeclarationSyntax.Body.Statements)
{
EmitTree(statement, cancellationToken);
}
}
else if (_method.IsAbstract)
{
Write("throw \"abstract\";");
WriteNewLine();
}
}
else if (operatorDeclarationSyntax != null)
{
if (operatorDeclarationSyntax.ExpressionBody != null)
{
if (!_method.ReturnsVoid)
{
WriteReturn(true);
}
EmitTree(operatorDeclarationSyntax.ExpressionBody.Expression,
cancellationToken);
WriteSemiColon(true);
}
else if (operatorDeclarationSyntax.Body != null)
{
foreach (var statement in operatorDeclarationSyntax.Body.Statements)
{
EmitTree(statement, cancellationToken);
}
}
else if (_method.IsAbstract)
{
Write("throw \"abstract\";");
WriteNewLine();
}
}
else if (arrowExpressionClauseSyntax != null)
{
if (!_method.ReturnsVoid)
{
WriteReturn(true);
}
EmitTree(arrowExpressionClauseSyntax.Expression,
cancellationToken);
WriteSemiColon(true);
}
else if (constructorDeclarationSyntax != null)
{
if (!Emitter.IsAbstract(_method.ContainingType))
{
if (constructorDeclarationSyntax.Initializer != null)
{
var ctor = (IMethodSymbol)Emitter
.GetSymbolInfo(constructorDeclarationSyntax.Initializer)
.Symbol;
var x = Emitter.GetMethodName(ctor);
if (x == "new")
{
Write("super");
}
else
{
Write(x);
}
WriteMethodInvocation(ctor,
constructorDeclarationSyntax.Initializer.ArgumentList,
constructorDeclarationSyntax.Initializer,
cancellationToken);
WriteSemiColon(true);
}
else if (!_method.IsStatic && _method.ContainingType.BaseType != null &&
_method.ContainingType.BaseType.SpecialType != SpecialType.System_Object)
{
var ctor = _method.ContainingType.BaseType.InstanceConstructors.FirstOrDefault(
c => c.Parameters.Length == 0);
if (ctor != null)
{
var x = Emitter.GetMethodName(ctor);
if (x == "new")
{
if (!Emitter.HasNoConstructor(_method.ContainingType.BaseType))
{
Write("super");
WriteOpenCloseParentheses();
WriteSemiColon(true);
}
}
else
{
Write(x);
WriteOpenCloseParentheses();
WriteSemiColon(true);
}
}
else
{
Debugger.Break();
}
}
}
// write default initializers
WriteDefaultInitializers(_method.ContainingType, _method.IsStatic, cancellationToken);
if (_method.IsStatic)
{
WriteES5PropertyDeclarations(_method.ContainingType);
}
if (constructorDeclarationSyntax.ExpressionBody != null)
{
EmitTree(constructorDeclarationSyntax.ExpressionBody);
WriteSemiColon(true);
}
if (constructorDeclarationSyntax.Body != null)
{
foreach (var statement in constructorDeclarationSyntax.Body.Statements)
{
EmitTree(statement, cancellationToken);
}
}
}
else if (accessorDeclarationSyntax != null)
{
if (accessorDeclarationSyntax.ExpressionBody != null)
{
if (_method.MethodKind == MethodKind.PropertyGet)
{
WriteReturn(true);
EmitTree(accessorDeclarationSyntax.ExpressionBody.Expression,
cancellationToken);
WriteSemiColon(true);
}
else if(_method.MethodKind == MethodKind.PropertySet)
{
var property = (IPropertySymbol)_method.replacedociatedSymbol;
if (property.GetMethod != null)
{
var typeInfo =
Emitter.GetTypeInfo(accessorDeclarationSyntax.ExpressionBody.Expression);
if (SymbolEquivalenceComparer.Instance.Equals(typeInfo.Type, property.Type))
{
WriteReturn(true);
EmitTree(accessorDeclarationSyntax.ExpressionBody.Expression,
cancellationToken);
WriteSemiColon(true);
}
else
{
EmitTree(accessorDeclarationSyntax.ExpressionBody.Expression,
cancellationToken);
WriteSemiColon(true);
WriteReturn(true);
Write(Emitter.GetSymbolName(property.GetMethod));
WriteOpenParentheses();
for (int i = 0; i < _method.Parameters.Length - 1; i++)
{
Write(Emitter.GetSymbolName(_method.Parameters[i]));
}
WriteCloseParentheses();
WriteSemiColon(true);
}
}
}
else
{
EmitTree(accessorDeclarationSyntax.ExpressionBody.Expression,
cancellationToken);
WriteSemiColon(true);
}
}
else if (accessorDeclarationSyntax.Body != null)
{
EmitterContext.SetterMethod =
_method.MethodKind == MethodKind.PropertySet ? _method : null;
foreach (var statement in accessorDeclarationSyntax.Body.Statements)
{
EmitTree(statement, cancellationToken);
}
EmitterContext.SetterMethod = null;
if (_method.MethodKind == MethodKind.PropertySet)
{
WriteReturn(true);
var property = (IPropertySymbol)_method.replacedociatedSymbol;
if (property.GetMethod != null)
{
Write(Emitter.GetMethodName(property.GetMethod));
WriteOpenParentheses();
if (property.IsIndexer)
{
for (int i = 0; i < property.GetMethod.Parameters.Length; i++)
{
if (i > 0)
{
WriteComma();
}
Write(property.GetMethod.Parameters[i].Name);
}
}
WriteCloseParentheses();
}
else
{
Write(_method.Parameters.Last().Name);
}
WriteSemiColon(true);
}
}
else
{
WriteDefaultImplementation(cancellationToken);
}
}
else
{
Debug.Fail($"Unhandled syntax node: {node.Kind()}");
}
}
}
else
{
WriteDefaultImplementation(cancellationToken);
}
if (_method.MethodKind == MethodKind.Constructor && !Emitter.HasNativeConstructors(_method.ContainingType) && Emitter.HasConstructorOverloads(_method.ContainingType))
{
WriteReturn(true);
WriteThis();
WriteSemiColon(true);
}
EndBlock();
WriteNewLine();
}
WriteComments(_method, false, cancellationToken);
}
19
Source : AttributeLoader.cs
with MIT License
from CoderLine
with MIT License
from CoderLine
private void HandleAttributeBuilderInvocation(InvocationExpressionSyntax node, IMethodSymbol method)
{
// add attribute
if (method.Name == "Add" && node.Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
{
var memberAccess = (MemberAccessExpressionSyntax)node.Expression;
AttributeBuilderDetails variableDetails = null;
if (memberAccess.Expression.Kind() == SyntaxKind.InvocationExpression)
{
// chained method calls
variableDetails = this.GetAttributesBuilderVariable(memberAccess.Expression);
}
else
{
var symbol = _semanticModel.GetSymbolInfo(memberAccess.Expression).Symbol;
if (symbol != null && symbol.Kind == SymbolKind.Local)
{
// variable access
_variables.TryGetValue(symbol.Name, out variableDetails);
}
}
if (variableDetails == null)
{
throw ReportError(Diagnostic.Create(PhaseErrors.PH012, node.Expression.GetLocation()));
}
foreach (var argument in node.ArgumentList.Arguments)
{
if (argument.Expression.Kind() != SyntaxKind.ObjectCreationExpression)
{
throw ReportError(Diagnostic.Create(PhaseErrors.PH013, argument.GetLocation()));
}
var newAttribute = (ObjectCreationExpressionSyntax)argument.Expression;
var constructor = (IMethodSymbol)_semanticModel.GetSymbolInfo(newAttribute).Symbol;
var constructorArguments = new List<TypedConstant>();
var namedArguments = new Dictionary<string, TypedConstant>();
for (var i = 0; i < newAttribute.ArgumentList.Arguments.Count; i++)
{
var ctorArgument = newAttribute.ArgumentList.Arguments[i];
var typeInfo = _semanticModel.GetTypeInfo(ctorArgument.Expression);
var value = _semanticModel.GetConstantValue(ctorArgument.Expression);
if (!value.HasValue)
{
throw ReportError(Diagnostic.Create(PhaseErrors.PH004,
ctorArgument.GetLocation(), constructor.Parameters[i].Name));
}
constructorArguments.Add(CreateTypedConstant(typeInfo.Type, value.Value));
}
if (newAttribute.Initializer != null)
{
foreach (var initializerStatement in newAttribute.Initializer.Expressions)
{
if (initializerStatement.Kind() != SyntaxKind.SimplereplacedignmentExpression)
{
throw ReportError(Diagnostic.Create(PhaseErrors.PH014, initializerStatement.GetLocation()));
}
var replacedignment = (replacedignmentExpressionSyntax)initializerStatement;
var symbol = _semanticModel.GetSymbolInfo(replacedignment.Left).Symbol;
var typeInfo = _semanticModel.GetTypeInfo(replacedignment.Right);
var value = _semanticModel.GetConstantValue(replacedignment.Right);
if (!value.HasValue)
{
throw ReportError(Diagnostic.Create(PhaseErrors.PH004,
replacedignment.Right.GetLocation(), symbol.Name));
}
namedArguments[symbol.Name] = CreateTypedConstant(typeInfo.Type, value.Value);
}
}
this.RegisterAttribute(variableDetails, new CustomAttributeData(constructor, constructorArguments, namedArguments)); ;
}
}
else
{
Debug.Fail("Missing handling of method");
}
}
19
Source : TextScanner.cs
with MIT License
from CommitteeOfZero
with MIT License
from CommitteeOfZero
protected void EatChar(char c)
{
char actualCharacter = PeekChar();
if (actualCharacter != c)
{
Debug.Fail($"Error while scanning source text. Expected: '{c}', found: '{actualCharacter}'.");
}
AdvanceChar();
}
See More Examples