Beispiel #1
0
 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;
 }
Beispiel #2
0
 public override void OnTryStatement(TryStatement node)
 {
     if (0 == node.ProtectedBlock.Statements.Count)
     {
         if (null != node.EnsureBlock && node.EnsureBlock.Statements.Count > 0)
         {
             ReplaceCurrentNode(node.EnsureBlock);
         }
         else
         {
             RemoveCurrentNode();
         }
     }
     else
     {
         base.OnTryStatement(node);
     }
 }
Beispiel #3
0
 public override void OnTryStatement(TryStatement node)
 {
     if (node.ProtectedBlock.IsEmpty)
     {
         if (null != node.EnsureBlock && !node.EnsureBlock.IsEmpty)
         {
             ReplaceCurrentNode(node.EnsureBlock);
         }
         else
         {
             RemoveCurrentNode();
         }
     }
     else
     {
         base.OnTryStatement(node);
     }
 }
        public override void LeaveTryStatement(TryStatement node)
        {
            base.LeaveTryStatement(node);

            Pop(node.ProtectedBlock.EndSourceLocation.Line);
        }
Beispiel #5
0
        //throws RecognitionException, TokenStreamException
        protected Block exception_handler(
            TryStatement t
            )
        {
            Block lastBlock;

            IToken  c = null;
            IToken  x = null;
            IToken  u = null;

                ExceptionHandler eh = null;
                TypeReference tr = null;
                Expression e = null;
                lastBlock = null;

            try {      // for error handling
            c = LT(1);
            match(EXCEPT);
            {
                switch ( LA(1) )
                {
                case ID:
                {
                    x = LT(1);
                    match(ID);
                    break;
                }
                case AS:
                case IF:
                case UNLESS:
                case COLON:
                {
                    break;
                }
                default:
                {
                    throw new NoViableAltException(LT(1), getFilename());
                }
                 }
            }
            {
                switch ( LA(1) )
                {
                case AS:
                {
                    match(AS);
                    tr=type_reference();
                    break;
                }
                case IF:
                case UNLESS:
                case COLON:
                {
                    break;
                }
                default:
                {
                    throw new NoViableAltException(LT(1), getFilename());
                }
                 }
            }
            {
                switch ( LA(1) )
                {
                case IF:
                case UNLESS:
                {
                    {
                        switch ( LA(1) )
                        {
                        case IF:
                        {
                            match(IF);
                            break;
                        }
                        case UNLESS:
                        {
                            u = LT(1);
                            match(UNLESS);
                            break;
                        }
                        default:
                        {
                            throw new NoViableAltException(LT(1), getFilename());
                        }
                         }
                    }
                    e=expression();
                    break;
                }
                case COLON:
                {
                    break;
                }
                default:
                {
                    throw new NoViableAltException(LT(1), getFilename());
                }
                 }
            }
            begin();
            if (0==inputState.guessing)
            {

                        eh = new ExceptionHandler(SourceLocationFactory.ToLexicalInfo(c));

                        eh.Declaration = new Declaration();
                        eh.Declaration.Type = tr;

                        if (x != null)
                        {
                            eh.Declaration.LexicalInfo = SourceLocationFactory.ToLexicalInfo(x);
                            eh.Declaration.Name = x.getText();
                        }
                        else
                        {
                            eh.Declaration.Name = null;
                            eh.Flags |= ExceptionHandlerFlags.Anonymous;
                        }
                        if (tr != null)
                        {
                            eh.Declaration.LexicalInfo = tr.LexicalInfo;
                        }
                        else if (x != null)
                        {
                            eh.Declaration.LexicalInfo = eh.LexicalInfo;
                        }
                        if(tr == null)
                        {
                            eh.Flags |= ExceptionHandlerFlags.Untyped;
                        }
                        if (e != null)
                        {
                            if(u != null)
                            {
                                UnaryExpression not = new UnaryExpression(SourceLocationFactory.ToLexicalInfo(u));
                                not.Operator = UnaryOperatorType.LogicalNot;
                                not.Operand = e;
                                e = not;
                            }
                            eh.FilterCondition = e;
                            eh.Flags |= ExceptionHandlerFlags.Filter;
                        }
                        eh.Block = new Block(SourceLocationFactory.ToLexicalInfo(c));

            }
            block(eh.Block.Statements);
            if (0==inputState.guessing)
            {

                        lastBlock = eh.Block;
                        t.ExceptionHandlers.Add(eh);

            }
            }
            catch (RecognitionException ex)
            {
            if (0 == inputState.guessing)
            {
                reportError(ex);
                recover(ex,tokenSet_95_);
            }
            else
            {
                throw ex;
            }
            }
            return lastBlock;
        }
Beispiel #6
0
        public override void OnTryStatement(TryStatement node)
        {
            ++_tryBlock;
            Label end = _il.BeginExceptionBlock();

            // The fault handler isn't very well supported by the
            // the ILGenerator. Thus, when there is a failure block
            // in the same try as an except or ensure block, we
            // need to do some special brute forcing with the exception
            // block context in the ILGenerator.
            if(null != node.FailureBlock && null != node.EnsureBlock)
            {
                ++_tryBlock;
                _il.BeginExceptionBlock();
            }

            if(null != node.FailureBlock && node.ExceptionHandlers.Count > 0)
            {
                ++_tryBlock;
                _il.BeginExceptionBlock();
            }

            Visit(node.ProtectedBlock);

            Visit(node.ExceptionHandlers);

            if(null != node.FailureBlock)
            {
                // Logic to back out of the manually forced blocks
                if(node.ExceptionHandlers.Count > 0)
                {
                    _il.EndExceptionBlock();
                    --_tryBlock;
                }

                _il.BeginFaultBlock();
                Visit(node.FailureBlock);

                // Logic to back out of the manually forced blocks once more
                if(null != node.EnsureBlock)
                {
                    _il.EndExceptionBlock();
                    --_tryBlock;
                }
            }

            if (null != node.EnsureBlock)
            {
                _il.BeginFinallyBlock();
                Visit(node.EnsureBlock);
            }

            _il.EndExceptionBlock();
            --_tryBlock;
        }
        public override void OnDestructor(Destructor node)
        {
            Method finalizer = CodeBuilder.CreateMethod(
                "Finalize",
                TypeSystemServices.VoidType,
                TypeMemberModifiers.Protected | TypeMemberModifiers.Override);
            finalizer.LexicalInfo = node.LexicalInfo;

            MethodInvocationExpression mie = new MethodInvocationExpression(new SuperLiteralExpression());

            Block bodyNew = new Block();
            Block ensureBlock = new Block();
            ensureBlock.Add (mie);

            TryStatement tryStatement = new TryStatement();
            tryStatement.EnsureBlock = ensureBlock;
            tryStatement.ProtectedBlock = node.Body;

            bodyNew.Add(tryStatement);
            finalizer.Body = bodyNew;

            node.ParentNode.Replace(node, finalizer);
        }
Beispiel #8
0
        //throws RecognitionException, TokenStreamException
        protected TryStatement try_stmt()
        {
            TryStatement s;

            IToken  t = null;
            IToken  ftoken = null;
            IToken  etoken = null;

                s = null;
                Block eblock = null;
                Block lastBlock = null;

            try {      // for error handling
            t = LT(1);
            match(TRY);
            if (0==inputState.guessing)
            {
                s = new TryStatement(SourceLocationFactory.ToLexicalInfo(t));
            }
            begin();
            if (0==inputState.guessing)
            {
                s.ProtectedBlock = new Block();
            }
            block(s.ProtectedBlock.Statements);
            if (0==inputState.guessing)
            {
                lastBlock = s.ProtectedBlock;
            }
            {    // ( ... )*
                for (;;)
                {
                    if ((LA(1)==EXCEPT))
                    {
                        lastBlock=exception_handler(s);
                    }
                    else
                    {
                        goto _loop315_breakloop;
                    }

                }
            _loop315_breakloop:				;
            }    // ( ... )*
            {
                switch ( LA(1) )
                {
                case FAILURE:
                {
                    ftoken = LT(1);
                    match(FAILURE);
                    if (0==inputState.guessing)
                    {
                        eblock = new Block(SourceLocationFactory.ToLexicalInfo(ftoken));
                    }
                    begin();
                    block(eblock.Statements);
                    if (0==inputState.guessing)
                    {
                        s.FailureBlock = lastBlock = eblock;
                    }
                    break;
                }
                case END:
                case ENSURE:
                {
                    break;
                }
                default:
                {
                    throw new NoViableAltException(LT(1), getFilename());
                }
                 }
            }
            {
                switch ( LA(1) )
                {
                case ENSURE:
                {
                    etoken = LT(1);
                    match(ENSURE);
                    if (0==inputState.guessing)
                    {
                        eblock = new Block(SourceLocationFactory.ToLexicalInfo(etoken));
                    }
                    begin();
                    block(eblock.Statements);
                    if (0==inputState.guessing)
                    {
                        s.EnsureBlock = lastBlock = eblock;
                    }
                    break;
                }
                case END:
                {
                    break;
                }
                default:
                {
                    throw new NoViableAltException(LT(1), getFilename());
                }
                 }
            }
            end(lastBlock);
            }
            catch (RecognitionException ex)
            {
            if (0 == inputState.guessing)
            {
                reportError(ex);
                recover(ex,tokenSet_79_);
            }
            else
            {
                throw ex;
            }
            }
            return s;
        }
Beispiel #9
0
	protected TryStatement  try_stmt() //throws RecognitionException, TokenStreamException
{
		TryStatement s;
		
		IToken  t = null;
		IToken  ftoken = null;
		IToken  etoken = null;
		
				s = null;		
				Block sblock = null;
				Block eblock = null;
			
		
		try {      // for error handling
			t = LT(1);
			match(TRY);
			if (0==inputState.guessing)
			{
				s = new TryStatement(ToLexicalInfo(t));
			}
			compound_stmt(s.ProtectedBlock);
			{    // ( ... )*
				for (;;)
				{
					if ((LA(1)==EXCEPT))
					{
						exception_handler(s);
					}
					else
					{
						goto _loop369_breakloop;
					}
					
				}
_loop369_breakloop:				;
			}    // ( ... )*
			{
				switch ( LA(1) )
				{
				case FAILURE:
				{
					ftoken = LT(1);
					match(FAILURE);
					if (0==inputState.guessing)
					{
						eblock = new Block(ToLexicalInfo(ftoken));
					}
					compound_stmt(eblock);
					if (0==inputState.guessing)
					{
						s.FailureBlock = eblock;
					}
					break;
				}
				case EOF:
				case DEDENT:
				case ESEPARATOR:
				case ASSEMBLY_ATTRIBUTE_BEGIN:
				case MODULE_ATTRIBUTE_BEGIN:
				case ABSTRACT:
				case BREAK:
				case CONTINUE:
				case CALLABLE:
				case CAST:
				case CHAR:
				case CLASS:
				case CONSTRUCTOR:
				case DEF:
				case DESTRUCTOR:
				case ENSURE:
				case ENUM:
				case EVENT:
				case FINAL:
				case FOR:
				case FALSE:
				case GOTO:
				case INTERFACE:
				case INTERNAL:
				case IF:
				case NEW:
				case NULL:
				case OVERRIDE:
				case PARTIAL:
				case PUBLIC:
				case PROTECTED:
				case PRIVATE:
				case RAISE:
				case RETURN:
				case SELF:
				case SUPER:
				case STATIC:
				case STRUCT:
				case THEN:
				case TRY:
				case TRANSIENT:
				case TRUE:
				case TYPEOF:
				case UNLESS:
				case VIRTUAL:
				case WHILE:
				case YIELD:
				case TRIPLE_QUOTED_STRING:
				case LPAREN:
				case DOUBLE_QUOTED_STRING:
				case SINGLE_QUOTED_STRING:
				case ID:
				case MULTIPLY:
				case LBRACK:
				case SPLICE_BEGIN:
				case DOT:
				case COLON:
				case LBRACE:
				case QQ_BEGIN:
				case SUBTRACT:
				case LONG:
				case INCREMENT:
				case DECREMENT:
				case ONES_COMPLEMENT:
				case INT:
				case BACKTICK_QUOTED_STRING:
				case RE_LITERAL:
				case DOUBLE:
				case FLOAT:
				case TIMESPAN:
				{
					break;
				}
				default:
				{
					throw new NoViableAltException(LT(1), getFilename());
				}
				 }
			}
			{
				switch ( LA(1) )
				{
				case ENSURE:
				{
					etoken = LT(1);
					match(ENSURE);
					if (0==inputState.guessing)
					{
						eblock = new Block(ToLexicalInfo(etoken));
					}
					compound_stmt(eblock);
					if (0==inputState.guessing)
					{
						s.EnsureBlock = eblock;
					}
					break;
				}
				case EOF:
				case DEDENT:
				case ESEPARATOR:
				case ASSEMBLY_ATTRIBUTE_BEGIN:
				case MODULE_ATTRIBUTE_BEGIN:
				case ABSTRACT:
				case BREAK:
				case CONTINUE:
				case CALLABLE:
				case CAST:
				case CHAR:
				case CLASS:
				case CONSTRUCTOR:
				case DEF:
				case DESTRUCTOR:
				case ENUM:
				case EVENT:
				case FINAL:
				case FOR:
				case FALSE:
				case GOTO:
				case INTERFACE:
				case INTERNAL:
				case IF:
				case NEW:
				case NULL:
				case OVERRIDE:
				case PARTIAL:
				case PUBLIC:
				case PROTECTED:
				case PRIVATE:
				case RAISE:
				case RETURN:
				case SELF:
				case SUPER:
				case STATIC:
				case STRUCT:
				case THEN:
				case TRY:
				case TRANSIENT:
				case TRUE:
				case TYPEOF:
				case UNLESS:
				case VIRTUAL:
				case WHILE:
				case YIELD:
				case TRIPLE_QUOTED_STRING:
				case LPAREN:
				case DOUBLE_QUOTED_STRING:
				case SINGLE_QUOTED_STRING:
				case ID:
				case MULTIPLY:
				case LBRACK:
				case SPLICE_BEGIN:
				case DOT:
				case COLON:
				case LBRACE:
				case QQ_BEGIN:
				case SUBTRACT:
				case LONG:
				case INCREMENT:
				case DECREMENT:
				case ONES_COMPLEMENT:
				case INT:
				case BACKTICK_QUOTED_STRING:
				case RE_LITERAL:
				case DOUBLE:
				case FLOAT:
				case TIMESPAN:
				{
					break;
				}
				default:
				{
					throw new NoViableAltException(LT(1), getFilename());
				}
				 }
			}
		}
		catch (RecognitionException ex)
		{
			if (0 == inputState.guessing)
			{
				reportError(ex, "try_stmt");
				recover(ex,tokenSet_84_);
			}
			else
			{
				throw ex;
			}
		}
		return s;
	}
 public void finally_block(TryStatement s)
 {
     IToken token = null;
     try
     {
         Block block;
         token = this.LT(1);
         this.match(0x11);
         if (base.inputState.guessing == 0)
         {
             Block block2;
             s.set_EnsureBlock(block2 = new Block(ToLexicalInfo(token)));
             block = block2;
         }
         this.compound_or_single_stmt(block);
     }
     catch (RecognitionException exception)
     {
         if (base.inputState.guessing != 0)
         {
             throw;
         }
         this.reportError(exception);
         this.recover(exception, tokenSet_15_);
     }
 }
		IMethod CreateDisposeMethod()
		{
			BooMethodBuilder mn = _enumerator.AddVirtualMethod("Dispose", TypeSystemServices.VoidType);
			mn.Method.LexicalInfo = this.LexicalInfo;
			
			LabelStatement noEnsure = CodeBuilder.CreateLabel(_generator.Method, "noEnsure").LabelStatement;
			mn.Body.Add(noEnsure);
			mn.Body.Add(SetStateTo(_finishedStateNumber));
			mn.Body.Add(new ReturnStatement());
			
			// Create a section calling all ensure methods for each converted try block
			LabelStatement[] disposeLabels = new LabelStatement[_labels.Count];
			for (int i = 0; i < _convertedTryStatements.Count; i++) {
				TryStatementInfo info = _convertedTryStatements[i];
				disposeLabels[info._stateNumber] = CodeBuilder.CreateLabel(_generator.Method, "$ensure_" + info._stateNumber).LabelStatement;
				mn.Body.Add(disposeLabels[info._stateNumber]);
				mn.Body.Add(SetStateTo(_finishedStateNumber));
				Block block = mn.Body;
				while (info._parent != null) {
					TryStatement ts = new TryStatement();
					block.Add(ts);
					ts.ProtectedBlock.Add(CallMethodOnSelf(info._ensureMethod));
					block = ts.EnsureBlock = new Block();
					info = info._parent;
				}
				block.Add(CallMethodOnSelf(info._ensureMethod));
				mn.Body.Add(new ReturnStatement());
			}
			
			// now map the labels of the suspended states to the labels we just created
			for (int i = 0; i < _labels.Count; i++) {
				if (_tryStatementInfoForLabels[i] == null)
					disposeLabels[i] = noEnsure;
				else
					disposeLabels[i] = disposeLabels[_tryStatementInfoForLabels[i]._stateNumber];
			}
			
			mn.Body.Insert(0, CodeBuilder.CreateSwitch(
			                  	this.LexicalInfo,
			                  	CodeBuilder.CreateMemberReference(_state),
			                  	disposeLabels));
			return mn.Entity;
		}
		public override void LeaveTryStatement(TryStatement node)
		{
			TryStatementInfo info = _tryStatementStack.Pop();
			if (info._containsYield) {
				ReplaceCurrentNode(info._replacement);
				TryStatementInfo currentTry = (_tryStatementStack.Count > 0) ? _tryStatementStack.Peek() : null;
				info._replacement.Add(node.ProtectedBlock);
				if (currentTry != null) {
					ConvertTryStatement(currentTry);
					info._replacement.Add(SetStateTo(currentTry._stateNumber));
				} else {
					// leave try block, reset state to prevent ensure block from being called again
					info._replacement.Add(SetStateTo(_finishedStateNumber));
				}
				BooMethodBuilder ensureMethod = _enumerator.AddMethod("$ensure" + info._stateNumber, TypeSystemServices.VoidType, TypeMemberModifiers.Private);
				ensureMethod.Body.Add(info._statement.EnsureBlock);
				info._ensureMethod = ensureMethod.Entity;
				info._replacement.Add(CallMethodOnSelf(ensureMethod.Entity));
				_convertedTryStatements.Add(info);
			}
		}
Beispiel #13
0
		override public object Clone()
		{
		
			TryStatement clone = new TryStatement();
			clone._lexicalInfo = _lexicalInfo;
			clone._endSourceLocation = _endSourceLocation;
			clone._documentation = _documentation;
			clone._isSynthetic = _isSynthetic;
			clone._entity = _entity;
			if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
			if (null != _modifier)
			{
				clone._modifier = _modifier.Clone() as StatementModifier;
				clone._modifier.InitializeParent(clone);
			}
			if (null != _protectedBlock)
			{
				clone._protectedBlock = _protectedBlock.Clone() as Block;
				clone._protectedBlock.InitializeParent(clone);
			}
			if (null != _exceptionHandlers)
			{
				clone._exceptionHandlers = _exceptionHandlers.Clone() as ExceptionHandlerCollection;
				clone._exceptionHandlers.InitializeParent(clone);
			}
			if (null != _failureBlock)
			{
				clone._failureBlock = _failureBlock.Clone() as Block;
				clone._failureBlock.InitializeParent(clone);
			}
			if (null != _ensureBlock)
			{
				clone._ensureBlock = _ensureBlock.Clone() as Block;
				clone._ensureBlock.InitializeParent(clone);
			}
			return clone;


		}
        public override bool EnterTryStatement(TryStatement node)
        {
            Push(new TryTreeNode(new EntitySourceOrigin(GetEntity(node))), node.LexicalInfo.Line);

            return base.EnterTryStatement(node);
        }
		override public void LeaveForStatement(ForStatement node)
		{
			_iteratorNode = node.Iterator;
			CurrentEnumeratorType = GetExpressionType(node.Iterator);

			if (null == CurrentBestEnumeratorType)
				return; //error

			DeclarationCollection declarations = node.Declarations;
			Block body = new Block(node.LexicalInfo);

			InternalLocal iterator = CodeBuilder.DeclareLocal(_current,
				Context.GetUniqueName("iterator"),
				CurrentBestEnumeratorType);

			if (CurrentBestEnumeratorType == CurrentEnumeratorType)
			{
				//$iterator = <node.Iterator>
				body.Add(
					CodeBuilder.CreateAssignment(
						node.LexicalInfo,
						CodeBuilder.CreateReference(iterator),
						node.Iterator));
			}
			else
			{
				//$iterator = <node.Iterator>.GetEnumerator()
				body.Add(
					CodeBuilder.CreateAssignment(
						node.LexicalInfo,
						CodeBuilder.CreateReference(iterator),
						CodeBuilder.CreateMethodInvocation(node.Iterator, CurrentBestGetEnumerator)));
			}

			// while __iterator.MoveNext():
			if (null == CurrentBestMoveNext)
				return; //error
			WhileStatement ws = new WhileStatement(node.LexicalInfo);
			ws.Condition = CodeBuilder.CreateMethodInvocation(
				CodeBuilder.CreateReference(iterator),
				CurrentBestMoveNext);

			if (null == CurrentBestGetCurrent)
				return; //error
			Expression current = CodeBuilder.CreateMethodInvocation(
				CodeBuilder.CreateReference(iterator),
				CurrentBestGetCurrent);

			if (1 == declarations.Count)
			{
				//	item = __iterator.Current
				ws.Block.Add(
					CodeBuilder.CreateAssignment(
						node.LexicalInfo,
						CodeBuilder.CreateReference((InternalLocal)declarations[0].Entity),
						current));
			}
			else
			{
				UnpackExpression(ws.Block,
				                 CodeBuilder.CreateCast(
				                 	CurrentEnumeratorItemType,
				                 	current),
				                 node.Declarations);
			}
			
			ws.Block.Add(node.Block);
			ws.OrBlock = node.OrBlock;
			ws.ThenBlock = node.ThenBlock;
			
			// try:
			//   while...
			// ensure:
			//   d = iterator as IDisposable
			//   d.Dispose() unless d is null
			if (IsAssignableFrom(TypeSystemServices.IDisposableType, CurrentBestEnumeratorType))
			{
				TryStatement tryStatement = new TryStatement();
				tryStatement.ProtectedBlock.Add(ws);
				tryStatement.EnsureBlock = new Block();
			
				CastExpression castExpression = new CastExpression();
				castExpression.Type = CodeBuilder.CreateTypeReference(TypeSystemServices.IDisposableType);
				castExpression.Target = CodeBuilder.CreateReference(iterator);
				castExpression.ExpressionType = TypeSystemServices.IDisposableType;
				tryStatement.EnsureBlock.Add(
					CodeBuilder.CreateMethodInvocation(castExpression, IDisposable_Dispose));

				body.Add(tryStatement);
			}
			else
			{
				body.Add(ws);
			}

			ReplaceCurrentNode(body);
		}
Beispiel #16
0
        protected override Statement ExpandImpl(MacroStatement macro){
            if (macro.Arguments.Count == 0){
                throw new Exception("need at least one IEnumerable parameter");
            }

            var result = new Block();
            Expression src = macro.Arguments[0];

            var idx = new ReferenceExpression("_idx");
            Expression item = new ReferenceExpression("i");
            var col = new ReferenceExpression("current_collection");
            if (src is BinaryExpression){
                item = ((BinaryExpression) src).Left;
                src = ((BinaryExpression) src).Right;
            }

            if (macro.Arguments.Count > 1){
                idx = (ReferenceExpression) macro.Arguments[1];
            }

            string prefix = macro.get<string>("_prefix") ?? "";
            string suffix = macro.get<string>("_suffix") ?? "";


            Func<string, MacroStatement> findmacro = s =>{
                                                         var r = macro.get<Node>(s);
                                                         if (null == r){
                                                             return null;
                                                         }
                                                         if (!(r is MacroStatement)){
                                                             var m = new MacroStatement("stub");
                                                             m.Body = new Block().add(r);
                                                             r = m;
                                                         }

                                                         return (MacroStatement) r;
                                                     };
            Func<MacroStatement, Block> extract = m =>{
                                                      if (null == m){
                                                          return null;
                                                      }
                                                      if (m.Body != null && !m.Body.IsEmpty){
                                                          if (m.Body.Statements.Count == 1){
                                                              if (m.Body.Statements[0] is ExpressionStatement){
                                                                  Expression _ex =
                                                                      ((ExpressionStatement) m.Body.Statements[0]).
                                                                          Expression;
                                                                  if (_ex is LiteralExpression ||
                                                                      !_ex.ToCodeString().ToLower().StartsWith("out")){
                                                                      return new Block().add(_ex.writeOut());
                                                                  }
                                                              }
                                                          }
                                                          return m.Body;
                                                      }
                                                      if (m.Arguments.Count == 0){
                                                          return null;
                                                      }
                                                      var r = new Block();
                                                      if (!(m.Arguments[0] is MethodInvocationExpression)){
                                                          r.Add(BrailBuildingHelper.WriteOut(m.Arguments[0]));
                                                      }
                                                      else{
                                                          r.Add(m.Arguments[0]);
                                                      }

                                                      return r;
                                                  };

            MacroStatement beforeall_macro = findmacro("beforeall");
            MacroStatement onitem_macro = findmacro("onitem") ?? macro;
            MacroStatement onerror_macro = findmacro("onerror");
            ;
            MacroStatement between_macro = findmacro("between");
            ;
            MacroStatement afterall_macro = findmacro("afterall");
            ;
            MacroStatement onempty_macro = findmacro("onempty");
            ;
            MacroStatement beforeeach_macro = findmacro("beforeeach");
            ;
            MacroStatement aftereach_macro = findmacro("aftereach");

            MacroStatement prepare_macro = findmacro("prepare");
            ;

            Block beforeall = extract(beforeall_macro);
            Block onitem = extractMainItemBlock(macro, extract, onitem_macro, item, prefix, suffix);
            Block onerror = extract(onerror_macro);
            Block between = extract(between_macro);
            Block afterall = extract(afterall_macro);
            Block onempty = null;

            bool proceed_on_empty = false;
            if (onempty_macro != null && onempty_macro.Arguments.Count != 0 &&
                onempty_macro.Arguments[0].ToCodeString() == "proceed"){
                proceed_on_empty = true;
            }
            else{
                onempty = extract(onempty_macro);
            }
            Block beforeeach = extract(beforeeach_macro);
            Block aftereach = extract(aftereach_macro);


//          _idx = 0

            Statement betweener = getBetweener(idx, between);
            result.Add(col.assign(new MethodInvocationExpression(new ReferenceExpression("_wrapcollection"), src)));
            result.Add(new ReferenceExpression("___proceed").assign(new BoolLiteralExpression(proceed_on_empty)));
            var mainblock = new Block();
            mainblock.Add(idx.assign(0));
            mainblock.Add(new IfStatement(
                              new BinaryExpression(BinaryOperatorType.Equality, new NullLiteralExpression(), col),
                              new Block().add(new BinaryExpression(BinaryOperatorType.Assign, col,
                                                                   new MethodInvocationExpression(
                                                                       new ReferenceExpression("_wrapcollection"),
                                                                       new ArrayLiteralExpression()))),
                              null
                              ));
            if (beforeall != null){
                mainblock.Add(beforeall);
            }
            var maincycle = new ForStatement();
            maincycle.Iterator = col;
            string declname = item.ToCodeString();
            TypeReference decltype = null;
            if (item is TryCastExpression){
                declname = ((TryCastExpression) item).Target.ToCodeString();
                decltype = ((TryCastExpression) item).Type;
            }
            maincycle.Declarations.Add(new Declaration(maincycle.LexicalInfo, declname, decltype));
            maincycle.Block = new Block();
            maincycle.ThenBlock = afterall;

            if (betweener != null){
                maincycle.Block.Add(betweener);
            }
            if (null != prepare_macro){
                maincycle.Block.Add(prepare_macro.Body);
            }
            if (null != beforeeach){
                maincycle.Block.Add(beforeeach);
            }
            if (onerror == null){
                maincycle.Block.Add(onitem);
            }
            else{
                var trycatch = new TryStatement();
                var exchandler = new ExceptionHandler();
                exchandler.Block = onerror;
                exchandler.Declaration = new Declaration("_ex", new SimpleTypeReference("System.Exception"));
                trycatch.ProtectedBlock = onitem;
                trycatch.ExceptionHandlers.Add(exchandler);
                maincycle.Block.Add(trycatch);
            }
            if (null != aftereach){
                maincycle.Block.Add(aftereach);
            }
            maincycle.Block.Add(new UnaryExpression(UnaryOperatorType.Increment, idx));

            mainblock.Add(maincycle);

            result.Add(
                new IfStatement(
                    getMainCondition(col),
                    mainblock,
                    onempty
                    )
                );

//          if null!=items and (items as IEnumerable).Cast[of System.Object]().Count() != 0:

            return result;
        }
Beispiel #17
0
        public override void OnTryStatement(TryStatement node)
        {
            WriteIndented();
            WriteKeyword("try:");
            WriteLine();
            Indent();
            WriteBlockStatements(node.ProtectedBlock);
            Dedent();
            Visit(node.ExceptionHandlers);

            if (null != node.FailureBlock)
            {
                WriteIndented();
                WriteKeyword("failure:");
                WriteLine();
                Indent();
                WriteBlockStatements(node.FailureBlock);
                Dedent();
            }

            if (null != node.EnsureBlock)
            {
                WriteIndented();
                WriteKeyword("ensure:");
                WriteLine();
                Indent();
                WriteBlockStatements(node.EnsureBlock);
                Dedent();
            }

            if(IsWhiteSpaceAgnostic)
            {
                WriteEnd();
            }
        }
		public object VisitTryCatchStatement(TryCatchStatement tryCatchStatement, object data)
		{
			B.TryStatement t = new B.TryStatement(GetLexicalInfo(tryCatchStatement));
			t.EndSourceLocation = GetLocation(tryCatchStatement.EndLocation);
			t.ProtectedBlock = ConvertBlock(tryCatchStatement.StatementBlock);
			t.EnsureBlock = ConvertBlock(tryCatchStatement.FinallyBlock);
			foreach (CatchClause clause in tryCatchStatement.CatchClauses) {
				B.ExceptionHandler handler = new B.ExceptionHandler(GetLexicalInfo(clause));
				handler.Block = ConvertBlock(clause.StatementBlock);
				B.TypeReference typeRef = ConvertTypeReference(clause.TypeReference);
				string name = clause.VariableName;
				if (typeRef != null) {
					if (name == null || name.Length == 0)
						name = GenerateName();
					handler.Declaration = new B.Declaration(name, typeRef);
				} else {
					if (name != null && name.Length > 0)
						handler.Declaration = new B.Declaration(name, null);
				}
				t.ExceptionHandlers.Add(handler);
			}
			return t;
		}
        public void try_statement(Block container)
        {
            IToken token = null;
            IToken token2 = null;
            IToken token3 = null;
            try
            {
                TryStatement statement;
                Block block;
                token = this.LT(1);
                this.match(0x2b);
                if (base.inputState.guessing == 0)
                {
                    statement = new TryStatement(ToLexicalInfo(token));
                    block = statement.get_ProtectedBlock();
                    container.Add(statement);
                }
                this.compound_or_single_stmt(block);
                while (true)
                {
                    TypeReference reference;
                    if ((this.LA(1) != 7) || (this.LA(2) != 0x3f))
                    {
                        break;
                    }
                    token2 = this.LT(1);
                    this.match(7);
                    this.match(0x3f);
                    token3 = this.LT(1);
                    this.match(0x3b);
                    switch (this.LA(1))
                    {
                        case 0x42:
                            this.match(0x42);
                            reference = this.type_reference();
                            break;

                        case 0x40:
                            break;

                        default:
                            throw new NoViableAltException(this.LT(1), this.getFilename());
                    }
                    this.match(0x40);
                    if (base.inputState.guessing == 0)
                    {
                        Declaration declaration;
                        ExceptionHandler handler;
                        if (reference == null)
                        {
                            reference = new SimpleTypeReference(ToLexicalInfo(token3), "System.Exception");
                        }
                        ExceptionHandler handler1 = handler = new ExceptionHandler(ToLexicalInfo(token2));
                        Declaration declaration1 = declaration = new Declaration(ToLexicalInfo(token3));
                        declaration.set_Name(token3.getText());
                        declaration.set_Type(reference);
                        handler.set_Declaration(declaration);
                        ExceptionHandler handler2 = handler;
                        statement.get_ExceptionHandlers().Add(handler2);
                        block = handler2.get_Block();
                        reference = null;
                    }
                    this.compound_or_single_stmt(block);
                }
                if ((this.LA(1) != 0x11) || !tokenSet_2_.member(this.LA(2)))
                {
                    if (!tokenSet_15_.member(this.LA(1)) || !tokenSet_20_.member(this.LA(2)))
                    {
                        throw new NoViableAltException(this.LT(1), this.getFilename());
                    }
                }
                else
                {
                    this.finally_block(statement);
                }
            }
            catch (RecognitionException exception)
            {
                if (base.inputState.guessing != 0)
                {
                    throw;
                }
                this.reportError(exception);
                this.recover(exception, tokenSet_15_);
            }
        }
		void CreateMoveNext()
		{
			Method generator = _generator.Method;
			
			BooMethodBuilder methodBuilder = _enumerator.AddVirtualMethod("MoveNext", TypeSystemServices.BoolType);
			methodBuilder.Method.LexicalInfo = generator.LexicalInfo;
			_moveNext = methodBuilder.Entity;
			
			TransformLocalsIntoFields(generator);

			TransformParametersIntoFieldsInitializedByConstructor(generator);
			
			methodBuilder.Body.Add(CreateLabel(generator));

			// Visit() needs to know the number of the finished state
			_finishedStateNumber = _labels.Count;
			LabelStatement finishedLabel = CreateLabel(generator);
			methodBuilder.Body.Add(generator.Body);
			generator.Body.Clear();
			
			Visit(methodBuilder.Body);
			
			methodBuilder.Body.Add(CreateYieldInvocation(LexicalInfo.Empty, _finishedStateNumber, null));
			methodBuilder.Body.Add(finishedLabel);
			
			methodBuilder.Body.Insert(0,
			                          CodeBuilder.CreateSwitch(
			                          	this.LexicalInfo,
			                          	CodeBuilder.CreateMemberReference(_state),
			                          	_labels));
			
			// if the method contains converted try statements, put it in a try/failure block
			if (_convertedTryStatements.Count > 0)
			{
				IMethod dispose = CreateDisposeMethod();
				
				var tryFailure = new TryStatement();
				tryFailure.ProtectedBlock.Add(methodBuilder.Body);
				tryFailure.FailureBlock = new Block();
				tryFailure.FailureBlock.Add(CallMethodOnSelf(dispose));
				methodBuilder.Body.Clear();
				methodBuilder.Body.Add(tryFailure);
			}
		}
Beispiel #21
0
        public override void OnTryStatement(TryStatement node)
        {
            Visit(node.ProtectedBlock);
            Visit(node.ExceptionHandlers);

            EnterEnsureBlock();
            Visit(node.FailureBlock);
            Visit(node.EnsureBlock);
            LeaveEnsureBlock();
        }
		public override bool EnterTryStatement(TryStatement node)
		{
			TryStatementInfo info = new TryStatementInfo();
			info._statement = node;
			if (_tryStatementStack.Count > 0)
				info._parent = _tryStatementStack.Peek();
			_tryStatementStack.Push(info);
			return true;
		}
Beispiel #23
0
        public override void OnTryStatement(TryStatement node)
        {
            _state.EnterTryBlock(node);
            _state.EnterProtectedBlock();
            Visit(node.ProtectedBlock);
            _state.LeaveProtectedBlock();

            Visit(node.ExceptionHandlers);

            Visit(node.FailureBlock);

            Visit(node.EnsureBlock);
            _state.LeaveTryBlock();
        }
Beispiel #24
0
	protected void exception_handler(
		TryStatement t
	) //throws RecognitionException, TokenStreamException
{
		
		IToken  c = null;
		IToken  x = null;
		IToken  u = null;
		
				ExceptionHandler eh = null;		
				TypeReference tr = null;
				Expression e = null;
			
		
		try {      // for error handling
			c = LT(1);
			match(EXCEPT);
			{
				switch ( LA(1) )
				{
				case ID:
				{
					x = LT(1);
					match(ID);
					break;
				}
				case AS:
				case IF:
				case UNLESS:
				case COLON:
				{
					break;
				}
				default:
				{
					throw new NoViableAltException(LT(1), getFilename());
				}
				 }
			}
			{
				switch ( LA(1) )
				{
				case AS:
				{
					match(AS);
					tr=type_reference();
					break;
				}
				case IF:
				case UNLESS:
				case COLON:
				{
					break;
				}
				default:
				{
					throw new NoViableAltException(LT(1), getFilename());
				}
				 }
			}
			{
				switch ( LA(1) )
				{
				case IF:
				case UNLESS:
				{
					{
						switch ( LA(1) )
						{
						case IF:
						{
							match(IF);
							break;
						}
						case UNLESS:
						{
							u = LT(1);
							match(UNLESS);
							break;
						}
						default:
						{
							throw new NoViableAltException(LT(1), getFilename());
						}
						 }
					}
					e=boolean_expression();
					break;
				}
				case COLON:
				{
					break;
				}
				default:
				{
					throw new NoViableAltException(LT(1), getFilename());
				}
				 }
			}
			if (0==inputState.guessing)
			{
				
						eh = new ExceptionHandler(ToLexicalInfo(c));
						
						eh.Declaration = new Declaration();
						eh.Declaration.Type = tr;
						
						if (x != null)
						{
							eh.Declaration.LexicalInfo = ToLexicalInfo(x);
							eh.Declaration.Name = x.getText();		
						}
						else
						{
							eh.Declaration.Name = null;
							eh.Flags |= ExceptionHandlerFlags.Anonymous;
						}
						if (tr != null)
						{
							eh.Declaration.LexicalInfo = tr.LexicalInfo;
						}
						else if (x != null)
						{
							eh.Declaration.LexicalInfo = eh.LexicalInfo;
						}
						if(tr == null)
						{
							eh.Flags |= ExceptionHandlerFlags.Untyped;
						}
						if (e != null)
						{
							if(u != null)
							{
								UnaryExpression not = new UnaryExpression(ToLexicalInfo(u));
								not.Operator = UnaryOperatorType.LogicalNot;
								not.Operand = e;
								e = not;
							}
							eh.FilterCondition = e;
							eh.Flags |= ExceptionHandlerFlags.Filter;
						}
					
			}
			compound_stmt(eh.Block);
			if (0==inputState.guessing)
			{
				
						t.ExceptionHandlers.Add(eh);
					
			}
		}
		catch (RecognitionException ex)
		{
			if (0 == inputState.guessing)
			{
				reportError(ex, "exception_handler");
				recover(ex,tokenSet_106_);
			}
			else
			{
				throw ex;
			}
		}
	}
Beispiel #25
0
 public void EnterTryBlock(TryStatement tryBlock)
 {
     _tryBlocks.Push(tryBlock);
 }
Beispiel #26
0
 public override void LeaveTryStatement(TryStatement node)
 {
     if (node.EnsureBlock == null && node.FailureBlock == null && node.ExceptionHandlers.Count == 0)
     {
         Error(CompilerErrorFactory.InvalidTryStatement(node));
     }
 }
        void CreateMoveNext()
        {
            Method generator = _generator.Method;

            BooMethodBuilder methodBuilder = _enumerator.AddVirtualMethod("MoveNext", TypeSystemServices.BoolType);
            methodBuilder.Method.LexicalInfo = generator.LexicalInfo;
            _moveNext = methodBuilder.Entity;

            foreach (Local local in generator.Locals)
            {
                InternalLocal entity = (InternalLocal)local.Entity;

                Field field = _enumerator.AddInternalField("$" + entity.Name + "$" + _context.AllocIndex(), entity.Type);
                _mapping[entity] = field.Entity;
            }
            generator.Locals.Clear();

            foreach (ParameterDeclaration parameter in generator.Parameters)
            {
                InternalParameter entity = (InternalParameter)parameter.Entity;
                if (entity.IsUsed)
                {
                    Field field = DeclareFieldInitializedFromConstructorParameter(_enumerator, _enumeratorConstructor,
                                                                                  entity.Name,
                                                                                  entity.Type);
                    _mapping[entity] = field.Entity;
                }
            }

            methodBuilder.Body.Add(CreateLabel(generator));
            // Visit() needs to know the number of the finished state
            _finishedStateNumber = _labels.Count;
            LabelStatement finishedLabel = CreateLabel(generator);
            methodBuilder.Body.Add(generator.Body);
            generator.Body.Clear();

            Visit(methodBuilder.Body);

            methodBuilder.Body.Add(CreateYieldInvocation(null, _finishedStateNumber));
            methodBuilder.Body.Add(finishedLabel);

            methodBuilder.Body.Insert(0,
                           CodeBuilder.CreateSwitch(
                           	this.LexicalInfo,
                           	CodeBuilder.CreateMemberReference(_state),
                           	_labels));

            // if the method contains converted try statements, put it in a try/failure block
            if (_convertedTryStatements.Count > 0)
            {
                IMethod dispose = CreateDisposeMethod();

                TryStatement tryFailure = new TryStatement();
                tryFailure.ProtectedBlock.Add(methodBuilder.Body);
                tryFailure.FailureBlock = new Block();
                tryFailure.FailureBlock.Add(CallMethodOnSelf(dispose));
                methodBuilder.Body.Clear();
                methodBuilder.Body.Add(tryFailure);
            }
        }