1
0

Kernel-Objects.st 31 KB

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