1
0

Kernel-Objects.st 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. Smalltalk current createPackage: 'Kernel-Objects' properties: #{}!
  2. nil subclass: #Object
  3. instanceVariableNames: ''
  4. package: 'Kernel-Objects'!
  5. !Object commentStamp!
  6. *Object is the root of the Smalltalk class system*. All classes in the system are subclasses of Object.
  7. Object provides default behavior common to all normal objects, such as:
  8. - access
  9. - copying
  10. - comparison
  11. - error handling
  12. - message sending
  13. - reflection
  14. Also utility messages that all objects should respond to are defined here.
  15. Object has no instance variable.
  16. ##Access
  17. Instance variables can be accessed with `#instVarAt:` and `#instVarAt:put:`. `Object >> instanceVariableNames` answers a collection of all instance variable names.
  18. Accessing JavaScript properties of an object is done through `#basicAt:`, `#basicAt:put:` and `basicDelete:`.
  19. ##Copying
  20. Copying an object is handled by `#copy` and `#deepCopy`. The first one performs a shallow copy of the receiver, while the second one performs a deep copy.
  21. The hook method `#postCopy` can be overriden in subclasses to copy fields as necessary to complete the full copy. It will be sent by the copy of the receiver.
  22. ##Comparison
  23. Objects understand equality `#=` and identity `#==` comparison.
  24. ##Error handling
  25. - `#halt` is the typical message to use for inserting breakpoints during debugging.
  26. - `#error:` throws a generic error exception
  27. - `#doesNotUnderstand:` handles the fact that there was an attempt to send the given message to the receiver but the receiver does not understand this message.
  28. Overriding this message can be useful to implement proxies for example.!
  29. !Object methodsFor: 'accessing'!
  30. basicAt: aString
  31. <return self[aString]>
  32. !
  33. basicAt: aString put: anObject
  34. <return self[aString] = anObject>
  35. !
  36. basicDelete: aString
  37. <delete self[aString]; return aString>
  38. !
  39. class
  40. <return self.klass>
  41. !
  42. identityHash
  43. <return self.identityHash || (self.identityHash = smalltalk.nextId());>
  44. !
  45. instVarAt: aSymbol
  46. | varname |
  47. varname := aSymbol asString.
  48. <return self['@'+varname]>
  49. !
  50. instVarAt: aSymbol put: anObject
  51. | varname |
  52. varname := aSymbol asString.
  53. <self['@' + varname] = anObject>
  54. !
  55. size
  56. self error: 'Object not indexable'
  57. !
  58. yourself
  59. ^self
  60. ! !
  61. !Object methodsFor: 'comparing'!
  62. = anObject
  63. ^self == anObject
  64. !
  65. == anObject
  66. ^self identityHash = anObject identityHash
  67. !
  68. ~= anObject
  69. ^(self = anObject) = false
  70. !
  71. ~~ anObject
  72. ^(self == anObject) = false
  73. ! !
  74. !Object methodsFor: 'converting'!
  75. -> anObject
  76. ^Association key: self value: anObject
  77. !
  78. asJSON
  79. | variables |
  80. variables := HashedCollection new.
  81. self class allInstanceVariableNames do: [:each |
  82. variables at: each put: (self instVarAt: each) asJSON].
  83. ^variables
  84. !
  85. asJSONString
  86. ^JSON stringify: self asJSON
  87. !
  88. asJavascript
  89. ^self asString
  90. !
  91. asString
  92. ^self printString
  93. ! !
  94. !Object methodsFor: 'copying'!
  95. copy
  96. ^self shallowCopy postCopy
  97. !
  98. deepCopy
  99. <
  100. var copy = self.klass._new();
  101. for(var i in self) {
  102. if(/^@.+/.test(i)) {
  103. copy[i] = self[i]._deepCopy();
  104. }
  105. }
  106. return copy;
  107. >
  108. !
  109. postCopy
  110. !
  111. shallowCopy
  112. <
  113. var copy = self.klass._new();
  114. for(var i in self) {
  115. if(/^@.+/.test(i)) {
  116. copy[i] = self[i];
  117. }
  118. }
  119. return copy;
  120. >
  121. ! !
  122. !Object methodsFor: 'error handling'!
  123. deprecatedAPI
  124. "Just a simple way to deprecate methods.
  125. #deprecatedAPI is in the 'error handling' protocol even if it doesn't throw an error,
  126. but it could in the future."
  127. console warn: thisContext home asString, ' is deprecated!! (in ', thisContext home home asString, ')'
  128. !
  129. doesNotUnderstand: aMessage
  130. MessageNotUnderstood new
  131. receiver: self;
  132. message: aMessage;
  133. signal
  134. !
  135. error: aString
  136. Error signal: aString
  137. !
  138. halt
  139. self error: 'Halt encountered'
  140. !
  141. shouldNotImplement
  142. self error: 'This method should not be implemented in ', self class name
  143. !
  144. subclassResponsibility
  145. self error: 'This method is a responsibility of a subclass'
  146. !
  147. try: aBlock catch: anotherBlock
  148. <try{result = aBlock()} catch(e) {result = anotherBlock(e)};
  149. return result;>
  150. ! !
  151. !Object methodsFor: 'initialization'!
  152. initialize
  153. ! !
  154. !Object methodsFor: 'message handling'!
  155. basicPerform: aSymbol
  156. ^self basicPerform: aSymbol withArguments: #()
  157. !
  158. basicPerform: aSymbol withArguments: aCollection
  159. <return self[aSymbol].apply(self, aCollection);>
  160. !
  161. perform: aSymbol
  162. ^self perform: aSymbol withArguments: #()
  163. !
  164. perform: aSymbol withArguments: aCollection
  165. | selector |
  166. selector := aSymbol asSelector.
  167. <return smalltalk.send(self, selector, aCollection)>
  168. ! !
  169. !Object methodsFor: 'printing'!
  170. log: aString block: aBlock
  171. | result |
  172. console log: aString, ' time: ', (Date millisecondsToRun: [result := aBlock value]) printString.
  173. ^result
  174. !
  175. printNl
  176. <console.log(self)>
  177. !
  178. printString
  179. ^'a ', self class name
  180. !
  181. storeOn: aStream
  182. aStream nextPutAll: self printString
  183. !
  184. storeString
  185. "Answer a String representation of the receiver from which the receiver
  186. can be reconstructed."
  187. ^ String streamContents: [:s | self storeOn: s]
  188. ! !
  189. !Object methodsFor: 'testing'!
  190. ifNil: aBlock
  191. "inlined in the Compiler"
  192. ^self
  193. !
  194. ifNil: aBlock ifNotNil: anotherBlock
  195. "inlined in the Compiler"
  196. ^anotherBlock value
  197. !
  198. ifNotNil: aBlock
  199. "inlined in the Compiler"
  200. ^aBlock value
  201. !
  202. ifNotNil: aBlock ifNil: anotherBlock
  203. "inlined in the Compiler"
  204. ^aBlock value
  205. !
  206. isClass
  207. ^false
  208. !
  209. isKindOf: aClass
  210. ^(self isMemberOf: aClass)
  211. ifTrue: [true]
  212. ifFalse: [self class inheritsFrom: aClass]
  213. !
  214. isMemberOf: aClass
  215. ^self class = aClass
  216. !
  217. isMetaclass
  218. ^false
  219. !
  220. isNil
  221. ^false
  222. !
  223. isNumber
  224. ^false
  225. !
  226. isParseFailure
  227. ^false
  228. !
  229. isString
  230. ^false
  231. !
  232. isSymbol
  233. ^false
  234. !
  235. notNil
  236. ^self isNil not
  237. !
  238. respondsTo: aSelector
  239. ^self class canUnderstand: aSelector
  240. ! !
  241. !Object class methodsFor: 'initialization'!
  242. initialize
  243. "no op"
  244. ! !
  245. Object subclass: #Boolean
  246. instanceVariableNames: ''
  247. package: 'Kernel-Objects'!
  248. !Boolean commentStamp!
  249. Boolean wraps the JavaScript `Boolean()` constructor. The `true` and `false` objects are the JavaScript boolean objects.
  250. Boolean defines the protocol for logic testing operations and conditional control structures for the logical values.
  251. Boolean instances are weither `true` or `false`.!
  252. !Boolean methodsFor: 'comparing'!
  253. = aBoolean
  254. aBoolean class = self class ifFalse: [^false].
  255. <return Boolean(self == true) == aBoolean>
  256. ! !
  257. !Boolean methodsFor: 'controlling'!
  258. & aBoolean
  259. <
  260. if(self == true) {
  261. return aBoolean;
  262. } else {
  263. return false;
  264. }
  265. >
  266. !
  267. and: aBlock
  268. ^self = true
  269. ifTrue: aBlock
  270. ifFalse: [false]
  271. !
  272. ifFalse: aBlock
  273. "inlined in the Compiler"
  274. ^self ifTrue: [] ifFalse: aBlock
  275. !
  276. ifFalse: aBlock ifTrue: anotherBlock
  277. "inlined in the Compiler"
  278. ^self ifTrue: anotherBlock ifFalse: aBlock
  279. !
  280. ifTrue: aBlock
  281. "inlined in the Compiler"
  282. ^self ifTrue: aBlock ifFalse: []
  283. !
  284. ifTrue: aBlock ifFalse: anotherBlock
  285. "inlined in the Compiler"
  286. <
  287. if(self == true) {
  288. return aBlock();
  289. } else {
  290. return anotherBlock();
  291. }
  292. >
  293. !
  294. not
  295. ^self = false
  296. !
  297. or: aBlock
  298. ^self = true
  299. ifTrue: [true]
  300. ifFalse: aBlock
  301. !
  302. | aBoolean
  303. <
  304. if(self == true) {
  305. return true;
  306. } else {
  307. return aBoolean;
  308. }
  309. >
  310. ! !
  311. !Boolean methodsFor: 'converting'!
  312. asJSON
  313. ^self
  314. ! !
  315. !Boolean methodsFor: 'copying'!
  316. deepCopy
  317. ^self
  318. !
  319. shallowCopy
  320. ^self
  321. ! !
  322. !Boolean methodsFor: 'printing'!
  323. printString
  324. <return self.toString()>
  325. ! !
  326. Object subclass: #Date
  327. instanceVariableNames: ''
  328. package: 'Kernel-Objects'!
  329. !Date commentStamp!
  330. The Date class is used to work with dates and times. Therefore `Date today` and `Date now` are both valid in
  331. Amber and answer the same date object.
  332. Date wraps the `Date()` JavaScript constructor, and Smalltalk date objects are JavaScript date objects.!
  333. !Date methodsFor: 'accessing'!
  334. day
  335. ^self dayOfWeek
  336. !
  337. day: aNumber
  338. self day: aNumber
  339. !
  340. dayOfMonth
  341. <return self.getDate()>
  342. !
  343. dayOfMonth: aNumber
  344. <self.setDate(aNumber)>
  345. !
  346. dayOfWeek
  347. <return self.getDay() + 1>
  348. !
  349. dayOfWeek: aNumber
  350. <return self.setDay(aNumber - 1)>
  351. !
  352. hours
  353. <return self.getHours()>
  354. !
  355. hours: aNumber
  356. <self.setHours(aNumber)>
  357. !
  358. milliseconds
  359. <return self.getMilliseconds()>
  360. !
  361. milliseconds: aNumber
  362. <self.setMilliseconds(aNumber)>
  363. !
  364. minutes
  365. <return self.getMinutes()>
  366. !
  367. minutes: aNumber
  368. <self.setMinutes(aNumber)>
  369. !
  370. month
  371. <return self.getMonth() + 1>
  372. !
  373. month: aNumber
  374. <self.setMonth(aNumber - 1)>
  375. !
  376. seconds
  377. <return self.getSeconds()>
  378. !
  379. seconds: aNumber
  380. <self.setSeconds(aNumber)>
  381. !
  382. time
  383. <return self.getTime()>
  384. !
  385. time: aNumber
  386. <self.setTime(aNumber)>
  387. !
  388. year
  389. <return self.getFullYear()>
  390. !
  391. year: aNumber
  392. <self.setFullYear(aNumber)>
  393. ! !
  394. !Date methodsFor: 'arithmetic'!
  395. + aDate
  396. <return self + aDate>
  397. !
  398. - aDate
  399. <return self - aDate>
  400. ! !
  401. !Date methodsFor: 'comparing'!
  402. < aDate
  403. <return self < aDate>
  404. !
  405. <= aDate
  406. <return self <= aDate>
  407. !
  408. > aDate
  409. <return self >> aDate>
  410. !
  411. >= aDate
  412. <return self >>= aDate>
  413. ! !
  414. !Date methodsFor: 'converting'!
  415. asDateString
  416. <return self.toDateString()>
  417. !
  418. asLocaleString
  419. <return self.toLocaleString()>
  420. !
  421. asMilliseconds
  422. ^self time
  423. !
  424. asNumber
  425. ^self asMilliseconds
  426. !
  427. asString
  428. <return self.toString()>
  429. !
  430. asTimeString
  431. <return self.toTimeString()>
  432. ! !
  433. !Date methodsFor: 'printing'!
  434. printString
  435. ^self asString
  436. ! !
  437. !Date class methodsFor: 'instance creation'!
  438. fromMilliseconds: aNumber
  439. ^self new: aNumber
  440. !
  441. fromSeconds: aNumber
  442. ^self fromMilliseconds: aNumber * 1000
  443. !
  444. fromString: aString
  445. "Example: Date fromString('2011/04/15 00:00:00')"
  446. ^self new: aString
  447. !
  448. millisecondsToRun: aBlock
  449. | t |
  450. t := Date now.
  451. aBlock value.
  452. ^Date now - t
  453. !
  454. new: anObject
  455. <return new Date(anObject)>
  456. !
  457. now
  458. ^self today
  459. !
  460. today
  461. ^self new
  462. ! !
  463. Object subclass: #JSObjectProxy
  464. instanceVariableNames: 'jsObject'
  465. package: 'Kernel-Objects'!
  466. !JSObjectProxy commentStamp!
  467. JSObjectProxy handles sending messages to JavaScript object, therefore accessing JavaScript objects from Amber is transparent.
  468. JSOjbectProxy makes intensive use of `#doesNotUnderstand:`.
  469. ## Examples
  470. JSObjectProxy objects are instanciated by Amber when a Smalltalk message is sent to a JavaScript object.
  471. window alert: 'hello world'.
  472. window inspect.
  473. (window jQuery: 'body') append: 'hello world'
  474. Smalltalk 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.
  475. ## Message conversion rules
  476. - `someUser name` becomes `someUser.name`
  477. - `someUser name: 'John'` becomes `someUser name = "John"`
  478. - `console log: 'hello world'` becomes `console.log('hello world')`
  479. - `(window jQuery: 'foo') css: 'background' color: 'red'` becomes `window.jQuery('foo').css('background', 'red')`
  480. __Note:__ For keyword-based messages, only the first keyword is kept: `window foo: 1 bar: 2` is equivalent to `window foo: 1 baz: 2`.!
  481. !JSObjectProxy methodsFor: 'accessing'!
  482. at: aSymbol
  483. | attr |
  484. attr := aSymbol asString.
  485. <return self['@jsObject'][attr]>
  486. !
  487. at: aSymbol put: anObject
  488. | attr |
  489. attr := aSymbol asString.
  490. <self['@jsObject'][attr] = anObject>
  491. !
  492. jsObject
  493. ^jsObject
  494. !
  495. jsObject: aJSObject
  496. jsObject := aJSObject
  497. ! !
  498. !JSObjectProxy methodsFor: 'proxy'!
  499. doesNotUnderstand: aMessage
  500. | obj selector jsSelector arguments |
  501. obj := self jsObject.
  502. selector := aMessage selector.
  503. jsSelector := selector asJavaScriptSelector.
  504. arguments := aMessage arguments.
  505. <if(obj[jsSelector] !!= undefined) {return smalltalk.send(obj, jsSelector, arguments)}>.
  506. super doesNotUnderstand: aMessage
  507. !
  508. inspectOn: anInspector
  509. | variables |
  510. variables := Dictionary new.
  511. variables at: '#self' put: self jsObject.
  512. anInspector setLabel: self printString.
  513. <for(var i in self['@jsObject']) {
  514. variables._at_put_(i, self['@jsObject'][i]);
  515. }>.
  516. anInspector setVariables: variables
  517. !
  518. printString
  519. ^self jsObject toString
  520. ! !
  521. !JSObjectProxy class methodsFor: 'instance creation'!
  522. on: aJSObject
  523. ^self new
  524. jsObject: aJSObject;
  525. yourself
  526. ! !
  527. Object subclass: #Number
  528. instanceVariableNames: ''
  529. package: 'Kernel-Objects'!
  530. !Number commentStamp!
  531. Number holds the most general methods for dealing with numbers.
  532. Number is directly mapped to JavaScript Number.
  533. Most arithmetic methods like `#+` `#/` `#-` `#max:` are directly inlined into javascript.
  534. ##Enumerating
  535. A Number can be used to evaluate a Block a fixed number of times:
  536. 5 timesRepeat: [Transcript show: 'This will be printed 5 times'; cr].
  537. 1 to: 5 do: [:aNumber| Transcript show: aNumber asString; cr].
  538. 1 to: 10 by: 2 do: [:aNumber| Transcript show: aNumber asString; cr].!
  539. !Number methodsFor: 'accessing'!
  540. identityHash
  541. ^self asString, 'n'
  542. ! !
  543. !Number methodsFor: 'arithmetic'!
  544. * aNumber
  545. "Inlined in the Compiler"
  546. <return self * aNumber>
  547. !
  548. + aNumber
  549. "Inlined in the Compiler"
  550. <return self + aNumber>
  551. !
  552. - aNumber
  553. "Inlined in the Compiler"
  554. <return self - aNumber>
  555. !
  556. / aNumber
  557. "Inlined in the Compiler"
  558. <return self / aNumber>
  559. !
  560. \\ aNumber
  561. <return self % aNumber>
  562. !
  563. max: aNumber
  564. <return Math.max(self, aNumber);>
  565. !
  566. min: aNumber
  567. <return Math.min(self, aNumber);>
  568. !
  569. negated
  570. ^0 - self
  571. !
  572. sqrt
  573. <return Math.sqrt(self)>
  574. !
  575. squared
  576. ^self * self
  577. ! !
  578. !Number methodsFor: 'comparing'!
  579. < aNumber
  580. "Inlined in the Compiler"
  581. <return self < aNumber>
  582. !
  583. <= aNumber
  584. "Inlined in the Compiler"
  585. <return self <= aNumber>
  586. !
  587. = aNumber
  588. aNumber isNumber ifFalse: [^false].
  589. <return Number(self) == aNumber>
  590. !
  591. > aNumber
  592. "Inlined in the Compiler"
  593. <return self >> aNumber>
  594. !
  595. >= aNumber
  596. "Inlined in the Compiler"
  597. <return self >>= aNumber>
  598. ! !
  599. !Number methodsFor: 'converting'!
  600. @ aNumber
  601. ^Point x: self y: aNumber
  602. !
  603. asJSON
  604. ^self
  605. !
  606. asJavascript
  607. ^'(', self printString, ')'
  608. !
  609. asPoint
  610. ^Point x: self y: self
  611. !
  612. asString
  613. ^self printString
  614. !
  615. atRandom
  616. ^(Random new next * self) truncated + 1
  617. !
  618. rounded
  619. <return Math.round(self);>
  620. !
  621. to: aNumber
  622. | array first last count |
  623. first := self truncated.
  624. last := aNumber truncated + 1.
  625. count := 1.
  626. array := Array new.
  627. (last - first) timesRepeat: [
  628. array at: count put: first.
  629. count := count + 1.
  630. first := first + 1].
  631. ^array
  632. !
  633. to: stop by: step
  634. | array value pos |
  635. value := self.
  636. array := Array new.
  637. pos := 1.
  638. step = 0 ifTrue: [self error: 'step must be non-zero'].
  639. step < 0
  640. ifTrue: [[ value >= stop ] whileTrue: [
  641. array at: pos put: value.
  642. pos := pos + 1.
  643. value := value + step]]
  644. ifFalse: [[ value <= stop ] whileTrue: [
  645. array at: pos put: value.
  646. pos := pos + 1.
  647. value := value + step]].
  648. ^array
  649. !
  650. truncated
  651. |result|
  652. self >= 0
  653. ifTrue: [<result = Math.floor(self);>]
  654. ifFalse: [<result = (Math.floor(self * (-1)) * (-1));>].
  655. ^ result
  656. ! !
  657. !Number methodsFor: 'copying'!
  658. copy
  659. ^self
  660. !
  661. deepCopy
  662. ^self copy
  663. ! !
  664. !Number methodsFor: 'enumerating'!
  665. timesRepeat: aBlock
  666. | integer count |
  667. integer := self truncated.
  668. count := 1.
  669. [count > self] whileFalse: [
  670. aBlock value.
  671. count := count + 1]
  672. !
  673. to: stop by: step do: aBlock
  674. | value |
  675. value := self.
  676. step = 0 ifTrue: [self error: 'step must be non-zero'].
  677. step < 0
  678. ifTrue: [[ value >= stop ] whileTrue: [
  679. aBlock value: value.
  680. value := value + step]]
  681. ifFalse: [[ value <= stop ] whileTrue: [
  682. aBlock value: value.
  683. value := value + step]]
  684. !
  685. to: stop do: aBlock
  686. "Evaluate aBlock for each number from self to aNumber."
  687. | nextValue |
  688. nextValue := self.
  689. [nextValue <= stop]
  690. whileTrue:
  691. [aBlock value: nextValue.
  692. nextValue := nextValue + 1]
  693. ! !
  694. !Number methodsFor: 'printing'!
  695. printShowingDecimalPlaces: placesDesired
  696. <return self.toFixed(placesDesired)>
  697. !
  698. printString
  699. <return String(self)>
  700. ! !
  701. !Number methodsFor: 'testing'!
  702. even
  703. ^ 0 = (self \\ 2)
  704. !
  705. isNumber
  706. ^true
  707. !
  708. isZero
  709. ^self = 0
  710. !
  711. negative
  712. "Answer whether the receiver is mathematically negative."
  713. ^ self < 0
  714. !
  715. odd
  716. ^ self even not
  717. !
  718. positive
  719. "Answer whether the receiver is positive or equal to 0. (ST-80 protocol)."
  720. ^ self >= 0
  721. ! !
  722. !Number methodsFor: 'timeouts/intervals'!
  723. clearInterval
  724. <clearInterval(Number(self))>
  725. !
  726. clearTimeout
  727. <clearTimeout(Number(self))>
  728. ! !
  729. !Number class methodsFor: 'instance creation'!
  730. pi
  731. <return Math.PI>
  732. ! !
  733. Object subclass: #Package
  734. instanceVariableNames: 'commitPathJs commitPathSt'
  735. package: 'Kernel-Objects'!
  736. !Package commentStamp!
  737. A Package is 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.
  738. A Package has a name, an Array of "requires", a comment and a Dictionary with other optional key value attributes. A Package can also be queried for its classes, but it will then resort to a reverse scan of all classes to find them.
  739. Packages are manipulated through "Smalltalk current", like for example finding one based on a name:
  740. Smalltalk current packageAt: 'Kernel'
  741. ...but you can also use:
  742. Package named: 'Kernel'
  743. 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
  744. 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. This can easily be seen in for example class
  745. String where the method category "*IDE" defines #inspectOn: which thus is a method belonging to the IDE package.
  746. You can fetch a package from the server:
  747. Package fetch: 'Additional-Examples'!
  748. !Package methodsFor: 'accessing'!
  749. commitPathJs
  750. ^ commitPathJs ifNil: [self class defaultCommitPathJs]
  751. !
  752. commitPathJs: aString
  753. commitPathJs := aString
  754. !
  755. commitPathSt
  756. ^ commitPathSt ifNil: [self class defaultCommitPathSt]
  757. !
  758. commitPathSt: aString
  759. commitPathSt := aString
  760. !
  761. dependencies
  762. ^self propertyAt: 'dependencies' ifAbsent: [#()]
  763. !
  764. dependencies: anArray
  765. ^self propertyAt: 'dependencies' put: anArray
  766. !
  767. name
  768. <return self.pkgName>
  769. !
  770. name: aString
  771. <self.pkgName = aString>
  772. !
  773. properties
  774. ^Smalltalk current readJSObject: (self basicAt: 'properties')
  775. !
  776. properties: aDict
  777. "We store it as a javascript object."
  778. | object |
  779. <object = {};>.
  780. aDict keysAndValuesDo: [:key :value |
  781. <object[key] = value>.
  782. ].
  783. <return self.properties = object>
  784. ! !
  785. !Package methodsFor: 'classes'!
  786. classes
  787. "We need to do a reverse scan."
  788. ^Smalltalk current classes select: [:c | c package == self]
  789. !
  790. sortedClasses
  791. "Answer all classes in the receiver, sorted by superclass/subclasses and by class name for common subclasses (Issue #143)."
  792. ^self class sortedClasses: self classes
  793. ! !
  794. !Package methodsFor: 'printing'!
  795. printString
  796. ^self name
  797. ! !
  798. !Package methodsFor: 'private'!
  799. jsProperties
  800. <return self.properties>
  801. !
  802. jsProperties: aJSObject
  803. <return self.properties = aJSObject>
  804. !
  805. propertiesAsJSON
  806. <return JSON.stringify(self.properties)>
  807. ! !
  808. !Package methodsFor: 'properties'!
  809. propertyAt: key
  810. <return self.properties[key]>
  811. !
  812. propertyAt: key ifAbsent: block
  813. ^(self propertyAt: key) ifNil: [block value]
  814. !
  815. propertyAt: key put: value
  816. <return self.properties[key] = value>
  817. ! !
  818. Package class instanceVariableNames: 'defaultCommitPathJs defaultCommitPathSt'!
  819. !Package class methodsFor: 'commit paths'!
  820. defaultCommitPathJs
  821. ^ defaultCommitPathJs ifNil: [ defaultCommitPathJs := 'js']
  822. !
  823. defaultCommitPathJs: aString
  824. defaultCommitPathJs := aString
  825. !
  826. defaultCommitPathSt
  827. ^ defaultCommitPathSt ifNil: [ defaultCommitPathSt := 'st']
  828. !
  829. defaultCommitPathSt: aString
  830. defaultCommitPathSt := aString
  831. !
  832. resetCommitPaths
  833. defaultCommitPathJs := nil.
  834. defaultCommitPathSt := nil.
  835. ! !
  836. !Package class methodsFor: 'loading-storing'!
  837. commitToLocalStorage: aPackageName
  838. | key sourceCode |
  839. key := 'smalltalk.packages.' , aPackageName.
  840. sourceCode := Exporter new exportPackage: aPackageName.
  841. <localStorage[key] = escape(sourceCode)>
  842. !
  843. fetch: aPackageName
  844. self fetch: aPackageName prefix: self defaultCommitPathJs, '/'
  845. !
  846. fetch: aPackageName prefix: aPrefix
  847. jQuery getScript: (aPrefix , aPackageName , '.js') onSuccess: [ Package init: aPackageName ]
  848. !
  849. init: aPackageName
  850. (smalltalk classes select: [ :each | <each.pkg.pkgName == aPackageName> ])
  851. do: [ :each | <smalltalk.init(each)> ];
  852. do: [ :each | each initialize ]
  853. ! !
  854. !Package class methodsFor: 'not yet classified'!
  855. named: aPackageName
  856. ^Smalltalk current packageAt: aPackageName
  857. !
  858. named: aPackageName ifAbsent: aBlock
  859. ^Smalltalk current packageAt: aPackageName ifAbsent: aBlock
  860. ! !
  861. !Package class methodsFor: 'sorting'!
  862. sortedClasses: classes
  863. "Answer classes, sorted by superclass/subclasses and by class name for common subclasses (Issue #143)"
  864. | children others nodes expandedClasses |
  865. children := #().
  866. others := #().
  867. classes do: [:each |
  868. (classes includes: each superclass)
  869. ifFalse: [children add: each]
  870. ifTrue: [others add: each]].
  871. nodes := children collect: [:each |
  872. ClassSorterNode on: each classes: others level: 0].
  873. nodes := nodes sorted: [:a :b | a theClass name <= b theClass name ].
  874. expandedClasses := Array new.
  875. nodes do: [:aNode |
  876. aNode traverseClassesWith: expandedClasses].
  877. ^expandedClasses
  878. ! !
  879. Object subclass: #Point
  880. instanceVariableNames: 'x y'
  881. package: 'Kernel-Objects'!
  882. !Point commentStamp!
  883. A `Point` represents an x-y pair of numbers usually designating a geometric coordinate.
  884. Points are traditionally created using the binary `#@` message to a number:
  885. 100@120
  886. Points can then be arithmetically manipulated:
  887. 100@100 + (10@10)
  888. ...or for example:
  889. (100@100) * 2
  890. **NOTE:** Creating a Point with a negative y-value will need a space after `@` in order to avoid a parsing error:
  891. 100@ -100 "but 100@-100 would not parse"
  892. Amber does not have much behavior in this class out-of-the-box.!
  893. !Point methodsFor: 'accessing'!
  894. x
  895. ^x
  896. !
  897. x: aNumber
  898. x := aNumber
  899. !
  900. y
  901. ^y
  902. !
  903. y: aNumber
  904. y := aNumber
  905. ! !
  906. !Point methodsFor: 'arithmetic'!
  907. * aPoint
  908. ^Point x: self x * aPoint asPoint x y: self y * aPoint asPoint y
  909. !
  910. + aPoint
  911. ^Point x: self x + aPoint asPoint x y: self y + aPoint asPoint y
  912. !
  913. - aPoint
  914. ^Point x: self x - aPoint asPoint x y: self y - aPoint asPoint y
  915. !
  916. / aPoint
  917. ^Point x: self x / aPoint asPoint x y: self y / aPoint asPoint y
  918. !
  919. = aPoint
  920. ^aPoint class = self class and: [
  921. (aPoint x = self x) & (aPoint y = self y)]
  922. ! !
  923. !Point methodsFor: 'converting'!
  924. asPoint
  925. ^self
  926. ! !
  927. !Point methodsFor: 'printing'!
  928. printString
  929. "Print receiver in classic x@y notation."
  930. ^String streamContents: [:stream |
  931. stream nextPutAll: x printString, '@'.
  932. (y notNil and: [y negative])
  933. ifTrue: [
  934. "Avoid ambiguous @- construct"
  935. stream space].
  936. stream nextPutAll: y printString]
  937. ! !
  938. !Point methodsFor: 'transforming'!
  939. translateBy: delta
  940. "Answer a Point translated by delta (an instance of Point)."
  941. ^(delta x + x) @ (delta y + y)
  942. ! !
  943. !Point class methodsFor: 'instance creation'!
  944. x: aNumber y: anotherNumber
  945. ^self new
  946. x: aNumber;
  947. y: anotherNumber;
  948. yourself
  949. ! !
  950. Object subclass: #Random
  951. instanceVariableNames: ''
  952. package: 'Kernel-Objects'!
  953. !Random commentStamp!
  954. `Random` is a random number generator and is implemented as a trivial wrapper around javascript `Math.random()` and is used like this:
  955. Random new next
  956. This will return a float x where x < 1 and x > 0. If you want a random integer from 1 to 10 you can use `#atRandom`
  957. 10 atRandom
  958. ...and if you want a random number in a specific interval this also works:
  959. (3 to: 7) atRandom
  960. ...but be aware that `#to:` does not create an Interval as in other Smalltalk implementations but in fact an `Array` of numbers, so it's better to use:
  961. 5 atRandom + 2
  962. Since `#atRandom` is implemented in `SequencableCollection` you can easy pick an element at random:
  963. #('a' 'b' 'c') atRandom
  964. ...or perhaps a letter from a `String`:
  965. 'abc' atRandom
  966. Since Amber does not have Characters this will return a `String` of length 1 like for example `'b'`.!
  967. !Random methodsFor: 'accessing'!
  968. next
  969. <return Math.random()>
  970. !
  971. next: anInteger
  972. ^(1 to: anInteger) collect: [:each | self next]
  973. ! !
  974. Object subclass: #Smalltalk
  975. instanceVariableNames: ''
  976. package: 'Kernel-Objects'!
  977. !Smalltalk commentStamp!
  978. Smalltalk has only one instance, accessed with `Smalltalk current`.
  979. It represents the global JavaScript variable `smalltalk` declared in `js/boot.js`.
  980. The `smalltalk` object holds all class and packages defined in the system.
  981. ## Classes
  982. Classes can be accessed using the following methods:
  983. - `#classes` answers the full list of Smalltalk classes in the system
  984. - `#at:` answers a specific class of `nil`
  985. ## Packages
  986. Packages can be accessed using the following methods:
  987. - `#packages` answers the full list of packages
  988. - `#packageAt:` answers a specific class of `nil`
  989. __note:__ classes and packages are accessed using strings, not symbols
  990. ## Parsing
  991. The `#parse:` method is used to parse Smalltalk source code.
  992. It requires the `Compiler` package and the `js/parser.js` parser file in order to work!
  993. !Smalltalk methodsFor: 'accessing'!
  994. at: aString
  995. <return self[aString]>
  996. !
  997. basicParse: aString
  998. <return smalltalk.parser.parse(aString)>
  999. !
  1000. classes
  1001. <return self.classes()>
  1002. !
  1003. parse: aString
  1004. | result |
  1005. self try: [result := self basicParse: aString] catch: [:ex | (self parseError: ex parsing: aString) signal].
  1006. ^result
  1007. !
  1008. parseError: anException parsing: aString
  1009. | row col message lines badLine code |
  1010. <row = anException.line;
  1011. col = anException.column;
  1012. message = anException.message;>.
  1013. lines := aString lines.
  1014. badLine := lines at: row.
  1015. badLine := (badLine copyFrom: 1 to: col - 1), ' ===>', (badLine copyFrom: col to: badLine size).
  1016. lines at: row put: badLine.
  1017. code := String streamContents: [:s |
  1018. lines withIndexDo: [:l :i |
  1019. s nextPutAll: i asString, ': ', l, String lf]].
  1020. ^ Error new messageText: ('Parse error on line ' , row , ' column ' , col , ' : ' , message , ' Below is code with line numbers and ===> marker inserted:' , String lf, code)
  1021. !
  1022. readJSObject: anObject
  1023. <return self.readJSObject(anObject)>
  1024. !
  1025. reservedWords
  1026. "JavaScript reserved words"
  1027. <return self.reservedWords>
  1028. !
  1029. send: aSelector to: anObject arguments: aCollection
  1030. | selector |
  1031. selector := aSelector asString asSelector.
  1032. <self.send(anObject, selector, aCollection)>
  1033. ! !
  1034. !Smalltalk methodsFor: 'classes'!
  1035. removeClass: aClass
  1036. aClass isMetaclass ifTrue: [self error: aClass asString, ' is a Metaclass and cannot be removed!!'].
  1037. aClass methodDictionary values do: [:each |
  1038. aClass removeCompiledMethod: each].
  1039. aClass class methodDictionary values do: [:each |
  1040. aClass class removeCompiledMethod: each].
  1041. self basicDelete: aClass name
  1042. ! !
  1043. !Smalltalk methodsFor: 'packages'!
  1044. packageAt: packageName
  1045. <return self.packages[packageName]>
  1046. !
  1047. packageAt: packageName ifAbsent: aBlock
  1048. ^(self packageAt: packageName) ifNil: aBlock
  1049. !
  1050. packages
  1051. "Return all Package instances in the system."
  1052. <return self.packages.all()>
  1053. !
  1054. removePackage: packageName
  1055. "Removes a package and all its classes."
  1056. | pkg |
  1057. pkg := self packageAt: packageName ifAbsent: [self error: 'Missing package: ', packageName].
  1058. pkg classes do: [:each |
  1059. self removeClass: each].
  1060. self deletePackage: packageName
  1061. !
  1062. renamePackage: packageName to: newName
  1063. "Rename a package."
  1064. | pkg |
  1065. pkg := self packageAt: packageName ifAbsent: [self error: 'Missing package: ', packageName].
  1066. (self packageAt: newName) ifNotNil: [self error: 'Already exists a package called: ', newName].
  1067. <smalltalk.packages[newName] = smalltalk.packages[packageName]>.
  1068. pkg name: newName.
  1069. self deletePackage: packageName.
  1070. ! !
  1071. !Smalltalk methodsFor: 'private'!
  1072. createPackage: packageName
  1073. "Create and bind a new package with given name and return it."
  1074. <return smalltalk.addPackage(packageName, nil)>
  1075. !
  1076. createPackage: packageName properties: aDict
  1077. "Create and bind a new package with given name and return it."
  1078. | object |
  1079. <object = {};>.
  1080. aDict keysAndValuesDo: [:key :value |
  1081. <object[key] = value>.
  1082. ].
  1083. <return smalltalk.addPackage(packageName, object)>
  1084. !
  1085. deletePackage: packageName
  1086. "Deletes a package by deleting its binding, but does not check if it contains classes etc.
  1087. To remove a package, use #removePackage instead."
  1088. <delete smalltalk.packages[packageName]>
  1089. ! !
  1090. Smalltalk class instanceVariableNames: 'current'!
  1091. !Smalltalk class methodsFor: 'accessing'!
  1092. current
  1093. <return smalltalk>
  1094. ! !
  1095. Object subclass: #UndefinedObject
  1096. instanceVariableNames: ''
  1097. package: 'Kernel-Objects'!
  1098. !UndefinedObject commentStamp!
  1099. UndefinedObject describes the behavior of its sole instance, `nil`. `nil` represents a prior value for variables that have not been initialized, or for results which are meaningless.
  1100. `nil` is the Smalltalk representation of the `undefined` JavaScript object.!
  1101. !UndefinedObject methodsFor: 'class creation'!
  1102. subclass: aString instanceVariableNames: anotherString
  1103. ^self subclass: aString instanceVariableNames: anotherString package: nil
  1104. !
  1105. subclass: aString instanceVariableNames: aString2 category: aString3
  1106. "Kept for compatibility."
  1107. self deprecatedAPI.
  1108. ^self subclass: aString instanceVariableNames: aString2 package: aString3
  1109. !
  1110. subclass: aString instanceVariableNames: aString2 package: aString3
  1111. ^ClassBuilder new
  1112. superclass: self subclass: aString instanceVariableNames: aString2 package: aString3
  1113. ! !
  1114. !UndefinedObject methodsFor: 'converting'!
  1115. asJSON
  1116. ^null
  1117. ! !
  1118. !UndefinedObject methodsFor: 'copying'!
  1119. deepCopy
  1120. ^self
  1121. !
  1122. shallowCopy
  1123. ^self
  1124. ! !
  1125. !UndefinedObject methodsFor: 'printing'!
  1126. printString
  1127. ^'nil'
  1128. ! !
  1129. !UndefinedObject methodsFor: 'testing'!
  1130. ifNil: aBlock
  1131. "inlined in the Compiler"
  1132. ^self ifNil: aBlock ifNotNil: []
  1133. !
  1134. ifNil: aBlock ifNotNil: anotherBlock
  1135. "inlined in the Compiler"
  1136. ^aBlock value
  1137. !
  1138. ifNotNil: aBlock
  1139. "inlined in the Compiler"
  1140. ^self
  1141. !
  1142. ifNotNil: aBlock ifNil: anotherBlock
  1143. "inlined in the Compiler"
  1144. ^anotherBlock value
  1145. !
  1146. isNil
  1147. ^true
  1148. !
  1149. notNil
  1150. ^false
  1151. ! !
  1152. !UndefinedObject class methodsFor: 'instance creation'!
  1153. new
  1154. self error: 'You cannot create new instances of UndefinedObject. Use nil'
  1155. ! !