This was brought about by this codegolf question.
Problem
A program is said to be pristine if it is:
- A working program (No errors).
- The program will produce errors by removing any contiguous substring of N characters, where
1 <= N < program length
.
My goal is to check if a given C# program's source is pristine or not with the assumption that the given program is already working.
What I Did
I generated all possible removal combinations and compiled the resulting string with CompileAssemblyFromSource
. Compile errors are then checked with CompilerResults.Errors
.
static bool isPristine(string sourceCode)
{
using (var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }))
{
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" });
parameters.GenerateExecutable = true;
int length = sourceCode.Length;
for (int i = 0; i < length; i++)
{
for (int j = 1; j < length - i; j++)
{
string sourceWithRemoval = sourceCode.Remove(i, j);
CompilerResults results = csc.CompileAssemblyFromSource(parameters, sourceWithRemoval);
if (results.Errors.Count == 0)
{
Debug.WriteLine("Still works by removing:");
Debug.WriteLine("@{0}@ ", sourceCode.Substring(i, j));
Debug.WriteLine("At index {0}.", i);
return false;
}
}
}
}
return true;
}
Usage
static void Main(string[] args)
{
string sourceCode = "class e{static void Main(){System.Console.Write(new char[1\n#if l\n#else\n*5]{'w','o','r','l','d'\n#if o\n#else\n});\n#endif\n}\n#endif\n}";
Console.WriteLine(isPristine(sourceCode) ? "Pristine" : "Not pristine");
Console.ReadLine();
}
Main Concerns
- What can I improve (performance, readability)?
- Are there better, faster C# techs that I should have used?
sourceCode
is actually a valid program. It will return true for any number of spaces. \$\endgroup\$