CodeGenerator.cs 35 KB

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