CodeGenerator.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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 (float)) {
  441. GenerateSingleFloatValue((float) e.Value);
  442. } else if (type == typeof (double)) {
  443. GenerateDoubleValue((double) e.Value);
  444. } else if (type == typeof (decimal)) {
  445. this.GenerateDecimalValue((decimal) e.Value);
  446. } else if (type == typeof (byte) || type == typeof (short) ||
  447. type == typeof (int) || type == typeof (long)) {
  448. // All of these should be IFormatable, I am just being safe/slow
  449. IFormattable formattable = e.Value as IFormattable;
  450. if (formattable != null) {
  451. output.Write (formattable.ToString (null, CultureInfo.InvariantCulture));
  452. } else {
  453. output.Write (e.Value.ToString ());
  454. }
  455. } else {
  456. throw new ArgumentException (string.Format(CultureInfo.InvariantCulture,
  457. "Invalid Primitive Type: {0}. Only CLS compliant primitive " +
  458. "types can be used. Consider using CodeObjectCreateExpression.",
  459. type.FullName));
  460. }
  461. }
  462. protected abstract void GenerateProperty (CodeMemberProperty p, CodeTypeDeclaration d);
  463. protected abstract void GeneratePropertyReferenceExpression (CodePropertyReferenceExpression e);
  464. protected abstract void GeneratePropertySetValueReferenceExpression (CodePropertySetValueReferenceExpression e);
  465. protected abstract void GenerateRemoveEventStatement (CodeRemoveEventStatement statement);
  466. protected virtual void GenerateSingleFloatValue (Single s)
  467. {
  468. output.Write (s.ToString(CultureInfo.InvariantCulture));
  469. }
  470. protected virtual void GenerateSnippetCompileUnit (CodeSnippetCompileUnit e)
  471. {
  472. if (e.LinePragma != null)
  473. GenerateLinePragmaStart (e.LinePragma);
  474. output.WriteLine (e.Value);
  475. if (e.LinePragma != null)
  476. GenerateLinePragmaEnd (e.LinePragma);
  477. }
  478. protected abstract void GenerateSnippetExpression (CodeSnippetExpression e);
  479. protected abstract void GenerateSnippetMember (CodeSnippetTypeMember m);
  480. protected virtual void GenerateSnippetStatement (CodeSnippetStatement s)
  481. {
  482. output.WriteLine (s.Value);
  483. }
  484. protected void GenerateStatement (CodeStatement s)
  485. {
  486. bool handled = false;
  487. #if NET_2_0
  488. if (s.StartDirectives.Count > 0)
  489. GenerateDirectives (s.StartDirectives);
  490. #endif
  491. if (s.LinePragma != null)
  492. GenerateLinePragmaStart (s.LinePragma);
  493. CodeAssignStatement assign = s as CodeAssignStatement;
  494. if (assign != null) {
  495. GenerateAssignStatement (assign);
  496. handled = true;
  497. }
  498. CodeAttachEventStatement attach = s as CodeAttachEventStatement;
  499. if (attach != null) {
  500. GenerateAttachEventStatement (attach);
  501. handled = true;
  502. }
  503. CodeCommentStatement comment = s as CodeCommentStatement;
  504. if (comment != null) {
  505. GenerateCommentStatement (comment);
  506. handled = true;
  507. }
  508. CodeConditionStatement condition = s as CodeConditionStatement;
  509. if (condition != null) {
  510. GenerateConditionStatement (condition);
  511. handled = true;
  512. }
  513. CodeExpressionStatement expression = s as CodeExpressionStatement;
  514. if (expression != null) {
  515. GenerateExpressionStatement (expression);
  516. handled = true;
  517. }
  518. CodeGotoStatement gotostmt = s as CodeGotoStatement;
  519. if (gotostmt != null) {
  520. GenerateGotoStatement (gotostmt);
  521. handled = true;
  522. }
  523. CodeIterationStatement iteration = s as CodeIterationStatement;
  524. if (iteration != null) {
  525. GenerateIterationStatement (iteration);
  526. handled = true;
  527. }
  528. CodeLabeledStatement label = s as CodeLabeledStatement;
  529. if (label != null) {
  530. GenerateLabeledStatement (label);
  531. handled = true;
  532. }
  533. CodeMethodReturnStatement returnstmt = s as CodeMethodReturnStatement;
  534. if (returnstmt != null) {
  535. GenerateMethodReturnStatement (returnstmt);
  536. handled = true;
  537. }
  538. CodeRemoveEventStatement remove = s as CodeRemoveEventStatement;
  539. if (remove != null) {
  540. GenerateRemoveEventStatement (remove);
  541. handled = true;
  542. }
  543. CodeSnippetStatement snippet = s as CodeSnippetStatement;
  544. if (snippet != null) {
  545. #if NET_2_0
  546. int indent = Indent;
  547. try {
  548. Indent = 0;
  549. GenerateSnippetStatement (snippet);
  550. } finally {
  551. Indent = indent;
  552. }
  553. #else
  554. GenerateSnippetStatement (snippet);
  555. #endif
  556. handled = true;
  557. }
  558. CodeThrowExceptionStatement exception = s as CodeThrowExceptionStatement;
  559. if (exception != null) {
  560. GenerateThrowExceptionStatement (exception);
  561. handled = true;
  562. }
  563. CodeTryCatchFinallyStatement trycatch = s as CodeTryCatchFinallyStatement;
  564. if (trycatch != null) {
  565. GenerateTryCatchFinallyStatement (trycatch);
  566. handled = true;
  567. }
  568. CodeVariableDeclarationStatement declaration = s as CodeVariableDeclarationStatement;
  569. if (declaration != null) {
  570. GenerateVariableDeclarationStatement (declaration);
  571. handled = true;
  572. }
  573. if (!handled)
  574. throw new ArgumentException ("Element type " + s + " is not supported.");
  575. if (s.LinePragma != null)
  576. GenerateLinePragmaEnd (s.LinePragma);
  577. #if NET_2_0
  578. if (s.EndDirectives.Count > 0)
  579. GenerateDirectives (s.EndDirectives);
  580. #endif
  581. }
  582. protected void GenerateStatements (CodeStatementCollection c)
  583. {
  584. foreach (CodeStatement statement in c)
  585. GenerateStatement (statement);
  586. }
  587. protected abstract void GenerateThisReferenceExpression (CodeThisReferenceExpression e);
  588. protected abstract void GenerateThrowExceptionStatement (CodeThrowExceptionStatement s);
  589. protected abstract void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement s);
  590. protected abstract void GenerateTypeEnd (CodeTypeDeclaration declaration);
  591. protected abstract void GenerateTypeConstructor (CodeTypeConstructor constructor);
  592. protected virtual void GenerateTypeOfExpression (CodeTypeOfExpression e)
  593. {
  594. output.Write ("typeof(");
  595. OutputType (e.Type);
  596. output.Write (")");
  597. }
  598. protected virtual void GenerateTypeReferenceExpression (CodeTypeReferenceExpression e)
  599. {
  600. OutputType (e.Type);
  601. }
  602. protected void GenerateTypes (CodeNamespace e)
  603. {
  604. foreach (CodeTypeDeclaration type in e.Types)
  605. GenerateType (type);
  606. }
  607. protected abstract void GenerateTypeStart (CodeTypeDeclaration declaration);
  608. protected abstract void GenerateVariableDeclarationStatement (CodeVariableDeclarationStatement e);
  609. protected abstract void GenerateVariableReferenceExpression (CodeVariableReferenceExpression e);
  610. //
  611. // Other members
  612. //
  613. /*
  614. * Output Methods
  615. */
  616. protected virtual void OutputAttributeArgument (CodeAttributeArgument argument)
  617. {
  618. string name = argument.Name;
  619. if ((name != null) && (name.Length > 0)) {
  620. output.Write (name);
  621. output.Write ('=');
  622. }
  623. GenerateExpression (argument.Value);
  624. }
  625. private void OutputAttributeDeclaration (CodeAttributeDeclaration attribute)
  626. {
  627. output.Write (attribute.Name.Replace ('+', '.'));
  628. output.Write ('(');
  629. IEnumerator enumerator = attribute.Arguments.GetEnumerator();
  630. if (enumerator.MoveNext()) {
  631. CodeAttributeArgument argument = (CodeAttributeArgument)enumerator.Current;
  632. OutputAttributeArgument (argument);
  633. while (enumerator.MoveNext()) {
  634. output.Write (',');
  635. argument = (CodeAttributeArgument)enumerator.Current;
  636. OutputAttributeArgument (argument);
  637. }
  638. }
  639. output.Write (')');
  640. }
  641. protected virtual void OutputAttributeDeclarations (CodeAttributeDeclarationCollection attributes)
  642. {
  643. GenerateAttributeDeclarationsStart (attributes);
  644. IEnumerator enumerator = attributes.GetEnumerator();
  645. if (enumerator.MoveNext()) {
  646. CodeAttributeDeclaration attribute = (CodeAttributeDeclaration)enumerator.Current;
  647. OutputAttributeDeclaration (attribute);
  648. while (enumerator.MoveNext()) {
  649. attribute = (CodeAttributeDeclaration)enumerator.Current;
  650. output.WriteLine (',');
  651. OutputAttributeDeclaration (attribute);
  652. }
  653. }
  654. GenerateAttributeDeclarationsEnd (attributes);
  655. }
  656. protected virtual void OutputDirection (FieldDirection direction)
  657. {
  658. switch (direction) {
  659. case FieldDirection.In:
  660. //output.Write ("in ");
  661. break;
  662. case FieldDirection.Out:
  663. output.Write ("out ");
  664. break;
  665. case FieldDirection.Ref:
  666. output.Write ("ref ");
  667. break;
  668. }
  669. }
  670. protected virtual void OutputExpressionList (CodeExpressionCollection expressions)
  671. {
  672. OutputExpressionList (expressions, false);
  673. }
  674. protected virtual void OutputExpressionList (CodeExpressionCollection expressions,
  675. bool newLineBetweenItems)
  676. {
  677. IEnumerator enumerator = expressions.GetEnumerator();
  678. if (enumerator.MoveNext()) {
  679. CodeExpression expression = (CodeExpression)enumerator.Current;
  680. GenerateExpression (expression);
  681. while (enumerator.MoveNext()) {
  682. expression = (CodeExpression)enumerator.Current;
  683. output.Write (',');
  684. if (newLineBetweenItems)
  685. output.WriteLine ();
  686. else
  687. output.Write (' ');
  688. GenerateExpression (expression);
  689. }
  690. }
  691. }
  692. protected virtual void OutputFieldScopeModifier (MemberAttributes attributes)
  693. {
  694. if ((attributes & MemberAttributes.VTableMask) == MemberAttributes.New)
  695. output.Write ("new ");
  696. switch (attributes & MemberAttributes.ScopeMask) {
  697. case MemberAttributes.Static:
  698. output.Write ("static ");
  699. break;
  700. case MemberAttributes.Const:
  701. output.Write ("const ");
  702. break;
  703. }
  704. }
  705. protected virtual void OutputIdentifier (string ident)
  706. {
  707. output.Write (ident);
  708. }
  709. protected virtual void OutputMemberAccessModifier (MemberAttributes attributes)
  710. {
  711. switch (attributes & MemberAttributes.AccessMask) {
  712. case MemberAttributes.Assembly:
  713. output.Write ("internal ");
  714. break;
  715. case MemberAttributes.FamilyAndAssembly:
  716. #if NET_2_0
  717. output.Write ("internal ");
  718. #else
  719. output.Write ("/*FamANDAssem*/ internal ");
  720. #endif
  721. break;
  722. case MemberAttributes.Family:
  723. output.Write ("protected ");
  724. break;
  725. case MemberAttributes.FamilyOrAssembly:
  726. output.Write ("protected internal ");
  727. break;
  728. case MemberAttributes.Private:
  729. output.Write ("private ");
  730. break;
  731. case MemberAttributes.Public:
  732. output.Write ("public ");
  733. break;
  734. }
  735. }
  736. protected virtual void OutputMemberScopeModifier (MemberAttributes attributes)
  737. {
  738. #if NET_2_0
  739. if ((attributes & MemberAttributes.VTableMask) == MemberAttributes.New)
  740. output.Write( "new " );
  741. #endif
  742. switch (attributes & MemberAttributes.ScopeMask) {
  743. case MemberAttributes.Abstract:
  744. output.Write ("abstract ");
  745. break;
  746. case MemberAttributes.Final:
  747. // Do nothing
  748. break;
  749. case MemberAttributes.Static:
  750. output.Write ("static ");
  751. break;
  752. case MemberAttributes.Override:
  753. output.Write ("override ");
  754. break;
  755. default:
  756. //
  757. // FUNNY! if the scope value is
  758. // rubbish (0 or >Const), and access
  759. // is public or protected, make it
  760. // "virtual".
  761. //
  762. // i'm not sure whether this is 100%
  763. // correct, but it seems to be MS
  764. // behavior.
  765. //
  766. // On .NET 2.0, internal members
  767. // are also marked "virtual".
  768. //
  769. MemberAttributes access = attributes & MemberAttributes.AccessMask;
  770. if (access == MemberAttributes.Public || access == MemberAttributes.Family)
  771. output.Write ("virtual ");
  772. break;
  773. }
  774. }
  775. protected virtual void OutputOperator (CodeBinaryOperatorType op)
  776. {
  777. switch (op) {
  778. case CodeBinaryOperatorType.Add:
  779. output.Write ("+");
  780. break;
  781. case CodeBinaryOperatorType.Subtract:
  782. output.Write ("-");
  783. break;
  784. case CodeBinaryOperatorType.Multiply:
  785. output.Write ("*");
  786. break;
  787. case CodeBinaryOperatorType.Divide:
  788. output.Write ("/");
  789. break;
  790. case CodeBinaryOperatorType.Modulus:
  791. output.Write ("%");
  792. break;
  793. case CodeBinaryOperatorType.Assign:
  794. output.Write ("=");
  795. break;
  796. case CodeBinaryOperatorType.IdentityInequality:
  797. output.Write ("!=");
  798. break;
  799. case CodeBinaryOperatorType.IdentityEquality:
  800. output.Write ("==");
  801. break;
  802. case CodeBinaryOperatorType.ValueEquality:
  803. output.Write ("==");
  804. break;
  805. case CodeBinaryOperatorType.BitwiseOr:
  806. output.Write ("|");
  807. break;
  808. case CodeBinaryOperatorType.BitwiseAnd:
  809. output.Write ("&");
  810. break;
  811. case CodeBinaryOperatorType.BooleanOr:
  812. output.Write ("||");
  813. break;
  814. case CodeBinaryOperatorType.BooleanAnd:
  815. output.Write ("&&");
  816. break;
  817. case CodeBinaryOperatorType.LessThan:
  818. output.Write ("<");
  819. break;
  820. case CodeBinaryOperatorType.LessThanOrEqual:
  821. output.Write ("<=");
  822. break;
  823. case CodeBinaryOperatorType.GreaterThan:
  824. output.Write (">");
  825. break;
  826. case CodeBinaryOperatorType.GreaterThanOrEqual:
  827. output.Write (">=");
  828. break;
  829. }
  830. }
  831. protected virtual void OutputParameters (CodeParameterDeclarationExpressionCollection parameters)
  832. {
  833. bool first = true;
  834. foreach (CodeParameterDeclarationExpression expr in parameters) {
  835. if (first)
  836. first = false;
  837. else
  838. output.Write (", ");
  839. GenerateExpression (expr);
  840. }
  841. }
  842. protected abstract void OutputType (CodeTypeReference t);
  843. protected virtual void OutputTypeAttributes (TypeAttributes attributes,
  844. bool isStruct,
  845. bool isEnum)
  846. {
  847. switch (attributes & TypeAttributes.VisibilityMask) {
  848. case TypeAttributes.NotPublic:
  849. // private by default
  850. break;
  851. case TypeAttributes.Public:
  852. case TypeAttributes.NestedPublic:
  853. output.Write ("public ");
  854. break;
  855. case TypeAttributes.NestedPrivate:
  856. output.Write ("private ");
  857. break;
  858. }
  859. if (isStruct)
  860. output.Write ("struct ");
  861. else if (isEnum)
  862. output.Write ("enum ");
  863. else {
  864. if ((attributes & TypeAttributes.Interface) != 0)
  865. output.Write ("interface ");
  866. else if (currentType is CodeTypeDelegate)
  867. output.Write ("delegate ");
  868. else {
  869. if ((attributes & TypeAttributes.Sealed) != 0)
  870. output.Write ("sealed ");
  871. if ((attributes & TypeAttributes.Abstract) != 0)
  872. output.Write ("abstract ");
  873. output.Write ("class ");
  874. }
  875. }
  876. }
  877. protected virtual void OutputTypeNamePair (CodeTypeReference type,
  878. string name)
  879. {
  880. OutputType (type);
  881. output.Write (' ');
  882. output.Write (name);
  883. }
  884. protected abstract string QuoteSnippetString (string value);
  885. /*
  886. * ICodeGenerator
  887. */
  888. protected abstract string CreateEscapedIdentifier (string value);
  889. string ICodeGenerator.CreateEscapedIdentifier (string value)
  890. {
  891. return CreateEscapedIdentifier (value);
  892. }
  893. protected abstract string CreateValidIdentifier (string value);
  894. string ICodeGenerator.CreateValidIdentifier (string value)
  895. {
  896. return CreateValidIdentifier (value);
  897. }
  898. private void InitOutput (TextWriter output, CodeGeneratorOptions options)
  899. {
  900. if (options == null)
  901. options = new CodeGeneratorOptions ();
  902. this.output = new IndentedTextWriter (output, options.IndentString);
  903. this.options = options;
  904. }
  905. void ICodeGenerator.GenerateCodeFromCompileUnit (CodeCompileUnit compileUnit,
  906. TextWriter output,
  907. CodeGeneratorOptions options)
  908. {
  909. InitOutput (output, options);
  910. if (compileUnit is CodeSnippetCompileUnit) {
  911. GenerateSnippetCompileUnit ((CodeSnippetCompileUnit) compileUnit);
  912. } else {
  913. GenerateCompileUnit (compileUnit);
  914. }
  915. }
  916. void ICodeGenerator.GenerateCodeFromExpression (CodeExpression expression,
  917. TextWriter output,
  918. CodeGeneratorOptions options)
  919. {
  920. InitOutput (output, options);
  921. GenerateExpression (expression);
  922. }
  923. void ICodeGenerator.GenerateCodeFromNamespace (CodeNamespace ns,
  924. TextWriter output,
  925. CodeGeneratorOptions options)
  926. {
  927. InitOutput (output, options);
  928. GenerateNamespace (ns);
  929. }
  930. void ICodeGenerator.GenerateCodeFromStatement (CodeStatement statement,
  931. TextWriter output,
  932. CodeGeneratorOptions options)
  933. {
  934. InitOutput (output, options);
  935. GenerateStatement (statement);
  936. }
  937. void ICodeGenerator.GenerateCodeFromType (CodeTypeDeclaration type,
  938. TextWriter output,
  939. CodeGeneratorOptions options)
  940. {
  941. InitOutput (output, options);
  942. GenerateType (type);
  943. }
  944. private void GenerateType (CodeTypeDeclaration type)
  945. {
  946. this.currentType = type;
  947. #if NET_2_0
  948. if (type.StartDirectives.Count > 0)
  949. GenerateDirectives (type.StartDirectives);
  950. #endif
  951. foreach (CodeCommentStatement statement in type.Comments)
  952. GenerateCommentStatement (statement);
  953. if (type.LinePragma != null)
  954. GenerateLinePragmaStart (type.LinePragma);
  955. GenerateTypeStart (type);
  956. CodeTypeMember[] members = new CodeTypeMember[type.Members.Count];
  957. type.Members.CopyTo (members, 0);
  958. #if NET_2_0
  959. if (!Options.VerbatimOrder)
  960. #endif
  961. {
  962. int[] order = new int[members.Length];
  963. for (int n = 0; n < members.Length; n++)
  964. order[n] = Array.IndexOf (memberTypes, members[n].GetType ()) * members.Length + n;
  965. Array.Sort (order, members);
  966. }
  967. // WARNING: if anything is missing in the foreach loop and you add it, add the type in
  968. // its corresponding place in CodeTypeMemberComparer class (below)
  969. CodeTypeDeclaration subtype = null;
  970. foreach (CodeTypeMember member in members) {
  971. CodeTypeMember prevMember = this.currentMember;
  972. this.currentMember = member;
  973. if (prevMember != null && subtype == null) {
  974. if (prevMember.LinePragma != null)
  975. GenerateLinePragmaEnd (prevMember.LinePragma);
  976. #if NET_2_0
  977. if (prevMember.EndDirectives.Count > 0)
  978. GenerateDirectives (prevMember.EndDirectives);
  979. #endif
  980. }
  981. if (options.BlankLinesBetweenMembers)
  982. output.WriteLine ();
  983. subtype = member as CodeTypeDeclaration;
  984. if (subtype != null) {
  985. GenerateType (subtype);
  986. this.currentType = type;
  987. continue;
  988. }
  989. #if NET_2_0
  990. if (currentMember.StartDirectives.Count > 0)
  991. GenerateDirectives (currentMember.StartDirectives);
  992. #endif
  993. foreach (CodeCommentStatement statement in member.Comments)
  994. GenerateCommentStatement (statement);
  995. if (member.LinePragma != null)
  996. GenerateLinePragmaStart (member.LinePragma);
  997. CodeMemberEvent eventm = member as CodeMemberEvent;
  998. if (eventm != null) {
  999. GenerateEvent (eventm, type);
  1000. continue;
  1001. }
  1002. CodeMemberField field = member as CodeMemberField;
  1003. if (field != null) {
  1004. GenerateField (field);
  1005. continue;
  1006. }
  1007. CodeEntryPointMethod epmethod = member as CodeEntryPointMethod;
  1008. if (epmethod != null) {
  1009. GenerateEntryPointMethod (epmethod, type);
  1010. continue;
  1011. }
  1012. CodeTypeConstructor typeCtor = member as CodeTypeConstructor;
  1013. if (typeCtor != null) {
  1014. GenerateTypeConstructor (typeCtor);
  1015. continue;
  1016. }
  1017. CodeConstructor ctor = member as CodeConstructor;
  1018. if (ctor != null) {
  1019. GenerateConstructor (ctor, type);
  1020. continue;
  1021. }
  1022. CodeMemberMethod method = member as CodeMemberMethod;
  1023. if (method != null) {
  1024. GenerateMethod (method, type);
  1025. continue;
  1026. }
  1027. CodeMemberProperty property = member as CodeMemberProperty;
  1028. if (property != null) {
  1029. GenerateProperty (property, type);
  1030. continue;
  1031. }
  1032. CodeSnippetTypeMember snippet = member as CodeSnippetTypeMember;
  1033. if (snippet != null) {
  1034. GenerateSnippetMember (snippet);
  1035. continue;
  1036. }
  1037. this.currentMember = prevMember;
  1038. }
  1039. // Hack because of previous continue usage
  1040. if (currentMember != null && !(currentMember is CodeTypeDeclaration)) {
  1041. if (currentMember.LinePragma != null)
  1042. GenerateLinePragmaEnd (currentMember.LinePragma);
  1043. #if NET_2_0
  1044. if (currentMember.EndDirectives.Count > 0)
  1045. GenerateDirectives (currentMember.EndDirectives);
  1046. #endif
  1047. }
  1048. this.currentType = type;
  1049. GenerateTypeEnd (type);
  1050. if (type.LinePragma != null)
  1051. GenerateLinePragmaEnd (type.LinePragma);
  1052. #if NET_2_0
  1053. if (type.EndDirectives.Count > 0)
  1054. GenerateDirectives (type.EndDirectives);
  1055. #endif
  1056. }
  1057. protected abstract string GetTypeOutput (CodeTypeReference type);
  1058. string ICodeGenerator.GetTypeOutput (CodeTypeReference type)
  1059. {
  1060. return GetTypeOutput (type);
  1061. }
  1062. protected abstract bool IsValidIdentifier (string value);
  1063. bool ICodeGenerator.IsValidIdentifier (string value)
  1064. {
  1065. return IsValidIdentifier (value);
  1066. }
  1067. public static bool IsValidLanguageIndependentIdentifier (string value)
  1068. {
  1069. if (value == null)
  1070. return false;
  1071. if (value.Equals (string.Empty))
  1072. return false;
  1073. switch (char.GetUnicodeCategory (value[0]))
  1074. {
  1075. case UnicodeCategory.LetterNumber:
  1076. case UnicodeCategory.LowercaseLetter:
  1077. case UnicodeCategory.TitlecaseLetter:
  1078. case UnicodeCategory.UppercaseLetter:
  1079. case UnicodeCategory.OtherLetter:
  1080. case UnicodeCategory.ModifierLetter:
  1081. case UnicodeCategory.ConnectorPunctuation:
  1082. if (value.Length > 1)
  1083. {
  1084. for (int x = 0; x < value.Length; x++)
  1085. {
  1086. switch (char.GetUnicodeCategory (value[x]))
  1087. {
  1088. case UnicodeCategory.LetterNumber:
  1089. case UnicodeCategory.LowercaseLetter:
  1090. case UnicodeCategory.TitlecaseLetter:
  1091. case UnicodeCategory.UppercaseLetter:
  1092. case UnicodeCategory.OtherLetter:
  1093. case UnicodeCategory.ModifierLetter:
  1094. case UnicodeCategory.ConnectorPunctuation:
  1095. case UnicodeCategory.DecimalDigitNumber:
  1096. case UnicodeCategory.NonSpacingMark:
  1097. case UnicodeCategory.SpacingCombiningMark:
  1098. case UnicodeCategory.Format:
  1099. return true;
  1100. }
  1101. return false;
  1102. }
  1103. }
  1104. else
  1105. return true;
  1106. break;
  1107. }
  1108. return false;
  1109. }
  1110. protected abstract bool Supports (GeneratorSupport supports);
  1111. bool ICodeGenerator.Supports (GeneratorSupport value)
  1112. {
  1113. return Supports (value);
  1114. }
  1115. protected virtual void ValidateIdentifier (string value)
  1116. {
  1117. if (!(IsValidIdentifier (value)))
  1118. throw new ArgumentException ("Identifier is invalid", "value");
  1119. }
  1120. [MonoTODO]
  1121. public static void ValidateIdentifiers (CodeObject e)
  1122. {
  1123. throw new NotImplementedException();
  1124. }
  1125. void ICodeGenerator.ValidateIdentifier (string value)
  1126. {
  1127. ValidateIdentifier (value);
  1128. }
  1129. // The position in the array determines the order in which those
  1130. // kind of CodeTypeMembers are generated. Less is more ;-)
  1131. static Type [] memberTypes = { typeof (CodeMemberField),
  1132. typeof (CodeSnippetTypeMember),
  1133. typeof (CodeTypeConstructor),
  1134. typeof (CodeConstructor),
  1135. typeof (CodeMemberProperty),
  1136. typeof (CodeMemberEvent),
  1137. typeof (CodeMemberMethod),
  1138. typeof (CodeTypeDeclaration),
  1139. typeof (CodeEntryPointMethod)
  1140. };
  1141. #if NET_2_0
  1142. protected virtual void GenerateDirectives (CodeDirectiveCollection directives)
  1143. {
  1144. }
  1145. #endif
  1146. }
  1147. }