PageRenderTime 68ms CodeModel.GetById 24ms RepoModel.GetById 1ms 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

Large files files are truncated, but you can click here to view the full file

  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", "de…

Large files files are truncated, but you can click here to view the full file