CodeGenerator.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. //
  2. // System.CodeDom.Compiler.CodeGenerator.cs
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. // Daniel Stodden ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected])
  8. // Andreas Nahr ([email protected])
  9. // Marek Safar ([email protected])
  10. //
  11. // (C) 2001-2003 Ximian, Inc.
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System.Globalization;
  34. using System.CodeDom;
  35. using System.Reflection;
  36. using System.IO;
  37. using System.Collections;
  38. namespace System.CodeDom.Compiler {
  39. public abstract class CodeGenerator : ICodeGenerator
  40. {
  41. private IndentedTextWriter output;
  42. private CodeGeneratorOptions options;
  43. private CodeTypeMember currentMember;
  44. private CodeTypeDeclaration currentType;
  45. //
  46. // Constructors
  47. //
  48. protected CodeGenerator()
  49. {
  50. }
  51. //
  52. // Properties
  53. //
  54. #if NET_2_0
  55. protected CodeTypeDeclaration CurrentClass {
  56. get {
  57. return currentType;
  58. }
  59. }
  60. #endif
  61. protected CodeTypeMember CurrentMember {
  62. get {
  63. return currentMember;
  64. }
  65. }
  66. protected string CurrentMemberName {
  67. get {
  68. if (currentMember == null)
  69. return "<% unknown %>";
  70. return currentMember.Name;
  71. }
  72. }
  73. protected string CurrentTypeName {
  74. get {
  75. if (currentType == null)
  76. return "<% unknown %>";
  77. return currentType.Name;
  78. }
  79. }
  80. protected int Indent {
  81. get {
  82. return output.Indent;
  83. }
  84. set {
  85. output.Indent = value;
  86. }
  87. }
  88. protected bool IsCurrentClass {
  89. get {
  90. if (currentType == null)
  91. return false;
  92. return currentType.IsClass && !(currentType is CodeTypeDelegate);
  93. }
  94. }
  95. protected bool IsCurrentDelegate {
  96. get {
  97. return currentType is CodeTypeDelegate;
  98. }
  99. }
  100. protected bool IsCurrentEnum {
  101. get {
  102. if (currentType == null)
  103. return false;
  104. return currentType.IsEnum;
  105. }
  106. }
  107. protected bool IsCurrentInterface {
  108. get {
  109. if (currentType == null)
  110. return false;
  111. return currentType.IsInterface;
  112. }
  113. }
  114. protected bool IsCurrentStruct {
  115. get {
  116. if (currentType == null)
  117. return false;
  118. return currentType.IsStruct;
  119. }
  120. }
  121. protected abstract string NullToken {
  122. get;
  123. }
  124. protected CodeGeneratorOptions Options {
  125. get {
  126. return options;
  127. }
  128. }
  129. protected TextWriter Output {
  130. get {
  131. return output;
  132. }
  133. }
  134. //
  135. // Methods
  136. //
  137. protected virtual void ContinueOnNewLine (string st)
  138. {
  139. output.WriteLine (st);
  140. }
  141. /*
  142. * Code Generation methods
  143. */
  144. protected abstract void GenerateArgumentReferenceExpression (CodeArgumentReferenceExpression e);
  145. protected abstract void GenerateArrayCreateExpression (CodeArrayCreateExpression e);
  146. protected abstract void GenerateArrayIndexerExpression (CodeArrayIndexerExpression e);
  147. protected abstract void GenerateAssignStatement (CodeAssignStatement s);
  148. protected abstract void GenerateAttachEventStatement (CodeAttachEventStatement s);
  149. protected abstract void GenerateAttributeDeclarationsStart (CodeAttributeDeclarationCollection attributes);
  150. protected abstract void GenerateAttributeDeclarationsEnd (CodeAttributeDeclarationCollection attributes);
  151. protected abstract void GenerateBaseReferenceExpression (CodeBaseReferenceExpression e);
  152. protected virtual void GenerateBinaryOperatorExpression (CodeBinaryOperatorExpression e)
  153. {
  154. output.Write ('(');
  155. GenerateExpression (e.Left);
  156. output.Write (' ');
  157. OutputOperator (e.Operator);
  158. output.Write (' ');
  159. GenerateExpression (e.Right);
  160. output.Write (')');
  161. }
  162. protected abstract void GenerateCastExpression (CodeCastExpression e);
  163. #if NET_2_0
  164. [MonoTODO]
  165. public virtual void GenerateCodeFromMember (CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options)
  166. {
  167. throw new NotImplementedException ();
  168. }
  169. #endif
  170. protected abstract void GenerateComment (CodeComment comment);
  171. protected virtual void GenerateCommentStatement (CodeCommentStatement statement)
  172. {
  173. GenerateComment (statement.Comment);
  174. }
  175. protected virtual void GenerateCommentStatements (CodeCommentStatementCollection statements)
  176. {
  177. foreach (CodeCommentStatement comment in statements)
  178. GenerateCommentStatement (comment);
  179. }
  180. protected virtual void GenerateCompileUnit (CodeCompileUnit compileUnit)
  181. {
  182. GenerateCompileUnitStart (compileUnit);
  183. CodeAttributeDeclarationCollection attributes = compileUnit.AssemblyCustomAttributes;
  184. if (attributes.Count != 0) {
  185. foreach (CodeAttributeDeclaration att in attributes) {
  186. GenerateAttributeDeclarationsStart (attributes);
  187. output.Write ("assembly: ");
  188. OutputAttributeDeclaration (att);
  189. GenerateAttributeDeclarationsEnd (attributes);
  190. }
  191. output.WriteLine ();
  192. }
  193. foreach (CodeNamespace ns in compileUnit.Namespaces)
  194. GenerateNamespace (ns);
  195. GenerateCompileUnitEnd (compileUnit);
  196. }
  197. protected virtual void GenerateCompileUnitEnd (CodeCompileUnit compileUnit)
  198. {
  199. #if NET_2_0
  200. if (compileUnit.EndDirectives.Count > 0)
  201. GenerateDirectives (compileUnit.EndDirectives);
  202. #endif
  203. }
  204. protected virtual void GenerateCompileUnitStart (CodeCompileUnit compileUnit)
  205. {
  206. #if NET_2_0
  207. if (compileUnit.StartDirectives.Count > 0) {
  208. GenerateDirectives (compileUnit.StartDirectives);
  209. Output.WriteLine ();
  210. }
  211. #endif
  212. }
  213. protected abstract void GenerateConditionStatement (CodeConditionStatement s);
  214. protected abstract void GenerateConstructor (CodeConstructor x, CodeTypeDeclaration d);
  215. protected virtual void GenerateDecimalValue (Decimal d)
  216. {
  217. Output.Write (d.ToString (CultureInfo.InvariantCulture));
  218. }
  219. #if NET_2_0
  220. [MonoTODO]
  221. protected virtual void GenerateDefaultValueExpression (CodeDefaultValueExpression e)
  222. {
  223. throw new NotImplementedException ();
  224. }
  225. #endif
  226. protected abstract void GenerateDelegateCreateExpression (CodeDelegateCreateExpression e);
  227. protected abstract void GenerateDelegateInvokeExpression (CodeDelegateInvokeExpression e);
  228. protected virtual void GenerateDirectionExpression (CodeDirectionExpression e)
  229. {
  230. OutputDirection (e.Direction);
  231. output.Write (' ');
  232. GenerateExpression (e.Expression);
  233. }
  234. protected virtual void GenerateDoubleValue (Double d)
  235. {
  236. Output.Write (d.ToString (CultureInfo.InvariantCulture));
  237. }
  238. protected abstract void GenerateEntryPointMethod (CodeEntryPointMethod m, CodeTypeDeclaration d);
  239. protected abstract void GenerateEvent (CodeMemberEvent ev, CodeTypeDeclaration d);
  240. protected abstract void GenerateEventReferenceExpression (CodeEventReferenceExpression e);
  241. protected void GenerateExpression (CodeExpression e)
  242. {
  243. if (e == null)
  244. throw new ArgumentNullException ("Value cannot be null.");
  245. CodeArgumentReferenceExpression argref = e as CodeArgumentReferenceExpression;
  246. if (argref != null) {
  247. GenerateArgumentReferenceExpression (argref);
  248. return;
  249. }
  250. CodeArrayCreateExpression mkarray = e as CodeArrayCreateExpression;
  251. if (mkarray != null) {
  252. GenerateArrayCreateExpression (mkarray);
  253. return;
  254. }
  255. CodeArrayIndexerExpression arrayidx = e as CodeArrayIndexerExpression;
  256. if (arrayidx != null) {
  257. GenerateArrayIndexerExpression (arrayidx);
  258. return;
  259. }
  260. CodeBaseReferenceExpression baseref = e as CodeBaseReferenceExpression;
  261. if (baseref != null) {
  262. GenerateBaseReferenceExpression (baseref);
  263. return;
  264. }
  265. CodeBinaryOperatorExpression binary = e as CodeBinaryOperatorExpression;
  266. if (binary != null) {
  267. GenerateBinaryOperatorExpression (binary);
  268. return;
  269. }
  270. CodeCastExpression cast = e as CodeCastExpression;
  271. if (cast != null) {
  272. GenerateCastExpression (cast);
  273. return;
  274. }
  275. CodeDelegateCreateExpression mkdel = e as CodeDelegateCreateExpression;
  276. if (mkdel != null) {
  277. GenerateDelegateCreateExpression (mkdel);
  278. return;
  279. }
  280. CodeDelegateInvokeExpression delinvoke = e as CodeDelegateInvokeExpression;
  281. if (delinvoke != null) {
  282. GenerateDelegateInvokeExpression (delinvoke);
  283. return;
  284. }
  285. CodeDirectionExpression direction = e as CodeDirectionExpression;
  286. if (direction != null) {
  287. GenerateDirectionExpression (direction);
  288. return;
  289. }
  290. CodeEventReferenceExpression eventref = e as CodeEventReferenceExpression;
  291. if ( eventref != null ) {
  292. GenerateEventReferenceExpression( eventref );
  293. return;
  294. }
  295. CodeFieldReferenceExpression fieldref = e as CodeFieldReferenceExpression;
  296. if (fieldref != null) {
  297. GenerateFieldReferenceExpression (fieldref);
  298. return;
  299. }
  300. CodeIndexerExpression idx = e as CodeIndexerExpression;
  301. if (idx != null) {
  302. GenerateIndexerExpression (idx);
  303. return;
  304. }
  305. CodeMethodInvokeExpression methodinv = e as CodeMethodInvokeExpression;
  306. if (methodinv != null) {
  307. GenerateMethodInvokeExpression (methodinv);
  308. return;
  309. }
  310. CodeMethodReferenceExpression methodref = e as CodeMethodReferenceExpression;
  311. if (methodref != null) {
  312. GenerateMethodReferenceExpression (methodref);
  313. return;
  314. }
  315. CodeObjectCreateExpression objref = e as CodeObjectCreateExpression;
  316. if (objref != null) {
  317. GenerateObjectCreateExpression (objref);
  318. return;
  319. }
  320. CodeParameterDeclarationExpression param = e as CodeParameterDeclarationExpression;
  321. if (param != null) {
  322. GenerateParameterDeclarationExpression (param);
  323. return;
  324. }
  325. CodePrimitiveExpression primitive = e as CodePrimitiveExpression;
  326. if (primitive != null) {
  327. GeneratePrimitiveExpression (primitive);
  328. return;
  329. }
  330. CodePropertyReferenceExpression propref = e as CodePropertyReferenceExpression;
  331. if (propref != null) {
  332. GeneratePropertyReferenceExpression (propref);
  333. return;
  334. }
  335. CodePropertySetValueReferenceExpression propset = e as CodePropertySetValueReferenceExpression;
  336. if (propset != null) {
  337. GeneratePropertySetValueReferenceExpression (propset);
  338. return;
  339. }
  340. CodeSnippetExpression snippet = e as CodeSnippetExpression;
  341. if (snippet != null) {
  342. GenerateSnippetExpression (snippet);
  343. return;
  344. }
  345. CodeThisReferenceExpression thisref = e as CodeThisReferenceExpression;
  346. if (thisref != null) {
  347. GenerateThisReferenceExpression (thisref);
  348. return;
  349. }
  350. CodeTypeOfExpression typeOf = e as CodeTypeOfExpression;
  351. if (typeOf != null) {
  352. GenerateTypeOfExpression (typeOf);
  353. return;
  354. }
  355. CodeTypeReferenceExpression typeref = e as CodeTypeReferenceExpression;
  356. if (typeref != null) {
  357. GenerateTypeReferenceExpression (typeref);
  358. return;
  359. }
  360. CodeVariableReferenceExpression varref = e as CodeVariableReferenceExpression;
  361. if (varref != null) {
  362. GenerateVariableReferenceExpression (varref);
  363. return;
  364. }
  365. throw new ArgumentException ("Element type " + e + " is not supported.");
  366. }
  367. protected abstract void GenerateExpressionStatement (CodeExpressionStatement statement);
  368. protected abstract void GenerateField (CodeMemberField f);
  369. protected abstract void GenerateFieldReferenceExpression (CodeFieldReferenceExpression e);
  370. protected abstract void GenerateGotoStatement (CodeGotoStatement statement);
  371. protected abstract void GenerateIndexerExpression (CodeIndexerExpression e);
  372. protected abstract void GenerateIterationStatement (CodeIterationStatement s);
  373. protected abstract void GenerateLabeledStatement (CodeLabeledStatement statement);
  374. protected abstract void GenerateLinePragmaStart (CodeLinePragma p);
  375. protected abstract void GenerateLinePragmaEnd (CodeLinePragma p);
  376. protected abstract void GenerateMethod (CodeMemberMethod m, CodeTypeDeclaration d);
  377. protected abstract void GenerateMethodInvokeExpression (CodeMethodInvokeExpression e);
  378. protected abstract void GenerateMethodReferenceExpression (CodeMethodReferenceExpression e);
  379. protected abstract void GenerateMethodReturnStatement (CodeMethodReturnStatement e);
  380. protected virtual void GenerateNamespace (CodeNamespace ns)
  381. {
  382. foreach (CodeCommentStatement statement in ns.Comments)
  383. GenerateCommentStatement (statement);
  384. GenerateNamespaceStart (ns);
  385. foreach (CodeNamespaceImport import in ns.Imports) {
  386. if (import.LinePragma != null)
  387. GenerateLinePragmaStart (import.LinePragma);
  388. GenerateNamespaceImport (import);
  389. if (import.LinePragma != null)
  390. GenerateLinePragmaEnd (import.LinePragma);
  391. }
  392. output.WriteLine();
  393. foreach (CodeTypeDeclaration type in ns.Types) {
  394. GenerateType (type);
  395. output.WriteLine();
  396. }
  397. GenerateNamespaceEnd (ns);
  398. }
  399. protected abstract void GenerateNamespaceStart (CodeNamespace ns);
  400. protected abstract void GenerateNamespaceEnd (CodeNamespace ns);
  401. protected abstract void GenerateNamespaceImport (CodeNamespaceImport i);
  402. protected void GenerateNamespaceImports (CodeNamespace e)
  403. {
  404. foreach (CodeNamespaceImport import in e.Imports) {
  405. if (import.LinePragma != null)
  406. GenerateLinePragmaStart (import.LinePragma);
  407. GenerateNamespaceImport (import);
  408. if (import.LinePragma != null)
  409. GenerateLinePragmaEnd (import.LinePragma);
  410. }
  411. }
  412. protected void GenerateNamespaces (CodeCompileUnit e)
  413. {
  414. foreach (CodeNamespace ns in e.Namespaces)
  415. GenerateNamespace (ns);
  416. }
  417. protected abstract void GenerateObjectCreateExpression (CodeObjectCreateExpression e);
  418. protected virtual void GenerateParameterDeclarationExpression (CodeParameterDeclarationExpression e)
  419. {
  420. if (e.CustomAttributes != null && e.CustomAttributes.Count > 0)
  421. OutputAttributeDeclarations (e.CustomAttributes);
  422. OutputDirection (e.Direction);
  423. OutputType (e.Type);
  424. output.Write (' ');
  425. output.Write (e.Name);
  426. }
  427. protected virtual void GeneratePrimitiveExpression (CodePrimitiveExpression e)
  428. {
  429. if (e.Value == null) {
  430. output.Write (NullToken);
  431. return;
  432. }
  433. Type type = e.Value.GetType ();
  434. if (type == typeof (bool)) {
  435. output.Write (e.Value.ToString ().ToLower (CultureInfo.InvariantCulture));
  436. } else if (type == typeof (char)) {
  437. output.Write ("'" + e.Value.ToString () + "'");
  438. } else if (type == typeof (string)) {
  439. output.Write (QuoteSnippetString ((string) e.Value));
  440. } else if (type == typeof (byte) || type == typeof (sbyte) || type == typeof (short) ||
  441. type == typeof (int) || type == typeof (long) || type == typeof (float) ||
  442. type == typeof (double) || type == typeof (decimal)) {
  443. // All of these should be IFormatable, I am just being safe/slow
  444. IFormattable formattable = e.Value as IFormattable;
  445. if (formattable != null)
  446. output.Write (formattable.ToString (null, CultureInfo.InvariantCulture));
  447. else
  448. output.Write (e.Value.ToString ());
  449. if (type == typeof (float))
  450. output.Write ("f");
  451. } else {
  452. throw new ArgumentException ("Value type (" + type + ") is not a primitive type");
  453. }
  454. }
  455. protected abstract void GenerateProperty (CodeMemberProperty p, CodeTypeDeclaration d);
  456. protected abstract void GeneratePropertyReferenceExpression (CodePropertyReferenceExpression e);
  457. protected abstract void GeneratePropertySetValueReferenceExpression (CodePropertySetValueReferenceExpression e);
  458. protected abstract void GenerateRemoveEventStatement (CodeRemoveEventStatement statement);
  459. protected virtual void GenerateSingleFloatValue (Single s)
  460. {
  461. output.Write (s.ToString(CultureInfo.InvariantCulture));
  462. }
  463. protected virtual void GenerateSnippetCompileUnit (CodeSnippetCompileUnit e)
  464. {
  465. if (e.LinePragma != null)
  466. GenerateLinePragmaStart (e.LinePragma);
  467. output.WriteLine (e.Value);
  468. if (e.LinePragma != null)
  469. GenerateLinePragmaEnd (e.LinePragma);
  470. }
  471. protected abstract void GenerateSnippetExpression (CodeSnippetExpression e);
  472. protected abstract void GenerateSnippetMember (CodeSnippetTypeMember m);
  473. protected virtual void GenerateSnippetStatement (CodeSnippetStatement s)
  474. {
  475. output.WriteLine (s.Value);
  476. }
  477. protected void GenerateStatement (CodeStatement s)
  478. {
  479. bool handled = false;
  480. #if NET_2_0
  481. if (s.StartDirectives.Count > 0)
  482. GenerateDirectives (s.StartDirectives);
  483. #endif
  484. if (s.LinePragma != null)
  485. GenerateLinePragmaStart (s.LinePragma);
  486. CodeAssignStatement assign = s as CodeAssignStatement;
  487. if (assign != null) {
  488. GenerateAssignStatement (assign);
  489. handled = true;
  490. }
  491. CodeAttachEventStatement attach = s as CodeAttachEventStatement;
  492. if (attach != null) {
  493. GenerateAttachEventStatement (attach);
  494. handled = true;
  495. }
  496. CodeCommentStatement comment = s as CodeCommentStatement;
  497. if (comment != null) {
  498. GenerateCommentStatement (comment);
  499. handled = true;
  500. }
  501. CodeConditionStatement condition = s as CodeConditionStatement;
  502. if (condition != null) {
  503. GenerateConditionStatement (condition);
  504. handled = true;
  505. }
  506. CodeExpressionStatement expression = s as CodeExpressionStatement;
  507. if (expression != null) {
  508. GenerateExpressionStatement (expression);
  509. handled = true;
  510. }
  511. CodeGotoStatement gotostmt = s as CodeGotoStatement;
  512. if (gotostmt != null) {
  513. GenerateGotoStatement (gotostmt);
  514. handled = true;
  515. }
  516. CodeIterationStatement iteration = s as CodeIterationStatement;
  517. if (iteration != null) {
  518. GenerateIterationStatement (iteration);
  519. handled = true;
  520. }
  521. CodeLabeledStatement label = s as CodeLabeledStatement;
  522. if (label != null) {
  523. GenerateLabeledStatement (label);
  524. handled = true;
  525. }
  526. CodeMethodReturnStatement returnstmt = s as CodeMethodReturnStatement;
  527. if (returnstmt != null) {
  528. GenerateMethodReturnStatement (returnstmt);
  529. handled = true;
  530. }
  531. CodeRemoveEventStatement remove = s as CodeRemoveEventStatement;
  532. if (remove != null) {
  533. GenerateRemoveEventStatement (remove);
  534. handled = true;
  535. }
  536. CodeSnippetStatement snippet = s as CodeSnippetStatement;
  537. if (snippet != null) {
  538. GenerateSnippetStatement (snippet);
  539. handled = true;
  540. }
  541. CodeThrowExceptionStatement exception = s as CodeThrowExceptionStatement;
  542. if (exception != null) {
  543. GenerateThrowExceptionStatement (exception);
  544. handled = true;
  545. }
  546. CodeTryCatchFinallyStatement trycatch = s as CodeTryCatchFinallyStatement;
  547. if (trycatch != null) {
  548. GenerateTryCatchFinallyStatement (trycatch);
  549. handled = true;
  550. }
  551. CodeVariableDeclarationStatement declaration = s as CodeVariableDeclarationStatement;
  552. if (declaration != null) {
  553. GenerateVariableDeclarationStatement (declaration);
  554. handled = true;
  555. }
  556. if (!handled)
  557. throw new ArgumentException ("Element type " + s + " is not supported.");
  558. if (s.LinePragma != null)
  559. GenerateLinePragmaEnd (s.LinePragma);
  560. #if NET_2_0
  561. if (s.EndDirectives.Count > 0)
  562. GenerateDirectives (s.EndDirectives);
  563. #endif
  564. }
  565. protected void GenerateStatements (CodeStatementCollection c)
  566. {
  567. foreach (CodeStatement statement in c)
  568. GenerateStatement (statement);
  569. }
  570. protected abstract void GenerateThisReferenceExpression (CodeThisReferenceExpression e);
  571. protected abstract void GenerateThrowExceptionStatement (CodeThrowExceptionStatement s);
  572. protected abstract void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement s);
  573. protected abstract void GenerateTypeEnd (CodeTypeDeclaration declaration);
  574. protected abstract void GenerateTypeConstructor (CodeTypeConstructor constructor);
  575. protected virtual void GenerateTypeOfExpression (CodeTypeOfExpression e)
  576. {
  577. output.Write ("typeof(");
  578. OutputType (e.Type);
  579. output.Write (")");
  580. }
  581. protected virtual void GenerateTypeReferenceExpression (CodeTypeReferenceExpression e)
  582. {
  583. OutputType (e.Type);
  584. }
  585. protected void GenerateTypes (CodeNamespace e)
  586. {
  587. foreach (CodeTypeDeclaration type in e.Types)
  588. GenerateType (type);
  589. }
  590. protected abstract void GenerateTypeStart (CodeTypeDeclaration declaration);
  591. protected abstract void GenerateVariableDeclarationStatement (CodeVariableDeclarationStatement e);
  592. protected abstract void GenerateVariableReferenceExpression (CodeVariableReferenceExpression e);
  593. //
  594. // Other members
  595. //
  596. /*
  597. * Output Methods
  598. */
  599. protected virtual void OutputAttributeArgument (CodeAttributeArgument argument)
  600. {
  601. string name = argument.Name;
  602. if ((name != null) && (name.Length > 0)) {
  603. output.Write (name);
  604. output.Write ('=');
  605. }
  606. GenerateExpression (argument.Value);
  607. }
  608. private void OutputAttributeDeclaration (CodeAttributeDeclaration attribute)
  609. {
  610. output.Write (attribute.Name.Replace ('+', '.'));
  611. output.Write ('(');
  612. IEnumerator enumerator = attribute.Arguments.GetEnumerator();
  613. if (enumerator.MoveNext()) {
  614. CodeAttributeArgument argument = (CodeAttributeArgument)enumerator.Current;
  615. OutputAttributeArgument (argument);
  616. while (enumerator.MoveNext()) {
  617. output.Write (',');
  618. argument = (CodeAttributeArgument)enumerator.Current;
  619. OutputAttributeArgument (argument);
  620. }
  621. }
  622. output.Write (')');
  623. }
  624. protected virtual void OutputAttributeDeclarations (CodeAttributeDeclarationCollection attributes)
  625. {
  626. GenerateAttributeDeclarationsStart (attributes);
  627. IEnumerator enumerator = attributes.GetEnumerator();
  628. if (enumerator.MoveNext()) {
  629. CodeAttributeDeclaration attribute = (CodeAttributeDeclaration)enumerator.Current;
  630. OutputAttributeDeclaration (attribute);
  631. while (enumerator.MoveNext()) {
  632. attribute = (CodeAttributeDeclaration)enumerator.Current;
  633. output.WriteLine (',');
  634. OutputAttributeDeclaration (attribute);
  635. }
  636. }
  637. GenerateAttributeDeclarationsEnd (attributes);
  638. }
  639. protected virtual void OutputDirection (FieldDirection direction)
  640. {
  641. switch (direction) {
  642. case FieldDirection.In:
  643. //output.Write ("in ");
  644. break;
  645. case FieldDirection.Out:
  646. output.Write ("out ");
  647. break;
  648. case FieldDirection.Ref:
  649. output.Write ("ref ");
  650. break;
  651. }
  652. }
  653. protected virtual void OutputExpressionList (CodeExpressionCollection expressions)
  654. {
  655. OutputExpressionList (expressions, false);
  656. }
  657. protected virtual void OutputExpressionList (CodeExpressionCollection expressions,
  658. bool newLineBetweenItems)
  659. {
  660. IEnumerator enumerator = expressions.GetEnumerator();
  661. if (enumerator.MoveNext()) {
  662. CodeExpression expression = (CodeExpression)enumerator.Current;
  663. GenerateExpression (expression);
  664. while (enumerator.MoveNext()) {
  665. expression = (CodeExpression)enumerator.Current;
  666. output.Write (',');
  667. if (newLineBetweenItems)
  668. output.WriteLine ();
  669. else
  670. output.Write (' ');
  671. GenerateExpression (expression);
  672. }
  673. }
  674. }
  675. protected virtual void OutputFieldScopeModifier (MemberAttributes attributes)
  676. {
  677. if ((attributes & MemberAttributes.VTableMask) == MemberAttributes.New)
  678. output.Write ("new ");
  679. switch (attributes & MemberAttributes.ScopeMask) {
  680. case MemberAttributes.Static:
  681. output.Write ("static ");
  682. break;
  683. case MemberAttributes.Const:
  684. output.Write ("const ");
  685. break;
  686. }
  687. }
  688. protected virtual void OutputIdentifier (string ident)
  689. {
  690. output.Write (ident);
  691. }
  692. protected virtual void OutputMemberAccessModifier (MemberAttributes attributes)
  693. {
  694. switch (attributes & MemberAttributes.AccessMask) {
  695. case MemberAttributes.Assembly:
  696. output.Write ("internal ");
  697. break;
  698. case MemberAttributes.FamilyAndAssembly:
  699. #if NET_2_0
  700. output.Write ("internal ");
  701. #else
  702. output.Write ("/*FamANDAssem*/ internal ");
  703. #endif
  704. break;
  705. case MemberAttributes.Family:
  706. output.Write ("protected ");
  707. break;
  708. case MemberAttributes.FamilyOrAssembly:
  709. output.Write ("protected internal ");
  710. break;
  711. case MemberAttributes.Private:
  712. output.Write ("private ");
  713. break;
  714. case MemberAttributes.Public:
  715. output.Write ("public ");
  716. break;
  717. }
  718. }
  719. protected virtual void OutputMemberScopeModifier (MemberAttributes attributes)
  720. {
  721. #if NET_2_0
  722. if ((attributes & MemberAttributes.VTableMask) == MemberAttributes.New)
  723. output.Write( "new " );
  724. #endif
  725. switch (attributes & MemberAttributes.ScopeMask) {
  726. case MemberAttributes.Abstract:
  727. output.Write ("abstract ");
  728. break;
  729. case MemberAttributes.Final:
  730. // Do nothing
  731. break;
  732. case MemberAttributes.Static:
  733. output.Write ("static ");
  734. break;
  735. case MemberAttributes.Override:
  736. output.Write ("override ");
  737. break;
  738. default:
  739. //
  740. // FUNNY! if the scope value is
  741. // rubbish (0 or >Const), and access
  742. // is public or protected, make it
  743. // "virtual".
  744. //
  745. // i'm not sure whether this is 100%
  746. // correct, but it seems to be MS
  747. // behavior.
  748. //
  749. // On .NET 2.0, internal members
  750. // are also marked "virtual".
  751. //
  752. MemberAttributes access = attributes & MemberAttributes.AccessMask;
  753. if (access == MemberAttributes.Public || access == MemberAttributes.Family)
  754. output.Write ("virtual ");
  755. break;
  756. }
  757. }
  758. protected virtual void OutputOperator (CodeBinaryOperatorType op)
  759. {
  760. switch (op) {
  761. case CodeBinaryOperatorType.Add:
  762. output.Write ("+");
  763. break;
  764. case CodeBinaryOperatorType.Subtract:
  765. output.Write ("-");
  766. break;
  767. case CodeBinaryOperatorType.Multiply:
  768. output.Write ("*");
  769. break;
  770. case CodeBinaryOperatorType.Divide:
  771. output.Write ("/");
  772. break;
  773. case CodeBinaryOperatorType.Modulus:
  774. output.Write ("%");
  775. break;
  776. case CodeBinaryOperatorType.Assign:
  777. output.Write ("=");
  778. break;
  779. case CodeBinaryOperatorType.IdentityInequality:
  780. output.Write ("!=");
  781. break;
  782. case CodeBinaryOperatorType.IdentityEquality:
  783. output.Write ("==");
  784. break;
  785. case CodeBinaryOperatorType.ValueEquality:
  786. output.Write ("==");
  787. break;
  788. case CodeBinaryOperatorType.BitwiseOr:
  789. output.Write ("|");
  790. break;
  791. case CodeBinaryOperatorType.BitwiseAnd:
  792. output.Write ("&");
  793. break;
  794. case CodeBinaryOperatorType.BooleanOr:
  795. output.Write ("||");
  796. break;
  797. case CodeBinaryOperatorType.BooleanAnd:
  798. output.Write ("&&");
  799. break;
  800. case CodeBinaryOperatorType.LessThan:
  801. output.Write ("<");
  802. break;
  803. case CodeBinaryOperatorType.LessThanOrEqual:
  804. output.Write ("<=");
  805. break;
  806. case CodeBinaryOperatorType.GreaterThan:
  807. output.Write (">");
  808. break;
  809. case CodeBinaryOperatorType.GreaterThanOrEqual:
  810. output.Write (">=");
  811. break;
  812. }
  813. }
  814. protected virtual void OutputParameters (CodeParameterDeclarationExpressionCollection parameters)
  815. {
  816. bool first = true;
  817. foreach (CodeParameterDeclarationExpression expr in parameters) {
  818. if (first)
  819. first = false;
  820. else
  821. output.Write (", ");
  822. GenerateExpression (expr);
  823. }
  824. }
  825. protected abstract void OutputType (CodeTypeReference t);
  826. protected virtual void OutputTypeAttributes (TypeAttributes attributes,
  827. bool isStruct,
  828. bool isEnum)
  829. {
  830. switch (attributes & TypeAttributes.VisibilityMask) {
  831. case TypeAttributes.NotPublic:
  832. // private by default
  833. break;
  834. case TypeAttributes.Public:
  835. case TypeAttributes.NestedPublic:
  836. output.Write ("public ");
  837. break;
  838. case TypeAttributes.NestedPrivate:
  839. output.Write ("private ");
  840. break;
  841. }
  842. if (isStruct)
  843. output.Write ("struct ");
  844. else if (isEnum)
  845. output.Write ("enum ");
  846. else {
  847. if ((attributes & TypeAttributes.Interface) != 0)
  848. output.Write ("interface ");
  849. else if (currentType is CodeTypeDelegate)
  850. output.Write ("delegate ");
  851. else {
  852. if ((attributes & TypeAttributes.Sealed) != 0)
  853. output.Write ("sealed ");
  854. if ((attributes & TypeAttributes.Abstract) != 0)
  855. output.Write ("abstract ");
  856. output.Write ("class ");
  857. }
  858. }
  859. }
  860. protected virtual void OutputTypeNamePair (CodeTypeReference type,
  861. string name)
  862. {
  863. OutputType (type);
  864. output.Write (' ');
  865. output.Write (name);
  866. }
  867. protected abstract string QuoteSnippetString (string value);
  868. /*
  869. * ICodeGenerator
  870. */
  871. protected abstract string CreateEscapedIdentifier (string value);
  872. string ICodeGenerator.CreateEscapedIdentifier (string value)
  873. {
  874. return CreateEscapedIdentifier (value);
  875. }
  876. protected abstract string CreateValidIdentifier (string value);
  877. string ICodeGenerator.CreateValidIdentifier (string value)
  878. {
  879. return CreateValidIdentifier (value);
  880. }
  881. private void InitOutput (TextWriter output, CodeGeneratorOptions options)
  882. {
  883. if (options == null)
  884. options = new CodeGeneratorOptions ();
  885. this.output = new IndentedTextWriter (output, options.IndentString);
  886. this.options = options;
  887. }
  888. void ICodeGenerator.GenerateCodeFromCompileUnit (CodeCompileUnit compileUnit,
  889. TextWriter output,
  890. CodeGeneratorOptions options)
  891. {
  892. InitOutput (output, options);
  893. if (compileUnit is CodeSnippetCompileUnit) {
  894. GenerateSnippetCompileUnit ((CodeSnippetCompileUnit) compileUnit);
  895. } else {
  896. GenerateCompileUnit (compileUnit);
  897. }
  898. }
  899. void ICodeGenerator.GenerateCodeFromExpression (CodeExpression expression,
  900. TextWriter output,
  901. CodeGeneratorOptions options)
  902. {
  903. InitOutput (output, options);
  904. GenerateExpression (expression);
  905. }
  906. void ICodeGenerator.GenerateCodeFromNamespace (CodeNamespace ns,
  907. TextWriter output,
  908. CodeGeneratorOptions options)
  909. {
  910. InitOutput (output, options);
  911. GenerateNamespace (ns);
  912. }
  913. void ICodeGenerator.GenerateCodeFromStatement (CodeStatement statement,
  914. TextWriter output,
  915. CodeGeneratorOptions options)
  916. {
  917. InitOutput (output, options);
  918. GenerateStatement (statement);
  919. }
  920. void ICodeGenerator.GenerateCodeFromType (CodeTypeDeclaration type,
  921. TextWriter output,
  922. CodeGeneratorOptions options)
  923. {
  924. InitOutput (output, options);
  925. GenerateType (type);
  926. }
  927. private void GenerateType (CodeTypeDeclaration type)
  928. {
  929. this.currentType = type;
  930. #if NET_2_0
  931. if (type.StartDirectives.Count > 0)
  932. GenerateDirectives (type.StartDirectives);
  933. #endif
  934. foreach (CodeCommentStatement statement in type.Comments)
  935. GenerateCommentStatement (statement);
  936. if (type.LinePragma != null)
  937. GenerateLinePragmaStart (type.LinePragma);
  938. GenerateTypeStart (type);
  939. CodeTypeMember[] members = new CodeTypeMember[type.Members.Count];
  940. type.Members.CopyTo (members, 0);
  941. #if NET_2_0
  942. if (!Options.VerbatimOrder)
  943. #endif
  944. {
  945. int[] order = new int[members.Length];
  946. for (int n = 0; n < members.Length; n++)
  947. order[n] = Array.IndexOf (memberTypes, members[n].GetType ()) * members.Length + n;
  948. Array.Sort (order, members);
  949. }
  950. // WARNING: if anything is missing in the foreach loop and you add it, add the type in
  951. // its corresponding place in CodeTypeMemberComparer class (below)
  952. CodeTypeDeclaration subtype = null;
  953. foreach (CodeTypeMember member in members) {
  954. CodeTypeMember prevMember = this.currentMember;
  955. this.currentMember = member;
  956. if (prevMember != null && subtype == null) {
  957. if (prevMember.LinePragma != null)
  958. GenerateLinePragmaEnd (prevMember.LinePragma);
  959. #if NET_2_0
  960. if (prevMember.EndDirectives.Count > 0)
  961. GenerateDirectives (prevMember.EndDirectives);
  962. #endif
  963. }
  964. if (options.BlankLinesBetweenMembers)
  965. output.WriteLine ();
  966. subtype = member as CodeTypeDeclaration;
  967. if (subtype != null) {
  968. GenerateType (subtype);
  969. this.currentType = type;
  970. continue;
  971. }
  972. #if NET_2_0
  973. if (currentMember.StartDirectives.Count > 0)
  974. GenerateDirectives (currentMember.StartDirectives);
  975. #endif
  976. foreach (CodeCommentStatement statement in member.Comments)
  977. GenerateCommentStatement (statement);
  978. if (member.LinePragma != null)
  979. GenerateLinePragmaStart (member.LinePragma);
  980. CodeMemberEvent eventm = member as CodeMemberEvent;
  981. if (eventm != null) {
  982. GenerateEvent (eventm, type);
  983. continue;
  984. }
  985. CodeMemberField field = member as CodeMemberField;
  986. if (field != null) {
  987. GenerateField (field);
  988. continue;
  989. }
  990. CodeEntryPointMethod epmethod = member as CodeEntryPointMethod;
  991. if (epmethod != null) {
  992. GenerateEntryPointMethod (epmethod, type);
  993. continue;
  994. }
  995. CodeTypeConstructor typeCtor = member as CodeTypeConstructor;
  996. if (typeCtor != null) {
  997. GenerateTypeConstructor (typeCtor);
  998. continue;
  999. }
  1000. CodeConstructor ctor = member as CodeConstructor;
  1001. if (ctor != null) {
  1002. GenerateConstructor (ctor, type);
  1003. continue;
  1004. }
  1005. CodeMemberMethod method = member as CodeMemberMethod;
  1006. if (method != null) {
  1007. GenerateMethod (method, type);
  1008. continue;
  1009. }
  1010. CodeMemberProperty property = member as CodeMemberProperty;
  1011. if (property != null) {
  1012. GenerateProperty (property, type);
  1013. continue;
  1014. }
  1015. CodeSnippetTypeMember snippet = member as CodeSnippetTypeMember;
  1016. if (snippet != null) {
  1017. GenerateSnippetMember (snippet);
  1018. continue;
  1019. }
  1020. this.currentMember = prevMember;
  1021. }
  1022. // Hack because of previous continue usage
  1023. if (currentMember != null && !(currentMember is CodeTypeDeclaration)) {
  1024. if (currentMember.LinePragma != null)
  1025. GenerateLinePragmaEnd (currentMember.LinePragma);
  1026. #if NET_2_0
  1027. if (currentMember.EndDirectives.Count > 0)
  1028. GenerateDirectives (currentMember.EndDirectives);
  1029. #endif
  1030. }
  1031. this.currentType = type;
  1032. GenerateTypeEnd (type);
  1033. if (type.LinePragma != null)
  1034. GenerateLinePragmaEnd (type.LinePragma);
  1035. #if NET_2_0
  1036. if (type.EndDirectives.Count > 0)
  1037. GenerateDirectives (type.EndDirectives);
  1038. #endif
  1039. }
  1040. protected abstract string GetTypeOutput (CodeTypeReference type);
  1041. string ICodeGenerator.GetTypeOutput (CodeTypeReference type)
  1042. {
  1043. return GetTypeOutput (type);
  1044. }
  1045. protected abstract bool IsValidIdentifier (string value);
  1046. bool ICodeGenerator.IsValidIdentifier (string value)
  1047. {
  1048. return IsValidIdentifier (value);
  1049. }
  1050. public static bool IsValidLanguageIndependentIdentifier (string value)
  1051. {
  1052. if (value == null)
  1053. return false;
  1054. if (value.Equals (string.Empty))
  1055. return false;
  1056. switch (char.GetUnicodeCategory (value[0]))
  1057. {
  1058. case UnicodeCategory.LetterNumber:
  1059. case UnicodeCategory.LowercaseLetter:
  1060. case UnicodeCategory.TitlecaseLetter:
  1061. case UnicodeCategory.UppercaseLetter:
  1062. case UnicodeCategory.OtherLetter:
  1063. case UnicodeCategory.ModifierLetter:
  1064. case UnicodeCategory.ConnectorPunctuation:
  1065. if (value.Length > 1)
  1066. {
  1067. for (int x = 0; x < value.Length; x++)
  1068. {
  1069. switch (char.GetUnicodeCategory (value[x]))
  1070. {
  1071. case UnicodeCategory.LetterNumber:
  1072. case UnicodeCategory.LowercaseLetter:
  1073. case UnicodeCategory.TitlecaseLetter:
  1074. case UnicodeCategory.UppercaseLetter:
  1075. case UnicodeCategory.OtherLetter:
  1076. case UnicodeCategory.ModifierLetter:
  1077. case UnicodeCategory.ConnectorPunctuation:
  1078. case UnicodeCategory.DecimalDigitNumber:
  1079. case UnicodeCategory.NonSpacingMark:
  1080. case UnicodeCategory.SpacingCombiningMark:
  1081. case UnicodeCategory.Format:
  1082. return true;
  1083. }
  1084. return false;
  1085. }
  1086. }
  1087. else
  1088. return true;
  1089. break;
  1090. }
  1091. return false;
  1092. }
  1093. protected abstract bool Supports (GeneratorSupport supports);
  1094. bool ICodeGenerator.Supports (GeneratorSupport value)
  1095. {
  1096. return Supports (value);
  1097. }
  1098. protected virtual void ValidateIdentifier (string value)
  1099. {
  1100. if (!(IsValidIdentifier (value)))
  1101. throw new ArgumentException ("Identifier is invalid", "value");
  1102. }
  1103. [MonoTODO]
  1104. public static void ValidateIdentifiers (CodeObject e)
  1105. {
  1106. throw new NotImplementedException();
  1107. }
  1108. void ICodeGenerator.ValidateIdentifier (string value)
  1109. {
  1110. ValidateIdentifier (value);
  1111. }
  1112. // The position in the array determines the order in which those
  1113. // kind of CodeTypeMembers are generated. Less is more ;-)
  1114. static Type [] memberTypes = { typeof (CodeMemberField),
  1115. typeof (CodeSnippetTypeMember),
  1116. typeof (CodeTypeConstructor),
  1117. typeof (CodeConstructor),
  1118. typeof (CodeMemberProperty),
  1119. typeof (CodeMemberEvent),
  1120. typeof (CodeMemberMethod),
  1121. typeof (CodeTypeDeclaration),
  1122. typeof (CodeEntryPointMethod)
  1123. };
  1124. #if NET_2_0
  1125. protected virtual void GenerateDirectives (CodeDirectiveCollection directives)
  1126. {
  1127. }
  1128. #endif
  1129. }
  1130. }