CodeGenerator.cs 36 KB

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