Kernel-Infrastructure.st 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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
  493. imports: anArray;
  494. transport: aTransport;
  495. beDirty.
  496. ^ pkg
  497. !
  498. named: aPackageName transport: aTransport
  499. | pkg |
  500. pkg := self named: aPackageName.
  501. pkg transport: aTransport; beDirty.
  502. ^ pkg
  503. ! !
  504. !Package class methodsFor: 'instance creation'!
  505. named: aString javaScriptDescriptor: anObject
  506. | pkg |
  507. pkg := Smalltalk createPackage: aString.
  508. pkg javaScriptDescriptor: anObject.
  509. ^ pkg
  510. !
  511. new: aString
  512. ^ Package new
  513. name: aString;
  514. yourself
  515. ! !
  516. !Package class methodsFor: 'sorting'!
  517. sortedClasses: classes
  518. ^ Array streamContents: [ :stream | stream << (ClassBuilder sortClasses: classes) ]
  519. ! !
  520. Object subclass: #PackageStateObserver
  521. slots: {}
  522. package: 'Kernel-Infrastructure'!
  523. !PackageStateObserver commentStamp!
  524. My current instance listens for any changes in the system that might affect the state of a package (being dirty).!
  525. !PackageStateObserver methodsFor: 'accessing'!
  526. announcer
  527. ^ SystemAnnouncer current
  528. ! !
  529. !PackageStateObserver methodsFor: 'actions'!
  530. observeSystem
  531. self announcer
  532. on: PackageAdded
  533. send: #onPackageAdded:
  534. to: self;
  535. on: ClassAnnouncement
  536. send: #onClassModification:
  537. to: self;
  538. on: MethodAnnouncement
  539. send: #onMethodModification:
  540. to: self
  541. ! !
  542. !PackageStateObserver methodsFor: 'reactions'!
  543. onClassModification: anAnnouncement
  544. anAnnouncement theClass ifNotNil: [ :theClass | theClass package beDirty ]
  545. !
  546. onMethodModification: anAnnouncement
  547. anAnnouncement method package ifNotNil: [ :package | package beDirty ]
  548. !
  549. onPackageAdded: anAnnouncement
  550. anAnnouncement package beDirty
  551. ! !
  552. PackageStateObserver class slots: {#current}!
  553. !PackageStateObserver class methodsFor: 'accessing'!
  554. current
  555. ^ current ifNil: [ current := self new ]
  556. ! !
  557. !PackageStateObserver class methodsFor: 'initialization'!
  558. initialize
  559. self current observeSystem
  560. ! !
  561. Object subclass: #Setting
  562. slots: {#key. #defaultValue}
  563. package: 'Kernel-Infrastructure'!
  564. !Setting commentStamp!
  565. I represent a setting **stored** at `Smalltalk settings`.
  566. In the current implementation, `Smalltalk settings` is an object persisted in the localStorage.
  567. ## API
  568. A `Setting` value can be read using `value` and set using `value:`.
  569. Settings are accessed with `'key' asSetting` or `'key' asSettingIfAbsent: aDefaultValue`.
  570. To read the value of a setting you can also use the convenience:
  571. `theValueSet := 'any.characteristic' settingValue`
  572. or with a default using:
  573. `theEnsuredValueSet := 'any.characteristic' settingValueIfAbsent: true`!
  574. !Setting methodsFor: 'accessing'!
  575. defaultValue
  576. ^ defaultValue
  577. !
  578. defaultValue: aStringifiableObject
  579. defaultValue := aStringifiableObject
  580. !
  581. key
  582. ^ key
  583. !
  584. key: aString
  585. key := aString
  586. !
  587. value
  588. ^ Smalltalk settings at: self key ifAbsent: [ self defaultValue ]
  589. !
  590. value: aStringifiableObject
  591. ^ Smalltalk settings at: self key put: aStringifiableObject
  592. ! !
  593. !Setting class methodsFor: 'instance creation'!
  594. at: aString ifAbsent: aDefaultValue
  595. ^ super new
  596. key: aString;
  597. defaultValue: aDefaultValue;
  598. yourself
  599. !
  600. new
  601. self shouldNotImplement
  602. ! !
  603. Object subclass: #SmalltalkImage
  604. slots: {#globalJsVariables. #packageDictionary}
  605. package: 'Kernel-Infrastructure'!
  606. !SmalltalkImage commentStamp!
  607. I represent the Smalltalk system, wrapping
  608. operations of variable `$core` declared in `base/boot.js`.
  609. ## API
  610. I have only one instance, accessed with global variable `Smalltalk`.
  611. ## Classes
  612. Classes can be accessed using the following methods:
  613. - `#classes` answers the full list of Smalltalk classes in the system
  614. - `#globals #at:` answers a specific global (usually, a class) or `nil`
  615. ## Packages
  616. Packages can be accessed using the following methods:
  617. - `#packages` answers the full list of packages
  618. - `#packageAt:` answers a specific package or `nil`
  619. ## Parsing
  620. The `#parse:` method is used to parse Amber source code.
  621. It requires the `Compiler` package and the `base/parser.js` parser file in order to work.!
  622. !SmalltalkImage methodsFor: 'accessing'!
  623. cancelOptOut: anObject
  624. "A Smalltalk object has a 'a$cls' property.
  625. If this property is shadowed for anObject by optOut:,
  626. the object is treated as plain JS object.
  627. This removes the shadow and anObject is Smalltalk object
  628. again if it was before."
  629. <inlineJS: 'delete anObject.a$cls;'>
  630. !
  631. core
  632. <inlineJS: 'return $core'>
  633. !
  634. globals
  635. <inlineJS: 'return $globals'>
  636. !
  637. optOut: anObject
  638. "A Smalltalk object has a 'a$cls' property.
  639. This shadows the property for anObject.
  640. The object is treated as plain JS object following this."
  641. <inlineJS: 'anObject.a$cls = null'>
  642. !
  643. parse: aString
  644. ^ Compiler new parse: aString
  645. !
  646. pseudoVariableNames
  647. ^ Compiler pseudoVariableNames
  648. !
  649. readJSObject: anObject
  650. <inlineJS: 'return $core.readJSObject(anObject)'>
  651. !
  652. reservedWords
  653. ^ #(
  654. "http://www.ecma-international.org/ecma-262/6.0/#sec-keywords"
  655. break case catch class const continue debugger
  656. default delete do else export extends finally
  657. for function if import in instanceof new
  658. return super switch this throw try typeof
  659. var void while with yield
  660. "in strict mode"
  661. let static
  662. "Amber protected words: these should not be compiled as-is when in code"
  663. arguments
  664. "http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words"
  665. await enum
  666. "in strict mode"
  667. implements interface package private protected public
  668. )
  669. !
  670. settings
  671. ^ SmalltalkSettings
  672. !
  673. version
  674. "Answer the version string of Amber"
  675. ^ '0.29.3-pre'
  676. ! !
  677. !SmalltalkImage methodsFor: 'accessing amd'!
  678. amdRequire
  679. ^ self core at: 'amdRequire'
  680. !
  681. defaultAmdNamespace
  682. ^ 'transport.defaultAmdNamespace' settingValue
  683. !
  684. defaultAmdNamespace: aString
  685. 'transport.defaultAmdNamespace' settingValue: aString
  686. ! !
  687. !SmalltalkImage methodsFor: 'classes'!
  688. classes
  689. ^ self core traitsOrClasses copy
  690. !
  691. removeClass: aClass
  692. aClass isMetaclass ifTrue: [ self error: aClass asString, ' is a Metaclass and cannot be removed!!' ].
  693. aClass allSubclassesDo: [ :subclass | self error: aClass name, ' has a subclass: ', subclass name ].
  694. aClass traitUsers ifNotEmpty: [ self error: aClass name, ' has trait users.' ].
  695. self deleteClass: aClass.
  696. aClass includingPossibleMetaDo: [ :each | each setTraitComposition: #() ].
  697. SystemAnnouncer current
  698. announce: (ClassRemoved new
  699. theClass: aClass;
  700. yourself)
  701. ! !
  702. !SmalltalkImage methodsFor: 'error handling'!
  703. asSmalltalkException: anObject
  704. "A JavaScript exception may be thrown.
  705. We then need to convert it back to a Smalltalk object"
  706. ^ anObject
  707. ifNil: [ [ self error: 'Error: nil' ] on: Error do: [ :e | e ] ]
  708. ifNotNil: [
  709. (self isError: anObject)
  710. ifTrue: [ anObject ]
  711. ifFalse: [ JavaScriptException on: anObject ] ]
  712. !
  713. try: actionBlock ifTrue: aBlock catch: anotherBlock
  714. "Similar to BlockClosure >> tryifTrue:catch:, but
  715. converts all JS exceptions to JavaScriptException instances."
  716. | smalltalkError |
  717. ^ actionBlock
  718. tryIfTrue: [ :error |
  719. smalltalkError := self asSmalltalkException: error.
  720. aBlock value: smalltalkError ]
  721. catch: [ anotherBlock value: smalltalkError ]
  722. ! !
  723. !SmalltalkImage methodsFor: 'globals'!
  724. addGlobalJsVariable: aString
  725. self globalJsVariables add: aString
  726. !
  727. deleteGlobalJsVariable: aString
  728. self globalJsVariables remove: aString ifAbsent:[]
  729. !
  730. globalJsVariables
  731. ^ globalJsVariables ifNil: [
  732. globalJsVariables := #(window document process global) ]
  733. ! !
  734. !SmalltalkImage methodsFor: 'image'!
  735. postFailedLoad: aPackage
  736. | keys descriptors |
  737. Smalltalk removePackage: aPackage name.
  738. keys := Set new.
  739. descriptors := self core packageDescriptors.
  740. descriptors keysAndValuesDo: [ :key :value | keys add: key ].
  741. keys do: [ :each |
  742. Smalltalk removePackage: each.
  743. descriptors removeKey: each ]
  744. !
  745. postLoad
  746. ^ self adoptPackageDescriptors then: [ :pkgs |
  747. | classes |
  748. pkgs do: #beClean.
  749. classes := Smalltalk classes select:
  750. [ :each | pkgs includes: each package ].
  751. classes do: [ :each |
  752. each = self class ifFalse: [ each initialize ] ].
  753. self sweepPackageDescriptors: pkgs ]
  754. ! !
  755. !SmalltalkImage methodsFor: 'packages'!
  756. beClean
  757. "Marks all packages clean."
  758. self packages do: #beClean
  759. !
  760. createPackage: packageName
  761. | package announcement |
  762. package := self basicCreatePackage: packageName.
  763. announcement := PackageAdded new
  764. package: package;
  765. yourself.
  766. SystemAnnouncer current announce: announcement.
  767. ^ package
  768. !
  769. packageAt: packageName ifAbsent: aBlock
  770. ^ self packageDictionary at: packageName ifAbsent: aBlock
  771. !
  772. packageAt: packageName ifPresent: aBlock
  773. ^ self packageDictionary at: packageName ifPresent: aBlock
  774. !
  775. packageDictionary
  776. ^ packageDictionary ifNil: [ packageDictionary := Dictionary new ]
  777. !
  778. packages
  779. "Return all Package instances in the system."
  780. ^ self packageDictionary values copy
  781. !
  782. removePackage: packageName
  783. "Removes a package and all its classes."
  784. | pkg |
  785. pkg := self packageAt: packageName ifAbsent: [ self error: 'Missing package: ', packageName ].
  786. pkg classes do: [ :each |
  787. self removeClass: each ].
  788. self packageDictionary removeKey: packageName.
  789. SystemAnnouncer current
  790. announce: (PackageRemoved new
  791. package: pkg;
  792. yourself)
  793. !
  794. renamePackage: packageName to: newName
  795. "Rename a package."
  796. | pkg |
  797. pkg := self packageAt: packageName ifAbsent: [ self error: 'Missing package: ', packageName ].
  798. self packageAt: newName ifPresent: [ self error: 'Already exists a package called: ', newName ].
  799. pkg name: newName; beDirty.
  800. self packageDictionary
  801. at: newName put: pkg;
  802. removeKey: packageName
  803. ! !
  804. !SmalltalkImage methodsFor: 'private'!
  805. adoptPackageDescriptors
  806. ^ self tryAdoptPackageDescriptorsBeyond: Set new
  807. !
  808. basicCreatePackage: packageName
  809. "Create and bind a new bare package with given name and return it."
  810. ^ self packageDictionary at: packageName ifAbsentPut: [ Package new: packageName ]
  811. !
  812. deleteClass: aClass
  813. "Deletes a class by deleting its binding only. Use #removeClass instead"
  814. <inlineJS: '$core.removeClass(aClass)'>
  815. !
  816. sweepPackageDescriptors: pkgs
  817. | pd |
  818. pd := self core packageDescriptors.
  819. pkgs do: [ :each | pd removeKey: each name ]
  820. !
  821. tryAdoptPackageDescriptorsBeyond: aSet
  822. | original |
  823. original := aSet copy.
  824. self core packageDescriptors keysAndValuesDo: [ :key :value |
  825. aSet add: (Package named: key javaScriptDescriptor: value) ].
  826. ^ (aSet allSatisfy: [ :each | original includes: each ])
  827. ifFalse: [ (Promise all: (aSet collect: #isReady)) then: [ self tryAdoptPackageDescriptorsBeyond: aSet ] ]
  828. ifTrue: [ Promise value: aSet ]
  829. ! !
  830. !SmalltalkImage methodsFor: 'testing'!
  831. existsJsGlobal: aString
  832. self deprecatedAPI: 'Use Platform >> includesGlobal: instead'.
  833. ^ Platform includesGlobal: aString
  834. !
  835. isError: anObject
  836. ^ (self isSmalltalkObject: anObject) and: [ anObject isError ]
  837. !
  838. isSmalltalkObject: anObject
  839. "Consider anObject a Smalltalk object if it has a 'a$cls' property.
  840. Note that this may be unaccurate"
  841. <inlineJS: 'return anObject.a$cls !!= null'>
  842. ! !
  843. SmalltalkImage class slots: {#current}!
  844. !SmalltalkImage class methodsFor: 'initialization'!
  845. initialize
  846. | st |
  847. st := self current.
  848. st globals at: 'Smalltalk' put: st
  849. ! !
  850. !SmalltalkImage class methodsFor: 'instance creation'!
  851. current
  852. ^ current ifNil: [ current := super new ] ifNotNil: [ self deprecatedAPI. current ]
  853. !
  854. new
  855. self shouldNotImplement
  856. ! !
  857. JSObjectProxy setTraitComposition: {TIsInGroup. TThenable} asTraitComposition!
  858. ! !
  859. !ProtoStream methodsFor: '*Kernel-Infrastructure'!
  860. nextPutJSObject: aJSObject
  861. self nextPut: aJSObject
  862. ! !
  863. !String methodsFor: '*Kernel-Infrastructure'!
  864. asJavaScriptPropertyName
  865. <inlineJS: 'return $core.st2prop(self)'>
  866. !
  867. asSetting
  868. "Answer aSetting dedicated to locally store a value using this string as key.
  869. Nil will be the default value."
  870. ^ Setting at: self ifAbsent: nil
  871. !
  872. asSettingIfAbsent: aDefaultValue
  873. "Answer aSetting dedicated to locally store a value using this string as key.
  874. Make this setting to have aDefaultValue."
  875. ^ Setting at: self ifAbsent: aDefaultValue
  876. !
  877. settingValue
  878. ^ self asSetting value
  879. !
  880. settingValue: aValue
  881. "Sets the value of the setting that will be locally stored using this string as key.
  882. Note that aValue can be any object that can be stringifyed"
  883. ^ self asSetting value: aValue
  884. !
  885. settingValueIfAbsent: aDefaultValue
  886. "Answer the value of the locally stored setting using this string as key.
  887. Use aDefaultValue in case no setting is found"
  888. ^ (self asSettingIfAbsent: aDefaultValue) value
  889. ! !