Kernel-Infrastructure.st 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. Smalltalk createPackage: 'Kernel-Infrastructure'!
  2. Object subclass: #AmberBootstrapInitialization
  3. slots: {}
  4. package: 'Kernel-Infrastructure'!
  5. !AmberBootstrapInitialization class methodsFor: 'organization'!
  6. organizeClasses
  7. Smalltalk classes do: [ :each | each enterOrganization ]
  8. !
  9. organizeMethods
  10. Smalltalk classes do: [ :eachClass |
  11. eachClass definedMethods do: [ :eachMethod |
  12. eachMethod methodClass methodOrganizationEnter: eachMethod andLeave: nil ] ]
  13. ! !
  14. !AmberBootstrapInitialization class methodsFor: 'public api'!
  15. run
  16. SmalltalkImage initialize.
  17. self
  18. organizeClasses;
  19. organizeMethods.
  20. ^ Smalltalk postLoad
  21. ! !
  22. ProtoObject subclass: #JSObjectProxy
  23. slots: {#jsObject}
  24. package: 'Kernel-Infrastructure'!
  25. !JSObjectProxy commentStamp!
  26. I handle sending messages to JavaScript objects, making JavaScript object accessing from Amber fully transparent.
  27. My instances make intensive use of `#doesNotUnderstand:`.
  28. My instances are automatically created by Amber whenever a message is sent to a JavaScript object.
  29. ## Usage examples
  30. JSObjectProxy objects are instanciated by Amber when a Smalltalk message is sent to a JavaScript object.
  31. window alert: 'hello world'.
  32. window inspect.
  33. (window jQuery: 'body') append: 'hello world'
  34. Amber messages sends are converted to JavaScript function calls or object property access _(in this order)_. If n one of them match, a `MessageNotUnderstood` error will be thrown.
  35. ## Message conversion rules
  36. - `someUser name` becomes `someUser.name`
  37. - `someUser name: 'John'` becomes `someUser name = "John"`
  38. - `console log: 'hello world'` becomes `console.log('hello world')`
  39. - `(window jQuery: 'foo') css: 'background' color: 'red'` becomes `window.jQuery('foo').css('background', 'red')`
  40. __Note:__ For keyword-based messages, only the first keyword is kept: `window foo: 1 bar: 2` is equivalent to `window foo: 1 baz: 2`.!
  41. !JSObjectProxy methodsFor: 'accessing'!
  42. at: aString
  43. <inlineJS: 'return $self.jsObject[aString]'>
  44. !
  45. at: aString ifAbsent: aBlock
  46. "return the aString property or evaluate aBlock if the property is not defined on the object"
  47. <inlineJS: '
  48. var obj = $self.jsObject;
  49. return aString in obj ? obj[aString] : aBlock._value();
  50. '>
  51. !
  52. at: aString ifPresent: aBlock
  53. "return the evaluation of aBlock with the value if the property is defined or return nil"
  54. <inlineJS: '
  55. var obj = $self.jsObject;
  56. return aString in obj ? aBlock._value_(obj[aString]) : nil;
  57. '>
  58. !
  59. at: aString ifPresent: aBlock ifAbsent: anotherBlock
  60. "return the evaluation of aBlock with the value if the property is defined
  61. or return value of anotherBlock"
  62. <inlineJS: '
  63. var obj = $self.jsObject;
  64. return aString in obj ? aBlock._value_(obj[aString]) : anotherBlock._value();
  65. '>
  66. !
  67. at: aString put: anObject
  68. <inlineJS: 'return $self.jsObject[aString] = anObject'>
  69. !
  70. in: aValuable
  71. ^ aValuable value: jsObject
  72. !
  73. jsObject
  74. ^ jsObject
  75. !
  76. removeKey: aString
  77. <inlineJS: 'delete $self.jsObject[aString]; return aString'>
  78. ! !
  79. !JSObjectProxy methodsFor: 'comparing'!
  80. = anObject
  81. ^ anObject class == self class and: [
  82. JSObjectProxy compareJSObjectOfProxy: self withProxy: anObject ]
  83. ! !
  84. !JSObjectProxy methodsFor: 'converting'!
  85. asJavaScriptObject
  86. "Answers the receiver in a stringify-friendly fashion"
  87. ^ jsObject
  88. ! !
  89. !JSObjectProxy methodsFor: 'enumerating'!
  90. keysAndValuesDo: aBlock
  91. <inlineJS: '
  92. var o = $self.jsObject;
  93. for(var i in o) {
  94. aBlock._value_value_(i, o[i]);
  95. }
  96. '>
  97. ! !
  98. !JSObjectProxy methodsFor: 'printing'!
  99. printOn: aStream
  100. aStream nextPutAll: self printString
  101. !
  102. printString
  103. <inlineJS: '
  104. var js = $self.jsObject;
  105. return !!js ? "<<malformed JS object proxy>>" : js.toString
  106. ? js.toString()
  107. : Object.prototype.toString.call(js)
  108. '>
  109. ! !
  110. !JSObjectProxy methodsFor: 'promises'!
  111. catch: aBlock
  112. (NativeFunction isNativeFunction: (self at: #then))
  113. ifTrue: [ ^ (TThenable >> #catch:) sendTo: jsObject arguments: {aBlock} ]
  114. ifFalse: [ ^ super catch: aBlock ]
  115. !
  116. on: aClass do: aBlock
  117. (NativeFunction isNativeFunction: (self at: #then))
  118. ifTrue: [ ^ (TThenable >> #on:do:) sendTo: jsObject arguments: {aClass. aBlock} ]
  119. ifFalse: [ ^ super on: aClass do: aBlock ]
  120. !
  121. then: aBlockOrArray
  122. (NativeFunction isNativeFunction: (self at: #then))
  123. ifTrue: [ ^ (TThenable >> #then:) sendTo: jsObject arguments: {aBlockOrArray} ]
  124. ifFalse: [ ^ super then: aBlockOrArray ]
  125. ! !
  126. !JSObjectProxy methodsFor: 'proxy'!
  127. doesNotUnderstand: aMessage
  128. ^ (JSObjectProxy lookupProperty: aMessage selector asJavaScriptPropertyName ofProxy: self)
  129. ifNil: [ super doesNotUnderstand: aMessage ]
  130. ifNotNil: [ :jsSelector |
  131. JSObjectProxy
  132. forwardMessage: jsSelector
  133. withArguments: aMessage arguments
  134. ofProxy: self ]
  135. ! !
  136. !JSObjectProxy methodsFor: 'streaming'!
  137. putOn: aStream
  138. aStream nextPutJSObject: jsObject
  139. ! !
  140. !JSObjectProxy class methodsFor: 'accessing'!
  141. null
  142. <inlineJS: 'return null'>
  143. !
  144. undefined
  145. <inlineJS: 'return undefined'>
  146. ! !
  147. !JSObjectProxy class methodsFor: 'instance creation'!
  148. on: aJSObject
  149. | instance |
  150. instance := self new.
  151. self jsObject: aJSObject ofProxy: instance.
  152. ^ instance
  153. ! !
  154. !JSObjectProxy class methodsFor: 'proxy'!
  155. addObjectVariablesTo: aDictionary ofProxy: aProxy
  156. <inlineJS: '
  157. var jsObject = aProxy.jsObject;
  158. for(var i in jsObject) {
  159. aDictionary._at_put_(i, jsObject[i]);
  160. }
  161. '>
  162. !
  163. associationsOfProxy: aProxy
  164. <inlineJS: '
  165. var jsObject = aProxy.jsObject, result = [];
  166. for(var i in jsObject) {
  167. result.push(i.__minus_gt(jsObject[i]));
  168. }
  169. return result;
  170. '>
  171. !
  172. compareJSObjectOfProxy: aProxy withProxy: anotherProxy
  173. <inlineJS: '
  174. var anotherJSObject = anotherProxy.a$cls ? anotherProxy.jsObject : anotherProxy;
  175. return aProxy.jsObject === anotherJSObject
  176. '>
  177. !
  178. forwardMessage: aString withArguments: anArray ofProxy: aProxy
  179. <inlineJS: '
  180. return $core.accessJavaScript(aProxy._jsObject(), aString, anArray);
  181. '>
  182. !
  183. jsObject: aJSObject ofProxy: aProxy
  184. <inlineJS: 'aProxy.jsObject = aJSObject'>
  185. !
  186. lookupProperty: aString ofProxy: aProxy
  187. "Looks up a property in JS object.
  188. Answer the property if it is present, or nil if it is not present."
  189. <inlineJS: 'return aString in aProxy._jsObject() ? aString : nil'>
  190. ! !
  191. Object subclass: #Organizer
  192. slots: {#elements}
  193. package: 'Kernel-Infrastructure'!
  194. !Organizer commentStamp!
  195. I represent categorization information.
  196. ## API
  197. Use `#addElement:` and `#removeElement:` to manipulate instances.!
  198. !Organizer methodsFor: 'accessing'!
  199. addElement: anObject
  200. self elements add: anObject
  201. !
  202. elements
  203. ^ elements
  204. !
  205. removeElement: anObject
  206. self elements remove: anObject ifAbsent: []
  207. ! !
  208. !Organizer methodsFor: 'initialization'!
  209. initialize
  210. super initialize.
  211. elements := Set new
  212. ! !
  213. Organizer subclass: #ClassOrganizer
  214. slots: {#traitOrBehavior}
  215. package: 'Kernel-Infrastructure'!
  216. !ClassOrganizer commentStamp!
  217. I am an organizer specific to classes. I hold method categorization information for classes.!
  218. !ClassOrganizer methodsFor: 'accessing'!
  219. addElement: aString
  220. super addElement: aString.
  221. SystemAnnouncer current announce: (ProtocolAdded new
  222. protocol: aString;
  223. theClass: self theClass;
  224. yourself)
  225. !
  226. removeElement: aString
  227. super removeElement: aString.
  228. SystemAnnouncer current announce: (ProtocolRemoved new
  229. protocol: aString;
  230. theClass: self theClass;
  231. yourself)
  232. !
  233. theClass
  234. ^ traitOrBehavior
  235. !
  236. theClass: aClass
  237. traitOrBehavior := aClass
  238. ! !
  239. !ClassOrganizer class methodsFor: 'instance creation'!
  240. on: aClass
  241. ^ self new
  242. theClass: aClass;
  243. yourself
  244. ! !
  245. Organizer subclass: #PackageOrganizer
  246. slots: {}
  247. package: 'Kernel-Infrastructure'!
  248. !PackageOrganizer commentStamp!
  249. I am an organizer specific to packages. I hold classes categorization information.!
  250. Object subclass: #Package
  251. slots: {#contextBlock. #basicTransport. #name. #transport. #imports. #dirty. #organization. #isReady}
  252. package: 'Kernel-Infrastructure'!
  253. !Package commentStamp!
  254. I am similar to a "class category" typically found in other Smalltalks like Pharo or Squeak. Amber does not have class categories anymore, it had in the beginning but now each class in the system knows which package it belongs to.
  255. Each package has a name and can be queried for its classes, but it will then resort to a reverse scan of all classes to find them.
  256. ## API
  257. Packages are manipulated through "Smalltalk current", like for example finding one based on a name or with `Package class >> #name` directly:
  258. Smalltalk current packageAt: 'Kernel'
  259. Package named: 'Kernel'
  260. A package differs slightly from a Monticello package which can span multiple class categories using a naming convention based on hyphenation. But just as in Monticello a package supports "class extensions" so a package can define behaviors in foreign classes using a naming convention for method categories where the category starts with an asterisk and then the name of the owning package follows.
  261. You can fetch a package from the server:
  262. Package load: 'Additional-Examples'!
  263. !Package methodsFor: 'accessing'!
  264. beClean
  265. dirty := false.
  266. SystemAnnouncer current announce: (PackageClean new
  267. package: self;
  268. yourself)
  269. !
  270. beDirty
  271. dirty := true.
  272. SystemAnnouncer current announce: (PackageDirty new
  273. package: self;
  274. yourself)
  275. !
  276. classTemplate
  277. ^ String streamContents: [ :stream | stream
  278. write: 'Object subclass: #NameOfSubclass'; lf;
  279. tab; write: 'instanceVariableNames: '''''; lf;
  280. tab; write: 'package: '; print: self name ]
  281. !
  282. context
  283. ^ self contextBlock
  284. ifNil: [ #{} ]
  285. ifNotNil: [ :block |
  286. | result |
  287. result := Dictionary new.
  288. block value keysAndValuesDo: [ :key :value | result at: key put: value ].
  289. result ]
  290. !
  291. contextBlock
  292. ^ contextBlock
  293. !
  294. contextBlock: aBlock
  295. contextBlock := aBlock
  296. !
  297. contextFunctionSource
  298. ^ (self imports reject: #isString)
  299. ifEmpty: [ nil ]
  300. ifNotEmpty: [ :namedImports |
  301. 'function () { return {',
  302. (',' join: (namedImports collect: [ :each | each key, ':', each key ])),
  303. '}; }' ]
  304. !
  305. definition
  306. ^ String streamContents: [ :stream | stream
  307. write: self class name; lf;
  308. tab; write: 'named: '; print: self name; lf;
  309. tab; write: { 'imports: '. self importsDefinition }; lf;
  310. tab; write: { 'transport: ('. self transport definition. ')' } ]
  311. !
  312. imports
  313. ^ imports ifNil: [
  314. self imports: #().
  315. imports ]
  316. !
  317. imports: anArray
  318. self validateImports: anArray.
  319. imports := anArray asSet
  320. !
  321. importsDefinition
  322. ^ String streamContents: [ :stream |
  323. stream write: '{'.
  324. self sortedImportsAsArray
  325. do: [ :each | stream print: each ]
  326. separatedBy: [ stream write: '. ' ].
  327. stream write: '}' ]
  328. !
  329. isReady
  330. ^ isReady
  331. !
  332. isReady: aPromise
  333. isReady := aPromise
  334. !
  335. javaScriptDescriptor: anObject
  336. | basicEval basicContext basicImports |
  337. basicImports := anObject at: 'imports' ifAbsent: [ #() ].
  338. self imports: (self importsFromJson: basicImports).
  339. basicTransport := anObject at: 'transport' ifAbsent: [].
  340. anObject at: 'isReady' ifPresent: [ :aPromise | self isReady: aPromise ].
  341. "TODO remove, backward compatibility"
  342. anObject at: 'innerEval' ifPresent: [ :evalBlock |
  343. self contextFunctionSource ifNotNil: [ :source |
  344. anObject at: 'context' put: (evalBlock value: '(', source, ')') ] ].
  345. basicContext := anObject at: 'context' ifAbsent: [ nil asJavaScriptObject ].
  346. self contextBlock: basicContext
  347. !
  348. name
  349. ^ name
  350. !
  351. name: aString
  352. name := aString
  353. !
  354. organization
  355. ^ organization
  356. !
  357. transport
  358. ^ transport ifNil: [
  359. self transport: (PackageTransport fromJson: self basicTransport).
  360. transport ]
  361. !
  362. transport: aPackageTransport
  363. transport := aPackageTransport.
  364. aPackageTransport package: self
  365. ! !
  366. !Package methodsFor: 'classes'!
  367. classes
  368. ^ self organization elements copy
  369. !
  370. setupClasses
  371. self classes do: [ :each | each initialize ]
  372. !
  373. sortedClasses
  374. "Answer all classes in the receiver, sorted by superclass/subclasses and by class name for common subclasses (Issue #143)."
  375. ^ self class sortedClasses: self classes
  376. ! !
  377. !Package methodsFor: 'converting'!
  378. importsAsJson
  379. ^ self sortedImportsAsArray collect: [ :each |
  380. each isString
  381. ifTrue: [ each ]
  382. ifFalse: [ each key, '=', each value ]]
  383. !
  384. importsFromJson: anArray
  385. "Parses array of string, eg. #('asdf' 'qwer=tyuo')
  386. into array of Strings and Associations,
  387. eg. {'asdf'. 'qwer'->'tyuo'}"
  388. ^ anArray collect: [ :each |
  389. | split |
  390. split := each tokenize: '='.
  391. split size = 1
  392. ifTrue: [ split first ]
  393. ifFalse: [ split first -> split second ]]
  394. ! !
  395. !Package methodsFor: 'dependencies'!
  396. loadDependencies
  397. "Returns list of packages that need to be loaded
  398. before loading this package."
  399. | classes packages |
  400. classes := self loadDependencyClasses.
  401. ^ (classes collect: [ :each | each package ]) asSet
  402. remove: self ifAbsent: [];
  403. yourself
  404. !
  405. loadDependencyClasses
  406. "Returns classes needed at the time of loading a package.
  407. These are all that are used to subclass
  408. and to define an extension method
  409. as well as all traits used"
  410. | starCategoryName |
  411. starCategoryName := '*', self name.
  412. ^ (self classes collect: [ :each | each superclass ]) asSet
  413. addAll: (Smalltalk classes select: [ :each |
  414. ({each. each theMetaClass} copyWithout: nil) anySatisfy: [ :any |
  415. (any protocols includes: starCategoryName) and: [
  416. (any ownMethodsInProtocol: starCategoryName) notEmpty ]]]);
  417. addAll: (Array streamContents: [ :as | self traitCompositions valuesDo: [ :each | as write: (each collect: [ :eachTT | eachTT trait ])]]);
  418. remove: nil ifAbsent: [];
  419. yourself
  420. !
  421. traitCompositions
  422. | traitCompositions |
  423. traitCompositions := Dictionary new.
  424. self classes do: [ :eachClass | eachClass includingPossibleMetaDo: [ :each |
  425. traitCompositions at: each put: each traitComposition ] ].
  426. ^ traitCompositions reject: [ :each | each isEmpty ]
  427. ! !
  428. !Package methodsFor: 'initialization'!
  429. initialize
  430. super initialize.
  431. organization := PackageOrganizer new.
  432. contextBlock := nil.
  433. dirty := nil.
  434. imports := nil.
  435. isReady := Promise new.
  436. transport := nil
  437. ! !
  438. !Package methodsFor: 'printing'!
  439. printOn: aStream
  440. super printOn: aStream.
  441. aStream
  442. nextPutAll: ' (';
  443. nextPutAll: self name;
  444. nextPutAll: ')'
  445. ! !
  446. !Package methodsFor: 'private'!
  447. basicTransport
  448. "Answer the transport literal JavaScript object as setup in the JavaScript file, if any"
  449. ^ basicTransport
  450. !
  451. sortedImportsAsArray
  452. "Answer imports sorted first by type (associations first),
  453. then by value"
  454. ^ self imports asArray
  455. sorted: [ :a :b |
  456. a isString not & b isString or: [
  457. a isString = b isString and: [
  458. a value <= b value ]]]
  459. ! !
  460. !Package methodsFor: 'testing'!
  461. isDirty
  462. ^ dirty ifNil: [ false ]
  463. !
  464. isPackage
  465. ^ true
  466. ! !
  467. !Package methodsFor: 'validation'!
  468. validateImports: aCollection
  469. aCollection do: [ :import |
  470. import isString ifFalse: [
  471. (import respondsTo: #key) ifFalse: [
  472. self error: 'Imports must be Strings or Associations' ].
  473. import key isString & import value isString ifFalse: [
  474. self error: 'Key and value must be Strings' ].
  475. (import key match: '^[a-zA-Z][a-zA-Z0-9]*$') ifFalse: [
  476. self error: 'Keys must be identifiers' ]]]
  477. ! !
  478. Package class slots: {#defaultCommitPathJs. #defaultCommitPathSt}!
  479. !Package class methodsFor: 'accessing'!
  480. named: aPackageName
  481. ^ Smalltalk
  482. packageAt: aPackageName
  483. ifAbsent: [
  484. Smalltalk createPackage: aPackageName ]
  485. !
  486. named: aPackageName ifAbsent: aBlock
  487. ^ Smalltalk packageAt: aPackageName ifAbsent: aBlock
  488. !
  489. named: aPackageName imports: anArray transport: aTransport
  490. | pkg |
  491. pkg := self named: aPackageName.
  492. pkg imports: anArray.
  493. pkg transport: aTransport.
  494. ^ pkg
  495. !
  496. named: aPackageName transport: aTransport
  497. | pkg |
  498. pkg := self named: aPackageName.
  499. pkg transport: aTransport.
  500. ^ pkg
  501. ! !
  502. !Package class methodsFor: 'instance creation'!
  503. named: aString javaScriptDescriptor: anObject
  504. | pkg |
  505. pkg := Smalltalk createPackage: aString.
  506. pkg javaScriptDescriptor: anObject.
  507. ^ pkg
  508. !
  509. new: aString
  510. ^ Package new
  511. name: aString;
  512. yourself
  513. ! !
  514. !Package class methodsFor: 'sorting'!
  515. sortedClasses: classes
  516. ^ Array streamContents: [ :stream | stream << (ClassBuilder sortClasses: classes) ]
  517. ! !
  518. Object subclass: #PackageStateObserver
  519. slots: {}
  520. package: 'Kernel-Infrastructure'!
  521. !PackageStateObserver commentStamp!
  522. My current instance listens for any changes in the system that might affect the state of a package (being dirty).!
  523. !PackageStateObserver methodsFor: 'accessing'!
  524. announcer
  525. ^ SystemAnnouncer current
  526. ! !
  527. !PackageStateObserver methodsFor: 'actions'!
  528. observeSystem
  529. self announcer
  530. on: PackageAdded
  531. send: #onPackageAdded:
  532. to: self;
  533. on: ClassAnnouncement
  534. send: #onClassModification:
  535. to: self;
  536. on: MethodAnnouncement
  537. send: #onMethodModification:
  538. to: self;
  539. on: ProtocolAnnouncement
  540. send: #onProtocolModification:
  541. to: self
  542. ! !
  543. !PackageStateObserver methodsFor: 'reactions'!
  544. onClassModification: anAnnouncement
  545. anAnnouncement theClass ifNotNil: [ :theClass | theClass package beDirty ]
  546. !
  547. onMethodModification: anAnnouncement
  548. anAnnouncement method package ifNotNil: [ :package | package beDirty ]
  549. !
  550. onPackageAdded: anAnnouncement
  551. anAnnouncement package beDirty
  552. !
  553. onProtocolModification: anAnnouncement
  554. anAnnouncement package ifNotNil: [ :package | package beDirty ]
  555. ! !
  556. PackageStateObserver class slots: {#current}!
  557. !PackageStateObserver class methodsFor: 'accessing'!
  558. current
  559. ^ current ifNil: [ current := self new ]
  560. ! !
  561. !PackageStateObserver class methodsFor: 'initialization'!
  562. initialize
  563. self current observeSystem
  564. ! !
  565. Object subclass: #Setting
  566. slots: {#key. #defaultValue}
  567. package: 'Kernel-Infrastructure'!
  568. !Setting commentStamp!
  569. I represent a setting **stored** at `Smalltalk settings`.
  570. In the current implementation, `Smalltalk settings` is an object persisted in the localStorage.
  571. ## API
  572. A `Setting` value can be read using `value` and set using `value:`.
  573. Settings are accessed with `'key' asSetting` or `'key' asSettingIfAbsent: aDefaultValue`.
  574. To read the value of a setting you can also use the convenience:
  575. `theValueSet := 'any.characteristic' settingValue`
  576. or with a default using:
  577. `theEnsuredValueSet := 'any.characteristic' settingValueIfAbsent: true`!
  578. !Setting methodsFor: 'accessing'!
  579. defaultValue
  580. ^ defaultValue
  581. !
  582. defaultValue: aStringifiableObject
  583. defaultValue := aStringifiableObject
  584. !
  585. key
  586. ^ key
  587. !
  588. key: aString
  589. key := aString
  590. !
  591. value
  592. ^ Smalltalk settings at: self key ifAbsent: [ self defaultValue ]
  593. !
  594. value: aStringifiableObject
  595. ^ Smalltalk settings at: self key put: aStringifiableObject
  596. ! !
  597. !Setting class methodsFor: 'instance creation'!
  598. at: aString ifAbsent: aDefaultValue
  599. ^ super new
  600. key: aString;
  601. defaultValue: aDefaultValue;
  602. yourself
  603. !
  604. new
  605. self shouldNotImplement
  606. ! !
  607. Object subclass: #SmalltalkImage
  608. slots: {#globalJsVariables. #packageDictionary}
  609. package: 'Kernel-Infrastructure'!
  610. !SmalltalkImage commentStamp!
  611. I represent the Smalltalk system, wrapping
  612. operations of variable `$core` declared in `base/boot.js`.
  613. ## API
  614. I have only one instance, accessed with global variable `Smalltalk`.
  615. ## Classes
  616. Classes can be accessed using the following methods:
  617. - `#classes` answers the full list of Smalltalk classes in the system
  618. - `#globals #at:` answers a specific global (usually, a class) or `nil`
  619. ## Packages
  620. Packages can be accessed using the following methods:
  621. - `#packages` answers the full list of packages
  622. - `#packageAt:` answers a specific package or `nil`
  623. ## Parsing
  624. The `#parse:` method is used to parse Amber source code.
  625. It requires the `Compiler` package and the `base/parser.js` parser file in order to work.!
  626. !SmalltalkImage methodsFor: 'accessing'!
  627. cancelOptOut: anObject
  628. "A Smalltalk object has a 'a$cls' property.
  629. If this property is shadowed for anObject by optOut:,
  630. the object is treated as plain JS object.
  631. This removes the shadow and anObject is Smalltalk object
  632. again if it was before."
  633. <inlineJS: 'delete anObject.a$cls;'>
  634. !
  635. core
  636. <inlineJS: 'return $core'>
  637. !
  638. globals
  639. <inlineJS: 'return $globals'>
  640. !
  641. optOut: anObject
  642. "A Smalltalk object has a 'a$cls' property.
  643. This shadows the property for anObject.
  644. The object is treated as plain JS object following this."
  645. <inlineJS: 'anObject.a$cls = null'>
  646. !
  647. parse: aString
  648. ^ Compiler new parse: aString
  649. !
  650. pseudoVariableNames
  651. ^ Compiler pseudoVariableNames
  652. !
  653. readJSObject: anObject
  654. <inlineJS: 'return $core.readJSObject(anObject)'>
  655. !
  656. reservedWords
  657. ^ #(
  658. "http://www.ecma-international.org/ecma-262/6.0/#sec-keywords"
  659. break case catch class const continue debugger
  660. default delete do else export extends finally
  661. for function if import in instanceof new
  662. return super switch this throw try typeof
  663. var void while with yield
  664. "in strict mode"
  665. let static
  666. "Amber protected words: these should not be compiled as-is when in code"
  667. arguments
  668. "http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words"
  669. await enum
  670. "in strict mode"
  671. implements interface package private protected public
  672. )
  673. !
  674. settings
  675. ^ SmalltalkSettings
  676. !
  677. version
  678. "Answer the version string of Amber"
  679. ^ '0.29.2-pre'
  680. ! !
  681. !SmalltalkImage methodsFor: 'accessing amd'!
  682. amdRequire
  683. ^ self core at: 'amdRequire'
  684. !
  685. defaultAmdNamespace
  686. ^ 'transport.defaultAmdNamespace' settingValue
  687. !
  688. defaultAmdNamespace: aString
  689. 'transport.defaultAmdNamespace' settingValue: aString
  690. ! !
  691. !SmalltalkImage methodsFor: 'classes'!
  692. classes
  693. ^ self core traitsOrClasses copy
  694. !
  695. removeClass: aClass
  696. aClass isMetaclass ifTrue: [ self error: aClass asString, ' is a Metaclass and cannot be removed!!' ].
  697. aClass allSubclassesDo: [ :subclass | self error: aClass name, ' has a subclass: ', subclass name ].
  698. aClass traitUsers ifNotEmpty: [ self error: aClass name, ' has trait users.' ].
  699. self deleteClass: aClass.
  700. aClass includingPossibleMetaDo: [ :each | each setTraitComposition: #() ].
  701. SystemAnnouncer current
  702. announce: (ClassRemoved new
  703. theClass: aClass;
  704. yourself)
  705. ! !
  706. !SmalltalkImage methodsFor: 'error handling'!
  707. asSmalltalkException: anObject
  708. "A JavaScript exception may be thrown.
  709. We then need to convert it back to a Smalltalk object"
  710. ^ anObject
  711. ifNil: [ [ self error: 'Error: nil' ] on: Error do: [ :e | e ] ]
  712. ifNotNil: [
  713. (self isError: anObject)
  714. ifTrue: [ anObject ]
  715. ifFalse: [ JavaScriptException on: anObject ] ]
  716. !
  717. try: actionBlock ifTrue: aBlock catch: anotherBlock
  718. "Similar to BlockClosure >> tryifTrue:catch:, but
  719. converts all JS exceptions to JavaScriptException instances."
  720. | smalltalkError |
  721. ^ actionBlock
  722. tryIfTrue: [ :error |
  723. smalltalkError := self asSmalltalkException: error.
  724. aBlock value: smalltalkError ]
  725. catch: [ anotherBlock value: smalltalkError ]
  726. ! !
  727. !SmalltalkImage methodsFor: 'globals'!
  728. addGlobalJsVariable: aString
  729. self globalJsVariables add: aString
  730. !
  731. deleteGlobalJsVariable: aString
  732. self globalJsVariables remove: aString ifAbsent:[]
  733. !
  734. globalJsVariables
  735. ^ globalJsVariables ifNil: [
  736. globalJsVariables := #(window document process global) ]
  737. ! !
  738. !SmalltalkImage methodsFor: 'image'!
  739. postLoad
  740. ^ self adoptPackageDescriptors then: [ :pkgs |
  741. | classes |
  742. pkgs do: #beClean.
  743. classes := Smalltalk classes select:
  744. [ :each | pkgs includes: each package ].
  745. classes do: [ :each |
  746. each = self class ifFalse: [ each initialize ] ].
  747. self sweepPackageDescriptors: pkgs ]
  748. ! !
  749. !SmalltalkImage methodsFor: 'packages'!
  750. beClean
  751. "Marks all packages clean."
  752. self packages do: #beClean
  753. !
  754. createPackage: packageName
  755. | package announcement |
  756. package := self basicCreatePackage: packageName.
  757. announcement := PackageAdded new
  758. package: package;
  759. yourself.
  760. SystemAnnouncer current announce: announcement.
  761. ^ package
  762. !
  763. packageAt: packageName ifAbsent: aBlock
  764. ^ self packageDictionary at: packageName ifAbsent: aBlock
  765. !
  766. packageAt: packageName ifPresent: aBlock
  767. ^ self packageDictionary at: packageName ifPresent: aBlock
  768. !
  769. packageDictionary
  770. ^ packageDictionary ifNil: [ packageDictionary := Dictionary new ]
  771. !
  772. packages
  773. "Return all Package instances in the system."
  774. ^ self packageDictionary values copy
  775. !
  776. removePackage: packageName
  777. "Removes a package and all its classes."
  778. | pkg |
  779. pkg := self packageAt: packageName ifAbsent: [ self error: 'Missing package: ', packageName ].
  780. pkg classes do: [ :each |
  781. self removeClass: each ].
  782. self packageDictionary removeKey: packageName
  783. !
  784. renamePackage: packageName to: newName
  785. "Rename a package."
  786. | pkg |
  787. pkg := self packageAt: packageName ifAbsent: [ self error: 'Missing package: ', packageName ].
  788. self packageAt: newName ifPresent: [ self error: 'Already exists a package called: ', newName ].
  789. pkg name: newName; beDirty.
  790. self packageDictionary
  791. at: newName put: pkg;
  792. removeKey: packageName
  793. ! !
  794. !SmalltalkImage methodsFor: 'private'!
  795. adoptPackageDescriptors
  796. ^ self tryAdoptPackageDescriptorsBeyond: Set new
  797. !
  798. basicCreatePackage: packageName
  799. "Create and bind a new bare package with given name and return it."
  800. ^ self packageDictionary at: packageName ifAbsentPut: [ Package new: packageName ]
  801. !
  802. deleteClass: aClass
  803. "Deletes a class by deleting its binding only. Use #removeClass instead"
  804. <inlineJS: '$core.removeClass(aClass)'>
  805. !
  806. sweepPackageDescriptors: pkgs
  807. | pd |
  808. pd := self core packageDescriptors.
  809. pkgs do: [ :each | pd removeKey: each name ]
  810. !
  811. tryAdoptPackageDescriptorsBeyond: aSet
  812. | original |
  813. original := aSet copy.
  814. self core packageDescriptors keysAndValuesDo: [ :key :value |
  815. aSet add: (Package named: key javaScriptDescriptor: value) ].
  816. ^ (aSet allSatisfy: [ :each | original includes: each ])
  817. ifFalse: [ (Promise all: (aSet collect: #isReady)) then: [ self tryAdoptPackageDescriptorsBeyond: aSet ] ]
  818. ifTrue: [ Promise value: aSet ]
  819. ! !
  820. !SmalltalkImage methodsFor: 'testing'!
  821. existsJsGlobal: aString
  822. self deprecatedAPI: 'Use Platform >> includesGlobal: instead'.
  823. ^ Platform includesGlobal: aString
  824. !
  825. isError: anObject
  826. ^ (self isSmalltalkObject: anObject) and: [ anObject isError ]
  827. !
  828. isSmalltalkObject: anObject
  829. "Consider anObject a Smalltalk object if it has a 'a$cls' property.
  830. Note that this may be unaccurate"
  831. <inlineJS: 'return anObject.a$cls !!= null'>
  832. ! !
  833. SmalltalkImage class slots: {#current}!
  834. !SmalltalkImage class methodsFor: 'initialization'!
  835. initialize
  836. | st |
  837. st := self current.
  838. st globals at: 'Smalltalk' put: st
  839. ! !
  840. !SmalltalkImage class methodsFor: 'instance creation'!
  841. current
  842. ^ current ifNil: [ current := super new ] ifNotNil: [ self deprecatedAPI. current ]
  843. !
  844. new
  845. self shouldNotImplement
  846. ! !
  847. JSObjectProxy setTraitComposition: {TIsInGroup. TThenable} asTraitComposition!
  848. ! !
  849. !ProtoStream methodsFor: '*Kernel-Infrastructure'!
  850. nextPutJSObject: aJSObject
  851. self nextPut: aJSObject
  852. ! !
  853. !String methodsFor: '*Kernel-Infrastructure'!
  854. asJavaScriptPropertyName
  855. <inlineJS: 'return $core.st2prop(self)'>
  856. !
  857. asSetting
  858. "Answer aSetting dedicated to locally store a value using this string as key.
  859. Nil will be the default value."
  860. ^ Setting at: self ifAbsent: nil
  861. !
  862. asSettingIfAbsent: aDefaultValue
  863. "Answer aSetting dedicated to locally store a value using this string as key.
  864. Make this setting to have aDefaultValue."
  865. ^ Setting at: self ifAbsent: aDefaultValue
  866. !
  867. settingValue
  868. ^ self asSetting value
  869. !
  870. settingValue: aValue
  871. "Sets the value of the setting that will be locally stored using this string as key.
  872. Note that aValue can be any object that can be stringifyed"
  873. ^ self asSetting value: aValue
  874. !
  875. settingValueIfAbsent: aDefaultValue
  876. "Answer the value of the locally stored setting using this string as key.
  877. Use aDefaultValue in case no setting is found"
  878. ^ (self asSettingIfAbsent: aDefaultValue) value
  879. ! !