protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if (Expression == null) throw new PrexoniteException("Expression must be assigned."); Expression.EmitValueCode(target); target.Emit(Position,OpCode.@throw); if (stackSemantics == StackSemantics.Value) target.Emit(Position,OpCode.ldc_null); }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if(stackSemantics == StackSemantics.Effect) return; Subject.EmitValueCode(target); var constType = Type as AstConstantTypeExpression; if (constType != null) target.Emit(Position,OpCode.cast_const, constType.TypeExpression); else { Type.EmitValueCode(target); target.Emit(Position,OpCode.cast_arg); } }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if (stackSemantics == StackSemantics.Effect) return; PFunction targetFunction; MetaEntry sharedNamesEntry; if (target.Loader.ParentApplication.TryGetFunction(_implementation.Id, _implementation.ModuleName, out targetFunction) && (!targetFunction.Meta.TryGetValue(PFunction.SharedNamesKey, out sharedNamesEntry) || !sharedNamesEntry.IsList || sharedNamesEntry.List.Length == 0)) target.Emit(Position,OpCode.ldr_func, _implementation.Id, target.ToInternalModule(_implementation.ModuleName)); else target.Emit(Position,OpCode.newclo, _implementation.Id, target.ToInternalModule(_implementation.ModuleName)); }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if (Elements.Count == 0) { target.Emit(Position,OpCode.newobj, 0, "Hash"); } else { foreach (var element in Elements) { if (element is AstConstant) throw new PrexoniteException( String.Concat( "Hashes are built from key-value pairs, not constants like ", element, ". [File: ", File, ", Line: ", Line, "]")); element.EmitCode(target,stackSemantics); } if(stackSemantics == StackSemantics.Effect) return; target.EmitStaticGetCall(Position, Elements.Count, "Hash", "Create", false); } }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if(stackSemantics == StackSemantics.Effect) return; target.Emit(Position,OpCode.exc); }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { //Jumps need special treatment for label resolution if (Instruction.Arguments == -1) { switch (Instruction.OpCode) { case OpCode.jump: target.EmitJump(Position, Instruction.Id); break; case OpCode.jump_t: target.EmitJumpIfTrue(Position, Instruction.Id); break; case OpCode.jump_f: target.EmitJumpIfFalse(Position, Instruction.Id); break; case OpCode.leave: target.EmitLeave(Position, Instruction.Id); break; default: goto emitNormally; } } else goto emitNormally; return; emitNormally: target.Emit(Position, Instruction); }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if(stackSemantics == StackSemantics.Effect) return; target.Emit(Position,OpCode.ldr_type, TypeExpression); }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if(stackSemantics == StackSemantics.Value) throw new NotSupportedException("Return nodes cannot be used with value stack semantics. (They don't produce any values)"); var warned = false; if (target.Function.Meta[Coroutine.IsCoroutineKey].Switch) _warnInCoroutines(target, ref warned); if (Expression != null) { _OptimizeNode(target, ref Expression); if (ReturnVariant == ReturnVariant.Exit) { _emitTailCallExit(target); return; } } switch (ReturnVariant) { case ReturnVariant.Exit: target.Emit(Position,OpCode.ret_exit); break; case ReturnVariant.Set: if (Expression == null) throw new PrexoniteException("Return assignment requires an expression."); Expression.EmitValueCode(target); target.Emit(Position,OpCode.ret_set); break; case ReturnVariant.Continue: if (Expression != null) { Expression.EmitValueCode(target); target.Emit(Position,OpCode.ret_set); _warnInCoroutines(target, ref warned); } target.Emit(Position,OpCode.ret_continue); break; case ReturnVariant.Break: target.Emit(Position,OpCode.ret_break); break; } }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if(stackSemantics == StackSemantics.Effect) return; if (Expression == null) throw new PrexoniteException("CreateCoroutine node requires an Expression."); Expression.EmitValueCode(target); foreach (var argument in _arguments) argument.EmitValueCode(target); target.Emit(Position,OpCode.newcor, _arguments.Count); }
private void _emitOrdinaryValueReturn(CompilerTarget target) { Expression.EmitValueCode(target); target.Emit(Position, OpCode.ret_value); }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if (stackSemantics == StackSemantics.Effect) return; _subject.EmitValueCode(target); var constType = _type as AstConstantTypeExpression; if (constType != null) { PType T = null; try { T = target.Loader.ConstructPType(constType.TypeExpression); } catch (PrexoniteException) { //ignore failures here } if ((object) T != null && T == PType.Null) target.Emit(Position,OpCode.check_null); else target.Emit(Position,OpCode.check_const, constType.TypeExpression); } else { _type.EmitValueCode(target); target.Emit(Position,OpCode.check_arg); } }
private void _emitIncrementDecrementCode(CompilerTarget target, StackSemantics value) { var symbolCall = _operand as AstIndirectCall; var symbol = symbolCall == null ? null : symbolCall.Subject as AstReference; EntityRef.Variable variableRef = null; var isVariable = symbol != null && symbol.Entity.TryGetVariable(out variableRef); var isPre = _operator == UnaryOperator.PreDecrement || _operator == UnaryOperator.PreIncrement; switch (_operator) { case UnaryOperator.PreIncrement: case UnaryOperator.PostIncrement: case UnaryOperator.PreDecrement: case UnaryOperator.PostDecrement: var isIncrement = _operator == UnaryOperator.PostIncrement || _operator == UnaryOperator.PreIncrement; if (isVariable) { Debug.Assert(variableRef != null); EntityRef.Variable.Local localRef; Action loadVar; Action perform; EntityRef.Variable.Global globalRef; // First setup the two actions if (variableRef.TryGetLocalVariable(out localRef)) { loadVar = () => target.EmitLoadLocal(Position, localRef.Id); perform = () => target.Emit(Position, isIncrement ? OpCode.incloc : OpCode.decloc, localRef.Id); } else if(variableRef.TryGetGlobalVariable(out globalRef)) { loadVar = () => target.EmitLoadGlobal(Position, globalRef.Id, globalRef.ModuleName); perform = () => target.Emit(Position, isIncrement ? OpCode.incglob : OpCode.decglob, globalRef.Id, globalRef.ModuleName); } else { throw new InvalidOperationException("Found variable entity that is neither a global nor a local variable."); } // Then decide in what order to apply them. if (!isPre && value == StackSemantics.Value) { loadVar(); } perform(); if (isPre && value == StackSemantics.Value) { loadVar(); } } else throw new PrexoniteException( "Node of type " + _operand.GetType() + " does not support increment/decrement operators."); break; // ReSharper disable RedundantCaseLabel case UnaryOperator.UnaryNegation: case UnaryOperator.LogicalNot: case UnaryOperator.OnesComplement: // ReSharper restore RedundantCaseLabel // ReSharper disable RedundantEmptyDefaultSwitchBranch default: break; //No effect // ReSharper restore RedundantEmptyDefaultSwitchBranch } }
public void DoEmitPartialApplicationCode(CompilerTarget target) { AstPlaceholder.DeterminePlaceholderIndices(Expressions.OfType<AstPlaceholder>()); var count = Expressions.Count; if (count == 0) { this.ConstFunc(null).EmitValueCode(target); return; } //only the very last condition may be a placeholder for (var i = 0; i < count; i++) { var value = Expressions[i]; var isPlaceholder = value.IsPlaceholder(); if (i == count - 1) { if (!isPlaceholder) { //there is no placeholder at all, wrap expression in const Debug.Assert(Expressions.All(e => !e.IsPlaceholder())); DoEmitCode(target,StackSemantics.Value); target.EmitCommandCall(Position, 1, Const.Alias); return; } } else { if (isPlaceholder) { _reportInvalidPlaceholders(target); return; } } } if (count == 0) { this.ConstFunc().EmitValueCode(target); } else if (count == 1) { Debug.Assert(Expressions[0].IsPlaceholder(), "Singleton ??-chain expected to consist of placeholder."); var placeholder = (AstPlaceholder) Expressions[0]; placeholder.IdFunc().EmitValueCode(target); } else { Debug.Assert(Expressions[count - 1].IsPlaceholder(), "Last expression in ??-chain expected to be placeholder."); var placeholder = (AstPlaceholder) Expressions[count - 1]; var prefix = new AstCoalescence(File, Line, Column); prefix.Expressions.AddRange(Expressions.Take(count - 1)); //check for null (keep a copy of prefix on stack) var constLabel = _generateEndLabel(); var endLabel = _generateEndLabel(); prefix._emitCode(target, constLabel, StackSemantics.Value); target.EmitDuplicate(Position); target.Emit(Position,OpCode.check_null); target.EmitJumpIfFalse(Position, constLabel); //prefix is null, identity function target.EmitPop(Position); placeholder.IdFunc().EmitValueCode(target); target.EmitJump(Position, endLabel); //prefix is not null, const function target.EmitLabel(Position, constLabel); target.EmitCommandCall(Position, 1, Const.Alias); target.EmitLabel(Position, endLabel); } }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if(stackSemantics == StackSemantics.Value) throw new NotSupportedException("Try-catch-finally blocks cannot be used with value stack semantics (They don't produce values)"); var prefix = "try\\" + Guid.NewGuid().ToString("N") + "\\"; var beginTryLabel = prefix + "beginTry"; var beginFinallyLabel = prefix + "beginFinally"; var beginCatchLabel = prefix + "beginCatch"; var endTry = prefix + "endTry"; if (TryBlock.IsEmpty) if (FinallyBlock.IsEmpty) return; else { //The finally block is not protected // A trycatchfinally with just a finally block is equivalent to the contents of the finally block // " try {} finally { $code } " => " $code " FinallyBlock.EmitEffectCode(target); return; } //Emit try block target.EmitLabel(Position, beginTryLabel); target.Emit(Position,OpCode.@try); TryBlock.EmitEffectCode(target); //Emit finally block target.EmitLabel(FinallyBlock.Position, beginFinallyLabel); var beforeEmit = target.Code.Count; FinallyBlock.EmitEffectCode(target); if (FinallyBlock.Count > 0 && target.Code.Count == beforeEmit) target.Emit(FinallyBlock.Position, OpCode.nop); target.EmitLeave(FinallyBlock.Position, endTry); //Emit catch block target.EmitLabel(CatchBlock.Position, beginCatchLabel); var usesException = ExceptionVar != null; var justRethrow = CatchBlock.IsEmpty && !usesException; if (usesException) { //Assign exception ExceptionVar = _GetOptimizedNode(target, ExceptionVar) as AstGetSet ?? ExceptionVar; ExceptionVar.Arguments.Add(new AstGetException(File, Line, Column)); ExceptionVar.Call = PCall.Set; ExceptionVar.EmitEffectCode(target); } if (!justRethrow) { //Exception handled CatchBlock.EmitEffectCode(target); } else { //Exception not handled => rethrow. // * Rethrow is implemented in the runtime * //AstThrow th = new AstThrow(File, Line, Column); //th.Expression = new AstGetException(File, Line, Column); //th.EmitCode(target); } target.EmitLabel(Position, endTry); target.Emit(Position,OpCode.nop); var block = new TryCatchFinallyBlock( _getAddress(target, beginTryLabel), _getAddress(target, endTry)) { BeginFinally = (!FinallyBlock.IsEmpty ? _getAddress(target, beginFinallyLabel) : -1), BeginCatch = (!justRethrow ? _getAddress(target, beginCatchLabel) : -1), UsesException = usesException }; //Register try-catch-finally block target.Function.Meta.AddTo(TryCatchFinallyBlock.MetaKey, block); target.Function.InvalidateTryCatchFinallyBlocks(); }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { foreach (var expr in Arguments) expr.EmitCode(target,stackSemantics); if(stackSemantics == StackSemantics.Value) target.Emit(Position,OpCode.newtype, Arguments.Count, TypeId); }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { var constType = _typeExpr as AstConstantTypeExpression; if (constType != null) { foreach (var arg in _arguments) arg.EmitValueCode(target); target.Emit(Position,OpCode.newobj, _arguments.Count, constType.TypeExpression); if(stackSemantics == StackSemantics.Effect) target.Emit(Position,Instruction.CreatePop()); } else { //Load type and call construct on it _typeExpr.EmitValueCode(target); foreach (var arg in _arguments) arg.EmitValueCode(target); var justEffect = stackSemantics == StackSemantics.Effect; target.EmitGetCall(Position, _arguments.Count, PType.ConstructFromStackId, justEffect); } }
protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if(stackSemantics == StackSemantics.Value) throw new NotSupportedException("Foreach loops don't produce values and can thus not be emitted with value semantics."); if (!IsInitialized) throw new PrexoniteException("AstForeachLoop requires List and Element to be set."); //Optimize expression _OptimizeNode(target, ref List); //Create the enumerator variable var enumVar = Block.CreateLabel("enumerator"); target.Function.Variables.Add(enumVar); //Create the element assignment statement var element = Element.GetCopy(); AstExpr optElem; if (element.TryOptimize(target, out optElem)) { element = optElem as AstGetSet; if (element == null) { target.Loader.ReportMessage(Message.Error(Resources.AstForeachLoop_DoEmitCode_ElementTooComplicated,Position,MessageClasses.ForeachElementTooComplicated)); return; } } var ldEnumVar = target.Factory.Call(Position, EntityRef.Variable.Local.Create(enumVar)); var getCurrent = new AstGetSetMemberAccess(File, Line, Column, ldEnumVar, "Current"); element.Arguments.Add(getCurrent); element.Call = PCall.Set; //Actual Code Generation var moveNextAddr = -1; var getCurrentAddr = -1; var disposeAddr = -1; //Get the enumerator target.BeginBlock(Block); List.EmitValueCode(target); target.EmitGetCall(List.Position, 0, "GetEnumerator"); var castAddr = target.Code.Count; target.Emit(List.Position, OpCode.cast_const, "Object(\"System.Collections.IEnumerator\")"); target.EmitStoreLocal(List.Position, enumVar); //check whether an enhanced CIL implementation is possible bool emitHint; if (element.DefaultAdditionalArguments + element.Arguments.Count > 1) //has additional arguments emitHint = false; else emitHint = true; var @try = new AstTryCatchFinally(Position, Block); @try.TryBlock = new AstActionBlock ( Position, @try, delegate { target.EmitJump(Position, Block.ContinueLabel); //Assignment (begin) target.EmitLabel(Position, Block.BeginLabel); getCurrentAddr = target.Code.Count; element.EmitEffectCode(target); //Code block Block.EmitEffectCode(target); //Condition (continue) target.EmitLabel(Position, Block.ContinueLabel); moveNextAddr = target.Code.Count; target.EmitLoadLocal(List.Position, enumVar); target.EmitGetCall(List.Position, 0, "MoveNext"); target.EmitJumpIfTrue(Position, Block.BeginLabel); //Break target.EmitLabel(Position, Block.BreakLabel); }); @try.FinallyBlock = new AstActionBlock ( Position, @try, delegate { disposeAddr = target.Code.Count; target.EmitLoadLocal(List.Position, enumVar); target.EmitCommandCall(List.Position, 1, Engine.DisposeAlias, true); }); @try.EmitEffectCode(target); target.EndBlock(); if (getCurrentAddr < 0 || moveNextAddr < 0 || disposeAddr < 0) throw new PrexoniteException( "Could not capture addresses within foreach construct for CIL compiler hint."); else if (emitHint) { var hint = new ForeachHint(enumVar, castAddr, getCurrentAddr, moveNextAddr, disposeAddr); Cil.Compiler.AddCilHint(target, hint); Action<int, int> mkHook = (index, original) => { AddressChangeHook hook = null; hook = new AddressChangeHook( original, newAddr => { foreach ( var hintEntry in target.Meta[Loader.CilHintsKey].List) { var entry = hintEntry.List; if (entry[0] == ForeachHint.Key && entry[index].Text == original.ToString(CultureInfo.InvariantCulture)) { entry[index] = newAddr.ToString(CultureInfo.InvariantCulture); // AddressChangeHook.ctor can be trusted not to call the closure. // ReSharper disable PossibleNullReferenceException // ReSharper disable AccessToModifiedClosure hook.InstructionIndex = newAddr; // ReSharper restore AccessToModifiedClosure // ReSharper restore PossibleNullReferenceException original = newAddr; } } }); target.AddressChangeHooks.Add(hook); }; mkHook(ForeachHint.CastAddressIndex + 1, castAddr); mkHook(ForeachHint.GetCurrentAddressIndex + 1, getCurrentAddr); mkHook(ForeachHint.MoveNextAddressIndex + 1, moveNextAddr); mkHook(ForeachHint.DisposeAddressIndex + 1, disposeAddr); } // else nothing }
private void _emitCode(CompilerTarget target, string endLabel, StackSemantics stackSemantics) { for (var i = 0; i < _expressions.Count; i++) { var expr = _expressions[i]; // Value semantics: duplicate of previous, rejected value needs to be popped // Effect semantics: no duplicates were created in the first place if (i > 0 && stackSemantics == StackSemantics.Value) target.EmitPop(Position); //For value semantics, we always generate a value //For effect semantics, we only need the intermediate expressions to create a value StackSemantics needValue; if (stackSemantics == StackSemantics.Value || i < _expressions.Count - 1) needValue = StackSemantics.Value; else needValue = StackSemantics.Effect; expr.EmitCode(target, needValue); //The last element doesn't need special handling, control just // falls into the surrounding code with the correct value on top of the stack if (i + 1 >= _expressions.Count) continue; if(stackSemantics == StackSemantics.Value) target.EmitDuplicate(Position); target.Emit(Position,OpCode.check_null); target.EmitJumpIfFalse(Position, endLabel); } }