Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Defaulting None for optional fields #165

Merged
merged 5 commits into from
Aug 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 77 additions & 20 deletions src/Nirum/Targets/Python.hs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import qualified Data.SemVer as SV
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Function (on)
import System.FilePath (joinPath)
import qualified Text.Email.Validate as E
import Text.InterpolatedString.Perl6 (q, qq)
Expand Down Expand Up @@ -320,16 +321,20 @@ toIndentedCodes f traversable concatenator =
T.intercalate concatenator $ map f traversable

compileParameters :: (ParameterName -> ParameterType -> Code)
-> [(T.Text, Code)]
-> [(T.Text, Code, Bool)]
-> Code
compileParameters gen nameTypePairs =
toIndentedCodes (uncurry gen) nameTypePairs ", "
compileParameters gen nameTypeTriples =
toIndentedCodes
(\ (n, t, o) -> gen n t `T.append` if o then "=None" else "")
nameTypeTriples ", "

compileFieldInitializers :: DS.DeclarationSet Field -> CodeGen Code
compileFieldInitializers fields = do
compileFieldInitializers :: DS.DeclarationSet Field -> Int -> CodeGen Code
compileFieldInitializers fields depth = do
initializers <- forM (toList fields) compileFieldInitializer
return $ T.intercalate "\n " initializers
return $ T.intercalate indentSpaces initializers
where
indentSpaces :: T.Text
indentSpaces = "\n" `T.append` T.replicate depth " "
compileFieldInitializer :: Field -> CodeGen Code
compileFieldInitializer (Field fieldName' fieldType' _) =
case fieldType' of
Expand Down Expand Up @@ -432,11 +437,19 @@ compileUnionTag :: Source -> Name -> Tag -> CodeGen Code
compileUnionTag source parentname d@(Tag typename' fields _) = do
typeExprCodes <- mapM (compileTypeExpression source)
[typeExpr | (Field _ typeExpr _) <- toList fields]
let className = toClassName' typename'
let optionFlags = [ case typeExpr of
OptionModifier _ -> True
_ -> False
| (Field _ typeExpr _) <- toList fields
]
className = toClassName' typename'
tagNames = map (toAttributeName' . fieldName) (toList fields)
nameNTypes = zip tagNames typeExprCodes
getOptFlag :: (T.Text, Code, Bool) -> Bool
getOptFlag (_, _, flag) = flag
nameTypeTriples = L.sortBy (compare `on` getOptFlag)
(zip3 tagNames typeExprCodes optionFlags)
slotTypes = toIndentedCodes
(\ (n, t) -> [qq|('{n}', {t})|]) nameNTypes ",\n "
(\ (n, t, _) -> [qq|('{n}', {t})|]) nameTypeTriples ",\n "
slots = if length tagNames == 1
then [qq|'{head tagNames}'|] `T.snoc` ','
else toIndentedCodes (\ n -> [qq|'{n}'|]) tagNames ",\n "
Expand All @@ -458,7 +471,27 @@ compileUnionTag source parentname d@(Tag typename' fields _) = do
typeRepr <- typeReprCompiler
arg <- parameterCompiler
ret <- returnCompiler
initializers <- compileFieldInitializers fields
pyVer <- getPythonVersion
initializers <- compileFieldInitializers fields $ case pyVer of
Python3 -> 2
Python2 -> 3
let initParams = compileParameters arg nameTypeTriples
inits = case pyVer of
Python2 -> [qq|
def __init__(self, **kwargs):
def __init__($initParams):
$initializers
pass
__init__(**kwargs)
validate_union_type(self)
|]
Python3 -> [qq|
def __init__(self{ if null nameTypeTriples
then T.empty
else ", *, " `T.append` initParams }) -> None:
$initializers
validate_union_type(self)
|]
return [qq|
class $className($parentClass):
{compileDocstringWithFields " " d fields}
Expand All @@ -474,9 +507,7 @@ class $className($parentClass):
def __nirum_tag_types__():
return [$slotTypes]

def __init__(self, {compileParameters arg nameNTypes}){ ret "None" }:
$initializers
validate_union_type(self)
{ inits :: T.Text }

def __repr__(self){ ret "str" }:
return '\{0\}(\{1\})'.format(
Expand Down Expand Up @@ -669,12 +700,20 @@ compileTypeDeclaration src d@TypeDeclaration { typename = typename'
fieldList = toList fields
typeExprCodes <- mapM (compileTypeExpression src)
[typeExpr | (Field _ typeExpr _) <- fieldList]
let fieldNames = map toAttributeName' [ name'
let optionFlags = [ case typeExpr of
OptionModifier _ -> True
_ -> False
| (Field _ typeExpr _) <- fieldList
]
fieldNames = map toAttributeName' [ name'
| (Field name' _ _) <- fieldList
]
nameTypePairs = zip fieldNames typeExprCodes
getOptFlag :: (T.Text, Code, Bool) -> Bool
getOptFlag (_, _, flag) = flag
nameTypeTriples = L.sortBy (compare `on` getOptFlag)
(zip3 fieldNames typeExprCodes optionFlags)
slotTypes = toIndentedCodes
(\ (n, t) -> [qq|'{n}': {t}|]) nameTypePairs ",\n "
(\ (n, t, _) -> [qq|'{n}': {t}|]) nameTypeTriples ",\n "
slots = toIndentedCodes (\ n -> [qq|'{n}'|]) fieldNames ",\n "
nameMaps = toIndentedCodes
toNamePair
Expand All @@ -693,7 +732,27 @@ compileTypeDeclaration src d@TypeDeclaration { typename = typename'
arg <- parameterCompiler
ret <- returnCompiler
typeRepr <- typeReprCompiler
initializers <- compileFieldInitializers fields
pyVer <- getPythonVersion
initializers <- compileFieldInitializers fields $ case pyVer of
Python3 -> 2
Python2 -> 3
let initParams = compileParameters arg nameTypeTriples
inits = case pyVer of
Python2 -> [qq|
def __init__(self, **kwargs):
def __init__($initParams):
$initializers
pass
__init__(**kwargs)
validate_record_type(self)
|]
Python3 -> [qq|
def __init__(self{ if null nameTypeTriples
then T.empty
else ", *, " `T.append` initParams }) -> None:
$initializers
validate_record_type(self)
|]
let clsType = arg "cls" "type"
return [qq|
class $className(object):
Expand All @@ -710,9 +769,7 @@ class $className(object):
def __nirum_field_types__():
return \{$slotTypes\}

def __init__(self, {compileParameters arg nameTypePairs}){ret "None"}:
$initializers
validate_record_type(self)
{inits :: T.Text}

def __repr__(self){ret "bool"}:
return '\{0\}(\{1\})'.format(
Expand Down
11 changes: 11 additions & 0 deletions test/nirum_fixture/fixture/foo.nrm
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,14 @@ record person (
record people (
{person} people
);

record product (
text name,
int64? price,
bool sale,
uri? url,
);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should test union tags as well e.g.:

union union-test = tag-a
                 | tag-b (text a, text? b, int64 c, int64 d?);


union animal = cat
| dog (text name, text? kind, int64 age, int64? weight)
;
22 changes: 19 additions & 3 deletions test/python/primitive_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
from nirum.service import Service
from six import PY3

from fixture.foo import (CultureAgnosticName, EastAsianName,
from fixture.foo import (CultureAgnosticName, Dog, EastAsianName,
EvaChar, FloatUnbox, Gender, ImportedTypeUnbox, Irum,
Line, MixedName, NullService,
Point1, Point2, Point3d, Pop, PingService, Rnb,
Run, Stop, Way, WesternName)
Point1, Point2, Point3d, Pop, PingService, Product,
Rnb, Run, Stop, Way, WesternName)
from fixture.foo.bar import PathUnbox, IntUnbox, Point
from fixture.qux import Path, Name

Expand Down Expand Up @@ -159,6 +159,14 @@ def test_record_with_one_field():
assert Line(length=3).__nirum_serialize__() == expected


def test_record_optional_initializer():
product = Product(name=u'coffee', sale=False)
assert product.name == u'coffee'
assert product.price is None
assert not product.sale
assert product.url is None


def test_union():
assert isinstance(MixedName, type)
assert MixedName.Tag.western_name.value == 'western_name'
Expand Down Expand Up @@ -232,6 +240,14 @@ def test_union_with_special_case():
assert Stop().__nirum_tag__.value == 'stop'


def test_union_tags_optional_initializer():
dog = Dog(name=u"Max", age=10)
assert dog.name == u"Max"
assert dog.kind is None
assert dog.age == 10
assert dog.weight is None


def test_service():
assert issubclass(NullService, Service)
assert issubclass(PingService, Service)
Expand Down