From 5285663c6f63a94b8ec5321709e185c95ef5c0f9 Mon Sep 17 00:00:00 2001 From: Hiroshi Shirosaki Date: Thu, 12 Nov 2015 17:15:47 +0900 Subject: [PATCH] Do not allow partial name in magic comments --- parse.y | 2 +- test/ruby/test_literal.rb | 29 +++++++++++++++++++++++++++-- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/parse.y b/parse.y index 56e4243..43e3b66 100644 --- a/parse.y +++ b/parse.y @@ -7088,7 +7088,7 @@ parser_magic_comment(struct parser_params *parser, const char *str, long len) if (s[i] == '-') s[i] = '_'; } do { - if (STRNCASECMP(p->name, s, n) == 0) { + if (n == (long)strlen(p->name) && STRNCASECMP(p->name, s, n) == 0) { n = vend - vbeg; if (p->length) { n = (*p->length)(parser, vbeg, n); diff --git a/test/ruby/test_literal.rb b/test/ruby/test_literal.rb index e523f11..cfa37ac 100644 --- a/test/ruby/test_literal.rb +++ b/test/ruby/test_literal.rb @@ -121,6 +121,31 @@ class TestRubyLiteral < Test::Unit::TestCase assert_equal "foo\n", `echo #{s}` end + def test_string_encoding_with_magic_comments + all_assertions do |a| + a.for("utf-8 string with indicator") do + str = eval("# -*- coding: utf-8 -*-\n""'foo'") + assert_equal(Encoding::UTF_8, str.encoding) + end + a.for("utf-8 string without indicator") do + str = eval("# coding: utf-8\n""'foo'") + assert_equal(Encoding::UTF_8, str.encoding) + end + a.for("us_ascii string with no magic comments") do + str = eval("'foo'") + assert_equal(Encoding::US_ASCII, str.encoding) + end + a.for("us_ascii string with invalid magic comments") do + str = eval("# c: utf-8\n""'foo'") + assert_equal(Encoding::US_ASCII, str.encoding) + end + a.for("us_ascii string with invalid magic comments and indicator") do + str = eval("# -*- c: utf-8 -*- \n""'foo'") + assert_equal(Encoding::US_ASCII, str.encoding) + end + end + end + def test_frozen_string all_assertions do |a| a.for("false with indicator") do @@ -151,8 +176,8 @@ class TestRubyLiteral < Test::Unit::TestCase str = eval("# frozen-string-literal: false x\n""'foo'") assert_not_predicate(str, :frozen?) end - a.for("true with succeeding garbage") do - str = eval("# frozen-string-literal: true x\n""'foo'") + a.for("false with invalid name") do + str = eval("# frozen: true\n""'foo'") assert_not_predicate(str, :frozen?) end end -- 2.5.0