Macro that will mimic new from c#
От: Liviu1  
Дата: 23.08.11 21:13
Оценка:
Hi all,

I am coming from a c# world and i am confused by the lack of "new" keyword.
I would like to define a "new" macro that will offer additional functionality, for example: new IMyInterface() => meaning : use some IOC to find an implementation of IMyInterface.

1) A problem is that "new" is reserved keyword and i cannot define a macro for it.

But even if i use another name, "New" for example, the macro compiles ok, but the use of it fails:

/out:obj\Debug\CodeGenMacrosTests.dll
F:\Projects\NemerleTests\ConsoleApplication1\CodeGenMacrosTests\Tests.n(19,29): error : parse error near `(...)' group: unexpected end of token sequence
F:\Projects\NemerleTests\ConsoleApplication1\CodeGenMacrosTests\Tests.n(19,29): error : parse error near separator or closing bracket: expecting `(' and some tokens inside
F:\Projects\NemerleTests\ConsoleApplication1\CodeGenMacrosTests\Tests.n(19,19): error : unable to parse syntax rule, stopped at: )
Done building project "CodeGenMacrosTests.nproj" -- FAILED.


namespace CSharp
{
macro New(typeName : PExpr)
// See: http://nemerle.org/wiki/Macros_tutorial#Adding_new_syntax_to_the_compiler and http://nemerle.org/wiki/Syntax_extensions
syntax ("New", typeName, "(",")")
{
Macro1Impl.DoTransform(Macros.ImplicitCTX(), typeName)
}

module Macro1Impl
{
public DoTransform(typer : Typer, typeName : PExpr) : PExpr
{
Macros.DefineCTX(typer);

<[ $typeName() ]>
}
}
}

USAGE:
module TestNew
{
TestNew() : void
{
def a = New object();// <= ERROR IS HERE BEFORE ()
}
}


What am i doing wrong?

Thank you
Re: Macro that will mimic new from c#
От: hardcase Пират http://nemerle.org
Дата: 24.08.11 10:27
Оценка:
Здравствуйте, Liviu1, Вы писали:

L>Hi all,


Hi!

L>I am coming from a c# world and i am confused by the lack of "new" keyword.

L>I would like to define a "new" macro that will offer additional functionality, for example: new IMyInterface() => meaning : use some IOC to find an implementation of IMyInterface.


L>1) A problem is that "new" is reserved keyword and i cannot define a macro for it.


It is not a problem to use it, but there is already exists macro "new" in Nemerle standard macro library. It simply creates anonymous type (like "new { ... }" expression in C#). Here is implementation, and usage:
using Nemerle.Extensions;

def foo = new(a = 10, b = "b");

Any anonymous class instance implements IAnonymous interface (it allows dictionary-like access).

L>But even if i use another name, "New" for example, the macro compiles ok, but the use of it fails:


L>What am i doing wrong?


Your mistake is here:
syntax ("New", typeName, "(",")")

typeName is expression so parentesies are redundant here. Right declaration should use pattern matching. Here is example:
  macro Resolve(typeName)
      syntax("resolve", typeName)
  {
    // valid type names are simple names like 'foo'
    //  or fully qualified names like 'foo.bar'
    //  or generic ones 'foo.bar.[baz]' (dot before square brace is required)
    def isValidTypeName(_)
    {
      | <[ $(_ : name) ]> => true
      | <[ $ns.$(_ : name) ]> => isValidTypeName(ns)

      | <[ $(_ : name).[ ..$typeArgs] ]> when !typeArgs.IsEmpty =>
        typeArgs.ForAll(isValidTypeName)

      | <[ $ns.$(_ : name).[ ..$typeArgs] ]> when !typeArgs.IsEmpty =>
        isValidTypeName(ns) && typeArgs.ForAll(isValidTypeName)

      | _ => false
    }
    if(isValidTypeName(typeName))
    {
      <[ $typeName () ]> // just call default constructor
    }
    else
    {
      Message.Error(typeName.Location, "valid type name expected");
      <[ () ]>
    }
  }

Usually accessing instance via IoC container is called "resolving". I think that calling macro "Resolve" this is better than "new".

Usage of that macro:
      def table = resolve System.Collections.Generic.Dictionary.[int, string];
      WriteLine(table);



P.S. Actual type (FixedType instance) can be accessed by:
def typer = Macros.ImplicitCTX();
def ft = typer.Env.BindFixedType(typeName);
/* иЗвиНите зА неРовнЫй поЧерК */
Re[2]: Macro that will mimic new from c#
От: Liviu1  
Дата: 24.08.11 10:40
Оценка:
Здравствуйте, hardcase,


Yes,
The resolve macro you sketched is ok. I did not know how to resolve the type, thank you for the details.
I succeeded implementing the "new" macro using @new as macro name.
What bothers me is that i cannot define a macro that takes parameters inside paranthesis:

macro X( name1, args)
syntax("X", name1, "(", Optional(args), ")")

that will match:

X A()
X A(p1)
X A(p1, p2)

This will give a compile error around () and even a null exception inside the Nemerle Compiler...


Вы писали:

H>Здравствуйте, Liviu1, Вы писали:


L>>Hi all,


H>Hi!


L>>I am coming from a c# world and i am confused by the lack of "new" keyword.

L>>I would like to define a "new" macro that will offer additional functionality, for example: new IMyInterface() => meaning : use some IOC to find an implementation of IMyInterface.


L>>1) A problem is that "new" is reserved keyword and i cannot define a macro for it.


H>It is not a problem to use it, but there is already exists macro "new" in Nemerle standard macro library. It simply creates anonymous type (like "new { ... }" expression in C#). Here is implementation, and usage:

H>
H>using Nemerle.Extensions;

H>def foo = new(a = 10, b = "b");
H>

H>Any anonymous class instance implements IAnonymous interface (it allows dictionary-like access).

L>>But even if i use another name, "New" for example, the macro compiles ok, but the use of it fails:


L>>What am i doing wrong?


H>Your mistake is here:

H>
H>syntax ("New", typeName, "(",")")
H>

H>typeName is expression so parentesies are redundant here. Right declaration should use pattern matching. Here is example:
H>
H>  macro Resolve(typeName)
H>      syntax("resolve", typeName)
H>  {
H>    // valid type names are simple names like 'foo'
H>    //  or fully qualified names like 'foo.bar'
H>    //  or generic ones 'foo.bar.[baz]' (dot before square brace is required)
H>    def isValidTypeName(_)
H>    {
H>      | <[ $(_ : name) ]> => true
H>      | <[ $ns.$(_ : name) ]> => isValidTypeName(ns)

H>      | <[ $(_ : name).[ ..$typeArgs] ]> when !typeArgs.IsEmpty =>
H>        typeArgs.ForAll(isValidTypeName)

H>      | <[ $ns.$(_ : name).[ ..$typeArgs] ]> when !typeArgs.IsEmpty =>
H>        isValidTypeName(ns) && typeArgs.ForAll(isValidTypeName)

H>      | _ => false
H>    }
H>    if(isValidTypeName(typeName))
H>    {
H>      <[ $typeName () ]> // just call default constructor
H>    }
H>    else
H>    {
H>      Message.Error(typeName.Location, "valid type name expected");
H>      <[ () ]>
H>    }
H>  }
H>

H>Usually accessing instance via IoC container is called "resolving". I think that calling macro "Resolve" this is better than "new".

H>Usage of that macro:

H>
H>      def table = resolve System.Collections.Generic.Dictionary.[int, string];
H>      WriteLine(table);
H>



H>P.S. Actual type (FixedType instance) can be accessed by:

H>
H>def typer = Macros.ImplicitCTX();
H>def ft = typer.Env.BindFixedType(typeName);
H>
Re[3]: Macro that will mimic new from c#
От: hardcase Пират http://nemerle.org
Дата: 24.08.11 10:48
Оценка:
Здравствуйте, Liviu1, Вы писали:

L>Здравствуйте, hardcase,



L>Yes,

L> The resolve macro you sketched is ok. I did not know how to resolve the type, thank you for the details.
L> I succeeded implementing the "new" macro using @new as macro name.
L> What bothers me is that i cannot define a macro that takes parameters inside paranthesis:

L> macro X( name1, args)

L> syntax("X", name1, "(", Optional(args), ")")

L>that will match:


L> X A()

L> X A(p1)
L> X A(p1, p2)

L>This will give a compile error around () and even a null exception inside the Nemerle Compiler...


Paranthesis are eaten by parser. Its meaning for parser is PExpr.Call.

To get such syntax work you have to parse options manually. This is not hard:
  macro Resolve(expr)
      syntax("resolve", expr)
  {
    def (typeName, options) = match(expr)
    {
      | <[ $typeName ( ..$options ) ]> => (typeName, options)
      | _ => (expr, [])
    };

    // valid type names are simple names like 'foo'
    //  or fully qualified names like 'foo.bar'
    //  or generic ones 'foo.bar[baz]'
    def isValidTypeName(_)
    {
      | <[ $(_ : name) ]> => true
      | <[ $ns.$(_ : name) ]> => isValidTypeName(ns)

      | <[ $(_ : name).[ ..$typeArgs] ]> when !typeArgs.IsEmpty =>
        typeArgs.ForAll(isValidTypeName)

      | <[ $ns.$(_ : name).[ ..$typeArgs] ]> when !typeArgs.IsEmpty =>
        isValidTypeName(ns) && typeArgs.ForAll(isValidTypeName)

      | _ => false
    }
    if(isValidTypeName(typeName))
    {
      <[ $typeName () ]> // invocation of default ctor
    }
    else
    {
      Message.Error(typeName.Location, "valid type name expected");
      <[ () ]>
    }
  }
/* иЗвиНите зА неРовнЫй поЧерК */
Re[4]: Macro that will mimic new from c#
От: Liviu1  
Дата: 24.08.11 15:04
Оценка:
Здравствуйте, hardcase

I SUCCEEDED. The key was to call the original "new" NEMERLE MACRO by hand. Simple example without any type checking:


namespace CSharp
{

macro @new(expr)
syntax ("new", expr)
{
Macro1Impl.DoTransform(Macros.ImplicitCTX(), expr)
}

module Macro1Impl
{
public DoTransform(typer : Typer, expr : PExpr) : PExpr
{
Macros.DefineCTX(typer);

def (typeName,options) = match(expr)
{
| <[ $typeName ( ..$options ) ]> => (typeName, options)
| <[ ( ..$options ) ]> => (null, options)
| _ => (expr, []);
}

if (typeName != null)
<[ $typeName ( ..$options )]>
else
{
def mcr = Nemerle.Extensions. AnonymousClassNormalCtorMacro();
def anonym = mcr.Run(typer, mcr.CallTransform(options));
<[ $anonym ]>
}
}
}
}



REGARDS



H>Здравствуйте, Liviu1, Вы писали:


L>>Здравствуйте, hardcase,



L>>Yes,

L>> The resolve macro you sketched is ok. I did not know how to resolve the type, thank you for the details.
L>> I succeeded implementing the "new" macro using @new as macro name.
L>> What bothers me is that i cannot define a macro that takes parameters inside paranthesis:

L>> macro X( name1, args)

L>> syntax("X", name1, "(", Optional(args), ")")

L>>that will match:


L>> X A()

L>> X A(p1)
L>> X A(p1, p2)

L>>This will give a compile error around () and even a null exception inside the Nemerle Compiler...


H>Paranthesis are eaten by parser. Its meaning for parser is PExpr.Call.


H>To get such syntax work you have to parse options manually. This is not hard:

H>
H>  macro Resolve(expr)
H>      syntax("resolve", expr)
H>  {
H>    def (typeName, options) = match(expr)
H>    {
H>      | <[ $typeName ( ..$options ) ]> => (typeName, options)
H>      | _ => (expr, [])
H>    };

H>    // valid type names are simple names like 'foo'
H>    //  or fully qualified names like 'foo.bar'
H>    //  or generic ones 'foo.bar[baz]'
H>    def isValidTypeName(_)
H>    {
H>      | <[ $(_ : name) ]> => true
H>      | <[ $ns.$(_ : name) ]> => isValidTypeName(ns)

H>      | <[ $(_ : name).[ ..$typeArgs] ]> when !typeArgs.IsEmpty =>
H>        typeArgs.ForAll(isValidTypeName)

H>      | <[ $ns.$(_ : name).[ ..$typeArgs] ]> when !typeArgs.IsEmpty =>
H>        isValidTypeName(ns) && typeArgs.ForAll(isValidTypeName)

H>      | _ => false
H>    }
H>    if(isValidTypeName(typeName))
H>    {
H>      <[ $typeName () ]> // invocation of default ctor
H>    }
H>    else
H>    {
H>      Message.Error(typeName.Location, "valid type name expected");
H>      <[ () ]>
H>    }
H>  }
H>
Re: Macro that will mimic new from c#
От: VladD2 Российская Империя www.nemerle.org
Дата: 24.08.11 17:42
Оценка:
Здравствуйте, Liviu1, Вы писали:

L>Hi all,


Это русскоязычный форум. По правилам этого форума общение на других языках на нем запрещено.
Кроме того этот форум не читают англоязычные члены комьюнити.
Вопросы на английском лучше задавать на https://groups.google.com/forum/#!forum/nemerle-en

This is a Russian-language forum. According to the rules of this forum communication in other languages ​​is prohibited.
Also this forum do not read English-language community members.
Will be better if you to ask your questions in https://groups.google.com/forum/#!forum/nemerle-en
Есть логика намерений и логика обстоятельств, последняя всегда сильнее.
Re[2]: Macro that will mimic new from c#
От: Liviu1  
Дата: 24.08.11 17:59
Оценка: +1
Здравствуйте, VladD2, Вы писали:

VD>Здравствуйте, Liviu1, Вы писали:


L>>Hi all,


VD>Это русскоязычный форум. По правилам этого форума общение на других языках на нем запрещено.

VD>Кроме того этот форум не читают англоязычные члены комьюнити.
VD>Вопросы на английском лучше задавать на https://groups.google.com/forum/#!forum/nemerle-en

VD>This is a Russian-language forum. According to the rules of this forum communication in other languages ​​is prohibited.

VD>Also this forum do not read English-language community members.
VD>Will be better if you to ask your questions in https://groups.google.com/forum/#!forum/nemerle-en


Слишком плохо.
Россия форума является более активным, чем в группе Google.
Разрешение международного языка в RSDN, только поможет Nemerle, чтобы стать более популярным,
потому что это действительно заслуживают.
Этот текст был переведен с Google Translate

I am reading this forum because i am Romanian and i learned a little russian in school, before 1999...
One big problem is that whole rsdn webpage cannot be translated directly using either google translate nor bing translate...
Re[3]: Macro that will mimic new from c#
От: Don Reba Канада https://stackoverflow.com/users/49329/don-reba
Дата: 24.08.11 18:39
Оценка:
Most people here who understand English would have answered your questions at StackOverflow.
Ce n'est que pour vous dire ce que je vous dis.
Re[4]: Macro that will mimic new from c#
От: Liviu1  
Дата: 24.08.11 18:44
Оценка:
Здравствуйте, Don Reba, Вы писали:

DR>Most people here who understand English would have answered your questions at StackOverflow.



Хорошо,

Когда у меня будет проблема, я отправлю также StackOverflow.

спасибо
Re[3]: Macro that will mimic new from c#
От: VladD2 Российская Империя www.nemerle.org
Дата: 24.08.11 19:00
Оценка:
Здравствуйте, Liviu1, Вы писали:

L>Россия форума является более активным, чем в группе Google.


Все кто понимает толк в Nemerle читают Google-группы.

L>Разрешение международного языка в RSDN, только поможет Nemerle, чтобы стать более популярным,

L>потому что это действительно заслуживают.
L>Этот текст был переведен с Google Translate

Это чувствуется .
I feel it .

L>I am reading this forum because i am Romanian and i learned a little russian in school, before 1999...

L>One big problem is that whole rsdn webpage cannot be translated directly using either google translate nor bing translate...

Why? Try it translation


PS

Unfortunate the Russian language very hard to translate.
Есть логика намерений и логика обстоятельств, последняя всегда сильнее.
Re[4]: Macro that will mimic new from c#
От: Don Reba Канада https://stackoverflow.com/users/49329/don-reba
Дата: 24.08.11 19:11
Оценка: +3
Здравствуйте, VladD2, Вы писали:

VD>Все кто понимает толк в Nemerle читают Google-группы.


Может я, конечно, недостаточно понимаю этот толк, но Гугл-группы не читаю. Только на Sourceforge я видел менее юзабильный форум для разработчиков.

Воообще не понимаю зачем их держать. StackOverflow на порядок удобней и помогает увеличивать видимость языка.
Ce n'est que pour vous dire ce que je vous dis.
Re[5]: Macro that will mimic new from c#
От: VladD2 Российская Империя www.nemerle.org
Дата: 24.08.11 19:40
Оценка:
Здравствуйте, Don Reba, Вы писали:

DR>Может я, конечно, недостаточно понимаю этот толк, но Гугл-группы не читаю.


Ну, и зря.
Хотя это чей ответ?

DR>Только на Sourceforge я видел менее юзабильный форум для разработчиков.


Возможно ты не видел их нового интерфейса:
https://groups.google.com/forum/#!forum/nemerle-en
На мой взгляд он очень приличный. Даже древесность прослеживается.

DR>Воообще не понимаю зачем их держать. StackOverflow на порядок удобней и помогает увеличивать видимость языка.


Ну, я лично StackOverflow не читаю. А выделенный форум все равно нужен.

Потом никто не мешает отвечать и там, и там. Вопросов пока что не очень много. Хотя на русском форуме их уже многовато.

Кстати, если ты завсегтатый StackOverflow, то делал бы там какие-нить заметочки. Это бы подогревало бы интерес к языку. И народ стал бы чаще задавать вопросы по Н на StackOverflow.
Есть логика намерений и логика обстоятельств, последняя всегда сильнее.
Re[5]: Macro that will mimic new from c#
От: VladD2 Российская Империя www.nemerle.org
Дата: 24.08.11 20:22
Оценка:
Здравствуйте, Liviu1, Вы писали:

L>Когда у меня будет проблема, я отправлю также StackOverflow.


Если нужен мой ответ, то лучше на гугшь. Я StackOverflow не читаю. Если только Google allerts сообщит.
Есть логика намерений и логика обстоятельств, последняя всегда сильнее.
Re[6]: Macro that will mimic new from c#
От: Don Reba Канада https://stackoverflow.com/users/49329/don-reba
Дата: 24.08.11 20:27
Оценка: +2
Здравствуйте, VladD2, Вы писали:

VD>Ну, я лично StackOverflow не читаю. А выделенный форум все равно нужен.


Если кто-то задаст особо каверзный вопрос, я тебя позову. Хотя, подписаться на тег nemerle ничего не стоит и спама на SO не бывает.

Выделенный форум нужен для обсуждения между членами команды, но для ответов на вопросы у него нет никаких преимуществ. Если бы все вопросы вместо групп спрашивали на SO, то на них отвечали бы быстрее, их видело бы гораздо больше людей и к ним можно было бы привлекать экспертов по смежным областям.
Ce n'est que pour vous dire ce que je vous dis.
Re[7]: Macro that will mimic new from c#
От: VladD2 Российская Империя www.nemerle.org
Дата: 25.08.11 16:38
Оценка:
Здравствуйте, Don Reba, Вы писали:

DR>Если кто-то задаст особо каверзный вопрос, я тебя позову. Хотя, подписаться на тег nemerle ничего не стоит и спама на SO не бывает.


Для этого, видимо, надо стать его членом. А я таковым, вроде как, не являюсь. Пару раз заходил туда под гуглеским экаунтом. Но не уверен, что на него можно и подписку оформлять.

DR>Выделенный форум нужен для обсуждения между членами команды, но для ответов на вопросы у него нет никаких преимуществ.


Ну, почему же? Это официальное место где всегда можно получить ответ именно от тех кто в этом деле шарит. На СтекОверфлоу много кого тусуется и можно получить мягко говоря неадекватный ответ.

DR>Если бы все вопросы вместо групп спрашивали на SO, то на них отвечали бы быстрее, их видело бы гораздо больше людей и к ним можно было бы привлекать экспертов по смежным областям.


Ну, вот не всем нужны ответы экспертов по смежным областям.

А вообще, тут вопрос курицы и яйца. Если бы было больше популярности, то и вопросов в разных местах было бы больше. А следовательно было бы больше популярности .
Есть логика намерений и логика обстоятельств, последняя всегда сильнее.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.