You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

parse.h 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /**
  2. * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  3. *
  4. * Copyright 2019 Huawei Technologies Co., Ltd
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef PIPELINE_PARSE_PARSE_H_
  19. #define PIPELINE_PARSE_PARSE_H_
  20. #include <vector>
  21. #include <string>
  22. #include <map>
  23. #include <set>
  24. #include <memory>
  25. #include "utils/misc.h"
  26. #include "ir/anf.h"
  27. #include "pipeline/parse/parse_base.h"
  28. #include "pipeline/parse/python_adapter.h"
  29. #include "pipeline/parse/function_block.h"
  30. namespace mindspore {
  31. namespace parse {
  32. // Parse status define
  33. enum ParseStatusCode : int {
  34. PARSE_SUCCESS = 0,
  35. PARSE_FUNCTION_IS_NULL, // python function is null
  36. PARSE_PARAMETER_INVALID, // parameter is invalid
  37. PARSE_NO_RETURN, // function no return node
  38. PARSE_NODE_TYPE_NO_MATCH, // ast node type is error
  39. PARSE_NODE_TYPE_UNKOWN, // node type is unkown
  40. PARSE_NODE_METHOD_UNSUPPORTED, // no method to parse the node
  41. PARSE_DONT_RESOLVE_SYMBOL, // can't resolve the string
  42. PARSE_NOT_SUPPORTED_COMPARE_EXPR, // the comparison is not supported
  43. PARSE_FAILURE = 0xFF
  44. };
  45. class AstNodeType;
  46. class ParseAst;
  47. // Parser to parse python function
  48. class Parser {
  49. public:
  50. explicit Parser(const std::shared_ptr<ParseAst> &ast);
  51. ~Parser() {}
  52. FuncGraphPtr ParseFuncGraph();
  53. FuncGraphPtr func_graph() const { return func_graph_; }
  54. ParseStatusCode errcode() const { return errcode_; }
  55. std::shared_ptr<ParseAst> ast() const { return ast_; }
  56. // get location info from the ast node
  57. LocationPtr GetLocation(const py::object &node) const;
  58. static void InitParserEnvironment(const py::object &obj);
  59. static void CleanParserResource();
  60. static FuncGraphPtr GetTopFuncGraph() { return top_func_graph_.lock(); }
  61. static void UpdateTopFuncGraph(const FuncGraphPtr &func_graph);
  62. private:
  63. // process the stmt node method list
  64. FunctionBlockPtr ParseReturn(const FunctionBlockPtr &block, const py::object &node);
  65. // parse expression
  66. FunctionBlockPtr ParseExpr(const FunctionBlockPtr &block, const py::object &node);
  67. // process a if statement
  68. FunctionBlockPtr ParseIf(const FunctionBlockPtr &block, const py::object &node);
  69. // process a while statement
  70. FunctionBlockPtr ParseWhile(const FunctionBlockPtr &block, const py::object &node);
  71. // process a for statement
  72. FunctionBlockPtr ParseFor(const FunctionBlockPtr &block, const py::object &node);
  73. // process a function def statement
  74. FunctionBlockPtr ParseFunctionDef(const FunctionBlockPtr &block, const py::object &node);
  75. // process a augment assign
  76. FunctionBlockPtr ParseAugAssign(const FunctionBlockPtr &block, const py::object &node);
  77. // process a global declaration
  78. FunctionBlockPtr ParseGlobal(const FunctionBlockPtr &block, const py::object &node);
  79. // process assign statement
  80. FunctionBlockPtr ParseAssign(const FunctionBlockPtr &block, const py::object &node);
  81. // process the expr and slice node method list
  82. AnfNodePtr ParseBinOp(const FunctionBlockPtr &block, const py::object &node);
  83. // process a variable name
  84. AnfNodePtr ParseName(const FunctionBlockPtr &block, const py::object &node);
  85. // process NoneType
  86. AnfNodePtr ParseNone(const FunctionBlockPtr &block, const py::object &node);
  87. // process Ellipsis
  88. AnfNodePtr ParseEllipsis(const FunctionBlockPtr &block, const py::object &node);
  89. // process a integer or float number
  90. AnfNodePtr ParseNum(const FunctionBlockPtr &block, const py::object &node);
  91. // process a string variable
  92. AnfNodePtr ParseStr(const FunctionBlockPtr &block, const py::object &node);
  93. // process a name
  94. AnfNodePtr ParseNameConstant(const FunctionBlockPtr &block, const py::object &node);
  95. // process a function call
  96. AnfNodePtr ParseCall(const FunctionBlockPtr &block, const py::object &node);
  97. // process the if expression
  98. AnfNodePtr ParseIfExp(const FunctionBlockPtr &block, const py::object &node);
  99. // process class type define
  100. AnfNodePtr ParseAttribute(const FunctionBlockPtr &block, const py::object &node);
  101. // process a compare expression
  102. AnfNodePtr ParseCompare(const FunctionBlockPtr &block, const py::object &node);
  103. // process a bool operation
  104. AnfNodePtr ParseBoolOp(const FunctionBlockPtr &block, const py::object &node);
  105. // process a lambda operation
  106. AnfNodePtr ParseLambda(const FunctionBlockPtr &block, const py::object &node);
  107. // process a tuple
  108. AnfNodePtr ParseTuple(const FunctionBlockPtr &block, const py::object &node);
  109. // process a tuple
  110. AnfNodePtr ParseList(const FunctionBlockPtr &block, const py::object &node);
  111. // process a tuple
  112. AnfNodePtr ParseSubscript(const FunctionBlockPtr &block, const py::object &node);
  113. // process a slice
  114. AnfNodePtr ParseSlice(const FunctionBlockPtr &block, const py::object &node);
  115. // process a extslice
  116. AnfNodePtr ParseExtSlice(const FunctionBlockPtr &block, const py::object &node);
  117. // process a tuple
  118. AnfNodePtr ParseIndex(const FunctionBlockPtr &block, const py::object &node);
  119. // process a unaryop
  120. AnfNodePtr ParseUnaryOp(const FunctionBlockPtr &block, const py::object &node);
  121. // process a dict ast node expression
  122. AnfNodePtr ParseDict(const FunctionBlockPtr &block, const py::object &node);
  123. // generate argument nodes for ast function node
  124. void GenerateArgsNodeForFunction(const FunctionBlockPtr &block, const py::object &function_node);
  125. // generate argument default value for ast function node
  126. void GenerateArgsDefaultValueForFunction(const FunctionBlockPtr &block, const py::object &function_node);
  127. // parse ast function node
  128. FunctionBlockPtr ParseFunction(const py::object &function_node, const FunctionBlockPtr &block = nullptr);
  129. // parse ast statements
  130. FunctionBlockPtr ParseStatements(FunctionBlockPtr block, const py::object &stmt_node);
  131. // parse one ast statement node
  132. FunctionBlockPtr ParseStatement(const FunctionBlockPtr &block, const py::object &node);
  133. // parse an ast expresion node
  134. AnfNodePtr ParseExprNode(const FunctionBlockPtr &block, const py::object &node);
  135. void MakeConditionBlocks(const FunctionBlockPtr &block, const FunctionBlockPtr &trueBlock,
  136. const FunctionBlockPtr &falseBlock);
  137. void RemoveUnnecessaryPhis();
  138. // write a new var
  139. void WriteAssignVars(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &value_node);
  140. // assign value to single variable name
  141. void HandleAssignName(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node);
  142. // assign value to tuple
  143. void HandleAssignTuple(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node);
  144. // assign value to class member
  145. void HandleAssignClassMember(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node);
  146. // assign value to subscript
  147. void HandleAssignSubscript(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node);
  148. // process a bool operation value list
  149. AnfNodePtr ProcessBoolOpValueList(const FunctionBlockPtr &block, const py::list &value_list, const py::object &op);
  150. CNodePtr GenerateIteratorInFor(const FunctionBlockPtr &block, const pybind11::object &node,
  151. const AnfNodePtr &op_iter);
  152. CNodePtr GenerateCondInFor(const ParameterPtr &iter_param, const FunctionBlockPtr &header_block,
  153. const AnfNodePtr &op_hasnext);
  154. FunctionBlockPtr GenerateBlockInFor(const TraceInfoPtr &trace_info);
  155. bool ParseKeywordsInCall(const FunctionBlockPtr &block, const py::object &node,
  156. std::vector<AnfNodePtr> *packed_arguments);
  157. bool ParseArgsInCall(const FunctionBlockPtr &block, const py::list &args, std::vector<AnfNodePtr> *packed_arguments,
  158. std::vector<AnfNodePtr> *group_arguments);
  159. AnfNodePtr GenerateAnfNodeForCall(const FunctionBlockPtr &block, const AnfNodePtr &call_function_anf_node,
  160. const std::vector<AnfNodePtr> &packed_arguments,
  161. const std::vector<AnfNodePtr> &group_arguments, bool need_unpack) const;
  162. ScopePtr GetScopeForParseFunction();
  163. void BuildMethodMap();
  164. FunctionBlockPtr MakeFunctionBlock(const Parser &parse) {
  165. FunctionBlockPtr block = std::make_shared<FunctionBlock>(parse);
  166. // In order to keep effect order in the sub-graphs which generated by control flow.
  167. // We copy the flags from the top graph to the sub-graphs.
  168. if (func_graph_ && !func_graph_->flags().empty()) {
  169. block->func_graph()->set_flags(func_graph_->flags());
  170. }
  171. func_block_list_.push_back(block);
  172. return block;
  173. }
  174. // return a make tuple for input elements list
  175. AnfNodePtr GenerateMakeTuple(const FunctionBlockPtr &block, const std::vector<AnfNodePtr> &element_nodes);
  176. // shared_ptr will be hold by GraphManager, so just hold a weak ref here.
  177. static FuncGraphWeakPtr top_func_graph_;
  178. // Python function id, used to indicate whether two CNodes come from the same Python function
  179. const std::shared_ptr<ParseAst> &ast_;
  180. FuncGraphPtr func_graph_;
  181. // error code setwhen parsing ast tree
  182. ParseStatusCode errcode_;
  183. // hold all reference for FunctionBlock in this round of parsing,
  184. // so in FunctionBlock class we can use FunctionBlock* in member
  185. // pre_blocks_ and jumps_ to break reference cycle.
  186. std::vector<FunctionBlockPtr> func_block_list_;
  187. using pStmtFunc = FunctionBlockPtr (Parser::*)(const FunctionBlockPtr &block, const py::object &node);
  188. using pExprFunc = AnfNodePtr (Parser::*)(const FunctionBlockPtr &block, const py::object &node);
  189. // define the function map to parse ast Statement
  190. std::map<std::string, pStmtFunc> stmt_method_map_;
  191. // define the function map to parse ast expression
  192. std::map<std::string, pExprFunc> expr_method_map_;
  193. };
  194. // AST node type define code to ast
  195. class AstNodeType {
  196. public:
  197. AstNodeType(const py::object &node, const std::string &name, AstMainType type)
  198. : node_(node), node_name_(name), main_type_(type) {}
  199. ~AstNodeType() {}
  200. std::string node_name() const { return node_name_; }
  201. py::object node() const { return node_; }
  202. AstMainType main_type() const { return main_type_; }
  203. private:
  204. const py::object &node_;
  205. const std::string node_name_;
  206. AstMainType main_type_;
  207. };
  208. using AstNodeTypePtr = std::shared_ptr<AstNodeType>;
  209. // A helper class to parse python function
  210. class ParseAst {
  211. public:
  212. explicit ParseAst(const py::object &obj) : obj_(obj), target_type_(PARSE_TARGET_UNKNOW), function_line_offset_(-1) {}
  213. ~ParseAst() = default;
  214. bool InitParseAstInfo(const std::string &python_mod_get_parse_method = PYTHON_MOD_GET_PARSE_METHOD);
  215. py::object GetAstNode();
  216. py::list GetArgs(const py::object &func_node);
  217. py::list GetArgsDefaultValues(const py::object &func_node);
  218. AstNodeTypePtr GetNodeType(const py::object &node);
  219. AstSubType GetOpType(const py::object &node);
  220. template <class... T>
  221. py::object CallParserObjMethod(const std::string &method, const T &... args) {
  222. return python_adapter::CallPyObjMethod(parser_, method, args...);
  223. }
  224. template <class... T>
  225. py::object CallParseModFunction(const std::string &function, const T &... args) {
  226. return python_adapter::CallPyModFn(module_, function, args...);
  227. }
  228. const std::string &function_name() const { return function_name_; }
  229. const std::string &function_module() const { return function_module_; }
  230. const std::string &function_filename() const { return function_filename_; }
  231. int function_line_offset() const { return function_line_offset_; }
  232. py::function function() { return function_; }
  233. ParseTargetTypeDef target_type() const { return target_type_; }
  234. py::object obj() { return obj_; }
  235. py::object parser() { return parser_; }
  236. py::object module() { return module_; }
  237. py::object ast_tree() { return ast_tree_; }
  238. bool IsClassMember(const py::object &node);
  239. // update the graph flags
  240. bool UpdateFuncGraphFlags(const FuncGraphPtr &func_graph);
  241. private:
  242. // save obj,eg: class instance or function
  243. py::object obj_;
  244. // function or class method.
  245. py::function function_;
  246. py::object ast_tree_;
  247. py::object parser_;
  248. py::module module_;
  249. // Is function or method
  250. ParseTargetTypeDef target_type_;
  251. std::string function_name_;
  252. std::string function_module_;
  253. std::string function_filename_;
  254. int function_line_offset_;
  255. };
  256. AnfNodePtr GetMixedPrecisionCastHelp(const FuncGraphPtr &func_graph, const AnfNodePtr &param);
  257. } // namespace parse
  258. } // namespace mindspore
  259. #endif // PIPELINE_PARSE_PARSE_H_