def testCircumfix(self): self.assertQueryParses( "[1, 2, 3]", ast.Tuple(ast.Literal(1), ast.Literal(2), ast.Literal(3))) self.assertQueryParses( # Lists and selection are non-ambiguous. "10 + ['foo', 'bar'][1]", ast.Sum( ast.Literal(10), ast.Select(ast.Tuple(ast.Literal("foo"), ast.Literal("bar")), ast.Literal(1))))
def testListLiterals(self): self.assertQueryMatches( "[1, 2, 3]", ast.Tuple(ast.Literal(1), ast.Literal(2), ast.Literal(3))) # Empty list literals should work. self.assertQueryMatches("[]", ast.Tuple()) # Arbitrary AST should now be allowed in lists. self.assertQueryMatches( "[x, f(x)]", ast.Tuple(ast.Var("x"), ast.Apply(ast.Var("f"), ast.Var("x"))))
def list(self): """Parse a list (tuple) which can contain any combination of types.""" start = self.tokens.matched.start if self.tokens.accept(common_grammar.rbracket): return ast.Tuple(start=start, end=self.tokens.matched.end, source=self.original) elements = [self.expression()] while self.tokens.accept(common_grammar.comma): elements.append(self.expression()) self.tokens.expect(common_grammar.rbracket) return ast.Tuple(*elements, start=start, end=self.tokens.matched.end, source=self.original)
def testKVPairs(self): self.assertQueryMatches("x: y", ast.Pair(ast.Var("x"), ast.Var("y"))) # KV pairs are used in named function arguments: self.assertQueryMatches( "f(10, 'strings': ['foo', 'bar'])", ast.Apply( ast.Var("f"), ast.Literal(10), ast.Pair(ast.Literal("strings"), ast.Tuple(ast.Literal("foo"), ast.Literal("bar"))))) # They can also appear in repeated values, forming a logical dictionary: self.assertQueryMatches( "('foo': foo, 'bar': bar)", ast.Repeat(ast.Pair(ast.Literal("foo"), ast.Var("foo")), ast.Pair(ast.Literal("bar"), ast.Var("bar"))))
def testBuiltins(self): self.assertQueryMatches( "filter(pslist(), proc.pid == 1)", ast.Filter( ast.Apply(ast.Var("pslist")), ast.Equivalence( ast.Resolve(ast.Var("proc"), ast.Literal("pid")), ast.Literal(1)))) self.assertQueryMatches( "map(pslist(), [proc.pid, proc['command']])", ast.Map( ast.Apply(ast.Var("pslist")), ast.Tuple(ast.Resolve(ast.Var("proc"), ast.Literal("pid")), ast.Select(ast.Var("proc"), ast.Literal("command"))))) self.assertQueryMatches( "bind(x: 1, y: 2)", ast.Bind(ast.Pair(ast.Var("x"), ast.Literal(1)), ast.Pair(ast.Var("y"), ast.Literal(2)))) self.assertQueryRaises("bind (x: 1, y: 2)")
def testLists(self): self.assertQueryMatches( "x inset [1, 2, 3]", ast.Membership( ast.Var("x"), ast.Tuple(ast.Literal(1), ast.Literal(2), ast.Literal(3))))