Ejemplo n.º 1
0
        public void SymbolTable_Basics()
        {
            var st = new SymbolTable <string, string>(parent: null)
            {
                { "bar", "foo" },
                { "baz", "qux" },
            };

            Assert.IsNull(st.Parent);

            Assert.ThrowsException <InvalidOperationException>(() => st.Add("bar", "qux"));

            Assert.IsTrue(st.TryGetValue("bar", out Indexed <string> foo));
            Assert.AreEqual("foo", foo.Value);
            Assert.AreEqual(0, foo.Index);
            Assert.AreEqual(foo, st["bar"]);

            Assert.IsTrue(st.TryGetValue("baz", out Indexed <string> qux));
            Assert.AreEqual("qux", qux.Value);
            Assert.AreEqual(1, qux.Index);

            Assert.IsFalse(st.TryGetValue("foo", out Indexed <string> unk));

            Assert.IsTrue(st.ToArray().SequenceEqual(new[] {
                new Indexed <KeyValuePair <string, string> >(new KeyValuePair <string, string>("bar", "foo"), 0),
                new Indexed <KeyValuePair <string, string> >(new KeyValuePair <string, string>("baz", "qux"), 1)
            }));

            Assert.IsNotNull(((IEnumerable)st).GetEnumerator());

            CollectionAssert.AreEqual(new[] { "bar", "baz" }, st.Symbols.ToArray());
        }
Ejemplo n.º 2
0
        sunStorableSymbol AddSystemVariable(string name)
        {
            var symbol = Scopes.DeclareVariable(MangleSystemSymbol(name));

            SymbolTable.Add(symbol);
            return(symbol);
        }
 public override void VisitEnter(Line line)
 {
     if (line.Type == LineType.Label)
     {
         _symbolTable.Add(new Symbol(line.Label, SymbolType.Label, _address));
     }
 }
Ejemplo n.º 4
0
        sunCallableSymbol AddSystemBuiltin(string name)
        {
            var symbol = new sunBuiltinSymbol(name, SymbolTable.Count);

            SymbolTable.Add(symbol);
            return(symbol);
        }
Ejemplo n.º 5
0
    void HandleTcpMessage(ITcpMessage msg)
    {
        switch (msg)
        {
        case ObjectCreatedMessage objMsg:
        {
            var id = objMsg.ObjectId;
            Objects[id] = new SyncObject(this, id, objMsg.OriginalNodeId);

            if (creationQueue.Count > 0 && objMsg.OriginalNodeId == NodeId)
            {
                lock (creationQueue)
                {
                    creationQueue.Dequeue().SetResult(id);
                }
            }

            Logger.Debug("Client", $"Received ObjectId={id}");

            InvokeObjectCreated(id);

            break;
        }

        case ObjectDeletedMessage delMsg:
        {
            var id = delMsg.ObjectId;
            Objects.Remove(id);

            Logger.Debug("Client", $"Received Deletion of ObjectId={id}");

            InvokeObjectDeleted(id);

            break;
        }

        case SymbolRegisteredMessage symMsg:
        {
            SymbolTable.Add(symMsg.Symbol, symMsg.SymbolId);
            if (symbolNotifier.IsWaiting(symMsg.Symbol))
            {
                symbolNotifier.Notify(symMsg.Symbol, symMsg.SymbolId);
            }

            Logger.Debug("Client", $"Received Symbol {symMsg.Symbol}->{symMsg.SymbolId}");
            break;
        }

        case EventSentMessage eventSentMessage:
        {
            HandleEventSentMessage(
                eventSentMessage.Name,
                eventSentMessage.Sender, eventSentMessage.Receiver,
                eventSentMessage.Args
                );
            break;
        }
        }
    }
Ejemplo n.º 6
0
    InterfaceType GetInterface(System.Type type, SymbolTable bindings)
    {
        string        name = GetName(type);
        InterfaceType t    = new InterfaceType(new InputElement(name), bindings);

        bindings.Add(t.Name, t);
        return((InterfaceType)FillIn(t, type));
    }
        public void FourSymbolsTwoDuplicatedOnce_WillReturnTwoEntries()
        {
            // Arrange
            var symbolTable = new SymbolTable();

            symbolTable.Add(new Symbol("a", QLType.Decimal, null));
            symbolTable.Add(new Symbol("a", QLType.Decimal, null));
            symbolTable.Add(new Symbol("d", QLType.Decimal, null));
            symbolTable.Add(new Symbol("d", QLType.Boolean, null));

            // Act & Assert
            var duplicateDetector = new DuplicateSymbolDetectionPipelineElement();
            var task = new ParsingTask("");

            task.SymbolTable = symbolTable;
            Assert.AreEqual(2, duplicateDetector.Process(task).Errors.Count);
        }
Ejemplo n.º 8
0
    StructType GetStruct(System.Type type, SymbolTable bindings)
    {
        string     name = GetName(type);
        StructType t    = new StructType(new InputElement(name), bindings);

        bindings.Add(t.Name, t);
        return((StructType)FillIn(t, type));
    }
Ejemplo n.º 9
0
    ClassType GetClass(System.Type type, SymbolTable bindings)
    {
        string    name = GetName(type);
        ClassType t    = new ClassType(new InputElement(name), bindings);

        bindings.Add(t.Name, t);
        return(FillIn(t, type));
    }
        public void UnknownIdentifierWithTypoTests()
        {
            SymbolTable.Add("soldHouseIn2010", QValueType.Boolean);
            QLSNode node     = QLSParserHelper.Parse(simpleWithTypoInQLS);
            var     analyser = new UnknownIdentifiersAnalyser();
            var     isValid  = analyser.Analyse(node);

            Assert.IsFalse(isValid);
        }
Ejemplo n.º 11
0
        private int AddKey(T v)
        {
            int vertexIndex = SymbolTable.Count;

            v.Id = vertexIndex;
            SymbolTable.Add(v, vertexIndex);
            Keys.Add(vertexIndex, v);
            return(vertexIndex);
        }
Ejemplo n.º 12
0
        public override void WriteToTable(SymbolTable table)
        {
            table.Add(this);

            foreach (var item in _types)
            {
                item.WriteToTable(table);
            }
        }
Ejemplo n.º 13
0
        public void NoIdentifiersAreUsed()
        {
            SymbolTable.Add("soldHouseIn2010", QValueType.Boolean);
            QLSNode node     = QLSParserHelper.Parse(simpleWithouIdentifiersQLS);
            var     analyser = new AllIdentifiersAreUsedAnalyser();
            var     result   = analyser.Analyse(node);

            Assert.IsFalse(result);
        }
        public override void VisitEnter(Line line)
        {
            if (line.Type == LineType.Label)
            {
                var pseudoAddress = 0; // just a filler

                _symbolTable.Add(new MSILSymbol(line.Label, SymbolType.Label, pseudoAddress, _gen.DefineLabel()));
            }
        }
Ejemplo n.º 15
0
        public override void WriteToTable(SymbolTable table)
        {
            table.Add(this);

            foreach (var item in _members)
            {
                item.definition.WriteToTable(table);
            }
        }
Ejemplo n.º 16
0
        public static EvalResult add_definition(SymbolTable symbols, FunCall val)
        {
            var new_fun_name = val.args[0].args.First().value.value;
            var parameters = FunCall.id_list(val.args[0].flattened_args().Skip(1).ToList());
            var fun_body = val.args[1];

            symbols.Add(new_fun_name, FunCall.id_list(new List<FunCall> { parameters, fun_body }));

            return new EvalResult(new EvalT(symbols, new FunCall(Token.symbol("Function Defined"))));
        }
Ejemplo n.º 17
0
        public bool AddVariable(string id, QValueType type)
        {
            if (!SymbolTable.Add(id, type))
            {
                Analyser.AddMessage(string.Format("Duplicate identifier {0} {1}", id, type), MessageType.ERROR);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 18
0
        public override bool TrySetSymbol(AstSymbol?symbol)
        {
            var success = base.TrySetSymbol(symbol);

            if (success)
            {
                symbol !.SymbolTable.Add(FunctionType);
            }
            return(success);
        }
        public static SymbolTable AddExtensionSymbols(this SymbolTable t)
        {
            // Add lock here to ensure thread safety when modifying a symbol table
            lock (_lock)
            {
                // Check whether extension method already exists
                if (t.Filter("nodesByType", 2).Count() == 0)
                {
                    t.Add("nodesByType", (IEnumerable <ITypedElement> f, string typeName) => NodesByType(f, typeName), doNullProp: true);
                }

                if (t.Filter("nodesByName", 2).Count() == 0)
                {
                    t.Add("nodesByName", (IEnumerable <ITypedElement> f, string name) => NodesByName(f, name), doNullProp: true);
                }
            }

            return(t);
        }
Ejemplo n.º 20
0
        private bool AddVariable(string id, QValueType type)
        {
            VisitedIDs.Add(id);
            if (!SymbolTable.Add(id, type))
            {
                Analyser.AddMessage(string.Format("Duplicate identifier {0} {1}", id, type), Language.QL, MessageType.ERROR);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 21
0
        // callables
        public sunBuiltinSymbol DeclareBuiltin(sunBuiltinDeclaration node)
        {
            if (SymbolTable.Get <sunCallableSymbol>().Any(i => i.Name == node.Name.Value))
            {
                throw new sunRedeclaredBuiltinException(node);
            }
            var symbol = new sunBuiltinSymbol(node.Name.Value, node.Parameters.ParameterInfo, SymbolTable.Count);

            SymbolTable.Add(symbol);
            return(symbol);
        }
Ejemplo n.º 22
0
        public Block Build()
        {
            SymbolTable symbols = new SymbolTable();

            for (int i = this.symbolStart; i < this.symbols.Symbols.Count; i++)
            {
                symbols.Add(this.symbols.Symbols[i]);
            }

            return(new Block(this.index, symbols, this.context, this.facts, this.rules, this.checks));
        }
Ejemplo n.º 23
0
        public static SymbolTable AddFhirExtensions(this SymbolTable t)
        {
            t.Add("hasValue", (ITypedElement f) => f.HasValue(), doNullProp: false);
            t.Add("resolve", (ITypedElement f, EvaluationContext ctx) => resolver(f, ctx), doNullProp: false);
            t.Add("htmlchecks", (ITypedElement f) => f.HtmlChecks(), doNullProp: false);

            return(t);

            ITypedElement resolver(ITypedElement f, EvaluationContext ctx)
            {
                if (ctx is FhirEvaluationContext fctx)
                {
                    return(f.Resolve(fctx.ElementResolver));
                }
                else
                {
                    return(f.Resolve());
                }
            }
        }
        public override IValue Evaluate()
        {
            // 3.4.1: If <cc-var-lhs> is a <TYPED-NAME> with a <type-suffix>, the <type-suffix> is ignored.
            var identifier    = _identifier.Evaluate().AsString;
            var constantValue = _expression.Evaluate();

            _symbolTable.Add(identifier, constantValue);
            return(new LivelinessExpression(
                       isAlive: new ConstantExpression(new BoolValue(false)),
                       code: _tokenText).Evaluate());
        }
Ejemplo n.º 25
0
        public void TestStr()
        {
            World       w    = new World();
            SymbolTable syms = new SymbolTable();

            ID    app_0 = syms.Add("app_0");
            ID    app_1 = syms.Add("app_1");
            ID    app_2 = syms.Add("app_2");
            ulong route = syms.Insert("route");
            ulong suff  = syms.Insert("route suffix");

            w.AddFact(new Fact(new Predicate(route, Arrays.AsList(new ID.Integer(0), app_0, new ID.Str("example.com")))));
            w.AddFact(new Fact(new Predicate(route, Arrays.AsList(new ID.Integer(1), app_1, new ID.Str("test.com")))));
            w.AddFact(new Fact(new Predicate(route, Arrays.AsList(new ID.Integer(2), app_2, new ID.Str("test.fr")))));
            w.AddFact(new Fact(new Predicate(route, Arrays.AsList(new ID.Integer(3), app_0, new ID.Str("www.example.com")))));
            w.AddFact(new Fact(new Predicate(route, Arrays.AsList(new ID.Integer(4), app_1, new ID.Str("mx.example.com")))));

            HashSet <Fact> res = TestSuffix(w, syms, suff, route, ".fr");

            foreach (Fact f in res)
            {
                Console.WriteLine("\t" + syms.PrintFact(f));
            }
            var expected = new HashSet <Fact>(Arrays.AsList(new Fact(new Predicate(suff, Arrays.AsList(app_2, new ID.Str("test.fr"))))));

            Assert.IsTrue(expected.SequenceEqual(res));

            res = TestSuffix(w, syms, suff, route, "example.com");
            foreach (Fact f in res)
            {
                Console.WriteLine("\t" + syms.PrintFact(f));
            }
            expected = new HashSet <Fact>(Arrays.AsList(new Fact(new Predicate(suff,
                                                                               Arrays.AsList(
                                                                                   app_0,
                                                                                   new ID.Str("example.com")))),
                                                        new Fact(new Predicate(suff,
                                                                               Arrays.AsList(app_0, new ID.Str("www.example.com")))),
                                                        new Fact(new Predicate(suff, Arrays.AsList(app_1, new ID.Str("mx.example.com"))))));
            Assert.IsTrue(expected.SequenceEqual(res));
        }
Ejemplo n.º 26
0
        public CSScanner(SymbolTable <TRecord, TType> .CreateRecordDelegate createSymbolRecord, CreateSrcObjDelegate createSourceObject, TType[] types)
        {
            m_symbolTable       = new SymbolTable <TRecord, TType>(createSymbolRecord);
            CreateSourceObject += createSourceObject;
            m_typeList          = types;

            foreach (string symbol in Settings.Default.Keywords.Split(' '))
            {
                m_symbolTable.Add(symbol, types[0]);
            }

            foreach (string symbol in Settings.Default.Modifiers.Split(' '))
            {
                m_symbolTable.Add(symbol, types[1]);
            }

            foreach (string symbol in Settings.Default.Operators.Split(' '))
            {
                m_symbolTable.Add(symbol, types[2]);
            }
        }
        public void InValidBoolComparisonTest()
        {
            SymbolTable.Add("TestBool", QValueType.Boolean);
            var left           = new IdentifierNode(new Location(0, 0), "TestBool");
            var right          = new LiteralNode(new Location(0, 0), "false", QValueType.Integer);
            var comparisonNode = new LogicalExpressionNode(new Location(0, 0), left, LogicalOperator.Or, right);

            var analyser = new StatementTypeAnalyser();
            var result   = analyser.Analyse(comparisonNode);

            Assert.IsFalse(result);
        }
Ejemplo n.º 28
0
        public void TestResource()
        {
            World       w    = new World();
            SymbolTable syms = new SymbolTable();

            ID    authority = syms.Add("authority");
            ID    ambient   = syms.Add("ambient");
            ulong resource  = syms.Insert("resource");
            ulong operation = syms.Insert("operation");
            ulong right     = syms.Insert("right");
            ID    file1     = syms.Add("file1");
            ID    file2     = syms.Add("file2");
            ID    read      = syms.Add("read");
            ID    write     = syms.Add("write");


            w.AddFact(new Fact(new Predicate(resource, Arrays.AsList(ambient, file2))));
            w.AddFact(new Fact(new Predicate(operation, Arrays.AsList(ambient, write))));
            w.AddFact(new Fact(new Predicate(right, Arrays.AsList(authority, file1, read))));
            w.AddFact(new Fact(new Predicate(right, Arrays.AsList(authority, file2, read))));
            w.AddFact(new Fact(new Predicate(right, Arrays.AsList(authority, file1, write))));

            ulong caveat1 = syms.Insert("caveat1");
            //r1: caveat2(#file1) <- resource(#ambient, #file1)
            Rule r1 = new Rule(
                new Predicate(caveat1, Arrays.AsList(file1)),
                Arrays.AsList(new Predicate(resource, Arrays.AsList(ambient, file1))
                              ), new List <Biscuit.Datalog.Expressions.Expression>());

            Console.WriteLine("testing caveat 1(should return nothing): " + syms.PrintRule(r1));
            var res = w.QueryRule(r1);

            Console.WriteLine(res);
            foreach (Fact f in res)
            {
                Console.WriteLine("\t" + syms.PrintFact(f));
            }
            Assert.IsTrue(res.IsEmpty());

            ulong caveat2 = syms.Insert("caveat2");
            ulong var0_id = syms.Insert("var0");
            ID    var0    = new ID.Variable(var0_id);
            //r2: caveat1(0?) <- resource(#ambient, 0?) && operation(#ambient, #read) && right(#authority, 0?, #read)
            Rule r2 = new Rule(
                new Predicate(caveat2, Arrays.AsList(var0)),
                Arrays.AsList(
                    new Predicate(resource, Arrays.AsList(ambient, var0)),
                    new Predicate(operation, Arrays.AsList(ambient, read)),
                    new Predicate(right, Arrays.AsList(authority, var0, read))
                    ), new List <Biscuit.Datalog.Expressions.Expression>());

            Console.WriteLine("testing caveat 2: " + syms.PrintRule(r2));
            res = w.QueryRule(r2);
            Console.WriteLine(res);
            foreach (Fact f in res)
            {
                Console.WriteLine("\t" + syms.PrintFact(f));
            }
            Assert.IsTrue(res.IsEmpty());
        }
        public void InitializeSymbols()
        {
            ImportedMethod currentMethod = Scope.TryImportCurrentMethod();

            if (currentMethod == null)
            {
                return; // Nothing to evaluate if we can't get the current method
            }
            // Add compiler intrinsics
            AddIntrinsics();

            // Add debugger intrinsics
            // (Not implemented yet)

            // Add globals
            ImportedType type = currentMethod.DeclaringType;

            foreach (ImportedField importedfield in type.GetFields())
            {
                IrisType irisType = importedfield.FieldType;
                if (irisType != IrisType.Invalid)
                {
                    SymbolTable.Add(importedfield.Name, irisType, StorageClass.Global, importedfield);
                }
            }

            // Add methods
            foreach (ImportedMethod importedMethod in type.GetMethods())
            {
                Method method = importedMethod.ConvertToIrisMethod();
                if (IsValidMethod(method))
                {
                    SymbolTable.Add(importedMethod.Name, method, StorageClass.Global, importedMethod);
                }
            }

            // Create symbol for query method and transition the SymbolTable to method scope
            _irisMethod = currentMethod.ConvertToIrisMethod();
            SymbolTable.OpenMethod("$.query", _irisMethod);

            // Add symbols for parameters
            foreach (Variable param in _irisMethod.GetParameters())
            {
                SymbolTable.Add(param.Name, param.Type, StorageClass.Argument);
            }

            // Add symbols for local variables
            foreach (LocalVariable local in Scope.GetLocals())
            {
                SymbolTable.Add(local.Name, local.Type, StorageClass.Local, local.Slot);
            }
        }
Ejemplo n.º 30
0
        AddNewSymbolRec(SymbolTableRecord newRec)
        {
            Debug.Assert(m_trans != null);

            ObjectId tblId = Utils.SymTbl.GetSymbolTableId(newRec.GetType(), m_db);

            SymbolTable tbl = (SymbolTable)m_trans.GetObject(tblId, OpenMode.ForWrite);

            Debug.Assert(tbl.Has(newRec.Name) == false);

            tbl.Add(newRec);
            m_trans.AddNewlyCreatedDBObject(newRec, true);
        }
Ejemplo n.º 31
0
    public Label AddLabel(InputElement label, MessageWriter msg)
    {
        Label t = LookupLabel(label);

        if (t != null)
        {
            msg.Error(label, "label '{0}' already defined at {1}", label.str,
                      new Coordinate(t.id).ToString());
        }
        t = new Label(label, labels);
        labels.Add(label.str, t);
        return(t);
    }
Ejemplo n.º 32
0
Archivo: CiParser.cs Proyecto: epi/cito
 public CiParser()
 {
     SymbolTable globals = new SymbolTable();
     globals.Add(CiBoolType.Value);
     globals.Add(CiByteType.Value);
     globals.Add(CiIntType.Value);
     globals.Add(CiStringPtrType.Value);
     globals.Add(new CiConst { Name = "true", Value = true, Type = CiBoolType.Value });
     globals.Add(new CiConst { Name = "false", Value = false, Type = CiBoolType.Value });
     globals.Add(new CiConst { Name = "null", Value = null, Type = CiType.Null });
     this.Symbols = new SymbolTable { Parent = globals };
 }
Ejemplo n.º 33
0
        public static SymbolTable Refactor(this SymbolTable table, string function)
        {
            var st = new SymbolTable(null);

            foreach (var item in table)
            {
                var parts = item.Key.Split('_');

                if (int.Parse(parts[2]) == 0)
                    st.Add(SymbolTable.BuildSymbolId(function, parts[1],
                                                     int.Parse(parts[2])),
                           new Symbol
                               {
                                   Function = function,
                                   Name = parts[1],
                                   Value = item.Value
                               });
            }

            return st;
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a struct declaration by passing a dictionary as the current members.
 /// </summary>
 /// <param name="theMembers">The dictionary with keyvaluepairs you know</param>
 internal StructDeclSymbol(Dictionary<string, Symbol> theMembers)
     : base()
 {
     members = new SymbolTable();
     members.Add(theMembers);
 }
Ejemplo n.º 35
0
        public static EvalResult evaluate_User_Function(SymbolTable symbols, FunCall fun_call)
        {
            FunCall definition = symbols[fun_call.value.value];
            FunCall funArgs = definition.args[0];
            FunCall funBody = definition.args[1];

            if (fun_call.args.Count != funArgs.args.Count)
                return gen_function_call_error(fun_call, funArgs.args.Count);

            var arg_pairs = funArgs.args.Zip(fun_call.args, (a, b) => new Tuple<FunCall, FunCall>(a, b));

            // Bind args and add to symbol table
            foreach (var arg_pair in arg_pairs) symbols.Add(arg_pair.Item1.value.value, arg_pair.Item2);

            return evaluate_FunCall(symbols, funBody);
        }
Ejemplo n.º 36
0
 public void NullObjectsCannotBeAdded()
 {
     SymbolTable table = new SymbolTable();
     Assert.Throws<NullReferenceException>(() => table.Add(null));
 }