public static Expression evaluate(BlockExpression formula) { var body = new Block(formula.LexicalInfo); for (int i = 0; i < formula.Body.Statements.Count; ++i) { var statement = formula.Body.Statements[i]; if (statement is ExpressionStatement && i == formula.Body.Statements.Count - 1) { var last = (ExpressionStatement)statement; body.Statements.Add(new ReturnStatement(last.Expression)); } else body.Statements.Add(formula.Body.Statements[i]); } var result = new BlockExpression(body); result.Parameters.Add(new ParameterDeclaration("this", CompilerContext.Current.CodeBuilder .CreateTypeReference(EvaluationContext.CurrentContext.GetType()))); result.ReturnType = CompilerContext.Current.CodeBuilder .CreateTypeReference(typeof(bool)); return new MethodInvocationExpression( new ReferenceExpression("SetEvaluationFunction"), result); }
//this method returns -1 if it doesn't detect unreachable code //else it returns the index of the first unreachable in block.Statements private int DetectUnreachableCode(Block block, Statement limit) { var unreachable = false; var idx = 0; foreach (var stmt in block.Statements) { //HACK: __switch__ builtin function is hard to detect/handle // within this context, let's ignore whatever is after __switch__ if (IsSwitchBuiltin(stmt)) return -1;//ignore followings if (unreachable && stmt is LabelStatement) return -1; if (stmt == limit) unreachable = true; else if (unreachable) { if (!stmt.IsSynthetic) Warnings.Add(CompilerWarningFactory.UnreachableCodeDetected(stmt)); return idx; } idx++; } return -1; }
B.Block ConvertBlock(BlockStatement block) { B.Block b = new B.Block(GetLexicalInfo(block)); b.EndSourceLocation = GetLocation(block.EndLocation); ConvertStatements(block.Children, b); return(b); }
public BooInferredReturnType(Block block, IClass context, bool useLastStatementIfNoReturnStatement) { if (block == null) throw new ArgumentNullException("block"); this.useLastStatementIfNoReturnStatement = useLastStatementIfNoReturnStatement; this.block = block; this.context = context; }
public static Statement MapStatementModifier(StatementModifier modifier, out Block block) { switch (modifier.Type) { case StatementModifierType.If: { IfStatement stmt = new IfStatement(modifier.LexicalInfo); stmt.Condition = modifier.Condition; stmt.TrueBlock = new Block(); block = stmt.TrueBlock; return stmt; } case StatementModifierType.Unless: { UnlessStatement stmt = new UnlessStatement(modifier.LexicalInfo); stmt.Condition = modifier.Condition; block = stmt.Block; return stmt; } case StatementModifierType.While: { WhileStatement stmt = new WhileStatement(modifier.LexicalInfo); stmt.Condition = modifier.Condition; block = stmt.Block; return stmt; } } throw CompilerErrorFactory.NotImplemented(modifier, string.Format("modifier {0} supported", modifier.Type)); }
B.Block ConvertBlock(BlockStatement block) { B.Block b = new B.Block(GetLexicalInfo(block)); b.EndSourceLocation = GetLocation(block.EndLocation); ConvertStatements(block.Children, b); return b; }
protected override Statement ExpandImpl(MacroStatement macro){ var result = new Block(); foreach (Statement st in macro.Body.Statements){ var decl = st as DeclarationStatement; var refer = st as ExpressionStatement; if(null==decl){ var ex = refer.Expression; if (ex is MethodInvocationExpression){ decl = new DeclarationStatement( new Declaration(((MethodInvocationExpression) refer.Expression).Target.ToCodeString(), null), null); } if(ex is BinaryExpression){ var b = ex as BinaryExpression; decl = new DeclarationStatement( new Declaration(b.Left.ToCodeString(),null),b.Right ); } } var bin = new BinaryExpression(BinaryOperatorType.Assign, new TryCastExpression(new ReferenceExpression(decl.Declaration.Name), decl.Declaration.Type), decl.Initializer); var def = new MacroStatement("definebrailproperty"); def.Arguments.Add(bin); result.Add(def); } return result; }
public IfStatement(LexicalInfo token, Expression condition, Block trueBlock, Block falseBlock) : base(token) { this.Condition = condition; this.TrueBlock = trueBlock; this.FalseBlock = falseBlock; }
void ConvertStatements(IEnumerable statements, B.Block b) { foreach (Statement n in statements) { AddToBlock(n, b); } }
//this method returns -1 if it doesn't detect unreachable code //else it returns the index of the first unreachable in block.Statements private int DetectUnreachableCode(Block block, Statement limit) { bool unreachable = false; int idx = 0; foreach (Statement stmt in block.Statements) { //HACK: __switch__ builtin function is hard to detect/handle // within this context, let's ignore whatever is after __switch__ ExpressionStatement est = stmt as ExpressionStatement; if (null != est) { MethodInvocationExpression mie = est.Expression as MethodInvocationExpression; if (null != mie && TypeSystem.BuiltinFunction.Switch == mie.Target.Entity) return -1;//ignore followings } if (unreachable && stmt is LabelStatement) return -1; if (stmt == limit) { unreachable = true; } else if (unreachable) { Warnings.Add( CompilerWarningFactory.UnreachableCodeDetected(stmt) ); return idx; } idx++; } return -1; }
B.Statement GetLastStatement(B.Block block) { if (block == null || block.Statements.Count == 0) { return(null); } return(block.Statements[block.Statements.Count - 1]); }
override public void OnBlock(Block block) { var currentChecked = _checked; _checked = AstAnnotations.IsChecked(block, Parameters.Checked); Visit(block.Statements); _checked = currentChecked; }
public void ForCoverage() { var block = new Block(); var statement = new ReturnStatement(new StringLiteralExpression("literal")); block.Statements.Add(statement); var visitor = new ReturnValueVisitor(); bool found = visitor.Found; visitor.OnReturnStatement(statement); }
public static bool IsNewBlock(MethodInvocationExpression method, out Block block) { block = null; if (method.Arguments.Count > 0 && method.Arguments[method.Arguments.Count - 1] is BlockExpression) { block = ((BlockExpression)method.Arguments[method.Arguments.Count - 1]).Body; } return block != null; }
public Statement Expand(IEnumerable<Node> generator) { Block resultingBlock = new Block(); foreach (Node node in generator) { //'yield' (ie. implicit 'yield null') means 'yield `macro`.Body' Node generatedNode = node ?? _node.Body; if (null == generatedNode) continue; TypeMember member = generatedNode as TypeMember; if (null != member) { ExpandTypeMember(member, resultingBlock); continue; } Block block = generatedNode as Block; if (null != block) { resultingBlock.Add(block); continue; } Statement statement = generatedNode as Statement; if (null != statement) { resultingBlock.Add(statement); continue; } Expression expression = generatedNode as Expression; if (null != expression) { resultingBlock.Add(expression); continue; } Import import = generatedNode as Import; if (null != import) { ExpandImport(import); continue; } throw new CompilerError(_node, "Unsupported expansion: " + generatedNode.ToCodeString()); } return resultingBlock.IsEmpty ? null : resultingBlock.Simplify(); }
B.Block ConvertBlock(List <Statement> statements) { if (statements.Count == 1) { if (statements[0] is BlockStatement) { return(ConvertBlock(statements[0] as BlockStatement)); } } B.Block b = new B.Block(); ConvertStatements(statements, b); return(b); }
public static Statement when(Expression expression) { var body = new Block(expression.LexicalInfo); body.Add(new ReturnStatement(expression)); var result = new BlockExpression(body); result.Parameters.Add( new ParameterDeclaration("order", CurrentContext.CodeBuilder.CreateTypeReference(typeof(Order)))); result.Parameters.Add( new ParameterDeclaration("customer", CurrentContext.CodeBuilder.CreateTypeReference(typeof(Customer)))); return new ReturnStatement(result); }
public static Block WriteOutCells(IEnumerable<CellDefinition> cells, bool header){ string tagname = header ? "th" : "td"; var onitem = new Block(); foreach (CellDefinition cell in cells){ var opentag = new ExpressionInterpolationExpression(); ExpressionInterpolationExpression attrs = getAttributes(cell.Attributes); opentag.append("<" + tagname).append(attrs).append(">"); onitem.add(opentag.writeOut()); onitem.add(cell.Value.brailOutResolve()); onitem.Add(("</" + tagname + ">").toLiteral().writeOut()); } return onitem; }
protected override Statement ExpandImpl(MacroStatement macro){ var result = new Block(); Expression outvar = macro.Arguments.Count == 0 ? new ReferenceExpression("_out") : macro.Arguments[0]; var tryer = new TryStatement(); var protectblock = new Block(); protectblock.add(new MethodInvocationExpression(new ReferenceExpression("_catchoutput"))); protectblock.add(macro.Body); tryer.ProtectedBlock = protectblock; tryer.EnsureBlock = new Block().add(outvar.assign(new MethodInvocationExpression(new ReferenceExpression("_endcatchoutput")))); result.Add(outvar.assign("")); result.Add(tryer); return result; }
public override Statement Expand(MacroStatement macro) { if (macro.Arguments.Count == 0) throw new MonoRailException("Section must be called with a name"); MacroStatement component = GetParentComponent(macro); componentContextName = ComponentNaming.GetComponentContextName(component); componentVariableName = ComponentNaming.GetComponentNameFor(component); string sectionName = macro.Arguments[0].ToString(); Block block = new Block(); //if (!Component.SupportsSection(section.Name)) // throw new ViewComponentException( String.Format("The section '{0}' is not supported by the ViewComponent '{1}'", section.Name, ComponentName)); MethodInvocationExpression supportsSection = new MethodInvocationExpression( AstUtil.CreateReferenceExpression(componentVariableName + ".SupportsSection"), new StringLiteralExpression(sectionName)); //create the new exception RaiseStatement raiseSectionNotSupportted = new RaiseStatement( new MethodInvocationExpression( AstUtil.CreateReferenceExpression(typeof(ViewComponentException).FullName), new StringLiteralExpression( String.Format("The section '{0}' is not supported by the ViewComponent '{1}'", sectionName, component.Arguments[0].ToString()) ) )); Block trueBlock = new Block(); trueBlock.Add(raiseSectionNotSupportted); IfStatement ifSectionNotSupported = new IfStatement(new UnaryExpression(UnaryOperatorType.LogicalNot, supportsSection), trueBlock, null); block.Add(ifSectionNotSupported); //componentContext.RegisterSection(sectionName); MethodInvocationExpression mie = new MethodInvocationExpression( new MemberReferenceExpression(new ReferenceExpression(componentContextName), "RegisterSection"), new StringLiteralExpression(sectionName), CodeBuilderHelper.CreateCallableFromMacroBody(CodeBuilder, macro)); block.Add(mie); IDictionary sections = (IDictionary) component["sections"]; if (sections == null) { component["sections"] = sections = new Hashtable(); } sections.Add(sectionName, block); return null; }
public Statement Reify(Statement node) { var result = node; if (node is MacroStatement) { // macro statements are replaced // so we need to wrap it in a Block // otherwise we would lose the result var parentNode = node.ParentNode; result = new Block(node); parentNode.Replace(node, result); } ApplyAttributesAndExpandMacros(); return result; }
protected override Statement ExpandImpl(MacroStatement macro){ if (macro.Arguments.Count == 0) { Context.Errors.Add(new CompilerError(macro.LexicalInfo, "call macro requires at least one reference or string attribute for action name")); } var basis = new ReferenceExpression("Html"); var method = new MemberReferenceExpression(basis, "RenderAction"); var call = new MethodInvocationExpression(method); int i = 0; var result = new Block(); foreach (Expression argument in macro.Arguments){ i++; Expression exp = argument; if (!(exp is HashLiteralExpression)){ //action and contrller parameters if (!(exp is NullLiteralExpression)){ exp = new StringLiteralExpression(argument.ToCodeString()); } call.Arguments.Add(exp); } else{ string name = "__rd"; result.Add( new DeclarationStatement( new Declaration(name, null), new MethodInvocationExpression(AstUtil.CreateReferenceExpression("RouteValueDictionary")) ) ); var dict = argument as HashLiteralExpression; foreach (ExpressionPair item in dict.Items){ result.Add( new MethodInvocationExpression( AstUtil.CreateReferenceExpression(name + ".Add"), item.First, item.Second ) ); } if (i == 2){ call.Arguments.Add(new NullLiteralExpression()); } call.Arguments.Add(AstUtil.CreateReferenceExpression(name)); } } result.Add(call); return result; }
public override void OnMacroStatement(MacroStatement node) { if (node.Name == "includeast") { var expander = new IncludeastMacro(); var statements = expander.ExpandGenerator(node); var block = new Block(); foreach (var statement in statements){ block.Statements.Add((Statement)statement); } node.ReplaceBy(block); } else{ base.OnMacroStatement(node); } }
private static Expression[] GetExpressionsFromBlock(Block block) { List<Expression> expressions = new List<Expression>(block.Statements.Count); foreach (Statement statement in block.Statements) { if (statement is ExpressionStatement) expressions.Add((statement as ExpressionStatement).Expression); else if (statement is MacroStatement) { MacroStatement macroStatement = statement as MacroStatement; if (macroStatement.Arguments.Count == 0 && macroStatement.Body.IsEmpty) { // Assume it is a reference expression ReferenceExpression refExp = new ReferenceExpression(macroStatement.LexicalInfo); refExp.Name = macroStatement.Name; expressions.Add(refExp); } else { // Assume it is a MethodInvocation MethodInvocationExpression mie = new MethodInvocationExpression(macroStatement.LexicalInfo); mie.Target = new ReferenceExpression(macroStatement.LexicalInfo, macroStatement.Name); mie.Arguments = macroStatement.Arguments; if (macroStatement.Body.IsEmpty == false) { // If the macro statement has a block, // transform it into a block expression and pass that as the last argument // to the method invocation. BlockExpression be = new BlockExpression(macroStatement.LexicalInfo); be.Body = macroStatement.Body.CloneNode(); mie.Arguments.Add(be); } expressions.Add(mie); } } else { throw new InvalidOperationException(string.Format("Can not transform block with {0} into argument.", statement.GetType())); } } return expressions.ToArray(); }
public override Statement Expand(MacroStatement macro) { var codeBlock = new Block(); // Castle.MonoRail.Views.Brail.DslProvider(BrailBase) var newDslWrapper = new MethodInvocationExpression { Target = AstUtil.CreateReferenceExpression("Castle.MonoRail.Views.Brail.DslProvider") }; newDslWrapper.Arguments.Add(new SelfLiteralExpression()); // dsl = Castle.MonoRail.Views.Brail.DslPRovider(BrailBase) var dslReference = AstUtil.CreateReferenceExpression("dsl"); codeBlock.Add(new BinaryExpression(BinaryOperatorType.Assign, dslReference, newDslWrapper)); if (macro.Arguments.Count == 1) { var language = LookupLanguageExtension(macro.Arguments[0].ToString()); // LanguageExtension(OutputStream) var newLanguage = new MethodInvocationExpression { Target = AstUtil.CreateReferenceExpression(language) }; newLanguage.Arguments.Add(AstUtil.CreateReferenceExpression("OutputStream")); var registerLanguage = new MethodInvocationExpression { Target = AstUtil.CreateReferenceExpression("dsl.Register") }; registerLanguage.Arguments.Add(newLanguage); // dsl.Register(LanguageExtension(OutputStream)) codeBlock.Add(registerLanguage); } // rewrite the remaining code to invoke methods on // the dsl reference var macroBlock = macro.Body; (new NameExpander(dslReference)).Visit(macroBlock); codeBlock.Add(macroBlock); // dsl.Flush(); codeBlock.Add(new MethodInvocationExpression(AstUtil.CreateReferenceExpression("dsl.Flush"))); return codeBlock; }
private Block extractMainItemBlock(MacroStatement macro, Func<MacroStatement, Block> extract, MacroStatement onitem_macro, Expression item, string prefix, string suffix){ Block onitem = null; if (onitem_macro == macro && (macro.Body == null || macro.Body.IsEmpty)){ Expression outer = item; if (prefix != "" || suffix != ""){ outer = new ExpressionInterpolationExpression() .append(prefix) .append(item) .append(suffix); } onitem = new Block().add(BrailBuildingHelper.WriteOut(outer)); } else{ onitem = extract(onitem_macro); } return onitem; }
public override Statement Expand(MacroStatement macro){ var result = new Block(); result.Statements.Add( new ExpressionStatement( new MethodInvocationExpression( AstUtil.CreateReferenceExpression("System.Console.WriteLine"), new StringLiteralExpression("Press any key...") ) ) ); result.Statements.Add( new ExpressionStatement( new MethodInvocationExpression( AstUtil.CreateReferenceExpression("System.Console.ReadKey") ) ) ); return result; }
public Statement Reify(Statement node) { var result = node; if (ShouldReify()) { if (node is MacroStatement) { // macro statements are replaced // so we need to wrap it in a Block // otherwise we would lose the result var parentNode = node.ParentNode; result = new Block(node); parentNode.Replace(node, result); } RunExpansionIterations(); } return result; }
void AddToBlock(Statement n, B.Block b) { object result = ConvertStatementInternal(n); if (result is ArrayList) { foreach (B.Statement stmt in (ArrayList)result) { b.Add(stmt); } } else { B.Statement stmt = (B.Statement)result; if (stmt != null) { b.Add(stmt); } } }
private void generateElement(XElement element, Block block) { var m = new MacroStatement(element.Name.LocalName); block.Add(m); //if ((!string.IsNullOrWhiteSpace(element.Value))) { // generateText(element.Value, m.Body); //} IList<string> skips = new List<string>(); skips.Add("_line"); skips.Add("_file"); if (element.Attribute("id") != null) { skips.Add("id"); if(element.attr("code")==element.attr("id")) { skips.Add("code"); } m.Arguments.Add(getSimplified(element.attr("id"))); if (element.Attribute("name") != null) { m.Arguments.Add(getSimplified(element.attr("name"))); skips.Add("name"); } } foreach (var attribute in element.Attributes()) { if (!skips.Contains(attribute.Name.LocalName)) { generateAttribute(attribute, m.Body); } } foreach (var e in element.Nodes()) { if (e is XElement) { generateElement((XElement)e, m.Body); } else if(e is XText){ generateText(((XText)e).Value,m.Body); } } }
public static void RenameLocals(Block block, StringComparer nameComparer) { FindVariableDeclarationsVisitor fvdv = new FindVariableDeclarationsVisitor(); block.Accept(fvdv); List<DeclarationStatement> list = new List<DeclarationStatement>(); foreach (DeclarationStatement decl in fvdv.Declarations) { DeclarationStatement conflict = null; int conflictIndex = -1; for (int i = 0; i < list.Count; i++) { if (nameComparer.Equals(list[i].Declaration.Name, decl.Declaration.Name)) { conflict = list[i]; conflictIndex = i; break; } } if (conflict == null) { list.Add(decl); } else { // Handle conflict: try if "moveup" would be sufficient if (IsSameType(decl.Declaration.Type, conflict.Declaration.Type, nameComparer)) { // create declaration at beginning of class and // replace decl & conflict by assignment DeclarationStatement newDecl = new DeclarationStatement(conflict.LexicalInfo); newDecl.Declaration = new Declaration(conflict.Declaration.LexicalInfo, conflict.Declaration.Name, conflict.Declaration.Type); block.Insert(0, newDecl); ReplaceWithInitializer(decl); ReplaceWithInitializer(conflict); list[conflictIndex] = newDecl; } else { string newName = FindFreeName(decl.Declaration.Name, list, fvdv.Declarations, nameComparer); decl.ParentNode.Accept(new RenameLocalsVisitor(decl.Declaration.Name, newName, nameComparer)); decl.Declaration.Name = newName; } } } }
public IEnumerable<Node> Substitute(MacroStatement callPointMacro){ var compiler = new BooCompiler(); compiler.Parameters.Pipeline = new CompilerPipeline(); compiler.Parameters.Pipeline.Add(new BooParsingStep()); compiler.Parameters.Input.Add(new StringInput("_code_", Code)); var compileresult = compiler.Run(); Node target = callPointMacro.ParentNode; while(!(target==null||(target is TypeDefinition))){ target = target.ParentNode; } if (null != target){ foreach (var member in compileresult.CompileUnit.Modules[0].Members){ ((TypeDefinition)target).Members.Add(member); } } var result = new Block(callPointMacro.LexicalInfo); foreach (var statement in compileresult.CompileUnit.Modules[0].Globals.Statements) { yield return statement; } }
int GetIndexAfterSuperInvocation(Block body) { int index = 0; foreach (Statement s in body.Statements) { if (NodeType.ExpressionStatement == s.NodeType) { Expression expression = ((ExpressionStatement)s).Expression; if (NodeType.MethodInvocationExpression == expression.NodeType) { if (NodeType.SuperLiteralExpression == ((MethodInvocationExpression)expression).Target.NodeType) { return index + 1; } } } ++index; } return 0; }
void AddInitializedGuardToInitializer(TypeDefinition type, Method initializer) { Field field = GetFieldsInitializerInitializedField(type); //run initializer code only if $initialized$ is false //hmm quasi-notation would be lovely here Block trueBlock = new Block(); trueBlock.Add(new GotoStatement(LexicalInfo.Empty, new ReferenceExpression("___initialized___"))); IfStatement cond = new IfStatement(CodeBuilder.CreateReference(field), trueBlock, null); initializer.Body.Insert(0, cond); //set $initialized$ field to true initializer.Body.Add( CodeBuilder.CreateFieldAssignment(field, new BoolLiteralExpression(true))); //label we're past the initializer initializer.Body.Add( new LabelStatement(LexicalInfo.Empty, "___initialized___")); }
private static void AddOptionalReturnStatement(Block body) { if (body.Statements.Count != 1) return; var stmt = body.FirstStatement as ExpressionStatement; if (null == stmt) return; var rs = new ReturnStatement(stmt.LexicalInfo, stmt.Expression, null); rs.Annotate(OptionalReturnStatementAnnotation); body.Replace(stmt, rs); }
B.Block ConvertMethodBlock(BlockStatement block) { B.Block b = ConvertBlock(block); RenameLocalsVisitor.RenameLocals(b, nameComparer); return(b); }