示例#1
0
        public void Run(SyneryParser.EachStatementContext context)
        {
            string parameterName        = context.Identifier().GetText();
            string tableName            = context.tableIdentifier().GetText();
            var    recordTypeDefinition = Controller.Interpret <SyneryParser.RecordTypeContext, KeyValuePair <SyneryType, IRecordType> >(context.recordType());

            if (Memory.Database.IsTable(tableName))
            {
                ITable table = Memory.Database.LoadTable(tableName);

                foreach (var row in table)
                {
                    // initialize a new scope for this block and push it on the scope stack

                    INestedScope blockScope = new BlockScope(Memory.CurrentScope);

                    // create the record from the row and declare/assign it as local variable

                    IRecord record = GetRecordFromTableRow(recordTypeDefinition.Value, row, table.Schema);

                    blockScope.DeclareVariable(parameterName, recordTypeDefinition.Key);
                    blockScope.AssignVariable(parameterName, record);

                    Controller.Interpret <SyneryParser.BlockContext, INestedScope, INestedScope>(context.block(), blockScope);

                    // stop execution if return was called
                    if (blockScope.IsTerminated == true)
                    {
                        break;
                    }
                }
            }
        }
示例#2
0
        private void WriteBlockHeader(BlockScope blockScope, string blockType)
        {
            string scopeFlags = null;
            var    sb         = StringBuilderPool.Acquire();

            try
            {
                if (!blockScope.IsKnownAtCompileTime)
                {
                    sb.Append('[');
                    sb.Append(NUglify.NotKnown);
                    sb.Append(']');
                }

                if (blockScope.UseStrict)
                {
                    sb.Append(NUglify.ScopeIsStrictFlag);
                }

                scopeFlags = sb.ToString();
            }
            finally
            {
                sb.Release();
            }

            WriteProgress();
            WriteProgress(NUglify.BlockScopeHeader.FormatInvariant(
                              blockType,
                              blockScope.Owner.Context.StartLineNumber,
                              blockScope.Owner.Context.StartColumn + 1,
                              scopeFlags));
        }
示例#3
0
        public void EnterMethodDefinition(
            ScopeBuilder /*!*/ locals,
            MSA.Expression /*!*/ selfParameter,
            MSA.ParameterExpression /*!*/ runtimeScopeVariable,
            MSA.Expression blockParameter,
            string /*!*/ methodName,
            Parameters parameters)
        {
            Assert.NotNull(locals, selfParameter, runtimeScopeVariable);

            MethodScope method = new MethodScope(
                locals,
                selfParameter,
                runtimeScopeVariable,
                blockParameter,
                methodName,
                parameters
                );

            method.Parent              = _currentElement;
            method.ParentRescue        = _currentRescue;
            method.ParentLoop          = _currentLoop;
            method.ParentBlock         = _currentBlock;
            method.ParentVariableScope = _currentVariableScope;
            method.ParentMethod        = _currentMethod;

            _currentElement       = method;
            _currentRescue        = null;
            _currentLoop          = null;
            _currentBlock         = null;
            _currentVariableScope = method;
            _currentMethod        = method;
        }
        protected override CrawlSyntaxNode VisitBlock(BlockNode block)
        {
            BlockScope scope = block.Scope.CollectIdentifiers(block);
            var        tmp   = ((BlockNode)base.VisitBlock(block));
            var        after = tmp.WithScope(scope);

            return(after);
        }
示例#5
0
        public void Run(SyneryParser.BlockContext context)
        {
            // initialize a new scope for this block and push it on the scope stack

            INestedScope blockScope = new BlockScope(Memory.CurrentScope);

            RunWithResult(context, blockScope);
        }
示例#6
0
                    public void Ascend(BlockScope scope)
                    {
                        _depth--;

                        for (var i = 0; i < scope.Uses; i++)
                        {
                            _ = _uses.Pop();
                        }
                    }
示例#7
0
        public void LeaveBlockDefinition()
        {
            Debug.Assert(_currentElement == _currentBlock);
            BlockScope oldBlock = _currentBlock;

            _currentElement       = oldBlock.Parent;
            _currentRescue        = oldBlock.ParentRescue;
            _currentLoop          = oldBlock.ParentLoop;
            _currentVariableScope = oldBlock.ParentVariableScope;
            _currentBlock         = oldBlock.ParentBlock;
        }
示例#8
0
        public void LeaveMethodDefinition()
        {
            Debug.Assert(_currentElement == _currentMethod);
            MethodScope oldMethod = _currentMethod;

            _currentElement       = oldMethod.Parent;
            _currentRescue        = oldMethod.ParentRescue;
            _currentLoop          = oldMethod.ParentLoop;
            _currentBlock         = oldMethod.ParentBlock;
            _currentVariableScope = oldMethod.ParentVariableScope;
            _currentMethod        = oldMethod.ParentMethod;
        }
        public static void InterpretHandleBlock(IInterpretationController controller, IHandleBlockData data, IValue eventRecord)
        {
            SyneryParser.BlockContext blockContext = data.Context as SyneryParser.BlockContext;

            if (blockContext != null)
            {
                // create a new block scope and set the parent scope of the OBSERVE-block as parent
                INestedScope blockScope = new BlockScope(data.ParentScope);

                // add the event record as local variable
                blockScope.DeclareVariable(data.ParameterName, eventRecord.Type);
                blockScope.AssignVariable(data.ParameterName, eventRecord.Value);

                // start interpreting the given HANDLE-block
                controller.Interpret <SyneryParser.BlockContext, INestedScope, INestedScope>(blockContext, blockScope);
            }
            else
            {
                throw new SyneryException("Can not interpret handle block because the given context is not a BlockContext");
            }
        }
        protected override CrawlSyntaxNode VisitBlock(BlockNode block)
        {
            string                 ns       = block.FindNameSpace()?.Module ?? "";
            BlockScope             scope    = new BlockScope();
            List <CrawlSyntaxNode> children = new List <CrawlSyntaxNode>();

            foreach (CrawlSyntaxNode child in block)
            {
                CrawlSyntaxNode          afterVisit = Visit(child);
                ClassTypeDeclerationNode asClass    = afterVisit as ClassTypeDeclerationNode;
                if (asClass != null)
                {
                    CrawlConstructedType type = scope.AddClass(asClass, ns);
                    children.Add(asClass.WithClassType(type));
                }
                else
                {
                    children.Add(afterVisit);
                }
            }

            return(block.Update(block.Interval, children, scope));
        }
示例#11
0
        public void EnterBlockDefinition(
            ScopeBuilder /*!*/ locals,
            MSA.Expression /*!*/ bfcVariable,
            MSA.Expression /*!*/ selfVariable,
            MSA.Expression /*!*/ runtimeScopeVariable,
            MSA.LabelTarget /*!*/ redoLabel)
        {
            Assert.NotNull(locals, bfcVariable, selfVariable);
            Assert.NotNull(redoLabel);

            BlockScope block = new BlockScope(locals, selfVariable, runtimeScopeVariable, bfcVariable, redoLabel);

            block.Parent              = _currentElement;
            block.ParentRescue        = _currentRescue;
            block.ParentLoop          = _currentLoop;
            block.ParentBlock         = _currentBlock;
            block.ParentVariableScope = _currentVariableScope;

            _currentElement       = block;
            _currentRescue        = null;
            _currentLoop          = null;
            _currentBlock         = block;
            _currentVariableScope = block;
        }
示例#12
0
    public override Method VisitMethod(Method method) {
      if (method == null) return null;
      if (method.IsNormalized) return method;
      this.MayReferenceThisAndBase = !(method is InstanceInitializer) || method.DeclaringType == null || method.DeclaringType.IsValueType;
      if (method.Name != null && method.Name.UniqueIdKey == StandardIds.Finalize.UniqueIdKey && method.HasCompilerGeneratedSignature &&
        method.DeclaringType is Class && ((Class)method.DeclaringType).IsAbstractSealedContainerForStatics)
        this.HandleError(method.Name, Error.DestructorInAbstractSealedClass);
      method.Attributes = this.VisitAttributeList(method.Attributes, method);
      method.ReturnAttributes = this.VisitAttributeList(method.ReturnAttributes);
      method.SecurityAttributes = this.VisitSecurityAttributeList(method.SecurityAttributes);
      if ((method.ReturnType == SystemTypes.DynamicallyTypedReference || method.ReturnType == SystemTypes.ArgIterator) && 
      (this.currentOptions == null || !this.currentOptions.NoStandardLibrary) ) {
        this.HandleError(method.Name, Error.CannotReturnTypedReference, this.GetTypeName(method.ReturnType));
        method.ReturnType = SystemTypes.Object;
      }
      if (method.Body != null) {
        if (method.DeclaringType is Interface && !method.IsStatic) {
          this.HandleError(method.Name, Error.InterfaceMemberHasBody, this.GetMethodSignature(method));
          method.Body = null;
        } else if (method.IsAbstract) {
          this.HandleError(method.Name, Error.AbstractHasBody, this.GetMethodSignature(method));
          method.Body = null;
        }
      } else if (!method.IsAbstract && !method.IsExtern && !this.isCompilingAContractAssembly) {
        this.HandleError(method.Name, Error.ConcreteMissingBody, this.GetMethodSignature(method));
        return null;
      } else if (method.TemplateParameters != null && method.TemplateParameters.Count > 0 && !this.useGenerics) {
        SourceContext ctx = method.TemplateParameters[0].SourceContext;
        ctx.EndPos = method.TemplateParameters[method.TemplateParameters.Count-1].SourceContext.EndPos;
        Debug.Assert(ctx.EndPos >= ctx.StartPos);
        Node n = new UnaryExpression();
        n.SourceContext = ctx;
        if (method.DeclaringType is Interface)
          this.HandleError(n, Error.AbstractInterfaceMethod);
        else
          this.HandleError(n, Error.AbstractMethodTemplate);
        return null;
      }
      BlockScope savedCurrentFinallyClause = this.currentFinallyClause;
      Method savedCurrentMethod = this.currentMethod;
      Return savedReturnNode = this.returnNode;
      Yield savedYieldNode = this.yieldNode;
      this.currentFinallyClause = null;
      this.currentMethod = method;
      this.returnNode = null;
      this.yieldNode = null;
      MethodScope scope = method.Scope;
      this.CheckForDuplicateDeclarations(scope);

      if ((this.currentPreprocessorDefinedSymbols != null && this.currentPreprocessorDefinedSymbols.ContainsKey("DefaultExposeBlocks")) &&
        !method.IsStatic && !(method is InstanceInitializer) && method.DeclaringType is Class && 
        !method.IsAbstract && method.CciKind == CciMemberKind.Regular && method.ApplyDefaultContract) {
        This thisOb = method.ThisParameter;
        MethodCall thisIsExposable = new MethodCall(
          new MemberBinding(null, SystemTypes.Guard.GetMethod(Identifier.For("FrameIsExposable"),
            SystemTypes.Object, SystemTypes.Type)),
            new ExpressionList(thisOb, new UnaryExpression(new Literal(method.DeclaringType, SystemTypes.Type),
            NodeType.Typeof, OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type))), NodeType.Call,
            SystemTypes.Boolean, method.Body.SourceContext);
        Assumption assumption = new Assumption(thisIsExposable);
        Expose expose = new Expose(NodeType.Write);
        expose.SourceContext = method.Body.SourceContext;
        expose.Instance = thisOb;
        expose.Body = method.Body;
        if (this.currentOptions != null && this.currentOptions.DisableGuardedClassesChecks)
          method.Body = new Block(new StatementList(assumption, expose));
        else
          method.Body = new Block(new StatementList(expose));
      }


      #region Check contract rules for all interface methods and base methods this method implements/overrides
      bool ok = true;
      if (method.IsVirtual && !method.IsCompilerControlled) {
        // use FindNearest..., can't rely on method.OverriddenMethod since it might not be set further up the chain
        Method overridden = method.DeclaringType.FindNearestOverriddenMethod(method);
        if (overridden != null) {
          ok &= this.CheckContractRules(overridden, method, method.DeclaringType);
        }
        for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplementedInterfaceMethods[i];
          ok &= this.CheckContractRules(ifaceMethod, method, method.DeclaringType);
        }
        for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i];
          ok &= this.CheckContractRules(ifaceMethod, method, method.DeclaringType);
        }
      }
      #endregion

      #region Contract Inheritance for method overrides and interface implementations (do this somewhere else?)
      // This needs to be done here (and not in VisitMethodContract) because method might not even have a contract
      if (method.IsVirtual && ok && !method.IsCompilerControlled) {
        // use FindNearest..., can't rely on method.OverriddenMethod since it might not be set further up the chain
        Method overridden = method.DeclaringType.FindNearestOverriddenMethod(method);
        // FindNearestOverriddenMethod doesn't care if method is "new" or an "override", so explicity test IsVirtual property
        MethodContract cumulativeContract = method.Contract == null ? new MethodContract(method) : method.Contract;
        bool somethingWasCopied = false;
        while (overridden != null && overridden.IsVirtual) {
          if (overridden.Contract != null) {
            cumulativeContract.CopyFrom(overridden.Contract);
            somethingWasCopied = true;
            break;
          }
          overridden = overridden.DeclaringType.FindNearestOverriddenMethod(overridden);
        }
        // Can inherit from at most one interface method
        bool ifaceContractWasCopied = false;
        for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplementedInterfaceMethods[i];
          if (ifaceMethod == null) continue;
          if (ifaceMethod.Contract != null) {
            if (ifaceContractWasCopied) {
              this.HandleError(method, Error.RequiresNotAllowedInInterfaceImplementation, this.GetMethodSignature(ifaceMethod));
              break;
            }
            cumulativeContract.CopyFrom(ifaceMethod.Contract);
            somethingWasCopied = true;
            ifaceContractWasCopied = true;
          }
        }
        for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i];
          if (ifaceMethod == null) continue;
          if (ifaceMethod.Contract != null) {
            if (ifaceContractWasCopied) {
              this.HandleError(method, Error.RequiresNotAllowedInInterfaceImplementation, this.GetMethodSignature(ifaceMethod));
              break;
            }
            cumulativeContract.CopyFrom(ifaceMethod.Contract);
            somethingWasCopied = true;
            ifaceContractWasCopied = true;
          }
        }
        if (method.Contract == null && somethingWasCopied) { // otherwise it was already copied into the method's contract 
          method.Contract = cumulativeContract;
        }
      }
      #endregion
      
      // For checked exceptions, the actual exceptions thrown must be a subset of the allowed exceptions
      TypeNodeList aes = new TypeNodeList();
      if (method.Contract != null && method.Contract.Ensures != null) {
        for (int i = 0, n = method.Contract.Ensures.Count; i < n; i++) {
          EnsuresExceptional ee = method.Contract.Ensures[i] as EnsuresExceptional;
          if (ee == null || ee.Inherited) continue;
          aes.Add(ee.Type);
        }
      }
      TypeNodeList saveAllowedExceptions = this.allowedExceptions;
      this.allowedExceptions = aes;
      // don't check method body of proxy methods.
      Method result = (method is ProxyMethod) ? method : base.VisitMethod(method);
      this.allowedExceptions = saveAllowedExceptions;


      if (this.yieldNode != null && TypeNode.StripModifiers(method.ReturnType) is Interface) {
        StatementList statements = new StatementList(1);
        TypeNode elementType = SystemTypes.Object;
        Interface stype = (Interface)TypeNode.StripModifiers(method.ReturnType);
        if (stype.TemplateArguments != null && stype.TemplateArguments.Count == 1) elementType = stype.TemplateArguments[0];
        Class state = scope.ClosureClass;
        elementType = scope.FixTypeReference(elementType);
        state.Flags |= TypeFlags.Abstract; //So that no complaints are given about missing methods added by Normalizer
        state.Interfaces = new InterfaceList(5);
        state.Interfaces.Add(SystemTypes.IEnumerable);
        state.Interfaces.Add((Interface)SystemTypes.GenericIEnumerator.GetTemplateInstance(this.currentType, elementType));
        state.Interfaces.Add(SystemTypes.IEnumerator);
        state.Interfaces.Add(SystemTypes.IDisposable);
        state.Interfaces.Add((Interface)SystemTypes.GenericIEnumerable.GetTemplateInstance(this.currentType, elementType));
        //Add these methods so that Normalizer can find them even when reference to iterator is forward
        Method moveNext = new Method(state, null, StandardIds.MoveNext, null, SystemTypes.Boolean, null);
        moveNext.CallingConvention = CallingConventionFlags.HasThis;
        moveNext.Flags = MethodFlags.Public|MethodFlags.Virtual;
        moveNext.Body = new Block(new StatementList());
        state.Members.Add(moveNext);
        Method getCurrent = new Method(state, null, StandardIds.getCurrent, null, elementType, null);
        getCurrent.CallingConvention = CallingConventionFlags.HasThis;
        getCurrent.Flags = MethodFlags.Public|MethodFlags.Virtual|MethodFlags.SpecialName;
        getCurrent.Body = new Block(new StatementList());
        state.Members.Add(getCurrent);
        Return ret = new Return(new ConstructIterator(state, method.Body, elementType, state));
        if (method.Name.SourceContext.Document != null) {
          ret.SourceContext = method.SourceContext;
          ret.SourceContext.EndPos = method.Name.SourceContext.EndPos;
          Debug.Assert(ret.SourceContext.EndPos >= ret.SourceContext.StartPos);
        }
        statements.Add(ret);
        method.Body = new Block(statements);
        method.Body.Scope = new BlockScope(scope, method.Body);
      }
      if (method.IsStatic && method.IsVirtual && !method.IsSpecialName) {
        method.Flags &= ~MethodFlags.Static;
        this.HandleError(method.Name, Error.StaticNotVirtual, this.GetMethodSignature(method));
      }
      if (!method.OverridesBaseClassMember) {
        if (method.NodeType == NodeType.InstanceInitializer || !method.IsSpecialName) {
          if (!(method.DeclaringType is Interface) && !(method.DeclaringType is DelegateNode)) {
            if (this.IsLessAccessible(method.ReturnType, method)) {
              this.HandleError(method.Name, Error.ReturnTypeLessAccessibleThanMethod, this.GetTypeName(method.ReturnType), this.GetMethodSignature(method));
              this.HandleRelatedError(method.ReturnType);
            }
            this.CheckParameterTypeAccessibility(method.Parameters, method);
          }
        } else {
          if (method.Name != null && Checker.OperatorName[method.Name.UniqueIdKey] != null) {
            if (this.IsLessAccessible(method.ReturnType, method)) {
              this.HandleError(method.Name, Error.ReturnTypeLessAccessibleThanOperator, this.GetTypeName(method.ReturnType), this.GetMethodSignature(method));
              this.HandleRelatedError(method.ReturnType);
            }
            this.CheckParameterTypeAccessibility(method.Parameters, method);
          }
        }
      }

      if (!method.IsSpecialName) {
        TypeNodeList implementedTypes = method.ImplementedTypes;
        if (implementedTypes != null) {
          InterfaceList declaringTypeInterfaces = this.GetTypeView(method.DeclaringType).Interfaces;
          for (int i = 0, n = implementedTypes.Count; i < n; i++) {
            Interface iface = implementedTypes[i] as Interface;
            if (iface == null) continue;
            if (!this.IsAllowedAsImplementedType(declaringTypeInterfaces, iface)) {
              Node offendingNode = method.ImplementedTypeExpressions[i];
              this.HandleError(offendingNode, Error.ContainingTypeDoesNotImplement, this.GetMethodSignature(method), this.GetTypeName(iface));
              this.HandleRelatedError(iface);
              implementedTypes = null;
              break;
            }
          }
        }
        MethodList implementedMethods = method.ImplementedInterfaceMethods;
        for (int i = 0, n = implementedTypes == null ? 0 : implementedTypes.Count; i < n; i++) {
          Interface iface = implementedTypes[i] as Interface;
          if (iface == null) continue;
          Method m = implementedMethods == null ? null : implementedMethods[i];
          if (m == null) {
            this.HandleError(method.Name, Error.InterfaceMemberNotFound, this.GetMemberSignature(method), this.GetTypeName(iface));
            this.HandleRelatedError(iface);
          } else if (m.IsSpecialName)
            this.HandleError(method.Name, Error.CannotExplicitlyImplementAccessor, this.GetMethodSignature(method), this.GetMethodSignature(m));
        }
      }
      if ((method.Flags & MethodFlags.PInvokeImpl) != 0) {
        Error e = Error.None;
        if (this.shadowedAssembly != null) {
          // Make sure this method has a counterpart in the shadowed method
          TypeNode type = this.GetCorrespondingShadowedTypeNode(method.DeclaringType);
          if (type == null) {
            this.HandleError(method.DeclaringType, Error.TypeMissingInShadowedAssembly, this.GetTypeName(method.DeclaringType));
          } else {
            int numParams = method.Parameters == null ? 0 : method.Parameters.Count;
            TypeNode[] types = new TypeNode[numParams];
            for (int i = 0; i < numParams; i++) { types[i] = this.GetCorrespondingShadowedTypeNode(TypeNode.StripModifiers(method.Parameters[i].Type)); }
            if (this.GetTypeView(type).GetMethod(method.Name, types) == null) {
              this.HandleError(method, Error.MethodMissingInShadowedAssembly, this.GetMethodSignature(method));
            }
          }
        } else if (this.isCompilingAContractAssembly)
          e = Error.None;
        else if (method.Body != null)
          e = Error.PInvokeHasBody;
        else if (method.IsAbstract)
          e = Error.AbstractAndExtern;
        else if (method.PInvokeImportName == null || method.PInvokeModule == null) {
          if (method.Attributes == null || method.Attributes.Count == 0)
            e = Error.PInvokeWithoutModuleOrImportName;
          else
            method.Flags &= ~MethodFlags.PInvokeImpl;
        }
        if (e != Error.None)
          this.HandleError(method.Name, e, this.GetMethodSignature(method));
      }
      if (method.IsPropertySetter && (method.IsPure || method.IsConfined || method.IsStateIndependent)) {
        this.HandleError(method, Error.MemberCannotBeAnnotatedAsPure, this.GetMethodSignature(method));
      }
      this.currentFinallyClause = savedCurrentFinallyClause;
      this.currentMethod = savedCurrentMethod;
      this.returnNode = savedReturnNode;
      this.yieldNode = savedYieldNode;
      return result;
    }
示例#13
0
	void Binding(out ComprehensionBinding binding) {
		binding = new ComprehensionBinding();
		TypeNode tn, dummy;
		Expression source;
		BlockScope newBlock;
		
		PType(out tn);
		binding.TargetVariableType = tn;
		newBlock = new BlockScope();
		newBlock.OuterScope = currentBlock;
		currentBlock = newBlock;
		
		Expect(23);
		Expect(54);
		Expect(22);
		PType(out dummy);
		Expect(24);
		Expect(49);
		string identName; 
		Ident(out identName);
		Identifier id = Identifier.For(identName);
		Field f = new Field(id);
		f.Type = tn;
		f.DeclaringType = currentBlock;
		currentBlock.Members.Add(f);
		MemberBinding mb = new MemberBinding(new ImplicitThis(),f);
		mb.Type = f.Type;
		binding.TargetVariable = mb;
		binding.ScopeForTemporaryVariables = currentBlock;
		
		Expect(50);
		Expect(23);
		Expr(out source);
		binding.SourceEnumerable = source;
		
	}
示例#14
0
 public override Statement VisitFinally(Finally Finally) {
   if (Finally == null) return null;
   BlockScope savedCurrentFinallyClause = this.currentFinallyClause;
   this.currentFinallyClause = Finally.Block.Scope;
   Finally.Block = this.VisitBlock(Finally.Block);
   this.currentFinallyClause = savedCurrentFinallyClause;
   return Finally;
 }
 public BlockNode(CrawlSyntaxNode parent, GreenCrawlSyntaxNode self, int indexInParent)
     : base(parent, self, indexInParent)
 {
     Scope = ((GreenBlockNode)self).Scope;
 }
示例#16
0
	void TrueComprehension(out Expression e) {
		Expression body;
		ExpressionList elist;
		BlockScope oldBlock = currentBlock;
		Comprehension compr = new Comprehension();
		
		Expect(65);
		FiltersAndBindings(out elist);
		Expect(66);
		Expr(out body);
		Expect(67);
		compr.BindingsAndFilters = elist;
		compr.Elements = new ExpressionList(body);
		compr.Type = SystemTypes.GenericIEnumerable.GetTemplateInstance(currentAssembly,body.Type);
		e = compr;
		currentBlock = oldBlock;
		
	}
示例#17
0
 public virtual void BuildAxisClosureMember(Expression source, AxisBuildState state, MemberAccessor ma, Block block, BlockScope scope) {
   Block inner = block; 
   bool isStatic = (source is Literal) && (source.Type == SystemTypes.Type);
   if (!this.IsLocal(source)) {
     Expression loc = this.NewClosureLocal(source.Type, scope);
     inner.Statements.Add(new AssignmentStatement(loc, source));
     source = loc;
   }
   // sanity check for member/type mismatch caused by aliases
   if (!isStatic && source.Type != ma.Member.DeclaringType) {
     Expression loc = this.NewClosureLocal(ma.Member.DeclaringType, scope);
     inner.Statements.Add(new AssignmentStatement(loc, this.typeSystem.ExplicitCoercion(source, loc.Type, this.TypeViewer)));
     source = loc;
   }
   Cardinality tcard = this.typeSystem.GetCardinality(state.YieldType, this.TypeViewer);
   Cardinality scard = this.typeSystem.GetCardinality(source, this.TypeViewer);
   if (scard != Cardinality.One) {
     Block b = new Block(new StatementList(3));
     inner.Statements.Add(this.IfNotNull(source, b));
     inner = b;
     source = this.GetNonNull(source, inner, scope);
   }
   TypeNode memberType = this.typeSystem.GetMemberType(ma.Member);
   MemberBinding mb = null;
   if (isStatic) {
     mb = new MemberBinding(null, ma.Member);
   }
   else {
     mb = new MemberBinding(source, ma.Member);
   }
   mb.Type = memberType;
   this.BuildAxisClosureExpression(mb, state, ma.Next, ma.Yield, inner, scope);
 }
示例#18
0
 internal GreenBlockNode(NodeType type, Interval interval, IEnumerable <GreenCrawlSyntaxNode> children, BlockScope scope) : base(
         type, interval, children)
 {
     Scope = scope;
 }
示例#19
0
 public virtual Expression GetNonNull(Expression source, Block block, BlockScope scope) {
   Expression nnx = this.GetNonNullExpression(source);
   if (nnx != source) {
     Expression loc = this.NewClosureLocal(nnx.Type, scope);
     block.Statements.Add(new AssignmentStatement(loc, nnx));
     return loc;
   }
   return source;
 }
 public CrawlSyntaxNode WithScope(BlockScope scope)
 {
     return(Update(Interval, this, scope));
 }
示例#21
0
        public void EnterMethodDefinition(
            ScopeBuilder/*!*/ locals, 
            MSA.Expression/*!*/ selfParameter,
            MSA.ParameterExpression/*!*/ runtimeScopeVariable,
            MSA.Expression blockParameter,
            string/*!*/ methodName,
            Parameters parameters) {
            Assert.NotNull(locals, selfParameter, runtimeScopeVariable);

            MethodScope method = new MethodScope(
                locals,
                selfParameter, 
                runtimeScopeVariable, 
                blockParameter, 
                methodName, 
                parameters
            );

            method.Parent = _currentElement;
            method.ParentRescue = _currentRescue;
            method.ParentLoop = _currentLoop;
            method.ParentBlock = _currentBlock;
            method.ParentVariableScope = _currentVariableScope;
            method.ParentMethod = _currentMethod;

            _currentElement = method;
            _currentRescue = null;
            _currentLoop = null;
            _currentBlock = null;
            _currentVariableScope = method;
            _currentMethod = method;
        }
示例#22
0
                    public void PushUse(BlockScope scope, UseStatementNode use)
                    {
                        _uses.Push((GetDepth(scope.Node), use));

                        scope.Uses++;
                    }
示例#23
0
        public void EnterBlockDefinition(
            ScopeBuilder/*!*/ locals,
            MSA.Expression/*!*/ bfcVariable,
            MSA.Expression/*!*/ selfVariable,
            MSA.ParameterExpression/*!*/ runtimeScopeVariable, 
            MSA.LabelTarget/*!*/ redoLabel) {
            Assert.NotNull(locals, bfcVariable, selfVariable);
            Assert.NotNull(redoLabel);

            BlockScope block = new BlockScope(locals, selfVariable, runtimeScopeVariable, bfcVariable, redoLabel);
            block.Parent = _currentElement;
            block.ParentRescue = _currentRescue;
            block.ParentLoop = _currentLoop;
            block.ParentBlock = _currentBlock;
            block.ParentVariableScope = _currentVariableScope;
            
            _currentElement = block;
            _currentRescue = null;
            _currentLoop = null;
            _currentBlock = block;
            _currentVariableScope = block;
        }
示例#24
0
 public virtual Block BuildAxisClosure(Expression source, AxisBuildState state, Accessor acc, BlockScope scope) {
   if (state.TypeClosures != null) {
     TypeNode tn = source.Type;
     CurrentClosure cc = (CurrentClosure) state.TypeClosures[tn.UniqueKey];
     if (cc == null) {
       cc = this.BeginCurrentClosure(state.YieldType, "axis");
       Parameter p = new Parameter(Identifier.For("source"), tn);
       cc.Method.Parameters = new ParameterList(1);
       cc.Method.Parameters.Add(p);
       state.TypeClosures[tn.UniqueKey] = cc;
       ParameterField pf = new ParameterField(cc.Method.Scope, null, FieldFlags.Public, p.Name, p.Type, null);
       pf.Parameter = p;
       cc.Method.Scope.Members.Add(pf);
       MemberBinding mb = new MemberBinding(new ImplicitThis(), pf);
       mb.Type = pf.Type;
       cc.Method.Body.Statements.Add(this.BuildAxisClosureBlock(mb, state, acc, cc.Method.Body.Scope));
       this.EndCurrentClosure(cc);
     }
     Block block = new Block(new StatementList(1));
     ImplicitThis it = new ImplicitThis();
     it.Type = cc.Method.DeclaringType;
     MethodCall mc = new MethodCall(new MemberBinding(it, cc.Method), new ExpressionList(source));
     mc.Type = cc.Method.ReturnType;
     if (cc.Method.IsVirtual) mc.NodeType = NodeType.Callvirt;
     Expression target = null;
     Block inner = null;
     block.Statements.Add(this.BuildClosureForEach(mc, ref target, out inner, scope));
     inner.Statements.Add(new Yield(target));
     return block;
   }
   return this.BuildAxisClosureBlock(source, state, acc, scope);
 }
示例#25
0
 public virtual void BuildAxisClosureExpression(Expression source, AxisBuildState state, Accessor next, bool yieldResult, Block inner, BlockScope scope) {
   Cardinality tcard = this.typeSystem.GetCardinality(state.YieldType, this.TypeViewer);
   Cardinality scard = this.typeSystem.GetCardinality(source, this.TypeViewer);
   // lift over collections
   while (true) {
     if (this.typeSystem.IsStructural(source.Type))
       goto lift_done;
     if (yieldResult && scard == tcard) 
       goto lift_done;        
     switch (scard) {
       case Cardinality.ZeroOrOne:
         Block b = new Block(new StatementList(3));
         inner.Statements.Add(this.IfNotNull(source, b));
         inner = b;
         source = this.GetNonNull(source, inner, scope);
         break;
       case Cardinality.ZeroOrMore:
       case Cardinality.OneOrMore:
         TypeNode elementType = this.typeSystem.GetStreamElementType(source, this.TypeViewer);
         Expression target = null;
         Block newInner = null;
         inner.Statements.Add(this.BuildClosureForEach(source, ref target, out newInner, scope));
         inner = newInner;
         source = target;
         break;
       default:
         goto lift_done;
     }
     scard = this.typeSystem.GetCardinality(source, this.TypeViewer);
   }
   lift_done:
     if (yieldResult) {
       if (scard == Cardinality.None) {
         Block b = new Block(new StatementList(1));
         inner.Statements.Add(this.IfNotNull(source, b));
         inner = b;
         source = this.GetNonNull(source, inner, scope);
       }
       if (state.YieldTarget != null && state.YieldBlock != null) {
         inner.Statements.Add(new AssignmentStatement(state.YieldTarget, this.typeSystem.ExplicitCoercion(source, state.YieldType, this.TypeViewer)));
         inner.Statements.Add(new Branch(Literal.True, state.YieldBlock));
       }
       else {
         inner.Statements.Add(new Yield(this.typeSystem.ExplicitCoercion(source, state.YieldType, this.TypeViewer)));
       }
     }
   if (next != null) {
     inner.Statements.Add(this.BuildAxisClosure(source, state, next, scope));
   }
 }
示例#26
0
 public override Field VisitField(Field field){
   if (field == null) return null;
   Scope savedScope = this.scope;
   BlockScope scope = new BlockScope(savedScope, null);
   scope.LexicalSourceExtent = field.SourceContext;
   this.scope = scope;
   this.AddToAllScopes(this.scope);
   Declarer declarer = this.GetDeclarer();
   declarer.VisitField(field, scope);
   field.Attributes = this.VisitAttributeList(field.Attributes);
   this.AbstractSealedUsedAsType = Error.AbstractSealedFieldType;
   field.Type = this.VisitTypeReference(field.Type, true);
   this.AbstractSealedUsedAsType = Error.NotAType;
   field.Initializer = this.VisitExpression(field.Initializer);
   if (field.IsLiteral){
     Literal lit = field.Initializer as Literal;
     if (lit != null) {
       field.DefaultValue = lit;
     }else{
       MemberBinding mb = field.Initializer as MemberBinding;
       if (mb != null){
         Field f = mb.BoundMember as Field;
         if (f != null && f.IsLiteral){
           field.DefaultValue = f.DefaultValue;
         }
       }
     }
   }
   this.AddNodePositionAndInfo(field.Name, new MemberBinding(null, field), IdentifierContexts.AllContext);
   Identifier prefix = field.Name.Prefix;
   if (prefix != null){
     AliasDefinition aliasDef = this.LookupAlias(prefix);
     if (aliasDef != null){
       prefix = aliasDef.AliasedUri;
       if (prefix == null) prefix = (Identifier)aliasDef.AliasedExpression;
     }
     if (prefix != null)
       field.Name.Prefix = prefix;
   }
   field.ImplementedInterfaces = this.VisitInterfaceReferenceList(field.ImplementedInterfaces);
   this.scope = savedScope;
   return field;
 }
        public new BlockNode Update(Interval interval, IEnumerable <CrawlSyntaxNode> children, BlockScope scope)
        {
            List <CrawlSyntaxNode> newchildren = children.ToList();

            if (Interval.Equals(interval) && AreEqual(newchildren) && scope == Scope)
            {
                return(this);
            }

            var green = new GreenBlockNode(NodeType.Block, interval, newchildren.Select(ExtractGreenNode), scope);

            return((BlockNode)Translplant(green.CreateRed(null, 0)));
        }
示例#28
0
 public virtual void BuildAxisClosureSequence(Expression source, AxisBuildState state, SequenceAccessor sqa, Block block, BlockScope scope) {
   if (!this.IsLocal(source)) {
     Expression loc = this.NewClosureLocal(source.Type, scope);
     block.Statements.Add(new AssignmentStatement(loc, source));
     source = loc;
   }
   foreach( Accessor acc in sqa.Accessors ) {
     block.Statements.Add(this.BuildAxisClosureBlock(source, state, acc, scope));
   }
 }
示例#29
0
 public virtual Block BuildAxisClosureBlock(Expression source, AxisBuildState state, Accessor accessor, BlockScope scope) {
   if (accessor == null || source == null || state == null || state.YieldType == null || scope == null)
     return null;
   MemberAccessor ma = accessor as MemberAccessor;
   if (ma != null) {
     Block block = new Block(new StatementList(3));
     this.BuildAxisClosureMember(source, state, ma, block, scope);
     return block;
   }
   SequenceAccessor sqa = accessor as SequenceAccessor;
   if (sqa != null) {
     Block block = new Block(new StatementList(sqa.Accessors.Count + 1));
     this.BuildAxisClosureSequence(source, state, sqa, block, scope);
     return block;
   }
   SwitchAccessor swa = accessor as SwitchAccessor;
   if (swa != null) {
     Block block = new Block(new StatementList());
     this.BuildAxisClosureUnion(source, state, swa, false, block, scope);
     return block;
   }
   // todo: add error message here
   return null;
 }
示例#30
0
 public virtual void BuildAxisClosureUnion(Expression source, AxisBuildState state, SwitchAccessor swa, bool yieldResult, Block block, BlockScope scope) {
   TypeUnion tu = source.Type as TypeUnion;
   Debug.Assert(tu != null, "Switch accessor must have type union");
   if (!this.IsLocal(source)) {
     Expression loc = this.NewClosureLocal(source.Type, scope);
     block.Statements.Add(new AssignmentStatement(loc, source));
     source = loc;
   }
   // determine type union tag and value
   Method mgetvalue = this.GetTypeView(tu).GetMethod(StandardIds.GetValue);
   MethodCall mcgetvalue = new MethodCall(new MemberBinding(source, mgetvalue), null); 
   mcgetvalue.Type = mgetvalue.ReturnType;
   Local locValue = new Local(SystemTypes.Object);
   block.Statements.Add(new AssignmentStatement(locValue, mcgetvalue));
   Method mgettag = this.GetTypeView(tu).GetMethod(StandardIds.GetTag);
   MethodCall mcgettag = new MethodCall(new MemberBinding(source, mgettag), null);
   mcgettag.Type = mgettag.ReturnType;
   Local locTag = new Local(SystemTypes.UInt32);
   block.Statements.Add(new AssignmentStatement(locTag, mcgettag));
   // switch on type union tag
   BlockList blocks = new BlockList(swa.Accessors.Count);
   Block endBlock = new Block(null);
   foreach( int id in swa.Accessors.Keys ) {
     Accessor acc = (Accessor) swa.Accessors[id];
     Block caseBlock = new Block(new StatementList(3));
     blocks.Add(caseBlock);
     block.Statements.Add(new Branch(new BinaryExpression(locTag, new Literal(id, SystemTypes.Int32), NodeType.Eq), caseBlock));
     Expression locvar = this.NewClosureLocal(swa.Type.Types[id], scope);
     caseBlock.Statements.Add(new AssignmentStatement(locvar, this.Unbox(locValue, locvar.Type)));
     this.BuildAxisClosureExpression(locvar, state, acc, yieldResult, caseBlock, scope);
     caseBlock.Statements.Add(new Branch(null, endBlock));
   }
   block.Statements.Add(new Branch(null, endBlock));
   for( int i = 0, n = blocks.Count; i < n; i++ ) {
     block.Statements.Add(blocks[i]);
   }
   block.Statements.Add(endBlock);
 }
示例#31
0
 public virtual Expression NewClosureLocal(TypeNode type, BlockScope scope) {
   if (scope == null) return null;
   Identifier id = Identifier.For("var: "+nLocal); nLocal++;
   Field f = new Field(scope, null, FieldFlags.CompilerControlled|FieldFlags.SpecialName, id, type, null);
   scope.Members.Add(f);
   MemberBinding mb = new MemberBinding(new ImplicitThis(scope,0), f);
   mb.Type = f.Type;
   return mb;
 }
示例#32
0
        public void LeaveBlockDefinition() {
            Debug.Assert(_currentElement == _currentBlock);
            BlockScope oldBlock = _currentBlock;

            _currentElement = oldBlock.Parent;
            _currentRescue = oldBlock.ParentRescue;
            _currentLoop = oldBlock.ParentLoop;
            _currentVariableScope = oldBlock.ParentVariableScope;
            _currentBlock = oldBlock.ParentBlock;
        }
示例#33
0
 public virtual Statement BuildClosureForEach(Expression source, ref Expression target, out Block body, BlockScope scope) {
   source = this.GetInnerExpression(source);
   if (source is QueryExpression) {
     QueryYielder yielder = new QueryYielder();
     yielder.Source = source;
     yielder.Body = body = new Block(new StatementList(1));
     if (target == null) target = this.NewClosureLocal(this.typeSystem.GetStreamElementType(source, this.TypeViewer), scope);
     yielder.Target = target;
     yielder.State = this.NewClosureLocal(SystemTypes.Int32, scope);
     return yielder;
   }else{
     if (target == null){
       TypeNode elementType = this.typeSystem.GetStreamElementType(source, this.TypeViewer);
       target = target = this.NewClosureLocal(elementType, scope);
     }
     Literal tmpSource = new Literal(null, source.Type);
     ForEach fe = new ForEach(target.Type, target, tmpSource, new Block(new StatementList(1)));
     fe.ScopeForTemporaryVariables = scope;
     Checker checker = new Checker(null, this.typeSystem, null, null, null);
     checker.currentType = this.typeSystem.currentType = (scope.CapturedForClosure ? scope.ClosureClass : this.currentMethod.DeclaringType);
     checker.VisitForEach(fe);
     Debug.Assert(fe.SourceEnumerable != null);
     if (fe.SourceEnumerable != null){
       Debug.Assert(fe.SourceEnumerable is CollectionEnumerator, "SourceEnumerable == "+fe.SourceEnumerable.GetType());
       CollectionEnumerator ce = (CollectionEnumerator)fe.SourceEnumerable;
       ce.Collection = source;
     }
     body = fe.Body;
     return fe;
   }
 }
示例#34
0
        public void LeaveMethodDefinition() {
            Debug.Assert(_currentElement == _currentMethod);
            MethodScope oldMethod = _currentMethod;

            _currentElement = oldMethod.Parent;
            _currentRescue = oldMethod.ParentRescue;
            _currentLoop = oldMethod.ParentLoop;
            _currentBlock = oldMethod.ParentBlock;
            _currentVariableScope = oldMethod.ParentVariableScope;
            _currentMethod = oldMethod.ParentMethod;
        }
示例#35
0
    /// <summary>
    /// Compiles the source text into a module.
    /// </summary>
    /// <param name="sourceText">The source text.</param>
    /// <param name="module">The source module.</param>
    /// <returns>The compiled module.</returns>
    public static Module Compile(string sourceText, string module = "")
    {
        var parser = new Parser(sourceText, module);

        // -------------------------------------------------------------------------

        LexicalScope scope = new FunctionScope(null)
        {
            Token = parser.Next
        };

        void EnterFunctionScope(Token token)
        {
            scope = new FunctionScope(scope)
            {
                Token = token
            };
        }

        void EnterBlockScope(Token token)
        {
            scope = new BlockScope(scope)
            {
                Token = token
            };
        }

        void EnterLoopScope(Token token)
        {
            scope = new LoopScope(scope)
            {
                Token = token
            };
        }

        void LeaveScope()
        {
            scope = scope.Scope;
            Debug.Assert(scope != null);
        }

        // -------------------------------------------------------------------------

        Slot MakeSlot(string name)
        {
            foreach (var found in scope.SlotsInScope)
            {
                if (found.Name == name)
                {
                    throw parser.Error($"'{name}' is already defined in this scope");
                }
            }

            var slot = new Slot {
                Name = name, Scope = scope
            };

            scope.Slots.Add(slot);
            return(slot);
        }

        Slot FindSlot(string name)
        {
            foreach (var found in scope.SlotsInScope)
            {
                if (found.Name == name)
                {
                    return(found);
                }
            }

            throw parser.Error($"Undefined '{name}'");
        }

        // -------------------------------------------------------------------------

        // Identifier declaration
        parser.Syntax.Declaration(Token.Word).Do((token, context) => new Identifier(MakeSlot(token.Text))
        {
            Token = token,
            Scope = scope,
        });

        // -------------------------------------------------------------------------

        // Grouping: ( expr )
        // Function expression: ( ) => expr_or_block
        // Function expression: ( ...ident ) => expr_or_block
        // Function expression: ( ident , ... ) => expr_or_block
        parser.Syntax.Primitive("(").Do((token, context) => {
            var isFunction =
                parser.Match(")", "=>") ||
                parser.Match(Token.Word, ",") ||
                parser.Match(Token.Word, ")", "=>") ||
                parser.Match("...", Token.Word, ")", "=>");

            if (isFunction)
            {
                var expression = new FunctionExpression {
                    Token = token,
                    Scope = scope,
                };

                EnterFunctionScope(token);
                {
                    parser.RepeatZeroOrMoreWithSeparatorUntil(")", ",", delegate {
                        var isRestParameter = parser.Optional("...");

                        if (parser.Declaration(context) is Identifier parameter)
                        {
                            var index = expression.Parameters.Count;
                            expression.Parameters.Add(parameter);

                            parameter.Slot.Kind     = SlotKind.Parameter;
                            parameter.Slot.ReadOnly = true; // <- parameters are always read-only

                            if (isRestParameter)
                            {
                                parameter.Slot.Source      = SlotSource.ArgumentSlice;
                                parameter.Slot.SourceIndex = index;
                                parser.Next.Require(")", "The rest parameter must be the last");
                            }
                            else
                            {
                                parameter.Slot.Source      = SlotSource.Argument;
                                parameter.Slot.SourceIndex = index;
                            }
                        }
                        else
                        {
                            throw parser.Error("Expected a parameter name");
                        }
                    });

                    var arrow = parser.Required("=>");

                    if (parser.Optional("{") is Token begin)
                    {
                        expression.Body = new Block {
                            Token = begin,
                            Scope = scope,
                        };

                        parser.RepeatZeroOrMoreUntil("}", delegate {
                            expression.Body.Statements.Add(parser.Statement(context) as Statement);
                        });
                    }
                    else if (parser.Expression(context) is Expression value)
                    {
                        expression.Body = new Block {
                            Token      = arrow,
                            Scope      = scope,
                            Statements =
                            {
                                new ReturnStatement {
                                    Token = arrow,
                                    Scope = scope,
                                    Value = value,
                                },
                            },
                        };
                    }
                    else
                    {
                        throw parser.Error("Expected an expression after '=>'");
                    }
                }