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 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 <stack>
  25. #include <memory>
  26. #include "utils/misc.h"
  27. #include "ir/anf.h"
  28. #include "pipeline/parse/parse_base.h"
  29. #include "pipeline/parse/python_adapter.h"
  30. #include "pipeline/parse/function_block.h"
  31. namespace mindspore {
  32. namespace parse {
  33. // Parse status define
  34. enum ParseStatusCode : int {
  35. PARSE_SUCCESS = 0,
  36. PARSE_FUNCTION_IS_NULL, // python function is null
  37. PARSE_PARAMETER_INVALID, // parameter is invalid
  38. PARSE_NO_RETURN, // function no return node
  39. PARSE_NODE_TYPE_NO_MATCH, // ast node type is error
  40. PARSE_NODE_TYPE_UNKOWN, // node type is unkown
  41. PARSE_NODE_METHOD_UNSUPPORTED, // no method to parse the node
  42. PARSE_DONT_RESOLVE_SYMBOL, // can't resolve the string
  43. PARSE_NOT_SUPPORTED_COMPARE_EXPR, // the comparison is not supported
  44. PARSE_FAILURE = 0xFF
  45. };
  46. class AstNodeType;
  47. class ParseAst;
  48. // Save loop info for 'continue' and 'break' statements.
  49. struct Loop {
  50. // Loop header block.
  51. FunctionBlockPtr header;
  52. // Loop iterator node, used in 'for loop'.
  53. AnfNodePtr iterator;
  54. // Loop end block.
  55. FunctionBlockPtr end;
  56. Loop(const FunctionBlockPtr &header, const AnfNodePtr &iterator, const FunctionBlockPtr &end)
  57. : header(header), iterator(iterator), end(end) {}
  58. ~Loop() = default;
  59. };
  60. // Loop context for loop stack management.
  61. class LoopContext {
  62. public:
  63. LoopContext(std::stack<Loop> *loops, const FunctionBlockPtr &header, const AnfNodePtr &iterator) : loops_(loops) {
  64. loops_->emplace(header, iterator, nullptr);
  65. }
  66. ~LoopContext() { loops_->pop(); }
  67. const FunctionBlockPtr &EndBlock() const { return loops_->top().end; }
  68. private:
  69. std::stack<Loop> *loops_;
  70. };
  71. // Parser to parse python function
  72. class Parser {
  73. public:
  74. explicit Parser(const std::shared_ptr<ParseAst> &ast);
  75. ~Parser() {}
  76. FuncGraphPtr ParseFuncGraph();
  77. FuncGraphPtr func_graph() const { return func_graph_; }
  78. ParseStatusCode errcode() const { return errcode_; }
  79. std::shared_ptr<ParseAst> ast() const { return ast_; }
  80. // get location info from the ast node
  81. LocationPtr GetLocation(const py::object &node) const;
  82. static void InitParserEnvironment(const py::object &obj);
  83. static void CleanParserResource();
  84. static FuncGraphPtr GetTopFuncGraph() { return top_func_graph_.lock(); }
  85. static void UpdateTopFuncGraph(const FuncGraphPtr &func_graph);
  86. private:
  87. // process the stmt node method list
  88. FunctionBlockPtr ParseReturn(const FunctionBlockPtr &block, const py::object &node);
  89. // parse expression
  90. FunctionBlockPtr ParseExpr(const FunctionBlockPtr &block, const py::object &node);
  91. // process a if statement
  92. FunctionBlockPtr ParseIf(const FunctionBlockPtr &block, const py::object &node);
  93. // process a while statement
  94. FunctionBlockPtr ParseWhile(const FunctionBlockPtr &block, const py::object &node);
  95. // process a for statement
  96. FunctionBlockPtr ParseFor(const FunctionBlockPtr &block, const py::object &node);
  97. // process a function def statement
  98. FunctionBlockPtr ParseFunctionDef(const FunctionBlockPtr &block, const py::object &node);
  99. // process a augment assign
  100. FunctionBlockPtr ParseAugAssign(const FunctionBlockPtr &block, const py::object &node);
  101. // process a global declaration
  102. FunctionBlockPtr ParseGlobal(const FunctionBlockPtr &block, const py::object &node);
  103. // process assign statement
  104. FunctionBlockPtr ParseAssign(const FunctionBlockPtr &block, const py::object &node);
  105. // process break statement
  106. FunctionBlockPtr ParseBreak(const FunctionBlockPtr &block, const py::object &node);
  107. // process continue statement
  108. FunctionBlockPtr ParseContinue(const FunctionBlockPtr &block, const py::object &node);
  109. // process pass statement
  110. FunctionBlockPtr ParsePass(const FunctionBlockPtr &block, const py::object &node);
  111. // process the expr and slice node method list
  112. AnfNodePtr ParseBinOp(const FunctionBlockPtr &block, const py::object &node);
  113. // process a variable name
  114. AnfNodePtr ParseName(const FunctionBlockPtr &block, const py::object &node);
  115. // process NoneType
  116. AnfNodePtr ParseNone(const FunctionBlockPtr &block, const py::object &node);
  117. // process Ellipsis
  118. AnfNodePtr ParseEllipsis(const FunctionBlockPtr &block, const py::object &node);
  119. // process a integer or float number
  120. AnfNodePtr ParseNum(const FunctionBlockPtr &block, const py::object &node);
  121. // process a string variable
  122. AnfNodePtr ParseStr(const FunctionBlockPtr &block, const py::object &node);
  123. // process a name
  124. AnfNodePtr ParseNameConstant(const FunctionBlockPtr &block, const py::object &node);
  125. // process a function call
  126. AnfNodePtr ParseCall(const FunctionBlockPtr &block, const py::object &node);
  127. // process the if expression
  128. AnfNodePtr ParseIfExp(const FunctionBlockPtr &block, const py::object &node);
  129. // process class type define
  130. AnfNodePtr ParseAttribute(const FunctionBlockPtr &block, const py::object &node);
  131. // process a compare expression
  132. AnfNodePtr ParseCompare(const FunctionBlockPtr &block, const py::object &node);
  133. // process a bool operation
  134. AnfNodePtr ParseBoolOp(const FunctionBlockPtr &block, const py::object &node);
  135. // process a lambda operation
  136. AnfNodePtr ParseLambda(const FunctionBlockPtr &block, const py::object &node);
  137. // process a tuple
  138. AnfNodePtr ParseTuple(const FunctionBlockPtr &block, const py::object &node);
  139. // process a tuple
  140. AnfNodePtr ParseList(const FunctionBlockPtr &block, const py::object &node);
  141. // process a tuple
  142. AnfNodePtr ParseSubscript(const FunctionBlockPtr &block, const py::object &node);
  143. // process a slice
  144. AnfNodePtr ParseSlice(const FunctionBlockPtr &block, const py::object &node);
  145. // process a extslice
  146. AnfNodePtr ParseExtSlice(const FunctionBlockPtr &block, const py::object &node);
  147. // process a tuple
  148. AnfNodePtr ParseIndex(const FunctionBlockPtr &block, const py::object &node);
  149. // process a unaryop
  150. AnfNodePtr ParseUnaryOp(const FunctionBlockPtr &block, const py::object &node);
  151. // process a dict ast node expression
  152. AnfNodePtr ParseDict(const FunctionBlockPtr &block, const py::object &node);
  153. // generate argument nodes for ast function node
  154. void GenerateArgsNodeForFunction(const FunctionBlockPtr &block, const py::object &function_node);
  155. // generate argument default value for ast function node
  156. void GenerateArgsDefaultValueForFunction(const FunctionBlockPtr &block, const py::object &function_node);
  157. // parse ast function node
  158. FunctionBlockPtr ParseFunction(const py::object &function_node, const FunctionBlockPtr &block = nullptr);
  159. // parse ast statements
  160. FunctionBlockPtr ParseStatements(FunctionBlockPtr block, const py::object &stmt_node);
  161. // parse one ast statement node
  162. FunctionBlockPtr ParseStatement(const FunctionBlockPtr &block, const py::object &node);
  163. // parse an ast expresion node
  164. AnfNodePtr ParseExprNode(const FunctionBlockPtr &block, const py::object &node);
  165. void MakeConditionBlocks(const FunctionBlockPtr &block, const FunctionBlockPtr &trueBlock,
  166. const FunctionBlockPtr &falseBlock);
  167. void RemoveUnnecessaryPhis();
  168. // write a new var
  169. void WriteAssignVars(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &value_node);
  170. // assign value to single variable name
  171. void HandleAssignName(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node);
  172. // assign value to tuple
  173. void HandleAssignTuple(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node);
  174. // assign value to class member
  175. void HandleAssignClassMember(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node);
  176. // assign value to subscript
  177. void HandleAssignSubscript(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node);
  178. // process a bool operation value list
  179. AnfNodePtr ProcessBoolOpValueList(const FunctionBlockPtr &block, const py::list &value_list, const py::object &op);
  180. CNodePtr GenerateIteratorInFor(const FunctionBlockPtr &block, const pybind11::object &node,
  181. const AnfNodePtr &op_iter);
  182. CNodePtr GenerateCondInFor(const ParameterPtr &iter_param, const FunctionBlockPtr &header_block,
  183. const AnfNodePtr &op_hasnext);
  184. FunctionBlockPtr GenerateBlockInFor(const TraceInfoPtr &trace_info);
  185. bool ParseKeywordsInCall(const FunctionBlockPtr &block, const py::object &node,
  186. std::vector<AnfNodePtr> *packed_arguments);
  187. bool ParseArgsInCall(const FunctionBlockPtr &block, const py::list &args, std::vector<AnfNodePtr> *packed_arguments,
  188. std::vector<AnfNodePtr> *group_arguments);
  189. AnfNodePtr GenerateAnfNodeForCall(const FunctionBlockPtr &block, const AnfNodePtr &call_function_anf_node,
  190. const std::vector<AnfNodePtr> &packed_arguments,
  191. const std::vector<AnfNodePtr> &group_arguments, bool need_unpack) const;
  192. ScopePtr GetScopeForParseFunction();
  193. void BuildMethodMap();
  194. FunctionBlockPtr MakeFunctionBlock(const Parser &parse) {
  195. FunctionBlockPtr block = std::make_shared<FunctionBlock>(parse);
  196. // In order to keep effect order in the sub-graphs which generated by control flow.
  197. // We copy the flags from the top graph to the sub-graphs.
  198. if (func_graph_ && !func_graph_->flags().empty()) {
  199. block->func_graph()->set_flags(func_graph_->flags());
  200. }
  201. func_block_list_.push_back(block);
  202. return block;
  203. }
  204. // return a make tuple for input elements list
  205. AnfNodePtr GenerateMakeTuple(const FunctionBlockPtr &block, const std::vector<AnfNodePtr> &element_nodes);
  206. // shared_ptr will be hold by GraphManager, so just hold a weak ref here.
  207. static FuncGraphWeakPtr top_func_graph_;
  208. // Python function id, used to indicate whether two CNodes come from the same Python function
  209. const std::shared_ptr<ParseAst> &ast_;
  210. FuncGraphPtr func_graph_;
  211. // error code setwhen parsing ast tree
  212. ParseStatusCode errcode_;
  213. // hold all reference for FunctionBlock in this round of parsing,
  214. // so in FunctionBlock class we can use FunctionBlock* in member
  215. // pre_blocks_ and jumps_ to break reference cycle.
  216. std::vector<FunctionBlockPtr> func_block_list_;
  217. using pStmtFunc = FunctionBlockPtr (Parser::*)(const FunctionBlockPtr &block, const py::object &node);
  218. using pExprFunc = AnfNodePtr (Parser::*)(const FunctionBlockPtr &block, const py::object &node);
  219. // define the function map to parse ast Statement
  220. std::map<std::string, pStmtFunc> stmt_method_map_;
  221. // define the function map to parse ast expression
  222. std::map<std::string, pExprFunc> expr_method_map_;
  223. // Save current loops to support 'continue', 'break' statement.
  224. std::stack<Loop> loops_;
  225. };
  226. // AST node type define code to ast
  227. class AstNodeType {
  228. public:
  229. AstNodeType(const py::object &node, const std::string &name, AstMainType type)
  230. : node_(node), node_name_(name), main_type_(type) {}
  231. ~AstNodeType() {}
  232. std::string node_name() const { return node_name_; }
  233. py::object node() const { return node_; }
  234. AstMainType main_type() const { return main_type_; }
  235. private:
  236. const py::object &node_;
  237. const std::string node_name_;
  238. AstMainType main_type_;
  239. };
  240. using AstNodeTypePtr = std::shared_ptr<AstNodeType>;
  241. // A helper class to parse python function
  242. class ParseAst {
  243. public:
  244. explicit ParseAst(const py::object &obj) : obj_(obj), target_type_(PARSE_TARGET_UNKNOW), function_line_offset_(-1) {}
  245. ~ParseAst() = default;
  246. bool InitParseAstInfo(const std::string &python_mod_get_parse_method = PYTHON_MOD_GET_PARSE_METHOD);
  247. py::object GetAstNode();
  248. py::list GetArgs(const py::object &func_node);
  249. py::list GetArgsDefaultValues(const py::object &func_node);
  250. AstNodeTypePtr GetNodeType(const py::object &node);
  251. AstSubType GetOpType(const py::object &node);
  252. template <class... T>
  253. py::object CallParserObjMethod(const std::string &method, const T &... args) {
  254. return python_adapter::CallPyObjMethod(parser_, method, args...);
  255. }
  256. template <class... T>
  257. py::object CallParseModFunction(const std::string &function, const T &... args) {
  258. return python_adapter::CallPyModFn(module_, function, args...);
  259. }
  260. const std::string &function_name() const { return function_name_; }
  261. const std::string &function_module() const { return function_module_; }
  262. const std::string &function_filename() const { return function_filename_; }
  263. int function_line_offset() const { return function_line_offset_; }
  264. py::function function() { return function_; }
  265. ParseTargetTypeDef target_type() const { return target_type_; }
  266. py::object obj() { return obj_; }
  267. py::object parser() { return parser_; }
  268. py::object module() { return module_; }
  269. py::object ast_tree() { return ast_tree_; }
  270. bool IsClassMember(const py::object &node);
  271. // update the graph flags
  272. bool UpdateFuncGraphFlags(const FuncGraphPtr &func_graph);
  273. private:
  274. // save obj,eg: class instance or function
  275. py::object obj_;
  276. // function or class method.
  277. py::function function_;
  278. py::object ast_tree_;
  279. py::object parser_;
  280. py::module module_;
  281. // Is function or method
  282. ParseTargetTypeDef target_type_;
  283. std::string function_name_;
  284. std::string function_module_;
  285. std::string function_filename_;
  286. int function_line_offset_;
  287. };
  288. AnfNodePtr GetMixedPrecisionCastHelp(const FuncGraphPtr &func_graph, const AnfNodePtr &param);
  289. } // namespace parse
  290. } // namespace mindspore
  291. #endif // PIPELINE_PARSE_PARSE_H_