Importer-Exporter.st 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. package := Smalltalk current packageAt: packageName.
  68. self exportPackagePrologueOf: package on: stream.
  69. [
  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 exportPackageEpilogueOf: package on: 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. exportPackageEpilogueOf: aPackage on: 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. exportPackagePrologueOf: aPackage on: 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. exportCategory: category on: aStream
  193. "Issue #143: sort methods alphabetically"
  194. aStream
  195. nextPutAll: '!!', (self classNameFor: (category at: #class));
  196. nextPutAll: ' methodsFor: ''', (category at: #name), '''!!'.
  197. ((category at: #methods) sorted: [:a :b | a selector <= b selector]) do: [:each |
  198. self exportMethod: each on: aStream].
  199. aStream nextPutAll: ' !!'; lf; lf
  200. !
  201. exportDefinitionOf: aClass on: aStream
  202. "Chunk format."
  203. aStream
  204. nextPutAll: (self classNameFor: aClass superclass);
  205. nextPutAll: ' subclass: #', (self classNameFor: aClass); lf;
  206. tab; nextPutAll: 'instanceVariableNames: '''.
  207. aClass instanceVariableNames
  208. do: [:each | aStream nextPutAll: each]
  209. separatedBy: [aStream nextPutAll: ' '].
  210. aStream
  211. nextPutAll: ''''; lf;
  212. tab; nextPutAll: 'package: ''', aClass category, '''!!'; lf.
  213. aClass comment notEmpty ifTrue: [
  214. aStream
  215. nextPutAll: '!!', (self classNameFor: aClass), ' commentStamp!!';lf;
  216. nextPutAll: (self chunkEscape: aClass comment), '!!';lf].
  217. aStream lf
  218. !
  219. exportMetaDefinitionOf: aClass on: aStream
  220. aClass class instanceVariableNames isEmpty ifFalse: [
  221. aStream
  222. nextPutAll: (self classNameFor: aClass class);
  223. nextPutAll: ' instanceVariableNames: '''.
  224. aClass class instanceVariableNames
  225. do: [:each | aStream nextPutAll: each]
  226. separatedBy: [aStream nextPutAll: ' '].
  227. aStream
  228. nextPutAll: '''!!'; lf; lf]
  229. !
  230. exportMethod: aMethod on: aStream
  231. aStream
  232. lf; lf; nextPutAll: (self chunkEscape: aMethod source); lf;
  233. nextPutAll: '!!'
  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. exportCategory: #{
  245. 'methods'->methods.
  246. 'name'->category.
  247. 'class'->aClass }
  248. on: aStream ]
  249. !
  250. exportPackageDefinitionOf: package on: aStream
  251. "Chunk format."
  252. aStream
  253. nextPutAll: 'Smalltalk current createPackage: ''', package name, '''!!';
  254. lf
  255. !
  256. exportPackageEpilogueOf: aPackage on: aStream.
  257. !
  258. exportPackageExtensionsOf: package on: aStream
  259. "We need to override this one too since we need to group
  260. all methods in a given protocol under a leading methodsFor: chunk
  261. for that class."
  262. "Issue #143: sort protocol alphabetically"
  263. | name map |
  264. name := package name.
  265. (Package sortedClasses: Smalltalk current classes) do: [:each |
  266. {each. each class} do: [:aClass |
  267. map := Dictionary new.
  268. aClass protocolsDo: [:category :methods |
  269. (category match: '^\*', name) ifTrue: [ map at: category put: methods ]].
  270. (map keys sorted: [:a :b | a <= b ]) do: [:category | | methods |
  271. methods := map at: category.
  272. self exportCategory: #{ 'methods'->methods. 'name'->category. 'class'->aClass} on: aStream ]]]
  273. !
  274. exportPackagePrologueOf: aPackage on: aStream.
  275. ! !
  276. Exporter subclass: #StrippedExporter
  277. instanceVariableNames: ''
  278. package: 'Importer-Exporter'!
  279. !StrippedExporter commentStamp!
  280. I export Amber code into a JavaScript string, but without any optional associated data like the Amber source code.!
  281. !StrippedExporter methodsFor: 'private'!
  282. exportDefinitionOf: aClass on: aStream
  283. aStream
  284. nextPutAll: 'smalltalk.addClass(';
  285. nextPutAll: '''', (self classNameFor: aClass), ''', ';
  286. nextPutAll: 'smalltalk.', (self classNameFor: aClass superclass);
  287. nextPutAll: ', ['.
  288. aClass instanceVariableNames
  289. do: [:each | aStream nextPutAll: '''', each, '''']
  290. separatedBy: [aStream nextPutAll: ', '].
  291. aStream
  292. nextPutAll: '], ''';
  293. nextPutAll: aClass category, '''';
  294. nextPutAll: ');'.
  295. aStream lf
  296. !
  297. exportMethod: aMethod on: aStream
  298. aStream
  299. nextPutAll: 'smalltalk.addMethod(';lf;
  300. "nextPutAll: aMethod selector asSelector asJavascript, ',';lf;"
  301. nextPutAll: 'smalltalk.method({';lf;
  302. nextPutAll: 'selector: ', aMethod selector asJavascript, ',';lf;
  303. nextPutAll: 'fn: ', aMethod fn compiledSource, ',';lf;
  304. nextPutAll: 'messageSends: ', aMethod messageSends asJavascript;
  305. nextPutAll: '}),';lf;
  306. nextPutAll: 'smalltalk.', (self classNameFor: aMethod methodClass);
  307. nextPutAll: ');';lf;lf
  308. ! !
  309. Object subclass: #Importer
  310. instanceVariableNames: ''
  311. package: 'Importer-Exporter'!
  312. !Importer commentStamp!
  313. I can import Amber code from a string in the chunk format.
  314. ## API
  315. Importer new import: aString!
  316. !Importer methodsFor: 'fileIn'!
  317. import: aStream
  318. | chunk result parser lastEmpty |
  319. parser := ChunkParser on: aStream.
  320. lastEmpty := false.
  321. [chunk := parser nextChunk.
  322. chunk isNil] whileFalse: [
  323. chunk isEmpty
  324. ifTrue: [lastEmpty := true]
  325. ifFalse: [
  326. result := Compiler new evaluateExpression: chunk.
  327. lastEmpty
  328. ifTrue: [
  329. lastEmpty := false.
  330. result scanFrom: parser]]]
  331. ! !
  332. Object subclass: #PackageHandler
  333. instanceVariableNames: ''
  334. package: 'Importer-Exporter'!
  335. !PackageHandler commentStamp!
  336. I am responsible for handling package loading and committing.
  337. I should not be used directly. Instead, use the corresponding `Package` methods.!
  338. !PackageHandler methodsFor: 'committing'!
  339. commit: aPackage
  340. {
  341. Exporter -> (aPackage commitPathJs, '/', aPackage name, '.js').
  342. StrippedExporter -> (aPackage commitPathJs, '/', aPackage name, '.deploy.js').
  343. ChunkExporter -> (aPackage commitPathSt, '/', aPackage name, '.st')
  344. }
  345. do: [ :commitStrategy|| fileContents |
  346. fileContents := String streamContents: [ :stream |
  347. commitStrategy key new exportPackage: aPackage name on: stream ].
  348. self ajaxPutAt: commitStrategy value data: fileContents ]
  349. displayingProgress: 'Committing package ', aPackage name
  350. ! !
  351. !PackageHandler methodsFor: 'loading'!
  352. loadPackage: packageName prefix: aString
  353. | url |
  354. url := '/', aString, '/js/', packageName, '.js'.
  355. jQuery
  356. ajax: url
  357. options: #{
  358. 'type' -> 'GET'.
  359. 'dataType' -> 'script'.
  360. 'complete' -> [ :jqXHR :textStatus |
  361. jqXHR readyState = 4
  362. ifTrue: [ self setupPackageNamed: packageName prefix: aString ] ].
  363. 'error' -> [ window alert: 'Could not load package at: ', url ]
  364. }
  365. !
  366. loadPackages: aCollection prefix: aString
  367. aCollection do: [ :each |
  368. self loadPackage: each prefix: aString ]
  369. ! !
  370. !PackageHandler methodsFor: 'private'!
  371. ajaxPutAt: aURL data: aString
  372. jQuery
  373. ajax: aURL
  374. options: #{
  375. 'type' -> 'PUT'.
  376. 'data' -> aString.
  377. 'contentType' -> 'text/plain;charset=UTF-8'.
  378. 'error' -> [ :xhr | self error: 'Commiting ' , aURL , ' failed with reason: "' , (xhr responseText) , '"'] }
  379. !
  380. setupPackageNamed: packageName prefix: aString
  381. (Package named: packageName)
  382. setupClasses;
  383. commitPathJs: '/', aString, '/js';
  384. commitPathSt: '/', aString, '/st'
  385. ! !
  386. !PackageHandler class methodsFor: 'loading'!
  387. loadPackages: aCollection prefix: aString
  388. ^ self new loadPackages: aCollection prefix: aString
  389. ! !
  390. !Package methodsFor: '*Importer-Exporter'!
  391. commit
  392. ^ PackageHandler new commit: self
  393. ! !