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