Example #1
0
        public override object VisitForeignFunDecl(PParser.ForeignFunDeclContext context)
        {
            // FUN name=Iden
            var fun = (Function)nodesToDeclarations.Get(context);

            // LPAREN funParamList? RPAREN
            var paramList = context.funParamList() != null
                ? (Variable[])Visit(context.funParamList())
                : new Variable[0];

            fun.Signature.Parameters.AddRange(paramList);

            // (COLON type)?
            fun.Signature.ReturnType = ResolveType(context.type());

            // SEMI
            // no function body
            fun.Role |= FunctionRole.Foreign;

            // Creates
            foreach (var createdInterface in context._interfaces)
            {
                if (CurrentScope.Lookup(createdInterface.GetText(), out Interface @interface))
                {
                    fun.AddCreatesInterface(@interface);
                }
                else
                {
                    throw Handler.MissingDeclaration(createdInterface, "interface", createdInterface.GetText());
                }
            }
            return(fun);
        }
Example #2
0
        private JsObject EvaluateModuleInternal(string script, IBaristaModuleLoader moduleLoader = null)
        {
            var mainModule = m_moduleRecordFactory.CreateBaristaModuleRecord(this, "", null, true, moduleLoader);

            //Set the global value - this is akin to node.js's 'global' variable (https://nodejs.org/api/globals.html#globals_global)
            //It's preferable for barista not to use this, however, right now I don't see a way to actually 'Set' values dynamically in a module namespace
            Object.DefineProperty(GlobalObject, "global", new JsPropertyDescriptor()
            {
                Configurable = false, Enumerable = false, Writable = false, Value = GlobalObject
            });

            //Now start the parsing.
            try
            {
                //First, parse our main module script.
                mainModule.ParseModuleSource(script);

                //Now we're ready, evaluate the main module.
                Engine.JsModuleEvaluation(mainModule.Handle);

                //Evaluate any pending promises.
                CurrentScope.ResolvePendingPromises();

                //Retrieve the module namespace.
                var moduleNamespace = Engine.JsGetModuleNamespace(mainModule.Handle);

                //Return the module namespace as an object.
                return(new JsObject(Engine, this, moduleNamespace));
            }
            finally
            {
                mainModule.Dispose();
            }
        }
Example #3
0
        public ValueTask StartCollectors(CancellationToken token = default)
        {
            var genericContianerType  = typeof(CollectorIntervalContainer <>);
            var genericContianerIType = typeof(CollectorIntervalContainer <>);

            // Filter all instance which can resolve as ICollector
            CollectorReadScope = CurrentScope.BeginLifetimeScope((builder) =>
            {
                foreach (var type in RegisteredCollector)
                {
                    var instance = CurrentScope.Resolve(type);
                    if (instance is ICollector collector)
                    {
                        var containerType  = genericContianerType.MakeGenericType(type);
                        var containerIType = genericContianerIType.MakeGenericType(type);
                        builder.RegisterType(containerType).As(containerIType);
                    }
                }
            });

            foreach (var type in RegisteredCollector)
            {
                var containerIType = genericContianerIType.MakeGenericType(type);
                var container      = CollectorReadScope.Resolve(containerIType) as ICollectorContainer;
                container.Run(token);
            }
            return(default);
        private SemanticResolver(
            ParserOptions parserOptions,
            Dictionary <string, DbParameterReferenceExpression> parameters,
            Dictionary <string, DbVariableReferenceExpression> variables,
            TypeResolver typeResolver)
        {
            _parserOptions = parserOptions;
            _parameters    = parameters;
            _variables     = variables;
            _typeResolver  = typeResolver;

            //
            // Creates Scope manager
            //
            _scopeManager = new ScopeManager(NameComparer);

            //
            // Push a root scope region
            //
            EnterScopeRegion();

            //
            // Add command free variables to the root scope
            //
            foreach (var variable in _variables.Values)
            {
                CurrentScope.Add(variable.VariableName, new FreeVariableScopeEntry(variable));
            }
        }
        public void DeclareVariable(string name, IMember value, VariableSource source, Location location, bool overwrite = true)
        {
            if (source == VariableSource.Import)
            {
                // Duplicate declaration so if variable gets overwritten it can still be retrieved. Consider:
                //    from X import A
                //    class A(A): ...
                CurrentScope.DeclareImported(name, value, location);
            }

            var member = GetInScope(name);

            if (member != null && !overwrite)
            {
                return;
            }

            if (source == VariableSource.Import && value is IVariable v)
            {
                CurrentScope.LinkVariable(name, v, location);
                return;
            }

            if (member != null)
            {
                if (!value.IsUnknown())
                {
                    CurrentScope.DeclareVariable(name, value, source, location);
                }
            }
            else
            {
                CurrentScope.DeclareVariable(name, value, source, location);
            }
        }
Example #6
0
        public void Visit(FunctionInvocationNode functionInvocationNode)
        {
            functionInvocationNode.Function.CurrentSymbolTable = CurrentScope;
            FunctionSymbolTableEntry entry = new FunctionSymbolTableEntry(functionInvocationNode.ReturnType, functionInvocationNode.Parameters);

            CurrentScope.AddOrUpdateSymbol(functionInvocationNode.Identifier, entry);
        }
Example #7
0
        //Adds a provided variable to the current scope or modifies an existing
        //variable with the same name (this is required because match variables unlike
        //regular variables in the same scope can shadow each other).
        private int AddMatchVariable(string varName, ElaExpression exp, out bool newV)
        {
            var sv = ScopeVar.Empty;

            newV = false;

            //Here we first check if such a name is already added and if this is the case simply fetch an
            //existing name.
            if (CurrentScope.Parent != null && CurrentScope.Parent.Locals.TryGetValue(varName, out sv) &&
                (sv.Flags & ElaVariableFlags.Parameter) == ElaVariableFlags.Parameter)
            {
                return(0 | sv.Address << 8);
            }
            else
            {
                var res = CurrentScope.TryChangeVariable(varName);
                newV = true;

                if (res != -1)
                {
                    return(0 | res << 8);
                }

                return(AddVariable(varName, exp, ElaVariableFlags.None, -1));
            }
        }
Example #8
0
        public override object VisitOnEventPushState(PParser.OnEventPushStateContext context)
        {
            //annotationSet?
            if (context.annotationSet() != null)
            {
                throw new NotImplementedException("push state annotations");
            }

            // PUSH stateName
            var targetState = FindState(context.stateName());

            // ON eventList
            var actions = new List <IStateAction>();

            foreach (var token in context.eventList().eventId())
            {
                if (!CurrentScope.Lookup(token.GetText(), out PEvent evt))
                {
                    throw Handler.MissingDeclaration(token, "event", token.GetText());
                }

                actions.Add(new EventPushState(token, evt, targetState));
            }
            return(actions.ToArray());
        }
        public void DeclareVariable(string name, IMember value, VariableSource source, Location location, bool overwrite = true)
        {
            var member = GetInScope(name);

            if (member != null && !overwrite)
            {
                return;
            }
            if (source == VariableSource.Import && value is IVariable v)
            {
                CurrentScope.LinkVariable(name, v, location);
                return;
            }
            if (member != null)
            {
                if (!value.IsUnknown())
                {
                    CurrentScope.DeclareVariable(name, value, source, location);
                }
            }
            else
            {
                CurrentScope.DeclareVariable(name, value, source, location);
            }
        }
Example #10
0
 /// <summary>
 ///     结束所有范围
 /// </summary>
 public static void EndAll()
 {
     while (CurrentScope != null)
     {
         CurrentScope.DoDispose();
     }
 }
Example #11
0
        public Statement DecompileForEach(bool isDynArray = false)
        {
            PopByte();
            var scopeStatements = new List <Statement>();

            var iteratorFunc = DecompileExpression();

            if (iteratorFunc == null)
            {
                return(null);
            }

            if (isDynArray)
            {
                Expression dynArrVar   = DecompileExpression();
                bool       hasIndex    = Convert.ToBoolean(ReadByte());
                Expression dynArrIndex = DecompileExpression();
                iteratorFunc = new DynArrayIterator(iteratorFunc, dynArrVar, dynArrIndex);
            }

            var scopeEnd = ReadUInt16(); // MemOff

            ForEachScopes.Push(scopeEnd);

            Scopes.Add(scopeStatements);
            CurrentScope.Push(Scopes.Count - 1);
            while (Position < Size)
            {
                if (CurrentIs(OpCodes.IteratorNext))
                {
                    PopByte(); // IteratorNext
                    if (PeekByte == (byte)OpCodes.IteratorPop)
                    {
                        StatementLocations[(ushort)(Position - 1)] = new IteratorNext();
                        StatementLocations[(ushort)Position]       = new IteratorPop();
                        PopByte(); // IteratorPop
                        break;
                    }
                    Position--;
                }

                var current = DecompileStatement();
                if (current == null)
                {
                    return(null); // ERROR ?
                }
                scopeStatements.Add(current);
            }
            CurrentScope.Pop();
            ForEachScopes.Pop();

            var statement = new ForEachLoop(iteratorFunc, new CodeBody(scopeStatements))
            {
                iteratorPopPos = Position - 1
            };

            StatementLocations.Add(StartPositions.Pop(), statement);
            return(statement);
        }
        public override void VisitProcedureDeclaration(ProcedureDeclaration procedureDeclaration)
        {
            PushScope(CurrentScope.CreateChildScope(procedureDeclaration));

            base.VisitProcedureDeclaration(procedureDeclaration);

            PopScope();
        }
Example #13
0
 /// <summary>
 /// Removes scopes until <c>CurrentScope == CurrentParentScope</c>. As each scope is
 /// removed, it is added as a child to its predecessor.
 /// </summary>
 public void RevertToNextParent()
 {
     while (CurrentScope != CurrentParentScope)
     {
         var scope = ScopeStack.Pop();
         CurrentScope.AddChildScope(scope);
     }
 }
        public static void CompileAssignment(Node node, ref List <Instruction> instructions)
        {
            CompileGeneral(node.Nodes[1], ref instructions);

            instructions.Add(new Instruction {
                OpCode = OperationCode.stloc,
                Value  = CurrentScope.GetIndexFromIdentifier(node.Nodes[0].Body)
            });
        }
        void IExpectationScope.Add(IExpectation expectation, bool hasHigherPrecedence)
        {
            if (expectation == null)
            {
                throw new ArgumentNullException("expectation");
            }

            CurrentScope.Add(expectation, hasHigherPrecedence);
        }
Example #16
0
 public void AddSymbol(ASTNode symbol, string type)
 {
     if (!CurrentScope.AddSymbol(symbol.Token, type))
     {
         TextSpan errorSpan = new TextSpan(symbol.Token.LinePosition, 1);
         Diagnostics.Semantic_ReportSymbolAlreadyDeclared(symbol.Token.Text, CurrentScope.Level, errorSpan, symbol.Token.LineNumber, type);
         return;
     }
     Diagnostics.Semantic_ReportAddingSymbol(symbol.Token.Text, type, CurrentScope.Level);
 }
Example #17
0
        private Function CreateAnonFunction(PParser.NoParamAnonEventHandlerContext context)
        {
            var fun = new Function(context)
            {
                Owner = CurrentMachine,
                Scope = CurrentScope.MakeChildScope()
            };

            nodesToDeclarations.Put(context, fun);
            return(fun);
        }
Example #18
0
        public override object VisitNonDefaultEvent(PParser.NonDefaultEventContext context)
        {
            // HALT | iden
            var eventName = context.GetText();

            if (!CurrentScope.Lookup(eventName, out PEvent pEvent))
            {
                throw Handler.MissingDeclaration(context, "event", eventName);
            }
            return(pEvent);
        }
        public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
        {
            Debug.WriteLine("Begin TypeDeclaration " + typeDeclaration.Name);

            PushScope(CurrentScope.CreateChildScope(typeDeclaration));

            base.VisitTypeDeclaration(typeDeclaration);

            PopScope();

            Debug.WriteLine("End TypeDeclaration " + typeDeclaration.Name);
        }
        public override void VisitSchemaDeclaration(SchemaDeclaration schemaDeclaration)
        {
            Debug.WriteLine("Begin SchemaDeclaration " + schemaDeclaration.Name);

            scopes_.Push(CurrentScope.CreateChildScope(schemaDeclaration));

            base.VisitSchemaDeclaration(schemaDeclaration);

            scopes_.Pop();

            Debug.WriteLine("End SchemaDeclaration " + schemaDeclaration.Name);
        }
Example #21
0
 public bool InternVariable(Token token, Token typeToken, out Var var)
 {
     if (token != null && token.IsVariable)
     {
         var = CurrentScope.FindVar(token.ToString());
         if (var == null)
         {
             var = CurrentScope.CreateVar(token, typeToken);
             return(true); //was interned
         }
     }
     var = null; //must assign out before return.
     return(false);
 }
Example #22
0
        public override object VisitOnEventGotoState(PParser.OnEventGotoStateContext context)
        {
            // annotationSet?
            if (context.annotationSet() != null)
            {
                throw new NotImplementedException("state transition annotations");
            }

            Function transitionFunction;

            if (context.funName != null)
            {
                // WITH funName=Iden
                var funName = context.funName.GetText();
                if (!CurrentScope.Lookup(funName, out transitionFunction))
                {
                    throw Handler.MissingDeclaration(context.funName, "function", funName);
                }
                transitionFunction.Role |= FunctionRole.TransitionFunction;
            }
            else if (context.anonEventHandler() != null)
            {
                // WITH anonEventHandler
                transitionFunction       = CreateAnonFunction(context.anonEventHandler());
                transitionFunction.Role |= FunctionRole.TransitionFunction;
            }
            else
            {
                // SEMI
                transitionFunction = null;
            }

            // GOTO stateName
            var target = FindState(context.stateName());

            // ON eventList
            var actions = new List <IStateAction>();

            foreach (var eventIdContext in context.eventList().eventId())
            {
                if (!CurrentScope.Lookup(eventIdContext.GetText(), out PEvent evt))
                {
                    throw Handler.MissingDeclaration(eventIdContext, "event", eventIdContext.GetText());
                }

                actions.Add(new EventGotoState(eventIdContext, evt, target, transitionFunction));
            }
            return(actions.ToArray());
        }
Example #23
0
        //Compiles a pattern as lazy by creating a thunk an initializing all pattern names with these thunks.
        private void CompileLazyPattern(int sys, ElaExpression pat, bool allowBang)
        {
            //First we need to obtain a list of all names, that declared in this pattern.
            var names = new List <String>();

            ExtractPatternNames(pat, names);

            //Walk through all names and create thunks
            for (var i = 0; i < names.Count; i++)
            {
                var      n = names[i];
                Label    funSkipLabel;
                int      address;
                LabelMap newMap;

                CompileFunctionProlog(null, 1, pat.Line, pat.Column, out funSkipLabel, out address, out newMap);

                var next = cw.DefineLabel();
                var exit = cw.DefineLabel();

                //As soon as already compiling pattern as lazy, we should enforce strictness even if
                //pattern is declared as lazy. Otherwise everything would crash, because here assume
                //that names are bound in this bound in the same scope.
                CompilePattern(1 | ((sys >> 8) << 8), pat, next, allowBang, true /*forceStrict*/);
                cw.Emit(Op.Br, exit);
                cw.MarkLabel(next);
                cw.Emit(Op.Failwith, (Int32)ElaRuntimeError.MatchFailed);
                cw.MarkLabel(exit);
                cw.Emit(Op.Nop);

                //Here we expect that our target variable is already declared by a pattern in the
                //same physical scope - so we can obtain and push it as a return value.
                var sv = GetVariable(n, pat.Line, pat.Column);
                PushVar(sv);
                CompileFunctionEpilog(null, 1, address, funSkipLabel);
                cw.Emit(Op.Newlazy);

                ScopeVar var;
                if (CurrentScope.Locals.TryGetValue(n, out var))
                {
                    //If it doesn't have a NoInit flag we are not good
                    if ((var.Flags & ElaVariableFlags.NoInit) == ElaVariableFlags.NoInit)
                    {
                        PopVar(var.Address = 0 | var.Address << 8); //Aligning it to local scope
                        CurrentScope.RemoveFlags(n, ElaVariableFlags.NoInit);
                    }
                }
            }
        }
Example #24
0
            object IConstantResolver.GetConstantIdentifier(string Name)
            {
                if (CurrentScope == null)
                {
                    return(null);
                }
                var Symbol = CurrentScope.FindSymbol(Name);

                if (Symbol == null)
                {
                    Console.Error.WriteLine("Can't find symbol {0}", Name);
                    return(null);
                }
                return(Symbol.ConstantValue);
            }
Example #25
0
        private LocalVariable /*!*/ DefineParameter(string /*!*/ name, SourceSpan location)
        {
            // we are in a method:
            Debug.Assert(CurrentScope.IsTop && !(CurrentScope is TopStaticLexicalScope));

            LocalVariable variable;

            if (CurrentScope.TryGetValue(name, out variable))
            {
                _tokenizer.ReportError(Errors.DuplicateParameterName);
                return(variable);
            }

            return(CurrentScope.AddVariable(name, location));
        }
Example #26
0
        internal MSA.Expression /*!*/ TryCatchAny(MSA.Expression /*!*/ tryBody, MSA.Expression /*!*/ catchBody)
        {
            var variable = CurrentScope.DefineHiddenVariable("#value", tryBody.Type);

            return
                (Ast.Block(
                     Ast.TryCatch(
                         Ast.Assign(variable, tryBody),
                         Ast.Catch(typeof(Exception),
                                   Ast.Assign(variable, catchBody)
                                   )
                         ),
                     variable
                     ));
        }
Example #27
0
        public void DeclareVariable(string name, IMember value, LocationInfo location, bool overwrite = false)
        {
            var member = GetInScope(name);

            if (member != null)
            {
                if (!value.IsUnknown())
                {
                    CurrentScope.DeclareVariable(name, value, location);
                }
            }
            else
            {
                CurrentScope.DeclareVariable(name, value, location);
            }
        }
Example #28
0
        public override object VisitStateIgnore(PParser.StateIgnoreContext context)
        {
            // IGNORE nonDefaultEventList
            var actions = new List <IStateAction>();

            foreach (var token in context.nonDefaultEventList()._events)
            {
                if (!CurrentScope.Lookup(token.GetText(), out PEvent evt))
                {
                    throw Handler.MissingDeclaration(token, "event", token.GetText());
                }
                actions.Add(new EventIgnore(token, evt));
            }

            return(actions.ToArray());
        }
Example #29
0
 public void NewScope()
 {
     if (RootScope is null)
     {
         RootScope    = new Scope(0);
         CurrentScope = RootScope;
         CurrentScope.MostRecentScope = RootScope;
         ScopeCounter = 0;
     }
     else
     {
         CurrentScope.AddDescendant(ScopeCounter, CurrentScope);
         ScopeCounter++;
         CurrentScope = CurrentScope.MostRecentScope;
     }
     Diagnostics.Semantic_ReportAddingNewScope(ScopeCounter, CurrentScope);
 }
Example #30
0
        // Add a specific set of methods into a new scope
        // Pop the scope but keep a pointer to it in a look up table
        private void AddBuiltinMethods(PredefScopes predefscope, Type codetype, Type deftype, PredefKinds kind)
        {
            var scope = CurrentScope.Push();

            PredefScopeDict[predefscope] = new BuiltinScopeInfo {
                Predef   = predefscope,
                CodeType = codetype,
                DefType  = deftype,
                Scope    = scope,
                Kind     = kind,
            };
            foreach (var binfo in CallInfo.GetBuiltinInfo(codetype))
            {
                AddMethod(binfo.Name, binfo, predefscope);
            }
            scope.Pop();
        }