Compiler-Semantic.st 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. Smalltalk createPackage: 'Compiler-Semantic'!
  2. Object subclass: #LexicalScope
  3. slots: {#node. #instruction. #temps. #args. #outerScope. #blockIndex}
  4. package: 'Compiler-Semantic'!
  5. !LexicalScope commentStamp!
  6. I represent a lexical scope where variable names are associated with ScopeVars
  7. Instances are used for block scopes. Method scopes are instances of MethodLexicalScope.
  8. I am attached to a ScopeVar and method/block nodes.
  9. Each context (method/closure) get a fresh scope that inherits from its outer scope.!
  10. !LexicalScope methodsFor: 'accessing'!
  11. alias
  12. ^ '$ctx', self scopeLevel asString
  13. !
  14. allVariableNames
  15. ^ self args keys, self temps keys
  16. !
  17. args
  18. ^ args ifNil: [ args := Dictionary new ]
  19. !
  20. bindingFor: aNode
  21. | identifier |
  22. identifier := aNode value.
  23. ^ self pseudoVars at: identifier ifAbsent: [
  24. self args at: identifier ifAbsent: [
  25. self temps at: identifier ifAbsent: [ nil ]]]
  26. !
  27. blockIndex
  28. ^ blockIndex ifNil: [ 0 ]
  29. !
  30. blockIndex: anInteger
  31. blockIndex := anInteger
  32. !
  33. instruction
  34. ^ instruction
  35. !
  36. instruction: anIRInstruction
  37. instruction := anIRInstruction
  38. !
  39. lookupVariable: aNode
  40. | lookup |
  41. lookup := (self bindingFor: aNode).
  42. lookup ifNil: [
  43. lookup := self outerScope ifNotNil: [
  44. (self outerScope lookupVariable: aNode) ]].
  45. ^ lookup
  46. !
  47. methodScope
  48. ^ self outerScope ifNotNil: [
  49. self outerScope methodScope ]
  50. !
  51. node
  52. "Answer the node in which I am defined"
  53. ^ node
  54. !
  55. node: aNode
  56. node := aNode
  57. !
  58. outerScope
  59. ^ outerScope
  60. !
  61. outerScope: aLexicalScope
  62. outerScope := aLexicalScope
  63. !
  64. pseudoVars
  65. ^ self methodScope pseudoVars
  66. !
  67. scopeLevel
  68. self outerScope ifNil: [ ^ 1 ].
  69. self isInlined ifTrue: [ ^ self outerScope scopeLevel ].
  70. ^ self outerScope scopeLevel + 1
  71. !
  72. temps
  73. ^ temps ifNil: [ temps := Dictionary new ]
  74. ! !
  75. !LexicalScope methodsFor: 'adding'!
  76. addArg: aString
  77. self args at: aString put: (ArgVar on: aString).
  78. (self args at: aString) scope: self
  79. !
  80. addTemp: aString
  81. self temps at: aString put: (TempVar on: aString).
  82. (self temps at: aString) scope: self
  83. ! !
  84. !LexicalScope methodsFor: 'testing'!
  85. canFlattenNonLocalReturns
  86. ^ self isInlined and: [ self outerScope canFlattenNonLocalReturns ]
  87. !
  88. isBlockScope
  89. ^ self isMethodScope not
  90. !
  91. isInlined
  92. ^ self instruction notNil and: [
  93. self instruction isInlined ]
  94. !
  95. isMethodScope
  96. ^ false
  97. ! !
  98. LexicalScope subclass: #MethodLexicalScope
  99. slots: {#iVars. #pseudoVars. #localReturn. #nonLocalReturns}
  100. package: 'Compiler-Semantic'!
  101. !MethodLexicalScope commentStamp!
  102. I represent a method scope.!
  103. !MethodLexicalScope methodsFor: 'accessing'!
  104. allVariableNames
  105. ^ super allVariableNames, self iVars keys
  106. !
  107. bindingFor: aNode
  108. ^ (super bindingFor: aNode) ifNil: [
  109. self iVars at: aNode value ifAbsent: [ nil ]]
  110. !
  111. iVars
  112. ^ iVars ifNil: [ iVars := Dictionary new ]
  113. !
  114. localReturn
  115. ^ localReturn ifNil: [ false ]
  116. !
  117. localReturn: aBoolean
  118. localReturn := aBoolean
  119. !
  120. methodScope
  121. ^ self
  122. !
  123. nonLocalReturns
  124. ^ nonLocalReturns ifNil: [ nonLocalReturns := OrderedCollection new ]
  125. !
  126. pseudoVars
  127. pseudoVars ifNil: [
  128. pseudoVars := Dictionary new.
  129. PseudoVar dictionary keysAndValuesDo: [ :each :impl |
  130. pseudoVars at: each put: ((impl on: each)
  131. scope: self methodScope;
  132. yourself) ] ].
  133. ^ pseudoVars
  134. ! !
  135. !MethodLexicalScope methodsFor: 'adding'!
  136. addIVar: aString
  137. self iVars at: aString put: (InstanceVar on: aString).
  138. (self iVars at: aString) scope: self
  139. !
  140. addNonLocalReturn: aScope
  141. self nonLocalReturns add: aScope
  142. !
  143. removeNonLocalReturn: aScope
  144. self nonLocalReturns remove: aScope ifAbsent: []
  145. ! !
  146. !MethodLexicalScope methodsFor: 'testing'!
  147. canFlattenNonLocalReturns
  148. ^ true
  149. !
  150. hasLocalReturn
  151. ^ self localReturn
  152. !
  153. hasNonLocalReturn
  154. ^ self nonLocalReturns notEmpty
  155. !
  156. isMethodScope
  157. ^ true
  158. ! !
  159. Object subclass: #ScopeVar
  160. slots: {#scope. #name}
  161. package: 'Compiler-Semantic'!
  162. !ScopeVar commentStamp!
  163. I am an entry in a LexicalScope that gets associated with variable nodes of the same name.
  164. There are 4 different subclasses of vars: temp vars, local vars, args, and unknown/global vars.!
  165. !ScopeVar methodsFor: 'accessing'!
  166. alias
  167. ^ self name asVariableName
  168. !
  169. name
  170. ^ name
  171. !
  172. name: aString
  173. name := aString
  174. !
  175. scope
  176. ^ scope
  177. !
  178. scope: aScope
  179. scope := aScope
  180. ! !
  181. !ScopeVar methodsFor: 'testing'!
  182. isClassRefVar
  183. ^ false
  184. !
  185. isExternallyKnownVar
  186. ^ false
  187. !
  188. isImmutable
  189. ^ false
  190. !
  191. isInstanceVar
  192. ^ false
  193. !
  194. isPseudoVar
  195. ^ false
  196. !
  197. isSelf
  198. ^ false
  199. !
  200. isSuper
  201. ^ false
  202. !
  203. isTempVar
  204. ^ false
  205. ! !
  206. !ScopeVar class methodsFor: 'instance creation'!
  207. on: aString
  208. ^ self new
  209. name: aString;
  210. yourself
  211. ! !
  212. ScopeVar subclass: #AliasVar
  213. slots: {}
  214. package: 'Compiler-Semantic'!
  215. !AliasVar commentStamp!
  216. I am an internally defined variable by the compiler!
  217. !AliasVar methodsFor: 'testing'!
  218. isImmutable
  219. ^ true
  220. ! !
  221. ScopeVar subclass: #ArgVar
  222. slots: {}
  223. package: 'Compiler-Semantic'!
  224. !ArgVar commentStamp!
  225. I am an argument of a method or block.!
  226. !ArgVar methodsFor: 'testing'!
  227. isImmutable
  228. ^ true
  229. ! !
  230. ScopeVar subclass: #ClassRefVar
  231. slots: {}
  232. package: 'Compiler-Semantic'!
  233. !ClassRefVar commentStamp!
  234. I am an class reference variable!
  235. !ClassRefVar methodsFor: 'accessing'!
  236. alias
  237. ^ '$globals.', self name
  238. ! !
  239. !ClassRefVar methodsFor: 'testing'!
  240. isClassRefVar
  241. ^ true
  242. !
  243. isImmutable
  244. ^ true
  245. ! !
  246. ScopeVar subclass: #ExternallyKnownVar
  247. slots: {}
  248. package: 'Compiler-Semantic'!
  249. !ExternallyKnownVar commentStamp!
  250. I am a variable known externally (not in method scope).!
  251. !ExternallyKnownVar methodsFor: 'testing'!
  252. isExternallyKnownVar
  253. ^ true
  254. ! !
  255. ScopeVar subclass: #InstanceVar
  256. slots: {}
  257. package: 'Compiler-Semantic'!
  258. !InstanceVar commentStamp!
  259. I am an instance variable of a method or block.!
  260. !InstanceVar methodsFor: 'testing'!
  261. alias
  262. ^ '$self.', self name
  263. !
  264. isInstanceVar
  265. ^ true
  266. ! !
  267. ScopeVar subclass: #PseudoVar
  268. slots: {}
  269. package: 'Compiler-Semantic'!
  270. !PseudoVar commentStamp!
  271. I am an pseudo variable.
  272. The five Smalltalk pseudo variables are: 'self', 'super', 'nil', 'true' and 'false'!
  273. !PseudoVar methodsFor: 'accessing'!
  274. alias
  275. ^ self name
  276. ! !
  277. !PseudoVar methodsFor: 'testing'!
  278. isImmutable
  279. ^ true
  280. !
  281. isPseudoVar
  282. ^ true
  283. !
  284. isSelf
  285. ^ name = 'self'
  286. ! !
  287. PseudoVar class slots: {#dictionary}!
  288. !PseudoVar class methodsFor: 'accessing'!
  289. dictionary
  290. ^ dictionary ifNil: [ dictionary := Dictionary new
  291. at: #self put: PseudoVar;
  292. at: #super put: SuperVar;
  293. at: #nil put: PseudoVar;
  294. at: #false put: PseudoVar;
  295. at: #true put: PseudoVar;
  296. at: #thisContext put: ThisContextVar;
  297. yourself ]
  298. ! !
  299. PseudoVar subclass: #SuperVar
  300. slots: {}
  301. package: 'Compiler-Semantic'!
  302. !SuperVar commentStamp!
  303. I am a 'super' pseudo variable.!
  304. !SuperVar methodsFor: 'accessing'!
  305. alias
  306. ^ '$self'
  307. !
  308. lookupAsJavaScriptSource
  309. ^ '($methodClass.superclass||$boot.nilAsClass).fn.prototype'
  310. ! !
  311. !SuperVar methodsFor: 'testing'!
  312. isSuper
  313. ^ true
  314. ! !
  315. PseudoVar subclass: #ThisContextVar
  316. slots: {}
  317. package: 'Compiler-Semantic'!
  318. !ThisContextVar commentStamp!
  319. I am a 'thisContext' pseudo variable.!
  320. !ThisContextVar methodsFor: 'accessing'!
  321. alias
  322. ^ '$core.getThisContext()'
  323. ! !
  324. ScopeVar subclass: #TempVar
  325. slots: {}
  326. package: 'Compiler-Semantic'!
  327. !TempVar commentStamp!
  328. I am an temporary variable of a method or block.!
  329. !TempVar methodsFor: 'testing'!
  330. isTempVar
  331. ^ true
  332. ! !
  333. NodeVisitor subclass: #SemanticAnalyzer
  334. slots: {#currentScope. #blockIndex. #thePackage. #theClass. #classReferences. #messageSends}
  335. package: 'Compiler-Semantic'!
  336. !SemanticAnalyzer commentStamp!
  337. I semantically analyze the abstract syntax tree and annotate it with informations such as non local returns and variable scopes.!
  338. !SemanticAnalyzer methodsFor: 'accessing'!
  339. classReferences
  340. ^ classReferences ifNil: [ classReferences := Set new ]
  341. !
  342. messageSends
  343. ^ messageSends ifNil: [ messageSends := Dictionary new ]
  344. !
  345. theClass
  346. ^ theClass
  347. !
  348. theClass: aClass
  349. theClass := aClass
  350. !
  351. thePackage
  352. ^ thePackage
  353. !
  354. thePackage: aPackage
  355. thePackage := aPackage
  356. ! !
  357. !SemanticAnalyzer methodsFor: 'error handling'!
  358. errorInvalidAssignment: aString
  359. InvalidAssignmentError new
  360. variableName: aString;
  361. signal
  362. !
  363. errorShadowingVariable: aString
  364. ShadowingVariableError new
  365. variableName: aString;
  366. signal
  367. !
  368. errorUnknownVariable: aString
  369. UnknownVariableError new
  370. variableName: aString;
  371. signal
  372. ! !
  373. !SemanticAnalyzer methodsFor: 'factory'!
  374. newBlockScope
  375. ^ self newScopeOfClass: LexicalScope
  376. !
  377. newMethodScope
  378. ^ self newScopeOfClass: MethodLexicalScope
  379. !
  380. newScopeOfClass: aLexicalScopeClass
  381. ^ aLexicalScopeClass new
  382. outerScope: currentScope;
  383. yourself
  384. ! !
  385. !SemanticAnalyzer methodsFor: 'private'!
  386. bindUnscopedVariable: aString
  387. aString isCapitalized ifTrue: [ "Capital letter variables might be globals."
  388. self classReferences add: aString.
  389. ^ ClassRefVar new name: aString; yourself ].
  390. "Throw an error if the variable is undeclared in the global JS scope (i.e. window).
  391. We allow all variables listed by Smalltalk>>#globalJsVariables.
  392. This list includes: `window`, `document`, `process` and `global`
  393. for nodejs and browser environments.
  394. This is only to make sure compilation works on both browser-based and nodejs environments.
  395. The ideal solution would be to use a pragma instead"
  396. ((Smalltalk globalJsVariables includes: aString)
  397. or: [ self isVariableKnown: aString inPackage: self thePackage ]) ifTrue: [
  398. ^ ExternallyKnownVar new name: aString; yourself ].
  399. self errorUnknownVariable: aString
  400. !
  401. nextBlockIndex
  402. blockIndex ifNil: [ blockIndex := 0 ].
  403. blockIndex := blockIndex + 1.
  404. ^ blockIndex
  405. ! !
  406. !SemanticAnalyzer methodsFor: 'scope'!
  407. popScope
  408. currentScope ifNotNil: [
  409. currentScope := currentScope outerScope ]
  410. !
  411. pushScope: aScope
  412. aScope outerScope: currentScope.
  413. currentScope := aScope
  414. !
  415. validateVariableScope: aString
  416. "Validate the variable scope in by doing a recursive lookup, up to the method scope"
  417. (currentScope lookupVariable: aString) ifNotNil: [
  418. self errorShadowingVariable: aString ]
  419. ! !
  420. !SemanticAnalyzer methodsFor: 'testing'!
  421. isVariableKnown: aString inPackage: aPackage
  422. ^ Compiler new
  423. eval: 'typeof(', aString, ')!!== "undefined"||(function(){try{return(', aString, ',true)}catch(_){return false}})()'
  424. forPackage: aPackage
  425. ! !
  426. !SemanticAnalyzer methodsFor: 'visiting'!
  427. visitAssignmentNode: aNode
  428. | lhs |
  429. super visitAssignmentNode: aNode.
  430. lhs := aNode left.
  431. lhs isImmutable ifTrue: [ self errorInvalidAssignment: lhs value ].
  432. lhs assigned: true
  433. !
  434. visitBlockNode: aNode
  435. self pushScope: self newBlockScope.
  436. aNode scope: currentScope.
  437. currentScope node: aNode.
  438. currentScope blockIndex: self nextBlockIndex.
  439. aNode parameters do: [ :each |
  440. self validateVariableScope: each.
  441. currentScope addArg: each ].
  442. super visitBlockNode: aNode.
  443. self popScope
  444. !
  445. visitCascadeNode: aNode
  446. aNode receiver: aNode dagChildren first receiver.
  447. super visitCascadeNode: aNode
  448. !
  449. visitMethodNode: aNode
  450. self pushScope: self newMethodScope.
  451. aNode scope: currentScope.
  452. currentScope node: aNode.
  453. self theClass allInstanceVariableNames do: [ :each |
  454. currentScope addIVar: each ].
  455. aNode arguments do: [ :each |
  456. self validateVariableScope: each.
  457. currentScope addArg: each ].
  458. super visitMethodNode: aNode.
  459. aNode
  460. classReferences: self classReferences;
  461. sendIndexes: self messageSends.
  462. self popScope.
  463. ^ aNode
  464. !
  465. visitReturnNode: aNode
  466. aNode scope: currentScope.
  467. currentScope isMethodScope
  468. ifTrue: [ currentScope localReturn: true ]
  469. ifFalse: [ currentScope methodScope addNonLocalReturn: currentScope ].
  470. super visitReturnNode: aNode
  471. !
  472. visitSendNode: aNode
  473. | sends |
  474. sends := self messageSends at: aNode selector ifAbsentPut: [ OrderedCollection new ].
  475. sends add: aNode.
  476. aNode index: sends size.
  477. super visitSendNode: aNode
  478. !
  479. visitSequenceNode: aNode
  480. aNode temps do: [ :each |
  481. self validateVariableScope: each.
  482. currentScope addTemp: each ].
  483. super visitSequenceNode: aNode
  484. !
  485. visitVariableNode: aNode
  486. "Bind a ScopeVar to aNode by doing a lookup in the current scope.
  487. If no var is found in scope, represent an externally known variable or throw an error."
  488. aNode binding:
  489. ((currentScope lookupVariable: aNode) ifNil: [ self bindUnscopedVariable: aNode value ])
  490. ! !
  491. !SemanticAnalyzer class methodsFor: 'instance creation'!
  492. on: aClass
  493. ^ self new
  494. theClass: aClass;
  495. yourself
  496. ! !
  497. CompilerError subclass: #SemanticError
  498. slots: {}
  499. package: 'Compiler-Semantic'!
  500. !SemanticError commentStamp!
  501. I represent an abstract semantic error thrown by the SemanticAnalyzer.
  502. Semantic errors can be unknown variable errors, etc.
  503. See my subclasses for concrete errors.
  504. The IDE should catch instances of Semantic error to deal with them when compiling!
  505. SemanticError subclass: #InvalidAssignmentError
  506. slots: {#variableName}
  507. package: 'Compiler-Semantic'!
  508. !InvalidAssignmentError commentStamp!
  509. I get signaled when a pseudo variable gets assigned.!
  510. !InvalidAssignmentError methodsFor: 'accessing'!
  511. messageText
  512. ^ ' Invalid assignment to variable: ', self variableName
  513. !
  514. variableName
  515. ^ variableName
  516. !
  517. variableName: aString
  518. variableName := aString
  519. ! !
  520. SemanticError subclass: #ShadowingVariableError
  521. slots: {#variableName}
  522. package: 'Compiler-Semantic'!
  523. !ShadowingVariableError commentStamp!
  524. I get signaled when a variable in a block or method scope shadows a variable of the same name in an outer scope.!
  525. !ShadowingVariableError methodsFor: 'accessing'!
  526. messageText
  527. ^ 'Variable shadowing error: ', self variableName, ' is already defined'
  528. !
  529. variableName
  530. ^ variableName
  531. !
  532. variableName: aString
  533. variableName := aString
  534. ! !
  535. SemanticError subclass: #UnknownVariableError
  536. slots: {#variableName}
  537. package: 'Compiler-Semantic'!
  538. !UnknownVariableError commentStamp!
  539. I get signaled when a variable is not defined.
  540. The default behavior is to allow it, as this is how Amber currently is able to seamlessly send messages to JavaScript objects.!
  541. !UnknownVariableError methodsFor: 'accessing'!
  542. messageText
  543. ^ 'Unknown Variable error: ', self variableName, ' is not defined'
  544. !
  545. variableName
  546. ^ variableName
  547. !
  548. variableName: aString
  549. variableName := aString
  550. ! !