Kernel-Infrastructure.st 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. Smalltalk createPackage: 'Kernel-Infrastructure'!
  2. Object subclass: #AmberBootstrapInitialization
  3. instanceVariableNames: ''
  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. instanceVariableNames: '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 ifFalse: [ ^ false ].
  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.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. compareJSObjectOfProxy: aProxy withProxy: anotherProxy
  164. <inlineJS: '
  165. var anotherJSObject = anotherProxy.a$cls ? anotherProxy["@jsObject"] : anotherProxy;
  166. return aProxy["@jsObject"] === anotherJSObject
  167. '>
  168. !
  169. forwardMessage: aString withArguments: anArray ofProxy: aProxy
  170. <inlineJS: '
  171. return $core.accessJavaScript(aProxy._jsObject(), aString, anArray);
  172. '>
  173. !
  174. jsObject: aJSObject ofProxy: aProxy
  175. <inlineJS: 'aProxy[''@jsObject''] = aJSObject'>
  176. !
  177. lookupProperty: aString ofProxy: aProxy
  178. "Looks up a property in JS object.
  179. Answer the property if it is present, or nil if it is not present."
  180. <inlineJS: 'return aString in aProxy._jsObject() ? aString : nil'>
  181. ! !
  182. Object subclass: #Organizer
  183. instanceVariableNames: 'elements'
  184. package: 'Kernel-Infrastructure'!
  185. !Organizer commentStamp!
  186. I represent categorization information.
  187. ## API
  188. Use `#addElement:` and `#removeElement:` to manipulate instances.!
  189. !Organizer methodsFor: 'accessing'!
  190. addElement: anObject
  191. self elements add: anObject
  192. !
  193. elements
  194. ^ elements
  195. !
  196. removeElement: anObject
  197. self elements remove: anObject ifAbsent: []
  198. ! !
  199. !Organizer methodsFor: 'initialization'!
  200. initialize
  201. super initialize.
  202. elements := Set new
  203. ! !
  204. Organizer subclass: #ClassOrganizer
  205. instanceVariableNames: 'traitOrBehavior'
  206. package: 'Kernel-Infrastructure'!
  207. !ClassOrganizer commentStamp!
  208. I am an organizer specific to classes. I hold method categorization information for classes.!
  209. !ClassOrganizer methodsFor: 'accessing'!
  210. addElement: aString
  211. super addElement: aString.
  212. SystemAnnouncer current announce: (ProtocolAdded new
  213. protocol: aString;
  214. theClass: self theClass;
  215. yourself)
  216. !
  217. removeElement: aString
  218. super removeElement: aString.
  219. SystemAnnouncer current announce: (ProtocolRemoved new
  220. protocol: aString;
  221. theClass: self theClass;
  222. yourself)
  223. !
  224. theClass
  225. ^ traitOrBehavior
  226. !
  227. theClass: aClass
  228. traitOrBehavior := aClass
  229. ! !
  230. !ClassOrganizer class methodsFor: 'instance creation'!
  231. on: aClass
  232. ^ self new
  233. theClass: aClass;
  234. yourself
  235. ! !
  236. Organizer subclass: #PackageOrganizer
  237. instanceVariableNames: ''
  238. package: 'Kernel-Infrastructure'!
  239. !PackageOrganizer commentStamp!
  240. I am an organizer specific to packages. I hold classes categorization information.!
  241. Object subclass: #Package
  242. instanceVariableNames: 'evalBlock basicTransport name transport imports dirty organization isReady'
  243. package: 'Kernel-Infrastructure'!
  244. !Package commentStamp!
  245. 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.
  246. 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.
  247. ## API
  248. Packages are manipulated through "Smalltalk current", like for example finding one based on a name or with `Package class >> #name` directly:
  249. Smalltalk current packageAt: 'Kernel'
  250. Package named: 'Kernel'
  251. 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.
  252. You can fetch a package from the server:
  253. Package load: 'Additional-Examples'!
  254. !Package methodsFor: 'accessing'!
  255. beClean
  256. dirty := false.
  257. SystemAnnouncer current announce: (PackageClean new
  258. package: self;
  259. yourself)
  260. !
  261. beDirty
  262. dirty := true.
  263. SystemAnnouncer current announce: (PackageDirty new
  264. package: self;
  265. yourself)
  266. !
  267. classTemplate
  268. ^ String streamContents: [ :stream | stream
  269. write: 'Object subclass: #NameOfSubclass'; lf;
  270. tab; write: 'instanceVariableNames: '''''; lf;
  271. tab; write: 'package: '; print: self name ]
  272. !
  273. definition
  274. ^ String streamContents: [ :stream | stream
  275. write: self class name; lf;
  276. tab; write: 'named: '; print: self name; lf;
  277. tab; write: { 'imports: '. self importsDefinition }; lf;
  278. tab; write: { 'transport: ('. self transport definition. ')' } ]
  279. !
  280. evalBlock
  281. ^ evalBlock
  282. !
  283. evalBlock: aBlock
  284. evalBlock := aBlock
  285. !
  286. imports
  287. ^ imports ifNil: [
  288. self imports: #().
  289. imports ]
  290. !
  291. imports: anArray
  292. self validateImports: anArray.
  293. imports := anArray asSet
  294. !
  295. importsDefinition
  296. ^ String streamContents: [ :stream |
  297. stream write: '{'.
  298. self sortedImportsAsArray
  299. do: [ :each | stream print: each ]
  300. separatedBy: [ stream write: '. ' ].
  301. stream write: '}' ]
  302. !
  303. isReady
  304. ^ isReady
  305. !
  306. isReady: aPromise
  307. isReady := aPromise
  308. !
  309. javaScriptDescriptor: anObject
  310. | basicEval basicImports basicIsReady |
  311. basicEval := anObject at: 'innerEval' ifAbsent: [ nil asJavaScriptObject ].
  312. basicImports := anObject at: 'imports' ifAbsent: [ #() ].
  313. basicTransport := anObject at: 'transport' ifAbsent: [].
  314. basicIsReady := anObject at: 'isReady' ifAbsent: Promise new.
  315. self
  316. evalBlock: basicEval;
  317. imports: (self importsFromJson: basicImports)
  318. !
  319. name
  320. ^ name
  321. !
  322. name: aString
  323. name := aString
  324. !
  325. organization
  326. ^ organization
  327. !
  328. transport
  329. ^ transport ifNil: [
  330. self transport: (PackageTransport fromJson: self basicTransport).
  331. transport ]
  332. !
  333. transport: aPackageTransport
  334. transport := aPackageTransport.
  335. aPackageTransport package: self
  336. ! !
  337. !Package methodsFor: 'classes'!
  338. classes
  339. ^ self organization elements copy
  340. !
  341. setupClasses
  342. self classes do: [ :each | each initialize ]
  343. !
  344. sortedClasses
  345. "Answer all classes in the receiver, sorted by superclass/subclasses and by class name for common subclasses (Issue #143)."
  346. ^ self class sortedClasses: self classes
  347. ! !
  348. !Package methodsFor: 'converting'!
  349. importsAsJson
  350. ^ self sortedImportsAsArray collect: [ :each |
  351. each isString
  352. ifTrue: [ each ]
  353. ifFalse: [ each key, '=', each value ]]
  354. !
  355. importsFromJson: anArray
  356. "Parses array of string, eg. #('asdf' 'qwer=tyuo')
  357. into array of Strings and Associations,
  358. eg. {'asdf'. 'qwer'->'tyuo'}"
  359. ^ anArray collect: [ :each |
  360. | split |
  361. split := each tokenize: '='.
  362. split size = 1
  363. ifTrue: [ split first ]
  364. ifFalse: [ split first -> split second ]]
  365. ! !
  366. !Package methodsFor: 'dependencies'!
  367. loadDependencies
  368. "Returns list of packages that need to be loaded
  369. before loading this package."
  370. | classes packages |
  371. classes := self loadDependencyClasses.
  372. ^ (classes collect: [ :each | each package ]) asSet
  373. remove: self ifAbsent: [];
  374. yourself
  375. !
  376. loadDependencyClasses
  377. "Returns classes needed at the time of loading a package.
  378. These are all that are used to subclass
  379. and to define an extension method
  380. as well as all traits used"
  381. | starCategoryName |
  382. starCategoryName := '*', self name.
  383. ^ (self classes collect: [ :each | each superclass ]) asSet
  384. addAll: (Smalltalk classes select: [ :each |
  385. each protocols, (each theMetaClass ifNil: [ #() ] ifNotNil: [ :meta | meta protocols])
  386. includes: starCategoryName ]);
  387. addAll: (Array streamContents: [ :as | self traitCompositions valuesDo: [ :each | as write: (each collect: [ :eachTT | eachTT trait ])]]);
  388. remove: nil ifAbsent: [];
  389. yourself
  390. !
  391. traitCompositions
  392. | traitCompositions |
  393. traitCompositions := Dictionary new.
  394. self classes do: [ :each |
  395. traitCompositions at: each put: each traitComposition.
  396. each theMetaClass ifNotNil: [ :meta | traitCompositions at: meta put: meta traitComposition ] ].
  397. ^ traitCompositions reject: [ :each | each isEmpty ]
  398. ! !
  399. !Package methodsFor: 'evaluating'!
  400. eval: aString
  401. ^ evalBlock
  402. ifNotNil: [ evalBlock value: aString ]
  403. ifNil: [ Compiler eval: aString ]
  404. ! !
  405. !Package methodsFor: 'initialization'!
  406. initialize
  407. super initialize.
  408. organization := PackageOrganizer new.
  409. evalBlock := nil.
  410. dirty := nil.
  411. imports := nil.
  412. isReady := Promise new.
  413. transport := nil
  414. ! !
  415. !Package methodsFor: 'printing'!
  416. printOn: aStream
  417. super printOn: aStream.
  418. aStream
  419. nextPutAll: ' (';
  420. nextPutAll: self name;
  421. nextPutAll: ')'
  422. ! !
  423. !Package methodsFor: 'private'!
  424. basicTransport
  425. "Answer the transport literal JavaScript object as setup in the JavaScript file, if any"
  426. ^ basicTransport
  427. !
  428. sortedImportsAsArray
  429. "Answer imports sorted first by type (associations first),
  430. then by value"
  431. ^ self imports asArray
  432. sorted: [ :a :b |
  433. a isString not & b isString or: [
  434. a isString = b isString and: [
  435. a value <= b value ]]]
  436. ! !
  437. !Package methodsFor: 'testing'!
  438. isDirty
  439. ^ dirty ifNil: [ false ]
  440. !
  441. isPackage
  442. ^ true
  443. ! !
  444. !Package methodsFor: 'validation'!
  445. validateImports: aCollection
  446. aCollection do: [ :import |
  447. import isString ifFalse: [
  448. (import respondsTo: #key) ifFalse: [
  449. self error: 'Imports must be Strings or Associations' ].
  450. import key isString & import value isString ifFalse: [
  451. self error: 'Key and value must be Strings' ].
  452. (import key match: '^[a-zA-Z][a-zA-Z0-9]*$') ifFalse: [
  453. self error: 'Keys must be identifiers' ]]]
  454. ! !
  455. Package class instanceVariableNames: 'defaultCommitPathJs defaultCommitPathSt'!
  456. !Package class methodsFor: 'accessing'!
  457. named: aPackageName
  458. ^ Smalltalk
  459. packageAt: aPackageName
  460. ifAbsent: [
  461. Smalltalk createPackage: aPackageName ]
  462. !
  463. named: aPackageName ifAbsent: aBlock
  464. ^ Smalltalk packageAt: aPackageName ifAbsent: aBlock
  465. !
  466. named: aPackageName imports: anArray transport: aTransport
  467. | pkg |
  468. pkg := self named: aPackageName.
  469. pkg imports: anArray.
  470. pkg transport: aTransport.
  471. ^ pkg
  472. !
  473. named: aPackageName transport: aTransport
  474. | pkg |
  475. pkg := self named: aPackageName.
  476. pkg transport: aTransport.
  477. ^ pkg
  478. ! !
  479. !Package class methodsFor: 'instance creation'!
  480. named: aString javaScriptDescriptor: anObject
  481. | pkg |
  482. pkg := Smalltalk createPackage: aString.
  483. pkg javaScriptDescriptor: anObject.
  484. ^ pkg
  485. !
  486. new: aString
  487. ^ Package new
  488. name: aString;
  489. yourself
  490. ! !
  491. !Package class methodsFor: 'sorting'!
  492. sortedClasses: classes
  493. "Answer classes, sorted by superclass/subclasses and by class name for common subclasses (Issue #143)"
  494. | children others nodes expandedClasses |
  495. children := #().
  496. others := #().
  497. classes do: [ :each |
  498. (classes includes: each superclass)
  499. ifFalse: [ children add: each ]
  500. ifTrue: [ others add: each ]].
  501. nodes := children collect: [ :each |
  502. ClassSorterNode on: each classes: others level: 0 ].
  503. nodes := nodes sorted: [ :a :b | a theClass name <= b theClass name ].
  504. expandedClasses := Array new.
  505. nodes do: [ :aNode |
  506. aNode traverseClassesWith: expandedClasses ].
  507. ^ expandedClasses
  508. ! !
  509. Object subclass: #PackageStateObserver
  510. instanceVariableNames: ''
  511. package: 'Kernel-Infrastructure'!
  512. !PackageStateObserver commentStamp!
  513. My current instance listens for any changes in the system that might affect the state of a package (being dirty).!
  514. !PackageStateObserver methodsFor: 'accessing'!
  515. announcer
  516. ^ SystemAnnouncer current
  517. ! !
  518. !PackageStateObserver methodsFor: 'actions'!
  519. observeSystem
  520. self announcer
  521. on: PackageAdded
  522. send: #onPackageAdded:
  523. to: self;
  524. on: ClassAnnouncement
  525. send: #onClassModification:
  526. to: self;
  527. on: MethodAnnouncement
  528. send: #onMethodModification:
  529. to: self;
  530. on: ProtocolAnnouncement
  531. send: #onProtocolModification:
  532. to: self
  533. ! !
  534. !PackageStateObserver methodsFor: 'reactions'!
  535. onClassModification: anAnnouncement
  536. anAnnouncement theClass ifNotNil: [ :theClass | theClass package beDirty ]
  537. !
  538. onMethodModification: anAnnouncement
  539. anAnnouncement method package ifNotNil: [ :package | package beDirty ]
  540. !
  541. onPackageAdded: anAnnouncement
  542. anAnnouncement package beDirty
  543. !
  544. onProtocolModification: anAnnouncement
  545. anAnnouncement package ifNotNil: [ :package | package beDirty ]
  546. ! !
  547. PackageStateObserver class instanceVariableNames: 'current'!
  548. !PackageStateObserver class methodsFor: 'accessing'!
  549. current
  550. ^ current ifNil: [ current := self new ]
  551. ! !
  552. !PackageStateObserver class methodsFor: 'initialization'!
  553. initialize
  554. self current observeSystem
  555. ! !
  556. Error subclass: #ParseError
  557. instanceVariableNames: ''
  558. package: 'Kernel-Infrastructure'!
  559. !ParseError commentStamp!
  560. Instance of ParseError are signaled on any parsing error.
  561. See `Smalltalk >> #parse:`!
  562. Object subclass: #Setting
  563. instanceVariableNames: 'key value defaultValue'
  564. package: 'Kernel-Infrastructure'!
  565. !Setting commentStamp!
  566. I represent a setting **stored** at `Smalltalk settings`.
  567. In the current implementation, `Smalltalk settings` is an object persisted in the localStorage.
  568. ## API
  569. A `Setting` value can be read using `value` and set using `value:`.
  570. Settings are accessed with `'key' asSetting` or `'key' asSettingIfAbsent: aDefaultValue`.
  571. To read the value of a setting you can also use the convenience:
  572. `theValueSet := 'any.characteristic' settingValue`
  573. or with a default using:
  574. `theEnsuredValueSet := 'any.characteristic' settingValueIfAbsent: true`!
  575. !Setting methodsFor: 'accessing'!
  576. defaultValue
  577. ^ defaultValue
  578. !
  579. defaultValue: aStringifiableObject
  580. defaultValue := aStringifiableObject
  581. !
  582. key
  583. ^ key
  584. !
  585. key: aString
  586. key := aString
  587. !
  588. value
  589. ^ Smalltalk settings at: self key ifAbsent: [ self defaultValue ]
  590. !
  591. value: aStringifiableObject
  592. ^ Smalltalk settings at: self key put: aStringifiableObject
  593. ! !
  594. !Setting class methodsFor: 'instance creation'!
  595. at: aString ifAbsent: aDefaultValue
  596. ^ super new
  597. key: aString;
  598. defaultValue: aDefaultValue;
  599. yourself
  600. !
  601. new
  602. self shouldNotImplement
  603. ! !
  604. Object subclass: #SmalltalkImage
  605. instanceVariableNames: 'globalJsVariables packageDictionary'
  606. package: 'Kernel-Infrastructure'!
  607. !SmalltalkImage commentStamp!
  608. I represent the Smalltalk system, wrapping
  609. operations of variable `$core` declared in `base/boot.js`.
  610. ## API
  611. I have only one instance, accessed with global variable `Smalltalk`.
  612. ## Classes
  613. Classes can be accessed using the following methods:
  614. - `#classes` answers the full list of Smalltalk classes in the system
  615. - `#globals #at:` answers a specific global (usually, a class) or `nil`
  616. ## Packages
  617. Packages can be accessed using the following methods:
  618. - `#packages` answers the full list of packages
  619. - `#packageAt:` answers a specific package or `nil`
  620. ## Parsing
  621. The `#parse:` method is used to parse Amber source code.
  622. It requires the `Compiler` package and the `base/parser.js` parser file in order to work.!
  623. !SmalltalkImage methodsFor: 'accessing'!
  624. cancelOptOut: anObject
  625. "A Smalltalk object has a 'a$cls' property.
  626. If this property is shadowed for anObject by optOut:,
  627. the object is treated as plain JS object.
  628. This removes the shadow and anObject is Smalltalk object
  629. again if it was before."
  630. <inlineJS: 'delete anObject.klass; delete anObject.a$cls;'>
  631. !
  632. core
  633. <inlineJS: 'return $core'>
  634. !
  635. globals
  636. <inlineJS: 'return $globals'>
  637. !
  638. includesKey: aKey
  639. <inlineJS: 'return $core.hasOwnProperty(aKey)'>
  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.klass = null; anObject.a$cls = null'>
  646. !
  647. parse: aString
  648. | result |
  649. [ result := self basicParse: aString ]
  650. tryCatch: [ :ex | (self parseError: ex parsing: aString) signal ].
  651. ^ result
  652. source: aString;
  653. yourself
  654. !
  655. pseudoVariableNames
  656. ^ #('self' 'super' 'nil' 'true' 'false' 'thisContext')
  657. !
  658. readJSObject: anObject
  659. <inlineJS: 'return $core.readJSObject(anObject)'>
  660. !
  661. reservedWords
  662. ^ #(
  663. "http://www.ecma-international.org/ecma-262/6.0/#sec-keywords"
  664. break case catch class const continue debugger
  665. default delete do else export extends finally
  666. for function if import in instanceof new
  667. return super switch this throw try typeof
  668. var void while with yield
  669. "in strict mode"
  670. let static
  671. "Amber protected words: these should not be compiled as-is when in code"
  672. arguments
  673. "http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words"
  674. await enum
  675. "in strict mode"
  676. implements interface package private protected public
  677. )
  678. !
  679. settings
  680. ^ SmalltalkSettings
  681. !
  682. version
  683. "Answer the version string of Amber"
  684. ^ '0.23.0-pre'
  685. ! !
  686. !SmalltalkImage methodsFor: 'accessing amd'!
  687. amdRequire
  688. ^ self core at: 'amdRequire'
  689. !
  690. defaultAmdNamespace
  691. ^ 'transport.defaultAmdNamespace' settingValue
  692. !
  693. defaultAmdNamespace: aString
  694. 'transport.defaultAmdNamespace' settingValue: aString
  695. ! !
  696. !SmalltalkImage methodsFor: 'classes'!
  697. classes
  698. ^ self core traitsOrClasses copy
  699. !
  700. removeClass: aClass
  701. aClass isMetaclass ifTrue: [ self error: aClass asString, ' is a Metaclass and cannot be removed!!' ].
  702. aClass allSubclassesDo: [ :subclass | self error: aClass name, ' has a subclass: ', subclass name ].
  703. aClass traitUsers ifNotEmpty: [ self error: aClass name, ' has trait users.' ].
  704. self deleteClass: aClass.
  705. aClass setTraitComposition: #().
  706. aClass theMetaClass ifNotNil: [ :meta | meta setTraitComposition: #() ].
  707. SystemAnnouncer current
  708. announce: (ClassRemoved new
  709. theClass: aClass;
  710. yourself)
  711. ! !
  712. !SmalltalkImage methodsFor: 'error handling'!
  713. asSmalltalkException: anObject
  714. "A JavaScript exception may be thrown.
  715. We then need to convert it back to a Smalltalk object"
  716. ^ ((self isSmalltalkObject: anObject) and: [ anObject isKindOf: Error ])
  717. ifTrue: [ anObject ]
  718. ifFalse: [ JavaScriptException on: anObject ]
  719. !
  720. parseError: anException parsing: aString
  721. (anException basicAt: 'location')
  722. ifNil: [ ^ anException pass ]
  723. ifNotNil: [ :loc |
  724. ^ ParseError new
  725. messageText:
  726. 'Parse error on line ', loc start line ,
  727. ' column ' , loc start column ,
  728. ' : Unexpected character ', (anException basicAt: 'found');
  729. yourself ]
  730. ! !
  731. !SmalltalkImage methodsFor: 'globals'!
  732. addGlobalJsVariable: aString
  733. self globalJsVariables add: aString
  734. !
  735. deleteGlobalJsVariable: aString
  736. self globalJsVariables remove: aString ifAbsent:[]
  737. !
  738. globalJsVariables
  739. ^ globalJsVariables ifNil: [
  740. globalJsVariables := #(window document process global) ]
  741. ! !
  742. !SmalltalkImage methodsFor: 'image'!
  743. postLoad
  744. ^ self adoptPackageDescriptors then: [ :pkgs |
  745. | classes |
  746. pkgs do: #beClean.
  747. classes := Smalltalk classes select:
  748. [ :each | pkgs includes: each package ].
  749. classes do: [ :each |
  750. each = self class ifFalse: [ each initialize ] ].
  751. self sweepPackageDescriptors: pkgs ]
  752. ! !
  753. !SmalltalkImage methodsFor: 'packages'!
  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. basicParse: aString
  803. ^ SmalltalkParser parse: aString
  804. !
  805. deleteClass: aClass
  806. "Deletes a class by deleting its binding only. Use #removeClass instead"
  807. <inlineJS: '$core.removeClass(aClass)'>
  808. !
  809. sweepPackageDescriptors: pkgs
  810. | pd |
  811. pd := self core packageDescriptors.
  812. pkgs do: [ :each | pd removeKey: each name ]
  813. !
  814. tryAdoptPackageDescriptorsBeyond: aSet
  815. | original |
  816. original := aSet copy.
  817. self core packageDescriptors keysAndValuesDo: [ :key :value |
  818. aSet add: (Package named: key javaScriptDescriptor: value) ].
  819. ^ (aSet allSatisfy: [ :each | original includes: each ])
  820. ifFalse: [ (Promise all: (aSet collect: #isReady)) then: [ self tryAdoptPackageDescriptorsBeyond: aSet ] ]
  821. ifTrue: [ Promise value: aSet ]
  822. ! !
  823. !SmalltalkImage methodsFor: 'testing'!
  824. existsJsGlobal: aString
  825. self deprecatedAPI: 'Use Platform >> includesGlobal: instead'.
  826. ^ Platform includesGlobal: aString
  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 instanceVariableNames: '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: {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. ! !