From c2ce06eba7627c7e3ed6d48ecb8a5f7148e25630 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sun, 22 Mar 2020 13:55:39 +0100 Subject: [PATCH] cgen: generate #ifdefs --- vlib/v/ast/ast.v | 3 +- vlib/v/checker/checker.v | 2 +- vlib/v/gen/cgen.v | 68 ++++++++++++++++++++++++++++++++++++++-- vlib/v/parser/comptime.v | 3 +- 4 files changed, 70 insertions(+), 6 deletions(-) diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 6189187216..1d9dbd9813 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -386,7 +386,8 @@ pub: pub struct CompIf { pub: - cond Expr +// cond Expr + val string stmts []Stmt pos token.Position mut: diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 954d08476c..50af39b4fd 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -530,7 +530,7 @@ fn (c mut Checker) stmt(node ast.Stmt) { } // ast.Attr {} ast.CompIf { - c.expr(it.cond) + // c.expr(it.cond) c.stmts(it.stmts) } ast.ConstDecl { diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index b66efc1129..3e80003941 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -268,12 +268,13 @@ fn (g mut Gen) stmt(node ast.Stmt) { g.const_decl(it) } ast.CompIf { - g.writeln('//#ifdef ') - g.expr(it.cond) + g.writeln('\n#ifdef ' + comp_if_to_ifdef(it.val)) + g.writeln('// #if $it.val') + // g.expr(it.cond) // println('comp if stmts $g.file.path:$it.pos.line_nr') g.stmts(it.stmts) // println('done') - g.writeln('//#endif') + g.writeln('#endif') } ast.DeferStmt { g.writeln('// defer') @@ -1965,3 +1966,64 @@ fn op_to_fn_name(name string) string { 'bad op $name'} } } + +fn comp_if_to_ifdef(name string) string { + match name { + 'windows' { + return '_WIN32' + } + 'mac' { + return '__APPLE__' + } + 'macos' { + return '__APPLE__' + } + 'linux' { + return '__linux__' + } + 'freebsd' { + return '__FreeBSD__' + } + 'openbsd' { + return '__OpenBSD__' + } + 'netbsd' { + return '__NetBSD__' + } + 'dragonfly' { + return '__DragonFly__' + } + 'msvc' { + return '_MSC_VER' + } + 'android' { + return '__ANDROID__' + } + 'js' { + return '_VJS' + } + 'solaris' { + return '__sun' + } + 'haiku' { + return '__haiku__' + } + 'tinyc' { + return 'tinyc' + } + 'debug' { + return '_VDEBUG' + } + 'linux_or_macos' { + return '' + } + 'no_bounds_checking' { + return 'NO_BOUNDS_CHECK' + } + else { + verror('bad os ifdef name "$name"') + } + } + // verror('bad os ifdef name "$name"') + return '' +} diff --git a/vlib/v/parser/comptime.v b/vlib/v/parser/comptime.v index 5b1ed3c71e..78af8a4353 100644 --- a/vlib/v/parser/comptime.v +++ b/vlib/v/parser/comptime.v @@ -11,13 +11,14 @@ pub fn (p mut Parser) comp_if() ast.CompIf { if p.tok.kind == .not { p.next() } - p.check_name() + val := p.check_name() if p.tok.kind == .question { p.next() } mut node := ast.CompIf{ stmts: p.parse_block() pos: pos + val: val } if p.tok.kind == .dollar && p.peek_tok.kind == .key_else { p.next()