Compiler-Semantic.st 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. validateAssignment
  207. self isImmutable ifTrue: [
  208. InvalidAssignmentError new
  209. variableName: self name;
  210. signal]
  211. ! !
  212. !ScopeVar class methodsFor: 'instance creation'!
  213. on: aString
  214. ^ self new
  215. name: aString;
  216. yourself
  217. ! !
  218. ScopeVar subclass: #AliasVar
  219. slots: {}
  220. package: 'Compiler-Semantic'!
  221. !AliasVar commentStamp!
  222. I am an internally defined variable by the compiler!
  223. !AliasVar methodsFor: 'testing'!
  224. isImmutable
  225. ^ true
  226. ! !
  227. ScopeVar subclass: #ArgVar
  228. slots: {}
  229. package: 'Compiler-Semantic'!
  230. !ArgVar commentStamp!
  231. I am an argument of a method or block.!
  232. !ArgVar methodsFor: 'testing'!
  233. isImmutable
  234. ^ true
  235. ! !
  236. ScopeVar subclass: #ClassRefVar
  237. slots: {}
  238. package: 'Compiler-Semantic'!
  239. !ClassRefVar commentStamp!
  240. I am an class reference variable!
  241. !ClassRefVar methodsFor: 'accessing'!
  242. alias
  243. ^ '$globals.', self name
  244. ! !
  245. !ClassRefVar methodsFor: 'testing'!
  246. isClassRefVar
  247. ^ true
  248. !
  249. isImmutable
  250. ^ true
  251. ! !
  252. ScopeVar subclass: #ExternallyKnownVar
  253. slots: {}
  254. package: 'Compiler-Semantic'!
  255. !ExternallyKnownVar commentStamp!
  256. I am a variable known externally (not in method scope).!
  257. !ExternallyKnownVar methodsFor: 'testing'!
  258. isExternallyKnownVar
  259. ^ true
  260. ! !
  261. ScopeVar subclass: #InstanceVar
  262. slots: {}
  263. package: 'Compiler-Semantic'!
  264. !InstanceVar commentStamp!
  265. I am an instance variable of a method or block.!
  266. !InstanceVar methodsFor: 'testing'!
  267. alias
  268. ^ '$self.', self name
  269. !
  270. isInstanceVar
  271. ^ true
  272. ! !
  273. ScopeVar subclass: #PseudoVar
  274. slots: {}
  275. package: 'Compiler-Semantic'!
  276. !PseudoVar commentStamp!
  277. I am an pseudo variable.
  278. The five Smalltalk pseudo variables are: 'self', 'super', 'nil', 'true' and 'false'!
  279. !PseudoVar methodsFor: 'accessing'!
  280. alias
  281. ^ self name
  282. ! !
  283. !PseudoVar methodsFor: 'testing'!
  284. isImmutable
  285. ^ true
  286. !
  287. isPseudoVar
  288. ^ true
  289. !
  290. isSelf
  291. ^ name = 'self'
  292. ! !
  293. PseudoVar class slots: {#dictionary}!
  294. !PseudoVar class methodsFor: 'accessing'!
  295. dictionary
  296. ^ dictionary ifNil: [ dictionary := Dictionary new
  297. at: #self put: PseudoVar;
  298. at: #super put: SuperVar;
  299. at: #nil put: PseudoVar;
  300. at: #false put: PseudoVar;
  301. at: #true put: PseudoVar;
  302. at: #thisContext put: ThisContextVar;
  303. yourself ]
  304. ! !
  305. PseudoVar subclass: #SuperVar
  306. slots: {}
  307. package: 'Compiler-Semantic'!
  308. !SuperVar commentStamp!
  309. I am a 'super' pseudo variable.!
  310. !SuperVar methodsFor: 'accessing'!
  311. alias
  312. ^ '$self'
  313. !
  314. lookupAsJavaScriptSource
  315. ^ '($methodClass.superclass||$boot.nilAsClass).fn.prototype'
  316. ! !
  317. !SuperVar methodsFor: 'testing'!
  318. isSuper
  319. ^ true
  320. ! !
  321. PseudoVar subclass: #ThisContextVar
  322. slots: {}
  323. package: 'Compiler-Semantic'!
  324. !ThisContextVar commentStamp!
  325. I am a 'thisContext' pseudo variable.!
  326. !ThisContextVar methodsFor: 'accessing'!
  327. alias
  328. ^ '$core.getThisContext()'
  329. ! !
  330. ScopeVar subclass: #TempVar
  331. slots: {}
  332. package: 'Compiler-Semantic'!
  333. !TempVar commentStamp!
  334. I am an temporary variable of a method or block.!
  335. !TempVar methodsFor: 'testing'!
  336. isTempVar
  337. ^ true
  338. ! !
  339. NodeVisitor subclass: #SemanticAnalyzer
  340. slots: {#currentScope. #blockIndex. #thePackage. #theClass. #classReferences. #messageSends}
  341. package: 'Compiler-Semantic'!
  342. !SemanticAnalyzer commentStamp!
  343. I semantically analyze the abstract syntax tree and annotate it with informations such as non local returns and variable scopes.!
  344. !SemanticAnalyzer methodsFor: 'accessing'!
  345. classReferences
  346. ^ classReferences ifNil: [ classReferences := Set new ]
  347. !
  348. messageSends
  349. ^ messageSends ifNil: [ messageSends := Dictionary new ]
  350. !
  351. theClass
  352. ^ theClass
  353. !
  354. theClass: aClass
  355. theClass := aClass
  356. !
  357. thePackage
  358. ^ thePackage
  359. !
  360. thePackage: aPackage
  361. thePackage := aPackage
  362. ! !
  363. !SemanticAnalyzer methodsFor: 'error handling'!
  364. errorShadowingVariable: aString
  365. ShadowingVariableError new
  366. variableName: aString;
  367. signal
  368. !
  369. errorUnknownVariable: aString
  370. UnknownVariableError new
  371. variableName: aString;
  372. signal
  373. ! !
  374. !SemanticAnalyzer methodsFor: 'factory'!
  375. newBlockScope
  376. ^ self newScopeOfClass: LexicalScope
  377. !
  378. newMethodScope
  379. ^ self newScopeOfClass: MethodLexicalScope
  380. !
  381. newScopeOfClass: aLexicalScopeClass
  382. ^ aLexicalScopeClass new
  383. outerScope: currentScope;
  384. yourself
  385. ! !
  386. !SemanticAnalyzer methodsFor: 'private'!
  387. bindUnscopedVariable: aString
  388. aString isCapitalized ifTrue: [ "Capital letter variables might be globals."
  389. self classReferences add: aString.
  390. ^ ClassRefVar new name: aString; yourself ].
  391. "Throw an error if the variable is undeclared in the global JS scope (i.e. window).
  392. We allow all variables listed by Smalltalk>>#globalJsVariables.
  393. This list includes: `window`, `document`, `process` and `global`
  394. for nodejs and browser environments.
  395. This is only to make sure compilation works on both browser-based and nodejs environments.
  396. The ideal solution would be to use a pragma instead"
  397. ((Smalltalk globalJsVariables includes: aString)
  398. or: [ self isVariableKnown: aString inPackage: self thePackage ]) ifTrue: [
  399. ^ ExternallyKnownVar new name: aString; yourself ].
  400. self errorUnknownVariable: aString
  401. !
  402. nextBlockIndex
  403. blockIndex ifNil: [ blockIndex := 0 ].
  404. blockIndex := blockIndex + 1.
  405. ^ blockIndex
  406. ! !
  407. !SemanticAnalyzer methodsFor: 'scope'!
  408. popScope
  409. currentScope ifNotNil: [
  410. currentScope := currentScope outerScope ]
  411. !
  412. pushScope: aScope
  413. aScope outerScope: currentScope.
  414. currentScope := aScope
  415. !
  416. validateVariableScope: aString
  417. "Validate the variable scope in by doing a recursive lookup, up to the method scope"
  418. (currentScope lookupVariable: aString) ifNotNil: [
  419. self errorShadowingVariable: aString ]
  420. ! !
  421. !SemanticAnalyzer methodsFor: 'testing'!
  422. isVariableKnown: aString inPackage: aPackage
  423. ^ Compiler new
  424. eval: 'typeof(', aString, ')!!== "undefined"||(function(){try{return(', aString, ',true)}catch(_){return false}})()'
  425. forPackage: aPackage
  426. ! !
  427. !SemanticAnalyzer methodsFor: 'visiting'!
  428. visitAssignmentNode: aNode
  429. super visitAssignmentNode: aNode.
  430. aNode left beAssigned
  431. !
  432. visitBlockNode: aNode
  433. self pushScope: self newBlockScope.
  434. aNode scope: currentScope.
  435. currentScope node: aNode.
  436. currentScope blockIndex: self nextBlockIndex.
  437. aNode parameters do: [ :each |
  438. self validateVariableScope: each.
  439. currentScope addArg: each ].
  440. super visitBlockNode: aNode.
  441. self popScope
  442. !
  443. visitCascadeNode: aNode
  444. aNode receiver: aNode dagChildren first receiver.
  445. super visitCascadeNode: aNode
  446. !
  447. visitMethodNode: aNode
  448. self pushScope: self newMethodScope.
  449. aNode scope: currentScope.
  450. currentScope node: aNode.
  451. self theClass allInstanceVariableNames do: [ :each |
  452. currentScope addIVar: each ].
  453. aNode arguments do: [ :each |
  454. self validateVariableScope: each.
  455. currentScope addArg: each ].
  456. super visitMethodNode: aNode.
  457. aNode
  458. classReferences: self classReferences;
  459. sendIndexes: self messageSends.
  460. self popScope.
  461. ^ aNode
  462. !
  463. visitReturnNode: aNode
  464. aNode scope: currentScope.
  465. currentScope isMethodScope
  466. ifTrue: [ currentScope localReturn: true ]
  467. ifFalse: [ currentScope methodScope addNonLocalReturn: currentScope ].
  468. super visitReturnNode: aNode
  469. !
  470. visitSendNode: aNode
  471. | sends |
  472. sends := self messageSends at: aNode selector ifAbsentPut: [ OrderedCollection new ].
  473. sends add: aNode.
  474. aNode index: sends size.
  475. super visitSendNode: aNode
  476. !
  477. visitSequenceNode: aNode
  478. aNode temps do: [ :each |
  479. self validateVariableScope: each.
  480. currentScope addTemp: each ].
  481. super visitSequenceNode: aNode
  482. !
  483. visitVariableNode: aNode
  484. "Bind a ScopeVar to aNode by doing a lookup in the current scope.
  485. If no var is found in scope, represent an externally known variable or throw an error."
  486. aNode binding:
  487. ((currentScope lookupVariable: aNode) ifNil: [ self bindUnscopedVariable: aNode value ])
  488. ! !
  489. !SemanticAnalyzer class methodsFor: 'instance creation'!
  490. on: aClass
  491. ^ self new
  492. theClass: aClass;
  493. yourself
  494. ! !
  495. CompilerError subclass: #SemanticError
  496. slots: {}
  497. package: 'Compiler-Semantic'!
  498. !SemanticError commentStamp!
  499. I represent an abstract semantic error thrown by the SemanticAnalyzer.
  500. Semantic errors can be unknown variable errors, etc.
  501. See my subclasses for concrete errors.
  502. The IDE should catch instances of Semantic error to deal with them when compiling!
  503. SemanticError subclass: #InvalidAssignmentError
  504. slots: {#variableName}
  505. package: 'Compiler-Semantic'!
  506. !InvalidAssignmentError commentStamp!
  507. I get signaled when a pseudo variable gets assigned.!
  508. !InvalidAssignmentError methodsFor: 'accessing'!
  509. messageText
  510. ^ ' Invalid assignment to variable: ', self variableName
  511. !
  512. variableName
  513. ^ variableName
  514. !
  515. variableName: aString
  516. variableName := aString
  517. ! !
  518. SemanticError subclass: #ShadowingVariableError
  519. slots: {#variableName}
  520. package: 'Compiler-Semantic'!
  521. !ShadowingVariableError commentStamp!
  522. I get signaled when a variable in a block or method scope shadows a variable of the same name in an outer scope.!
  523. !ShadowingVariableError methodsFor: 'accessing'!
  524. messageText
  525. ^ 'Variable shadowing error: ', self variableName, ' is already defined'
  526. !
  527. variableName
  528. ^ variableName
  529. !
  530. variableName: aString
  531. variableName := aString
  532. ! !
  533. SemanticError subclass: #UnknownVariableError
  534. slots: {#variableName}
  535. package: 'Compiler-Semantic'!
  536. !UnknownVariableError commentStamp!
  537. I get signaled when a variable is not defined.
  538. The default behavior is to allow it, as this is how Amber currently is able to seamlessly send messages to JavaScript objects.!
  539. !UnknownVariableError methodsFor: 'accessing'!
  540. messageText
  541. ^ 'Unknown Variable error: ', self variableName, ' is not defined'
  542. !
  543. variableName
  544. ^ variableName
  545. !
  546. variableName: aString
  547. variableName := aString
  548. ! !