I'm working on a custom interpreter for fun ;)
What I have so far is assigning variables, defining and calling functions, arrays, loops, if blocks etc...
I've started adding OOP elements to my language and I'm having trouble implementing the "this" / "self" keyword.
I just cannot figure out a solution to this problem.
I've thought about a few solutions:
a class stores it's instances (as a dictionary) and when the "this" keyword appears, the interpreter ignores "private" and "public" keywords (to call a private method from a public one), creates a call to the method referenced by "this" and returns.
the "this" keyword is a reference which under the hood is the instance itself, but the method access modifiers are dropped for that call. this is similar to the first one, but I cannot think of anything better.
Also it would be nice if you knew C# (primarly) or C++, since I'm heavily relying on OOP to create my interpreter.
heres a small sample of code that I would like to implement:
struct Dog has
pub prop age;
prv def bark() do
println "woof woof";
end
pub def run(dist) do
loop 0 to $dist with "d" do
println ("the dog ran " + string $d) + " meters";
$self.bark();
end
end
end
def main(args) do
new Dog -> $dog;
7 -> $dog.age;
println $dog.age;
$dog.run 30;
end
notice that the bark() method is "prv" (private). I would like to know how can I make the struct be aware of it's instances so I can make the dog bark each time it runs (calling a private method from a public method).
Thanks in advance
Your interpreter is going to need to keep an execution stack and environment (otherwise you wouldn't know where to return to after a method is finished, etc.).
In this execution stack/env, apart from a function pointer/signature, you'd also keep the object the method is being invoked on (if any, remember about static-like functions).
This reference that you'd store would then be also accessed when de-referencing $this. And actually this is both part 1 and 2 of your idea - you could put some kind of checks like visibility of methods etc. there.
Good luck, sounds like a fun project!
Related
Example:
data class T(val flag: Boolean) {
constructor(n: Int) : this(run {
// Some computation here...
<Boolean result>
})
}
In this example, the custom constructor needs to run some computation in order to determine which value to pass to the primary constructor, but the compiler does not accept the run, citing Cannot access 'run' before superclass constructor has been called, which, if I understand correctly, means instead of interpreting it as the non-extension run (the variant with no object reference in https://kotlinlang.org/docs/reference/scope-functions.html#function-selection), it construes it as a call to this.run (the variant with an object reference in the above table) - which is invalid as the object has not completely instantiated yet.
What can I do in order to let the compiler know I mean the run function which is not an extension method and doesn't take a scope?
Clarification: I am interested in an answer to the question as asked, not in a workaround.
I can think of several workarounds - ways to rewrite this code in a way that works as intended without calling run: extracting the code to a function; rewriting it as a (possibly highly nested) let expression; removing the run and invoking the lambda (with () after it) instead (funnily enough, IntelliJ IDEA tags that as Redundant lambda creation and suggests to Inline the body, which reinstates the non-compiling run). But the question is not how to rewrite this without using run - it's how to make run work in this context.
A good answer should do one of the following things:
Explain how to instruct the compiler to call a function rather than an extension method when a name is overloaded, in general; or
Explain how to do that specifically for run; or
Explain that (and ideally also why) it is not possible to do (ideally with supporting references); or
Explain what I got wrong, in case I got something wrong and the whole question is irrelevant (e.g. if my analysis is incorrect, and the problem is something other than the compiler construing the call to run as this.run).
If someone has a neat workaround not mentioned above they're welcome to post it in a comment - not as an answer.
In case it matters: I'm using multi-platform Kotlin 1.4.20.
Kotlin favors the receiver overload if it is in scope. The solution is to use the fully qualified name of the non-receiver function:
kotlin.run { //...
The specification is explained here.
Another option when the overloads are not in the same package is to use import renaming, but that won't work in this case since both run functions are in the same package.
Sorry for the terrible title, but I can't seem to find an allowable way to ask this question, because I don't know how to refer to the code constructs I am looking at.
Looking at this file: https://github.com/Hexworks/caves-of-zircon-tutorial/blob/master/src/main/kotlin/org/hexworks/cavesofzircon/systems/InputReceiver.kt
I don't understand what is going on here:
override fun update(entity: GameEntity<out EntityType>, context: GameContext): Boolean {
val (_, _, uiEvent, player) = context
I can understand some things.
We are overriding the update function, which is defined in the Behavior class, which is a superclass of this class.
The update function accepts two parameters. A GameEntity named entity, and a GameContext called context.
The function returns a Boolean result.
However, I do not understand the next line at all. Just open and close parentheses, two underscores as the first two parameters, and then an assignment to the context argument. What is it we are assigning the value of context to?
Based on IDE behavior, apparently the open-close parentheses are related to the constructor for GameContext. But I would not know that otherwise. I also don't understand what the meaning is of the underscores in the argument list.
And finally, I have read about the declaration-site variance keyword "out", but I don't really understand what it means here. We have GameEntity<out EntityType>. So as I understand it, that means this method produces EntityType, but does not consume it. How is that demonstrated in this code?
val (_, _, uiEvent, player) = context
You are extracting the 3rd and 4th value from the context and ignoring the first two.
Compare https://kotlinlang.org/docs/reference/multi-declarations.html .
About out: i don't see it being used in the code snippet you're showing. You might want to show the full method.
Also, maybe it is there only for the purpose of overriding the method, to match the signature of the function.
To cover the little bit that Incubbus's otherwise-great answer missed:
In the declaration
override fun update(entity: GameEntity<out EntityType>, // …
the out means that you could call the function and pass a GameEntity<SubclassOfEntityType> (or even a SubclassOfGameEntity<SubclassOfEntityType>).
With no out, you'd have to pass a GameEntity<EntityType> (or a SubclassOfGameEntity<EntityType>).
I guess that's inherited from the superclass method that you're overriding. After all, if the superclass method could be called with a GameEntity<SubclassOfEntityType>, then your override will need to handle that too. (The Liskov substitution principle in action!)
This question already has answers here:
Difference between . and : in Lua
(3 answers)
Closed 8 years ago.
I'm still playing around with lua modules and I've found the following "interesting" issue that occurs depending on how you create your methods / functions inside a module.
Note the following code in a file called test_suite.lua:
local mtests = {} -- public interface
function mtests:create_widget(arg1)
print(arg1)
-- does something
assert(condition)
print("TEST PASSED")
end
return mtests
Using the above code, arg1 is always nil, no matter what I pass in when calling create_widget(). However, if I change the definition of the function to look like this:
function mtests.create_widget(arg1) -- notice the period instead of colon
print(arg1)
-- does something
assert(condition)
print("TEST PASSED")
end
then, the system displays arg1 properly.
This is how I call the method:
execute_test.lua
local x = require "test_suite"
x.create_widget(widgetname)
Can you tell me what the difference is? I've been reading: http://lua-users.org/wiki/ModuleDefinition
But I haven't come across anything that explains this to me.
Thanks.
All a colon does in a function declaration is add an implicit self argument. It's just a bit of syntactic sugar.
So if you're calling this with (assuming you assign the mtests table to foo), foo.create_widget(bar), then bar is actually assigned to self, and arg1 is left unassigned, and hence nil.
foo = {}
function foo:bar(arg)
print(self)
print(arg)
end
Calling it as foo.bar("Hello") prints this:
Hello
nil
However, calling it as foo:bar("Hello") or foo.bar(foo, "Hello") gives you this:
table: 0xDEADBEEF (some hex identifier)
Hello
It's basically the difference between static and member methods in a language like Java, C#, C++, etc.
Using : is more or less like using a this or self reference, and your object (table) does not have a arg1 defined on it (as something like a member). On the other way, using . is just like defining a function or method that is part of the table (maybe a static view if you wish) and then it uses the arg1 that was defined on it.
. defines a static method / member, a static lib, Which means you can't create a new object of it. static methods / libs are just for having some customized functions like printing or download files from the web, clearing memory and...
: Is used for object members, members that are not static. These members change something in an object, for example clearing a specified textbox, deleting an object and...
Metamethod functions(Functions that have :) can be made in lua tables or C/C++ Bindings. a metamethod function is equal to something like this on a non-static object:
function meta:Print()
self:Remove()
end
function meta.Print(self)
self:Remove()
end
Also, with . you can get a number/value that doesn't require any call from a non-static or static object. For example:
-- C:
int a = 0;
-- Lua:
print(ent.a)
-- C:
int a()
{
return 0;
}
-- Lua:
print(ent:a())
same function on a static member would be:
print(entlib.a())
Basically, each non-static object that has a function that can be called will be converted to : for better use.
Smalltalk syntax (and features) can be found pretty exotic (and even disturbing) when you come from a more C-like syntax world. I found myself losing time with some
I would be interested in learning knowing what you found really exotic compared to more classic/mainstream languages and that you think helps to understand the language.
For example, evaluation with logic operators :
(object1 = object2) & (object3 = object4) : this will evaluate the whole expression, even if the left part is false, the rest will be evaluated.
(object1 = object2) and: [object3 = object4] : this will evaluate the left part, and only will evaluate the right part if the first is true.
Everything is an object, and everything above the VM's available for inspection and modification. (Primitives are part of the VM, conceptually at least.) Even your call stack's available (thisContext) - Seaside implemented continuations back in the day by simply swizzling down the call stack into a stream, and restoring it (returning to the continuation) by simply reading out activation frames from that stream!
You can construct a selector from a string and turn it into a Symbol and send it as a message: self perform: 'this', 'That' will do the same thing as self thisThat. (But don't do this, for the same reasons you should avoid eval in both Lisps and PHP: very hard to debug!)
Message passing: it's not method invocation!
#become: is probably a bit of a shock to anyone who hasn't seen it before. (tl;dr a wholesale swapping of two object pointers - all references to B now point to A, and all references to A now point to B)
Primitves
someMethod
<primitive 14122 wtf>
"fail and execute the following"
[self] inlineCopyInject: [:t1 | self].
My first wrestling session with Smalltalk was the metaclass implementation.
Consider this:
What is the class of 'This is a string'? Well, something like String.
What is the class of String? String class. Note: this is a class, but it has no name, it just prints itself as 'String class'.
What is the class of String class? Metaclass. Note: this is a named class.
What is the class of Metaclass? As you might expect (or not) this is Metaclass class. Of which, again as you might expect, the class is Metaclass again.
This is the first circularity. Another one which I found rather esoteric at first (of course, now I eat metaclasses for breakfast) is the next one:
What is the superclass of String? Object (eventually, different implementations of Smalltalk have different class hierarchies of these basic classes).
What is the superclass of Object? nil. Now this is an interesting answer in Smalltalk, because it actually is an object! nil class answers UndefinedObject. Of which the superclass is ... Object.
Navigating through the superclass and instance of relations was a real rollercoster ride for me in those days...
How about selective breakpointing (which I actually use at times):
foo
thisContext sender selector == #bar ifTrue:[ self halt ].
...
will debug itself, but only if called from bar. Useful, if foo is called for from zillion other places and a regular breakpoint hits too often.
I've always been fond of the Smalltalk quine:
quine
^thisContext method getSource
(Pharo version.)
I have a class and I want to change the name of a specific method in run time.
I guess there's a method in the 'Behavior' class that does it. But I just can't find it. any help? [in squeak]
The normal way a user does this is to modify the method source and 'accept it' then delete the old version. So it's not likely that basic Squeak includes a single method to do this, although I could be wrong.
However if you install, for example, OmniBrowser there is a method refactoring called 'rename' and you could inspect and find code to perform this refactoring. It is fairly complex, firstly because the refactorings are done using the command pattern which involves a little redirection to work out, but secondly because this is a fairly complex refactoring which includes modifying the call sites.
What you are suggesting puts HUGE red flags up for me.
What is it you are trying to accomplish with this?
Do you mean you want to change the name of the method you are calling at runtime?
If so, that's easy.
do something like:
|methodName|
methodName := self useMethod1 ifTrue: [#method1 ] ifFalse:[ #method2 ].
self perform: methodName.
You best use a refactoring
r := RenameMethodRefactoring
renameMethod: #foo:foo:
in: Foo
to: #bar:bar:
permutation: (1 to: #foo:foo: numArgs).
r execute.
Avoid voodoo magic in real code when possible.
That being said you can do some very interesting things by manipulating methods dynamically.
For instance the code bricks in Etoys are translated into Smalltalk methods. Other DSL implementations can also benefit from similar metaprogramming tricks.
After experimenting a bit I came up with the following code for renaming unary methods:
renameMethod: oldMethod inClass: class to: newMethod
| oldSelector newSelector source parser |
oldSelector := oldMethod asSymbol.
newSelector := newMethod asSymbol.
oldSelector = newSelector ifTrue: [^self].
"Get method category"
category := (LocatedMethod location: class selector: oldSelector) category.
"Get method source code"
source := class sourceCodeAt: oldSelector.
"Replace selector in method source"
(parser := class parserClass new) parseSelector: source.
source := (newSelector asString), (source allButFirst: parser endOfLastToken).
"Compile modified source"
class compile: source classified: category.
"Remove old selector"
class removeSelector: oldSelector
You could probably find an easier way to do this if you browse through the Squeak code a bit longer than I did.
You can't change a method's name, really, because it doesn't have one.
An object's method dictionary maps Symbols to CompiledMethods. "Change the name of a method" means "move the CompiledMethod value from this key to that key".