Kernel-Objects.st 30 KB

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