1# Copyright 2019 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Utility function to parse text into an ir_data.Expression.""" 16 17from compiler.front_end import module_ir 18from compiler.front_end import parser 19from compiler.front_end import tokenizer 20 21 22def parse(text): 23 """Parses text as an Expression. 24 25 This parses text using the expression subset of the Emboss grammar, and 26 returns an ir_data.Expression. The expression only needs to be syntactically 27 valid; it will not go through symbol resolution or type checking. This 28 function is not intended to be called on arbitrary input; it asserts that the 29 text successfully parses, but does not return errors. 30 31 Arguments: 32 text: The text of an Emboss expression, like "4 + 5" or "$max(1, a, b)". 33 34 Returns: 35 An ir_data.Expression corresponding to the textual form. 36 37 Raises: 38 AssertionError if text is not a well-formed Emboss expression, and 39 assertions are enabled. 40 """ 41 tokens, errors = tokenizer.tokenize(text, "") 42 assert not errors, "{!r}".format(errors) 43 # tokenizer.tokenize always inserts a newline token at the end, which breaks 44 # expression parsing. 45 parse_result = parser.parse_expression(tokens[:-1]) 46 assert not parse_result.error, "{!r}".format(parse_result.error) 47 return module_ir.build_ir(parse_result.parse_tree) 48