Importer-Exporter.st 13 KB

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