public CompileLog generateStructDeclaration(StringBuilder codeBuilder, TbsStruct tbs) { var log = new CompileLog(); codeBuilder.AppendLine($"struct {tbs.Typename};"); return(log); }
public CompileLog generateEnumDeclration(StringBuilder codeBuilder, TbsEnum tbs) { var log = new CompileLog(); codeBuilder.AppendLine($"enum {tbs.Typename};"); return(log); }
public async Task <Type> CompileSourceCode(string code) { Console.WriteLine("Compile assembly"); var assembly = await Compile(code); if (assembly != null) { CompileLog.Add("Searching for first exported type."); return(assembly.GetExportedTypes().FirstOrDefault()); } return(null); }
public CompileLog generateEnumDefinition(StringBuilder codeBuilder, TbsEnum tbs) { var log = new CompileLog(); codeBuilder.AppendLine($"enum {tbs.Typename} {{"); foreach (var option in tbs.Options) { codeBuilder.AppendLine($"{option},"); } codeBuilder.AppendLine($"}};\n"); return(log); }
public async Task <Assembly> Compile(string code) { await Init(); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(LanguageVersion.Preview)); foreach (var diagnostic in syntaxTree.GetDiagnostics()) { CompileLog.Add(diagnostic.ToString()); } if (syntaxTree.GetDiagnostics().Any(i => i.Severity == DiagnosticSeverity.Error)) { CompileLog.Add("Parse SyntaxTree Error!"); return(null); } CompileLog.Add("Parse SyntaxTree Success"); CSharpCompilation compilation = CSharpCompilation.Create("CompileBlazorInBlazor.Demo", new[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (MemoryStream stream = new MemoryStream()) { EmitResult result = compilation.Emit(stream); foreach (var diagnostic in result.Diagnostics) { CompileLog.Add(diagnostic.ToString()); } if (!result.Success) { CompileLog.Add("Compilation error"); return(null); } CompileLog.Add("Compilation success!"); stream.Seek(0, SeekOrigin.Begin); // var context = new CollectibleAssemblyLoadContext(); Assembly assemby = AppDomain.CurrentDomain.Load(stream.ToArray()); return(assemby); } return(null); }
public CompileLog generateEnumDefinition(StringBuilder codeBuilder, TbsEnum tbs) { var log = new CompileLog(); if (CsPublicDatastructure) { codeBuilder.Append("public "); } codeBuilder.AppendLine($"enum {tbs.Typename} : UINT8 {{"); foreach (var option in tbs.Options) { codeBuilder.AppendLine($" {option},"); //ToDo add manual NumericAssociation (=3) } codeBuilder.AppendLine($"}};\n"); return(log); }
public async Task <Type> CompileBlazor(string code) { CompileLog.Add("Create fileSystem"); var fileSystem = new EmptyRazorProjectFileSystem(); CompileLog.Add("Create engine"); // Microsoft.AspNetCore.Blazor.Build. var engine = RazorProjectEngine.Create(RazorConfiguration.Create(RazorLanguageVersion.Version_3_0, "Blazor", new RazorExtension[0]), fileSystem, b => { //BlazorExtensionInitializer.Register(b); }); CompileLog.Add("Create file"); var file = new MemoryRazorProjectItem(code, true, "/App", "/App/App.razor"); CompileLog.Add("File process and GetCSharpDocument"); var doc = engine.Process(file).GetCSharpDocument(); CompileLog.Add("Get GeneratedCode"); var csCode = doc.GeneratedCode; CompileLog.Add("Read Diagnostics"); foreach (var diagnostic in doc.Diagnostics) { CompileLog.Add(diagnostic.ToString()); } if (doc.Diagnostics.Any(i => i.Severity == RazorDiagnosticSeverity.Error)) { return(null); } CompileLog.Add(csCode); CompileLog.Add("Compile assembly"); var assembly = await Compile(csCode); if (assembly != null) { CompileLog.Add("Search Blazor component"); return(assembly.GetExportedTypes().FirstOrDefault(i => i.IsSubclassOf(typeof(ComponentBase)))); } return(null); }
public async Task <Assembly> Compile(string code) { await Init(); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(LanguageVersion.Latest)); foreach (var diagnostic in syntaxTree.GetDiagnostics()) { CompileLog.Add(diagnostic.ToString()); } if (syntaxTree.GetDiagnostics().Any(i => i.Severity == DiagnosticSeverity.Error)) { CompileLog.Add("Parse SyntaxTree Error!"); return(null); } CompileLog.Add("Parse SyntaxTree Success"); //https://stackoverflow.com/questions/35711461/how-to-get-roslyn-to-compile-when-referenced-assemblies-have-references-to-both var op = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); op = op.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); CSharpCompilation compilation = CSharpCompilation.Create("WasmRoslyn.Demo", new[] { syntaxTree }, references, op); using (MemoryStream stream = new MemoryStream()) { EmitResult result = compilation.Emit(stream); foreach (var diagnostic in result.Diagnostics) { CompileLog.Add(diagnostic.ToString()); } if (!result.Success) { CompileLog.Add("Compilation error"); return(null); } CompileLog.Add("Compilation success!"); Assembly assemby = AppDomain.CurrentDomain.Load(stream.ToArray()); return(assemby); } }
public CompileLog generateStructDefinition(StringBuilder codeBuilder, TbsStruct tbs) { var log = new CompileLog(); codeBuilder.AppendLine($"struct {tbs.Typename} {{ //Size={tbs.PhysicalSize}"); foreach (var member in tbs.Members) { if (member.IsScalar) { codeBuilder.AppendLine($"{member.Typename} {member.Identifier};//@Offset {member.LocalOffset}"); } else { codeBuilder.AppendLine($"{member.Typename} {member.Identifier}[{member.ArraySize}];//ArrSize={member.ArraySize} @Offset {member.LocalOffset}"); } } codeBuilder.AppendLine($"}};\n"); return(log); }
private extern static void HHA_CompileHHP(string hhpFile, CompileLog g1, CompileLog g2, int stack);
public IEnumerable <Instruction> Lex(string sourceCode, CompileLog log) { string[] lines = sourceCode.Split(new string[] { LineSperator }, StringSplitOptions.None); int lineCounter = 0; foreach (var line in lines) { var codeLine = line.TrimStart(WhiteSpace); if (codeLine.StartsWith("#")) { log.Warning(lineCounter.ToString(), "Ignoring Compiler Directive", "AbaSim.Compiler does not support compiler directives. You have to configure the runtime separately to change runtime settings."); continue; } Instruction i = new Instruction(); List <string> args = new List <string>(); i.Arguments = args; if (codeLine.StartsWith(CommentSeparator.ToString() + CommentSeparator.ToString())) { i.Comment = codeLine.Substring(2); yield return(i); continue; } int offset = 0; int boffset = 0; Stage stage = Stage.LabelRunning; int commentFirstSymbolSeenOffset = -2; bool seenArgumentSeparatorSymbol = true; //set initially to true, as first argument does not need to be comma separated string location = null; while (offset < codeLine.Length) { location = lineCounter.ToString() + ":" + offset.ToString(); bool isWhiteSpace = WhiteSpace.Contains(codeLine[offset]); switch (stage) { case Stage.LabelRunning: if (codeLine[offset] == LabelTerminator) { i.Label = codeLine.Substring(boffset, offset - boffset); stage = Stage.OperationPending; } else if (isWhiteSpace) { i.Operation = codeLine.Substring(boffset, offset - boffset); stage = Stage.ArgumentsPending; } break; case Stage.OperationPending: if (!isWhiteSpace) { boffset = offset; stage = Stage.OperationRunning; } break; case Stage.OperationRunning: if (isWhiteSpace) { i.Operation = codeLine.Substring(boffset, offset - boffset); stage = Stage.ArgumentsPending; } break; case Stage.ArgumentsPending: if (!isWhiteSpace) { if (codeLine[offset] == ArgumentSeparator) { if (seenArgumentSeparatorSymbol) { args.Add(string.Empty); log.Warning(location, "Empty item in argument list.", null); } } else if (codeLine[offset] == CommentSeparator) { if (commentFirstSymbolSeenOffset == -2) { commentFirstSymbolSeenOffset = offset; } else if (commentFirstSymbolSeenOffset == offset - 1) { stage = Stage.CommentRunning; boffset = offset + 1; } else { log.Error(location, "Unexpected comment separator.", "Comments must be started by 2 comment separator characters (\"" + CommentSeparator.ToString() + "\")."); } } else { boffset = offset; stage = Stage.ArgumentsRunning; if (!seenArgumentSeparatorSymbol) { log.Warning(location, "Arguments are separated by whitespace instead of \"" + ArgumentSeparator.ToString() + "\"", "According to the language standard, arguments must be separated by an argument separator character and optionally additional whitespace."); } } } break; case Stage.ArgumentsRunning: if (isWhiteSpace) { stage = Stage.ArgumentsPending; args.Add(codeLine.Substring(boffset, offset - boffset)); } break; } offset++; } if (stage == Stage.OperationRunning || stage == Stage.LabelRunning) { i.Operation = codeLine.Substring(boffset); } else if (stage == Stage.CommentRunning) { i.Comment = codeLine.Substring(boffset); } else if (stage == Stage.ArgumentsRunning) { args.Add(codeLine.Substring(boffset, offset - boffset)); } i.SourceLine = lineCounter; yield return(i); lineCounter++; //var codeLine = line.TrimStart(WhiteSpace); //if (codeLine.StartsWith("//") || codeLine.StartsWith("#")) //{ // continue; //} //int offset = 0; //int boffset = 0; //Stage stage = Stage.LabelPending; //Instruction i = new Instruction(); //List<string> args = new List<string>(); //i.Arguments = args; //int commentFirstSymbolSeenOffset = -2; //while (offset < codeLine.Length) //{ // bool isWhiteSpace = WhiteSpace.Contains(codeLine[offset]); // if (isWhiteSpace && stage <= Stage.LabelPending) // { // //ignore leading space // boffset++; // } // else if (!isWhiteSpace && stage == Stage.LabelPending) // { // stage = Stage.LabelRunning; // } // else if (codeLine[offset] == ':' && stage <= Stage.LabelRunning) // { // if (offset == 0) // { // throw new InvalidSymbolException(codeLine[offset].ToString(), lineCounter, offset, "label name"); // } // i.Label = codeLine.Substring(boffset, offset - boffset); // boffset = offset + 1; // stage = Stage.OperationPending; // } // else if (isWhiteSpace && stage == Stage.OperationPending) // { // //ignore leading space // boffset++; // } // else if (!isWhiteSpace && stage == Stage.OperationPending) // { // stage = Stage.OperationRunning; // } // else if (isWhiteSpace && stage <= Stage.OperationRunning) // { // i.Operation = codeLine.Substring(boffset, offset - boffset); // if (i.Operation == string.Empty) // { // throw new InvalidSymbolException(codeLine[offset].ToString(), lineCounter, offset, "operation"); // } // boffset = offset + 1; // stage = Stage.ArgumentsPending; // } // else if (isWhiteSpace && stage <= Stage.ArgumentsPending) // { // //ignore leading space // boffset++; // } // else if (!isWhiteSpace && stage == Stage.ArgumentsPending) // { // stage = Stage.ArgumentsRunning; // } // else if ((codeLine[offset] == ',' || isWhiteSpace || codeLine[offset] == '/') && stage == Stage.ArgumentsRunning) // { // if (boffset < offset) // { // //argument completed // args.Add(codeLine.Substring(boffset, offset - boffset)); // boffset = offset + 1; // } // else // { // //more than one space // boffset++; // } // if (codeLine[offset] == '/') // { // if (commentFirstSymbolSeenOffset == offset - 1) // { // stage = Stage.CommentRunning; // boffset = offset + 1; // } // else if (commentFirstSymbolSeenOffset == -2) // { // commentFirstSymbolSeenOffset = offset; // } // else // { // throw new InvalidSymbolException("/", lineCounter, offset, "comment start token (\"\")"); // } // } // } // offset++; //} //if (stage == Stage.CommentRunning) //{ // i.Comment = codeLine.Substring(boffset); //} //else if (stage == Stage.ArgumentsRunning) //{ // args.Add(codeLine.Substring(boffset, offset - boffset)); //} //i.SourceLine = lineCounter; //yield return i; //lineCounter++; } }
IEnumerable <Instruction> ICompileStep <string, IEnumerable <Instruction> > .Compile(string input, CompileLog log) { return(Lex(input, log)); }
public CompileLog generateStructDefinition(StringBuilder codeBuilder, TbsStruct tbs) { var log = new CompileLog(); if (CsPublicDatastructure) { codeBuilder.Append("public "); } codeBuilder.AppendLine($"class {tbs.Typename} : Tinybuffers.IBufferable {{"); codeBuilder.AppendLine($" public int Size => {tbs.PhysicalSize};"); codeBuilder.AppendLine(""); //Members foreach (var member in tbs.Members) { if (member.IsScalar) { codeBuilder.AppendLine($" public {member.Typename} {member.Identifier}; //@Offset {member.LocalOffset}"); } else { codeBuilder.AppendLine($" public {member.Typename}[] {member.Identifier} = new {member.Typename}[{member.ArraySize}]; //@Offset {member.LocalOffset}"); } } codeBuilder.AppendLine(""); //BuildBuffer Method codeBuilder.AppendLine($"public void BuildBuffer(byte[] buffer, int atOffset = 0) {{"); foreach (var member in tbs.Members) { string additionalCast = (member.Type is TbsEnum) ? "(Byte)" : ""; codeBuilder.AppendLine($" buffer.SetPartialBuffer({additionalCast}this.{member.Identifier}, atOffset + {member.LocalOffset});"); } codeBuilder.AppendLine($"}}"); //UnpackBuffer Method codeBuilder.AppendLine($"public void Unbuffer(in byte[] buffer, int atOffset = 0) {{"); foreach (var member in tbs.Members) { if (member.Type is TbsEnum) { codeBuilder.AppendLine($" Byte _{member.Identifier} = (Byte)this.{member.Identifier};"); codeBuilder.AppendLine($" buffer.ReadInto(ref _{member.Identifier}, atOffset + {member.LocalOffset});"); codeBuilder.AppendLine($" this.{member.Identifier} = ({member.Typename})_{member.Identifier};"); } else { codeBuilder.AppendLine($" buffer.ReadInto(ref this.{member.Identifier}, atOffset + {member.LocalOffset});"); } } codeBuilder.AppendLine($"}}"); //Conviniece Methods codeBuilder.AppendLine($"public {tbs.Typename}(in byte[] buffer) {{"); codeBuilder.AppendLine($" Unbuffer(buffer);"); codeBuilder.AppendLine($"}}"); codeBuilder.AppendLine($"public byte[] BuildBuffer() {{"); codeBuilder.AppendLine($" byte[] outputBuffer = new byte[Size];"); codeBuilder.AppendLine($" BuildBuffer(outputBuffer);"); codeBuilder.AppendLine($" return outputBuffer;"); codeBuilder.AppendLine($"}}"); codeBuilder.AppendLine($"}};\n"); return(log); }
public ITbsType Promote(IList <ITbsType> knownTypes, CompileLog log) { return(this); }
public async Task <Type> CompileBlazor(string code) { CompileLog.Add("Create fileSystem"); var fileSystem = new EmptyRazorProjectFileSystem(); CompileLog.Add("Create engine"); // Microsoft.AspNetCore.Blazor.Build. var engine = RazorProjectEngine.Create(RazorConfiguration.Create(RazorLanguageVersion.Version_3_0, "Blazor", new RazorExtension[0]), fileSystem, b => { // RazorExtensions.Register(b); // b.SetRootNamespace(DefaultRootNamespace); // Turn off checksums, we're testing code generation. // b.Features.Add(new SuppressChecksum()); // if (LineEnding != null) // { // b.Phases.Insert(0, new ForceLineEndingPhase(LineEnding)); // } // Including MVC here so that we can find any issues that arise from mixed MVC + Components. // Microsoft.AspNetCore.Mvc.Razor.Extensions.RazorExtensions.Register(b); // // // Features that use Roslyn are mandatory for components // Microsoft.CodeAnalysis.Razor.CompilerFeatures.Register(b); // // b.Features.Add(new CompilationTagHelperFeature()); // b.Features.Add(new DefaultMetadataReferenceFeature() // { // References = references, // }); }); CompileLog.Add("Create file"); var file = new MemoryRazorProjectItem(code, true, "/App", "/App/App.razor"); CompileLog.Add("File process and GetCSharpDocument"); var doc = engine.Process(file).GetCSharpDocument(); CompileLog.Add("Get GeneratedCode"); var csCode = doc.GeneratedCode; CompileLog.Add("Read Diagnostics"); foreach (var diagnostic in doc.Diagnostics) { CompileLog.Add(diagnostic.ToString()); } if (doc.Diagnostics.Any(i => i.Severity == RazorDiagnosticSeverity.Error)) { return(null); } CompileLog.Add(csCode); CompileLog.Add("Compile assembly"); var assembly = await Compile(csCode); if (assembly != null) { CompileLog.Add("Search Blazor component"); return(assembly.GetExportedTypes().FirstOrDefault(i => i.IsSubclassOf(typeof(ComponentBase)))); } return(null); }