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.cc 80 kB

5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  1. /**
  2. * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  3. *
  4. * Copyright 2019-2021 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. #include "pipeline/jit/parse/parse.h"
  19. #include <utility>
  20. #include <string>
  21. #include <memory>
  22. #include <unordered_map>
  23. #include <sstream>
  24. #include <algorithm>
  25. #include "pipeline/jit/parse/resolve.h"
  26. #include "frontend/operator/ops.h"
  27. #include "pipeline/jit/parse/data_converter.h"
  28. #include "frontend/operator/composite/composite.h"
  29. #include "utils/ms_context.h"
  30. #include "debug/trace.h"
  31. namespace mindspore {
  32. namespace parse {
  33. FuncGraphPtr ParsePythonCode(const py::object &obj, const std::string &python_mod_get_parse_method) {
  34. (void)python_adapter::set_python_scoped();
  35. if (!obj || py::isinstance<py::none>(obj)) {
  36. MS_LOG(ERROR) << "Parse the python code failed, obj is nullptr or none";
  37. return nullptr;
  38. }
  39. auto ast = std::make_shared<ParseAst>(obj);
  40. bool success = ast->InitParseAstInfo(python_mod_get_parse_method);
  41. if (!success) {
  42. MS_LOG(ERROR) << "Parse code to ast tree failed.";
  43. return nullptr;
  44. }
  45. auto parser = std::make_shared<Parser>(ast);
  46. FuncGraphPtr func_graph = parser->ParseFuncGraph();
  47. if (func_graph == nullptr) {
  48. MS_LOG(ERROR) << "Parse python code failed, errcode = " << parser->errcode();
  49. return nullptr;
  50. }
  51. return func_graph;
  52. }
  53. TypePtr GetMixedPrecisionTargetType(const FuncGraphPtr &func_graph) {
  54. if (func_graph->has_flag(GRAPH_FLAG_MIX_PRECISION_FP32)) {
  55. return kFloat32;
  56. } else if (func_graph->has_flag(GRAPH_FLAG_MIX_PRECISION_FP16)) {
  57. return kFloat16;
  58. } else {
  59. return nullptr;
  60. }
  61. }
  62. // If any mixed precision flag add a cast node after the parameter node.
  63. AnfNodePtr GetMixedPrecisionCastHelp(const FuncGraphPtr &func_graph, const AnfNodePtr &param) {
  64. TypePtr dst_type;
  65. if (func_graph->has_flag(GRAPH_FLAG_MIX_PRECISION_FP32)) {
  66. dst_type = kFloat32;
  67. } else if (func_graph->has_flag(GRAPH_FLAG_MIX_PRECISION_FP16)) {
  68. dst_type = kFloat16;
  69. } else {
  70. return param;
  71. }
  72. auto cast_helper = prim::kPrimMixedPrecisionCast;
  73. auto cast = func_graph->NewCNodeAfter(param, {NewValueNode(cast_helper), NewValueNode(dst_type), param});
  74. return cast;
  75. }
  76. FuncGraphWeakPtr Parser::top_func_graph_ = FuncGraphWeakPtr();
  77. Parser::Parser(const std::shared_ptr<ParseAst> &ast) : ast_(ast) {
  78. errcode_ = PARSE_SUCCESS;
  79. BuildMethodMap();
  80. }
  81. void Parser::BuildMethodMap() {
  82. stmt_method_map_["Return"] = &Parser::ParseReturn;
  83. stmt_method_map_["Expr"] = &Parser::ParseExpr;
  84. stmt_method_map_["If"] = &Parser::ParseIf;
  85. stmt_method_map_["Assign"] = &Parser::ParseAssign;
  86. stmt_method_map_["While"] = &Parser::ParseWhile;
  87. stmt_method_map_["For"] = &Parser::ParseFor;
  88. stmt_method_map_["FunctionDef"] = &Parser::ParseFunctionDef;
  89. stmt_method_map_["AugAssign"] = &Parser::ParseAugAssign;
  90. stmt_method_map_["Global"] = &Parser::ParseGlobal;
  91. stmt_method_map_["Break"] = &Parser::ParseBreak;
  92. stmt_method_map_["Continue"] = &Parser::ParseContinue;
  93. stmt_method_map_["Pass"] = &Parser::ParsePass;
  94. expr_method_map_["NoneType"] = &Parser::ParseNone;
  95. expr_method_map_["BinOp"] = &Parser::ParseBinOp;
  96. expr_method_map_["Name"] = &Parser::ParseName;
  97. expr_method_map_["Num"] = &Parser::ParseNum;
  98. expr_method_map_["Str"] = &Parser::ParseStr;
  99. expr_method_map_["Constant"] = &Parser::ParseConstant;
  100. expr_method_map_["NameConstant"] = &Parser::ParseNameConstant;
  101. expr_method_map_["Call"] = &Parser::ParseCall;
  102. expr_method_map_["IfExp"] = &Parser::ParseIfExp;
  103. expr_method_map_["Attribute"] = &Parser::ParseAttribute;
  104. expr_method_map_["Compare"] = &Parser::ParseCompare;
  105. expr_method_map_["BoolOp"] = &Parser::ParseBoolOp;
  106. expr_method_map_["Lambda"] = &Parser::ParseLambda;
  107. expr_method_map_["Tuple"] = &Parser::ParseTuple;
  108. expr_method_map_["List"] = &Parser::ParseList;
  109. expr_method_map_["Subscript"] = &Parser::ParseSubscript;
  110. expr_method_map_["Slice"] = &Parser::ParseSlice;
  111. expr_method_map_["ExtSlice"] = &Parser::ParseExtSlice;
  112. expr_method_map_["Index"] = &Parser::ParseIndex;
  113. expr_method_map_["UnaryOp"] = &Parser::ParseUnaryOp;
  114. expr_method_map_["Dict"] = &Parser::ParseDict;
  115. expr_method_map_["Ellipsis"] = &Parser::ParseEllipsis;
  116. }
  117. void Parser::UpdateTopFuncGraph(const FuncGraphPtr &func_graph) { top_func_graph_ = FuncGraphWeakPtr(func_graph); }
  118. void Parser::InitParserEnvironment(const py::object &obj) {
  119. Parser::top_func_graph_ = FuncGraphWeakPtr();
  120. ScopeManager::GetInstance().ClearScope();
  121. (void)python_adapter::CallPyFn(PYTHON_MOD_PARSE_MODULE, PYTHON_PARSE_GENERATE_SCOPE, obj);
  122. }
  123. void Parser::CleanParserResource() {
  124. Parser::top_func_graph_ = FuncGraphWeakPtr();
  125. ScopeManager::GetInstance().ClearScope();
  126. }
  127. AnfNodePtr AppendParameterObj(const FuncGraphPtr &func_graph, const py::object &obj) {
  128. MS_EXCEPTION_IF_NULL(func_graph);
  129. auto value = py::cast<tensor::MetaTensorPtr>(obj);
  130. // Parameter object should not be none
  131. if (value == nullptr || !value->is_parameter()) {
  132. MS_LOG(EXCEPTION) << "Parameter error: because obj is not Parameter object.";
  133. }
  134. // Get the parameter name from parameter object
  135. auto param_name = value->param_info()->name();
  136. auto top_graph = func_graph;
  137. // If the parameter node has been created , return it
  138. AnfNodePtr para_node = nullptr;
  139. for (const auto &param : top_graph->parameters()) {
  140. auto param_node = dyn_cast<Parameter>(param);
  141. if (param_node != nullptr && param_node->name() == param_name) {
  142. para_node = param;
  143. break;
  144. }
  145. }
  146. if (para_node == nullptr) {
  147. auto node = top_graph->AddWeightParameter(param_name);
  148. node->set_default_param(value);
  149. // set_abstract for parameter
  150. auto abs = value->ToAbstract();
  151. // Boarden value
  152. abs = abs->Broaden();
  153. node->set_abstract(abs);
  154. para_node = node;
  155. }
  156. return para_node;
  157. }
  158. void UpdataParam(const FuncGraphPtr &top_graph, const py::object &cell) {
  159. auto params = py::list(cell.attr("get_parameters")()).cast<std::vector<py::object>>();
  160. for (const auto &param : params) {
  161. (void)AppendParameterObj(top_graph, param);
  162. }
  163. }
  164. void CheckFuncReturn(const FuncGraphPtr &fn, const std::shared_ptr<ParseAst> &ast) {
  165. // Check whether the functions referred by this function and itself are missing 'return' statement
  166. auto mng = Manage(fn, false);
  167. for (const auto &func_graph : mng->func_graphs()) {
  168. if (func_graph->get_return() != nullptr) {
  169. continue;
  170. }
  171. py::object node = ast->GetAstNode();
  172. py::list ret = ast->CallParserObjMethod(PYTHON_PARSE_GET_LOCATION, node);
  173. py::str desc =
  174. python_adapter::CallPyModFn(ast->module(), PYTHON_MOD_GET_OBJECT_DESCRIPTION, ast->function(), ret[0], ret[1]);
  175. MS_EXCEPTION(TypeError) << "Missing return statement in " << desc.cast<std::string>() << ".";
  176. }
  177. // Clear manager info after checking missing return
  178. for (const auto &fg : mng->func_graphs()) {
  179. fg->ClearAllManagerInfo();
  180. }
  181. }
  182. FuncGraphPtr Parser::ParseFuncGraph() {
  183. // Get ast FunctionDef node
  184. py::object node = ast_->GetAstNode();
  185. FunctionBlockPtr pFnBlock = ParseFunction(node);
  186. if (errcode() != PARSE_SUCCESS) {
  187. MS_LOG(ERROR) << "Parse function error, code is " << errcode();
  188. return nullptr;
  189. }
  190. RemoveUnnecessaryPhis();
  191. MS_EXCEPTION_IF_NULL(pFnBlock);
  192. CheckFuncReturn(pFnBlock->func_graph(), ast_);
  193. return pFnBlock->func_graph();
  194. }
  195. void Parser::GenerateArgsNodeForFunction(const FunctionBlockPtr &block, const py::object &fn_node) {
  196. py::object func_args = python_adapter::GetPyObjAttr(fn_node, "args");
  197. py::object var_arg_node = python_adapter::GetPyObjAttr(func_args, "vararg");
  198. block->func_graph()->set_has_vararg(!py::isinstance<py::none>(var_arg_node));
  199. py::object kw_arg_node = python_adapter::GetPyObjAttr(func_args, "kwarg");
  200. block->func_graph()->set_has_kwarg(!py::isinstance<py::none>(kw_arg_node));
  201. py::list kwonly_args = python_adapter::GetPyObjAttr(func_args, "kwonlyargs");
  202. block->func_graph()->set_kwonlyargs_count(SizeToLong(kwonly_args.size()));
  203. MS_EXCEPTION_IF_NULL(ast_);
  204. py::list args = ast_->GetArgs(fn_node);
  205. for (std::size_t i = 0; i < args.size(); i++) {
  206. std::string arg_name = py::cast<std::string>(args[i].attr("arg"));
  207. if (ast()->target_type() == PARSE_TARGET_OBJECT_INSTANCE) {
  208. if (arg_name == "self") {
  209. continue;
  210. }
  211. }
  212. TraceGuard guard(GetLocation(args[i]));
  213. auto para_node = std::make_shared<Parameter>(block->func_graph());
  214. MS_EXCEPTION_IF_NULL(para_node);
  215. para_node->set_name(arg_name);
  216. para_node->debug_info()->set_name(arg_name);
  217. block->func_graph()->add_parameter(para_node);
  218. AnfNodePtr para_after_cast = GetMixedPrecisionCastHelp(block->func_graph(), para_node);
  219. block->WriteVariable(arg_name, para_after_cast);
  220. MS_LOG(DEBUG) << "The arg[" << i << "] is " << arg_name;
  221. }
  222. }
  223. void Parser::GenerateArgsDefaultValueForFunction(const FunctionBlockPtr &block, const py::object &fn_node) {
  224. py::list defaults = ast_->GetArgsDefaultValues(fn_node);
  225. py::list args = ast_->GetArgs(fn_node);
  226. std::vector<std::string> namelist_for_default_value;
  227. std::vector<AnfNodePtr> default_values;
  228. for (std::size_t i = 0; i < args.size(); i++) {
  229. std::string arg_name = py::cast<std::string>(args[i].attr("arg"));
  230. if (ast()->target_type() == PARSE_TARGET_OBJECT_INSTANCE) {
  231. if (arg_name == "self") {
  232. continue;
  233. }
  234. }
  235. namelist_for_default_value.push_back(arg_name);
  236. if (py::isinstance<py::none>(defaults[i])) {
  237. default_values.push_back(NewValueNode(kNull));
  238. } else {
  239. default_values.push_back(ParseExprNode(block, defaults[i]));
  240. }
  241. }
  242. block->func_graph()->SetDefaultValues(namelist_for_default_value, default_values);
  243. }
  244. ScopePtr Parser::GetScopeForParseFunction() {
  245. ScopePtr scope = ScopeManager::GetInstance().GetCurrentScope();
  246. if (ast()->target_type() == PARSE_TARGET_OBJECT_INSTANCE) {
  247. py::object scope_str = python_adapter::CallPyFn(PYTHON_MOD_PARSE_MODULE, PYTHON_PARSE_GET_SCOPE_NAME, ast_->obj());
  248. if (!py::isinstance<py::none>(scope_str)) {
  249. auto scope_name = py::cast<std::string>(scope_str);
  250. scope = std::make_shared<Scope>(scope_name);
  251. }
  252. }
  253. return scope;
  254. }
  255. FunctionBlockPtr Parser::ParseFunction(const py::object &node, const FunctionBlockPtr &block) {
  256. ScopePtr scope = GetScopeForParseFunction();
  257. // The node created in the parsefunction context, will inherit the scope created using scope_guard
  258. ScopeGuard scope_guard(scope);
  259. TraceGuard trace_guard(data_converter::GetObjKey(ast()->obj())[0], GetLocation(node));
  260. FunctionBlockPtr pFunBlock = MakeFunctionBlock(*this);
  261. if (block != nullptr) {
  262. pFunBlock->AddPrevBlock(block);
  263. } else {
  264. func_graph_ = pFunBlock->func_graph();
  265. }
  266. pFunBlock->Mature();
  267. auto current_fg = pFunBlock->func_graph();
  268. auto function_name = py::cast<std::string>(python_adapter::GetPyObjAttr(node, "name"));
  269. MS_LOG(DEBUG) << "The function name is " << function_name;
  270. current_fg->debug_info()->set_name(function_name);
  271. MS_EXCEPTION_IF_NULL(ast_);
  272. py::list deco_list = node.attr("decorator_list");
  273. if (!deco_list.empty()) {
  274. current_fg->debug_info()->set_deco_location(GetLocation(deco_list));
  275. }
  276. bool set_flag = UpdateFuncGraphFlags(ast_->function(), current_fg);
  277. if (!ast_->obj().is(ast_->function())) {
  278. set_flag = set_flag && UpdateFuncGraphFlags(ast_->obj(), current_fg);
  279. }
  280. if (!set_flag) {
  281. MS_LOG(ERROR) << "Set flags failed";
  282. return nullptr;
  283. }
  284. GenerateArgsNodeForFunction(pFunBlock, node);
  285. // When parsing the top graph of construct, save the top graph
  286. if (GetTopFuncGraph() == nullptr) {
  287. UpdateTopFuncGraph(pFunBlock->func_graph());
  288. }
  289. // Save the function node to block
  290. pFunBlock->WriteVariable(function_name, NewValueNode(current_fg));
  291. py::object funcObj = python_adapter::GetPyObjAttr(node, "body");
  292. (void)ParseStatements(pFunBlock, funcObj);
  293. // Add unused variables as isolate nodes.
  294. for (auto &func_block : func_block_list_) {
  295. if (func_block->func_graph()->get_return() != nullptr) {
  296. // Find unused variables.
  297. func_block->FindIsolatedNodes();
  298. // Attach all isolated nodes.
  299. func_block->AttachIsolatedNodesBeforeReturn();
  300. }
  301. }
  302. if (current_fg->get_return() == nullptr) {
  303. py::list ret = ast_->CallParserObjMethod(PYTHON_PARSE_GET_LOCATION, node);
  304. py::str desc = python_adapter::CallPyModFn(ast_->module(), PYTHON_MOD_GET_OBJECT_DESCRIPTION, node, ret[0], ret[1]);
  305. MS_EXCEPTION(TypeError) << "Missing return statement in " << desc.cast<std::string>() << ".";
  306. }
  307. GenerateArgsDefaultValueForFunction(pFunBlock, node);
  308. return pFunBlock;
  309. }
  310. FunctionBlockPtr Parser::ParseStatements(FunctionBlockPtr block, const py::object &nodes) {
  311. auto node_list = py::cast<py::list>(nodes);
  312. size_t count = py::len(node_list);
  313. MS_LOG(DEBUG) << "The nodes count is " << count;
  314. for (size_t i = 0; i < count; ++i) {
  315. auto node = node_list[i];
  316. block = ParseStatement(block, node);
  317. // Insert appropriate depended items for the function block if it has a return node
  318. if (block->func_graph()->get_return() != nullptr) {
  319. // Skip statements after 'return' (or 'break', 'continue').
  320. break;
  321. }
  322. }
  323. return block;
  324. }
  325. FunctionBlockPtr Parser::ParseStatement(const FunctionBlockPtr &block, const py::object &node) {
  326. TraceGuard trace_guard(GetLocation(node));
  327. auto node_type = ast_->GetNodeType(node);
  328. // Check the node type
  329. AstMainType nodeType = node_type->main_type();
  330. if (nodeType != AST_MAIN_TYPE_STMT) {
  331. MS_LOG(INFO) << "Node type is error : " << nodeType;
  332. return block;
  333. }
  334. // Call the process function
  335. std::string node_name = node_type->node_name();
  336. MS_LOG(DEBUG) << "Ast node is " << node_name;
  337. if (stmt_method_map_.count(node_name)) {
  338. auto stmt_block = (this->*stmt_method_map_[node_name])(block, node);
  339. TraceManager::ClearParseOrResolveDebugInfo();
  340. return stmt_block;
  341. } else {
  342. errcode_ = PARSE_NODE_METHOD_UNSUPPORTED;
  343. MS_LOG(EXCEPTION) << "Unsupported syntax '" << node_name << "'.";
  344. }
  345. }
  346. AnfNodePtr Parser::ParseExprNode(const FunctionBlockPtr &block, const py::object &node) {
  347. MS_LOG(DEBUG) << "Process ast expr";
  348. TraceGuard trace_guard(GetLocation(node));
  349. auto node_type = ast_->GetNodeType(node);
  350. // Check the node type
  351. AstMainType node_main_type = node_type->main_type();
  352. if (node_main_type != AST_MAIN_TYPE_EXPR) {
  353. MS_LOG(ERROR) << "Node type is error : " << node_main_type;
  354. errcode_ = PARSE_NODE_TYPE_NO_MATCH;
  355. return nullptr;
  356. }
  357. // Call the process function
  358. std::string node_name = node_type->node_name();
  359. MS_LOG(DEBUG) << "Ast node is " << node_name;
  360. if (expr_method_map_.count(node_name)) {
  361. auto expr_node = (this->*expr_method_map_[node_name])(block, node);
  362. TraceManager::ClearParseOrResolveDebugInfo();
  363. return expr_node;
  364. } else {
  365. errcode_ = PARSE_NODE_METHOD_UNSUPPORTED;
  366. MS_LOG(EXCEPTION) << "Unsupported syntax '" << node_name << "'.";
  367. }
  368. }
  369. // Process the expr statement and expand it
  370. FunctionBlockPtr Parser::ParseExpr(const FunctionBlockPtr &block, const py::object &node) {
  371. MS_LOG(DEBUG) << "Process ast Expr";
  372. // Expr only have value, no target
  373. py::tuple expand_info = ast_->CallParseModFunction(PYTHON_PARSE_EXPAND_EXPR_STATEMENT, node);
  374. // Refer python function expand_expr_statement, expand_info is one of the following:
  375. // True, expr.value, x
  376. // True, expr.value
  377. // False, None, None
  378. //
  379. // Check the expand info result
  380. auto is_expand = py::cast<bool>(expand_info[0]);
  381. if (is_expand) {
  382. // Process the expr statement
  383. py::object value_object = expand_info[1];
  384. // Make a Expr CNode.
  385. AnfNodePtr call_node = ParseExprNode(block, value_object);
  386. if (py::len(expand_info) == 2) {
  387. // Expression that not assigned to any variable.
  388. // This is usually a call with side effects.
  389. // e.g.: print(x)
  390. // We save it as an isolated node.
  391. auto &no_return_node = call_node;
  392. MS_LOG(INFO) << "Isolated node found(NoReturn), no_return_node: " << no_return_node->DebugString(2)
  393. << ", block: " << block << "/"
  394. << (block->func_graph() ? block->func_graph()->ToString() : "FG(Null)")
  395. << ", Line: " << trace::GetDebugInfo(no_return_node->debug_info(), "", kSourceLineTipDiscard);
  396. block->AddIsolatedNode(no_return_node);
  397. } else {
  398. // Expand the assign statement,
  399. // e.g.: x.append(y) -> x = x.append(y)
  400. py::object target_node = expand_info[2];
  401. WriteAssignVars(block, target_node, call_node);
  402. }
  403. }
  404. return block;
  405. }
  406. LocationPtr Parser::GetLocation(const py::object &node) const {
  407. MS_EXCEPTION_IF_NULL(ast_);
  408. py::list ret = ast_->CallParserObjMethod(PYTHON_PARSE_GET_LOCATION, node);
  409. if (ret.size() < 5) {
  410. MS_LOG(EXCEPTION) << "List size should not be less than 5.";
  411. }
  412. // Refer to Location::Location() for each member of ret: line, column, line_end, column_end.
  413. auto location = std::make_shared<Location>(ret[0].cast<std::string>(), ret[1].cast<int64_t>(), ret[2].cast<int64_t>(),
  414. ret[3].cast<int64_t>(), ret[4].cast<int64_t>());
  415. return location;
  416. }
  417. void Parser::MakeConditionBlocks(const FunctionBlockPtr &pre_block, const FunctionBlockPtr &true_block,
  418. const FunctionBlockPtr &false_block) {
  419. true_block->AddPrevBlock(pre_block);
  420. true_block->Mature();
  421. false_block->AddPrevBlock(pre_block);
  422. false_block->Mature();
  423. }
  424. FunctionBlockPtr Parser::ParseReturn(const FunctionBlockPtr &block, const py::object &node) {
  425. MS_LOG(DEBUG) << "Process ast return";
  426. MS_EXCEPTION_IF_NULL(block);
  427. // Create return valuenode
  428. AnfNodePtr pReturnValueNode = NewValueNode(prim::kPrimReturn);
  429. // Parse the return Statements value
  430. py::object value = python_adapter::GetPyObjAttr(node, "value");
  431. AnfNodePtr pReturnStatementNode = ParseExprNode(block, value);
  432. // Create the cnode
  433. CNodePtr pReturnCNode = block->func_graph()->NewCNodeInOrder({pReturnValueNode, pReturnStatementNode});
  434. block->func_graph()->set_return(pReturnCNode);
  435. return block;
  436. }
  437. // Process binary operators,eg: `a + b`, `a | b`, etc.
  438. AnfNodePtr Parser::ParseBinOp(const FunctionBlockPtr &block, const py::object &node) {
  439. MS_LOG(DEBUG) << "Process ast BinOP";
  440. py::object left = python_adapter::GetPyObjAttr(node, "left");
  441. py::object right = python_adapter::GetPyObjAttr(node, "right");
  442. py::object op = python_adapter::GetPyObjAttr(node, "op");
  443. // Create left and right ANF node
  444. AnfNodePtr left_node = ParseExprNode(block, left);
  445. if (left_node == nullptr) {
  446. MS_LOG(WARNING) << "DoBinOp process left node failed: " << errcode();
  447. return nullptr;
  448. }
  449. AnfNodePtr right_node = ParseExprNode(block, right);
  450. if (right_node == nullptr) {
  451. MS_LOG(WARNING) << "DoBinOp process right node failed:" << errcode();
  452. return nullptr;
  453. }
  454. // Resolve the op
  455. AnfNodePtr op_node = block->MakeResolveAstOp(op);
  456. // Create apply node
  457. return block->func_graph()->NewCNodeInOrder({op_node, left_node, right_node});
  458. }
  459. AnfNodePtr Parser::ParseName(const FunctionBlockPtr &block, const py::object &node) {
  460. MS_LOG(DEBUG) << "Process ast Name";
  461. auto name_id = py::cast<std::string>(python_adapter::GetPyObjAttr(node, "id"));
  462. MS_LOG(DEBUG) << "The Name id is " << name_id;
  463. if (block->IsGlobalVar(name_id)) {
  464. return block->MakeResolveSymbol(name_id);
  465. }
  466. return block->ReadVariable(name_id);
  467. }
  468. AnfNodePtr Parser::ParseNone(const FunctionBlockPtr &, const py::object &) {
  469. MS_LOG(DEBUG) << "Process ast NoneType";
  470. return NewValueNode(kNone);
  471. }
  472. AnfNodePtr Parser::ParseEllipsis(const FunctionBlockPtr &, const py::object &) {
  473. MS_LOG(DEBUG) << "Process ast Ellipsis";
  474. return NewValueNode(kEllipsis);
  475. }
  476. AnfNodePtr Parser::ParseNum(const FunctionBlockPtr &, const py::object &node) {
  477. MS_LOG(DEBUG) << "Process ast Num";
  478. py::object obj = python_adapter::GetPyObjAttr(node, "n");
  479. if (py::isinstance<py::int_>(obj)) {
  480. MS_LOG(INFO) << "The Num is int64_t:" << (std::string)py::str(obj);
  481. auto data = py::cast<int64_t>(obj);
  482. return NewValueNode(data);
  483. } else if (py::isinstance<py::float_>(obj)) {
  484. MS_LOG(INFO) << "The Num is float:" << (std::string)py::str(obj);
  485. auto data = py::cast<float>(obj);
  486. return NewValueNode(data);
  487. } else {
  488. // no else actually
  489. MS_LOG(ERROR) << "Unsupported Num type : " << (std::string)py::str(obj);
  490. errcode_ = PARSE_NODE_TYPE_UNKNOWN;
  491. return nullptr;
  492. }
  493. }
  494. AnfNodePtr Parser::ParseStr(const FunctionBlockPtr &, const py::object &node) {
  495. MS_LOG(DEBUG) << "Process ast Str";
  496. auto str_s = py::cast<std::string>(python_adapter::GetPyObjAttr(node, "s"));
  497. return NewValueNode(str_s);
  498. }
  499. AnfNodePtr Parser::ParseConstant(const FunctionBlockPtr &, const py::object &node) {
  500. MS_LOG(DEBUG) << "Process ast Constant";
  501. py::object obj = python_adapter::GetPyObjAttr(node, "value");
  502. if (py::isinstance<py::bool_>(obj)) {
  503. MS_LOG(INFO) << "The Constant is bool:" << (std::string)py::str(obj);
  504. auto data = py::cast<bool>(obj);
  505. return NewValueNode(data);
  506. } else if (py::isinstance<py::int_>(obj)) {
  507. MS_LOG(INFO) << "The Constant is int64_t:" << (std::string)py::str(obj);
  508. auto data = py::cast<int64_t>(obj);
  509. return NewValueNode(data);
  510. } else if (py::isinstance<py::float_>(obj)) {
  511. MS_LOG(INFO) << "The Constant is float:" << (std::string)py::str(obj);
  512. auto data = py::cast<float>(obj);
  513. return NewValueNode(data);
  514. } else if (py::isinstance<py::str>(obj)) {
  515. MS_LOG(INFO) << "The Constant is string:" << (std::string)py::str(obj);
  516. auto data = py::cast<std::string>(obj);
  517. return NewValueNode(data);
  518. } else if (py::isinstance<py::none>(obj)) {
  519. MS_LOG(INFO) << "The Constant is none:" << (std::string)py::str(obj);
  520. return NewValueNode(kNone);
  521. } else if (py::isinstance<py::ellipsis>(obj)) {
  522. MS_LOG(INFO) << "The Constance is ellipsis:" << (std::string)py::str(obj);
  523. return NewValueNode(kEllipsis);
  524. } else {
  525. // no else actually
  526. MS_EXCEPTION(TypeError) << "Unsupported Constant type : " << (std::string)py::str(obj);
  527. }
  528. }
  529. AnfNodePtr Parser::ParseNameConstant(const FunctionBlockPtr &, const py::object &node) {
  530. MS_LOG(DEBUG) << "Process ast NameConstant";
  531. py::object obj = python_adapter::GetPyObjAttr(node, "value");
  532. if (py::isinstance<py::bool_>(obj)) {
  533. MS_LOG(INFO) << "The NameConstant is bool:" << (std::string)py::str(obj);
  534. auto data = py::cast<bool>(obj);
  535. return NewValueNode(data);
  536. } else if (py::isinstance<py::none>(obj)) {
  537. MS_LOG(INFO) << "The NameConstant is none:" << (std::string)py::str(obj);
  538. return NewValueNode(kNone);
  539. } else {
  540. // no else actually
  541. MS_LOG(ERROR) << "Unsupported NameConstant type: " << (std::string)py::str(obj);
  542. errcode_ = PARSE_NODE_TYPE_UNKNOWN;
  543. return nullptr;
  544. }
  545. }
  546. AnfNodePtr Parser::GenerateMakeTuple(const FunctionBlockPtr &block, const std::vector<AnfNodePtr> &element_nodes) {
  547. AnfNodePtr make_tuple_op = block->MakeResolveOperation(NAMED_PRIMITIVE_MAKETUPLE);
  548. std::vector<AnfNodePtr> make_tuple_nodes;
  549. make_tuple_nodes.push_back(make_tuple_op);
  550. (void)std::transform(element_nodes.begin(), element_nodes.end(), std::back_inserter(make_tuple_nodes),
  551. [](AnfNodePtr arg) -> AnfNodePtr { return arg; });
  552. return block->func_graph()->NewCNodeInOrder(make_tuple_nodes);
  553. }
  554. AnfNodePtr Parser::ParseSuper(const FunctionBlockPtr &block, const py::list &args) {
  555. py::object father_class;
  556. if (args.empty()) {
  557. father_class = py::none();
  558. } else if (args.size() == 2) {
  559. father_class = args[0];
  560. auto arg_type = AstSubType(py::cast<int32_t>(ast_->CallParseModFunction(PYTHON_PARSE_GET_AST_TYPE, args[1])));
  561. if (arg_type != AST_SUB_TYPE_NAME || py::cast<std::string>(python_adapter::GetPyObjAttr(args[1], "id")) != "self") {
  562. MS_EXCEPTION(ArgumentError) << "When call 'super', the second arg should be 'self'.";
  563. }
  564. } else {
  565. MS_EXCEPTION(ArgumentError) << "When call 'super', the args number should be 0 or 2, but got" << args.size() << ".";
  566. }
  567. py::object target_class_instance = ast()->CallParserObjMethod(PYTHON_PARSE_ANALYZE_SUPER, father_class, ast()->obj());
  568. py::object namespace_var = ast_->CallParseModFunction(PYTHON_MOD_GET_MEMBER_NAMESPACE_SYMBOL, target_class_instance);
  569. NameSpacePtr name_space = std::make_shared<NameSpace>(RESOLVE_NAMESPACE_NAME_CLASS_MEMBER, namespace_var);
  570. SymbolPtr symbol = std::make_shared<Symbol>("namespace");
  571. return block->MakeResolve(name_space, symbol);
  572. }
  573. // Process function call, eg : f1(x, y) ...
  574. AnfNodePtr Parser::ParseCall(const FunctionBlockPtr &block, const py::object &node) {
  575. MS_LOG(DEBUG) << "Process ast Call";
  576. // Process function call
  577. py::object function_ast_node = python_adapter::GetPyObjAttr(node, "func");
  578. py::list args = python_adapter::GetPyObjAttr(node, "args");
  579. auto arg_type =
  580. AstSubType(py::cast<int32_t>(ast_->CallParseModFunction(PYTHON_PARSE_GET_AST_TYPE, function_ast_node)));
  581. if (arg_type == AST_SUB_TYPE_NAME) {
  582. auto name_id = py::cast<std::string>(python_adapter::GetPyObjAttr(function_ast_node, "id"));
  583. if (name_id == "super") {
  584. return ParseSuper(block, args);
  585. }
  586. }
  587. AnfNodePtr call_function_anf_node = ParseExprNode(block, function_ast_node);
  588. // Function call arguments should be passed in as groups and unpacked later using unpack call
  589. std::vector<AnfNodePtr> packed_arguments;
  590. std::vector<AnfNodePtr> group_arguments;
  591. bool need_unpack_args = ParseArgsInCall(block, args, &packed_arguments, &group_arguments);
  592. bool need_unpack_keywords = ParseKeywordsInCall(block, node, &packed_arguments);
  593. // If there is stared or keyword argument, unpack may be needed
  594. bool need_unpack = need_unpack_args || need_unpack_keywords;
  595. return GenerateAnfNodeForCall(block, call_function_anf_node, packed_arguments, group_arguments, need_unpack);
  596. }
  597. CNodePtr MakeUnpackCall(const FuncGraphPtr &func_graph, const AnfNodePtr &call_function_anf_node,
  598. const std::vector<AnfNodePtr> &packed_arguments) {
  599. std::vector<AnfNodePtr> unpack_call_nodes;
  600. auto unpack_call_op = NewValueNode(std::make_shared<prim::UnpackCall>(NAMED_METAGRAPH_UNPACKCALL));
  601. unpack_call_nodes.push_back(unpack_call_op);
  602. unpack_call_nodes.push_back(call_function_anf_node);
  603. (void)std::transform(packed_arguments.begin(), packed_arguments.end(), std::back_inserter(unpack_call_nodes),
  604. [](AnfNodePtr node) -> AnfNodePtr { return node; });
  605. CNodePtr unpack_call = func_graph->NewCNodeInOrder(unpack_call_nodes);
  606. return unpack_call;
  607. }
  608. AnfNodePtr Parser::GenerateAnfNodeForCall(const FunctionBlockPtr &block, const AnfNodePtr &call_function_anf_node,
  609. const std::vector<AnfNodePtr> &packed_arguments,
  610. const std::vector<AnfNodePtr> &group_arguments, bool need_unpack) const {
  611. // If there is keyword arguments or starred, using an unpack_call op to unpack the argument
  612. if (need_unpack) {
  613. return MakeUnpackCall(block->func_graph(), call_function_anf_node, packed_arguments);
  614. }
  615. // else there is no keyword arguments and starred, parsed as normal arguments without unpack
  616. std::vector<AnfNodePtr> func_call_nodes;
  617. func_call_nodes.push_back(call_function_anf_node);
  618. (void)std::transform(group_arguments.begin(), group_arguments.end(), std::back_inserter(func_call_nodes),
  619. [](AnfNodePtr node) -> AnfNodePtr { return node; });
  620. CNodePtr call_anf_node = block->func_graph()->NewCNodeInOrder(func_call_nodes);
  621. return call_anf_node;
  622. }
  623. bool Parser::ParseArgsInCall(const FunctionBlockPtr &block, const py::list &args,
  624. std::vector<AnfNodePtr> *packed_arguments, std::vector<AnfNodePtr> *group_arguments) {
  625. bool need_unpack = false;
  626. for (size_t i = 0; i < args.size(); i++) {
  627. auto arg_node = AstSubType(py::cast<int32_t>(ast_->CallParseModFunction(PYTHON_PARSE_GET_AST_TYPE, args[i])));
  628. if (arg_node == AST_SUB_TYPE_STARRED) {
  629. if (!group_arguments->empty()) {
  630. packed_arguments->push_back(GenerateMakeTuple(block, *group_arguments));
  631. }
  632. packed_arguments->push_back(ParseExprNode(block, python_adapter::GetPyObjAttr(args[i], "value")));
  633. group_arguments->clear();
  634. need_unpack = true;
  635. } else {
  636. group_arguments->push_back(ParseExprNode(block, args[i]));
  637. }
  638. }
  639. if (!group_arguments->empty()) {
  640. packed_arguments->push_back(GenerateMakeTuple(block, *group_arguments));
  641. }
  642. return need_unpack;
  643. }
  644. bool Parser::ParseKeywordsInCall(const FunctionBlockPtr &block, const py::object &node,
  645. std::vector<AnfNodePtr> *packed_arguments) {
  646. bool need_unpack = false;
  647. py::list keywords = python_adapter::GetPyObjAttr(node, "keywords");
  648. if (!keywords.empty()) {
  649. need_unpack = true;
  650. std::vector<AnfNodePtr> keys;
  651. std::vector<AnfNodePtr> values;
  652. for (size_t index = 0; index < keywords.size(); index++) {
  653. auto kw_key = python_adapter::GetPyObjAttr(keywords[index], "arg");
  654. auto kw_value = python_adapter::GetPyObjAttr(keywords[index], "value");
  655. if (py::isinstance<py::none>(kw_key)) {
  656. packed_arguments->push_back(ParseExprNode(block, kw_value));
  657. } else {
  658. auto kw_key_c = kw_key.cast<std::string>();
  659. keys.push_back(NewValueNode(kw_key_c));
  660. values.push_back(ParseExprNode(block, kw_value));
  661. }
  662. }
  663. auto keys_tuple = GenerateMakeTuple(block, keys);
  664. auto values_tuple = GenerateMakeTuple(block, values);
  665. auto make_dict_op = block->MakeResolveOperation(NAMED_PRIMITIVE_MAKEDICT);
  666. std::vector<AnfNodePtr> make_dict_nodes;
  667. make_dict_nodes.push_back(make_dict_op);
  668. make_dict_nodes.push_back(keys_tuple);
  669. make_dict_nodes.push_back(values_tuple);
  670. packed_arguments->push_back(block->func_graph()->NewCNodeInOrder(make_dict_nodes));
  671. }
  672. return need_unpack;
  673. }
  674. // Process call attributes of class type define, eg: x.y()
  675. AnfNodePtr Parser::ParseAttribute(const FunctionBlockPtr &block, const py::object &node) {
  676. MS_LOG(DEBUG) << "Process ast Attribute";
  677. // Process class value,eg: self.xx
  678. if (ast()->target_type() == PARSE_TARGET_OBJECT_INSTANCE) {
  679. if (ast_->IsClassMember(node)) {
  680. std::string var_name = "self.";
  681. std::string attr_name = node.attr("attr").cast<std::string>();
  682. (void)var_name.append(attr_name);
  683. auto attr_obj = ast()->obj().attr(attr_name.c_str());
  684. if (py::hasattr(ast()->obj(), attr_name.c_str()) &&
  685. (py::hasattr(attr_obj, PYTHON_PRIMITIVE_FLAG) || py::isinstance<py::int_>(attr_obj) ||
  686. py::isinstance<py::float_>(attr_obj) || py::isinstance<py::bool_>(attr_obj) ||
  687. py::isinstance<py::str>(attr_obj) || data_converter::IsCellInstance(attr_obj))) {
  688. return block->MakeResolveSymbol(var_name);
  689. } else {
  690. return block->ReadVariable(var_name);
  691. }
  692. }
  693. }
  694. // Process the get attr
  695. // Use the Primitive replace the operation resolve node (getattr),
  696. // because the getattr will eventually be converted to Primitive node
  697. AnfNodePtr op_node = NewValueNode(prim::kPrimGetAttr);
  698. // Process the attr body
  699. py::object value_body = python_adapter::GetPyObjAttr(node, "value");
  700. AnfNodePtr value_node = ParseExprNode(block, value_body);
  701. if (value_node == nullptr) {
  702. MS_LOG(WARNING) << "Parse attribute failed";
  703. return nullptr;
  704. }
  705. // Process the node attr
  706. auto attr_str = python_adapter::GetPyObjAttr(node, "attr").cast<std::string>();
  707. MS_LOG(DEBUG) << "Attr = " << attr_str;
  708. AnfNodePtr attr_node = nullptr;
  709. {
  710. TraceGuard guard(GetLocation(python_adapter::GetPyObjAttr(node, "attr")));
  711. attr_node = NewValueNode(attr_str);
  712. }
  713. // Create the apply node
  714. return block->func_graph()->NewCNodeInOrder({op_node, value_node, attr_node});
  715. }
  716. // Process comparison expression : a == b. a > b etc.
  717. AnfNodePtr Parser::ParseCompare(const FunctionBlockPtr &block, const py::object &node) {
  718. MS_LOG(DEBUG) << "Process ast Compare";
  719. // For python comparison ,there may be if x>y>5 ,
  720. // Which there is two ops , but we only support one now
  721. py::list ops = python_adapter::GetPyObjAttr(node, "ops");
  722. if (ops.size() > MAX_COMPARISON_OPS_SUPPORTED) {
  723. MS_LOG(ERROR) << "MindSpore does not support comparison with operators more than one now, ops size =" << ops.size();
  724. return nullptr;
  725. }
  726. py::object left = python_adapter::GetPyObjAttr(node, "left");
  727. py::list comparators = python_adapter::GetPyObjAttr(node, "comparators");
  728. AnfNodePtr left_node = ParseExprNode(block, left);
  729. AnfNodePtr right_node = ParseExprNode(block, comparators[0]);
  730. MS_EXCEPTION_IF_NULL(block);
  731. AnfNodePtr op_node = block->MakeResolveAstOp(ops[0]);
  732. return block->func_graph()->NewCNodeInOrder({op_node, left_node, right_node});
  733. }
  734. AnfNodePtr Parser::ProcessBoolOpValueList(const FunctionBlockPtr &block, const py::list &value_list, AstSubType mode) {
  735. // If there is only one bool op now
  736. if (value_list.size() == 1) {
  737. AnfNodePtr first_node = ParseExprNode(block, value_list[0]);
  738. return first_node;
  739. } else {
  740. py::object first = value_list[0];
  741. py::list rest;
  742. for (size_t i = 1; i < value_list.size(); i++) {
  743. rest.append(value_list[i]);
  744. }
  745. MS_EXCEPTION_IF_NULL(block);
  746. FunctionBlockPtr true_block = nullptr;
  747. FunctionBlockPtr false_block = nullptr;
  748. {
  749. TraceGuard guard(std::make_shared<TraceIfExpTrueBranch>(block->func_graph()->debug_info()));
  750. true_block = MakeFunctionBlock(*this);
  751. }
  752. {
  753. TraceGuard guard(std::make_shared<TraceIfExpFalseBranch>(block->func_graph()->debug_info()));
  754. false_block = MakeFunctionBlock(*this);
  755. }
  756. MakeConditionBlocks(block, true_block, false_block);
  757. FunctionBlockPtr b1, b2;
  758. // If it is and, we need to process the rest nodes;
  759. // If it is or, we continue to next
  760. if (mode == AST_SUB_TYPE_AND) {
  761. b1 = true_block;
  762. b2 = false_block;
  763. } else if (mode == AST_SUB_TYPE_OR) {
  764. b2 = true_block;
  765. b1 = false_block;
  766. } else {
  767. MS_LOG(ERROR) << "Not supported mode: " << mode;
  768. return nullptr;
  769. }
  770. AnfNodePtr test_node = ParseExprNode(block, first);
  771. AnfNodePtr rest_node = ProcessBoolOpValueList(b1, rest, mode);
  772. b1->func_graph()->set_output(rest_node);
  773. b2->func_graph()->set_output(test_node);
  774. auto cond_node = block->ForceToBoolNode(test_node);
  775. auto switch_app = block->func_graph()->NewCNodeInOrder({NewValueNode(prim::kPrimSwitch), cond_node,
  776. NewValueNode(true_block->func_graph()),
  777. NewValueNode(false_block->func_graph())});
  778. std::vector<AnfNodePtr> call_graph_nodes{switch_app};
  779. auto switch_app_call = block->func_graph()->NewCNodeInOrder(call_graph_nodes);
  780. return switch_app_call;
  781. }
  782. }
  783. // Process comparison expression : a and b. a or b .
  784. AnfNodePtr Parser::ParseBoolOp(const FunctionBlockPtr &block, const py::object &node) {
  785. MS_LOG(DEBUG) << "Process ast BoolOp";
  786. py::object op_node = python_adapter::GetPyObjAttr(node, "op");
  787. AstSubType op_type = ast_->GetOpType(op_node);
  788. if (op_type == AST_SUB_TYPE_UNKNOWN) {
  789. MS_LOG(WARNING) << "ProcessBoolOp, got unknown op type";
  790. return nullptr;
  791. }
  792. py::list op_values = python_adapter::GetPyObjAttr(node, "values");
  793. return ProcessBoolOpValueList(block, op_values, op_type);
  794. }
  795. // Process a function def
  796. FunctionBlockPtr Parser::ParseFunctionDef(const FunctionBlockPtr &block, const py::object &node) {
  797. MS_LOG(DEBUG) << "Process ast FunctionDef";
  798. FunctionBlockPtr function_block = ParseFunction(node, block);
  799. MS_EXCEPTION_IF_NULL(function_block);
  800. // Get function name
  801. py::str name = python_adapter::GetPyObjAttr(node, "name");
  802. std::string function_name = name;
  803. ValueNodePtr valuenode_graph = NewValueNode(function_block->func_graph());
  804. block->WriteVariable(function_name, valuenode_graph);
  805. return block;
  806. }
  807. // Process a lambda expression . like lambda x,y: x + y
  808. AnfNodePtr Parser::ParseLambda(const FunctionBlockPtr &block, const py::object &node) {
  809. MS_LOG(DEBUG) << "Process ast Lambda";
  810. FunctionBlockPtr func_block = MakeFunctionBlock(*this);
  811. func_block->AddPrevBlock(block);
  812. func_block->Mature();
  813. // Get lambda args
  814. py::list args = ast_->GetArgs(node);
  815. for (std::size_t i = 0; i < args.size(); i++) {
  816. std::string arg = py::cast<std::string>(args[i].attr("arg"));
  817. TraceGuard guard(GetLocation(args[i]));
  818. auto para_node = std::make_shared<Parameter>(func_block->func_graph());
  819. para_node->debug_info()->set_name(arg);
  820. func_block->func_graph()->add_parameter(para_node);
  821. func_block->WriteVariable(arg, para_node);
  822. MS_LOG(DEBUG) << "The arg[" << i << "] is " << arg;
  823. }
  824. py::object body_node = python_adapter::GetPyObjAttr(node, "body");
  825. AnfNodePtr lambda_body_node = ParseExprNode(func_block, body_node);
  826. func_block->func_graph()->set_output(lambda_body_node);
  827. ValueNodePtr const_graph = NewValueNode(func_block->func_graph());
  828. return const_graph;
  829. }
  830. // Process a tuple
  831. AnfNodePtr Parser::ParseTuple(const FunctionBlockPtr &block, const py::object &node) {
  832. MS_LOG(DEBUG) << "Process ast Tuple";
  833. MS_EXCEPTION_IF_NULL(block);
  834. py::tuple elts = python_adapter::GetPyObjAttr(node, "elts");
  835. if (elts.size() == 0) {
  836. auto empty_tuple = std::vector<ValuePtr>();
  837. return NewValueNode(std::make_shared<ValueTuple>(empty_tuple));
  838. }
  839. std::vector<AnfNodePtr> tuple_vec;
  840. AnfNodePtr make_tuple_op = block->MakeResolveOperation(NAMED_PRIMITIVE_MAKETUPLE);
  841. tuple_vec.emplace_back(make_tuple_op);
  842. for (size_t i = 0; i < elts.size(); i++) {
  843. AnfNodePtr node_ptr = ParseExprNode(block, elts[i]);
  844. tuple_vec.emplace_back(node_ptr);
  845. }
  846. CNodePtr tuple_app = block->func_graph()->NewCNodeInOrder(tuple_vec);
  847. return tuple_app;
  848. }
  849. // Process a list
  850. AnfNodePtr Parser::ParseList(const FunctionBlockPtr &block, const py::object &node) {
  851. MS_LOG(DEBUG) << "Process ast List";
  852. MS_EXCEPTION_IF_NULL(block);
  853. py::list elts = python_adapter::GetPyObjAttr(node, "elts");
  854. if (elts.size() == 0) {
  855. auto empty_list = std::vector<ValuePtr>();
  856. return NewValueNode(std::make_shared<ValueList>(empty_list));
  857. }
  858. std::vector<AnfNodePtr> list_vec;
  859. AnfNodePtr make_list_op = block->MakeResolveOperation(NAMED_PRIMITIVE_MAKELIST);
  860. list_vec.emplace_back(make_list_op);
  861. for (size_t i = 0; i < elts.size(); i++) {
  862. AnfNodePtr node_ptr = ParseExprNode(block, elts[i]);
  863. list_vec.emplace_back(node_ptr);
  864. }
  865. CNodePtr list_app = block->func_graph()->NewCNodeInOrder(list_vec);
  866. return list_app;
  867. }
  868. // Process a subscript, such as x[y] , node expressed as value[slice]
  869. AnfNodePtr Parser::ParseSubscript(const FunctionBlockPtr &block, const py::object &node) {
  870. MS_LOG(DEBUG) << "Process ast Subscript";
  871. MS_EXCEPTION_IF_NULL(block);
  872. AnfNodePtr op_getitem = block->MakeResolveOperation(NAMED_PRIMITIVE_GETITEM);
  873. py::object value_node = python_adapter::GetPyObjAttr(node, "value");
  874. py::object slice_node = python_adapter::GetPyObjAttr(node, "slice");
  875. AnfNodePtr value = ParseExprNode(block, value_node);
  876. AnfNodePtr slice = ParseExprNode(block, slice_node);
  877. return block->func_graph()->NewCNodeInOrder({op_getitem, value, slice});
  878. }
  879. // Process a slice, get the slice value
  880. AnfNodePtr Parser::ParseSlice(const FunctionBlockPtr &block, const py::object &node) {
  881. MS_LOG(DEBUG) << "Process ast Slice";
  882. MS_EXCEPTION_IF_NULL(block);
  883. AnfNodePtr op_makeslice = block->MakeResolveOperation(NAMED_PRIMITIVE_MAKESLICE);
  884. py::object start = python_adapter::GetPyObjAttr(node, "lower");
  885. py::object stop = python_adapter::GetPyObjAttr(node, "upper");
  886. py::object step = python_adapter::GetPyObjAttr(node, "step");
  887. AnfNodePtr start_node = ParseExprNode(block, start);
  888. AnfNodePtr stop_node = ParseExprNode(block, stop);
  889. AnfNodePtr step_node = ParseExprNode(block, step);
  890. return block->func_graph()->NewCNodeInOrder({op_makeslice, start_node, stop_node, step_node});
  891. }
  892. // Process a extslice
  893. AnfNodePtr Parser::ParseExtSlice(const FunctionBlockPtr &block, const py::object &node) {
  894. MS_LOG(DEBUG) << "Process ast ExtSlice";
  895. MS_EXCEPTION_IF_NULL(block);
  896. AnfNodePtr make_tuple_op = block->MakeResolveOperation(NAMED_PRIMITIVE_MAKETUPLE);
  897. py::tuple slice_tuple = python_adapter::GetPyObjAttr(node, "dims");
  898. std::vector<AnfNodePtr> node_vec;
  899. node_vec.emplace_back(make_tuple_op);
  900. for (size_t i = 0; i < slice_tuple.size(); i++) {
  901. AnfNodePtr node_ptr = ParseExprNode(block, slice_tuple[i]);
  902. node_vec.emplace_back(node_ptr);
  903. }
  904. CNodePtr tuple_conde = block->func_graph()->NewCNodeInOrder(node_vec);
  905. return tuple_conde;
  906. }
  907. // Process a index, get the index number
  908. AnfNodePtr Parser::ParseIndex(const FunctionBlockPtr &block, const py::object &node) {
  909. MS_LOG(DEBUG) << "Process ast Index";
  910. py::object value_node = python_adapter::GetPyObjAttr(node, "value");
  911. return ParseExprNode(block, value_node);
  912. }
  913. // Process a UnaryOp, +a, -b
  914. AnfNodePtr Parser::ParseUnaryOp(const FunctionBlockPtr &block, const py::object &node) {
  915. MS_LOG(DEBUG) << "Process ast UnaryOp";
  916. py::object op = python_adapter::GetPyObjAttr(node, "op");
  917. MS_EXCEPTION_IF_NULL(block);
  918. // Resolve the op
  919. AnfNodePtr op_node = block->MakeResolveAstOp(op);
  920. py::object operand = python_adapter::GetPyObjAttr(node, "operand");
  921. AnfNodePtr operand_node = ParseExprNode(block, operand);
  922. return block->func_graph()->NewCNodeInOrder({op_node, operand_node});
  923. }
  924. // Process a dict ast node expression
  925. AnfNodePtr Parser::ParseDict(const FunctionBlockPtr &block, const py::object &node) {
  926. MS_LOG(DEBUG) << "Process ast Dict";
  927. py::list keys = node.attr("keys");
  928. py::list values = node.attr("values");
  929. std::vector<AnfNodePtr> key_nodes;
  930. std::vector<AnfNodePtr> value_nodes;
  931. for (size_t i = 0; i < keys.size(); i++) {
  932. key_nodes.push_back(ParseExprNode(block, keys[i]));
  933. value_nodes.push_back(ParseExprNode(block, values[i]));
  934. }
  935. auto keys_tuple = GenerateMakeTuple(block, key_nodes);
  936. auto values_tuple = GenerateMakeTuple(block, value_nodes);
  937. MS_EXCEPTION_IF_NULL(block);
  938. auto make_dict_op = block->MakeResolveOperation(NAMED_PRIMITIVE_MAKEDICT);
  939. return block->func_graph()->NewCNodeInOrder({make_dict_op, keys_tuple, values_tuple});
  940. }
  941. // Process a augment assign such as a += b or mat[stride_slice] += b.
  942. FunctionBlockPtr Parser::ParseAugAssign(const FunctionBlockPtr &block, const py::object &node) {
  943. MS_LOG(DEBUG) << "Process ast AugAssign";
  944. MS_EXCEPTION_IF_NULL(block);
  945. MS_EXCEPTION_IF_NULL(ast_);
  946. py::object target_obj = python_adapter::GetPyObjAttr(node, "target");
  947. py::object op_obj = python_adapter::GetPyObjAttr(node, "op");
  948. py::object value_obj = python_adapter::GetPyObjAttr(node, "value");
  949. AnfNodePtr target_node = nullptr;
  950. AnfNodePtr op_node = block->MakeResolveAstOp(op_obj);
  951. AnfNodePtr value_node = ParseExprNode(block, value_obj);
  952. auto ast_type = AstSubType(py::cast<int32_t>(ast_->CallParseModFunction(PYTHON_PARSE_GET_AST_TYPE, target_obj)));
  953. if (ast_type == AST_SUB_TYPE_NAME) {
  954. target_node = ParseName(block, target_obj);
  955. } else if (ast_type == AST_SUB_TYPE_SUBSCRIPT) {
  956. target_node = ParseSubscript(block, target_obj);
  957. } else if (ast_->IsClassMember(target_obj)) {
  958. target_node = ParseAttribute(block, target_obj);
  959. } else {
  960. MS_LOG(EXCEPTION) << "Not supported augassign";
  961. }
  962. if (target_node == nullptr) {
  963. MS_LOG(EXCEPTION) << "Can not get target node ";
  964. }
  965. CNodePtr augassign_app = block->func_graph()->NewCNodeInOrder({op_node, target_node, value_node});
  966. WriteAssignVars(block, target_obj, augassign_app);
  967. return block;
  968. }
  969. // Process global declaration such as 'global x';
  970. FunctionBlockPtr Parser::ParseGlobal(const FunctionBlockPtr &block, const py::object &node) {
  971. MS_LOG(DEBUG) << "Process ast Global";
  972. MS_EXCEPTION_IF_NULL(block);
  973. py::list vars = python_adapter::GetPyObjAttr(node, "names");
  974. for (auto &item : vars) {
  975. block->AddGlobalVar(py::cast<std::string>(item));
  976. }
  977. return block;
  978. }
  979. // Process a if statement
  980. FunctionBlockPtr Parser::ParseIf(const FunctionBlockPtr &block, const py::object &node) {
  981. MS_LOG(DEBUG) << "Process ast If";
  982. py::object test_node = python_adapter::GetPyObjAttr(node, "test");
  983. AnfNodePtr condition_node = ParseExprNode(block, test_node);
  984. MS_EXCEPTION_IF_NULL(block);
  985. CNodePtr bool_node = block->ForceToBoolNode(condition_node);
  986. FunctionBlockPtr true_block = nullptr;
  987. FunctionBlockPtr false_block = nullptr;
  988. {
  989. TraceGuard guard(std::make_shared<TraceIfStmtTrueBranch>(block->func_graph()->debug_info()));
  990. true_block = MakeFunctionBlock(*this);
  991. }
  992. {
  993. TraceGuard guard(std::make_shared<TraceIfStmtFalseBranch>(block->func_graph()->debug_info()));
  994. false_block = MakeFunctionBlock(*this);
  995. }
  996. MakeConditionBlocks(block, true_block, false_block);
  997. FunctionBlockPtr after_block = nullptr;
  998. {
  999. TraceGuard guard(std::make_shared<TraceIfStmtAfterBranch>(block->func_graph()->debug_info()));
  1000. after_block = MakeFunctionBlock(*this);
  1001. }
  1002. if (MsContext::GetInstance()->backend_policy() != "ge") {
  1003. // For backends excludes 'ge', it can handle multi graph call, use this flag to
  1004. // generate call not inline `after_block` graph to reduce if by if switch expansion.
  1005. after_block->func_graph()->set_flag(FUNC_GRAPH_FLAG_AFTER_BLOCK, true);
  1006. }
  1007. // Process the if-true branch
  1008. py::object bodyNode = python_adapter::GetPyObjAttr(node, "body");
  1009. FunctionBlockPtr true_end = ParseStatements(true_block, bodyNode);
  1010. // If the return_ is set ,it has its own continuation block
  1011. if (true_end->func_graph()->get_return() == nullptr) {
  1012. true_end->Jump(after_block, nullptr);
  1013. }
  1014. // Process the orelse branch
  1015. py::object orelseNode = python_adapter::GetPyObjAttr(node, "orelse");
  1016. FunctionBlockPtr false_end = ParseStatements(false_block, orelseNode);
  1017. // If the return_ is set ,it has its own continuation block
  1018. if (false_end->func_graph()->get_return() == nullptr) {
  1019. false_end->Jump(after_block, nullptr);
  1020. }
  1021. block->ConditionalJump(bool_node, true_block, false_block);
  1022. after_block->Mature();
  1023. return after_block;
  1024. }
  1025. FunctionBlockPtr Parser::ParseWhile(const FunctionBlockPtr &block, const py::object &node) {
  1026. MS_LOG(DEBUG) << "Process ast While";
  1027. MS_EXCEPTION_IF_NULL(block);
  1028. MS_LOG(INFO) << "Parse while statement";
  1029. FunctionBlockPtr header_block = nullptr;
  1030. FunctionBlockPtr body_block = nullptr;
  1031. FunctionBlockPtr after_block = nullptr;
  1032. {
  1033. TraceGuard guard(std::make_shared<TraceWhileHeader>(block->func_graph()->debug_info()));
  1034. header_block = MakeFunctionBlock(*this);
  1035. }
  1036. {
  1037. TraceGuard guard(std::make_shared<TraceWhileBody>(block->func_graph()->debug_info()));
  1038. body_block = MakeFunctionBlock(*this);
  1039. }
  1040. {
  1041. TraceGuard guard(std::make_shared<TraceWhileAfter>(block->func_graph()->debug_info()));
  1042. after_block = MakeFunctionBlock(*this);
  1043. }
  1044. body_block->AddPrevBlock(header_block);
  1045. after_block->AddPrevBlock(header_block);
  1046. block->Jump(header_block, nullptr);
  1047. py::object test_node = python_adapter::GetPyObjAttr(node, "test");
  1048. AnfNodePtr condition_node = ParseExprNode(header_block, test_node);
  1049. condition_node = header_block->ForceToWhileCond(condition_node);
  1050. body_block->Mature();
  1051. header_block->ConditionalJump(condition_node, body_block, after_block);
  1052. // Parse loop body statements with loop context.
  1053. LoopContext loop_context{&loops_, header_block, nullptr};
  1054. py::object body_node = python_adapter::GetPyObjAttr(node, "body");
  1055. FunctionBlockPtr after_body = ParseStatements(body_block, body_node);
  1056. if (after_body->func_graph()->get_return() == nullptr) {
  1057. after_body->Jump(header_block, nullptr);
  1058. }
  1059. header_block->Mature();
  1060. after_block->Mature();
  1061. auto &end_block = loop_context.EndBlock();
  1062. if (end_block) {
  1063. // end_block exists if we encounter 'break' in loop body.
  1064. after_block->Jump(end_block, nullptr);
  1065. end_block->Mature();
  1066. return end_block;
  1067. }
  1068. // No 'break', no end_block.
  1069. return after_block;
  1070. }
  1071. CNodePtr Parser::GenerateIteratorInFor(const FunctionBlockPtr &block, const py::object &node,
  1072. const AnfNodePtr &op_iter) {
  1073. py::object iter_node = python_adapter::GetPyObjAttr(node, "iter");
  1074. AnfNodePtr iter_anf_node = ParseExprNode(block, iter_node);
  1075. return block->func_graph()->NewCNodeInOrder({op_iter, iter_anf_node});
  1076. }
  1077. CNodePtr Parser::GenerateCondInFor(const ParameterPtr &iter_param, const FunctionBlockPtr &header_block,
  1078. const AnfNodePtr &op_hasnext) {
  1079. MS_EXCEPTION_IF_NULL(header_block);
  1080. return header_block->func_graph()->NewCNodeInOrder({op_hasnext, iter_param});
  1081. }
  1082. FunctionBlockPtr Parser::GenerateBlockInFor(const TraceInfoPtr &trace_info) {
  1083. TraceGuard trace_guard(trace_info);
  1084. FunctionBlockPtr body_block = MakeFunctionBlock(*this);
  1085. return body_block;
  1086. }
  1087. int64_t GetForTransToWhileLoop() {
  1088. static const auto loop_str = common::GetEnv("ENV_FOR_TO_WHILE_LOOP");
  1089. // int64 support 63bits positive num mostly.
  1090. if (loop_str.size() > 63 || loop_str.empty()) {
  1091. return MAX_FOR_LOOP_COUNT;
  1092. }
  1093. if (std::any_of(loop_str.begin(), loop_str.end(), [](char c) { return c < '0' || c > '9'; })) {
  1094. return MAX_FOR_LOOP_COUNT;
  1095. }
  1096. int64_t loop_count;
  1097. std::stringstream ss;
  1098. ss << loop_str;
  1099. ss >> loop_count;
  1100. return loop_count;
  1101. }
  1102. // A for loop will generate 3 functions :the test, the body, and the continuation
  1103. // for x in xs:
  1104. // body
  1105. // It is compiled to be following statement
  1106. // if len(xs) < max_loop_cnt:
  1107. // ParseForIter() // use iter to implement for loop, which always unroll loop
  1108. // else:
  1109. // ParseForLoop() // use loop var to implement for loop, which always sink loop
  1110. FunctionBlockPtr Parser::ParseFor(const FunctionBlockPtr &block, const py::object &node) {
  1111. MS_LOG(DEBUG) << "Process ast For, create an if else statement";
  1112. MS_EXCEPTION_IF_NULL(block);
  1113. // Create statement 'len(xs) < MAX_FOR_LOOP_COUNT'
  1114. AnfNodePtr op_len = block->MakeResolveSymbol(NAMED_PRIMITIVE_LEN);
  1115. py::object iter_obj = python_adapter::GetPyObjAttr(node, NAMED_PRIMITIVE_ITER);
  1116. AnfNodePtr iter_node = ParseExprNode(block, iter_obj);
  1117. CNodePtr len_iter = block->func_graph()->NewCNodeInOrder({op_len, iter_node});
  1118. CNodePtr bool_node = block->func_graph()->NewCNodeInOrder(
  1119. {NewValueNode(prim::kPrimScalarLt), len_iter, NewValueNode(GetForTransToWhileLoop())});
  1120. // Create statement 'if len(xs) < prim::MAX_FOR_LOOP_COUNT then ParseForIter else ParseForLoop'
  1121. FunctionBlockPtr true_block = nullptr;
  1122. FunctionBlockPtr false_block = nullptr;
  1123. {
  1124. TraceGuard guard(std::make_shared<TraceIfStmtTrueBranch>(block->func_graph()->debug_info()));
  1125. true_block = MakeFunctionBlock(*this);
  1126. }
  1127. {
  1128. TraceGuard guard(std::make_shared<TraceIfStmtFalseBranch>(block->func_graph()->debug_info()));
  1129. false_block = MakeFunctionBlock(*this);
  1130. }
  1131. MakeConditionBlocks(block, true_block, false_block);
  1132. FunctionBlockPtr after_block = nullptr;
  1133. {
  1134. TraceGuard guard(std::make_shared<TraceIfStmtAfterBranch>(block->func_graph()->debug_info()));
  1135. after_block = MakeFunctionBlock(*this);
  1136. }
  1137. FunctionBlockPtr true_end = ParseForIter(true_block, node);
  1138. true_end->Jump(after_block, nullptr);
  1139. FunctionBlockPtr false_end = ParseForLoop(false_block, node);
  1140. false_end->Jump(after_block, nullptr);
  1141. block->ConditionalJump(bool_node, true_block, false_block);
  1142. after_block->Mature();
  1143. return after_block;
  1144. }
  1145. // A for loop will generate 3 functions :the test, the body, and the continuation
  1146. // for x in xs:
  1147. // body
  1148. // It is compiled to be following statement
  1149. // it = iter(xs)
  1150. // while hastnext(it)
  1151. // x, it = next(it)
  1152. // body
  1153. FunctionBlockPtr Parser::ParseForIter(const FunctionBlockPtr &block, const py::object &node) {
  1154. MS_LOG(DEBUG) << "Process ast For";
  1155. MS_EXCEPTION_IF_NULL(block);
  1156. AnfNodePtr op_iter = block->MakeResolveOperation(NAMED_PRIMITIVE_ITER);
  1157. AnfNodePtr op_next = block->MakeResolveOperation(NAMED_PRIMITIVE_NEXT);
  1158. AnfNodePtr op_getitem = block->MakeResolveOperation(NAMED_PRIMITIVE_GETITEM);
  1159. AnfNodePtr op_hasnext = block->MakeResolveOperation(NAMED_PRIMITIVE_HASNEXT);
  1160. // Generate the iterator apply
  1161. CNodePtr iter_apply = GenerateIteratorInFor(block, node, op_iter);
  1162. MS_EXCEPTION_IF_NULL(iter_apply);
  1163. FunctionBlockPtr header_block =
  1164. GenerateBlockInFor(std::make_shared<TraceForHeader>(block->func_graph()->debug_info()));
  1165. MS_EXCEPTION_IF_NULL(header_block);
  1166. // Generate the hasnext apply which is a condition
  1167. ParameterPtr iter_param = header_block->func_graph()->add_parameter();
  1168. CNodePtr cond_apply = GenerateCondInFor(iter_param, header_block, op_hasnext);
  1169. // Generate the body of the for statement
  1170. FunctionBlockPtr body_block = GenerateBlockInFor(std::make_shared<TraceForBody>(block->func_graph()->debug_info()));
  1171. MS_EXCEPTION_IF_NULL(body_block);
  1172. body_block->AddPrevBlock(header_block);
  1173. // Generate the iterator next apply
  1174. // Process as following: `app = next(it); target = app[0]; it = app[1];`
  1175. CNodePtr app = body_block->func_graph()->NewCNodeInOrder({op_next, iter_param});
  1176. CNodePtr target_app =
  1177. body_block->func_graph()->NewCNodeInOrder({op_getitem, app, NewValueNode(static_cast<int64_t>(0))});
  1178. py::object target_node = python_adapter::GetPyObjAttr(node, "target");
  1179. CNodePtr iter2_app =
  1180. body_block->func_graph()->NewCNodeInOrder({op_getitem, app, NewValueNode(static_cast<int64_t>(1))});
  1181. WriteAssignVars(body_block, target_node, target_app);
  1182. // Link the variable name with the target
  1183. auto it_info = std::make_shared<TraceIterator>(target_app->debug_info());
  1184. iter_param->debug_info()->set_trace_info(it_info);
  1185. iter2_app->debug_info()->set_trace_info(it_info);
  1186. iter_apply->debug_info()->set_trace_info(it_info);
  1187. FunctionBlockPtr after_block = nullptr;
  1188. {
  1189. TraceGuard guard(std::make_shared<TraceForAfter>(block->func_graph()->debug_info()));
  1190. after_block = MakeFunctionBlock(*this);
  1191. }
  1192. MS_EXCEPTION_IF_NULL(after_block);
  1193. after_block->AddPrevBlock(header_block);
  1194. block->Jump(header_block, iter_apply);
  1195. body_block->Mature();
  1196. header_block->ConditionalJump(cond_apply, body_block, after_block);
  1197. // Parse loop body statements with loop context.
  1198. LoopContext loop_context{&loops_, header_block, iter2_app};
  1199. py::object body_node = python_adapter::GetPyObjAttr(node, "body");
  1200. FunctionBlockPtr after_body_block = ParseStatements(body_block, body_node);
  1201. if (after_body_block->func_graph()->get_return() == nullptr) {
  1202. after_body_block->Jump(header_block, iter2_app);
  1203. }
  1204. header_block->Mature();
  1205. after_block->Mature();
  1206. auto &end_block = loop_context.EndBlock();
  1207. if (end_block) {
  1208. // end_block exists if we encounter 'break' in loop body.
  1209. after_block->Jump(end_block, nullptr);
  1210. end_block->Mature();
  1211. return end_block;
  1212. }
  1213. // No 'break', no end_block.
  1214. return after_block;
  1215. }
  1216. // A for loop will generate 3 functions :the test, the body, and the continuation
  1217. // for x in xs:
  1218. // body
  1219. // It is compiled to be following statement
  1220. // i = 0
  1221. // while i < len(xs)
  1222. // x = xs[i]
  1223. // i = i + 1
  1224. // body
  1225. FunctionBlockPtr Parser::ParseForLoop(const FunctionBlockPtr &block, const py::object &node) {
  1226. MS_LOG(DEBUG) << "Process ast For by loop variable";
  1227. MS_EXCEPTION_IF_NULL(block);
  1228. AnfNodePtr op_len = block->MakeResolveSymbol(NAMED_PRIMITIVE_LEN);
  1229. AnfNodePtr op_getitem = block->MakeResolveOperation(NAMED_PRIMITIVE_GETITEM);
  1230. // Get variable name of 'x' in statement 'for x in xs'
  1231. py::object target_node = python_adapter::GetPyObjAttr(node, "target");
  1232. // Create statement 'len(xs)'
  1233. py::object iter_obj = python_adapter::GetPyObjAttr(node, "iter");
  1234. AnfNodePtr iter_node = ParseExprNode(block, iter_obj);
  1235. MS_EXCEPTION_IF_NULL(iter_node);
  1236. // Generate node for loop count and convert it to tensor, to make the loop not unroll
  1237. CNodePtr scalar_len = block->func_graph()->NewCNodeInOrder({op_len, iter_node});
  1238. auto scalar_to_tensor = prim::GetPythonOps("ScalarToTensor", "mindspore.ops.operations");
  1239. auto scalar_to_tensor_node = block->func_graph()->NewCNodeInOrder({NewValueNode(scalar_to_tensor)});
  1240. CNodePtr len_iter = block->func_graph()->NewCNodeInOrder({scalar_to_tensor_node, scalar_len});
  1241. FunctionBlockPtr header_block =
  1242. GenerateBlockInFor(std::make_shared<TraceForHeader>(block->func_graph()->debug_info()));
  1243. MS_EXCEPTION_IF_NULL(header_block);
  1244. // Create loop variable 'i'
  1245. ParameterPtr loop_var = header_block->func_graph()->add_parameter();
  1246. // Create loop condition 'i < len(xs)'
  1247. auto prim_less = prim::GetPythonOps("Less", "mindspore.ops.operations");
  1248. auto less_node = header_block->func_graph()->NewCNodeInOrder({NewValueNode(prim_less)});
  1249. CNodePtr cond_node = header_block->func_graph()->NewCNodeInOrder({less_node, loop_var, len_iter});
  1250. // Generate the body of the for statement
  1251. FunctionBlockPtr body_block = GenerateBlockInFor(std::make_shared<TraceForBody>(block->func_graph()->debug_info()));
  1252. MS_EXCEPTION_IF_NULL(body_block);
  1253. body_block->AddPrevBlock(header_block);
  1254. // Create 'x = xs[i]'
  1255. CNodePtr target_var = body_block->func_graph()->NewCNodeInOrder({op_getitem, iter_node, loop_var});
  1256. WriteAssignVars(body_block, target_node, target_var);
  1257. // Create 'i = i + 1'
  1258. CNodePtr loop_var_inc = body_block->func_graph()->NewCNodeInOrder(
  1259. {NewValueNode(prim::kPrimScalarAdd), loop_var, NewValueNode(static_cast<int64_t>(1))});
  1260. body_block->WriteVariable(loop_var->name(), loop_var_inc);
  1261. // Link the variable name with the target
  1262. auto it_info = std::make_shared<TraceIterator>(loop_var_inc->debug_info());
  1263. loop_var->debug_info()->set_trace_info(it_info);
  1264. len_iter->debug_info()->set_trace_info(it_info);
  1265. FunctionBlockPtr after_block = nullptr;
  1266. {
  1267. TraceGuard guard(std::make_shared<TraceForAfter>(block->func_graph()->debug_info()));
  1268. after_block = MakeFunctionBlock(*this);
  1269. }
  1270. MS_EXCEPTION_IF_NULL(after_block);
  1271. after_block->AddPrevBlock(header_block);
  1272. block->Jump(header_block, NewValueNode(static_cast<int64_t>(0)));
  1273. body_block->Mature();
  1274. header_block->ConditionalJump(cond_node, body_block, after_block, false);
  1275. // Parse loop body statements with loop context.
  1276. LoopContext loop_context{&loops_, header_block, loop_var_inc};
  1277. py::object body_node = python_adapter::GetPyObjAttr(node, "body");
  1278. FunctionBlockPtr after_body_block = ParseStatements(body_block, body_node);
  1279. if (after_body_block->func_graph()->get_return() == nullptr) {
  1280. after_body_block->Jump(header_block, loop_var_inc);
  1281. }
  1282. header_block->Mature();
  1283. after_block->Mature();
  1284. auto &end_block = loop_context.EndBlock();
  1285. if (end_block) {
  1286. // end_block exists if we encounter 'break' in loop body.
  1287. after_block->Jump(end_block, nullptr);
  1288. end_block->Mature();
  1289. return end_block;
  1290. }
  1291. // No 'break', no end_block.
  1292. return after_block;
  1293. }
  1294. AnfNodePtr Parser::ParseIfExp(const FunctionBlockPtr &block, const py::object &node) {
  1295. MS_LOG(DEBUG) << "Process ast IfExp";
  1296. MS_EXCEPTION_IF_NULL(block);
  1297. py::object test_node = python_adapter::GetPyObjAttr(node, "test");
  1298. AnfNodePtr condition_node = ParseExprNode(block, test_node);
  1299. CNodePtr bool_node = block->ForceToBoolNode(condition_node);
  1300. FunctionBlockPtr true_block = nullptr;
  1301. FunctionBlockPtr false_block = nullptr;
  1302. {
  1303. TraceGuard guard(std::make_shared<TraceIfExpTrueBranch>(block->func_graph()->debug_info()));
  1304. true_block = MakeFunctionBlock(*this);
  1305. }
  1306. {
  1307. TraceGuard guard(std::make_shared<TraceIfExpFalseBranch>(block->func_graph()->debug_info()));
  1308. false_block = MakeFunctionBlock(*this);
  1309. }
  1310. MakeConditionBlocks(block, true_block, false_block);
  1311. // Process the if-true branch
  1312. py::object bodyNode = python_adapter::GetPyObjAttr(node, "body");
  1313. true_block->func_graph()->debug_info()->set_location(GetLocation(bodyNode));
  1314. AnfNodePtr true_node = ParseExprNode(true_block, bodyNode);
  1315. // Process the orelse branch
  1316. py::object orelseNode = python_adapter::GetPyObjAttr(node, "orelse");
  1317. false_block->func_graph()->debug_info()->set_location(GetLocation(orelseNode));
  1318. AnfNodePtr false_node = ParseExprNode(false_block, orelseNode);
  1319. true_block->func_graph()->set_output(true_node);
  1320. false_block->func_graph()->set_output(false_node);
  1321. // Use the Primitive replace the operation resolve node (switch),
  1322. // because the switch will eventually be converted to Primitive node
  1323. CNodePtr switch_app = block->func_graph()->NewCNodeInOrder({NewValueNode(prim::kPrimSwitch), bool_node,
  1324. NewValueNode(true_block->func_graph()),
  1325. NewValueNode(false_block->func_graph())});
  1326. std::vector<AnfNodePtr> call_graph_nodes{switch_app};
  1327. CNodePtr switch_app_call = block->func_graph()->NewCNodeInOrder(call_graph_nodes);
  1328. return switch_app_call;
  1329. }
  1330. void Parser::HandleAssignName(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node) {
  1331. MS_EXCEPTION_IF_NULL(block);
  1332. MS_EXCEPTION_IF_NULL(assigned_node);
  1333. py::str name = python_adapter::GetPyObjAttr(targ, "id");
  1334. std::string name_id = name;
  1335. assigned_node->debug_info()->set_name(name_id);
  1336. // Set the debug name of the constant graph
  1337. if (IsValueNode<FuncGraph>(assigned_node)) {
  1338. // The value should be graph
  1339. auto fg = GetValueNode<FuncGraphPtr>(assigned_node);
  1340. if (fg->debug_info()->name().empty()) {
  1341. fg->debug_info()->set_name(name_id);
  1342. }
  1343. }
  1344. block->WriteVariable(name_id, assigned_node);
  1345. }
  1346. void Parser::HandleAssignTuple(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &assigned_node) {
  1347. MS_EXCEPTION_IF_NULL(block);
  1348. AnfNodePtr op_getitem = block->MakeResolveOperation(NAMED_PRIMITIVE_GETITEM);
  1349. py::list items = python_adapter::GetPyObjAttr(targ, "elts");
  1350. for (size_t i = 0; i < items.size(); i++) {
  1351. // Use the Primitive replace the operation resolve node (getitem),
  1352. // because the getitem will eventually be converted to Primitive node
  1353. CNodePtr item_apply =
  1354. block->func_graph()->NewCNodeInOrder({op_getitem, assigned_node, NewValueNode(static_cast<int64_t>(i))});
  1355. py::object elt = items[i];
  1356. WriteAssignVars(block, elt, item_apply);
  1357. }
  1358. }
  1359. void Parser::HandleAssignClassMember(const FunctionBlockPtr &block, const py::object &targ,
  1360. const AnfNodePtr &assigned_node) {
  1361. // Now only support the self.xx = xxxxx, can't support x.y = xxxx
  1362. AnfNodePtr target_node = ParseExprNode(block, targ);
  1363. MS_EXCEPTION_IF_NULL(target_node);
  1364. auto attr_name = targ.attr("attr").cast<std::string>();
  1365. std::string var_name = "self." + attr_name;
  1366. // Now only support the self.xxx = yyy, where self.xxx must be a defined Parameter type
  1367. if (!py::hasattr(ast()->obj(), common::SafeCStr(attr_name))) {
  1368. MS_EXCEPTION(TypeError) << "'" << var_name << "' should be a Parameter, but not defined.";
  1369. }
  1370. auto obj = ast()->obj().attr(common::SafeCStr(attr_name));
  1371. auto obj_type = obj.attr("__class__").attr("__name__");
  1372. if (!py::hasattr(obj, "__parameter__")) {
  1373. MS_EXCEPTION(TypeError) << "'" << var_name << "' should be a Parameter, but got '"
  1374. << py::str(obj).cast<std::string>() << "' with type '"
  1375. << py::str(obj_type).cast<std::string>() << ".";
  1376. }
  1377. MS_EXCEPTION_IF_NULL(block);
  1378. MS_LOG(DEBUG) << "SetState write " << var_name << " : " << target_node->ToString();
  1379. block->SetStateAssign(target_node, assigned_node);
  1380. }
  1381. void Parser::HandleAssignSubscript(const FunctionBlockPtr &block, const py::object &targ,
  1382. const AnfNodePtr &assigned_node) {
  1383. MS_EXCEPTION_IF_NULL(block);
  1384. AnfNodePtr op_setitem = block->MakeResolveOperation(NAMED_PRIMITIVE_SETITEM);
  1385. py::object value_obj = python_adapter::GetPyObjAttr(targ, "value");
  1386. py::object slice_obj = python_adapter::GetPyObjAttr(targ, "slice");
  1387. AnfNodePtr value_node = ParseExprNode(block, value_obj);
  1388. AnfNodePtr slice_node = ParseExprNode(block, slice_obj);
  1389. CNodePtr setitem_app = block->func_graph()->NewCNodeInOrder({op_setitem, value_node, slice_node, assigned_node});
  1390. // Getitem apply should return the sequence data structure itself
  1391. std::string var_name;
  1392. if (ast_->IsClassMember(value_obj)) {
  1393. auto attr_name = value_obj.attr("attr").cast<std::string>();
  1394. var_name = "self." + attr_name;
  1395. if (!py::hasattr(ast()->obj(), common::SafeCStr(attr_name))) {
  1396. MS_EXCEPTION(TypeError) << "'" << var_name << "' was not defined in the class '__init__' function.";
  1397. }
  1398. auto obj = ast()->obj().attr(common::SafeCStr(attr_name));
  1399. auto obj_type = obj.attr("__class__").attr("__name__");
  1400. if (!py::hasattr(obj, "__parameter__")) {
  1401. MS_EXCEPTION(TypeError) << "'" << var_name << "' should be a Parameter, but got '"
  1402. << py::str(obj).cast<std::string>() << "' with type '"
  1403. << py::str(obj_type).cast<std::string>() << "'.";
  1404. }
  1405. block->WriteVariable(var_name, setitem_app);
  1406. return;
  1407. }
  1408. if (AstSubType(py::cast<int32_t>(ast_->CallParseModFunction(PYTHON_PARSE_GET_AST_TYPE, value_obj))) ==
  1409. AST_SUB_TYPE_SUBSCRIPT) {
  1410. HandleAssignSubscript(block, value_obj, setitem_app);
  1411. return;
  1412. }
  1413. if (!py::hasattr(value_obj, "id")) {
  1414. MS_EXCEPTION(TypeError) << "Attribute id not found in " << py::str(value_obj).cast<std::string>();
  1415. }
  1416. var_name = value_obj.attr("id").cast<std::string>();
  1417. block->WriteVariable(var_name, setitem_app);
  1418. }
  1419. void Parser::WriteAssignVars(const FunctionBlockPtr &block, const py::object &targ, const AnfNodePtr &value_node) {
  1420. MS_EXCEPTION_IF_NULL(value_node);
  1421. MS_LOG(DEBUG) << "Process WriteAssignVars";
  1422. auto ast_type = AstSubType(py::cast<int32_t>(ast_->CallParseModFunction(PYTHON_PARSE_GET_AST_TYPE, targ)));
  1423. if (ast_type == AST_SUB_TYPE_NAME) {
  1424. HandleAssignName(block, targ, value_node);
  1425. } else if (ast_type == AST_SUB_TYPE_TUPLE) {
  1426. HandleAssignTuple(block, targ, value_node);
  1427. } else if (ast_type == AST_SUB_TYPE_SUBSCRIPT) {
  1428. HandleAssignSubscript(block, targ, value_node);
  1429. } else if (ast_->IsClassMember(targ)) {
  1430. HandleAssignClassMember(block, targ, value_node);
  1431. } else if (ast_type == AST_SUB_TYPE_ATTRIBUTE) {
  1432. MS_LOG(EXCEPTION) << "The subnet attributes cannot be changed in the network"
  1433. << " NodeInfo: " << trace::GetDebugInfo(value_node->debug_info());
  1434. } else {
  1435. MS_LOG(EXCEPTION) << "Not supported assign type: " << ast_type
  1436. << " NodeInfo: " << trace::GetDebugInfo(value_node->debug_info());
  1437. }
  1438. }
  1439. // Process a assign statement, such as a =b, a,b = tup
  1440. FunctionBlockPtr Parser::ParseAssign(const FunctionBlockPtr &block, const py::object &node) {
  1441. MS_LOG(DEBUG) << "Process ast assign";
  1442. py::object value_object = python_adapter::GetPyObjAttr(node, "value");
  1443. AnfNodePtr value_node = ParseExprNode(block, value_object);
  1444. py::object targets_object = python_adapter::GetPyObjAttr(node, "targets");
  1445. py::int_ pcount = python_adapter::CallPyObjMethod(targets_object, "__len__");
  1446. size_t count = LongToSize(pcount);
  1447. MS_LOG(DEBUG) << "The nodes count is " << count;
  1448. for (size_t i = 0; i < count; i++) {
  1449. auto target_node = py::cast<py::list>(targets_object)[i];
  1450. WriteAssignVars(block, target_node, value_node);
  1451. }
  1452. return block;
  1453. }
  1454. FunctionBlockPtr Parser::ParseBreak(const FunctionBlockPtr &block, const py::object &node) {
  1455. if (loops_.empty()) {
  1456. // Report error if loop context not set for the 'break' statement.
  1457. MS_LOG(EXCEPTION) << "Unexpected 'break'.";
  1458. }
  1459. // Get current loop.
  1460. Loop &loop = loops_.top();
  1461. if (loop.end == nullptr) {
  1462. // Create end_block if it is not existed.
  1463. TraceGuard trace_guard(std::make_shared<TraceLoopEnd>(block->func_graph()->debug_info()));
  1464. loop.end = MakeFunctionBlock(*this);
  1465. }
  1466. // Jump to the end_block.
  1467. block->Jump(loop.end, nullptr);
  1468. return block;
  1469. }
  1470. FunctionBlockPtr Parser::ParseContinue(const FunctionBlockPtr &block, const py::object &node) {
  1471. if (loops_.empty()) {
  1472. // Report error if loop context not set for the 'continue' statement.
  1473. MS_LOG(EXCEPTION) << "Unexpected 'continue.";
  1474. }
  1475. // Jump to the header of the loop with iterator called.
  1476. Loop &loop = loops_.top();
  1477. block->Jump(loop.header, loop.iterator);
  1478. return block;
  1479. }
  1480. FunctionBlockPtr Parser::ParsePass(const FunctionBlockPtr &block, const py::object &node) {
  1481. // We just bypass 'pass' statement.
  1482. return block;
  1483. }
  1484. AnfNodePtr FindPhis(const std::unordered_map<ParameterPtr, AnfNodePtr> &removable_phis, const AnfNodePtr &node) {
  1485. const auto &inp = node->cast<ParameterPtr>();
  1486. const auto &iter = removable_phis.find(inp);
  1487. if (iter == removable_phis.end()) {
  1488. return node;
  1489. }
  1490. return FindPhis(removable_phis, iter->second);
  1491. }
  1492. void Parser::RemoveUnnecessaryPhis() {
  1493. // Merge all removable phis to one map;
  1494. std::unordered_map<ParameterPtr, AnfNodePtr> removable_phis;
  1495. std::vector<ParameterPtr> phis;
  1496. for (FunctionBlockPtr &block : func_block_list_) {
  1497. MS_EXCEPTION_IF_NULL(block);
  1498. removable_phis.insert(block->removable_phis().begin(), block->removable_phis().end());
  1499. std::transform(block->removable_phis().begin(), block->removable_phis().end(), std::back_inserter(phis),
  1500. [](const std::pair<ParameterPtr, AnfNodePtr> &pair) { return pair.first; });
  1501. }
  1502. if (removable_phis.empty()) {
  1503. return;
  1504. }
  1505. auto fg_name = func_graph_->ToString();
  1506. auto mng = Manage(func_graph_, false);
  1507. // Replace the nodes
  1508. // Remove from inside to outside
  1509. for (int64_t idx = SizeToLong(phis.size() - 1); idx >= 0; idx--) {
  1510. auto phi = phis[LongToSize(idx)];
  1511. auto new_node = FindPhis(removable_phis, phi);
  1512. mng->Replace(phi, new_node);
  1513. }
  1514. // Remove the parameter
  1515. for (FunctionBlockPtr &block : func_block_list_) {
  1516. MS_EXCEPTION_IF_NULL(block);
  1517. auto &local_removable_phis = block->removable_phis();
  1518. if (local_removable_phis.empty()) {
  1519. continue;
  1520. }
  1521. auto func_graph = block->func_graph();
  1522. auto &parameters = func_graph->parameters();
  1523. std::vector<AnfNodePtr> new_parameters(parameters.size());
  1524. auto it = std::copy_if(
  1525. parameters.begin(), parameters.end(), new_parameters.begin(), [&local_removable_phis](const AnfNodePtr &param) {
  1526. return local_removable_phis.find(param->cast<ParameterPtr>()) == local_removable_phis.end();
  1527. });
  1528. // Shrink container to new size
  1529. new_parameters.resize(std::distance(new_parameters.begin(), it));
  1530. func_graph->set_parameters(new_parameters);
  1531. }
  1532. for (const auto &fg : mng->func_graphs()) {
  1533. fg->ClearAllManagerInfo();
  1534. }
  1535. }
  1536. // ParseAst class code
  1537. bool ParseAst::InitParseAstInfo(const std::string &python_mod_get_parse_method) {
  1538. // Init the type
  1539. target_type_ = PARSE_TARGET_UNKNOW;
  1540. // Call python parse, get the parser fn
  1541. module_ = python_adapter::GetPyModule(PYTHON_MOD_PARSE_MODULE);
  1542. py::object parse_method = python_adapter::GetPyObjAttr(obj_, PYTHON_EXTERN_PARSE_METHOD);
  1543. // Get the obj type
  1544. auto type = data_converter::GetObjType(obj_);
  1545. if (type == RESOLVE_TYPE_FUNCTION) {
  1546. target_type_ = PARSE_TARGET_FUNCTION;
  1547. function_ = obj_;
  1548. } else if (type == RESOLVE_TYPE_METHOD) {
  1549. // Process the method ,need get the method's self obj
  1550. target_type_ = PARSE_TARGET_METHOD;
  1551. py::object method_object = python_adapter::GetPyObjAttr(obj_, PYTHON_GET_METHOD_SELF_CLASS);
  1552. if (py::isinstance<py::none>(method_object)) {
  1553. MS_LOG(ERROR) << "Get method's self object instance failed.";
  1554. return false;
  1555. }
  1556. target_type_ = PARSE_TARGET_OBJECT_INSTANCE;
  1557. function_ = obj_;
  1558. obj_ = method_object;
  1559. } else if (type == RESOLVE_TYPE_CLASS_INSTANCE) {
  1560. // obj is class instance, get the method to parse.
  1561. function_ = python_adapter::CallPyModFn(module_, python_mod_get_parse_method, obj_, parse_method);
  1562. if (py::isinstance<py::none>(function_)) {
  1563. MS_LOG(ERROR) << "Get obj method function failed.";
  1564. return false;
  1565. }
  1566. target_type_ = PARSE_TARGET_OBJECT_INSTANCE;
  1567. // Check the fn is method
  1568. auto obj_type = data_converter::GetObjType(function_);
  1569. if (obj_type != RESOLVE_TYPE_METHOD) {
  1570. MS_LOG(WARNING) << "Parse method function is invalid.";
  1571. return false;
  1572. }
  1573. } else {
  1574. MS_LOG(WARNING) << "Parse obj is invalid, only can parse function and obj, type = " << type;
  1575. return false;
  1576. }
  1577. // Call python parse get ast tree
  1578. parser_ = python_adapter::CallPyModFn(module_, PYTHON_MOD_PARSE_OBJECT_FUNCTION, function_, parse_method);
  1579. ast_tree_ = python_adapter::CallPyObjMethod(parser_, "parse");
  1580. // Get fn name and module
  1581. function_module_ = py::cast<std::string>(python_adapter::GetPyObjAttr(parser_, "function_module"));
  1582. function_name_ = py::cast<std::string>(python_adapter::GetPyObjAttr(parser_, "function_name"));
  1583. function_filename_ = py::cast<std::string>(python_adapter::GetPyObjAttr(parser_, "filename"));
  1584. function_line_offset_ = py::cast<int64_t>(python_adapter::GetPyObjAttr(parser_, "line_offset"));
  1585. return true;
  1586. }
  1587. // Get ast tree node : is the tree bode list[0]
  1588. py::object ParseAst::GetAstNode() {
  1589. py::list tree_body = python_adapter::GetPyObjAttr(ast_tree_, "body");
  1590. py::object ast_node = tree_body[0];
  1591. return ast_node;
  1592. }
  1593. py::list ParseAst::GetArgs(const py::object &func_node) {
  1594. py::list ret = python_adapter::CallPyModFn(module_, PYTHON_PARSE_GET_ARGS, func_node);
  1595. return ret;
  1596. }
  1597. py::list ParseAst::GetArgsDefaultValues(const py::object &func_node) {
  1598. py::list ret = python_adapter::CallPyModFn(module_, PYTHON_PARSE_GET_ARGS_DEFAULT_VALUES, func_node);
  1599. return ret;
  1600. }
  1601. AstNodeTypePtr ParseAst::GetNodeType(const py::object &node) {
  1602. py::list list_value = python_adapter::CallPyModFn(module_, PYTHON_PARSE_GET_NODE_TYPE, node);
  1603. if (list_value.size() < 2) {
  1604. MS_LOG(ERROR) << "The node of python method must has 2 values.";
  1605. return nullptr;
  1606. }
  1607. auto node_name = py::cast<std::string>(list_value[0]);
  1608. auto type = AstMainType(py::cast<int32_t>(list_value[1]));
  1609. return std::make_shared<AstNodeType>(node, node_name, type);
  1610. }
  1611. AstSubType ParseAst::GetOpType(const py::object &node) {
  1612. auto op_type = AstSubType(python_adapter::CallPyModFn(module_, PYTHON_PARSE_GET_AST_TYPE, node).cast<int32_t>());
  1613. return op_type;
  1614. }
  1615. bool ParseAst::IsClassMember(const py::object &node) {
  1616. py::object ret = CallParseModFunction(PYTHON_MOD_PARSE_CHECK_IS_CLASS_MEMBER, node);
  1617. if (!py::isinstance<py::bool_>(ret)) {
  1618. MS_LOG(ERROR) << "The result of mod function parse, should be bool type.";
  1619. return false;
  1620. }
  1621. return ret.cast<bool>();
  1622. }
  1623. bool UpdateFuncGraphFlags(const py::object &obj, const FuncGraphPtr &func_graph) {
  1624. if (func_graph == nullptr) {
  1625. MS_LOG(ERROR) << "FuncGraph is null";
  1626. return false;
  1627. }
  1628. if (!py::hasattr(obj, PYTHON_EXTERN_MINDSPORE_FLAG)) {
  1629. MS_LOG(DEBUG) << "No flags";
  1630. return true;
  1631. }
  1632. py::dict flags = python_adapter::GetPyObjAttr(obj, PYTHON_EXTERN_MINDSPORE_FLAG);
  1633. for (auto &item : flags) {
  1634. if (!py::isinstance<py::str>(item.first)) {
  1635. MS_LOG(ERROR) << "Type error in flags dict convert";
  1636. return false;
  1637. }
  1638. auto name = py::cast<std::string>(item.first);
  1639. if (py::isinstance<py::bool_>(item.second)) {
  1640. auto value = py::cast<bool>(item.second);
  1641. MS_LOG(DEBUG) << "Flag name: " << name << ". Value: " << value;
  1642. func_graph->set_flag(name, value);
  1643. } else if (py::isinstance<py::str>(item.second)) {
  1644. auto value = py::cast<std::string>(item.second);
  1645. MS_LOG(DEBUG) << "Flag name: " << name << ". Value: " << value;
  1646. func_graph->set_attr(name, MakeValue(value));
  1647. } else {
  1648. MS_LOG(ERROR) << "Type error in flags/attrs dict convert";
  1649. return false;
  1650. }
  1651. }
  1652. return true;
  1653. }
  1654. // Generate and copy a ValueNode, or a CNode with its child nodes
  1655. static AnfNodePtr CopyNodesFromParamDefaultValue(const FuncGraphPtr &func_graph, const AnfNodePtr &param_node) {
  1656. MS_EXCEPTION_IF_NULL(param_node);
  1657. if (param_node->isa<ValueNode>()) {
  1658. return std::make_shared<ValueNode>(param_node->cast<ValueNodePtr>()->value());
  1659. }
  1660. // Parameter default value is CNode.
  1661. std::size_t index = 0;
  1662. std::vector<AnfNodePtr> old_cnodes;
  1663. old_cnodes.emplace_back(param_node);
  1664. auto res = func_graph->NewCNodeInOrder({});
  1665. std::vector<CNodePtr> new_cnodes;
  1666. new_cnodes.emplace_back(res);
  1667. while (index < old_cnodes.size()) {
  1668. auto current = old_cnodes[index];
  1669. auto current_new_cnode = new_cnodes[index];
  1670. index++;
  1671. MS_EXCEPTION_IF_NULL(current);
  1672. if (current->isa<CNode>()) {
  1673. auto &inputs = current->cast<CNodePtr>()->inputs();
  1674. for (auto it = inputs.begin(); it != inputs.end(); it++) {
  1675. AnfNodePtr input = *it;
  1676. if (input != nullptr && input->isa<CNode>()) {
  1677. old_cnodes.emplace_back(input);
  1678. auto new_cnode = func_graph->NewCNodeInOrder({});
  1679. new_cnodes.emplace_back(new_cnode);
  1680. current_new_cnode->add_input(new_cnode);
  1681. } else if (input->isa<ValueNode>()) {
  1682. current_new_cnode->add_input(std::make_shared<ValueNode>(input->cast<ValueNodePtr>()->value()));
  1683. } else {
  1684. MS_LOG(EXCEPTION) << "Wrong type item in default parameters: " << input->ToString();
  1685. }
  1686. }
  1687. }
  1688. }
  1689. return res;
  1690. }
  1691. FuncGraphPtr MakeTopGraph(const py::object &cell, const ValuePtr &cell_ptr) {
  1692. auto current_graph = dyn_cast<FuncGraph>(cell_ptr);
  1693. if (current_graph == nullptr) {
  1694. MS_LOG(EXCEPTION) << "Current graph cast failed from " << cell_ptr->ToString();
  1695. }
  1696. auto func_graph = std::make_shared<FuncGraph>();
  1697. func_graph->debug_info()->set_name(current_graph->debug_info()->name() + "_wrapper");
  1698. // Copy all parameters information
  1699. for (auto &para : current_graph->parameters()) {
  1700. auto param = func_graph->add_parameter();
  1701. auto orig_param = para->cast<ParameterPtr>();
  1702. auto name = orig_param->name();
  1703. param->set_name(name);
  1704. param->debug_info()->set_name(name);
  1705. }
  1706. func_graph->set_has_vararg(current_graph->has_vararg());
  1707. func_graph->set_has_kwarg(current_graph->has_kwarg());
  1708. func_graph->set_kwonlyargs_count(current_graph->kwonlyargs_count());
  1709. // Copy all default values
  1710. for (auto &d : current_graph->parameter_default_value()) {
  1711. func_graph->set_param_default_value(d.first, CopyNodesFromParamDefaultValue(func_graph, d.second));
  1712. }
  1713. // cell_obj
  1714. MS_LOG(DEBUG) << "add Flag for " << std::string(py::str(cell));
  1715. parse::UpdateFuncGraphFlags(cell, func_graph);
  1716. // Top graph's construct flag
  1717. if (py::hasattr(cell, "construct")) {
  1718. parse::UpdateFuncGraphFlags(cell.attr("construct"), func_graph);
  1719. }
  1720. auto unpacking = func_graph->has_vararg() || func_graph->has_kwarg();
  1721. if (!unpacking) {
  1722. std::vector<AnfNodePtr> inputs;
  1723. inputs.emplace_back(NewValueNode(cell_ptr));
  1724. auto &params = func_graph->parameters();
  1725. (void)std::transform(params.begin(), params.end(), std::back_inserter(inputs),
  1726. [](AnfNodePtr node) -> AnfNodePtr { return node; });
  1727. func_graph->set_output(func_graph->NewCNodeInOrder(inputs));
  1728. } else {
  1729. // ret = cell_obj(*arg, *kwargs)
  1730. auto call_fn = MakeUnpackCall(func_graph, NewValueNode(cell_ptr), func_graph->parameters());
  1731. // Set output as ret
  1732. func_graph->set_output(call_fn);
  1733. }
  1734. return func_graph;
  1735. }
  1736. } // namespace parse
  1737. } // namespace mindspore