PageRenderTime 74ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/Languages/IronPython/IronPython/Modules/_ast.cs

http://github.com/IronLanguages/main
C# | 3664 lines | 3013 code | 560 blank | 91 comment | 362 complexity | 265edc1ebd043a6c2d7c6242a4637c06 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Jeff Hardy 2010.
  4. * Copyright (c) Dan Eloff 2008-2009.
  5. *
  6. * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  7. * copy of the license can be found in the License.html file at the root of this distribution. If
  8. * you cannot locate the Apache License, Version 2.0, please send an email to
  9. * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  10. * by the terms of the Apache License, Version 2.0.
  11. *
  12. * You must not remove this notice, or any other, from this software.
  13. *
  14. *
  15. * ***************************************************************************/
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Generic;
  19. using Generic = System.Collections.Generic;
  20. using System.Diagnostics;
  21. using System.Reflection;
  22. using System.Runtime.CompilerServices;
  23. using IronPython.Compiler;
  24. using IronPython.Compiler.Ast;
  25. using IronPython.Runtime;
  26. using IronPython.Runtime.Operations;
  27. using IronPython.Runtime.Types;
  28. using IronPython.Runtime.Exceptions;
  29. using Microsoft.Scripting;
  30. using Microsoft.Scripting.Runtime;
  31. using Microsoft.Scripting.Utils;
  32. using PyOperator = IronPython.Compiler.PythonOperator;
  33. using PythonList = IronPython.Runtime.List;
  34. using System.Runtime.InteropServices;
  35. using AstExpression = IronPython.Compiler.Ast.Expression;
  36. #if FEATURE_NUMERICS
  37. using System.Numerics;
  38. #else
  39. using Microsoft.Scripting.Math;
  40. using Complex = Microsoft.Scripting.Math.Complex64;
  41. #endif
  42. [assembly: PythonModule("_ast", typeof(IronPython.Modules._ast))]
  43. namespace IronPython.Modules
  44. {
  45. public static class _ast
  46. {
  47. public const string __version__ = "62047";
  48. public const int PyCF_ONLY_AST = 0x400;
  49. private class ThrowingErrorSink : ErrorSink
  50. {
  51. public static new readonly ThrowingErrorSink/*!*/ Default = new ThrowingErrorSink();
  52. private ThrowingErrorSink() {
  53. }
  54. public override void Add(SourceUnit sourceUnit, string message, SourceSpan span, int errorCode, Severity severity) {
  55. if (severity == Severity.Warning) {
  56. PythonOps.SyntaxWarning(message, sourceUnit, span, errorCode);
  57. } else {
  58. throw PythonOps.SyntaxError(message, sourceUnit, span, errorCode);
  59. }
  60. }
  61. }
  62. internal static PythonAst ConvertToPythonAst(CodeContext codeContext, AST source ) {
  63. Statement stmt;
  64. PythonCompilerOptions options = new PythonCompilerOptions(ModuleOptions.ExecOrEvalCode);
  65. SourceUnit unit = new SourceUnit(codeContext.LanguageContext, NullTextContentProvider.Null, "", SourceCodeKind.AutoDetect);
  66. CompilerContext compilerContext = new CompilerContext(unit, options, ErrorSink.Default);
  67. bool printExpression = false;
  68. if (source is Expression) {
  69. Expression exp = (Expression)source;
  70. stmt = new ReturnStatement(expr.Revert(exp.body));
  71. } else if (source is Module) {
  72. Module module = (Module)source;
  73. stmt = _ast.stmt.RevertStmts(module.body);
  74. } else if (source is Interactive) {
  75. Interactive interactive = (Interactive)source;
  76. stmt = _ast.stmt.RevertStmts(interactive.body);
  77. printExpression = true;
  78. } else
  79. throw PythonOps.TypeError("unsupported type of AST: {0}",(source.GetType()));
  80. return new PythonAst(stmt, false, ModuleOptions.ExecOrEvalCode, printExpression, compilerContext, new int[] {} );
  81. }
  82. internal static AST BuildAst(CodeContext context, SourceUnit sourceUnit, PythonCompilerOptions opts, string mode) {
  83. Parser parser = Parser.CreateParser(
  84. new CompilerContext(sourceUnit, opts, ThrowingErrorSink.Default),
  85. (PythonOptions)context.LanguageContext.Options);
  86. PythonAst ast = parser.ParseFile(true);
  87. return ConvertToAST(ast, mode);
  88. }
  89. private static mod ConvertToAST(PythonAst pythonAst, string kind) {
  90. ContractUtils.RequiresNotNull(pythonAst, "pythonAst");
  91. ContractUtils.RequiresNotNull(kind, "kind");
  92. return ConvertToAST((SuiteStatement)pythonAst.Body, kind);
  93. }
  94. private static mod ConvertToAST(SuiteStatement suite, string kind) {
  95. ContractUtils.RequiresNotNull(suite, "suite");
  96. ContractUtils.RequiresNotNull(kind, "kind");
  97. switch (kind) {
  98. case "exec":
  99. return new Module(suite);
  100. case "eval":
  101. return new Expression(suite);
  102. case "single":
  103. return new Interactive(suite);
  104. default:
  105. throw new ArgumentException("kind must be 'exec' or 'eval' or 'single'");
  106. }
  107. }
  108. [PythonType]
  109. public abstract class AST
  110. {
  111. private PythonTuple __fields = new PythonTuple(); // Genshi assumes _fields in not None
  112. private PythonTuple __attributes = new PythonTuple(); // Genshi assumes _fields in not None
  113. protected int? _lineno; // both lineno and col_offset are expected to be int, in cpython anything is accepted
  114. protected int? _col_offset;
  115. public PythonTuple _fields {
  116. get { return __fields; }
  117. protected set { __fields = value; }
  118. }
  119. public PythonTuple _attributes {
  120. get { return __attributes; }
  121. protected set { __attributes = value; }
  122. }
  123. public int lineno {
  124. get {
  125. if (_lineno != null) return (int)_lineno;
  126. throw PythonOps.AttributeErrorForMissingAttribute(PythonTypeOps.GetName(this), "lineno");
  127. }
  128. set { _lineno = value; }
  129. }
  130. public int col_offset {
  131. get {
  132. if (_col_offset != null) return (int)_col_offset;
  133. throw PythonOps.AttributeErrorForMissingAttribute(PythonTypeOps.GetName(this), "col_offset");
  134. }
  135. set { _col_offset = value; }
  136. }
  137. public void __setstate__(PythonDictionary state) {
  138. restoreProperties(__attributes, state);
  139. restoreProperties(__fields, state);
  140. }
  141. internal void restoreProperties(IEnumerable<object> names, IDictionary source) {
  142. foreach (object name in names) {
  143. if (name is string) {
  144. try {
  145. string key = (string)name;
  146. this.GetType().GetProperty(key).SetValue(this, source[key], null);
  147. } catch (Generic.KeyNotFoundException) {
  148. // ignore missing
  149. }
  150. }
  151. }
  152. }
  153. internal void storeProperties(IEnumerable<object> names, IDictionary target) {
  154. foreach (object name in names) {
  155. if (name is string) {
  156. string key = (string)name;
  157. object val;
  158. try {
  159. val = this.GetType().GetProperty(key).GetValue(this, null);
  160. target.Add(key, val);
  161. } catch (System.Reflection.TargetInvocationException) {
  162. // field not set
  163. }
  164. }
  165. }
  166. }
  167. internal PythonDictionary getstate() {
  168. PythonDictionary d = new PythonDictionary(10);
  169. storeProperties(__fields, d);
  170. storeProperties(__attributes, d);
  171. return d;
  172. }
  173. public virtual object/*!*/ __reduce__() {
  174. return PythonTuple.MakeTuple(DynamicHelpers.GetPythonType(this), new PythonTuple(), getstate());
  175. }
  176. public virtual object/*!*/ __reduce_ex__(int protocol) {
  177. return __reduce__();
  178. }
  179. protected void GetSourceLocation(Node node) {
  180. _lineno = node.Start.Line;
  181. // IronPython counts from 1; CPython counts from 0
  182. _col_offset = node.Start.Column - 1;
  183. }
  184. internal static PythonList ConvertStatements(Statement stmt) {
  185. return ConvertStatements(stmt, false);
  186. }
  187. internal static PythonList ConvertStatements(Statement stmt, bool allowNull) {
  188. if (stmt == null)
  189. if (allowNull)
  190. return PythonOps.MakeEmptyList(0);
  191. else
  192. throw new ArgumentNullException("stmt");
  193. if (stmt is SuiteStatement) {
  194. SuiteStatement suite = (SuiteStatement)stmt;
  195. PythonList list = PythonOps.MakeEmptyList(suite.Statements.Count);
  196. foreach (Statement s in suite.Statements)
  197. if (s is SuiteStatement) // multiple stmt in a line
  198. foreach (Statement s2 in ((SuiteStatement)s).Statements)
  199. list.Add(Convert(s2));
  200. else
  201. list.Add(Convert(s));
  202. return list;
  203. }
  204. return PythonOps.MakeListNoCopy(Convert(stmt));
  205. }
  206. internal static stmt Convert(Statement stmt) {
  207. stmt ast;
  208. if (stmt is FunctionDefinition)
  209. ast = new FunctionDef((FunctionDefinition)stmt);
  210. else if (stmt is ReturnStatement)
  211. ast = new Return((ReturnStatement)stmt);
  212. else if (stmt is AssignmentStatement)
  213. ast = new Assign((AssignmentStatement)stmt);
  214. else if (stmt is AugmentedAssignStatement)
  215. ast = new AugAssign((AugmentedAssignStatement)stmt);
  216. else if (stmt is DelStatement)
  217. ast = new Delete((DelStatement)stmt);
  218. else if (stmt is PrintStatement)
  219. ast = new Print((PrintStatement)stmt);
  220. else if (stmt is ExpressionStatement)
  221. ast = new Expr((ExpressionStatement)stmt);
  222. else if (stmt is ForStatement)
  223. ast = new For((ForStatement)stmt);
  224. else if (stmt is WhileStatement)
  225. ast = new While((WhileStatement)stmt);
  226. else if (stmt is IfStatement)
  227. ast = new If((IfStatement)stmt);
  228. else if (stmt is WithStatement)
  229. ast = new With((WithStatement)stmt);
  230. else if (stmt is RaiseStatement)
  231. ast = new Raise((RaiseStatement)stmt);
  232. else if (stmt is TryStatement)
  233. ast = Convert((TryStatement)stmt);
  234. else if (stmt is AssertStatement)
  235. ast = new Assert((AssertStatement)stmt);
  236. else if (stmt is ImportStatement)
  237. ast = new Import((ImportStatement)stmt);
  238. else if (stmt is FromImportStatement)
  239. ast = new ImportFrom((FromImportStatement)stmt);
  240. else if (stmt is ExecStatement)
  241. ast = new Exec((ExecStatement)stmt);
  242. else if (stmt is GlobalStatement)
  243. ast = new Global((GlobalStatement)stmt);
  244. else if (stmt is ClassDefinition)
  245. ast = new ClassDef((ClassDefinition)stmt);
  246. else if (stmt is BreakStatement)
  247. ast = new Break();
  248. else if (stmt is ContinueStatement)
  249. ast = new Continue();
  250. else if (stmt is EmptyStatement)
  251. ast = new Pass();
  252. else
  253. throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType());
  254. ast.GetSourceLocation(stmt);
  255. return ast;
  256. }
  257. internal static stmt Convert(TryStatement stmt) {
  258. if (stmt.Finally != null) {
  259. PythonList body;
  260. if (stmt.Handlers != null && stmt.Handlers.Count != 0) {
  261. stmt tryExcept = new TryExcept(stmt);
  262. tryExcept.GetSourceLocation(stmt);
  263. body = PythonOps.MakeListNoCopy(tryExcept);
  264. } else
  265. body = ConvertStatements(stmt.Body);
  266. return new TryFinally(body, ConvertStatements(stmt.Finally));
  267. }
  268. return new TryExcept(stmt);
  269. }
  270. internal static PythonList ConvertAliases(IList<DottedName> names, IList<string> asnames) {
  271. PythonList list = PythonOps.MakeEmptyList(names.Count);
  272. if (names == FromImportStatement.Star) // does it ever happen?
  273. list.Add(new alias("*", null));
  274. else
  275. for (int i = 0; i < names.Count; i++)
  276. list.Add(new alias(names[i].MakeString(), asnames[i]));
  277. return list;
  278. }
  279. internal static PythonList ConvertAliases(IList<string> names, IList<string> asnames) {
  280. PythonList list = PythonOps.MakeEmptyList(names.Count);
  281. if (names == FromImportStatement.Star)
  282. list.Add(new alias("*", null));
  283. else
  284. for (int i = 0; i < names.Count; i++)
  285. list.Add(new alias(names[i], asnames[i]));
  286. return list;
  287. }
  288. internal static slice TrySliceConvert(AstExpression expr) {
  289. if (expr is SliceExpression)
  290. return new Slice((SliceExpression)expr);
  291. if (expr is ConstantExpression && ((ConstantExpression)expr).Value == PythonOps.Ellipsis)
  292. return Ellipsis.Instance;
  293. if (expr is TupleExpression && ((TupleExpression)expr).IsExpandable)
  294. return new ExtSlice(((Tuple)Convert(expr)).elts);
  295. return null;
  296. }
  297. internal static expr Convert(AstExpression expr) {
  298. return Convert(expr, Load.Instance);
  299. }
  300. internal static expr Convert(AstExpression expr, expr_context ctx) {
  301. expr ast;
  302. if (expr is ConstantExpression)
  303. ast = Convert((ConstantExpression)expr);
  304. else if (expr is NameExpression)
  305. ast = new Name((NameExpression)expr, ctx);
  306. else if (expr is UnaryExpression) {
  307. var unaryOp = new UnaryOp((UnaryExpression)expr);
  308. ast = unaryOp.TryTrimTrivialUnaryOp();
  309. } else if (expr is BinaryExpression)
  310. ast = Convert((BinaryExpression)expr);
  311. else if (expr is AndExpression)
  312. ast = new BoolOp((AndExpression)expr);
  313. else if (expr is OrExpression)
  314. ast = new BoolOp((OrExpression)expr);
  315. else if (expr is CallExpression)
  316. ast = new Call((CallExpression)expr);
  317. else if (expr is ParenthesisExpression)
  318. return Convert(((ParenthesisExpression)expr).Expression);
  319. else if (expr is LambdaExpression)
  320. ast = new Lambda((LambdaExpression)expr);
  321. else if (expr is ListExpression)
  322. ast = new List((ListExpression)expr, ctx);
  323. else if (expr is TupleExpression)
  324. ast = new Tuple((TupleExpression)expr, ctx);
  325. else if (expr is DictionaryExpression)
  326. ast = new Dict((DictionaryExpression)expr);
  327. else if (expr is ListComprehension)
  328. ast = new ListComp((ListComprehension)expr);
  329. else if (expr is GeneratorExpression)
  330. ast = new GeneratorExp((GeneratorExpression)expr);
  331. else if (expr is MemberExpression)
  332. ast = new Attribute((MemberExpression)expr, ctx);
  333. else if (expr is YieldExpression)
  334. ast = new Yield((YieldExpression)expr);
  335. else if (expr is ConditionalExpression)
  336. ast = new IfExp((ConditionalExpression)expr);
  337. else if (expr is IndexExpression)
  338. ast = new Subscript((IndexExpression)expr, ctx);
  339. else if (expr is BackQuoteExpression)
  340. ast = new Repr((BackQuoteExpression)expr);
  341. else if (expr is SetExpression)
  342. ast = new Set((SetExpression)expr);
  343. else if (expr is DictionaryComprehension)
  344. ast = new DictComp((DictionaryComprehension)expr);
  345. else if (expr is SetComprehension)
  346. ast = new SetComp((SetComprehension)expr);
  347. else
  348. throw new ArgumentTypeException("Unexpected expression type: " + expr.GetType());
  349. ast.GetSourceLocation(expr);
  350. return ast;
  351. }
  352. internal static expr Convert(ConstantExpression expr) {
  353. expr ast;
  354. if (expr.Value == null)
  355. return new Name("None", Load.Instance);
  356. if (expr.Value is int || expr.Value is double || expr.Value is Int64 || expr.Value is BigInteger || expr.Value is Complex)
  357. ast = new Num(expr.Value);
  358. else if (expr.Value is string)
  359. ast = new Str((string)expr.Value);
  360. else if (expr.Value is IronPython.Runtime.Bytes)
  361. ast = new Str(Converter.ConvertToString(expr.Value));
  362. else
  363. throw new ArgumentTypeException("Unexpected constant type: " + expr.Value.GetType());
  364. return ast;
  365. }
  366. internal static expr Convert(BinaryExpression expr) {
  367. AST op = Convert(expr.Operator);
  368. if (BinaryExpression.IsComparison(expr)) {
  369. return new Compare(expr);
  370. } else {
  371. if (op is @operator) {
  372. return new BinOp(expr, (@operator)op);
  373. }
  374. }
  375. throw new ArgumentTypeException("Unexpected operator type: " + op.GetType());
  376. }
  377. internal static AST Convert(Node node) {
  378. AST ast;
  379. if (node is TryStatementHandler)
  380. ast = new ExceptHandler((TryStatementHandler)node);
  381. else
  382. throw new ArgumentTypeException("Unexpected node type: " + node.GetType());
  383. ast.GetSourceLocation(node);
  384. return ast;
  385. }
  386. internal static PythonList Convert(IList<ComprehensionIterator> iterators) {
  387. ComprehensionIterator[] iters = new ComprehensionIterator[iterators.Count];
  388. iterators.CopyTo(iters, 0);
  389. PythonList comps = new PythonList();
  390. int start = 1;
  391. for (int i = 0; i < iters.Length; i++) {
  392. if (i == 0 || iters[i] is ComprehensionIf)
  393. if (i == iters.Length - 1)
  394. i++;
  395. else
  396. continue;
  397. ComprehensionIf[] ifs = new ComprehensionIf[i - start];
  398. Array.Copy(iters, start, ifs, 0, ifs.Length);
  399. comps.Add(new comprehension((ComprehensionFor)iters[start - 1], ifs));
  400. start = i + 1;
  401. }
  402. return comps;
  403. }
  404. internal static PythonList Convert(ComprehensionIterator[] iters) {
  405. Generic.List<ComprehensionFor> cfCollector =
  406. new Generic.List<ComprehensionFor>();
  407. Generic.List<Generic.List<ComprehensionIf>> cifCollector =
  408. new Generic.List<Generic.List<ComprehensionIf>>();
  409. Generic.List<ComprehensionIf> cif = null;
  410. for (int i = 0; i < iters.Length; i++) {
  411. if (iters[i] is ComprehensionFor) {
  412. ComprehensionFor cf = (ComprehensionFor)iters[i];
  413. cfCollector.Add(cf);
  414. cif = new Generic.List<ComprehensionIf>();
  415. cifCollector.Add(cif);
  416. } else {
  417. ComprehensionIf ci = (ComprehensionIf)iters[i];
  418. cif.Add(ci);
  419. }
  420. }
  421. PythonList comps = new PythonList();
  422. for (int i = 0; i < cfCollector.Count; i++)
  423. comps.Add(new comprehension(cfCollector[i], cifCollector[i].ToArray()));
  424. return comps;
  425. }
  426. internal static AST Convert(PyOperator op) {
  427. // We treat operator classes as singletons here to keep overhead down
  428. // But we cannot fully make them singletons if we wish to keep compatibility wity CPython
  429. switch (op) {
  430. case PyOperator.Add:
  431. return Add.Instance;
  432. case PyOperator.BitwiseAnd:
  433. return BitAnd.Instance;
  434. case PyOperator.BitwiseOr:
  435. return BitOr.Instance;
  436. case PyOperator.Divide:
  437. return Div.Instance;
  438. case PyOperator.TrueDivide:
  439. return TrueDivide.Instance;
  440. case PyOperator.Equal:
  441. return Eq.Instance;
  442. case PyOperator.FloorDivide:
  443. return FloorDiv.Instance;
  444. case PyOperator.GreaterThan:
  445. return Gt.Instance;
  446. case PyOperator.GreaterThanOrEqual:
  447. return GtE.Instance;
  448. case PyOperator.In:
  449. return In.Instance;
  450. case PyOperator.Invert:
  451. return Invert.Instance;
  452. case PyOperator.Is:
  453. return Is.Instance;
  454. case PyOperator.IsNot:
  455. return IsNot.Instance;
  456. case PyOperator.LeftShift:
  457. return LShift.Instance;
  458. case PyOperator.LessThan:
  459. return Lt.Instance;
  460. case PyOperator.LessThanOrEqual:
  461. return LtE.Instance;
  462. case PyOperator.Mod:
  463. return Mod.Instance;
  464. case PyOperator.Multiply:
  465. return Mult.Instance;
  466. case PyOperator.Negate:
  467. return USub.Instance;
  468. case PyOperator.Not:
  469. return Not.Instance;
  470. case PyOperator.NotEqual:
  471. return NotEq.Instance;
  472. case PyOperator.NotIn:
  473. return NotIn.Instance;
  474. case PyOperator.Pos:
  475. return UAdd.Instance;
  476. case PyOperator.Power:
  477. return Pow.Instance;
  478. case PyOperator.RightShift:
  479. return RShift.Instance;
  480. case PyOperator.Subtract:
  481. return Sub.Instance;
  482. case PyOperator.Xor:
  483. return BitXor.Instance;
  484. default:
  485. throw new ArgumentException("Unexpected PyOperator: " + op, "op");
  486. }
  487. }
  488. }
  489. [PythonType]
  490. public class alias : AST
  491. {
  492. private string _name;
  493. private string _asname; // Optional
  494. public alias() {
  495. _fields = new PythonTuple(new[] { "name", "asname" });
  496. }
  497. internal alias(string name, [Optional]string asname)
  498. : this() {
  499. _name = name;
  500. _asname = asname;
  501. }
  502. public string name {
  503. get { return _name; }
  504. set { _name = value; }
  505. }
  506. public string asname {
  507. get { return _asname; }
  508. set { _asname = value; }
  509. }
  510. }
  511. [PythonType]
  512. public class arguments : AST
  513. {
  514. private PythonList _args;
  515. private string _vararg; // Optional
  516. private string _kwarg; // Optional
  517. private PythonList _defaults;
  518. public arguments() {
  519. _fields = new PythonTuple(new[] { "args", "vararg", "kwarg", "defaults" });
  520. }
  521. public arguments(PythonList args, [Optional]string vararg, [Optional]string kwarg, PythonList defaults)
  522. :this() {
  523. _args = args;
  524. _vararg = vararg;
  525. _kwarg = kwarg;
  526. _defaults = defaults;
  527. }
  528. internal arguments(IList<Parameter> parameters)
  529. : this() {
  530. _args = PythonOps.MakeEmptyList(parameters.Count);
  531. _defaults = PythonOps.MakeEmptyList(parameters.Count);
  532. foreach (Parameter param in parameters) {
  533. if (param.IsList)
  534. _vararg = param.Name;
  535. else if (param.IsDictionary)
  536. _kwarg = param.Name;
  537. else {
  538. args.Add(new Name(param));
  539. if (param.DefaultValue != null)
  540. defaults.Add(Convert(param.DefaultValue));
  541. }
  542. }
  543. }
  544. internal arguments(Parameter[] parameters)
  545. : this(parameters as IList<Parameter>) {
  546. }
  547. internal Parameter[] Revert() {
  548. List<Parameter> parameters = new List<Parameter>();
  549. int argIdx = args.Count - 1;
  550. for (int defIdx = defaults.Count - 1; defIdx >= 0; defIdx--, argIdx--) {
  551. Name name = (Name)args[argIdx];
  552. Parameter p = new Parameter(name.id);
  553. p.DefaultValue = expr.Revert(defaults[defIdx]);
  554. parameters.Add(p);
  555. }
  556. while (argIdx >= 0) {
  557. Name name = (Name)args[argIdx--];
  558. parameters.Add(new Parameter(name.id));
  559. }
  560. parameters.Reverse();
  561. if (vararg != null)
  562. parameters.Add(new Parameter(vararg, ParameterKind.List));
  563. if (kwarg != null)
  564. parameters.Add(new Parameter(kwarg, ParameterKind.Dictionary));
  565. return parameters.ToArray();
  566. }
  567. public PythonList args {
  568. get { return _args; }
  569. set { _args = value; }
  570. }
  571. public string vararg {
  572. get { return _vararg; }
  573. set { _vararg = value; }
  574. }
  575. public string kwarg {
  576. get { return _kwarg; }
  577. set { _kwarg = value; }
  578. }
  579. public PythonList defaults {
  580. get { return _defaults; }
  581. set { _defaults = value; }
  582. }
  583. }
  584. [PythonType]
  585. public abstract class boolop : AST
  586. {
  587. }
  588. [PythonType]
  589. public abstract class cmpop : AST
  590. {
  591. internal PythonOperator Revert() {
  592. if (this == Eq.Instance)
  593. return PyOperator.Equal;
  594. if (this == Gt.Instance)
  595. return PyOperator.GreaterThan;
  596. if (this == GtE.Instance)
  597. return PyOperator.GreaterThanOrEqual;
  598. if (this == In.Instance)
  599. return PyOperator.In;
  600. if (this == Is.Instance)
  601. return PyOperator.Is;
  602. if (this == IsNot.Instance)
  603. return PyOperator.IsNot;
  604. if (this == Lt.Instance)
  605. return PyOperator.LessThan;
  606. if (this == LtE.Instance)
  607. return PyOperator.LessThanOrEqual;
  608. if (this == NotEq.Instance)
  609. return PythonOperator.NotEqual;
  610. if (this == NotIn.Instance)
  611. return PythonOperator.NotIn;
  612. throw PythonOps.TypeError("Unexpected compare operator: {0}", GetType());
  613. }
  614. }
  615. [PythonType]
  616. public class comprehension : AST
  617. {
  618. private expr _target;
  619. private expr _iter;
  620. private PythonList _ifs;
  621. public comprehension() {
  622. _fields = new PythonTuple(new[] { "target", "iter", "ifs" });
  623. }
  624. public comprehension(expr target, expr iter, PythonList ifs)
  625. : this() {
  626. _target = target;
  627. _iter = iter;
  628. _ifs = ifs;
  629. }
  630. internal comprehension(ComprehensionFor listFor, ComprehensionIf[] listIfs)
  631. : this() {
  632. _target = Convert(listFor.Left, Store.Instance);
  633. _iter = Convert(listFor.List);
  634. _ifs = PythonOps.MakeEmptyList(listIfs.Length);
  635. foreach (ComprehensionIf listIf in listIfs)
  636. _ifs.Add(Convert(listIf.Test));
  637. }
  638. internal static ComprehensionIterator[] RevertComprehensions(PythonList comprehensions) {
  639. Generic.List<ComprehensionIterator> comprehensionIterators =
  640. new Generic.List<ComprehensionIterator>();
  641. foreach (comprehension comp in comprehensions) {
  642. ComprehensionFor cf = new ComprehensionFor(expr.Revert(comp.target), expr.Revert(comp.iter));
  643. comprehensionIterators.Add(cf);
  644. foreach (expr ifs in comp.ifs) {
  645. comprehensionIterators.Add(new ComprehensionIf(expr.Revert(ifs)));
  646. }
  647. }
  648. return comprehensionIterators.ToArray();
  649. }
  650. public expr target {
  651. get { return _target; }
  652. set { _target = value; }
  653. }
  654. public expr iter {
  655. get { return _iter; }
  656. set { _iter = value; }
  657. }
  658. public PythonList ifs {
  659. get { return _ifs; }
  660. set { _ifs = value; }
  661. }
  662. }
  663. [PythonType]
  664. public class excepthandler : AST
  665. {
  666. public excepthandler() {
  667. _attributes = new PythonTuple(new[] { "lineno", "col_offset" });
  668. }
  669. }
  670. [PythonType]
  671. public abstract class expr : AST
  672. {
  673. protected expr() {
  674. _attributes = new PythonTuple(new[] { "lineno", "col_offset" });
  675. }
  676. internal virtual AstExpression Revert() {
  677. throw PythonOps.TypeError("Unexpected expr type: {0}", GetType());
  678. }
  679. internal static AstExpression Revert(expr ex) {
  680. if (ex == null)
  681. return null;
  682. return ex.Revert();
  683. }
  684. internal static AstExpression Revert(object ex) {
  685. if (ex == null)
  686. return null;
  687. Debug.Assert(ex is expr);
  688. return ((expr)ex).Revert();
  689. }
  690. internal static AstExpression[] RevertExprs(PythonList exprs) {
  691. // it is assumed that list elements are expr
  692. AstExpression[] ret = new AstExpression[exprs.Count];
  693. for (int i = 0; i < exprs.Count; i++)
  694. ret[i] = ((expr)exprs[i]).Revert();
  695. return ret;
  696. }
  697. }
  698. [PythonType]
  699. public abstract class expr_context : AST
  700. {
  701. }
  702. [PythonType]
  703. public class keyword : AST
  704. {
  705. private string _arg;
  706. private expr _value;
  707. public keyword() {
  708. _fields = new PythonTuple(new[] { "arg", "value" });
  709. }
  710. public keyword(string arg, expr value)
  711. : this() {
  712. _arg = arg;
  713. _value = value;
  714. }
  715. internal keyword(IronPython.Compiler.Ast.Arg arg)
  716. : this() {
  717. _arg = arg.Name;
  718. _value = Convert(arg.Expression);
  719. }
  720. public string arg {
  721. get { return _arg; }
  722. set { _arg = value; }
  723. }
  724. public expr value {
  725. get { return _value; }
  726. set { _value = value; }
  727. }
  728. }
  729. [PythonType]
  730. public abstract class mod : AST
  731. {
  732. internal abstract PythonList GetStatements();
  733. }
  734. [PythonType]
  735. public abstract class @operator : AST
  736. {
  737. internal PythonOperator Revert() {
  738. if (this == Add.Instance)
  739. return PythonOperator.Add;
  740. if (this == BitAnd.Instance)
  741. return PyOperator.BitwiseAnd;
  742. if (this == BitOr.Instance)
  743. return PyOperator.BitwiseOr;
  744. if (this == Div.Instance)
  745. return PyOperator.Divide;
  746. if (this == FloorDiv.Instance)
  747. return PyOperator.FloorDivide;
  748. if (this == LShift.Instance)
  749. return PyOperator.LeftShift;
  750. if (this == Mod.Instance)
  751. return PythonOperator.Mod;
  752. if (this == Mult.Instance)
  753. return PythonOperator.Multiply;
  754. if (this == Pow.Instance)
  755. return PythonOperator.Power;
  756. if (this == RShift.Instance)
  757. return PyOperator.RightShift;
  758. if (this == Sub.Instance)
  759. return PythonOperator.Subtract;
  760. if (this == BitXor.Instance)
  761. return PythonOperator.Xor;
  762. throw PythonOps.TypeError("Unexpected unary operator: {0}", GetType());
  763. }
  764. }
  765. [PythonType]
  766. public abstract class slice : AST
  767. {
  768. }
  769. [PythonType]
  770. public abstract class stmt : AST
  771. {
  772. protected stmt() {
  773. _attributes = new PythonTuple(new[] { "lineno", "col_offset" });
  774. }
  775. internal virtual Statement Revert() {
  776. throw PythonOps.TypeError("Unexpected statement type: {0}", GetType());
  777. }
  778. internal static Statement RevertStmts(PythonList stmts) {
  779. if (stmts.Count == 1)
  780. return ((stmt)stmts[0]).Revert();
  781. Statement[] statements = new Statement[stmts.Count];
  782. for (int i = 0; i < stmts.Count; i++)
  783. statements[i] = ((stmt)stmts[i]).Revert();
  784. return new SuiteStatement(statements);
  785. }
  786. }
  787. [PythonType]
  788. public abstract class unaryop : AST
  789. {
  790. internal PyOperator Revert() {
  791. if (this == Invert.Instance)
  792. return PyOperator.Invert;
  793. if (this == USub.Instance)
  794. return PythonOperator.Negate;
  795. if (this == Not.Instance)
  796. return PythonOperator.Not;
  797. if (this == UAdd.Instance)
  798. return PythonOperator.Pos;
  799. throw PythonOps.TypeError("Unexpected unary operator: {0}", GetType());
  800. }
  801. }
  802. [PythonType]
  803. public class Add : @operator
  804. {
  805. internal static Add Instance = new Add();
  806. }
  807. [PythonType]
  808. public class And : boolop
  809. {
  810. internal static And Instance = new And();
  811. }
  812. [PythonType]
  813. public class Assert : stmt
  814. {
  815. private expr _test;
  816. private expr _msg; // Optional
  817. public Assert() {
  818. _fields = new PythonTuple(new[] { "test", "msg" });
  819. }
  820. public Assert(expr test, expr msg, [Optional]int? lineno, [Optional]int? col_offset)
  821. : this() {
  822. _test = test;
  823. _msg = msg;
  824. _lineno = lineno;
  825. _col_offset = col_offset;
  826. }
  827. internal Assert(AssertStatement stmt)
  828. : this() {
  829. _test = Convert(stmt.Test);
  830. if (stmt.Message != null)
  831. _msg = Convert(stmt.Message);
  832. }
  833. internal override Statement Revert() {
  834. return new AssertStatement(expr.Revert(test), expr.Revert(msg));
  835. }
  836. public expr test {
  837. get { return _test; }
  838. set { _test = value; }
  839. }
  840. public expr msg {
  841. get { return _msg; }
  842. set { _msg = value; }
  843. }
  844. }
  845. [PythonType]
  846. public class Assign : stmt
  847. {
  848. private PythonList _targets;
  849. private expr _value;
  850. public Assign() {
  851. _fields = new PythonTuple(new[] { "targets", "value" });
  852. }
  853. public Assign(PythonList targets, expr value, [Optional]int? lineno, [Optional]int? col_offset)
  854. : this() {
  855. _targets = targets;
  856. _value = value;
  857. _lineno = lineno;
  858. _col_offset = col_offset;
  859. }
  860. internal Assign(AssignmentStatement stmt)
  861. : this() {
  862. _targets = PythonOps.MakeEmptyList(stmt.Left.Count);
  863. foreach (AstExpression expr in stmt.Left)
  864. _targets.Add(Convert(expr, Store.Instance));
  865. _value = Convert(stmt.Right);
  866. }
  867. internal override Statement Revert() {
  868. return new AssignmentStatement(expr.RevertExprs(targets), expr.Revert(value));
  869. }
  870. public PythonList targets {
  871. get { return _targets; }
  872. set { _targets = value; }
  873. }
  874. public expr value {
  875. get { return _value; }
  876. set { _value = value; }
  877. }
  878. }
  879. [PythonType]
  880. public class Attribute : expr
  881. {
  882. private expr _value;
  883. private string _attr;
  884. private expr_context _ctx;
  885. public Attribute() {
  886. _fields = new PythonTuple(new[] { "value", "attr", "ctx" });
  887. }
  888. public Attribute(expr value, string attr, expr_context ctx,
  889. [Optional]int? lineno, [Optional]int? col_offset)
  890. : this() {
  891. _value = value;
  892. _attr = attr;
  893. _ctx = ctx;
  894. _lineno = lineno;
  895. _col_offset = col_offset;
  896. }
  897. internal Attribute(MemberExpression attr, expr_context ctx)
  898. : this() {
  899. _value = Convert(attr.Target);
  900. _attr = attr.Name;
  901. _ctx = ctx;
  902. }
  903. internal override AstExpression Revert() {
  904. return new MemberExpression(expr.Revert(value), attr);
  905. }
  906. public expr value {
  907. get { return _value; }
  908. set { _value = value; }
  909. }
  910. public string attr {
  911. get { return _attr; }
  912. set { _attr = value; }
  913. }
  914. public expr_context ctx {
  915. get { return _ctx; }
  916. set { _ctx = value; }
  917. }
  918. }
  919. [PythonType]
  920. public class AugAssign : stmt
  921. {
  922. private expr _target;
  923. private @operator _op;
  924. private expr _value;
  925. public AugAssign() {
  926. _fields = new PythonTuple(new[] { "target", "op", "value" });
  927. }
  928. public AugAssign(expr target, @operator op, expr value,
  929. [Optional]int? lineno, [Optional]int? col_offset)
  930. : this() {
  931. _target = target;
  932. _op = op;
  933. _value = value;
  934. _lineno = lineno;
  935. _col_offset = col_offset;
  936. }
  937. internal AugAssign(AugmentedAssignStatement stmt)
  938. : this() {
  939. _target = Convert(stmt.Left, Store.Instance);
  940. _value = Convert(stmt.Right);
  941. _op = (@operator)Convert(stmt.Operator);
  942. }
  943. internal override Statement Revert() {
  944. return new AugmentedAssignStatement(op.Revert(), expr.Revert(target), expr.Revert(value));
  945. }
  946. public expr target {
  947. get { return _target; }
  948. set { _target = value; }
  949. }
  950. public @operator op {
  951. get { return _op; }
  952. set { _op = value; }
  953. }
  954. public expr value {
  955. get { return _value; }
  956. set { _value = value; }
  957. }
  958. }
  959. /// <summary>
  960. /// Not used.
  961. /// </summary>
  962. [PythonType]
  963. public class AugLoad : expr_context
  964. {
  965. }
  966. /// <summary>
  967. /// Not used.
  968. /// </summary>
  969. [PythonType]
  970. public class AugStore : expr_context
  971. {
  972. }
  973. [PythonType]
  974. public class BinOp : expr
  975. {
  976. private expr _left;
  977. private expr _right;
  978. private @operator _op;
  979. public BinOp() {
  980. _fields = new PythonTuple(new[] { "left", "op", "right" });
  981. }
  982. public BinOp(expr left, @operator op, expr right, [Optional]int? lineno, [Optional]int? col_offset)
  983. : this() {
  984. _left = left;
  985. _op = op;
  986. _right = right;
  987. _lineno = lineno;
  988. _col_offset = col_offset;
  989. }
  990. internal BinOp(BinaryExpression expr, @operator op)
  991. : this() {
  992. _left = Convert(expr.Left);
  993. _right = Convert(expr.Right);
  994. _op = op;
  995. }
  996. internal override AstExpression Revert() {
  997. return new BinaryExpression(op.Revert(), expr.Revert(left), expr.Revert(right));
  998. }
  999. public expr left {
  1000. get { return _left; }
  1001. set { _left = value; }
  1002. }
  1003. public expr right {
  1004. get { return _right; }
  1005. set { _right = value; }
  1006. }
  1007. public @operator op {
  1008. get { return _op; }
  1009. set { _op = value; }
  1010. }
  1011. }
  1012. [PythonType]
  1013. public class BitAnd : @operator
  1014. {
  1015. internal static BitAnd Instance = new BitAnd();
  1016. }
  1017. [PythonType]
  1018. public class BitOr : @operator
  1019. {
  1020. internal static BitOr Instance = new BitOr();
  1021. }
  1022. [PythonType]
  1023. public class BitXor : @operator
  1024. {
  1025. internal static BitXor Instance = new BitXor();
  1026. }
  1027. [PythonType]
  1028. public class BoolOp : expr
  1029. {
  1030. private boolop _op;
  1031. private PythonList _values;
  1032. public BoolOp() {
  1033. _fields = new PythonTuple(new[] { "op", "values" });
  1034. }
  1035. public BoolOp(boolop op, PythonList values, [Optional]int? lineno, [Optional]int? col_offset)
  1036. : this() {
  1037. _op = op;
  1038. _values = values;
  1039. _lineno = lineno;
  1040. _col_offset = col_offset;
  1041. }
  1042. internal BoolOp(AndExpression and)
  1043. : this() {
  1044. _values = PythonOps.MakeListNoCopy(Convert(and.Left), Convert(and.Right));
  1045. _op = And.Instance;
  1046. }
  1047. internal BoolOp(OrExpression or)
  1048. : this() {
  1049. _values = PythonOps.MakeListNoCopy(Convert(or.Left), Convert(or.Right));
  1050. _op = Or.Instance;
  1051. }
  1052. internal override AstExpression Revert() {
  1053. if (op == And.Instance) {
  1054. AndExpression ae = new AndExpression(
  1055. expr.Revert(values[0]),
  1056. expr.Revert(values[1]));
  1057. return ae;
  1058. } else if (op == Or.Instance) {
  1059. OrExpression oe = new OrExpression(
  1060. expr.Revert(values[0]),
  1061. expr.Revert(values[1]));
  1062. return oe;
  1063. }
  1064. throw PythonOps.TypeError("Unexpected boolean operator: {0}", op);
  1065. }
  1066. public boolop op {
  1067. get { return _op; }
  1068. set { _op = value; }
  1069. }
  1070. public PythonList values {
  1071. get { return _values; }
  1072. set { _values = value; }
  1073. }
  1074. }
  1075. [PythonType]
  1076. public class Break : stmt
  1077. {
  1078. internal static Break Instance = new Break();
  1079. internal Break()
  1080. : this(null, null) { }
  1081. public Break([Optional]int? lineno, [Optional]int? col_offset) {
  1082. _lineno = lineno;
  1083. _col_offset = col_offset;
  1084. }
  1085. internal override Statement Revert() {
  1086. return new BreakStatement();
  1087. }
  1088. }
  1089. [PythonType]
  1090. public class Call : expr
  1091. {
  1092. private expr _func;
  1093. private PythonList _args;
  1094. private PythonList _keywords;
  1095. private expr _starargs; // Optional
  1096. private expr _kwargs; // Optional
  1097. public Call() {
  1098. _fields = new PythonTuple(new[] { "func", "args", "keywords", "starargs", "kwargs" });
  1099. }
  1100. public Call( expr func, PythonList args, PythonList keywords,
  1101. [Optional]expr starargs, [Optional]expr kwargs,
  1102. [Optional]int? lineno, [Optional]int? col_offset)
  1103. :this() {
  1104. _func = func;
  1105. _args = args;
  1106. _keywords = keywords;
  1107. _starargs = starargs;
  1108. _kwargs = kwargs;
  1109. _lineno = lineno;
  1110. _col_offset = col_offset;
  1111. }
  1112. internal Call(CallExpression call)
  1113. : this() {
  1114. _args = PythonOps.MakeEmptyList(call.Args.Count);
  1115. _keywords = new PythonList();
  1116. _func = Convert(call.Target);
  1117. foreach (Arg arg in call.Args) {
  1118. if (arg.Name == null)
  1119. _args.Add(Convert(arg.Expression));
  1120. else if (arg.Name == "*")
  1121. _starargs = Convert(arg.Expression);
  1122. else if (arg.Name == "**")
  1123. _kwargs = Convert(arg.Expression);
  1124. else
  1125. _keywords.Add(new keyword(arg));
  1126. }
  1127. }
  1128. internal override AstExpression Revert() {
  1129. AstExpression target = expr.Revert(func);
  1130. List<Arg> newArgs = new List<Arg>();
  1131. foreach (expr ex in args)
  1132. newArgs.Add(new Arg(expr.Revert(ex)));
  1133. if (null != starargs)
  1134. newArgs.Add(new Arg("*", expr.Revert(starargs)));
  1135. if (null != kwargs)
  1136. newArgs.Add(new Arg("**", expr.Revert(kwargs)));
  1137. foreach (keyword kw in keywords)
  1138. newArgs.Add(new Arg(kw.arg, expr.Revert(kw.value)));
  1139. return new CallExpression(target, newArgs.ToArray());
  1140. }
  1141. public expr func {
  1142. get { return _func; }
  1143. set { _func = value; }
  1144. }
  1145. public PythonList args {
  1146. get { return _args; }
  1147. set { _args = value; }
  1148. }
  1149. public PythonList keywords {
  1150. get { return _keywords; }
  1151. set { _keywords = value; }
  1152. }
  1153. public expr starargs {
  1154. get { return _starargs; }
  1155. set { _starargs = value; }
  1156. }
  1157. public expr kwargs {
  1158. get { return _kwargs; }
  1159. set { _kwargs = value; }
  1160. }
  1161. }
  1162. [PythonType]
  1163. public class ClassDef : stmt
  1164. {
  1165. private string _name;
  1166. private PythonList _bases;
  1167. private PythonList _body;
  1168. private PythonList _decorator_list;
  1169. public ClassDef() {
  1170. _fields = new PythonTuple(new[] { "name", "bases", "body", "decorator_list" });
  1171. }
  1172. public ClassDef(string name, PythonList bases, PythonList body, PythonList decorator_list,
  1173. [Optional]int? lineno, [Optional]int? col_offset)
  1174. : this() {
  1175. _name = name;
  1176. _bases = bases;
  1177. _body = body;
  1178. _decorator_list = decorator_list;
  1179. _lineno = lineno;
  1180. _col_offset = col_offset;
  1181. }
  1182. internal ClassDef(ClassDefinition def)
  1183. : this() {
  1184. _name = def.Name;
  1185. _bases = PythonOps.MakeEmptyList(def.Bases.Count);
  1186. foreach (AstExpression expr in def.Bases)
  1187. _bases.Add(Convert(expr));
  1188. _body = ConvertStatements(def.Body);
  1189. if (def.Decorators != null) {
  1190. _decorator_list = PythonOps.MakeEmptyList(def.Decorators.Count);
  1191. foreach (AstExpression expr in def.Decorators)
  1192. _decorator_list.Add(Convert(expr));
  1193. } else
  1194. _decorator_list = PythonOps.MakeEmptyList(0);
  1195. }
  1196. internal override Statement Revert() {
  1197. ClassDefinition cd = new ClassDefinition(name, expr.RevertExprs(bases), RevertStmts(body));
  1198. if (decorator_list.Count != 0)
  1199. cd.Decorators = expr.RevertExprs(decorator_list);
  1200. return cd;
  1201. }
  1202. public string name {
  1203. get { return _name; }
  1204. set { _name = value; }
  1205. }
  1206. public PythonList bases {
  1207. get { return _bases; }
  1208. set { _bases = value; }
  1209. }
  1210. public PythonList body {
  1211. get { return _body; }
  1212. set { _body = value; }
  1213. }
  1214. public PythonList decorator_list {
  1215. get { return _decorator_list; }
  1216. set { _decorator_list = value; }
  1217. }
  1218. }
  1219. [PythonType]
  1220. public class Compare : expr
  1221. {
  1222. private expr _left;
  1223. private PythonList _ops;
  1224. private PythonList _comparators;
  1225. public Compare() {
  1226. _fields = new PythonTuple(new[] { "left", "ops", "comparators" });
  1227. }
  1228. public Compare(expr left, PythonList ops, PythonList comparators,
  1229. [Optional]int? lineno, [Optional]int? col_offset)
  1230. : this() {
  1231. _left = left;
  1232. _ops = ops;
  1233. _comparators = comparators;
  1234. _lineno = lineno;
  1235. _col_offset = col_offset;
  1236. }
  1237. internal Compare(BinaryExpression expr)
  1238. : this() {
  1239. _left = Convert(expr.Left);
  1240. _ops = PythonOps.MakeList();
  1241. _comparators = PythonOps.MakeList();
  1242. while (BinaryExpression.IsComparison(expr.Right)) {
  1243. BinaryExpression right = (BinaryExpression)expr.Right;
  1244. // start accumulating ops and comparators
  1245. _ops.Add(Convert(expr.Operator));
  1246. _comparators.Add(Convert(right.Left));
  1247. expr = right;
  1248. }
  1249. _ops.Add(Convert(expr.Operator));
  1250. _comparators.Add(Convert(expr.Right));
  1251. }
  1252. internal override AstExpression Revert() {
  1253. // the most likely case first
  1254. if (ops.Count == 1) {
  1255. return new BinaryExpression(
  1256. ((cmpop)(ops[0])).Revert(),
  1257. expr.Revert(left),
  1258. expr.Revert(comparators[0]));
  1259. }
  1260. // chaining of comparators is processed here (a>b>c> ...)
  1261. Debug.Assert(ops.Count > 1, "expected 2 or more ops in chained comparator");
  1262. int i = ops.Count - 1;
  1263. BinaryExpression right = new BinaryExpression(
  1264. ((cmpop)(ops[i])).Revert(),
  1265. expr.Revert(comparators[i - 1]),
  1266. expr.Revert(comparators[i]));
  1267. i--;
  1268. while (i > 0) {
  1269. right = new BinaryExpression(
  1270. ((cmpop)(ops[i])).Revert(),
  1271. expr.Revert(comparators[i - 1]),
  1272. right);
  1273. i--;
  1274. }
  1275. return new BinaryExpression(
  1276. ((cmpop)(ops[0])).Revert(),
  1277. expr.Revert(left),
  1278. right);
  1279. }
  1280. public expr left {
  1281. get { return _left; }
  1282. set { _left = value; }
  1283. }
  1284. public PythonList ops {
  1285. get { return _ops; }
  1286. set { _ops = value; }
  1287. }
  1288. public PythonList comparators {
  1289. get { return _comparators; }
  1290. set { _comparators = value; }
  1291. }
  1292. }
  1293. [PythonType]
  1294. public class Continue : stmt
  1295. {
  1296. internal static Continue Instance = new Continue();
  1297. internal Continue()
  1298. : this(null, null) { }
  1299. public Continue([Optional]int? lineno, [Optional]int? col_offset) {
  1300. _lineno = lineno;
  1301. _col_offset = col_offset;
  1302. }
  1303. internal override Statement Revert() {
  1304. return new ContinueStatement();
  1305. }
  1306. }
  1307. [PythonType]
  1308. public class Del : expr_context
  1309. {
  1310. internal static Del Instance = new Del();
  1311. }
  1312. [PythonType]
  1313. public class Delete : stmt
  1314. {
  1315. private PythonList _targets;
  1316. public Delete() {
  1317. _fields = new PythonTuple(new[] { "targets", });
  1318. }
  1319. public Delete(PythonList targets, [Optional]int? lineno, [Optional]int? col_offset)
  1320. : this() {
  1321. _targets = targets;
  1322. _lineno = lineno;
  1323. _col_offset = col_offset;
  1324. }
  1325. internal Delete(DelStatement stmt)
  1326. : this() {
  1327. _targets = PythonOps.MakeEmptyList(stmt.Expressions.Count);
  1328. foreach (AstExpression expr in stmt.Expressions)
  1329. _targets.Add(Convert(expr, Del.Instance));
  1330. }
  1331. internal override Statement Revert() {
  1332. return new DelStatement(expr.RevertExprs(targets));
  1333. }
  1334. public PythonList targets {
  1335. get { return _targets; }
  1336. set { _targets = value; }
  1337. }
  1338. }
  1339. [PythonType]
  1340. public class Dict : expr
  1341. {
  1342. private PythonList _keys;
  1343. private PythonList _values;
  1344. public Dict() {
  1345. _fields = new PythonTuple(new[] { "keys", "values" });
  1346. }
  1347. public Dict(PythonList keys, PythonList values, [Optional]int? lineno, [Optional]int? col_offset)
  1348. : this() {
  1349. _keys = keys;
  1350. _values = values;
  1351. _lineno = lineno;
  1352. _col_offset = col_offset;
  1353. }
  1354. internal Dict(DictionaryExpression expr)
  1355. : this() {
  1356. _keys = PythonOps.MakeEmptyList(expr.Items.Count);
  1357. _values = PythonOps.MakeEmptyList(expr.Items.Count);
  1358. foreach (SliceExpression item in expr.Items) {
  1359. _keys.Add(Convert(item.SliceStart));
  1360. _values.Add(Convert(item.SliceStop));
  1361. }
  1362. }
  1363. internal override AstExpression Revert() {
  1364. SliceExpression[] e = new SliceExpression[values.Count];
  1365. for (int i = 0; i < values.Count; i++) {
  1366. e[i] = new SliceExpression(
  1367. expr.Revert(keys[i]),
  1368. expr.Revert(values[i]),
  1369. null,
  1370. false);
  1371. }
  1372. return new DictionaryExpression(e);
  1373. }
  1374. public PythonList keys {
  1375. get { return _keys; }
  1376. set { _keys = value; }
  1377. }
  1378. public PythonList values {
  1379. get { return _values; }
  1380. set { _values = value; }
  1381. }
  1382. }
  1383. [PythonType]
  1384. public class DictComp : expr
  1385. {
  1386. private expr _key;
  1387. private expr _value;
  1388. private PythonList _generators;
  1389. public DictComp() {
  1390. _fields = new PythonTuple(new[] { "key", "value", "generators" });
  1391. }
  1392. public DictComp(expr key, expr value, PythonList generators,
  1393. [Optional]int? lineno, [Optional]int? col_offset)
  1394. : this() {
  1395. _key = key;
  1396. _value = value;
  1397. _generators = generators;
  1398. _lineno = lineno;
  1399. _col_offset = col_offset;
  1400. }
  1401. internal DictComp(DictionaryComprehension comp)
  1402. : this() {
  1403. _key = Convert(comp.Key);
  1404. _value = Convert(comp.Value);
  1405. _generators = Convert(comp.Iterators);
  1406. }
  1407. internal override AstExpression Revert() {
  1408. return new DictionaryComprehension(expr.Revert(key), expr.Revert(value), comprehension.RevertComprehensions(generators));
  1409. }
  1410. public expr key {
  1411. get { return _key; }
  1412. set { _key = value; }
  1413. }
  1414. public expr value {
  1415. get { return _value; }
  1416. set { _value = value; }
  1417. }
  1418. public PythonList generators {
  1419. get { return _generators; }
  1420. set { _generators = value; }
  1421. }
  1422. }
  1423. [PythonType]
  1424. public class Div : @operator
  1425. {
  1426. internal static Div Instance = new Div();
  1427. }
  1428. [PythonType]
  1429. public class TrueDivide : @operator
  1430. {
  1431. internal static TrueDivide Instance = new TrueDivide();
  1432. }
  1433. [PythonType]
  1434. public class Ellipsis : slice
  1435. {
  1436. internal static Ellipsis Instance = new Ellipsis();
  1437. }
  1438. [PythonType]
  1439. public class Eq : cmpop
  1440. {
  1441. internal static Eq Instance = new Eq();
  1442. }
  1443. [PythonType]
  1444. public class ExceptHandler : excepthandler
  1445. {
  1446. private expr _type;
  1447. private expr _name;
  1448. private PythonList _body;
  1449. public ExceptHandler() {
  1450. _fields = new PythonTuple(new[] { "type", "name", "body" });
  1451. }
  1452. public ExceptHandler([Optional]expr type, [Optional]expr name, PythonList body,
  1453. [Optional]int? lineno, [Optional]int? col_offset)
  1454. : this() {
  1455. _type = type;
  1456. _name = name;
  1457. _body = body;
  1458. _lineno = lineno;
  1459. _col_offset = col_offset;
  1460. }
  1461. internal ExceptHandler(TryStatementHandler stmt)
  1462. : this() {
  1463. if (stmt.Test != null)
  1464. _type = Convert(stmt.Test);
  1465. if (stmt.Target != null)
  1466. _name = Convert(stmt.Target, Store.Instance);
  1467. _body = ConvertStatements(stmt.Body);
  1468. }
  1469. internal TryStatementHandler RevertHandler() {
  1470. return new TryStatementHandler(expr.Revert(type), expr.Revert(name), stmt.RevertStmts(body));
  1471. }
  1472. public expr type {
  1473. get { return _type; }
  1474. set { _type = value; }
  1475. }
  1476. public expr name {
  1477. get { return _name; }
  1478. set { _name = value; }
  1479. }
  1480. public PythonList body {
  1481. get { return _body; }
  1482. set { _body = value; }
  1483. }
  1484. }
  1485. [PythonType]
  1486. public class Exec : stmt
  1487. {
  1488. private expr _body;
  1489. private expr _globals; // Optional
  1490. private expr _locals; // Optional
  1491. public Exec() {
  1492. _fields = new PythonTuple(new[] { "body", "globals", "locals" });
  1493. }
  1494. public Exec(expr body, [Optional]expr globals, [Optional]expr locals,
  1495. [Optional]int? lineno, [Optional]int? col_offset)
  1496. : this() {
  1497. _body = body;
  1498. _globals = globals;
  1499. _locals = locals;
  1500. _lineno = lineno;
  1501. _col_offset = col_offset;
  1502. }
  1503. public Exec(ExecStatement stmt)
  1504. : this() {
  1505. _body = Convert(stmt.Code);
  1506. if (stmt.Globals != null)
  1507. _globals = Convert(stmt.Globals);
  1508. if (stmt.Locals != null)
  1509. _locals = Convert(stmt.Locals);
  1510. }
  1511. internal override Statement Revert() {
  1512. return new ExecStatement(expr.Revert(body), expr.Revert(locals), expr.Revert(globals));
  1513. }
  1514. public expr body {
  1515. get { return _body; }
  1516. set { _body = value; }
  1517. }
  1518. public expr globals {
  1519. get { return _globals; }
  1520. set { _globals = value; }
  1521. }
  1522. public expr locals {
  1523. get { return _locals; }
  1524. set { _locals = value; }
  1525. }
  1526. }
  1527. [PythonType]
  1528. public class Expr : stmt
  1529. {
  1530. private expr _value;
  1531. public Expr() {
  1532. _fields = new PythonTuple(new[] { "value", });
  1533. }
  1534. public Expr(expr value, [Optional]int? lineno, [Optional]int? col_offset)
  1535. : this() {
  1536. _value = value;
  1537. _lineno = lineno;
  1538. _col_offset = col_offset;
  1539. }
  1540. internal Expr(ExpressionStatement stmt)
  1541. : this() {
  1542. _value = Convert(stmt.Expression);
  1543. }
  1544. internal override Statement Revert() {
  1545. return new ExpressionStatement(expr.Revert(value));
  1546. }
  1547. public expr value {
  1548. get { return _value; }
  1549. set { _value = value; }
  1550. }
  1551. }
  1552. [PythonType]
  1553. public class Expression : mod
  1554. {
  1555. private expr _body;
  1556. public Expression() {
  1557. _fields = new PythonTuple(new[] { "body", });
  1558. }
  1559. public Expression(expr body)
  1560. : this() {
  1561. _body = body;
  1562. }
  1563. internal Expression(SuiteStatement suite)
  1564. : this() {
  1565. _body = Convert(((ExpressionStatement)suite.Statements[0]).Expression);
  1566. }
  1567. internal override PythonList GetStatements() {
  1568. return PythonOps.MakeListNoCopy(_body);
  1569. }
  1570. public expr body {
  1571. get { return _body; }
  1572. set { _body = value; }
  1573. }
  1574. }
  1575. [PythonType]
  1576. public class ExtSlice : slice
  1577. {
  1578. private PythonList _dims;
  1579. public ExtSlice() {
  1580. _fields = new PythonTuple(new[] { "dims", });
  1581. }
  1582. public ExtSlice(PythonList dims)
  1583. : this() {
  1584. _dims = dims;
  1585. }
  1586. internal AstExpression[] Revert() {
  1587. List<AstExpression> ret = new List<AstExpression>(dims.Count);
  1588. foreach (expr ex in dims)
  1589. ret.Add(expr.Revert(ex));
  1590. return ret.ToArray();
  1591. }
  1592. public PythonList dims {
  1593. get { return _dims; }
  1594. set { _dims = value; }
  1595. }
  1596. }
  1597. [PythonType]
  1598. public class FloorDiv : @operator
  1599. {
  1600. internal static FloorDiv Instance = new FloorDiv();
  1601. }
  1602. [PythonType]
  1603. public class For : stmt
  1604. {
  1605. private expr _target;
  1606. private expr _iter;
  1607. private PythonList _body;
  1608. private PythonList _orelse; // Optional, default []
  1609. public For() {
  1610. _fields = new PythonTuple(new[] { "target", "iter", "body", "orelse" });
  1611. }
  1612. public For(expr target, expr iter, PythonList body, [Optional]PythonList orelse,
  1613. [Optional]int? lineno, [Optional]int? col_offset)
  1614. : this() {
  1615. _target = target;
  1616. _iter = iter;
  1617. _body = body;
  1618. if (null == orelse)
  1619. _orelse = new PythonList();
  1620. else
  1621. _orelse = orelse;
  1622. _lineno = lineno;
  1623. _col_offset = col_offset;
  1624. }
  1625. internal For(ForStatement stmt)
  1626. : this() {
  1627. _target = Convert(stmt.Left, Store.Instance);
  1628. _iter = Convert(stmt.List);
  1629. _body = ConvertStatements(stmt.Body);
  1630. _orelse = ConvertStatements(stmt.Else, true);
  1631. }
  1632. internal override Statement Revert() {
  1633. return new ForStatement(expr.Revert(target), expr.Revert(iter), RevertStmts(body), RevertStmts(orelse));
  1634. }
  1635. public expr target {
  1636. get { return _target; }
  1637. set { _target = value; }
  1638. }
  1639. public expr iter {
  1640. get { return _iter; }
  1641. set { _iter = value; }
  1642. }
  1643. public PythonList body {
  1644. get { return _body; }
  1645. set { _body = value; }
  1646. }
  1647. public PythonList orelse {
  1648. get { return _orelse; }
  1649. set { _orelse = value; }
  1650. }
  1651. }
  1652. [PythonType]
  1653. public class FunctionDef : stmt
  1654. {
  1655. private string _name;
  1656. private arguments _args;
  1657. private PythonList _body;
  1658. private PythonList _decorator_list;
  1659. public FunctionDef() {
  1660. _fields = new PythonTuple(new[] { "name", "args", "body", "decorator_list" });
  1661. }
  1662. public FunctionDef(string name, arguments args, PythonList body, PythonList decorator_list,
  1663. [Optional]int? lineno, [Optional]int? col_offset)
  1664. : this() {
  1665. _name = name;
  1666. _args = args;
  1667. _body = body;
  1668. _decorator_list = decorator_list;
  1669. _lineno = lineno;
  1670. _col_offset = col_offset;
  1671. }
  1672. internal FunctionDef(FunctionDefinition def)
  1673. : this() {
  1674. _name = def.Name;
  1675. _args = new arguments(def.Parameters);
  1676. _body = ConvertStatements(def.Body);
  1677. if (def.Decorators != null) {
  1678. _decorator_list = PythonOps.MakeEmptyList(def.Decorators.Count);
  1679. foreach (AstExpression expr in def.Decorators)
  1680. _decorator_list.Add(Convert(expr));
  1681. } else
  1682. _decorator_list = PythonOps.MakeEmptyList(0);
  1683. }
  1684. internal override Statement Revert() {
  1685. FunctionDefinition fd = new FunctionDefinition(name, args.Revert(), RevertStmts(body));
  1686. fd.IsGenerator = _containsYield;
  1687. _containsYield = false;
  1688. if (decorator_list.Count != 0)
  1689. fd.Decorators = expr.RevertExprs(decorator_list);
  1690. return fd;
  1691. }
  1692. public string name {
  1693. get { return _name; }
  1694. set { _name = value; }
  1695. }
  1696. public arguments args {
  1697. get { return _args; }
  1698. set { _args = value; }
  1699. }
  1700. public PythonList body {
  1701. get { return _body; }
  1702. set { _body = value; }
  1703. }
  1704. public PythonList decorator_list {
  1705. get { return _decorator_list; }
  1706. set { _decorator_list = value; }
  1707. }
  1708. }
  1709. [PythonType]
  1710. public class GeneratorExp : expr
  1711. {
  1712. private expr _elt;
  1713. private PythonList _generators;
  1714. public GeneratorExp() {
  1715. _fields = new PythonTuple(new[] { "elt", "generators" });
  1716. }
  1717. public GeneratorExp(expr elt, PythonList generators, [Optional]int? lineno, [Optional]int? col_offset)
  1718. : this() {
  1719. _elt = elt;
  1720. _generators = generators;
  1721. _lineno = lineno;
  1722. _col_offset = col_offset;
  1723. }
  1724. // given following generator: (a for b in c for d in e for f in g)
  1725. // PythonAST (Iron) Representation looks like this:
  1726. //
  1727. // Iterable
  1728. // NameExpression c
  1729. //
  1730. // Function
  1731. // FunctionDefinition<genexpr>
  1732. // Parameter__gen_$_parm__
  1733. // ForStatement
  1734. // NameExpression b
  1735. // NameExpression __gen_$_parm__
  1736. // ForStatement
  1737. // NameExpression d
  1738. // NameExpression e
  1739. // ForStatement
  1740. // NameExpression f
  1741. // NameExpression g
  1742. // ExpressionStatement
  1743. // YieldExpression
  1744. // NameExpression a
  1745. //
  1746. // and corresponding ast (implementation agnostic) looks like this:
  1747. // ('Expression', ('GeneratorExp', (1, 1),
  1748. // ('Name', (1, 1), 'a', ('Load',)),
  1749. // [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), []),
  1750. // ('comprehension', ('Name', (1, 18), 'd', ('Store',)), ('Name', (1, 23), 'e', ('Load',)), []),
  1751. // ('comprehension', ('Name', (1, 29), 'f', ('Store',)), ('Name', (1, 34), 'g', ('Load',)), [])
  1752. // ]))
  1753. internal GeneratorExp(GeneratorExpression expr)
  1754. : this() {
  1755. ExtractListComprehensionIterators walker = new ExtractListComprehensionIterators();
  1756. expr.Function.Body.Walk(walker);
  1757. ComprehensionIterator[] iters = walker.Iterators;
  1758. Debug.Assert(iters.Length != 0, "A generator expression cannot have zero iterators.");
  1759. iters[0] = new ComprehensionFor(((ComprehensionFor)iters[0]).Left, expr.Iterable);
  1760. _elt = Convert(walker.Yield.Expression);
  1761. _generators = Convert(iters);
  1762. }
  1763. internal class ExtractListComprehensionIterators : PythonWalker
  1764. {
  1765. private readonly List<ComprehensionIterator> _iterators = new List<ComprehensionIterator>();
  1766. public YieldExpression Yield;
  1767. public ComprehensionIterator[] Iterators {
  1768. get { return _iterators.ToArray(); }
  1769. }
  1770. public override bool Walk(ForStatement node) {
  1771. _iterators.Add(new ComprehensionFor(node.Left, node.List));
  1772. node.Body.Walk(this);
  1773. return false;
  1774. }
  1775. public override bool Walk(IfStatement node) {
  1776. _iterators.Add(new ComprehensionIf(node.Tests[0].Test));
  1777. node.Tests[0].Body.Walk(this);
  1778. return false;
  1779. }
  1780. public override bool Walk(YieldExpression node) {
  1781. Yield = node;
  1782. return false;
  1783. }
  1784. }
  1785. // TODO: following 2 names are copy paste from Parser.cs
  1786. // it would be better to have them in one place
  1787. private const string generatorFnName = "<genexpr>";
  1788. private const string generatorFnArgName = "__gen_$_parm__";
  1789. internal override AstExpression Revert() {
  1790. Statement stmt = new ExpressionStatement(new YieldExpression(expr.Revert(elt)));
  1791. int comprehensionIdx = generators.Count - 1;
  1792. AstExpression list;
  1793. do {
  1794. comprehension c = (comprehension)generators[comprehensionIdx];
  1795. if (c.ifs != null && c.ifs.Count != 0) {
  1796. int ifIdx = c.ifs.Count - 1;
  1797. while (ifIdx >= 0) {
  1798. IfStatementTest ist = new IfStatementTest(expr.Revert(c.ifs[ifIdx]), stmt);
  1799. stmt = new IfStatement(new IfStatementTest[] { ist }, null);
  1800. ifIdx--;
  1801. }
  1802. }
  1803. list = expr.Revert(c.iter);
  1804. stmt = new ForStatement(expr.Revert(c.target), list, stmt, null);
  1805. comprehensionIdx--;
  1806. } while (comprehensionIdx >= 0);
  1807. ((ForStatement)stmt).List = new NameExpression(generatorFnArgName);
  1808. Parameter parameter = new Parameter(generatorFnArgName, 0);
  1809. FunctionDefinition functionDefinition = new FunctionDefinition(generatorFnName, new Parameter[] { parameter }, stmt);
  1810. functionDefinition.IsGenerator = true;
  1811. return new GeneratorExpression(functionDefinition, list);
  1812. }
  1813. public expr elt {
  1814. get { return _elt; }
  1815. set { _elt = value; }
  1816. }
  1817. public PythonList generators {
  1818. get { return _generators; }
  1819. set { _generators = value; }
  1820. }
  1821. }
  1822. [PythonType]
  1823. public class Global : stmt
  1824. {
  1825. private PythonList _names;
  1826. public Global() {
  1827. _fields = new PythonTuple(new[] { "names", });
  1828. }
  1829. public Global(PythonList names, [Optional]int? lineno, [Optional]int? col_offset)
  1830. : this() {
  1831. _names = names;
  1832. _lineno = lineno;
  1833. _col_offset = col_offset;
  1834. }
  1835. internal Global(GlobalStatement stmt)
  1836. : this() {
  1837. _names = new PythonList(stmt.Names);
  1838. }
  1839. internal override Statement Revert() {
  1840. string[] newNames = new string[names.Count];
  1841. for (int i = 0; i < names.Count; i++)
  1842. newNames[i] = (string)names[i];
  1843. return new GlobalStatement(newNames);
  1844. }
  1845. public PythonList names {
  1846. get { return _names; }
  1847. set { _names = value; }
  1848. }
  1849. }
  1850. [PythonType]
  1851. public class Gt : cmpop
  1852. {
  1853. internal static Gt Instance = new Gt();
  1854. }
  1855. [PythonType]
  1856. public class GtE : cmpop
  1857. {
  1858. internal static GtE Instance = new GtE();
  1859. }
  1860. [PythonType]
  1861. public class If : stmt
  1862. {
  1863. private expr _test;
  1864. private PythonList _body;
  1865. private PythonList _orelse; // Optional, default []
  1866. public If() {
  1867. _fields = new PythonTuple(new[] { "test", "body", "orelse" });
  1868. }
  1869. public If(expr test, PythonList body, [Optional]PythonList orelse,
  1870. [Optional]int? lineno, [Optional]int? col_offset)
  1871. : this() {
  1872. _test = test;
  1873. _body = body;
  1874. if (null == orelse)
  1875. _orelse = new PythonList();
  1876. else
  1877. _orelse = orelse;
  1878. _lineno = lineno;
  1879. _col_offset = col_offset;
  1880. }
  1881. internal If(IfStatement stmt)
  1882. : this() {
  1883. If current = this;
  1884. If parent = null;
  1885. foreach (IfStatementTest ifTest in stmt.Tests) {
  1886. if (parent != null) {
  1887. current = new If();
  1888. parent._orelse = PythonOps.MakeListNoCopy(current);
  1889. }
  1890. current.Initialize(ifTest);
  1891. parent = current;
  1892. }
  1893. current._orelse = ConvertStatements(stmt.ElseStatement, true);
  1894. }
  1895. internal void Initialize(IfStatementTest ifTest) {
  1896. _test = Convert(ifTest.Test);
  1897. _body = ConvertStatements(ifTest.Body);
  1898. GetSourceLocation(ifTest);
  1899. }
  1900. internal override Statement Revert() {
  1901. List<IfStatementTest> tests = new List<IfStatementTest>();
  1902. tests.Add(new IfStatementTest(expr.Revert(test), RevertStmts(body)));
  1903. If currIf = this;
  1904. while (currIf.orelse != null && currIf.orelse.Count == 1 && currIf.orelse[0] is If) {
  1905. If orelse = (If)currIf.orelse[0];
  1906. tests.Add(new IfStatementTest(expr.Revert(orelse.test), RevertStmts(orelse.body)));
  1907. currIf = orelse;
  1908. }
  1909. return new IfStatement(tests.ToArray(), RevertStmts(currIf.orelse));
  1910. }
  1911. public expr test {
  1912. get { return _test; }
  1913. set { _test = value; }
  1914. }
  1915. public PythonList body {
  1916. get { return _body; }
  1917. set { _body = value; }
  1918. }
  1919. public PythonList orelse {
  1920. get { return _orelse; }
  1921. set { _orelse = value; }
  1922. }
  1923. }
  1924. [PythonType]
  1925. public class IfExp : expr
  1926. {
  1927. private expr _test;
  1928. private expr _body;
  1929. private expr _orelse;
  1930. public IfExp() {
  1931. _fields = new PythonTuple(new[] { "test", "body", "orelse" });
  1932. }
  1933. public IfExp(expr test, expr body, expr orelse, [Optional]int? lineno, [Optional]int? col_offset)
  1934. : this() {
  1935. _test = test;
  1936. _body = body;
  1937. _orelse = orelse;
  1938. _lineno = lineno;
  1939. _col_offset = col_offset;
  1940. }
  1941. internal IfExp(ConditionalExpression cond)
  1942. : this() {
  1943. _test = Convert(cond.Test);
  1944. _body = Convert(cond.TrueExpression);
  1945. _orelse = Convert(cond.FalseExpression);
  1946. }
  1947. internal override AstExpression Revert() {
  1948. return new ConditionalExpression(expr.Revert(test), expr.Revert(body), expr.Revert(orelse));
  1949. }
  1950. public expr test {
  1951. get { return _test; }
  1952. set { _test = value; }
  1953. }
  1954. public expr body {
  1955. get { return _body; }
  1956. set { _body = value; }
  1957. }
  1958. public expr orelse {
  1959. get { return _orelse; }
  1960. set { _orelse = value; }
  1961. }
  1962. }
  1963. private static char[] MODULE_NAME_SPLITTER = new char[1] { '.' };
  1964. [PythonType]
  1965. public class Import : stmt
  1966. {
  1967. private PythonList _names;
  1968. public Import() {
  1969. _fields = new PythonTuple(new[] { "names", });
  1970. }
  1971. public Import(PythonList names, [Optional]int? lineno, [Optional]int? col_offset)
  1972. : this() {
  1973. _names = names;
  1974. _lineno = lineno;
  1975. _col_offset = col_offset;
  1976. }
  1977. internal Import(ImportStatement stmt)
  1978. : this() {
  1979. _names = ConvertAliases(stmt.Names, stmt.AsNames);
  1980. }
  1981. internal override Statement Revert() {
  1982. ModuleName[] moduleNames = new ModuleName[names.Count];
  1983. String[] asNames = new String[names.Count];
  1984. for (int i = 0; i < names.Count; i++) {
  1985. alias alias = (alias)names[i];
  1986. moduleNames[i] = new ModuleName(alias.name.Split(MODULE_NAME_SPLITTER));
  1987. asNames[i] = alias.asname;
  1988. }
  1989. return new ImportStatement(moduleNames, asNames, false); // TODO: not so sure about the relative/absolute argument here
  1990. }
  1991. public PythonList names {
  1992. get { return _names; }
  1993. set { _names = value; }
  1994. }
  1995. }
  1996. [PythonType]
  1997. public class ImportFrom : stmt
  1998. {
  1999. private string _module; // Optional
  2000. private PythonList _names;
  2001. private int _level; // Optional, default 0
  2002. public ImportFrom() {
  2003. _fields = new PythonTuple(new[] { "module", "names", "level" });
  2004. }
  2005. public ImportFrom([Optional]string module, PythonList names, [Optional]int level,
  2006. [Optional]int? lineno, [Optional]int? col_offset)
  2007. : this() {
  2008. _module = module;
  2009. _names = names;
  2010. _level = level;
  2011. _lineno = lineno;
  2012. _col_offset = col_offset;
  2013. }
  2014. public ImportFrom(FromImportStatement stmt)
  2015. : this() {
  2016. _module = stmt.Root.MakeString();
  2017. _module = string.IsNullOrEmpty(_module) ? null : _module;
  2018. _names = ConvertAliases(stmt.Names, stmt.AsNames);
  2019. if (stmt.Root is RelativeModuleName)
  2020. _level = ((RelativeModuleName)stmt.Root).DotCount;
  2021. }
  2022. internal override Statement Revert() {
  2023. ModuleName root = null;
  2024. bool absolute = false; // TODO: absolute import appears in ModuleOptions, not sure how it should work together
  2025. if (module != null)
  2026. if (module[0] == '.') // relative module
  2027. root = new RelativeModuleName(module.Split(MODULE_NAME_SPLITTER), level);
  2028. else {
  2029. root = new ModuleName(module.Split(MODULE_NAME_SPLITTER));
  2030. absolute = true;
  2031. }
  2032. if (names.Count == 1 && ((alias)names[0]).name == "*")
  2033. return new FromImportStatement(root, (string[])FromImportStatement.Star, null, false, absolute);
  2034. String[] newNames = new String[names.Count];
  2035. String[] asNames = new String[names.Count];
  2036. for (int i = 0; i < names.Count; i++) {
  2037. alias alias = (alias)names[i];
  2038. newNames[i] = alias.name;
  2039. asNames[i] = alias.asname;
  2040. }
  2041. return new FromImportStatement(root, newNames, asNames, false, absolute);
  2042. }
  2043. public string module {
  2044. get { return _module; }
  2045. set { _module = value; }
  2046. }
  2047. public PythonList names {
  2048. get { return _names; }
  2049. set { _names = value; }
  2050. }
  2051. public int level {
  2052. get { return _level; }
  2053. set { _level = value; }
  2054. }
  2055. }
  2056. [PythonType]
  2057. public class In : cmpop
  2058. {
  2059. internal static In Instance = new In();
  2060. }
  2061. [PythonType]
  2062. public class Index : slice
  2063. {
  2064. private expr _value;
  2065. public Index() {
  2066. _fields = new PythonTuple(new[] { "value", });
  2067. }
  2068. public Index(expr value)
  2069. : this() {
  2070. _value = value;
  2071. }
  2072. public expr value {
  2073. get { return _value; }
  2074. set { _value = value; }
  2075. }
  2076. }
  2077. [PythonType]
  2078. public class Interactive : mod
  2079. {
  2080. private PythonList _body;
  2081. public Interactive() {
  2082. _fields = new PythonTuple(new[] { "body", });
  2083. }
  2084. public Interactive(PythonList body)
  2085. : this() {
  2086. _body = body;
  2087. }
  2088. internal Interactive(SuiteStatement suite)
  2089. : this() {
  2090. _body = ConvertStatements(suite);
  2091. }
  2092. internal override PythonList GetStatements() {
  2093. return _body;
  2094. }
  2095. public PythonList body {
  2096. get { return _body; }
  2097. set { _body = value; }
  2098. }
  2099. }
  2100. [PythonType]
  2101. public class Invert : unaryop
  2102. {
  2103. internal static Invert Instance = new Invert();
  2104. }
  2105. [PythonType]
  2106. public class Is : cmpop
  2107. {
  2108. internal static Is Instance = new Is();
  2109. }
  2110. [PythonType]
  2111. public class IsNot : cmpop
  2112. {
  2113. internal static IsNot Instance = new IsNot();
  2114. }
  2115. [PythonType]
  2116. public class Lambda : expr
  2117. {
  2118. private arguments _args;
  2119. private expr _body;
  2120. public Lambda() {
  2121. _fields = new PythonTuple(new[] { "args", "body" });
  2122. }
  2123. public Lambda(arguments args, expr body, [Optional]int? lineno, [Optional]int? col_offset)
  2124. : this() {
  2125. _args = args;
  2126. _body = body;
  2127. _lineno = lineno;
  2128. _col_offset = col_offset;
  2129. }
  2130. internal Lambda(LambdaExpression lambda)
  2131. : this() {
  2132. FunctionDef def = (FunctionDef)Convert(lambda.Function);
  2133. _args = def.args;
  2134. Debug.Assert(def.body.Count == 1, "LambdaExpression body should be one statement.");
  2135. stmt statement = (stmt)def.body[0];
  2136. if (statement is Return)
  2137. _body = ((Return)statement).value;
  2138. else if (statement is Expr) {
  2139. // What should be sufficient is:
  2140. // _body = ((Expr)statement).value;
  2141. // but, AST comes with trees containing twice YieldExpression.
  2142. // For:
  2143. // lamba x: (yield x)
  2144. // it comes back with:
  2145. //
  2146. //IronPython.Compiler.Ast.LambdaExpression
  2147. //IronPython.Compiler.Ast.FunctionDefinition<lambda$334>generator
  2148. // IronPython.Compiler.Ast.Parameter x
  2149. // IronPython.Compiler.Ast.ExpressionStatement
  2150. // IronPython.Compiler.Ast.YieldExpression <<<<<<<<
  2151. // IronPython.Compiler.Ast.YieldExpression <<<<<<<< why twice?
  2152. // IronPython.Compiler.Ast.NameExpression x
  2153. _body = ((Yield)((Expr)statement).value).value;
  2154. } else
  2155. throw PythonOps.TypeError("Unexpected statement type: {0}, expected Return or Expr", statement.GetType());
  2156. }
  2157. internal override AstExpression Revert() {
  2158. Statement newBody;
  2159. AstExpression exp = expr.Revert(body);
  2160. if (!_containsYield)
  2161. newBody = new ReturnStatement(exp);
  2162. else
  2163. newBody = new ExpressionStatement(exp);
  2164. Parameter[] para = args.Revert();
  2165. FunctionDefinition fd = new FunctionDefinition(null, para, newBody);
  2166. fd.IsGenerator = _containsYield;
  2167. _containsYield = false;
  2168. return new LambdaExpression(fd);
  2169. }
  2170. public arguments args {
  2171. get { return _args; }
  2172. set { _args = value; }
  2173. }
  2174. public expr body {
  2175. get { return _body; }
  2176. set { _body = value; }
  2177. }
  2178. }
  2179. [PythonType]
  2180. public class List : expr
  2181. {
  2182. private PythonList _elts;
  2183. private expr_context _ctx;
  2184. public List() {
  2185. _fields = new PythonTuple(new[] { "elts", "ctx" });
  2186. }
  2187. public List(PythonList elts, expr_context ctx, [Optional]int? lineno, [Optional]int? col_offset)
  2188. : this() {
  2189. _elts = elts;
  2190. _ctx = ctx;
  2191. _lineno = lineno;
  2192. _col_offset = col_offset;
  2193. }
  2194. internal List(ListExpression list, expr_context ctx)
  2195. : this() {
  2196. _elts = PythonOps.MakeEmptyList(list.Items.Count);
  2197. foreach (AstExpression expr in list.Items)
  2198. _elts.Add(Convert(expr, ctx));
  2199. _ctx = ctx;
  2200. }
  2201. internal override AstExpression Revert() {
  2202. AstExpression[] e = new AstExpression[elts.Count];
  2203. int i = 0;
  2204. foreach (expr el in elts)
  2205. e[i++] = expr.Revert(el);
  2206. return new ListExpression(e);
  2207. }
  2208. public PythonList elts {
  2209. get { return _elts; }
  2210. set { _elts = value; }
  2211. }
  2212. public expr_context ctx {
  2213. get { return _ctx; }
  2214. set { _ctx = value; }
  2215. }
  2216. }
  2217. [PythonType]
  2218. public class ListComp : expr
  2219. {
  2220. private expr _elt;
  2221. private PythonList _generators;
  2222. public ListComp() {
  2223. _fields = new PythonTuple(new[] { "elt", "generators" });
  2224. }
  2225. public ListComp(expr elt, PythonList generators, [Optional]int? lineno, [Optional]int? col_offset)
  2226. : this() {
  2227. _elt = elt;
  2228. _generators = generators;
  2229. _lineno = lineno;
  2230. _col_offset = col_offset;
  2231. }
  2232. internal ListComp(ListComprehension comp)
  2233. : this() {
  2234. _elt = Convert(comp.Item);
  2235. _generators = Convert(comp.Iterators);
  2236. }
  2237. internal override AstExpression Revert() {
  2238. AstExpression item = expr.Revert(elt);
  2239. ComprehensionIterator[] iters = comprehension.RevertComprehensions(generators);
  2240. return new ListComprehension(item, iters);
  2241. }
  2242. public expr elt {
  2243. get { return _elt; }
  2244. set { _elt = value; }
  2245. }
  2246. public PythonList generators {
  2247. get { return _generators; }
  2248. set { _generators = value; }
  2249. }
  2250. }
  2251. [PythonType]
  2252. public class Load : expr_context
  2253. {
  2254. internal static Load Instance = new Load();
  2255. }
  2256. [PythonType]
  2257. public class Lt : cmpop
  2258. {
  2259. internal static Lt Instance = new Lt();
  2260. }
  2261. [PythonType]
  2262. public class LtE : cmpop
  2263. {
  2264. internal static LtE Instance = new LtE();
  2265. }
  2266. [PythonType]
  2267. public class LShift : @operator
  2268. {
  2269. internal static LShift Instance = new LShift();
  2270. }
  2271. [PythonType]
  2272. public class Mod : @operator
  2273. {
  2274. internal static Mod Instance = new Mod();
  2275. }
  2276. [PythonType]
  2277. public class Module : mod
  2278. {
  2279. private PythonList _body;
  2280. public Module() {
  2281. _fields = new PythonTuple(new[] { "body", });
  2282. }
  2283. public Module(PythonList body)
  2284. : this() {
  2285. _body = body;
  2286. }
  2287. internal Module(SuiteStatement suite)
  2288. : this() {
  2289. _body = ConvertStatements(suite);
  2290. }
  2291. public PythonList body {
  2292. get { return _body; }
  2293. set { _body = value; }
  2294. }
  2295. internal override PythonList GetStatements() {
  2296. return _body;
  2297. }
  2298. }
  2299. [PythonType]
  2300. public class Mult : @operator
  2301. {
  2302. internal static Mult Instance = new Mult();
  2303. }
  2304. [PythonType]
  2305. public class Name : expr
  2306. {
  2307. private string _id;
  2308. private expr_context _ctx;
  2309. public Name() {
  2310. _fields = new PythonTuple(new[] { "id", "ctx" });
  2311. }
  2312. public Name(string id, expr_context ctx, [Optional]int? lineno, [Optional]int? col_offset)
  2313. : this() {
  2314. _id = id;
  2315. _ctx = ctx;
  2316. _lineno = lineno;
  2317. _col_offset = col_offset;
  2318. }
  2319. public Name(String id, expr_context ctx)
  2320. : this(id, ctx, null, null) { }
  2321. internal Name(Parameter para)
  2322. : this(para.Name, Param.Instance) {
  2323. GetSourceLocation(para);
  2324. }
  2325. internal Name(NameExpression expr, expr_context ctx)
  2326. : this(expr.Name, ctx) {
  2327. GetSourceLocation(expr);
  2328. }
  2329. internal override AstExpression Revert() {
  2330. return new NameExpression(id);
  2331. }
  2332. public expr_context ctx {
  2333. get { return _ctx; }
  2334. set { _ctx = value; }
  2335. }
  2336. public string id {
  2337. get { return _id; }
  2338. set { _id = value; }
  2339. }
  2340. }
  2341. [PythonType]
  2342. public class Not : unaryop
  2343. {
  2344. internal static Not Instance = new Not();
  2345. }
  2346. [PythonType]
  2347. public class NotEq : cmpop
  2348. {
  2349. internal static NotEq Instance = new NotEq();
  2350. }
  2351. [PythonType]
  2352. public class NotIn : cmpop
  2353. {
  2354. internal static NotIn Instance = new NotIn();
  2355. }
  2356. [PythonType]
  2357. public class Num : expr
  2358. {
  2359. private object _n;
  2360. public Num() {
  2361. _fields = new PythonTuple(new[] { "n", });
  2362. }
  2363. internal Num(object n)
  2364. : this(n, null, null) { }
  2365. public Num(object n, [Optional]int? lineno, [Optional]int? col_offset)
  2366. : this() {
  2367. _n = n;
  2368. _lineno = lineno;
  2369. _col_offset = col_offset;
  2370. }
  2371. internal override AstExpression Revert() {
  2372. return new ConstantExpression(n);
  2373. }
  2374. public object n {
  2375. get { return _n; }
  2376. set { _n = value; }
  2377. }
  2378. }
  2379. [PythonType]
  2380. public class Or : boolop
  2381. {
  2382. internal static Or Instance = new Or();
  2383. }
  2384. [PythonType]
  2385. public class Param : expr_context
  2386. {
  2387. internal static Param Instance = new Param();
  2388. }
  2389. [PythonType]
  2390. public class Pass : stmt
  2391. {
  2392. internal static Pass Instance = new Pass();
  2393. internal Pass()
  2394. : this(null, null) { }
  2395. public Pass([Optional]int? lineno, [Optional]int? col_offset) {
  2396. _lineno = lineno;
  2397. _col_offset = col_offset;
  2398. }
  2399. internal override Statement Revert() {
  2400. return new EmptyStatement();
  2401. }
  2402. }
  2403. [PythonType]
  2404. public class Pow : @operator
  2405. {
  2406. internal static Pow Instance = new Pow();
  2407. }
  2408. [PythonType]
  2409. public class Print : stmt
  2410. {
  2411. private expr _dest; // optional
  2412. private PythonList _values;
  2413. private bool _nl;
  2414. public Print() {
  2415. _fields = new PythonTuple(new[] { "dest", "values", "nl" });
  2416. }
  2417. public Print([Optional]expr dest, PythonList values, bool nl,
  2418. [Optional]int? lineno, [Optional]int? col_offset)
  2419. : this() {
  2420. _dest = dest;
  2421. _values = values;
  2422. _nl = nl;
  2423. _lineno = lineno;
  2424. _col_offset = col_offset;
  2425. }
  2426. internal Print(PrintStatement stmt)
  2427. : this() {
  2428. if (stmt.Destination != null)
  2429. _dest = Convert(stmt.Destination);
  2430. _values = PythonOps.MakeEmptyList(stmt.Expressions.Count);
  2431. foreach (AstExpression expr in stmt.Expressions)
  2432. _values.Add(Convert(expr));
  2433. _nl = !stmt.TrailingComma;
  2434. }
  2435. internal override Statement Revert() {
  2436. return new PrintStatement(expr.Revert(dest), expr.RevertExprs(values), !nl);
  2437. }
  2438. public expr dest {
  2439. get { return _dest; }
  2440. set { _dest = value; }
  2441. }
  2442. public PythonList values {
  2443. get { return _values; }
  2444. set { _values = value; }
  2445. }
  2446. public bool nl {
  2447. get { return _nl; }
  2448. set { _nl = value; }
  2449. }
  2450. }
  2451. [PythonType]
  2452. public class Raise : stmt
  2453. {
  2454. private expr _type; // Optional
  2455. private expr _inst; // Optional
  2456. private expr _tback; // Optional
  2457. public Raise() {
  2458. _fields = new PythonTuple(new[] { "type", "inst", "tback" });
  2459. }
  2460. public Raise([Optional]expr type, [Optional]expr inst, [Optional]expr tback,
  2461. [Optional]int? lineno, [Optional]int? col_offset)
  2462. : this() {
  2463. _type = type;
  2464. _inst = inst;
  2465. _tback = tback;
  2466. _lineno = lineno;
  2467. _col_offset = col_offset;
  2468. }
  2469. internal Raise(RaiseStatement stmt)
  2470. : this() {
  2471. if (stmt.ExceptType != null)
  2472. _type = Convert(stmt.ExceptType);
  2473. if (stmt.Value != null)
  2474. _inst = Convert(stmt.Value);
  2475. if (stmt.Traceback != null)
  2476. _tback = Convert(stmt.Traceback);
  2477. }
  2478. internal override Statement Revert() {
  2479. return new RaiseStatement(expr.Revert(type), expr.Revert(inst), expr.Revert(tback));
  2480. }
  2481. public expr type {
  2482. get { return _type; }
  2483. set { _type = value; }
  2484. }
  2485. public expr inst {
  2486. get { return _inst; }
  2487. set { _inst = value; }
  2488. }
  2489. public expr tback {
  2490. get { return _tback; }
  2491. set { _tback = value; }
  2492. }
  2493. }
  2494. [PythonType]
  2495. public class Repr : expr
  2496. {
  2497. private expr _value;
  2498. public Repr() {
  2499. _fields = new PythonTuple(new[] { "value", });
  2500. }
  2501. public Repr(expr value, [Optional]int? lineno, [Optional]int? col_offset)
  2502. : this() {
  2503. _value = value;
  2504. _lineno = lineno;
  2505. _col_offset = col_offset;
  2506. }
  2507. internal Repr(BackQuoteExpression expr)
  2508. : this() {
  2509. _value = Convert(expr.Expression);
  2510. }
  2511. internal override AstExpression Revert() {
  2512. return new BackQuoteExpression(expr.Revert(value));
  2513. }
  2514. public expr value {
  2515. get { return _value; }
  2516. set { _value = value; }
  2517. }
  2518. }
  2519. [PythonType]
  2520. public class Return : stmt
  2521. {
  2522. private expr _value; // Optional
  2523. public Return() {
  2524. _fields = new PythonTuple(new[] { "value", });
  2525. }
  2526. public Return([Optional]expr value, [Optional]int? lineno, [Optional]int? col_offset)
  2527. : this() {
  2528. _value = value;
  2529. _lineno = lineno;
  2530. _col_offset = col_offset;
  2531. }
  2532. public Return(ReturnStatement statement)
  2533. : this() {
  2534. // statement.Expression is never null
  2535. //or is it?
  2536. if (statement.Expression == null)
  2537. _value = null;
  2538. else
  2539. _value = Convert(statement.Expression);
  2540. }
  2541. internal override Statement Revert() {
  2542. return new ReturnStatement(expr.Revert(value));
  2543. }
  2544. public expr value {
  2545. get { return _value; }
  2546. set { _value = value; }
  2547. }
  2548. }
  2549. [PythonType]
  2550. public class RShift : @operator
  2551. {
  2552. internal static RShift Instance = new RShift();
  2553. }
  2554. [PythonType]
  2555. public class Set : expr
  2556. {
  2557. private PythonList _elts;
  2558. public Set() {
  2559. _fields = new PythonTuple(new[] { "elts" });
  2560. }
  2561. public Set(PythonList elts, [Optional]int? lineno, [Optional]int? col_offset)
  2562. : this() {
  2563. _elts = elts;
  2564. _lineno = lineno;
  2565. _col_offset = col_offset;
  2566. }
  2567. internal Set(SetExpression setExpression)
  2568. : this() {
  2569. _elts = new PythonList(setExpression.Items.Count);
  2570. foreach (AstExpression item in setExpression.Items) {
  2571. _elts.Add(Convert(item));
  2572. }
  2573. }
  2574. internal override AstExpression Revert() {
  2575. AstExpression[] e = new AstExpression[elts.Count];
  2576. int i = 0;
  2577. foreach (expr el in elts)
  2578. e[i++] = expr.Revert(el);
  2579. return new SetExpression(e);
  2580. }
  2581. public PythonList elts {
  2582. get { return _elts; }
  2583. set { _elts = value; }
  2584. }
  2585. }
  2586. [PythonType]
  2587. public class SetComp : expr
  2588. {
  2589. private expr _elt;
  2590. private PythonList _generators;
  2591. public SetComp() {
  2592. _fields = new PythonTuple(new[] { "elt", "generators" });
  2593. }
  2594. public SetComp(expr elt, PythonList generators, [Optional]int? lineno, [Optional]int? col_offset)
  2595. : this() {
  2596. _elt = elt;
  2597. _generators = generators;
  2598. _lineno = lineno;
  2599. _col_offset = col_offset;
  2600. }
  2601. internal SetComp(SetComprehension comp)
  2602. : this() {
  2603. _elt = Convert(comp.Item);
  2604. _generators = Convert(comp.Iterators);
  2605. }
  2606. internal override AstExpression Revert() {
  2607. AstExpression item = expr.Revert(elt);
  2608. ComprehensionIterator[] iters = comprehension.RevertComprehensions(generators);
  2609. return new SetComprehension(item, iters);
  2610. }
  2611. public expr elt {
  2612. get { return _elt; }
  2613. set { _elt = value; }
  2614. }
  2615. public PythonList generators {
  2616. get { return _generators; }
  2617. set { _generators = value; }
  2618. }
  2619. }
  2620. [PythonType]
  2621. public class Slice : slice
  2622. {
  2623. private expr _lower; // Optional
  2624. private expr _upper; // Optional
  2625. private expr _step; // Optional
  2626. public Slice() {
  2627. _fields = new PythonTuple(new[] { "lower", "upper", "step" });
  2628. }
  2629. public Slice([Optional]expr lower, [Optional]expr upper, [Optional]expr step)
  2630. // default interpretation of missing step is [:]
  2631. // in order to get [::], please provide explicit Name('None',Load.Instance)
  2632. : this() {
  2633. _lower = lower;
  2634. _upper = upper;
  2635. _step = step;
  2636. }
  2637. internal Slice(SliceExpression expr)
  2638. : this() {
  2639. if (expr.SliceStart != null)
  2640. _lower = Convert(expr.SliceStart);
  2641. if (expr.SliceStop != null)
  2642. _upper = Convert(expr.SliceStop);
  2643. if (expr.StepProvided)
  2644. if (expr.SliceStep != null)
  2645. _step = Convert(expr.SliceStep); // [x:y:z]
  2646. else
  2647. _step = new Name("None", Load.Instance); // [x:y:]
  2648. }
  2649. public expr lower {
  2650. get { return _lower; }
  2651. set { _lower = value; }
  2652. }
  2653. public expr upper {
  2654. get { return _upper; }
  2655. set { _upper = value; }
  2656. }
  2657. public expr step {
  2658. get { return _step; }
  2659. set { _step = value; }
  2660. }
  2661. }
  2662. [PythonType]
  2663. public class Store : expr_context
  2664. {
  2665. internal static Store Instance = new Store();
  2666. }
  2667. [PythonType]
  2668. public class Str : expr
  2669. {
  2670. private string _s;
  2671. public Str() {
  2672. _fields = new PythonTuple(new[] { "s", });
  2673. }
  2674. internal Str(String s)
  2675. : this(s, null, null) { }
  2676. public Str(string s, [Optional]int? lineno, [Optional]int? col_offset)
  2677. : this() {
  2678. _s = s;
  2679. _lineno = lineno;
  2680. _col_offset = col_offset;
  2681. }
  2682. internal override AstExpression Revert() {
  2683. return new ConstantExpression(s);
  2684. }
  2685. public string s {
  2686. get { return _s; }
  2687. set { _s = value; }
  2688. }
  2689. }
  2690. [PythonType]
  2691. public class Sub : @operator
  2692. {
  2693. internal static Sub Instance = new Sub();
  2694. }
  2695. [PythonType]
  2696. public class Subscript : expr
  2697. {
  2698. private expr _value;
  2699. private slice _slice;
  2700. private expr_context _ctx;
  2701. public Subscript() {
  2702. _fields = new PythonTuple(new[] { "value", "slice", "ctx" });
  2703. }
  2704. public Subscript( expr value, slice slice, expr_context ctx,
  2705. [Optional]int? lineno, [Optional]int? col_offset )
  2706. : this() {
  2707. _value = value;
  2708. _slice = slice;
  2709. _ctx = ctx;
  2710. _lineno = lineno;
  2711. _col_offset = col_offset;
  2712. }
  2713. internal Subscript(IndexExpression expr, expr_context ctx)
  2714. : this() {
  2715. _value = Convert(expr.Target);
  2716. _ctx = ctx;
  2717. _slice = TrySliceConvert(expr.Index);
  2718. if (_slice == null)
  2719. _slice = new Index(Convert(expr.Index));
  2720. }
  2721. internal override AstExpression Revert() {
  2722. AstExpression index = null;
  2723. if (slice is Index)
  2724. index = expr.Revert(((Index)slice).value);
  2725. else if (slice is Slice) {
  2726. Slice concreteSlice = (Slice)slice;
  2727. AstExpression start = null;
  2728. if (concreteSlice.lower != null)
  2729. start = expr.Revert(concreteSlice.lower);
  2730. AstExpression stop = null;
  2731. if (concreteSlice.upper != null)
  2732. stop = expr.Revert(concreteSlice.upper);
  2733. AstExpression step = null;
  2734. bool stepProvided = false;
  2735. if (concreteSlice.step != null) {
  2736. stepProvided = true;
  2737. if (concreteSlice.step is Name && ((Name)concreteSlice.step).id == "None") {
  2738. // pass
  2739. } else {
  2740. step = expr.Revert(concreteSlice.step);
  2741. }
  2742. }
  2743. index = new SliceExpression(start, stop, step, stepProvided);
  2744. } else if (slice is Ellipsis) {
  2745. index = new ConstantExpression(PythonOps.Ellipsis);
  2746. } else if (slice is ExtSlice) {
  2747. index = new TupleExpression(true, ((ExtSlice)slice).Revert());
  2748. } else {
  2749. Debug.Assert(false, "Unexpected type when converting Subscript: " + slice.GetType());
  2750. }
  2751. return new IndexExpression(expr.Revert(value), index);
  2752. }
  2753. public expr value {
  2754. get { return _value; }
  2755. set { _value = value; }
  2756. }
  2757. public slice slice {
  2758. get { return _slice; }
  2759. set { _slice = value; }
  2760. }
  2761. public expr_context ctx {
  2762. get { return _ctx; }
  2763. set { _ctx = value; }
  2764. }
  2765. }
  2766. /// <summary>
  2767. /// Not an actual node. We don't create this, but it's here for compatibility.
  2768. /// </summary>
  2769. [PythonType]
  2770. public class Suite : mod
  2771. {
  2772. private PythonList _body;
  2773. public Suite() {
  2774. _fields = new PythonTuple(new[] { "body", });
  2775. }
  2776. public Suite(PythonList body)
  2777. : this() {
  2778. _body = body;
  2779. }
  2780. public PythonList body {
  2781. get { return _body; }
  2782. set { _body = value; }
  2783. }
  2784. internal override PythonList GetStatements() {
  2785. return _body;
  2786. }
  2787. }
  2788. [PythonType]
  2789. public class TryExcept : stmt
  2790. {
  2791. private PythonList _body;
  2792. private PythonList _handlers;
  2793. private PythonList _orelse; // Optional, default []
  2794. public TryExcept() {
  2795. _fields = new PythonTuple(new[] { "body", "handlers", "orelse" });
  2796. }
  2797. public TryExcept(PythonList body, PythonList handlers, [Optional]PythonList orelse,
  2798. [Optional]int? lineno, [Optional]int? col_offset )
  2799. : this() {
  2800. _body = body;
  2801. _handlers = handlers;
  2802. if (null == orelse)
  2803. _orelse = new PythonList();
  2804. else
  2805. _orelse = orelse;
  2806. _lineno = lineno;
  2807. _col_offset = col_offset;
  2808. }
  2809. internal TryExcept(TryStatement stmt)
  2810. : this() {
  2811. _body = ConvertStatements(stmt.Body);
  2812. _handlers = PythonOps.MakeEmptyList(stmt.Handlers.Count);
  2813. foreach (TryStatementHandler tryStmt in stmt.Handlers)
  2814. _handlers.Add(Convert(tryStmt));
  2815. _orelse = ConvertStatements(stmt.Else, true);
  2816. }
  2817. internal override Statement Revert() {
  2818. TryStatementHandler[] tshs = new TryStatementHandler[handlers.Count];
  2819. for (int i = 0; i < handlers.Count; i++) {
  2820. tshs[i] = ((ExceptHandler)handlers[i]).RevertHandler();
  2821. }
  2822. return new TryStatement(RevertStmts(body), tshs, RevertStmts(orelse), null);
  2823. }
  2824. public PythonList body {
  2825. get { return _body; }
  2826. set { _body = value; }
  2827. }
  2828. public PythonList handlers {
  2829. get { return _handlers; }
  2830. set { _handlers = value; }
  2831. }
  2832. public PythonList orelse {
  2833. get { return _orelse; }
  2834. set { _orelse = value; }
  2835. }
  2836. }
  2837. [PythonType]
  2838. public class TryFinally : stmt
  2839. {
  2840. private PythonList _body;
  2841. private PythonList _finalbody;
  2842. public TryFinally() {
  2843. _fields = new PythonTuple(new[] { "body", "finalbody" });
  2844. }
  2845. public TryFinally(PythonList body, PythonList finalBody,
  2846. [Optional]int? lineno, [Optional]int? col_offset)
  2847. : this() {
  2848. _body = body;
  2849. _finalbody = finalbody;
  2850. _lineno = lineno;
  2851. _col_offset = col_offset;
  2852. }
  2853. internal TryFinally(PythonList body, PythonList finalbody)
  2854. : this() {
  2855. _body = body;
  2856. _finalbody = finalbody;
  2857. }
  2858. internal override Statement Revert() {
  2859. if (body.Count == 1 && body[0] is TryExcept) {
  2860. TryExcept te = (TryExcept)body[0];
  2861. TryStatementHandler[] tshs = new TryStatementHandler[te.handlers.Count];
  2862. for (int i = 0; i < te.handlers.Count; i++) {
  2863. tshs[i] = ((ExceptHandler)te.handlers[i]).RevertHandler();
  2864. }
  2865. return new TryStatement(RevertStmts(te.body), tshs, RevertStmts(te.orelse), RevertStmts(finalbody));
  2866. }
  2867. return new TryStatement(RevertStmts(body), null, null, RevertStmts(finalbody));
  2868. }
  2869. public PythonList body {
  2870. get { return _body; }
  2871. set { _body = value; }
  2872. }
  2873. public PythonList finalbody {
  2874. get { return _finalbody; }
  2875. set { _finalbody = value; }
  2876. }
  2877. }
  2878. [PythonType]
  2879. public class Tuple : expr
  2880. {
  2881. private PythonList _elts;
  2882. private expr_context _ctx;
  2883. public Tuple() {
  2884. _fields = new PythonTuple(new[] { "elts", "ctx" });
  2885. }
  2886. public Tuple(PythonList elts, expr_context ctx, [Optional]int? lineno, [Optional]int? col_offset)
  2887. : this() {
  2888. _elts = elts;
  2889. _ctx = ctx;
  2890. _lineno = lineno;
  2891. _col_offset = col_offset;
  2892. }
  2893. internal Tuple(TupleExpression list, expr_context ctx)
  2894. : this() {
  2895. _elts = PythonOps.MakeEmptyList(list.Items.Count);
  2896. foreach (AstExpression expr in list.Items)
  2897. _elts.Add(Convert(expr, ctx));
  2898. _ctx = ctx;
  2899. }
  2900. internal override AstExpression Revert() {
  2901. AstExpression[] e = new AstExpression[elts.Count];
  2902. int i = 0;
  2903. foreach (expr el in elts)
  2904. e[i++] = expr.Revert(el);
  2905. return new TupleExpression(false, e);
  2906. }
  2907. public PythonList elts {
  2908. get { return _elts; }
  2909. set { _elts = value; }
  2910. }
  2911. public expr_context ctx {
  2912. get { return _ctx; }
  2913. set { _ctx = value; }
  2914. }
  2915. }
  2916. [PythonType]
  2917. public class UnaryOp : expr
  2918. {
  2919. private unaryop _op;
  2920. private expr _operand;
  2921. public UnaryOp() {
  2922. _fields = new PythonTuple(new[] { "op", "operand" });
  2923. }
  2924. internal UnaryOp(UnaryExpression expression)
  2925. : this() {
  2926. _op = (unaryop)Convert(expression.Op);
  2927. _operand = Convert(expression.Expression);
  2928. }
  2929. public UnaryOp(unaryop op, expr operand, [Optional]int? lineno, [Optional]int? col_offset)
  2930. : this() {
  2931. _op = op;
  2932. _operand = operand;
  2933. _lineno = lineno;
  2934. _col_offset = col_offset;
  2935. }
  2936. internal override AstExpression Revert() {
  2937. return new UnaryExpression(op.Revert(), expr.Revert(operand));
  2938. }
  2939. public unaryop op {
  2940. get { return _op; }
  2941. set { _op = value; }
  2942. }
  2943. public expr operand {
  2944. get { return _operand; }
  2945. set { _operand = value; }
  2946. }
  2947. internal expr TryTrimTrivialUnaryOp() {
  2948. // in case of +constant or -constant returns underlying Num
  2949. // representation, otherwise unmodified itself
  2950. var num = _operand as Num;
  2951. if (null == num) {
  2952. return this;
  2953. }
  2954. if (_op is UAdd) {
  2955. return num;
  2956. }
  2957. if (!(_op is USub)) {
  2958. return this;
  2959. }
  2960. // list of possible types can be found in:
  2961. // class AST {
  2962. // internal static expr Convert(ConstantExpression expr);
  2963. // }
  2964. if (num.n is int) {
  2965. num.n = -(int)num.n;
  2966. } else if (num.n is double) {
  2967. num.n = -(double)num.n;
  2968. } else if (num.n is Int64) {
  2969. num.n = -(Int64)num.n;
  2970. } else if (num.n is BigInteger) {
  2971. num.n = -(BigInteger)num.n;
  2972. } else if (num.n is Complex) {
  2973. num.n = -(Complex)num.n;
  2974. } else {
  2975. return this;
  2976. }
  2977. return num;
  2978. }
  2979. }
  2980. [PythonType]
  2981. public class UAdd : unaryop
  2982. {
  2983. internal static UAdd Instance = new UAdd();
  2984. }
  2985. [PythonType]
  2986. public class USub : unaryop
  2987. {
  2988. internal static USub Instance = new USub();
  2989. }
  2990. [PythonType]
  2991. public class While : stmt
  2992. {
  2993. private expr _test;
  2994. private PythonList _body;
  2995. private PythonList _orelse; // Optional, default []
  2996. public While() {
  2997. _fields = new PythonTuple(new[] { "test", "body", "orelse" });
  2998. }
  2999. public While(expr test, PythonList body, [Optional]PythonList orelse,
  3000. [Optional]int? lineno, [Optional]int? col_offset)
  3001. : this() {
  3002. _test = test;
  3003. _body = body;
  3004. if (null == orelse)
  3005. _orelse = new PythonList();
  3006. else
  3007. _orelse = orelse;
  3008. _lineno = lineno;
  3009. _col_offset = col_offset;
  3010. }
  3011. internal While(WhileStatement stmt)
  3012. : this() {
  3013. _test = Convert(stmt.Test);
  3014. _body = ConvertStatements(stmt.Body);
  3015. _orelse = ConvertStatements(stmt.ElseStatement, true);
  3016. }
  3017. internal override Statement Revert() {
  3018. return new WhileStatement(expr.Revert(test), RevertStmts(body), RevertStmts(orelse));
  3019. }
  3020. public expr test {
  3021. get { return _test; }
  3022. set { _test = value; }
  3023. }
  3024. public PythonList body {
  3025. get { return _body; }
  3026. set { _body = value; }
  3027. }
  3028. public PythonList orelse {
  3029. get { return _orelse; }
  3030. set { _orelse = value; }
  3031. }
  3032. }
  3033. [PythonType]
  3034. public class With : stmt
  3035. {
  3036. private expr _context_expr;
  3037. private expr _optional_vars; // Optional
  3038. private PythonList _body;
  3039. public With() {
  3040. _fields = new PythonTuple(new[] { "context_expr", "optional_vars", "body" });
  3041. }
  3042. public With(expr context_expr, [Optional]expr optional_vars, PythonList body,
  3043. [Optional]int? lineno, [Optional]int? col_offset)
  3044. : this() {
  3045. _context_expr = context_expr;
  3046. _optional_vars = optional_vars;
  3047. _body = body;
  3048. _lineno = lineno;
  3049. _col_offset = col_offset;
  3050. }
  3051. internal With(WithStatement with)
  3052. : this() {
  3053. _context_expr = Convert(with.ContextManager);
  3054. if (with.Variable != null)
  3055. _optional_vars = Convert(with.Variable);
  3056. _body = ConvertStatements(with.Body);
  3057. }
  3058. internal override Statement Revert() {
  3059. return new WithStatement(expr.Revert(context_expr), expr.Revert(optional_vars), RevertStmts(body));
  3060. }
  3061. public expr context_expr {
  3062. get { return _context_expr; }
  3063. set { _context_expr = value; }
  3064. }
  3065. public expr optional_vars {
  3066. get { return _optional_vars; }
  3067. set { _optional_vars = value; }
  3068. }
  3069. public PythonList body {
  3070. get { return _body; }
  3071. set { _body = value; }
  3072. }
  3073. }
  3074. // if yield is detected, the containing function has to be marked as generator
  3075. private static bool _containsYield = false;
  3076. [PythonType]
  3077. public class Yield : expr
  3078. {
  3079. private expr _value; // Optional
  3080. public Yield() {
  3081. _fields = new PythonTuple(new[] { "value", });
  3082. }
  3083. public Yield([Optional]expr value, [Optional]int? lineno, [Optional]int? col_offset)
  3084. : this() {
  3085. _value = value;
  3086. _lineno = lineno;
  3087. _col_offset = col_offset;
  3088. }
  3089. internal Yield(YieldExpression expr)
  3090. : this() {
  3091. // expr.Expression is never null
  3092. _value = Convert(expr.Expression);
  3093. }
  3094. internal override AstExpression Revert() {
  3095. _containsYield = true;
  3096. return new YieldExpression(expr.Revert(value));
  3097. }
  3098. public expr value {
  3099. get { return _value; }
  3100. set { _value = value; }
  3101. }
  3102. }
  3103. }
  3104. }