Platform-ImportExport.st 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. Smalltalk createPackage: 'Platform-ImportExport'!
  2. Object subclass: #AbstractExporter
  3. instanceVariableNames: ''
  4. package: 'Platform-ImportExport'!
  5. !AbstractExporter commentStamp!
  6. I am an abstract exporter for Amber source code.
  7. ## API
  8. Use `#exportPackage:on:` to export a given package on a Stream.!
  9. !AbstractExporter methodsFor: 'accessing'!
  10. extensionMethodsOfPackage: aPackage
  11. | result |
  12. result := OrderedCollection new.
  13. (self extensionProtocolsOfPackage: aPackage) do: [ :each |
  14. result addAll: each ownMethods ].
  15. ^ result
  16. !
  17. extensionProtocolsOfPackage: aPackage
  18. | extensionName result |
  19. extensionName := '*', aPackage name.
  20. result := OrderedCollection new.
  21. "The classes must be loaded since it is extensions only.
  22. Therefore topological sorting (dependency resolution) does not matter here.
  23. Not sorting topologically improves the speed by a number of magnitude.
  24. Not to shuffle diffs, classes are sorted by their name."
  25. (Smalltalk classes asArray sorted: [ :a :b | a name < b name ]) do: [ :each |
  26. ({each. each theMetaClass} copyWithout: nil) do: [ :behavior |
  27. (behavior protocols includes: extensionName) ifTrue: [
  28. result add: (ExportMethodProtocol name: extensionName theClass: behavior) ] ] ].
  29. ^ result
  30. ! !
  31. !AbstractExporter methodsFor: 'output'!
  32. exportPackage: aPackage on: aStream
  33. self subclassResponsibility
  34. ! !
  35. AbstractExporter subclass: #ChunkExporter
  36. instanceVariableNames: ''
  37. package: 'Platform-ImportExport'!
  38. !ChunkExporter commentStamp!
  39. I am an exporter dedicated to outputting Amber source code in the classic Smalltalk chunk format.
  40. I do not output any compiled code.!
  41. !ChunkExporter methodsFor: 'accessing'!
  42. extensionCategoriesOfPackage: aPackage
  43. "Issue #143: sort protocol alphabetically"
  44. | name map result |
  45. name := aPackage name.
  46. result := OrderedCollection new.
  47. (Package sortedClasses: Smalltalk classes) do: [ :each |
  48. {each. each theMetaClass} do: [ :aClass |
  49. map := Dictionary new.
  50. aClass protocolsDo: [ :category :methods |
  51. category = ('*', name) ifTrue: [ map at: category put: methods ] ].
  52. result addAll: ((map keys sorted: [ :a :b | a <= b ]) collect: [ :category |
  53. MethodCategory name: category theClass: aClass methods: (map at: category) ]) ] ].
  54. ^ result
  55. !
  56. ownCategoriesOfClass: aClass
  57. "Answer the protocols of aClass that are not package extensions"
  58. "Issue #143: sort protocol alphabetically"
  59. | map |
  60. map := Dictionary new.
  61. aClass protocolsDo: [ :each :methods |
  62. (each match: '^\*') ifFalse: [ map at: each put: methods ] ].
  63. ^ (map keys sorted: [ :a :b | a <= b ]) collect: [ :each |
  64. MethodCategory name: each theClass: aClass methods: (map at: each) ]
  65. !
  66. ownCategoriesOfMetaClass: aClass
  67. "Issue #143: sort protocol alphabetically"
  68. ^ self ownCategoriesOfClass: aClass theMetaClass
  69. !
  70. ownMethodProtocolsOfClass: aClass
  71. "Answer a collection of ExportMethodProtocol object of aClass that are not package extensions"
  72. ^ aClass ownProtocols collect: [ :each |
  73. ExportMethodProtocol name: each theClass: aClass ]
  74. ! !
  75. !ChunkExporter methodsFor: 'convenience'!
  76. chunkEscape: aString
  77. "Replace all occurrences of !! with !!!! and trim at both ends."
  78. ^ (aString replace: '!!' with: '!!!!') trimBoth
  79. ! !
  80. !ChunkExporter methodsFor: 'output'!
  81. exportBehavior: aBehavior on: aStream
  82. aBehavior exportBehaviorDefinitionTo: aStream using: self.
  83. self
  84. exportProtocols: (self ownMethodProtocolsOfClass: aBehavior)
  85. on: aStream
  86. !
  87. exportCategoryEpilogueOf: aCategory on: aStream
  88. aStream write: ' !!'; lf; lf
  89. !
  90. exportCategoryPrologueOf: aCategory on: aStream
  91. aStream
  92. write: '!!';
  93. print: aCategory theClass;
  94. write: ' methodsFor: ';
  95. print: aCategory;
  96. write: '!!'
  97. !
  98. exportDefinitionOf: aClass on: aStream
  99. "Chunk format."
  100. aStream
  101. print: aClass superclass;
  102. write: ' subclass: ';
  103. printSymbol: aClass name;
  104. lf.
  105. "aClass traitComposition
  106. ifNotEmpty: [ aStream tab; write: {'uses: '. aClass traitCompositionDefinition}; lf ]."
  107. aStream
  108. tab;
  109. write: 'instanceVariableNames: ';
  110. print: (' ' join: aClass instanceVariableNames);
  111. lf;
  112. tab;
  113. write: 'package: ';
  114. print: aClass category;
  115. write: '!!';
  116. lf.
  117. aClass comment ifNotEmpty: [ aStream
  118. write: '!!'; print: aClass; write: ' commentStamp!!'; lf;
  119. write: { self chunkEscape: aClass comment. '!!' }; lf ].
  120. aStream lf
  121. !
  122. exportMetaDefinitionOf: aClass on: aStream
  123. | classIvars classTraitComposition |
  124. classIvars := aClass class instanceVariableNames.
  125. classTraitComposition := aClass class traitComposition.
  126. (classIvars notEmpty "or: [classTraitComposition notEmpty]") ifTrue: [
  127. aStream
  128. print: aClass theMetaClass.
  129. aStream space. "classTraitComposition
  130. ifEmpty: [ aStream space ]
  131. ifNotEmpty: [ aStream lf; tab; write: {'uses: '. aClass class traitCompositionDefinition}; lf; tab ]."
  132. aStream
  133. write: 'instanceVariableNames: ';
  134. print: (' ' join: classIvars);
  135. write: '!!'; lf; lf ]
  136. !
  137. exportMethod: aMethod on: aStream
  138. aStream
  139. lf; lf; write: (self chunkEscape: aMethod source); lf;
  140. write: '!!'
  141. !
  142. exportPackage: aPackage on: aStream
  143. self
  144. exportPackageDefinitionOf: aPackage on: aStream;
  145. exportPackageImportsOf: aPackage on: aStream.
  146. aPackage sortedClasses do: [ :each |
  147. self exportBehavior: each on: aStream.
  148. each theMetaClass ifNotNil: [ :meta | self exportBehavior: meta on: aStream ] ].
  149. self exportPackageTraitCompositionsOf: aPackage on: aStream.
  150. self
  151. exportProtocols: (self extensionProtocolsOfPackage: aPackage)
  152. on: aStream
  153. !
  154. exportPackageDefinitionOf: aPackage on: aStream
  155. aStream
  156. write: 'Smalltalk createPackage: ';
  157. print: aPackage name;
  158. write: '!!';
  159. lf
  160. !
  161. exportPackageImportsOf: aPackage on: aStream
  162. aPackage imports ifNotEmpty: [ :imports | aStream
  163. write: '(Smalltalk packageAt: ';
  164. print: aPackage name;
  165. write: ' ifAbsent: [ self error: ';
  166. print: 'Package not created: ', aPackage name;
  167. write: { ' ]) imports: '. self chunkEscape: aPackage importsDefinition. '!!' };
  168. lf ]
  169. !
  170. exportPackageTraitCompositionsOf: aPackage on: aStream
  171. aPackage traitCompositions ifNotEmpty: [ :traitCompositions |
  172. traitCompositions keysAndValuesDo: [ :key :value | self exportTraitComposition: value of: key on: aStream ].
  173. aStream write: '!! !!'; lf; lf ]
  174. !
  175. exportProtocol: aProtocol on: aStream
  176. aProtocol ownMethods ifNotEmpty: [ :methods |
  177. self exportProtocolPrologueOf: aProtocol on: aStream.
  178. methods do: [ :method |
  179. self exportMethod: method on: aStream ].
  180. self exportProtocolEpilogueOf: aProtocol on: aStream ]
  181. !
  182. exportProtocolEpilogueOf: aProtocol on: aStream
  183. aStream write: ' !!'; lf; lf
  184. !
  185. exportProtocolPrologueOf: aProtocol on: aStream
  186. aStream
  187. write: '!!';
  188. print: aProtocol theClass;
  189. write: ' methodsFor: ';
  190. print: aProtocol name;
  191. write: '!!'
  192. !
  193. exportProtocols: aCollection on: aStream
  194. aCollection do: [ :each |
  195. self exportProtocol: each on: aStream ]
  196. !
  197. exportTraitComposition: aTraitComposition of: aBehavior on: aStream
  198. aStream
  199. print: aBehavior;
  200. write: ' setTraitComposition: ';
  201. write: aBehavior traitCompositionDefinition;
  202. write: ' asTraitComposition!!';
  203. lf
  204. !
  205. exportTraitDefinitionOf: aClass on: aStream
  206. "Chunk format."
  207. aStream
  208. write: 'Trait named: '; printSymbol: aClass name; lf.
  209. "aClass traitComposition
  210. ifNotEmpty: [ aStream tab; write: {'uses: '. aClass traitCompositionDefinition}; lf ]."
  211. aStream
  212. tab; write: 'package: '; print: aClass category; write: '!!'; lf.
  213. aClass comment ifNotEmpty: [
  214. aStream
  215. write: '!!'; print: aClass; write: ' commentStamp!!'; lf;
  216. write: { self chunkEscape: aClass comment. '!!' }; lf ].
  217. aStream lf
  218. ! !
  219. AbstractExporter subclass: #Exporter
  220. instanceVariableNames: ''
  221. package: 'Platform-ImportExport'!
  222. !Exporter commentStamp!
  223. I am responsible for outputting Amber code into a JavaScript string.
  224. The generated output is enough to reconstruct the exported data, including Smalltalk source code and other metadata.
  225. ## Use case
  226. I am typically used to save code outside of the Amber runtime (committing to disk, etc.).!
  227. !Exporter methodsFor: 'accessing'!
  228. ownMethodsOfClass: aClass
  229. "Issue #143: sort methods alphabetically"
  230. ^ ((aClass methodDictionary values) sorted: [ :a :b | a selector <= b selector ])
  231. reject: [ :each | (each protocol match: '^\*') ]
  232. !
  233. ownMethodsOfMetaClass: aClass
  234. "Issue #143: sort methods alphabetically"
  235. ^ self ownMethodsOfClass: aClass theMetaClass
  236. ! !
  237. !Exporter methodsFor: 'output'!
  238. exportBehavior: aBehavior on: aStream
  239. aBehavior exportBehaviorDefinitionTo: aStream using: self.
  240. aBehavior ownMethods do: [ :method |
  241. self exportMethod: method on: aStream ]
  242. !
  243. exportDefinitionOf: aClass on: aStream
  244. aStream
  245. lf;
  246. write: {
  247. '$core.addClass('.
  248. aClass name asJavaScriptSource. ', '.
  249. aClass superclass ifNil: [ 'null' ] ifNotNil: [ :superclass | superclass asJavaScriptSource ]. ', '.
  250. aClass instanceVariableNames asJavaScriptSource. ', '.
  251. aClass category asJavaScriptSource.
  252. ');' }.
  253. aClass comment ifNotEmpty: [
  254. aStream
  255. lf;
  256. write: '//>>excludeStart("ide", pragmas.excludeIdeData);'; lf;
  257. write: { aClass asJavaScriptSource. '.comment='. aClass comment crlfSanitized asJavaScriptSource. ';' }; lf;
  258. write: '//>>excludeEnd("ide");' ].
  259. aStream lf
  260. !
  261. exportMetaDefinitionOf: aClass on: aStream
  262. aStream lf.
  263. aClass theMetaClass instanceVariableNames ifNotEmpty: [ :classIvars | aStream
  264. write: { aClass theMetaClass asJavaScriptSource. '.iVarNames = '. classIvars asJavaScriptSource. ';' };
  265. lf ]
  266. !
  267. exportMethod: aMethod on: aStream
  268. aStream
  269. write: '$core.addMethod('; lf;
  270. write: '$core.method({'; lf;
  271. write: { 'selector: '. aMethod selector asJavaScriptSource. ',' }; lf;
  272. write: { 'protocol: '. aMethod protocol asJavaScriptSource. ',' }; lf;
  273. write: { 'fn: '. aMethod fn compiledSource. ',' }; lf;
  274. write: '//>>excludeStart("ide", pragmas.excludeIdeData);'; lf;
  275. write: { 'args: '. aMethod arguments asJavaScriptSource. ',' }; lf;
  276. write: { 'source: '. aMethod source asJavaScriptSource. ',' }; lf;
  277. write: { 'referencedClasses: '. aMethod referencedClasses asJavaScriptSource. ',' }; lf;
  278. write: '//>>excludeEnd("ide");'; lf;
  279. write: { 'messageSends: '. aMethod messageSends asJavaScriptSource }; lf;
  280. write: '}),'; lf;
  281. write: { aMethod methodClass asJavaScriptSource. ');' }; lf; lf
  282. !
  283. exportPackage: aPackage on: aStream
  284. self
  285. exportPackagePrologueOf: aPackage on: aStream;
  286. exportPackageDefinitionOf: aPackage on: aStream;
  287. exportPackageContextOf: aPackage on: aStream;
  288. exportPackageImportsOf: aPackage on: aStream;
  289. exportPackageTransportOf: aPackage on: aStream.
  290. aPackage sortedClasses do: [ :each |
  291. self exportBehavior: each on: aStream.
  292. each theMetaClass ifNotNil: [ :meta | self exportBehavior: meta on: aStream ] ].
  293. self exportPackageTraitCompositionsOf: aPackage on: aStream.
  294. (self extensionMethodsOfPackage: aPackage) do: [ :each |
  295. self exportMethod: each on: aStream ].
  296. self exportPackageEpilogueOf: aPackage on: aStream
  297. !
  298. exportPackageBodyBlockPrologueOf: aPackage on: aStream
  299. aStream
  300. write: 'if(!!("nilAsValue" in $boot))$boot.nilAsValue=$boot.nilAsReceiver;'; lf;
  301. write: 'var $core=$boot.api,nil=$boot.nilAsValue,$nil=$boot.nilAsReceiver,$recv=$boot.asReceiver,$globals=$boot.globals;'; lf
  302. !
  303. exportPackageContextOf: aPackage on: aStream
  304. aStream
  305. write: {
  306. '($core.packageDescriptors||$core.packages)['.
  307. aPackage name asJavaScriptSource.
  308. '].innerEval = '.
  309. 'function (expr) { return eval(expr); }'.
  310. ';' };
  311. lf
  312. !
  313. exportPackageDefinitionOf: aPackage on: aStream
  314. aStream
  315. write: { '$core.addPackage('. aPackage name asJavaScriptSource. ');' };
  316. lf
  317. !
  318. exportPackageEpilogueOf: aPackage on: aStream
  319. self subclassResponsibility
  320. !
  321. exportPackageImportsOf: aPackage on: aStream
  322. aPackage importsAsJson ifNotEmpty: [ :imports |
  323. aStream
  324. write: {
  325. '($core.packageDescriptors||$core.packages)['.
  326. aPackage name asJavaScriptSource.
  327. '].imports = '.
  328. imports asJavaScriptSource.
  329. ';' };
  330. lf ]
  331. !
  332. exportPackagePrologueOf: aPackage on: aStream
  333. self subclassResponsibility
  334. !
  335. exportPackageTraitCompositionsOf: aPackage on: aStream
  336. aPackage traitCompositions ifNotEmpty: [ :traitCompositions |
  337. traitCompositions keysAndValuesDo: [ :key :value | self exportTraitComposition: value of: key on: aStream ].
  338. aStream lf ]
  339. !
  340. exportPackageTransportOf: aPackage on: aStream
  341. aStream
  342. write: {
  343. '($core.packageDescriptors||$core.packages)['.
  344. aPackage name asJavaScriptSource.
  345. '].transport = '.
  346. aPackage transport asJSONString.
  347. ';' };
  348. lf
  349. !
  350. exportTraitComposition: aTraitComposition of: aBehavior on: aStream
  351. aStream write: {
  352. '$core.setTraitComposition('.
  353. aTraitComposition asJavaScriptSource.
  354. ', '.
  355. aBehavior asJavaScriptSource.
  356. ');' };
  357. lf
  358. !
  359. exportTraitDefinitionOf: aClass on: aStream
  360. aStream
  361. lf;
  362. write: {
  363. '$core.addTrait('.
  364. aClass name asJavaScriptSource. ', '.
  365. aClass category asJavaScriptSource.
  366. ');' }.
  367. aClass comment ifNotEmpty: [
  368. aStream
  369. lf;
  370. write: '//>>excludeStart("ide", pragmas.excludeIdeData);'; lf;
  371. write: { aClass asJavaScriptSource. '.comment='. aClass comment crlfSanitized asJavaScriptSource. ';' }; lf;
  372. write: '//>>excludeEnd("ide");' ].
  373. aStream lf
  374. ! !
  375. Exporter subclass: #AmdExporter
  376. instanceVariableNames: 'namespace'
  377. package: 'Platform-ImportExport'!
  378. !AmdExporter commentStamp!
  379. I am used to export Packages in an AMD (Asynchronous Module Definition) JavaScript format.!
  380. !AmdExporter methodsFor: 'output'!
  381. exportPackageEpilogueOf: aPackage on: aStream
  382. aStream
  383. write: '});';
  384. lf
  385. !
  386. exportPackagePrologueOf: aPackage on: aStream
  387. | importsForOutput loadDependencies pragmaStart pragmaEnd |
  388. pragmaStart := ''.
  389. pragmaEnd := ''.
  390. importsForOutput := self importsForOutput: aPackage.
  391. loadDependencies := self amdNamesOfPackages: aPackage loadDependencies.
  392. importsForOutput value ifNotEmpty: [
  393. pragmaStart := String lf, '//>>excludeStart("imports", pragmas.excludeImports);', String lf.
  394. pragmaEnd := String lf, '//>>excludeEnd("imports");', String lf ].
  395. aStream
  396. write: {
  397. 'define('.
  398. ((#('amber/boot' ':1:'), importsForOutput value, #(':2:'), loadDependencies asArray sorted) asJavaScriptSource
  399. replace: ',\s*["'']:1:["'']' with: pragmaStart)
  400. replace: ',\s*["'']:2:["'']' with: pragmaEnd.
  401. ', function('.
  402. ((((#('$boot' ':1:'), importsForOutput key, #(':2:')) join: ',')
  403. replace: ',\s*:1:' with: pragmaStart)
  404. replace: ',\s*:2:' with: pragmaEnd).
  405. '){"use strict";' };
  406. lf.
  407. self exportPackageBodyBlockPrologueOf: aPackage on: aStream
  408. ! !
  409. !AmdExporter methodsFor: 'private'!
  410. amdNamesOfPackages: anArray
  411. ^ (anArray
  412. select: [ :each | (self amdNamespaceOfPackage: each) notNil ])
  413. collect: [ :each | (self amdNamespaceOfPackage: each), '/', each name ]
  414. !
  415. amdNamespaceOfPackage: aPackage
  416. ^ (aPackage transport type = 'amd')
  417. ifTrue: [ aPackage transport namespace ]
  418. ifFalse: [ nil ]
  419. !
  420. importsForOutput: aPackage
  421. "Returns an association where key is list of import variables
  422. and value is list of external dependencies, with ones imported as variables
  423. put at the beginning with same order as is in key.
  424. For example imports:{'jQuery'->'jquery'. 'bootstrap'} would yield
  425. #('jQuery') -> #('jquery' 'bootstrap')"
  426. | namedImports anonImports importVarNames |
  427. namedImports := #().
  428. anonImports := #().
  429. importVarNames := #().
  430. aPackage imports do: [ :each | each isString
  431. ifTrue: [ anonImports add: each ]
  432. ifFalse: [ namedImports add: each value.
  433. importVarNames add: each key ]].
  434. ^ importVarNames -> (namedImports, anonImports)
  435. ! !
  436. Object subclass: #ChunkParser
  437. instanceVariableNames: 'stream last'
  438. package: 'Platform-ImportExport'!
  439. !ChunkParser commentStamp!
  440. I am responsible for parsing aStream contents in the chunk format.
  441. ## API
  442. ChunkParser new
  443. stream: aStream;
  444. nextChunk!
  445. !ChunkParser methodsFor: 'accessing'!
  446. last
  447. ^ last
  448. !
  449. stream: aStream
  450. stream := aStream
  451. ! !
  452. !ChunkParser methodsFor: 'reading'!
  453. nextChunk
  454. "The chunk format (Smalltalk Interchange Format or Fileout format)
  455. is a trivial format but can be a bit tricky to understand:
  456. - Uses the exclamation mark as delimiter of chunks.
  457. - Inside a chunk a normal exclamation mark must be doubled.
  458. - A non empty chunk must be a valid Smalltalk expression.
  459. - A chunk on top level with a preceding empty chunk is an instruction chunk:
  460. - The object created by the expression then takes over reading chunks.
  461. This method returns next chunk as a String (trimmed), empty String (all whitespace) or nil."
  462. | char result chunk |
  463. result := '' writeStream.
  464. [ char := stream next.
  465. char notNil ] whileTrue: [
  466. char = '!!' ifTrue: [
  467. stream peek = '!!'
  468. ifTrue: [ stream next "skipping the escape double" ]
  469. ifFalse: [ ^ last := result contents trimBoth "chunk end marker found" ]].
  470. result nextPut: char ].
  471. ^ last := nil "a chunk needs to end with !!"
  472. ! !
  473. !ChunkParser class methodsFor: 'instance creation'!
  474. on: aStream
  475. ^ self new stream: aStream
  476. ! !
  477. Object subclass: #ClassCommentReader
  478. instanceVariableNames: 'class'
  479. package: 'Platform-ImportExport'!
  480. !ClassCommentReader commentStamp!
  481. I provide a mechanism for retrieving class comments stored on a file.
  482. See also `ClassCategoryReader`.!
  483. !ClassCommentReader methodsFor: 'accessing'!
  484. class: aClass
  485. class := aClass
  486. ! !
  487. !ClassCommentReader methodsFor: 'fileIn'!
  488. scanFrom: aChunkParser
  489. | chunk |
  490. chunk := aChunkParser nextChunk.
  491. chunk ifNotEmpty: [
  492. self setComment: chunk ].
  493. ! !
  494. !ClassCommentReader methodsFor: 'initialization'!
  495. initialize
  496. super initialize.
  497. ! !
  498. !ClassCommentReader methodsFor: 'private'!
  499. setComment: aString
  500. class comment: aString
  501. ! !
  502. Object subclass: #ClassProtocolReader
  503. instanceVariableNames: 'class category'
  504. package: 'Platform-ImportExport'!
  505. !ClassProtocolReader commentStamp!
  506. I provide a mechanism for retrieving class descriptions stored on a file in the Smalltalk chunk format.!
  507. !ClassProtocolReader methodsFor: 'accessing'!
  508. class: aClass category: aString
  509. class := aClass.
  510. category := aString
  511. ! !
  512. !ClassProtocolReader methodsFor: 'fileIn'!
  513. scanFrom: aChunkParser
  514. | chunk |
  515. [ chunk := aChunkParser nextChunk.
  516. chunk isEmpty ] whileFalse: [
  517. self compileMethod: chunk ]
  518. ! !
  519. !ClassProtocolReader methodsFor: 'initialization'!
  520. initialize
  521. super initialize.
  522. ! !
  523. !ClassProtocolReader methodsFor: 'private'!
  524. compileMethod: aString
  525. Compiler new install: aString forClass: class protocol: category
  526. ! !
  527. Object subclass: #ExportMethodProtocol
  528. instanceVariableNames: 'name theClass'
  529. package: 'Platform-ImportExport'!
  530. !ExportMethodProtocol commentStamp!
  531. I am an abstraction for a method protocol in a class / metaclass.
  532. I know of my class, name and methods.
  533. I am used when exporting a package.!
  534. !ExportMethodProtocol methodsFor: 'accessing'!
  535. methods
  536. ^ (self theClass methodsInProtocol: self name)
  537. sorted: [ :a :b | a selector <= b selector ]
  538. !
  539. name
  540. ^ name
  541. !
  542. name: aString
  543. name := aString
  544. !
  545. ownMethods
  546. ^ (self theClass ownMethodsInProtocol: self name)
  547. sorted: [ :a :b | a selector <= b selector ]
  548. !
  549. theClass
  550. ^ theClass
  551. !
  552. theClass: aClass
  553. theClass := aClass
  554. ! !
  555. !ExportMethodProtocol class methodsFor: 'instance creation'!
  556. name: aString theClass: aClass
  557. ^ self new
  558. name: aString;
  559. theClass: aClass;
  560. yourself
  561. ! !
  562. Object subclass: #Importer
  563. instanceVariableNames: 'lastSection lastChunk'
  564. package: 'Platform-ImportExport'!
  565. !Importer commentStamp!
  566. I can import Amber code from a string in the chunk format.
  567. ## API
  568. Importer new import: aString!
  569. !Importer methodsFor: 'accessing'!
  570. lastChunk
  571. ^ lastChunk
  572. !
  573. lastSection
  574. ^ lastSection
  575. ! !
  576. !Importer methodsFor: 'fileIn'!
  577. import: aStream
  578. | chunk result parser lastEmpty |
  579. parser := ChunkParser on: aStream.
  580. lastEmpty := false.
  581. lastSection := 'n/a, not started'.
  582. lastChunk := nil.
  583. [
  584. [ chunk := parser nextChunk.
  585. chunk isNil ] whileFalse: [
  586. chunk
  587. ifEmpty: [ lastEmpty := true ]
  588. ifNotEmpty: [
  589. lastSection := chunk.
  590. result := Compiler new evaluateExpression: chunk.
  591. lastEmpty
  592. ifTrue: [
  593. lastEmpty := false.
  594. result scanFrom: parser ]] ].
  595. lastSection := 'n/a, finished'
  596. ] on: Error do: [:e | lastChunk := parser last. e resignal ].
  597. ! !
  598. Error subclass: #PackageCommitError
  599. instanceVariableNames: ''
  600. package: 'Platform-ImportExport'!
  601. !PackageCommitError commentStamp!
  602. I get signaled when an attempt to commit a package has failed.!
  603. Object subclass: #PackageHandler
  604. instanceVariableNames: ''
  605. package: 'Platform-ImportExport'!
  606. !PackageHandler commentStamp!
  607. I am responsible for handling package loading and committing.
  608. I should not be used directly. Instead, use the corresponding `Package` methods.!
  609. !PackageHandler methodsFor: 'accessing'!
  610. chunkContentsFor: aPackage
  611. ^ String streamContents: [ :str |
  612. self chunkExporter exportPackage: aPackage on: str ]
  613. !
  614. chunkExporterClass
  615. ^ ChunkExporter
  616. !
  617. commitPathJsFor: aPackage
  618. self subclassResponsibility
  619. !
  620. commitPathStFor: aPackage
  621. self subclassResponsibility
  622. !
  623. contentsFor: aPackage
  624. ^ String streamContents: [ :str |
  625. self exporter exportPackage: aPackage on: str ]
  626. !
  627. exporterClass
  628. self subclassResponsibility
  629. ! !
  630. !PackageHandler methodsFor: 'committing'!
  631. commit: aPackage
  632. self
  633. commit: aPackage
  634. onSuccess: []
  635. onError: [ :error |
  636. PackageCommitError new
  637. messageText: 'Commiting failed with reason: "' , (error responseText) , '"';
  638. signal ]
  639. !
  640. commit: aPackage onSuccess: aBlock onError: anotherBlock
  641. self
  642. commitJsFileFor: aPackage
  643. onSuccess: [
  644. self
  645. commitStFileFor: aPackage
  646. onSuccess: [ aPackage beClean. aBlock value ]
  647. onError: anotherBlock ]
  648. onError: anotherBlock
  649. !
  650. commitJsFileFor: aPackage onSuccess: aBlock onError: anotherBlock
  651. self
  652. ajaxPutAt: (self commitPathJsFor: aPackage), '/', aPackage name, '.js'
  653. data: (self contentsFor: aPackage)
  654. onSuccess: aBlock
  655. onError: anotherBlock
  656. !
  657. commitStFileFor: aPackage onSuccess: aBlock onError: anotherBlock
  658. self
  659. ajaxPutAt: (self commitPathStFor: aPackage), '/', aPackage name, '.st'
  660. data: (self chunkContentsFor: aPackage)
  661. onSuccess: aBlock
  662. onError: anotherBlock
  663. ! !
  664. !PackageHandler methodsFor: 'error handling'!
  665. onCommitError: anError
  666. PackageCommitError new
  667. messageText: 'Commiting failed with reason: "' , (anError responseText) , '"';
  668. signal
  669. ! !
  670. !PackageHandler methodsFor: 'factory'!
  671. chunkExporter
  672. ^ self chunkExporterClass new
  673. !
  674. exporter
  675. ^ self exporterClass new
  676. ! !
  677. !PackageHandler methodsFor: 'loading'!
  678. load: aPackage
  679. "Should return a TThenable"
  680. self subclassResponsibility
  681. ! !
  682. !PackageHandler methodsFor: 'private'!
  683. ajaxPutAt: aURL data: aString onSuccess: aBlock onError: anotherBlock
  684. | xhr |
  685. xhr := Platform newXhr.
  686. xhr open: 'PUT' url: aURL async: true.
  687. xhr onreadystatechange: [
  688. xhr readyState = 4 ifTrue: [
  689. (xhr status >= 200 and: [ xhr status < 300 ])
  690. ifTrue: aBlock
  691. ifFalse: anotherBlock ]].
  692. xhr send: aString
  693. ! !
  694. PackageHandler subclass: #AmdPackageHandler
  695. instanceVariableNames: ''
  696. package: 'Platform-ImportExport'!
  697. !AmdPackageHandler commentStamp!
  698. I am responsible for handling package loading and committing.
  699. I should not be used directly. Instead, use the corresponding `Package` methods.!
  700. !AmdPackageHandler methodsFor: 'accessing'!
  701. commitPathJsFor: aPackage
  702. ^ self toUrl: (self namespaceFor: aPackage)
  703. !
  704. commitPathStFor: aPackage
  705. "If _source is not mapped, .st will be committed to .js path.
  706. It is recommended not to use _source as it can be deprecated."
  707. | path pathWithout |
  708. path := self toUrl: (self namespaceFor: aPackage), '/_source'.
  709. pathWithout := self commitPathJsFor: aPackage.
  710. ^ path = (pathWithout, '/_source') ifTrue: [ pathWithout ] ifFalse: [ path ]
  711. !
  712. exporterClass
  713. ^ AmdExporter
  714. ! !
  715. !AmdPackageHandler methodsFor: 'committing'!
  716. namespaceFor: aPackage
  717. ^ aPackage transport namespace
  718. ! !
  719. !AmdPackageHandler methodsFor: 'loading'!
  720. load: aPackage
  721. ^ Promise new: [ :model |
  722. Smalltalk amdRequire
  723. ifNil: [ self error: 'AMD loader not present' ]
  724. ifNotNil: [ :require |
  725. require
  726. value: { (self namespaceFor: aPackage), '/', aPackage name }
  727. value: [ :result | model value: result ]
  728. value: [ :error | model signal: error ] ] ]
  729. ! !
  730. !AmdPackageHandler methodsFor: 'private'!
  731. toUrl: aString
  732. ^ Smalltalk amdRequire
  733. ifNil: [ self error: 'AMD loader not present' ]
  734. ifNotNil: [ :require | (require basicAt: 'toUrl') value: aString ]
  735. ! !
  736. !AmdPackageHandler class methodsFor: 'commit paths'!
  737. defaultNamespace
  738. ^ Smalltalk defaultAmdNamespace
  739. !
  740. defaultNamespace: aString
  741. Smalltalk defaultAmdNamespace: aString
  742. ! !
  743. Object subclass: #PackageTransport
  744. instanceVariableNames: 'package'
  745. package: 'Platform-ImportExport'!
  746. !PackageTransport commentStamp!
  747. I represent the transport mechanism used to commit a package.
  748. My concrete subclasses have a `#handler` to which committing is delegated.!
  749. !PackageTransport methodsFor: 'accessing'!
  750. commitHandlerClass
  751. self subclassResponsibility
  752. !
  753. definition
  754. ^ ''
  755. !
  756. package
  757. ^ package
  758. !
  759. package: aPackage
  760. package := aPackage
  761. !
  762. type
  763. ^ self class type
  764. ! !
  765. !PackageTransport methodsFor: 'committing'!
  766. commit
  767. self commitHandler commit: self package
  768. !
  769. commitOnSuccess: aBlock onError: anotherBlock
  770. self commitHandler
  771. commit: self package
  772. onSuccess: aBlock
  773. onError: anotherBlock
  774. ! !
  775. !PackageTransport methodsFor: 'converting'!
  776. asJavaScriptObject
  777. ^ #{ 'type' -> self type }
  778. ! !
  779. !PackageTransport methodsFor: 'factory'!
  780. commitHandler
  781. ^ self commitHandlerClass new
  782. ! !
  783. !PackageTransport methodsFor: 'initialization'!
  784. setupFromJson: anObject
  785. "no op. override if needed in subclasses"
  786. ! !
  787. !PackageTransport methodsFor: 'loading'!
  788. load
  789. ^ (self commitHandler load: self package)
  790. then: [ Smalltalk postLoad ]
  791. ! !
  792. PackageTransport class instanceVariableNames: 'registry'!
  793. !PackageTransport class methodsFor: 'accessing'!
  794. classRegisteredFor: aString
  795. ^ registry at: aString
  796. !
  797. defaultType
  798. ^ AmdPackageTransport type
  799. !
  800. type
  801. "Override in subclasses"
  802. ^ nil
  803. ! !
  804. !PackageTransport class methodsFor: 'initialization'!
  805. initialize
  806. super initialize.
  807. self == PackageTransport
  808. ifTrue: [ registry := #{} ]
  809. ifFalse: [ self register ]
  810. ! !
  811. !PackageTransport class methodsFor: 'instance creation'!
  812. for: aString
  813. ^ (self classRegisteredFor: aString) new
  814. !
  815. fromJson: anObject
  816. anObject ifNil: [ ^ self for: self defaultType ].
  817. ^ (self for: anObject type)
  818. setupFromJson: anObject;
  819. yourself
  820. ! !
  821. !PackageTransport class methodsFor: 'registration'!
  822. register
  823. PackageTransport register: self
  824. !
  825. register: aClass
  826. aClass type ifNotNil: [
  827. registry at: aClass type put: aClass ]
  828. ! !
  829. PackageTransport subclass: #AmdPackageTransport
  830. instanceVariableNames: 'namespace'
  831. package: 'Platform-ImportExport'!
  832. !AmdPackageTransport commentStamp!
  833. I am the default transport for committing packages.
  834. See `AmdExporter` and `AmdPackageHandler`.!
  835. !AmdPackageTransport methodsFor: 'accessing'!
  836. commitHandlerClass
  837. ^ AmdPackageHandler
  838. !
  839. definition
  840. ^ String streamContents: [ :stream | stream
  841. write: { self class name. ' namespace: ' }; print: self namespace ]
  842. !
  843. namespace
  844. ^ namespace ifNil: [ self defaultNamespace ]
  845. !
  846. namespace: aString
  847. namespace := aString
  848. ! !
  849. !AmdPackageTransport methodsFor: 'actions'!
  850. setPath: aString
  851. "Set the path the the receiver's `namespace`"
  852. (require basicAt: 'config') value: #{
  853. 'paths' -> #{
  854. self namespace -> aString
  855. }
  856. }.
  857. ! !
  858. !AmdPackageTransport methodsFor: 'converting'!
  859. asJavaScriptObject
  860. ^ super asJavaScriptObject
  861. at: 'amdNamespace' put: self namespace;
  862. yourself
  863. ! !
  864. !AmdPackageTransport methodsFor: 'defaults'!
  865. defaultNamespace
  866. ^ Smalltalk defaultAmdNamespace
  867. ! !
  868. !AmdPackageTransport methodsFor: 'initialization'!
  869. setupFromJson: anObject
  870. self namespace: (anObject at: 'amdNamespace')
  871. ! !
  872. !AmdPackageTransport methodsFor: 'printing'!
  873. printOn: aStream
  874. super printOn: aStream.
  875. aStream
  876. nextPutAll: ' (AMD Namespace: ';
  877. nextPutAll: self namespace;
  878. nextPutAll: ')'
  879. ! !
  880. !AmdPackageTransport class methodsFor: 'accessing'!
  881. type
  882. ^ 'amd'
  883. ! !
  884. !AmdPackageTransport class methodsFor: 'instance creation'!
  885. namespace: aString
  886. ^ self new
  887. namespace: aString;
  888. yourself
  889. ! !
  890. !Class methodsFor: '*Platform-ImportExport'!
  891. exportBehaviorDefinitionTo: aStream using: anExporter
  892. anExporter exportDefinitionOf: self on: aStream
  893. ! !
  894. !Metaclass methodsFor: '*Platform-ImportExport'!
  895. exportBehaviorDefinitionTo: aStream using: anExporter
  896. anExporter exportMetaDefinitionOf: self instanceClass on: aStream
  897. ! !
  898. !Package methodsFor: '*Platform-ImportExport'!
  899. commit
  900. ^ self transport commit
  901. !
  902. load
  903. ^ self transport load
  904. !
  905. loadFromNamespace: aString
  906. ^ self transport
  907. namespace: aString;
  908. load
  909. ! !
  910. !Package class methodsFor: '*Platform-ImportExport'!
  911. load: aPackageName
  912. ^ (self named: aPackageName) load
  913. !
  914. load: aPackageName fromNamespace: aString
  915. ^ (self named: aPackageName) loadFromNamespace: aString
  916. ! !
  917. !TBehaviorProvider methodsFor: '*Platform-ImportExport'!
  918. methodsFor: aString
  919. ^ ClassProtocolReader new
  920. class: self category: aString;
  921. yourself
  922. !
  923. methodsFor: aString stamp: aStamp
  924. "Added for file-in compatibility, ignores stamp."
  925. ^ self methodsFor: aString
  926. ! !
  927. !TMasterBehavior methodsFor: '*Platform-ImportExport'!
  928. commentStamp
  929. ^ ClassCommentReader new
  930. class: self;
  931. yourself
  932. !
  933. commentStamp: aStamp prior: prior
  934. ^ self commentStamp
  935. ! !
  936. !Trait methodsFor: '*Platform-ImportExport'!
  937. exportBehaviorDefinitionTo: aStream using: anExporter
  938. anExporter exportTraitDefinitionOf: self on: aStream
  939. ! !