Hello Plus Plus/Compiler

From Esolang
Jump to navigation Jump to search

To compile using the Mono compiler, use mcs filename.cs.

using System;
using System.IO;
using System.CodeDom.Compiler;

namespace HelloPP
{
	class MainClass
	{
		public static string GenerateCode (string output)
		{
			return @"
using System;

namespace HelloPP
{
	class MainClass
	{
		public static void Main ()
		{
			Console.Write(@" + "\"" + output + "\"" + @");
		}
	}
}
";
		} // public static string GenerateCode
		
		public static void Main (string[] args)
		{
			string sourceFilename = string.Empty;
			string outputFilename = string.Empty;
			
			if (args.Length != 1 && args.Length != 2) {
				Console.WriteLine("Hello++ .NET Compiler by Propeng");
				Console.WriteLine("Usage: {0} <source> [destination]",
					Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));
				Environment.Exit(1);
			}
			
			if (args.Length == 1) {
				sourceFilename = args[0];
				outputFilename = "a.out";
			} else if (args.Length == 2) {
				sourceFilename = args[0];
				outputFilename = args[1];
			}
			
			if (Directory.Exists(sourceFilename)) {
				Console.WriteLine("{0}: Is a directory", sourceFilename);
				Environment.Exit(1);
			} else if (Directory.Exists(outputFilename)) {
				Console.WriteLine("{0}: Is a directory", outputFilename);
				Environment.Exit(1);
			}
			
			StreamReader reader;
			
			try {
				reader = new StreamReader(sourceFilename);
				
				char[] chars = reader.ReadToEnd().ToCharArray();
				string output = string.Empty;
				
				foreach (char sourceChar in chars) {
					if (sourceChar.ToString().ToLower() == "h")
						output += "Hello World" + Environment.NewLine;
				}
				
				System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
				parameters.GenerateExecutable = true;
				parameters.GenerateInMemory = false;
				parameters.OutputAssembly = outputFilename;
				
				try {
					CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("C#");
					CompilerResults results =
						codeProvider.CompileAssemblyFromSource(parameters, GenerateCode(output));
					
					foreach(CompilerError error in results.Errors) {
						Console.WriteLine(error.Line + ": " + error.ErrorNumber + " " + error.ErrorText);
					}
				} catch (Exception e) {
					Console.WriteLine("{0}: {1}", outputFilename, e.Message);
					Environment.Exit(1);
				}
			} catch (FileNotFoundException) {
				Console.WriteLine("{0}: No such file or directory", sourceFilename);
				Environment.Exit(1);
			} catch (IOException ioe) {
				Console.WriteLine("{0}: I/O Error", sourceFilename);
				Console.WriteLine(ioe.StackTrace);
				Environment.Exit(2);
			} catch (Exception une) {
				Console.WriteLine("{0}: {1}", sourceFilename, une.Message);
				Console.WriteLine(une.StackTrace);
				Environment.Exit(2);
			}
		} // public static void Main
	} // class MainClass
} // namespace HelloPP