RBParser message nodes and targeting the receiver and the argument? - pharo

Trying to get some of my old code up and running in Pharo. Some method names are different but after some hardship I managed to find equivalents that work.
I am parsing my code and I'd like to check if the receiver or any of the arguments is aSymbol in an effort to match them to supported alternatives. I've managed to do this to selectors, by analysing RBMessageNode s
aNode selector == aSymbol ifTrue: [ aNode selector: replacementSymbol ].
How can this be done to arguments and receivers? Is there a comprehensive guide on RBParser somewhere?

By direct manipulation
Assuming that you are looking for cases like this:
aSymbol message: aSymbol message: aSymbol
For receiver you should do:
(aNode isMessage and: [
aNode receiver isVariable and: [
aNode receiver name = 'aSymbol' ]]) ifTrue: [
"do your job here" ]
Here is another example on how to replace #aSymbol arguments with #newSymbol:
messageNode arguments: (messageNode arguments collect: [ :arg |
(arg isLiteralNode and: [ arg value = #aSymbol ])
ifFalse: [ arg ]
ifTrue: [ | newNode |
newNode := #aNewSymbol asLiteralNode.
arg replaceSourceWith: newNode.
newNode ] ]).
methodClass compile: ast newSource
The replaceSourceWith: makes sure that just a source will be replaced, but for newSource to actually return a new source you also need to swap the nodes themselves, that's why I'm doing a collect on arguments and return the new ones where needed.
You can view help about RBParser in Word Menu > Help > Help Browser > Refactoring Framework.
You can also play around by inspecting
RBParser parseExpression: 'aSymbol message: aSymbol message: aSymbol'
and looking at its contents
By Parse Tree Transformation
You can use pattern code to match and replace certain code. For example to change the symbol argument of a perform: message you can do this:
ast := yourMethod parseTree.
rewriter := RBParseTreeRewriter new
replace: '`receiver perform: #aSymbol'
with: '`receiver perform: #newSelector'.
(rewriter executeTree: ast) ifTrue: [
yourMethod class compile: ast newSource ]
You can learn more about the pattern matching syntax in the help topic Word Menu > Help > Help Browser > Refactoring Framework > Refactoring Engine > RBPatternParser …. I thing that MatchTool from pharo catalog can greatly help you in testing the match expressions (it also has a dedicated help topic about the matching syntax) while RewriteTool can help you to preview how your code will be transformed.

Related

How to use warm starts in Minizinc?

I'm trying to use the warm start anotation in Minizinc to give a known suboptimal solution to a model.
I started by trying to execute this warm start example from the Minizinc documentation (the only one they provide):
array[1..3] of var 0..10: x;
array[1..3] of var 0.0..10.5: xf;
var bool: b;
array[1..3] of var set of 5..9: xs;
constraint b+sum(x)==1;
constraint b+sum(xf)==2.4;
constraint 5==sum( [ card(xs[i]) | i in index_set(xs) ] );
solve
:: warm_start_array( [ %%% Can be on the upper level
warm_start( x, [<>,8,4] ), %%% Use <> for missing values
warm_start( xf, array1d(-5..-3, [5.6,<>,4.7] ) ),
warm_start( xs, array1d( -3..-2, [ 6..8, 5..7 ] ) )
] )
:: seq_search( [
warm_start_array( [ %%% Now included in seq_search to keep order
warm_start( x, [<>,5,2] ), %%% Repeated warm_starts allowed but not specified
warm_start( xf, array1d(-5..-3, [5.6,<>,4.7] ) ),
warm_start( xs, array1d( -3..-2, [ 6..8, 5..7 ] ) )
] ),
warm_start( [b], [true] ),
int_search(x, first_fail, indomain_min)
] )
minimize x[1] + b + xf[2] + card( xs[1] intersect xs[3] );
The example runs, and it gets the optimal solution. However, the output displays warnings stating all the warm start anotations were ignored.
Warning, ignored search annotation: warm_start_array([warm_start([[xi(1), xi(2)], [i(5), i(2)]]), warm_start([[xf(0), xf(2)], [f(5.6), f(4.7)]]), warm_start([[xs(0), xs(1), xs(2)], [s(), s()]])])
Warning, ignored search annotation: warm_start([[xb(0)], [b(true)]])
Warning, ignored search annotation: warm_start_array([warm_start([[xi(1), xi(2)], [i(8), i(4)]]), warm_start([[xf(0), xf(2)], [f(5.6), f(4.7)]]), warm_start([[xs(0), xs(1), xs(2)], [s(), s()]])])
I didnt modified anything in the example, just copy-pasted it and ran it in the Minizinc IDE with the Geocode default solver. In case it is relevant, I'm using Windows. I have ran other models and used other search anotations without problems.
In the example there is two blocks of warm stars (one after solve and one inside seq_search). I'm not sure if both are necessary. I tried removing one, then the other, but the warnings still happen for all the remaining warm start anotations. Also I dont get why 'b' isnt refered in the fisrt block.
There is a similar example in git https://github.com/google/or-tools/issues/539 but it also produces the warnings.
If someone could point me out to a working example of warm_start it would be great.
Your usage of the warm_start annotations are correct, but warm start annotations are currently not supported in most solvers. At the time of writing I believe the warm start annotations are only supported by the Mixed Integer Programming interfaces (CoinBC, Gurobi, CPlex, XPress, and SCIP). Although we've been working on adding support for the annotation in Gecode and Chuffed, support for this annotation has not been included in any of the released versions.

Why file path string is not splitting

I want to find files in a directory, then split the pathname and print each part of path on a separate line:
(Directory working: '.')
allFilesMatching: '*.st' do: [ :ff | (ff name)
findTokens: '/' "Linux separator"
"splitOn: '/' -this also does not work"
do: [ :i|
i displayNl ]]
However it is giving following error:
$ gst firstline.st
"Global garbage collection... done"
Object: '/home/abcd/firstline.st' error: did not understand #findTokens:do:
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
String(Object)>>doesNotUnderstand: #findTokens:do: (SysExcept.st:1448)
optimized [] in UndefinedObject>>executeStatements (firstline.st:3)
[] in Kernel.RecursiveFileWrapper(FilePath)>>filesMatching:do: (FilePath.st:903)
[] in Kernel.RecursiveFileWrapper>>namesDo:prefixLength: (VFS.st:378)
[] in File>>namesDo: (File.st:589)
BlockClosure>>ensure: (BlkClosure.st:268)
File>>namesDo: (File.st:586)
Kernel.RecursiveFileWrapper>>namesDo:prefixLength: (VFS.st:373)
Kernel.RecursiveFileWrapper>>namesDo: (VFS.st:396)
Kernel.RecursiveFileWrapper(FilePath)>>filesMatching:do: (FilePath.st:902)
File(FilePath)>>allFilesMatching:do: (FilePath.st:775)
Directory class>>allFilesMatching:do: (Directory.st:225)
UndefinedObject>>executeStatements (firstline.st:2)
The error message is really long and complex!
Both findTokens and splitOn are not working.
Where is the problem and how can this be solved.
The message maybe long but the line says the reason:
Object: '/home/abcd/firstline.st' error: did not understand #findTokens:do
You probably want to use a split differently, probably using subStrings: $character. I just tried it on GNU Smalltalk windows version:
The command:
'C:\prg_sdk\GNU Smalltalk(x86)\share\smalltalk\unsupported\torture.st' subStrings: $\
The result:
OrderedCollection ('C:' 'prg_sdk' 'GNU Smalltalk(x86)' 'share' 'smalltalk' 'unsupported' 'torture.st' )
Where you get your path when you have it in the collection. You start either from beginning or end.
For example you can start from beginning like this:
resultPath := nil.
pathCollection := 'C:\prg_sdk\GNU Smalltalk(x86)\share\smalltalk\unsupported\torture.st' subStrings: $\.
pathCollection do: [ :eachPartPath |
resultPath := (resultPath isNil) ifTrue: [
eachPartPath
] ifFalse: [
resultPath, '\', eachPartPath
].
resultPath displayNl
]

AutoHotKey: read of two underscore keys

One part of my AutoHotKey script should recognize if __ is typed.
Following the AutoHotKey documentation, I've tried:
~__::
tooltip,hi world
return
and got this error:
Line Text: ~__::
Error: Invalid hotkey.
this shows no errors, but works only for one underscore:
~_::
tooltip,hi world
return
this shows no errors, but it just clears the __:
:*:__::
tooltip,hi world
return
this shows error Error: Invalid hotkey.:
~:*:__::
tooltip,hi world
return
this shows no errors, but does nothing (Doku: Executehotstring) :
:X:~__::
tooltip,hi world
return
Here are 4 potential solutions. I have left one working, comment out/uncomment hotkey labels by adding/removing leading semicolons as appropriate.
The 2 blocks of code are functionally equivalent, and for the 2 alternatives, within each block, b0 prevents automatic backspacing, i.e. the underscores that you typed are not deleted.
;:*?:__:: ;deletes the underscores
:b0*?:__:: ;does not delete the underscores
SoundBeep
return
;note: the X option requires AHK v1.1.28+
;:X*?:__::SoundBeep ;deletes the underscores
;:Xb0*?:__::SoundBeep ;does not delete the underscores
This AutoHotKey recognize if __ is typed:
countUnderscore :=0
~_::
countUnderscore++
if(countUnderscore == 2){
tooltip, %countUnderscore% = countUnderscore
countUnderscore := 0
}
return

AC_ARG_ENABLE in an m4_foreach_w loop: no help string

I wish to generate a lot of --enable-*/--disable-* options by something like:
COMPONENTS([a b c], [yes])
where the second argument is the default value of the automatic enable_* variable. My first attempt was to write an AC_ARG_ENABLE(...) within an m4_foreach_w, but so far, I'm only getting the first component to appear in the ./configure --help output.
If I add hand-written AC_ARG_ENABLEs, they work as usual.
Regardless, the --enable-*/--disable-* options work as they should, just the help text is missing.
Here's the full code to reproduce the problem:
AC_INIT([foo], 1.0)
AM_INIT_AUTOMAKE([foreign])
AC_DEFUN([COMPONENTS],
[
m4_foreach_w([component], [$1], [
AS_ECHO(["Processing [component] component with default enable=$2"])
AC_ARG_ENABLE([component],
[AS_HELP_STRING([--enable-[]component], [component] component)],
,
[enable_[]AS_TR_SH([component])=$2]
)
])
AC_ARG_ENABLE([x],
[AS_HELP_STRING([--enable-[]x], [component x])],
,
[enable_[]AS_TR_SH([x])=$2]
)
AC_ARG_ENABLE([y],
[AS_HELP_STRING([--enable-[]y], [component y])],
,
[enable_[]AS_TR_SH([y])=$2]
)
])
COMPONENTS([a b c], [yes])
for var in a b c x y; do
echo -n "\$enable_$var="
eval echo "\$enable_$var"
done
AC_CONFIG_FILES(Makefile)
AC_OUTPUT
And an empty Makefile.am. To verify that the options work:
$ ./configure --disable-a --disable-b --disable-d --disable-x
configure: WARNING: unrecognized options: --disable-d
...
Processing component a with default enable=yes
Processing component b with default enable=yes
Processing component c with default enable=yes
$enable_a=no
$enable_b=no
$enable_c=yes
$enable_x=no
$enable_y=yes
After I poked around in autoconf sources, I figured out this has to do with the m4_divert_once call in the implementation of AC_ARG_ENABLE:
# AC_ARG_ENABLE(FEATURE, HELP-STRING, [ACTION-IF-TRUE], [ACTION-IF-FALSE])
# ------------------------------------------------------------------------
AC_DEFUN([AC_ARG_ENABLE],
[AC_PROVIDE_IFELSE([AC_PRESERVE_HELP_ORDER],
[],
[m4_divert_once([HELP_ENABLE], [[
Optional Features:
--disable-option-checking ignore unrecognized --enable/--with options
--disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
--enable-FEATURE[=ARG] include FEATURE [ARG=yes]]])])dnl
m4_divert_once([HELP_ENABLE], [$2])dnl
_AC_ENABLE_IF([enable], [$1], [$3], [$4])dnl
])# AC_ARG_ENABLE
# m4_divert_once(DIVERSION-NAME, CONTENT)
# ---------------------------------------
# Output CONTENT into DIVERSION-NAME once, if not already there.
# An end of line is appended for free to CONTENT.
m4_define([m4_divert_once],
[m4_expand_once([m4_divert_text([$1], [$2])])])
I'm guessing that the HELP-STRING argument is remembered in it's unexpanded form, so it is added just once for all components. Manually expanding the AC_HELP_STRING does what I want:
AC_DEFUN([COMPONENTS],
[
m4_foreach_w([comp], [$1], [
AS_ECHO(["Processing component 'comp' with default enable=$2"])
AC_ARG_ENABLE([comp],
m4_expand([AS_HELP_STRING([--enable-comp], enable component comp)]),
,
[enable_[]AS_TR_SH([comp])=$2]
)
])
])
COMPONENTS([a b c x y], [yes])
I couldn't find a way to properly quote components so that it appears as a string, after being used as the loop variable in m4_foreach_w, so I just renamed it to spare me the trouble.

Alex lex.x compilation : Not in scope 'begin'

I have the below statements in Lex.x to parse block comments.
<0> "//".* { tokWValue LTokComment }
<0> "/*" { begin blockcomment }
<blockcomment> "*/" { begin 0 }
<blockcomment> . { tokWValue LTokComment }
But If I generate Lex.hs using Alex, it does not add the 'begin' function.
This results in the below compilation error.
src/Lex.x:367:18: Not in scope: ‘begin’
src/Lex.x:368:18: Not in scope: ‘begin’
Any idea what might be wrong?
I am using wrapper 'posn'
Start codes are only available when using any of the monad-... wrappers.
If you read the docs for the monad wrapper -- Section 5.3.3 - The "monad" wrapper -- you see that it is the first wrapper which keeps track of the start code.
You can also verify this by finding the alex wrapper files -- look for the directory containing the files AlexWrapper-basic, AlexWrapper-posn, etc. On OS X when installing the Haskell Platform they are located in a directory like /Library/Haskell/ghc-7.10.2-x86_64/share/alex-3.1.4. The functions begin and andBegin only occur in the monad-related wrappers.

Resources