public virtual void VisitCatchClause(CatchClause catchClause) { if (ThrowException) { throw (Exception)CreateException(catchClause); } }
private void CreateMethod(CatchClause catchClause, VariableDeclarationExpression variable, out Expression methodInvocationExpression) { methodInvocationExpression = null; stackVariable4 = catchClause.get_Filter() as BlockStatement; V_0 = (((stackVariable4.get_Statements().First <Statement>() as ExpressionStatement).get_Expression() as BinaryExpression).get_Right() as SafeCastExpression).get_Expression() as VariableReferenceExpression; V_0.set_Variable(variable.get_Variable()); V_1 = stackVariable4.get_Statements().Last <Statement>() as ExpressionStatement; V_1.set_Expression(new ReturnExpression(V_1.get_Expression(), V_1.get_Expression().get_MappedInstructions())); V_2 = this.context.get_TypeContext().get_GeneratedFilterMethods().get_Count() + this.methodsToBeDecompiled.get_Count(); V_3 = new MethodDefinition(String.Format("JustDecompileGenerated_Filter_{0}", V_2), 1, this.context.get_MethodContext().get_Method().get_Module().get_TypeSystem().get_Boolean()); V_3.set_Body(new MethodBody(V_3)); V_3.set_MetadataToken(new MetadataToken(0x6000000, 0xffffff - V_2)); V_3.set_IsStatic(this.context.get_MethodContext().get_Method().get_IsStatic()); V_3.set_HasThis(!V_3.get_IsStatic()); V_3.set_DeclaringType(this.context.get_MethodContext().get_Method().get_DeclaringType()); V_3.set_SemanticsAttributes(0); V_3.set_IsJustDecompileGenerated(true); V_4 = new DecompilationContext(this.CloneAndReplaceMethodBody(this.context.get_MethodContext(), V_3.get_Body()), this.context.get_TypeContext(), this.context.get_Language()); V_5 = V_0.get_Variable().Resolve(); if (V_4.get_MethodContext().get_VariableDefinitionToNameMap().ContainsKey(V_5)) { V_4.get_MethodContext().get_VariableDefinitionToNameMap().Add(V_5, "JustDecompileGenerated_Exception"); } else { V_4.get_MethodContext().get_VariableDefinitionToNameMap().set_Item(V_5, "JustDecompileGenerated_Exception"); } dummyVar0 = V_4.get_MethodContext().get_VariablesToNotDeclare().Add(variable.get_Variable()); this.methodsToBeDecompiled.Add(new FilterMethodToBeDecompiled(V_3, catchClause, V_4, catchClause.get_Filter() as BlockStatement)); V_6 = this.AddAllParameters(catchClause, V_3, variable); methodInvocationExpression = this.CreateMethodInvocation(V_3, V_6); return; }
protected internal override Statement VisitTryCatch(TryCatch inst) { var tryCatch = new TryCatchStatement(); tryCatch.TryBlock = ConvertAsBlock(inst.TryBlock); foreach (var handler in inst.Handlers) { var catchClause = new CatchClause(); var v = handler.Variable; catchClause.AddAnnotation(new ILVariableResolveResult(v, v.Type)); if (v != null) { if (v.StoreCount > 1 || v.LoadCount > 0 || v.AddressCount > 0) { catchClause.VariableName = v.Name; catchClause.Type = exprBuilder.ConvertType(v.Type); } else if (!v.Type.IsKnownType(KnownTypeCode.Object)) { catchClause.Type = exprBuilder.ConvertType(v.Type); } } if (!handler.Filter.MatchLdcI4(1)) { catchClause.Condition = exprBuilder.TranslateCondition(handler.Filter); } catchClause.Body = ConvertAsBlock(handler.Body); tryCatch.CatchClauses.Add(catchClause); } return(tryCatch); }
public override void visit_catch_clause(CatchClause clause) { current_method_inner_error = true; var error_type = (ErrorType)clause.error_type; if (error_type.error_domain != null) { generate_error_domain_declaration(error_type.error_domain, cfile); } ccode.add_label(clause.clabel_name); ccode.open_block(); if (clause.error_variable != null) { visit_local_variable(clause.error_variable); ccode.add_assignment(get_variable_cexpression(get_local_cname(clause.error_variable)), get_variable_cexpression("_inner_error_")); } else { // error object is not used within catch statement, clear it var cclear = new CCodeFunctionCall(new CCodeIdentifier("g_clear_error")); cclear.add_argument(new CCodeUnaryExpression(CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression("_inner_error_"))); ccode.add_expression(cclear); } ccode.add_assignment(get_variable_cexpression("_inner_error_"), new CCodeConstant("NULL")); clause.body.emit(this); ccode.close(); }
bool IsRedundant(CatchClause catchClause) { if (!IsThrowsClause(catchClause)) { return(false); } var type = ctx.Resolve(catchClause.Type).Type; var n = catchClause.NextSibling; while (n != null) { var nextClause = n as CatchClause; if (nextClause != null) { if (nextClause.Type.IsNull && !IsThrowsClause(nextClause)) { return(false); } if (!IsThrowsClause(nextClause) && type.GetDefinition().IsDerivedFrom(ctx.Resolve(nextClause.Type).Type.GetDefinition())) { return(false); } } n = n.NextSibling; } return(true); }
public override void VisitCatchClause(CatchClause catchClause) { base.VisitCatchClause(catchClause); AstType type = catchClause.Type; if (!type.IsNull) { var resolvedType = ctx.Resolve(type); if (resolvedType.IsError || !resolvedType.Type.Namespace.Equals("System") || !resolvedType.Type.Name.Equals("Exception")) { return; } } var body = catchClause.Body; if (body.Statements.Any()) { return; } AddIssue(new CodeIssue(catchClause.CatchToken, ctx.TranslateString("Empty general catch clause suppresses any error"))); }
public TryFrame( TryFrameType frameType, CatchClause catchClause) { FrameType = frameType; CatchClause = catchClause; }
public virtual ICodeNode VisitCatchClause(CatchClause node) { node.set_Body((BlockStatement)this.Visit(node.get_Body())); node.set_Variable((VariableDeclarationExpression)this.Visit(node.get_Variable())); node.set_Filter((Statement)this.Visit(node.get_Filter())); return(node); }
CatchClause FindNearestFinallyClause(int instOffset) { CatchClause nearestClause = null; foreach (var tryClause in tryClauses) { if (instOffset >= tryClause.tryStart && instOffset < tryClause.tryEnd) { if (tryClause.catchClauses.Count == 1) { var catchClause = tryClause.catchClauses[0]; if (catchClause.finallyClause) { if (nearestClause == null || IsNearest(instOffset, nearestClause.catchStart, nearestClause.catchEnd, catchClause.catchStart, catchClause.catchEnd)) { nearestClause = catchClause; } } } } } return(nearestClause); }
void ScanCatchClauseForNestedTry(CatchClause catchClause) { // the stack contains an exception object on entry to all handlers, // regardless of the clause type. a 'catch' or 'filter' handler // typically starts by storing (or popping) the object. // a 'finally' or 'fault' handler typically keeps the object on the // stack, for use by a later 'endfinally' instruction. // // however, if the 'finally' clause has a nested try/catch region, // then a thrown exception would clear the stack. to work around // this, in such a case, we store the exception object in a local // (see also ExceptionClauseSetup and SaveExceptionObject), and // then load it in Translate_Endfinally if (catchClause.finallyClause) { foreach (var tryClause in tryClauses) { if (tryClause.tryStart >= catchClause.catchStart && tryClause.tryEnd <= catchClause.catchEnd) { catchClause.hasNestedTry = true; } } } }
CatchClause FindNearestCatchClause(int instOffset) { // find the catch clause that contains offset of the current // instruction. if a catch clause itself contains a 'try' block, // then multiple catch clauses may apply. in this case we select // the catch clauses nerarest to the instruction, as that would // be the innermost catch clause. CatchClause nearestClause = null; foreach (var tryClause in tryClauses) { foreach (var catchClause in tryClause.catchClauses) { if (instOffset >= catchClause.catchStart && instOffset < catchClause.catchEnd) { if (nearestClause == null || IsNearest(instOffset, nearestClause.catchStart, nearestClause.catchEnd, catchClause.catchStart, catchClause.catchEnd)) { nearestClause = catchClause; } } } } return(nearestClause); }
public override void VisitCatchClause(CatchClause catchClause) { base.VisitCatchClause(catchClause); var exceptionResolveResult = ctx.Resolve(catchClause.VariableNameToken) as LocalResolveResult; if (exceptionResolveResult == null) { return; } var catchVisitor = new CatchClauseVisitor(ctx, exceptionResolveResult.Variable); catchClause.Body.AcceptVisitor(catchVisitor); foreach (var throwStatement in catchVisitor.OffendingThrows) { var localThrowStatement = throwStatement; var title = ctx.TranslateString("The exception is rethrown with explicit usage of the variable"); var action = new CodeAction(ctx.TranslateString("Change to 'throw;'"), script => { script.Replace(localThrowStatement, new ThrowStatement()); }, catchClause); AddDiagnosticAnalyzer(new CodeIssue(localThrowStatement, title, action)); } }
public override UstNode VisitCatchClause(CatchClauseSyntax node) { TypeToken typeToken; IdToken varName; if (node.Declaration == null) { typeToken = new TypeToken("Exception", node.CatchKeyword.GetTextSpan(), FileNode); varName = new IdToken("e", node.CatchKeyword.GetTextSpan(), FileNode); } else { typeToken = ConvertType(base.Visit(node.Declaration.Type)); varName = new IdToken(node.Declaration.Identifier.ValueText ?? "", node.Declaration.GetTextSpan(), FileNode); } var body = (BlockStatement)VisitBlock(node.Block); var result = new CatchClause( typeToken, varName, body, node.GetTextSpan(), FileNode); return(result); }
public virtual ICodeNode VisitCatchClause(CatchClause node) { node.Body = (BlockStatement)Visit(node.Body); node.Variable = (VariableDeclarationExpression)Visit(node.Variable); node.Filter = (Statement)Visit(node.Filter); return(node); }
public FilterMethodToBeDecompiled(MethodDefinition method, CatchClause catchClause, DecompilationContext context, BlockStatement block) { this.Method = method; this.CatchClause = catchClause; this.Context = context; this.Block = block; }
// Build a try-catch-finally statement public static void BuildExceptionHandler(IronyParser parser, Root root, Expression parentExpression, ParseTreeNode currentNode) { var ex = new ExceptionHandler(parentExpression, currentNode.Token.Convert()); parentExpression.ChildExpressions.Add(ex); // Build the contents of the try block parser.ConsumeParseTree(root, ex.Try, currentNode.ChildNodes[0]); // Build each case block. if (currentNode.ChildNodes[1].ChildNodes.Count > 0) { foreach (var node in currentNode.ChildNodes[1].ChildNodes) { var c = new CatchClause(ex, node.Token.Convert()); c.Type = node.ChildNodes[1].FindTokenAndGetText(); c.Name = node.ChildNodes[2].FindTokenAndGetText(); ex.CatchClauses.Add(c); parser.ConsumeParseTree(root, c, node.ChildNodes[3]); } } // Build the finally block. parser.ConsumeParseTree(root, ex.Finally, currentNode.ChildNodes[2]); }
public virtual void VisitCatchClause(CatchClause node) { this.Visit(node.get_Body()); this.Visit(node.get_Variable()); this.Visit(node.get_Filter()); return; }
private static void DecompileHandler(BasicBlock containingBlock, BasicBlock handlerBlock, TryCatchFinallyStatement tryStatement) { if (handlerBlock.ExceptionInformation.HandlerKind == HandlerKind.Finally) { tryStatement.FinallyBody = handlerBlock; } else if (handlerBlock.ExceptionInformation.HandlerKind == HandlerKind.Fault) { tryStatement.FaultBody = handlerBlock; } else { CatchClause catchClause = new CatchClause(); catchClause.Body = handlerBlock; catchClause.ExceptionType = handlerBlock.ExceptionInformation.ExceptionType; if (handlerBlock.ExceptionInformation.HandlerKind == HandlerKind.Catch) { catchClause.ExceptionContainer = ExtractExceptionContainer(handlerBlock); } else if (handlerBlock.ExceptionInformation.HandlerKind == HandlerKind.Filter) { catchClause.FilterCondition = ExtractFilterCondition(handlerBlock); } tryStatement.CatchClauses.Add(catchClause); } //Remove handler from statements in containing block containingBlock.Statements[containingBlock.Statements.Count - 1] = GetBasicBlockStartingAt(handlerBlock, handlerBlock.ExceptionInformation.HandlerEndOffset); RemoveEndFinally(handlerBlock); }
// TODO: Wait until Roslyn gets this implemented public override IStatement VisitTryStatement(TryStatementSyntax node) { var catches = new List <ICatchClause>(); foreach (var c in node.Catches) { var c_prime = new CatchClause() { //Body = MkBlockStatement(this.Visit(c.Block, arg)), }; if (c.Declaration != null) { var cDecl = c.Declaration; } } var tcf = new TryCatchFinallyStatement() { CatchClauses = catches, Locations = Helper.SourceLocation(this.tree, node), TryBody = Helper.MkBlockStatement(this.Visit(node.Block)), }; if (node.Finally != null) { tcf.FinallyBody = Helper.MkBlockStatement(this.Visit(node.Finally.Block)); } return(tcf); }
public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context) { Expression basicBody = _tryExpr.GenCode(rhc, objx, context); if (basicBody.Type == typeof(void)) { basicBody = Expression.Block(basicBody, Expression.Default(typeof(object))); } Expression tryBody = Expression.Convert(basicBody, typeof(object)); CatchBlock[] catches = new CatchBlock[_catchExprs.count()]; for (int i = 0; i < _catchExprs.count(); i++) { CatchClause clause = (CatchClause)_catchExprs.nth(i); ParameterExpression parmExpr = Expression.Parameter(clause.Type, clause.Lb.Name); clause.Lb.ParamExpression = parmExpr; catches[i] = Expression.Catch(parmExpr, Expression.Convert(clause.Handler.GenCode(rhc, objx, context), typeof(object))); } Expression tryStmt = _finallyExpr == null ? catches.Length == 0 ? tryBody : Expression.TryCatch(tryBody, catches) : Expression.TryCatchFinally(tryBody, _finallyExpr.GenCode(RHC.Statement, objx, context), catches); return(tryStmt); }
public override Expression GenDlr(GenContext context) { Expression basicBody = _tryExpr.GenDlr(context); // Wrap the basic body, a Comma, in a return to a label LabelTarget target = Expression.Label(basicBody.Type, "ret_label"); //Expression tryBody = Expression.Return(target, basicBody); Expression tryBody = basicBody; CatchBlock[] catches = new CatchBlock[_catchExprs.count()]; for (int i = 0; i < _catchExprs.count(); i++) { CatchClause clause = (CatchClause)_catchExprs.nth(i); ParameterExpression parmExpr = Expression.Parameter(clause.Type, clause.Lb.Name); clause.Lb.ParamExpression = parmExpr; catches[i] = Expression.Catch(parmExpr, clause.Handler.GenDlr(context)); } TryExpression tryStmt = _finallyExpr == null ? Expression.TryCatch(tryBody, catches) : Expression.TryCatchFinally(tryBody, _finallyExpr.GenDlr(context), catches); Expression defaultValue = Expression.Default(basicBody.Type); Expression whole = Expression.Block(tryStmt, Expression.Label(target, defaultValue)); return(whole); }
public override object VisitCatchClause(CatchClause catchClause, CSharpAstResolver astResolver) { ResolveResult resolveResult = astResolver.Resolve(catchClause.Type); if (resolveResult != null) { Tree.Tree t = SourceImporter.SourceImporter.Tree; //1) target node ClassNode targetNode = new ClassNode(resolveResult.Type.FullName, resolveResult); targetNode = t.AddOrGetClassNode(resolveResult.Type.Namespace, targetNode);//override if already in tree with that node if (targetNode != null) { //2) caller node (can't be null) //find out class in which the invocation statement is found TypeDeclaration classDeclaration = catchClause.Ancestors.Where(a => a is TypeDeclaration).Cast <TypeDeclaration>().First(); //resolve the class declaration TypeResolveResult resolvedClass = astResolver.Resolve(classDeclaration) as TypeResolveResult; if (resolvedClass != null) { ClassNode callerNode = new ClassNode(resolvedClass.Type.FullName, resolvedClass); callerNode = t.AddOrGetClassNode(resolvedClass.Type.Namespace, callerNode); //override if already in tree with that node //3) edge (dependency) between caller and target callerNode.AddDependency(targetNode); } } } return(base.VisitCatchClause(catchClause, astResolver)); }
void Translate_Throw(Mono.Cecil.Cil.Instruction inst) { if (inst.OpCode.Code == Code.Rethrow) { // if a catch clause contains a 'rethrow' instruction then // a reference to the exception object should have previously // been saved in a local (in SaveExceptionObject) CatchClause nearestClause = FindNearestCatchClause(inst.Offset); if (!nearestClause.includesRethrow) { throw new InvalidProgramException(); } code.NewInstruction(0x19 /* aload */, null, nearestClause.tryClause.localIndex); } // in the jvm, the stack trace is recorded when the exception // object is created. in the clr, the stack trace is recorded // only when the exception is thrown, so we have to emulate it. // // (also note that our system.Exception replacement (in baselib) // discards the initial call to fillInStackTrace, which occurs // during the construction of the exception object.) code.NewInstruction(0xB6 /* invokevirtual */, ThrowableType, new JavaMethodRef("fillInStackTrace", ThrowableType)); code.NewInstruction(0xBF /* athrow */, null, null); }
public override ICodeNode VisitCatchClause(CatchClause node) { node.set_Body((BlockStatement)this.Visit(node.get_Body())); if (node.get_Filter() == null || node.get_Filter() as BlockStatement == null) { return(node); } this.currentCatchClause = node; node.set_Filter((Statement)this.Visit(node.get_Filter())); this.currentCatchClause = null; stackVariable27 = CatchClausesFilterPattern.TryMatch(node.get_Filter() as BlockStatement, out V_0, out V_1); if (!stackVariable27) { if (V_0 == null || String.op_Equality(V_0.get_ExpressionType().get_FullName(), "System.Object") || !CatchClausesFilterPattern.TryMatchMethodStructure(node.get_Filter() as BlockStatement)) { throw new NotSupportedException("Unsupported structure of filter clause."); } this.CreateMethod(node, V_0, out V_1); } dummyVar0 = this.context.get_MethodContext().get_VariablesToNotDeclare().Add(V_0.get_Variable()); if (!stackVariable27) { node.set_Variable(V_0.CloneExpressionOnly() as VariableDeclarationExpression); } else { node.set_Variable(V_0); } node.set_Type(V_0.get_ExpressionType()); node.set_Filter(new ExpressionStatement(V_1)); return(node); }
public override object VisitCatchClause(CatchClause catchClause, object data) { catchClause.Condition.Parent = catchClause; catchClause.StatementBlock.Parent = catchClause; catchClause.TypeReference.Parent = catchClause; return(base.VisitCatchClause(catchClause, data)); }
public virtual void VisitCatchClause(CatchClause catchClause) { if (this.ThrowException) { throw (System.Exception) this.CreateException(catchClause); } }
protected override void VisitCatchClause(CatchClause catchClause) { using (StartNodeObject(catchClause)) { Member("param", catchClause.Param); Member("body", catchClause.Body); } }
public UnifiedElement VisitCatchClause(CatchClause catchClause, object data) { var type = LookupType(catchClause.Type); var name = UnifiedVariableIdentifier.Create(catchClause.VariableName); var body = catchClause.Body.TryAcceptForExpression(this).ToBlock(); return(UnifiedCatch.Create(type.ToSet(), name, body)); }
public override void VisitCatchClause(CatchClause catchClause) { if (!catchClause.VariableNameToken.IsNull) { AddVariable(catchClause.VariableNameToken, catchClause.VariableName); } base.VisitCatchClause(catchClause); }
public override void Clone(JsNode node) { base.Clone(node); var node2 = (JsTryStatement)node; node2.TryBlock = TryBlock.Clone(); node2.CatchClause = CatchClause.Clone(); node2.FinallyBlock = FinallyBlock.Clone(); }
public TryStatement(Statement statement, CatchClause catchClause, FinallyClause finallyClause) { Statement = statement; Catch = catchClause; Finally = finallyClause; SourceOffset = statement.SourceOffset; Use(Statement); Use(Catch); Use(Finally); m.Util.Diagnose.Debug.Assert(Catch != null || Finally != null, "SyntaxError: Missing catch or finally after try"); }
public override void VisitCatchClause(CatchClause catchClause) { base.VisitCatchClause(catchClause); var exceptionResolveResult = ctx.Resolve(catchClause.VariableNameToken) as LocalResolveResult; if (exceptionResolveResult == null) return; var catchVisitor = new CatchClauseVisitor(ctx, exceptionResolveResult.Variable); catchClause.Body.AcceptVisitor(catchVisitor); foreach (var throwStatement in catchVisitor.OffendingThrows) { var localThrowStatement = throwStatement; var title = ctx.TranslateString("The exception is rethrown with explicit usage of the variable"); var action = new CodeAction(ctx.TranslateString("Change to 'throw;'"), script => { script.Replace(localThrowStatement, new ThrowStatement()); }); AddIssue(localThrowStatement, title, new [] { action }); } }
static Statement GetWatchInstrument (string id, Expression expr) { var r = new MemberReferenceExpression ( new MemberReferenceExpression ( new MemberReferenceExpression ( new IdentifierExpression ("Continuous"), "Server"), "WatchStore"), "Record"); var i = new ExpressionStatement (new InvocationExpression (r, new PrimitiveExpression (id), expr)); var t = new TryCatchStatement (); t.TryBlock = new BlockStatement (); t.TryBlock.Statements.Add (i); var c = new CatchClause (); c.Body = new BlockStatement (); t.CatchClauses.Add (c); return t; }
bool IsRedundant(CatchClause catchClause) { var firstStatement = catchClause.Body.Statements.FirstOrNullObject(); if (firstStatement.IsNull) { return false; } var throwStatement = firstStatement as ThrowStatement; if (throwStatement == null) { return false; } return throwStatement.Expression.IsNull; }
IEnumerable<Statement> TransformNode(ILNode node) { if (node is ILLabel) { yield return new Ast.LabelStatement { Label = ((ILLabel)node).Name }.WithAnnotation(node.ILRanges); } else if (node is ILExpression) { AstNode codeExpr = TransformExpression((ILExpression)node); if (codeExpr != null) { if (codeExpr is Ast.Expression) { yield return new Ast.ExpressionStatement { Expression = (Ast.Expression)codeExpr }; } else if (codeExpr is Ast.Statement) { yield return (Ast.Statement)codeExpr; } else { throw new Exception(); } } } else if (node is ILWhileLoop) { ILWhileLoop ilLoop = (ILWhileLoop)node; Expression expr; WhileStatement whileStmt = new WhileStatement() { Condition = expr = ilLoop.Condition != null ? (Expression)TransformExpression(ilLoop.Condition) : new PrimitiveExpression(true), EmbeddedStatement = TransformBlock(ilLoop.BodyBlock) }; expr.AddAnnotation(ilLoop.ILRanges); yield return whileStmt; } else if (node is ILCondition) { ILCondition conditionalNode = (ILCondition)node; bool hasFalseBlock = conditionalNode.FalseBlock.EntryGoto != null || conditionalNode.FalseBlock.Body.Count > 0; BlockStatement trueStmt; var ifElseStmt = new Ast.IfElseStatement { Condition = (Expression)TransformExpression(conditionalNode.Condition), TrueStatement = trueStmt = TransformBlock(conditionalNode.TrueBlock), FalseStatement = hasFalseBlock ? TransformBlock(conditionalNode.FalseBlock) : null }; ifElseStmt.Condition.AddAnnotation(conditionalNode.ILRanges); if (ifElseStmt.FalseStatement == null) trueStmt.HiddenEnd = NRefactoryExtensions.CreateHidden(conditionalNode.FalseBlock.GetSelfAndChildrenRecursiveILRanges(), trueStmt.HiddenEnd); yield return ifElseStmt; } else if (node is ILSwitch) { ILSwitch ilSwitch = (ILSwitch)node; if (ilSwitch.Condition.InferredType.GetElementType() == ElementType.Boolean && ( from cb in ilSwitch.CaseBlocks where cb.Values != null from val in cb.Values select val ).Any(val => val != 0 && val != 1)) { // If switch cases contain values other then 0 and 1, force the condition to be non-boolean ilSwitch.Condition.ExpectedType = corLib.Int32; } SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) }; switchStmt.Expression.AddAnnotation(ilSwitch.ILRanges); switchStmt.HiddenEnd = NRefactoryExtensions.CreateHidden(ilSwitch.EndILRanges, switchStmt.HiddenEnd); foreach (var caseBlock in ilSwitch.CaseBlocks) { SwitchSection section = new SwitchSection(); if (caseBlock.Values != null) { section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, (ilSwitch.Condition.ExpectedType ?? ilSwitch.Condition.InferredType).ToTypeDefOrRef()) })); } else { section.CaseLabels.Add(new CaseLabel()); } section.Statements.Add(TransformBlock(caseBlock)); switchStmt.SwitchSections.Add(section); } yield return switchStmt; } else if (node is ILTryCatchBlock) { ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node); var tryCatchStmt = new Ast.TryCatchStatement(); tryCatchStmt.TryBlock = TransformBlock(tryCatchNode.TryBlock); tryCatchStmt.TryBlock.HiddenStart = NRefactoryExtensions.CreateHidden(tryCatchNode.ILRanges, tryCatchStmt.TryBlock.HiddenStart); foreach (var catchClause in tryCatchNode.CatchBlocks) { if (catchClause.ExceptionVariable == null && (catchClause.ExceptionType == null || catchClause.ExceptionType.GetElementType() == ElementType.Object)) { tryCatchStmt.CatchClauses.Add(new Ast.CatchClause { Body = TransformBlock(catchClause) }.WithAnnotation(catchClause.StlocILRanges)); } else { tryCatchStmt.CatchClauses.Add( new Ast.CatchClause { Type = AstBuilder.ConvertType(catchClause.ExceptionType), VariableNameToken = catchClause.ExceptionVariable == null ? null : Identifier.Create(catchClause.ExceptionVariable.Name).WithAnnotation(catchClause.ExceptionVariable.IsParameter ? TextTokenType.Parameter : TextTokenType.Local), Body = TransformBlock(catchClause) }.WithAnnotation(catchClause.ExceptionVariable).WithAnnotation(catchClause.StlocILRanges)); } } if (tryCatchNode.FinallyBlock != null) tryCatchStmt.FinallyBlock = TransformBlock(tryCatchNode.FinallyBlock); if (tryCatchNode.FaultBlock != null) { CatchClause cc = new CatchClause(); cc.Body = TransformBlock(tryCatchNode.FaultBlock); cc.Body.Add(new ThrowStatement()); // rethrow tryCatchStmt.CatchClauses.Add(cc); } yield return tryCatchStmt; } else if (node is ILFixedStatement) { ILFixedStatement fixedNode = (ILFixedStatement)node; FixedStatement fixedStatement = new FixedStatement(); for (int i = 0; i < fixedNode.Initializers.Count; i++) { var initializer = fixedNode.Initializers[i]; Debug.Assert(initializer.Code == ILCode.Stloc); ILVariable v = (ILVariable)initializer.Operand; VariableInitializer vi; fixedStatement.Variables.Add(vi = new VariableInitializer { NameToken = Identifier.Create(v.Name).WithAnnotation(v.IsParameter ? TextTokenType.Parameter : TextTokenType.Local), Initializer = (Expression)TransformExpression(initializer.Arguments[0]) }.WithAnnotation(v)); vi.AddAnnotation(ILRange.OrderAndJoin(initializer.GetSelfAndChildrenRecursiveILRanges())); if (i == 0) vi.AddAnnotation(ILRange.OrderAndJoin(fixedNode.ILRanges)); } fixedStatement.Type = AstBuilder.ConvertType(((ILVariable)fixedNode.Initializers[0].Operand).Type); fixedStatement.EmbeddedStatement = TransformBlock(fixedNode.BodyBlock); yield return fixedStatement; } else if (node is ILBlock) { yield return TransformBlock((ILBlock)node); } else { throw new Exception("Unknown node type"); } }
IEnumerable<Statement> TransformNode(ILNode node) { if (node is ILLabel) { yield return new LabelStatement { Label = ((ILLabel)node).Name }; } else if (node is ILExpression) { List<ILRange> ilRanges = ILRange.OrderAndJoint(node.GetSelfAndChildrenRecursive<ILExpression>().SelectMany(e => e.ILRanges)); AstNode codeExpr = TransformExpression((ILExpression)node); if (codeExpr != null) { codeExpr = codeExpr.WithAnnotation(ilRanges); if (codeExpr is Expression) { yield return new ExpressionStatement { Expression = (Expression)codeExpr }; } else if (codeExpr is Statement) { yield return (Statement)codeExpr; } else { throw new Exception(); } } } else if (node is ILWhileLoop) { ILWhileLoop ilLoop = (ILWhileLoop)node; WhileStatement whileStmt = new WhileStatement() { Condition = ilLoop.Condition != null ? (Expression)TransformExpression(ilLoop.Condition) : new PrimitiveExpression(true), EmbeddedStatement = TransformBlock(ilLoop.BodyBlock) }; yield return whileStmt; } else if (node is ILCondition) { ILCondition conditionalNode = (ILCondition)node; bool hasFalseBlock = conditionalNode.FalseBlock.EntryGoto != null || conditionalNode.FalseBlock.Body.Count > 0; yield return new IfElseStatement { Condition = (Expression)TransformExpression(conditionalNode.Condition), TrueStatement = TransformBlock(conditionalNode.TrueBlock), FalseStatement = hasFalseBlock ? TransformBlock(conditionalNode.FalseBlock) : null }; } else if (node is ILSwitch) { ILSwitch ilSwitch = (ILSwitch)node; if (TypeAnalysis.IsBoolean(ilSwitch.Condition.InferredType) && ( from cb in ilSwitch.CaseBlocks where cb.Values != null from val in cb.Values select val ).Any(val => val != 0 && val != 1)) { // If switch cases contain values other then 0 and 1, force the condition to be non-boolean ilSwitch.Condition.ExpectedType = typeSystem.Int32; } SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) }; foreach (var caseBlock in ilSwitch.CaseBlocks) { SwitchSection section = new SwitchSection(); if (caseBlock.Values != null) { section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, ilSwitch.Condition.ExpectedType ?? ilSwitch.Condition.InferredType) })); } else { section.CaseLabels.Add(new CaseLabel()); } section.Statements.Add(TransformBlock(caseBlock)); switchStmt.SwitchSections.Add(section); } yield return switchStmt; } else if (node is ILTryCatchBlock) { ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node); var tryCatchStmt = new TryCatchStatement(); tryCatchStmt.TryBlock = TransformBlock(tryCatchNode.TryBlock); foreach (var catchClause in tryCatchNode.CatchBlocks) { CatchClause clause = new CatchClause { Body = TransformBlock(catchClause) }; if (catchClause.ExceptionVariable != null || (catchClause.ExceptionType != null && !catchClause.ExceptionType.IsCorLibType("System", "Object"))) { clause.Type = AstBuilder.ConvertType(catchClause.ExceptionType); clause.VariableName = catchClause.ExceptionVariable == null ? null : catchClause.ExceptionVariable.Name; clause.AddAnnotation(catchClause.ExceptionVariable); } if (catchClause.FilterBlock != null) { clause.Filter = new FilterClause { Expression = new LambdaExpression { Body = TransformBlock(catchClause.FilterBlock) }.WithAnnotation(new FilterClauseAnnotation()) }; } tryCatchStmt.CatchClauses.Add(clause); } if (tryCatchNode.FinallyBlock != null) tryCatchStmt.FinallyBlock = TransformBlock(tryCatchNode.FinallyBlock); if (tryCatchNode.FaultBlock != null) { CatchClause cc = new CatchClause(); cc.Body = TransformBlock(tryCatchNode.FaultBlock); cc.Body.Add(new ThrowStatement()); // rethrow tryCatchStmt.CatchClauses.Add(cc); } yield return tryCatchStmt; } else if (node is ILFixedStatement) { ILFixedStatement fixedNode = (ILFixedStatement)node; FixedStatement fixedStatement = new FixedStatement(); foreach (ILExpression initializer in fixedNode.Initializers) { Debug.Assert(initializer.Code == ILCode.Stloc); ILVariable v = (ILVariable)initializer.Operand; fixedStatement.Variables.Add( new VariableInitializer { Name = v.Name, Initializer = (Expression)TransformExpression(initializer.Arguments[0]) }.WithAnnotation(v)); } fixedStatement.Type = AstBuilder.ConvertType(((ILVariable)fixedNode.Initializers[0].Operand).Type); fixedStatement.EmbeddedStatement = TransformBlock(fixedNode.BodyBlock); yield return fixedStatement; } else if (node is ILBlock) { yield return TransformBlock((ILBlock)node); } else { throw new Exception("Unknown node type"); } }
IEnumerable<Statement> TransformNode(ILNode node) { if (node is ILLabel) { yield return new Ast.LabelStatement { Label = ((ILLabel)node).Name }; } else if (node is ILExpression) { List<ILRange> ilRanges = ((ILExpression)node).GetILRanges(); AstNode codeExpr = TransformExpression((ILExpression)node); if (codeExpr != null) { codeExpr = codeExpr.WithAnnotation(ilRanges); if (codeExpr is Ast.Expression) { yield return new Ast.ExpressionStatement { Expression = (Ast.Expression)codeExpr }; } else if (codeExpr is Ast.Statement) { yield return (Ast.Statement)codeExpr; } else { throw new Exception(); } } } else if (node is ILWhileLoop) { ILWhileLoop ilLoop = (ILWhileLoop)node; WhileStatement whileStmt = new WhileStatement() { Condition = ilLoop.Condition != null ? (Expression)TransformExpression(ilLoop.Condition) : new PrimitiveExpression(true), EmbeddedStatement = TransformBlock(ilLoop.BodyBlock) }; yield return whileStmt; } else if (node is ILCondition) { ILCondition conditionalNode = (ILCondition)node; bool hasFalseBlock = conditionalNode.FalseBlock.EntryGoto != null || conditionalNode.FalseBlock.Body.Count > 0; yield return new Ast.IfElseStatement { Condition = (Expression)TransformExpression(conditionalNode.Condition), TrueStatement = TransformBlock(conditionalNode.TrueBlock), FalseStatement = hasFalseBlock ? TransformBlock(conditionalNode.FalseBlock) : null }; } else if (node is ILSwitch) { ILSwitch ilSwitch = (ILSwitch)node; SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) }; foreach (var caseBlock in ilSwitch.CaseBlocks) { SwitchSection section = new SwitchSection(); if (caseBlock.Values != null) { section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, ilSwitch.Condition.InferredType) })); } else { section.CaseLabels.Add(new CaseLabel()); } section.Statements.Add(TransformBlock(caseBlock)); switchStmt.SwitchSections.Add(section); } yield return switchStmt; } else if (node is ILTryCatchBlock) { ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node); var tryCatchStmt = new Ast.TryCatchStatement(); tryCatchStmt.TryBlock = TransformBlock(tryCatchNode.TryBlock); foreach (var catchClause in tryCatchNode.CatchBlocks) { tryCatchStmt.CatchClauses.Add( new Ast.CatchClause { Type = AstBuilder.ConvertType(catchClause.ExceptionType), VariableName = catchClause.ExceptionVariable == null ? null : catchClause.ExceptionVariable.Name, Body = TransformBlock(catchClause) }); } if (tryCatchNode.FinallyBlock != null) tryCatchStmt.FinallyBlock = TransformBlock(tryCatchNode.FinallyBlock); if (tryCatchNode.FaultBlock != null) { CatchClause cc = new CatchClause(); cc.Body = TransformBlock(tryCatchNode.FaultBlock); cc.Body.Add(new ThrowStatement()); // rethrow tryCatchStmt.CatchClauses.Add(cc); } yield return tryCatchStmt; } else if (node is ILBlock) { yield return TransformBlock((ILBlock)node); } else if (node is ILComment) { yield return new CommentStatement(((ILComment)node).Text).WithAnnotation(((ILComment)node).ILRanges); } else { throw new Exception("Unknown node type"); } }
public virtual void VisitCatchClause(CatchClause catchClause) { StartNode(catchClause); DebugStart(catchClause); WriteKeywordReference(CatchClause.CatchKeywordRole, currentTryReference); if (!catchClause.Type.IsNull) { Space(policy.SpaceBeforeCatchParentheses); var braceHelper = BraceHelper.LeftParen(this, CodeBracesRangeFlags.Parentheses); Space(policy.SpacesWithinCatchParentheses); catchClause.Type.AcceptVisitor(this); if (!string.IsNullOrEmpty(catchClause.VariableName)) { Space(); WriteIdentifier(catchClause.VariableNameToken); } Space(policy.SpacesWithinCatchParentheses); braceHelper.RightParen(); } DebugEnd(catchClause); if (!catchClause.Condition.IsNull) { Space(); WriteKeywordReference(CatchClause.WhenKeywordRole, currentTryReference); Space(policy.SpaceBeforeIfParentheses); var braceHelper = BraceHelper.LeftParen(this, CodeBracesRangeFlags.Parentheses); Space(policy.SpacesWithinIfParentheses); catchClause.Condition.AcceptVisitor(this); Space(policy.SpacesWithinIfParentheses); braceHelper.RightParen(); } catchClause.Body.AcceptVisitor(this); EndNode(catchClause); }
public StringBuilder VisitCatchClause(CatchClause catchClause, int data) { throw new SLSharpException("SL# does not have exceptions."); }
private Location Statement(Seq<Statement> statements, bool isTop) { ConsumeCommentStatement(statements); switch (Current.Tag) { case InputElementTag.LBrace: { return BlockStatements("block", false, statements); } case InputElementTag.Var: { var variableDeclarations = new Seq<VariableDeclaration>(); var loc = VariableDeclarations(variableDeclarations); statements.Add(new VariableStatement(loc, variableDeclarations)); return loc; } case InputElementTag.Semicolon: { var loc = Current.Loc; Consume(); return loc; } case InputElementTag.If: { var loc = Current.Loc; Consume(); Only("if statement", "'('", InputElementTag.LParen); var condition = Expression(false); Only("if statement", "')'", InputElementTag.RParen); condition = ConsumeCommentExpression(condition); var thenStatements = new Seq<Statement>(); loc = loc.Union(Statement(thenStatements, false)); if (Current.Tag == InputElementTag.Else) { var elseStatements = new Seq<Statement>(); Consume(); loc = loc.Union(Statement(elseStatements, false)); statements.Add(new IfStatement(loc, condition, new Statements(thenStatements), new Statements(elseStatements))); } else statements.Add(new IfStatement(loc, condition, new Statements(thenStatements))); return loc; } case InputElementTag.Do: { var loc = Current.Loc; Consume(); var body = new Seq<Statement>(); Statement(body, false); Only("do statement", "'while'", InputElementTag.While); Only("do statement", "'('", InputElementTag.LParen); var condition = Expression(false); Only("do statement", "')'", InputElementTag.RParen); condition = ConsumeCommentExpression(condition); OptSemicolon("do statement"); loc = loc.Union(condition.Loc); statements.Add(new DoStatement(loc, new Statements(body), condition)); return loc; } case InputElementTag.While: { var loc = Current.Loc; Consume(); Only("while statement", "'('", InputElementTag.LParen); var condition = Expression(false); Only("while statement", "')'", InputElementTag.RParen); condition = ConsumeCommentExpression(condition); var body = new Seq<Statement>(); loc = loc.Union(Statement(body, false)); statements.Add(new WhileStatement(loc, condition, new Statements(body))); return loc; } case InputElementTag.For: { var loc = Current.Loc; Consume(); var loopClause = LoopClause(); var body = new Seq<Statement>(); loc = loc.Union(Statement(body, false)); statements.Add(new ForStatement(loc, loopClause, new Statements(body))); return loc; } case InputElementTag.Continue: { var loc = Current.Loc; Consume(); // ask for Current to make sure lastLineTerminator is updates var isid = Current.Tag == InputElementTag.Identifier; var label = default(Identifier); if (lastLineTerminator == null) { if (isid) { label = new Identifier(Current.Loc, Current.Value); loc = loc.Union(label.Loc); Consume(); } OptSemicolon("continue statement"); } statements.Add(new ContinueStatement(loc, label)); return loc; } case InputElementTag.Break: { var loc = Current.Loc; Consume(); // ask for Current to make sure lastLineTerminator is updates var isid = Current.Tag == InputElementTag.Identifier; var label = default(Identifier); if (lastLineTerminator == null) { if (isid) { label = new Identifier(Current.Loc, Current.Value); loc = loc.Union(label.Loc); Consume(); } OptSemicolon("break statement"); } statements.Add(new BreakStatement(loc, label)); return loc; } case InputElementTag.Return: { var loc = Current.Loc; Consume(); var value = default(Expression); // ask for Current to make sure lastLineTerminator is updates var isExpr = IsExpression(); if (lastLineTerminator == null) { if (isExpr) { value = Expression(false); loc = loc.Union(value.Loc); } OptSemicolon("return statement"); if (value != null) value = ConsumeCommentExpression(value); } statements.Add(new ReturnStatement(loc, value)); return loc; } case InputElementTag.With: { var loc = Current.Loc; Consume(); Only("with statement", "'('", InputElementTag.LParen); var environment = Expression(false); Only("with statement", "')'", InputElementTag.RParen); environment = ConsumeCommentExpression(environment); var body = new Seq<Statement>(); loc = loc.Union(Statement(body, false)); statements.Add(new WithStatement(loc, environment, new Statements(body))); return loc; } case InputElementTag.Identifier: { var loc = Current.Loc; var ie = Current; Consume(); if (Current.Tag == InputElementTag.Colon) { var label = new Identifier(ie.Loc, ie.Value); Consume(); var body = new Seq<Statement>(); loc = loc.Union(Statement(body, false)); statements.Add(new LabelledStatement(loc, label, new Statements(body))); } else { Regurgitate(ie); var expression = Expression(false); loc = expression.Loc; OptSemicolon("expression statement"); expression = ConsumeCommentExpression(expression); statements.Add(new ExpressionStatement(loc, expression)); } return loc; } case InputElementTag.Switch: { var loc = Current.Loc; Consume(); Only("switch statement", "'('", InputElementTag.LParen); var value = Expression(false); Only("switch statement", "')'", InputElementTag.RParen); value = ConsumeCommentExpression(value); Only("switch statement", "'{'", InputElementTag.LBrace); var cases = new Seq<CaseClause>(); var defaultc = default(DefaultClause); while (Current.Tag != InputElementTag.RBrace) { if (Current.Tag == InputElementTag.Case) { var caseLoc = Current.Loc; Consume(); var caseValue = Expression(false); Only("case clause", "':'", InputElementTag.Colon); var caseBody = new Seq<Statement>(); while (Current.Tag != InputElementTag.Case && Current.Tag != InputElementTag.Default && Current.Tag != InputElementTag.RBrace) caseLoc = caseLoc.Union(Statement(caseBody, false)); ConsumeCommentStatement(caseBody); cases.Add(new CaseClause(caseLoc, caseValue, new Statements(caseBody))); } else if (Current.Tag == InputElementTag.Default) { if (defaultc != null) throw MsgError ("case clause", String.Format("default clause already present at {0}", defaultc.Loc)); var defaultLoc = Current.Loc; Consume(); Only("default clause", "':'", InputElementTag.Colon); var defaultBody = new Seq<Statement>(); while (Current.Tag != InputElementTag.Case && Current.Tag != InputElementTag.Default && Current.Tag != InputElementTag.RBrace) defaultLoc = defaultLoc.Union(Statement(defaultBody, false)); ConsumeCommentStatement(defaultBody); defaultc = new DefaultClause(defaultLoc, new Statements(defaultBody), cases.Count); } else throw IEError("switch statement", "'case' or 'default' or '}'"); } loc = loc.Union(Current.Loc); Consume(); statements.Add(new SwitchStatement(loc, value, cases, defaultc)); return loc; } case InputElementTag.Throw: { var loc = Current.Loc; Consume(); // ask for Current to make sure lastLineTerminator is updates var dummy = Current; var value = default(Expression); if (lastLineTerminator == null) { value = Expression(false); OptSemicolon("throw statement"); value = ConsumeCommentExpression(value); } else { value = Expression(false); value = ConsumeCommentExpression(value); } loc = loc.Union(value.Loc); statements.Add(new ThrowStatement(loc, value)); return loc; } case InputElementTag.Try: { var loc = Current.Loc; Consume(); var tryStatements = new Seq<Statement>(); BlockStatements("try statement", false, tryStatements); var catchc = default(CatchClause); var finallyc = default(FinallyClause); if (Current.Tag == InputElementTag.Catch) { var catchLoc = Current.Loc; Consume(); Only("catch clause", "'('", InputElementTag.LParen); if (Current.Tag != InputElementTag.Identifier) throw IEError("catch clasue", "identifier"); var name = new Identifier(Current.Loc, Current.Value); Consume(); Only("catch clause", "')'", InputElementTag.RParen); var catchBody = new Seq<Statement>(); catchLoc = catchLoc.Union(BlockStatements("catch clause", false, catchBody)); catchc = new CatchClause(catchLoc, name, new Statements(catchBody)); loc = loc.Union(catchLoc); } if (Current.Tag == InputElementTag.Finally) { var finallyLoc = Current.Loc; Consume(); var finallyBody = new Seq<Statement>(); finallyLoc = finallyLoc.Union(BlockStatements("finally clause", false, finallyBody)); finallyc = new FinallyClause(finallyLoc, new Statements(finallyBody)); loc = loc.Union(finallyLoc); } else if (catchc == null) throw IEError("try statement", "'catch' or 'finally'"); statements.Add(new TryStatement(loc, new Statements(tryStatements), catchc, finallyc)); return loc; } case InputElementTag.Function: { if (lexer.IsStrict && !isTop) throw MsgError("statement", "function declarations not permitted in nested blocks"); var loc = Current.Loc; Consume(); if (Current.Tag != InputElementTag.Identifier) throw IEError("function declaration", "identifier"); var name = new Identifier(Current.Loc, Current.Value); Consume(); if (Current.Tag != InputElementTag.LParen) throw IEError("function declaration", "'('"); var parameters = new Seq<Identifier>(); DelimitedList ("function declaration parameters", "',' or ')'", InputElementTag.Comma, InputElementTag.RParen, () => { if (Current.Tag != InputElementTag.Identifier) throw IEError("function declaration parameters", "identifier"); parameters.Add(new Identifier(Current.Loc, Current.Value)); Consume(); }); var body = new Seq<Statement>(); loc = loc.Union(BlockStatements("function declaration", true, body)); statements.Add(new FunctionDeclaration(loc, name, parameters, new Statements(body))); return loc; } default: { var expression = Expression(false); var loc = expression.Loc; OptSemicolon("expression statement"); expression = ConsumeCommentExpression(expression); statements.Add(new ExpressionStatement(loc, expression)); return loc; } } }
CatchClause ConvertCatch (Catch ctch) { CatchClause result = new CatchClause (); var location = LocationsBag.GetLocations (ctch); result.AddChild (new CSharpTokenNode (Convert (ctch.loc), "catch".Length), CatchClause.Roles.Keyword); if (ctch.TypeExpression != null) { if (location != null) result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), CatchClause.Roles.LPar); result.AddChild (ConvertToType (ctch.TypeExpression), CatchClause.Roles.Type); if (ctch.Variable != null && !string.IsNullOrEmpty (ctch.Variable.Name)) result.AddChild (new Identifier (ctch.Variable.Name, Convert (ctch.Variable.Location)), CatchClause.Roles.Identifier); if (location != null) result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), CatchClause.Roles.RPar); } result.AddChild ((BlockStatement)ctch.Block.Accept (this), CatchClause.Roles.Body); return result; }
public void VisitCatchClause(CatchClause catchClause) { JsonObject visitCatch = new JsonObject(); visitCatch.Comment = "VisitCatchClause"; AddKeyword(visitCatch, "catch-keyword", CatchClause.CatchKeywordRole); if (!catchClause.Type.IsNull) { visitCatch.AddJsonValue("type-info", GenTypeInfo(catchClause.Type)); if (!string.IsNullOrEmpty(catchClause.VariableName)) { visitCatch.AddJsonValue("identifier", GetIdentifier(catchClause.VariableNameToken)); } } visitCatch.AddJsonValue("catch-body", GenStatement(catchClause.Body)); Push(visitCatch); }
public virtual object VisitCatchClause(CatchClause catchClause, object data) { Debug.Assert((catchClause != null)); Debug.Assert((catchClause.TypeReference != null)); Debug.Assert((catchClause.StatementBlock != null)); Debug.Assert((catchClause.Condition != null)); nodeStack.Push(catchClause.TypeReference); catchClause.TypeReference.AcceptVisitor(this, data); catchClause.TypeReference = ((TypeReference)(nodeStack.Pop())); nodeStack.Push(catchClause.StatementBlock); catchClause.StatementBlock.AcceptVisitor(this, data); catchClause.StatementBlock = ((Statement)(nodeStack.Pop())); nodeStack.Push(catchClause.Condition); catchClause.Condition.AcceptVisitor(this, data); catchClause.Condition = ((Expression)(nodeStack.Pop())); return null; }
public void VisitCatchClause(CatchClause node) { VisitChildren(node); }
public virtual void VisitCatchClause(CatchClause catchClause) { StartNode(catchClause); WriteKeyword(CatchClause.CatchKeywordRole); if (!catchClause.Type.IsNull) { Space(policy.SpaceBeforeCatchParentheses); LPar(); Space(policy.SpacesWithinCatchParentheses); catchClause.Type.AcceptVisitor(this); if (!string.IsNullOrEmpty(catchClause.VariableName)) { Space(); WriteIdentifier(catchClause.VariableNameToken); } Space(policy.SpacesWithinCatchParentheses); RPar(); } if (!catchClause.Condition.IsNull) { Space(); WriteKeyword(CatchClause.WhenKeywordRole); Space(policy.SpaceBeforeIfParentheses); LPar(); Space(policy.SpacesWithinIfParentheses); catchClause.Condition.AcceptVisitor(this); Space(policy.SpacesWithinIfParentheses); RPar(); } WriteBlock(catchClause.Body, policy.StatementBraceStyle); EndNode(catchClause); }
public override void VisitCatchClause(CatchClause catchClause) { // Handled in TryCatchStatement }
public override void VisitCatchClause(CatchClause catchClause) { if (!catchClause.VariableNameToken.IsNull) AddVariable(catchClause.VariableNameToken, catchClause.VariableName); base.VisitCatchClause(catchClause); }
public virtual object VisitCatchClause(CatchClause catchClause, object data) { Debug.Assert((catchClause != null)); Debug.Assert((catchClause.TypeReference != null)); Debug.Assert((catchClause.StatementBlock != null)); Debug.Assert((catchClause.Condition != null)); catchClause.TypeReference.AcceptVisitor(this, data); catchClause.StatementBlock.AcceptVisitor(this, data); return catchClause.Condition.AcceptVisitor(this, data); }
public virtual void VisitCatchClause(CatchClause catchClause) { if (this.ThrowException) { throw (Exception)this.CreateException(catchClause); } }
private JsBlockStatement CompileCatchClause(LocalResolveResult catchVariable, CatchClause catchClause, bool isCatchAll, bool isOnly) { SetRegion(catchClause.GetRegion()); JsStatement variableDeclaration = null; if (!catchClause.VariableNameToken.IsNull) { JsExpression compiledAssignment; if (isCatchAll) // If this is the only handler we need to construct the exception compiledAssignment = isOnly ? _runtimeLibrary.MakeException(JsExpression.Identifier(_variables[catchVariable.Variable].Name), this) : JsExpression.Identifier(_variables[catchVariable.Variable].Name); else compiledAssignment = _runtimeLibrary.Downcast(JsExpression.Identifier(_variables[catchVariable.Variable].Name), _compilation.FindType(KnownTypeCode.Exception), _resolver.Resolve(catchClause.Type).Type, this); variableDeclaration = JsStatement.Var(_variables[((LocalResolveResult)_resolver.Resolve(catchClause.VariableNameToken)).Variable].Name, compiledAssignment); } var result = CreateInnerCompiler().Compile(catchClause.Body); if (variableDeclaration != null) result = JsStatement.Block(new[] { variableDeclaration }.Concat(result.Statements)); return result; }
TryStatement(BlockStatement body, CatchClause[] catchClauses, BlockStatement finallyBlock) : super(StatementKind.Try) {
public override void VisitTryCatchStatement (TryCatchStatement tryCatchStatement) { base.VisitTryCatchStatement (tryCatchStatement); var catches = tryCatchStatement.CatchClauses.ToList (); if (catches.Count == 0) return; var varName = catches.Where (x => !string.IsNullOrEmpty (x.VariableName)).Select (x => x.VariableName).FirstOrDefault (); if (varName == null) { varName = "_ex"; } // // Fix first // foreach (var c in catches) { if (string.IsNullOrEmpty (c.VariableName)) { c.VariableName = varName; } } // // Merge them // if (catches.Count > 0) { var body = new BlockStatement (); var newCatch = new CatchClause { VariableName = varName, Body = body, }; IfElseStatement lastIf = null; foreach (var c in catches) { var cbody = c.Body; cbody.Remove (); var iff = new IfElseStatement (GetNotNullTypeCheck (varName, c.Type), cbody); if (lastIf == null) body.Add (iff); else lastIf.FalseStatement = iff; lastIf = iff; c.Remove (); } var rethrow = new ThrowStatement (new IdentifierExpression (varName)); if (lastIf == null) body.Add (rethrow); else lastIf.FalseStatement = rethrow; tryCatchStatement.CatchClauses.Add (newCatch); } }
CatchClause ConvertCatch(Catch ctch) { var result = new CatchClause(); var location = LocationsBag.GetLocations(ctch); result.AddChild(new CSharpTokenNode(Convert(ctch.loc), CatchClause.CatchKeywordRole), CatchClause.CatchKeywordRole); if (ctch.TypeExpression != null) { if (location != null) result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar); if (ctch.TypeExpression != null) result.AddChild(ConvertToType(ctch.TypeExpression), Roles.Type); if (ctch.Variable != null && !string.IsNullOrEmpty(ctch.Variable.Name)) result.AddChild(Identifier.Create(ctch.Variable.Name, Convert(ctch.Variable.Location)), Roles.Identifier); if (location != null && location.Count > 1) result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar); } if (ctch.Block != null) result.AddChild((BlockStatement)ctch.Block.Accept(this), Roles.Body); return result; }
CatchClause ConvertCatch (Catch ctch) { CatchClause result = new CatchClause (); var location = LocationsBag.GetLocations (ctch); if (location != null) result.AddChild (new CSharpTokenNode (Convert (location[0]), "catch".Length), CatchClause.Roles.Keyword); if (ctch.Type_expr != null) { if (location != null) result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), CatchClause.Roles.LPar); result.AddChild ((INode)ctch.Type_expr.Accept (this), CatchClause.Roles.ReturnType); if (!string.IsNullOrEmpty (ctch.Name)) result.AddChild (new Identifier (ctch.Name, Convert (location[1])), CatchClause.Roles.Identifier); if (location != null) result.AddChild (new CSharpTokenNode (Convert (location[2]), 1), CatchClause.Roles.RPar); } result.AddChild ((INode)ctch.Block.Accept (this), CatchClause.Roles.Body); return result; }
IEnumerable<Statement> TransformNode(ILNode node) { if (node is ILLabel) { yield return new Ast.LabelStatement { Label = ((ILLabel)node).Name }; } else if (node is ILExpression) { List<ILRange> ilRanges = ILRange.OrderAndJoint(node.GetSelfAndChildrenRecursive<ILExpression>().SelectMany(e => e.ILRanges)); AstNode codeExpr = TransformExpression((ILExpression)node); if (codeExpr != null) { codeExpr = codeExpr.WithAnnotation(ilRanges); if (codeExpr is Ast.Expression) { yield return new Ast.ExpressionStatement { Expression = (Ast.Expression)codeExpr }; } else if (codeExpr is Ast.Statement) { yield return (Ast.Statement)codeExpr; } else { throw new Exception(); } } } else if (node is ILWhileLoop) { ILWhileLoop ilLoop = (ILWhileLoop)node; WhileStatement whileStmt = new WhileStatement() { Condition = ilLoop.Condition != null ? (Expression)TransformExpression(ilLoop.Condition) : new PrimitiveExpression(true), EmbeddedStatement = TransformBlock(ilLoop.BodyBlock) }; yield return whileStmt; } else if (node is ILCondition) { ILCondition conditionalNode = (ILCondition)node; bool hasFalseBlock = conditionalNode.FalseBlock.EntryGoto != null || conditionalNode.FalseBlock.Body.Count > 0; yield return new Ast.IfElseStatement { Condition = (Expression)TransformExpression(conditionalNode.Condition), TrueStatement = TransformBlock(conditionalNode.TrueBlock), FalseStatement = hasFalseBlock ? TransformBlock(conditionalNode.FalseBlock) : null }; } else if (node is ILSwitch) { ILSwitch ilSwitch = (ILSwitch)node; SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) }; foreach (var caseBlock in ilSwitch.CaseBlocks) { SwitchSection section = new SwitchSection(); if (caseBlock.Values != null) { section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, ilSwitch.Condition.InferredType) })); } else { section.CaseLabels.Add(new CaseLabel()); } section.Statements.Add(TransformBlock(caseBlock)); switchStmt.SwitchSections.Add(section); } yield return switchStmt; } else if (node is ILTryCatchBlock) { ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node); var tryCatchStmt = new Ast.TryCatchStatement(); tryCatchStmt.TryBlock = TransformBlock(tryCatchNode.TryBlock); foreach (var catchClause in tryCatchNode.CatchBlocks) { if (catchClause.ExceptionVariable == null && (catchClause.ExceptionType == null || catchClause.ExceptionType.MetadataType == MetadataType.Object)) { tryCatchStmt.CatchClauses.Add(new Ast.CatchClause { Body = TransformBlock(catchClause) }); } else { tryCatchStmt.CatchClauses.Add( new Ast.CatchClause { Type = AstBuilder.ConvertType(catchClause.ExceptionType), VariableName = catchClause.ExceptionVariable == null ? null : catchClause.ExceptionVariable.Name, Body = TransformBlock(catchClause) }); } } if (tryCatchNode.FinallyBlock != null) tryCatchStmt.FinallyBlock = TransformBlock(tryCatchNode.FinallyBlock); if (tryCatchNode.FaultBlock != null) { CatchClause cc = new CatchClause(); cc.Body = TransformBlock(tryCatchNode.FaultBlock); cc.Body.Add(new ThrowStatement()); // rethrow tryCatchStmt.CatchClauses.Add(cc); } yield return tryCatchStmt; } else if (node is ILFixedStatement) { ILFixedStatement fixedNode = (ILFixedStatement)node; FixedStatement fixedStatement = new FixedStatement(); foreach (ILExpression initializer in fixedNode.Initializers) { Debug.Assert(initializer.Code == ILCode.Stloc); ILVariable v = (ILVariable)initializer.Operand; fixedStatement.Variables.Add( new VariableInitializer { Name = v.Name, Initializer = (Expression)TransformExpression(initializer.Arguments[0]) }.WithAnnotation(v)); } fixedStatement.Type = AstBuilder.ConvertType(((ILVariable)fixedNode.Initializers[0].Operand).Type); fixedStatement.EmbeddedStatement = TransformBlock(fixedNode.BodyBlock); yield return fixedStatement; } else if (node is ILBlock) { yield return TransformBlock((ILBlock)node); } else { throw new Exception("Unknown node type"); } }
public virtual object VisitCatchClause(CatchClause catchClause, object data) { throw new global::System.NotImplementedException("CatchClause"); }
public virtual void VisitCatchClause (CatchClause catchClause) { VisitChildren (catchClause); }
private CatchClause ParseCatchClause(TokenSet followers, ref bool seenEmptyCatch) //^ requires this.currentToken == Token.Catch; //^ ensures followers[this.currentToken] || this.currentToken == Token.EndOfFile; { if (seenEmptyCatch) this.HandleError(Error.TooManyCatches); SourceLocationBuilder slb = new SourceLocationBuilder(this.scanner.SourceLocationOfLastScannedToken); this.GetNextToken(); TypeExpression exeptionType; NameDeclaration/*?*/ name = null; if (this.currentToken == Token.LeftParenthesis) { this.Skip(Token.LeftParenthesis); exeptionType = this.ParseTypeExpression(false, false, followers|Token.Identifier|Token.RightParenthesis); if (Parser.IdentifierOrNonReservedKeyword[this.currentToken]) name = this.ParseNameDeclaration(); this.Skip(Token.RightParenthesis); } else { exeptionType = this.GetTypeExpressionFor(Token.Object, slb.GetSourceLocation()); } BlockStatement body = this.ParseBlock(followers); slb.UpdateToSpan(body.SourceLocation); CatchClause result = new CatchClause(exeptionType, null, name, body, slb); //^ assume followers[this.currentToken] || this.currentToken == Token.EndOfFile; return result; }
public void VisitCatchClause(CatchClause catchClause) { StartNode(catchClause); WriteKeyword(CatchClause.CatchKeywordRole); if (!catchClause.Type.IsNull) { Space(policy.SpaceBeforeCatchParentheses); LPar(); Space(policy.SpacesWithinCatchParentheses); catchClause.Type.AcceptVisitor(this); if (!string.IsNullOrEmpty(catchClause.VariableName)) { Space(); catchClause.VariableNameToken.AcceptVisitor(this); } Space(policy.SpacesWithinCatchParentheses); RPar(); } catchClause.Body.AcceptVisitor(this); EndNode(catchClause); }
public virtual object TrackedVisitCatchClause(CatchClause catchClause, object data) { return base.VisitCatchClause(catchClause, data); }