Compiler-Semantic.st 14 KB

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