internal static FunctionBodyMetadata Read(BinaryReader reader) { var bodyMetadata = new FunctionBodyMetadata(); var body = new FunctionBody(); bodyMetadata.FunctionBody = body; var bodysize = reader.ReadVarUint32(); var marker = reader.BaseStream.Position; var count = reader.ReadVarUint32(); for (var i = 0; i < count; i++) { body.Locals.Add(LocalEntryMetadata.Read(reader).Local); } body.Ast = reader.ReadBytes((int)(bodysize - reader.BaseStream.Position + marker)); if (reader.BaseStream.Position != marker + bodysize) { throw new NotSupportedException("unexpected read offset"); } return(bodyMetadata); }
public static Container WithReadModelConvenienceFunctions(this FunctionBody functionBody, Type type) { var excludePropertiesFrom = typeof(IReadModel); var properties = type.GetProperties(); if (excludePropertiesFrom != null) { properties = properties.Where(p => !excludePropertiesFrom.GetProperties().Select(pi => pi.Name).Contains(p.Name)).ToArray(); } foreach (var property in properties) { var functionName = string.Format("matching{0}", property.Name.ToPascalCase()); var propertyName = property.Name.ToCamelCase(); var filter = new ObjectLiteral(); filter.Assign(propertyName).WithLiteral(propertyName); functionBody.Property(functionName, p => p.WithFunction(function => function .WithParameters(propertyName) .Body .Scope("self", scope => scope.FunctionCall(f => f.WithName("instanceMatching").WithParameters(new[] { filter }) ) ) ) ); } return(functionBody); }
private FunctionDiff functionDiff(IDocumentSchema schema) { var body = schema.DbObjects.DefinitionForFunction(Function); var expected = new FunctionBody(Function, new string[] { ToDropSignature() }, GenerateFunction()); return(new FunctionDiff(expected, body)); }
public PatternSignature( IReadOnlyList <string> argumentValues, string pathValue, FunctionBody body) : this(argumentValues, pathValue, null, body) { }
public static FunctionBody WithServerMethodsFrom(this FunctionBody body, Type type) { body.Property("server", p => p.WithObjectLiteral(o => { var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (var method in methods) { if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_")) { continue; } o.Assign(method.Name.ToCamelCase()).WithFunction(f => { f.Body.Variant("result", v => { v.WithFunctionCall(fc => fc .WithName("self.invokeServerMethod") .WithParameters("\"" + method.Name + "\"", "arguments") ); }); f.Body.Return(new Literal("result")); }); } })); return(body); }
public override string ToString() { return(new StringBuilder().Append("function(") .Append(string.Join(",", ArgumentNames)).AppendLine(")") .AppendLine(FunctionBody.ToString()).AppendLine("end") .ToString()); }
public void DecompileFunction(StreamWriter output, int functionIndex) { FunctionBody body = WasmModule.FunctionBodies[functionIndex]; FunctionSignature signature = WasmModule.FunctionTypes[WasmModule.Functions[functionIndex]]; int indent = 1; output.WriteLine($"fun_{functionIndex:X8}: # {signature}"); foreach (var instruction in body.Instructions) { indent += instruction.OpCode switch { OpCode.Else => - 1, // temporary OpCode.End => - 1, _ => 0, }; output.WriteLine(new string('\t', indent) + instruction); indent += instruction.OpCode switch { OpCode.Block => 1, OpCode.Loop => 1, OpCode.If => 1, OpCode.Else => 1, _ => 0, }; } // At the end, expect to be 1 indent level lower due to trailing `end` instruction if (indent != 0) { throw new Exception("Function body contains unbalanced branching instructions"); } output.WriteLine(); }
public override void GenerateCode(CodeGeneration.CodeGenerator cg) { var funcinfo = (FunctionInfo)FunctionIDNode.ReferencedThing; funcinfo.Locals = new List <KeyValuePair <string, VariableInfo> >(FunctionScope.GetLocals()); //get it's ILGen var innergenerator = funcinfo.ILMethod.GetILGenerator(); cg.EnterGenerationScope(innergenerator); var paramarr = funcinfo.Parameters.ToArray(); for (int i = 0; i < paramarr.Length; i++) { var parameter = paramarr[i]; //get the variable for the param var paramvarinfo = (VariableInfo)funcinfo.FunctionScope.ResolveVarOrFunction(parameter.Key); //link the var with is Ilvariable paramvarinfo.ILLocalVariable = cg.CreateTigerVar(parameter.Value.GetILType()); //load the argument cg.IlGenerator.Emit(OpCodes.Ldarg, i); cg.IlGenerator.Emit(OpCodes.Stsfld, paramvarinfo.ILLocalVariable); } FunctionBody.GenerateCode(cg); cg.IlGenerator.Emit(OpCodes.Ret); cg.LeaveGenerationScope(); }
public void DecompileFunction(StreamWriter output, int functionIndex) { FunctionBody body = WasmModule.FunctionBodies[functionIndex]; FunctionSignature signature = WasmModule.FunctionTypes[WasmModule.Functions[functionIndex]]; // get IR var context = new IntermediateContext(signature, WasmModule, output); List <IntermediateInstruction> instructions = new IntermediateConverter(WasmModule, body, signature).Convert(); output.Write(signature.ToString($"fun_{functionIndex:X8}")); output.WriteLine(" {"); // write all IR while simulating the stack foreach (IntermediateInstruction instruction in instructions) { HandleInstruction(ref context, instruction); } output.WriteLine("}"); if (context.Indentation != 0) { throw new Exception("Function body has unbalanced indentation"); } if (context.Stack.Count != 0) { throw new Exception($"Unbalanced stack, found {context.Stack.Count} remaining values"); } output.WriteLine(); }
public async Task <LambdaProxyResponse> ExecuteFunction( ApiGatewayProxyRequest request, ILambdaContext context) { var requestBody = FunctionBody.GenerateFromRepspnse(request); var ser = new JsonSerializer(); var htmlWeb = new HtmlWeb(); var document = htmlWeb.Load(requestBody.url); var ogImage = GetMetaValue(document, "og:image"); var title = GetTitle(document); var description = GetMetaValue(document, "description"); var coffeeData = new CoffeeData { Title = title, Description = description, OGImage = ogImage, }; var memStream = new MemoryStream(); ser.Serialize(coffeeData, memStream); var body = memStream.ToString(); memStream.Flush(); return(await Task.FromResult <LambdaProxyResponse>( new LambdaProxyResponse { statusCode = HttpStatusCode.OK, body = body, })); }
private WasmFunctionDefinition MakeInterpreterThunk(int index, FunctionBody body, ILGenerator generator) { var signature = types[index]; // Create an interpreted function definition. var func = new WasmFunctionDefinition(signature, body, module); // Call it. EmitExternalCall( generator, signature.ParameterTypes.Count, func, signature.ParameterTypes .Select <WasmValueType, Func <ILGenerator, Type> >( (p, i) => gen => { gen.Emit(OpCodes.Ldarg, i); return(ValueHelpers.ToClrType(p)); }) .ToArray()); // Return. generator.Emit(OpCodes.Ret); return(func); }
/// <summary> /// Creates a child block from this basic block. /// </summary> /// <returns>A child block.</returns> public BasicBlockBuilder CreateChildBlock() { var result = FunctionBody.AppendBasicBlock(); result.UnwindTarget = UnwindTarget; result.ManualUnwindTarget = ManualUnwindTarget; return(result); }
public override void VisitFunctionBody(FunctionBody node) { // only include as-operators inside function bodies if the position is also within the body if (_position > node.TextStart && _position < node.End) { base.VisitFunctionBody(node); } }
public void do_substitutions() { var func = new FunctionBody(new DbObjectName("public", "mt_upsert_target"), new string[0], theFunctionBody); func.BuildTemplate($"*{DdlRules.SCHEMA}*").ShouldBe("*public*"); func.BuildTemplate($"*{DdlRules.FUNCTION}*").ShouldBe("*mt_upsert_target*"); func.BuildTemplate($"*{DdlRules.SIGNATURE}*").ShouldBe($"*{Function.ParseSignature(func.Body)}*"); }
static void Main(string[] args) { // 失望 Console.InputEncoding = Encoding.Unicode; Console.OutputEncoding = Encoding.Unicode; Console.CursorVisible = true; Console.WriteLine("MyScript 0.9"); VM vm = new VM(); vm.global_table["echo"] = new MyConsole(); MyScriptStdLib.LibString.Register(vm); MyTable module = new MyTable(); StringBuilder sb = new StringBuilder(); for (; ;) { if (sb.Length > 0) { Console.Write('>'); } Console.Write("> "); string line = Console.ReadLine(); if (line == null) { return; } sb.AppendLine(line); var source = sb.ToString(); if (IsComplete(source) == false) { continue; } try { FunctionBody tree = vm.Parse(source); if (tree.block.statements.Count == 1 && tree.block.statements[0] is ExpSyntaxTree) { source = "return " + source; tree = vm.Parse(source); var func = tree.CreateFunction(vm, module); var obj = func.Call(); if (obj is not null) { Console.WriteLine($"{obj}"); } } else { vm.DoString(source, module); } } catch (Exception e) { Console.WriteLine($"Error: {e.Message}"); } sb.Clear(); } }
/// <summary> /// Creates a WebAssembly function definition from the given signature, /// function body and declaring module. /// </summary> /// <param name="Signature">The function's signature.</param> /// <param name="Body">The function's body.</param> /// <param name="Module">The declaring module.</param> public WasmFunctionDefinition( FunctionType Signature, FunctionBody Body, ModuleInstance Module) { this.Signature = Signature; this.body = Body; this.Module = Module; }
/// <summary> /// Creates a WebAssembly function definition from the given signature, /// function body and declaring module. /// </summary> /// <param name="signature">The function's signature.</param> /// <param name="body">The function's body.</param> /// <param name="module">The declaring module.</param> public WasmFunctionDefinition( FunctionType signature, FunctionBody body, ModuleInstance module) { this.Signature = signature; this.body = body; this.Module = module; }
private static void AssertEquivalentLocals(FunctionBody first, FunctionBody second) { var firstCopy = new FunctionBody(first.Locals, first.BodyInstructions); var secondCopy = new FunctionBody(second.Locals, second.BodyInstructions); firstCopy.ExpandLocalEntries(); secondCopy.ExpandLocalEntries(); Assert.IsTrue(Enumerable.SequenceEqual <LocalEntry>(firstCopy.Locals, secondCopy.Locals)); }
private void cleanAllFields() { Param_name.Clear(); funcName.Clear(); possibleParams.Items.Clear(); Param_type.SelectedIndex = -1; FunctionBody.Clear(); ReturnTypeCombo.SelectedIndex = -1; }
private void InitFunctions(WebAssemblyFile file) { logger.Debug("Instanciating Functions."); Dictionary <uint, FuncType> type_info = new Dictionary <uint, FuncType>(); for (uint i = 0; i < (uint)file.type.entries.Length; i++) { type_info[i] = file.type.entries[i]; logger.ConditionalTrace($"Type {i} = {file.type.entries[i]}."); } logger.ConditionalTrace($"file.function.types.Length = {file.function.types.Length} and file.code.bodies.Length = {file.code.bodies.Length}."); if (file.function.types.Length != file.code.bodies.Length) { throw new Exception("Invalid file"); } uint import_count = (uint)functions.Count; logger.ConditionalTrace($"Import count = {import_count}."); for (uint i = 0; i < (uint)file.code.bodies.Length; i++) { uint index = file.function.types[i]; FunctionBody body = file.code.bodies[i]; uint func_indx = i + import_count; logger.ConditionalTrace($"Function {func_indx} = {body}."); functions[func_indx] = new FunctionInstance { module = "this", is_in_module = true, code = body.code, parameters = type_info[index].param_types, return_type = type_info[index].return_type, }; List <WebAssemblyType> locals_unwrapped = new List <WebAssemblyType>(); foreach (var local in body.locals) { locals_unwrapped.AddRange(Enumerable.Repeat(local.type, (int)local.count)); } functions[func_indx].locals = locals_unwrapped.ToArray(); logger.ConditionalTrace($"Final object = {functions[func_indx]}."); } logger.Debug("Done instanciating Functions."); }
public static FunctionBody WithNamespaceMappersFrom(this FunctionBody global, PathToNamespaceMappers namespaceMappers) { foreach (var map in namespaceMappers.Maps) { global.Access("namespaceMapper", a => a.WithFunctionCall( f => f.WithName("addMapping").WithParameters("\"" + map.Key + "\"", "\"" + map.Value + "\""))); } return(global); }
private PatternSignature( IReadOnlyList <string> argumentValues, string pathValue, string bodyText, FunctionBody bodySyntax) { this.ArgumentValues = argumentValues; this.PathValue = pathValue; _bodyText = bodyText; _bodySyntax = bodySyntax; }
public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer) { writer.WriteLine(GenerateFunction()); if (schema.StoreOptions.OwnerName.IsNotEmpty()) { writer.WriteLine(); var expected = new FunctionBody(Function, new string[] { ToDropSignature() }, GenerateFunction()); writer.WriteLine(expected.ToOwnershipCommand(schema.StoreOptions.OwnerName)); } }
protected override void VisitFunctionBody(FunctionBody tree) { _TrySetResult(tree); if (_result != null) { return; } if (tree.param_list != null) { VisitAnySyntaxTree(tree.param_list); } VisitAnySyntaxTree(tree.block); }
public CodeSection(BinaryReader reader) : base(reader) { uint count = LEB128.ReadUInt32(reader); if (count > int.MaxValue) { throw new NotImplementedException($"Count larger than {int.MaxValue} bytes not supported."); } bodies = new FunctionBody[count]; for (uint i = 0; i < count; i++) { bodies[i] = new FunctionBody(reader); } }
public override void ConsolidateNames(ref Dictionary <string, List <Node> > names) { Dictionary <string, List <Node> > localNames = new Dictionary <string, List <Node> >(); Singnature.ConsolidateNames(ref (localNames)); Pattern.ConsolidateNames(ref (localNames)); FunctionBody.ConsolidateNames(ref (localNames)); if (names.ContainsKey(Name)) { throw new Exception(); } List <Node> namelist = new List <Node>(); namelist.Add(this); names.Add(Name, namelist); }
public void write_patch_with_designated_owner() { var func = new FunctionBody(new FunctionName("public", "mt_upsert_target"), new string[0], theFunctionBody); var patch = new SchemaPatch(); var options = new StoreOptions { OwnerName = "bill" }; var diff = new FunctionDiff(func, null); diff.WritePatch(options, patch); patch.UpdateDDL.ShouldContain("ALTER FUNCTION public.mt_upsert_target(jsonb, character varying, uuid, uuid) OWNER TO \"bill\";"); }
public void write_patch_without_designated_owner() { var func = new FunctionBody(new FunctionName("public", "mt_upsert_target"), new string[0], theFunctionBody); var patch = new SchemaPatch(); var options = new StoreOptions { OwnerName = null }; var diff = new FunctionDiff(func, null); diff.WritePatch(options, patch); patch.UpdateDDL.ShouldNotContain("OWNER TO"); }
//only compare return type, attributes and signature public override bool Equals(object other) { var otherNode = other as FunctionDefinitionNode; if (null == otherNode) { return(false); } bool equalSignature = EqualityComparer <ArgumentSignatureNode> .Default.Equals(Signature, otherNode.Signature) && ReturnType.Equals(otherNode.ReturnType) && Attributes.SequenceEqual(otherNode.Attributes); bool equalBody = FunctionBody.Equals(otherNode.FunctionBody); return(equalSignature && equalBody); }
public void CompressLocals() { var rand = new Random(); // Generate one hundred local entries. Create a compressed function body // from them as well as an uncompressed function body. Then check that they // declare the same locals. int testCount = 100; for (int i = 0; i < testCount; i++) { var localEntries = GenerateLocalEntries(rand, rand.Next(50), 10); var compressed = new FunctionBody(localEntries, Enumerable.Empty <Instruction>()); compressed.CompressLocalEntries(); var uncompressed = new FunctionBody(localEntries, Enumerable.Empty <Instruction>()); AssertEquivalentLocals(compressed, uncompressed); } }
/// <summary> /// Initializes a new instance of <see cref="Function"/> /// </summary> /// <param name="parameters">Optional parameters for the function</param> public Function(params string[] parameters) { Parameters = parameters; Body = new FunctionBody(); }