Importer-Exporter.st 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. Smalltalk current createPackage: 'Importer-Exporter'!
  2. Object subclass: #ChunkExporter
  3. instanceVariableNames: ''
  4. package: 'Importer-Exporter'!
  5. !ChunkExporter commentStamp!
  6. I am an exporter dedicated to outputting Amber source code in the classic Smalltalk chunk format.
  7. I do not output any compiled code.!
  8. !ChunkExporter class methodsFor: 'exporting-accessing'!
  9. extensionCategoriesOfPackage: package
  10. "Issue #143: sort protocol alphabetically"
  11. | name map result |
  12. name := package name.
  13. result := OrderedCollection new.
  14. (Package sortedClasses: Smalltalk current classes) do: [:each |
  15. {each. each class} do: [:aClass |
  16. map := Dictionary new.
  17. aClass protocolsDo: [:category :methods |
  18. (category match: '^\*', name) ifTrue: [ map at: category put: methods ]].
  19. result addAll: ((map keys sorted: [:a :b | a <= b ]) collect: [:category |
  20. #{ 'methods'->(map at: category). 'name'->category. 'class'->aClass}]) ]].
  21. ^result
  22. !
  23. methodsOfCategory: category
  24. "Issue #143: sort methods alphabetically"
  25. ^(category at: #methods) sorted: [:a :b | a selector <= b selector]
  26. !
  27. ownCategoriesOfClass: aClass
  28. "Issue #143: sort protocol alphabetically"
  29. | map |
  30. map := Dictionary new.
  31. aClass protocolsDo: [:category :methods |
  32. (category match: '^\*') ifFalse: [ map at: category put: methods ]].
  33. ^(map keys sorted: [:a :b | a <= b ]) collect: [:category |
  34. #{
  35. 'methods'->(map at: category).
  36. 'name'->category.
  37. 'class'->aClass }]
  38. !
  39. ownCategoriesOfMetaClass: aClass
  40. "Issue #143: sort protocol alphabetically"
  41. ^self ownCategoriesOfClass: aClass class
  42. ! !
  43. !ChunkExporter class methodsFor: 'exporting-output'!
  44. exportCategoryEpilogueOf: category on: aStream
  45. aStream nextPutAll: ' !!'; lf; lf
  46. !
  47. exportCategoryPrologueOf: category on: aStream
  48. aStream
  49. nextPutAll: '!!', (self classNameFor: (category at: #class));
  50. nextPutAll: ' methodsFor: ''', (category at: #name), '''!!'
  51. !
  52. exportDefinitionOf: aClass on: aStream
  53. "Chunk format."
  54. aStream
  55. nextPutAll: (self classNameFor: aClass superclass);
  56. nextPutAll: ' subclass: #', (self classNameFor: aClass); lf;
  57. tab; nextPutAll: 'instanceVariableNames: '''.
  58. aClass instanceVariableNames
  59. do: [:each | aStream nextPutAll: each]
  60. separatedBy: [aStream nextPutAll: ' '].
  61. aStream
  62. nextPutAll: ''''; lf;
  63. tab; nextPutAll: 'package: ''', aClass category, '''!!'; lf.
  64. aClass comment notEmpty ifTrue: [
  65. aStream
  66. nextPutAll: '!!', (self classNameFor: aClass), ' commentStamp!!';lf;
  67. nextPutAll: (self chunkEscape: aClass comment), '!!';lf].
  68. aStream lf
  69. !
  70. exportMetaDefinitionOf: aClass on: aStream
  71. aClass class instanceVariableNames isEmpty ifFalse: [
  72. aStream
  73. nextPutAll: (self classNameFor: aClass class);
  74. nextPutAll: ' instanceVariableNames: '''.
  75. aClass class instanceVariableNames
  76. do: [:each | aStream nextPutAll: each]
  77. separatedBy: [aStream nextPutAll: ' '].
  78. aStream
  79. nextPutAll: '''!!'; lf; lf]
  80. !
  81. exportMethod: aMethod on: aStream
  82. aStream
  83. lf; lf; nextPutAll: (self chunkEscape: aMethod source); lf;
  84. nextPutAll: '!!'
  85. !
  86. exportPackageDefinitionOf: package on: aStream
  87. "Chunk format."
  88. aStream
  89. nextPutAll: 'Smalltalk current createPackage: ''', package name, '''!!';
  90. lf
  91. ! !
  92. !ChunkExporter class methodsFor: 'fileOut'!
  93. recipe
  94. "Export a given package."
  95. | exportCategoryRecipe |
  96. exportCategoryRecipe := {
  97. self -> #exportCategoryPrologueOf:on:.
  98. {
  99. self -> #methodsOfCategory:.
  100. self -> #exportMethod:on: }.
  101. self -> #exportCategoryEpilogueOf:on: }.
  102. ^{
  103. self -> #exportPackageDefinitionOf:on:.
  104. {
  105. PluggableExporter -> #ownClassesOfPackage:.
  106. self -> #exportDefinitionOf:on:.
  107. { self -> #ownCategoriesOfClass: }, exportCategoryRecipe.
  108. self -> #exportMetaDefinitionOf:on:.
  109. { self -> #ownCategoriesOfMetaClass: }, exportCategoryRecipe }.
  110. { self -> #extensionCategoriesOfPackage: }, exportCategoryRecipe
  111. }
  112. ! !
  113. !ChunkExporter class methodsFor: 'private'!
  114. chunkEscape: aString
  115. "Replace all occurrences of !! with !!!! and trim at both ends."
  116. ^(aString replace: '!!' with: '!!!!') trimBoth
  117. !
  118. classNameFor: aClass
  119. ^aClass isMetaclass
  120. ifTrue: [aClass instanceClass name, ' class']
  121. ifFalse: [
  122. aClass isNil
  123. ifTrue: ['nil']
  124. ifFalse: [aClass name]]
  125. ! !
  126. Object subclass: #ChunkParser
  127. instanceVariableNames: 'stream'
  128. package: 'Importer-Exporter'!
  129. !ChunkParser commentStamp!
  130. I am responsible for parsing aStream contents in the chunk format.
  131. ## API
  132. ChunkParser new
  133. stream: aStream;
  134. nextChunk!
  135. !ChunkParser methodsFor: 'accessing'!
  136. stream: aStream
  137. stream := aStream
  138. ! !
  139. !ChunkParser methodsFor: 'reading'!
  140. nextChunk
  141. "The chunk format (Smalltalk Interchange Format or Fileout format)
  142. is a trivial format but can be a bit tricky to understand:
  143. - Uses the exclamation mark as delimiter of chunks.
  144. - Inside a chunk a normal exclamation mark must be doubled.
  145. - A non empty chunk must be a valid Smalltalk expression.
  146. - A chunk on top level with a preceding empty chunk is an instruction chunk:
  147. - The object created by the expression then takes over reading chunks.
  148. This metod returns next chunk as a String (trimmed), empty String (all whitespace) or nil."
  149. | char result chunk |
  150. result := '' writeStream.
  151. [char := stream next.
  152. char notNil] whileTrue: [
  153. char = '!!' ifTrue: [
  154. stream peek = '!!'
  155. ifTrue: [stream next "skipping the escape double"]
  156. ifFalse: [^result contents trimBoth "chunk end marker found"]].
  157. result nextPut: char].
  158. ^nil "a chunk needs to end with !!"
  159. ! !
  160. !ChunkParser class methodsFor: 'not yet classified'!
  161. on: aStream
  162. ^self new stream: aStream
  163. ! !
  164. Object subclass: #Exporter
  165. instanceVariableNames: ''
  166. package: 'Importer-Exporter'!
  167. !Exporter commentStamp!
  168. I am responsible for outputting Amber code into a JavaScript string.
  169. The generated output is enough to reconstruct the exported data, including Smalltalk source code and other metadata.
  170. ## Use case
  171. I am typically used to save code outside of the Amber runtime (committing to disk, etc.).
  172. ## API
  173. Use `#exportAll`, `#exportClass:` or `#exportPackage:` methods.!
  174. !Exporter class methodsFor: 'exporting-accessing'!
  175. extensionMethodsOfPackage: package
  176. "Issue #143: sort classes and methods alphabetically"
  177. | name result |
  178. name := package name.
  179. result := OrderedCollection new.
  180. (Package sortedClasses: Smalltalk current classes) do: [:each |
  181. {each. each class} do: [:aClass |
  182. result addAll: (((aClass methodDictionary values)
  183. sorted: [:a :b | a selector <= b selector])
  184. select: [:method | method category match: '^\*', name]) ]].
  185. ^result
  186. !
  187. ownMethodsOfClass: aClass
  188. "Issue #143: sort methods alphabetically"
  189. ^((aClass methodDictionary values) sorted: [:a :b | a selector <= b selector])
  190. reject: [:each | (each category match: '^\*')]
  191. !
  192. ownMethodsOfMetaClass: aClass
  193. "Issue #143: sort methods alphabetically"
  194. ^self ownMethodsOfClass: aClass class
  195. ! !
  196. !Exporter class methodsFor: 'exporting-output'!
  197. exportDefinitionOf: aClass on: aStream
  198. aStream
  199. lf;
  200. nextPutAll: 'smalltalk.addClass(';
  201. nextPutAll: '''', (self classNameFor: aClass), ''', ';
  202. nextPutAll: 'smalltalk.', (self classNameFor: aClass superclass);
  203. nextPutAll: ', ['.
  204. aClass instanceVariableNames
  205. do: [:each | aStream nextPutAll: '''', each, '''']
  206. separatedBy: [aStream nextPutAll: ', '].
  207. aStream
  208. nextPutAll: '], ''';
  209. nextPutAll: aClass category, '''';
  210. nextPutAll: ');'.
  211. aClass comment notEmpty ifTrue: [
  212. aStream
  213. lf;
  214. nextPutAll: 'smalltalk.';
  215. nextPutAll: (self classNameFor: aClass);
  216. nextPutAll: '.comment=';
  217. nextPutAll: aClass comment asJavascript;
  218. nextPutAll: ';'].
  219. aStream lf
  220. !
  221. exportMetaDefinitionOf: aClass on: aStream
  222. aStream lf.
  223. aClass class instanceVariableNames isEmpty ifFalse: [
  224. aStream
  225. nextPutAll: 'smalltalk.', (self classNameFor: aClass class);
  226. nextPutAll: '.iVarNames = ['.
  227. aClass class instanceVariableNames
  228. do: [:each | aStream nextPutAll: '''', each, '''']
  229. separatedBy: [aStream nextPutAll: ','].
  230. aStream nextPutAll: '];', String lf]
  231. !
  232. exportMethod: aMethod on: aStream
  233. aStream
  234. nextPutAll: 'smalltalk.addMethod(';lf;
  235. "nextPutAll: aMethod selector asSelector asJavascript, ',';lf;"
  236. nextPutAll: 'smalltalk.method({';lf;
  237. nextPutAll: 'selector: ', aMethod selector asJavascript, ',';lf;
  238. nextPutAll: 'category: ''', aMethod category, ''',';lf;
  239. nextPutAll: 'fn: ', aMethod fn compiledSource, ',';lf;
  240. nextPutAll: 'args: ', aMethod arguments asJavascript, ','; lf;
  241. nextPutAll: 'source: ', aMethod source asJavascript, ',';lf;
  242. nextPutAll: 'messageSends: ', aMethod messageSends asJavascript, ',';lf;
  243. nextPutAll: 'referencedClasses: ', aMethod referencedClasses asJavascript.
  244. aStream
  245. lf;
  246. nextPutAll: '}),';lf;
  247. nextPutAll: 'smalltalk.', (self classNameFor: aMethod methodClass);
  248. nextPutAll: ');';lf;lf
  249. !
  250. exportPackageDefinitionOf: package on: aStream
  251. aStream
  252. nextPutAll: 'smalltalk.addPackage(';
  253. nextPutAll: '''', package name, ''');';
  254. lf
  255. !
  256. exportPackageEpilogueOf: aPackage on: aStream
  257. aStream
  258. nextPutAll: '})(global_smalltalk,global_nil,global__st);';
  259. lf
  260. !
  261. exportPackagePrologueOf: aPackage on: aStream
  262. aStream
  263. nextPutAll: '(function(smalltalk,nil,_st){';
  264. lf
  265. ! !
  266. !Exporter class methodsFor: 'fileOut'!
  267. recipe
  268. "Export a given package."
  269. ^{
  270. self -> #exportPackagePrologueOf:on:.
  271. self -> #exportPackageDefinitionOf:on:.
  272. {
  273. PluggableExporter -> #ownClassesOfPackage:.
  274. self -> #exportDefinitionOf:on:.
  275. {
  276. self -> #ownMethodsOfClass:.
  277. self -> #exportMethod:on: }.
  278. self -> #exportMetaDefinitionOf:on:.
  279. {
  280. self -> #ownMethodsOfMetaClass:.
  281. self -> #exportMethod:on: } }.
  282. {
  283. self -> #extensionMethodsOfPackage:.
  284. self -> #exportMethod:on: }.
  285. self -> #exportPackageEpilogueOf:on:
  286. }
  287. ! !
  288. !Exporter class methodsFor: 'private'!
  289. classNameFor: aClass
  290. ^aClass isMetaclass
  291. ifTrue: [aClass instanceClass name, '.klass']
  292. ifFalse: [
  293. aClass isNil
  294. ifTrue: ['nil']
  295. ifFalse: [aClass name]]
  296. ! !
  297. Exporter subclass: #StrippedExporter
  298. instanceVariableNames: ''
  299. package: 'Importer-Exporter'!
  300. !StrippedExporter commentStamp!
  301. I export Amber code into a JavaScript string, but without any optional associated data like the Amber source code.!
  302. !StrippedExporter class methodsFor: 'exporting-output'!
  303. exportDefinitionOf: aClass on: aStream
  304. aStream
  305. lf;
  306. nextPutAll: 'smalltalk.addClass(';
  307. nextPutAll: '''', (self classNameFor: aClass), ''', ';
  308. nextPutAll: 'smalltalk.', (self classNameFor: aClass superclass);
  309. nextPutAll: ', ['.
  310. aClass instanceVariableNames
  311. do: [:each | aStream nextPutAll: '''', each, '''']
  312. separatedBy: [aStream nextPutAll: ', '].
  313. aStream
  314. nextPutAll: '], ''';
  315. nextPutAll: aClass category, '''';
  316. nextPutAll: ');'.
  317. aStream lf
  318. !
  319. exportMethod: aMethod on: aStream
  320. aStream
  321. nextPutAll: 'smalltalk.addMethod(';lf;
  322. "nextPutAll: aMethod selector asSelector asJavascript, ',';lf;"
  323. nextPutAll: 'smalltalk.method({';lf;
  324. nextPutAll: 'selector: ', aMethod selector asJavascript, ',';lf;
  325. nextPutAll: 'fn: ', aMethod fn compiledSource, ',';lf;
  326. nextPutAll: 'messageSends: ', aMethod messageSends asJavascript;
  327. nextPutAll: '}),';lf;
  328. nextPutAll: 'smalltalk.', (self classNameFor: aMethod methodClass);
  329. nextPutAll: ');';lf;lf
  330. ! !
  331. Object subclass: #Importer
  332. instanceVariableNames: ''
  333. package: 'Importer-Exporter'!
  334. !Importer commentStamp!
  335. I can import Amber code from a string in the chunk format.
  336. ## API
  337. Importer new import: aString!
  338. !Importer methodsFor: 'fileIn'!
  339. import: aStream
  340. | chunk result parser lastEmpty |
  341. parser := ChunkParser on: aStream.
  342. lastEmpty := false.
  343. [chunk := parser nextChunk.
  344. chunk isNil] whileFalse: [
  345. chunk isEmpty
  346. ifTrue: [lastEmpty := true]
  347. ifFalse: [
  348. result := Compiler new evaluateExpression: chunk.
  349. lastEmpty
  350. ifTrue: [
  351. lastEmpty := false.
  352. result scanFrom: parser]]]
  353. ! !
  354. Object subclass: #PackageHandler
  355. instanceVariableNames: ''
  356. package: 'Importer-Exporter'!
  357. !PackageHandler commentStamp!
  358. I am responsible for handling package loading and committing.
  359. I should not be used directly. Instead, use the corresponding `Package` methods.!
  360. !PackageHandler methodsFor: 'committing'!
  361. commit: aPackage
  362. {
  363. Exporter -> (aPackage commitPathJs, '/', aPackage name, '.js').
  364. StrippedExporter -> (aPackage commitPathJs, '/', aPackage name, '.deploy.js').
  365. ChunkExporter -> (aPackage commitPathSt, '/', aPackage name, '.st')
  366. }
  367. do: [ :commitStrategy|| fileContents |
  368. fileContents := String streamContents: [ :stream |
  369. (PluggableExporter newUsing: commitStrategy key recipe) exportPackage: aPackage on: stream ].
  370. self ajaxPutAt: commitStrategy value data: fileContents ]
  371. displayingProgress: 'Committing package ', aPackage name
  372. ! !
  373. !PackageHandler methodsFor: 'loading'!
  374. loadPackage: packageName prefix: aString
  375. | url |
  376. url := '/', aString, '/js/', packageName, '.js'.
  377. jQuery
  378. ajax: url
  379. options: #{
  380. 'type' -> 'GET'.
  381. 'dataType' -> 'script'.
  382. 'complete' -> [ :jqXHR :textStatus |
  383. jqXHR readyState = 4
  384. ifTrue: [ self setupPackageNamed: packageName prefix: aString ] ].
  385. 'error' -> [ window alert: 'Could not load package at: ', url ]
  386. }
  387. !
  388. loadPackages: aCollection prefix: aString
  389. aCollection do: [ :each |
  390. self loadPackage: each prefix: aString ]
  391. ! !
  392. !PackageHandler methodsFor: 'private'!
  393. ajaxPutAt: aURL data: aString
  394. jQuery
  395. ajax: aURL
  396. options: #{
  397. 'type' -> 'PUT'.
  398. 'data' -> aString.
  399. 'contentType' -> 'text/plain;charset=UTF-8'.
  400. 'error' -> [ :xhr | self error: 'Commiting ' , aURL , ' failed with reason: "' , (xhr responseText) , '"'] }
  401. !
  402. setupPackageNamed: packageName prefix: aString
  403. (Package named: packageName)
  404. setupClasses;
  405. commitPathJs: '/', aString, '/js';
  406. commitPathSt: '/', aString, '/st'
  407. ! !
  408. !PackageHandler class methodsFor: 'loading'!
  409. loadPackages: aCollection prefix: aString
  410. ^ self new loadPackages: aCollection prefix: aString
  411. ! !
  412. Object subclass: #PluggableExporter
  413. instanceVariableNames: 'recipe'
  414. package: 'Importer-Exporter'!
  415. !PluggableExporter methodsFor: 'accessing'!
  416. recipe
  417. ^recipe
  418. !
  419. recipe: anArray
  420. recipe := anArray
  421. ! !
  422. !PluggableExporter methodsFor: 'fileOut'!
  423. export: anObject usingRecipe: anArray on: aStream
  424. | args |
  425. args := { anObject. aStream }.
  426. anArray do: [ :each | | val |
  427. val := each value.
  428. val == each
  429. ifFalse: [ "association"
  430. each key perform: val withArguments: args ]
  431. ifTrue: [ "sub-array"
  432. | selection |
  433. selection := each first key perform: each first value withArguments: { anObject }.
  434. selection do: [ :eachPart | self export: eachPart usingRecipe: each allButFirst on: aStream ]]]
  435. !
  436. exportAll
  437. "Export all packages in the system."
  438. ^String streamContents: [:stream |
  439. Smalltalk current packages do: [:pkg |
  440. self exportPackage: pkg on: stream]]
  441. !
  442. exportPackage: aPackage on: aStream
  443. self export: aPackage usingRecipe: self recipe on: aStream
  444. ! !
  445. !PluggableExporter class methodsFor: 'exporting-accessing'!
  446. newUsing: recipe
  447. ^self new recipe: recipe; yourself
  448. !
  449. ownClassesOfPackage: package
  450. "Export classes in dependency order.
  451. Update (issue #171): Remove duplicates for export"
  452. ^package sortedClasses asSet
  453. ! !
  454. !Package methodsFor: '*Importer-Exporter'!
  455. commit
  456. ^ PackageHandler new commit: self
  457. ! !