1
0

Kernel-Objects.st 29 KB

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