Importer-Exporter.st 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. Smalltalk current createPackage: 'Importer-Exporter'!
  2. Object subclass: #AbstractExporter
  3. instanceVariableNames: ''
  4. package: 'Importer-Exporter'!
  5. !AbstractExporter commentStamp!
  6. I am an abstract exporter for Amber source code.!
  7. !AbstractExporter methodsFor: 'convenience'!
  8. chunkEscape: aString
  9. "Replace all occurrences of !! with !!!! and trim at both ends."
  10. ^(aString replace: '!!' with: '!!!!') trimBoth
  11. !
  12. classNameFor: aClass
  13. ^aClass isMetaclass
  14. ifTrue: [ aClass instanceClass name, ' class' ]
  15. ifFalse: [
  16. aClass isNil
  17. ifTrue: [ 'nil' ]
  18. ifFalse: [ aClass name ] ]
  19. ! !
  20. !AbstractExporter methodsFor: 'fileOut'!
  21. recipe
  22. "Recipe to export a given package."
  23. self subclassResponsibility
  24. ! !
  25. AbstractExporter class instanceVariableNames: 'default'!
  26. !AbstractExporter class methodsFor: 'instance creation'!
  27. default
  28. ^ default ifNil: [ default := self new ]
  29. ! !
  30. AbstractExporter subclass: #ChunkExporter
  31. instanceVariableNames: ''
  32. package: 'Importer-Exporter'!
  33. !ChunkExporter commentStamp!
  34. I am an exporter dedicated to outputting Amber source code in the classic Smalltalk chunk format.
  35. I do not output any compiled code.!
  36. !ChunkExporter methodsFor: 'accessing'!
  37. extensionCategoriesOfPackage: aPackage
  38. "Issue #143: sort protocol alphabetically"
  39. | name map result |
  40. name := aPackage name.
  41. result := OrderedCollection new.
  42. (Package sortedClasses: Smalltalk current classes) do: [:each |
  43. {each. each class} do: [:aClass |
  44. map := Dictionary new.
  45. aClass protocolsDo: [:category :methods |
  46. (category match: '^\*', name) ifTrue: [ map at: category put: methods ]].
  47. result addAll: ((map keys sorted: [:a :b | a <= b ]) collect: [:category |
  48. MethodCategory name: category theClass: aClass methods: (map at: category)]) ]].
  49. ^result
  50. !
  51. methodsOfCategory: aCategory
  52. "Issue #143: sort methods alphabetically"
  53. ^(aCategory methods) sorted: [:a :b | a selector <= b selector]
  54. !
  55. ownCategoriesOfClass: aClass
  56. "Answer the protocols of aClassthat are not package extensions"
  57. "Issue #143: sort protocol alphabetically"
  58. | map |
  59. map := Dictionary new.
  60. aClass protocolsDo: [:category :methods |
  61. (category match: '^\*') ifFalse: [ map at: category put: methods ]].
  62. ^(map keys sorted: [:a :b | a <= b ]) collect: [:category |
  63. MethodCategory name: category theClass: aClass methods: (map at: category) ]
  64. !
  65. ownCategoriesOfMetaClass: aClass
  66. "Issue #143: sort protocol alphabetically"
  67. ^self ownCategoriesOfClass: aClass class
  68. ! !
  69. !ChunkExporter methodsFor: 'fileOut'!
  70. recipe
  71. "Export a given package."
  72. | exportCategoryRecipe |
  73. exportCategoryRecipe := {
  74. self -> #exportCategoryPrologueOf:on:.
  75. {
  76. self -> #methodsOfCategory:.
  77. self -> #exportMethod:on: }.
  78. self -> #exportCategoryEpilogueOf:on: }.
  79. ^{
  80. self -> #exportPackageDefinitionOf:on:.
  81. {
  82. PluggableExporter -> #ownClassesOfPackage:.
  83. self -> #exportDefinitionOf:on:.
  84. { self -> #ownCategoriesOfClass: }, exportCategoryRecipe.
  85. self -> #exportMetaDefinitionOf:on:.
  86. { self -> #ownCategoriesOfMetaClass: }, exportCategoryRecipe }.
  87. { self -> #extensionCategoriesOfPackage: }, exportCategoryRecipe
  88. }
  89. ! !
  90. !ChunkExporter methodsFor: 'output'!
  91. exportCategoryEpilogueOf: aCategory on: aStream
  92. aStream nextPutAll: ' !!'; lf; lf
  93. !
  94. exportCategoryPrologueOf: aCategory on: aStream
  95. aStream
  96. nextPutAll: '!!', (self classNameFor: aCategory theClass);
  97. nextPutAll: ' methodsFor: ''', aCategory name, '''!!'
  98. !
  99. exportDefinitionOf: aClass on: aStream
  100. "Chunk format."
  101. aStream
  102. nextPutAll: (self classNameFor: aClass superclass);
  103. nextPutAll: ' subclass: #', (self classNameFor: aClass); lf;
  104. tab; nextPutAll: 'instanceVariableNames: '''.
  105. aClass instanceVariableNames
  106. do: [:each | aStream nextPutAll: each]
  107. separatedBy: [aStream nextPutAll: ' '].
  108. aStream
  109. nextPutAll: ''''; lf;
  110. tab; nextPutAll: 'package: ''', aClass category, '''!!'; lf.
  111. aClass comment notEmpty ifTrue: [
  112. aStream
  113. nextPutAll: '!!', (self classNameFor: aClass), ' commentStamp!!';lf;
  114. nextPutAll: (self chunkEscape: aClass comment), '!!';lf].
  115. aStream lf
  116. !
  117. exportMetaDefinitionOf: aClass on: aStream
  118. aClass class instanceVariableNames isEmpty ifFalse: [
  119. aStream
  120. nextPutAll: (self classNameFor: aClass class);
  121. nextPutAll: ' instanceVariableNames: '''.
  122. aClass class instanceVariableNames
  123. do: [:each | aStream nextPutAll: each]
  124. separatedBy: [aStream nextPutAll: ' '].
  125. aStream
  126. nextPutAll: '''!!'; lf; lf]
  127. !
  128. exportMethod: aMethod on: aStream
  129. aStream
  130. lf; lf; nextPutAll: (self chunkEscape: aMethod source); lf;
  131. nextPutAll: '!!'
  132. !
  133. exportPackageDefinitionOf: aPackage on: aStream
  134. "Chunk format."
  135. aStream
  136. nextPutAll: 'Smalltalk current createPackage: ''', aPackage name, '''!!';
  137. lf
  138. ! !
  139. !ChunkExporter class methodsFor: 'exporting-accessing'!
  140. extensionCategoriesOfPackage: package
  141. "Issue #143: sort protocol alphabetically"
  142. | name map result |
  143. name := package name.
  144. result := OrderedCollection new.
  145. (Package sortedClasses: Smalltalk current classes) do: [:each |
  146. {each. each class} do: [:aClass |
  147. map := Dictionary new.
  148. aClass protocolsDo: [:category :methods |
  149. (category match: '^\*', name) ifTrue: [ map at: category put: methods ]].
  150. result addAll: ((map keys sorted: [:a :b | a <= b ]) collect: [:category |
  151. MethodCategory name: category theClass: aClass methods: (map at: category)]) ]].
  152. ^result
  153. !
  154. methodsOfCategory: category
  155. "Issue #143: sort methods alphabetically"
  156. ^(category methods) sorted: [:a :b | a selector <= b selector]
  157. !
  158. ownCategoriesOfClass: aClass
  159. "Issue #143: sort protocol alphabetically"
  160. | map |
  161. map := Dictionary new.
  162. aClass protocolsDo: [:category :methods |
  163. (category match: '^\*') ifFalse: [ map at: category put: methods ]].
  164. ^(map keys sorted: [:a :b | a <= b ]) collect: [:category |
  165. MethodCategory name: category theClass: aClass methods: (map at: category) ]
  166. !
  167. ownCategoriesOfMetaClass: aClass
  168. "Issue #143: sort protocol alphabetically"
  169. ^self ownCategoriesOfClass: aClass class
  170. ! !
  171. !ChunkExporter class methodsFor: 'exporting-output'!
  172. exportCategoryEpilogueOf: category on: aStream
  173. aStream nextPutAll: ' !!'; lf; lf
  174. !
  175. exportCategoryPrologueOf: category on: aStream
  176. aStream
  177. nextPutAll: '!!', (self classNameFor: category theClass);
  178. nextPutAll: ' methodsFor: ''', category name, '''!!'
  179. !
  180. exportDefinitionOf: aClass on: aStream
  181. "Chunk format."
  182. aStream
  183. nextPutAll: (self classNameFor: aClass superclass);
  184. nextPutAll: ' subclass: #', (self classNameFor: aClass); lf;
  185. tab; nextPutAll: 'instanceVariableNames: '''.
  186. aClass instanceVariableNames
  187. do: [:each | aStream nextPutAll: each]
  188. separatedBy: [aStream nextPutAll: ' '].
  189. aStream
  190. nextPutAll: ''''; lf;
  191. tab; nextPutAll: 'package: ''', aClass category, '''!!'; lf.
  192. aClass comment notEmpty ifTrue: [
  193. aStream
  194. nextPutAll: '!!', (self classNameFor: aClass), ' commentStamp!!';lf;
  195. nextPutAll: (self chunkEscape: aClass comment), '!!';lf].
  196. aStream lf
  197. !
  198. exportMetaDefinitionOf: aClass on: aStream
  199. aClass class instanceVariableNames isEmpty ifFalse: [
  200. aStream
  201. nextPutAll: (self classNameFor: aClass class);
  202. nextPutAll: ' instanceVariableNames: '''.
  203. aClass class instanceVariableNames
  204. do: [:each | aStream nextPutAll: each]
  205. separatedBy: [aStream nextPutAll: ' '].
  206. aStream
  207. nextPutAll: '''!!'; lf; lf]
  208. !
  209. exportMethod: aMethod on: aStream
  210. aStream
  211. lf; lf; nextPutAll: (self chunkEscape: aMethod source); lf;
  212. nextPutAll: '!!'
  213. !
  214. exportPackageDefinitionOf: package on: aStream
  215. "Chunk format."
  216. aStream
  217. nextPutAll: 'Smalltalk current createPackage: ''', package name, '''!!';
  218. lf
  219. ! !
  220. !ChunkExporter class methodsFor: 'fileOut'!
  221. recipe
  222. "Export a given package."
  223. | exportCategoryRecipe |
  224. exportCategoryRecipe := {
  225. self -> #exportCategoryPrologueOf:on:.
  226. {
  227. self -> #methodsOfCategory:.
  228. self -> #exportMethod:on: }.
  229. self -> #exportCategoryEpilogueOf:on: }.
  230. ^{
  231. self -> #exportPackageDefinitionOf:on:.
  232. {
  233. PluggableExporter -> #ownClassesOfPackage:.
  234. self -> #exportDefinitionOf:on:.
  235. { self -> #ownCategoriesOfClass: }, exportCategoryRecipe.
  236. self -> #exportMetaDefinitionOf:on:.
  237. { self -> #ownCategoriesOfMetaClass: }, exportCategoryRecipe }.
  238. { self -> #extensionCategoriesOfPackage: }, exportCategoryRecipe
  239. }
  240. ! !
  241. !ChunkExporter class methodsFor: 'private'!
  242. chunkEscape: aString
  243. "Replace all occurrences of !! with !!!! and trim at both ends."
  244. ^(aString replace: '!!' with: '!!!!') trimBoth
  245. !
  246. classNameFor: aClass
  247. ^aClass isMetaclass
  248. ifTrue: [aClass instanceClass name, ' class']
  249. ifFalse: [
  250. aClass isNil
  251. ifTrue: ['nil']
  252. ifFalse: [aClass name]]
  253. ! !
  254. AbstractExporter subclass: #Exporter
  255. instanceVariableNames: ''
  256. package: 'Importer-Exporter'!
  257. !Exporter commentStamp!
  258. I am responsible for outputting Amber code into a JavaScript string.
  259. The generated output is enough to reconstruct the exported data, including Smalltalk source code and other metadata.
  260. ## Use case
  261. I am typically used to save code outside of the Amber runtime (committing to disk, etc.).
  262. ## API
  263. Use `#exportAll`, `#exportClass:` or `#exportPackage:` methods.!
  264. !Exporter methodsFor: 'accessing'!
  265. extensionMethodsOfPackage: aPackage
  266. "Issue #143: sort classes and methods alphabetically"
  267. | name result |
  268. name := aPackage name.
  269. result := OrderedCollection new.
  270. (Package sortedClasses: Smalltalk current classes) do: [:each |
  271. {each. each class} do: [:aClass |
  272. result addAll: (((aClass methodDictionary values)
  273. sorted: [:a :b | a selector <= b selector])
  274. select: [:method | method category match: '^\*', name]) ]].
  275. ^result
  276. !
  277. ownMethodsOfClass: aClass
  278. "Issue #143: sort methods alphabetically"
  279. ^((aClass methodDictionary values) sorted: [:a :b | a selector <= b selector])
  280. reject: [:each | (each category match: '^\*')]
  281. !
  282. ownMethodsOfMetaClass: aClass
  283. "Issue #143: sort methods alphabetically"
  284. ^self ownMethodsOfClass: aClass class
  285. ! !
  286. !Exporter methodsFor: 'convenience'!
  287. classNameFor: aClass
  288. ^aClass isMetaclass
  289. ifTrue: [ aClass instanceClass name, '.klass' ]
  290. ifFalse: [
  291. aClass isNil
  292. ifTrue: [ 'nil' ]
  293. ifFalse: [ aClass name ] ]
  294. ! !
  295. !Exporter methodsFor: 'fileOut'!
  296. recipe
  297. "Export a given package."
  298. ^{
  299. self -> #exportPackagePrologueOf:on:.
  300. self -> #exportPackageDefinitionOf:on:.
  301. {
  302. PluggableExporter -> #ownClassesOfPackage:.
  303. self -> #exportDefinitionOf:on:.
  304. {
  305. self -> #ownMethodsOfClass:.
  306. self -> #exportMethod:on: }.
  307. self -> #exportMetaDefinitionOf:on:.
  308. {
  309. self -> #ownMethodsOfMetaClass:.
  310. self -> #exportMethod:on: } }.
  311. {
  312. self -> #extensionMethodsOfPackage:.
  313. self -> #exportMethod:on: }.
  314. self -> #exportPackageEpilogueOf:on:
  315. }
  316. ! !
  317. !Exporter methodsFor: 'output'!
  318. exportDefinitionOf: aClass on: aStream
  319. aStream
  320. lf;
  321. nextPutAll: 'smalltalk.addClass(';
  322. nextPutAll: '''', (self classNameFor: aClass), ''', ';
  323. nextPutAll: 'smalltalk.', (self classNameFor: aClass superclass);
  324. nextPutAll: ', ['.
  325. aClass instanceVariableNames
  326. do: [:each | aStream nextPutAll: '''', each, '''']
  327. separatedBy: [aStream nextPutAll: ', '].
  328. aStream
  329. nextPutAll: '], ''';
  330. nextPutAll: aClass category, '''';
  331. nextPutAll: ');'.
  332. aClass comment notEmpty ifTrue: [
  333. aStream
  334. lf;
  335. nextPutAll: 'smalltalk.';
  336. nextPutAll: (self classNameFor: aClass);
  337. nextPutAll: '.comment=';
  338. nextPutAll: aClass comment asJavascript;
  339. nextPutAll: ';'].
  340. aStream lf
  341. !
  342. exportMetaDefinitionOf: aClass on: aStream
  343. aStream lf.
  344. aClass class instanceVariableNames isEmpty ifFalse: [
  345. aStream
  346. nextPutAll: 'smalltalk.', (self classNameFor: aClass class);
  347. nextPutAll: '.iVarNames = ['.
  348. aClass class instanceVariableNames
  349. do: [:each | aStream nextPutAll: '''', each, '''']
  350. separatedBy: [aStream nextPutAll: ','].
  351. aStream nextPutAll: '];', String lf]
  352. !
  353. exportMethod: aMethod on: aStream
  354. aStream
  355. nextPutAll: 'smalltalk.addMethod(';lf;
  356. "nextPutAll: aMethod selector asSelector asJavascript, ',';lf;"
  357. nextPutAll: 'smalltalk.method({';lf;
  358. nextPutAll: 'selector: ', aMethod selector asJavascript, ',';lf;
  359. nextPutAll: 'category: ''', aMethod category, ''',';lf;
  360. nextPutAll: 'fn: ', aMethod fn compiledSource, ',';lf;
  361. nextPutAll: 'args: ', aMethod arguments asJavascript, ','; lf;
  362. nextPutAll: 'source: ', aMethod source asJavascript, ',';lf;
  363. nextPutAll: 'messageSends: ', aMethod messageSends asJavascript, ',';lf;
  364. nextPutAll: 'referencedClasses: ', aMethod referencedClasses asJavascript.
  365. aStream
  366. lf;
  367. nextPutAll: '}),';lf;
  368. nextPutAll: 'smalltalk.', (self classNameFor: aMethod methodClass);
  369. nextPutAll: ');';lf;lf
  370. !
  371. exportPackageDefinitionOf: aPackage on: aStream
  372. aStream
  373. nextPutAll: 'smalltalk.addPackage(';
  374. nextPutAll: '''', aPackage name, ''');';
  375. lf
  376. !
  377. exportPackageEpilogueOf: aPackage on: aStream
  378. aStream
  379. nextPutAll: '})(global_smalltalk,global_nil,global__st);';
  380. lf
  381. !
  382. exportPackagePrologueOf: aPackage on: aStream
  383. aStream
  384. nextPutAll: '(function(smalltalk,nil,_st){';
  385. lf
  386. ! !
  387. !Exporter class methodsFor: 'exporting-accessing'!
  388. extensionMethodsOfPackage: package
  389. "Issue #143: sort classes and methods alphabetically"
  390. | name result |
  391. name := package name.
  392. result := OrderedCollection new.
  393. (Package sortedClasses: Smalltalk current classes) do: [:each |
  394. {each. each class} do: [:aClass |
  395. result addAll: (((aClass methodDictionary values)
  396. sorted: [:a :b | a selector <= b selector])
  397. select: [:method | method category match: '^\*', name]) ]].
  398. ^result
  399. !
  400. ownMethodsOfClass: aClass
  401. "Issue #143: sort methods alphabetically"
  402. ^((aClass methodDictionary values) sorted: [:a :b | a selector <= b selector])
  403. reject: [:each | (each category match: '^\*')]
  404. !
  405. ownMethodsOfMetaClass: aClass
  406. "Issue #143: sort methods alphabetically"
  407. ^self ownMethodsOfClass: aClass class
  408. ! !
  409. !Exporter class methodsFor: 'exporting-output'!
  410. exportDefinitionOf: aClass on: aStream
  411. aStream
  412. lf;
  413. nextPutAll: 'smalltalk.addClass(';
  414. nextPutAll: '''', (self classNameFor: aClass), ''', ';
  415. nextPutAll: 'smalltalk.', (self classNameFor: aClass superclass);
  416. nextPutAll: ', ['.
  417. aClass instanceVariableNames
  418. do: [:each | aStream nextPutAll: '''', each, '''']
  419. separatedBy: [aStream nextPutAll: ', '].
  420. aStream
  421. nextPutAll: '], ''';
  422. nextPutAll: aClass category, '''';
  423. nextPutAll: ');'.
  424. aClass comment notEmpty ifTrue: [
  425. aStream
  426. lf;
  427. nextPutAll: 'smalltalk.';
  428. nextPutAll: (self classNameFor: aClass);
  429. nextPutAll: '.comment=';
  430. nextPutAll: aClass comment asJavascript;
  431. nextPutAll: ';'].
  432. aStream lf
  433. !
  434. exportMetaDefinitionOf: aClass on: aStream
  435. aStream lf.
  436. aClass class instanceVariableNames isEmpty ifFalse: [
  437. aStream
  438. nextPutAll: 'smalltalk.', (self classNameFor: aClass class);
  439. nextPutAll: '.iVarNames = ['.
  440. aClass class instanceVariableNames
  441. do: [:each | aStream nextPutAll: '''', each, '''']
  442. separatedBy: [aStream nextPutAll: ','].
  443. aStream nextPutAll: '];', String lf]
  444. !
  445. exportMethod: aMethod on: aStream
  446. aStream
  447. nextPutAll: 'smalltalk.addMethod(';lf;
  448. "nextPutAll: aMethod selector asSelector asJavascript, ',';lf;"
  449. nextPutAll: 'smalltalk.method({';lf;
  450. nextPutAll: 'selector: ', aMethod selector asJavascript, ',';lf;
  451. nextPutAll: 'category: ''', aMethod category, ''',';lf;
  452. nextPutAll: 'fn: ', aMethod fn compiledSource, ',';lf;
  453. nextPutAll: 'args: ', aMethod arguments asJavascript, ','; lf;
  454. nextPutAll: 'source: ', aMethod source asJavascript, ',';lf;
  455. nextPutAll: 'messageSends: ', aMethod messageSends asJavascript, ',';lf;
  456. nextPutAll: 'referencedClasses: ', aMethod referencedClasses asJavascript.
  457. aStream
  458. lf;
  459. nextPutAll: '}),';lf;
  460. nextPutAll: 'smalltalk.', (self classNameFor: aMethod methodClass);
  461. nextPutAll: ');';lf;lf
  462. !
  463. exportPackageDefinitionOf: package on: aStream
  464. aStream
  465. nextPutAll: 'smalltalk.addPackage(';
  466. nextPutAll: '''', package name, ''');';
  467. lf
  468. !
  469. exportPackageEpilogueOf: aPackage on: aStream
  470. aStream
  471. nextPutAll: '})(global_smalltalk,global_nil,global__st);';
  472. lf
  473. !
  474. exportPackagePrologueOf: aPackage on: aStream
  475. aStream
  476. nextPutAll: '(function(smalltalk,nil,_st){';
  477. lf
  478. ! !
  479. !Exporter class methodsFor: 'fileOut'!
  480. amdRecipe
  481. "Export a given package with amd transport type."
  482. | legacy |
  483. legacy := self recipe.
  484. ^(legacy copyFrom: 1 to: 2),
  485. { AmdExporter -> #exportPackageTransportOf:on: },
  486. (legacy copyFrom: 3 to: legacy size)
  487. !
  488. recipe
  489. "Export a given package."
  490. ^{
  491. AmdExporter -> #exportPackagePrologueOf:on:.
  492. self -> #exportPackageDefinitionOf:on:.
  493. {
  494. PluggableExporter -> #ownClassesOfPackage:.
  495. self -> #exportDefinitionOf:on:.
  496. {
  497. self -> #ownMethodsOfClass:.
  498. self -> #exportMethod:on: }.
  499. self -> #exportMetaDefinitionOf:on:.
  500. {
  501. self -> #ownMethodsOfMetaClass:.
  502. self -> #exportMethod:on: } }.
  503. {
  504. self -> #extensionMethodsOfPackage:.
  505. self -> #exportMethod:on: }.
  506. AmdExporter -> #exportPackageEpilogueOf:on:
  507. }
  508. ! !
  509. !Exporter class methodsFor: 'private'!
  510. classNameFor: aClass
  511. ^aClass isMetaclass
  512. ifTrue: [aClass instanceClass name, '.klass']
  513. ifFalse: [
  514. aClass isNil
  515. ifTrue: ['nil']
  516. ifFalse: [aClass name]]
  517. ! !
  518. Exporter subclass: #StrippedExporter
  519. instanceVariableNames: ''
  520. package: 'Importer-Exporter'!
  521. !StrippedExporter commentStamp!
  522. I export Amber code into a JavaScript string, but without any optional associated data like the Amber source code.!
  523. !StrippedExporter methodsFor: 'output'!
  524. exportDefinitionOf: aClass on: aStream
  525. aStream
  526. lf;
  527. nextPutAll: 'smalltalk.addClass(';
  528. nextPutAll: '''', (self classNameFor: aClass), ''', ';
  529. nextPutAll: 'smalltalk.', (self classNameFor: aClass superclass);
  530. nextPutAll: ', ['.
  531. aClass instanceVariableNames
  532. do: [:each | aStream nextPutAll: '''', each, '''']
  533. separatedBy: [aStream nextPutAll: ', '].
  534. aStream
  535. nextPutAll: '], ''';
  536. nextPutAll: aClass category, '''';
  537. nextPutAll: ');'.
  538. aStream lf
  539. !
  540. exportMethod: aMethod on: aStream
  541. aStream
  542. nextPutAll: 'smalltalk.addMethod(';lf;
  543. "nextPutAll: aMethod selector asSelector asJavascript, ',';lf;"
  544. nextPutAll: 'smalltalk.method({';lf;
  545. nextPutAll: 'selector: ', aMethod selector asJavascript, ',';lf;
  546. nextPutAll: 'fn: ', aMethod fn compiledSource, ',';lf;
  547. nextPutAll: 'messageSends: ', aMethod messageSends asJavascript;
  548. nextPutAll: '}),';lf;
  549. nextPutAll: 'smalltalk.', (self classNameFor: aMethod methodClass);
  550. nextPutAll: ');';lf;lf
  551. ! !
  552. !StrippedExporter class methodsFor: 'exporting-output'!
  553. exportDefinitionOf: aClass on: aStream
  554. aStream
  555. lf;
  556. nextPutAll: 'smalltalk.addClass(';
  557. nextPutAll: '''', (self classNameFor: aClass), ''', ';
  558. nextPutAll: 'smalltalk.', (self classNameFor: aClass superclass);
  559. nextPutAll: ', ['.
  560. aClass instanceVariableNames
  561. do: [:each | aStream nextPutAll: '''', each, '''']
  562. separatedBy: [aStream nextPutAll: ', '].
  563. aStream
  564. nextPutAll: '], ''';
  565. nextPutAll: aClass category, '''';
  566. nextPutAll: ');'.
  567. aStream lf
  568. !
  569. exportMethod: aMethod on: aStream
  570. aStream
  571. nextPutAll: 'smalltalk.addMethod(';lf;
  572. "nextPutAll: aMethod selector asSelector asJavascript, ',';lf;"
  573. nextPutAll: 'smalltalk.method({';lf;
  574. nextPutAll: 'selector: ', aMethod selector asJavascript, ',';lf;
  575. nextPutAll: 'fn: ', aMethod fn compiledSource, ',';lf;
  576. nextPutAll: 'messageSends: ', aMethod messageSends asJavascript;
  577. nextPutAll: '}),';lf;
  578. nextPutAll: 'smalltalk.', (self classNameFor: aMethod methodClass);
  579. nextPutAll: ');';lf;lf
  580. ! !
  581. Object subclass: #AmdExporter
  582. instanceVariableNames: ''
  583. package: 'Importer-Exporter'!
  584. !AmdExporter class methodsFor: 'exporting-output'!
  585. exportPackageEpilogueOf: aPackage on: aStream
  586. aStream
  587. nextPutAll: '});';
  588. lf
  589. !
  590. exportPackagePrologueOf: aPackage on: aStream
  591. aStream
  592. nextPutAll: 'define("';
  593. nextPutAll: (aPackage amdNamespace ifNil: [ 'amber' ]); "ifNil: only for LegacyPH, it should not happen with AmdPH"
  594. nextPutAll: '/';
  595. nextPutAll: aPackage name;
  596. nextPutAll: '", ';
  597. nextPutAll: (#('amber_vm/smalltalk' 'amber_vm/nil' 'amber_vm/_st'), (self amdNamesOfPackages: aPackage loadDependencies)) asJavascript;
  598. nextPutAll: ', function(smalltalk,nil,_st){';
  599. lf
  600. !
  601. exportPackageTransportOf: aPackage on: aStream
  602. aStream
  603. nextPutAll: 'smalltalk.packages[';
  604. nextPutAll: aPackage name asJavascript;
  605. nextPutAll: '].transport = ';
  606. nextPutAll: aPackage transportJson;
  607. nextPutAll: ';';
  608. lf
  609. ! !
  610. !AmdExporter class methodsFor: 'private'!
  611. amdNamesOfPackages: anArray
  612. | deps depNames |
  613. ^(anArray
  614. select: [ :each | each amdNamespace notNil ])
  615. collect: [ :each | each amdNamespace, '/', each name ]
  616. ! !
  617. Object subclass: #ChunkParser
  618. instanceVariableNames: 'stream'
  619. package: 'Importer-Exporter'!
  620. !ChunkParser commentStamp!
  621. I am responsible for parsing aStream contents in the chunk format.
  622. ## API
  623. ChunkParser new
  624. stream: aStream;
  625. nextChunk!
  626. !ChunkParser methodsFor: 'accessing'!
  627. stream: aStream
  628. stream := aStream
  629. ! !
  630. !ChunkParser methodsFor: 'reading'!
  631. nextChunk
  632. "The chunk format (Smalltalk Interchange Format or Fileout format)
  633. is a trivial format but can be a bit tricky to understand:
  634. - Uses the exclamation mark as delimiter of chunks.
  635. - Inside a chunk a normal exclamation mark must be doubled.
  636. - A non empty chunk must be a valid Smalltalk expression.
  637. - A chunk on top level with a preceding empty chunk is an instruction chunk:
  638. - The object created by the expression then takes over reading chunks.
  639. This metod returns next chunk as a String (trimmed), empty String (all whitespace) or nil."
  640. | char result chunk |
  641. result := '' writeStream.
  642. [char := stream next.
  643. char notNil] whileTrue: [
  644. char = '!!' ifTrue: [
  645. stream peek = '!!'
  646. ifTrue: [stream next "skipping the escape double"]
  647. ifFalse: [^result contents trimBoth "chunk end marker found"]].
  648. result nextPut: char].
  649. ^nil "a chunk needs to end with !!"
  650. ! !
  651. !ChunkParser class methodsFor: 'not yet classified'!
  652. on: aStream
  653. ^self new stream: aStream
  654. ! !
  655. Object subclass: #Importer
  656. instanceVariableNames: ''
  657. package: 'Importer-Exporter'!
  658. !Importer commentStamp!
  659. I can import Amber code from a string in the chunk format.
  660. ## API
  661. Importer new import: aString!
  662. !Importer methodsFor: 'fileIn'!
  663. import: aStream
  664. | chunk result parser lastEmpty |
  665. parser := ChunkParser on: aStream.
  666. lastEmpty := false.
  667. [chunk := parser nextChunk.
  668. chunk isNil] whileFalse: [
  669. chunk isEmpty
  670. ifTrue: [lastEmpty := true]
  671. ifFalse: [
  672. result := Compiler new evaluateExpression: chunk.
  673. lastEmpty
  674. ifTrue: [
  675. lastEmpty := false.
  676. result scanFrom: parser]]]
  677. ! !
  678. Object subclass: #MethodCategory
  679. instanceVariableNames: 'methods name theClass'
  680. package: 'Importer-Exporter'!
  681. !MethodCategory commentStamp!
  682. I am an abstraction for a method category in a class / metaclass.
  683. I know of my class, name and methods.
  684. I am used when exporting a package.!
  685. !MethodCategory methodsFor: 'accessing'!
  686. methods
  687. ^methods
  688. !
  689. methods: aCollection
  690. methods := aCollection
  691. !
  692. name
  693. ^name
  694. !
  695. name: aString
  696. name := aString
  697. !
  698. theClass
  699. ^theClass
  700. !
  701. theClass: aClass
  702. theClass := aClass
  703. ! !
  704. !MethodCategory class methodsFor: 'not yet classified'!
  705. name: aString theClass: aClass methods: anArray
  706. ^self new
  707. name: aString;
  708. theClass: aClass;
  709. methods: anArray;
  710. yourself
  711. ! !
  712. InterfacingObject subclass: #PackageHandler
  713. instanceVariableNames: ''
  714. package: 'Importer-Exporter'!
  715. !PackageHandler commentStamp!
  716. I am responsible for handling package loading and committing.
  717. I should not be used directly. Instead, use the corresponding `Package` methods.!
  718. !PackageHandler methodsFor: 'committing'!
  719. commit: aPackage
  720. self commitChannels
  721. do: [ :commitStrategyFactory || fileContents commitStrategy |
  722. commitStrategy := commitStrategyFactory value: aPackage.
  723. fileContents := String streamContents: [ :stream |
  724. (PluggableExporter forRecipe: commitStrategy key) exportPackage: aPackage on: stream ].
  725. self ajaxPutAt: commitStrategy value data: fileContents ]
  726. displayingProgress: 'Committing package ', aPackage name
  727. !
  728. commitChannels
  729. self subclassResponsibility
  730. ! !
  731. !PackageHandler methodsFor: 'private'!
  732. ajaxPutAt: aURL data: aString
  733. self
  734. ajax: #{
  735. 'url' -> aURL.
  736. 'type' -> 'PUT'.
  737. 'data' -> aString.
  738. 'contentType' -> 'text/plain;charset=UTF-8'.
  739. 'error' -> [ :xhr | self error: 'Commiting ' , aURL , ' failed with reason: "' , (xhr responseText) , '"'] }
  740. ! !
  741. PackageHandler class instanceVariableNames: 'registry'!
  742. !PackageHandler class methodsFor: 'accessing'!
  743. classRegisteredFor: aString
  744. ^registry at: aString
  745. !
  746. for: aString
  747. ^(self classRegisteredFor: aString) new
  748. ! !
  749. !PackageHandler class methodsFor: 'initialization'!
  750. initialize
  751. super initialize.
  752. registry := #{}
  753. ! !
  754. !PackageHandler class methodsFor: 'registry'!
  755. register: aClass for: aString
  756. registry at: aString put: aClass
  757. !
  758. registerFor: aString
  759. PackageHandler register: self for: aString
  760. ! !
  761. PackageHandler subclass: #AmdPackageHandler
  762. instanceVariableNames: ''
  763. package: 'Importer-Exporter'!
  764. !AmdPackageHandler commentStamp!
  765. I am responsible for handling package loading and committing.
  766. I should not be used directly. Instead, use the corresponding `Package` methods.!
  767. !AmdPackageHandler methodsFor: 'committing'!
  768. commitChannels
  769. ^{
  770. [ :pkg | Exporter amdRecipe -> (pkg commitPathJs, '/', pkg name, '.js') ].
  771. [ :pkg | StrippedExporter amdRecipe -> (pkg commitPathJs, '/', pkg name, '.deploy.js') ].
  772. [ :pkg | ChunkExporter recipe -> (pkg commitPathSt, '/', pkg name, '.st') ]
  773. }
  774. !
  775. commitPathJsFor: aPackage
  776. ^self toUrl: (self namespaceFor: aPackage)
  777. !
  778. commitPathStFor: aPackage
  779. "if _source is not mapped, .st commit will likely fail"
  780. ^self toUrl: (self namespaceFor: aPackage), '/_source'.
  781. !
  782. namespaceFor: aPackage
  783. ^aPackage amdNamespace
  784. ifNil: [ aPackage amdNamespace: self class defaultNamespace; amdNamespace ]
  785. ! !
  786. !AmdPackageHandler methodsFor: 'private'!
  787. toUrl: aString
  788. (Smalltalk current at: '_amd_require')
  789. ifNil: [ self error: 'AMD loader not present' ]
  790. ifNotNil: [ :require | ^(require basicAt: 'toUrl') value: aString ]
  791. ! !
  792. AmdPackageHandler class instanceVariableNames: 'defaultNamespace'!
  793. !AmdPackageHandler class methodsFor: 'commit paths'!
  794. commitPathsFromLoader
  795. "TODO"
  796. !
  797. defaultNamespace
  798. ^ defaultNamespace ifNil: [ self error: 'AMD default namespace not set.' ]
  799. !
  800. defaultNamespace: aString
  801. defaultNamespace := aString
  802. !
  803. resetCommitPaths
  804. defaultNamespace := nil
  805. ! !
  806. !AmdPackageHandler class methodsFor: 'initialization'!
  807. initialize
  808. super initialize.
  809. self registerFor: 'amd'.
  810. self commitPathsFromLoader
  811. ! !
  812. PackageHandler subclass: #LegacyPackageHandler
  813. instanceVariableNames: ''
  814. package: 'Importer-Exporter'!
  815. !LegacyPackageHandler commentStamp!
  816. I am responsible for handling package loading and committing.
  817. I should not be used directly. Instead, use the corresponding `Package` methods.!
  818. !LegacyPackageHandler methodsFor: 'committing'!
  819. commitChannels
  820. ^{
  821. [ :pkg | Exporter default recipe -> (pkg commitPathJs, '/', pkg name, '.js') ].
  822. [ :pkg | StrippedExporter default recipe -> (pkg commitPathJs, '/', pkg name, '.deploy.js') ].
  823. [ :pkg | ChunkExporter default recipe -> (pkg commitPathSt, '/', pkg name, '.st') ]
  824. }
  825. !
  826. commitPathJsFor: aPackage
  827. ^self class defaultCommitPathJs
  828. !
  829. commitPathStFor: aPackage
  830. ^self class defaultCommitPathSt
  831. ! !
  832. !LegacyPackageHandler methodsFor: 'loading'!
  833. loadPackage: packageName prefix: aString
  834. | url |
  835. url := '/', aString, '/js/', packageName, '.js'.
  836. self
  837. ajax: #{
  838. 'url' -> url.
  839. 'type' -> 'GET'.
  840. 'dataType' -> 'script'.
  841. 'complete' -> [ :jqXHR :textStatus |
  842. jqXHR readyState = 4
  843. ifTrue: [ self setupPackageNamed: packageName prefix: aString ] ].
  844. 'error' -> [ self alert: 'Could not load package at: ', url ]
  845. }
  846. !
  847. loadPackages: aCollection prefix: aString
  848. aCollection do: [ :each |
  849. self loadPackage: each prefix: aString ]
  850. ! !
  851. !LegacyPackageHandler methodsFor: 'private'!
  852. setupPackageNamed: packageName prefix: aString
  853. (Package named: packageName)
  854. setupClasses;
  855. commitPathJs: '/', aString, '/js';
  856. commitPathSt: '/', aString, '/st'
  857. ! !
  858. LegacyPackageHandler class instanceVariableNames: 'defaultCommitPathJs defaultCommitPathSt'!
  859. !LegacyPackageHandler class methodsFor: 'commit paths'!
  860. commitPathsFromLoader
  861. <
  862. var commitPath = typeof amber !!== 'undefined' && amber.commitPath;
  863. if (!!commitPath) return;
  864. if (commitPath.js) self._defaultCommitPathJs_(commitPath.js);
  865. if (commitPath.st) self._defaultCommitPathSt_(commitPath.st);
  866. >
  867. !
  868. defaultCommitPathJs
  869. ^ defaultCommitPathJs ifNil: [ defaultCommitPathJs := 'js']
  870. !
  871. defaultCommitPathJs: aString
  872. defaultCommitPathJs := aString
  873. !
  874. defaultCommitPathSt
  875. ^ defaultCommitPathSt ifNil: [ defaultCommitPathSt := 'st']
  876. !
  877. defaultCommitPathSt: aString
  878. defaultCommitPathSt := aString
  879. !
  880. resetCommitPaths
  881. defaultCommitPathJs := nil.
  882. defaultCommitPathSt := nil
  883. ! !
  884. !LegacyPackageHandler class methodsFor: 'initialization'!
  885. initialize
  886. super initialize.
  887. self registerFor: 'unknown'.
  888. self commitPathsFromLoader
  889. ! !
  890. !LegacyPackageHandler class methodsFor: 'loading'!
  891. loadPackages: aCollection prefix: aString
  892. ^ self new loadPackages: aCollection prefix: aString
  893. ! !
  894. Object subclass: #PluggableExporter
  895. instanceVariableNames: 'recipe'
  896. package: 'Importer-Exporter'!
  897. !PluggableExporter commentStamp!
  898. I am an engine for exporting structured data on a Stream.
  899. My instances are created using
  900. PluggableExporter newUsing: recipe,
  901. where recipe is structured description of the exporting algorithm.
  902. The actual exporting is done by interpreting the recipe using a `RecipeInterpreter`.
  903. I am used to export amber packages, so I have a convenience method
  904. `exportPackage: aPackage on: aStream`
  905. which exports `aPackage` using the `recipe`
  906. (it is otherwise no special, so it may be renamed to export:on:)!
  907. !PluggableExporter methodsFor: 'accessing'!
  908. interpreter
  909. ^ RecipeInterpreter new
  910. !
  911. recipe
  912. ^recipe
  913. !
  914. recipe: anArray
  915. recipe := anArray
  916. ! !
  917. !PluggableExporter methodsFor: 'fileOut'!
  918. exportAllPackages
  919. "Export all packages in the system."
  920. ^String streamContents: [:stream |
  921. Smalltalk current packages do: [:pkg |
  922. self exportPackage: pkg on: stream]]
  923. !
  924. exportPackage: aPackage on: aStream
  925. self interpreter interpret: self recipe for: aPackage on: aStream
  926. ! !
  927. !PluggableExporter class methodsFor: 'convenience'!
  928. ownClassesOfPackage: package
  929. "Export classes in dependency order.
  930. Update (issue #171): Remove duplicates for export"
  931. ^package sortedClasses asSet
  932. ! !
  933. !PluggableExporter class methodsFor: 'instance creation'!
  934. forRecipe: aRecipe
  935. ^self new recipe: aRecipe; yourself
  936. ! !
  937. Object subclass: #RecipeInterpreter
  938. instanceVariableNames: ''
  939. package: 'Importer-Exporter'!
  940. !RecipeInterpreter commentStamp!
  941. I am an interpreter for export recipes.
  942. ## Recipe format
  943. Recipe is an array, which can contain two kinds of elements:
  944. - an assocation where the key is the receiver and the value is a two-arguments selector
  945. In this case, `receiver perform: selector withArguments: { data. stream }` is called.
  946. This essentially defines one step of export process.
  947. The key (eg. receiver) is presumed to be some kind of 'repository' of the exporting methods
  948. that just format appropriate aspect of data into a stream; like a class or a singleton,
  949. so that the recipe itself can be decoupled from data.
  950. - a subarray, where first element is special and the rest is recursive recipe.
  951. `subarray first` must be an association similar to one above,
  952. with key being the 'repository' receiver, but value is one-arg selector.
  953. In this case, `receiver perform: selector withArguments: { data }` should create a collection.
  954. Then, the sub-recipe (`subarray allButFirst`) is applied to every element of a collection, eg.
  955. collection do: [ :each | self export: each using: sa allButFirst on: stream ]!
  956. !RecipeInterpreter methodsFor: 'accessing'!
  957. recipe
  958. ^recipe
  959. !
  960. recipe: anArray
  961. recipe := anArray
  962. ! !
  963. !RecipeInterpreter methodsFor: 'interpreting'!
  964. interpret: aRecipe for: anObject on: aStream
  965. | recipeStream |
  966. recipeStream := aRecipe readStream.
  967. [ recipeStream atEnd ] whileFalse: [
  968. self
  969. interpretStep: recipeStream next
  970. for: anObject
  971. on: aStream ]
  972. !
  973. interpretStep: aRecipeStep for: anObject on: aStream
  974. aRecipeStep value == aRecipeStep ifTrue: [
  975. ^ self interpretSubRecipe: aRecipeStep for: anObject on: aStream ].
  976. aRecipeStep key perform: aRecipeStep value withArguments: { anObject. aStream }
  977. !
  978. interpretSubRecipe: aRecipe for: anObject on: aStream
  979. | selection |
  980. selection := aRecipe first key
  981. perform: aRecipe first value
  982. withArguments: { anObject }.
  983. selection do: [ :each |
  984. self interpret: aRecipe allButFirst for: each on: aStream ]
  985. ! !
  986. !Package methodsFor: '*Importer-Exporter'!
  987. amdNamespace
  988. <return (self.transport && self.transport.amdNamespace) || nil>
  989. !
  990. amdNamespace: aString
  991. <
  992. if (!!self.transport) { self.transport = { type: 'amd' }; }
  993. if (self.transport.type !!== 'amd') { throw new Error('Package '+self._name()+' has transport type '+self.transport.type+', not "amd".'); }
  994. self.transport.amdNamespace = aString;
  995. >
  996. !
  997. commit
  998. ^ self transport commit: self
  999. !
  1000. commitPathJs
  1001. ^ (extension ifNil: [ extension := #{} ]) at: #commitPathJs ifAbsent: [self transport commitPathJsFor: self]
  1002. !
  1003. commitPathJs: aString
  1004. ^ (extension ifNil: [ extension := #{} ]) at: #commitPathJs put: aString
  1005. !
  1006. commitPathSt
  1007. ^ (extension ifNil: [ extension := #{} ]) at: #commitPathSt ifAbsent: [self transport commitPathStFor: self]
  1008. !
  1009. commitPathSt: aString
  1010. ^ (extension ifNil: [ extension := #{} ]) at: #commitPathSt put: aString
  1011. !
  1012. transport
  1013. ^ PackageHandler for: self transportType
  1014. !
  1015. transportJson
  1016. <return JSON.stringify(self.transport || null);>
  1017. !
  1018. transportType
  1019. <return (self.transport && self.transport.type) || 'unknown';>
  1020. ! !